# Simple Server API with Users
# Copyright Brett Hartshorn 2012-2013
# License: "New" BSD

import os, sys, ctypes, time, json, struct, inspect
import random
import bpy

## make sure we can import and load data from same directory ##
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
if SCRIPT_DIR not in sys.path: sys.path.append( SCRIPT_DIR )

import core
import Server
import simple_action_api
import api_gen
from api_gen import BlenderProxy, UserProxy, Animation, Animations
from websocket import websocksimplify

class UserServer( websocksimplify.WebSocketServer ):
	pass

class BlenderServer( core.BlenderHack ):

	def start_server(self):
		self.websocket_server = s = UserServer()
		host = Server.HOST_NAME
		port = 8080
		for arg in sys.argv:
			if arg.startswith('--port='):
				port = int( arg.split('=')[-1] )
			if arg.startswith('--ip='):
				a = arg.split('=')
				if len(a) == 2 and a[-1]:
					host = a[-1]

		Server.set_host_and_port( host, port )

		s.initialize(
			listen_host=host,
			listen_port=port,
			read_callback=self.on_websocket_read_update,
			write_callback=self.on_websocket_write_update,
			new_client_callback=self.on_new_client,
		)
		lsock = s.create_listener_socket()
		s.start_listener_thread()

	def on_new_client(self, sock):
		addr = sock.getpeername()
		print('[on new client]', addr)

		if addr in Server.GameManager.clients:
			print('[websocket] RELOADING CLIENT:', addr )
			raise SystemExit
		else:
			print('_'*80)
			print('[websocket] NEW CLIENT:', addr )
			Server.GameManager.add_player( addr, websocket=sock )

	def on_websocket_read_update(self, sock, frames):
		'''
		protocol:
			if first byte is null, then the next 24 bytes is the camera location as packed floats,
			if its a single byte then its a keystroke,
			if it begins with "{" and ends with "}" then its a json message/request,
			otherwise it is part of the generated websocket api.
		'''

		player = Server.GameManager.get_player_by_socket( sock )
		if not player: return
		addr = player.address

		for frame in frames:
			if not frame: continue
			if frame[0] == 0:
				frame = frame[1:]
				if len(frame)!=24:
					print(frame)
					continue

				x1,y1,z1, x2,y2,z2 = struct.unpack('<ffffff', frame)
				#print(x1,y1,z1)
				if addr in Server.GameManager.clients:
					player = Server.GameManager.clients[ addr ]
					player.set_focal_point( (x2,y2,z2) )
					player.set_location( (x1,y1,z1) )    # callbacks get triggered
				else:
					print('[websocket ERROR] client address not in GameManager.clients')
					raise RuntimeError

			elif len(frame) == 1: ## TODO unicode 2bytes
				print(frame)
				print( frame.decode('utf-8') )

			elif len(frame) > 2 and chr(frame[0]) == '{' and chr(frame[-1]) == '}':
				jmsg = json.loads( frame.decode('utf-8') )
				print('client sent json data', jmsg)
				player.on_websocket_json_message( jmsg )

			else:
				print('doing custom action...', frame)
				## action api ##
				code = chr( frame[0] )
				action = player.new_action(code, frame[1:])
				## logic here can check action before doing it.
				if action:
					#assert action.calling_object
					action.do()

	_bps = 0
	_bps_start = None
	_debug_kbps = True
	def on_websocket_write_update(self, sock):
		player = Server.GameManager.get_player_by_socket( sock )
		msg = player.create_message_stream( bpy.context )
		if msg is None:
			#return None
			return bytes(0)

		rawbytes = json.dumps( msg ).encode('utf-8')
		if self._debug_kbps:
			now = time.time()
			self._bps += len( rawbytes )
			#print('frame Kbytes', len(rawbytes)/1024 )
			if self._bps_start is None or now-self._bps_start > 1.0:
				print('kilobytes per second', self._bps/1024)
				self._bps_start = now
				self._bps = 0
		return rawbytes

	def setup_websocket_callback_api(self, api):
		simple_action_api.create_callback_api( api )

class App( BlenderServer ):
	def __init__(self, api):
		print('init server app')
		self.setup_server(api)

	def setup_server(self, api):
		api.update( api_gen.get_decorated() )
		self.setup_websocket_callback_api(api)
		self.setup_blender_hack( bpy.context, use_gtk=False, headless=True )
		print('blender hack setup ok')
		Server.set_api( self )
		print('custom api set')

	def mainloop_poll(self, now, dt):  ## for subclasses to overload ##
		time.sleep(0.01)

	def mainloop(self):
		print('enter main')
		drops = 0
		self._mainloop_prev_time = time.time()
		self.active = True
		while self.active:
			now = time.time()
			dt = 1.0 / 30.0
			if now - self._mainloop_prev_time:
				dt = 1.0 / ( now - self._mainloop_prev_time )
			self._mainloop_prev_time = now
			#print('FPS', dt)

			for ob in bpy.data.objects:  ## this is threadsafe?
				#ob.update_tag( {'OBJECT', 'DATA', 'TIME'} )  ## super slow
				ob.update_tag( {'OBJECT'} )

			api_gen.AnimationManager.tick()
			bpy.context.scene.update()  ## required for headless mode

			fully_updated = self.update_blender()
			self.mainloop_poll(now, dt)

def default_click_callback( user=UserProxy, ob=BlenderProxy ):
	print('select callback', user, ob)
	w = api_gen.get_wrapped_objects()[ ob ]
	view = w( user )
	view['selected'] = time.time()  ## allow multiple selections, the server can filter to most recent to.
	if 0:
		view['location'] = list( ob.location.to_tuple() )
		#view['location'] = Animation( seconds=3.0, y=-5.0) # TODO relative and absolute
		view['location'] = Animations(
			Animation( seconds=3.0, y=-5.0),
			Animation( seconds=3.0, y=5.0),
			Animation( seconds=3.0, z=1.0),
			Animation( seconds=3.0, z=-1.0),
		)
		view['rotation_euler'] = list( ob.rotation_euler )
		view['rotation_euler'] = Animations(
			Animation( seconds=3.0, x=-5.0),
			Animation( seconds=3.0, x=5.0),
		)
		view().on_click = api_gen.get_callback( 'next1')

def next1( user=UserProxy, ob=BlenderProxy ):
	print('next click callback1')
	w = api_gen.get_wrapped_objects()[ ob ]
	view = w( user )
	view['color'] = [1,1,0, 1]
	view().on_click = api_gen.get_callback( 'next2')

def next2( user=UserProxy, ob=BlenderProxy ):
	print('next click callback2')
	w = api_gen.get_wrapped_objects()[ ob ]
	view = w( user )
	view['color'] = [0,1,1, 1]
	view().on_click = api_gen.get_callback( 'next3')

def next3( user=UserProxy, ob=BlenderProxy ):
	print('next click callback3')
	w = api_gen.get_wrapped_objects()[ ob ]
	view = w( user )
	view['color'] = Animations(
		Animation( seconds=2.0, x=0.5, y=0.5, z=0.1),
		Animation( seconds=2.0, x=1.0, y=0.1, z=0.5),
		Animation( seconds=2.0, z=1.0),
		Animation( seconds=2.0, z=-1.0),
	)
	#view[ '.modifiers["Bevel"].width' ] = 0.5  # this style is simple ## TODO mesh streaming so this can be tested, support bevel in dump_collada

def default_input_callback( user=UserProxy, ob=BlenderProxy, input_string=ctypes.c_char_p ):
	print( 'default INPUT CALLBACK', user, ob, input_string )
	#if ob.name == 'login':
	#	if 'login.input' not in bpy.data.objects:
	#		a = bpy.data.objects.new(
	#			name="[data] %s"%name,
	#			object_data= a.data
	#		)
	#		bpy.context.scene.objects.link( a )
	#		a.parent = ob
	w = api_gen.get_wrapped_objects()[ ob ]
	view = w( user )

API = {
	'default_click': default_click_callback,
	'default_input'	: default_input_callback,
	'next1' : next1,
	'next2' : next2,
	'next3' : next3,
}

if __name__ == '__main__':
	app = App( API )
	app.start_server()
	print('-----main loop------')
	app.mainloop()


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

import sys
import math
import numpy as np
import collections
import matplotlib.pyplot as plt
from Planner import Planner
from PriorityQueue import PriorityQueue

class RRTPlanner(Planner):

    def plan(self, environment, start, goal):
        """
        Method to plan the path

        Parameters
        ----------
        environment: Environment
            Map of the environment that provides collision checking
        start: numpy array (6x1)
            start configuration of the robot (x,y,z,phi_x,phi_y,phi_z)
        goal: numpy array (6x1)
            goal configuration of the robot (x,y,z,phi_x,phi_y,phi_z)

        Returns
        -------
        list(numpy array (4x4))
            the path between the start and the goal Pose in SE(3) coordinates
        """

        n_samples = 1

        nodes = []
        nodes.append(start)

        predecessors = []
        predecessors.append(-1)

        n_iterations = 0

        # environment.plot_environment(self.construct_pose_matrix(start))
        while True:
            # Generate valid sample
            sample = self.generate_samples(n_samples, start.size)[0]
            while environment.check_robot_collision(self.construct_pose_matrix(sample)):
                sample = self.generate_samples(n_samples, start.size)[0]

            # Find the nearest node to the sample
            min_node_index = -1
            min_distance = np.inf
            for i in range(len(nodes)):
                distance = np.linalg.norm(nodes[i][0:3] - sample[0:3])
                if min_distance > distance:
                    min_distance = distance
                    min_node_index = i

            # distance_queue = PriorityQueue()
            # for i in range(len(nodes)):
            #     distance = np.linalg.norm(nodes[i][0:3] - sample[0:3])
            #     distance_queue.push(i, distance)

            # Add small step toward the sample
            # while distance_queue.empty() == False:
            # _, top = distance_queue.pop()
            min_node = nodes[min_node_index]

            # Compute the new point
            computed_path, _ = self.compute_path_between(min_node, sample)
            new_node = computed_path[0]

            # Check if the new node is valid
            if environment.check_robot_collision(self.construct_pose_matrix(new_node)):
                continue

            nodes.append(new_node)
            predecessors.append(min_node_index)
            # self.plot_nodes([new_node])

            # Check if the goal is reachable
            if self.is_goal_reachable(nodes[-1], goal, environment):
                break

            if n_iterations % 100 == 0:
                print("Iteration:", n_iterations)
            n_iterations += 1

        # Add the goal state to the nodes list
        predecessors.append(len(nodes) - 1)
        nodes.append(goal)

        # Path reconstruction
        path = self.reconstruct_path(nodes, predecessors, len(nodes) - 1)

        return list(map(lambda x: self.construct_pose_matrix(x), path))

    def is_goal_reachable(self, node, goal, environment):
        path, _ = self.compute_path_between(node, goal)
        return self.is_path_valid(path, environment)

FEL-UIR/05 Randomized Sampling-based Algorithms/samplingplanner/RRTPlanner.py


import pytest
import click.testing

from chess_stats import console

@pytest.fixture
def runner():
    return click.testing.CliRunner()

@pytest.mark.e2e
def test_main_succeeds(runner):
    result = runner.invoke(
        console.main, args=["jjjulio", "2020"], catch_exceptions=False
    )
    assert result.exit_code == 0


import numpy as np
import matplotlib.pyplot as mlp

# konstanter
l = 1. # fjaerkonstant i kg/s**2
m = 1. # masse i kg

# egenfrekvens i Hz
omega_0 = np.sqrt( l/m )

# tidskritt i s
delta_t = 0.01

# antal tidsskritt
nn = 5000

# array for tid
t = np.empty( nn )
# array for utslaget
x = np.empty( nn )
# array for hastighet
v = np.empty( nn )

# initialbetingelser
t[0] = 0.
x[0] = 0. # initiale utslaget er 0
v[0] = 1. # initiale hastigheten er 1 m/s

for i in range( 1, nn ):

    # gaa et tidskritt
    t[i] = t[i-1] + delta_t

    # hastighet
    v[i] = v[i-1] - omega_0**2*x[i-1]*delta_t
    # posisjon
    x[i] = x[i-1] + v[i-1]*delta_t

# beregner potensielle energi
e_p = 0.5*l*x**2

# beregner kinetisk energi
e_k = 0.5*m*v**2

mlp.plot( t, x, 'r', t, v, 'g' )
mlp.xlabel("tid")
mlp.ylabel("utslag/hastighet")
mlp.show()


import os.path as osp
import numpy as np
import torch
from torch_geometric.datasets import TUDataset
from torch_geometric.data import DataLoader
from data import NodeDegreeFeatureDataLoader, SameFeatureDataLoader
from train import train

def prepare_config_for_dataset(config, dataset):
    if config.node_features == 'node_degree':
        get_max_node_degree
        dataset_loader = DataLoader(dataset, batch_size=config.batch_size)
        max_node_degree = 0
        min_node_degree = 1000000
        for data in dataset_loader:
            edge_index, _ = remove_self_loops(data.edge_index)
            row, col = edge_index
            out = scatter_add(torch.ones(len(data.batch))[col], row, dim=0, dim_size=len(data.batch))
            max_node_degree = max(max_node_degree, out.max())
        config.max_node_degree = max_node_degree
        config.num_features = max_node_degree + 1
    elif config.node_features == 'categorical':
        data = next(iter(dataset_loader))
        config.num_features = data.x.shape[1]
    elif config.node_features == 'same':
        config.num_features = config.same_feature_dim

def cross_validation(config):
    dataset_name = config.dataset_name
    dataset_path = osp.join(osp.dirname(os.getcwd()), '..', 'data', dataset_name)
    dataset = TUDataset(dataset_path, name=dataset_name).shuffle()

    prepare_config_for_dataset(config, dataset)

    cross_validation_batches = config.cross_validation_batches
    cross_validation_batch_size = len(dataset) // cross_validation_batches
    results = []
    train_histories = []
    test_histories = []
    for i in range(cross_validation_batches):
        start_index = i * cross_validation_batch_size
        end_index = (i + 1) * cross_validation_batch_size if i + 1 < cross_validation_batches else len(dataset)
        test_dataset = dataset[start_index:end_index]
        train_dataset = dataset[:start_index] + dataset[end_index:]

        if config.node_features == 'categorical':
            test_loader = DataLoader(test_dataset, batch_size=config.batch_size)
            train_loader = DataLoader(train_dataset, batch_size=config.batch_size)
        elif config.node_features == 'node_degree':
            test_loader = NodeDegreeFeatureDataLoader(test_dataset, config.max_node_degree, batch_size=config.batch_size)
            train_loader = NodeDegreeFeatureDataLoader(train_dataset, config.max_node_degree, batch_size=config.batch_size)
        elif config.node_features == 'same':
            test_loader = SameFeatureDataLoader(test_dataset, config.same_feature_dim, batch_size=config.batch_size)
            train_loader = SameFeatureDataLoader(train_dataset, config.same_feature_dim, batch_size=config.batch_size)

        train_history, test_history = train(config, train_dataset, test_dataset)
        train_histories.append(train_history)
        test_histories.append(test_history)
        results.append(np.max(test_history))

    avg = np.mean(results)
    std = np.std(results)
    return avg, std


"""Child-Sum Tree-LSTM."""
import tensorflow as tf
from models import base
import spacy
import numpy as np
import tensorflow_fold as td
from util import blocks, binary_tokenize

class MyModel(base.Model):
    """Child-Sum Tree-LSTM.

    Following the model presented in Tai, Socher, and Manning (2015)
    "Improved Semantic Representations From Tree-Structured Long
    Short-Term Memory Networks."

    https://arxiv.org/abs/1503.00075
    """

    def __init__(self, seq_length, emb_dim, hidden_dim,
                 embeddings, emb_train, vocab_dict, batch_size):
        super(MyModel, self).__init__(seq_length, emb_dim, hidden_dim,
                                      embeddings, emb_train)

        # We need the vocab_dict for lookups
        self.vocab_dict = vocab_dict
        self.batch_size = batch_size

        # Parameters for the classifier
        self.W_mlp = tf.Variable(
            tf.random_normal([self.dim * 4, self.dim], stddev=0.1))
        self.b_mlp = tf.Variable(tf.random_normal([self.dim], stddev=0.1))

        self.W_cl = tf.Variable(tf.random_normal([self.dim, 3], stddev=0.1))
        self.b_cl = tf.Variable(tf.random_normal([3], stddev=0.1))

        # Create the word embedding for this model
        self.word_embedding = td.Embedding(
            *embeddings.shape,  # the star unpacks a tuple
            initializer=embeddings,
            name='word_embedding')

        # Create the lstm cell for our model.
        # Putting the cell in the td.ScoperLayer ensures the
        # LSTMs variables are encapsulated from the rest of
        # the graph and get created exactly once.
        tree_lstm = td.ScopedLayer(
            tf.contrib.rnn.DropoutWrapper(
                blocks.ChildSumTreeLSTMCell(
                    self.dim,
                    keep_prob=self.keep_rate_ph),
                input_keep_prob=self.keep_rate_ph,
                output_keep_prob=self.keep_rate_ph),
            name_or_scope='tree_lstm')

        # Create the forward declaration for recursion
        # going to need to think about the output type here... make sure of it.
        # deleting the output_type specification for now...
        embed_subtree = td.ForwardDeclaration(name='embed_subtree')

        def collect_children(children):
            # children are LstmStateTuples
            cells = tf.stack([t[0] for t in children])
            hidden_states = tf.stack(t[1] for t in children)
            return (cells, hidden_states)

        # The basic set of blocks for tree2vec
        def tree2vec():
            lookup_word = lambda word: self.vocab_dict[word]
            word2vec = (td.GetItem(0) >> td.InputTransform(lookup_word) >>
                        td.Scalar('int32') >> self.word_embedding)
            # No such think as zero_input in dependency tree
            zero_state = td.Zeros(td.TensorType((1, 300)))
            # pair2vec - what does that return???
            leaf_case = td.AllOf(word2vec, zero_state)
            # here word2vec too, there is no zero input in this kind of tree
            # but how to deal with the other side?
            # the answer must have to do with expanding down rows of a matrix
            # yes, the right side is a string that will work out to children
            # and we need to process the children, then concatenate them into
            # a new vector
            internal_node_case = td.AllOf(word2vec, )

            def is_leaf(x):
                return len(x) == 1
            return td.OneOf(is_leaf, [internal_node_case, leaf_case])

            pair2vec = (embed_subtree(), embed_subtree())
            zero_state = td.Zeros((tree_lstm.state_size,) * 2)
            zero_inp = td.Zeros(self.word_embedding.output_type.shape[0])
            word_case = td.AllOf(word2vec, zero_state)
            pair_case = td.AllOf(zero_inp, pair2vec)
            return td.OneOf(len, [(1, word_case), (2, pair_case)])

        # For threading the LSTM output correctly
        def thread_lstm_output():
            c = td.Composition(name='thread_lstm_output')
            with c.scope():
                c.output.reads(c.input[1])
            return c

        # For embedding a tree
        def embed_tree():
            return td.InputTransform(binary_tokenize.tokenize) >> tree2vec() \
                   >> tree_lstm >> thread_lstm_output()

        # Define the output layer to connect back to TF
        encoder = embed_tree()
        embed_subtree.resolve_to(embed_tree())

        # Compile the model to pass it to TF
        # Making the compiler accessible is necessary
        # for creating the feed dictionary
        self.compiler = td.Compiler.create(encoder)
        encoder_out = self.compiler.output_tensors
        stacked = tf.stack(encoder_out, axis=0)
        premise_encodings = tf.squeeze(tf.slice(
            stacked,
            [1, 0, 0],
            [1, self.batch_size, self.dim]))
        hypothesis_encodings = tf.squeeze(tf.slice(
            stacked,
            [1, self.batch_size, 0],
            [1, self.batch_size, self.dim]))

        ### Mou et al. concat layer ###
        diff = tf.subtract(premise_encodings, hypothesis_encodings)
        mul = tf.multiply(premise_encodings, hypothesis_encodings)
        h = tf.concat([premise_encodings, hypothesis_encodings, diff, mul], 1)

        # MLP layer
        h_mlp = tf.nn.relu(tf.matmul(h, self.W_mlp) + self.b_mlp)
        # Dropout applied to classifier
        h_drop = tf.nn.dropout(h_mlp, self.keep_rate_ph)

        # Get prediction
        self.logits = tf.matmul(h_drop, self.W_cl) + self.b_cl

        # Define the cost function
        self.total_cost = tf.reduce_mean(
            tf.nn.sparse_softmax_cross_entropy_with_logits(labels=self.y,
                                                           logits=self.logits))


n = int(input())
dic = {}
dic2 = {}
for i in range(n):
    # name = input()
    # sNum = input()
    # num = int(input())
    name, sNum, num = input().split()
    dic[num] = name
    dic2[num] = sNum

maxNum = -1
minNum = 101
for k,v in dic.items(): #便利字典 https://blog.csdn.net/Cashey1991/article/details/45704249
    #print(k, v)
    if int(k) > maxNum:
        maxNum = int(k)
    elif int(k) < minNum:
        minNum = int(k)

# print(dic[str(maxNum)] + " " + dic2[str(maxNum)])
# print(dic[str(minNum)] + " " + dic2[str(minNum)])
print(dic[maxNum] + " " + dic2[maxNum])
print(dic[minNum] + " " + dic2[minNum])

'''
https://blog.csdn.net/wuguangbin1230/article/details/70174926

python dict按照key 排序：
1、method 1.

items = dict.items()
items.sort()
for key,value in items:
   print key, value # print key,dict[key]
2、method 2.

print key, dict[key] for key in sorted(dict.keys())

python dict按照value排序：
method 1：

把dictionary中的元素分离出来放到一个list中，对list排序，从而间接实现对dictionary的排序。这个“元素”可以是key，value或者item。

method2：

#用lambda表达式来排序，更灵活：
sorted(dict.items(), lambda x, y: cmp(x[1], y[1]))
#降序
sorted(dict.items(), lambda x, y: cmp(x[1], y[1]), reverse=True)
'''
'''
https://pintia.cn/problem-sets/994805260223102976/problems/994805321640296448
1004 成绩排名 (20)（20 分）
读入n名学生的姓名、学号、成绩，分别输出成绩最高和成绩最低学生的姓名和学号。

输入格式：每个测试输入包含1个测试用例，格式为\

  第1行：正整数n
  第2行：第1个学生的姓名 学号 成绩
  第3行：第2个学生的姓名 学号 成绩
  ... ... ...
  第n+1行：第n个学生的姓名 学号 成绩
其中姓名和学号均为不超过10个字符的字符串，成绩为0到100之间的一个整数，这里保证在一组测试用例中没有两个学生的成绩是相同的。

输出格式：对每个测试用例输出2行，第1行是成绩最高学生的姓名和学号，第2行是成绩最低学生的姓名和学号，字符串间有1空格。

输入样例：

3
Joe Math990112 89
Mike CS991301 100
Mary EE990830 95
输出样例：

Mike CS991301
Joe Math990112
'''


# encoding: utf-8

import os
from apidata import api
from apidata.utils.api_tools import compose_api_info
from apidata.utils.file_parse import get_decorator_func_doc,get_filename_list

#  提供API-DATA规范的数据
def get_all_api_data(dir=None, file_type='py', data_api=None, decor_list=None,except_dirs=None,except_paths=None, except_files=None):
    """
    :description 获取接口信息
    :param dir: 需要解析的路径
    :param file_type: 需要解析的文件类型
    :param decor_name: 需要获取__doc__的装饰器
    :return:
    """
    # 从method_doc_map获取所有接口方法，重组数格式
    if not except_dirs:
        except_dirs = list()
    if not except_paths:
        except_paths = list()
    if not except_files:
        except_files = list()
    result = dict()
    if not data_api:
        data_api = ['get_all_api']
    if not decor_list:
        decor_list = ['api_data']
    if not dir:
        dir = os.path.abspath('.')
    file_list = get_filename_list(dir, file_type, except_dirs, except_paths, except_files)
    api.method_doc_map = get_decorator_func_doc(file_list, decor_list)
    api_name_list = api.method_doc_map.keys()
    for i in api_name_list:
        item = compose_api_info(i, api.method_doc_map)
        result[i] = item
    for x in data_api:
        if x in result:
            result.pop(x)
    return result


import matplotlib.pyplot as plt

a1 = 2.0 # Prey growth rate when there are no predators
a2 = 1.0 # Predator growth rate when there are no prey
b1 = 1.0 # predators supressing prey growth rate
b2 = 1.0 # enhancement of predator growth rate because of prey

maxt = 20.0
dt = 0.1 # step size
N = maxt/dt # number of steps

# Initial conditions
t = [0.0]
x = [0.9] # Prey Population
y = [1.0] # Predator Population

def f(x, y):
	return  (a1 - b1*y)*x

def g(x, y):
	return (-a2 + b2*x)*y

for i in range(0,int(N)):
	K = f(x[i], y[i]) * dt
	I = g(x[i], y[i]) * dt

	x.append(x[i] + dt * f(x[i] + K/2.0, y[i] + I/2.0))
	y.append(y[i] + dt * g(x[i] + K/2.0, y[i] + I/2.0))
	t.append(t[i] + dt)

plt.plot(x, y)
plt.show()


from tlorem import TLOREM

from sklearn.svm import SVC
from sklearn.neural_network import MLPClassifier
from sklearn.ensemble import RandomForestClassifier

from sklearn.datasets import fetch_20newsgroups

from sklearn.feature_extraction.text import TfidfVectorizer

def main():

    random_state = 0

    binary = True

    if binary:
        categories = ['alt.atheism', 'soc.religion.christian']
        newsgroups_train = fetch_20newsgroups(subset='train', categories=categories)
        newsgroups_test = fetch_20newsgroups(subset='test', categories=categories)
    else:
        newsgroups_train = fetch_20newsgroups(subset='train')
        newsgroups_test = fetch_20newsgroups(subset='test')

    class_name = 'class'
    class_values = [x.split('.')[-1] if 'misc' not in x else '.'.join(x.split('.')[-2:]) for x in
                    newsgroups_train.target_names]

    if not binary:
        class_values[3] = 'pc.hardware'
        class_values[4] = 'mac.hardware'

    vectorizer = TfidfVectorizer(lowercase=False)  # Convert a collection of raw documents to a matrix of TF-IDF features
    X_train = vectorizer.fit_transform(newsgroups_train.data)
    X_test = vectorizer.transform(newsgroups_test.data)
    Y_train = newsgroups_train.target
    Y_test = newsgroups_test.target

    K = newsgroups_train.data

    bb = RandomForestClassifier(n_estimators=100, random_state=random_state)
    # bb = SVC(random_state=random_state)
    # bb = MLPClassifier(random_state=random_state)
    bb.fit(X_train, Y_train)

    def bb_predict(texts):
        Xtfidf = vectorizer.transform(texts)
        return bb.predict(Xtfidf)

    i2e = 2
    text = newsgroups_test.data[i2e]
    x_text = X_test[i2e]

    print('text = "%s"' % text)
    print('')

    bb_outcome = bb_predict([text])[0]
    bb_outcome_str = class_values[bb_outcome]
    print('bb(x) = { %s }' % bb_outcome_str)
    print('')

    explainer = TLOREM(K, bb_predict, class_name, class_values, neigh_type='lime', size=1000, ocr=0.1, bow=True,
                       split_expression=r'\W+', kernel_width=None, kernel=None, random_state=0, verbose=True)

    exp = explainer.explain_instance(text, num_samples=1000, use_weights=True, metric='cosine')

    print('e = {\n\tr = %s\n\tc = %s    \n}' % (exp.rstr(), exp.cstr()))
    # for crule in exp.crules:
    #     print(crule)
    # print(exp.bb_pred, exp.dt_pred, exp.fidelity)
    print('')

    print(exp.get_text_rule())
    print('')

    for text_crule in exp.get_text_counterfactuals():
        print(text_crule)
    print('')

if __name__ == "__main__":
    main()


from django.contrib.auth.decorators import login_required, user_passes_test
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.db.models import Count, F
from django.http import JsonResponse
from django.shortcuts import render
from django.template.defaultfilters import date
from django.urls import reverse
from django.views.generic import TemplateView, UpdateView

from _main.utils import HxMixin, DatatablesMixin
from akun.models import Pegawai, WajibLapor
from .. import utils
from ..forms import VerifikatorForm
from ..models import Pelaporan

def check_role(user):
    if user.is_admin_kementerian or user.is_verifikator:
        return True
    return False

@login_required
@user_passes_test(check_role)
def tunggu_verifikasi_data(req):
    wl_ditangani = WajibLapor.lhkasn_objects.filter(pelaporan__isactive=True, pelaporan__verified_by=req.user.nama)\
        .aggregate(jml=Count('pelaporan__wajib_lapor', distinct=True))
    lhkasn_ditangani = wl_ditangani.get('jml')
    max_lhkasn = req.session.get('max_lhkasn', 0)
    lhkasn_revisi = WajibLapor.lhkasn_objects.filter(pelaporan__isactive=True,
                                                     pelaporan__status=Pelaporan.Status.MENUNGGU,
                                                     pelaporan__verified_by=req.user.nama)\
        .values('nama', 'nip', id_pelaporan=F('pelaporan__id_pelaporan'), tanggal_submit=F('pelaporan__tanggal_submit'),
                no_pelaporan=F('pelaporan__no_pelaporan'), status=F('pelaporan__status'), remarks=F('pelaporan__remarks'))
    jml_revisi = lhkasn_revisi.aggregate(jml=Count('pelaporan__wajib_lapor', distinct=True)).get('jml')
    lhkasn_baru = WajibLapor.lhkasn_objects.none()
    max_tampil = 10

    if jml_revisi >= max_tampil:
        lhkasn_revisi = lhkasn_revisi[:max_tampil]
    else:
        kurang = 0
        if lhkasn_ditangani <= max_lhkasn:
            kurang = max_lhkasn - lhkasn_ditangani

        verifikator = Pegawai.objects.filter(role=Pegawai.Peran.VERIFIKATOR).values_list('nama', flat=True)
        lhkasn_baru = WajibLapor.lhkasn_objects.filter(pelaporan__isactive=True,
                                                       pelaporan__status=Pelaporan.Status.MENUNGGU)\
            .exclude(pelaporan__verified_by__in=verifikator)\
            .values('nama', 'nip',
                    id_pelaporan=F('pelaporan__id_pelaporan'),
                    tanggal_submit=F('pelaporan__tanggal_submit'),
                    no_pelaporan=F('pelaporan__no_pelaporan'),
                    status=F('pelaporan__status'),
                    remarks=F('pelaporan__remarks')).order_by('?')
        if jml_revisi + kurang >= max_tampil:
            lhkasn_baru = lhkasn_baru[:max_tampil - jml_revisi]
        else:
            lhkasn_baru = lhkasn_baru[:kurang]

    return render(req, 'lhkasn/verifikasi/verifikasi_menunggu_data.html', {'lhkasn_revisi': lhkasn_revisi,
                                                                           'lhkasn_baru': lhkasn_baru, })

class TungguVerifikasiView(LoginRequiredMixin, TemplateView):
    template_name = 'lhkasn/verifikasi/verifikasi_menunggu.html'
    extra_context = {
        'menungguVerifikasiMenu': True,
    }

    def dispatch(self, request, *args, **kwargs):
        wl_lhkasn = WajibLapor.lhkasn_objects.filter(pelaporan__isactive=True,
                                                     pelaporan__status__gte=Pelaporan.Status.MENUNGGU)\
            .aggregate(jml=Count('pelaporan__wajib_lapor', distinct=True)).get('jml')
        jumlah_verifikator = Pegawai.objects.filter(role=Pegawai.Peran.VERIFIKATOR).count()
        sisa_bagi = wl_lhkasn % jumlah_verifikator
        if sisa_bagi != 0:
            wl_lhkasn += (jumlah_verifikator - sisa_bagi)
        request.session['max_lhkasn'] = wl_lhkasn / jumlah_verifikator

        return super().dispatch(request, *args, **kwargs)

class LhkasnDisetujuiView(LoginRequiredMixin, UserPassesTestMixin, DatatablesMixin, TemplateView):
    template_name = 'lhkasn/verifikasi/verifikasi_setuju.html'
    extra_context = {
        'verifikasiDisetujuiMenu': True,
        'title': 'Verifikasi LHKASN',
        'header': 'Laporan LHKASN Yang Disetujui',
    }
    queryset = None
    total_list = 0

    def test_func(self):
        queryset = WajibLapor.lhkasn_objects.filter(pelaporan__isactive=True,
                                                    pelaporan__status=Pelaporan.Status.DITERIMA) \
            .distinct().order_by('-pelaporan__verified') \
            .values('nama', 'nip', id_pelaporan=F('pelaporan__id_pelaporan'),
                    tanggal_submit=F('pelaporan__tanggal_submit'),
                    no_pelaporan=F('pelaporan__no_pelaporan'), pelaporan_ke=F('pelaporan__pelaporan_ke'),
                    status=F('pelaporan__status'), verified_by=F('pelaporan__verified_by'),
                    verified=F('pelaporan__verified'))
        self.queryset = queryset
        self.total_list = queryset.count()
        return check_role(self.request.user)

    def get_fetch_data(self):
        queryset, filtered_list = self.get_datatables_param(request=self.request, queryset=self.queryset)
        data = list()
        for pelaporan in queryset:
            sub_data = list()

            kolom_nama = f'{pelaporan.get("nama")}
' \
                         f'NIP {pelaporan.get("nip")}'
            kolom_tanggal_lapor = f'{date(pelaporan.get("tanggal_submit"), "d F Y")}
' \
                                  f'Pelaporan ke-{pelaporan.get("pelaporan_ke")}'

            kolom_status = f'{utils.get_display(pelaporan.get("status"))}
' \
                           f'' \
                           f' {pelaporan.get("verified_by")} ' \
                           f'({date(pelaporan.get("verified"), "d M Y")} - {date(pelaporan.get("verified"), "H:i")})' \
                           f''

            cetak_url = reverse('lhkasnApp:cetakBuktiLhkasnUrl', kwargs={'pelaporan_id': pelaporan.get("id_pelaporan")})
            kolom_aksi = f'' \
                         f' Cetak Bukti Lapor'
            sub_data.append(kolom_nama)
            sub_data.append(kolom_tanggal_lapor)
            sub_data.append(kolom_status)
            sub_data.append(kolom_aksi)
            data.append(sub_data)

        data_output = {
            'recordsTotal': self.total_list,
            'recordsFiltered': filtered_list,
            'data': data
        }

        return JsonResponse(data=data_output)

class LhkasnDitolakView(LoginRequiredMixin, UserPassesTestMixin, DatatablesMixin, TemplateView):
    template_name = 'lhkasn/verifikasi/verifikasi_ditolak.html'
    extra_context = {
        'verifikasiDitolakMenu': True,
        'title': 'Verifikasi LHKASN',
        'header': 'Laporan LHKASN Yang Ditolak',
    }
    queryset = None
    total_list = 0

    def test_func(self):
        queryset = WajibLapor.lhkasn_objects.filter(pelaporan__isactive=True, pelaporan__status=Pelaporan.Status.REVISI)\
            .distinct().order_by('-pelaporan__verified') \
            .values('nama', 'nip', id_pelaporan=F('pelaporan__id_pelaporan'),
                    tanggal_submit=F('pelaporan__tanggal_submit'),
                    no_pelaporan=F('pelaporan__no_pelaporan'), status=F('pelaporan__status'),
                    remarks=F('pelaporan__remarks'),
                    verified_by=F('pelaporan__verified_by'), verified=F('pelaporan__verified'))
        self.queryset = queryset
        self.total_list = queryset.count()
        return check_role(self.request.user)

    def get_fetch_data(self):
        queryset, filtered_list = self.get_datatables_param(request=self.request, queryset=self.queryset)
        data = list()
        for pelaporan in queryset:
            sub_data = list()

            kolom_nama = f'{pelaporan.get("nama")}
' \
                         f'NIP {pelaporan.get("nip")}'
            kolom_tanggal_lapor = f'{date(pelaporan.get("tanggal_submit"), "d F Y")}
' \
                                  f'Pelaporan ke-{pelaporan.get("pelaporan_ke")}'

            kolom_status = f'{utils.get_display(pelaporan.get("status"))}
' \
                           f'' \
                           f' {pelaporan.get("verified_by")} ' \
                           f'({date(pelaporan.get("verified"), "d M Y")} - {date(pelaporan.get("verified"), "H:i")})' \
                           f''
            kolom_alasan = f'{pelaporan.get("remarks")}'
            sub_data.append(kolom_nama)
            sub_data.append(kolom_tanggal_lapor)
            sub_data.append(kolom_status)
            sub_data.append(kolom_alasan)
            data.append(sub_data)

        data_output = {
            'recordsTotal': self.total_list,
            'recordsFiltered': filtered_list,
            'data': data
        }

        return JsonResponse(data=data_output)

class VerifikasiLhkasnView(LoginRequiredMixin, UserPassesTestMixin, HxMixin, UpdateView):
    model = Pelaporan
    form_class = VerifikatorForm
    hx_template = 'lhkasn/verifikasi/form_verifikasi.html'
    pk_url_kwarg = 'pelaporan_id'
    success_url = 'sukses/'

    def test_func(self):
        return check_role(self.request.user)

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs['user'] = self.request.user
        return kwargs

    def get_context_data(self, **kwargs):
        cx = super().get_context_data(**kwargs)
        cx['rekap'] = self.get_object().get_rekap_harta()
        return cx

    def form_valid(self, form):
        super().form_valid(form=form)
        return self.htmx_response()


import sys
sys.stdin = open("input.txt","r")
sys.setrecursionlimit(10000)

def dfs(s):
    visited[s] = True
    for w in graph[s]:
        if not visited[w]:
            visited[w] = True
            dfs(w)

N, M = map(int,input().split())

graph = [[] for _ in range(N+1)]
visited = [False] * (N + 1)
ans = 0

for _ in range(M):
    s, e = map(int,input().split())
    graph[s].append(e)
    graph[e].append(s)

for i in range(1, N+ 1):
    if not visited[i]:
        ans += 1
        dfs(i)

print(ans)


import argparse, sys
import unittest
from pybicl.tools.class_polyA_site import PolyA
from pybicl.utils import Isoform, Exon
from pybicl.operation import IvalTree

def block2iso(block, chrom, strand):
    exon_li = [Exon(chrom, s, e, strand) for s, e in block]
    iso = Isoform()
    iso.init_by_exons(exon_li)
    return iso

class TestPolyA(unittest.TestCase):
    def test_pos_pA(self):
        iso1 = block2iso([(100, 200), (500, 650)], "Chr1", "+")
        iso2 = block2iso([(100, 200), (500, 600)], "Chr1", "+")
        iso3 = block2iso([(100, 200), (500, 550)], "Chr1", "+")
        iso4 = block2iso([(100, 200), (300, 400)], "Chr1", "+")
        iso5 = block2iso([(100, 250)], "Chr1", "+")
        iso6 = block2iso([(100, 150)], "Chr1", "+")
        iso_li = [iso1, iso2, iso3, iso4, iso5, iso6]
        pa_tree = IvalTree(True)
        pa_worker = PolyA("test", iso_li, 0, True)
        res = sorted(pa_worker.classify_polya(pa_tree), key=lambda x: x[0])
        self.assertListEqual(
            res,
            [(149, "E"), (249, "lc"), (399, "ls"), (549, "F"), (599, "M"), (649, "L")])

    def test_neg_pA(self):
        iso1 = block2iso([(50, 200), (500, 600)], "Chr1", "-")
        iso2 = block2iso([(100, 200), (500, 600)], "Chr1", "-")
        iso3 = block2iso([(150, 200), (500, 600)], "Chr1", "-")
        iso4 = block2iso([(300, 400), (500, 600)], "Chr1", "-")
        iso5 = block2iso([(450, 600)], "Chr1", "-")
        iso6 = block2iso([(500, 600)], "Chr1", "-")
        iso_li = [iso1, iso2, iso3, iso4, iso5, iso6]
        pa_tree = IvalTree(True)
        pa_worker = PolyA("test", iso_li, 0, True)
        res = sorted(pa_worker.classify_polya(pa_tree), key=lambda x: x[0])
        self.assertListEqual(
            res,
            [(50, "L"), (100, "M"), (150, "F"), (300, "ls"), (450, "lc"), (500, "E")])


"""
Base backend to connect richie with an LMS
"""
import re
import time

from django.core.cache import cache
from django.utils import timezone

from richie.apps.courses.factories import CourseRunFactory

class BaseLMSBackend:
    """
    Base backend to hold the methods common to all backends and provide a skeleton for others.
    """

    def __init__(self, configuration, *args, **kwargs):
        """Attache configuration to the backend instance."""
        super().__init__(*args, **kwargs)
        self.configuration = configuration

    def extract_course_id(self, url):
        """Extract the LMS course id from the course run url."""
        return re.match(self.configuration["COURSE_REGEX"], url).group("course_id")

class DemoLMSBackend(BaseLMSBackend):
    """LMS backend for Richie to mock the behavior of an LMS."""

    @staticmethod
    def get_cache_key(username, course_id):
        """Compute compound cache key from username and course id."""
        return f"demo_lms_backend_enrollment_{username:s}_{course_id:s}"

    def get_enrollment(self, user, url):
        """Get fake enrollment status from cache for a user on a course run given its url."""
        course_id = self.extract_course_id(url)
        course_run = CourseRunFactory.build()

        if cache.get(self.get_cache_key(user.username, course_id)):
            return {
                "created": timezone.now().isoformat(),  # 2020-07-21T17:42:04.675422Z
                "mode": "audit",
                "is_active": True,
                "course_details": {
                    "course_id": course_id,
                    "course_name": f"Course: {course_id:s}",
                    "enrollment_start": course_run.enrollment_start.isoformat(),
                    "enrollment_end": course_run.enrollment_end.isoformat(),
                    "course_start": course_run.start.isoformat(),
                    "course_end": course_run.end.isoformat(),
                    "invite_only": False,
                    "course_modes": [
                        {
                            "slug": "audit",
                            "name": "Audit",
                            "min_price": 0,
                            "suggested_prices": "",
                            "currency": "eur",
                            "expiration_datetime": None,
                            "description": None,
                            "sku": None,
                            "bulk_sku": None,
                        }
                    ],
                },
                "user": user.username,
            }

        return None

    def set_enrollment(self, user, url):
        """Set fake enrollment to cache for a user with a course run given its url."""

        time.sleep(0.3)
        course_id = self.extract_course_id(url)

        cache.set(self.get_cache_key(user.username, course_id), True)
        return True


# -*- coding: utf-8 -*-
"""
test_dfl_parser: unittests for the dfl_parser_functions

The tests relies on the specific test files which are pruned
versions of original files.

@author: rein
@license: MIT
@version 0.1
"""

import unittest
import dfl_parser
from datetime import datetime
import dateutil.parser as dup
import numpy as np

class TestMatchInformation(unittest.TestCase):
    """Unit test class for the dfl_parser
    """
    @classmethod
    def setUpClass(cls, fname='./test/dfl/MatchInformation/test.xml'):
        mip = dfl_parser.MatchInformationParser()
        mip.run(fname)
        cls._teams,cls._match = mip.getTeamInformation()

    def test_pitch_specs(self):
        match = TestMatchInformation._match
        self.assertEqual(match['stadium']['length'],105.0)
        self.assertEqual(match['stadium']['width'],69.0);

    def test_team_ids(self):
        match = TestMatchInformation._match
        self.assertEqual(match['home'],'DFL-ABC-12345A')
        self.assertEqual(match['guest'],'DFL-ABC-12345B')

    def test_no_players(self):
        teams = TestMatchInformation._teams
        self.assertEqual(len(teams['guest']),6)
        self.assertEqual(len(teams['home']),6)

    def test_player_name(self):
        teams = TestMatchInformation._teams
        self.assertEqual(teams['home'][0]['id'], u"DFL-OBJ-a00001")

    def test_single_player(self):
        teams = TestMatchInformation._teams
        barney = [p for p in teams['guest'] if \
                    p['id'] == 'DFL-OBJ-b00004'][0]
        self.assertEqual(barney['name'],'B. Rubble')
        self.assertEqual(barney['position'], 'MZ')
        self.assertEqual(barney['trikot'],4)

class TestMatchEvent(unittest.TestCase):
    """Unit test class for the MatchEventParser.
    """
    @classmethod
    def setUpClass(cls, fname='./test/dfl/EventData/test.xml'):
        mep = dfl_parser.MatchEventParser()
        mep.run(fname)
        cls._play_time, cls._subs = mep.getEventInformation()

    def test_playing_time(self):
        play_time = TestMatchEvent._play_time
        self.assertEqual(play_time['firstHalf'][0],
               dup.parse('2015-05-16T15:30:40.320+02:00'))
        self.assertEqual(play_time['firstHalf'][1],
               dup.parse('2015-05-16T15:30:40.640+02:00'))

class TestMatchPosition(unittest.TestCase):
    """Unit test class for the MatchPositionParser.
    """
    @classmethod
    def setUpClass(cls, fname='./test/dfl/ObservedPositionalData/test.xml'):
        mip = dfl_parser.MatchInformationParser()
        fname_match = "./test/dfl/MatchInformation/test.xml"
        mip.run(fname_match)
        teams, match = mip.getTeamInformation()
        mpp = dfl_parser.MatchPositionParser(match,teams)
        mpp.run(fname)
        cls._pos_data, cls._ball_data, timestamps = mpp.getPositionInformation()

    def test_number_of_player(self):
        pos_data = TestMatchPosition._pos_data
        guest_1st = pos_data['guest']['1st']
        guest_2nd = pos_data['guest']['2nd']
        home_1st = pos_data['home']['1st']
        home_2nd = pos_data['home']['2nd']
        self.assertEqual(len(guest_1st),3)
        self.assertEqual(len(guest_2nd),4)
        self.assertEqual(len(home_1st),3)
        self.assertEqual(len(home_2nd),4)

    def test_xy_data(self):
        # Testing guest data
        guest_1st = TestMatchPosition._pos_data['guest']['1st']
        p_idxs = {data[0]: i for (i,data) in enumerate(guest_1st)}
        pid_1 = p_idxs[u'DFL-OBJ-b00002']
        self.assertEqual(guest_1st[pid_1][1].shape,(9,3))
        self.assertTrue(np.all(guest_1st[pid_1][1][0,:3]==(10000.0,10.0,20.0)))
        # Testing home data
        home_2nd = TestMatchPosition._pos_data['home']['2nd']
        p_idxs = {data[0]:i for (i,data) in enumerate(home_2nd)}
        pid_2 = p_idxs[u'DFL-OBJ-a00004']
        self.assertEqual(home_2nd[pid_2][1].shape,(4,3))
        self.assertTrue(np.all(home_2nd[pid_2][1][2,:2]==(100007.0,57.0)))

class TestSanity(unittest.TestCase):
    """Unit test for more general checks.
    """
    @classmethod
    def setUpClass(cls):
        mep = dfl_parser.MatchEventParser()
        mep.run('./test/dfl/EventData/test.xml')
        cls._play_time, cls._subs = mep.getEventInformation()
        mip = dfl_parser.MatchInformationParser()
        fname_match = "./test/dfl/MatchInformation/test.xml"
        mip.run(fname_match)
        teams, match = mip.getTeamInformation()
        mpp = dfl_parser.MatchPositionParser(match,teams)
        mpp.run('./test/dfl/ObservedPositionalData/test.xml')
        cls._pos_data, cls._ball_data, cls._timestamps = mpp.getPositionInformation()

    def test_time_sanity(self):
        print(TestSanity._timestamps)
        self.assertEqual(TestSanity._timestamps[0][0],TestSanity._play_time['firstHalf'][0])

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


import os
import logging
import errno
import os.path as osp
from tensorflow.keras.utils import get_file

from graphgallery import is_list_like

def download_file(raw_paths, urls):

    last_except = None
    for file_name, url in zip(raw_paths, urls):
        try:
            get_file(file_name, origin=url)
        except Exception as e:
            last_except = e

    if last_except is not None:
        raise last_except

def files_exist(files):
    if is_list_like(files):
        return len(files) != 0 and all([osp.exists(f) for f in files])
    else:
        return osp.exists(files)

def makedirs(path):
    try:
        os.makedirs(osp.expanduser(osp.normpath(path)))
    except OSError as e:
        if e.errno != errno.EEXIST and osp.isdir(path):
            raise e

def makedirs_from_path(path, verbose=True):
    file_dir = osp.split(osp.realpath(path))[0]
    if not osp.exists(file_dir):
        makedirs(file_dir)
        if verbose:
            logging.log(logging.WARNING,
                        f"Creating a folder in {path}.")


import json
import os
import re
import subprocess
import tkinter as tk
from tkinter import filedialog
from autointercut import VideoClipGroup, auto_sync_cut_folders, auto_cut_secondary
from autointercututils import to_ffmpeg_duration
from PIL import Image, ImageTk

class ClipGroupFrame(tk.Frame):
    def __init__(self, root, clip_label):
        tk.Frame.__init__(self, root)
        self.clip_info = None
        self.selected_index = None
        self.seek_time = 0

        # Clip listbox
        tk.Button(self, text=f'{clip_label} Clips', command=self.populate_listbox_items).grid(row=0, column=0)

        clip_name_lb_frame = tk.Frame(self)
        clip_name_lb_frame.grid(row=1, column=0, sticky='NS')
        clip_name_lb_frame.grid_rowconfigure(0, weight=1)

        y_scroll = tk.Scrollbar(clip_name_lb_frame, orient=tk.VERTICAL)
        y_scroll.grid(row=0, column=1, sticky='NS')
        x_scroll = tk.Scrollbar(clip_name_lb_frame, orient=tk.HORIZONTAL)
        x_scroll.grid(row=1, column=0, sticky='WE')

        self.clip_name_lb = tk.Listbox(clip_name_lb_frame, xscrollcommand=x_scroll.set, yscrollcommand=y_scroll.set,
                                       exportselection=False)
        self.clip_name_lb.bind('<<ListboxSelect>>', self.select_clip)
        self.clip_name_lb.grid(row=0, column=0, sticky='NS')
        self.clip_name_lb.bind('<FocusIn>', lambda event: self.focus_set())
        x_scroll.config(command=self.clip_name_lb.xview)
        y_scroll.config(command=self.clip_name_lb.yview)

        # Clip panel
        self.clip_panel = tk.Label(self)
        self.clip_panel.grid(row=2, column=0)
        self.clip_panel.bind('<Button-1>', lambda event: self.focus_set())
        self.bind('<KeyPress>', self.seek)

    def populate_listbox_items(self):
        self.clip_info = None
        self.selected_index = None

        directory = filedialog.askdirectory()

        if directory:
            self.video_clip_group = VideoClipGroup(directory, 0, 0)

            self.clip_name_lb.delete(0, tk.END)
            for clip in self.video_clip_group.clips:
                clip_name = os.path.basename(clip['file_path'])
                self.clip_name_lb.insert(tk.END, clip_name)

    def select_clip(self, event):
        self.seek_time = 0
        self.selected_index = self.clip_name_lb.index(tk.ANCHOR)
        self.current_clip_path = os.path.join(self.video_clip_group.directory, self.clip_name_lb.get(self.selected_index))

        video_size_output = subprocess.check_output(['ffprobe',
                                                     '-v', 'quiet',
                                                     '-print_format', 'json',
                                                     '-show_format',
                                                     '-show_streams',
                                                     self.current_clip_path])

        video_info = json.loads(video_size_output)
        self.clip_info = {}
        self.clip_info['width'] = video_info['streams'][0]['width']
        self.clip_info['height'] = video_info['streams'][0]['height']
        self.clip_info['duration'] = float(video_info['streams'][0]['duration'])
        self.update_clip_panel()

    def update_clip_panel(self):
        timestamp = to_ffmpeg_duration(self.seek_time)
        image_data = subprocess.check_output(['ffmpeg',
                                              '-ss', timestamp,
                                              '-i', self.current_clip_path,
                                              '-vframes', '1',
                                              '-f', 'image2pipe',
                                              '-vcodec', 'rawvideo',
                                              '-pix_fmt', 'rgb24',
                                              '-'], bufsize=10 ** 8, stderr=subprocess.DEVNULL)
        image = Image.frombytes('RGB', (self.clip_info['width'], self.clip_info['height']), image_data)
        iwidth, iheight = image.size
        aspect_ratio = iwidth / iheight
        image = image.resize((640, int(640 / aspect_ratio)), Image.ANTIALIAS)
        image = ImageTk.PhotoImage(image)
        self.clip_panel.configure(image=image)
        self.clip_panel.image = image

    def seek(self, event):
        if not self.clip_info:
            return
        if event.keysym == 'Left':
            next_seek_time = self.seek_time - 1
        elif event.keysym == 'Right':
            next_seek_time = self.seek_time + 1
        elif event.keysym == 'Up':
            next_seek_time = self.seek_time - 5
        elif event.keysym == 'Down':
            next_seek_time = self.seek_time + 5
        else:
            return

        if next_seek_time >= 0 and next_seek_time < self.clip_info['duration']:
            self.seek_time = next_seek_time
            self.update_clip_panel()

class AutocutGui(tk.Frame):
    def __init__(self, root):
        tk.Frame.__init__(self, root)

        self.primary_clips_frame = ClipGroupFrame(self, 'Primary')
        self.primary_clips_frame.grid(row=0, column=0)
        self.secondary_clips_frame = ClipGroupFrame(self, 'Secondary')
        self.secondary_clips_frame.grid(row=0, column=1)

        # Buttons to perform autocuts
        match_and_rename_btn = tk.Button(self, text='Match and Rename',
                                        command=lambda : self.match('RENAME_AND_PAD'))
        match_and_rename_btn.grid(row=2, column=0, columnspan=2, sticky='WE')
        match_and_copy_btn = tk.Button(self, text='Match and Copy',
                                       command=lambda : self.match('COPY'))
        match_and_copy_btn.grid(row=3, column=0, columnspan=2, sticky='WE')
        autocut_secondary_from_primary_btn = tk.Button(self, text='Autocut Secondary from Primary',
                                                       command=self.autocut_secondary_from_primary)
        autocut_secondary_from_primary_btn.grid(row=4, column=0, columnspan=2, sticky='WE')

    def match(self, option):
        primary_clip_group = self.primary_clips_frame.video_clip_group
        primary_selected_index = self.primary_clips_frame.selected_index
        primary_seek_time = self.primary_clips_frame.seek_time
        secondary_selected_index = self.secondary_clips_frame.selected_index
        secondary_clip_group = self.secondary_clips_frame.video_clip_group
        secondary_seek_time = self.secondary_clips_frame.seek_time
        if primary_clip_group == None or primary_selected_index == None \
            or secondary_clip_group == None or secondary_clip_group == None:
            return

        auto_sync_cut_folders(primary_clip_group.directory, primary_selected_index, primary_seek_time,
                              secondary_clip_group.directory, secondary_selected_index, secondary_seek_time,
                              option)

    def autocut_secondary_from_primary(self):
        primary_clip_group = self.primary_clips_frame.video_clip_group
        primary_selected_index = self.primary_clips_frame.selected_index
        primary_seek_time = self.primary_clips_frame.seek_time
        secondary_selected_index = self.secondary_clips_frame.selected_index
        secondary_clip_group = self.secondary_clips_frame.video_clip_group
        secondary_seek_time = self.secondary_clips_frame.seek_time
        if primary_clip_group == None or primary_selected_index == None \
                or secondary_clip_group == None or secondary_clip_group == None:
            return

        auto_cut_secondary(primary_clip_group.directory, primary_selected_index, primary_seek_time,
                              secondary_clip_group.directory, secondary_selected_index, secondary_seek_time,)

if __name__ == '__main__':
    root = tk.Tk()
    cut_gui = AutocutGui(root)
    cut_gui.pack()
    root.mainloop()


n=0
maior=0
menor=2.30
homens=0
while n != 50:
    altura= float(input("Qual a Altura ?:"))
    while (altura < 1.00 or altura > 2.30):
        print("ALTURA INVALIDA")
        altura= float(input("Qual a Altura ?:"))
    if altura >= maior:
        maior = altura
    if altura < menor:
        menor = altura
    sexo= input("Qual sexo da pessoa ? M para Masculino e F para Feminino:")
    while sexo != "M" and sexo != "F":
        print("SEXO INVALIDO")
        sexo= input("Qual sexo da pessoa ? M para Masculino e F para Feminino:")
    if sexo == "M":
        homens = homens + 1
    n = n + 1
print("A Maior Altura e:",maior)
print("A Menor Altura e:",menor)
print("A Quantidade de Homens e:",homens)


from random import randint
from os import environ

from asyncio import sleep

from dbl.client import DBLClient
from decouple import config
from discord import Embed, Colour, Member, TextChannel, VoiceChannel, PermissionOverwrite
from discord.ext import commands

command_prefix = '>>'

class TRPGCog(commands.Cog):
    object_id = 115

    def __init__(self, client: commands.Bot):
        self.client: commands.Bot = client
        self.dbl_token = config('DBL_TOKEN')
        self.dblpy = DBLClient(client, self.dbl_token, autopost=True)

    @commands.command(name='초대링크', brief='봇을 초대하기 위한 링크를 확인합니다.',
                      help='봇을 서버에 초대하기 위해 필요한 링크를 확인합니다.')
    async def invite_link(self, ctx: commands.Context):
        url = 'https://discordbots.org/bot/609223331945906186'
        embed = Embed(title=':link: 봇 초대 링크', colour=Colour.blurple(),
                      description=f'봇을 다른 서버에 초대하려면 **[여기]({url})**를 클릭하세요.')
        embed.set_author(name=ctx.author, icon_url=ctx.author.avatar_url)
        embed.set_thumbnail(url=self.client.user.avatar_url)
        await ctx.send(ctx.author.mention, embed=embed)

    @commands.command(name='도움말', aliases=('도움', 'h', 'help'), brief='명령어의 도움말을 확인합니다.',
                      help='명령어의 도움말을 확인합니다.\n'
                           '사용법은 다음과 같습니다.\n'
                           '```\n'
                           f'{command_prefix}도움말 굴림\n'
                           f'{command_prefix}도움말 명령어\n'
                           f'{command_prefix}도움말 개인방\n'
                           '```\n'
                           f'봇이 어떤 명령어를 제공하는지 알고 싶다면 "{command_prefix}명령어" 명령어를 사용해보세요.')
    async def help(self, ctx: commands.Context, *tokens: str):
        cmd: commands.Bot = self.client
        if tokens:
            for token in tokens:
                if isinstance(cmd, commands.Bot) or isinstance(cmd, commands.Group):
                    inner_cmd = cmd.get_command(token)
                else:
                    break
                cmd: commands.Command = inner_cmd
        else:
            cmd: commands.Command = self.help
        if cmd is None:
            await ctx.send(f'"{" ".join(tokens)}" 명령어를 찾을 수 없습니다.')
            return
        help_embed = Embed(title=f'**{self.client.command_prefix}'
                                 f'{cmd.full_parent_name + " " if cmd.full_parent_name else ""}{cmd.name}**',
                           description=cmd.brief, colour=Colour.blurple())
        help_embed.set_author(name=ctx.author, icon_url=ctx.author.avatar_url)
        help_embed.set_thumbnail(url=self.client.user.avatar_url)
        help_embed.add_field(name=':gear: 기능', value=cmd.help, inline=False)
        if cmd.aliases:
            help_embed.add_field(name=':asterisk: 대체 가능한 단어', value=', '.join([f'"{a}"' for a in cmd.aliases]),
                                 inline=False)
        if isinstance(cmd, commands.Group):
            value = '이 명령어는 다음의 하위 명령어를 포함하고 있습니다.\n```\n'
            for subcommand in cmd.commands:
                value += f'{self.client.command_prefix}'
                value += f'{subcommand.full_parent_name + " " if subcommand.full_parent_name else ""}'
                value += f'{subcommand.name}\n'
            value += '```'
            help_embed.add_field(name=':diamond_shape_with_a_dot_inside: 하위 명령어', value=value, inline=False)
        await ctx.send(embed=help_embed)

    @commands.command(name='명령어', aliases=('cmd', '커맨드', '커멘드', 'cmds'), brief='봇 명령어 목록을 조회합니다.',
                      help='봇이 제공하는 명령어들의 목록을 조회합니다.')
    async def cmd(self, ctx: commands.Context):
        cmds = [f'명령어 목록입니다.\n{"-" * 40}\n']
        for cmd in self.client.commands:
            cmd_brief = f'**{self.client.command_prefix}{f" {cmd.full_parent_name} " if cmd.full_parent_name else ""}'
            cmd_brief += f'{cmd.name}**\n-- *{cmd.brief}*\n\n'
            if len(cmds) == 1 and len(cmds[-1] + cmd_brief) > 2048:
                cmds.append(cmd_brief)
            elif len(cmds[-1] + cmd_brief) > 1024:
                cmds.append(cmd_brief)
            else:
                cmds[-1] += cmd_brief
        cmd_embed = Embed(title='명령어 목록', description=cmds.pop(0), colour=Colour.blurple())
        cmd_embed.set_thumbnail(url=self.client.user.avatar_url)
        cmd_embed.set_author(name=ctx.author, icon_url=ctx.author.avatar_url)
        embeds = [cmd_embed]
        for cmd_brief in cmds:
            embeds[-1].add_field(name='-', value=cmd_brief, inline=False)
            if len(embeds[-1]) > 6000 or len(embeds[-1].fields) > 25:
                embeds[-1].remove_field(-1)
                embeds.append(Embed(colour=Colour.blurple()))
                embeds[-1].add_field(name='-', value=cmd_brief)
        for embed in embeds:
            await ctx.send(ctx.author.mention, embed=embed)

    @commands.command(name='굴림', aliases=('주사위', '굴리기', 'r', 'roll', '굴'), brief='주사위를 굴립니다.',
                      help='주사위를 굴립니다.\n'
                           '사용법은 다음과 같습니다.\n'
                           '```\n'
                           '[육면체 주사위 굴림]\n'
                           f'{command_prefix}굴림\n\n'
                           '[복잡한 주사위 굴림]\n'
                           f'{command_prefix}굴림 D%\n'
                           f'{command_prefix}굴림 10D + 5\n'
                           f'{command_prefix}굴림 10 + 2D20 + 4 - 11 - 4D\n'
                           '```')
    async def roll(self, ctx: commands.Context, *, roll: str = 'D'):
        parts = []
        if '+' in roll or '-' in roll:
            for part in roll.split('+'):
                if not part.strip():
                    continue
                if '-' in roll:
                    for i in range(len(part.split('-'))):
                        parts_ = part.split('-')
                        if not parts_[i].strip():
                            continue
                        part_dict = {'raw': parts_[i].strip().upper(), 'sign': '-', 'process': None, 'result': None}
                        if i:
                            part_dict['sign'] = '-'
                        else:
                            part_dict['sign'] = '+'
                        parts.append(part_dict)
                else:
                    parts.append({'raw': part.strip().upper(), 'sign': '+', 'process': None, 'result': None})
        else:
            parts.append({'raw': roll.strip().upper(), 'sign': '+', 'process': None, 'result': None})
        for part in parts:
            part['raw'] = part['raw'].replace(' ', '', part['raw'].count(' '))
            if 'D' in part['raw']:
                raws = part['raw'].split('D')
                try:
                    dices = int(raws[0].strip() if raws[0] else 1)
                    pips = int((raws[1].strip() if raws[1] != '%' else '100') if raws[1] else 6)
                except ValueError:
                    await ctx.send('주사위 수와 눈을 정확한 숫자로 입력해주세요.')
                    return
                if dices <= 0:
                    await ctx.send('주사위의 수는 한 개 이상이어야 합니다.')
                    return
                if pips <= 0:
                    await ctx.send('주사위의 눈은 한 개 이상이어야 합니다.')
                    return
                throwns = []
                for i in range(dices):
                    throwns.append(randint(1, pips))
                part['process'] = str(throwns)
                part['result'] = sum(throwns) * (-1 if part['sign'] == '-' else 1)
            else:
                part['process'] = part['raw']
                try:
                    part['result'] = int(part['raw']) * (-1 if part['sign'] == '-' else 1)
                except ValueError:
                    await ctx.send('더하는 값을 정확한 숫자로 입력해주세요.')
                    return
        raw_description = ''
        process_description = ''
        for part in parts:
            raw_description += f'{part["sign"]} {part["raw"]} '
            process_description += f'{part["sign"]} {part["process"]} '
        description = '**' + raw_description + '**'
        description += '\n= ' + process_description
        description += '\n= ***__' + str(sum(part['result'] for part in parts)) + '__***'
        embed = Embed(title=':game_die: 주사위 굴림', description=description, colour=Colour.blurple())
        embed.set_author(name=ctx.author, icon_url=ctx.author.avatar_url)
        embed.set_thumbnail(url=self.client.user.avatar_url)
        await ctx.send(ctx.author.mention, embed=embed)

    @commands.command(name='개인방', aliases=('pc', 'pr', 'private', '비밀방'),
                      brief='개인방을 만듭니다.',
                      help='특정 멤버만 볼 수 있는 텍스트/음성 채널을 만듭니다.\n'
                           '사용법은 다음과 같습니다.\n'
                           '```\n'
                           f'{command_prefix}개인방 @userName#1234\n'
                           f'{command_prefix}개인방 userName\n'
                           f'{command_prefix}개인방 @secondUser#5678 @andThird#9012 @fourth#3456\n'
                           f'{command_prefix}개인방 secondUser andThird fourth'
                           '```\n'
                           ' 참여하는 멤버를 `@이름#0000`와 같이 언급할 수 없다면 '
                           '`이름`과 같이 이름만 입력해도 됩니다.')
    async def private_room(self, ctx: commands.Context, member: Member, *members: Member):
        msg = await ctx.send(f'{ctx.author.mention} 개인방을 만들고 있습니다...')
        try:
            overwrites = {ctx.guild.default_role: PermissionOverwrite(read_messages=False),
                          self.client.user: PermissionOverwrite(read_messages=True)}
            members = list(members)
            members.append(member)
            for member in members:
                overwrites[member] = PermissionOverwrite(read_messages=True)
            text_channel: TextChannel = await ctx.guild.create_text_channel(f'개인방 {self.object_id}호실',
                                                                            overwrites=overwrites)
            voice_channel: VoiceChannel = await ctx.guild.create_voice_channel(f'개인방 {self.object_id}호실',
                                                                               overwrites=overwrites)
            text_url = f'https://discordapp.com/channels/{ctx.guild.id}/{text_channel.id}'
            voice_url = f'https://discordapp.com/channels/{ctx.guild.id}/{voice_channel.id}'
            embed = Embed(title=':spy: 개인방 개설', colour=Colour.blurple(), description='개인방을 개설했습니다.')
            embed.set_author(name=ctx.author, icon_url=ctx.author.avatar_url)
            embed.set_thumbnail(url=ctx.guild.icon_url)
            embed.add_field(name=':busts_in_silhouette: 멤버', inline=False,
                            value=f':small_orange_diamond: {ctx.author}\n:small_blue_diamond: ' +
                                  ('\n:small_blue_diamond: '.join(str(member) for member in members)))
            embed.add_field(name=':envelope: 텍스트 채널', value=f'텍스트 채널을 보려면 **[여기]({text_url})**를 클릭하세요.')
            embed.add_field(name=':loud_sound: 음성 채널 (화면공유)',
                            value=f'음성 채널에서 화면공유를 활성화하려면 **[여기]({voice_url})**를 클릭하세요.')
            await msg.edit(content=f'{ctx.author.mention} 개인방을 만들었습니다.', embed=embed)
            await text_channel.send(embed=embed)
            self.object_id += 1
        except BaseException as e:
            await msg.edit(content=f'개인방을 만들 수 없습니다...```\n{e}\n```')

bot = commands.Bot(command_prefix=command_prefix, help_command=None, case_insensitive=True)
bot.add_cog(TRPGCog(bot))

bot_token = config("BOT_TOKEN")
bot.run(bot_token)


"""
Author : Raquel G. Alhama
Desc:
"""
import json
import sys
from src.configs.config_loader import load_config, json2strid

wins=[1,2,3,4,5,7,10]
thrs=[10, 50, 100]
dyns=[None, ""]
sizes=[100]#tried 500 but gives lots of nan
negatives=[15] # only for sgns; tried 0 gives lots of nan
negs=[1,15] #only for svd
#simthrs=[0.6, 0.7, 0.8, 0.9] Not generate in configs but only during evaluation

def generate_config_files(baseconf, repr):
    confnumbr=1
    lines=""
    for actconf in generate_configs(baseconf, repr):
        newf="configs/config%i.json"%confnumbr
        with open(newf, "w") as fn:
            json.dump(actconf, fn, indent=4, sort_keys=True)
        name=json2strid(newf, repr)
        lines+=name+"\n"
        confnumbr+=1

    #Write list of model ids
    with open("list_of_confs_for_corrs_%s.txt"%repr, "w") as fn:
        fn.write(lines)

def generate_configs(baseconfig_f, repr):
    actconf=load_config(baseconfig_f)
    for win in wins:
        for thr in thrs:
            for dyn in dyns:
                for size in sizes:
                    actconf['counts']['win'] = win
                    actconf['counts']['thr'] = thr
                    actconf['counts']['dyn'] = dyn
                    actconf['svd']['dim'] = size
                    actconf['sgns']['size'] = size
                    if repr == 'sgns':
                        for negative in negatives:
                            actconf['sgns']['negative'] = negative
                            yield actconf
                    elif repr == 'svd':
                        for neg in negs:
                            actconf['svd']['neg'] = neg
                            yield actconf

if __name__ == "__main__":
    baseconfig_f="configs/base/base.json"
    model=sys.argv[1]
    print(model)
    generate_config_files(baseconfig_f, model)


import cv2
from face_detect.align_custom import AlignCustom
from face_detect.face_feature import FaceFeature
from face_detect.mtcnn_detect import MTCNNDetect
from face_detect.tf_graph import FaceRecGraph
import sys
import json
import numpy as np
import time

'''
Description:
User input his/her name or ID -> Images from Video Capture -> detect the face -> crop the face and align it
    -> face is then categorized in 3 types: Center, Left, Right
    -> Extract 128D vectors( face features)
    -> Append each newly extracted face 128D vector to its corresponding position type (Center, Left, Right)
    -> Press Q to stop capturing
    -> Find the center ( the mean) of those 128D vectors in each category. ( np.mean(...) )
    -> Save

'''

usb_cam = 0  # select webcam
MTCNNGraph = FaceRecGraph()
aligner = AlignCustom()
extract_feature = FaceFeature(FRGraph)
face_rec = MTCNNDetect(MTCNNGraph, scale_factor=2)

def create_manual_data():
    FRGraph = FaceRecGraph()
    MTCNNGraph = FaceRecGraph()
    aligner = AlignCustom()
    extract_feature = FaceFeature(FRGraph)
    face_rec = MTCNNDetect(MTCNNGraph, scale_factor=2)

    vs = cv2.VideoCapture(usb_cam)  # get input from webcam
    start = time.time()
    PERIOD_OF_TIME = 15  # input time to break
    print('Input your name..')
    new_name = input()  # get in add_user
    f = open('face_detect/facerec_128D.txt', 'r')
    data_set = json.loads(f.read())
    person_imgs = {"Left": [], "Right": [], "Center": []}
    person_features = {"Left": [], "Right": [], "Center": []}
    print("Please start turning slowly. Press 'q' to save and add this new user to the dataset")
    while True:
        _, frame = vs.read()
        rects, landmarks = face_rec.detect_face(
            frame, 80)  # min face size is set to 80x80
        aligns = []
        positions = []
        for (i, rect) in enumerate(rects):
            aligned_frame, pos = aligner.align(160, frame, landmarks[:, i])
            if len(aligned_frame) == 160 and len(aligned_frame[0]) == 160:
                person_imgs[pos].append(aligned_frame)
                aligns.append(aligned_frame)
                positions.append(pos)

        if(len(aligns) > 0):
            features_arr = extract_feature.get_features(aligns)
            recog_data = findPeople(features_arr, positions)
            for (i, rect) in enumerate(rects):
                # draw bounding box for the face
                cv2.rectangle(frame, (rect[0], rect[1]),
                              (rect[2], rect[3]), (0, 255, 0), 2)

        cv2.imshow("Captured face", frame)
        key = cv2.waitKey(1) & 0xFF
        if key == ord("q"):
            break
        # break function in time
        if time.time() > start + PERIOD_OF_TIME:
            break

    for pos in person_imgs:  # there r some exceptions here, but I'll just leave it as this to keep it simple
        person_features[pos] = [
            np.mean(extract_feature.get_features(person_imgs[pos]), axis=0).tolist()]
    data_set[new_name] = person_features
    f = open('face_detect/facerec_128D.txt', 'w')
    f.write(json.dumps(data_set))

    cv2.destroyAllWindows()

'''
facerec_128D.txt Data Structure:
{
"Person ID": {
    "Center": [[128D vector]],
    "Left": [[128D vector]],
    "Right": [[128D Vector]]
    }
}
This function basically does a simple linear search for
^the 128D vector with the min distance to the 128D vector of the face on screen
'''

def findPeople(features_arr, positions, thres=0.6, percent_thres=90):
    '''
    :param features_arr: a list of 128d Features of all faces on screen
    :param positions: a list of face position types of all faces on screen
    :param thres: distance threshold
    :return: person name and percentage
    '''
    f = open('face_detect/facerec_128D.txt', 'r')
    data_set = json.loads(f.read())
    returnRes = []
    for (i, features_128D) in enumerate(features_arr):
        result = "Unknown"
        smallest = sys.maxsize
        for person in data_set.keys():
            person_data = data_set[person][positions[i]]
            for data in person_data:
                distance = np.sqrt(np.sum(np.square(data-features_128D)))
                if(distance < smallest):
                    smallest = distance
                    result = person
        percentage = min(100, 100 * thres / smallest)
        if percentage <= percent_thres:
            result = "Unknown"
        returnRes.append((result, percentage))
    return returnRes

if __name__ == '__main__':
    create_manual_data()


#import pymongo
#from pymongo import MongoClient
#import pyotp
from UIDdb import Db

UID_db = Db() #Initialization of Class

def app_search(UID):
     app_query_result= UID_db.lookup(UID)

     appList = [appName['appName'] for appName in app_query_result]

     return appList

def user_search(UID):
     user_query_result = UID_db.lookup(UID)
     ownerName = [Owner['Owner'] for Owner in user_query_result]

     for item in ownerName:
           userName = item

     return userName

#def app_OTP(key):
    #totp = pyotp.TOTP(key)
    #otp = totp.now()
    #return 'Welcome to UID Server \n' + 'Your OTP is %s' %otp


from KMCLib import *
import numpy

class CustomRateCalculator(KMCRateCalculatorPlugin):
    """ Class for defining the custom rates function for the KMCLib paper. """

    def rate(self, geometry, elements_before, elements_after, rate_constant,
            process_number, coordinate):
        """ Overloaded base class API function """
        diff = 1.0

        # Get the number of U and D neighbours
        u_neighbours = len([ e for e in [elements_before[1],
            elements_before[2], elements_before[3], elements_before[4]] if e == "U"])
        d_neighbours = len([ e for e in [elements_before[1],
            elements_before[2], elements_before[3], elements_before[4]] if e == "D"])

        # Flipping U -> D
        if process_number == 0:
            # D neighbours count as negetive, U neighbours as positive
            diff = u_neighbours - d_neighbours

        # Flipping D -> U
        if process_number == 1:
            # U neighbours count as negetive, D neighbours as positive
            diff = d_neighbours - u_neighbours

        J = 1.0
        kbT = 1.0

        return min(1.0, numpy.exp(-diff*J/kbT))

    def cutoff(self):
        """ Determines the cutoff for this custom model """
        return 1.0

# Load the configuration and interactions
configuration = KMCConfigurationFromScript("config.py")
interactions = KMCInteractionsFromScript("interaction.py")

# Set the rate calculator
interactions.setRateCalculator(rate_calculator=CustomRateCalculator)

# Create the model
model = KMCLatticeModel(configuration, interactions)

# Define the parameters
control_parameters = KMCControlParameters(number_of_steps=1000000,
                                          dump_interval=10000)

# Run the simulation -- save trajectory to 'ising_traj.py'
model.run(control_parameters, trajectory_filename='ising_traj.py')

# Save the results to file


import discord
from discord.ext import tasks, commands
import core.vars

class Math(commands.Cog):
    debug = True

    def __init__(self, bot):
        print("Math: Initialized")
        self.bot = bot

    def cog_unload(self):
        self.temp.cancel()

    @commands.command(aliases=['deg','temp','temperature'])
    async def degree(self, ctx, temperature, scale):
        """ Convert temperatures between fahrenheit and celsius """
        if(scale == "C" or scale == "c" or scale == "celsius" or scale == "celsius"):
            celsius = float(temperature)
            fahrenheit = celsius*9/5+32
            kelvin = celsius + 273.15
            await ctx.send("{c:.2f}°C = {f:.2f}°F or {k:.2f}°K".format(c=celsius,f=fahrenheit,k=kelvin))
            if(self.debug == True and core.vars.debug == True):
                print("Math: Converted Celsius to Fahrenheit")
        if(scale == "F" or scale == "f" or scale == "Fahrenheit" or scale == "fahrenheit"):
            fahrenheit = float(temperature)
            celsius = (fahrenheit-32)*5/9
            kelvin = celsius + 273.15
            await ctx.send("{f:.2f}°F = {c:.2f}°C or {k:.2f}°K".format(f=fahrenheit,c=celsius,k=kelvin))
            if(self.debug == True and core.vars.debug == True):
                print("Math: Converted Fahrenheit to Celsius")
        if(scale == "K" or scale == "k" or scale == "Kelvin" or scale == "kelvin"):
            kelvin = float(temperature)
            celsius = kelvin - 273.15
            fahrenheit = celsius*9/5+32
            await ctx.send("{k:.2f}°K = {c:.2f}°C or {f:.2f}°F".format(k=kelvin,c=celsius,f=fahrenheit))
            if(self.debug == True and core.vars.debug == True):
                print("Math: Converted Kelvin to Celsius")

    @commands.command()
    async def add(self,ctx,num1,num2):
        """ Adds two numbers together """
        await ctx.send(str(float(num1)+float(num2)))
        if(self.debug == True and core.vars.debug == True):
            print("Math: Added {} and {}".format(num1,num2))

    @commands.command()
    async def nether(self,ctx,xcoord,zcoord):
        """ Converts given Overworld coordinates to Nether coordinates """
        xcoord = float(xcoord)
        zcoord = float(zcoord)
        await ctx.send("Nether Coords:\nX: {x:.2f}\nZ: {z:.2f}".format(x=xcoord/8,z=zcoord/8))
        if(self.debug == True and core.vars.debug == True):
            print("Converted Overworld coords to Nether coords")
def setup(bot):
    bot.add_cog(Math(bot))


from datetime import datetime

from flask import render_template, flash, redirect, url_for, request, current_app, jsonify
from flask_login import current_user, login_required

from app import db
from app.main.forms import EditProfileForm, EmptyForm, EquationForm, MessageForm
from app.main import bp
from app.models import User, Equation, Message, Notification

@bp.before_request
def before_request():
    if current_user.is_authenticated:
        current_user.last_seen = datetime.utcnow()
        db.session.commit()

@bp.route('/', methods=['GET', 'POST'])
@bp.route('/index', methods=['GET', 'POST'])
@login_required
def index():
    form = EquationForm()
    if form.validate_on_submit():
        equation = Equation(x_var=form.x_var.data, y_var=form.y_var.data, operator=form.operator.data,
                            author=current_user)
        equation.calculate()
        db.session.add(equation)
        db.session.commit()
        flash('Equation has been submitted!')
        return redirect(url_for('main.index'))
    page = request.args.get('page', 1, type=int)
    equations = current_user.followed_equations().paginate(page, current_app.config['EQUATIONS_PER_PAGE'], False)
    next_url = url_for('main.index', page=equations.next_num) if equations.has_next else None
    prev_url = url_for('main.index', page=equations.prev_num) if equations.has_prev else None
    return render_template('index.html', title='Home', form=form, equations=equations.items, next_url=next_url,
                           prev_url=prev_url)

@bp.route('/user/<username>')
@login_required
def user(username):
    user = User.query.filter_by(username=username).first_or_404()
    page = request.args.get('page', 1, type=int)
    equations = user.equations.order_by(Equation.timestamp.desc()).paginate(
        page, current_app.config['EQUATIONS_PER_PAGE'], False)
    next_url = url_for('main.user', page=equations.next_num) if equations.has_next else None
    prev_url = url_for('main.user', page=equations.prev_num) if equations.has_prev else None
    form = EmptyForm()
    return render_template('user.html', user=user, equations=equations.items, next_url=next_url,
                           prev_url=prev_url, form=form)

@bp.route('/edit_profile', methods=['GET', 'POST'])
@login_required
def edit_profile():
    form = EditProfileForm(current_user.username)
    if form.validate_on_submit():
        current_user.username = form.username.data
        db.session.commit()
        flash('Your changes have been saved.')
        return redirect(url_for('main.edit_profile'))
    elif request.method == 'GET':
        form.username.data = current_user.username
    return render_template('edit_profile.html', title='Edit Profile', form=form)

@bp.route('/follow/<username>', methods=['POST'])
@login_required
def follow(username):
    form = EmptyForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=username).first()
        if user is None:
            flash(f'User {username} not found.')
            return redirect(url_for('main.index'))
        if user == current_user:
            flash('Error, you cannot follow yourself.')
            return redirect(url_for('main.user', username=username))
        current_user.follow(user)
        db.session.commit()
        flash(f'You are now following {username}!')
        return redirect(url_for('main.user', username=username))
    else:
        return redirect(url_for('main.index'))

@bp.route('/unfollow/<username>', methods=['POST'])
@login_required
def unfollow(username):
    form = EmptyForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=username).first()
        if user is None:
            flash(f'User {username} not found.')
            return redirect(url_for('main.index'))
        if user == current_user:
            flash('Error, you cannot unfollow yourself.')
            return redirect(url_for('main.user', username=username))
        current_user.unfollow(user)
        db.session.commit()
        flash(f'You are no longer following user: {username}!')
        return redirect(url_for('main.user', username=username))
    else:
        return redirect(url_for('main.index'))

@bp.route('/explore')
@login_required
def explore():
    page = request.args.get('page', 1, type=int)
    equations = Equation.query.order_by(Equation.timestamp.desc()).paginate(page,
                                                                            current_app.config['EQUATIONS_PER_PAGE'],
                                                                            False)
    next_url = url_for('main.explore', page=equations.next_num) if equations.has_next else None
    prev_url = url_for('main.explore', page=equations.prev_num) if equations.has_prev else None
    return render_template('index.html', title='Explore', equations=equations.items, next_url=next_url,
                           prev_url=prev_url)

@bp.route('/send_message/<recipient>', methods=['GET', 'POST'])
@login_required
def send_message(recipient):
    user = User.query.filter_by(username=recipient).first_or_404()
    form = MessageForm()
    if form.validate_on_submit():
        msg = Message(author=current_user, recipient=user,
                      body=form.message.data)
        db.session.add(msg)
        user.add_notification('unread_message_count', user.new_messages())
        db.session.commit()
        flash('Your message has been sent.')
        return redirect(url_for('main.user', username=recipient))
    return render_template('send_message.html', title='Send Message',
                           form=form, recipient=recipient)

@bp.route('/user/<username>/popup')
@login_required
def user_popup(username):
    user = User.query.filter_by(username=username).first_or_404()
    form = EmptyForm()
    return render_template('user_popup.html', user=user, form=form)

@bp.route('/messages')
@login_required
def messages():
    current_user.last_message_read_time = datetime.utcnow()
    current_user.add_notification('unread_message_count', 0)
    db.session.commit()
    page = request.args.get('page', 1, type=int)
    messages = current_user.messages_received.order_by(
        Message.timestamp.desc()).paginate(
            page, current_app.config['POSTS_PER_PAGE'], False)
    next_url = url_for('main.messages', page=messages.next_num) \
        if messages.has_next else None
    prev_url = url_for('main.messages', page=messages.prev_num) \
        if messages.has_prev else None
    return render_template('messages.html', messages=messages.items,
                           next_url=next_url, prev_url=prev_url)

bp.route('/notifications')
@login_required
def notifications():
    since = request.args.get('since', 0.0, type=float)
    notifications = current_user.notifications.filter(Notification.timestamp > since).order_by(Notification.timestamp.asc())
    return jsonify([{
        'name': n.name,
        'data': n.get_data(),
        'timestamp': n.timestamp
    } for n in notifications])


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter

color_bars = ['#1f77b4', '#ff7f0e']
color_lines = ['#2ca02c', '#d62728']
plt.style.use('seaborn-ticks')
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(15, 5.95))
ax2 = ax.twinx()

legend = []

# Formatting axis tick labels
def million(x, pos):
    return '%1.0fM' % (x * 1e-6)

def thousand(x, pos):
    return '%1.0fK' % (x * 1e-3)

def clean_data():
    df = pd.read_csv('who_suicide_statistics_modified3.csv', sep=",")
    df.rename(columns={c: c.strip() for c in df.columns}, inplace=True)
    df['suicides_no'] = df['suicides_no'].apply(lambda x: x if str(x).isnumeric() else 0).apply(np.int64)
    df['HDI for year'].fillna(0, inplace=True)
    df['gdp_for_year ($)'] = df['gdp_for_year ($)'].apply(lambda x: str(x).replace(',', '')).apply(np.int64)
    df['year'] = df['year'].astype('str')
    return df

df = clean_data()

df_pop = df.groupby(['year', 'sex']).agg({'population': 'sum'}).sort_values(by='year', ascending=True).reset_index().pivot(index='year', columns='sex', values='population')
df_suicide = df.groupby(['year', 'sex']).agg({'suicides_no': 'sum'}).sort_values(by='year', ascending=True).reset_index().pivot(index='year', columns='sex', values='suicides_no')

# Renaming columns for legend purpose (Population)
df_pop.rename(columns={'female': 'Female (Population)', 'male': 'Male (Population)'}, inplace=True)
df_pop.plot.bar(color=color_bars, ax=ax, legend=False)
ax.yaxis.set_major_formatter(FuncFormatter(million))

# Renaming columns for legend purpose (Suicides)
df_suicide.rename(columns={'female': 'Female (Suicide)', 'male': 'Male (Suicide)'}, inplace=True)
df_suicide.plot(color=color_lines, ax=ax2, legend=False, markersize=13, lw=5, marker='o')
ax2.yaxis.set_major_formatter(FuncFormatter(thousand))

ax.set_xlabel('Year', fontsize=20, fontweight="bold")
ax.set_ylabel('Population (Millions)', fontsize=20, fontweight="bold")
ax2.set_ylabel('# of Suicides (Thousands)', fontsize=20, fontweight="bold")

ax.tick_params(axis="x", labelsize=20, labelcolor="black", direction="out", length=5, labelrotation=85, pad=0.5)
ax.tick_params(axis="y", labelsize=20, labelcolor="black", direction="out", length=5)
ax2.tick_params(axis="y", labelsize=20, labelcolor="black", direction="out", length=5)

h1, l1 = ax.get_legend_handles_labels()
h2, l2 = ax2.get_legend_handles_labels()

ax.legend(h1 + h2, l1+l2, fontsize=18, loc='upper center', ncol=4, bbox_to_anchor=(0.5, -0.2))
plt.tight_layout()

# Output figure to file
plt.savefig("population_suicide_rate_per_year_sex.pdf",  bbox_inches="tight")


import os
import random

from django.conf import settings
from django.shortcuts import render
from django.urls import reverse
from django.http import HttpResponse, JsonResponse

from .models import Greeting

# Create your views here.
def index(request):
    return JsonResponse({
        "index": reverse("index"),
        "host": reverse("host"),
        "db": reverse("db")
    })

def host(request):
    try:
        lower_bound = int(os.environ.get("LOWER_RANDOM", 97))
        upper_bound = int(os.environ.get("UPPER_RANDOM", 97+25))
        randint = random.randint(lower_bound, upper_bound)
        random_char = chr(randint)
    except (TypeError, ValueError):
        random_char = "💩"

    return JsonResponse({
        "hostname": settings.HOST_NAME,
        "random_char": random_char
    })

def db(request):

    greeting = Greeting()
    greeting.save()

    greetings_serialized = [g.serialize() for g in Greeting.objects.all().order_by("-when")]

    resp = {
        'count': len(greetings_serialized),
        'data': greetings_serialized
    }

    return JsonResponse(resp)


# Time Complexity :O(n)
# Space Complexity :O(1)
# Did this code successfully run on Leetcode : yes
# Any problem you faced while coding this : no

# Your code here along with comments explaining your approach
class Solution(object):
    def merge(self, nums1, m, nums2, n):
        """
        :type nums1: List[int]
        :type m: int
        :type nums2: List[int]
        :type n: int
        :rtype: None Do not return anything, modify nums1 in-place instead.
        """
        #get end of both arrays
        i = m-1
        j = n-1
        e = m+n-1
        # sort it from the back highest to lowest
        while j >=0 and i >=0:
            if nums1[i] > nums2[j]:
                nums1[e] = nums1[i]
                i-=1
            else:
                nums1[e] = nums2[j]
                j-=1
            e-=1
        #fill the restif in the second array
        while j >=0:
            nums1[e] = nums2[j]
            j-=1
            e-=1


import os
import unittest
from tests.pages.address_page import AddressPage

from selenium.webdriver import DesiredCapabilities, Remote

class AddressTest(unittest.TestCase):
    DEFAULT_PHOTO = 'data/test_prod_photo.jpg'
    PROFILE_PHOTO = 'data/test_rest_photo.jpg'
    BIG_PROFILE_PHOTO = 'data/test_big_photo.jpg'
    WRONG_PROFILE_PHOTO = 'data/test_non_photo_file'

    def setUp(self):
        browser = os.environ.get('BROWSER', 'CHROME')

        self.driver = Remote(
            command_executor='http://127.0.0.1:4444/wd/hub',
            desired_capabilities=getattr(DesiredCapabilities, browser).copy()
        )

        self.address_page = AddressPage(self.driver)
        self.address_page.open()

        self.address_form = self.address_page.form

    def test_wrong_address_input(self):
        self.address_form.wait_open()

        self.address_form.set_address('some address')
        address_error = self.address_form.get_input_error()

        self.assertEqual(address_error, 'с точностью до дома')

    def test_help_block(self):
        self.address_form.wait_open()

        self.address_form.set_address('Маяковская')

        self.assertEqual(self.address_form.wait_help_block(), True)

    def tearDown(self):
        self.driver.quit()


#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#
import tensorflow as tf
import os

a = tf.placeholder(tf.int32, shape=None, name="a")
b = tf.placeholder(tf.int32, shape=None, name="b")
c = tf.placeholder(tf.int32, shape=None, name="c")

v = tf.Variable(dtype=tf.int32, initial_value=tf.constant(2), name="v")
aa = tf.multiply(a, v)
bb = tf.multiply(a, v)
cc = tf.add(c, bb)
global_step = tf.contrib.framework.get_or_create_global_step()
global_step_inc = tf.assign_add(global_step, 1)
hooks = [tf.train.StopAtStepHook(last_step=2)]
with tf.Session() as mon_sess:
    mon_sess.run(tf.initialize_all_variables())
    for i in range(2):
        print(mon_sess.run([aa, cc, global_step_inc], feed_dict={a: [1, 2, 3], b: [1, 2, 3],
                                                                 c: [1, 2, 3]}))

    signatures = {
        tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: {
            'inputs': {'a': a, "b": b, "c": c},
            'outputs': {"aa": aa, "cc": cc},
            'method_name': tf.saved_model.signature_constants.PREDICT_METHOD_NAME
        }
    }

    export_dir = os.path.dirname(os.path.abspath(__file__)) + "/export2"
    try:
        tf.gfile.DeleteRecursively(export_dir)
    except tf.errors.OpError:
        pass
    builder = tf.saved_model.builder.SavedModelBuilder(export_dir)

    signature_def_map = {}
    for key, sig in signatures.items():
        signature_def_map[key] = tf.saved_model.signature_def_utils.build_signature_def(
            inputs={name: tf.saved_model.utils.build_tensor_info(tensor) for name, tensor in
                    sig['inputs'].items()},
            outputs={name: tf.saved_model.utils.build_tensor_info(tensor) for name, tensor in
                     sig['outputs'].items()},
            method_name=sig['method_name'] if 'method_name' in sig else key)

        builder.add_meta_graph_and_variables(
            mon_sess,
            tf.saved_model.tag_constants.SERVING.split(','),
            signature_def_map=signature_def_map,
            clear_devices=True)
        builder.save()


# Time Complexity : O(n)
# Space Complexity : O(n) n = no. chars in Trie
# Did this code successfully run on Leetcode : No (Getting empty value)
# Any problem you faced while coding this : No

class Solution(object):

    class TrieNode():
        def __init__(self):
            self.children = {}
            self.word = ''

    def __init__(self):
        self.root = self.TrieNode()
        self.res = ''

    def insert(self, word):
        curr = self.root
        for c in word:
            if c not in curr.children:
                curr.children[c] = self.TrieNode()
            curr = curr.children[c]

        curr.word = word

    def dfs(self, root):
        if len(root.word) > len(self.res):
            self.res = root.word

        for i in range(len(root.children)):
            if root.children[i] is not None:
                self.dfs(root.children[i])

    def longestWord(self, words):
        """
        :type words: List[str]
        :rtype: str
        """
        if len(words) == 0:
            return

        root = self.TrieNode()
        for word in words:
            self.insert(word)

        self.dfs(root)
        return self.res


# Hyppopy - A Hyper-Parameter Optimization Toolbox
#
# Copyright (c) German Cancer Research Center,
# Division of Medical Image Computing.
# All rights reserved.
#
# This software is distributed WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE.
#
# See LICENSE

import unittest

from hyppopy.solvers.OptunaSolver import *
from hyppopy.FunctionSimulator import FunctionSimulator
from hyppopy.HyppopyProject import HyppopyProject

class OptunaSolverTestSuite(unittest.TestCase):

    def setUp(self):
        pass

    def test_solver_complete(self):
        config = {
            "hyperparameter": {
                "axis_00": {
                    "domain": "uniform",
                    "data": [300, 800],
                    "type": float
                },
                "axis_01": {
                    "domain": "uniform",
                    "data": [-1, 1],
                    "type": float
                },
                "axis_02": {
                    "domain": "uniform",
                    "data": [0, 10],
                    "type": float
                }
            },
            "max_iterations": 100
        }

        project = HyppopyProject(config)
        solver = OptunaSolver(project)
        vfunc = FunctionSimulator()
        vfunc.load_default()
        solver.blackbox = vfunc
        solver.run(print_stats=False)
        df, best = solver.get_results()
        self.assertTrue(300 <= best['axis_00'] <= 800)
        self.assertTrue(-1 <= best['axis_01'] <= 1)
        self.assertTrue(0 <= best['axis_02'] <= 10)

        for status in df['status']:
            self.assertTrue(status)
        for loss in df['losses']:
            self.assertTrue(isinstance(loss, float))

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