import os

from unittest import TestCase

from grafana_api.model import APIModel
from grafana_api.library import Library

class LibraryTest(TestCase):
    model: APIModel = APIModel(
        host=os.environ["GRAFANA_HOST"],
        token=os.environ["GRAFANA_TOKEN"],
        http2_support=True if os.environ["HTTP2"] == "True" else False,
    )
    library: Library = Library(model)

    def test_a_get_all_library_elements(self):
        self.assertEqual(
            dict(
                {"result": {"totalCount": 0, "elements": [], "page": 1, "perPage": 100}}
            ),
            self.library.get_all_library_elements(),
        )

    def test_b_create_library_element(self):
        self.library.create_library_element(72, {"test": "test"}, name="Test")

    def test_c_get_library_element_by_uid(self):
        self.assertEqual(
            "Test",
            self.library.get_library_element_by_uid(
                self.library.get_library_element_by_name("Test")
                .get("result")[0]
                .get("uid")
            )
            .get("result")
            .get("name"),
        )

    def test_d_get_library_element_by_name(self):
        self.assertEqual(
            "Test",
            self.library.get_library_element_by_name("Test")
            .get("result")[0]
            .get("name"),
        )

    def test_e_get_library_element_connections(self):
        self.assertEqual(
            dict({"result": []}),
            self.library.get_library_element_connections(
                self.library.get_library_element_by_name("Test")
                .get("result")[0]
                .get("uid")
            ),
        )

    def test_g_delete_library_element(self):
        self.library.delete_library_element(
            self.library.get_library_element_by_name("Test").get("result")[0].get("uid")
        )

        self.assertEqual(
            dict(
                {"result": {"totalCount": 0, "elements": [], "page": 1, "perPage": 100}}
            ),
            self.library.get_all_library_elements(),
        )


from torch import nn
import torch.nn.functional as F

cfg = {
    'vgg11': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
    'vgg13': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
    'vgg16': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],
    'vgg19': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'],
    'vgg19cut': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'N'],
}

class StyleEncoder(nn.Module):
    def __init__(self, sty_dim=128):
        super(StyleEncoder, self).__init__()
        # network layers setting
        self.features = make_layers(cfg['vgg11'], True)
        self.cont = nn.Linear(512, sty_dim)

        self._initialize_weights()

    def forward(self, x):
        x = self.features(x)
        x = F.adaptive_avg_pool2d(x, (1, 1))
        flat = x.view(x.size(0), -1)
        cont = self.cont(flat)

        return cont

    def _initialize_weights(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
                if m.bias is not None:
                    nn.init.constant_(m.bias, 0)
            elif isinstance(m, nn.BatchNorm2d):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)
            elif isinstance(m, nn.Linear):
                nn.init.normal_(m.weight, 0, 0.01)
                nn.init.constant_(m.bias, 0)

def make_layers(cfg, batch_norm=False):
    layers = []
    in_channels = 3
    for v in cfg:
        if v == 'M':
            layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
        else:
            conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)
            if batch_norm:
                layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=False)]
            else:
                layers += [conv2d, nn.ReLU(inplace=False)]
            in_channels = v
    return nn.Sequential(*layers)


# Standard library imports
from pathlib import Path
import sys
import time

# Third party imports
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy as sp

# Adds this file's grandparent directory to the Python module search
# path so it can find the package. This allows user to run the script
# without having to install the package.
sys.path.append(str(Path(__file__).resolve().parents[1]))

# Local application imports
from trajectory_optimization import paths, simulation, socp_problem

def _main():
    test_paths = {
        'left_turn': paths.LeftTurnPath,
        'right_turn': paths.RightTurnPath,
        'straight': paths.StraightLinePath
    }

    traversal_times = list()
    solve_times = list()
    for path_name, path_cls in test_paths.items():
        for path_param in range(5, 15 + 1):
            path = path_cls(path_param)
            problem = socp_problem.SocpProblem(path, K=20)

            solver_opts = {
                'max_iters': 300,
                'feastol': 1e-6  # Default: 1e-8
            }

            for time_goal in range(5, 25 + 1):
                time_start = time.process_time_ns()
                results = problem.solve(time_goal, verbose=False, **solver_opts)
                time_stop = time.process_time_ns()
                solve_time = time_stop - time_start

                if results is None:
                    traversal_times.append((path_name, path_param, time_goal,
                                            np.nan, np.nan))
                    solve_times.append((path_name, path_param, time_goal, np.nan))
                    continue

                rel_err = abs(1 - results.trav_time / time_goal)
                traversal_times.append((path_name, path_param, time_goal,
                                        results.trav_time, rel_err))

                solve_times.append((path_name, path_param, time_goal, solve_time))

    traversal_times_df = pd.DataFrame(traversal_times,
                                      columns=['Path', 'Param', 'Time Goal',
                                               'Time', 'Rel Err'])
    print(traversal_times_df)
    traversal_times_df.to_csv('output.csv')

    print(f"mean error (rel err): {traversal_times_df['Rel Err'].mean():>.4e}")
    print(f"std dev. (rel err):   {traversal_times_df['Rel Err'].std():>.4e}")

    solve_times_df = pd.DataFrame(solve_times, columns=['Path', 'Param',
                                                        'Time Goal',
                                                        'Solve Time'])
    print(solve_times_df)
    solve_times_df.to_csv('solver_times.csv')

    print(f"mean solver time (ms): {solve_times_df['Solve Time'].mean() / 1e6:>.4}")
    print(f"std dev. (ms):         {solve_times_df['Solve Time'].std() / 1e6:>.4}")

    return 0

if __name__ == '__main__':
    sys.exit(_main())


import itertools

n,m = map(int,input().split())
arr = []
num1 = [] # 집
num2 = [] # 치킨

for i in range(n):
  arr.append(list(map(int,input().split())))

for i in range(n):
  for j in range(n):
    if arr[i][j] == 1:
      num1.append(i+1)
      num1.append(j+1)
    elif arr[i][j] == 2:
      num2.append(i+1)
      num2.append(j+1)

num1_index = [num1[i*2:(i+1)*2] for i in range((len(num1)+1)//2)] #집 좌표
num2_index = [num2[i*2:(i+1)*2] for i in range((len(num2)+1)//2)] #치킨 좌표

com = list(itertools.combinations((num2_index),m)) #치킨집 m개 조합

num = 0
for i in range(len(num1_index)):
  minimal = []
  for j in range(0,m):
    list =[]
    temp = abs(num1_index[i][0] - com[i][j][0]) + abs(num1_index[i][1] - com[i][j][1])
    list.append(temp)
  res = min(list) #집x와 치킨집 사이의 치킨거리.
  num += res #도시의 치킨거리
  minimal.append(num)
print(min(minimal))


from django.http import JsonResponse
from django.shortcuts import render, redirect
from .models import Product, ProductCategory, Basket
from django.core.paginator import Paginator
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from telebot.sendmessage import send_telegram

# Create your views here.
def index(request):
    context = {
        'title': "Market Place"
    }
    return render(request, 'products/index.html', context=context)

def products(request, category_id=None):
    search_query = request.GET.get("search", "")
    context = {
        'title': "Market Place - Catalog",
        'categories': ProductCategory.objects.all(),
    }
    if category_id:
        products = Product.objects.filter(category_id=category_id)
    else:
        if search_query:
            products = Product.objects.filter(
                Q(name__icontains=search_query) | Q(short_description__icontains=search_query))
        else:
            products = Product.objects.all()
    paginator = Paginator(products, 6)  # saifada 3 dona tavarni ko'rsatadi
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)

    context.update({"products": page_obj})
    return render(request, 'products/products.html', context=context)

@login_required
def basket_add(request, product_id):
    current_page = 'profile'
    product = Product.objects.get(id=product_id)
    baskets = Basket.objects.filter(user=request.user, product=product)
    if not baskets.exists():
        Basket.objects.create(user=request.user, product=product, quantity=1)
        return redirect(current_page)
    else:
        basket = baskets.first()
        basket.quantity += 1
        basket.save()
        return redirect(current_page)

def plus_cart(request):
    if request.method == 'GET':
        prod_id = request.GET['prod_id']
        c = Basket.objects.get(Q(product=prod_id) & Q(user=request.user))
        c.quantity += 1
        c.save()
        user = request.user
        baskets = Basket.objects.filter(user=user)

        one_price = 0
        for res in baskets:
            one_price = res.sum()
        total_quantity = sum(basket.quantity for basket in baskets)
        total_price = sum(basket.sum() for basket in baskets)

        data = {
            'quantity': c.quantity,
            'total_price': total_price,
            'total_quantity': total_quantity,
            "one_price": one_price,
        }
        return JsonResponse(data)

def minus_cart(request):
    if request.method == 'GET':
        prod_id = request.GET['prod_id']
        c = Basket.objects.get(Q(product=prod_id) & Q(user=request.user))
        c.quantity -= 1
        c.save()
        user = request.user
        baskets = Basket.objects.filter(user=user)

        one_price = 0
        for res in baskets:
            one_price = res.sum()
        total_quantity = sum(basket.quantity for basket in baskets)

        total_price = sum(basket.sum() for basket in baskets)

        data = {
            'quantity': c.quantity,
            'total_quantity': total_quantity,
            "one_price": one_price,
            'total_price': total_price,
        }
        return JsonResponse(data)

def remove_cart(request):
    if request.method == 'GET':
        prod_id = request.GET['prod_id']
        c = Basket.objects.get(Q(product=prod_id) & Q(user=request.user))
        c.quantity += 1
        c.delete()
        user = request.user
        baskets = Basket.objects.filter(user=user)

        one_price = 0
        for res in baskets:
            one_price = res.sum()
        total_quantity = sum(basket.quantity for basket in baskets)

        total_price = sum(basket.sum() for basket in baskets)

        data = {
            'quantity': c.quantity,
            'total_quantity': total_quantity,
            "one_price": one_price,
            'total_price': total_price,
        }
        return JsonResponse(data)

def thanks_page(request):
    user = request.user
    baskets = Basket.objects.filter(user=user)
    name = user.first_name
    phone = user.phone
    res = ""
    for basket in baskets:
        pr_name = basket.product.name
        quantity = str(basket.quantity)
        ls = f"\n{pr_name} - {quantity} dona"
        res += ls
    send_telegram(tg_name=name, tg_phone=phone, tg_order=res)
    context = {
        "title": "Raxmat"
    }

    return render(request, 'products/thanks.html', context=context)


import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.svm import SVR
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.neighbors import KNeighborsRegressor
from sklearn.neural_network import MLPRegressor
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error, median_absolute_error, precision_score, recall_score, f1_score
from time import time
import numpy as np
from sklearn.preprocessing import LabelEncoder

df = pd.read_csv('Final Data.csv')

df_melt = df.melt(id_vars='Name Of District', var_name='Year-Gender-Class', value_name='Value')

df_melt[['Year', 'Gender', 'Class']] = df_melt['Year-Gender-Class'].str.split('-', expand=True)

df_melt['Year'] = df_melt['Year'].astype(int)

X = df_melt[['Year', 'Gender', 'Class', 'Name Of District']]
y = df_melt['Value']

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

le_gender = LabelEncoder()
le_district = LabelEncoder()

X_train['Gender'] = le_gender.fit_transform(X_train['Gender'])

X_train['Name Of District'] = le_district.fit_transform(X_train['Name Of District'])

X_test['Gender'] = le_gender.transform(X_test['Gender'])

X_test['Name Of District'] = le_district.transform(X_test['Name Of District'])

models = [

    ("Random Forest", RandomForestRegressor(), 33),
]

results = []

for name, model, params in models:
    start_time = time()
    model.fit(X_train, y_train)
    training_time = round(time() - start_time, 2)
    y_pred = model.predict(X_test)
    y_train_pred = model.predict(X_train)
    results.append({
        "Model": name,
        "Accuracy": model.score(X_test, y_test),
        "MAE": mean_absolute_error(y_test, y_pred),
        "MSE": mean_squared_error(y_test, y_pred),
        "RMSE": np.sqrt(mean_squared_error(y_test, y_pred)),
        "R-SQ": r2_score(y_test, y_pred),
        "MedAE": median_absolute_error(y_test, y_pred),
        "Number of Parameters": params
    })

results_df = pd.DataFrame(results)
print(results_df)

new_data = pd.DataFrame({
    'Year': [2026],
    'Gender': ['Boys'],
    'Class': ['9'],
    'Name Of District': ['Ahmadabad']
})

new_data['Gender'] = le_gender.transform(new_data['Gender'])
new_data['Name Of District'] = le_district.transform(new_data['Name Of District'])

for name, model, params in models:
    prediction = model.predict(new_data)
    print(f"The prediction for 2020 Boys class 9 in Ahmedabad using {name} is {prediction}")

Student Dropout Analysis For School Education Model.py


import io, os, sys

if 'PyPy' in sys.version:
    input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
    def strput():
        return input().decode()
else:
    input = sys.stdin.readline
    def strput():
        return input()

# code starts here

class Fenwick:
    size = 0
    bit = []

    def __init__(self, n):
        for i in range(n + 1):
            self.bit.append(0)
        self.size = n

    def update(self, pos, val):
        u = pos
        while u <= self.size:
            self.bit[u] += val
            u += u & (-u)

    def get(self, pos):
        res, u = 0, pos
        while u > 0:
            res += self.bit[u]
            u -= u & (-u)
        return res

def main():
    n = int(input())
    pos = [-1]
    hgt = [-1]
    for i in range(1, n + 1):
        p, h = [int(x) for x in input().split()]
        pos.append(p)
        hgt.append(h)

    q = int(input())
    ans = [0 for x in range(q)]
    query = [[] for x in range(n + 1)]
    for i in range(1, q + 1):
        l, r = [int(x) for x in input().split()]
        query[l].append((r, i))

    stack = []
    tree = Fenwick(n)
    for i in range(n, 0, -1):
        while len(stack) > 0:
            top = stack[-1]
            if pos[top] > pos[i] + hgt[i]:
                need = pos[top] - pos[i] - hgt[i]
                tree.update(top, min(0, need - tree.get(top) + tree.get(top - 1)))
                break
            tree.update(top, - tree.get(top) + tree.get(top - 1))
            stack.pop()

        stack.append(i)
        for j in query[i]:
            ans[j[1] - 1] = tree.get(j[0])
        tree.update(i, pos[i] - pos[i - 1])

    print('\n'.join(map(str, ans)))

if __name__ == "__main__":
    main()


import datetime

from jsonschema.exceptions import ValidationError

from pykechain.enums import (
    PropertyType, ScopeStatus,
    KEChainPages,
    ScopeMemberActions,
    ScopeRoles,
    ScopeCategory,
)
from pykechain.exceptions import NotFoundError, MultipleFoundError, IllegalArgumentError
from pykechain.models import Team, Scope
from pykechain.models.sidebar.sidebar_manager import SideBarManager
from pykechain.utils import is_url
from tests.classes import TestBetamax

class TestScopes(TestBetamax):
    """
    Test retrieval and scope attributes and methods.
    """

    def test_scope_attributes(self):
        attributes = [
            "_client",
            "_json_data",
            "id",
            "name",
            "created_at",
            "updated_at",
            "ref",
            "process",
            "workflow_root",
            "description",
            "status",
            "category",
            "tags",
            "start_date",
            "due_date",
        ]

        obj = self.project
        for attribute in attributes:
            with self.subTest(attribute):
                self.assertTrue(
                    hasattr(obj, attribute),
                    f"Could not find '{attribute}' in the object: '{obj.__dict__.keys()}'",
                )

    def test_retrieve_scopes(self):
        self.assertTrue(self.client.scopes())

    def test_retrieve_scope_with_refs(self):
        # setup
        scope_ref = "bike-project"
        scope_name = "Bike Project"
        scope = self.client.scope(ref=scope_ref)

        # testing
        self.assertIsInstance(scope, Scope)
        self.assertTrue(scope.name, scope_name)

    def test_retrieve_scope_with_kwargs(self):
        retrieve_scopes_with_kwargs = self.client.scopes(name__icontains="Bike")
        self.assertTrue(retrieve_scopes_with_kwargs)
        self.assertTrue(len(retrieve_scopes_with_kwargs) >= 1)

    def test_retrieve_single_unknown(self):
        with self.assertRaises(NotFoundError):
            self.client.scope("123lladadwd")

    def test_retrieve_single_multiple(self):
        with self.assertRaises(MultipleFoundError):
            self.client.scope()

    def test_team_property_of_scope(self):
        """Test for the property 'team' of a scope."""
        team = self.project.team

        self.assertIsNone(team)

    def test_side_bar(self):
        side_bar_manager = self.project.side_bar()

        self.assertIsInstance(side_bar_manager, SideBarManager)

    def test_root_properties(self):
        for value in [
            self.project.workflow_root_process,
            self.project.catalog_root_process,
            self.project.app_root_process,
            self.project.product_root_model,
            self.project.product_root_instance,
            self.project.catalog_root_model,
            self.project.catalog_root_instance,
        ]:
            with self.subTest(""):
                self.assertIsNotNone(value)

class TestScopeMembers(TestBetamax):
    """
    Tests user assignment to a scope.
    """

    DEFAULTS = {
        ScopeRoles.MANAGER: [
            "superuser",
            "testmanager",
        ],
        ScopeRoles.LEADMEMBER: [
            "superuser",
            "testlead",
        ],
        ScopeRoles.SUPERVISOR: ["supervisor"],
        ScopeRoles.MEMBER: [
            "testuser",
        ],
    }

    def _reset_members(self):
        """Reset the scope members by removing all members and adding the defaults"""
        [
            self.project.remove_member(member=member["username"])
            for member in self.project.members()
        ]

        for role in [
            ScopeRoles.MANAGER,
            ScopeRoles.LEADMEMBER,
            ScopeRoles.MEMBER,
            ScopeRoles.SUPERVISOR,
        ]:
            for member in self.DEFAULTS[role]:
                self.project._update_scope_project_team(ScopeMemberActions.ADD, role, member)

    def setUp(self):
        super().setUp()
        self._reset_members()

    def tearDown(self):
        self._reset_members()
        super().tearDown()

    def test_reset_members(self):
        """Test `_reset_members` method of the test class"""
        self.assertTrue(True)

    def test_members(self):
        scope = self.project

        # Helper function:
        def get_member_names(**kwargs):
            return [member["username"] for member in scope.members(**kwargs)]

        all_members = set(get_member_names())
        managers = set(get_member_names(is_manager=True))
        supervisors = set(get_member_names(is_supervisor=True))
        non_managers = set(get_member_names(is_manager=False))
        leads = set(get_member_names(is_leadmember=True))
        non_leads = set(get_member_names(is_leadmember=False))
        basic_members = set(get_member_names(is_manager=False, is_leadmember=False))

        self.assertEqual(5, len(all_members), msg=",".join(all_members))
        self.assertTrue(
            basic_members and leads and managers and supervisors,
            msg="Test scope must have a member of every type!",
        )

        all_roles = basic_members | leads | managers | supervisors
        remaining_non_leads = all_roles - leads
        remaining_non_managers = all_roles - managers

        self.assertSetEqual(
            all_roles, all_members, msg="The sum of all roles should equal all members."
        )
        self.assertSetEqual(remaining_non_leads, non_leads)
        self.assertSetEqual(remaining_non_managers, non_managers)

    def test_add_member(self):
        member_to_be_added = "anotheruser"
        self.project.add_member(member_to_be_added)
        self.project = self.client.scope(pk=self.project.id)
        project_members = self.project.members()

        # testing
        self.assertTrue(member_to_be_added in [member["username"] for member in project_members])

    def test_add_member_by_id(self):
        member_id = 4
        with self.assertRaises(IllegalArgumentError):
            # noinspection PyTypeChecker
            self.project.add_member(member_id)

    def test_add_non_existing_member(self):
        member_to_be_added = "Nobody"
        with self.assertRaises(NotFoundError):
            self.project.add_member(member_to_be_added)

    def test_remove_member(self):
        member_to_be_removed = "anotheruser"
        # setUp
        self.project.add_member(member_to_be_removed)
        # testing
        self.project.remove_member(member_to_be_removed)
        self.project = self.client.scope(pk=self.project.id)
        project_members = self.project.members()
        self.assertTrue(
            member_to_be_removed not in [member["username"] for member in project_members]
        )

    def test_add_manager(self):
        manager_to_be_added = "anotheruser"
        # testing
        self.project.add_manager(manager_to_be_added)
        self.project = self.client.scope(pk=self.project.id)
        project_managers = self.project.members(is_manager=True)
        self.assertTrue(
            manager_to_be_added in [manager["username"] for manager in project_managers]
        )

    def test_remove_manager(self):
        manager_to_be_removed = "anotheruser"
        # setUp
        self.project.add_manager(manager_to_be_removed)
        # testing
        self.project.remove_manager(manager_to_be_removed)
        self.project = self.client.scope(pk=self.project.id)
        project_managers = self.project.members(is_manager=True)
        self.assertTrue(
            manager_to_be_removed not in [manager["username"] for manager in project_managers]
        )
        project_managers = self.project.members(is_manager=False)
        self.assertTrue(
            manager_to_be_removed in [manager["username"] for manager in project_managers]
        )

    def test_add_leadmember(self):
        leadmember_to_be_added = "anotheruser"
        # testing
        self.project.add_leadmember(leadmember_to_be_added)
        self.project = self.client.scope(pk=self.project.id)
        project_leadmembers = self.project.members(is_leadmember=True)
        self.assertTrue(
            leadmember_to_be_added
            in [leadmember["username"] for leadmember in project_leadmembers]
        )

    def test_remove_leadmember(self):
        leadmember_to_be_removed = "anotheruser"
        # setUp
        self.project.add_leadmember(leadmember_to_be_removed)
        # testing
        self.project.remove_leadmember(leadmember_to_be_removed)
        self.project = self.client.scope(pk=self.project.id)
        project_leadmembers = self.project.members(is_leadmember=True)
        self.assertTrue(
            leadmember_to_be_removed
            not in [leadmember["username"] for leadmember in project_leadmembers]
        )
        project_leadmembers = self.project.members(is_leadmember=False)
        self.assertTrue(
            leadmember_to_be_removed
            in [leadmember["username"] for leadmember in project_leadmembers]
        )

    def test_add_supervisor(self):
        supervisor_to_be_added = "anotheruser"
        # testing
        self.project.add_supervisor(supervisor_to_be_added)
        self.project = self.client.scope(pk=self.project.id)
        project_supervisors = self.project.members(is_supervisor=True)
        self.assertTrue(
            supervisor_to_be_added
            in [supervisor["username"] for supervisor in project_supervisors]
        )

    def test_remove_supervisor(self):
        supervisor_to_be_removed = "anotheruser"
        # setUp
        self.project.add_supervisor(supervisor_to_be_removed)
        # testing
        self.project.remove_supervisor(supervisor_to_be_removed)
        self.project = self.client.scope(pk=self.project.id)
        project_supervisors = self.project.members(is_supervisor=True)
        self.assertTrue(
            supervisor_to_be_removed
            not in [supervisor["username"] for supervisor in project_supervisors]
        )

class TestScopeEdit(TestBetamax):
    """
    Test modifications to a scope.
    """

    def setUp(self):
        super().setUp()
        testing_project = self.project
        self.project = None
        self.project_info = [{
                "id": 0,
                "name": "Project name",
                "value": "Bike project wannabe",
                "property_type": PropertyType.CHAR_VALUE,
            },
            {
                "id": 1,
                "name": "Project number",
                "value": 12,
                "property_type": PropertyType.INT_VALUE,
            }]
        self.scope = testing_project.clone()

    def tearDown(self):
        if self.scope:
            self.scope.delete()
        super().tearDown()

    # 2.2.0+
    # noinspection PyTypeChecker
    def test_edit_scope(self):
        # setUp
        new_scope_name = "Pykechain testing (bike project)"
        new_scope_description = (
            "Project used to build a Bike. Part-time job is to also test Pykechain."
        )
        new_start_date = datetime.datetime(2018, 12, 5, tzinfo=None)
        new_due_date = datetime.datetime(2018, 12, 8, tzinfo=None)
        new_tags = ["tag_one", "tag_two"]

        self.scope.edit(
            name=new_scope_name,
            description=new_scope_description,
            tags=new_tags,
            start_date=new_start_date,
            due_date=new_due_date,
            status=ScopeStatus.CLOSED,
            category=ScopeCategory.TEMPLATE_SCOPE,
        )

        retrieved_project = self.client.scope(id=self.scope.id, status=ScopeStatus.CLOSED)

        # testing
        self.assertEqual(new_scope_name, retrieved_project.name)
        self.assertEqual(new_scope_description, retrieved_project.description)
        self.assertIn(
            retrieved_project._json_data["start_date"],
            ("2018-12-05T00:00:00Z", "2018-12-05T00:00:00+00:00"),
        )
        self.assertIn(
            retrieved_project._json_data["due_date"],
            ("2018-12-08T00:00:00Z", "2018-12-08T00:00:00+00:00"),
        )
        self.assertEqual(ScopeStatus.CLOSED, retrieved_project.status)
        self.assertEqual(ScopeCategory.TEMPLATE_SCOPE, retrieved_project.category)
        self.assertEqual(new_tags, retrieved_project.tags)

        with self.assertRaises(IllegalArgumentError):
            self.scope.edit(name=True)

        with self.assertRaises(IllegalArgumentError):
            self.scope.edit(description=new_start_date)

        with self.assertRaises(IllegalArgumentError):
            self.scope.edit(start_date="Yes, man!")

        with self.assertRaises(IllegalArgumentError):
            self.scope.edit(due_date="Wrong")

        with self.assertRaises(IllegalArgumentError):
            self.scope.edit(status="ILLEGAL_STATUS_WILL_CAUSE_ERR")

        with self.assertRaises(IllegalArgumentError):
            self.scope.edit(category="Ice scoop")

        with self.assertRaises(IllegalArgumentError):
            self.scope.edit(tags="tags must be a list of strings")

    # test added due to #847 - providing no inputs overwrites values
    def test_edit_scope_clearing_values(self):
        # setUp
        initial_name = "Pykechain testing (bike project)"
        initial_description = (
            "Project used to build a Bike. Part-time job is to also test Pykechain."
        )
        initial_start_date = datetime.datetime(2018, 12, 5, tzinfo=None)
        initial_due_date = datetime.datetime(2018, 12, 8, tzinfo=None)
        initial_tags = ["tag_one", "tag_two"]
        team_one, team_two = self.client.teams()[:2]

        self.scope.edit(
            name=initial_name,
            description=initial_description,
            tags=initial_tags,
            start_date=initial_start_date,
            due_date=initial_due_date,
            team=team_two,
        )

        # Edit without mentioning values, everything should stay the same
        new_name = "Just Pykechain testing (bike project)"
        self.scope.edit(name=new_name)

        # testing
        self.assertEqual(self.scope.name, new_name)
        self.assertEqual(self.scope.description, initial_description)
        self.assertEqual(
            self.scope.start_date.strftime("%Y/%m/%d, %H:%M:%S"),
            initial_start_date.strftime("%Y/%m/%d, %H:%M:%S"),
        )
        self.assertEqual(
            self.scope.due_date.strftime("%Y/%m/%d, %H:%M:%S"),
            initial_due_date.strftime("%Y/%m/%d, %H:%M:%S"),
        )
        self.assertEqual(self.scope.tags, initial_tags)

        # Edit with clearing the values, name and status cannot be cleared
        self.scope.edit(
            name=None, description=None, tags=None, start_date=None, due_date=None, status=None
        )
        self.scope.refresh()
        self.assertEqual(self.scope.name, new_name)
        self.assertEqual(self.scope.description, "")
        self.assertEqual(self.scope.start_date, None)
        self.assertEqual(self.scope.due_date, None)
        self.assertEqual(self.scope.tags, list())

    # v2.3.3
    def test_edit_scope_team(self):
        """Test capabilities of changing team scope"""

        team_one, team_two = self.client.teams()[:2]

        self.scope.edit(team=team_one)
        self.assertEqual(self.scope.team, team_one)

        self.scope.edit(team=team_two)
        self.assertEqual(self.scope.team, team_two)

    def test_edit_project_info(self):
        self.scope.edit(project_info=self.project_info)

        retrieved_project_info = self.scope.get_project_info()

        self.assertIsInstance(retrieved_project_info, list)
        self.assertListEqual(retrieved_project_info, self.project_info)

    def test_clear_project_info_edit_project(self):
        self.scope.set_project_info(project_info=self.project_info)

        retrieved_project_info = self.scope.get_project_info()

        self.assertIsInstance(retrieved_project_info, list)
        self.assertListEqual(retrieved_project_info, self.project_info)

        # clean up the project info
        self.scope.edit(project_info=list())

        retrieved_project_info = self.scope.get_project_info()

        self.assertIsInstance(retrieved_project_info, list)
        self.assertListEqual(retrieved_project_info, [])

    def test_set_landing_page(self):
        tasks = [
            self.scope.activities()[0],
            KEChainPages.DATA_MODEL,
        ]

        for task in tasks:
            with self.subTest(msg=task):
                self.scope.set_landing_page(activity=task)

    def test_get_landing_page(self):
        landing_page = self.scope.get_landing_page_url()

        self.assertIsNone(landing_page)

        self.scope.set_landing_page(activity=self.scope.activities()[0])
        landing_page = self.scope.get_landing_page_url()

        self.assertIsInstance(landing_page, str)
        self.assertTrue(is_url(self.client.api_root + landing_page))

    def test_set_project_info(self):
        self.scope.set_project_info(project_info=self.project_info)

        retrieved_project_info = self.scope.get_project_info()

        self.assertIsInstance(retrieved_project_info, list)
        self.assertListEqual(retrieved_project_info, self.project_info)

    def test_get_project_info(self):
        retrieved_project_info = self.scope.get_project_info()

        self.assertListEqual(retrieved_project_info, [])

        self.scope.set_project_info(project_info=self.project_info)

        retrieved_project_info = self.scope.get_project_info()
        self.assertListEqual(retrieved_project_info, self.project_info)

    def test_set_project_info_with_wrong_attributes(self):
        with self.assertRaises(ValidationError):
            self.scope.set_project_info(project_info={})
        with self.assertRaises(ValidationError):
            project_info_too_many_attributes = self.project_info
            for prop_dict in project_info_too_many_attributes:
                prop_dict['some_key'] = "some value"
            self.scope.set_project_info(project_info=project_info_too_many_attributes)
        with self.assertRaises(ValidationError):
            for prop in self.project_info:
                prop.pop('id')
            self.scope.set_project_info(project_info=self.project_info)

    def test_empty_project_info(self):
        self.scope.set_project_info(project_info=self.project_info)

        retrieved_project_info = self.scope.get_project_info()

        self.assertIsInstance(retrieved_project_info, list)
        self.assertListEqual(retrieved_project_info, self.project_info)

        # clean up the project info
        self.scope.set_project_info(project_info=list())

        retrieved_project_info = self.scope.get_project_info()

        self.assertIsInstance(retrieved_project_info, list)
        self.assertListEqual(retrieved_project_info, [])


# coding: utf-8

import os
import sys
import copy
import logging
import pytest
import collections
import hubblestack.config
import pstats
import subprocess
import yaml
import hubblestack.loader
import hubblestack.daemon
import hubblestack.syspaths

log = logging.getLogger(__name__)
Loaders = collections.namedtuple("Loaders", 'opts mods grains utils'.split())
TestPaths = collections.namedtuple("TestPaths", 'tests sources hubble output ext'.split())

tests_dir = os.path.dirname(os.path.realpath(__file__))
sources_dir = os.path.dirname(os.path.dirname(tests_dir))
hubble_dir = os.path.join(sources_dir, 'hubblestack')
output_dir = os.path.join(tests_dir, 'output')
ext_dir = os.path.join(hubble_dir, 'extmods')

@pytest.fixture
def test_paths():
    return TestPaths(tests_dir, sources_dir, hubble_dir, output_dir, ext_dir)

if sources_dir not in sys.path:
    sys.path.insert(0, sources_dir)

# docker as root, developer homedir as 1000
# set HS_CHOWN_BACK=1000:1000 to chown -R $HS_CHOWN_BACK sources_dir
please_chown_my_files_back_to_me = 'HS_CHOWN_BACK'

# if true (in the string sense), attempt to profile hubble during testing
profile_enabling_env_var = 'HS_PROFILE'

@pytest.fixture(scope='session')
def osqueryd():
    tests_dir = os.path.dirname(os.path.realpath(__file__))
    sources_dir = os.path.dirname(os.path.dirname(tests_dir))
    config = os.path.join(sources_dir, 'conf', 'osqueryd.conf')
    cmd = ['osqueryd', '--disable-logging', '--config_path', config]
    with open(os.devnull, 'w') as fh:
        p = subprocess.Popen(cmd, stdout=fh, stderr=fh)
        yield p

def quiet_salt():
    class QuietSalt(logging.Filter):
        def filter(self, record):
            if record.name.startswith('salt.'):
                if 'Executing command' in record.msg:
                    record.levelno = logging.DEBUG
                    record.levelname = 'DEBUG'
                elif 'nebula' in record.msg:
                    pass
                else:
                    return 0
            return True

    qs = QuietSalt()
    for handler in logging.root.handlers:
        handler.addFilter(qs)

def update_config(config_file):
    with open(config_file) as ifh:
        dat = yaml.load(ifh, Loader=yaml.SafeLoader)

    dat['log_file'] = os.path.join(output_dir, 'hubble.log')
    dat['cachedir'] = os.path.join(output_dir, '.cache')
    dat['pidfile']  = os.path.join(output_dir, '.pidfile')

    with open(config_file, 'w') as ofh:
        yaml.dump(dat, ofh)

@pytest.fixture(scope='session')
def config_file():
    return os.path.join(tests_dir, 'resources', 'test.config')

@pytest.fixture(scope='session')
def HSL(config_file):
    if not os.path.isdir(output_dir):
        os.makedirs(output_dir)
    quiet_salt()
    update_config(config_file)
    hubblestack.daemon.load_config(['-c', config_file])
    hsl = Loaders(hubblestack.daemon.__opts__, hubblestack.daemon.__mods__,
        hubblestack.daemon.__grains__, hubblestack.daemon.__utils__)
    yield hsl

@pytest.fixture(scope='function')
def __mods__(HSL):
    return HSL.mods

@pytest.fixture(scope='function')
def __utils__(HSL):
    return HSL.utils

@pytest.fixture(scope='function')
def __grains__(HSL):
    return copy.deepcopy(HSL.grains)

@pytest.fixture(scope='function')
def __opts__(HSL):
    return copy.deepcopy(HSL.opts)

##### profiling
prof_filenames = set()

@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_call(item):
    if os.environ.get(profile_enabling_env_var):
        import cProfile
        filename, lineno, funcname = item.location # item.name is just the function name
        profile_name = filename.split('/')[-1][:-3]
        profile_name += '-' + funcname + '.pstats'
        prof_filename = os.path.join(output_dir, profile_name)
        prof_filenames.add(prof_filename)
        try:
            os.makedirs(output_dir)
        except OSError:
            pass
        prof = cProfile.Profile()
        prof.enable()

    yield

    if os.environ.get(profile_enabling_env_var):
        prof.dump_stats(prof_filename)
        prof_filenames.add(prof_filename)

def pytest_sessionfinish(session, exitstatus):
    if os.environ.get(profile_enabling_env_var):
        # shamelessly ripped from pytest-profiling — then modified to taste
        if prof_filenames:
            combined = None
            for pfname in prof_filenames:
                if not os.path.isfile(pfname):
                    continue
                if combined is None:
                    combined = pstats.Stats(pfname)
                else:
                    combined.add(pfname)

            if combined:
                cfilename = os.path.join(output_dir, 'combined.pstats')
                csvg      = os.path.join(output_dir, 'combined.svg')
                combined.dump_stats(cfilename)

                gp_cmd = [ 'gprof2dot', '-f', 'pstats', cfilename ]

                gp = subprocess.Popen(gp_cmd, stdout=subprocess.PIPE)
                dp = subprocess.Popen(['dot', '-Tsvg', '-o', csvg], stdin=gp.stdout)
                dp.communicate()

    pcmf = os.environ.get(please_chown_my_files_back_to_me)
    if pcmf:
        p = subprocess.Popen(['chown', '-R', pcmf, sources_dir])
        p.communicate()
        print('\nchowned back files to {}'.format(pcmf))


import os
import requests
from dotenv import load_dotenv

load_dotenv()
DISCORD_KEY = os.getenv('DISCORD_KEY')
RIOT_API_KEY = os.getenv('RIOT_API_KEY')

WORKING_DIR = os.getcwd()

PATHS = {
     'cwd':WORKING_DIR
    ,'help':os.path.join(WORKING_DIR,'helptext.txt')
    ,'version':os.path.join(WORKING_DIR, 'version.txt')
}

REQUEST_COUNT = 0

SEASONS = requests.get('http://static.developer.riotgames.com/docs/lol/seasons.json').json()
CURR_SEASON = SEASONS[-1]['id']

VERSION = {
     'summoner':'4'
    ,'match':'4'
    ,'clash':'1'
    ,'league':'4'
}

REGION = {
    'north_america':'NA1'
}

QUEUE_ID = {
    'clash':'700'
}

TEAM = {
    'sloppy_toppy':'926281'
}

URL = {
     'base':'https://{REGION}.api.riotgames.com/lol'
    ,'summoner_by_name':'/summoner/v{VER}/summoners/by-name/{queryval}' #summonername
    ,'summoner_by_id':'/summoner/v{VER}/summoners/{queryval}' #SummonerId
    ,'clash_match_by_account':'/match/v{VER}/matchlists/by-account/{queryval}'+'?queue={queue}'.format(queue=QUEUE_ID['clash']) #accountid
    ,'match_by_account':'/match/v{VER}/matchlists/by-account/{queryval}'+'?endIndex=50' #accountid
    ,'match_by_match':'/match/v{VER}/matches/{queryval}' #matchId
    ,'clash_by_team':'/clash/v{VER}/teams/{queryval}' #teamId
    ,'clash_by_summoner':'/clash/v{VER}/players/by-summoner/{queryval}' #summonerId
    ,'clash_tourn_by_team':'/clash/v{VER}/tournaments/by-team/{queryval}' #teamId
    ,'league_by_summoner':'/league/v{VER}/entries/by-summoner/{queryval}' #summonerId
    ,'dd_champion':'http://ddragon.leagueoflegends.com/cdn/10.9.1/data/en_US/champion.json'
}

CHAMP_JSON = requests.get(URL['dd_champion']).json()
CHAMP_DATA = CHAMP_JSON['data']
CHAMP_NAME_LOOKUP = {}
for champ in CHAMP_DATA:
    champ_id = int(CHAMP_DATA[champ]['key'])
    champ_name = CHAMP_DATA[champ]['name']
    CHAMP_NAME_LOOKUP.update({champ_id:champ_name})

#for item in CHAMP_NAME_LOOKUP:
    #print(item + ' ' + CHAMP_NAME_LOOKUP[item])


"""Buildbot module that handles communications between the Buildbot and
GitHub."""

from config import cfg

import events
import utils

import collections
import json
import logging
import os
import os.path
import queue
import re
import requests
import uuid

def make_netstring(s):
    """Creates a netstring from a blob of bytes."""
    return str(len(s)).encode('ascii') + b':' + s + b','

def make_build_request(repo, pr_id, job_id, baserev, headrev, patch, who,
                       comment):
    """Creates a build request binary blob in the format expected by the
    buildbot."""

    request_dict = {
        'branch': '',
        'builderNames': cfg.buildbot.pr_builders,
        'jobid': job_id,
        'baserev': baserev,
        'patch_level': 1,
        'patch_body': patch,
        'who': who,
        'comment': comment,
        'properties': {
            'branchname': 'pr-%d' % pr_id,
            'headrev': headrev,
            'shortrev': headrev[:6],
            'pr_id': pr_id,
            'repo': repo,
        },
    }
    encoded = json.dumps(request_dict, ensure_ascii=True).encode('ascii')
    version = make_netstring(b'5')
    return version + make_netstring(encoded)

def send_build_request(build_request):
    """Stores the build request (atomically) in the buildbot jobdir."""

    path = os.path.join(cfg.buildbot.jobdir, 'tmp', str(uuid.uuid4()))
    open(path, 'wb').write(build_request)
    final_path = os.path.join(cfg.buildbot.jobdir, 'new', str(uuid.uuid4()))
    os.rename(path, final_path)
    logging.info('Sent build request: %r', final_path)

class PullRequestBuilder:
    def __init__(self):
        self.queue = queue.Queue()

    def push(self, in_behalf_of, trusted, repo, pr_id):
        self.queue.put((in_behalf_of, trusted, repo, pr_id))

    def run(self):
        while True:
            in_behalf_of, trusted, repo, pr_id = self.queue.get()

            # To check if a PR is mergeable, we need to request it directly.
            pr = requests.get('https://api.github.com/repos/%s/pulls/%d'
                    % (repo, pr_id)).json()
            logging.info('PR %s mergeable: %s (%s)', pr_id, pr['mergeable'],
                    pr['mergeable_state'])

            base_sha = pr['base']['sha']
            head_sha = pr['head']['sha']

            if not trusted:
                status_evt = events.PullRequestBuildStatus(repo, head_sha,
                        'default', 'failure', '',
                        'PR not built because %s is not auto-trusted.'
                            % in_behalf_of)
                events.dispatcher.dispatch('prbuilder', status_evt)
                continue

            # mergeable can be None!
            if pr['mergeable'] is False:
                status_evt = events.PullRequestBuildStatus(repo, head_sha,
                        'default', 'failure', '',
                        'PR cannot be merged, please rebase.')
                events.dispatcher.dispatch('prbuilder', status_evt)
                continue

            status_evt = events.PullRequestBuildStatus(repo, head_sha,
                        'default', 'success', '',
                        'Very basic checks passed, handed off to Buildbot.')
            events.dispatcher.dispatch('prbuilder', status_evt)

            for builder in cfg.buildbot.pr_builders:
                status_evt = events.PullRequestBuildStatus(repo, head_sha,
                        builder, 'pending', cfg.buildbot.url + '/waterfall',
                        'Auto build in progress')
                events.dispatcher.dispatch('prbuilder', status_evt)

            patch = requests.get('https://github.com/%s/pull/%d.patch'
                                 % (repo, pr_id)).text
            req = make_build_request(repo, pr_id,
                    '%d-%s' % (pr_id, head_sha[:6]), base_sha,
                    head_sha, patch,
                    'Central (on behalf of: %s)' % in_behalf_of,
                    'Auto build for PR #%d (%s).' % (pr_id, head_sha))
            send_build_request(req)

class PullRequestListener(events.EventTarget):
    """Listens for new or synchronized pull requests and starts a new build."""

    def __init__(self, builder):
        super(PullRequestListener, self).__init__()
        self.builder = builder

    def accept_event(self, evt):
        return evt.type == events.GHPullRequest.TYPE

    def push_event(self, evt):
        if evt.action == 'opened' or evt.action == 'synchronize':
            if evt.repo in cfg.github.maintain:
                self.builder.push(evt.author, evt.safe_author, evt.repo,
                                  evt.id)

class ManualPullRequestListener(events.EventTarget):
    """Listens for comments from trusted users on PRs for a keyword to build
    a PR from an untrusted user."""

    def __init__(self, builder):
        super(ManualPullRequestListener, self).__init__()
        self.builder = builder

    def accept_event(self, evt):
        return evt.type == events.GHIssueComment.TYPE

    def push_event(self, evt):
        if not evt.safe_author:
            return
        if cfg.github.rebuild_command.lower() not in evt.body.lower():
            return
        if evt.repo not in cfg.github.maintain:
            return
        self.builder.push(evt.author, evt.safe_author, evt.repo, evt.id)

class IRCRebuildListener(events.EventTarget):
    """Listen for rebuild commands on IRC."""

    def __init__(self, builder):
        super(IRCRebuildListener, self).__init__()
        self.builder = builder

    def accept_event(self, evt):
        return evt.type == events.IRCMessage.TYPE

    def push_event(self, evt):
        trusted = 'o' in evt.modes
        if not evt.direct or not trusted:
            return
        matches = re.search(r'\brebuild (pr ?)?(?P<pr_id>\d+)\b', evt.what, re.I)
        if not matches:
            return
        pr_id = matches.group('pr_id')
        try:
            pr_id = int(pr_id)
        except ValueError:
            return
        self.builder.push(evt.who, trusted, cfg.irc.rebuild_repo, pr_id)

class BuildStatusCollector:
    def __init__(self):
        self.queue = queue.Queue()

    def push(self, evt):
        self.queue.put(evt)

    def run(self):
        while True:
            evt = self.queue.get()
            builder = evt.payload.build.builderName
            props = { a: b for (a, b, _) in evt.payload.build.properties }
            has_all_required = True
            for required in ('headrev', 'repo', 'buildnumber', 'pr_id'):
                if required not in props:
                    has_all_required = False
                    break  # Not PR build.
            if not has_all_required:
                continue
            headrev = props['headrev']
            repo = props['repo']
            buildnumber = props['buildnumber']
            pr_id = props['pr_id']
            success = evt.payload.results in (0, 1)  # SUCCESS/WARNING

            if builder in cfg.buildbot.pr_builders:
                url = cfg.buildbot.url + '/builders/%s/builds/%s' % (
                        builder, buildnumber)

                if not success:
                    evt = events.PullRequestBuildStatus(repo, headrev, builder,
                            'failure', url,
                            'Build failed on builder %s' % builder)
                    events.dispatcher.dispatch('buildbot', evt)
                else:
                    evt = events.PullRequestBuildStatus(repo, headrev, builder,
                            'success', url, 'Build succeeded on the Buildbot.')
                    events.dispatcher.dispatch('buildbot', evt)
            elif builder in cfg.buildbot.fifoci_builders and success:
                evt = events.PullRequestFifoCIStatus(
                        repo, headrev, builder, pr_id)
                events.dispatcher.dispatch('buildbot', evt)

class BBHookListener(events.EventTarget):
    def __init__(self, collector):
        super(BBHookListener, self).__init__()
        self.collector = collector

    def accept_event(self, evt):
        return evt.type == events.RawBBHook.TYPE

    def push_event(self, evt):
        if evt.bb_type == 'buildFinished':
            self.collector.push(evt.raw)

def start():
    """Starts all the Buildbot related services."""

    pr_builder = PullRequestBuilder()
    events.dispatcher.register_target(PullRequestListener(pr_builder))
    events.dispatcher.register_target(ManualPullRequestListener(pr_builder))
    events.dispatcher.register_target(IRCRebuildListener(pr_builder))
    utils.DaemonThread(target=pr_builder.run).start()

    collector = BuildStatusCollector()
    events.dispatcher.register_target(BBHookListener(collector))
    utils.DaemonThread(target=collector.run).start()


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import logging
import random

import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
import scipy.integrate as integrate
from scipy.stats import cauchy

from statesim.state import State

logger = logging.getLogger(__name__)

class InternationalSystem(object):
    """ Main object controlling the simulation.

    Attributes
    ----------
    config : dict
        houses parameters governing the simulation

    Methods
    -------
    generate_world()
        Generates a dict of State objects and their borders and diplomacy
    random_power()
        Used to randomly assign initial power levels to states
    """

    def __init__(self, config):
        """
        Parameters
        ----------
        config : dict
            houses parameters governing the simulation
        """
        self.config = config
        self.turn = 0
        self.state = []
        self.system = []
        self.wars = []
        self.network = self.generate_world()

        self.draw_borders(self.network)

    def generate_world(self):
        """ Creates the world. First, uses networkx to generate a 'map' which
        is represented by a network with each node as a state, and each edge as
        a border.

        The network is converted to a dictionary.

        The initial power distribution is calculated and assigned to each state.
        """

        network = nx.random_regular_graph(self.config['network_p'],
                                          self.config['network_n'],
                                          seed=self.config['seed'])

        # Initialize all states
        world = {}
        for i in network.nodes:
            state = State(name=i, power=self.random_power(),
                          misperception=self.config['misperception_sigma'])
            world[i] = state

        self.world = world

        # Record initial distribution of power
        power_dist = np.array([i.power for i in world.values()])
        first_turn = {'turn': 0,
                      'n': len(world),
                      'min': np.min(power_dist),
                      'p25': np.percentile(power_dist, 0.25),
                      'p50': np.percentile(power_dist, 0.5),
                      'p75': np.percentile(power_dist, 0.75),
                      'max': np.max(power_dist),
                      'avg': np.mean(power_dist),
                      'sd': np.std(power_dist)}
        self.system.append(first_turn)

        return network

    def draw(self):
        """
        """
        nx.draw_networkx(self.network)

    def draw_borders(self, network):
        """ """
        # Wipe out existing borders
        for i in self.world.keys():
            try:
                neighbors = [j for j in self.network.neighbors(i) if j != i]
                self.world[i].border = [self.world[j] for j in neighbors]
            except KeyError:
                raise

    def likelihood_victory(self, a, b):
        """ Returns the probability state A wins a war against state B.

        Computes the area underneath a logistic function between the log of
        the power ratio of the two states.

        The parameter victory_sigma controls how 'steep' the curve is. As
        sigma increases, chance becomes more important; less powerful states
        have a greater chance of victory against more pwoerful states. The
        power ratio becomes more and more deterministic and sigma decreases.
        """
        a_power = sum(a.alliance)
        b_power = sum(b.alliance)
        sigma = self.config['victory_sigma']
        const = 1 / np.sqrt(np.pi * sigma)
        f = lambda x: np.exp( -1 * np.square(x / sigma) )
        area = integrate.quad( f, -np.inf, np.log(a_power / b_power) )
        lv_init = area[0] * const
        if lv_init < 0:
            lv = 0.0
        elif lv_init > 1:
            lv = 1.0
        else:
            lv = lv_init
        return lv

    def record_peace(self, a, b):
        """ Records outcomes where no war occurs to war data set.
        """
        peace = {'turn': self.turn,
                 'war': False,
                 'offense': a.name,
                 'defense': b.name,
                 'offense0': a.power,
                 'defense0': b.power,
                 'offense1': sum([i.power for i in a.alliance]),
                 'defense1': sum([i.power for i in b.alliance]),
                 'outcome': 'NA'}

        self.wars.append(peace)

        return None

    def war(self, a, b):
        """ Determines which side wins the war. Returns object specifying data,
        about the war, which is then used to determine war costs, etc.

        Calculates the probility a beats b, using a logistic function. Then
        uses this probability as p in a single binomial trial. If result is 1,
        a wins; else b wins.

        Returns
        """
        lv = self.likelihood_victory(a, b)
        victory = bool( np.random.binomial(1, lv, 1) )

        war = {'turn': self.turn,
               'war': True,
               'offense': a.name,
               'defense': b.name,
               'offense0': a.power,
               'defense0': b.power,
               'offense1': sum([i.power for i in a.alliance]),
               'defense1': sum([i.power for i in b.alliance]),
               'outcome': a.name if victory == True else b.name}
        self.wars.append(war)

        return {'victor': a if victory == True else b,
                'loser': b if victory == True else a,
                'offense': a,
                'defense': b,
                'likelihood_victory': lv,
                'lsr': max(a.power, b.power) / (a.power + b.power)}

    def assess_war_damage(self, war):
        """
        Imposes a war cost equally to all sides. The parameter max_war_cost
        controls how costly this can be. By default, since max_war_cost is .25,
        no state can lose more than 25 percent of their power in a war. The war
        war cost percentage is applied equally to all victor and loser states
        and their allies.

        2. Take reparations form losing side and distribute to winning side
        """
        # War cost
        max_cost = self.config['max_war_cost']
        lsr = war['lsr']
        war_cost = (1.0 - ((lsr - 0.5) / 0.5)) * max_cost
        weight = min(self.config['war_cost_disp'], max_cost * np.random.uniform())

        victor_states = war['victor'].alliance
        loser_states = war['loser'].alliance

        #################
        # Versailles rule

        if self.config['versailles']:

            # if state is victor:
            if war['victor'] == war['offense']:
            # target surrenders LV% of power
                transfer = war['loser'].power * war['likelihood_victory']
                war['loser'].power = war['loser'].power - transfer
                war['victor'].power += transfer
            # elif target is victor:
            elif war['victor'] == war['defense']:
            # state surrenders 1-LV % of power
                transfer = war['victor'].power * (1 - war['likelihood_victory'])
                war['victor'].power = war['victor'].power - transfer
                war['loser'].power += transfer

        #################

        for i in victor_states:
            cost = max(war_cost - weight, 0.01)
            i.power = max(i.power * (1 - cost), 1)  # do not let victors fall below 1
            logger.info('%s assessed war damage of %s percent' % (i, round(cost, 2)*100))

        for i in loser_states:
            cost = min(1, war_cost + weight)
            i.power = i.power * (1 - cost)
            logger.info('%s assessed war damage of %s percent' % (i, round(cost, 2)*100))

        # Spoils -- TODO seperate function
        total_reparations = sum( [i.power * self.config['reparations'] for i in loser_states] )
        for i in loser_states:
            reparations = max(i.power * self.config['reparations'], .01)
            i.power = i.power - reparations
            logger.info('%s is forced to pay %s power units in reparations' % (i, round(reparations, 2)))

        # Each victor recieves a portion of spoils, proportionate to their
        # contribution to total power of alliance
        total_victor_power = sum(victor_states)
        for i in victor_states:
            reparations = total_reparations * (i.power / total_victor_power)
            i.power += reparations
            logger.info('%s has claimed %s power units as spoils of war' % (i, round(reparations, 2)))

        for k in self.world.keys():
            if self.world[k].power < 1.0:
                self.world[k].conquered = war['victor']

    def end_turn(self):
        """ 1. Remove states with no power left; if so, redraw network and borders
        2. Wipe out alliances
        3. Economic growth

        Power adjustment segment. A. Eliminate all states with no remaining
        power or cells of territory. B. End the run if only one state is left
        or the iteration limit is reached. Otherwise, grant all remaining states
         internal power growth of 3 percent. The simulation moves to segment.
        """
        for k in list(self.world.keys()):
            if self.world[k].power < 1:
                logger.info('State %s is removed from system' % k)

                # Record state death
                # STATE: state ID | turn death |
                death = {'state_id': k,
                         'survived_to': self.turn}
                self.state.append(death)

                # If conquered, give borders to conquering state and delete from system
                n = k
                neighbors = [j for j in self.network.neighbors(n) if self.world[j].power > 1]
                new_borders = [j for j in neighbors if j != k and self.world[j].power > 1]
                for j in new_borders:
                    self.network.add_edge(self.world[k].conquered.name, j)
                self.network.remove_node(k)
                del self.world[k]
            else:
                self.world[k].alliance = [self.world[k]]
                # growth = np.random.normal(loc=self.config['growth_mu'],
                #                           scale=self.config['growth_sigma'])
                growth = self.random_growth()
                self.world[k].power = max(self.world[k].power * (1 + growth), 1)  # cannot grow below 0

                # Update power0 assessments of themselves
                power = self.world[k].power
                power0 = power * np.random.normal(loc=1, scale=self.config['misperception_sigma'])
                self.world[k].power0 = power0

        self.draw_borders(self.network)

        # Record distribution of power
        power_dist = np.array([i.power for i in self.world.values()])
        power_record = {'turn': self.turn,
                        'n': len(self.world),
                        'min': np.min(power_dist),
                        'p25': np.percentile(power_dist, 0.25),
                        'p50': np.percentile(power_dist, 0.5),
                        'p75': np.percentile(power_dist, 0.75),
                        'max': np.max(power_dist),
                        'avg': np.mean(power_dist),
                        'sd': np.std(power_dist)}
        self.system.append(power_record)

        logger.info('Turn ended')

    def random_growth(self):
        """ Cauchy distribution with barriers at -30 and 15 percent.
        """
        growth = cauchy.rvs(size=1, loc=self.config['growth_mu'],
                            scale=self.config['growth_sigma'])[0]
        if growth < -0.30:
            return -0.30
        elif growth > 0.15:
            return 0.15
        else:
            return growth

    def random_power(self):
        """ Used to assign a random power level to a state in the
        initialization phase.

        Generates a random number from a normal distribution with a mean and
        standard deviation specified in the config file. Does not permit power
        to fall below one.
        """
        power_init = np.random.normal(loc=self.config['power_dist_mu'],
                                      scale=self.config['power_dist_sigma'])
        power = max(power_init, 1)
        return power

    def plot_power(self):
        """
        """
        x = [self.world[k].power for k in self.world.keys()]
        plt.hist(x)

    def random_state(self):
        """ Returns a random state from the world, propotional to its share
        of power in the world.
        """
        states = [k for k in self.world.keys()]
        total_power = sum([self.world[i].power for i in states])
        power_dist = [self.world[i].power / total_power for i in states]
        random_state = np.random.choice(states, 1, power_dist)[0]

        return self.world[random_state]


import math

from control.shapes import ControlSquare, ControlRectangle, Shape
from no_division.shapes import NoDivisionTriangle
from utilities import ConstructorSet

CIRCLE_CONSTANT = math.pi * 0.5 * 0.5

class PrecomputedConstCircle(Shape):
    def __init__(self, width: float):
        self.width = width

    def area(self) -> float:
        return CIRCLE_CONSTANT * self.width * self.width

class PrecomputedClassAttrCircle(Shape):
    circle_const =  math.pi * 0.5 * 0.5
    def __init__(self, width: float):
        self.width = width

    def area(self) -> float:
        return self.circle_const * self.width * self.width

PRECOMPUTED_CONSTRUCTORS: ConstructorSet = {
    'square': ControlSquare,
    'rectangle': ControlRectangle,
    'triangle': NoDivisionTriangle,
    'circle': PrecomputedConstCircle
}

PRECOMPUTED_CLASS_ATTR_CONSTRUCTORS: ConstructorSet = {
    'square': ControlSquare,
    'rectangle': ControlRectangle,
    'triangle': NoDivisionTriangle,
    'circle': PrecomputedClassAttrCircle,
}


import os
import trimesh
import os.path as path
import configargparse
from trimesh_handler import *
import timeit

# --------------------------------------------------------#
# ------------------------ PARSER ------------------------#
# --------------------------------------------------------#

def get_parser():
    parser = configargparse.get_argument_parser()

    parser.add_argument('--input', '-in', type=str,
                        help='object name to use as input from inputs folder, input file MUST be in inputs folder')
    parser.add_argument('--input-type', '-t', type=str, default='ply',
                        help='input file type, defauld is ply')
    parser.add_argument('--iterations', '-i', type=int, default=1,
                        help='number of iterations to run, default is a single iteration')
    parser.add_argument('--results', '-r', type=int, default=1,
                        help='number of results to provide, must be maximum as number of iterations')
    parser.add_argument('--constraints', '-c', nargs='+', type=int, required=True,
                        help='a list of constraints chosen from 0 to 5: [0-2]:Rotational, [3-5]:XYZ')
    parser.add_argument('--convex-hull', '-cv', action='store_true', required=False,
                        help='a flag to use input`s convex hull')

    parsed = parser.parse_args()
    parsed.constraints = np.array([[1.0 if i in parsed.constraints else 0.0 for i in range(6)]])
    parsed.clustering = parsed.results < parsed.iterations
    assert parsed.iterations >= 0 and parsed.results >= 0, 'iteration must be bigger than 0'
    assert parsed.results <= parsed.iterations, 'iterations must be bigger than results'

    return parsed

# ------------------------------------------------------#
# ------------------------ MAIN ------------------------#
# ------------------------------------------------------#

def input_path(filename: str, file_type='ply'):
    file_full_path = f'{path.pardir}{path.sep}{"inputs"}{path.sep}{filename}.{file_type}'
    if path.exists(file_full_path):
        return file_full_path
    else:
        raise ValueError('Given input file doesnt exist, please rerun with an existing file or add the wanted file into '
                         'inputs directory')

def main():
    vectors = []
    results = []

    args = get_parser()
    mesh_data = trimesh_handler(
        mesh=trimesh.load(input_path(args.input, args.input_type)),
        constraints=args.constraints,
        convex_hull=args.convex_hull
    )

    # Folders preparing
    c = ''.join([str(i) for i in range(6) if args.constraints[0][i]])
    out_folder = f'{path.pardir}{path.sep}outputs{path.sep}{args.input}_{c}{path.sep}'
    all_folder = f'{out_folder}all'
    os.makedirs(all_folder, exist_ok=True)
    start = timeit.default_timer()
    for iteration in range(args.iterations):
        print(f'\n Staring computing for {args.input} ')
        print(f'\n\t - Computing iteration: #{iteration}')
        starting_point = calc_starting_point(mesh_data)
        curr_shell = shell_computation(mesh_data, starting_point)
        results.append(mesh_data.current_holder_T)
        vectors.append(curr_shell)
        out_path = f'{all_folder}{path.sep}{args.input}_{iteration}.obj'
        mesh_data.current_holder_T.export(out_path)
        print(f'\n\t\t ~ Exporting: {out_path}')

    if args.clustering:
        clustered_folder = f'{out_folder}clustered'
        os.makedirs(clustered_folder, exist_ok=True)

        print(f'\n\t Running Clustering {args.iterations}->{args.results}:')
        clustering = clustering_fit(vectors, args.results)
        clustered = [False for i in range(args.results)]

        for i in range(len(vectors)):
            for j in range(i, len(vectors)):
                if clustering.labels_[j] == i:
                    if not clustered[i]:
                        out_path = f'{clustered_folder}{path.sep}{args.input}_{i}.obj'
                        results[i].export(out_path)
                        print(f'\t ~ Export: {out_path}')
                        clustered[i] = True

    print(f'\nFinished running Auto-Connect for {args.input} \n')
    print(f'Execution took: {timeit.default_timer()-start} seconds\n')

if __name__ == "__main__":
    main()


import torch
import torch.nn as nn
from torch.autograd import Variable
# 导入torch.nn模块。实际上，“nn”是neural networks（神经网络）的缩写
#  nn.RNN的参数设置
#  input_size   输入x的特征大小(以mnist图像为例，特征大小为28*28 = 784)
#  hidden_size   隐藏层h的特征大小 即隐藏层节点的个数
#  num_layers    循环层的数量（RNN中重复的部分） 层数
#  nonlinearity   激活函数 默认为tanh，可以设置为relu
#  bias   是否设置偏置，默认为True
#  batch_first   默认为false, 设置为True之后，输入输出为(batch_size, seq_len, input_size)
#  dropout   默认为0
#  bidirectional   默认为False，True设置为RNN为双向

class DKT(nn.Module):
    def __init__(self, input_dim, hidden_dim, layer_dim, output_dim):
        super(DKT, self).__init__()
        self.hidden_dim = hidden_dim
        self.layer_dim = layer_dim
        self.output_dim = output_dim
        self.rnn = nn.RNN(input_dim, hidden_dim, layer_dim, batch_first=True,nonlinearity='tanh')
        self.fc = nn.Linear(self.hidden_dim, self.output_dim)

    def forward(self, x):
        device = x.device
        # torch.zeros 返回一个形状为为size,类型为torch.dtype，里面的每一个值都是0的tensor
        h0 = Variable(torch.zeros(self.layer_dim, x.size(0), self.hidden_dim)).to(device)
        out,hn = self.rnn(x, h0)
        res = self.fc(out)
        return res

# 输出形状
# DKT(
#   (rnn): RNN(246, 100, dropout=0.02)
#   (dense): Linear(in_features=100, out_features=123, bias=True)
#   (sig): Sigmoid()
#  )


#!/usr/bin/env python3
"""this is a pagination module
"""

from typing import Tuple

def index_range(page: int, page_size: int) -> Tuple[int, int]:
    """return a start index and an end index as tuple
    """

    if page <= 0 or page_size <= 0:
        raise ValueError("Page and page_size must be positive integers")

    start_index = (page - 1) * page_size
    end_index = page * page_size

    return (start_index, end_index)


from django.shortcuts import render, redirect
from accounts.models import *
from .forms import OrderForm, CustomerForm, ProductForm
# Create your views here.
from django.http import HttpResponse

def home(request):
    orders = Order.objects.all()
    customers = Customer.objects.all()
    total_orders = orders.count()
    order_delivered = orders.filter(status='Delivered').count()
    order_pending = orders.filter(status='Pending').count()
    context = {'orders': orders, 'customers': customers, 'total_orders': total_orders,
               'order_delivered': order_delivered, 'order_pending': order_pending}
    return render(request, 'accounts/dashboard.html', context)

def products(request):
    products = Product.objects.all()
    return render(request, 'accounts/products.html', {'products': products})

def customer(request, pk):
    customer = Customer.objects.get(id=pk)
    orders = customer.order_set.all()
    total_order = orders.count()
    context = {'customer': customer, 'orders': orders, 'total_order': total_order}
    return render(request, 'accounts/customer.html', context)

def createOrder(request):
    form = OrderForm()
    if request.method == 'POST':
        form = OrderForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/')
    context = {'form': form}
    return render(request, 'accounts/order_form.html', context)

def updateOrder(request, pk):
    order = Order.objects.get(id=pk)
    form = OrderForm(instance=order)
    context = {'form': form}
    if request.method == 'POST':
        form = OrderForm(request.POST, instance=order)
        if form.is_valid():
            form.save()
            return redirect('/')
    return render(request, 'accounts/order_form.html', context)

def deleteOrder(request, pk):
    order = Order.objects.get(id=pk)
    if request.method == 'POST':
        order.delete()
        return redirect('/')
    context = {'item': order}
    return render(request, 'accounts/delete.html', context)

def createCustomer(request):
    form = CustomerForm()
    if request.method == 'POST':
        form = CustomerForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/')
    context = {'form': form}
    return render(request, 'accounts/customer_form.html', context)

def createProduct(request):
    form = ProductForm()
    if request.method == 'POST':
        form = ProductForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/')
    context = {'form': form}
    return render(request, 'accounts/product_form.html', context)


# -*- coding: utf-8 -*-
import sys
import cv2
import numpy as np

# 主函数
if __name__ == "__main__":
    # 输入图像矩阵，转换为array
    if len(sys.argv) > 1:
        image = cv2.imread(sys.argv[1], cv2.IMREAD_COLOR)
    else:
        print("Usage: python RGB.py imageFile")
        sys.exit(1)

    # 显示彩色图像
    cv2.imshow("bgr", image)

    # 得到三个颜色通道
    b = image[:,:,0]
    g = image[:,:,1]
    r = image[:,:,2]

    # 显示三个颜色通道
    cv2.imshow("b", b)
    cv2.imshow("g", g)
    cv2.imshow("r", r)

    cv2.waitKey(0)
    cv2.destroyAllWindows()


from __future__ import print_function

import modbus_tk
import modbus_tk.defines as cst
from modbus_tk import modbus_tcp, hooks
from utils import log_wrap
import time
import threading

# [ TODO ] Take care of wheel-up / wheel-down.

class StarCommand(object):
    '''
    class Move(object):
        STOP = 0
        LEFT = 1
        RIGHT = 2

    class Pick(object):
        STOP = 0
        FRAME_1 = 1
        FRAME_2 = 2

    class Place(object):
        STOP = 0
        FRAME_1 = 1
        FRAME_2 = 2

    class Button(object):
        NONE = 0
        START = 1
        STOP = 2
    '''
    class AgvTask(object):
        NO_TASK = 0
        GO = 1

    class AgvTaskStation(object):
        UNKNOWN = 0
        READY = 1
        PLACE = 2
        PICK = 3

    class ElfinTask(object):
        NO_TASK = 0
        READY = 1
        PLACE_1 = 2
        PLACE_2 = 3
        PICK_1 = 4
        PICK_2 = 5

class StarState(object):
    class AgvStation(object):
        UNKNOWN = 0
        PLACE = 1
        PICK = 2

    class InitState(object):
        UNINITIALIZED = 0
        READY = 1

    class TaskState(object):
        NO_TASK = 0
        FINISHED = 1
        RUNNING = 2
        ERROR = 255

    def __init__(self):
        self.Log = log_wrap( prefix = "[ Star State ] ")
        #self.response_move = 0
        #self.response_place = 0
        #self.response_pick = 0
        #self.response_button = 0
        #self.agv_position = StarState.AgvStation.UNKNOWN
        #self.init_state_elfin = StarState.InitState.UNINITIALIZED
        #self.init_state_agv = StarState.InitState.UNINITIALIZED

        self.elfin_task_id = 0
        self.elfin_task    = 0
        self.elfin_task_param_0 = 0
        self.elfin_task_param_1 = 0
        self.elfin_task_status = 0

        self.agv_task_id = 0
        self.agv_task    = 0
        self.agv_task_param_0 = 0
        self.agv_task_param_1 = 0
        self.agv_task_status = 0

    def debug_output(self):
        #self.Log.info("[ star state ] response_move = %s"%(self.response_move))
        #self.Log.info("[ star state ] response_place = %s"%(self.response_place))
        #self.Log.info("[ star state ] response_pick = %s"%(self.response_pick))
        #self.Log.info("[ star state ] response_button = %s"%(self.response_button))
        #self.Log.info("[ star state ] agv_position = %s"%(self.agv_position))
        #self.Log.info("[ star state ] init_state_elfin = %s"%(self.init_state_elfin))
        #self.Log.info("[ star state ] init_state_agv = %s"%(self.init_state_agv))

        self.Log.info(" elfin_task_id = %s"%(self.elfin_task_id))
        self.Log.info(" elfin_task = %s"%(self.elfin_task))
        self.Log.info(" elfin_task_param_0 = %s"%(self.elfin_task_param_0))
        self.Log.info(" elfin_task_param_1 = %s"%(self.elfin_task_param_1))
        self.Log.info(" elfin_task_status = %s"%(self.elfin_task_status))

        self.Log.info(" agv_task_id = %s"%(self.agv_task_id))
        self.Log.info(" agv_task = %s"%(self.agv_task))
        self.Log.info(" agv_task_param_0 = %s"%(self.agv_task_param_0))
        self.Log.info(" agv_task_param_1 = %s"%(self.agv_task_param_1))
        self.Log.info(" agv_task_status = %s"%(self.agv_task_status))

class StarRegister(object):
    class HR(object):
        # Holding registers

        #MOVE = 0
        #PLACE = 1
        #PICK = 2
        #BUTTON = 3

        ELFIN_TASK_ID = 0
        ELFIN_TASK    = 1
        ELFIN_TASK_PARAM_0 = 2
        ELFIN_TASK_PARAM_1 = 3

        AGV_TASK_ID = 4
        AGV_TASK    = 5
        AGV_TASK_PARAM_0 = 6
        AGV_TASK_PARAM_1 = 7

    class IR(object):
        # Input registers

        #ELFIN_ERROR = 0
        #AGV_STATION = 2

        ELFIN_TASK_ID = 0
        ELFIN_TASK    = 1
        ELFIN_TASK_PARAM_0 = 2
        ELFIN_TASK_PARAM_1 = 3
        ELFIN_TASK_STATUS = 4

        AGV_TASK_ID = 5
        AGV_TASK    = 6
        AGV_TASK_PARAM_0 = 7
        AGV_TASK_PARAM_1 = 8
        AGV_TASK_STATUS = 9

class StarAdapter(object):

    def __init__(self,
                 ip="127.0.0.1", port=502,
                 log_message = False):
        self.Log = log_wrap(prefix = "[ Star Adapter ]")
        self.master = None
        self.ip = ip
        self.port = port
        self.__log_message = log_message
        self.__modbus_lock = threading.Lock()

        self.__state_history = None

        self.__connected = False
        self.__connecting = False
        self.__need_connection = False
        self.__connect_thread = None

        self.__running = True
        self.__updating_state = False
        self.__update_state_thread = None

        self.__star_state = StarState()
        pass

    def reconfigure(self, ip, port, log_message=False):
        self.ip = ip
        self.port = port
        self.__log_message = log_message

    # [ TODO ] Need reconnection
    def connect(self):
        if(self.__connected):
            self.Log.info("connect(): Star Modbus slave connected. Do nothing.")
            return

        if(self.__connecting):
            self.Log.info("connect(): Already connecting Star Modbus slave. Do nothing.")
            return

        self.Log.info("connect(): Start connection thread.")

        self.__need_connection = True
        self.__connect_thread = threading.Thread(target = self.__connect_loop)
        self.__connect_thread.setDaemon(True)
        self.__connect_thread.start()

    def disconnect(self):
        if(not self.__connected):
            self.Log.info("disconnect(): Star Modbus slave not connected. Do nothing.")
            return

        if(self.__connecting):
            self.__connecting = False

        if(self.__connect_thread):
            self.__connect_thread.join()
            self.__connect_thread = None

        if(self.master):
            self.master.close()

    def wait_for_connection(self):
        self.Log.info("Waiting for connection...")
        while(self.__running):
            if(self.__connected):
                break
            else:
                time.sleep(0.1)

    def __connect_loop(self):
        self.__connecting = True
        # Connect to the slave
        while (self.__running and self.__need_connection):
            try:
                self.Log.info("Try connecting to %s:%s"%(self.ip, self.port))
                self.master = modbus_tcp.TcpMaster( host = self.ip ,
                                                    port = self.port ,
                                                    timeout_in_sec = 5.0 )
                self.master.set_timeout(5.0)

                self.master.open()
                self.Log.info("Star modbus connection established.")
                self.__connected = True
                self.__connecting = False
                self.__need_connection = False
                break
            except modbus_tk.modbus.ModbusError as exc:
                self.Log.error("Failed connecting Star, try reconnecting")
                time.sleep(1)

    def init(self):
        self.start_update_state()

    def clean_up(self):
        self.__running = False
        self.stop_update_state()
        self.disconnect()

    # logger.info(master.execute(1, cst.READ_COILS, 0, 10))
    # logger.info(master.execute(1, cst.READ_DISCRETE_INPUTS, 0, 8))
    # logger.info(master.execute(1, cst.READ_INPUT_REGISTERS, 100, 3))
    # logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 100, 12))
    # logger.info(master.execute(1, cst.WRITE_SINGLE_COIL, 7, output_value=1))
    # logger.info(master.execute(1, cst.WRITE_SINGLE_REGISTER, 100, output_value=54))
    # logger.info(master.execute(1, cst.WRITE_MULTIPLE_COILS, 0, output_value=[1, 1, 0, 1, 1, 0, 1, 1]))
    # logger.info(master.execute(1, cst.WRITE_MULTIPLE_REGISTERS, 100, output_value=xrange(12)))

    def write(self, slave_id, mode, addr, output_value):
        try:
            self.__modbus_lock.acquire()
            msg = self.master.execute( slave_id, mode,
                                       addr, output_value = output_value )
            self.__modbus_lock.release()
            if(self.__log_message):
                self.Log.info("Reply: %s"%(repr(msg)))
            return msg
        except modbus_tk.modbus.ModbusError as exc:
            self.Log.error("Execution failed: "
                           "slave[%d], mode[%d], "
                           "addr[%d], output_value[%s]"
                           ""%(slave_id,
                               mode,
                               addr,
                               output_value))
            return None

    def read(self, slave_id, mode, addr, number):
        try:
            self.__modbus_lock.acquire()
            msg = self.master.execute( slave_id, mode,
                                       addr, number )
            self.__modbus_lock.release()
            if(self.__log_message):
                self.Log.info("Reply: %s"%(repr(msg)))
            return msg
        except modbus_tk.modbus.ModbusError as exc:
            self.Log.error("Execution failed: "
                           "slave[%d], mode[%d], "
                           "addr[%d], output_value[%s]"
                           ""%(slave_id,
                               mode,
                               addr,
                               output_value))
            return None

    def write_bit_one(self, addr, value):
        return self.write(1, cst.WRITE_SINGLE_COIL, addr, output_value=value)

    def write_bit_multi(self, addr, values):
        return self.write(1, cst.WRITE_MULTIPLE_COILS, addr, output_value=value)

    def write_byte_one(self, addr, value):
        return self.write(1, cst.WRITE_SINGLE_REGISTER, addr, output_value=value)
            # logger.info(master.execute(1, cst.WRITE_SINGLE_REGISTER, 100, output_value=54))

    def write_byte_multi(self, addr, values):
        return self.write(1, cst.WRITE_MULTIPLE_REGISTERS, addr, output_value=value)

    # read coils
    def read_bit_rw(self, addr, number):
        return self.read(1, cst.READ_COILS, addr, number)

    # read discrete inputs
    def read_bit_r(self, addr, number):
        return self.read(1, cst.READ_DISCRETE_INPUTS, addr, number)

    # read holding registers
    def read_byte_rw(self, addr, number):
        return self.read(1, cst.READ_HOLDING_REGISTERS, addr, number)

    # read input registers
    def read_byte_r(self, addr, number):
        return self.read(1, cst.READ_INPUT_REGISTERS, addr, number)

    def agv_set_task_id(self, task_id):
        self.write_byte_one( StarRegister.HR.AGV_TASK_ID,
                             task_id )

    def agv_set_task(self, task_type):
        self.write_byte_one( StarRegister.HR.AGV_TASK,
                             task_type )

    def agv_set_task_param_0(self, task_param_0 ):
        self.write_byte_one( StarRegister.HR.AGV_TASK_PARAM_0,
                             task_param_0 )

    def agv_set_task_param_1(self, task_param_1 ):
        self.write_byte_one( StarRegister.HR.AGV_TASK_PARAM_1,
                             task_param_1 )

    def agv_get_last_task_id(self):
        return self.read_byte_r( StarRegister.IR.AGV_TASK_ID,
                                 1 )[0]

    def agv_add_task_inner( self ,
                            task_type = 0 ,
                            task_param_0 = 0 ,
                            task_param_1 = 0 ):
        last_task_id = self.agv_get_last_task_id()
        task_id = last_task_id + 1
        self.agv_set_task( task_type )
        self.agv_set_task_param_0( task_param_0 )
        self.agv_set_task_param_1( task_param_1 )
        self.agv_set_task_id( task_id )

        while(self.__running):
            if ( (self.__star_state.agv_task_id      == task_id     ) and
                 (self.__star_state.agv_task         == task_type   ) and
                 (self.__star_state.agv_task_param_0 == task_param_0) and
                 (self.__star_state.agv_task_param_1 == task_param_1) and
                 (self.__star_state.agv_task_status  != StarState.TaskState.NO_TASK) ):
                self.agv_set_task( StarCommand.AgvTask.NO_TASK )
                break
            else:
                time.sleep(0.1)

    def agv_add_task( self ,
                      task_type = 0 ,
                      task_param_0 = 0 ,
                      task_param_1 = 0 ):
        self.agv_add_task_inner( task_type,
                                 task_param_0 )

    def agv_go_ready(self):
        self.agv_add_task( task_type = StarCommand.AgvTask.GO,
                           task_param_0 = StarCommand.AgvTaskStation.READY )

    def agv_go_pick(self):
        self.agv_add_task( task_type = StarCommand.AgvTask.GO,
                           task_param_0 = StarCommand.AgvTaskStation.PICK )

    def agv_go_place(self):
        self.agv_add_task( task_type = StarCommand.AgvTask.GO,
                           task_param_0 = StarCommand.AgvTaskStation.PLACE )

    def agv_go(self, station):
        if(station == 1):
            self.agv_go_place()
        elif(station == 2):
            self.agv_go_pick()
        else:
            self.Log.error("agv_go(): station ID [%d] invalid. "
                           "Only 2 stations available."
                           ""%(station))

    def wait_agv_task_finish(self):
        while(self.__running):
            if (self.__star_state.agv_task_status != StarState.TaskState.RUNNING):
                break
            else:
                time.sleep(0.1)

    def elfin_set_task_id(self, task_id):
        self.Log.info("elfin_set_task_id(%d)"%(task_id))
        self.write_byte_one( StarRegister.HR.ELFIN_TASK_ID,
                             task_id )

    def elfin_set_task(self, task_type):
        self.Log.info("elfin_set_task(%d)"%(task_type))
        self.write_byte_one( StarRegister.HR.ELFIN_TASK,
                             task_type )

    def elfin_set_task_param_0(self, task_param_0 ):
        self.Log.info("elfin_set_task_param_0(%d)"%(task_param_0))
        self.write_byte_one( StarRegister.HR.ELFIN_TASK_PARAM_0,
                             task_param_0 )

    def elfin_set_task_param_1(self, task_param_1 ):
        self.Log.info("elfin_set_task_param_1(%d)"%(task_param_1))
        self.write_byte_one( StarRegister.HR.ELFIN_TASK_PARAM_1,
                             task_param_1 )

    def elfin_get_last_task_id(self):
        self.Log.info("elfin_get_last_task_id()")
        return self.read_byte_r( StarRegister.IR.ELFIN_TASK_ID,
                                 1 )[0]

    def elfin_add_task_inner( self ,
                              task_type = 0 ,
                              task_param_0 = 0 ,
                              task_param_1 = 0 ):
        self.Log.info("elfin_add_task_inner()")
        last_task_id = self.elfin_get_last_task_id()
        task_id = last_task_id + 1
        self.Log.info("elfin_add_task_inner(): last_task_id[%d], task_id[%d]"
                      ""%(last_task_id, task_id))
        self.elfin_set_task( task_type )
        self.elfin_set_task_param_0( task_param_0 )
        self.elfin_set_task_param_1( task_param_1 )
        self.elfin_set_task_id( task_id )

        while(self.__running):
            if ( (self.__star_state.elfin_task_id      == task_id     ) and
                 (self.__star_state.elfin_task         == task_type   ) and
                 (self.__star_state.elfin_task_param_0 == task_param_0) and
                 (self.__star_state.elfin_task_param_1 == task_param_1) and
                 (self.__star_state.elfin_task_status  != StarState.TaskState.NO_TASK) ):
                self.elfin_set_task( StarCommand.ElfinTask.NO_TASK )
                break
            else:
                time.sleep(0.1)

    def elfin_add_task( self ,
                        task_type = 0 ,
                        task_param_0 = 0 ,
                        task_param_1 = 0 ):
        self.Log.info("elfin_add_task()")
        self.elfin_add_task_inner( task_type,
                                   task_param_0 )

    def elfin_ready(self):
        self.Log.info("elfin_ready()")
        self.elfin_add_task( task_type = StarCommand.ElfinTask.READY )

    def elfin_place(self, block=1):
        if(block == 1):
            self.elfin_add_task( task_type = StarCommand.ElfinTask.PLACE_1 )
        elif(block == 2):
            self.elfin_add_task( task_type = StarCommand.ElfinTask.PLACE_2 )
        else:
            self.Log.error("elfin_place(): block ID [%d] invalid. "
                           "Only 2 blocks available."
                           ""%(block))

    def elfin_pick(self, block=1):
        if(block == 1):
            self.elfin_add_task( task_type = StarCommand.ElfinTask.PICK_1 )
        elif(block == 2):
            self.elfin_add_task( task_type = StarCommand.ElfinTask.PICK_2 )
        else:
            self.Log.error("elfin_pick(): block ID [%d] invalid. "
                           "Only 2 blocks available."
                           ""%(block))

    def wait_elfin_task_finish(self):
        while(self.__running):
            if (self.__star_state.elfin_task_status != StarState.TaskState.RUNNING):
                break
            else:
                time.sleep(0.1)

#    def __move(self, command):
#        self.write_byte_one( StarRegister.HoldingRegister.MOVE, command )

#    def move_station(self, station):
#        self.__move(station)

#    def move_stop(self):
#        self.__move(StarCommand.Move.STOP)

#    def __place(self, command):
#        self.write_byte_one( StarRegister.HoldingRegister.Place, command )

#    def place_material(self, material):
#        self.__place(material)

#    def place_stop(self):
#        self.__place(StarCommand.Place.STOP)

#    def __pick(self, command):
#        self.write_byte_one( StarRegister.HoldingRegister.PICK, command )

#    def pick_material(self, material):
#        self.__pick(material)

#    def pick_stop(self):
#        self.__pick(StarCommand.Pick.STOP)

#    def __trigger_button(self, command):
#        self.write_byte_one( StarRegister.HoldingRegister.BUTTON, command )

#    def trigger_button(self, button):
#        self.__trigger_button(button)

#    def trigger_button_none(self):
#        self.__trigger_button( StarCommand.Button.NONE )

#    def trigger_button_start(self):
#        self.__trigger_button( StarCommand.Button.START )

#    def trigger_button_stop(self):
#        self.__trigger_button( StarCommand.Button.STOP )

#    def trigger_button_initialize(self):
#        self.__trigger_button( StarCommand.Button.INITIALIZE )

    def update_state(self):
        self.__state = (
            self.__star_state.elfin_task_id ,
            self.__star_state.elfin_task    ,
            self.__star_state.elfin_task_param_0 ,
            self.__star_state.elfin_task_param_1 ,
            self.__star_state.elfin_task_status  ,

            self.__star_state.agv_task_id ,
            self.__star_state.agv_task    ,
            self.__star_state.agv_task_param_0 ,
            self.__star_state.agv_task_param_1 ,
            self.__star_state.agv_task_status  ,
        ) = self.read_byte_r(0,10)

        if(self.__state_history):
            if(filter(lambda x:x,
                      map(lambda y:self.__state[y]!=self.__state_history[y],
                          xrange(len(self.__state))))):
                self.Log.info("="*30)
                self.__star_state.debug_output()

        self.__state_history = self.__state

        #self.__star_state.agv_position = read_byte_r(19,1)
        #self.__star_state.init_state_elfin = read_bit_r(0,1)
        #self.__star_state.init_state_agv = read_bit_r(1,1)

        #if(self.__log_messsage):

    def update_state_loop(self):
        self.__updating_state = True
        while(self.__running and self.__updating_state):
            self.update_state()
            time.sleep(0.1)

    def start_update_state(self):
        if(self.__updating_state):
            return
        self.__update_state_thread = threading.Thread( target = self.update_state_loop )
        self.__update_state_thread.setDaemon(True)
        self.__update_state_thread.start()

    def stop_update_state(self):
        if(not self.__updating_state):
            return
        self.__updating_state = False
        self.__update_state_thread.join()
        self.__update_state_thread = None

def main():
    """main"""
#    logger = modbus_tk.utils.create_logger("console", level=logging.DEBUG)

    def on_after_recv(data):
        master, bytes_data = data
#        logger.info(bytes_data)

    hooks.install_hook('modbus.Master.after_recv', on_after_recv)

    try:

        def on_before_connect(args):
            master = args[0]
#            logger.debug("on_before_connect {0} {1}".format(master._host, master._port))

        hooks.install_hook("modbus_tcp.TcpMaster.before_connect", on_before_connect)

        def on_after_recv(args):
            response = args[1]
#            logger.debug("on_after_recv {0} bytes received".format(len(response)))

        hooks.install_hook("modbus_tcp.TcpMaster.after_recv", on_after_recv)

        # Connect to the slave
        master = modbus_tcp.TcpMaster()
        master.set_timeout(5.0)
#        logger.info("connected")

#        logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 3))

        # logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 2, data_format='f'))

        # Read and write floats
        # master.execute(1, cst.WRITE_MULTIPLE_REGISTERS, starting_address=0, output_value=[3.14], data_format='>f')
        # logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 2, data_format='>f'))

        # send some queries
        # logger.info(master.execute(1, cst.READ_COILS, 0, 10))
        # logger.info(master.execute(1, cst.READ_DISCRETE_INPUTS, 0, 8))
        # logger.info(master.execute(1, cst.READ_INPUT_REGISTERS, 100, 3))
        # logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 100, 12))
        # logger.info(master.execute(1, cst.WRITE_SINGLE_COIL, 7, output_value=1))
        # logger.info(master.execute(1, cst.WRITE_SINGLE_REGISTER, 100, output_value=54))
        # logger.info(master.execute(1, cst.WRITE_MULTIPLE_COILS, 0, output_value=[1, 1, 0, 1, 1, 0, 1, 1]))
        # logger.info(master.execute(1, cst.WRITE_MULTIPLE_REGISTERS, 100, output_value=xrange(12)))

    except modbus_tk.modbus.ModbusError as exc:
        pass
 #       logger.error("%s- Code=%d", exc, exc.get_exception_code())

if __name__ == "__main__":
    #main()
    pass


# -*- coding: utf-8 -*-

import socket
import sys
import time
import base64
import subprocess

HOST = '' #all available interfaces
PORT = 2222

#1. open Socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
print ('Socket created')

#2. bind to a address and port
try:
    s.bind((HOST, PORT))
except socket.error as msg:
    print ('Bind Failed. Error code: ' + str(msg[0]) + ' Message: ' + msg[1])
    sys.exit()

print ('Socket bind complete')

#3. Listen for incoming connections
s.listen(10)
print ('Socket now listening')

it = 2
#keep talking with the client
while 1:
    #4. Accept connection
    conn, addr = s.accept()
    print ('Connected with ' + addr[0] + ':' + str(addr[1]))

    id = conn.recv(255).decode()
    print('id : *' + id+ '*')

    timestamp = conn.recv(26).decode()
    print('timestamp : *' + timestamp +'*')

    result = conn.recv(1).decode()
    print('result : ' + result)

    if(result == '1'):
        it = 4
    elif(result == '0'):
        it = 2
    for i in range(1, it):
        #5. Read/Send
        img = ""
        len_data = conn.recv(1024).decode()
        len_data = int(len_data)
        size = 0

        print("Data Reading")

        while 1:
            data = conn.recv(65536)
            str_data = data.decode()
            img += data.decode()
            size += len(str_data)
            if size == len_data:
                print("Finished Data Reading")
                break

        with open('/root/openface/temp/test_'+str(i)+'.jpeg', 'wb') as f:
            f.write(base64.b64decode(img))
        time.sleep(0.1)
    break

res_list = {}

for j in range(1,it):
    # start face recognigionc
    res=subprocess.check_output(['/root/openface/demos/classifier_test.py infer /root/openface/embedding/us/classifier.pkl /root/openface/temp/test_'+str(j)+'.jpeg'], universal_newlines=True,shell=True)
    print("res: {}".format(res))

    # store recognition result
    name, accuracy = res.split(':')
    accuracy = float(accuracy)

    if accuracy > 0.5:
        if name in res_list.keys():
            res_list[name][1] += 1
            if res_list[name][0] < accuracy:
            	res_list[name][0] = accuracy
        else:
            res_list[name] = [accuracy, 1]

    print("res_list: {}".format(res_list))

if not res_list:
    print("*stranger*")
else:
    res_list = sorted(res_list.items(), key = lambda x: (x[1][1], x[1][0]), reverse = True)
    print("final res: *{}*".format(res_list[0][0]))

conn.close()
s.close()