# Katrin Erk February 2023
# interface to Aurelie's Word2vec vectors

import numpy as np
import re

# using gensim for computing cosines
from gensim.models import KeyedVectors

from vgnames import VGOBJECTS, VGATTRIBUTES, VGRELATIONS

class VectorInterface:
    def __init__(self, vgpath_obj):
        vecfilename = vgpath_obj.vg_vecfilename()
        self.object_vec = { }
        self.attrib_vec = { }
        self.predarg0_vec = { }
        self.predarg1_vec = { }

        ###
        # read vectors,
        # vectors for objects will be available in
        # object_vec, a dictionary
        # object label -> vector of floating point numbers
        with open(vecfilename) as f:
            for line in f:
                pieces = line.split()
                # first word is label
                label = pieces[0]
                # from what I can see, vectors for attributes have no .n at the end,
                # and vectors for relations are actually for relation-argument pairs,
                # and always have parentheses.
                # what are they for?
                #
                # determine vectors for objects:
                # remove .n
                # and turn underscores to spaces
                if label.endswith(".n") and "(" not in label and ")" not in label:
                    # object
                    label = label[:-2]
                    label = label.replace("_", " ")
                    self.object_vec[ label ] = np.array([ float(v) for v in pieces[1:]])

                elif "(" in label and ")" in label:
                    # relation, curried: relation plus one argument
                    match = re.match("(.+)\((.+),(.+)\)$", label)
                    if match is None:
                        print("Vec Util: could not decompose label", label)
                        continue

                    predicate = match[1]
                    arg0 = match[2]
                    arg1 = match[3]

                    predicate = predicate.replace("|", " ")
                    if arg0 == "-":
                        # pred/arg1 combination
                        if not arg1.endswith(".n"):
                            print("Vec Util: arg should be a noun but isn't", arg1)
                        arg1 = arg1[:-2]
                        arg1 = arg1.replace("_", " ")
                        self.predarg1_vec[ (predicate, arg1) ] = np.array([ float(v) for v in pieces[1:]])

                    elif arg1 == "-":
                        # pred/arg0 combination
                        if not arg0.endswith(".n"):
                            print("Vec Util: arg should be a noun but isn't", arg0)
                        arg0 = arg0[:-2]
                        arg0 = arg0.replace("_", " ")
                        self.predarg0_vec[ (predicate, arg0) ] = np.array([ float(v) for v in pieces[1:]])

                    else:
                        print("Vec Util: could not parse pred/arg entry, did not find - entry", label)

                else:
                    # attribute
                    label = label.replace("|", " ")
                    self.attrib_vec[ label ] = np.array([ float(v) for v in pieces[1:]])

        # make gensim KeyedVector for objects, attributes, predicates to support similarity to centroid
        self.object_kv = KeyedVectors(len(list(self.object_vec.values())[0]))
        self.object_kv.add_vectors(list(self.object_vec.keys()), list(self.object_vec.values()))
        self.object_kv.fill_norms()
        self.object_kv_index_key = dict( (self.object_kv.get_index(key), key) for key in self.object_vec.keys())

        self.attrib_kv = KeyedVectors(len(list(self.attrib_vec.values())[0]))
        self.attrib_kv.add_vectors(list(self.attrib_vec.keys()), list(self.attrib_vec.values()))
        self.attrib_kv.fill_norms()
        self.attrib_kv_index_key = dict( (self.attrib_kv.get_index(key), key) for key in self.attrib_vec.keys())

        self.predarg0_kv = KeyedVectors(len(list(self.predarg0_vec.values())[0]))
        self.predarg0_kv.add_vectors([self.kc(k) for k in self.predarg0_vec.keys()], list(self.predarg0_vec.values()))
        self.predarg0_kv.fill_norms()
        self.predarg0_kv_index_key = dict( (self.predarg0_kv.get_index(self.kc(key)), key) for key in self.predarg0_vec.keys())

        self.predarg1_kv = KeyedVectors(len(list(self.predarg1_vec.values())[0]))
        self.predarg1_kv.add_vectors([self.kc(k) for k in self.predarg1_vec.keys()], list(self.predarg1_vec.values()))
        self.predarg1_kv.fill_norms()
        self.predarg1_kv_index_key = dict( (self.predarg1_kv.get_index(self.kc(key)), key) for key in self.predarg1_vec.keys())

    # key transforms for pred/arg pairs
    def kc(self, predarg):
        return "|".join(predarg)

    def all_objects_sim_centroid(self, object_labels):
        centroid = self.object_kv.get_mean_vector(object_labels)
        if sum(centroid) == 0.0:
            return None

        # compute similarity from centroid to all objects
        sims = self.object_kv.cosine_similarities(centroid, self.object_kv.get_normed_vectors())

        # and return as list of pairs (object label, sim)
        return [  (self.object_kv_index_key[ix], sim) for ix, sim in enumerate(sims.tolist()) ]
        # sortedlist = sorted([ (self.object_kv_index_key[ix], sim) for ix, sim in enumerate(sims.tolist())], key = lambda p:p[1], reverse = True)
        # return [(ix, sim) for ix, sim in sortedlist if sim > 0]

    # all similarities, to this label, ranked highest to lowest,
    # where type = object, attr, predarg0, predarg1
    def ranked_sims(self, label, elltype):
        if elltype == VGOBJECTS:
            simfunc = self.object_kv.similar_by_key
            keydict = self.object_kv_index_key
            tlabel = label

        elif elltype == VGATTRIBUTES:
            simfunc = self.attrib_kv.similar_by_key
            keydict = self.attrib_kv_index_key
            tlabel = label

        elif elltype == "predarg0":
            simfunc = self.predarg0_kv.similar_by_key
            keydict = self.predarg0_kv_index_key
            tlabel = self.kc(label)

        elif elltype == "predarg1":
            simfunc = self.predarg1_kv.similar_by_key
            keydict = self.predarg1_kv_index_key
            tlabel = self.kc(label)

        else:
            raise Exception("unknown label type " + elltype)

        # all similarities, ranked
        sims = simfunc(tlabel, topn = None)
        # add item labels
        pairs = [ (keydict[ix], sim) for ix, sim in enumerate(sims.tolist())]
        # sort by similarity, first will be self
        sortedlist = sorted(pairs, key = lambda p:p[1], reverse= True)
        # return all above-zero similarities
        return [ (ix, sim) for ix, sim in sortedlist if sim > 0]


from __future__ import absolute_import

from ansible.modules.source_control.gitlab_project import GitLabProject

from .gitlab import (GitlabModuleTestCase,
                     python_version_match_requirement,
                     resp_get_group, resp_get_project_by_name, resp_create_project,
                     resp_get_project, resp_delete_project, resp_get_user)

# Gitlab module requirements
if python_version_match_requirement():
    from gitlab.v4.objects import Project

# Unit tests requirements
from httmock import with_httmock  # noqa

class TestGitlabProject(GitlabModuleTestCase):
    @with_httmock(resp_get_user)
    def setUp(self):
        super(TestGitlabProject, self).setUp()

        self.gitlab_instance.user = self.gitlab_instance.users.get(1)
        self.moduleUtil = GitLabProject(module=self.mock_module, gitlab_instance=self.gitlab_instance)

    @with_httmock(resp_get_group)
    @with_httmock(resp_get_project_by_name)
    def test_project_exist(self):
        group = self.gitlab_instance.groups.get(1)

        rvalue = self.moduleUtil.existsProject(group, "diaspora-client")

        self.assertEqual(rvalue, True)

        rvalue = self.moduleUtil.existsProject(group, "missing-project")

        self.assertEqual(rvalue, False)

    @with_httmock(resp_get_group)
    @with_httmock(resp_create_project)
    def test_create_project(self):
        group = self.gitlab_instance.groups.get(1)
        project = self.moduleUtil.createProject(group, {"name": "Diaspora Client", "path": "diaspora-client", "namespace_id": group.id})

        self.assertEqual(type(project), Project)
        self.assertEqual(project.name, "Diaspora Client")

    @with_httmock(resp_get_project)
    def test_update_project(self):
        project = self.gitlab_instance.projects.get(1)

        changed, newProject = self.moduleUtil.updateProject(project, {"name": "New Name"})

        self.assertEqual(changed, True)
        self.assertEqual(type(newProject), Project)
        self.assertEqual(newProject.name, "New Name")

        changed, newProject = self.moduleUtil.updateProject(project, {"name": "New Name"})

        self.assertEqual(changed, False)
        self.assertEqual(newProject.name, "New Name")

    @with_httmock(resp_get_group)
    @with_httmock(resp_get_project_by_name)
    @with_httmock(resp_delete_project)
    def test_delete_project(self):
        group = self.gitlab_instance.groups.get(1)

        self.moduleUtil.existsProject(group, "diaspora-client")

        rvalue = self.moduleUtil.deleteProject()

        self.assertEqual(rvalue, None)


import bpy
from bpy import*
from bpy.props import*

def get_AllObjectsInSelection():
    return bpy.context.selected_objects

def get_hideSelectObjects(object_list):
    for i in object_list:
        i.hide_select = True
    bpy.ops.object.select_all(action='DESELECT')
    return True

class RTS_OT_RePattern_Freeze(bpy.types.Operator):
    # base function from vismaya
    bl_idname = "rts_ot.freeze_selected"
    bl_label = "Freeze Selection"
    bl_description = "Disables Selection"

    def execute(self, context):
        selection = get_AllObjectsInSelection()
        n = len(selection)
        if n > 0:
            get_hideSelectObjects(selection)
            self.report({'INFO'}, "%d Object%s frozen." % (n, "s"[n==1:]))
        else:
            self.report({'INFO'}, 'Nothing selected.')
        return{'FINISHED'}

def get_AllObjectsInScene():
    return bpy.data.objects

def get_dehideSelectObjects(object_list):
    hidedObjs = []
    for i in object_list:
        if i.hide_select == True:
            i.hide_select = False
            hidedObjs.append(i)
    return hidedObjs

def get_highlightObjects(selection_list):
   for i in selection_list:
        bpy.data.objects[i.name].select_set(True)

class RTS_OT_RePattern_Unfreeze(bpy.types.Operator):
    # base function from vismaya
    bl_idname = "rts_ot.unfreeze_selected"
    bl_label = "Unfreeze All"
    bl_description = "Enables Selection"

    def execute(self, context):
        bpy.ops.object.select_all(action='DESELECT')
        selection = get_AllObjectsInScene()
        n = len(selection)

        if n > 0:
            freezed_array = get_dehideSelectObjects(selection)
            get_highlightObjects(freezed_array)
            self.report({'INFO'}, "%d Object%s released." % (n, "s"[n==1:]))
        else:
            self.report({'INFO'}, 'Nothing selected.')

        return{'FINISHED'}


import tkinter as tk
import threading
from PIL import ImageTk, Image
from socket import *

class AXEPapichAXE:
    def __init__(self):
        self.win = tk.Tk()
        self.win.title('AXEpapichAXE')
        self.win.geometry("256x256+150+80")
        self.win.config(bg='#800000')
        self.win.minsize(512, 294)

        self.images = [ImageTk.PhotoImage(Image.open(f"images/axe{i}.jpg")) for i in range(1, 35)]
        self.image_index = 0

        self.frame = None
        self.lab = None

        self.setup_ui()
        self.start_server()

    def setup_ui(self):
        self.frame = tk.Frame(self.win, bg='#800000')
        self.frame.pack(fill=tk.BOTH, expand=True)

        self.lab = tk.Label(self.frame, image=self.images[0])
        self.lab.pack(pady=20)

        self.win.protocol("WM_DELETE_WINDOW", self.finish)

    def change_image(self):
        self.image_index = (self.image_index + 1) % len(self.images)
        self.lab.configure(image=self.images[self.image_index])

    def start_server(self):
        new_thread = threading.Thread(target=self._server_thread)
        new_thread.start()

    def _server_thread(self):
        server = socket(AF_INET, SOCK_STREAM)
        server.bind(("192.168.26.73", 6842))
        server.listen()

        user, addr = server.accept()

        while True:
            data = user.recv(1)
            if not data:
                break
            self.change_image()

    def finish(self):
        self.win.destroy()

    def run(self):
        self.win.mainloop()

if __name__ == "__main__":
    app = AXEPapichAXE()
    app.run()


import cv2
import numpy as np
import sys

base_path1 = 'InputContentImages/'
image_sel = sys.argv[1]

A = cv2.imread(base_path1 + image_sel + '.jpg')
G = A.copy()

# Create the pyramids
gauss_A = [G]
lap_A = []

levels = 4

for i in xrange(levels-1):
    G = cv2.pyrDown(G)
    gauss_A.append(G)

lap_A.append(gauss_A[len(gauss_A)-1])

for i in xrange(levels-1,0,-1):
    gauss_upscl = cv2.pyrUp(gauss_A[i])
    gauss_upscl = cv2.resize(gauss_upscl, (gauss_A[i-1].shape[1], gauss_A[i-1].shape[0]))
    lap = cv2.subtract(gauss_A[i-1], gauss_upscl)
    lap = lap * 2
    lap = cv2.dilate(lap, np.ones((3,3), np.uint8))
    lap_A.append(lap)

base_path2 = 'InputContentImagePyramids/'

for i in xrange(levels):
    cv2.imwrite(base_path2 + image_sel + 'g' + str(i) + '.jpg', cv2.resize(gauss_A[i], (A.shape[1], A.shape[0])))
    cv2.imshow('Levels Gauss' + str(i), cv2.resize(gauss_A[i], (A.shape[1], A.shape[0])))
    cv2.waitKey(0)

for i in xrange(levels):
    cv2.imwrite(base_path2 + image_sel + 'l' + str(i) + '.jpg', cv2.resize(lap_A[i], (A.shape[1], A.shape[0])))
    cv2.imshow('Levels Lap' + str(i), cv2.resize(lap_A[i], (A.shape[1], A.shape[0])))
    cv2.waitKey(0)

cv2.destroyAllWindows()


from featurevectorizer import FeatureVectorizer
from searn_parser import SearnModelTemplateFeatures
from shift_reduce_helper import PARSE_ACTIONS, allowed_action

class SearnModelTemplateFeaturesRegression(SearnModelTemplateFeatures):
    def __init__(self, ngram_extractor, feature_extractor, cost_function, min_feature_freq, cr_tags,
                     base_learner_fact, crel_learner_fact,
                     beta=0.2, positive_val=1, sparse=True, log_fn=lambda s: print(s)):

        super(SearnModelTemplateFeaturesRegression, self).__init__(ngram_extractor=ngram_extractor,
                                                                   feature_extractor=feature_extractor,
                                                                   cost_function=cost_function,
                                                                   min_feature_freq=min_feature_freq,
                                                                   cr_tags=cr_tags,
                                                                   base_learner_fact=base_learner_fact,
                                                                   beta=beta,
                                                                   positive_val=positive_val,
                                                                   sparse=sparse,
                                                                   log_fn=log_fn)
        self.crel_learner_fact = crel_learner_fact

    def train_parse_models(self, examples):
        models = {}
        self.current_parser_feat_vectorizer = FeatureVectorizer(min_feature_freq=self.min_feature_freq,
                                                                sparse=self.sparse)
        xs = self.current_parser_feat_vectorizer.fit_transform(examples.xs)

        for action in PARSE_ACTIONS:
            # positive examples have negative cost, negative examples have positive cost
            lbls = [-1 if i > 0 else 1 for i in examples.get_labels_for(action)]    # type: List[int]
            costs = examples.get_weights_for(action)                                # type: List[float]

            # Ensure the costs is > 0 so that the lost cost examples provide some more info
            #ys = [lbl * max(0.1, cost) for (lbl,cost) in zip(lbls, costs)]
            ys = [lbl * cost for (lbl, cost) in zip(lbls, costs)]

            mdl = self.base_learner_fact()
            mdl.fit(xs, ys)

            models[action] = mdl

        self.current_parser_models = models
        self.parser_models.append(models)

    def predict_parse_action(self, feats, tos):
        xs = self.current_parser_feat_vectorizer.transform(feats)
        pred_by_label = {}
        for action in self.randomize_actions():
            if not allowed_action(action, tos):
                continue

            pred_by_label[action] = self.current_parser_models[action].predict(xs)[0]

        # Get label with the lowest cost
        min_act, min_val = min(pred_by_label.items(), key=lambda tpl: tpl[1])
        return min_act


from datetime import datetime

import polars as pl

from polars_queries import utils

Q_NUM = 10
# Note: Q10's answer verification has flakiness due to randomness in sorting on equal revenue values.

def q():
    var1 = datetime(1993, 10, 1)
    var2 = datetime(1994, 1, 1)
    var3 = "R"

    customer_ds = utils.get_customer_ds()
    line_item_ds = utils.get_line_item_ds()
    orders_ds = utils.get_orders_ds()
    nation_ds = utils.get_nation_ds()

    q_final = (
        customer_ds.join(orders_ds, left_on="c_custkey", right_on="o_custkey")
        .join(line_item_ds, left_on="o_orderkey", right_on="l_orderkey")
        .join(nation_ds, left_on="c_nationkey", right_on="n_nationkey")
        .filter(pl.col("o_orderdate") >= var1)
        .filter(pl.col("o_orderdate") < var2)
        .filter(pl.col("l_returnflag") == var3)
        .with_column(
            (pl.col("l_extendedprice") * (1 - pl.col("l_discount"))).alias("revenue")
        )
        .groupby(["c_custkey","c_name", "c_acctbal", "c_phone", "n_name", "c_address", "c_comment"])
        .agg([pl.sum("revenue")])
        .select(
            [
                "c_custkey",
                "c_name",
                "revenue",
                "c_acctbal",
                "n_name",
                "c_address",
                "c_phone",
                "c_comment"
            ]
        )
        .sort(by="revenue", reverse=True)
        .with_column(pl.col(pl.datatypes.Utf8).str.strip().keep_name())
    )

    utils.run_query(Q_NUM, q_final)

if __name__ == "__main__":
    q()


"""
Circuit: Schematic Creation and Analysis
----------------------------------------
This example shows how you can use PyAEDT to add a subcircuit to a Circuit design.
 Push down into the child subcircuit and pop up to the parent design.
"""

import os

##########################################################
# Set Non Graphical Mode.
# Default is False

non_graphical = os.getenv("PYAEDT_NON_GRAPHICAL", "False").lower() in ("true", "1", "t")

###############################################################################
# Launch AEDT and Circuit
# ~~~~~~~~~~~~~~~~~~~~~~~
# This examples launches AEDT 2022R1 in graphical mode.

from pyaedt import Circuit
circuit = Circuit(specified_version="2022.1", non_graphical=non_graphical)

###############################################################################
# Add new subcircuit
# ~~~~~~~~~~~~~~~~~~
# This example adds a new subcircuit to the previously created Circuit design
# becoming the child circuit.
# Then it pushes down into the child subcircuit.

subcircuit = circuit.modeler.schematic.create_subcircuit([0.0, 0.0])
subcircuit_name = subcircuit.composed_name
circuit.push_down(subcircuit)

###############################################################################
# Subcircuit parameterization
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~
# This method parameterizes the subcircuit and adds a resistor, inductor,
# and a capacitor with the value given by the parameters.
# They are then connected in series.
# The ``pop_up`` method provides for getting back to the parent design.

circuit.variable_manager.set_variable("R_val", "35ohm", circuit_parameter=True)
circuit.variable_manager.set_variable("L_val", "1e-7H", circuit_parameter=True)
circuit.variable_manager.set_variable("C_val", "5e-10F", circuit_parameter=True)
p1 = circuit.modeler.schematic.create_interface_port("In")
r1 = circuit.modeler.schematic.create_resistor(value="R_val")
l1 = circuit.modeler.schematic.create_inductor(value="L_val")
c1 = circuit.modeler.schematic.create_capacitor(value="C_val")
p2 = circuit.modeler.schematic.create_interface_port("Out")
circuit.modeler.schematic.connect_components_in_series([p1, r1, l1, c1, p2])
circuit.pop_up()

###############################################################################
# Subcircuit duplication
# ~~~~~~~~~~~~~~~~~~~~~~
# The formerly created subcircuit is duplicated, and a new parameter value is set.
# It works only in graphical mode.

if not non_graphical:
    new_comp = circuit.modeler.schematic.duplicate(subcircuit_name, [0.0512, 0])
    new_comp.parameters["R_val"] = "75ohm"

circuit.release_desktop(True, True)


import unittest

from ..src.primitives import Arrangement, Note
from ..src.species import FirstSpeciesTwoVoices
from ..src.voices import CantusFirmus
from ..src.voices import Voice

class FuxExampleTestCase(unittest.TestCase):
    def test_first_fux_example_is_valid(self):
        dorian_cf = CantusFirmus('dorian')
        arrangement = Arrangement(FirstSpeciesTwoVoices, cantus_firmus=dorian_cf, cantus_firmus_voice_index=0)
        arrangement.insert_voice(
            1,
            Voice([Note('A', 4), Note('A', 4), Note('G', 4), Note('A', 4), Note('B', 4), Note('C', 5), Note('C', 5), Note('B', 4), Note('D', 5), Note('C#', 5), Note('D', 5)]),
        )

        validation_results = arrangement.validate()

        self.assertFalse(validation_results.is_empty(), 'Validation results should not be empty')
        self.assertTrue(validation_results, 'Valid example is failing validation')

    def test_first_fux_counterexample_is_invalid(self):
        dorian_cf = CantusFirmus('dorian')
        arrangement = Arrangement(FirstSpeciesTwoVoices, cantus_firmus=dorian_cf, cantus_firmus_voice_index=1)
        arrangement.insert_voice(
            0,
            Voice([Note('G', 3), Note('D', 4), Note('A', 3), Note('F', 3), Note('E', 3), Note('D', 3), Note('F', 3), Note('C', 4), Note('D', 4), Note('C#', 4), Note('D', 4)]),
        )

        validation_results = arrangement.validate()

        self.assertFalse(validation_results.is_empty(), 'Validation results should not be empty')
        self.assertFalse(validation_results, 'Invalid example is passing validation')

if __name__ == '__main__':
    unittest.main()


import datetime
import os
import matplotlib.pyplot as plt
from history import History
import numpy as np

class SlideshowService:
    def __init__(self):
        pass

    def get_next_image_index(self, current_index, file_num):
        return 0 if current_index+1 >= file_num else current_index + 1

    def fit_the_size(self, canvas_height, image_height):
        diff_h = 1
        if canvas_height < image_height:
            diff_h = canvas_height / image_height

        return diff_h

    def get_history_all(self, history_file_name):
        save_filename = history_file_name
        history_file_path = "history/{}".format(save_filename)
        history_list = []
        with open(history_file_path, 'r', encoding='utf-8') as f:
            for line in f.readlines():
                csv = line.rstrip(os.linesep).split(",")
                history = History()
                history.file_path = csv[0]
                history.time_limit = csv[1]
                history.start_time = datetime.datetime.fromisoformat(csv[2])
                history.end_time = datetime.datetime.fromisoformat(csv[3])
                history.diff_time = csv[4]
                history.create_datetime = datetime.datetime.fromisoformat(csv[5])
                history_list.append(history)

        return history_list

    def get_report(self, history_list):
        history_dict = {}
        for i in history_list:
            if not i.create_datetime.date() in history_dict:
                value_list = []
                value_list.append(i)
                history_dict.update({i.create_datetime.date():value_list})
            else:
                history_dict[i.create_datetime.date()].append(i)

        return history_dict

    def create_graph(self, history_dict):
        fig = plt.Figure()
        x=np.array([key for key in history_dict.keys()])
        y=np.array([len(i[1]) for i in history_dict.items()])
        ax = fig.add_subplot()
        ax.plot(x, y)
        ax.grid()

        return fig

    def practice_time_distribution(self, history_list):
        history_dict = {0:[],1:[],2:[],3:[],4:[],5:[]
                       ,6:[],7:[],8:[],9:[],10:[],11:[]
                       ,12:[],13:[],14:[],15:[],16:[],17:[]
                       ,18:[],19:[],20:[],21:[],22:[],23:[]}

        for i in history_list:
            history_dict[i.create_datetime.hour].append(i)

        return history_dict


import numpy as np
from pyannow import math

def learn(inputs, targets, weights=[0.1,0.1], bias=1, lrate=0.05, nepoch=10000, lrule='delta', actfunc='threshold'):

    for epoch in range(nepoch):

        # feedforward inputs
        if bias is None:
            ins = np.dot(inputs, weights)
        else:
            ins = np.dot(inputs, weights) + bias

        # feedforward outputs
        if actfunc == 'sigmoid':
            outs = math.sigmoid(ins)
            derr = math.sigmoid_der(outs)
        elif actfunc == 'linear':
            outs = ins
            derr = np.ones_like(outs)
        else:
            outs = threshold(ins)
            derr = np.ones_like(outs)

        err = outs - targets
        derr_err = err * derr
        der_f = np.dot(inputs.T,derr_err)

        weights -= lrate * der_f

        if bias is not None:
            err_sum = derr_err.sum()
            bias -= lrate * err_sum

        # for i in derr_err:
        #     bias -= lrate * i

        tss = math.tss(outs, targets)
        if tss == 0:
            break

    if bias is not None:
        bias = bias.round(3)
    res = {'outputs':outs.round(3),
    'weights':weights.round(3),
    'bias':bias,
    'tss':tss.round(3),
    'epoch':epoch}

    return res

# def slff(inputs, targets, weights=[0.1], bias=[1], lrate=0.05, nepoch=1000, lrule='delta', actfunc='threshold'):

#     res = {'outputs':outs, 'weights':weights, 'bias':bias, 'derivatives':der_f, 'tss':tss}

#     return res

def threshold(x, th=0, up=1, down=0):
    return np.where(x>th, up, down)

def linear(x, th=0, up=1, down=0):
    return np.where(x>th, up, down)


#☆𝒐𝒎𝒂𝒋𝒊𝒏𝒂𝒊☆#
import sys
import math
from math import ceil, floor
import itertools
from functools import lru_cache,reduce
from collections import deque
inf=10**20
sys.setrecursionlimit(10000000)
input=lambda : sys.stdin.readline().rstrip()
'''''✂'''''''''''''''''''''''''''''''''''''''''''''''''''''''''

n=int(input())
a=list(map(int,input().split()))
b=set(a)
if len(b)==1 and 0 in b:
    print('Yes')
elif len(b)==3:
    q,w,e=b
    if q^w^e==0 and a.count(q)==a.count(w)==a.count(e):
        print('Yes')
    else:
        print('No')
elif len(b)==2 and 0 in b:
    q,w=b
    if a.count(max(q,w))==a.count(0)*2:
        print('Yes')
    else:
        print('No')
else:
    print('No')


'''
# 백준_12738_가장 긴 증가하는 부분 수열 3. 골드 2. 풀이: 23.08.13

## LIS: 최장 증가 부분 수열을 이용한 문제들
- DP로 풀면, 시간복잡도가 크다: O(n^2)
- 따라서 시간복잡도를 개선하기 위해 이분 탐색을 활용해야한다: O(nlogn)
- 백준에서는 입력의 최댓값에 따라 유형이 나뉜다.
    - dp: 11053, 14002, 11054, 11055, 11722
    - 이분탐색: 12015, 12738, 14003
-> dp와 이분탐색의 두 방법으로 풀어보자

# How to
- 역시나 입력값이 매우 크고(1,000,000) 음수가 주어지며, LIS의 길이를 묻는 질문.
    - 따라서 bisect 사용

# Review
- 풀이 시간: 5분
'''

# Code
# DP -> 시간초과 확정이라, 코드 구현 안함

# 1. 이분탐색 bisect
## 메모리: 157840 KB, 시간: 880 ms
from bisect import bisect_left
n = int(input())
arr = tuple(map(int, input().split()))
result = [arr[0]]

for i in arr:
    if result[-1] < i:
        result.append(i)

    else: # result[-1] >= i
        result[bisect_left(result, i)] = i

print(len(result))


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

version = '1.0.5'

import os
import io
try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

dependencies = [
    'pyserial'
]

#def read(filename):
#    return open(os.path.join(os.path.dirname(__file__), filename)).read()

def read(*names, **kwargs):
    return io.open(
        os.path.join(os.path.dirname(__file__), *names),
        encoding=kwargs.get('encoding', 'utf8')
    ).read()

setup(
    name="kacors485",
    version=version,
    author="Andreas Plieninger",
    author_email="info@andreasplieninger.com",
    url="https://github.com/plieningerweb/kacors485",
    description="Python library to retrive and parse information from kaco inverters over serial interface",
    packages=['kacors485'],
    long_description='',
    include_package_data=True,
    install_requires=dependencies,
    license = "GNU GPLv3",
    classifiers=[
        'License :: OSI Approved :: GNU General Public License (GPL)',
        'Intended Audience :: Developers',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Topic :: Software Development :: Libraries'
    ],
)


# -*- coding: utf-8 -*-
"""
This script facilitates the matching of REC1 rivers with OpenStreetMap (OSM) waterways by finding the closest
OSM waterway to each REC1 river. It also determines the target points used for the river input in the BG-Flood model.
"""

from typing import Union

import geopandas as gpd
import pandas as pd
import numpy as np
import xarray as xr
from shapely.geometry import Point
from sqlalchemy.engine import Engine

from newzealidar.utils import get_dem_band_and_resolution_by_geometry

def match_rec1_river_and_osm_waterway(
        rec1_network_data_on_bbox: gpd.GeoDataFrame,
        osm_waterways_data_on_bbox: gpd.GeoDataFrame,
        distance_m: int = 300) -> gpd.GeoDataFrame:
    """
    Matches REC1 network data with OSM waterways data based on their spatial proximity within a specified distance
    threshold.

    Parameters
    ----------
    rec1_network_data_on_bbox : gpd.GeoDataFrame
        A GeoDataFrame containing the REC1 network data that intersects with the catchment area boundary.
    osm_waterways_data_on_bbox : gpd.GeoDataFrame
        A GeoDataFrame containing the OSM waterways data that intersects with the catchment area boundary.
    distance_m : int, optional
        Distance threshold in meters for spatial proximity matching. The default value is 300 meters.

    Returns
    -------
    gpd.GeoDataFrame
        A GeoDataFrame containing the matched REC1 network data and OSM waterways data, including spatial proximity
        information.
    """
    # Select relevant columns from REC1 network data
    rec1_on_bbox = rec1_network_data_on_bbox[
        ['objectid', 'rec1_boundary_point_centre', 'boundary_line', 'boundary_line_no']]
    # Select relevant columns from OSM waterways data
    osm_on_bbox = osm_waterways_data_on_bbox[
        ['id', 'osm_boundary_point_centre', 'boundary_line', 'boundary_line_no']]
    # Spatially join the REC1 and OSM data based on the nearest distance within the distance threshold
    matched_rec1_and_osm = gpd.sjoin_nearest(rec1_on_bbox, osm_on_bbox, how='inner',
                                             distance_col="distances", max_distance=distance_m)
    # Find duplicated columns
    duplicated_columns = matched_rec1_and_osm.T.duplicated(keep='last')
    # Select the indexes of the duplicated columns to drop
    columns_to_drop = duplicated_columns[duplicated_columns].index
    # Drop the duplicated columns
    matched_rec1_and_osm.drop(columns=columns_to_drop, inplace=True)
    # Rename specific columns for consistency
    matched_rec1_and_osm = matched_rec1_and_osm.rename(
        columns={'boundary_line_right': 'boundary_line', 'boundary_line_no_right': 'boundary_line_no'})
    # Set the 'boundary_line' column as the geometry column
    matched_rec1_and_osm = matched_rec1_and_osm.set_geometry("boundary_line")
    # Drop unnecessary columns
    matched_rec1_and_osm = matched_rec1_and_osm.drop(columns=['rec1_boundary_point_centre', 'index_right'])
    # Sort the matched data based on the 'distances' column
    matched_rec1_and_osm = matched_rec1_and_osm.sort_values(by='distances')
    # Drop duplicate rows based on the 'id' column, keeping the first occurrence
    matched_rec1_and_osm = matched_rec1_and_osm.drop_duplicates(subset='id', keep='first')
    # Sort the matched data based on the 'boundary_line_no' column and reset the index
    matched_rec1_and_osm = matched_rec1_and_osm.sort_values(by='boundary_line_no').reset_index(drop=True)
    return matched_rec1_and_osm

def find_closest_osm_waterways(
        rec1_network_data_on_bbox: gpd.GeoDataFrame,
        osm_waterways_data_on_bbox: gpd.GeoDataFrame,
        distance_m: int = 300) -> gpd.GeoDataFrame:
    """
    Finds the closest OSM waterway to each REC1 river within the specified distance threshold.

    Parameters
    ----------
    rec1_network_data_on_bbox : gpd.GeoDataFrame
        A GeoDataFrame containing the REC1 network data that intersects with the catchment area boundary.
    osm_waterways_data_on_bbox : gpd.GeoDataFrame
        A GeoDataFrame containing the OSM waterways data that intersects with the catchment area boundary.
    distance_m : int, optional
        Distance threshold in meters for determining the closest OSM waterway. The default value is 300 meters.

    Returns
    -------
    gpd.GeoDataFrame
        A GeoDataFrame containing the closest OSM waterway to each REC1 river.
    """
    # Match REC1 and OSM data based on proximity
    matched_rec1_and_osm = match_rec1_river_and_osm_waterway(
        rec1_network_data_on_bbox, osm_waterways_data_on_bbox, distance_m)
    # Extract REC1 object IDs and OSM IDs from the matched REC1 and OSM data
    closest_osm_waterway_ids = matched_rec1_and_osm[['objectid', 'id']]
    # Merge the extracted REC1 object IDs and OSM IDs with the original OSM waterways data
    closest_osm_waterways = closest_osm_waterway_ids.merge(osm_waterways_data_on_bbox, on='id', how='left')
    # Drop the 'waterway' column from the merged data
    closest_osm_waterways.drop(columns=['waterway'], inplace=True)
    # Convert the merged data to a GeoDataFrame and set the geometry column
    closest_osm_waterways = gpd.GeoDataFrame(closest_osm_waterways, geometry='osm_boundary_point_centre')
    return closest_osm_waterways

def get_elevations_from_hydro_dem(
        single_closest_osm_waterway: gpd.GeoDataFrame,
        hydro_dem: xr.Dataset,
        hydro_dem_resolution: Union[int, float]) -> gpd.GeoDataFrame:
    """
    Extracts the nearest elevation values from the Hydrologically Conditioned DEM (Hydro DEM) for the area
    surrounding the closest OpenStreetMap (OSM) waterway, along with their corresponding coordinates.

    Parameters
    ----------
    single_closest_osm_waterway : gpd.GeoDataFrame
        A GeoDataFrame representing a single row of the closest OSM waterways.
    hydro_dem : xr.Dataset
        Hydrologically Conditioned DEM (Hydro DEM) for the catchment area.
    hydro_dem_resolution: Union[int, float]
        Resolution of the Hydrologically Conditioned DEM (Hydro DEM).

    Returns
    -------
    gpd.GeoDataFrame
        A GeoDataFrame containing the nearest elevation values extracted from the Hydrologically Conditioned DEM
        (Hydro DEM) for the area surrounding the closest OSM waterway, along with their corresponding coordinates.
    """
    # Buffer the boundary line using the Hydro DEM resolution
    single_closest_osm_waterway['boundary_line_buffered'] = (
        single_closest_osm_waterway['boundary_line'].buffer(distance=hydro_dem_resolution, cap_style=2))
    # Clip the Hydro DEM using the buffered boundary line
    clipped_hydro_dem = hydro_dem.rio.clip(single_closest_osm_waterway['boundary_line_buffered'])
    # Get the x and y coordinates of the OSM boundary point center
    osm_boundary_point_centre = single_closest_osm_waterway['osm_boundary_point_centre'].iloc[0]
    osm_bound_point_x, osm_bound_point_y = osm_boundary_point_centre.x, osm_boundary_point_centre.y
    # Find the indices of the closest x and y coordinates in the clipped Hydro DEM
    midpoint_x_index = int(np.argmin(abs(clipped_hydro_dem['x'].values - osm_bound_point_x)))
    midpoint_y_index = int(np.argmin(abs(clipped_hydro_dem['y'].values - osm_bound_point_y)))
    # Define the starting and ending indices for the x coordinates in the clipped Hydro DEM
    start_x_index = max(0, midpoint_x_index - 2)
    end_x_index = min(midpoint_x_index + 3, len(clipped_hydro_dem['x']))
    # Define the starting and ending indices for the y coordinates in the clipped Hydro DEM
    start_y_index = max(0, midpoint_y_index - 2)
    end_y_index = min(midpoint_y_index + 3, len(clipped_hydro_dem['y']))
    # Extract the x and y coordinates within the defined range from the clipped Hydro DEM
    x_range = clipped_hydro_dem['x'].values[slice(start_x_index, end_x_index)]
    y_range = clipped_hydro_dem['y'].values[slice(start_y_index, end_y_index)]
    # Extract elevation values for the specified x and y coordinates from the clipped Hydro DEM
    elevation_values = clipped_hydro_dem.sel(x=x_range, y=y_range).to_dataframe().reset_index()
    # Create Point objects for each row using 'x' and 'y' coordinates, storing them in 'target_point' column
    elevation_values['target_point'] = elevation_values.apply(lambda row: Point(row['x'], row['y']), axis=1)
    # Remove unnecessary columns from the elevation data
    elevation_values.drop(columns=['x', 'y', 'band', 'spatial_ref', 'data_source', 'lidar_source'], inplace=True)
    # Rename the 'z' column to 'elevation_value' for clarity and consistency
    elevation_values.rename(columns={'z': 'elevation'}, inplace=True)
    # Convert the elevation data to a GeoDataFrame with 'target_point' as the geometry column
    elevation_values = gpd.GeoDataFrame(elevation_values, geometry='target_point', crs=single_closest_osm_waterway.crs)
    return elevation_values

def get_target_location_from_hydro_dem(
        single_closest_osm_waterway: gpd.GeoDataFrame,
        hydro_dem: xr.Dataset,
        hydro_dem_resolution: Union[int, float]) -> gpd.GeoDataFrame:
    """
    Get the target location with the minimum elevation from the Hydrologically Conditioned DEM (Hydro DEM)
    to the closest OpenStreetMap (OSM) waterway. This location is crucial for the river input in the BG-Flood model,
    as it enables precise identification of where to add the river as a vertical discharge.

    Parameters
    ----------
    single_closest_osm_waterway : gpd.GeoDataFrame
        A GeoDataFrame representing a single row of the closest OSM waterways.
    hydro_dem : xr.Dataset
        Hydrologically Conditioned DEM (Hydro DEM) for the catchment area.
    hydro_dem_resolution: Union[int, float]
        Resolution of the Hydrologically Conditioned DEM (Hydro DEM).

    Returns
    -------
    gpd.GeoDataFrame
        A GeoDataFrame containing the target location (Point) with the minimum elevation from the Hydrologically
        Conditioned DEM (Hydro DEM) to the closest OSM waterway.
    """
    # Obtain the nearest elevation values from the Hydro DEM to the closest OSM waterway
    elevation_values = get_elevations_from_hydro_dem(single_closest_osm_waterway, hydro_dem, hydro_dem_resolution)
    # Derive the midpoint by determining the centroid of all target points
    midpoint_coord = elevation_values['target_point'].unary_union.centroid
    # Calculate the distances between each target point and the midpoint
    elevation_values['distance'] = elevation_values['target_point'].distance(midpoint_coord)
    # Find the minimum elevation value
    min_elevation_value = elevation_values['elevation'].min()
    # Extract the rows with the minimum elevation value
    min_elevation_rows = elevation_values[elevation_values['elevation'] == min_elevation_value]
    # Select the closest point to the midpoint based on the minimum distance
    min_elevation_location = min_elevation_rows.sort_values('distance').head(1)
    # Remove unnecessary columns and reset the index
    min_elevation_location = min_elevation_location.drop(columns=['distance']).reset_index(drop=True)
    return min_elevation_location

def get_closest_osm_waterways_with_target_locations(
        engine: Engine,
        catchment_area: gpd.GeoDataFrame,
        rec1_network_data_on_bbox: gpd.GeoDataFrame,
        osm_waterways_data_on_bbox: gpd.GeoDataFrame,
        distance_m: int = 300) -> gpd.GeoDataFrame:
    """
    Get the closest OpenStreetMap (OSM) waterway to each REC1 river within the specified distance threshold,
    along with the identified target locations used for the river input in the BG-Flood model.

    Parameters
    ----------
    engine : Engine
        The engine used to connect to the database.
    catchment_area : gpd.GeoDataFrame
        A GeoDataFrame representing the catchment area.
    rec1_network_data_on_bbox : gpd.GeoDataFrame
        A GeoDataFrame containing the REC1 network data that intersects with the catchment area boundary.
    osm_waterways_data_on_bbox : gpd.GeoDataFrame
        A GeoDataFrame containing the OSM waterways data that intersects with the catchment area boundary.
    distance_m : int, optional
        Distance threshold in meters for determining the closest OSM waterway. The default value is 300 meters.

    Returns
    -------
    gpd.GeoDataFrame
        A GeoDataFrame containing the closest OSM waterway to each REC1 river, along with the identified
        target locations used for the river input in the BG-Flood model.
    """
    # Find the closest OSM waterway to each REC1 river within the specified distance threshold
    closest_osm_waterways = find_closest_osm_waterways(
        rec1_network_data_on_bbox, osm_waterways_data_on_bbox, distance_m)
    # Retrieve the Hydro DEM data and resolution for the specified catchment area
    hydro_dem, res_no = get_dem_band_and_resolution_by_geometry(engine, catchment_area)
    # Initialize an empty GeoDataFrame to store the target locations
    closest_waterways_w_target_loc = gpd.GeoDataFrame()
    # Iterate over each row in the 'closest_osm_waterways' GeoDataFrame
    for i in range(len(closest_osm_waterways)):
        # Extract the current row for processing
        single_closest_osm_waterway = closest_osm_waterways.iloc[i:i + 1].reset_index(drop=True)
        # Obtain the target location with the minimum elevation from the Hydro DEM to the closest OSM waterway
        min_elevation_location = get_target_location_from_hydro_dem(single_closest_osm_waterway, hydro_dem, res_no)
        # Merge the target location data with the current OSM waterway data
        single_w_target_loc = single_closest_osm_waterway.merge(
            min_elevation_location, how='left', left_index=True, right_index=True)
        # Append the merged data to the overall GeoDataFrame
        closest_waterways_w_target_loc = pd.concat([closest_waterways_w_target_loc, single_w_target_loc])
    # Add the Hydro DEM resolution information to the resulting GeoDataFrame
    closest_waterways_w_target_loc['dem_resolution'] = res_no
    # Set the geometry column and reset the index
    closest_waterways_w_target_loc = closest_waterways_w_target_loc.set_geometry('target_point').reset_index(drop=True)
    return closest_waterways_w_target_loc

def get_matched_data_with_target_locations(
        engine: Engine,
        catchment_area: gpd.GeoDataFrame,
        rec1_network_data_on_bbox: gpd.GeoDataFrame,
        osm_waterways_data_on_bbox: gpd.GeoDataFrame,
        distance_m: int = 300) -> gpd.GeoDataFrame:
    """
    Get the matched data between REC1 rivers and OSM waterways within the specified distance threshold,
    along with the identified target locations used for the river input in the BG-Flood model.

    Parameters
    ----------
    engine : Engine
        The engine used to connect to the database.
    catchment_area : gpd.GeoDataFrame
        A GeoDataFrame representing the catchment area.
    rec1_network_data_on_bbox : gpd.GeoDataFrame
        A GeoDataFrame containing the REC1 network data that intersects with the catchment area boundary.
    osm_waterways_data_on_bbox : gpd.GeoDataFrame
        A GeoDataFrame containing the OSM waterways data that intersects with the catchment area boundary.
    distance_m : int, optional
        Distance threshold in meters for determining the closest OSM waterway. The default value is 300 meters.

    Returns
    -------
    gpd.GeoDataFrame
        A GeoDataFrame containing the matched data between REC1 rivers and OSM waterways, along with the identified
        target locations used for the river input in the BG-Flood model.
    """
    # Get the closest OSM waterway to each REC1 river along with the identified target locations used for BG-Flood
    closest_osm_waterways_with_target_locations = get_closest_osm_waterways_with_target_locations(
        engine, catchment_area, rec1_network_data_on_bbox, osm_waterways_data_on_bbox, distance_m)
    # Merge REC1 network data with the closest OSM waterways
    matched_data = rec1_network_data_on_bbox.merge(
        closest_osm_waterways_with_target_locations, on='objectid', how='right')
    # Drop unnecessary columns from the merged data
    matched_data.drop(columns=['boundary_line_no_x', 'boundary_line_x'], inplace=True)
    # Rename specific columns for consistency
    matched_data = matched_data.rename(
        columns={'boundary_line_no_y': 'boundary_line_no', 'boundary_line_y': 'boundary_line'})
    # Set the geometry column
    matched_data = matched_data.set_geometry("target_point")
    return matched_data


#!/usr/bin/env python3

import os

def tail_is_touching_heading(head_knot: complex, tail_knot: complex) -> bool:
	return abs(head_knot.real - tail_knot.real) <= 1 and abs(head_knot.imag - tail_knot.imag) <= 1

def tail_displacement(head_knot: complex, tail_knot: complex) -> complex:
	vertical_displacement = (head_knot.real > tail_knot.real) - (head_knot.real < tail_knot.real)
	horizontal_displacement = (head_knot.imag > tail_knot.imag) - (head_knot.imag < tail_knot.imag)

	return complex(vertical_displacement, horizontal_displacement)

def solution(elements: list[tuple[str, int]]) -> int:
	directional_displacement_dict = {'U': 1j, 'D': -1j, 'L': -1, 'R': 1}
	head_knot_location, tail_knot_location = 0j, 0j

	tail_knot_locations_visited = set()

	for direction, steps in elements:
		for _ in range(steps):
			head_knot_location += directional_displacement_dict[direction]

			if not tail_is_touching_heading(head_knot_location, tail_knot_location):
				tail_knot_location += tail_displacement(head_knot_location, tail_knot_location)
				tail_knot_locations_visited.add(tail_knot_location)

	return len(tail_knot_locations_visited)

def main():
	aoc_day_loc = os.path.dirname(__file__)

	with open(os.path.join(aoc_day_loc, 'inputs.txt'), 'r') as file:
		raw_data = [line.strip().split() for line in file.readlines()]
		inputs = [(elem1, int(elem2)) for elem1, elem2 in raw_data]

	print('Day 09 : Rope Bridge - part 1')
	print(f'>>> Answer : {solution(inputs)}')

if __name__ == '__main__':
	main()


#!/usr/bin/env python3

# BoBoBo

import driven.util as util
import driven.embed.sengine.sengine as wsgi_server
import driven.driven_process as driven_process
from driven.driven_app import driven_app

if __name__ == "__main__":
    args = util.get_server_cmdargs()
    if args.mode == 'driven':
        driven_processes = driven_process.start(
            'driven-test-process', './driven-process-test.yaml')
        wsgi_server.bootstrap_with_driven(
            '', 8000, driven_process, {'name': 'sengine'})
    else:
        app = driven_app(
            'app_example', {'logger': util.get_logger({'name': 'app_example'})})
        wsgi_server.bootstrap(
            '', 8000, {'app_example': app}, {'name': 'sengine'})


from odoo import models, api, _
from odoo.exceptions import UserError

class AccountMoveLineMaxcam(models.Model):
    _inherit = 'account.move.line'

    @api.constrains('price_unit')
    def _constrains_standard_price(self):
        for record in self:
            if record.move_id.move_type == 'out_invoice' and record.product_id:
                if record.price_unit < record.product_id.standard_price:
                    raise UserError(_("Los precios de venta no pueden ser menor que el costo de venta"))


from flask import Flask, jsonify, request, render_template
from rules import Rules
from flask_cors import CORS, cross_origin
import csv

app = Flask(__name__)
CORS(app=app)
csv_dict = {}
with open('fields.csv', 'r') as csv_file:
    reader = csv.reader(csv_file)
    for row in reader:
        csv_dict[row[0]] = row[0]+'.'+row[1]

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/createGroup/<group>', methods=['GET'])
def createGroup(group):
    obj = Rules()
    response = jsonify(obj.createGroup(group))
    return response

@app.route('/getGroups/', methods=['GET'])
def getGroup():
    obj = Rules()
    response = jsonify(obj.getGroups())
    return response

@app.route('/editGroup/<group>&<newName>', methods=['GET'])
def editGroup(group, newName):
    obj = Rules()
    response = jsonify(obj.editGroups(group, newName))
    return response

@app.route('/deleteGroup/<group>', methods=['GET'])
def deleteGroup(group):
    obj = Rules()
    response = jsonify(obj.deleteGroup(group))
    return response

@app.route('/addRule/<group>&<rule>&<field>&<criteria>&<int:value>', methods=["GET"])
def addeRule(group, rule, field, criteria, value):
    obj = Rules(group=group, ruleName=rule, field=csv_dict[field],
                criteria=criteria, value=value)
    response = jsonify({
        "Response": obj.post()
    })
    return response

@app.route('/getRules/', methods=['GET'])
def get():
    obj = Rules()
    response = jsonify(obj.get())
    return response

@app.route('/deleteRule/<rule>', methods=["GET"])
def deleteRule(rule):
    try:
        obj = Rules(ruleName=rule)
        response = jsonify({
            "Response": obj.delete()
        })
        return response
    except Exception as e:
        response = jsonify({
            "Response": False,
            "Reason": f"{e}"
        })
        return response

@app.route('/updateRule/<group>&<rule>&<field>&<criteria>&<int:value>', methods=["GET"])
def updateRule(group, rule, field, criteria, value):
    try:
        obj = Rules(group=group, ruleName=rule, field=csv_dict[field],
                    criteria=criteria, value=value)
        response = jsonify({
            "Response": obj.update()
        })
        return response
    except Exception as e:
        response = jsonify({
            "Response": False,
            "Reason": f"{e}"
        })
        return response

@app.route("/apply/<int:days>", methods=["GET"])
def apply(days):
    obj = Rules()
    response = jsonify(obj.apply(days=days))
    return response

if __name__ == "__main__":
    app.run(debug=True)


# enlarge to consider hyperfine coupling
from copy import deepcopy
from scipy.sparse import csc_matrix,bmat
import numpy as np

def add_nucleus(atin,s=0.5):
  at = deepcopy(atin) # copy object
  norig = atin.sx.shape[0] # original shape
  def enlarge(m,n=2):
    mo = [[None for j in range(n)] for i in range(n)]
    for i in range(n): mo[i][i] = m
    mo = bmat(mo) # return matrix
    return mo
  if s==0.5:
    ns = 2 # additional size, nuclear spin
    iden = csc_matrix(np.identity(norig,dtype=np.complex)) # identity operator
    iz = bmat([[iden,None],[None,-iden]])/2.
    ix = bmat([[None,iden],[iden,None]])/2.
    iy = bmat([[None,-1j*iden],[1j*iden,None]])/2.
  else: raise # raise error
  for key in at.terms: # loop over
    at.terms[key] = enlarge(at.terms[key],n=ns) # enlarge Hamiltonian
  at.update() # update attributes
  # add the new atributes
  at.ix = ix
  at.iy = iy
  at.iz = iz
  at.terms["ix"] = ix
  at.terms["iy"] = iy
  at.terms["iz"] = iz
  # add a new attribute
  si = at.terms["sx"]*ix + at.terms["sy"]*iy + at.terms["sz"]*iz
  at.si = si  # add hyper
  at.terms["si"] = si # add hyperfine coupling
  at.has_nucleus = True # has nucleus
  return at


"""In this project, our final Python script will need to be able to deliver the following information when the script is run:

1. Total number of votes cast
2. A complete list of candidates who received votes
3. Total number of votes each candidate received
4. Percentage of votes each candidate won
5. The winner of the election based on popular vote
6. Save the results to our text file"""

## 1. Get the Total Votes from election_results.csv.

# Add dependencies.
import csv
import os

# Assign a variable to load a file from a path.
file_to_load = os.path.join("Resources", "election_results.csv")
# Assign a variable to save the file to a path.
file_to_save = os.path.join("analysis", "election_analysis_for_candidate.txt")

# Initialize a total vote counter.
total_votes = 0

with open(file_to_load) as election_data:
    file_reader = csv.reader(election_data)

    # REad the header row.
    headers = next(file_reader)

    #Print each row in the CSV file.
    for row in file_reader:
            #2. Add to the totla vote count.
            total_votes += 1
    fstring_total_vote = (
        f"\nTask#1 Result\n"
        f"------------------------------------\n"
        f"Total number of votes cast is {total_votes}\n"
        f"------------------------------------\n")

# Print the totla votes.
print(fstring_total_vote)

with open(file_to_save, "w") as txt_file:
    # Save the final vote count to the text file.
    txt_file.write(fstring_total_vote)

#resutls: Total number of votes cast is 369711

## 2. Get the list of candidates who received votes

import csv
import os
# Assign a variable to load a file from a path and to save the file to a path.
file_to_load = os.path.join("Resources", "election_results.csv")
file_to_save = os.path.join("analysis", "election_analysis_for_candidate.txt")

#Initialial vote count.
total_votes = 0

# Candidate Options
candidate_options = []

# Open the election results and read the file.
with open(file_to_load) as election_data:
    file_reader = csv.reader(election_data)

    # Read the header row.
    headers = next(file_reader)

    # Print each row in the CSV file.
    for row in file_reader:
        # Add to the total vote count.
        total_votes += 1

        # Print the candidate name from each row.
        candidate_name = row[2]

        # If the candidate does not match any existing candidate...
        if candidate_name not in candidate_options:
            # Add it to the list of candidates.
            candidate_options.append(candidate_name)

    fstring_candiate_list = (
        f"\nTask#2 Result\n"
        f"------------------------------------\n"
        f"The list of candidates who received votes is \n"
        f"{candidate_options}\n"
        f"------------------------------------\n")

# Print the candidate list.
print(fstring_candiate_list)

with open(file_to_save, "a") as txt_file:
    # Save the final vote count to the text file.
    txt_file.write(fstring_candiate_list)

#resutls: The list of candidates who received votes are ['Charles Casper Stockham', 'Diana DeGette', 'Raymon Anthony Doane']

"""resutls: ['Charles Casper Stockham', 'Diana DeGette', 'Raymon Anthony Doane']"""

## 3. Get the total number of votes each candidate received

import csv
import os
file_to_load = os.path.join("Resources", "election_results.csv")
fiel_to_save = os.path.join("analysis", "election_analysis_for_candidate.txt")

total_votes = 0

candidate_options = []

candidate_votes= {}

with open(file_to_load) as election_data:
    file_reader = csv.reader(election_data)

    header = next(file_reader)

    for row in file_reader:
        total_votes += 1

        candidate_name = row[2]

        if candidate_name not in candidate_options:

            candidate_options.append(candidate_name)

            candidate_votes[candidate_name] =  0

        candidate_votes[candidate_name] += 1

    fstring_candidate_votes = (
        f"\nTask#3 Result\n"
        f"------------------------------------\n"
        f"The total number of votes each candidate received is \n"
        f"{candidate_votes}\n"
        f"------------------------------------\n")

# Print the candidate list.
print(fstring_candidate_votes)

with open(file_to_save, "a") as txt_file:
    # Save the final vote count to the text file.
    txt_file.write(fstring_candidate_votes)

#resutls:The total number of votes each candidate received are {'Charles Casper Stockham': 85213, 'Diana DeGette': 272892, 'Raymon Anthony Doane': 11606}

## 4. Get the percentage of votes each candidate won

# Add our dependencies.

import csv
import os
# Assign a variable to load a file from a path.
file_to_load = os.path.join("Resources/election_results.csv")
# Assign a variable to save the file to a path.
file_to_save = os.path.join("analysis", "election_analysis_for_candidate.txt")

# 1. Initialize a total vote counter.
total_votes = 0
#Creaste a list for both Candidate and County.
candidate_options = []
county_options = []
candidate_votes = {}
county_votes = {}

# Winning Candidate & County and Winning Count Tracker
winning_candidate = ""
winning_count = 0
winning_percentage = 0

# Open the election results and read the file.
with open(file_to_load) as election_data:
    # Read the file object with the reader function.
    file_reader = csv.reader(election_data)
    # Print the header row.To ensure it would skip this row.
    headers = next(file_reader)

    # Print each row in the CSV file.
    for row in file_reader:
        # Add to the total vote count.
        total_votes += 1

        # Print the candidate name from each row.
        candidate_name = row[2]

        if candidate_name not in candidate_options:
          # Add the candidate name to the candidate list.
            candidate_options.append(candidate_name)

           # 2. Begin tracking that candidate's vote count.
            candidate_votes[candidate_name] = 0

        # Add a vote to that candidate's count
        candidate_votes[candidate_name] += 1

    with open(file_to_save, "a") as txt_file:
        # Print the final vote count to the terminal.
        election_results = (
            f"\nElection Results\n"
            f"-------------------------\n"
            f"Total Votes: {total_votes:,}\n"
            f"-------------------------\n")

#        print(election_results, end="")
    # Save the final vote count to the text file.
#        txt_file.write(election_results)

# Determine "f" by looping through the counts.
        # 1. Iterate through the candidate list.

        vote_percentage_dict = {}
        for candidate_name in candidate_votes:
            # 2. Retrieve vote count of a candidate.
            votes = candidate_votes[candidate_name]
            # Print the candidate vote dictionary.

            # 3. Calculate the percentage of votes.
            vote_percentage = float(votes) / float(total_votes)*100

            # 4. Add the candidate name and percentage of votes.
            vote_percentage_dict[candidate_name] = round(vote_percentage,1)

        candidate_results = (
                        f"\nTask#4 Result\n"
                        f"------------------------------------\n"
                        f"The percentage of votes each candidate won is \n"
                        f"{vote_percentage_dict}\n")

        print(candidate_results)

        #result:The percentage of votes each candidate won is {'Charles Casper Stockham': 23.0, 'Diana DeGette': 73.8, 'Raymon Anthony Doane': 3.1}

        # Save the candidate results to our text file.
        txt_file.write(candidate_results)

#5. Determine winning vote count, winning percentage, and winning candidate.

if (votes > winning_count) and (vote_percentage > winning_percentage):
            # If true then set winning_count = votes and winning_percent =
            # vote_percentage.
    winning_count = votes
    winning_percentage = vote_percentage
                # And, set the winning_candidate equal to the candidate's name.
    winning_candidate = candidate_name
    winning_candidate_summary = (
            f"\nTask#5 Result\n"
            f"------------------------------------\n"
            f"winning_candidate_summary\n"
            f"Winner: {winning_candidate}\n"
            f"Winning Vote Count: {winning_count:,}\n"
            f"Winning Percentage: {winning_percentage:.1f}%\n"
            f"-------------------------\n")
    print(winning_candidate_summary)

# 6. Save the candidate results to our text file.
    with open(file_to_save, "a") as txt_file:
        txt_file.write(winning_candidate_summary)

# Results:
#winning_candidate_summary
#Winner: Raymon Anthony Doane
#Winning Vote Count: 11,606
#Winning Percentage: 3.1%


import json

def load_config(config_name):
    with open(config_name, 'r') as f:
        config = json.load(f)
    # scripts = json.load(open(config_name))
    def eval_json(config):
        for k in config:
            if type(config[k]) != dict:
                if type(config[k]) is str:
                    # if python types, then evaluate str expressions
                    if config[k][:5] in ['range', 'float']:
                        config[k] = eval(config[k])
            else:
                eval_json(config[k])
    eval_json(config)
    return config

def json_dumps(**kwargs):
    # __repr__ may contain `\n`, json replaces it by `\\n` + indent
    return json.dumps(**kwargs).replace('\\n', '\n    ')

class JSONEncoder(json.JSONEncoder):
    def default(self, x):
        # add encoding for other types if necessary
        if isinstance(x, range):
            return 'range({}, {})'.format(x.start, x.stop)
        if not isinstance(x, (int, str, list, float, bool)):
            return repr(x)
        return json.JSONEncoder.default(self, x)


import os
import requests

from urllib.parse import urlparse

def download_img(url, filepath):
    response = requests.get(url)
    response.raise_for_status()

    with open(filepath, 'wb') as file:
        file.write(response.content)

def get_urls_file_extension(url):
    parsed_link = urlparse(url)
    splitted_path = os.path.splitext(parsed_link.path)
    return splitted_path[-1]


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

import numpy as np
import time
import subprocess
from typing import Iterable, List
from read_eval import read_eval_output
from tqdm import tqdm

def shell_command(command):
    peval = subprocess.Popen(
                command,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT)
    stdout, stderr = peval.communicate()
    return stdout.decode("utf-8")

def read_starsem(fn: str) -> Iterable[List[str]]:
    sentence = []
    with open(fn) as fh:
        for line in fh:
            if line == "\n":
                yield sentence
                sentence = []
            else:
                sentence.append(line.split())

def eval_singles(gold: Iterable[str], pred: Iterable[str]):
    tpfpfns = []
    for g, p in tqdm(zip(gold, pred), total=len(gold)):
        with open("g.tmp", "w") as gh, open("p.tmp", "w") as ph:
            print("\n".join(["\t".join(x) for x in g]), end="\n\n", file=gh)
            print("\n".join(["\t".join(x) for x in p]), end="\n\n", file=ph)
        peval = shell_command("perl eval.cd-sco.pl -g g.tmp -s p.tmp".split())
        results = read_eval_output(peval.split("\n"))
        tpfpfns.append(np.array([[v["tp"], v["fp"], v["fn"]] for v in
                                 results.values()]
                                )
                       )
    return np.array(tpfpfns)

class color:
    PURPLE = '\033[95m'
    CYAN = '\033[96m'
    DARKCYAN = '\033[36m'
    BLUE = '\033[94m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    RED = '\033[91m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'
    END = '\033[0m'

def prec(x, i, j):
    return np.divide(x[..., i], (x[..., i] + x[..., j] + 1e-6))

def rec(x, i, j):
    return np.divide(x[..., i], (x[..., i] + x[..., j] + 1e-6))

def fscore(p, r):
    return np.divide(2 * p * r, (p + r + 1e-6))

def compute_scores(scores, counts, p, r, x):
    scores[:, x] = fscore(p, r)
    return scores

def fill_scores(scores, evals, debug=False):
    eval_cnts = evals.shape[0] if len(evals.shape) > 2 else 1
    if eval_cnts == 1:
        a, b = evals.shape
        evals = np.reshape(evals, (1, a, b))
    for i in range(eval_cnts):
        scores[i, ..., 0] = prec(evals[i], 0, 1)
        scores[i, ..., 1] = rec(evals[i], 0, 2)
        scores[i, ..., 2] = fscore(scores[i, ..., 0], scores[i, ..., 1])

        if debug:
            print(scores[i, ..., 0])
            print(scores[i, ..., 1])
            print(scores[i, ..., 2])
    return scores

def main(b, folder, devtest, setup1, setup2, debug=False):

    if debug:
        s = time.time()

    r = 5
    gold = list(read_starsem(f"{folder}/neg_{devtest}.starsem"))
    pred1 = []
    pred2 = []
    for i in range(1, r+1):
        print(f"Run: {i}")
        p1_fn = f"{folder}/{setup1}/{devtest}.starsem.{i}.pred"
        p2_fn = f"{folder}/{setup2}/{devtest}.starsem.{i}.pred"
        p1 = read_starsem(p1_fn)
        p2 = read_starsem(p2_fn)
        pred1.extend(eval_singles(gold, p1))
        pred2.extend(eval_singles(gold, p2))

    # number of runs
    n = len(gold)
    b = int(b)

    M1 = np.array(pred1)
    M2 = np.array(pred2)

    if debug:
        print(f"reading in data {time.time() - s}")
        s = time.time()

    # sample 'b' ids for a test set of size 'n' with 'r' runs
    # np.random.choice(n * r, n*b).reshape(b, n)

    if debug:
        print(f"data as matrix {time.time() - s}")
        s = time.time()

    # sample_ids samples b datasets of size n with indices ranging the five
    # runs creating a sample out of all runs
    sample_ids = np.random.choice(n * r, n*b).reshape(b, n)

    # fill a zero matrix with how often each sentence was drawn in one sample
    samples = np.zeros((n*r, b))
    for j in range(b):
        for i in range(n):
            samples[sample_ids[j, i], j] += 1

    if debug:
        print(f"get samples {time.time() - s}")
        s = time.time()

    # get the counts for the sample
    # Mx has the counts per sentence and samples chooses how often each sample
    # is taken resulting in a matrix of b rows with sums of tp, fp, fn etc.
    evals1 = (np.einsum('ijk,il->ljk', M1, samples))
    evals2 = (np.einsum('ijk,il->ljk', M2, samples))

    if debug:
        print(f"extract sample counts {time.time() - s}")
        s = time.time()

    # compute the eval measures for each row/sample
    sample_scores1 = fill_scores(np.zeros((b, M1.shape[1], M1.shape[2])), evals1, False)
    sample_scores2 = fill_scores(np.zeros((b, M2.shape[1], M2.shape[2])), evals2, False)

    if debug:
        print(f"compute scores {time.time() - s}")
        s = time.time()
        print(np.sum(M1, axis=0))

    # scores for the dataset across all runs
    true_scores1 = fill_scores(np.zeros((1, M1.shape[1], M1.shape[2])), np.sum(M1, axis=0))
    true_scores2 = fill_scores(np.zeros((1, M2.shape[1], M2.shape[2])), np.sum(M2, axis=0))

    # bootstrap scores
    deltas = true_scores1 - true_scores2
    deltas *= 2

    diffs = sample_scores1 - sample_scores2
    diffs_plus = np.where(diffs >= 0, diffs, 0)
    diffs_minus = np.where(diffs < 0, diffs, 0)

    if debug:
        print("sample_scores1")
        print(sample_scores1)
        print("sample_scores2")
        print(sample_scores2)
        print("diffs")
        print(diffs)
        print("diffs_plus")
        print(diffs_plus)
        print("diffs_minus")
        print(diffs_minus)

    deltas_plus = np.where(deltas > 0, deltas, np.float("inf"))

    deltas_minus = np.where(deltas < 0, deltas, -np.float("inf"))
    s1 = np.sum(diffs_plus > deltas_plus, axis=0)
    s2 = np.sum(diffs_minus < deltas_minus, axis=0)

    if debug:
        print(f"the rest {time.time() - s}")

        print(true_scores1)
        print(true_scores2)

        print(s1 / b)
        print(s2 / b)

        print()
    s1 = s1 / b
    s2 = s2 / b
    end = color.END

    print(f"{color.BOLD}{color.BLUE}{setup1} || {color.RED}{setup2}{color.END}")
    _m, _p, _r, _f = "Measure Precision Recall Fscore".split()
    print(f"{_m:<15}{_p:<21}\t{_r:<21}\t{_f:<21}")
    for i, name in enumerate("CUE SM ST FN".split()):
        print(f"{name:<13}:", end=" ")
        for j, mea in enumerate("Prec. Rec. Fscore".split()):
            x = true_scores1[0][i][j]
            y = true_scores2[0][i][j]
            z = s1[i][j] if x > y else s2[i][j]
            if z < 0.05 and x > y:
                bold = color.BLUE
            elif z < 0.05 and y > x:
                bold = color.RED
            else:
                bold = color.END
            # print(f"{bold}{name:<13}: {x:.2%}\t{y:.2%}\t{z:.4f}{end}", end="\t")
            print(f"{bold}{x:.2%}\t{y:.2%}\t{z:.4f}{end}", end="\t")
        print()

    print()
    if debug:
        for r_i in [1, 2, 3, 4, 5]:
            print(r_i)
            # scores for the dataset across all runs (i-1)*int(n/5):int(n/5)*i
            print(M1.shape)
            m1 = M1[(r_i-1)*int(n):int(n)*r_i, ...]
            m2 = M2[(r_i-1)*int(n):int(n)*r_i, ...]
            print(m1.shape)
            print(np.sum(m1, axis=0))
            print(np.sum(m2, axis=0))
            true_scores1 = fill_scores(np.zeros((1, m1.shape[1], m1.shape[2])), np.sum(m1, axis=0))
            true_scores2 = fill_scores(np.zeros((1, m2.shape[1], m2.shape[2])), np.sum(m2, axis=0))
            # true_scores1 = fill_scores(np.zeros((1, 8)), np.sum(M1[(r_i-1)*int(N/r):int(N/r)*r_i, :], axis=0))
            # true_scores2 = fill_scores(np.zeros((1, 8)), np.sum(M2[(r_i-1)*int(N/r):int(N/r)*r_i, :], axis=0))
            print(true_scores1)
            print(true_scores2)

if __name__ == "__main__":
    import sys
    b = 10e5
    debug = True
    folder = sys.argv[1]
    devtest = sys.argv[2]
    setup1 = sys.argv[3]
    setup2 = sys.argv[4]

    main(b, folder, devtest, setup1, setup2, debug=debug)


#!/usr/bin/python3

import sys
from telnetlib import FORWARD_X
import tty
import termios
from enum import IntEnum, unique
from turtle import forward
import RPi.GPIO as GPIO
from motor import Motor, MotorDirection
from sensors import HCSR04, HCSR04Event
from controller import PIDController, IntersectionType
from pins import RaspiPin, RaspiPinError
import time

class Droid:
    def __init__(self, battery_voltage=9.0, motor_voltage=6.0, warn=True,
                 speed=0.5):
        GPIO.setmode(GPIO.BCM)
        GPIO.setwarnings(warn)
        self.speed = speed
        self.motors = Motor(battery_voltage, motor_voltage)

    def __del__(self):
        self._cleanup()

    def _set_led1(self, state):
        GPIO.output(RaspiPin.LED1_PIN, state)

    def _set_led2(self, state):
        GPIO.output(RaspiPin.LED2_PIN, state)

    def _set_oc1(self, state):
        GPIO.output(RaspiPin.OC1_PIN, state)

    def _set_oc2(self, state):
        GPIO.output(RaspiPin.OC2_PIN, state)

    def _cleanup(self):
        GPIO.cleanup()

    def forward(self):
        self.motors.forward(speed=self.speed)

    def backward(self):
        self.motors.backward(speed=self.speed)

    def stop(self):
        self.motors.stop()

    def right(self):
        self.motors.right(speed=self.speed)

    def left(self):
        self.motors.left(speed=self.speed)

class RoverKey(IntEnum):
    UP = 0
    DOWN = 1
    RIGHT = 2
    LEFT = 3
    STOP = 4

class RoverDroid(Droid):
    def __init__(self, battery_voltage=9.0, motor_voltage=6.0, warn=True,
                 speed=0.5):
        Droid.__init__(self, battery_voltage, motor_voltage, warn, speed)

    def _read_char(self):
        """Read chars from keyboard"""
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        if ch == '0x03':
            raise KeyboardInterrupt
        return ch

    def _read_key(self):
        """Converts keys from keyboard to directions to the droid"""
        c1 = self._read_char()
        if ord(c1) != 0x1b:
            # escape char
            return RoverKey.STOP
        c2 = self._read_char()
        if ord(c2) != 0x5b:
            # [ char
            raise KeyboardInterrupt
        c3 = self._read_char()
        return RoverKey(ord(c3) - 65)  # 0=Up, 1=Down, 2=Right, 3=Left arrows

    def run(self):
        """Continuously read keys stroke from the keyboard and applies
        directions to current droid"""
        try:
            print("Use the arrow keys to move the robot")
            print("Press CTRL-c to quit the program")
            while True:
                key = self._read_key()
                if key is RoverKey.UP:
                    print("ROVER", "FORWARD")
                    self.forward()
                elif key is RoverKey.DOWN:
                    print("ROVER", "BACKWARD")
                    self.backward()
                elif key is RoverKey.LEFT:
                    print("ROVER", "TURN LEFT")
                    self.left()
                elif key is RoverKey.RIGHT:
                    print("ROVER", "TURN RIGHT")
                    self.right()
                elif key is RoverKey.STOP:
                    print("ROVER", "STOP")
                    self.stop()
                else:
                    print("ROVER", "UNKNOWN VALUE:", key)
                    raise KeyboardInterrupt
        except KeyboardInterrupt:
            self._cleanup()

class Droid3Sensors(Droid):
    """Class to explore a maze with a controller to drives motors according to
    sensors"""

    def __init__(self, battery_voltage=9.0, motor_voltage=6.0, warn=True,
                 speed=0.5, low=15., high=50., target=20., KP=0.005, KD=0.0002,
                 KI=0.0, sample_time=0.001):
        Droid.__init__(self, battery_voltage, motor_voltage, warn, speed)
        print("Robot 3 Sensors with controller", "speed=%02f" % speed)
        self.left_sensor = HCSR04("LEFT", RaspiPin.ECHO_PIN_3,
                                  RaspiPin.TRIGGER_PIN_3, low=low, high=high)
        self.front_sensor = HCSR04("FRONT", RaspiPin.ECHO_PIN_1,
                                   RaspiPin.TRIGGER_PIN_1, low=2*low, high=high)
        self.right_sensor = HCSR04("RIGHT", RaspiPin.ECHO_PIN_2,
                                   RaspiPin.TRIGGER_PIN_2, low=low, high=high)
        self.controller = PIDController(self.motors, self.left_sensor,
                                        self.front_sensor, self.right_sensor,
                                        speed=speed, target=target, KP=KP,
                                        KD=KD, KI=KI, sample_time=sample_time)

    def explore(self):
        """Explores maze until the exit is found"""
        while True:
            """front_sensor_event, distance = self.controller.get_front_distance()
            right_sensor_event, distance = self.controller.get_right_distance()
            left_sensor_event, distance = self.controller.get_left_distance()

            if front_sensor_event is HCSR04Event.DANGER:
                print("DANGER in front! Turn!")
                self.right()
            else:
                self.forward()

            if right_sensor_event is HCSR04Event.DANGER:
                print("DANGER at right! STOP!")
                self.stop()
            elif right_sensor_event is HCSR04Event.WALL:
                print("WALL DETECTED !")

            if left_sensor_event is HCSR04Event.DANGER:
                print("DANGER at right! STOP!")
                self.stop()"""

            front_sensor_event, front_distance = self.controller.get_front_distance()
            right_sensor_event, right_distance = self.controller.get_right_distance()
            left_sensor_event, left_distance = self.controller.get_left_distance()

            print("front sensor event: " + str(front_sensor_event)
                + " front_distance: " + str(front_distance)
                + "\nright_sensor_event: " + str(right_sensor_event)
                + " right_distance: " + str(right_distance)
                + "\nleft_sensor_event: " + str(left_sensor_event)
                + " left_distance: " + str(left_distance))

            if self.controller.get_intersection_type(left_sensor_event, front_sensor_event, right_sensor_event) is IntersectionType.PathFour:
                print("DEHORS")
                self.motors.stop()
                self.controller.passPathThreeRightFront()
            elif self.controller.get_intersection_type(left_sensor_event, front_sensor_event, right_sensor_event) is IntersectionType.PathThreeLeftFront:
                print("Allez tout droit")
                self.controller.passPathThreeLeftFront()
            elif self.controller.get_intersection_type(left_sensor_event, front_sensor_event, right_sensor_event) is IntersectionType.PathThreeRightFront:
                print("Allez à droite")
                self.controller.passPathThreeRightFront()
            elif self.controller.get_intersection_type(left_sensor_event, front_sensor_event, right_sensor_event) is IntersectionType.PathThreeLeftRight:
                print("Allez à droite")
                self.controller.passPathThreeLeftRight()
                while (self.controller.get_right_distance()[1] is HCSR04Event.NOTHING):
                    self.motors.forward()
            elif self.controller.get_intersection_type(left_sensor_event, front_sensor_event, right_sensor_event) is IntersectionType.PathTwoLeft:
                print("Allez à gauche")
                self.controller.passPathTwoLeft()
            elif self.controller.get_intersection_type(left_sensor_event, front_sensor_event, right_sensor_event) is IntersectionType.PathTwoRight:
                print("Allez a droite")
                self.controller.passPathTwoRight()
            elif self.controller.get_intersection_type(left_sensor_event, front_sensor_event, right_sensor_event) is IntersectionType.PathTwoFront:
                print("C'est un couloir, allez tout droit")
                print("Going to the next intersection")
                self.controller.go_to_the_next_intersection()
            elif self.controller.get_intersection_type(left_sensor_event, front_sensor_event, right_sensor_event) is IntersectionType.PathOne:
                print("Cul de sac, Demi tour")
                self.controller.passDeadEnd()
            else:
                print("Erreur, stop")


import json
import os
import time

from tool.get_bin import get_bin
from multiprocessing import Pool
from panoramix.paronomix import panoramix
from panoramix.paronomix_str import panoramix_str

def get_str_to_panoramix_double(path, result_path):
    """
    :param path: path is the path where the binary code of the parsed data is stored
                path is the path of the binary code file, the internal storage is the binary code of each contract address, and the data item contains the basic information of each contract
    :param result_path: result_path stores the results in this path, which is a directory. Each parsing result is stored separately in a json file and saved in this path
    :return:
    """
    list = []
    # First iterate through the folders
    g = os.walk(path)
    # Traverse the results of the analysis and count
    for path, dir_list, file_list in g:
        for file_name in file_list:
            filepath = path + file_name  # The specific file path where each binary code is stored
            list.append(filepath)

    all_num = 0
    time_out = 0

    pool = Pool(processes=4)  # Start four work processes
    for i in list:
        # print(i)
        # print(type(i))
        all_num = all_num + 1
        print(all_num)
        try:
            # if all_num == 100 :
            #     break
            f = open(i, "r")  # Open i, read the string of binary code
            str = f.read()
            # print(str)
            print(str)
            addr_list = address = i.split('/')
            add = addr_list[-1]
            add_list = add.split('.')
            address = add_list[0]

            pool.apply_async(panoramix_str, args=(str, address, result_path,))
        except Exception as e:
            time_out = time_out + 1
            print(e)
            pass
            continue

    pool.close()
    pool.join()
    print("all_num", all_num)
    print("time_out", time_out)


from pathlib import Path
from typing import Union
import gzip
import json

ann_folder = Path("ann")
json_folder = Path("json")
text_folder = Path("text")

def get_filename_no_ext(path: Union[Path, str]):
    if isinstance(path, str):
        path = Path(path)
    path = path.stem.__str__()
    path = path.split(".")[0]
    return path

def get_filestar_name(filename: str):
    return get_filename_no_ext(filename)[:-1] + "*"

def load_jsongz(json_filename: Union[Path, str]) -> json:
    if isinstance(json_filename, Path):
        json_filename = json_filename.__str__()
    with gzip.open(json_filename, "r") as f:
        data = f.read()
        j = json.loads(data.decode('utf-8'))
    return j

def read_txt(path: Union[Path, str]):
    if isinstance(path, Path):
        path = path.__str__()
    with open(path, encoding="UTF8") as txt:
        return txt.read()


from os.path import join, exists
import os

debug = True
'''project path, change your path here'''
path_code = 'F:\\Dropbox\\DataScience\\Project\\MTCNN-TF-Vehicle'

'''path to detection dataset'''
path_detection = join(path_code, 'TrainingSets', 'detection')
path_detection_imgs = join(path_detection, 'imgs')
path_detection_labels = join(path_detection, 'anno_detection.txt')

'''path to intermediate outputs'''
path_output_files = 'E:\\DM\\MTCNN\\TMP' # requires large disk space in this folder
path_output_txt = join(path_output_files, 'txt')
path_output_models = join(path_output_files, 'models')
path_output_logs = join(path_output_files, 'logs')
if not exists(path_output_files): os.makedirs(path_output_files)
if not exists(path_output_models): os.makedirs(path_output_models)
if not exists(path_output_logs): os.makedirs(path_output_logs)
if not exists(path_output_txt): os.makedirs(path_output_txt)

'''path to landmark dataset'''
path_landmark = join(path_code, 'TrainingSets', 'landmark')
path_landmark_imgs = join(path_landmark, 'imgs')
path_landmark_labels = join(path_landmark, 'anno_landmark.txt')

'''general config'''
classtype = {'neg':0, 'pos':1, 'part':-1, 'landmark':-2}
resize = {'pnet':12, 'rnet':24, 'onet':48}

'''training params'''
# epoch = [18, 14, 22]
epoch = [14, 18, 22] # training epoch for pnet, rnet and onet
BATCH_SIZE = 350 # batch size during training
# weighted propotions for each data type in a merged training batch
weights = {'pos':1, 'part':1, 'neg':3, 'landmark':0.01}
# learning rate decay policy
# for example, in this setting, use initial learning rate for the first 0.3 training process
# the learning rate will be decayed by a factor of 0.1**1 during 0.3~0.6 training process
# the learning rate will be decayed by a factgor of 0.1**3 after 0.9 training process
lr_decay_factor = 0.1
lr_decay_boundary = [0.3, 0.6, 0.9]

'''model params'''
hard_example_ratio = 0.7 # hard example selection ratio, only enabled in classification

# how much each loss contributes to total loss
loss_ratio = {
            'pnet': {'cls':1.0, 'bbox':0.5, 'landmark':0.0},
            'rnet': {'cls':1.0, 'bbox':0.5, 'landmark':0.0},
            'onet': {'cls':1.0, 'bbox':0.5, 'landmark':0.0}
             }
'''
loss_ratio = {
            'pnet': {'cls':1.0, 'bbox':0.5, 'landmark':0.5},
            'rnet': {'cls':1.0, 'bbox':0.5, 'landmark':0.5},
            'onet': {'cls':1.0, 'bbox':0.5, 'landmark':1.0}
             }
'''


def binary_search(n: int) -> int:
    start, end = 0, n1 - 1
    while start <= end:
        mid = (start + end) // 2
        if n == note1[mid]:
            return 1
        elif n > note1[mid]:
            start = mid + 1
        else:
            end = mid - 1
    return 0

t = int(input())
for _ in range(t):
    n1 = int(input())
    note1 = sorted(list(map(int, input().split())))
    n2 = int(input())
    note2 = list(map(int, input().split()))
    for num in note2:
        print(binary_search(num))


import time
from datetime import datetime, timedelta
from math import atan2, cos, radians, sin, sqrt
from typing import Dict, List, Optional, Tuple, TypeVar, Union

import openrouteservice as ors  # type: ignore
import pytz
import requests
from django.conf import settings
from django.contrib.gis.geos.point import Point
from django.core.management.base import BaseCommand, CommandError

from auto.models import AutoRide, GPSData, Vehicle

Point_ = TypeVar("Point_", bound=Union[List[float], Tuple[float, float]])

class Command(BaseCommand):
    help = "Запускает движение авто по заданному маршруту между 2 точками"
    WRITE_TIME_OPTION = 60

    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self.client = ors.Client(key=settings.OPENROUTESERVISE_API)
        self.current_speed: int = 0
        self.timestamp: datetime = datetime.now(tz=pytz.UTC)

    def add_arguments(self, parser) -> None:
        parser.add_argument("vehicle_id", type=int, help="ID автомобиля")
        parser.add_argument("start_address", type=str, help="Начальный адрес поездки")
        parser.add_argument("end_address", type=str, help="Конечный адрес поездки")
        parser.add_argument("vehicle_speed", type=int, help="Скорость автомобиля")
        parser.add_argument("vehicle_acceleration", type=int, help="Ускорение автомобиля")
        parser.add_argument("in_real_time", type=bool, help="В реальном времени")
        parser.add_argument("--yes", action="store_true")
        parser.add_argument("--no", dest="in_real_time", action="store_false")
        parser.set_defaults(in_real_time=False)

    def handle(self, *args, **options) -> None:
        self.vehicle_id = options["vehicle_id"]
        self.start_address = options["start_address"]
        self.end_address = options["end_address"]
        self.vehicle_speed = options["vehicle_speed"]
        self.vehicle_acceleration = options["vehicle_acceleration"]
        self.in_real_time = options.get("in_real_time")

        enterprise = Vehicle.objects.get(pk=self.vehicle_id).enterprise
        if enterprise:
            self.tzinfo = pytz.timezone(enterprise.timezone)
        else:
            self.tzinfo = pytz.UTC
        self.start_time = self.timestamp

        start_point = self.get_coordinates_from_address(self.start_address)
        if start_point is None:
            CommandError("Начальный адрес не корректный")
            return

        end_point = self.get_coordinates_from_address(self.end_address)
        if end_point is None:
            CommandError("Конечный адрес не корректный")
            return

        this_ride = AutoRide(
            vehicle_id=self.vehicle_id,
            start_date=self.timestamp,
            end_date=None,
            start_point=Point(*start_point),
            end_point=None,
            distance=0,
        )
        this_ride.save()

        self.stdout.write(
            self.style.SUCCESS(f"{self.timestamp} - Начата поездка из {self.start_address} в {self.end_address}")
        )
        coordinates = self.get_track(start_point, end_point)

        # MAIN LOOP
        i = 0
        distance_p1_p2 = None
        total_distance = 0

        while i < len(coordinates) - 1:
            point_1 = coordinates[i]
            point_2 = coordinates[i + 1]

            if self.in_real_time:
                time.sleep(self.WRITE_TIME_OPTION)
            new_speed = self.WRITE_TIME_OPTION * self.vehicle_acceleration

            if new_speed > self.vehicle_speed:
                self.current_speed = self.vehicle_speed
                self.vehicle_acceleration = 0
            else:
                self.current_speed = new_speed

            vehicle_dist: int = (
                self.current_speed * self.WRITE_TIME_OPTION
                + self.vehicle_acceleration * (self.WRITE_TIME_OPTION**2) // 2
            )
            total_distance += vehicle_dist
            print(self.current_speed, total_distance)
            return

            if not distance_p1_p2:
                distance_p1_p2 = self.distance_between_coordinates(point_1, point_2)

            if vehicle_dist < distance_p1_p2:
                distance_p1_p2 = distance_p1_p2 - vehicle_dist
                t: float = vehicle_dist / distance_p1_p2
                self.write_point_to_base(point_1, point_2, t)
                self.timestamp += timedelta(seconds=self.WRITE_TIME_OPTION)
                continue
            else:
                distance_p1_p2 = vehicle_dist - distance_p1_p2
                distance_p1_p2 = None
                i += 1
                continue

        this_ride.end_point = Point(end_point)
        this_ride.end_date = self.timestamp
        this_ride.distance = total_distance
        this_ride.save()

    def get_coordinates_from_address(self, address: str) -> Optional[Point_]:
        endpoint_search = "https://api.openrouteservice.org/geocode/search"
        params: Dict[str, Union[int, str]] = {
            "api_key": settings.OPENROUTESERVISE_API,
            "text": address,
            "size": 1,
            "lang": "ru",
        }
        response = requests.get(endpoint_search, params=params)
        result = response.json()["features"][0]["geometry"]["coordinates"]
        if result:
            return result
        return None

    def get_track(
        self,
        start_point: Point_,
        end_point: Point_,
    ) -> List[Point_]:
        route = self.client.directions(
            coordinates=([start_point] + [end_point]),
            profile="driving-car",
            format="geojson",
        )
        return route["features"][0]["geometry"]["coordinates"]

    @staticmethod
    def distance_between_coordinates(start: Point_, end: Point_):
        R = 6371000
        lon1, lat1 = start
        lon2, lat2 = end
        d_lat = radians(lat2 - lat1)
        d_lon = radians(lon2 - lon1)
        a = (sin(d_lat / 2) ** 2) + cos(radians(lat1)) * cos(radians(lat2)) * (sin(d_lon / 2) ** 2)
        c = 2 * atan2(sqrt(a), sqrt(1 - a))
        distance = R * c
        return round(distance, 2)

    def write_point_to_base(self, point_1: Point_, point_2: Point_, t: float) -> None:
        lat1, lon1 = point_1
        lat2, lon2 = point_2

        delta_lat = lat2 - lat1
        delta_lon = lon2 - lon1

        lat = round(lat1 + delta_lat * t, 6)
        lon = round(lon1 + delta_lon * t, 6)
        point = Point(lat, lon)
        GPSData.objects.create(vehicle_id=self.vehicle_id, point=point, timestamp=self.timestamp)
        current_time = self.timestamp.replace(tzinfo=self.tzinfo).strftime("%Y-%m-%d: %H:%M")
        in_road = str(self.timestamp - self.start_time)
        self.stdout.write(
            self.style.SUCCESS(f"INFO: {current_time} записана точка - lat: {lat}, lon: {lon}, в пути {in_road}")
        )


from imageai.Detection import ObjectDetection

import os

exec_path = os.getcwd()

detector = ObjectDetection()
detector.setModelTypeAsRetinaNet()
detector.setModelPath("resnet50_coco_best_v2.1.0.h5")
detector.loadModel()

list = detector.detectObjectsFromImage(input_image="objects.jpg",
                                    output_image_path ="new_objects.jpg",
                                    minimum_percentage_probability=30,
                                    display_percentage_probability=False,
                                    display_object_name=False)

Python_Анализ_изображений/Задание 12. РАСПОЗНАВАНИЕ ОБЪЕКТОВ НА КАРТИНКЕ/z12_Shabakov.py


# Testing viewing the products
# as well as the adding, editing, and deleting that the superuser is able to do
from django.test import TestCase
from models import Product, Category
from forms import ProductForm

# Create your tests here.

def create_test_prod():
    cat = Category(name='sale', friendly_name='sale')
    cat.save()
    product = Product(
        category=cat,
        sku='111111',
        name='test',
        description='Test Description',
        price='10.99',
        image='img.jpg',
        )

    # save product

    product.save()
    return (product, cat)

class ProductsViewsTest(TestCase):

    """
    Test main products view returns properly
    """

    def test_get_products_page(self):
        response = self.client.get('/products/')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'products/products.html')

    def test_get_one_product_page(self):
        (product, cat) = create_test_prod()
        response = self.client.get('/products/' + str(product.id))
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'products/one_product.html')

class TestProductModel(TestCase):

    """
    Test the Product Model is working
    """

    def test_product_model(self):

        # create a product

        (product, cat) = create_test_prod()

        # check to see that the product fields equal the saved products values

        self.assertEqual(product.category, cat)
        self.assertEqual(product.sku, '111111')
        self.assertEqual(product.name, 'test')
        self.assertEqual(product.description, 'Test Description')
        self.assertEqual(product.price, '10.99')
        self.assertEqual(product.image, 'img.jpg')

class ProductFormTest(TestCase):

    """
    Check that validation works when a user doesn't fill in at
    least one field, all fields are required, tests forms.py
    """

    def test_product_form(self):
        form = ProductForm({
            'category': 'sale',
            'sku': '111111',
            'name': 'test',
            'description': 'Test Description',
            'price': '10',
            })
        self.assertFalse(form.is_valid())

    def test_product_name_is_required(self):
        form = ProductForm({'name': ''})
        self.assertFalse(form.is_valid())
        self.assertIn('name', form.errors.keys())
        self.assertEqual(form.errors['name'][0],
                         'This field is required.')

    def test_product_description_is_required(self):
        form = ProductForm({'description': ''})
        self.assertFalse(form.is_valid())
        self.assertIn('description', form.errors.keys())
        self.assertEqual(form.errors['description'][0],
                         'This field is required.')

    def test_product_price_is_required(self):
        form = ProductForm({'price': ''})
        self.assertFalse(form.is_valid())
        self.assertIn('price', form.errors.keys())
        self.assertEqual(form.errors['price'][0],
                         'This field is required.')


def solve():
    a, b = map(int, input().split())
    s = (a + b)//4
    n = min(a,b)
    if s <= n:
        print(s)
    else:
        print(n)

if __name__ == "__main__":
    for i in range(int(input())):
        solve()


import os
from rest_framework import serializers
from rest_framework.exceptions import AuthenticationFailed
from . import facebook, google
from .register import register_social_user
from ..users.serializers import UserSerializer

class FacebookSocialAuthSerializer(serializers.Serializer):
    """Handles serialization of facebook related data"""
    auth_token = serializers.CharField()

    def validate_auth_token(self, auth_token):
        user_data = facebook.Facebook.validate(auth_token)
        try:
            if not user_data.get('email'):
                raise serializers.ValidationError('Invalid email address. Please login again.')

            data = {
                'user_id': user_data.get('id'),
                'email': user_data.get('email'),
                'first_name': user_data.get('first_name'),
                'last_name': user_data.get('last_name'),
                'dob': user_data.get('birthday'),
                'provider': 'facebook'
            }
            user_data = register_social_user(data=data)

            return {'user': UserSerializer(instance=user_data.get('user')).data, 'token': user_data.get('token')}

        except Exception as identifier:
            raise serializers.ValidationError(
                'The token is invalid or you have already registered. Please login again.')

class GoogleSocialAuthSerializer(serializers.Serializer):
    """Handles serialization of google related data"""
    auth_token = serializers.CharField()

    def validate_auth_token(self, auth_token):
        user_data = google.Google.validate(auth_token)
        try:
            if user_data['aud'] != os.environ.get('GOOGLE_CLIENT_ID'):
                serializers.ValidationError('The token is invalid or expired. Please login again.')
            if not user_data.get('email'):
                raise serializers.ValidationError('Invalid email address. Please login again.')

            data = {
                'user_id': user_data.get('sub'),
                'email': user_data.get('email'),
                'first_name': user_data.get('given_name'),
                'last_name': user_data.get('family_name'),
                'dob': user_data.get('birthday'),
                'provider': 'google'
            }
            user_data = register_social_user(data=data)

            return {'user': UserSerializer(instance=user_data.get('user')).data, 'token': user_data.get('token')}

        except Exception as identifier:
            raise serializers.ValidationError('The token is invalid or expired. Please login again.')