# import numpy as np
import autograd.numpy as np
import matplotlib.pyplot as plt
from collections import defaultdict
from scipy.spatial import Delaunay
from skimage.draw import line
from bresenham import bresenham
import os
from autograd.builtins import isinstance, tuple

class VascularGenerator:
    def __init__(self, min_range=1, max_range=10, dim=2, num_of_nodes=20):
        self.graph = defaultdict(list)
        self.update_count = 0
        # Create Wall start and end points
        self.min_range = float(min_range)
        self.max_range = float(max_range)
        self.left_wall_startend = np.array([[self.min_range, self.min_range], [self.min_range, self.max_range]])
        self.right_wall_startend = np.array([[self.max_range, self.min_range], [self.max_range, self.max_range]])

        # Create Left and Right Walls
        self.left_wall, self.right_wall = self.create_walls(self.min_range, self.max_range, num_of_nodes)

        # Generate random points
        self.pts, self.moveable_pts = self.generate_pts(self.min_range, self.max_range, num_of_nodes, dim,
                                                        self.left_wall, self.right_wall,
                                                        self.left_wall_startend, self.right_wall_startend)

        # Create the Planar graph using the Delaunay Method
        self.tri = Delaunay(self.pts)

        # Create Edges
        self.edges = self.generate_edges(self.tri, self.pts)

        # Convert Edges to image
        self.img = self.convert_to_img2(self.edges, max_range)

    def add_edge_to_graph(self, np_pt1, np_pt2):
        # print('Line 42: ', np_pt1, type(np_pt1))
        # print('Add edge: line 40: ')
        # print('  ', np_pt1, list(np_pt1))
        if type(np_pt1) != type(np.array((2,4))):
            np_pt1 = list(np_pt1._value)
            np_pt2 = list(np_pt2._value)
        else:
            np_pt1 = list(np_pt1)
            np_pt2 = list(np_pt2)
        # print('Adding To Graph: ', np_pt1, np_pt2)
        if tuple(np_pt1) not in self.graph.keys():
            self.graph[tuple(np_pt1)]
        if tuple(np_pt2) not in self.graph.keys():
            self.graph[tuple(np_pt2)]
        # Compares the x values

        if np_pt1[0] < np_pt2[0]:
            # if not self.arreq_in_list(np_pt2, self.graph[tuple(np_pt1)]):
            if not np_pt2 in self.graph[tuple(np_pt1)]:
                self.graph[tuple(np_pt1)].append(np_pt2)
        elif np_pt1[0] == np_pt2[0] and np_pt1[1] > np_pt2[1]:              # Added this to enforce bottom-right node as exit
            # if not self.arreq_in_list(np_pt2, self.graph[tuple(np_pt1)]):
            if not np_pt2 in self.graph[tuple(np_pt1)]:
                self.graph[tuple(np_pt1)].append(np_pt2)
        else:
            # if not self.arreq_in_list(np_pt1, self.graph[tuple(np_pt2)]):
            if not np_pt1 in self.graph[tuple(np_pt2)]:
                self.graph[tuple(np_pt2)].append(np_pt1)

    def arreq_in_list(self, myarr, list_arrays):
        # https://stackoverflow.com/questions/23979146/check-if-numpy-array-is-in-list-of-numpy-arrays
        return next((True for elem in list_arrays if np.array_equal(elem, myarr)), False)

    def arreq_in_list_wIdx(self, myarr, list_arrays):
        return next((idx for idx, elem in enumerate(list_arrays) if np.array_equal(elem, myarr)), -1)

    def depth_first_search(self):
        # https://www.geeksforgeeks.org/depth-first-search-or-dfs-for-a-graph/
        num_nodes = len(self.pts)
        visted_nodes = [False] * num_nodes

        for i in range(num_nodes):
            if not visted_nodes[i]:
                node = self.pts[i]
                self.dfs_helper(i, node, visted_nodes)

    def dfs_helper(self, node_idx, node, visted_nodes):
        visted_nodes[node_idx] = True
        # print(node)

        for i, node in enumerate(self.graph[tuple(node)]):
            if not visted_nodes[node_idx]:
                self.dfs_helper(i, node, visted_nodes)

    def generate_edges(self, tri, pts):
        edges = []
        for _, s in enumerate(tri.simplices):
            tri_pts = pts[s]
            # print('Line 98: ', tri_pts, list(tri_pts))

            for i, pt in enumerate(tri_pts):
                if i == 0:
                    continue
                elif pt[0] == tri_pts[-1][0] and pt[1] == tri_pts[-1][1]:
                    self.add_edge_to_graph(pt, tri_pts[0])

                self.add_edge_to_graph(tri_pts[i-1], pt)

        topl_to_topR = (np.array([self.min_range, self.max_range]), np.array([self.max_range, self.max_range]))
        btml_to_btmR = (np.array([self.min_range, self.min_range]), np.array([self.max_range, self.min_range]))

        for pt_pair in [topl_to_topR, btml_to_btmR]:
            pt1, pt2 = pt_pair
            pt1 = [i for i in pt1]
            pt2 = [i for i in pt2]

            if pt2 in self.graph[tuple(pt1)]:
            # if self.arreq_in_list(pt2, self.graph[tuple(pt1)]):
                idx = self.arreq_in_list_wIdx(pt2, self.graph[tuple(pt1)])
                del self.graph[tuple(pt1)][idx]
            elif pt1 in self.graph[tuple(pt2)]:
            # elif self.arreq_in_list(pt1, self.graph[tuple(pt2)]):
                idx = self.arreq_in_list_wIdx(pt1, self.graph[tuple(pt2)])
                del self.graph[tuple(pt1)][idx]

        edges = []
        for tuple_pt, np_pt_list in self.graph.items():
            for np_pt in np_pt_list:
                # edges.append((np.asarray(tuple_pt), list(np_pt)))
                edges.append((list(tuple_pt), list(np_pt)))

        return edges

    def convert_to_img2(self, edges, max_range):
        img = []
        for _ in range(int(max_range + 1.0)):
            img.append([0.0 for i in range(int(max_range + 1.0))])

        for edge in edges:
            pt1, pt2 = edge
            # print(pt1, type(pt1))
            # print(pt1, np.array(pt1))
            # print('line 142: ', [i for i in list(pt1)], pt1[0][0])
            pt1 = [int(i) for i in list(pt1)]
            pt2 = [int(i) for i in list(pt2)]
            pts_on_line = list(bresenham(pt1[0], pt1[1], pt2[0], pt2[1]))
            for x, y in pts_on_line:
                if (x == pt1[0] and y == pt1[1]) or (x == pt2[0] and y == pt2[1]):
                    img[x][y] = 2
                else:
                    img[x][y] = 1

        return np.array(img)

    def add_flows_to_img(self, flow_dict):
        img = []
        for _ in range(int(self.max_range + 1)):
            img.append([0 for i in range(int(self.max_range + 1))])

        for pt_key, flow_val in flow_dict.items():
            pt1, pt2 = pt_key
            pt1 = [int(i) for i in list(pt1)]
            pt2 = [int(i) for i in list(pt2)]
            pts_on_line = list(bresenham(pt1[0], pt1[1], pt2[0], pt2[1]))
            for x, y in pts_on_line:
                img[x][y] = flow_val

        self.img = np.array(img)

        return self.img

    # ====================== #
    # ==== Create Walls ==== #
    # ====================== #
    def create_walls(self, min, max, num_of_nodes):
        # Number of Wall nodes = 1% of number of nodes
        high_node_val = int(num_of_nodes / 5)
        num_left_nodes = 1
        num_right_nodes = 1
        if high_node_val > 1:
            num_left_nodes = np.random.randint(1, high=high_node_val)
            num_right_nodes = np.random.randint(1, high=high_node_val)

        left_wall = []
        right_wall = []

        # Create Nodes for Left Wall (In)
        for i in range(num_left_nodes):
            node = [[min, np.random.randint(min + 1, max - 1)]]
            if node[0] in left_wall:
                i -= 1
            else:
                left_wall.append(node[0])

        # Create Nodes for Right Wall (Out)
        for i in range(num_right_nodes):
            node = [[max, np.random.randint(min + 1, max - 1)]]
            if node[0] in right_wall:
                i -= 1
            else:
                right_wall.append(node[0])

        return np.array(left_wall), np.array(right_wall)

    def calculate_distance(self, point, neighbor):
        '''
        Euclidean distance
        '''
        dist = np.linalg.norm(point - neighbor)
        return dist

    def flatten_mvable_pts(self):

        # flattened_pts = sorted(self.moveable_pts, key=lambda k: (-k[0], k[1]),  reverse=True)
        # print('VasGen Line 216: ', flattened_pts)
        # flattened_pts = np.hstack(flattened_pts)
        # flattened_pts = ()
        # for np_pt in list(sorted(self.moveable_pts, key=lambda k: (-k[0], k[1]),  reverse=True)):
        #     flattened_pts += tuple(np_pt)

        # return flattened_pts
        return self.moveable_pts

    def update_moveable_pts(self, new_mvable_pts):
        tuple_of_pts = ()
        prev = None
        cur = None
        for i in range(2, len(new_mvable_pts)+2, 2):
            cur  = new_mvable_pts[i-2:i]
            if i > 2:
                tuple_of_pts = tuple_of_pts + (prev, cur)
            prev = cur

        # print('tup of pts: ', tuple_of_pts)
        # print('np.vstack: ', np.vstack((tuple_of_pts)))
        # print('test  :\n', np.vstack({tuple(row) for row in tuple_of_pts}))
        # val = np.vstack((tuple_of_pts))
        print('VasGen Line 238: ', type(new_mvable_pts), new_mvable_pts, np.vstack(new_mvable_pts))
        print('VasGen Line 239: ', type(tuple_of_pts), tuple_of_pts)
        # self.moveable_pts = np.vstack((tuple_of_pts))
        self.moveable_pts = np.vstack(new_mvable_pts)
        # new_mvable_pts = np.unique(val, axis=0)
        # new_mvable_pts = val
        # pts = new_mvable_pts
        pts = self.moveable_pts
        pts = np.append(pts, self.left_wall, axis=0)
        pts = np.append(pts, self.right_wall, axis=0)
        pts = np.append(pts, self.left_wall_startend, axis=0)
        pts = np.append(pts, self.right_wall_startend, axis=0)
        self.pts = np.array(sorted(pts, key=lambda k: (-k[0], k[1]),  reverse=True))

        # Update all points off of image
        # self.pts = pts

        self.graph = defaultdict(list)
        # self.moveable_pts = new_mvable_pts
        # print('pts: \n', self.pts)
        # print(type(self.pts), str(type(self.pts)), type(np.array((2, 4))))
        if type(self.pts) != type(np.array((2, 4))):
            # print(self.pts._value)
            self.tri = Delaunay(self.pts._value)
        else:
            self.tri = Delaunay(self.pts)

        # self.tri = Delaunay(self.pts)

        self.edges = self.generate_edges(self.tri, self.pts)
        self.img = None
        self.img = self.convert_to_img2(self.edges, self.max_range)
        self.update_count = self.update_count + 1
        # self.print_images(graph_name='Vasc_Graph_' + str(self.update_count) + '.png', img_name='Vasc2D_img_' +str(self.update_count)+ '.png')

    def generate_pts(self, min_range, max_range, num_pts, dim, lt_wall, rht_wall, lt_startend, rht_startend):
        pts = np.random.uniform(low=min_range, high=max_range, size=(num_pts, dim))
        pts = [list(pt) for pt in pts]
        moveable_pts = pts
        # print('VasGen Line 280 ', moveable_pts)
        # print('VasGen Line 281 ', pts)
        # print('VasGen Line 282 ', lt_wall)
        # print('VasGen Line 283 ', rht_wall)
        # print('VasGen Line 284 ', lt_startend)
        # print('VasGen Line 285 ', rht_startend)

        # for pt in

        # for pt in list(lt_wall)+list(rht_wall)+list(lt_startend)+list(rht_startend):
        #     pts.append(list(pt))

        # print('VasGen Line 290 ', pts)
        # print('VasGen Line 290 ', np.array(pts))
        # pts.append([list(pt) for pt in lt_wall])
        # pts.append([list(pt) for pt in rht_wall])
        # pts.append([list(pt) for pt in lt_startend])
        # pts.append([list(pt) for pt in rht_startend])

        pts = np.append(pts, lt_wall, axis=0)
        pts = np.append(pts, rht_wall, axis=0)
        pts = np.append(pts, lt_startend, axis=0)
        pts = np.append(pts, rht_startend, axis=0)
        # print(pts)
        # print(np.array(pts))

        pts = np.array(sorted(np.array(pts), key=lambda k: (-k[0], k[1]),  reverse=True))

        # print('VasGen Line 306: \n', pts)

        # os.sys.exit()

        return pts, moveable_pts

    def count_nodes(self, *argv):
        count = 0
        for arg in argv:
            count = count + len(arg)
        return count

    def print_images(self, graph_name='Vasc_Graph.png', img_name='Vasc2D_img.png'):
        fig = plt.figure()
        for j, s in enumerate(self.tri.simplices):
            p = self.pts[s].mean(axis=0)
            plt.text(p[0], p[1], 'Cell #%d' % j, ha='center') # label triangles
        plt.triplot(self.pts[:,0], self.pts[:,1], self.tri.simplices)
        plt.plot(self.pts[:,0], self.pts[:,1], 'o')
        # plt.savefig(graph_name)
        fig.savefig(graph_name)
        plt.close(fig)

        # https://stackoverflow.com/questions/38191855/zero-pad-numpy-array
        img = np.pad(self.img, ((2, 3), (2, 3)), 'constant')
        plt.imsave(img_name, np.rot90(img), cmap='jet')

    def pretty(self, d, indent=0):
        for key, value in d.items():
            print('\t' * indent + str(key))
            if isinstance(value, dict):
                self.pretty(value, indent+1)
            else:
                print('\t' * (indent+1) + str(value))


#!/usr/bin/env python
###################################################################
# basic_example.py : A very simple test script example which include:
#     common_setup
#     Tescases
#     common_cleanup
# The purpose of this sample test script is to show the "hello world"
# of aetest.
###################################################################

# To get a logger for the script
from ats.log.utils import banner
from genie.conf import Genie
import logging
from pyats import aetest

from genie.utils.config import Config

# Get your logger for your script
log = logging.getLogger(__name__)

###################################################################
###                  COMMON SETUP SECTION                       ###
###################################################################

# This is how to create a CommonSetup
# You can have one of no CommonSetup
# CommonSetup can be named whatever you want

class device_setup(aetest.CommonSetup):
    """ Common Setup section """

    # Connect to each device in the testbed'
    @aetest.subsection
    def connect(self, testbed, steps):
        genie_testbed = Genie.init(testbed)
        device_list = []
        device_name = []

        for device in genie_testbed.devices.values():
            with steps.start("Connecting to device '{d}'".format(d=device.name)):
                log.info(banner(
                    "Connecting to device '{d}'".format(d=device.name)))
                try:
                    device.connect()
                except Exception as e:
                    self.failed("Failed to establish connection to '{}'".format(
                        device.name))

                device_list.append(device)
                device_name.append(device.name)
        log.info((device_list))
        aetest.loop.mark(device_commands, devices=device_list, uids=device_name)

###################################################################
###                     TESTCASES SECTION                       ###
###################################################################

# This is how to create a testcase
# You can have 0 to as many testcase as wanted

# Testcase name : tc_one
class device_commands(aetest.Testcase):
    """ This is user Testcases section """

    @ aetest.test
    def parse_running_config(self, devices):
        """ Parsing running config """

        output = devices.execute('show running-config')
        config = Config(output)
        config.tree()

        #  Storing running configuration to use later
        self.config_output = config.config

    @aetest.test
    def disable_source_routing(self, devices):
        """ Disabling ip source-route on device """

        if 'no ip source-route' in self.config_output.keys():
            self.skipped('Device is already configured properly')
        #  Executing 'no ip source-route' on device
        devices.configure("no ip source-route")

if __name__ == '__main__': # pragma: no cover
    aetest.main()


import base64

def encode(secret_string):
    bytes_string = secret_string.encode('ascii')
    code_string = base64.b64encode(bytes_string)
    secret_string_out = code_string.decode('ascii')
    print(f"Encode string is: {secret_string_out} ")

def decode(secret_string):
    bytes_string_out = secret_string.encode('ascii')
    code_string_out = base64.b64decode(bytes_string_out)
    secret_string_out = code_string_out.decode('ascii')
    print(f"Decode string is: {secret_string_out}")

def main():
    user_string = input("Your string is: ")
    action = input("write what you want to do - encode or decode:  ")
    if (action == 'encode'):
        encode(user_string)
    elif (action == 'decode'):
        decode(user_string)
    else:
        print("wrong action !!!")

if __name__ == '__main__':
    main()


'''

This file is for rearranging the reversed vocab tags to have the proper format
<number> <tag> <string>

'''

def number_of_lines(lines):

    num_of_lines = 0

    for line in lines:
        if line[0] != '#':
            num_of_lines += 1

    return num_of_lines

filename = "Vocab.gr"
file = open(filename)
fileLines = file.readlines()

numOfLinesInFile = number_of_lines(fileLines)
vocab = [''] * numOfLinesInFile

for i, line in enumerate(fileLines):
    if line[0] != '#':
        strings = line.split(" ")
        #print(strings)
        vocab[i] = "1 " + strings[1].replace("\n","") + " " + strings[0] + "\n"
        print(vocab[i])

rearrangedVocabFile = open('vocab-rearranged.gr', 'w')
for item in vocab:
    rearrangedVocabFile.write(item)

rearrangedVocabFile.close()

print("parsed grammar rules written to vocab-rearranged.gr")


import vizdoom as vzd

def create_game(config_path: str, color: bool=False, depth: bool=True, label: bool=False,
                automap: bool=False, res: tuple[int, int]=(256, 144), visibility: bool=False, *args, **kwargs) -> vzd.vizdoom.DoomGame:
    """Creates a vizdoom game instance with configurable options

    Args:
        config_path (str): scenario configuration path
        color (bool, optional): color (CRCGCB) or grayscale (GRAY8). Defaults to False.
        depth (bool, optional): depth buffer availability. Defaults to True.
        label (bool, optional): labels buffer availability. Defaults to False.
        automap (bool, optional): automap buffer availability. Defaults to False.
        res (tuple[int, int], optional): internal rendering resolution. Defaults to (256, 144).
        visibility (bool, optional): whether to display game window. Defaults to False.
        asyn (NoneType, optional): keyword argument, if present would set game to asynchronus mode.
        spec (NoneType, optional): keyword argument, if present would set game to spectator mode.
    Returns:
        vzd.vizdoom.DoomGame: _description_
    """

    # create an instance of doom game
    print("Initializing Doom... ", end='')
    game = vzd.DoomGame()

    # remove named arguments set to boolean False or anything representing that
    for key, value in kwargs.items():
        if not value:
            del kwargs[key]

    # load scenario's default configuration
    game.load_config(config_path)

    # set game to sync/async player mode or async spectator mode
    game.set_mode(vzd.Mode.PLAYER) if "asyn" not in kwargs else \
        (game.set_mode(vzd.Mode.ASYNC_PLAYER) if "spec" not in kwargs else \
            game.set_mode(vzd.Mode.ASYNC_SPECTATOR))

    # set rendering options
    exec(f"game.set_screen_resolution(vzd.ScreenResolution.RES_{res[0]:d}X{res[1]:d})")
    exec(f"game.set_screen_format(vzd.ScreenFormat.{'CRCGCB' if color else 'GRAY8'})")
    game.set_window_visible(visibility)

    # no need to set buffer access if human is playing
    if "spec" not in kwargs:
        # set "cheating" buffer access
        game.set_depth_buffer_enabled(depth)
        game.set_labels_buffer_enabled(label)
        game.set_automap_buffer_enabled(automap)
        if "automap_config" in kwargs:
            config = kwargs["automap_config"]
            game.set_automap_mode(config["mode"])
            game.set_automap_rotate(config["rotate"])
            game.set_automap_render_textures(config["texture"])

    # finished initializing the game
    game.init()
    print("done")
    return game


from tkinter import ttk
from tkinter import *
from tkinter.ttk import *
import numpy as np
import math
import pandas as pd
import string

class Application(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)
        self.grid()
        self.create_widgets()
        style = ttk.Style()     # Create style
        style.configure("Blue.TFrame", background="blue") # Set bg color
        self.config(style='Blue.TFrame')    # Apply style to widget

    def create_widgets(self):
        label1 = Label(self, text="Enter Text:")
        label1.grid(row=0,column=0)
        self.txt1 = Entry(self,width=30)
        self.txt1.grid(row=1,column=0)
        label2 = Label(self, text="Enter a key:")
        label2.grid(row=2,column=0)
        self.txt2 = Entry(self,width=30)
        self.txt2.grid(row=3,column=0)
        label3 = Label(self, text="Result:")
        label3.grid(row=4,column=0)
        self.txt3 = Entry(self,width=30)
        self.txt3.grid(row=5,column=0)
        self.button1 = Button(self, text="Encrypt")
        self.button1.grid(row=6,column=0)
        self.button1["command"] = self.encrypt
        self.button2 = Button(self, text="Refresh")
        self.button2.grid(row=7,column=5)
        self.button2["command"] = self.refresh1

        label4 = Label(self, text="Text:")
        label4.grid(row=8,column=0)
        self.txt4 = Entry(self,width=30)
        self.txt4.grid(row=9,column=0)
        label5 = Label(self, text="Key:")
        label5.grid(row=10,column=0)
        self.txt5 = Entry(self,width=30)
        self.txt5.grid(row=11,column=0)
        label6 = Label(self, text="Result:")
        label6.grid(row=12,column=0)
        self.txt6 = Entry(self,width=30)
        self.txt6.grid(row=13,column=0)
        self.button3 = Button(self, text="Decrypt")
        self.button3.grid(row=14,column=0)
        self.button3["command"] = self.decrypt

    def refresh1(self):
        self.txt1.delete(0, "end")
        self.txt1.update()
        self.txt2.delete(0, "end")
        self.txt2.update()
        self.txt3.delete(0, "end")
        self.txt3.update()
        self.txt4.delete(0, "end")
        self.txt4.update()
        self.txt5.delete(0, "end")
        self.txt5.update()
        self.txt6.delete(0, "end")
        self.txt6.update()

    def encrypt(self):
        def caesar(text, step):
            alphabets = (string.ascii_lowercase, string.ascii_uppercase, string.digits)
            def shift(alphabet):
                return alphabet[step:] + alphabet[:step]

            shifted_alphabets = tuple(map(shift, alphabets))
            joined_aphabets = ''.join(alphabets)
            joined_shifted_alphabets = ''.join(shifted_alphabets)
            table = str.maketrans(joined_aphabets, joined_shifted_alphabets)
            return text.translate(table)
        ss = caesar(self.txt1.get(), int(self.txt2.get()))
        self.txt3.insert(INSERT,ss)
        self.txt4.insert(INSERT,self.txt3.get())
        self.txt5.insert(INSERT,self.txt2.get())

    def decrypt(self):
        def caesar1(text, step):
            alphabets = (string.ascii_lowercase, string.ascii_uppercase, string.digits)
            def shift(alphabet):
                return alphabet[step:] + alphabet[:step]

            shifted_alphabets = tuple(map(shift, alphabets))
            joined_aphabets = ''.join(alphabets)
            joined_shifted_alphabets = ''.join(shifted_alphabets)
            table = str.maketrans(joined_shifted_alphabets,joined_aphabets)
            return text.translate(table)
        ss1= caesar1(self.txt4.get(), int(self.txt5.get()))
        self.txt6.insert(INSERT,ss1)

root = Tk()
root.title("Caesar Cipher")
root.geometry("368x352")
app = Application(root)

root.mainloop()


#!/usr/bin/env python3

# I did not plan this out at all and it is the most satisfying thing I've ever seen.
from Environment import Environment
from LambdaStack import LambdaStack
from CommandLine import CommandLine
from Interpreter import Interpreter

class Main:
    """Main execution class. Also servers as a bridge between the View and Controller and the Model."""

    def Main(self):
        """Initialise the system."""
        self.commandLine = CommandLine(self, "> ")
        self.interpreter = self.MakeInterpreter()
        self.commandLine.Splash()
        self.commandLine.Run()

    def MakeInterpreter(self):
        return Interpreter(
            Environment(256), # Initialise the environment with 8-bit cells
            LambdaStack(),
            self.commandLine
        )

    def Quit(self, command):
        raise SystemExit

    def Reset(self, command):
        del self.interpreter
        self.interpreter = self.MakeInterpreter()
        self.commandLine.Log("Sucessfully reset interpreter.")

    def State(self, command):
        self.commandLine.LogState(
            self.interpreter.state.tape,
            (self.interpreter.state.pointer, self.interpreter.state.tape.leftMost, self.interpreter.state.tape.rightMost),
            self.interpreter.stack,
            command.split(' ')
        )

    def RunFile(self, command):
        files = command.split(' ')
        for file in files:
            try:
                with open(file, 'r') as scriptFile:
                    script = scriptFile.read()
            except:
                self.commandLine.Log("Could not open file '{}'".format(file))
            else:
                self.Run(script)

    def Run(self, code):
        try:
            self.interpreter.Execute(code)
        except Exception as e:
            self.commandLine.Log(e)

if __name__ == "__main__":
    main = Main()
    main.Main()


import pika, sys

#establish the connection
connection = pika.BlockingConnection(parameters=pika.ConnectionParameters(host="localhost"))
channel = connection.channel()

#declare direct type exchange
channel.exchange_declare(exchange="tutorial4", exchange_type="direct")

#basically getting log type want to receive
severities  = sys.argv[1:]
if not severities:
    sys.stderr.write("Usage: %s [info] [warning] [error]\n" % sys.argv[0])
    sys.exit(1)

#declare and get the name of queue
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue

#create bind for each log type it want to listen
for severity in severities:
    channel.queue_bind(exchange="tutorial4", queue=queue_name, routing_key=severity)

print(' [*] Waiting for logs. To exit press CTRL+C')

def callback(ch, method, properties, body):
    print(" [x] %r:%r" % (method.routing_key, body))

channel.basic_consume(callback, queue=queue_name, no_ack=True)
channel.start_consuming()


# 3.	Вывести на экран числа от -N до N

# n = int(input('Введите число n: '))
# def elemets(n):
#     for i in range(-n, n+1):
#         print(f'{i}')
#     return i
# print(elemets(n))

n = int(input('Введите число n: '))
def elements(n):
    a = [i for i in range(-n, n + 1)]
    return a
print(elements(n))


import re
from avatar2 import *
from avatar2.peripherals import *
from pandare import *

from .logger import *
from .consts import *

class UARTPeripheral(AvatarPeripheral):
    def hw_read(self, offset, size):
        if offset == 0x18:
            self.status ^= 1
            if self.status == 0:
                return 0x20

        return 0

    def hw_write(self, offset, size, value):
        if offset == 0x0:
            self.logger.info(chr(value))

            return size
        return 0

    def __init__(self, name, address, size, **kwargs):
        AvatarPeripheral.__init__(self, name, address, size)

        self.logger = Logger(camel_to_snake(
            __class__.__name__), logging.INFO, extra_info=False)
        self.status = 0
        self.write_handler[0:size] = self.hw_write
        self.read_handler[0:size] = self.hw_read

class MMIOPeripheral(AvatarPeripheral):
    def hw_read(self, offset, size):
        if offset in self.saved_offsets_with_ret.keys():
            return self.saved_offsets_with_ret[offset]

        if offset in self.offsets_ret_const.keys():
            return self.offsets_ret_const[offset]

        return 0x0

    def hw_write(self, offset, size, value):
        if offset in self.offsets_ret_const.keys():
            return size

        self.saved_offsets_with_ret[offset] = value
        return size

    def __init__(self, name, address, size, **kwargs):
        AvatarPeripheral.__init__(self, name, address, size)

        self.saved_offsets_with_ret = {}
        self.offsets_ret_const = {}
        self.write_handler[0:size] = self.hw_write
        self.read_handler[0:size] = self.hw_read

class ClockPeripheral(MMIOPeripheral):
    def hw_read(self, offset, size):
        if offset in self.offsets_ret_clock.keys():
            return self.offsets_ret_clock[offset](self.cyclic_clock())

        return super().hw_read(offset, size)

    def hw_write(self, offset, size, value):
        if offset in self.offsets_ret_clock.keys():
            self.clock = value
        else:
            super().hw_write(offset, size, value)

        return 1

    def cyclic_clock(self, clock_cycle=0x10000_0000):
        self.clock = ((self.clock + 1) % clock_cycle)
        return self.clock

    def __init__(self, name, address, size, **kwargs):
        super().__init__(name, address, size)
        self.clock = 0
        self.offsets_ret_clock = {}
        self.write_handler[0:size] = self.hw_write
        self.read_handler[0:size] = self.hw_read

class Periph0x4p8e7(MMIOPeripheral):
    def __init__(self, name, address, size, **kwargs):
        MMIOPeripheral.__init__(self, name, address, size)

        self.saved_offsets_with_ret = {
            0x0: NORMAL_MODE,  # modify to change boot mode, alternatives: DUMP_MODE, NORMAL_MODE
        }

class Periph0x8p3e7(MMIOPeripheral):
    def __init__(self, name, address, size, **kwargs):
        MMIOPeripheral.__init__(self, name, address, size)

        self.saved_offsets_with_ret = {
            0x4: 0x03550000, 0x2004: 0x00030000, 0x201c: 0x00000002,
            0x202c: 0x00000001,
            # 0xc034: 0xfffffffc
        }
        self.offsets_ret_const = {
            0x2078: 0x80000000, 0x2090: 0x3f000000,
        }
        self.offsets_ret_clock = {
            # 0x201c: (lambda x: x | 0xffffff00),
            # 0x202c: (lambda x: x | 0xffffff00),
            # 0x2078: (lambda x: x | 0xffffff00),
            # 0x2088: (lambda x: x | 0xffffff00),
            # 0x4308: (lambda x: x | 0xffffff00),
            # 0x2090: (lambda x: x | 0x3e000000)
        }

class Periph0x9p5B4e7(MMIOPeripheral):
    def __init__(self, name, address, size, **kwargs):
        super().__init__(name, address, size)
        self.saved_offsets_with_ret = {
            0x88: 0x2
        }

class Periph0x9p645e7(MMIOPeripheral):
    def __init__(self, name, address, size, **kwargs):
        super().__init__(name, address, size)
        self.saved_offsets_with_ret = {
            0x28: 0x1
        }

def camel_to_snake(name):
    name = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
    return re.sub('([a-z0-9])([A-Z])', r'\1_\2', name).lower()


import pyrebase

from django.conf import settings

firebase = pyrebase.initialize_app(settings.FIREBASE_CONFIG)
storage = firebase.storage()

def upload_to_firebase(img_name,folder_name,path_local):
    path_on_cloud = f'{folder_name}/{img_name}.jpg'
    imgurl = storage.child(path_on_cloud).put(path_local)
    img_url=storage.child(path_on_cloud).get_url(imgurl['downloadTokens'])

    print(img_url)

    return img_url


import numpy as np
from sympy import *

class NonlinearEquations:
    def __init__(self, initial, secant_init_1, secant_init_2, eps, function, function_derivative):
        self.initial = initial
        self.secant_init_1 = secant_init_1
        self.secant_init_2 = secant_init_2
        self.eps = eps
        self.function = function
        self.function_derivative = function_derivative
        self.Newton_solver = None
        self.Secant_solver = None

    def __Newton(self):
        def calculate(x_axis, level):
            x_axis = x_axis - self.function(x_axis) / self.function_derivative(x_axis)
            if self.function(x_axis) < self.eps:
                return x_axis, level
            return calculate(x_axis, level+1)
        self.Newton_solver = list(map(calculate, iter(self.initial), iter(np.ones(len(self.initial)))))

    def __Secant(self):
        def calculate(x_now, x_previous, level):
            x_after = x_now - self.function(x_now) / (self.function(x_now) - self.function(x_previous)) * (x_now - x_previous)
            if self.function(x_after) < self.eps:
                return x_after, level
            return calculate(x_after, x_now, level+1)
        self.Secant_solver = list(map(calculate, self.secant_init_1, self.secant_init_2, iter(np.ones(len(self.initial)))))

    def call(self):
        self.__Newton()
        self.__Secant()

if __name__ == "__main__":
    def f(x):
        return x ** 3 / 3 - x

    def f_derivative(x):
        return x ** 2 - 1

    Newton_init = [0.1, 0.2, 0.9, 9.]
    Secant_init = np.array([[0.0, 0.1], [0.1, 0.2], [0.8, 0.9], [8., 9.]])
    eps = 1e-5
    nonlinear_equations = NonlinearEquations(Newton_init, list(Secant_init[:, 0]),
                                             list(Secant_init[:, 1]), eps, f, f_derivative)
    nonlinear_equations.call()
    print("Newton迭代，初值、根和迭代步数：")
    for i in range(len(Newton_init)):
        print(Newton_init[i], nonlinear_equations.Newton_solver[i][0],
              nonlinear_equations.Newton_solver[i][1])
    print("弦截法，初值、根和迭代步数：")
    for i in range(len(Secant_init)):
        print(Secant_init[i][0], Secant_init[i][1],nonlinear_equations.Secant_solver[i][0],
              nonlinear_equations.Secant_solver[i][1])
    print("done")


# Write your unique_values function here:
def unique_values(my_dictionary):
    unique_vals = {}
    for val in my_dictionary.values():
        if(not val in unique_vals ):
            unique_vals[val] = 1
    return len(unique_vals.keys())
# Uncomment these function calls to test your  function:
print(unique_values({0:3, 1:1, 4:1, 5:3}))
# should print 2
print(unique_values({0:3, 1:3, 4:3, 5:3}))
# should print 1


# %% imports and settings
import json
import os
from functools import wraps
import pandas as pd
import torch
from transformers import (
    AutoModelForCausalLM,
    AutoTokenizer,
)

from typing import Dict, List, Tuple
import argparse
from IPython import get_ipython

# %%
parser = argparse.ArgumentParser()
parser.add_argument(
    "-m",
    "--model-path",
    type=str,
    required=True,
    help="Path to the model to evaluate",
)
parser.add_argument(
    "-d",
    "--data-path",
    type=str,
    required=True,
    help="Path to the data to evaluate",
)
parser.add_argument(
    "-l",
    "--max-new-tokens",
    type=int,
    required=False,
    default=256,
    help="Max number of new tokens to generate",
)
parser.add_argument(
    "-b",
    "--batch-size",
    type=int,
    default=64,
    required=False,
    help="Batch size for generation",
)
# TODO: rename the dir
parser.add_argument(
    "-s",
    "--save-dir",
    type=str,
    required=False,
    default="/mnt/default/eval_results/",
)
parser.add_argument(
    "--replace",
    action="store_true",
    default=False,
    help="Replace the saved file with the generated file",
)

def isnotebook():
    try:
        shell = get_ipython().__class__.__name__
        if shell == "ZMQInteractiveShell":
            return True  # Jupyter notebook or qtconsole
        elif shell == "TerminalInteractiveShell":
            return True  # Terminal running IPython
        else:
            return False  # Other type (?)
    except NameError:
        return False  # Probably standard Python interpreter

if isnotebook():
    args = parser.parse_args(
        args=[
            "--model-path",
            "/home/v-haotiancui/NL2Code/Copilot-2/code2text/GPT-J/results/finetune2-ft-stage2-gpt2-Explanations",
            "--data-path",
            "/home/v-haotiancui/NL2Code/Copilot-2/dataset/QualifiedExplanations.chunks.valid.jsonl",
            "--batch-size",
            "32",
            "--save-dir",
            "/home/v-haotiancui/NL2Code/Copilot-2/code2text/GPT-J/results/",
            "--replace",
        ]
    )
else:
    args = parser.parse_args()

"""
for local test
python eval-gpt-neo.py \
    --model-path /home/v-haotiancui/NL2Code/Copilot-2/code2text/GPT-J/results/finetune2-ft-stage2-gpt2-Explanations \
    --data-path /home/v-haotiancui/NL2Code/Copilot-2/dataset/QualifiedExplanations.chunks.valid.jsonl \
    --batch-size 32 \
    --save-dir /home/v-haotiancui/NL2Code/Copilot-2/code2text/GPT-J/results/ \
    --replace

for amlk8s
python eval-gpt-neo.py \
    --model-path /mnt/default/ft-stage2-gpt2-GithubCodeDocStep1n2Filtered-Jan21-13-24-2022/checkpoint-14750 \
    --data-path /mnt/default/data/QualifiedExplanations.chunks.valid.jsonl \
    --batch-size 64

"""

# print args
print(args)

output_file_jsonl = os.path.join(
    args.save_dir,
    "eval-"
    + ((args.model_path.split("/")[-2] + "-") if "/" in args.model_path else "")
    + args.model_path.split("/")[-1]
    + ".jsonl",
)
output_file_csv = os.path.join(
    args.save_dir,
    "eval-"
    + ((args.model_path.split("/")[-2] + "-") if "/" in args.model_path else "")
    + args.model_path.split("/")[-1]
    + ".csv",
)
# mkdir if needed
if not os.path.exists(args.save_dir):
    os.makedirs(args.save_dir)
if os.path.exists(output_file_jsonl):
    if args.replace:
        print(
            f"Result already exists. Going to replace"
            f" {output_file_jsonl} and {output_file_csv}"
        )
    else:
        print(f"File {output_file_jsonl} already exists, skipping evaluation")
        exit()
print(f"Evaluating model at {args.model_path}")
print(f"Save to {output_file_jsonl}, {output_file_csv}")
# %% load the model
def load_model(model_path: str) -> Tuple[AutoModelForCausalLM, AutoTokenizer]:
    """Load a model from a path.

    Args:
        model_path: Path to the model.

    Returns:
        model: The model.
        tokenizer: The tokenizer.
    """
    model = AutoModelForCausalLM.from_pretrained(model_path)
    # put model to gpu if available
    if torch.cuda.is_available():
        model = model.to("cuda")
    tokenizer = AutoTokenizer.from_pretrained(model_path)
    tokenizer.padding_side = "left"
    if not tokenizer.pad_token:
        tokenizer.pad_token = tokenizer.eos_token
    return model, tokenizer

# read jsonl file
def load_code_doc(data_file: str):
    assert os.path.exists(data_file)
    if data_file.endswith(".jsonl"):
        with open(data_file) as f:
            data = [json.loads(line) for line in f]
        if "docstring" in data[0]:
            docs = [d["docstring"] for d in data]
        else:
            docs = [d["doc"] for d in data]
        block_codes = (
            [d["blocks_codes"] for d in data] if "blocks_codes" in data[0] else None
        )
        codes = [d["code"] for d in data]
    elif data_file.endswith(".json"):
        with open(data_file) as f:
            data = json.load(f)
        docs = [d["docstring"] for d in data]
        block_codes = None
        codes = [d["code"] for d in data]
    return docs, block_codes, codes

# %% make promt
def make_prompt(codes: List[str]) -> List[str]:
    def decorate(code):
        prompt = "# Python 3 \n" + code + '\n\n"""Explanation of what the code does: \n'
        return prompt

    prompts = [decorate(code) for code in codes]
    return prompts

def generate(prompts, tokenizer, model, length=2048, max_new_tokens=2048):
    if max_new_tokens > tokenizer.model_max_length * 0.25:
        raise ValueError(
            f"max_new_tokens larger than 25% of the model maximum length: {tokenizer.model_max_length}."
            " Please reduce it and leave enough length for the input."
        )
    length = min(length, tokenizer.model_max_length - max_new_tokens)
    input = tokenizer(prompts, return_tensors="pt", padding=True, truncation=True)
    # truncate on the left to length
    for k, v in input.items():
        input[k] = input[k][:, -length:]
    input = input.to(model.device)

    length = len(input["input_ids"][0]) + max_new_tokens
    print(f"Generating {length} tokens")
    gen_tokens = model.generate(
        **input,
        do_sample=True,
        temperature=0.1,
        max_length=length,
    )
    gen_text = tokenizer.batch_decode(gen_tokens, skip_special_tokens=True)
    return gen_text

def cut_gentext(raw_text):
    text = raw_text[raw_text.find("code does: \n") + 12 :]
    text = text[: text.find('"""') if text.find('"""') > -1 else len(text)]
    return text

# %% actual run
model, tokenizer = load_model(args.model_path)
docs, block_codes, codes = load_code_doc(args.data_path)
prompts = make_prompt(codes)
batch_size = args.batch_size
max_new_tokens = args.max_new_tokens
res = []
for i in range(0, len(prompts), batch_size):
    print(f"running example {i}/{len(prompts)}")
    batch = prompts[i : i + batch_size]
    gen_text = generate(batch, tokenizer, model, max_new_tokens=max_new_tokens)
    for j, text in enumerate(gen_text):
        d = {
            "gen": cut_gentext(text),
            "raw_gen": text,
            "source": batch[j],
            "reference": docs[i + j],
        }
        res.append(d)

if args.replace or not os.path.exists(output_file_jsonl):
    with open(output_file_jsonl, "w") as f:
        for d in res:
            f.write(json.dumps(d) + "\n")

# also make a csv
if args.replace or not os.path.exists(output_file_csv):
    df = pd.DataFrame(res)
    df.to_csv(output_file_csv, index=True)

# %%


# -*- encoding: utf-8 -*-

from odoo import api, fields, models, registry, _
from odoo.addons.amazon_ept_v10.amazon_emipro_api.mws import Reports,Products
from odoo.exceptions import UserError
import time, datetime, base64, csv, threading, sys
from StringIO import StringIO
from requests import request

class BrowseNode(models.Model):
    _inherit = 'amazon.browse.node.ept'

    # marketplace_id = fields.Many2one('amazon.marketplace.ept', string=u'Marketplace')

    @api.multi
    def name_get(self):
        result = []
        for node in self:
            name = node.name
            id = node.id
            country_name = node.country_id.name
            while True:
                if node.parent_id:
                    name = node.parent_id.name + '/' + name
                    node = node.parent_id
                else:
                    break
            result.append((id, country_name + '/' + name))
        return result


import os
from pyserverchan import pyserver
import time

def watch_python():
    result = "function watch_python():"
    try:
        python_pid = os.popen('pidof python').read().split()
        if len(python_pid) == 1:
            return "No python found!!!"
        result += os.popen(f'top -p {",".join(python_pid)} -c -b -n1').read()
    except BaseException:
        result += "watch_python() failed"
    return result

def watch_folder(file_path):
    result = f"function watch_folder({file_path}):"
    try:
        result += os.popen(f'ls -alh {file_path}').read()
    except BaseException:
        result += f"watch_folder({file_path}) failed"
    return result

def single_watch():
    now_time = time.asctime(time.localtime(time.time()))
    result_python = watch_python()
    result_folder1 = watch_folder("~/user001/thuys/specter_fast/model/")
    result_word2vec = watch_folder("~/user001/thuys/embedding/word2vec/")
    result_glove = watch_folder("~/user001/thuys/embedding/glove/")
    result = os.linesep.join([now_time, result_python, result_folder1, result_word2vec, result_glove])
    result = result.replace(os.linesep, os.linesep + os.linesep)

    if result_python == "No python found!!!":
        result = result_python

    #print(result)
    svc = pyserver.ServerChan()
    svc.output_to_weixin(title='Jiangsu_GPU Server Python Process', content=result)

    if result == "No python found!!!":
        return 1
    return 0

def main():
    no_python_count = 0
    no_python_count += single_watch()
    while no_python_count < 3:
        time.sleep(3600 * 3)
        no_python_count += single_watch()

if __name__ == "__main__":
    main()


#I can write a simple script that automatically launches the browser to a specific address on google maps
#it would be cool if I could run this program and the cmd line args would be the address

import webbrowser, sys, pyperclip

sys.argv #would have the cmd line args e.g ['mapit.py', '870', 'Valencia', 'St.']

#check if cmd line arguments were passed
if len(sys.argv) > 1:
    #['mapit.py', '870', 'Valencia', 'St.'] to '870 Valencia St.'
    address = ' '.join(sys.argv[1:])
else: #assuming user has the address on their clipboard
    address = pyperclip.paste()

# https://www.google.com/maps/place/<ADDRESS>
webbrowser.open('https://www.google.com/maps/place/' + address)

#I'm gonna create a batch file to make it super easy to run this script. Its the mapit.bat
#then in cmd run I type: mapit 870 Valencia St.
#If i have the address copied on my clipboard, I can instead in cmd run type: mapit


from typing import Union

import services

class BarcodeCleaner:
    @staticmethod
    def get_tokens(barcodes: Union[list, str]) -> list:
        if not isinstance(barcodes, list):
            barcodes = barcodes.split(",")
        tokens = [token.split(",") for token in barcodes]
        tokens = services.flatten(tokens)
        tokens = [token.strip() for token in tokens]
        return tokens

    @staticmethod
    def get_google_barcodes_from_info(info):
        tokens = BarcodeCleaner.get_tokens(info)

        tokens = [
            token.lstrip("0")
            for token in tokens
            if len(token) == 13 or (len(token) == 14 and str(token[0]) == "0")
        ]

        google_barcodes = [t for t in tokens if t.isdigit()]

        return list(set(google_barcodes))

    @staticmethod
    def get_clean_barcodes(barcodes):
        # "42424,4234324" -> ["42424,4234324"] -> ["42424", "4234324"]
        tokens = BarcodeCleaner.get_tokens(barcodes)
        b8_13 = [token for token in tokens if len(token) in {8, 13}]
        b14 = [
            token[1:]
            for token in tokens
            if len(token) == 14 and str(token[0]) == "0" and str(token[1]) != "0"
        ]
        clean_barcodes = [b for b in b8_13 + b14 if b.isdigit()]

        return list(set(clean_barcodes))

if __name__ == "__main__":
    print(
        BarcodeCleaner.get_clean_barcodes(
            [
                "2009994000001"
            ]  # "4242424242425,08242424242425, 00000012345678, 8690710140022"
        )
    )
    print(BarcodeCleaner.get_clean_barcodes("4242424242425"))


import pandas as pd

#sampling data
# try:
#     from StringIO import StringIO
# except ImportError:
#     from io import StringIO
# review_file = 'yelp_tip.csv'    # replace this with your data file
# df = pd.read_csv(review_file)
# df_sample = df.sample(frac=0.05)
# df_sample.to_csv("yelp_tip_sample.csv", index=None)

#import files
review = pd.read_csv('yelp_review_sample.csv')
business = pd.read_csv('yelp_business_sample.csv')
print(review.columns)
print(business.columns)
review = review.rename(columns={'date':'review_date', 'stars':'review_stars'})
business = business.rename(columns={'name':'business_name','neighborhood':'bs_neighborhood', 'address': 'bs_address',
                                    'city':'bs_city', 'state':'bs_state', 'postal_code': 'bs_postal_code',
                                    'latitude':'bs_latitude', 'longitude': 'bs_longitude', 'stars':'bs_stars',
                                    'review_count': 'bs_review_count', 'is_open':'bs_is_open',
                                    'categories':'bs_categories'})

#merge files
review_business_merged = pd.merge(review, business, how='inner', on = 'business_id')

#change columns order

review_business_merged= review_business_merged[['review_id', 'user_id', 'business_id','business_name','bs_stars',
                                               'review_stars','text', 'review_date', 'useful', 'funny', 'cool',
                                               'bs_neighborhood','bs_address', 'bs_city','bs_state','bs_postal_code',
                                               'bs_latitude', 'bs_longitude', 'bs_review_count', 'bs_is_open',
                                               'bs_categories']]

review_business_merged.to_csv('business_review_sample.csv', index=False)


import sys
import json
import _thread
import importlib
import threading
from flask import Flask,render_template,request,redirect,url_for
from libs import ip_scan
from libs.management import ConfigManage
from exts import db
from config import devel,prod
from models import Info,Plugin,Batch,Config
from EquipmentScan.Scan import EquipmentScan

app = Flask(__name__)

SURVIVE_IP = 0

app.config.from_object(prod)
if len(sys.argv) > 1:
    extra_config = importlib.import_module('config.%s' % sys.argv[1])
    app.config.from_object(extra_config)

db.init_app(app)

try:
    db.create_all(app=app)
except Exception as e:
    print(e)

@app.route('/')
def _index():
    return redirect(url_for('_scan'))

#扫描页面
@app.route('/scan/',methods=['GET','POST'])
def _scan():
    if request.method == 'GET':
        plugin = Plugin.query.filter().all()
        context = {
            'plugin': plugin,
        }
        return render_template('video-start.html',**context)
    elif request.method == 'POST':
        target = request.form.get('target','')
        plugin_list = request.form.getlist('plugin_list[]')

        def ttt(target, plugin_list):
            survive_ip = ip_scan.ArpScan.survive_scan(target)
            t = threading.Thread(target=EquipmentScan(target, survive_ip, plugin_list).run())
            t.start()

        _thread.start_new_thread(ttt,(target, plugin_list))
        return 'success'

@app.route('/progress_bar/',methods=['GET','POST'])
def _progress_bar():
    if request.method == 'POST':
        batch = Batch.query.filter().order_by(Batch.id.desc()).first()
        info  = []
        if batch:
            for i in batch.information:
                dic = {}
                for key in ['id', 'ip', 'info']:
                    dic[key] = getattr(i, key)
                info.append(dic)
            if not batch.total:
                batch.total = 0
            if not batch.progress:
                batch.progress = 0

            context = {
                'progress': int(batch.progress),
                'info':info,
                'total':int(batch.total),
            }
            return json.dumps(context)
        else:
            context = {
                'progress': 0,
                'info': [],
                'total': 0,
            }
            return json.dumps(context)
    elif request.method == 'GET':
        context = {
            'progress':0,
            'info':[],
            'total':0,
        }
        return render_template('video-being.html', **context)

#配置页面
@app.route('/config/',methods=['GET','POST'])
def _config():
    if request.method == 'GET':
        for i in ['hikvision_camera_slice','hikvision_camera_port','keda_camera_port',
                  'dahua_camera_port','thread_num','port_list''recv_num']:
            i = Config.query.filter(Config.key == i).first()

        hikvision_camera_slice = Config.query.filter(Config.key == 'hikvision_camera_slice').first()
        hikvision_camera_port = Config.query.filter(Config.key == 'hikvision_camera_port').first()
        keda_camera_port = Config.query.filter(Config.key == 'keda_camera_port').first()
        dahua_camera_port = Config.query.filter(Config.key == 'dahua_camera_port').first()

        thread_num = Config.query.filter(Config.key == 'thread_num').first()
        port_list = Config.query.filter(Config.key == 'port_list').first()
        recv_num = Config.query.filter(Config.key == 'recv_num').first()
        context = {
            'hikvision_camera_slice':hikvision_camera_slice,
            'hikvision_camera_port':hikvision_camera_port,
            'keda_camera_port':keda_camera_port,
            'dahua_camera_port':dahua_camera_port,
            'port_list': port_list,
            'thread_num': thread_num,
            'recv_num': recv_num,
        }
        return render_template('config.html',**context)
    elif request.method == 'POST':
        #海康插件变量
        hikvision_camera_port = request.form.get('hikvision_camera_port','')
        hikvision_camera_slice = request.form.get('hikvision_camera_slice','')
        #科达插件变量
        keda_camera_port = request.form.get('keda_camera_port', '')
        #大华插件变量
        dahua_camera_port = request.form.get('dahua_camera_port', '')

        #平台变量
        thread_num = request.form.get('thread_num','')
        port_list = request.form.get('port_list','')
        recv_num = request.form.get('recv_num','')
        dic = {'thread_num':thread_num,'port_list':port_list,'hikvision_camera_port':hikvision_camera_port,
               'hikvision_camera_slice':hikvision_camera_slice,'keda_camera_port':keda_camera_port,
               'dahua_camera_port':dahua_camera_port,'recv_num':recv_num}
        for key,value in dic.items():
            ConfigManage.update(key,value)
        return 'success'

#搜索页面
@app.route('/search/',methods=['GET','POST'])
def _search():
    if request.method == 'GET':
        return render_template('search.html')
    elif request.method == 'POST':
        q = request.form.get('q','')
        if (':' in q) and (q.split(':')[0] == 'pi'):
            info = Batch.query.filter(Batch.id == q.split(':')[1]).first()
            if info:
                info = info.information
            else:info = ''
        else:
            info = Info.query.filter(Info.ip == q).all()
        context = {
            'info': info,
        }
        return render_template('detail.html',**context)


#!/usr/bin/env python3
from pymoos import pymoos
import time

class pingMOOS(pymoos.comms):
    """pingMOOS is an example python MOOS app.
    It basically just connects to the MOOSDB

    Attributes:
        moos_community: a string representing the address of the Community
        moos_port:      an interger defining the port
    """

    def __init__(self, moos_community, moos_port):
        """Initiates MOOSComms, sets the callbacks and runs the loop"""
        super(pingMOOS, self).__init__()
        self.server = moos_community
        self.port = moos_port
        self.name = 'pingMOOS'

        self.set_on_connect_callback(self.__on_connect)
        self.set_on_mail_callback(self.__on_new_mail)

        self.add_active_queue('pong_queue', self.on_pong_message)
        self.add_message_route_to_active_queue('pong_queue', 'PONG')

        self.run(self.server, self.port, self.name)

    def __on_connect(self):
        """OnConnect callback"""
        print("Connected to", self.server, self.port,
              "under the name ", self.name)
        self.register ('PING', 0) # just to prove that the callback work
        return self.register('PONG', 0)

    def __on_new_mail(self):
        """OnNewMail callback"""
        for msg in self.fetch():
            print("OnNewMail caught", msg.key(), "!")
        return True

    def on_pong_message(self, msg):
        """Special callback for PONG"""
        print("on_pong_message activated by",
              msg.key(), "with value", msg.double())
        return True

def main():
    pinger = pingMOOS('localhost', 9002)

    while True:
        time.sleep(1)
        pinger.notify('PING', 'Hello world!', -1);

if __name__ == "__main__":
    main()


from absl.testing import parameterized

import numpy as np

from tensorflow.python.eager import context
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.framework import indexed_slices
from tensorflow.python.framework import ops
from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gradients_impl
from tensorflow.python.ops.ragged import ragged_factory_ops
from tensorflow.python.ops.ragged import ragged_gather_ops
from tensorflow.python.ops.ragged import ragged_tensor
from tensorflow.python.platform import googletest

@test_util.run_all_in_graph_and_eager_modes
class RaggedGatherOpTest(test_util.TensorFlowTestCase, parameterized.TestCase):

  @parameterized.named_parameters([
      # Basic gather (axis=0 and batch_dims=0)
      dict(testcase_name='Params1DTensor_Indices1DTensor',
           params=['a', 'b', 'c', 'd', 'e'],
           indices=[2, 0, 2, 1],
           expected=['c', 'a', 'c', 'b']),
      dict(testcase_name='Params1DTensor_Indices2DRagged',
           params=['a', 'b', 'c', 'd', 'e'],
           indices=[[3, 1, 2], [1], [], [0]],
           expected=[['d', 'b', 'c'], ['b'], [], ['a']]),
      dict(testcase_name='Params2DRagged_Indices0DTensor',
           params=[['a', 'b'], ['c', 'd', 'e'], ['f'], [], ['g']],
           indices=1,
           expected=['c', 'd', 'e']),
      dict(testcase_name='Params2DRagged_Indices1DTensor',
           params=[['a', 'b', 'c'], ['d'], [], ['e']],
           indices=[3, 1, 2, 1, 0],
           expected=[
               ['e'], ['d'], [], ['d'], ['a', 'b', 'c']]),
      dict(testcase_name='Params2DRagged_Indices2DRagged',
           params=[['a', 'b', 'c'], ['d'], [], ['e']],
           indices=[[3, 1, 2], [1], [], [0]],
           expected=[
               [['e'], ['d'], []], [['d']], [], [['a', 'b', 'c']]]),
      dict(testcase_name='Params3DRagged_Indices2DTensor',
           params=[
               [['a', 'b'], []], [['c', 'd'], ['e'], ['f']], [['g']]],
           indices=[[1, 2], [0, 1], [2, 2]],
           indices_ragged_rank=0,
           expected=[
               [[['c', 'd'], ['e'], ['f']], [['g']]],
               [[['a', 'b'], []], [['c', 'd'], ['e'], ['f']]],
               [[['g']], [['g']]]]),
      dict(testcase_name='Params3DRagged_Indices3DTensor',
           params=[[['a', 'b'], []],
                   [['c', 'd'], ['e'], ['f']],
                   [['g']]],
           indices=[[[1, 2], [0, 1], [2, 2]], [[0, 0], [1, 2], [0, 1]]],
           indices_ragged_rank=0,
           expected=[
               [[[['c', 'd'], ['e'], ['f']], [['g']]],
                [[['a', 'b'], []], [['c', 'd'], ['e'], ['f']]],
                [[['g']], [['g']]]],
               [[[['a', 'b'], []], [['a', 'b'], []]],
                [[['c', 'd'], ['e'], ['f']], [['g']]],
                [[['a', 'b'], []], [['c', 'd'], ['e'], ['f']]]]]),
      dict(testcase_name='Params1DTensor_Indices4DRaggedRank2',
           params=['a', 'b', 'c', 'd', 'e', 'f', 'g'],
           indices=[[[[3, 4], [0, 6]], []],
                    [[[2, 1], [1, 0]], [[2, 5]], [[2, 3]]],
                    [[[1, 0]]]],
           indices_ragged_rank=2,
           expected=[
               [[['d', 'e'], ['a', 'g']], []],
               [[['c', 'b'], ['b', 'a']], [['c', 'f']], [['c', 'd']]],
               [[['b', 'a']]]]),
      # Batch gather (batch_dims=1)
      dict(testcase_name='Batch1D_Params2DRagged_Indices1DTensor',
           params=[['a', 'b'], ['c'], ['d', 'e', 'f', 'g'], ['h']],
           indices=[1, 0, 3, 0],
           batch_dims=1,
           expected=['b', 'c', 'g', 'h']),
      dict(testcase_name='Batch1D_Params2DRagged_Indices2DTensor',
           params=[['a', 'b'], ['c'], ['d', 'e', 'f', 'g'], ['h']],
           indices=[[1, 0], [0, 0], [3, 1], [0, 0]],
           indices_ragged_rank=0,
           batch_dims=1,
           expected=[['b', 'a'], ['c', 'c'], ['g', 'e'], ['h', 'h']]),
      dict(testcase_name='Batch1D_Params2DRagged_Indices2DRagged',
           params=[['a', 'b'], ['c'], ['d', 'e', 'f', 'g'], ['h']],
           indices=[[1, 0], [], [3, 2, 1], [0]],
           batch_dims=1,
           expected=[['b', 'a'], [], ['g', 'f', 'e'], ['h']]),
      dict(testcase_name='Batch1D_Params3DRagged_Indices3DRagged',
           params=[[['a'], ['b', 'c']],
                   [],
                   [['d', 'e', 'f'], ['g'], ['h', 'i'], ['j']],
                   [['k']]],
           indices=[[[1, 0], []], [], [[3, 2, 1], [0]], [[0]]],
           batch_dims=1,
           expected=[[[['b', 'c'], ['a']], []],
                     [],
                     [[['j'], ['h', 'i'], ['g']], [['d', 'e', 'f']]],
                     [[['k']]]]),
      # Batch gather (batch_dims=2)
      dict(testcase_name='Batch2D_Params3DRagged_Indices2DRagged',
           params=[[['a', 'b', 'c'], ['d', 'e'], ['f']],
                   [['g'], ['h', 'i']]],
           indices=[[0, 1, 0], [0, 1]],
           batch_dims=2,
           expected=[['a', 'e', 'f'], ['g', 'i']]),
      dict(testcase_name='Batch2D_Params3DRagged_Indices3DRagged',
           params=[[['a', 'b', 'c'], ['d', 'e'], ['f']],
                   [['g'], ['h', 'i']]],
           indices=[[[2, 1, 0], [1, 1], [0]], [[0], []]],
           batch_dims=2,
           expected=[[['c', 'b', 'a'], ['e', 'e'], ['f']], [['g'], []]]),
      # Batch gather (batch_dims=3)
      dict(testcase_name='Batch3D_Params4DRagged_Indices3DRagged',
           params=[[[['a', 'b', 'c'], ['d', 'e'], ['f']],
                    [['g'], ['h', 'i']]], [[['j']]]],
           indices=[[[0, 1, 0], [0, 1]], [[0]]],
           batch_dims=3,
           expected=[[['a', 'e', 'f'], ['g', 'i']], [['j']]]),
      # Axis gather (axis=1)
      dict(testcase_name='Params2DRagged_Indices0DTensor_axis_1',
           params=[['a', 'b'], ['c', 'd', 'e'], ['f', 'g'], ['h', 'i', 'j'],
                   ['k', 'l']],
           indices=1,
           axis=1,
           expected=['b', 'd', 'g', 'i', 'l']),
      dict(testcase_name='Params2DRagged_Indices1DTensor_axis_1',
           params=[['a', 'b'], ['c', 'd', 'e'], ['f', 'g'], ['h', 'i', 'j'],
                   ['k', 'l']],
           indices=[1, 0],
           axis=1,
           expected=[['b', 'a'], ['d', 'c'], ['g', 'f'], ['i', 'h'],
                     ['l', 'k']]),
      dict(testcase_name='Params3DRagged_Indices0DTensor_axis_1',
           params=[[['a', 'b'], ['c', 'd', 'e']],
                   [['f', 'g'], ['h', 'i', 'j'], ['k', 'l']]],
           indices=1,
           axis=1,
           expected=[['c', 'd', 'e'], ['h', 'i', 'j']]),
      dict(testcase_name='Params3DRagged_Indices1DTensor_axis_1',
           params=[[['a', 'b'], ['c', 'd', 'e']],
                   [['f', 'g'], ['h', 'i', 'j'], ['k', 'l']]],
           indices=[1, 0],
           axis=1,
           expected=[[['c', 'd', 'e'], ['a', 'b']],
                     [['h', 'i', 'j'], ['f', 'g']]]),
      # Batch/axis gather, batch = 1, axis > batch
      dict(testcase_name='Params3DRagged_Indices1DTensor_batch_1_axis_2',
           params=[[['a', 'b'], ['c', 'd', 'e']],
                   [['f', 'g'], ['h', 'i', 'j'], ['k', 'l']]],
           indices=[1, 0],
           axis=2,
           batch_dims=1,
           expected=[['b', 'd'], ['f', 'h', 'k']]),
      dict(testcase_name='Params4DRagged_Indices1DTensor_batch_1_axis_2',
           params=[[[['a', 'b'], ['c', 'd', 'e']]],
                   [[['f', 'g']], [['h', 'i', 'j'], ['k', 'l']]]],
           indices=[0, 1],
           axis=2,
           batch_dims=1,
           expected=[[['a', 'b']],
                     [['h', 'i', 'j'], ['k', 'l']]]),
  ])  # pyformat: disable
  def testRaggedGather(self,
                       params,
                       indices,
                       expected,
                       axis=None,
                       batch_dims=0,
                       params_ragged_rank=None,
                       indices_ragged_rank=None):
    params = ragged_factory_ops.constant(params, ragged_rank=params_ragged_rank)
    indices = ragged_factory_ops.constant(
        indices, ragged_rank=indices_ragged_rank)
    actual = ragged_gather_ops.gather(
        params, indices, axis=axis, batch_dims=batch_dims)
    self.assertAllEqual(actual, self._str_to_bytes(expected))

  def _str_to_bytes(self, x):
    if isinstance(x, list):
      return [self._str_to_bytes(v) for v in x]
    elif isinstance(x, str) and bytes is not str:
      return bytes(x, 'utf-8')
    else:
      return x

  def testOutOfBoundsError(self):
    tensor_params = ['a', 'b', 'c']
    tensor_indices = [0, 1, 2]
    ragged_params = ragged_factory_ops.constant([['a', 'b'], ['c']])
    ragged_indices = ragged_factory_ops.constant([[0, 3]])
    with self.assertRaisesRegex(errors.InvalidArgumentError,
                                r'indices\[1\] = 3 is not in \[0, 3\)'):
      self.evaluate(ragged_gather_ops.gather(tensor_params, ragged_indices))
    with self.assertRaisesRegex(errors.InvalidArgumentError,
                                r'indices\[2\] = 2 is not in \[0, 2\)'):
      self.evaluate(ragged_gather_ops.gather(ragged_params, tensor_indices))
    with self.assertRaisesRegex(errors.InvalidArgumentError,
                                r'indices\[1\] = 3 is not in \[0, 2\)'):
      self.evaluate(ragged_gather_ops.gather(ragged_params, ragged_indices))

  def testUnknownIndicesRankError(self):
    if context.executing_eagerly():
      return
    params = ragged_factory_ops.constant([], ragged_rank=1)
    indices = constant_op.constant([0], dtype=dtypes.int64)
    indices = array_ops.placeholder_with_default(indices, None)
    self.assertRaisesRegex(ValueError,
                           r'rank\(indices\) must be known statically',
                           ragged_gather_ops.gather, params, indices)

  # pylint: disable=bad-whitespace
  @parameterized.parameters([
      # params.shape=[2, None]; indices.shape=[3]
      dict(
          params        = [[1.0, 2.0], [3.0, 4.0, 5.0]],
          indices       = [0, 0, 1],
          expected_out  = [[1.0, 2.0], [1.0, 2.0], [3.0, 4.0, 5.0]],
          out_grad      = [[0.1, 0.2], [0.3, 0.4], [0.5, 0.6, 0.7]],
          expected_grad = [[0.4, 0.6], [0.5, 0.6, 0.7]]),
      # params.shape=[2, None]; indices.shape=[0]
      dict(
          params        = [[1, 2], [3, 4, 5]],
          indices       = [],
          expected_out  = [],
          out_grad      = [],
          expected_grad = [[0, 0], [0, 0, 0]]),
      # params.shape=[2, None]; indices.shape=[2, 2]
      dict(
          params        = [[1.0, 2.0], [3.0, 4.0, 5.0]],
          indices       = [[0, 0], [1, 0]],
          expected_out  = [[[1.0, 2.0], [1.0, 2.0]],
                           [[3.0, 4.0, 5.0], [1.0, 2.0]]],
          out_grad      = [[[0.1, 0.2], [0.3, 0.4]],
                           [[0.5, 0.6, 0.7], [0.8, 0.9]]],
          expected_grad = [[1.2, 1.5], [0.5, 0.6, 0.7]]),
      # params.shape=[3, None, None]; indices.shape=[3]
      dict(
          params        = [[[1, 2], [3, 4, 5]], [[6.0]], [[7.0, 8.0]]],
          indices       = [2, 1, 2],
          expected_out  = [[[7.0, 8.0]], [[6.0]], [[7.0, 8.0]]],
          out_grad      = [[[0.1, 0.2]], [[0.3]], [[0.4, 0.5]]],
          expected_grad = [[[0, 0], [0, 0, 0]], [[0.3]], [[0.5, 0.7]]]),
      # params.shape=[3, None, None]; indices.shape=[0]
      dict(
          params        = [[[1, 2], [3, 4, 5]], [[6.0]], [[7.0, 8.0]]],
          indices       = [2, 1, 2],
          expected_out  = [[[7.0, 8.0]], [[6.0]], [[7.0, 8.0]]],
          out_grad      = [[[0.1, 0.2]], [[0.3]], [[0.4, 0.5]]],
          expected_grad = [[[0, 0], [0, 0, 0]], [[0.3]], [[0.5, 0.7]]]),
      # params.shape=[0, None]; indices.shape=[0]
      dict(
          params        = [],
          indices       = [],
          expected_out  = [],
          out_grad      = [],
          expected_grad = [],
          params_ragged_rank = 1),
      # params.shape=[2, None, 2]; indices.shape=[3]
      dict(
          params        = [[[1, 2], [3, 4]], [], [[5, 6]]],
          indices       = [1, 1, 2, 0, 2],
          expected_out  = [[], [], [[5, 6]], [[1, 2], [3, 4]], [[5, 6]]],
          out_grad      = [[], [], [[1, 2]], [[3, 4], [5, 6]], [[7, 7]]],
          expected_grad = [[[3, 4], [5, 6]], [], [[8, 9]]],
          params_ragged_rank = 1),
  ])  # pyformat: disable
  @test_util.run_deprecated_v1
  def testGradient(self,
                   params,
                   indices,
                   expected_out,
                   out_grad,
                   expected_grad,
                   params_ragged_rank=None):
    """Tests that ragged_gather generates the right gradient.

    Args:
      params: The `params` that should be passed to `gather`.
      indices: The `indices` that should be passed to `gather`.
      expected_out: The expected value of `gather(params, indices)`.
        `expected_out.shape = indices.shape + params.shape[1:]`.
      out_grad: The value that should be fed in as the gradient for `out`
        when testing the gradient of `ragged_gather`.  Must have the same
        shape as `expected_out`.
      expected_grad: The expected gradient for that should be returned for
        `params`.  Must have hte same shape as `params`.
      params_ragged_rank: The ragged_rank of `params`.
    """
    if context.executing_eagerly():
      return

    params = ragged_factory_ops.constant(
        params, dtype=dtypes.float32, ragged_rank=params_ragged_rank)
    indices = constant_op.constant(indices, dtype=dtypes.int32)
    out_ragged_rank = params.ragged_rank + indices.shape.ndims - 1
    out_grad = ragged_factory_ops.constant(
        out_grad, dtype=dtypes.float32, ragged_rank=out_ragged_rank)
    expected_out = ragged_factory_ops.constant(
        expected_out, dtype=dtypes.float32, ragged_rank=out_ragged_rank)
    expected_grad = ragged_factory_ops.constant(
        expected_grad,
        dtype=dtypes.float32,
        ragged_rank=params.ragged_rank)

    out = ragged_gather_ops.gather(params, indices)
    self.assertAllClose(out, expected_out)

    grads = gradients_impl.gradients(
        out.flat_values,
        (params.nested_row_splits + (params.flat_values, indices,)),
        out_grad.flat_values)
    param_nested_splits_grads = grads[:-2]
    params_flat_values_grad = grads[-2]
    indices_grad = grads[-1]
    self.assertEqual(indices_grad, None)
    for splits_grad in param_nested_splits_grads:
      self.assertEqual(splits_grad, None)

    # The gradient generates an IndexedSlices; convert back to a normal Tensor.
    self.assertIsInstance(params_flat_values_grad, indexed_slices.IndexedSlices)
    params_flat_values_grad = ops.convert_to_tensor(params_flat_values_grad)

    params_grad = params.with_flat_values(params_flat_values_grad)
    self.assertAllClose(params_grad, expected_grad, atol=2e-6, rtol=2e-6)

  @parameterized.parameters([
      # Basic gather (batch_dims == 0, axis == 0)
      dict(params_shape=[3, 4], indices_shape=[], axis=0),
      dict(params_shape=[3, 4], indices_shape=[5], axis=0),
      dict(params_shape=[3, 4], indices_shape=[2, 5], axis=0),
      # Gather over axis (axis > 0)
      dict(params_shape=[3, 4], indices_shape=[], axis=1),
      dict(params_shape=[3, 4], indices_shape=[2], axis=1),
      dict(params_shape=[3, 4], indices_shape=[2, 5], axis=1),
      dict(params_shape=[7, 3, 1], indices_shape=[2, 4], axis=1),
      dict(params_shape=[3, 4, 5, 6], indices_shape=[2, 1, 7], axis=1),
      dict(params_shape=[7, 3, 5], indices_shape=[], axis=2),
      dict(params_shape=[7, 3, 5], indices_shape=[2], axis=2),
      dict(params_shape=[7, 3, 5], indices_shape=[4, 2], axis=2),
      dict(params_shape=[7, 3, 5, 6], indices_shape=[4, 2], axis=2),
      dict(params_shape=[7, 3, 5, 6], indices_shape=[], axis=3),
      dict(params_shape=[7, 3, 5, 6], indices_shape=[4], axis=3),
      dict(params_shape=[7, 3, 5, 6], indices_shape=[8, 4], axis=3),
      dict(params_shape=[7, 3, 5, 6], indices_shape=[2, 3, 2, 3], axis=3),
      # Batched gather (batch_dims > 0)
      dict(params_shape=[7, 3], indices_shape=[7], batch_dims=1),
      dict(params_shape=[7, 3], indices_shape=[7, 5], batch_dims=1),
      dict(params_shape=[5, 3], indices_shape=[5, 7, 4, 2], batch_dims=1),
      dict(params_shape=[2, 3, 6], indices_shape=[2], batch_dims=1),
      dict(params_shape=[7, 3, 6], indices_shape=[7, 5, 4, 2], batch_dims=1),
      dict(params_shape=[7, 3, 5], indices_shape=[7, 3], batch_dims=2),
      dict(params_shape=[7, 3, 5], indices_shape=[7, 3, 2], batch_dims=2),
      dict(params_shape=[7, 3, 5, 6], indices_shape=[7, 3, 5], batch_dims=3),
      dict(params_shape=[2, 3, 5, 6], indices_shape=[2, 3, 5, 7], batch_dims=3),
      # Batched gather with axis (axis > batch_dims > 0)
      dict(params_shape=[2, 3, 6], indices_shape=[2], axis=2, batch_dims=1),
      dict(params_shape=[2, 3, 6], indices_shape=[2, 4], axis=2, batch_dims=1),
      dict(
          params_shape=[3, 1, 6, 7], indices_shape=[3, 4], axis=3,
          batch_dims=1),
      dict(
          params_shape=[3, 2, 6, 7], indices_shape=[3, 4], axis=3,
          batch_dims=1),
      dict(
          params_shape=[2, 3, 6, 7], indices_shape=[2, 3], axis=3,
          batch_dims=2),
  ])
  def testMatchesDenseGather(self,
                             params_shape,
                             indices_shape,
                             axis=None,
                             batch_dims=0):
    # Build random params & indices matrics w/ the expected shapes.
    if axis is None:
      axis = batch_dims
    params = np.random.randint(100, size=params_shape, dtype=np.int32)
    indices = np.random.randint(
        params_shape[axis], size=indices_shape, dtype=np.int32)

    # Use array_ops.gather to get the expected value.
    expected = array_ops.gather(
        params, indices, axis=axis, batch_dims=batch_dims)

    # Build ragged tensors with varying ragged_ranks from params & axis.
    params_tensors = [params] + [
        ragged_tensor.RaggedTensor.from_tensor(params, ragged_rank=i)
        for i in range(1, len(params_shape))
    ]
    indices_tensors = [indices] + [
        ragged_tensor.RaggedTensor.from_tensor(indices, ragged_rank=i)
        for i in range(1, len(indices_shape))
    ]

    # For each combination of params & axis tensors, check that
    # ragged_gather_ops.gather matches array_ops.gather.
    for params_tensor in params_tensors:
      for indices_tensor in indices_tensors:
        actual = ragged_gather_ops.gather(
            params_tensor, indices_tensor, axis=axis, batch_dims=batch_dims)
        if isinstance(actual, ragged_tensor.RaggedTensor):
          actual = actual.to_tensor()
        self.assertAllEqual(
            expected, actual, 'params.ragged_rank=%s, indices.ragged_rank=%s' %
            (getattr(params_tensor, 'ragged_rank',
                     0), getattr(indices_tensor, 'ragged_rank', 0)))

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


# This Python 3 environment comes with many helpful analytics libraries installed

# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python

# For example, here's several helpful packages to load in

import numpy as np # linear algebra

import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

import matplotlib.pyplot as plt

import seaborn as sns

# Input data files are available in the "../input/" directory.

# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory

import os

for dirname, _, filenames in os.walk('/kaggle/input'):

    for filename in filenames:

        print(os.path.join(dirname, filename))

# Any results you write to the current directory are saved as output.
train_data = pd.read_csv("/kaggle/input/cat-in-the-dat/train.csv", index_col='id')

test_data = pd.read_csv("/kaggle/input/cat-in-the-dat/test.csv", index_col='id')
train_data.head()
y = train_data.pop('target')
print("Training data shape =", train_data.shape)

print("Testing data shape =", test_data.shape)
null_val_train = [(x, y) for (x, y) in train_data.isnull().sum().items() if y > 0]

null_val_test = [(x, y) for (x, y) in test_data.isnull().sum().items() if y > 0]

print("Null Values in training data =", len(null_val_train))

print("Null Values in testing data =", len(null_val_test))
for col in train_data.columns:

    print(col, train_data[col].nunique())
full_data = pd.concat([train_data, test_data], axis=0)

train_rows = train_data.shape[0]

del train_data

del test_data

full_data.shape
full_data['bin_3'] = full_data['bin_3'].map({'T': 1, 'F': 0})

full_data['bin_4'] = full_data['bin_4'].map({'Y': 1, 'N': 0})
for col in ['ord_1', 'ord_2', 'ord_3', 'ord_4']:

    print(col, list(np.unique(full_data[col])))
full_data['ord_5_len'] = full_data['ord_5'].map(len)

full_data['ord_5_len'] -= 2

full_data['ord_5_len'].map(abs).any()
m1 = {'Contributor': 1, 'Expert': 2, 'Grandmaster': 4, 'Master': 3, 'Novice': 0}

full_data['ord_1'] = full_data['ord_1'].map(m1)

m2 = {'Boiling Hot': 4, 'Cold': 1, 'Freezing': 0, 'Hot': 3, 'Lava Hot': 5, 'Warm': 2}

full_data['ord_2'] = full_data['ord_2'].map(m2)

full_data['ord_3'] = full_data['ord_3'].apply(lambda x: ord(x) - ord('a'))

full_data['ord_4'] = full_data['ord_4'].apply(lambda x: ord(x) - ord('A'))

full_data['ord_5a'] = full_data['ord_5'].str[0]

full_data['ord_5b'] = full_data['ord_5'].str[1]

full_data['ord_5a'] = full_data['ord_5a'].map({val : idx for idx, val in enumerate(np.unique(full_data['ord_5a']))})

full_data['ord_5b'] = full_data['ord_5b'].map({val : idx for idx, val in enumerate(np.unique(full_data['ord_5b']))})

full_data.drop(['ord_5', 'ord_5_len'], axis=1, inplace=True)
full_data[['nom_7', 'nom_8', 'nom_9']].head()
full_data.drop(['nom_7', 'nom_8', 'nom_9'], axis=1, inplace=True)
full_data['day'] = full_data['day']/7.0

full_data['month'] = full_data['month']/12.0
full_data = pd.get_dummies(data=full_data, columns=['nom_0', 'nom_1', 'nom_2', 'nom_3', 'nom_4', 'nom_5', 'nom_6'], prefix_sep='_', sparse=True)
full_data.head()
train_data = full_data[:train_rows]

test_data = full_data[train_rows:]

del full_data
train_data.shape
from sklearn.linear_model import LogisticRegression

lr = LogisticRegression(solver='sag', class_weight='balanced', random_state=0, max_iter=200, n_jobs=-1)
from sklearn.model_selection import GridSearchCV

from sklearn.model_selection import StratifiedKFold

kfold = StratifiedKFold(n_splits=5, random_state=0,)

params = {'C': [0.79]}

grid = GridSearchCV(estimator=lr,

                  param_grid=params,

                  cv=kfold

                  )
grid.fit(train_data, y)
model = grid.best_estimator_

print(grid.best_score_)
y_pred = model.predict_proba(test_data)
y_pred = y_pred[:, 1]
y_pred = pd.Series(y_pred)

test_df = pd.DataFrame([test_data.index, y_pred]).transpose()

test_df.columns = ['id', 'target']
test_df['id'] = test_df['id'].astype(int)

test_df.head()
test_df.to_csv('submission.csv', index=False)


#! /usr/bin/env python3

import os.path
import glob
import json

backlight_dir = glob.glob("/sys/class/backlight/*")[0]

def get_from_file(name):
    with open(os.path.join(backlight_dir, name), "r") as f:
        return int(f.read())

max_brightness = get_from_file("max_brightness")

class Py3status:
    cache_timeout = 0

    def brightness(self):
        current = get_from_file("brightness")

        return {
            "full_text": "BRT " + str(int(100 * (current / max_brightness))) + "%",
        }

if __name__ == "__main__":
    s = Py3status()
    print(json.dumps(s.brightness(), indent=4))


import os
import textwrap
from typing import List
from uuid import uuid4
from environment import AUDIO_CUT_TIME, TEXT_CONFIG, tmp_dir
from common.SentenceInfo import SentenceInfo

def get_text_overlay_filter(text: str, start_time: float, end_time: float) -> str:
	font_size = TEXT_CONFIG.FONT_SIZE
	font_file = TEXT_CONFIG.FONT_PATH
	font_color = TEXT_CONFIG.FONT_COLOR
	x = TEXT_CONFIG.X_COEF
	y = TEXT_CONFIG.Y_COEF

	use_box = TEXT_CONFIG.BOX
	box_w = TEXT_CONFIG.BOX_W
	box_color = TEXT_CONFIG.BOX_COLOR

	text = textwrap.fill(text, width=TEXT_CONFIG.CHARS_PER_LINE)

	text_path = os.path.join(tmp_dir, uuid4().hex)
	with open(text_path, 'w') as f:
		f.write(text)

	timing_config = f"enable='between(t,{start_time},{end_time})'"
	styling_config = f"fontsize={font_size}:fontcolor={font_color}:fontfile={font_file}"
	box_config = f"box={use_box}:boxborderw={box_w}:boxcolor={box_color}"
	return f"drawtext=textfile='{text_path}':{styling_config}:x={x}*w:y={y}*h:{timing_config}:{box_config}"

def get_text_filter(sentences: List[SentenceInfo], source: str, dest: str) -> str:
	filters = []
	start_time = 0
	for s in sentences:
		end_time = start_time + s.length
		filters.append(get_text_overlay_filter(s.text, start_time, end_time - 0.1))
		start_time = end_time

	filters_str = f'{dest};{dest}'.join(filters)
	return f'{source}{filters_str}{dest}'

def convert_seconds_to_time(seconds: float) -> str:
	hours = int(seconds // 3600)
	minutes = int((seconds % 3600) // 60)
	seconds = int(seconds % 60)

	return f'{hours:02d}:{minutes:02d}:{seconds:02d}'

def get_input_command(path: str, end_time: float, start_time: float = 0) -> str:
	return f'-ss {start_time} -t {end_time} -i "{path}"'

def get_audio_input(sentences: List[SentenceInfo]) -> str:
	inputs = []
	for s in sentences:
		inputs.append(get_input_command(s.audio_path, s.length, AUDIO_CUT_TIME))

	return " ".join(inputs)

def get_audio_concat(start_index: int, end_index: int, final_name: str) -> str:
	no_streams = end_index - start_index + 1
	filter = ""
	for i in range(start_index, end_index + 1):
		filter += f'[{i}:a]'
	filter += f'concat=n={no_streams}:v=0:a=1'
	filter += final_name
	return filter


import requests
import pandas as pd
import json

def callAPI(key, videoId):
  return requests.get('https://www.googleapis.com/youtube/v3/videos',
              params={
                  'key': key,
                  'part': 'statistics',
                  'id': videoId
              })

def statistics(key, videoId):
    response = callAPI(key, videoId).json()
    statistics = response['items'][0]['statistics']
    return statistics


arr = 1
res = [0 for x in range(10)]
for _ in range(3):
    num = int(input())
    arr *= num
arr = str(arr)
for i in arr:
    res[int(i)] += 1
for j in res:
    print(j)


import urllib
import urllib2
from core import base
try:
    import json
except ImportError:
    import simplejson as json

class IMDB(base.baseClass):
    @classmethod
    def imdb(cls, search):
        data = urllib2.urlopen('http://www.imdbapi.com/?' + urllib.urlencode({'t': search})).read()
        return json.loads(data)

    def on_privmsg(self, address, target, text):
        if text[0] in base.prefix and text.strip().split(' ', 1)[0][1:] == 'imdb' and len(text.split()) >= 2:
            search = ' '.join(text.split()[1:])
            if len(search) > 0:
                try:
                    imdbdata = self.imdb(search)
                except (urllib2.HTTPError, ValueError) as e:
                    self.irc.msg(target, 'Unable to retrieve IMDB information')
                else:
                    if 'Response' in result and result['Response'] == 'False':
                        msg = '[IMDB] Nothing found'
                    elif 'Response' in result and result['Response'] == 'True':
                        msg = '[IMDB] {Title} ({Year}). Genre: {Genre}. Director: {Director}. Rating: {imdbRating}. Runtime: {Runtime}. http://imdb.com/title/{imdbID}/'.format(**result)
                    self.irc.msg(target, msg.split('\n')[0])


import yaml

class Route(yaml.YAMLObject):
    """Symbolic base class for routes"""
    yaml_tag = u'!route'

    def __init__(self, service_name, class_name, service, prefix):
        self.service_name = service_name
        self.class_name = class_name
        self.service = service
        self.prefix = prefix
        self.is_main_route = (prefix == 'main')

    @classmethod
    def from_dict(cls, service_name=None, class_name=None, service=None, prefix=None, **kwargs):
        return cls(service_name, class_name, service, prefix)


# nested if - if inside if

e_name = input("Enter your name : ")
e_age = int(input("Enter your age : "))

if e_age >= 18:
    qualification = int(input("Enter your qualification : "))
    if qualification >= 15:
        experience = float(input("Enter your experience (in years) : "))
        if experience >= 1:
            print("Congrats! You are hired!")
        else:
            print("Please do an internship and re-apply in our company post that. Thank You!")
    else:
        print("Please complete your education and re-apply in our company")
else:
    print("Sorry you are still a kid!")


import asyncio
import logging

from aiogram import Bot, Dispatcher
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.contrib.fsm_storage.redis import RedisStorage2

from tgbot.config import load_config
from tgbot.filters import register_all_filters
from tgbot.handlers import register_all_handlers
from tgbot.models.models import db

logger = logging.getLogger(__name__)

async def main():
    logging.basicConfig(
        level=logging.INFO,
        format=u'%(filename)s:%(lineno)d #%(levelname)-8s [%(asctime)s] - %(name)s - %(message)s',
    )
    logger.info('Starting bot')
    config = load_config('.env')

    storage = RedisStorage2() if config.tg_bot.use_redis else MemoryStorage()
    bot = Bot(token=config.tg_bot.token, parse_mode='HTML')
    dp = Dispatcher(bot, storage=storage)

    bot['config'] = config
    register_all_filters(dp)
    register_all_handlers(dp)

    try:
        await db.set_bind(f'postgresql://'
                          f'{config.db.user}:{config.db.password}@'
                          f'{config.db.host}:5432/{config.db.database}')
        await dp.start_polling()
    finally:
        await dp.storage.close()
        await dp.storage.wait_closed()
        await bot.session.close()
        await db.pop_bind().close()

if __name__ == '__main__':
    try:
        asyncio.run(main())
    except (KeyboardInterrupt, SystemExit):
        logger.error('Bot stopped!')


#!/usr/local/bin/python3

import sys
import numpy as np
import random

import shapes
from tetromino import Tetromino
from read_board_state import read_board_state
from write_board_state import write_board_state
from create_board_state import clear_complete_rows

def task_planner(path, shape_num, outpath):
    """
    Determine the best goal state for a given initial board state and tetromino

    Params:
        path (string): file location of initial board state
        shape_num (int): tetromino identifier
        outpath (string): file location of result board state

    Returns:
        goal_state (numpy array): array consisting of board state and pose
    """
    board = read_board_state(path)
    board[board > 1] = 1
    _, board = clear_complete_rows(board)
    tetromino = Tetromino(shapes.shapes[int(shape_num)], 0, -2)
    end_states = _create_end_states(board, tetromino)

    all_stats = []
    for item in end_states:

        state = item[0]

        # count lines cleared
        num_lines_cleared = 0
        state_copy = np.copy(state)
        state_copy[state_copy > 1] = 1
        row_sums = state_copy.sum(axis=1)
        for sum in row_sums:
            assert sum < 11  # row cannot be overfull
            assert sum >= 0  # row cannot have negative numbers
            if sum == 10:
                num_lines_cleared += 1

        # calc height
        height = 0
        for i in range(len(row_sums)):
            if row_sums[i] > 0:
                height = 20 - i
                break

        # count holes (any space below a block is a hole)
        num_holes = 0
        for c in range(len(state[0])):

            start_counting_holes = False
            for r in range(len(state)):

                if not start_counting_holes:
                    if state[r][c] > 0:  # potential ceiling block found
                        start_counting_holes = True
                else:
                    if state[r][c] == 0:  # zero found below nonzero
                        num_holes += 1

        # count empty spaces in bottom row
        num_empty = 0
        for space in state[len(state)-1]:
            if space == 0:
                num_empty += 1

        all_stats.append(
            (item, num_lines_cleared, height, num_holes, num_empty)
        )

    best_stats = all_stats

    # prioritize most lines cleared
    max_lines_cleared = 0
    for stats in best_stats:
        if stats[1] >= max_lines_cleared:
            max_lines_cleared = stats[1]
    temp_best = []
    for stats in best_stats:
        if stats[1] >= max_lines_cleared:
            temp_best.append(stats)
    best_stats = temp_best

    # prioritize smallest height
    min_height = 20
    for stats in best_stats:
        if stats[2] <= min_height:
            min_height = stats[2]
    temp_best = []
    for stats in best_stats:
        if stats[2] <= min_height:
            temp_best.append(stats)
    best_stats = temp_best
    if min_height >= 20:
        return 'Game Over'

    # prioritize fewest holes
    min_holes = 200
    for stats in best_stats:
        if stats[3] <= min_holes:
            min_holes = stats[3]
    temp_best = []
    for stats in best_stats:
        if stats[3] <= min_holes:
            temp_best.append(stats)
    best_stats = temp_best

    # prioritize filling bottom row
    min_empty_spaces = 10
    for stats in best_stats:
        if stats[4] <= min_empty_spaces:
            min_empty_spaces = stats[4]
    temp_best = []
    for stats in best_stats:
        if stats[4] <= min_empty_spaces:
            temp_best.append(stats)
    best_stats = temp_best

    goal_state = random.choice(best_stats)[0]
    write_board_state(outpath, goal_state[0])

    return goal_state

def _create_end_states(board, tetromino):
    """
    Helper function for task_planner()

    Param:
        tetromino (Tetromino): shape in play with up-to-date position
        board (numpy array): current board state

    Returns:
        end_states (list): list of numpy arrays representing each possible end
                            state
    """

    end_states = []
    for rot_num in range(4):  # for each unique rotation of shape (3)
        for loc_col in range(-2, 12):  # all possible cols tetromino can be in

            tetromino.row = -2  # new col, start at top
            tetromino.col = loc_col
            end_pose = [0, 0, 0]

            # find first valid row
            invalid_col = False
            while _collision_exists(tetromino, board):
                if tetromino.row >= 20:
                    invalid_col = True
                    break
                tetromino.row += 1
            if invalid_col:
                continue

            # increment row until collision
            while True:
                tetromino.row += 1
                if _collision_exists(tetromino, board):  # row not valid
                    tetromino.row -= 1  # go back to last valid row
                    break

            # save end state to file
            end_pose[0] = tetromino.row
            end_pose[1] = tetromino.col
            end_pose[2] = rot_num
            outboard = np.copy(board)
            for trow in range(4):
                for tcol in range(4):
                    if tetromino.shape[trow][tcol] == 2:  # collision matters
                                                            # (cell found)

                        # determine absolute location of tetris cell in board
                        brow = trow + tetromino.row
                        bcol = tcol + tetromino.col
                        outboard[brow][bcol] = 2
            path = str(
                './Output/possible_state'
                + str(rot_num)
                + '_' + str(loc_col) + '.txt'
            )
            write_board_state(path, outboard)

            # append to end state set
            end_states.append((outboard, end_pose))

        tetromino.rotate()

    return end_states

def _collision_exists(tetromino, board):
    """
    Helper function for task_planner()

    Param:
        tetromino (Tetromino): shape in play with up-to-date position
        board (numpy array): current board state

    Returns:
        (boolean): if tetromino is out of bounds or overlaps an occupied cell
    """
    # (trow, tcol) represent relative location of shape in 4x4 grid
    for trow in range(4):
        for tcol in range(4):
            if tetromino.shape[trow][tcol] == 2:  # collision matters (cell found)

                # determine absolute location of tetris cell in board
                brow = trow + tetromino.row
                bcol = tcol + tetromino.col

                # check collision
                if (
                    # check out of bounds
                    (brow < 0) or (brow > 19)
                    or (bcol < 0) or (bcol > 9)

                    # check collision w/ existing shapes
                    or (board[brow][bcol] != 0)
                ):
                    return True
                # NOTE: cell is in valid location if this line reached
    # NOTE: all cells in valid location if this line reached
    return False

if __name__ == '__main__':
    if len(sys.argv) != 3:
        print("usage: python3 task_planner.py <path> <shape_num>")
        exit(-1)
    else:
        task_planner(sys.argv[1], sys.argv[2])


import numpy as np
npa = np.array
# f = open(r"/Users/matt/Desktop/data.txt")
import matplotlib
# matplotlib.use('qt5agg')
from matplotlib import pylab as plt
#
# for line in f.readlines():
#     data = line.strip('\n\r\t ').split(',')
#     if data[-1] == '':
#         data = data[:-1]
#     p = npa([float(each) for each in data[1:]])
#     l = len(p)
#     if l % 2 == 0:
#         ps = p.reshape((l // 2, 2))
#     else:
#         ps = p[:-1].reshape((l // 2, 2))
#     plt.plot(ps[:, 0], ps[:, 1], '*-')

data = np.loadtxt('/Users/matt/Desktop/data.txt', delimiter=',')

from mpl_toolkits.mplot3d import Axes3D
#
x = data[:, 1]
y = data[:, 2]
z = data[:, 3]

# plt.plot(x, y, 'ro')
# for i, (xi, yi) in enumerate(zip(x, y)):
#     plt.text(xi, yi, str(i))
fig = plt.figure(figsize=(8, 6))
ax = Axes3D(fig)

# x = (x - np.mean(x)) / (x.max() - x.min())
# y = (y - np.mean(y)) / (y.max() - y.min())*20
# z = (z - np.mean(z)) / (z.max() - z.min())
ax.plot(x, y, z, color="deeppink")

ax.set(xlabel="X", ylabel="Y", zlabel="Z")

# ax.set_yticks([-1, 0, 1])
# ax.set_yticklabels(['min', 0, 'max'])
for i, (xi, yi, zi) in enumerate(zip(x, y, z)):
    ax.text(xi, yi, zi, str(i))
ax.set_zticks([-1, 0, 1])

# plt.axis("equal")
# print(x[1:] - x[:-1])
# print(y[1:] - y[:-1])
# diff_x = x[1:] - x[:-1]
# diff_y = y[1:] - y[:-1]
# indx, = np.where(diff_x > 0.1)
# for i, (xi, yi, zi) in enumerate(zip(x, y, z)):
#     ax.text(xi, yi, zi, str(i))
#     if i in (indx):
plt.show()