import os
import shutil
from typing import Dict, Any, Optional

import statey as st
from statey import (
    Machine,
    transition,
    TaskSession,
    task,
    StateSnapshot,
    StateConfig,
)
from statey.syms import types, utils, Object, impl

FileConfigType = st.Struct["location":str, "data":str]

StatType = st.Struct[
    "mode":int,
    "ino":int,
    "dev":int,
    "nlink":int,
    "uid":int,
    "gid":int,
    "size":int,
    "atime":float,
    "mtime":float,
    "ctime":float,
]

FileType = st.Struct["location":str, "data":str, "stat":StatType]

@st.function
def realpath(path: str) -> str:
    """
    Wrapper for os.path.realpath
    """
    return os.path.realpath(path)

class FileMachine(Machine):
    """
    Simple file state machine
    """

    UP = st.State("UP", FileConfigType, FileType)
    DOWN = st.NullState("DOWN")

    async def refresh(self, current: StateSnapshot) -> StateSnapshot:
        state = current.state.state
        if state == self.null_state.state:
            return current
        if not os.path.isfile(current.data["location"]):
            return StateSnapshot({}, self.null_state)
        data = self.get_file_info(current.data["location"])
        return StateSnapshot(data, current.state)

    async def finalize(self, current: StateSnapshot) -> StateSnapshot:
        return StateSnapshot(dict(current.data, data=""), current.state)

    @staticmethod
    def get_file_info(path: str) -> FileType:
        location = os.path.realpath(path)
        with open(location) as f:
            data = f.read()

        stat_info = os.stat(path)
        return {
            "location": location,
            "data": data,
            "stat": {
                "mode": stat_info.st_mode,
                "ino": stat_info.st_ino,
                "dev": stat_info.st_dev,
                "nlink": stat_info.st_nlink,
                "uid": stat_info.st_uid,
                "gid": stat_info.st_gid,
                "size": stat_info.st_size,
                "atime": stat_info.st_atime,
                "mtime": stat_info.st_mtime,
                "ctime": stat_info.st_ctime,
            },
        }

    @staticmethod
    def get_file_expected(config: st.StateConfig) -> Dict[str, Any]:
        with_realpath = st.struct_replace(
            config.obj, location=realpath(config.obj.location)
        )
        return st.fill_unknowns(with_realpath, FileType)

    @task.new
    async def remove_file(self, path: str) -> types.EmptyType:
        """
        Delete the file
        """
        os.remove(path)
        return {}

    @task.new
    async def set_file(self, data: FileConfigType) -> FileType:
        """
        Set the file's contents
        """
        path = os.path.realpath(data["location"])
        with open(path, "w+") as f:
            f.write(data["data"])
        return self.get_file_info(path)

    @task.new
    async def rename_file(self, from_path: str, to_path: str) -> FileType:
        from_path = os.path.realpath(from_path)
        to_path = os.path.realpath(to_path)
        os.rename(from_path, to_path)
        return self.get_file_info(to_path)

    @transition("UP", "UP")
    async def modify(
        self, current: StateSnapshot, config: StateConfig, session: TaskSession
    ) -> Object:

        differ = session.ns.registry.get_differ(current.state.input_type)
        diffconfig = differ.config()
        expected = self.get_file_expected(config)

        def compare_realpaths(x, y):
            return os.path.realpath(x) == os.path.realpath(y)

        diffconfig.set_comparison("location", compare_realpaths)

        current_as_config = st.filter_struct(current.obj, config.type)
        diff = differ.diff(current_as_config, config.obj, session, diffconfig)

        if not diff:
            return current.obj

        loc_changed = "location" in diff
        data_changed = "data" in diff

        # If location changes only we can just rename the file
        if loc_changed and not data_changed:
            return session["rename_file"] << (
                self.rename_file(current.obj.location, config.obj.location) >> expected
            )

        if loc_changed:
            raise st.exc.NullRequired

        return session["update_file"] << (self.set_file(config.obj) >> expected)

    @transition("DOWN", "UP")
    async def create(
        self, current: StateSnapshot, config: StateConfig, session: TaskSession
    ) -> Object:

        expected = self.get_file_expected(config)
        return session["create_file"] << (self.set_file(config.obj) >> expected)

    @transition("UP", "DOWN")
    async def delete(
        self, current: StateSnapshot, config: StateConfig, session: TaskSession
    ) -> Object:

        session["delete_file"] << self.remove_file(current.obj.location)
        return st.Object({})

# Declaring global resources

File = FileMachine("file")

RESOURCES = [File]

def register(registry: Optional["Registry"] = None) -> None:
    """
    Register default resources in this module
    """
    if registry is None:
        registry = st.registry

    for resource in RESOURCES:
        registry.register(resource)


import socket
import json
import time
import math
import tflearn
from tflearn.layers.core import input_data, fully_connected
from tflearn.layers.estimator import regression
import numpy as np
from random import randint
'''
Skynet Bot NN System
Supervised Learning

We send lists to the GAME/SERVER

ACTION CODES WE SEND:
0 - connecting | our indication to start the game. No other data is sent. // send this again AFTER you receive a 0 code from the Server to restart multiple games for training.
1 - action | this indicates the client is sending us an action for us to execute.
2 - quitting | this indicates the client is quitting. We should end the game gracefully.

ACTIONS:
A list of required instructions, output by the neural network. Can have any # of list elements.

TYPE: JSON
CONTENT: [ACTION CODE, [action instructions1,2,3,4,amt_of_observations.....]]
EXAMPLE: ["action", [1,amt_of_observations,-2]]
USAGE: This will essentially instruct the game that the data being sent is in fact an action we wish it to perform.
The data can represent anything, and it's not our job to necessarily care what it means -  it can vary.

RESPONSES WE RECEIVE:
2 - game is complete, will restart
1 - game in process | send a list of observations with this code.
0 - game is complete, no restart | pair with an extra value that indiciates how well the AI did.
-1 - not available | no extra data to send. Default state.
The server will send us lists of observations regularly. We will then process those observations,
make a decision, and proceed this cycle until we receive an "end of game" code from the game.

RESPONSE EXAMPLE:
[1, [observations]] ... e.g. [1, [1,a5,-2,3....]]
or
[0, 4141]
[0, 0.5242]
We can use the data immediately after the response code to figure out things such as, "How well
did our AI do in reaching its goal?". 0 response codes will take all data retrieved in the testing process
and use it to re-evaluate weights it uses to make decisions. The goal the AI is trying to reach can be
specified to our NN before the process begins, and then we can use that data to help the AI make better
decisions later.

 FUTURE PLANS: To make this system more robust, and able to handle more complex instructions, it may make sense to
               nest multiple neural networks together to make more complex decisions independent of one another.
               So, for a real-time strategy game [say, starcraft] we could attempt a framework that does the following:

                    Main Strategy NN [Delegates Tasks]
                    | Micro NN             | Macro NN
                    + Makes Decisions      + Makes decisions based on "build orders"
                    Focused solely on unit   More broad decisionmaking
                    control

'''
CLIENT_IP = "127.0.0.1" # That's Me!
SERVER_IP = "127.0.0.1"

IN_PORT = 50066 # The port we receive data from the game/server with. - IN
OUT_PORT = 50055 # The port we send data to the game/server with. - OUT
MSG_LIST = [0, 'Connecting...'] # connecting
active = True
lr=0.001
filename = "snake_nn_2.tflearn"
test_gamaes = 1000
initial_games = 10000
goal = 2000
amt_of_observations = 5 # including the action: so, 4 observations, 1 action paired with them.

# kinda irrelevant - just for use in the snake game.
vectors_and_keys = [
                [[-1, 0], 0],
                [[0, 1], 1],
                [[1, 0], 2],
                [[0, -1], 3]
                ]

training_data = [] # this is where we will return training data to be used.
PREV_GAME_OBS = []
CURRENT_GAME_OBS = [] # list of all observation/action pairs for a game. When game completes, they will be paired with a goal value.
MODE = 1 # MODES: 0 = Inactive, 1 = Data Population + Training (Supervised Learning), 2 = Model Testing

def model():
    network = input_data(shape=[None, amt_of_observations, 1], name='input') # shape of data [left, forward, right, angle,

    # Activation and Regularization inside a layer:
    network = fully_connected(network, 25, activation='relu') # hidden layer neurons
    # Equivalent to:
    network = fully_connected(network, 1, activation='linear') # hidden layer neurons

    # Optimizer, Objective and Metric:
    network = regression(network, optimizer='adam', learning_rate=lr, loss='mean_square', name='target')
    model = tflearn.DNN(network, tensorboard_dir='log')
    return model

def train_model(training_data, model):
    X = np.array([i[0] for i in training_data]).reshape(-1, amt_of_observations, 1) # observations array
    y = np.array([i[1] for i in training_data]).reshape(-1, 1) # fitness value
    model.fit(X,y, n_epoch = 3, shuffle = True, run_id = filename)
    model.save(filename)
    return model

def generate_random_action():
    action = randint(0,2) - 1
    return action
    #return action, get_game_action(snake, action)

def generate_observation(snake, food, obstacles):
    snake_direction = get_snake_direction_vector(snake)
    food_direction = get_food_direction_vector(snake, food)
    barrier_left = is_direction_blocked(snake, turn_vector_to_the_left(snake_direction), obstacles)
    barrier_front = is_direction_blocked(snake, snake_direction, obstacles)
    barrier_right = is_direction_blocked(snake, turn_vector_to_the_right(snake_direction), obstacles)
    angle = get_angle(snake_direction, food_direction)
    return np.array([int(barrier_left), int(barrier_front), int(barrier_right), angle])

def add_action_to_observation(observation, action):
    return np.append([action], observation)

def get_snake_direction_vector(snake):
    return np.array(snake[0]) - np.array(snake[1])

def get_food_direction_vector(snake, food):
    return np.array(food) - np.array(snake[0])

def normalize_vector(vector):
    return vector / np.linalg.norm(vector)

def get_food_distance(snake, food):
    return np.linalg.norm(get_food_direction_vector(snake, food))

def is_direction_blocked(snake, direction, obstacles):
    point = np.array(snake[0]) + np.array(direction)
    return(point.tolist() in snake[:-1] or point[0] == 0 or point[1] == 0 or point[0] == 21 or point[1] == 21 or (point.tolist() in obstacles))

def turn_vector_to_the_left(vector):
    return np.array([-vector[1], vector[0]])

def turn_vector_to_the_right(vector):
    return np.array([vector[1], -vector[0]])

def get_angle(a, b):
    a = normalize_vector(a)
    b = normalize_vector(b)
    return math.atan2(a[0] * b[1] - a[1] * b[0], a[0] * b[0] + a[1] * b[1]) / math.pi

def get_game_action(snake, action):
    print("snake: " + str(snake))
    print("random action: " + str(action))
    snake_direction = get_snake_direction_vector(snake)
    new_direction = snake_direction
    if action == -1:
        new_direction = turn_vector_to_the_left(snake_direction)
    elif action == 1:
        new_direction = turn_vector_to_the_right(snake_direction)
    for pair in vectors_and_keys:
        if pair[0] == new_direction.tolist():
            game_action = pair[1]
    return game_action

def generate_action(snake):
    action = make_prediction(0,2) - 1
    return get_game_action(snake, action)

def make_prediction(observations, model, prev_observations):
    new_observations = generate_observation(observations[2],observations[3],observations[4])
    print(str(new_observations))
    predictions = []
    for action in range(-1,2):
        predictions.append(model.predict(add_action_to_observation(new_observations, action).reshape(-1, amt_of_observations, 1))) # amt_of_observations is the number of observations we pass.
    return int(np.argmax(np.array(predictions)))

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((CLIENT_IP, IN_PORT)) # bind the incoming data port.

print("loading nn")
nn_model = model()
nn_model.load(filename)

# initial connection
print("Connecting to Game Server at: " + SERVER_IP + ":" + str(OUT_PORT) + "...")
sock.sendto((json.dumps(MSG_LIST)).encode(), (SERVER_IP, OUT_PORT)) # inform the server we have connected.
# game step loop
while active: # while we're playing
    try:
        data, addr = sock.recvfrom(1024) # we wait for server's response.
        received_json = json.loads(data)
        print("data received:" + str(received_json))

        # If game is in progress, process data according to the mode we have selected.
        if(received_json[0] == 1): # if game is in progress, process observations.
            if(MODE == 1): # data population AND training mode [random actions, supervised results]
                CURRENT_GAME_OBS = received_json[1] # take in the list of observations
                #MSG_LIST[1] = generate_action(CURRENT_GAME_OBS[2]) # this is the snake.
                MSG_LIST[1] = get_game_action(CURRENT_GAME_OBS[2], make_prediction(CURRENT_GAME_OBS, nn_model, PREV_GAME_OBS) - 1) # see snake.py and snake_nn2.py from iteration 2 for reasoning
                print (MSG_LIST[1])
                # acquire the action to take from our NN, format as a json list.
                MSG_LIST[0] = 1 # code to indicate we are sending an action [ see above ]
                print (MSG_LIST[0])
                sock.sendto((json.dumps(MSG_LIST)).encode(), (SERVER_IP, OUT_PORT)) # send our action to the server.
                print("sending data: " + str(MSG_LIST))
            elif(MODE == 2): # Model Testing
                CURRENT_GAME_OBS = received_json[1] # take in the list of observations
                print(CURRENT_GAME_OBS)
                # acquire the action to take from our NN, format as a json list.
                MSG_LIST[0] = 1 # code to indicate we are sending an action [ see above ]
                print(MSG_LIST[0])
                sock.sendto((json.dumps(MSG_LIST)).encode(), (SERVER_IP, OUT_PORT)) # send our action to the server.
                print("sending data: " + str(MSG_LIST))
                # TESTING MODE - USES THE NN TO GENERATE ACTIONS
        elif(received_json[0] == 0): # if the game is over and is not restarting.
            print("The game server has disconnected: Game Complete, no restart.")
            active = 0
            break
        elif(received_json[0] == 2): # if game is complete, and will restart.
            print("Game complete! Negotiating restart...")
        else:
            print("The game server is not ready yet. Exiting...")
            break

    except Exception as e:
        print("An Error has Occurred: " + str(e))
        #exit()


# Copyright 2019-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
#     http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.

import pytest

from braket.aws import AwsDevice

DWAVE_ARN = "arn:aws:braket:::device/qpu/d-wave/DW_2000Q_6"
RIGETTI_ARN = "arn:aws:braket:::device/qpu/rigetti/Aspen-8"
IONQ_ARN = "arn:aws:braket:::device/qpu/ionq/ionQdevice"
SIMULATOR_ARN = "arn:aws:braket:::device/quantum-simulator/amazon/sv1"

@pytest.mark.parametrize("arn", [(RIGETTI_ARN), (IONQ_ARN), (DWAVE_ARN), (SIMULATOR_ARN)])
def test_device_creation(arn, aws_session):
    device = AwsDevice(arn, aws_session=aws_session)
    assert device.arn == arn
    assert device.name
    assert device.status
    assert device.type
    assert device.provider_name
    assert device.properties

def test_device_across_regions(aws_session):
    # assert QPUs across different regions can be created using the same aws_session
    AwsDevice(RIGETTI_ARN, aws_session)
    AwsDevice(IONQ_ARN, aws_session)

@pytest.mark.parametrize("arn", [(RIGETTI_ARN), (IONQ_ARN), (DWAVE_ARN), (SIMULATOR_ARN)])
def test_get_devices_arn(arn):
    results = AwsDevice.get_devices(arns=[arn])
    assert results[0].arn == arn

def test_get_devices_others():
    provider_names = ["Amazon Braket"]
    types = ["SIMULATOR"]
    statuses = ["ONLINE"]
    results = AwsDevice.get_devices(provider_names=provider_names, types=types, statuses=statuses)
    assert results
    for result in results:
        assert result.provider_name in provider_names
        assert result.type in types
        assert result.status in statuses

def test_get_devices_all():
    result_arns = [result.arn for result in AwsDevice.get_devices()]
    for arn in [DWAVE_ARN, RIGETTI_ARN, IONQ_ARN, SIMULATOR_ARN]:
        assert arn in result_arns


import connection
import pandas as pd
import cx_Oracle

file_open = pd.read_csv(r"D:\DB_PROJECT\dbapp\dbproject\datasets\bj\products.csv")

df = file_open[['name','subhead']]
arr = df.values.tolist()
for i in range(len(arr)):
    image_path = "/assets/images/"+"{}"+"_bj.png".format(i+1)
    try:
        connection.c.execute("insert into products (int({}),{},{},{},5,'ice cream');".format(i+1,arr[i][0],arr[i][1],image_path))

        print("Product {} is added.".format(i+1))
    except cx_Oracle.Error as e:
        print("Error message:",e)
#connection.c.execute("commit;")
connection.c.close();


import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BOARD)

GPIO_TRIGGER = 38
GPIO_ECHO = 40

GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)

def distance():
    #set TRIGGER to HIGH
    GPIO.output(GPIO_TRIGGER, True)
    time.sleep(0.00001)
    GPIO.output(GPIO_TRIGGER, False)

    StartTime = time.time()
    StopTime = time.time()

    while GPIO.input(GPIO_ECHO) == 0:
        StartTime = time.time()

    while GPIO.input(GPIO_ECHO) == 1:
        StopTime = time.time()

    TimeElapsed = StopTime - StartTime

    distance = (TimeElapsed * 34300) /2

    return distance

def main():
    dist = distance()
    print("{\"front-distance\": %.1f}" % dist)
    # try:
    #     while True:
    #         dist = distance()
    #         print("front-distance: %.1f" % dist)
    #         time.sleep(0.5)
    # except KeyboardInterrupt:
    #     print("Measurement stopped by user")
    #     GPIO.cleanup()
main()


# hm_tester.py
#
# Try to find a way to hide the mouse pointer; The obvious way, to set window.mouseVisible = False, only works after
# clicking once inside the fullscreen window when two monitors are connected.
#
# REFERENCES:
#
# Custom Mouse:
# https://groups.google.com/forum/#!topic/psychopy-users/ZZkM82GzUic
# http://www.psychopy.org/api/visual/custommouse.html
#
#

# Things to try:
# - Simulate a mouse click
# - Hide the mouse using CustomMouse.
# - Use CustomMouse to create and invisible mouse.
# - Bound the mouse off the lower-right corner of the screen
# - Bound the mouse onto the other screen
# - Use another API (Pyglet)

from psychopy import visual, core, event, iohub
import pyglet

# works until the operator clicks outside of the fullscreen window
def t1():
    w = visual.Window(screen=1, fullscr=True, units='pix')
    m = visual.CustomMouse(w, visible=False)
    t_end = core.getTime() + 20
    while core.getTime() < t_end:
        m.draw()
        core.wait(0.010)
    w.close()

def t2():
    w = visual.Window(screen=1, fullscr=True, units='pix')
    m = visual.CustomMouse(w, visible=False, leftLimit = 1900, topLimit = 20)
    t_end = core.getTime() + 20
    while core.getTime() < t_end:
        m.draw()
        core.wait(0.010)
    w.close()

def t3():
    platform = pyglet.window.get_platform()
    display = platform.get_default_display()
    screens = display.get_screens()
    w = pyglet.window.Window(fullscreen=True, screen=screens[1])
    w.set_exclusive_mouse(True)
    pyglet.app.run()

# This one works.
def t4():
    w = visual.Window(screen=1, fullscr=True, units='pix')
    m = event.Mouse(visible=False, win=w)
    m.setExclusive(True)
    t_end = core.getTime() + 10
    while core.getTime() < t_end:
        core.wait(0.010)
    m.setExclusive(False)
    w.close()

def t5():
    # Open the window and hide the cursor
    w = visual.Window(screen=1, fullscr=True, units='pix')
    m = event.Mouse(visible=False, win=w)
    m.setExclusive(True)

    # Turn on IOHub
    io = iohub.launchHubServer()
    kb = io.devices.keyboard

    # Delay a while
    t_end = core.getTime() + 10
    while core.getTime() < t_end:
        core.wait(0.010)

    # Turn off iohub, release the cursor and close the window
    io.quit()
    m.setExclusive(False)
    w.close()


from django.conf.urls import patterns, include, url
from django.contrib import admin

admin.autodiscover()

urlpatterns = patterns('',
    (r'^api2/', include('kitchn.api.urls')),
    (r'^api/inventory/', include('kitchn.inventory.urls')),
    (r'^api/recipe/', include('kitchn.recipe.urls')),

    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    url(r'^admin/', include(admin.site.urls)),
    url(r'.*', 'kitchn.views.home', name='home'),
)


import chainer.links as L
import chainer.functions as F
import glob
import chainer
from chainer import serializers
from model import VGGFine
from dataset import DataSet

def predict_loop(dataset: chainer.Chain, label: int=0):
    """
    @param dataset <chainer.Chain> : chaienrのデータセットクラス
    @param label <int>             : 正解ラベル
    学習器で予測した結果と正解ラベルを出力する
    """

    for i in range(len(dataset)):
        x = dataset.get_example(i)
        y = model.predictor(x[None, ...])
        y = y.data
        print("pred: " + str(y.argmax(axis=1)[0]) + "\t" + "ans: " + str(label))

def predict():
    """
    学習した結果を使ってラベルの予測をする
    """

    global model
    model = L.Classifier(VGGFine())
    serializers.load_npz("../result/serializers.save_npz", model)
    # anim_face_dataのラベル予測
    datadir = glob.glob("../../data/anim_face_data/*")
    data = DataSet(datadir)
    predict_loop(data, 0)
    # imagenet_dataのラベル予測
    datadir = glob.glob("../../data/imagenet_data/*")
    data = DataSet(datadir)
    predict_loop(data, 1)

if __name__ == "__main__":
    predict()


from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import json
from selenium.webdriver.common.by import By
driver = webdriver.Chrome('./chromedriver')
stations = []
driver.maximize_window()

url = "https://www.circlek.se/station-search"
driver.get(url)

cookie_button = WebDriverWait(driver, 10).until(EC.visibility_of_element_located(
    (By.ID, "CybotCookiebotDialogBodyLevelButtonLevelOptinAllowAll")))
cookie_button.click()

driver.find_element_by_class_name("filtering-icon ").click()
driver.find_element_by_id("edit-eu-miles-98").click()
driver.find_element_by_id("edit-eu-milesplus-98").click()
driver.find_element_by_id("new-search").click()

def load_stations(results):
    print("loadstations")
    for res in results:
        WebDriverWait(driver, 20).until(EC.visibility_of_element_located(
        (By.CLASS_NAME, "container-station-address")))
        address = res.find_element_by_class_name(
            "container-station-address").text

        address_rows = address.split(",")

        source = url
        station = {'Station': "Cirkle K", 'City': address_rows[1].strip(),
                   'Adress': address_rows[0].strip(), "Oktan": "Ja", "Source": source}

        stations.append(station)
    print("done loading stations")
count = 0
while True:

    try:
        WebDriverWait(driver, 10).until(EC.visibility_of_element_located(
            (By.CLASS_NAME, "search-result")))

        load_stations(driver.find_elements_by_class_name("search-result"))
        count = count + 1
        print(count)
        try:
            driver.find_element_by_id("next-page").click()
            WebDriverWait(driver, 20).until(EC.visibility_of_element_located(
            (By.CLASS_NAME, "search-result")))
            results = driver.find_elements_by_class_name("search-result")
        except:
            break

    except Exception as e:
        print(e)

f = open("circle_k.json", "w", encoding="utf-8")
f.write(json.dumps(stations))
f.close()
driver.close()


import random
from collections import deque
import gym
import numpy as np
import tensorflow as tf
from gym import wrappers
import ppaquette_gym_doom
from ppaquette_gym_doom.wrappers import SetResolution, ToDiscrete
from gym.wrappers import SkipWrapper

def create_env(seed=None):
    # env_spec = gym.spec('ppaquette/DoomBasic-v0')
    env_spec = gym.spec('ppaquette/DoomCorridor-v0')
    env_spec.id = 'DoomCorridor-v0'
    env = env_spec.make()

    # if seed is not None:
    #     env.seed(seed)

    return SetResolution('160x120')(SkipWrapper(repeat_count=4)(ToDiscrete('minimal')(env)))

def ddqn_replay_train(mainDQN, targetDQN, train_batch, dis = 0.9):
    '''
    Double DQN implementation
    :param mainDQN: main DQN
    :param targetDQN: target DQN
    :param train_batch: minibatch for train
    :return: loss
    '''
    x_stack = np.empty(0).reshape(0, mainDQN.input_size)
    y_stack = np.empty(0).reshape(0, mainDQN.output_size)

    # Get stored information from the buffer
    for state, action, reward, next_state, done in train_batch:
        Q = mainDQN.predict(state)

        # terminal?
        if done:
            Q[0, action] = reward
        else:
            # Double DQN: y = r + gamma * targetDQN(s')[a] where
            # a = argmax(mainDQN(s'))
            Q[0, action] = reward + dis * targetDQN.predict(next_state)[0, np.argmax(mainDQN.predict(next_state))]

        # print(Q)
        # print(state)
        state = np.reshape(state, [-1, 160 * 120 * 3])

        y_stack = np.vstack([y_stack, Q])
        x_stack = np.vstack([x_stack, state])

    # Train our network using target and predicted Q values on each episode
    return mainDQN.update(x_stack, y_stack)

def get_copy_var_ops(dest_scope_name="target", src_scope_name="main"):

    # Copy variables src_scope to dest_scope
    op_holder = []

    src_vars = tf.get_collection(
        tf.GraphKeys.TRAINABLE_VARIABLES, scope=src_scope_name)
    dest_vars = tf.get_collection(
        tf.GraphKeys.TRAINABLE_VARIABLES, scope=dest_scope_name)

    for src_var, dest_var in zip(src_vars, dest_vars):
        op_holder.append(dest_var.assign(src_var.value()))

    return op_holder


#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Copyright: Deutsches Zentrum fuer Luft- und Raumfahrt e.V., 2015 (c)
Contact: daniel.boehnke@dlr.de and jonas.jepsen@dlr.de
'''
from cmath import pi

from VAMPzero.Handler.Parameter import parameter

rad = pi / 180.

class cRoot(parameter):
    '''
    Calculates the root chord of the elevator (note: only one elevator is considered).

    :Unit: [m]

    :Source:

    :Author: Lisanne van Veen
    '''

    def __init__(self, value=0., unit='m', parent='', cpacsPath=''):
        super(cRoot, self).__init__(value=value, unit=unit, doc=self.__doc__, status='init', parent=parent,
                                    cpacsPath=cpacsPath)

    def calc(self):
        '''
        Assumes that the taper ratio of the elevator is equal to the taper ratio of the htp
        (cTip = taperRatioHtp*cRoot).
        The reference area of the elevator and the span of the elevator could be used to calculate
        the value of the average chord length. Due to the linear taper ratio the average chord
        length is located in the middle. (cTip + cRoot)/2 = cAVG
        The abovementioned equations are then used to calculate cRoot en cTip.

        :Source:
        '''

        refAreaElevator = self.parent.refArea.getValue()
        spanElevator = self.parent.span.getValue()
        taperRatioHtp = self.parent.htp.taperRatio.getValue()

        cAVGElevator = refAreaElevator / spanElevator
        cRootElevator = 2. * cAVGElevator / (1. + taperRatioHtp)

        return self.setValueCalc(cRootElevator)

        ###################################################################################################
        #EOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFE#
        ###################################################################################################


import numpy as np
import torch
import pickle
from HEnet import HENet
from sampler import Sampler
from torch import nn, optim
from torch.autograd import Variable
from sampler import Sampler
from pathlib import Path
from dataset import FallData, Flip, Scale, Translate
from dataset import Normalize, OutsideIamge, RemoveJoints
from torch.utils.data import DataLoader
from torchvision.transforms import transforms
import warnings
warnings.filterwarnings("ignore")
def main():
  Path("saved_model").mkdir(exist_ok=True)
  device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
  batch_size = 64
  num_epochs = 100
  test_step = 50
  with open('TrainAndTestData/inputs.pkl','rb') as source: inputs = pickle.load(source)
  with open('TrainAndTestData/label.pkl','rb') as source: labels = pickle.load(source)
  with open('TrainAndTestData/inputs_test.pkl','rb') as source: test_inputs = pickle.load(source)
  with open('TrainAndTestData/label_test.pkl','rb') as source: test_labels = pickle.load(source)
  inputs = np.reshape(inputs, (inputs.shape[0], 32, 15, 3))
  inputs = np.transpose(inputs, (0, 3, 1, 2))
  inputs[:, 2, :, :] = 0
  labels = np.asarray(labels,dtype=np.int32)
  test_inputs = np.reshape(test_inputs, (test_inputs.shape[0], 32, 15, 3))
  test_inputs = np.transpose(test_inputs, (0, 3, 1, 2))
  test_inputs[:, 2, :, :] = 0
  test_labels = np.asarray(test_labels,dtype=np.int32)
  train_dataset = FallData(inputs,labels,
                     transform=transforms.Compose([
                         OutsideIamge(),
                         RemoveJoints(),
                         Scale(),
                         Translate(),
                         Flip(),
                         Normalize()
                     ]))
  test_dataset = FallData(test_inputs,test_labels,
                       transform=transforms.Compose([
                           RemoveJoints(),
                           Normalize()
                       ]))

  datasampler = Sampler(train_dataset)
  train_loader = DataLoader(train_dataset, batch_size=batch_size,sampler = datasampler)
  test_loader = DataLoader(test_dataset, batch_size=1, shuffle=False)
  Encrypted_model = HENet(10)
  Encrypted_model.to(device)
  CrossEntropyLoss = nn.CrossEntropyLoss()
  optimizer = optim.SGD(Encrypted_model.parameters(), lr = 0.01, momentum = 0.9, weight_decay = 5e-4)
  scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.5)
  best_cost = 100
  for epoch in range(num_epochs):
    costs=0
    Encrypted_model.train()
    scheduler.step()
    for i, data in enumerate(train_loader):
      train_data = Variable(data["x"]).to(device)
      train_label = Variable(torch.tensor(data["y"], dtype=torch.long)).to(device)
      optimizer.zero_grad()
      outputs = Encrypted_model(train_data)
      cost = CrossEntropyLoss(outputs, train_label)
      cost.backward()
      costs += cost.item()
      optimizer.step()
    total_cost = costs / len(train_loader)
    if total_cost<best_cost:
      print ('\033[91m'+"Saving the model"+'\033[0m')
      torch.save(Encrypted_model.state_dict(), "saved_model/Fall_model.torch")
      best_cost=total_cost
    print("Epoch: %s, Loss: %s" %(epoch,total_cost))
    acc = 0
    if ((epoch+1) % test_step == 0):
      Encrypted_model.eval()
      for i, data in enumerate(test_loader):
        test_data = Variable(data["x"]).to(device)
        test_label = data["y"].numpy()[0]
        outputs = Encrypted_model(test_data).data.cpu().numpy()[0]
        predicts = np.argmax(outputs)
        acc += (predicts == test_label).sum()
      accuracy = acc / len(test_loader)
      print('\33[34m'+"Test set accuracy: %.2f" %(accuracy)+'\033[0m')
  print ('\033[91m'+"Saving the final model"+'\033[0m')
  torch.save(Encrypted_model.state_dict(), "saved_model/Fall_model_final.torch")
if __name__ == '__main__':
  main()


from django.urls import path
from . import views

urlpatterns = [
    path('register/', views.registerPage, name='register_page'),
    path('login/', views.loginPage, name='login_page'),
    path('logout/', views.logoutUser, name='logout_page'),
    path('user/', views.userPage, name='user_page'),
    path('', views.home, name='home'),
    path('photo/<str:pk>/', views.viewFood, name='food'),
    path('add/', views.addFood, name='add'),
    path('update/<str:pk>/', views.updateRecipes, name='update_recipes'),
    path('delete/<str:pk>/', views.deleteRecipes, name='delete_recipes'),
]


##############################################################################
#
#    Copyright (C) 2017 - OutTech (<http://www.outtech.com.br>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from odoo import fields, models, _, api
from calendar import monthrange
from datetime import datetime
import base64
import pytz

class ConfirpReport(models.Model):
    _name = 'confirp.report'

    def _get_company(self):
        company_id = self.env.user.company_id
        return company_id

    company_id = fields.Many2one('res.company', 'Company', required=True, default=_get_company, readonly=True)
    journal_id = fields.Many2one('account.journal', 'Journal', required=True)
    period_id = fields.Date(string='Date Start', required=True)
    period_end_id = fields.Date(string='Date End', required=True)

    def cofirp_report(self):
        dict_data = {'header': {}, 'detail': {}, 'footer': {}}
        confirp_file = []
        debit = ''
        credit = ''

        move_date = datetime.strptime(self.period_id, "%Y-%m-%d")
        start_date = datetime.strptime('%s-%s-%s' % (move_date.year, move_date.month, '01'), '%Y-%m-%d')
        month_range = monthrange(move_date.year, move_date.month)
        final_date = datetime.strptime('%s-%s-%s' % (move_date.year, move_date.month, month_range[1]), '%Y-%m-%d')

        account_move_ids = self.env['account.move'].search([('company_id','=',self.env.user.company_id.id),('date','>=',start_date),('date','<=',final_date),('journal_id','=',self.journal_id.id)])
        for account_move in account_move_ids:
            company_name = self.env.user.company_id.name[0:4]
            account_date = datetime.strptime(account_move.date, "%Y-%m-%d")
            account_day = account_date.day
            account_month = account_date.month
            account_year = account_date.year
            journal = account_move.journal_id

            if journal.type == 'bank':
                if journal.bank_id:
                    bank_code = journal.bank_id.bic
            else:
                bank_code = ''

            # move_ids = self.env['account.move.line'].search([('move_id','=',account_move.id)])
            for move in account_move.line_ids:
                if move.credit:
                    credit = move.credit
                if move.debit:
                    debit = move.debit

            report_line = {account_move.name: {
                'CodEmpresa': company_name,
                'DiaLancamento': account_day,
                'MesLancamento': account_month,
                'AnoLancamento': account_year,
                'NumNotaFiscal': '',
                'ContaDebito': 54321,
                'EntradaSaida': 'E',
                'Banco': bank_code,
                'CentroCusto': '',
                'Valor': debit,
                'Historico': account_move.ref,
                'PadraoSistema': '',
                'ContaCredito': 12345,
            }}
            dict_data['detail'].update(report_line)

        confirp_report_txt = self.env['file.export.layout'].create_file('RelatorioConfirp', dict_data)

        obj_ir_attachment = self.env['ir.attachment']
        w_timezone = self.env['res.users'].browse(self._uid).tz
        now = datetime.now(pytz.timezone(w_timezone))

        src_ir_attachment = obj_ir_attachment.search([('res_model', '=', 'confirp.report'), ('res_id', '=', self.id)])

        filename = 'CONFIRP_%04d%02d%02d_%02d%02d%02d.txt' % (now.year,
                                                          now.month,
                                                          now.day,
                                                          now.hour,
                                                          now.minute,
                                                          now.second)

        if src_ir_attachment:
            attach_val = {
                'name': filename,
                'datas_fname': filename,
                'datas': base64.b64encode(confirp_report_txt.encode('ascii', 'replace'))
            }
            obj_ir_attachment.write(src_ir_attachment, attach_val)
        else:
            attach_vals = {'name': filename,
                           'datas_fname': filename,
                           'datas': base64.b64encode(confirp_report_txt.encode('ascii', 'replace')),
                           'file_type': format,
                           'res_model': 'confirp.report',
                           'res_id': self._uid
                           }

            obj_ir_attachment.create(attach_vals)

        confirp_report_download = self.env['confirp.report.download'].create({
            'data': base64.b64encode(confirp_report_txt.encode('ascii', 'replace')), 'filename': filename})

        return {
            'type': 'ir.actions.act_window',
            'res_model': 'confirp.report.download',
            'view_mode': 'form',
            'view_type': 'form',
            'res_id': confirp_report_download.id,
            'views': [(False, 'form')],
            'target': 'new'
        }

class ConfirpReportDownload(models.Model):
    _name = 'confirp.report.download'

    filename = fields.Char('Filename', invisible=True, filename="filename")
    data = fields.Binary('File', readonly=True)


import mxnet as mx
from mxnet import gluon

from openml import OpenMLTask, OpenMLClassificationTask, OpenMLRegressionTask

from typing import Callable

# _default_criterion_gen returns a criterion based on the task type - regressions use
# gluon.loss.L2Loss while classifications use gluon.loss.SoftmaxCrossEntropyLoss
def _default_criterion_gen(task: OpenMLTask) -> gluon.loss.Loss:
    if isinstance(task, OpenMLRegressionTask):
        return gluon.loss.L2Loss()
    elif isinstance(task, OpenMLClassificationTask):
        return gluon.loss.SoftmaxCrossEntropyLoss()
    else:
        raise ValueError(task)

# criterion_gen returns the criterion based on the task type
criterion_gen = _default_criterion_gen  # type: Callable[[OpenMLTask], gluon.loss.Loss]

# optimizer represents the optimizer to be used during training of the model
optimizer = mx.optimizer.Adam()  # type: mx.optimizer.Optimizer

# batch_size represents the processing batch size for training
batch_size = 32  # type: int

# epoch_count represents the number of epochs the model should be trained for
epoch_count = 32  # type: int

# sanitize represents the number that will be used to replace NaNs in train and test data
sanitize_value = 1e-6  # type: float

# context represents the context of the MXNet model - by default it will use the CPU
context = mx.cpu()  # type: mx.context.Context

def _setup():
    global criterion_gen
    global optimizer
    global batch_size
    global epoch_count
    global sanitize_value
    global context

_setup()


#!/bin/python3

import os

def lights(num):
    """ Returns the numbers of ways n light bulbs can
        be lit (i.e. permutations of n) modulo 10 000 """

    return (2 ** num - 1) % 100000

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    t = int(input())

    for t_itr in range(t):
        n = int(input())

        result = lights(n)

        fptr.write(str(result) + '\n')

    fptr.close()


import numpy as np
import csv as csv
import theano, re, cPickle
import theano.tensor as T
import matplotlib.pyplot as plt

# How to run the script using GPU and proper floating point configuration
# THEANO_FLAGS='cuda.root=/usr/local/cuda-5.0/bin,device=gpu,floatX=float32' python [filename].py

theano.config.floatX = 'float32'

# Load the train dataset
f = file('../../data_lab/train_data.dat', 'rb')
train_data = np.array(cPickle.load(f), dtype=np.float32)
f.close()

# Separate the test dataset into train, cross, and test set.
train_set = train_data[0:534, 0::]
cross_set = train_data[534:712, 0::]
ttest_set = train_data[712::, 0::]

# Separate the features and the labels
# ==============================================================================
train_set_x = train_set[0::,1::]
train_set_y = train_set[0::,0]
# ==============================================================================
cross_set_x = cross_set[0::,1::]
cross_set_y = cross_set[0::,0]
# ==============================================================================
ttest_set_x = ttest_set[0::,1::]
ttest_set_y = ttest_set[0::,0]
# ==============================================================================

# Get the dimensions of the training dataset
num_examples = train_set_x.shape[0]
num_features = train_set_x.shape[1]

# Load the test dataset
f = file('../../data_lab/test_data.dat', 'rb')
test_set = np.array(cPickle.load(f), dtype=np.float32)
f.close()

# ==============================================================================
# Logistic Regression
# ==============================================================================

# Declare Theano symbolic variables
x = T.matrix("x")
y = T.vector("y")

x.tag.test_value = train_set_x
y.tag.test_value = train_set_y

# Declare theta = (w,b) = (weight, biasvector) = (weight vector, bias vector)
weight = theano.shared(
    np.zeros(num_features).astype(theano.config.floatX), name="weight")

biasvector = theano.shared(
    np.asarray(0., dtype=theano.config.floatX), name="biasvector")

hypothesis = T.nnet.sigmoid(T.dot(x, weight) + biasvector)

# The prediction threshold
prediction = hypothesis > 0.5

# Cross-entropy loss function
celf = -y * T.log(hypothesis) - (1 - y) * T.log(1 - hypothesis)

# Regularization parameter
var_lambda = 1.0

# The cost to optimize (with regularization)
cost = celf.mean() + (var_lambda / (2.0 * num_examples)) * (weight ** 2).sum()

# The gradient of the cost function wrt weight
grad_of_weight, grad_of_biasvector = T.grad(cost, [weight, biasvector])

# Learning rate
var_alpha = 0.005

# Updates to be performed during optimization
updates={weight: weight - var_alpha * grad_of_weight,
biasvector: biasvector - var_alpha * grad_of_biasvector}

# Compile expressions to function.
train = theano.function(
    inputs=[x, y],
    outputs=[prediction, celf, cost],
    updates=updates,
    name="train",
    allow_input_downcast=False)

predict = theano.function(
    inputs=[x],
    outputs=prediction,
    name="predict",
    allow_input_downcast=False)

# Error functions
error = celf.mean()

err_func = theano.function(
    inputs=[x, y],
    outputs=[error],
    name="err_func",
    allow_input_downcast=False)

# The number of times to run the loop to optimize the cost function
training_steps = 50000

# Start training the algorithm
#for i in range(training_steps):
#    pred, err, costing = train(train_set_x, train_set_y)

train_err = []
cross_err = []

for i in range(1, num_examples):
    Xtemp = train_set_x[0:i,::]
    ytemp = train_set_y[0:i]
    train(Xtemp, ytemp)
    train_err.append(err_func(Xtemp, ytemp)[0].tolist())
    cross_err.append(err_func(cross_set_x, cross_set_y)[0].tolist())

train_err = np.array(train_err, dtype=np.float32)
cross_err = np.array(cross_err, dtype=np.float32)

# Generate the learning curve
plt.figure()
plt.plot(range(1, num_examples), cross_err, 'b')
plt.plot(range(1, num_examples), train_err, 'r')
plt.xlabel('Number of Examples')
plt.ylabel('Error')
plt.show()

# Get all the predicted values
predicted_vector = predict(test_set)

# Generate the submission file
open_file_object = csv.writer(open("logist_theano_submission.csv", "wb"))
test_file_object = csv.reader(open('../../data_lab/test.csv', 'rb'))

test_file_object.next()

i = 0
for row in test_file_object:
    row.insert(0,predicted_vector[i].astype(np.uint8))
    open_file_object.writerow(row)
    i += 1


import pytest
import sympy
import BondGraphTools as bgt
import BondGraphTools.sim_tools as sim

@pytest.mark.use_fixture("rlc")
def test_build(rlc):
    assert len(rlc.state_vars) == 2
    assert len(rlc.ports) == 0

@pytest.mark.use_fixture("rlc")
def test_build_and_drive(rlc):
    se = bgt.new("Se")
    assert len(se.control_vars) == 1
    rlc += se

    for comp in rlc.components.values():
        if comp.type == "0":
            rlc.connect(se, comp)
            break

    assert len(rlc.bonds) == 4
    assert len(rlc.control_vars) == 1

def test_symbolic_params():
    r = bgt.new("R", value=sympy.symbols('r'))
    l = bgt.new("I", value=sympy.symbols('l'))
    c = bgt.new("C", value=sympy.symbols('c'))
    kvl = bgt.new("0", name="kvl")

    rlc = r + l + c + kvl

    rlc.connect(r, kvl)
    rlc.connect(l, kvl)
    rlc.connect(c, kvl)

    assert len(rlc.params) == 3

    assert set(rlc.params.values()) & set(sympy.symbols('r, l, c'))

@pytest.mark.use_fixture("rlc")
def test_rlc_con_rel(rlc):

    rel = rlc.constitutive_relations

    eq1 = sympy.sympify("dx_0 - x_1")
    eq2 = sympy.sympify("dx_1 + x_0 + x_1")

    for r in rel:
        assert r in (eq1, eq2)

    assert "x_0" in rlc.state_vars
    assert "x_1" in rlc.state_vars

@pytest.mark.skip
@pytest.mark.usefixture("rlc")
def test_add_forcing(rlc):
    port = rlc.make_port()

    assert port == 0

    rlc.connect((rlc, port), "0_0")

    assert rlc.ports == {
        0: (rlc, port)
    }

    ts, ps, cv = rlc.basis_vectors

    assert len(ps) == 1

    assert rlc.constitutive_relations == list(
        sympy.sympify("dx_0 - x_1, dx_1 + f_0 + x_0 + x_1, e_0 - x_1")
    )

def test_tf():
    l = bgt.new("I", value=1)
    c = bgt.new("C", value=1)
    tf = bgt.new("TF", value=0.5)

    tflc = tf + l + c
    tflc.connect(l, (tf, 1))
    tflc.connect(c, (tf, 0))

    c,m,lp,nlp,const = tflc.system_model()
    assert nlp.is_zero
    assert const ==[]

def test_se():

    Se = bgt.new('Se', value=1)
    c = bgt.new('C', value=1)
    vc = Se + c

    assert Se.constitutive_relations == [sympy.sympify("e_0 - 1")]
    vc.connect(Se, c)

    assert vc.constitutive_relations == [sympy.sympify("dx_0"),
                                         sympy.sympify("x_0 - 1")]


from PIL import Image

def decode_image(file_location="encoded_image.png"):
    encoded_image = Image.open(file_location)
    # Get red channel data
    red_channel = encoded_image.split()[0]

    x_size = encoded_image.size[0]
    y_size = encoded_image.size[1]

    decoded_image = Image.new("RGB", encoded_image.size)
    pixels = decoded_image.load()

    bits = ""

    class Found(Exception): pass
    try:
        for i in range(x_size):
            for j in range(y_size):
                pixel_value = red_channel.getpixel((j, i))
                # Get each bit from the red channel
                pixel_bit = bin(pixel_value)[-1]
                # print(pixel_bit)
                bits += pixel_bit
                # Stop condition if byte is null
                if pixel_value == 0:
                    raise Found
    except Found:
        i = 0
        decoded_string = ""
        the_bytes = ''
        while i<= len(bits):
            # Combine bits into bytes
            byte = bits[i:i+8]
            # print(byte)
            i += 9
            the_bytes += byte
            # Try decoding byte into ascii string
            string_byte = chr(int(byte, 2))
            decoded_string += string_byte

        # print(the_bytes)
        print(decoded_string)

decode_image()


import networkx as n
import matplotlib.pyplot as p
from matplotlib.patches import *

def d(G,pos,ax,sg=None):

    for n in G:
        c=Circle(pos[n],radius=0.02,alpha=0.5)
        axis.add_patch(c)
        G.node[n]['attr']=c
        x,y=pos[n]

    for (u,v,d) in G.edges(data=True):
        n1=G.node[u]['attr']
        n2=G.node[v]['attr']
        rad=0.1

        alpha=0.5
        color='#009900'

        e = FancyArrowPatch(n1.center,n2.center,patchA=n1,patchB=n2,
                            arrowstyle='wedge',
                            connectionstyle='arc3,rad=%s'%rad,
                            mutation_scale=10.0,
                            lw=2,
                            alpha=alpha,
                            color=color)

        axis.add_patch(e)
    return e

G=n.Graph([(1,2),(1,3),(2,3)])

pos=n.krackhardt_kite_graph(G)
axis=p.gca()
d(G,pos,axis)
axis.autoscale()
p.axis('equal')
p.axis('off')
p.show()


import os
import shutil
import threading
import time
import datetime
import json
import signal
from math import sqrt, log
import random

import numpy as np
import requests
import pandas as pd

import settings2

def keepFileInRange(path, range):
    """
    保留文件夹下多少数据文件
    :return:
    """
    try:
        file_list = os.listdir(path)
        delete_count = len(file_list) - range
        if delete_count <= 0:
            return
        print("需要删除文件个数:%s" % delete_count)
        t1 = time.time()
        for file in file_list[:delete_count]:
            os.remove(os.path.join(path, file))
        print("删除完成耗时:%s" % (time.time() - t1))
    except Exception as e:
        print(e)
        print("路径不存在或者为空")

def machineDataSuperviser(count):
    """
    控制振动数据移动后文件夹下文件数目
    """
    while True:
        for machine in os.listdir(settings2.MACHINE_TOOL_OUTPUT_PATH):
            machine_path = os.path.join(settings2.MACHINE_TOOL_OUTPUT_PATH, machine)
            for tool in os.listdir(machine_path):
                tool_path = os.path.join(machine_path, tool)
                keepFileInRange(tool_path, count)
        time.sleep(count / 10)

def keepRMSData(rms_path, count):
    """
    每个刀号保留count个数目文件
    :param rms_path:
    :param count:
    :return:
    """
    try:
        while True:
            maps = {}
            counts = 0
            for filename in os.listdir(rms_path)[::-1]:
                tool_name = filename.split("-")[0]
                now_count = maps.get(tool_name, 0)
                now_count += 1
                if tool_name in maps.keys():
                    if maps[tool_name] >= count:
                        delete_file = os.path.join(rms_path, filename)
                        os.remove(delete_file)
                        counts += 1
                    else:
                        maps[tool_name] += 1
                else:
                    maps[tool_name] = 1
            print("移除%s个文件" % counts)
            time.sleep(count / 10)
    except Exception as e:
        print(e)

def resultDataSuperviser(count):
    while True:
        for machine in os.listdir(settings2.OUTPUT_BASE_PATH):
            machine_path = os.path.join(settings2.OUTPUT_BASE_PATH, machine)
            for dir_name in os.listdir(machine_path):
                target_path = os.path.join(machine_path, dir_name)
                # print("检查路径->%s"%target_path)
                if dir_name == settings2.VIRBATION_RMS_OUTPUT_PATH_NAME:
                    continue
                keepFileInRange(target_path, count)
        time.sleep(count / 4)

def machineDataSrcSuperviser(count, path):
    while True:
        keepFileInRange(path, count)
        time.sleep(count / 2)

class ProcessFile(threading.Thread):
    def __init__(self, machine_name, machineInfo_input_path, vibrationData_input_path, using_tool_input_path,
                 vibrationData_move_path, result_output_path):
        super().__init__()
        self.machine_name = machine_name

        self.machineInfo_input_path = machineInfo_input_path
        self.vibrationData_input_path = vibrationData_input_path
        self.using_tool_input_path = using_tool_input_path
        self.vibrationData_move_path = vibrationData_move_path
        self.virbation_raw_output_path = os.path.join(result_output_path, settings2.VIRBATION_OUTPUT_PATH_NAME)
        self.load_data_output_path = os.path.join(result_output_path, settings2.LOAD_DATA_OUTPUT_PATH_NAME)
        self.vibration_rms_output_path = os.path.join(result_output_path, settings2.VIRBATION_RMS_OUTPUT_PATH_NAME)
        self.old_tool = 0
        self.usingTool = 0
        self.last_trans_time = self.now
        self.checkPathOrCreate(self.vibrationData_move_path)
        self.checkPathOrCreate(self.virbation_raw_output_path)
        self.checkPathOrCreate(self.load_data_output_path)
        self.checkPathOrCreate(self.vibration_rms_output_path)

        self.hasChangeTool = False
        self.old_vib_data = ""
        self.old_vib_data_count = 0

    def setToolInfo(self):
        """
        获取当前机台加工刀具信息
        :param path:
        :return:
        """

        if not os.path.exists(self.using_tool_input_path):
            print("当前机台加工刀具信息无法确认")
            return False
        path = self.using_tool_input_path

        file_list = os.listdir(path)
        try:
            if file_list:
                tool_info_file = file_list[0]
                temp = tool_info_file.rsplit("-", 1)
                str_time = temp[0]
                tool_name = temp[1].rsplit(".")[0]

                if tool_name == "0" or tool_name == "None":
                    # 说明当前机台正在换刀或者待机中
                    self.usingTool = 0
                    return False
                if not self.usingTool:
                    self.usingTool = tool_name
                elif tool_name != self.usingTool:
                    print("刀具更换:%s->>%s" % (self.usingTool, tool_name))
                    self.old_tool = self.usingTool
                    self.usingTool = tool_name
                    self.hasChangeTool = True

                else:
                    self.hasChangeTool = False
                return True
            else:
                print("路径%s没有文件" % path)
                return False
        except Exception:
            print("机台信息获取失败")

    @staticmethod
    def findLastBeforTime(str_time, files_path=None, p1='%Y-%m-%d-%H-%M-%S-%f', p2='%Y-%m-%d-%H-%M-%S-%f'):
        """
        在files_path中寻找一个文件，这个文件名表示的时间需要比str_time小并且最接近str_time
        算法思路:
            1. 获取路径下所有文件列表 并排序
            2. 把str_time转换为可以比较的形式compile_time
            3. 遍历排序后的列表，其每个元素与compile_time进行一一对比
                1. 如果元素比str_time小继续循环
                2. 如果元素比str_time大：
                    1. 如果元素是第一个元素 则返回-1
                    2. 否则返回上一个元素
            4. 如果遍历完成后还没有返回 则说明所有元素都比compile_time小 即返回列表下最后一个文件
        :param str_time: 要进行比较的时间 2020-12-12-10-07-26-935
        :param files_path: 要寻找的文件夹 2020-12-12-10-07-26-935
        :param p: 时间解析格式如
        :return:  返回最接近并且比时间str_time小的时间为文件名的文件
        """
        # 把str_time转化为可以比较的形式
        try:
            compile_t = datetime.datetime.strptime(str_time, p1)
        except Exception:
            print("需要对比的时间：%s不能被格式：%s所解析，请检查解析格式是否正确" % (str_time, p1))
            return -1
        t_list = os.listdir(files_path)
        if t_list:
            try:
                t_list.sort(key=lambda x: datetime.datetime.strptime(x.split(".")[0], p2))
            except Exception:
                print("路径下：%s文件不能被格式：%s所解析，请检查解析格式是否正确" % (files_path, p1))
            for i, tm in enumerate(t_list):
                # 获得文件所表示的时间字符串并且转换为可以比较的类型
                tm = os.path.splitext(tm)[0]
                t = datetime.datetime.strptime(tm, p2)
                if t > compile_t:
                    return t_list[i - 1] if i != 0 else -1
            return t_list[-1]
        else:
            print("路径：%s下不存在文件" % files_path)

    @staticmethod
    def findLastAfterTime(str_time, files_path=None, p1='%Y-%m-%d-%H-%M-%S-%f', p2='%Y-%m-%d-%H-%M-%S-%f'):
        """
        在files_path中寻找一个文件，这个文件名表示的时间需要比str_time大并且最接近str_time
        算法思路:
            1. 获取路径下所有文件列表 并排序
            2. 把str_time转换为可以比较的形式compile_time
            3. 遍历排序后的列表，其每个元素与compile_time进行一一对比
                1. 如果元素比str_time小继续循环
                2. 如果元素比str_time大直接返回
            4. 如果遍历完成后还没有返回 则说明所有元素都比compile_time小 即返回列表下最后一个文件
        :param str_time: 要进行比较的时间 2020-12-12-10-07-26-935
        :param files_path: 要寻找的文件夹 2020-12-12-10-07-26-935
        :param p1: 时间str_time的解析格式如
        :param p2: 文件路径files_path下文件名的时间解析格式如
        :return:  返回最接近并且比时间str_time小的时间为文件名的文件
        """
        # 把str_time转化为可以比较的形式
        try:
            compile_t = datetime.datetime.strptime(str_time, p1)
        except Exception:
            print("需要对比的时间：%s不能被格式：%s所解析，请检查解析格式是否正确" % (str_time, p1))
            return -1
        t_list = os.listdir(files_path)
        if t_list:
            try:
                t_list.sort(key=lambda x: datetime.datetime.strptime(x.split(".")[0], p2))
            except Exception:
                print("路径下：%s文件不能被格式：%s所解析，请检查解析格式是否正确" % (files_path, p1))
            for i, tm in enumerate(t_list):
                # 获得文件所表示的时间字符串并且转换为可以比较的类型
                tm = os.path.splitext(tm)[0]
                t = datetime.datetime.strptime(tm, p2)
                if t > compile_t:
                    return t_list[i]
            return t_list[-1]
        else:
            print("路径：%s下不存在文件" % files_path)

    @staticmethod
    def checkPathOrCreate(path):
        if os.path.exists(path):
            print("路径已存在->%s" % path)
        else:
            print("创建路径:%s" % path)
            os.makedirs(path, exist_ok=True)

    @staticmethod
    def moveFilesTo(start_file, end_file, src, dest, p='%Y-%m-%d-%H-%M-%S-%f'):
        """
        移动范围内文件到指定目录
        :param start_file: src下开始移动的文件名
        :param end_file: src下结束移动的文件名
        :param src: 源文件地址
        :param dest: 目的地址
        :return:
        """
        t1 = time.time()
        file_list = os.listdir(src)
        if not file_list:
            print("源文件路径[%s]为空" % src)
            return -1

        file_list.sort(key=lambda x: datetime.datetime.strptime(x.split(".")[0], p))
        start = file_list.index(start_file)
        end = file_list.index(end_file)
        for file in file_list[start:end + 1]:
            file_path = os.path.join(src, file)
            shutil.copy(file_path, dest)
        print("移动文件耗时:%s" % (time.time() - t1))

    @property
    def now(self):
        return datetime.datetime.now()

    @property
    def machineTool_output_path(self):
        """
        振动数据分类路径
        :return:
        """
        return os.path.join(self.vibrationData_move_path, self.usingTool)

    @property
    def machineOldTool_output_path(self):
        """
        振动数据分类路径
        :return:
        """
        return os.path.join(self.vibrationData_move_path, self.old_tool)

    @staticmethod
    def date_to_str(date):
        return date.strftime('%Y-%m-%d-%H-%M-%S-%f')[:-3]

    def process_vibrationData(self):
        """
        把振动数据进行变换处理

        :param file_path:  分类收振动数据存放文件路径
        :param tools_num:  当前加工刀具
        :return:
        """
        data = []
        filenames = os.listdir(self.machineTool_output_path)
        filenames.sort(key=lambda x: datetime.datetime.strptime(x.split(".")[0], settings2.VIBRATION_FILENAME_PATTERN))
        if len(filenames) < 60:
            print("路径->%s下文件数目不够" % self.machineTool_output_path)
        else:
            count = 0
            for filename in filenames[::-1]:
                if count > 60:
                    break
                data_file_path = os.path.join(self.machineTool_output_path, filename)
                with open(data_file_path, 'r') as f:
                    line = f.readline()
                    if line.endswith(","):
                        line = line[:-1]
                    if line:
                        # curLine = [x for x in line.strip().split(",") if x]
                        curLine = line.strip().split(",")
                        try:
                            fline = np.array(list(map(int, curLine)))
                        except Exception as e:
                            print(e)
                            print("文件内容有误:%s" % data_file_path)
                        tem = sqrt(np.sum(fline ** 2) / len(fline))
                        data.append(tem)
                        count += 1
            # 不够60 补齐至60个数据 极端情况下可能出现不足60个：如果文件存在但是没有内容
            for _ in range(60 - len(data)):
                data.append(data[-1])

            data = np.array(data[::-1])
            data = 1/(1+log(data.mean(), 10e12))
            d = dict(data=data)
            # en_json = json.dumps(d, ensure_ascii=True)
            now_str = self.now.strftime(settings2.OUTPUT_FILENAME_PATTERN)
            tool_name = str(self.usingTool)
            if len(tool_name) == 1:
                tool_name = "T0" + tool_name
            else:
                tool_name = "T" + tool_name
            output_file_name = "%s-%s.json" % (tool_name, now_str)
            file_path = os.path.join(self.vibration_rms_output_path, output_file_name)
            with open(file_path, 'w') as f:
                json.dump(dict(data=data), f)

    def reduce_vibrationData_fre(self):
        """
        降频振动数据原始值 把震动数据处理后移动到指定路径下
        只读取路径下最新生成的文件
        :return: Json数据文件
        """
        file_list = os.listdir(self.vibrationData_input_path)
        file_list.sort(key=lambda x: datetime.datetime.strptime(x.split(".")[0], settings2.VIBRATION_FILENAME_PATTERN))
        if file_list:
            data_path = os.path.join(self.vibrationData_input_path, file_list[-1])
            if self.machine_name == "0002":
                # print(data_path)
                pass
            with open(data_path, 'r') as f:
                line = f.readline()
                if line:
                    curLine = line.strip().split(",")

                    data = list(map(int, curLine[0:60]))

                    now_str = self.now.strftime(settings2.OUTPUT_FILENAME_PATTERN)
                    output_file_name = "%s.json" % now_str
                    file_path = os.path.join(self.virbation_raw_output_path, output_file_name)
                    with open(file_path, 'w') as f:
                        json.dump(dict(data=data), f)
            self.old_vib_data = file_list[-1]
        else:
            print("路径：%s下不存在文件" % self.vibrationData_input_path)

    def process_machineData(self):
        file_list = os.listdir(self.machineInfo_input_path)
        if file_list:
            data_path = os.path.join(self.machineInfo_input_path, file_list[-2])
            # 可能由于文件读取xlsx文件是文件正在创建过程中导致无法正确读取而报错
            try:
                df = pd.read_csv(data_path, header=None)
            except Exception as e:
                print(e)
                return
            data = np.array(df.iloc[:, 2]).tolist()
            now_str = self.now.strftime(settings2.OUTPUT_FILENAME_PATTERN)
            output_file_name = "%s.json" % now_str
            file_path = os.path.join(self.load_data_output_path, output_file_name)
            with open(file_path, 'w') as f:
                json.dump(dict(data=data), f)

        pass

    def run(self) -> None:
        """
        算法本体
        算法每隔60s运行一次指定算法程序来处理振动数据得到变换后的振动数据
        算法每隔1s运行一次指定算法程序来处理振动数据得到降频振动数据
        算法每隔1s运行一次指定算法程序来处理机台信息得到负载信息
        :return:
        """

        while 1:

            while True:
                self.reduce_vibrationData_fre()
                self.process_machineData()
                time.sleep(1)

                if not self.setToolInfo():
                    print("获取机台信息失败")
                    break
                last_trans_time_str = self.date_to_str(self.last_trans_time)
                now_str = self.date_to_str(self.now)
                print("%s->上次传输数据时间:%s, 当前时间:%s, 当前加工刀具:%s" % (
                    self.machine_name, last_trans_time_str, now_str, self.usingTool))
                if (self.now - self.last_trans_time).seconds >= 60 and self.usingTool != 0:
                    first_vib_file = self.findLastAfterTime(last_trans_time_str,
                                                            files_path=self.vibrationData_input_path,
                                                            p1="%Y-%m-%d-%H-%M-%S-%f",
                                                            p2=settings2.VIBRATION_FILENAME_PATTERN)
                    last_vib_file = self.findLastBeforTime(now_str, files_path=self.vibrationData_input_path)
                    self.checkPathOrCreate(self.machineTool_output_path)
                    self.last_trans_time = self.now
                    self.moveFilesTo(first_vib_file, last_vib_file, self.vibrationData_input_path,
                                     self.machineTool_output_path)

                    t1 = time.time()
                    self.process_vibrationData()
                    print("处理完成时间：%s" % (time.time() - t1))
                # 如果换刀了 需要移动
                if self.hasChangeTool:
                    first_vib_file = self.findLastAfterTime(last_trans_time_str,
                                                            files_path=self.vibrationData_input_path,
                                                            p1="%Y-%m-%d-%H-%M-%S-%f",
                                                            p2=settings2.VIBRATION_FILENAME_PATTERN)
                    last_vib_file = self.findLastBeforTime(now_str, files_path=self.vibrationData_input_path,
                                                           p1="%Y-%m-%d-%H-%M-%S-%f",
                                                           p2=settings2.VIBRATION_FILENAME_PATTERN
                                                           )
                    self.checkPathOrCreate(self.machineOldTool_output_path)
                    self.last_trans_time = self.now
                    self.moveFilesTo(first_vib_file, last_vib_file, self.vibrationData_input_path,
                                     self.machineOldTool_output_path)

if __name__ == '__main__':
    try:

        t_list = []
        for machine in settings2.MACHINE_SETTINGS:
            t_list.append(
                ProcessFile(machine_name=machine["param"], machineInfo_input_path=machine["MachineData_INPUT_PATH"],
                            vibrationData_input_path=machine["SensorData_INPUT_PATH"],
                            using_tool_input_path=machine['ToolInfo_INPUT_PATH'],
                            vibrationData_move_path=machine["SensorData_MOVE_PATH"],
                            result_output_path=machine["Result_OUPUT_PATH"]))
            t_list.append(
                threading.Thread(target=machineDataSrcSuperviser, args=(180, machine["MachineData_INPUT_PATH"])))
            t_list.append(threading.Thread(target=keepRMSData, args=(
                os.path.join(machine["Result_OUPUT_PATH"], settings2.VIRBATION_RMS_OUTPUT_PATH_NAME),
                settings2.RMS_RESULT_RANGE)))
        t_list.append(threading.Thread(target=machineDataSuperviser, args=(120,)))
        t_list.append(threading.Thread(target=resultDataSuperviser, args=(120,)))

        for t in t_list:
            t.start()
        for t in t_list:
            t.join()
    except Exception as e:
        print(e)


# 每日早上 01:00 更新前一日的全部数据
import pandas as pd
import os, time
from datetime import timedelta

# 获取日期
def get_time():
    t = time.localtime(time.time())
    d, m = t.tm_mday,  t.tm_mon
    return m, d
m, d = get_time()

# 判断是否已经更新
update_time = open('dxylastest/update','r').read()
if update_time != '2020-%02d-%02d' % (m, d):
    update_time = '2020-%02d-%02d' % (m, d)
    # 加载 lastest historical data
    df = pd.read_csv('dxylastest/city.csv')
    # 增量更新
    shell = "wget http://69.171.70.18:5000/data/city_level_2020-%02d-%02dT00.csv -P dxylastest/" % (m,d)
    os.system(shell)
    columns = ['date','provinceShortName','city.cityName','city.confirmedCount','city.curedCount','city.deadCount','city.suspectedCount',
               'confirmedCount','suspectedCount','curedCount','deadCount','comment']
    tmp = pd.read_json('dxylastest/' + 'city_level_2020-%02d-%02dT00.csv' % (m,d))
    tmp['date'] = update_time
    tmp['date'] = pd.to_datetime(tmp['date']) - timedelta(days=1)
    df = df.append(tmp[columns])
    #df.sort_values("date",inplace=True)
    df.drop_duplicates(inplace=True)
    df.to_csv('dxylastest/city.csv',index=0)
    # 导出 rds
    os.system('Rscript csv2rds.R')
    # clear
    open('dxylastest/update','w').write(update_time)
else:
    print('everything is updated')


"""

    rex.widget.widget
    =================

    :copyright: 2015, Prometheus Research, LLC

"""

from collections import OrderedDict
import inspect

from rex.core import ProxyVal, SeqVal, RecordField
from rex.core import Extension, Error

from .transitionable import as_transitionable
from .field import FieldBase, Field, ComputedField, ResponderField
from .util import PropsContainer

__all__ = ('Widget', 'GroupWidget', 'NullWidget', 'RawWidget')

JS_IS_STRING_ERROR_MESSAGE = """
Expected "js_type" class atribute to be a tuple of ('<pkg name>', '<symbol>')

Previously "js_type" was used to specify a JS module which exports a React
component for a widget. Now it is changed to specify a pair of JS package and a
name of the symbol exported from package's entry point which points to a React
component.

If previously "js_type" was:

    js_type = "my-app/lib/Component"

Now it should be:

    js_type = ("my-app", "Component")

While "my-app" JS package entry point (usually "static/js/lib/index.js") should
contain:

    export Component from "./Component.js"

""".strip()

class WidgetMeta(type(Extension)): # pylint: disable=no-init

    def __new__(mcs, name, bases, members): # pylint: disable=bad-classmethod-argument
        fields = [(n, field.__clone__(name=n) if field.name is None else field)
                  for n, field in list(members.items())
                  if isinstance(field, FieldBase)]
        fields.sort(key=lambda __field: -__field[1].order)
        members.update(fields)
        cls = type(Extension).__new__(mcs, name, bases, members)
        # js_type validation
        if hasattr(cls, 'js_type') and cls.js_type is not None:
            if isinstance(cls.js_type, str):
                raise Error(
                    'Error while defining %s.%s widget:' % (
                        cls.__module__, cls.__name__),
                    JS_IS_STRING_ERROR_MESSAGE)
        cls._fields = OrderedDict()
        if not (name == 'Widget' and members['__module__'] == __name__):
            cls._fields.update([f for base in bases
                                if issubclass(base, Widget)
                                for f in list(base._fields.items())])
        cls._fields.update(fields)
        cls._configuration = cls.Configuration({
            field.name: field
            for field in list(cls._fields.values())
            if isinstance(field, Field)})
        return cls

_suppress_validation = False

class Widget(Extension, metaclass=WidgetMeta):
    """ Widget class is used to define configuration interface for React
    components.

    For each React component which is to be exposed through URL mapping there
    should be a :class:`Widget` subclass defined which describes the
    configuration interface::

        class MyWidget(Widget):

            name = 'MyWidget'
            js_type = 'my-package/my-widget'

            title = Field(
                StrVal()
                doc='Title')

            hint = Field(
                StrVal(), default='No hint',
                doc='Hint')

    The snippet above defines a new widget ``MyWidget``.

    Class attribute ``name`` is used to refer to widget type from URL Mapping
    configuration. Class attribute ``js_type`` points to a CommonJS module which
    exports a React component corresponding to a widget.

    Widget defines two fields, one of them, ``title`` is required because it
    doesn't have default value while ``hint`` is optional.

    Widgets can be instantiated through YAML::

        w = Widget.parse('''
        !<MyWidget>
        title: Title
        ''')

    or directly via its constructor::

        w = Widget(title='Title')

    """

    name = None
    js_type = None

    _validate = ProxyVal()
    _validate_values = ProxyVal()
    _fields = OrderedDict()

    class Configuration(object):

        def __init__(self, fields):
            self.fields = fields

        def __call__(self, widget_class, values):
            return widget_class.validated(**values)

    @classmethod
    def parse(cls, value):
        validate = cls._validate.validate.__class__(widget_class=cls)
        if isinstance(value, str) or hasattr(value, 'read'):
            return validate.parse(value)
        else:
            raise Error('Cannot parse a widget from:', repr(value))

    @classmethod
    def validated(cls, **values):
        global _suppress_validation # pylint: disable=global-statement
        _suppress_validation = True
        try:
            return cls(**values)
        finally:
            _suppress_validation = False

    @classmethod
    def enabled(cls):
        return cls.name is not None

    @classmethod
    def signature(cls):
        return cls.name

    NOT_DOCUMENTED = 'Widget is not documented'

    @classmethod
    def document_header(cls):
        if isinstance(cls.name, str):
            return str(cls.name)
        return super(Widget, cls).document_header()

    @classmethod
    def document_all(cls, package=None):
        entries = [extension.document() for extension in cls.all(package)
                       if extension.name is not None]
        entries.sort(key=(lambda e: e.header))
        return entries

    @classmethod
    def document_fields(cls):
        fields = []
        template = '  * ``{name}``\n\n      {doc}'
        for field in sorted(list(cls._fields.values()), key=(lambda f: f.name)):
            if isinstance(field, (ComputedField, ResponderField)):
                continue
            fields.append(template.format(
                name=field.name,
                doc=(field.doc or 'Field is not documented')
            ))
        fields = '\n'.join(fields)
        if fields:
            fields = '\n\nFields:\n' + fields
        return fields

    @classmethod
    def document_content(cls):
        fields = cls.document_fields()
        doc = inspect.cleandoc(cls.__doc__ or cls.NOT_DOCUMENTED) + fields
        return inspect.cleandoc(doc)

    def __init__(self, package=None, **values):
        super(Widget, self).__init__()
        global _suppress_validation # pylint: disable=global-statement
        if not _suppress_validation:
            values = self._validate_values(self.__class__, values)
        else:
            _suppress_validation = False
        self.package = package
        self.values = values

    def __clone__(self, **values):
        next_values = {}
        next_values.update(self.values)
        next_values.update(values)
        next_values['package'] = self.package
        return self.__class__(**next_values)

    def __validated_clone__(self, **values):
        next_values = {}
        next_values.update(self.values)
        next_values.update(values)
        return self.__class__.validated(**next_values)

    def __repr__(self):
        return "%s(...)" % (self.__class__.__name__,)

@as_transitionable(Widget, tag='widget')
def _format_Widget(widget, req, path): # pylint: disable=invalid-name
    values = OrderedDict()
    values.update(widget.values)
    for name, field in list(widget._fields.items()):
        if field.transitionable:
            if field.as_transitionable:
                values[name] = field.as_transitionable(widget, field(widget))
            else:
                values[name] = field(widget)
        elif name in values:
            del values[name]
    pkg_name, symbol_name = widget.js_type
    return '@js-package::' + pkg_name, symbol_name, PropsContainer(values)

class WidgetComposition(Widget):

    def __init__(self, underlying=None, **values):
        super(WidgetComposition, self).__init__(**values)
        if underlying is None:
            underlying = self.render()
        self.underlying = underlying

    def render(self):
        raise NotImplementedError('%s.render() is not implemented' % \
                                  self.__class__.__name__)

@as_transitionable(WidgetComposition)
def _format_WidgetComposition(widget, req, path): # pylint: disable=invalid-name
    return widget.underlying

class GroupWidget(Widget):

    children = Field(SeqVal(Widget._validate))

@as_transitionable(GroupWidget, tag='array')
def _format_GroupWidget(widget, req, path): # pylint: disable=invalid-name
    return widget.children

class NullWidget(Widget):

    _singleton = None

    def __new__(cls, package=None):
        if cls._singleton is None:
            cls._singleton = Widget.__new__(cls)
        return cls._singleton

@as_transitionable(NullWidget, tag='_')
def _format_NullWidget(widget, req, path): # pylint: disable=invalid-name
    return None

class RawWidget(object):

    __slots__ = ('js_type', 'values')

    def __init__(self, js_type, values):
        self.js_type = js_type
        self.values = values

@as_transitionable(RawWidget, tag='widget')
def _format_RawWidget(widget, req, path): # pylint: disable=invalid-name
    pkg_name, symbol_name = widget.js_type
    return '@js-package::' + pkg_name, symbol_name, PropsContainer(widget.values)

def raw_widget(*args, **kwargs):
    if len(args) < 1:
        raise TypeError(
            "At least one position arg should be used to define "
            "'js_type'")
    elif len(args) == 1:
        js_type = args[0]
        values = {}
    elif len(args) == 2:
        js_type = args[0]
        values = dict(args[1])
    else:
        raise TypeError("Too many positional arguments provided")
    values.update(kwargs)
    return RawWidget(js_type, values)


"""
This module contains the CodeHasher class, which hashes code objects
into values that uniquely identify those objects.

Bionic uses the CodeHasher class to detect any changes to entity
functions. When an entity function changes, the entity value may also
change, which requires Bionic to invalidate the cache and compute the
entity again.

This class is only used when versioning mode is set to "auto" or
"assisted". Since the logic doesn't cover every type of code change,
like changes to references or classes, these versioning modes are still
experimental. When we can detect all kinds of code changes, we will
make "auto" mode the default behavior.

Since Bionic uses these encodings to detect changes, any changes to
encoding will make caching backwards-incompatible. If you make any
changes to this module that can change the encoding, update
CACHE_SCHEMA_VERSION to update cache scheme.
"""

from enum import Enum
import hashlib
import inspect
import warnings

from .utils.misc import oneline

PREFIX_SEPARATOR = b"$"

class CodeHasher:
    """
    This class hashes code objects into values that uniquely identify
    those objects. If two code objects have different behavior, they
    should ideally have different hashes. However, for now, we only
    examine the function bytecode and associated constants. We will add
    more functionality like checking function references and any
    changes to class objects.

    Since this class doesn't examine the references and class objects,
    it doesn't actually achieve the ideal behavior we described above.
    """

    def __init__(self):
        self._hash = hashlib.new("md5")
        # This is used to detect circular references.
        self._object_depths_by_id = {}

    @classmethod
    def hash(cls, obj):
        hasher = cls()
        hasher._check_and_ingest(obj=obj)
        return hasher._hash.hexdigest()

    def hexdigest(self):
        return self._hash.hexdigest()

    def update(self, obj):
        return self._check_and_ingest(obj)

    def _ingest_raw_prefix_and_bytes(self, type_prefix, obj_bytes=b""):
        self._hash.update(type_prefix.value)
        self._hash.update(get_size_as_bytes(obj_bytes))
        self._hash.update(PREFIX_SEPARATOR)
        self._hash.update(obj_bytes)

    def _check_and_ingest(self, obj):
        """
        Checks for circular references before calling the _ingest
        method, which does the actual encoding.
        """
        obj_id = id(obj)

        # If the obj is already being hashed, break the circular ref by
        # analyzing the depth of the value instead.
        if obj_id in self._object_depths_by_id:
            obj = self._object_depths_by_id[obj_id]
            self._ingest_raw_prefix_and_bytes(
                type_prefix=TypePrefix.CIRCULAR_REF,
                obj_bytes=str(self._object_depths_by_id[obj_id]).encode(),
            )
            return

        self._object_depths_by_id[obj_id] = len(self._object_depths_by_id)
        self._ingest(obj)
        del self._object_depths_by_id[obj_id]

    def _ingest(self, obj):
        """
        Contains the logic that analyzes the objects and encodes them
        into bytes that are added to the hash.
        """
        if isinstance(obj, bytes):
            self._ingest_raw_prefix_and_bytes(
                type_prefix=TypePrefix.BYTES, obj_bytes=obj
            )

        elif isinstance(obj, bytearray):
            self._ingest_raw_prefix_and_bytes(
                type_prefix=TypePrefix.BYTEARRAY, obj_bytes=obj
            )

        elif obj is None:
            self._ingest_raw_prefix_and_bytes(
                type_prefix=TypePrefix.NONE, obj_bytes=b"None"
            )

        elif isinstance(obj, int):
            self._ingest_raw_prefix_and_bytes(
                type_prefix=TypePrefix.INT,
                obj_bytes=str(obj).encode(),
            )

        elif isinstance(obj, float):
            self._ingest_raw_prefix_and_bytes(
                type_prefix=TypePrefix.FLOAT,
                obj_bytes=str(obj).encode(),
            )

        elif isinstance(obj, str):
            self._ingest_raw_prefix_and_bytes(
                type_prefix=TypePrefix.STRING,
                obj_bytes=obj.encode(),
            )

        elif isinstance(obj, bool):
            self._ingest_raw_prefix_and_bytes(
                type_prefix=TypePrefix.BOOL,
                obj_bytes=str(obj).encode(),
            )

        elif isinstance(obj, (list, set, tuple)):
            if isinstance(obj, list):
                type_prefix = TypePrefix.LIST
            elif isinstance(obj, set):
                type_prefix = TypePrefix.SET
            else:
                type_prefix = TypePrefix.TUPLE
            obj_bytes = str(len(obj)).encode()
            self._ingest_raw_prefix_and_bytes(
                type_prefix=type_prefix,
                obj_bytes=obj_bytes,
            )
            for elem in obj:
                self._check_and_ingest(elem)

        elif isinstance(obj, dict):
            self._ingest_raw_prefix_and_bytes(
                type_prefix=TypePrefix.DICT,
                obj_bytes=str(len(obj)).encode(),
            )
            for key, elem in obj.items():
                self._check_and_ingest(key)
                self._check_and_ingest(elem)

        elif inspect.isroutine(obj):
            self._ingest_raw_prefix_and_bytes(type_prefix=TypePrefix.ROUTINE)
            self._check_and_ingest(obj.__defaults__)
            self._ingest_code(obj.__code__)

        elif inspect.iscode(obj):
            self._ingest_raw_prefix_and_bytes(type_prefix=TypePrefix.CODE)
            self._ingest_code(obj)

        else:
            # TODO: Verify that we hash all Python constant types.
            self._ingest_raw_prefix_and_bytes(type_prefix=TypePrefix.DEFAULT)
            message = oneline(
                f"""
                Found a constant {obj!r} of type {type(obj)!r} that
                Bionic doesn't know how to hash. This is most likely a
                bug in Bionic. Please raise a new issue at
                https://github.com/square/bionic/issues to let us know.
                """
            )
            warnings.warn(message)

    def _ingest_code(self, code):
        # TODO: Find references for the code and analyze references.
        self._check_and_ingest(code.co_code)

        # TODO: Maybe there is a way using which we can differentiate
        # between lambda variable names and string constants that end
        # with `.<lambda>`.
        consts = [
            const
            for const in code.co_consts
            if not (isinstance(const, str) and const.endswith(".<lambda>"))
        ]
        self._check_and_ingest(consts)

class TypePrefix(Enum):
    """
    Represents a unique value for each type that CodeHasher hashes that
    is prefixed to avoid collision between same encoded values.

    If you change the prefix of any type, or add a new prefix, it can
    change the encoding of objects. Since Bionic uses these encodings
    to detect changes, any changes to encoding will make caching
    backwards-incompatible. Update CACHE_SCHEMA_VERSION to update cache
    scheme if you change the encoding.
    """

    BYTES = b"AA"
    BYTEARRAY = b"AB"
    NONE = b"AC"
    STRING = b"AD"
    INT = b"AE"
    FLOAT = b"AF"
    BOOL = b"AG"
    LIST = b"AH"
    SET = b"AI"
    TUPLE = b"AJ"
    DICT = b"AK"
    ROUTINE = b"AL"
    CODE = b"AM"
    CIRCULAR_REF = b"AN"
    DEFAULT = b"ZZ"

def get_size_as_bytes(obj_bytes):
    assert isinstance(obj_bytes, (bytes, bytearray))
    return str(len(obj_bytes)).encode()


#rubi
n=int(input())
l=[int(x) for x in input().split()]
t=0
if(n==len(l)):
  for i in range(0,n):
    for j in range(i+1,n):
      t=l[i]^l[j]

print(t)


# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------

from msrest.serialization import Model

class PeriodicTimerSourceInfo(Model):
    """Periodic timer event source.

    All required parameters must be populated in order to send to Azure.

    :param start_time: Required. The time of the day that results in a valid
     trigger. Schedule is computed with reference to the time specified up to
     seconds. If timezone is not specified the time will considered to be in
     device timezone. The value will always be returned as UTC time.
    :type start_time: datetime
    :param schedule: Required. Periodic frequency at which timer event needs
     to be raised. Supports daily, hourly, minutes, and seconds.
    :type schedule: str
    :param topic: Topic where periodic events are published to IoT device.
    :type topic: str
    """

    _validation = {
        'start_time': {'required': True},
        'schedule': {'required': True},
    }

    _attribute_map = {
        'start_time': {'key': 'startTime', 'type': 'iso-8601'},
        'schedule': {'key': 'schedule', 'type': 'str'},
        'topic': {'key': 'topic', 'type': 'str'},
    }

    def __init__(self, *, start_time, schedule: str, topic: str=None, **kwargs) -> None:
        super(PeriodicTimerSourceInfo, self).__init__(**kwargs)
        self.start_time = start_time
        self.schedule = schedule
        self.topic = topic


# Third parties imports
import pytest

# Local imports
from oblivion import functions

@pytest.mark.parametrize(
    "args,result", [
        ((b'test', 1), b'\x1b'),
        ((b'test', 2), b'\x1b\xc2'),
    ])
def test_mask_generation_function(args, result):
    """Test functions.mask_generation_function."""
    assert functions.mask_generation_function(*args) == result

@pytest.mark.parametrize(
    "args,result", [
        ((2,), (2, 3, 5, 7)),
        ((3,), (5, 7, 11, 13)),
    ])
def test_generate_prime(args, result):
    """Test functions.generate_prime."""
    assert functions.generate_prime(*args) in result


#
# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
#

import sys
import re
import time
import subprocess

Import('AgentEnv')
env = AgentEnv.Clone()

cflags = env['CCFLAGS']
cflags.append('-Wno-return-type')
cflags.append('-fexceptions')
cflags.append('-Wno-unused-variable')

##########################################################################
# Rules to generate buildinfo.cc
##########################################################################

# Dependencies on external libraries first
buildinfo_dep_libs = [
    '#build/lib/libthrift.a',
    '#build/lib/libthriftasio.a',
    '#build/lib/libhttp.a',
    '#build/lib/libhttp_parser.a',
    '#build/lib/libpugixml.a',
    '#build/lib/libsandesh.a',
    '#build/lib/libsandeshflow.a',
    '#build/lib/libsandeshvns.a'
]

def MapBuildCmnLib(list):
    return map(lambda x: File('../../../' + x).abspath, list)

# Common contrail libraries
buildinfo_dep_libs += MapBuildCmnLib([
    'base/libbase.a',
    'base/libcpuinfo.a',
    'db/libdb.a',
    'dns/bind/libbind_interface.a',
    'ifmap/libifmap_agent.a',
    'ifmap/libifmap_common.a',
    'io/libio.a',
    'ksync/libksync.a',
    'net/libnet.a',
    'route/libroute.a',
    'schema/libbgp_schema.a',
    'schema/libifmap_vnc.a',
    'schema/libxmpp_unicast.a',
    'schema/libxmpp_multicast.a',
    'vrouter/utils/libvrutil.a',
    'xml/libxml.a',
    'xmpp/libxmpp.a'
     ])

def MapBuildAgentLib(list):
    return map(lambda x: File('../' + x).abspath, list)

# agent libraries
buildinfo_dep_libs += MapBuildAgentLib([
    'cfg/libcfg.a',
    'cmn/libvnswcmn.a',
    'controller/libvnswctrl.a',
    'filter/libfilter.a',
    'kstate/libkstate.a',
    'vrouter/ksync/libvnswksync.a',
    'openstack/libnova_ins.a',
    'openstack/libnova_ins_thrift.a',
    'port_ipc/libport_ipc.a',
    'oper/libvnswoperdb.a',
    'pkt/libpkt.a', 'diag/libdiag.a',
    'services/libagent_services.a', 'uve/libuve.a',
    'uve/libstatsuve.a', 'vrouter/flow_stats/libflowstats.a',
    'vrouter/stats_collector/libstatscollector.a'
])

env.GenerateBuildInfoCode(
    target = ['buildinfo.h', 'buildinfo.cc'],
    source = buildinfo_dep_libs + ['main.cc'],
    path=str(Dir('.').abspath))
env.Depends('main.o', 'buildinfo.cc')

# Add contrail-vrouter-agent specific libraries
env.Prepend(LIBS = AgentEnv['CONTRAIL_LIBS'])

# Whole-arhive flag causes the library to be included in the resulting output
# even though there may not be any calls requiring its presence. We need this
# for kstate library so that the HTML file for kstate  is listed in agent
# introspect page
env.Prepend(LINKFLAGS = ['-Wl,--whole-archive', '-rdynamic', '-lkstate', '-ldiag',
                         '-Wl,--no-whole-archive'])

#Add -Wno-return-type to ignore errors from thrift generated code in
#InstanceService.h
if sys.platform.startswith('freebsd'):
    platform_dependent = 'freebsd/pkt0_interface.cc'
elif sys.platform.startswith('linux'):
    platform_dependent = 'linux/pkt0_interface.cc'

contrail_vrouter_agent = env.Program(target = 'contrail-vrouter-agent',
                     source = ['buildinfo.cc',
                               'contrail_agent_init.cc',
                               'main.cc',
                               'pkt0_interface_base.cc',
                                platform_dependent])

env.Alias('contrail-vrouter-agent', contrail_vrouter_agent)
env.Default(contrail_vrouter_agent)

# Documentation
doc_files = []
doc_files += env['AGENT_COMMON_DOC_FILES']
doc_files += env['AGENT_UVE_DOC_FILES']
doc_files += env['AGENT_KSYNC_DOC_FILES']
doc_files += env['AGENT_FLOW_DOC_FILES']

# Please update sandesh/common/vns.sandesh on process name change
env.Alias('install', env.Install(env['INSTALL_BIN'], contrail_vrouter_agent))
env.Alias('install', env.Install(env['INSTALL_EXAMPLE'],
          'contrail-vrouter-agent-health-check.py'))
env.Alias('install', env.Install(env['INSTALL_CONF'],
          '../contrail-vrouter-agent.conf'))
env.Alias('install',
        env.InstallAs(env['INSTALL_CONF'] +
        '/supervisord_vrouter_files/' + 'contrail-vrouter-agent.ini',
        '../contrail-vrouter-agent.ini'))
env.Alias('install',
        env.InstallAs(env['INSTALL_INITD'] + '/contrail-vrouter-agent',
        '../contrail-vrouter.initd.supervisord'))
env.Alias('install', env.Install(env['INSTALL_CONF'],
    '../supervisord_vrouter.conf'))
env.Alias('install', env.Install(
    env['INSTALL_MESSAGE_DOC'] + '/contrail-vrouter-agent/',
    doc_files))


from Grafo import Grafo
#******************************************************************************
# Librerías para generar valores aleatorios
from random import seed
from random import randint
from random import random
#******************************************************************************
def grafoErdosRenyi(n, m, dirigido=False, auto=False):
  '''
  Genera grafo aleatorio con el modelo Erdos-Renyi
  :param n: número de nodos (> 0)
  :param m: número de aristas (>= n-1)
  :param dirigido: el grafo es dirigido?
  :param auto: permitir auto-ciclos?
  :return: grafo generado
  '''
  #Generar objeto grafo
  nombre='grafoErdosRenyi_n_'+str(n)+'_m_'+str(m)
  grafo = Grafo(nombre,dirigido,auto)

  #si el número de nodos es 0 regresar el grafo vacio
  if n==0:
      return grafo

  #Generar n nodos
  for i in range(n):
    grafo.agregar_nodo(i)

  #Elegir dos nodos de manera aleatoria y crear una arista entre los nodos, evitar si ya existe la arista, repetir m veces
  count=0
  while(count<m):
    nodo1 = randint(0, n-1)
    nodo2 = randint(0, n-1)
    if not auto: #Si no existe autociclos
      if nodo1 == nodo2: #Es un autociclo
        continue; #Genera una nueva iteración
    if not grafo.checarSiAristaExiste(nodo1,nodo2): #Agregar arista si todavía no existe
      grafo.agregar_arista(nodo1,nodo2)
      count+=1

  return grafo
#******************************************************************************


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
FCode Challenge: Solve the Overlap Alignment Problem.
     Input: Two strings v and w, each of length at most 1000.
     Output: The score of an optimal overlap alignment of v and w, followed by an alignment of a suffix v' of v and a prefix w' of w
     achieving this maximum score. Use an alignment score in which matches count +1 and both the mismatch and indel penalties are 2.

Sample Input:
PAWHEAE
HEAGAWGHEE

Sample Output:
1
HEAE
HEAG

"""
import numpy as np
import math

np.set_printoptions(threshold=math.nan)

#Output Longest Common Sequence
def OutputLCS(backtrack,v,w,i,j,p,q):
    if i == 0 and j == 0:
        return p,q
    x = backtrack[i,j]
    if x == 0:
        OutputLCS(backtrack,v,w,0,0,p,q)
    if x == 1:#right
        OutputLCS(backtrack,v,w,i,j-1,p,q)
        p.append('-')
        q.append(w[j-1])
    elif x == 2:#down
        OutputLCS(backtrack,v,w,i-1,j,p,q)
        p.append(v[i-1])
        q.append('-')
    elif x == 3:#diagonal
        OutputLCS(backtrack,v,w,i-1,j-1,p,q)
        p.append(v[i-1])
        q.append(w[j-1])
    return p,q

def OverlapAlignment(v,w):
    m,n = len(v),len(w)
    s,backtrack = np.zeros((m+1,n+1)),np.zeros((m+1,n+1))
    p,q,a,b = "","",0,0
    node = -(math.inf)
    for i in range(1,m+1):
        for j in range(1,n+1):
            diag = -2
            if v[i-1] == w[j-1]:
                diag = 1
            s.itemset((i,j), max(s[i-1,j]-2, s[i,j-1]-2, s[i-1,j-1]+diag))
            if s[i,j] == s[i,j-1]-2:
                backtrack.itemset((i,j),1)
            elif s[i,j] == s[i-1,j]-2:
                backtrack.itemset((i,j), 2)
            elif s[i,j] == (s[i-1,j-1]+diag):
                backtrack.itemset((i,j), 3)
            if s[i,j] >= node and (i == m):
                node = s[i,j]
                node_r = i
                node_c = j
    i,j = node_r,node_c
    while j>0:
        x = backtrack[i,j]
        if x == 1: #right
            p = '-' + p
            q = w[j-1] + q
            j -= 1
        elif x == 2: #down
            p = v[i-1] + p
            q = '-' + q
            i -= 1
        elif x == 3:#diag
            p = v[i-1] + p
            q = w[j-1] + q
            i -= 1
            j -= 1
    return "\n".join([x for x in [str(int(s[node_r,node_c])),p,q]])