import logging

from config import settings
from port.client import PortClient
from targets import Slack
from generators import SlackMessageGenerator

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class Handler:
    @classmethod
    def generate_scorecards_reminders(cls):
        logger.info("Initializing Port client")
        port_client = PortClient(settings.port_api_url, settings.port_client_id, settings.port_client_secret)
        logger.info(f"Fetching entities for team {settings.team}, blueprint {settings.blueprint}, scorecard {settings.scorecard}")
        entities = port_client.search_entities(
            {
                "combinator": "and",
                "rules": [
                    {
                        "property": "$blueprint",
                        "operator": "=",
                        "value": settings.blueprint
                    },
                    {
                        "property": "$team",
                        "operator": "containsAny",
                        "value": [settings.team]
                    }
                ]
            }
        )
        if not entities:
            logger.info("No entities found")
            return
        if settings.target_kind == "slack":
            logger.info(f"Generating scorecards reminders for {len(entities)} entities")
            blocks = SlackMessageGenerator().generate_scorecards_reminders(settings.blueprint,
                                                                           settings.scorecard,
                                                                           entities)
            logger.info("Sending scorecards reminders to slack channel")
            Slack().send_message(blocks)


dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]

blocks = {'|': [2, 3], '-': [0, 1], '+': [0, 1, 2, 3],
          '1': [0, 2], '2': [0, 3], '3': [1, 3], '4': [1, 2]}

def in_range(x, y):
    return 0 <= x < r and 0 <= y < c

r, c = map(int, input().split())
a = [list(input()) for _ in range(r)]
cnt = [[0] * c for _ in range(r)]

for i in range(r):
    for j in range(c):
        if a[i][j] == '.':
            continue
        if a[i][j] == 'M' or a[i][j] == 'Z':
            cnt[i][j] = 1
        elif a[i][j] == '+':
            cnt[i][j] = 4
        else:
            cnt[i][j] = 2

for x in range(r):
    for y in range(c):

        if a[x][y] == '.':
            continue
        if a[x][y] == 'M' or a[x][y] == 'Z':

            for i in range(4):
                nx, ny = x + dx[i], y + dy[i]
                if not in_range(nx, ny):
                    continue
                if a[nx][ny] == '.':
                    continue
                cnt[nx][ny] -= 1

            continue

        for i in blocks[a[x][y]]:
            nx, ny = x + dx[i], y + dy[i]

            cnt[nx][ny] -= 1

for x in range(r):
    for y in range(c):
        if cnt[x][y] < 0:

            for block, dir in blocks.items():

                total = abs(cnt[x][y])

                for i in dir:
                    nx, ny = x + dx[i], y + dy[i]

                    if not in_range(nx, ny) or cnt[nx][ny] == 0:
                        break
                    if cnt[nx][ny] == 1:
                        total -= 1

                if total == 0:
                    print(x+1, y+1, block)
                    exit()


# You are given two non-empty linked lists representing two non-negative integers. The digits are
# stored in reverse order, and each of their nodes contains a single digit. Add the two numbers
# and return the sum as a linked list. You may assume the two numbers do not contain any leading
# zero, except the number 0 itself.

# Example 1:
# Input: l1 = [2,4,3], l2 = [5,6,4]
# Output: [7,0,8]
# Explanation: 342 + 465 = 807.

# Example 2:
# Input: l1 = [0], l2 = [0]
# Output: [0]

# Example 3:
# Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
# Output: [8,9,9,9,0,0,0,1]

# Constraints:
# The number of nodes in each linked list is in the range [1, 100].
# 0 <= Node.val <= 9
# It is guaranteed that the list represents a number that does not have leading zeros.

from typing import Optional
from typing import List

# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution:
    def calculate(self, v1, v2, stack: List[int], carry) -> int:
        val = v1 + v2 + carry
        if val > 9:
            carry = val // 10
            stack.append(val % 10)
        else:
            carry = 0
            stack.append(val)
        return carry

    def recurseSum(self, l1: Optional[ListNode], l2 : Optional[ListNode], stack : List[int], carry):
        if l1 is None and l2 is None:
            if carry > 0:
                stack.append(carry)
            return
        if l1 is not None:
            if l2 is None:
                carry = self.calculate(l1.val, 0, stack, carry)
                self.recurseSum(l1.next, l2, stack, carry)
        if l2 is not None:
            if l1 is None:
                carry = self.calculate(0, l2.val, stack, carry)
                self.recurseSum(l1, l2.next, stack, carry)
        if l1 is not None and l2 is not None:
            carry = self.calculate(l1.val, l2.val, stack, carry)
            self.recurseSum(l1.next, l2.next, stack, carry)

    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        stack = []
        self.recurseSum(l1,l2,stack,0)
        root = ListNode(None,None)
        temp = root
        print(stack)
        for i in range(0, len(stack)):
            print(stack[i])
            temp.val = stack[i]
            if i < len(stack)-1:
               temp.next = ListNode(None,None)
               temp = temp.next
        return root

s = Solution()

# equal length LL
l1 = ListNode(2, ListNode(4, ListNode(3, None)))
l2 = ListNode(5, ListNode(6, ListNode(4, None)))
s.addTwoNumbers(l1,l2)

# unequal length LL, L2 > L1
l1 = ListNode(2, ListNode(3, None))
l2 = ListNode(5, ListNode(6, ListNode(4, None)))
s.addTwoNumbers(l1,l2)

# unequal length LL, L1 > L2
l2 = ListNode(2, ListNode(3, None))
l1 = ListNode(5, ListNode(6, ListNode(4, None)))
s.addTwoNumbers(l1,l2)

# unequal length LL, L1 > L2
l2 = ListNode(2, None)
l1 = ListNode(5, ListNode(6, ListNode(4, None)))
s.addTwoNumbers(l1,l2)

# L2 is None
l2 = ListNode(0, None)
l1 = ListNode(5, ListNode(6, ListNode(4, None)))
s.addTwoNumbers(l1,l2)

# Uneven with overflow carry
l1 = ListNode(9, ListNode(9, ListNode(9, ListNode(9, ListNode(9, ListNode(9, ListNode(9, ListNode(9, None))))))))
l2 = ListNode(9, ListNode(9, ListNode(9, ListNode(9, None))))
s.addTwoNumbers(l1,l2)


import argparse
import datetime
import os

def parse_args():
    arg_parser = argparse.ArgumentParser()
    arg_parser.add_argument('--dataset_dir', type=str, help='dataset directory to use for training/testing OR '
                                                            'dataset filename, in case of synthetic data.',
                            default='./S20-Two-Camera-Dataset/Metadata_Image_Pairs'
                            )
    arg_parser.add_argument('--dataset_type', type=str, default='real_trans',
                            help='dataset type ['
                                 '`hist`: individual histograms | '
                                 '`aug_hist`: augmented histograms | '
                                 '`syn_trans`: synthetic transforms | '
                                 '`syn_trans_rad`: synthetic transforms (radiometric) | '
                                 '`real_trans`: transforms from real images (S20) | '
                                 '`real_trans_aug`: transforms from real images (S20), augmented | '
                                 ']')
    arg_parser.add_argument('--n_aug_real', type=int, help='number of augmentations per image (for real data)',
                            default=1)
    arg_parser.add_argument('--cam_p', type=str, help='first camera ID (for NUS dataset)', default='NikonD5200')
    arg_parser.add_argument('--cam_f', type=str, help='second camera ID (for NUS dataset)', default='Canon1DsMkIII')
    arg_parser.add_argument('--target_cam', type=int, help='target camera for which to estimate illuminant ( 0 or 1)',
                            default=0)
    arg_parser.add_argument('--n_images', type=int,
                            help='number of images to use in training, 0 means to use all images', default=0)
    arg_parser.add_argument('--model_type', type=str, default='1in1out_trans',
                            help='model type. '
                                 '`1in1out`: input 1 histogram, output 1 WB. '
                                 '`2in1out`: input 2 histograms, output 1 WB. '
                                 '`2in2out`: input 2 histograms, output 2 WB. '
                                 '`2in2out_trans`: input 2 histograms, output 2 WB, use histogram in loss. '
                                 '`3in2out_trans`: input 2 histograms + transform, output 2 WB, use histogram in loss. '
                                 '`1in1out_trans`: input transform only, output 1 WB. '
                            )
    arg_parser.add_argument('--experiments_dir', type=str, help='directory to save all experiments\' outputs',
                            default='./experiments'
                            )
    arg_parser.add_argument('--experiment_dir', type=str, help='path to an existing experiment to continue training',
                            default='')
    arg_parser.add_argument('--test_model_path', type=str, help='path to model to be tested',
                            default=''
                            )
    arg_parser.add_argument('--experiment_name', type=str, help='experiment name', default='')
    arg_parser.add_argument('--tensorboard_dir', type=str, help='tensorboard log directory',
                            default=''
                            )
    arg_parser.add_argument('--n_cross_val', type=int, help='number of cross validation parts', default=3)
    arg_parser.add_argument('--cross_val_idx', type=int, help='0-based index of cross validation part to run, '
                                                              'if -1, all parts will be run', default=-1)
    arg_parser.add_argument('--random_seed', type=int, help='random seed for reproducibility', default=999)
    arg_parser.add_argument('--learn_rate', type=float, help='learning rate', default=1e-4)
    arg_parser.add_argument('--loss', type=str,
                            help='loss function [mae, mse, cos, ang, ang_mae, mae_trans, mae_trans_wgt]',
                            default='mae')
    arg_parser.add_argument('--trans_weight', type=float, help='weight of transform term in loss', default=1.0)
    arg_parser.add_argument('--n_epochs', type=int, help='number of epochs', default=2000)
    arg_parser.add_argument('--batch_size', type=int, help='batch size', default=16)
    arg_parser.add_argument('--arch_id', type=int, help='architecture ID',
                            default=3
                            )
    arg_parser.add_argument('--n_conv_layers', type=int, help='number of convolutional layers', default=5)
    arg_parser.add_argument('--n_filters', type=int, help='number of filters in each layers', default=64)
    arg_parser.add_argument('--n_dense_layers', type=int, help='number of dense layers for dense models', default=2)
    arg_parser.add_argument('--n_dense_units', type=int, help='number of dense units per layer for dense models',
                            default=9)
    arg_parser.add_argument('--n_outputs', type=int, help='number of model outputs', default=2)
    arg_parser.add_argument('--n_workers', type=int, help='number of processes for data loading', default=8)
    arg_parser.add_argument('--n_ds_reps', type=int,
                            help='number of dataset repetitions, epochs will be divided by this number', default=10)
    arg_parser.add_argument('--last_layer', type=str,
                            default='exp',
                            help='choice of last layer activation (exp, sigmoid, relu, ...)')

    args = arg_parser.parse_args()
    return args

def set_experiment_params(args):
    # experiment's name, directory, etc.
    if args.experiment_dir != '':
        # an existing experiment (continue training or testing model)
        args.continue_training = True
    else:
        # a new experiment
        args.continue_training = False
        timestamp = datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
        args.experiment_dir = os.path.join(args.experiments_dir, timestamp)
        # append experiment name
        if args.experiment_name != '':
            args.experiment_dir = "{}_{}".format(args.experiment_dir, args.experiment_name)
        args.script_name = os.path.basename(__file__)
        print("args.experiment_dir = {}".format(args.experiment_dir))

    os.makedirs(args.experiments_dir, exist_ok=True)
    os.makedirs(args.experiment_dir, exist_ok=True)

    # directories to save training/testing sample images
    args.train_samples_dir = os.path.join(args.experiment_dir, 'train_samples')
    args.test_samples_dir = os.path.join(args.experiment_dir, 'test_samples')
    os.makedirs(args.train_samples_dir, exist_ok=True)
    os.makedirs(args.test_samples_dir, exist_ok=True)

    # model directory
    args.best_model_dir = os.path.join(args.experiment_dir, 'best_model')
    os.makedirs(args.best_model_dir, exist_ok=True)

    # log files
    args.log_file = os.path.join(args.experiment_dir, 'log.txt')
    args.best_model_info_file = os.path.join(args.experiment_dir, 'best_model_info.txt')
    args.model_summary_fn = os.path.join(args.experiment_dir, 'model_summary.txt')

    # tensorboard
    if args.tensorboard_dir == '' or args.tensorboard_dir is None:
        args.tensorboard_dir = os.path.join(args.experiment_dir, 'tensorboard')
    os.makedirs(args.tensorboard_dir, exist_ok=True)

    # lastly, save experiment's arguments/parameters
    args_file = os.path.join(args.experiment_dir, 'args.txt')
    with open(args_file, 'w')as af:
        af.write(str(args))

    return args


#/usr/bin/python

"""
epistasis.py

calculates epistatis scores (AB - A*B) for all mutation pairs. Using input of ratios .m1 and .m2 files, finds all possible epistatis scores

python epistatis.py -f PATHTOALLMUTSFILE

"""

def main():

	#lists to store fitness scores
	singles = {} #can use a dictionary for speed, since there's only on entry for each variant
	doubles = []
	epistasis = []

	#open, store single mutants file
	for line in open(option.infile+'.m1', 'r').readlines()[1:]:
		l = line.strip().split('\t')
		sID = l[0].split('-')
		singles[sID[0]+sID[1]] = float(l[9])

	#open, store double mutants file
	for line in open(option.infile+'.m2', 'r').readlines()[1:]:
		l = line.strip().split('\t')
		sID = map(lambda x: x.split(','), l[0].split('-'))
		doubles.append([ ','.join([ sID[0][i]+sID[1][i] for i in range(len(sID[0])) ]), float(l[9]) ])

	for k in doubles:
		[a,b] = k[0].split(',')
		if a in singles and b in singles:
			epistasis.append( [ k[0], k[1], singles[a] * singles[b],  k[1] - (singles[a] * singles[b]) ] ) #[ k1_seqID, k1_fitness, pred_k1_fitness, epistasis ]

	#open output file
	f_out = open(option.infile+'-epistasis', 'w')

	#print output
	print >> f_out, '\t'.join(['seqID', 'double_fitness', 'predicted_fitness', 'epistasis'])
	for i in epistasis:
		print >> f_out, '\t'.join(map(str, i))

	f_out.close()

if __name__ == '__main__':

	from optparse import OptionParser

	parser = OptionParser()
	parser.add_option('-f', '--file', action = 'store', type = 'string', dest = 'infile', help = 'path to file containing all fitness values')
	(option, args) = parser.parse_args()

	main()


#Ejercicio 03

import libreria

#MENU PARA PEDIR OPERADORES
def agregar_operador():
    libreria.pedir_operador("Ingrese el operador:")
    print("Se agrego operador")

#MENU GENERAL
opc=0
max=5
while(max == 5):
    print("#########################")
    print("##########MENU###########")
    print("#1. sustraendo")
    print("#2. diferencia")
    print("#3. multiplicador")
    print("#4. division")
    print("#5. Salir")
    opc=libreria.pedir_numero("Elegir numero:", 1, 5)

#Fin_menu

#Mapeo_de_funciones
    if ( opc == 1):
        agregar_operador()
    if ( opc == 2):

        agregar_operador()
    if ( opc == 3):
        agregar_operador()
    if ( opc == 4):
        agregar_operador()

print("Fin del Programa")


import math
import numpy as np
import datetime
import ias
import random
import networkx as nx
import UserNetwork
#A=[[0,1,1,0,1,0,0,1,0,0,0],[1,0,1,1,0,1,0,0,0,1,0],[1,1,0,1,1,0,1,0,0,0,0],[0,1,1,0,0,1,1,0,0,0,0],[1,0,1,0,0,0,0,1,1,0,0],[0,1,0,1,0,0,1,0,0,1,0],[0,0,1,1,0,1,0,0,1,1,0],[1,0,0,0,1,0,0,0,1,0,0],[0,0,0,0,1,0,1,1,0,1,0],[0,1,0,0,0,1,1,0,1,0,0],[0,0,0,0,0,0,0,0,0,0,0]]
A=UserNetwork.a
seed=ias.ias
ds=ias.ds
n=len(A)
A=np.matrix(A)
G=nx.from_numpy_matrix(A)
def ShortestPathModel():
    I=[0 for i in range(len(A))] #I indicates the informed status of the nodes
    prob=[random.uniform(0,1) for i in range(n)] #assigning probability to all nodes
    for i in range(len(ds)):
        sp=nx.shortest_path(G,target=ds[i])#returns a dictinary to sp for shortest path from all the nodes to ds[i]
        c=math.inf #no. of shortest path nodes
        sh=0
        try:
            for s in seed:
                if c>len(sp[s]):#finding out the seed that has shortest path to ds[i]
                    c=len(sp[s])
                    sh=s       #the seed that has the shortest path to ds[i]
            if(prob[ds[i]]<=random.uniform(0,1)):#comparing edge-weight to individual probability
                I[ds[i]] =1 #the node is informed
        except:
            I[ds[i]]=0# if the node is disconnected

    return(I)

R=20000    #no.of simulations
avg=[[] for i in range(R)] #list of I returned by each simulations
start=datetime.datetime.now()
for i in range(R):
    print(i)
    avg[i]=ShortestPathModel() #for each simulation the method returns the I list that represents informed status of the nodes

s=[0 for i in range(n)]#the sum of the no.of times each node got influenced out of R simulations
for i in range(n):
    for j in range(R):
        s[i]+=avg[j][i]
for i in seed:      #all seeds are set to inf
    s[i]=math.inf
end=datetime.datetime.now()
print('SPM')
print('Nodes',n)
print('Seed=',seed)
#print(s)
d={'0-4999':0,'5000-9999':0,'10000-14999':0,'15000-20000':0} #dictionary for all categories
for a in s:
    if a>=0 and a<=4999:    #if no.of informed nodes are in the range 0-4999
        d['0-4999']=d['0-4999']+1
    if a>=5000 and a<=9999:
        d['5000-9999']=d['5000-9999']+1     #if no.of informed nodes are in the range 0-4999
    if a>=10000 and a<=14999:
        d['10000-14999']=d['10000-14999']+1 #if no.of informed nodes are in the range 0-4999
    if a>=15000 and a<=20000:
        d['15000-20000']=d['15000-20000']+1 #if no.of informed nodes are in the range 0-4999
print(d)
print('Start',start)
print('End',end)
t1=(end.minute-start.minute)*60
t2=abs(start.second-end.second)
print('Time taken',abs(t1-t2),'secs')


# @Time :2018/8/20 002016:04
# @Author :Alex
# @File  :Person.py

"""
定义一个人的类
"""

class Person:
    role = 'person'  # 人的角色分类

    def __init__(self, name, age, height):
        self.name = name  # 每个人都有一个自己的昵称
        self.age = age  # 每个人都有自己的年龄
        self.height = height  # 每个人都有自己的身高
        self.grade = 0  # 定义这个人的年级

    def fight(self):  # 人都可以走路，属于一种行为特性，也称为动态属性
        print('%d年级的身高%d厘米的%d岁的%s在打'%(self.grade, self.height, self.age, self.name))

class Dog:
    role = 'dog'

    def __init__(self,name,age,height,color):
        self.name = name
        self.age = age
        self.height = height
        self.color = color
    def bite(self):
        print('{}的身高{}cm的{}岁的{}在咬'.format(self.color,self.height,self.age,self.name))
'''
属性引用(类名.属性)
'''
print(Person.role)
print(Person.fight)
print(Dog.role)
print(Dog.bite)

'''
实例化(类名(参数)) 实例化的过程就是  类 → 对象 的过程
默认是无参的构造函数，不需要参数
有参的构造函数使用 __init__来创建

person = Person() 类名()的调用就等效于执行了 Person.__init__()
__init__() 执行完就会返回一个类似字典的结构，里面包含人类所属的 一些属性 和  方法
可以变相理解为：person = {'name':'xiaoming', 'walk':walk, 'role':'person'}
'''
person = Person('小明', 20, 178)
dog = Dog('小黑',5,50,'黑色')
# 对象.属性 = 值，可以对对象的属性进行修改
person.grade = 6
person.age = 25
# 调用对象的方法
person.fight()
dog.bite()


from tornado import tcpserver, iostream, gen
from tornado.iostream import StreamClosedError
from tornado.concurrent import return_future, Future
from puller import logger, session
from puller.models import Device, DeviceData
from puller.hmframe import insert_crc, bytes_to_float, bytes_to_double, \
    unpack_frame, parse_data, compute_hisdata_addr, DATA_LENGTHS, \
    gen_collect_cmd_frame
from bitstring import BitArray, Bits, pack
from socket import inet_ntoa
import struct, datetime

now = datetime.datetime.now

class Puller(tcpserver.TCPServer):
    device_dict = {}

    def handle_stream(self, stream, address):
        logger.info('New connection from %s' % str(address))
        self.handle_registration(stream, address)

    @gen.coroutine
    def handle_registration(self, stream, address):
        try:
            # receives the 21-byte registration info and proceeds.
            # Otherwise yield and keep waiting.
            message = yield stream.read_bytes(21)

            # unpacks the received bytes into phone number, IP addr.
            reg_data = struct.unpack('!I11scIc',message)
            phone = reg_data[1]

            logger.info('Registered device(%s)' % phone)

            # adds this new device into database.
            device = Device(18, phone, stream)
            session.add(device)
            session.commit()
            self.device_dict[device.portid] = device

        except Exception as e:
            logger.exception('Register device(%s) failed' % phone)
            logger.exception('In handle_registration %s' % e)
        else:
            logger.info('[Device list] %s' % self.device_dict.keys())
            device.colltype = 'R'
            self.handle_device(device)

    @gen.coroutine
    def collect_data(self, device, data_type, interval=1, chktime=None):
        try:
            timestamp = now() if data_type==4 and not chktime else chktime
            recv_frame = BitArray()
            request_frame = gen_collect_cmd_frame(device.devaddr, data_type,
                interval, timestamp)

            # sends out the inqury command frame.
            yield device.stream.write(request_frame.bytes)

            # receives the first 4 leading bytes
            recv_bytes = yield device.stream.read_bytes(4)

            leading, head, remain_length = struct.unpack('!HBB', recv_bytes)
            recv_frame += hex(leading)
            recv_frame += hex(head)
            recv_frame += hex(remain_length)

            # receives the remaining bytes from device.
            remain_bytes = yield device.stream.read_bytes(remain_length)

            for byte in remain_bytes:
                recv_frame += BitArray(uint=ord(byte), length=8)

            # unpacks the binary data into a Python dict object
            frame_dict = unpack_frame(remain_bytes, DATA_LENGTHS[data_type])

            # parses those data bytes into JSON.
            data_json = parse_data(frame_dict['data'])

            logger.info('Received: %s' % recv_frame)

        except StreamClosedError:
            logger.exception('Device(%s) lost connection' % device.portid)
            self.device_dict.pop(device.portid)
        except Exception as e:
            logger.error('In collect_data %s' % str(e))
            self.device_dict.pop(device.portid)
            device.stream.close()
            device.online = False
        else:
            raise gen.Return(data_json)

    @gen.coroutine
    def send_cmd(self, device, message):
        device = self.device_dict.get(device.portid, None)
        if not device:
            raise Exception('No such device')

        try:
            yield device.stream.write(message)
        except StreamClosedError:
            logger.exception('Device(%s) lost connections' % device.portid)
            self.device_dict.pop(device.portid)
            device.online = False

    @gen.coroutine
    def handle_device(self, device, chktime=None):
        action = device.colltype or 'R'
        cmd = None
        try:
            # get msg from rabbitmq.
            # process the msg.

            if action == 'R':
                timestamp = now()

                data = yield self.collect_data(device, 4)
                # Ensures we only store data in a interval of 1 minute.

                if not device.chktime or (timestamp.minute != device.chktime.minute):
                    device.chktime = timestamp
                    logger.info("storing data")
                    #devdata = DeviceData(data)
                    #device.devdata.append(devdata)
                    #session.add(device)
                    #session.commit()

                logger.info('[Parsed data] %s' % data)
                delay = 60 - timestamp.second
                if delay > 55:
                    # This is only for keeping the connection alive.
                    # The data returned is not meant to be stored in database.
                    self.io_loop.call_later(55, self.handle_device, device)
                else:
                    self.io_loop.call_later(delay, self.handle_device, device)

            elif action == 'C':
                yield self.send_cmd(device, cmd)
                self.io_loop.add_callback(self.handle_device, device)

            elif action == 'H':
                chktime = chktime
                yield self.collect_data(device, 4, chktime=chktime)
                device.chktime = chktime
                # request history data from device right in the next iteration.
                #devdata = DeviceData(data)
                #device.devdata.append(devdata)
                #session.add(device)
                #session.commit()
                chktime += datetime.timedelta(0,60,0)
                self.io_loop.add_callback(self.handle_device, device, chktime)

        except Exception as e:
            logger.exception(str(e))
            raise e


#!/bin/python3

import math
import os
import random
import re
import sys

#
# Complete the 'clique' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
#  1. INTEGER n
#  2. INTEGER m
#

def clique(n, m):
    # Write your code here
    def getNum(r):
        if r < 1:
            return 1
        # return (n*n - (n%r)*math.ceil(n/r)*math.ceil(n/r) - (r - (n%r))*math.floor(n/r)*math.floor(n/r))/2
        return ((n**2 - (n%r)*(math.ceil(n/r)**2) - (r - (n%r))*(math.floor(n/r)**2) ))//2
    low, high = 1, n
    answer = -1
    # for i in range(low+1, high+2):
    #     print(i, getNum(i))
    #     if getNum(i) >= m:
    #         return i
    while low <= high:
        mid = (low+high)//2
        num = getNum(mid)
        if m <= num:
            answer = mid
            high = mid-1
        else:
            low = mid+1
    return answer

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

    t = int(input().strip())

    for t_itr in range(t):
        first_multiple_input = input().rstrip().split()

        n = int(first_multiple_input[0])

        m = int(first_multiple_input[1])

        result = clique(n, m)

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

    fptr.close()


import sys
import random
from time import sleep
import glob, os
from midi_player import MidiPlayer
from hotkey_listener import HotkeyListener

playlist_dirs = ['other', 'genshin']
playlist = []
player_speed = 100
auto_play = False
random_play = False

def switch_to_midi_dir():
    # change dir to midi_files
    curr_dir = os.getcwd()
    if "midi_files" in curr_dir:
        midi_dir = curr_dir.split("midi_files")[0] + "/midi_files"
        os.chdir(midi_dir)
    else:
        os.chdir("midi_files")
    curr_dir = os.getcwd()

def update_playlist():
    playlist.clear()
    for dir_name in playlist_dirs:
        for file in glob.glob(dir_name + "/*.mid"):
            playlist.append(file)

def get_help():
    help_str = 'usage: --num [1-%d] (0 to exit)\n' % (len(playlist))
    for index, name in enumerate(playlist, start=1):
        help_str += "%d: %s\n" % (index, name)
    return help_str

def adjust_speed(player: MidiPlayer, value):
    global player_speed
    player_speed += value
    if player_speed < 20:
        player_speed = 20
    player.set_speed(player_speed)
    print('adjust speed to: %d%%' % player_speed)

def toggle_pause(player: MidiPlayer):
    global auto_play
    player.toggle_pause()
    auto_play = not auto_play

def toggle_random(player: MidiPlayer):
    global random_play
    player.toggle_random()
    random_play = not random_play
    print('random mode:', random_play)

if __name__ == '__main__':
    switch_to_midi_dir()
    update_playlist()
    midi_player = MidiPlayer()
    midi_player.set_debug(False)
    hotkey_listener = HotkeyListener()
    hotkey_listener.register_hotkey("-", adjust_speed, args=(midi_player, -4))
    hotkey_listener.register_hotkey("+", adjust_speed, args=(midi_player, 4))
    hotkey_listener.register_hotkey("/", toggle_pause, args=(midi_player,))
    hotkey_listener.register_hotkey("*", toggle_random, args=(midi_player,))
    hotkey_listener.start_listener()
    print('start listening hotkeys: use -/+ to adjust speed...')

    line = ''
    while True:
        update_playlist()
        print(get_help())
        print('input your music choice:(0 to randomly autoplay)')
        try:
            line = input()
        except KeyboardInterrupt:
            print('exit lyresong autoplay.')
            hotkey_listener.stop_listener()
            sys.exit(0)

        try:
            choice = int(line)
            if choice == 0:
                current = next = -1
                auto_play = True
                while auto_play:
                    if next != -1:
                        current = next
                    else:
                        current = random.randint(0,len(playlist)-1)
                    next = random.randint(0,len(playlist)-1)
                    mid = playlist[current]
                    # classic\雪掩的往事.mid
                    # classic\龙脊雪山-雪掩的往事-Dragonspine_Snow_Buried_Tales.mid
                    song_name = mid.split("\\")[1].replace(".mid","").replace("Piano_","")
                    song_name_parts = song_name.split("-")
                    if len(song_name_parts) > 1:
                        song_name = "-".join(song_name_parts[:-1])
                    next_song_name = playlist[next].split("\\")[1].replace(".mid","")
                    song_name_parts = next_song_name.split("-")
                    if len(song_name_parts) > 1:
                        next_song_name = "-".join(song_name_parts[:-1])
                    print(f"当前演奏：{song_name}")
                    print(f"下一曲：{next_song_name}")
                    with open("playinfo.txt","wt") as f:
                        f.write(f"当前演奏：{song_name}")
                    sleep(4)
                    midi_player.play(mid)
            elif 0 < choice <= len(playlist):
                mid = playlist[choice - 1]
                midi_player.play(mid)
            else:
                continue
        except FileNotFoundError:
            print("The midi file has been deleted, now refresh dir...")
            update_playlist()
        except (NameError, ValueError, KeyboardInterrupt):
            continue


import numpy as np
import matplotlib.pyplot as plt

from MyfirstNN.MyFirstNN import NeuralNetwork

'''
-----------输出结果-----------
第1轮训练...  正确率 =  0.958
第2轮训练...  正确率 =  0.9656
第3轮训练...  正确率 =  0.968
第4轮训练...  正确率 =  0.9707
第5轮训练...  正确率 =  0.9725
'''

# 设置参数
input_nodes = 784
hidden_nodes = 200
output_nodes = 10
learn_rate = 0.15

# 初始化网络
n = NeuralNetwork(input_nodes, hidden_nodes, output_nodes, learn_rate)

# 载入训练数据集
training_data_file = open("../mnist/mnist_train_100.csv", 'r')
training_data_list = training_data_file.readlines()
training_data_file.close()
'''
# 可视化第一条数据
all_values = training_data_list[0].split(',')
image_array = np.asfarray(all_values[1:]).reshape(28, 28)
a = plt.imshow(image_array, cmap='Greys')
plt.show(a)
'''

# 5 轮训练
epochs = 5
for e in range(epochs):
    print(f"第{e+1}轮训练...", end="  ")
    for record in training_data_list:
        all_values = record.split(',')
        inputs = (np.asfarray(all_values[1:]) / 255.0 * 0.99) + 0.01  # 归一化输入值到0.01~1之间
        targets = np.zeros(output_nodes) + 0.01
        targets[int(all_values[0])] = 0.99
        n.train(inputs, targets)

    # 载入测试数据
    test_data_file = open("../mnist/mnist_test_10.csv", 'r')
    test_data_list = test_data_file.readlines()
    test_data_file.close()

    scorecard = []
    for rec in test_data_list:
        values = rec.split(',')
        correct_label = int(values[0])
        inputs = (np.asfarray(values[1:]) / 255.0 * 0.99) + 0.01  # 归一化输入值到0.01~1之间
        outputs = n.query(inputs)
        label = np.argmax(outputs)
        if label == correct_label:
            scorecard.append(1)
        else:
            scorecard.append(0)

    scorecard_array = np.asarray(scorecard)
    print("正确率 = ", scorecard_array.sum() / scorecard_array.size)


from __future__ import absolute_import
from __future__ import division
from contextlib import contextmanager
from functools import partial
import threading

from six.moves import queue

from . import libnl

_POOL_SIZE = 5

_NL_SOCKET_BUFF_SIZE = 1024 * 512

_tls = threading.local()

class NLSocketPool(object):
    """Pool of netlink sockets."""

    def __init__(self, size):
        if size <= 0:
            raise ValueError('Invalid socket pool size %r. Must be positive')
        self._semaphore = threading.BoundedSemaphore(size)
        self._sockets = queue.Queue(maxsize=size)

    @contextmanager
    def socket(self):
        """Returns a socket from the pool (creating it when needed)."""
        if hasattr(_tls, 'socket'):
            yield _tls.socket
        else:
            with self._semaphore:
                _tls.socket = self._get_socket()
                try:
                    yield _tls.socket
                finally:
                    self._put_socket(_tls.socket)
                    del _tls.socket

    def _get_socket(self):
        try:
            socket = self._sockets.get_nowait()
        except queue.Empty:
            socket = _open_socket()
        return socket

    def _put_socket(self, socket):
        self._sockets.put_nowait(socket)

_pool = NLSocketPool(_POOL_SIZE)

def _open_socket(callback_function=None, callback_arg=None):
    """Returns an open netlink socket.
    callback_function: Modify the callback handler associated with the
    socket. Callback function requires two arguments:
        nl_message: netlink message passed by the socket
        args: optional argument defined by _nl_socket_modify_cb()
    callback_arg: optional argument passed to the callback function
    """
    sock = libnl.nl_socket_alloc()
    try:
        if callback_function is not None:
            libnl.nl_socket_disable_seq_check(sock)
            libnl.nl_socket_modify_cb(
                sock,
                libnl.NlCbKind.NL_CB_DEFAULT,
                libnl.NlCbKind.NL_CB_CUSTOM,
                callback_function,
                callback_arg,
            )

        libnl.nl_connect(sock, libnl.NETLINK_ROUTE)
        libnl.nl_socket_set_buffer_size(sock, _NL_SOCKET_BUFF_SIZE, 0)
    except:
        libnl.nl_socket_free(sock)
        raise
    return sock

def _close_socket(sock):
    """Closes and frees the resources of the passed netlink socket."""
    libnl.nl_socket_free(sock)

@contextmanager
def _cache_manager(cache_allocator, sock):
    """Provides a cache using cache_allocator and frees it and its links upon
    exit."""
    cache = cache_allocator(sock)
    try:
        yield cache
    finally:
        libnl.nl_cache_free(cache)

def _socket_memberships(socket_membership_function, socket, groups):
    groups_codes = [libnl.GROUPS[g] for g in groups]
    groups_codes = groups_codes + [0] * (
        len(libnl.GROUPS) - len(groups_codes) + 1
    )
    try:
        socket_membership_function(socket, *groups_codes)
    except:
        libnl.nl_socket_free(socket)
        raise

_add_socket_memberships = partial(
    _socket_memberships, libnl.nl_socket_add_memberships
)
_drop_socket_memberships = partial(
    _socket_memberships, libnl.nl_socket_drop_memberships
)


import requests
import time as t
url = 'https://www.reddit.com/r/todayilearned/new/.json'

class VariableThings:
    previous_title = ''
    newPost = True

fr = open('TIL facts.txt', 'r')
lines = []
for i in enumerate(fr):
    lines.append(i)
fr.close()
numberOfLines = len(lines)
lastTitleLine = numberOfLines - 5
VariableThings.previous_title = lines[lastTitleLine][1][:-1]

def get_new_post():
    raw_data = requests.get(url, headers={'User-agent': 'Parth bot 0.002'})
    json_data = raw_data.json()
    raw_title = json_data['data']['children'][0]['data']['title']
    other_data = json_data['data']['children'][0]['data']
    clean_title(raw_title, other_data)

def clean_title(text, data):
    clean_text = text[4:]
    if 'that' in clean_text[:6]:
        clean_text = clean_text[5:]
    clean_text = clean_text[:1].upper() + clean_text[1:]
    check_fact(clean_text, VariableThings.previous_title, data)
    VariableThings.previous_title = clean_text

def check_fact(new, old, data):
    if new == old:
        if VariableThings.newPost:
            print('No new fact available.')
        VariableThings.newPost = False
        return
    else:
        useful_data = {'title': new, 'upvotes': str(data['ups']), 'downvotes': str(data['downs']),
                       'post_time': data["created_utc"], 'permalink': data['permalink'], 'author': data['author'],
                       'link': data['url']}
        print_fact(useful_data)
        VariableThings.newPost = True

def print_fact(data):
    text_data = {'fact':
                 data['title'] + '\nLink: ' + data['link'] + '\nPermalink: ' + 'www.reddit.com' + data['permalink'] +
                 '\nSubmitter: ' + data['author'] + '\tDate posted: ' + t.asctime(t.localtime(data['post_time'])) +
                 '\n\n'
                 }

    fw = open('TIL Facts.txt', 'a')
    fw.write(text_data['fact'])
    fw.close()
    print(text_data['fact'])

while True:
    get_new_post()
    t.sleep(30)


import PIL.Image as Image
import os
from torchvision import transforms as transforms
import csv
fh = open(r'D:\代码\论文\me\data1.csv', 'r')
reader = csv.reader(fh)
#print(len(reader))
outfile = r'D:\代码\论文\test'
i = 401

for row in reader:
    im = Image.open(row[0])
    new_im = transforms.RandomHorizontalFlip(p=1)(im) #shuiping
    path = 'test_'+ '000' + str(i) + '.png'
    new_im.save(os.path.join(outfile, path))

    new_im = transforms.RandomVerticalFlip(p=1)(new_im)  # shuiping
    path = 'test_' + '0000' + str(i) + '.png'
    new_im.save(os.path.join(outfile, path))

    new_im = transforms.RandomVerticalFlip(p=1)(im) #chuizhi
    path = 'test_' + '00000' + str(i) + '.png'
    new_im.save(os.path.join(outfile, path))
    i +=1


import xmltodict
import json
import time

# read the XML file
with open('input.xml', 'r') as file:
    xml_data = file.read()

# convert XML to JSON and measure the time taken
start_time = time.time()
json_data = json.dumps(xmltodict.parse(xml_data), indent=4)
end_time = time.time()

# print the JSON output and time taken
# print(json_data)
print(f"\nTime taken for conversion: {end_time - start_time} seconds")

with open("data1.json", "w") as json_file:
		json_file.write(json_data)


import openpmd_api as io

def write_to_openpmd_file(file_prefix, file_format, grid, wavelength, pol):
    """
    Write the laser field into an openPMD file

    Parameters
    ----------
    file_prefix: string
        The file name will start with this prefix.

    file_format: string
        Format to be used for the output file. Options are "h5" and "bp".

    grid: Grid
        A grid object containing the array (n-dimensional, n=2 for
        dim='rt', n=3 for dim='xyt') with complex envelope of the electric field.
        and metadata

    wavelength: scalar
        Central wavelength for which the laser pulse envelope is defined.

    pol: list of 2 complex numbers
        Polarization vector that multiplies array_in to get the Ex and Ey array_ins.
    """
    array_in = grid.field
    box = grid.box
    dim = box.dim

    # Create file
    series = io.Series(
        "{}_%05T.{}".format(file_prefix, file_format),
        io.Access.create)
    i = series.iterations[0]

    # Store metadata needed to reconstruct the field
    i.set_attribute("wavelength", wavelength)
    i.set_attribute("pol", pol)

    # Define E_real, E_imag as scalar records
    for comp_name in ['E_real', 'E_imag']:

        # Define the mesh
        m = i.meshes[comp_name]
        m.grid_spacing = [ (hi-lo)/npoints for hi, lo, npoints in \
                               zip( box.hi, box.lo, box.npoints ) ]
        m.grid_global_offset = box.lo
        m.unit_dimension = {
            io.Unit_Dimension.M:  1,
            io.Unit_Dimension.L:  1,
            io.Unit_Dimension.I: -1,
            io.Unit_Dimension.T: -3
        }
        if dim == 'xyt':
            m.geometry = io.Geometry.cartesian
            m.axis_labels = ['x', 'y', 't']
        elif dim == 'rt':
            m.geometry = io.Geometry.thetaMode
            m.axis_labels = ['r', 't']

        # Define the dataset
        dataset = io.Dataset(array_in.real.dtype, array_in.real.shape)
        E = m[io.Mesh_Record_Component.SCALAR]
        E.position = [0]*len(dim)
        E.reset_dataset(dataset)

        # Pick the correct field
        if comp_name == 'E_real':
            data = (array_in).real.copy()
        elif comp_name == 'E_imag':
            data = (array_in).imag.copy()
        E.store_chunk( data )

    series.flush()


class Node:
    def __init__(self,data):
        self.data=data
        self.next=None

class Stack():
    def __init__(self):
        self.head=None

    def push(self,data):
        newnode=Node(data)

        if self.isEmpty():
            self.head=newnode
            return
        newnode.next=self.head
        self.head=newnode

    def isEmpty(self):
        if self.head is None:
            return True
        else :
            return False

    def pop(self):
        if not self.isEmpty():
            popped=self.head.data
            self.head=self.head.next
            return popped

    def print_stack(self):
        temp=self.head
        if self.isEmpty():
            print("Empty Stack")
        while(temp):
            print(temp.data)
            temp=temp.next

stack=Stack()
stack.push(1)
stack.push(2)
stack.print_stack()
stack.pop()
stack.print_stack()


from aocd import lines
import re

# Initial stack:
#
#    [V] [G]             [H]
#[Z] [H] [Z]         [T] [S]
#[P] [D] [F]         [B] [V] [Q]
#[B] [M] [V] [N]     [F] [D] [N]
#[Q] [Q] [D] [F]     [Z] [Z] [P] [M]
#[M] [Z] [R] [D] [Q] [V] [T] [F] [R]
#[D] [L] [H] [G] [F] [Q] [M] [G] [W]
#[N] [C] [Q] [H] [N] [D] [Q] [M] [B]
#
# Example command:
#
# 'move 2 from 2 to 1'

class Stacks():
    def __init__(self, lines):
        self.lines = lines
        self.reset_stack()

    def reset_stack(self):
        self.stacks = {}
        for line in self.lines:
            if (len(line) == 0):
                break
            for idx, c in enumerate(line):
                if c == '[':
                    column = int(idx/4)+1
                    if column in self.stacks:
                        self.stacks[column].append(line[idx+1])
                    else:
                        self.stacks[column] = [line[idx+1]]

    def move_from_stack_to_stack(self, amount: int, source: int, target: int, keep_stack_order: bool):
        containers_to_move = []
        for i in range(0, amount):
            if keep_stack_order:
                containers_to_move.insert(0, self.stacks.get(source)[i])
            else:
                containers_to_move.append(self.stacks.get(source)[i])
        for container in containers_to_move:
            self.stacks[target].insert(0, container)
            self.stacks[source].pop(0)

    def act_move_order(self, line: str, keep_stack_order: bool):
        amount, source, target = list(map(int, re.findall(r'\d+', line)))
        if keep_stack_order:
            self.move_from_stack_to_stack(amount, source, target, True)
        else:
            self.move_from_stack_to_stack(amount, source, target, False)

    def print_ans(self):
        ans = ""
        for key in sorted(self.stacks):
            ans = ans + self.stacks[key][0]
        print(ans)

    def solve(self, keep_stack_order: bool):
        for line in self.lines:
            if len(line) == 0 or line[0] != 'm':
                continue
            self.act_move_order(line, keep_stack_order)
        self.print_ans()
        self.reset_stack()

stacks = Stacks(lines)
stacks.solve(False)
stacks.solve(True)


# #6.3
guess_me=5

for n in range(10):
    print(n)
    if n < guess_me:
        print('Too low')
    elif n > guess_me:
        print('Oops')
    else:
        print('Found It!')
        break

# 6.2
# guess_me = 7
# number = 1
#
# while number < guess_me:
#     print(number)
#     print('Too low')
#     number = number + 1
# else:
#
#     number == guess_me
#     print(number)
#     print('Found it!')
#     number = number + 1
#
#     number > guess_me
#     print(number)
#     print('Oops')
#     break

# last = input('Please enter students last name: ')
# for name in last:
#     if last == 'ZZZ':
#         break
# first = input('Please enter students first name: ')
# GPA = input('Please enter student GPA?:')
# GPA = float(GPA)
# if GPA >= 3.5:
#     print(f"{first}  {last} has made the Dean's list.")
#
# if GPA >= 3.25 and GPA < 3.4999:
#     print(f"{first}  {last}  has made the Honor Roll.")
#
# if GPA < 3.25:
#     print("You can do better.")


import pandas as pd
from dataclasses import dataclass
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import CategoricalNB
from sklearn.tree import DecisionTreeClassifier
from sklearn import metrics

@dataclass
class MLDataSet:
    '''Class for representing dataset for ML.'''
    x_train: pd.DataFrame # feature dataframe for training.
    y_train: pd.DataFrame # label dataframe for training. Size is equal of x_train.
    x_test: pd.DataFrame  # feature dataframe for testing.
    y_test: pd.DataFrame  # label dataframe for testing. Size is equal to x_test.

def read_data() -> pd.DataFrame:
    '''Reads the intended data file and return it as Data Frame.'''
    df = pd.read_csv('mushrooms.csv')
    return shuffle(df)

def process_data_frame_for_sklearn(df: pd.DataFrame):
    ''' Processes data frame and prepare it for sklearn modules.
    Args:
        df: DataFrame containing the entire dataset.
    Returns:
        A MLDataSet instance.
    '''
    column_names = list(df.columns)

    for column in column_names:
        df[column] = df[column].astype('category').cat.codes

    class_column = column_names[0]
    feature_columns = column_names[1:]

    # Create data frame with features only.
    X = df[feature_columns]
    # Create data frame with labels only.
    Y = df[class_column]

    # Split input in 70/30 with 70% as train set, 30% as test set.
    x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=0.3, random_state=0)
    d = MLDataSet(x_train=x_train, y_train=y_train, x_test=x_test, y_test=y_test)
    return d

def decision_tree_based_classification(d: MLDataSet):
    '''Classify the data with decision tree.'''
    clf = DecisionTreeClassifier(max_depth=5)
    clf = clf.fit(d.x_train, d.y_train)
    y_pred = clf.predict(d.x_test)
    print('--------------')
    print('Decision tree performance:')
    print('Accuracy: ', metrics.accuracy_score(d.y_test, y_pred=y_pred))
    print('F1 score: ', metrics.f1_score(d.y_test, y_pred=y_pred, average='weighted'))

def naive_bayes_classification(d: MLDataSet):
    '''Naive Bayes based classfication'''
    clf = CategoricalNB()
    clf = clf.fit(d.x_train, d.y_train)
    y_pred = clf.predict(d.x_test)
    print('--------------')
    print('Naive Bayes performance:')
    print('Accuracy: ', metrics.accuracy_score(d.y_test, y_pred=y_pred))
    print('F1 score: ', metrics.f1_score(d.y_test, y_pred=y_pred, average='weighted'))

def main():
    df = read_data()
    ds = process_data_frame_for_sklearn(df)
    decision_tree_based_classification(ds)
    naive_bayes_classification(ds)

if __name__ == '__main__':
    main()


# _*_ coding: utf-8 _*_
import pandas as pd

from analyzeData import common

class MergeRequestRate:
    """
    输入：一个项目的mr列表
    输出：三种rate

    类使用说明：
    1.提供初始化所用的mr列表并进行初始化
    2.调用get函数对三种rate进行获取

    ps：
    仅对一个项目进行rate计算与返回
    若要计算多个，请在外层进行循环
    """
    projects = []
    time_list = []
    time_label = []

    merge_request = []  # 存放一个项目的mr列表

    merge_request_num = {}  # mr总个数
    merged_mr_num = {}  # merged的mr个数
    closed_mr_num = {}  # closed个数
    opened_mr_num = {}  # opened个数

    merged_rate = []  # merged的mr比例
    closed_rate = []  # closed的比例
    opened_rate = []  # opened的比例

    def __init__(self, projects, date):
        """ 初始化构造函数 """

        """ 初始化项目列表 """
        self.set_pj(projects)

        """ 初始化时间列表 """
        self.set_tm(date)

        """ 初始化列表们 """
        self.init_lists()

        """ 计算三种比例 """
        self.rate_calculate()

    def init_lists(self):
        """ 初始化列表们 """

        for project in self.projects:
            self.merge_request_num[project] = {}

            self.merged_mr_num[project] = {}
            self.closed_mr_num[project] = {}
            self.opened_mr_num[project] = {}

            self.merged_rate.append([])
            self.closed_rate.append([])
            self.opened_rate.append([])

            self.set_pj_lists(project)

    def set_pj_lists(self, project):
        """ 设置列表们 """

        for time in self.time_label:
            self.merge_request_num[project][time] = 0
            self.merged_mr_num[project][time] = 0
            self.closed_mr_num[project][time] = 0
            self.opened_mr_num[project][time] = 0

    def set_tm(self, date):
        """ 设置时间列表 """

        self.time_list = common.getTimeListFromTuple(date)
        self.time_label = common.getTimeLableFromTime(self.time_list)

    def set_pj(self, projects):
        """ 设置project列表 """

        if isinstance(projects, list):
            self.projects = projects

    def set_mr(self, merge_request):
        """ 设置mr列表与统计mr总数 """

        """ 判断是否为列表，是的话，进行初始化 """
        if isinstance(merge_request, list):
            self.merge_request = merge_request
            # self.merge_request_num = len(merge_request)

    def rate_calculate(self):
        """ 计算三种比例 """

        for index, project in enumerate(self.projects):
            self.set_mr(common.getMergeRequestInstances(project))

            """ 对三种状态下的mr数量进行统计 """
            for mr in self.merge_request:
                time = mr.created_at[0:7]
                if time in self.merge_request_num[project].keys():
                    self.merge_request_num[project][time] += 1
                    if mr.state == 'merged':
                        self.merged_mr_num[project][time] += 1
                    elif mr.state == 'closed':
                        self.closed_mr_num[project][time] += 1
                    else:
                        self.opened_mr_num[project][time] += 1

            """ 对三种状态下的mr比例进行统计 """
            for i in self.merge_request_num[project].keys():
                self.merged_rate[index].append(self.merged_mr_num[project][i] / self.merge_request_num[project][i])
                self.closed_rate[index].append(self.closed_mr_num[project][i] / self.merge_request_num[project][i])
                self.opened_rate[index].append(self.opened_mr_num[project][i] / self.merge_request_num[project][i])

    def get_merged_rate(self):
        """ 返回merged状态的mr的比例 """
        return self.merged_rate

    def get_closed_rate(self):
        """ 返回closed状态的mr的比例 """
        return self.closed_rate

    def get_opened_rate(self):
        """ 返回opened状态的mr的比例 """
        return self.opened_rate

    def get_df_merged_rate(self):
        return pd.DataFrame(self.merged_rate, index=self.projects, columns=self.time_label)

    def get_df_closed_rate(self):
        return pd.DataFrame(self.closed_rate, index=self.projects, columns=self.time_label)

    def get_df_opened_rate(self):
        return pd.DataFrame(self.opened_rate, index=self.projects, columns=self.time_label)

if __name__ == '__main__':
    mrRate = MergeRequestRate(['tezos'], (2020, 7, 2020, 9))
    df1 = mrRate.get_df_merged_rate()
    print(df1)
    print('f')


''' @file examples/exp/replace.py
@brief Demonstrates use of the replace function.
'''
import sys
import os
# add the current working directory to the path
# DO NOT MOVE THE FOLLOWING STATEMENT
# if using autopep8 formatter, for example, set argument '--ignore=E402'
sys.path.append(os.getcwd())
from apg_py.exp.exp import ApgExp

title = '''This example will demonstrate how replace matched
results. The replacements can be simple string replacements,
replacements with components of the result or with a custom
function for complex replacements.
'''
print()
print(title)

pattern = '''start = X / Y
X = A B C
A = "a"
B = "b"
C = "c"
Y = 'xyz'
'''
print()
print('PATTERN')
print(pattern)
header = 'RESULT'
testno = 0

# replace only the first match
exp = ApgExp(pattern)
input = '---abc___xyz+++'
repl = '555'
result = exp.replace(input, repl)
testno += 1
print('\n' + str(testno) + ') Replace only the first match.')
print('input string: ' + input)
print('replacement string: ' + repl)
print(header)
print(result)

# replace all matches
exp = ApgExp(pattern, 'g')
input = '---abc___xyz+++'
result = exp.replace(input, repl)
testno += 1
print('\n' + str(testno) + ') Replace all matches with the "g" flag.')
print('input string: ' + input)
print('replacement string: ' + repl)
print(header)
print(result)

# special replacement characters
exp = ApgExp(pattern)
input = '---abc___xyz+++'
repl = '$$-$&->555-$$'
result = exp.replace(input, repl)
testno += 1
print('\n' + str(testno) + ') Special characters $$ and $&.')
print('input string: ' + input)
print('replacement string: ' + repl)
print(header)
print(result)
repl = 'left($`)|555|right($\')'
result = exp.replace(input, repl)
testno += 1
print('\n' + str(testno) + ') Special characters $` and $\'.')
print('input string: ' + input)
print('replacement string: ' + repl)
print(header)
print(result)

# rule name matches in replacement
exp.include()
repl = '${C}-${B}-${A}'
result = exp.replace(input, repl)
testno += 1
print('\n' + str(testno) + ') Special characters ${rulename}.')
print('input string: ' + input)
print('replacement string: ' + repl)
print(header)
print(result)

def fn(input, result):
    # note rule names are case insensitive and always stored in lower case
    if(len(result.rules['A'.lower()])):
        special = '555'
    else:
        special = '666'
    return special

# complex replacement function
exp = ApgExp(pattern, 'g')
exp.include()
result = exp.replace(input, fn)
testno += 1
print('\n' + str(testno) + ') Special function for complex replacement.')
print('input string: ' + input)
print(header)
print(result)

testno += 1
print(
    '\n' +
    str(testno) +
    ') See examples/exp/ast.py for an example of using the AST for a complex replacement function.')


# -*- coding: utf-8 -*-
"""
Created on Sun Jun 14 20:48:44 2020

@author: Maxim Speshilov
"""

import numpy as np
from multiprocessing import Pool

def newton_n(z_0):
    z = z_0
    f =  np.polynomial.Polynomial([1., 0, -2.,  -2.])
    df = f.deriv()
    roots = f.roots()
    max_iter = 100

    for n in range(max_iter):
        z = z - f(z) / df(z)

    k = np.argmin(np.abs(np.ones_like(roots) * z - roots))

    return k

if __name__ == '__main__':

     with Pool() as pool:

         x = np.linspace(-1., 1., 1000)
         y = np.linspace(-1., 1., 1000)
         xx, yy = np.meshgrid(x, y)
         points = np.vstack(np.vstack([xx.ravel(), yy.ravel()])).T
         points = points[:, 0] + 1.0j * points[:, 1]

         result = np.array(pool.map(newton_n, points)).reshape((1000, 1000))

         with open('newton.npy', 'wb') as fout:
             np.save(fout, result)

         print('Result in newton.npy')


# ！/usr/bin/python3
# -- coding: utf-8 --
# @Time : 2022/6/13 11:00 AM
# @Author : grady

from modem import voiceCall
from audio import Audio
import utime as time
from driver import GPIO
from driver import UART
import aliyun
import _thread

###############################
# 更改产品信息
productKey = "xxxxxxxx"
productSecret = "xxxxxxxx"
# 更改电话号码
# 需要发拨打的目标电话号码，长度为11的字符串格式
tele_phone = 'xxxxxxxxxxx'
###############################

global flag
flag = 0
# 实例化key1
key1 = GPIO(10, 10)
key1.open("KEY1")
# gbs初始化
gps_module = UART()
gps_module.open("serial1")
gps_module.setBaudRate(9600)  # gps模块的波特率是9600
readBuf = bytearray(512)  # 创建一个字节数组，用于接受串口数据

# 按键中断回调函数
def key1_callback(args):
    global flag, tele_phone
    if flag == 0:
        flag = 1
        # 拨打电话
        print('=== call ===')
        # 将yourphone改为用户电话号码，文本格式，加''
        vc.callStart(tele_phone)
        time.sleep(1)
    elif flag == 1:
        flag = 0
        # 挂断电话
        print('----callend----')
        vc.callEnd()
    else:
        pass
    key1.disableIrq()
    key1.clearIrq()

def enable_key():
    # 开启中断
    key1.enableIrq(key1_callback)

# 接听回调
def voice_callback(args):
    if args[0] == 10:
        print('voicecall incoming call, PhoneNO.: ', args[6])
    elif args[0] == 11:
        print('voicecall connected, PhoneNO.: ', args[6])
    elif args[0] == 12:
        print('voicecall disconnect')
    elif args[0] == 13:
        print('voicecall is waiting, PhoneNO.: ', args[6])
    elif args[0] == 14:
        print('voicecall dialing, PhoneNO.: ', args[6])
    elif args[0] == 15:
        print('voicecall alerting, PhoneNO.: ', args[6])
    elif args[0] == 16:
        print('voicecall holding, PhoneNO.: ', args[6])

# 纬度
def latitude(d, h):
    if d == "":
        return 0
    hemi = "" if h == "N" else "-"
    # 度
    deg = int(d[0:2])
    # 分
    min = str(float(d[2:]) / 60)[1:]
    return hemi + str(deg) + min

# 经度
def longitude(d, h):
    if d == "":
        return 0
    hemi = "" if h == "E" else "-"
    # 度
    deg = int(d[0:3])
    # 分
    min = str(float(d[3:]) / 60)[1:]

    return hemi + str(deg) + min

location_data = {}

def gps():
    while True:
        if flag == 1:
            # 串口读
            size = gps_module.read(readBuf)
            data = readBuf
            # print(readBuf)
            # 将字节数据转化成字符串数据
            data_str = data.decode()
            # 判断是否有数据 且数据中是否包含"$GNRMC"
            if size != 0 and "$GNRMC" in data_str and "$GNVTG" in data_str:
                # 删除"\r\n"后，字符串变为列表
                data_list = data_str.split('\r\n')
                for i in range(len(data_list)):
                    if "$GNRMC" in data_list[i]:
                        # print(data_list[i])
                        # 删除","
                        result = data_list[i].split(',')
                        # print(result)
                        # $GNRMC,075622.000,A,3116.56922,N,12044.12475,E,0.00,0.00,020422,,,A,V*01
                        # ['$GNRMC', '075622.000', 'A', '3116.56922', 'N', '12044.12475', 'E', '0.00', '0.00', '020422', '', '', 'A', 'V*01']
                        # 在GNRMC中取数据
                        if len(result) == 14:
                            lat = latitude(result[3], result[4])
                            long = longitude(result[5], result[6])
                            print("lat:", lat)
                            print("long:", long)
                            location_data['lat'] = lat
                            location_data['long'] = long
                            aliyun.up_data(location_data)
        else:
            pass
        time.sleep(1)

if __name__ == '__main__':
    aliyun.connect(productKey, productSecret)  # 连接阿里云
    # 拨打电话实例化
    vc = voiceCall()
    ad = Audio()
    ad.set_pa()  # 电话功能需要预先开启功放
    ad.setVolume(10)  # 设置音量
    time.sleep(1)
    # 设置自动应答
    vc.setCallback(voice_callback)  # 设置监听回调函数
    vc.setAutoAnswer(5000)  # 设置自动应答时间 ms

    print('-----start-----')
    _thread.start_new_thread(gps, ())  # 开启gps线程
    # 打开按键使能
    enable_key()


from transformers.convert_graph_to_onnx import convert
from transformers import AutoTokenizer, DistilBertTokenizer
from os import environ
from psutil import cpu_count
from onnxruntime import InferenceSession, SessionOptions, get_all_providers
import os

def pt2onnx(model_dir):
    # Handles all the above steps for you
    new_dir = f"onnx/{os.path.basename(model_dir)}/"
    convert(framework="pt", model=model_dir,
                            output=os.path.join(new_dir, 'model.onnx'), opset=11)
    tokenizer = AutoTokenizer.from_pretrained(model_dir)
    tokenizer.save_pretrained(new_dir)

def create_model_for_provider(model_path: str, provider: str) -> InferenceSession:
  assert provider in get_all_providers(), f"provider {provider} not found, {get_all_providers()}"
  # Few properties than might have an impact on performances (provided by MS)
  options = SessionOptions()
  options.intra_op_num_threads = 1

  # Load the model as a graph and prepare the CPU backend
  return InferenceSession(model_path, options, providers=[provider])

def prepare_input(tokens_ids):
    inputs_onnx = {k: v.cpu().detach().numpy() for k, v in tokens_ids.items()}
    print(inputs_onnx)
    return inputs_onnx

def load_model(model_dir):
    print(f"model dir is {model_dir}")
    tokenizer = DistilBertTokenizer.from_pretrained(model_dir)

    # Constants from the performance optimization available in onnxruntime
    # It needs to be done before importing onnxruntime
    environ["OMP_NUM_THREADS"] = str(cpu_count(logical=True))
    environ["OMP_WAIT_POLICY"] = 'ACTIVE'

    cpu_model = create_model_for_provider(os.path.join(model_dir, "model.onnx"), "CPUExecutionProvider")

    # Inputs are provided through numpy array
    model_inputs = tokenizer("My name is Bert", return_tensors="pt")
    inputs_onnx = prepare_input(model_inputs)

    # Run the model (None = get all the outputs)
    cpu_model.run(None, inputs_onnx)[0]

    return cpu_model

if __name__ == "__main__":
    from transformers import TFAutoModel, AutoTokenizer, AutoModel
    model = AutoModel.from_pretrained('distilbert-base-uncased')
    tokenizer = AutoTokenizer.from_pretrained('distilbert-base-uncased')

    dir = 'tmp'
    os.system(f'rm -r {dir}')
    os.system(f'rm -r onnx/{dir}')
    os.system(f'mkdir {dir}')

    model.save_pretrained(dir)
    tokenizer.save_pretrained(dir)

    pt2onnx(dir)
    load_model(os.path.join('onnx', dir))


import numpy as np
from loguru import logger
from rectpack import newPacker, PackingMode, PackingBin, SORT_AREA
from rectpack.maxrects import MaxRectsBaf, MaxRectsBl, MaxRectsBlsf, MaxRectsBssf

import utils, layers, superitems

MAXRECTS_PACKING_STRATEGIES = [MaxRectsBaf, MaxRectsBssf, MaxRectsBlsf, MaxRectsBl]

def maxrects_multiple_layers(superitems_pool, pallet_dims, add_single=True):
    """
    Given a superitems pool and the maximum dimensions to pack them into,
    return a layer pool with warm start placements
    """
    logger.debug("MR-ML-Offline starting")
    logger.debug(f"MR-ML-Offline {'used' if add_single else 'not_used'} as warm_start")
    logger.debug(f"MR-ML-Offline {len(superitems_pool)} superitems to place")

    # Return a layer with a single item if only one is present in the superitems pool
    if len(superitems_pool) == 1:
        layer_pool = layers.LayerPool(superitems_pool, pallet_dims, add_single=True)
        uncovered = 0
    else:
        generated_pools = []
        for strategy in MAXRECTS_PACKING_STRATEGIES:
            # Build initial layer pool
            layer_pool = layers.LayerPool(superitems_pool, pallet_dims, add_single=add_single)

            # Create the maxrects packing algorithm
            packer = newPacker(
                mode=PackingMode.Offline,
                bin_algo=PackingBin.Global,
                pack_algo=strategy,
                sort_algo=SORT_AREA,
                rotation=False,
            )

            # Add an infinite number of layers (no upper bound)
            packer.add_bin(pallet_dims.width, pallet_dims.depth, count=float("inf"))

            # Add superitems to be packed
            ws, ds, _ = superitems_pool.get_superitems_dims()
            for i, (w, d) in enumerate(zip(ws, ds)):
                packer.add_rect(w, d, rid=i)

            # Start the packing procedure
            packer.pack()

            # Build a layer pool
            for layer in packer:
                spool, scoords = [], []
                for superitem in layer:
                    spool += [superitems_pool[superitem.rid]]
                    scoords += [utils.Coordinate(superitem.x, superitem.y)]

                spool = superitems.SuperitemPool(superitems=spool)
                layer_pool.add(layers.Layer(spool, scoords, pallet_dims))
                layer_pool.sort_by_densities(two_dims=False)

            # Add the layer pool to the list of generated pools
            generated_pools += [layer_pool]

        # Find the best layer pool by considering the number of placed superitems,
        # the number of generated layers and the density of each layer dense
        uncovered = [len(pool.not_covered_superitems()) for pool in generated_pools]
        n_layers = [len(pool) for pool in generated_pools]
        densities = [pool[0].get_density(two_dims=False) for pool in generated_pools]
        pool_indexes = utils.argsort(list(zip(uncovered, n_layers, densities)), reverse=True)
        layer_pool = generated_pools[pool_indexes[0]]
        uncovered = uncovered[pool_indexes[0]]

    logger.debug(
        f"MR-ML-Offline generated {len(layer_pool)} layers with 3D densities {layer_pool.get_densities(two_dims=False)}"
    )
    logger.debug(
        f"MR-ML-Offline placed {len(superitems_pool) - uncovered}/{len(superitems_pool)} superitems"
    )
    return layer_pool

def maxrects_single_layer_offline(superitems_pool, pallet_dims, superitems_in_layer=None):
    """
    Given a superitems pool and the maximum dimensions to pack them into,
    try to fit each superitem in a single layer (if not possible, return an error)
    """
    logger.debug("MR-SL-Offline starting")

    # Set all superitems in layer
    if superitems_in_layer is None:
        superitems_in_layer = np.arange(len(superitems_pool))

    logger.debug(f"MR-SL-Offline {superitems_in_layer}/{len(superitems_pool)} superitems to place")

    # Iterate over each placement strategy
    ws, ds, _ = superitems_pool.get_superitems_dims()
    for strategy in MAXRECTS_PACKING_STRATEGIES:
        # Create the maxrects packing algorithm
        packer = newPacker(
            mode=PackingMode.Offline,
            bin_algo=PackingBin.Global,
            pack_algo=strategy,
            sort_algo=SORT_AREA,
            rotation=False,
        )

        # Add one bin representing one layer
        packer.add_bin(pallet_dims.width, pallet_dims.depth, count=1)

        # Add superitems to be packed
        for i in superitems_in_layer:
            packer.add_rect(ws[i], ds[i], rid=i)

        # Start the packing procedure
        packer.pack()

        # Feasible packing with a single layer
        if len(packer) == 1 and len(packer[0]) == len(superitems_in_layer):
            spool = superitems.SuperitemPool(superitems=[superitems_pool[s.rid] for s in packer[0]])
            layer = layers.Layer(
                spool, [utils.Coordinate(s.x, s.y) for s in packer[0]], pallet_dims
            )
            logger.debug(
                f"MR-SL-Offline generated a new layer with {len(layer)} superitems "
                f"and {layer.get_density(two_dims=False)} 3D density"
            )
            return layer

    return None

def maxrects_single_layer_online(superitems_pool, pallet_dims, superitems_duals=None):
    """
    Given a superitems pool and the maximum dimensions to pack them into, try to fit
    the greatest number of superitems in a single layer following the given order
    """
    logger.debug("MR-SL-Online starting")

    # If no duals are given use superitems' heights as a fallback
    ws, ds, hs = superitems_pool.get_superitems_dims()
    if superitems_duals is None:
        superitems_duals = np.array(hs)

    # Sort rectangles by duals
    indexes = utils.argsort(list(zip(superitems_duals, hs)), reverse=True)
    logger.debug(
        f"MR-SL-Online {sum(superitems_duals[i] > 0 for i in indexes)} non-zero duals to place"
    )

    # Iterate over each placement strategy
    generated_layers, num_duals = [], []
    for strategy in MAXRECTS_PACKING_STRATEGIES:
        # Create the maxrects packing algorithm
        packer = newPacker(
            mode=PackingMode.Online,
            pack_algo=strategy,
            rotation=False,
        )

        # Add one bin representing one layer
        packer.add_bin(pallet_dims.width, pallet_dims.depth, count=1)

        # Online packing procedure
        n_packed, non_zero_packed, layer_height = 0, 0, 0
        for i in indexes:
            if superitems_duals[i] > 0 or hs[i] <= layer_height:
                packer.add_rect(ws[i], ds[i], i)
                if len(packer[0]) > n_packed:
                    n_packed = len(packer[0])
                    if superitems_duals[i] > 0:
                        non_zero_packed += 1
                    if hs[i] > layer_height:
                        layer_height = hs[i]
        num_duals += [non_zero_packed]

        # Build layer after packing
        spool, coords = [], []
        for s in packer[0]:
            spool += [superitems_pool[s.rid]]
            coords += [utils.Coordinate(s.x, s.y)]
        layer = layers.Layer(superitems.SuperitemPool(spool), coords, pallet_dims)
        generated_layers += [layer]

    # Find the best layer by taking into account the number of
    # placed superitems with non-zero duals and density
    layer_indexes = utils.argsort(
        [
            (duals, layer.get_density(two_dims=False))
            for duals, layer in zip(num_duals, generated_layers)
        ],
        reverse=True,
    )
    layer = generated_layers[layer_indexes[0]]

    logger.debug(
        f"MR-SL-Online generated a new layer with {len(layer)} superitems "
        f"(of which {num_duals[layer_indexes[0]]} with non-zero dual) "
        f"and {layer.get_density(two_dims=False)} 3D density"
    )
    return layer


"""
Écrire une fonction duree qui reçoit deux paramètres debut et fin.
Ces derniers sont des couples (tuples de deux composantes)
dont la première composante représente une heure et la seconde les minutes.
"""
def duree(debut, fin):
    D = debut[0]*60 + debut[1]
    F = fin[0]*60 + fin [1]
    if D < F:
        result = F - D
        H = result//60
        M = result % 60
        dur = (H,M)
    else:
        result = 1440 + (F-D)
        H = result//60
        M = result % 60
        dur = (H,M)
    return dur

duree ((14, 39), (18, 45)) #(4, 6)


import pprint
import math
from time import perf_counter
import cProfile

def find_neighbors(pos):
    row,col=pos
    list_pos=list()
    for dr in [-1,0,1]:
        for dc in [-1,0,1]:
            list_pos.append((row+dr,col+dc))
    del list_pos[list_pos.index((row,col))]
    return list_pos

def find_distance(pos1,pos2):
    row1,col1=pos1
    row2,col2=pos2
    return math.sqrt(pow(row1-row2,2)+pow(col1-col2,2))

class DijkstraSolver:
    def __init__(self, filepath):
        """Zero based with
           <space> or <period>=open
           s=start
           f=finish
           anything else=wall"""
        self.filepath=filepath
        # Map characters in file to initial distances or walls
        map_char={"s": 0,
                  "f": float("inf"),
                  " ": float("inf"),
                  ".": float("inf")}
        self.dist_visited=dict()
        self.dist_unvisited=dict()
        # Read file contents, row by row
        with open(self.filepath,"r") as file_handle:
            has_start=False
            has_finish=False
            row=0
            for line in file_handle:
                column=0
                for element in line:
                    if element=="f":
                        if not has_finish:
                            self.finish=(row,column)
                            has_finish=True
                        else:
                            raise ValueError("File contains multiple end points")
                    if element=="s":
                        if not has_start:
                            self.start=(row,column)
                            has_start=True
                        else:
                            raise ValueError("File contains multiple start points")
                    init_dist=map_char.get(element,"wall")
                    visited=(init_dist=="wall" or element==has_start)
                    if visited:
                        self.dist_visited[(row, column)]={"dist": init_dist,
                                                         "parent": None}
                    else:
                        self.dist_unvisited[(row, column)]={"dist": init_dist,
                                                            "parent": None}
                    column+=1
                row+=1
            if not has_finish:
                raise ValueError("File does not contain end point")
            if not has_start:
                raise ValueError("File does not contain start point")

    def find_path(self):
        current=self.start
        current_point=self.dist_unvisited[self.start]
        outside={'dist': 'wall', 'parent': None}
        while self.finish not in self.dist_visited:
            #print("Currently on", current)
            for neighbor in find_neighbors(current):
                #print("  Checking neighbor",neighbor)
                neighbor_point=self.dist_unvisited.get(neighbor,outside)
                #print("    Neighbor",neighbor,"is not visited")
                neighbor_dist=current_point["dist"]
                neighbor_dist+=find_distance(current,neighbor)
                if not isinstance((neighbor_point["dist"]), str) and \
                                neighbor_point["dist"]>neighbor_dist:
                    neighbor_point["dist"]=neighbor_dist
                    neighbor_point["parent"]=current
                    #print("    Neighbor distance is",neighbor_dist)
                    #print("    Neighbor parent is",current)
                    #print("    Neighbor",neighbor,"is visited")
            self.dist_visited[current]=self.dist_unvisited.pop(current)
            #print("  Point",current,"is visited")
            #print("  ",end="")
            #pprint.pprint(current_point)
            mindist=float("inf")
            minpoint=None
            for point in self.dist_unvisited:
                point_dict=self.dist_unvisited[point]
                point_dist=point_dict["dist"]
                if point != current:
                    if not isinstance(point_dist,str) and \
                                mindist>point_dist:
                        mindist=point_dist
                        minpoint=point
            if minpoint is None:
                exit_while=True
                break
            else:
                exit_while=False
            current=minpoint
            current_point=self.dist_unvisited[current]
        #endwhile
        if exit_while:
            return "There is no pathway"
        else:
            next_point=self.finish
            pathway=[next_point]
            while next_point != self.start:
                next_point=self.dist_visited[next_point]["parent"]
                pathway.append(next_point)
            pathway.reverse()
            ans_dict=dict()
            ans_dict["path"]=pathway
            ans_dict["dist"]=self.dist_visited[self.finish]["dist"]
            return ans_dict

if __name__=="__main__":
    filename=input("Please enter a filename: ")
    q=DijkstraSolver(filename)
    pprint.pprint(q.dist_visited)
    print("Start node is:", q.start)
    print("Finish node is:", q.finish)
    #start=perf_counter()
    cProfile.run("path=q.find_path()")
    #end=perf_counter()
    print("Path is:")
    pprint.pprint(path)
    #print("Time taken is:",end-start)


from conans import ConanFile, CMake, tools
from conans.errors import ConanInvalidConfiguration
import os

required_conan_version = ">=1.33.0"

class GeographiclibConan(ConanFile):
    name = "geographiclib"
    description = "Convert geographic units and solve geodesic problems"
    topics = ("conan", "geographiclib", "geodesic")
    url = "https://github.com/conan-io/conan-center-index"
    homepage = "https://geographiclib.sourceforge.io"
    license = "MIT"

    settings = "os", "arch", "compiler", "build_type"
    options = {
        "shared": [True, False],
        "fPIC": [True, False],
        "precision": ["float", "double", "extended", "quadruple", "variable"],
        "tools": [True, False]
    }
    default_options = {
        "shared": False,
        "fPIC": True,
        "precision": "double",
        "tools": True
    }

    exports_sources = ["CMakeLists.txt"]
    generators = "cmake"
    _cmake = None

    @property
    def _source_subfolder(self):
        return "source_subfolder"

    @property
    def _build_subfolder(self):
        return "build_subfolder"

    def config_options(self):
        if self.settings.os == "Windows":
            del self.options.fPIC

    def configure(self):
        if self.options.shared:
            del self.options.fPIC

    @property
    def _min_compiler_version_default_cxx11(self):
        # Minimum compiler version having C++11 math functions
        return {
            "apple-clang": "3.3",
            "gcc": "4.9",
            "clang": "6",
            "Visual Studio": "14",  # guess
        }.get(str(self.settings.compiler), False)

    def validate(self):
        if tools.Version(self.version) >= "1.51":
            if self.settings.compiler.get_safe("cppstd"):
                tools.check_min_cppstd(self, 11)

            def lazy_lt_semver(v1, v2):
                lv1 = [int(v) for v in v1.split(".")]
                lv2 = [int(v) for v in v2.split(".")]
                min_length = min(len(lv1), len(lv2))
                return lv1[:min_length] < lv2[:min_length]

            minimum_version = self._min_compiler_version_default_cxx11
            if not minimum_version:
                self.output.warn("geographiclib {} requires C++11 math functions. Your compiler is unknown. Assuming it supports this feature.".format(self.version))
            elif lazy_lt_semver(str(self.settings.compiler.version), minimum_version):
                raise ConanInvalidConfiguration("geographiclib {} requires C++11 math functions, which your compiler does not support.".format(self.version))

        if self.options.precision not in ["float", "double"]:
            # FIXME: add support for extended, quadruple and variable precisions
            # (may require external libs: boost multiprecision for quadruple, mpfr for variable)
            raise ConanInvalidConfiguration("extended, quadruple and variable precisions not yet supported in this recipe")

    def source(self):
        tools.get(**self.conan_data["sources"][self.version],
                  destination=self._source_subfolder, strip_root=True)

    def _patch_sources(self):
        cmakelists = os.path.join(self._source_subfolder, "CMakeLists.txt")
        # it does not work on Windows but is not needed
        tools.replace_in_file(cmakelists, "add_subdirectory (js)", "")
        # Don't install system libs
        tools.replace_in_file(cmakelists, "include (InstallRequiredSystemLibraries)", "")
        # Don't build tools if asked
        if not self.options.tools:
            tools.replace_in_file(cmakelists, "add_subdirectory (tools)", "")
            tools.replace_in_file(os.path.join(self._source_subfolder, "cmake", "CMakeLists.txt"),
                                  "${TOOLS}", "")

    def _configure_cmake(self):
        if not self._cmake:
            self._cmake = CMake(self)
            self._cmake.definitions["GEOGRAPHICLIB_LIB_TYPE"] = "SHARED" if self.options.shared else "STATIC"
            self._cmake.definitions["GEOGRAPHICLIB_PRECISION"] = self._cmake_option_precision
            self._cmake.configure(build_folder=self._build_subfolder)
        return self._cmake

    @property
    def _cmake_option_precision(self):
        return {
            "float": 1,
            "double": 2,
            "extended": 3,
            "quadruple": 4,
            "variable": 5,
        }.get(str(self.options.precision))

    def build(self):
        self._patch_sources()
        cmake = self._configure_cmake()
        cmake.build()

    def package(self):
        self.copy(pattern="LICENSE.txt", dst="licenses", src=self._source_subfolder)
        cmake = self._configure_cmake()
        cmake.install()
        for folder in ["share", os.path.join("lib", "python"), os.path.join("lib", "pkgconfig"),
                       os.path.join("lib", "cmake"), "sbin", "python", "matlab", "doc", "cmake"]:
            tools.rmdir(os.path.join(os.path.join(self.package_folder, folder)))
        tools.remove_files_by_mask(os.path.join(self.package_folder, "bin"), "*.pdb")

    def package_info(self):
        self.cpp_info.filenames["cmake_find_package"] = "geographiclib"
        self.cpp_info.filenames["cmake_find_package_multi"] = "geographiclib"
        self.cpp_info.names["cmake_find_package"] = "GeographicLib"
        self.cpp_info.names["cmake_find_package_multi"] = "GeographicLib"
        self.cpp_info.libs = tools.collect_libs(self)
        self.cpp_info.defines.append("GEOGRAPHICLIB_SHARED_LIB={}".format("1" if self.options.shared else "0"))

        if self.options.tools:
            bin_path = os.path.join(self.package_folder, "bin")
            self.output.info("Appending PATH environment variable: {}".format(bin_path))
            self.env_info.PATH.append(bin_path)


import yaml
# from optparse import OptionParser
import argparse
import torch
import wandb
import os

from models.build import build_model
import utils.multiprocessing as mpu
import utils.utils as uu
import train
import utils.distributed as du

parser = argparse.ArgumentParser()
parser.add_argument("--config_file", dest="config_file")
parser.add_argument("--only_test", dest="only_test", action='store_true')
parser.add_argument("--feature_extract", dest="feature_extract", action='store_true')

parser.add_argument("--only_test_epoch", dest="only_test_epoch", type=int, default=-1)
parser.add_argument(
        "--init_method",
        dest="init_method",
        help="Initialization method, includes TCP or shared file-system",
        default="tcp://localhost:9999",
        type=str,
    )
parser.add_argument("--model_path", dest="model_path", default='')
parser.add_argument("--experiment_save_dir", dest="experiment_save_dir", default='')
parser.add_argument("--experiment_save_dir_default", dest="experiment_save_dir_default", default='')
parser.add_argument("--calculate_triplet_loss", dest="calculate_triplet_loss", default=True)

parser.add_argument("--training_scene_dir", dest="training_scene_dir", default='')
parser.add_argument("--testing_scene_dir", dest="testing_scene_dir", default='')
parser.add_argument("--csv_file_path", dest="csv_file_path", default='')
parser.add_argument("--training_yaml_file_dir", dest="training_yaml_file_dir", default='')
parser.add_argument("--testing_yaml_file_dir", dest="testing_yaml_file_dir", default='')
parser.add_argument("--model_dir", dest="model_dir", default='')

def fill_in_args_from_terminal(args, options):
    if options.model_dir != '':
        args.files.model_dir = options.model_dir
    if options.training_scene_dir != '':
        args.files.training_scene_dir = options.training_scene_dir
    if options.training_yaml_file_dir != '':
        args.files.training_yaml_file_dir = options.training_yaml_file_dir
    if options.testing_yaml_file_dir != '':
        args.files.testing_yaml_file_dir = options.testing_yaml_file_dir
    if options.csv_file_path != '':
        args.files.csv_file_path = options.csv_file_path

    if options.testing_scene_dir != '':
        args.files.testing_scene_dir = options.testing_scene_dir

    if options.experiment_save_dir != '':
        args.experiment_save_dir = options.experiment_save_dir

    if options.experiment_save_dir_default != '':
        args.experiment_save_dir_default = options.experiment_save_dir_default

    if options.model_path != '':
        args.model_config.model_path = options.model_path
        args.training_config.epochs = int(options.model_path.split('/')[-1].split('.')[0])

    if options.only_test_epoch > 0:
        args.training_config.epochs = options.only_test_epoch

    if options.only_test:
        args.training_config.train = False
    if options.feature_extract:
        args.testing_config.feature_extract = True

    args.testing_config.calculate_triplet_loss = options.calculate_triplet_loss

    return args

def main():
    # (options, args) = parser.parse_args()
    options = parser.parse_args()
    f =  open(options.config_file)
    # f = open('configs/config_all_occlusion.yaml')
    args_dict = yaml.safe_load(f)
    default_args_dict = yaml.safe_load(open('configs/default.yaml'))
    args_dict_filled = uu.fill_in_args_from_default(args_dict, default_args_dict)
    args = uu.Struct(args_dict_filled)

    args = fill_in_args_from_terminal(args, options)

    if args.num_gpus > 1:
        torch.multiprocessing.spawn(
            mpu.run,
            nprocs=args.num_gpus,
            args=(
                args.num_gpus,
                train.train,
                options.init_method,
                0,
                1,
                "nccl",
                args,
            ),
            daemon=False,
        )
    else:
        train.train(args)

if __name__ == "__main__":
    torch.multiprocessing.set_start_method("forkserver")
    main()


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

import zipfile,os,time,random,hashlib,json,ConfigParser,const,sys,constTable

class Common:
    CONST=const
    CONST.RUNTIME_PATH=os.path.dirname(os.path.realpath(__file__))+"/../runtime"
    CONST.CONF_PATH=os.path.dirname(os.path.realpath(__file__))+"/../config"
    CONST.ERROR=constTable.constTable().ERROR

    def __init__(self):
        pass

    def dp(self,obj):
        print(obj)
        sys.exit(-1)

    def tanslate(self,str,form_code="utf-8",to_code="cp936"):
        return str.decode(form_code).encode(to_code)

    def dict2json(self,dict):
        return json.dumps(dict)

    def json2dict(self,json_str):
        return json.loads(json_str)

    def readBinFile(self,fs,length):
            return fs.read(length)

    def writeBinFile(self,path,text,mode="wb"):
        pass

    def readFile(self,path,mode):
        file = open(path, mode)
        try:
           text = file.read()
        finally:
            file.close()
        return text

    def writeFile(self,path,text,mode):
        file = open(path, mode)
        try:
            file.write(text)
        finally:
            file.close()

    def baleZip(self,form_file_path,to_file_path):
        to_file_path+=".zip"
        z = zipfile.ZipFile(to_file_path, 'w', zipfile.ZIP_DEFLATED)
        startdir = form_file_path
        child_list=[]
        self.baleFolder(startdir,child_list)

        for filename in child_list:
            pre_len = len(os.path.dirname(filename))
            arcname = filename[pre_len:].strip(os.path.sep)   #相对路径
            z.write(filename, arcname)
        z.close()
        return to_file_path

    def baleFolder(self,dir_path,child_list):
        parents = os.listdir(dir_path)
        for parent in parents:
            child = os.path.join(dir_path,parent)
            if os.path.isdir(child):
                if os.stat(child).st_size<=0:
                    child_list.append(child)
                else:
                    child_list =  self.baleFolder(child,child_list)
            else:
                child_list.append(child)
        return child_list

    def getRuntimeDir(self,sub_dir=".",isFull=False,isTemp=""):
        runTimePath=self.CONST.RUNTIME_PATH

        if isFull:
           runTimePath += "/"+sub_dir+"/"+time.strftime("%Y/%m/%d", time.localtime())

        if len(isTemp)>0:
            runTimePath+="/"+isTemp

        if not os.path.exists(runTimePath):
            os.makedirs(runTimePath)

        return runTimePath

    def md5(self,str):
        m = hashlib.md5()
        m.update(str)
        return m.hexdigest()

    def getConf(self,conf_path,section,option):
        cf = ConfigParser.ConfigParser()
        cf.read(conf_path)
        return cf.get(section,option)

    def getClientConf(self,section,option):
        return self.getConf(self.CONST.CONF_PATH,section,option)

    def createPacket(self,data,package_num,method="",status=""):
        head={
                "method":method,
                "package_num":package_num,
                "size":len(data),
                "md5":self.md5(data),
                "data":data,
                "status":status
             }

        packet=""
        for key, value in head.items():
            if(str(value)!=""):
                packet+=str(key)+":"+str(value)+"\n"
        return packet+"\0"

    def createRetStrPackage(self,package_num,error,size):
        if not self.CONST.ERROR.has_key(error):
            error="FAIL"
        error_num=self.CONST.ERROR[error]

        return self.createPacket(error+"|"+str(size),package_num,status=error_num)

    def getDirSize(self,path):
        size=0
        for root, dirs, files in os.walk(path):
            for f in files:
                size += os.path.getsize(os.path.join(root, f))
        return size

    def getFileSize(self,path):
        return os.path.getsize(path)


'''Entry point for chineurs server'''
from concurrent.futures import ThreadPoolExecutor
import functools
import json
import urllib

from flask import jsonify, redirect, render_template, request, session, url_for

from chineurs import (
    authentication,
    celery,
    facebook_group,
    resources,
    storage,
    youtube_playlist)
from chineurs.app import APP

@APP.errorhandler(authentication.AuthExpired)
def handle_expired_credentials(error):  # pylint:disable=unused-argument
    '''Handles expired credentials'''
    APP.logger.exception(
        'Auth expired, redirecting from {}'.format(request.url))
    return redirect(authentication.get_facebook_authentication_uri(
        full_url('facebook')))

def user_id_required(route):
    '''Wraps a route to require a UUID and redirect if not present'''
    @functools.wraps(route)
    def decorated_route(*args, **kwargs):
        '''Checks if user_id is in session, redirects to authenticate if not'''
        if 'user_id' not in session:
            APP.logger.info(
                'No user id, redirecting from {}'.format(request.url))
            return redirect(
                authentication.get_facebook_authentication_uri(
                    full_url('facebook')))
        return route(*args, **kwargs)
    return decorated_route

@APP.route('/logout')
def logout():
    '''Clears session'''
    APP.logger.info('Clearing UUID')
    session.clear()
    return redirect(url_for('home'))

@APP.route('/')
@user_id_required
def home():
    '''Home page'''
    user = storage.get_user_by_id(session['user_id'])  # pylint:disable=E1120
    headers = {}
    user['google_credentials'].apply(headers)
    executor = ThreadPoolExecutor(max_workers=2)
    fb_groups = executor.submit(lambda: facebook_group.get_groups(
        user['fb_access_token']))
    playlists = executor.submit(lambda: youtube_playlist.get_playlists(
        headers))
    return render_template(
        'index.html',
        resources=resources.get_resources(),
        data=json.dumps({
            'update_url': url_for('update'),
            'facebook_groups': fb_groups.result(),
            'youtube_playlists': playlists.result()}))

@APP.route('/facebook')
def facebook():
    '''Gets the Facebook auth token and stores it in cookies'''
    session['user_id'] = authentication.save_facebook_access_token(
        request.args.get('code'),
        full_url('facebook'))
    return redirect(
        authentication.get_google_authentication_uri(full_url('google')))

@APP.route('/google')
def google():
    '''Saves Google credentials'''
    authentication.save_google_credentials(
        session['user_id'],
        request.args.get('code'),
        full_url('google'))
    return redirect(url_for('home'))

@APP.route('/update', methods=['POST'])
def update():
    '''Uploads all new videos to YouTube'''
    task_uuid = storage.new_job()  # pylint:disable=E1120
    celery.update.delay(
        session['user_id'],
        request.get_json()['group_id'],
        request.get_json()['playlist_id'],
        task_uuid)
    return jsonify({'done_url': url_for('done', task_uuid=task_uuid)})

@APP.route('/done/<task_uuid>')
def done(task_uuid):
    '''Checks if a given youtube upload request if done'''
    # pylint:disable=E1120
    return jsonify(storage.get_job_progress(task_uuid))
    # pylint:enable=E1120

def full_url(route):
    '''Returns an absolute URL using the host in the request'''
    parts = urllib.parse.urlparse(request.url)
    scheme = parts[0]
    netloc = parts[1]
    return urllib.parse.urlunparse(
        [scheme, netloc, url_for(route), None, None, None])

# if APP.debug:
#     from werkzeug.contrib.profiler import ProfilerMiddleware
#     APP = ProfilerMiddleware(APP, open('profile', 'w'))