import serial
import time
import hashlib

# define constants
SERIAL_DEVICE = '/dev/ttyS0' # for pi zero w
# SERIAL_DEVICE = '/dev/ttyAMA0' # for pi 3+
BAUD_RATE = 115200 # for SIM7000 family
# BAUD_RATE = 9600 # for SIM800 family
TIMEOUT = 10 # wait for 10 seconds before giving up on a command (it is high to account for the GPS latency)
ENTER_KEY = '\r\n'
FULL_FUNC = 'AT+CFUN=1'
GPS_LOCATION_CMD = 'AT+CGNSINF'
GPS_ON = 'AT+CGNSPWR=1'
GPS_OFF = 'AT+CGNSPWR=0'
GET_IMEI = 'AT+GSN'
SET_CMEE = 'AT+CMEE=1'
SET_SAPBR = 'AT+SAPBR=3,1,"%s","%s"'
APN_BEARER_OPEN = 'AT+SAPBR=1,1'
APN_BEARER_CLOSE = 'AT+SAPBR=0,1'
HTTP_INIT = 'AT+HTTPINIT'
HTTP_PARAM = 'AT+HTTPPARA="%s",%s'
HTTP_URL = 'AT+HTTPPARA="URL","%s"'
HTTP_DATA = 'AT+HTTPDATA=%s'
HTTP_START = 'AT+HTTPACTION=1'
HTTP_END = 'AT+HTTPTERM'
HTTP_READ = 'AT+HTTPREAD'

def send_command(cmd):
    # Define serial device
    sr_dev = serial.Serial(SERIAL_DEVICE, baudrate=BAUD_RATE, timeout=1)
    # Transmit command to the SIM Module
    sr_dev.write(cmd+ENTER_KEY)
    # Receive output from the SIM Module
    rxbuffer = sr_dev.read(len(cmd)) # this will be the echo of the command
    print(rxbuffer)
    rxbuffer = sr_dev.read(100) # read the max characters allowed
    print(rxbuffer)
    print(sr_dev.read(100)) # read any additional characters to empty out buffer
    time.sleep(5)
    return rxbuffer

def get_location():
    while(send_command(GPS_ON)==None or send_command(GPS_ON)==''):
        continue
    lat = 0
    lgt = 0
    while (lat==0) and (lgt==0): # it takes a while before the GPS is ready wait for minimum 5-10 minutes
        data = send_command(GPS_LOCATION_CMD).split(',')
        if (len(data)>4): # sometimes due to not enough power device does not respond
            lat = 0 if data[3] == '' else float(data[3])
            lgt = 0 if data[4] == '' else float(data[4])
        else:
            lat = 0
            lgt = 0
        time.sleep(10)
    send_command(GPS_OFF)
    return (lat, lgt)

def send_location(loc, base_url):
    # loc = tuple(lat, long)
    print(loc)
    # get ID
    imei = "salt"+send_command(GET_IMEI)
    hash = hashlib.sha1(imei.encode("UTF-8")).hexdigest()
    uid = hash[:10]
    url = base_url+'?id='+uid+'&x='+str(loc[0])+'&y='+str(loc[1])
    # start post request
    send_command('AT+CIPSHUT')
    send_command(SET_CMEE)
    send_command(SET_SAPBR%("CONTYPE","GPRS"))
    send_command(SET_SAPBR%("APN","hologram"))
    while( 'OK' not in send_command(APN_BEARER_OPEN)):
        continue
    send_command(HTTP_INIT)
    send_command(HTTP_PARAM%("CID","1"))
    send_command(HTTP_URL%(url))
    send_command(HTTP_START)
    result = send_command(HTTP_READ)
    send_command(HTTP_END)
    send_command(APN_BEARER_CLOSE)
    print(result)

if __name__ == "__main__":
    url = 'http://iottracker.herokuapp.com/footprint'
    while True:
        send_location(get_location(), url)
        time.sleep(300)


"""
Run a full set of queries using the testdb_210126 database.

Tests in this file will only be run when the --midas-test-full-db option is passed to the pycharm
command.

Database files and query sequences are located in tests/data/testdb_210126, but only the genome
database file is included in version control. Other files need to be obtained separately. See the
Readme.md file in that directory for more information.
"""

import json
from csv import DictReader

import pytest

from midas.io.seq import SequenceFile, find_kmers_in_files
from midas.signatures.hdf5 import HDF5Signatures
from midas.db.midasdb import MIDASDatabase
from midas.db.models import ReferenceGenomeSet
from midas.query import runquery
from midas.cli import cli

@pytest.fixture(autouse=True, scope='module')
def testdb_files(request, testdb_dir):
	"""Paths to testdb_210126 files.

	Skips all dependent tests if the --midas-test-full-db command line option is not passed.

	Checks that the directory and required files/subdirectories exist and fails tests immediately
	if they do not.
	"""
	if not request.config.getoption('midas_test_full_db'):
		pytest.skip('--midas-test-full-db option not given')

	files = dict(
		root=testdb_dir,
		db=testdb_dir / 'testdb_210126-genomes.db',
		signatures=testdb_dir / 'testdb_210126-signatures.h5',
		queries=testdb_dir / 'query-seqs/queries.csv',
	)

	for k, v in files.items():
		# Raises FileNotFoundError if does not exist
		files[k] = v.resolve()

	return files

@pytest.fixture(scope='module')
def signatures(testdb_files):
	"""K-mer signatures for test genomes."""
	return HDF5Signatures.open(testdb_files['signatures'])

@pytest.fixture(scope='module')
def testdb(testdb_session, signatures):
	"""Full MIDASDatabase object for test db."""

	session = testdb_session()
	gset = session.query(ReferenceGenomeSet).one()

	return MIDASDatabase(gset, signatures)

@pytest.fixture(scope='module')
def query_data(testdb_files):
	"""Query files and their expected taxa."""
	table_path = testdb_files['queries']
	seqs_dir = table_path.parent

	files = []
	expected_taxa = []

	with open(table_path, newline='') as f:
		for row in DictReader(f):
			file = SequenceFile(
				path=seqs_dir / (row['name'] + '.fa'),
				format='fasta',
			)
			files.append(file)
			expected_taxa.append(row['expected_taxon'])

	return files, expected_taxa

def test_query_python(testdb, query_data):
	"""Run a full query using the Python API."""

	query_files, expected_taxa = query_data
	query_sigs = find_kmers_in_files(testdb.kmerspec, query_files)

	results = runquery(testdb, query_sigs, query_files)

	assert len(results.items) == len(query_files)

	for item, file, expected_key in zip(results.items, query_files, expected_taxa):
		expected_taxon = testdb.genomeset.taxa.filter_by(key=expected_key).one() if expected_key else None

		assert item.input.file == file
		assert item.success

		if expected_taxon is None:
			assert item.predicted_taxon is None
			assert item.report_taxon is None
			assert item.primary_match is None
		else:
			assert item.predicted_taxon == expected_taxon
			assert item.report_taxon == expected_taxon
			assert item.primary_match is not None
			assert item.primary_match.matching_taxon == expected_taxon

			# In this database, closest match should be primary match
			assert item.closest_match == item.primary_match

		assert not item.warnings
		assert item.error is None

@pytest.mark.parametrize('out_fmt', ['json'])
def test_query_cli(testdb_files, query_data, out_fmt, tmp_path):
	"""Run a full query using the command line interface."""
	results_file = tmp_path / 'results.json'
	query_files, expected_taxa = query_data

	args = [
		f'--db={testdb_files["root"]}',
		'query',
		f'--output={results_file}',
		f'--outfmt={out_fmt}',
		*(str(f.path) for f in query_files),
	]

	cli.main(args, standalone_mode=False)

	if out_fmt == 'json':
		_check_results_json(results_file, query_files, expected_taxa)
	else:
		assert False

def _check_results_json(results_file, query_files, expected_taxa):
	with results_file.open() as f:
		results = json.load(f)

	items = results['items']
	assert isinstance(items, list)
	assert len(items) == len(query_files)

	for item, file, expected in zip(items, query_files, expected_taxa):
		assert item['input']['label'] == file.path.name
		assert item['success'] is True

		if expected == '':
			assert item['predicted_taxon'] is None
			assert item['report_taxon'] is None
			assert item['primary_match'] is None
		else:
			predicted = item['predicted_taxon']
			assert predicted is not None
			assert predicted['key'] == expected
			assert item['report_taxon'] == predicted
			assert item['primary_match'] is not None
			assert item['primary_match']['matching_taxon']['key'] == expected

			# In this database, closest match should be primary match
			assert item['closest_match'] == item['primary_match']

		assert item['warnings'] == []
		assert item['error'] is None


"""Description de l'environnement"""
import numpy as np
from . import turn as t
from . import snake
from . import apple

class Environment:
    NOTHING = 0
    SNAKE = 1
    APPLE = 2

    def __init__(self, grid_size_x=10, grid_size_y=10):
        """Init the grid at the begining of the game"""
        self.grid_size_x = grid_size_x
        self.grid_size_y = grid_size_y
        self.grid = np.zeros((self.grid_size_x, self.grid_size_y))
        self.tmp = []

        """Init la durée d'un tour"""
        self.turn = t.Turn(0.5)

        """Init le serpent"""
        self.snake = snake.Snake(4, 4)
        self.set_grid(self.snake.get_head()[0], self.snake.get_head()[1], self.SNAKE)

        """Init la pomme à une place random"""
        self.apple = apple.Apple(np.random.randint(0, 9), np.random.randint(0, 9))
        while not self.is_empty(self.apple.get_apple()[0], self.apple.get_apple()[1]):
            self.apple.set_apple(np.random.randint(0, 9), np.random.randint(0, 9))
        self.set_grid(self.apple.get_apple()[0], self.apple.get_apple()[1], self.APPLE)

    def delete(self, x, y):
        """Permet d'effacer un élément de la grille"""
        self.grid[x, y] = self.NOTHING

    def set_grid(self, x, y, element):
        """Place un élément dans la grille"""
        self.grid[x, y] = element

    def erase_grid(self):
        for x, row in enumerate(self.grid):
            for y, element in enumerate(row):
                self.grid[x, y] = self.NOTHING

    def get_grid(self):
        """Retourne la grille de jeu"""
        return self.grid

    def is_empty(self, x, y):
        """Retourne vrai si la case de la grille demandée est vide"""
        if self.grid[x, y] == self.NOTHING:
            return True
        else:
            return False

    def next_move(self, mouvement):
        """Permet de générer la grille pour le prochain tour"""
        """Check l'ancien mouvement pour éviter l'effet de revenir en arrière"""
        if mouvement == 0:  # gauche
            if self.snake.get_size() > 1:
                if [self.snake.get_head()[0] - 1, self.snake.get_head()[1]] == self.snake.get_body()[1]:
                    self.snake.move_snake(1, 0)
                else:
                    self.snake.move_snake(-1, 0)
            else:
                self.snake.move_snake(-1, 0)
        elif mouvement == 1:  # haut
            if self.snake.get_size() > 1:
                if [self.snake.get_head()[0], self.snake.get_head()[1] - 1] == self.snake.get_body()[1]:
                    self.snake.move_snake(0, 1)
                else:
                    self.snake.move_snake(0, -1)
            else:
                self.snake.move_snake(0, -1)
        elif mouvement == 2:  # droite
            if self.snake.get_size() > 1:
                if [self.snake.get_head()[0] + 1, self.snake.get_head()[1]] == self.snake.get_body()[1]:
                    self.snake.move_snake(-1, 0)
                else:
                    self.snake.move_snake(1, 0)
            else:
                self.snake.move_snake(1, 0)
        elif mouvement == 3:  # bas
            if self.snake.get_size() > 1:
                if [self.snake.get_head()[0], self.snake.get_head()[1] + 1] == self.snake.get_body()[1]:
                    self.snake.move_snake(0, -1)
                else:
                    self.snake.move_snake(0, 1)
            else:
                self.snake.move_snake(0, 1)

        """Vérification si le snake est au bon endroit"""
        self.check_loose(self.snake.get_head())

        """Check si tete serpent sur la meme case que la pomme"""
        if self.apple.get_apple() == self.snake.get_head():
            """Ajoute body"""
            self.snake.add_body()
            """Définit une nouvelle pomme"""
            self.apple.set_apple(np.random.randint(0, 9), np.random.randint(0, 9))
            while not self.is_empty(self.apple.get_apple()[0], self.apple.get_apple()[1]):
                self.apple.set_apple(np.random.randint(0, 9), np.random.randint(0, 9))
            """Accélère le jeu"""
            self.turn.reduce_turn()
            """Redéfinition de la grille"""
            self.erase_grid()
            for i in range(0, self.snake.get_size()):
                self.set_grid(self.snake.get_body()[i][0], self.snake.get_body()[i][1], self.SNAKE)
        elif self.snake.get_body().count(self.snake.get_head()) > 1:
            """Si le serpent touche son body"""
            exit(0)

        """Redéfinition de la grille"""
        self.erase_grid()
        for i in range(0, self.snake.get_size()):
            self.set_grid(self.snake.get_body()[i][0], self.snake.get_body()[i][1], self.SNAKE)
        self.set_grid(self.apple.get_apple()[0], self.apple.get_apple()[1], self.APPLE)

    def check_loose(self, position):
        """Vérifie qu'on est toujours dans l'environnement"""
        if position[0] < 0 or position[1] < 0:
            exit(0)
        elif position[0] > 9 or position[1] > 9:
            exit(0)


import docx, os, sys

backgrounds = {}
with open('backgrounds.txt', 'r') as f:
    for line in f:
        backgrounds[line.strip()] = set()

non_bg = {}

cutscenes = {}

direcs = ["Act 3 Prim"]#["Act 1", "Act 2 Lilith", "Act 2 Prim"]#, "Act 3 Prim", "Act 3 Lilith"]

for direc in direcs:
    for f in os.listdir(f'./{direc}'):
        doc = docx.Document("./"+direc+"/"+f)
        for line in doc.paragraphs:
            if line.runs[0].bold:
                if 'OR' in line.text:
                    continue
                cleaned = line.text.replace("’", "'").replace("–", "-")

                if 'Cutscene' in cleaned or 'Nostalgia' in cleaned or 'End Scene' in cleaned:
                    continue

                if cleaned not in backgrounds:
                    if cleaned in non_bg:
                        non_bg[cleaned].add(f'{direc}/{f}')
                    else:
                        non_bg[cleaned] = set([f'{direc}/{f}'])

print("\nERRORS? ----------\n")

for bg in non_bg:
    print(bg)
    for f in non_bg[bg]:
        print("    "+f)
    print()


from collections import deque

n, m = map(int, input().split())

def dijkstra(G, start):
    Q = deque()
    s = {}
    s[start] = 0
    Q.append(start)
    while Q:
        v = Q.pop()
        for u in G[v]:
            if (u not in s) or ((s[v]+G[v][u])<s[u]):
                s[u] = s[v] + G[v][u]
                Q.append(u)
    return(s)

def sum_of_dict(d):
    dkeys = d.keys()
    s = 0
    for i in dkeys:
        s += d[i]
    return s

def add_edge(G, a, b, weight):
    if a not in G:
        G[a] = {b: weight}
    else:
        G[a][b] = weight

G = {i:{} for i in range(n)}
for i in range(m):
    a, b, weight = input().split()
    weight = int(weight)
    a = int(a)
    b = int(b)
    add_edge(G, a, b, weight)
    add_edge(G, b, a, weight)

a = [sum_of_dict(dijkstra(G, i)) for i in range(n)]
print(a.index(min(a)))


import os
import math
import sys
ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(ROOT_DIR)
sys.path.append(os.path.join(ROOT_DIR, 'models'))
sys.path.append(os.path.join(ROOT_DIR, 'data'))
sys.path.append(os.path.join(ROOT_DIR, 'utils'))

import argparse
import torch

from model import import_class, compute_iou, compute_iou_scannet
from network import *

parser = argparse.ArgumentParser()
parser.add_argument('--gpu_id', type=int, default=0, help='GPU to use [default: GPU 0]')
parser.add_argument('--model_name', type=str, default='PS2Net', help='name of model')
parser.add_argument('--dataset_name', type=str, default='ScanNet', help='the dataset to use [options: S3DIS, ScanNet]')

parser.add_argument('--data_dir', default='../datasets/ScanNet/P3/', help='path to point clouds')
parser.add_argument('--block_size', type=float, default=1.0, help='the size of blocks to split rooms')
parser.add_argument('--stride', type=float, default=1.0, help='the stride to slide along xy plane to split rooms')
parser.add_argument('--classes', type=int, default=21, help='S3DIS or ScanNet')
parser.add_argument('--log_dir', default='../log_scannet/P3_**', help='Log dir [default: log]')
parser.add_argument('--checkpoint', type=str, default=None, help='name of pre-trained network parameters')

parser.add_argument('--nThreads', default=1, type=int, help='# threads for loading data')
parser.add_argument('--batch_size', type=int, default=1, help='Batch Size during training')
parser.add_argument('--max_volumes', type=int, default=18, help='Maximum processing volumrs during testing')

parser.add_argument('--num_point', type=int, default=4096, help='Point number [default: 4096]')
parser.add_argument('--input_feat', type=int, default=3, help='The dimension of raw input features [Option: 3 or 9]')
parser.add_argument('--K', type=int, default=20, help='the maximum value of KNN')
parser.add_argument('--knn_list', default='[20,20,20,20]', help='the number of nearest neighbors to extract local feature in each encoder')
parser.add_argument('--num_clusters', default='[16,16,16,16]', help='NetVLAD hyperparameter, the number of clusters for each encoder')
parser.add_argument('--output_dim', default='[128,128,128,128]', help='size of the output space for dimension reduction after NetVLAD in each encoder')

parser.add_argument('--encoder_paras', default='[[64,64,128],[64,64,128],[64,64,128],[64,64,128]]',
                    help='The architecture of stacked encoder network.')
parser.add_argument('--encoder_dropout', default='[[0,0,0],[0,0,0],[0,0,0],[0,0,0]]',
                    help='The dropout_ratio in the stacked encoder networks.')
parser.add_argument('--decoder_paras', default='[512, 256, 128]',
                    help='The architecture of decoder network. [MLP, MLP]')
parser.add_argument('--decoder_dropout', default='[0, 0, 0]',
                    help='The dropout_ratio in the decoder network (the last dropout_ratio is set to 0)')

parser.add_argument('--activation', type=str, default='relu', help='activation function: relu, prelu, elu, leakyrelu')
parser.add_argument('--normalization', type=str, default='batch', help='normalization function: batch or instance')
parser.add_argument('--norm_momentum', type=float, default=0.1, help='normalization momentum, typically 0.1.')
parser.add_argument('--lossweight_path', type=str, default=None, help='the path to the label weights for weighted cross-entropy loss')

parser.add_argument('--augment', type=bool, default=False, help='Data augment or not [default: False]')
parser.add_argument('--test_area', type=str, default='5', help='Which areas to use for test, option:[1-6] [default: 5]')
opt = parser.parse_args()

args = vars(opt)
print('------------ Options -------------')
for k, v in sorted(args.items()):
    print('%s: %s' % (str(k), str(v)))
print('-------------- End ----------------')

LOG_DIR = opt.log_dir
if not os.path.exists(LOG_DIR):
    print('Please assign the log_dir used for storing training data!')
    exit()

LOG_FOUT = open(os.path.join(LOG_DIR, 'log_test_ep%s.txt' %opt.checkpoint.split('_')[0]), 'w')
LOG_FOUT.write(str(opt) + '\n')

def log_string(out_str):
    LOG_FOUT.write(out_str + '\n')
    LOG_FOUT.flush()
    print(out_str)

if __name__ == '__main__':

    if opt.dataset_name == 'S3DIS':
        from P1_data_loader import S3DISDataset
        testset = S3DISDataset('test', opt)
    elif opt.dataset_name == 'ScanNet':
        from P1_data_loader import ScannetDatasetWholeScene
        testset = ScannetDatasetWholeScene(opt.data_dir, opt.num_point, opt.K, 'test')
    else:
        raise Exception('Please enter correct dataset name. Options: S3DIS or ScanNet')

    testloader = torch.utils.data.DataLoader(testset, batch_size=opt.batch_size, shuffle=False,
                                              num_workers=opt.nThreads, drop_last=True)
    log_string('#testing point clouds = %d' % len(testset))

    network = import_class('network', opt.model_name)(opt)
    if opt.checkpoint is not None:
        checkpoint = torch.load(os.path.join(LOG_DIR, 'checkpoints', opt.checkpoint))
        network.load_state_dict(checkpoint['state_dict'])

    network = network.cuda()

    softmax = torch.nn.Softmax(dim=1)

    print('Evaluating begins..')
    with torch.no_grad():

        predicted_label_total = []
        gt_label_total = []

        for i, data in enumerate(testloader):
            input_pc, knn_idx, input_label = data

            if opt.dataset_name == 'ScanNet':
                input_pc = input_pc.view(-1, input_pc.shape[2], input_pc.shape[3]).cuda()
                knn_idx = knn_idx.view(-1, knn_idx.shape[2], knn_idx.shape[3]).long().cuda()
                input_label = input_label.view(-1, input_label.shape[2]).long().cuda()
            else:
                input_pc = input_pc.cuda()
                knn_idx = knn_idx.long().cuda()
                input_label = input_label.long().cuda()

            network.eval()

            # When evaluate ScanNet whole scene, process the scene in batch if the scene contains too many blocks.
            if input_pc.shape[0] > opt.max_volumes:
                num_batches = math.ceil(input_pc.shape[0] / opt.max_volumes)
                # print('The number of resultant volumes (%d) is larger than max_volumes (%d), processing in %d batches'
                #      %(input_pc.shape[0], opt.max_volumes, num_batches))
                pred = []

                for j in range(num_batches):
                    start_idx = j*opt.max_volumes
                    if j != num_batches -1:
                        end_idx = (j+1)*opt.max_volumes
                    else:
                        end_idx = input_pc.shape[0] + 1
                    pc_slice = input_pc[start_idx:end_idx,:,:]
                    knn_slice = knn_idx[start_idx:end_idx,:,:]

                    score_slice = network(pc_slice, knn_slice)
                    pred_slice = softmax(score_slice)
                    pred.append(pred_slice)
                pred = torch.cat(pred, dim=0)
            else:
                score = network(input_pc, knn_idx)
                pred = softmax(score)

            # accumulate accuracy
            _, predicted_label = torch.max(pred.detach(), dim=1, keepdim=False)

            predicted_label_total.append(predicted_label.cpu().detach())
            gt_label_total.append(input_label.cpu().detach())

        # compute iou
        predicted_label_total = torch.cat(predicted_label_total, dim=0).view(-1, opt.num_point)
        print(predicted_label_total.size())
        gt_label_total = torch.cat(gt_label_total, dim=0).view(-1, opt.num_point)
        if opt.dataset_name == 'S3DIS':
            test_accuracy, test_macc, test_iou, iou_perclass = compute_iou(predicted_label_total, gt_label_total, opt.classes)
        elif opt.dataset_name == 'ScanNet':
            test_accuracy, test_macc, test_iou, iou_perclass = compute_iou_scannet(predicted_label_total, gt_label_total, opt.classes)
        log_string('Test overall accuracy is %f' %test_accuracy)
        log_string('Test_macc is %f' %test_macc)
        log_string('Test_iou is %f' %test_iou)
        log_string(str(iou_perclass))

    LOG_FOUT.close()


'''
International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows:

'a' maps to ".-",
'b' maps to "-...",
'c' maps to "-.-.", and so on.

Given an array of strings words where each word can be written as a concatenation of the Morse code of each letter.

Return the number of different transformations among all words we have.

Example 1:

Input: words = ["gin","zen","gig","msg"]
Output: 2
Explanation: The transformation of each word is:
"gin" -> "--...-."
"zen" -> "--...-."
"gig" -> "--...--."
"msg" -> "--...--."
There are 2 different transformations: "--...-." and "--...--.".
'''

class Solution:
    def uniqueMorseRepresentations(self, words: List[str]) -> int:
        # Morse code
        morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
        # Hash map
        hmap = defaultdict(int)
        # Get word and decode it
        for word in words:
            re = ""
            for c in word:
                re += morse[(ord(c) - ord("a"))]
            # update hashmap
            hmap[re] = 1 + hmap.get(re,0)
        # ans will be the len of hashmap (num of keys)
        return(len(hmap))

LeetCode/Easy/804. Unique Morse Code Words.py


varsta = int(input('Varsta dv. este : '))
print(varsta)
varsta_ok = varsta >=18
varsta_no = varsta < 18
pasaport = input('Detineti un pasaport?  : ')
print(pasaport)
pasaport_da = 'da'
pasaport_nu = 'nu'

if varsta >=18  and pasaport == pasaport_da:
    print('Aveti dreputl sa calatoriti')
elif varsta >= 18 and pasaport == pasaport_nu:
    print('major fara pasaport, nu puteti calatori')
else:
    print('Suntei minor, trebuie sa calatoriti cu unul dintre parinti cel putin')

insotit_mama =input('Sunteti insotit de mama: ')
print(insotit_mama)
insotit_mama_da = 'da'
insotit_mama_nu = 'nu'
insotit_tata =input('Sunteti insotit de tata: ')
print(insotit_tata)
insotit_tata_da = 'da'
insotit_tata_nu = 'nu'

if insotit_mama == insotit_mama_da and insotit_tata == insotit_tata_da:
    print('Indepliniti conditiile, calatoriti impreuna cu ambii parinti')
elif insotit_mama == insotit_mama_da and insotit_tata == insotit_tata_nu:
    print('Calatoriti doar cu mama, dar aveti nevoie de act de permisiune a tatalui')
elif insotit_tata == insotit_tata_da and insotit_mama == insotit_mama_nu:
    print('Calatoriti impreuna cu tata, dar aveti nevoie de act de permsiune a mamei')
else:
    print('Sunteti minor nu puteti calatori singur')
act_permisiune_tata = input('atasati actul de permisiune al  tatalui: ')
print(act_permisiune_tata)
act_permisiune_tata_da = 'da'
act_permisiune_tata_nu = 'nu'

act_permisiune_mama = input('atasati actul de permisiune al  mamei: ')
print(act_permisiune_mama)
act_permisiune_mama_da = 'da'
act_permisiune_mama_nu = 'nu'

if insotit_tata == insotit_tata_da and insotit_mama == insotit_mama_nu and act_permisiune_mama == act_permisiune_mama_da:
    print('calatoriti cu tata, cu act de permisiune din partea mamei')
elif insotit_tata == insotit_tata_da and insotit_mama == insotit_mama_nu and act_permisiune_mama == act_permisiune_mama_nu:
    print('nu puteti calatoriti cu tata, cu act de permisiune din partea mamei')
elif insotit_mama == insotit_mama_da and insotit_tata== insotit_tata_nu and act_permisiune_tata == act_permisiune_tata_da :
    print('calatoriti cu mama, cu un act de permisiune din partea tatalui')
elif insotit_mama == insotit_mama_da and insotit_tata== insotit_tata_nu and act_permisiune_tata == act_permisiune_tata_nu :
    print('Nu puteti calatori fara act de permisiune din partea tatalui')
else:
    print('Nu puteti calatori fara nicio permisiune ')


#!/usr/bin/env python

from lvds.slack.connect import SlackConnect

import sys

class SlackMsg(SlackConnect):

    default_channel=None

    ignore_interactive = False

    def __init__(self, username=None, default_channel=None):
        if username is None:
            raise AttributeError("which username should we use with Slack?")

        SlackConnect.__init__(self, username)

        if default_channel is not None:
            if default_channel.startswith("@"):
                self.default_channel = self.userid(default_channel[1:])
            else:
                self.default_channel = default_channel

    def userid(self, user=None):

        if user is None:
            raise AttributeError("user can not be empty")

        acct_id = None
        for acct in self.test_connection().api_call("users.list")['members']:
            if 'profile' in acct and \
              acct['profile']['display_name_normalized'] == user:
                  acct_id = acct['id']
                  break

        if acct_id is None:
            raise AttributeError("lookup for {} failed.".format(user))

        for acct in self.test_connection().api_call("im.list")['ims']:
            if acct['user'] == acct_id:
                return acct['id']

        return None

    """
      channel: CHANNEL_ID or #channel or @username
    """
    def msg(self, message, channel=None):

        if message is None:
            if sys.stdout.isatty():
                print("no message means nothing to do")
            return

        sc = self.test_connection()

        if channel is None:
            if self.default_channel is not None:
                channel = self.default_channel
            else:
                channel = '#random'
        elif channel.startswith("@"):
            channel = self.userid(channel[1:])

        ret = None
        if not self.ignore_interactive and sys.stdout.isatty():
            print("SLACK: [%s]: %s" % (channel, message))
        else:
            ret = sc.api_call(
              'chat.postMessage',
              as_user=True,
              channel=channel,
              text=message
            )

        return ret

if __name__ == "__main__":

    defaults = {
      'robot': 'slackinator',
      'channel': '#playground' # for users place an @ in front of the username
                               # i.e. @Steve
    }

    if sys.stdout.isatty():

        print("Since you are running this interactively, you can modify the\n"
          "defaults, however nothing will actually be sent to Slack, instead\n"
          "you will get a notification as to what would have been sent out.\n"
          "\nIf you want to have these tests sent to slack, you need to run\n"
          "it non-interactively, in other words in the background.\n\n"
          "i.e. on unix enter ` | grep test` at the end of your "
          "command.\nThis makes it non-interactive.\n"
          "**This robot must be identified in your slack configuration "
          "file.**\n")

        robot = input("which robot do you want to be sending the messages? "
          "[{}] > ".format(defaults['robot'])
        )

        if len(robot) == 0:
            robot = defaults['robot']

        channel = input("which channel do you want to receive the messages? "
          "[{}] > ".format(defaults['channel'])
        )

        if len(channel) == 0:
            channel = defaults['channel']
    else:
        robot = defaults['robot']
        channel = defaults['channel']

    sm = SlackMsg(robot)
    print(sm.msg("TEST: and here I am", channel))

    sm2 = SlackMsg(robot, channel)
    print(sm2.msg("TEST: using defaults"))


from PyQt5.QtGui import QImage, QPixmap
from requests import get as getURL
from requests.exceptions import RequestException

from ..DBInterface import FILM_TABLE, FilmInterface, getColumn
from ..RecommendationSystem import RecommendationSystem
from .HomepagePartUI import Ui_HomepagePart

class HomepagePart(Ui_HomepagePart):
    def setupHomepage(self, HomepagePart):
        self.retranslateUi = super().retranslateUi
        super().setupUi(HomepagePart)

        self.Recommendation1.enterEvent = self.RecommendationTitle1.enterEvent
        self.Recommendation1.leaveEvent = self.RecommendationTitle1.leaveEvent
        self.Recommendation2.enterEvent = self.RecommendationTitle2.enterEvent
        self.Recommendation2.leaveEvent = self.RecommendationTitle2.leaveEvent
        self.Recommendation3.enterEvent = self.RecommendationTitle3.enterEvent
        self.Recommendation3.leaveEvent = self.RecommendationTitle3.leaveEvent

        self.recommendationSystem = RecommendationSystem(self.login)
        self.makeRecommendationInfo()

    def showHomepage(self):
        self.makeRecommendationInfo()
        self.SearchFrame.show()
        self.RecommendationFrame.show()
        self.HLineSearch.show()
        self.Search.setAutoDefault(True)
        self.Search.setDefault(True)

    def hideHomepage(self):
        self.SearchFrame.hide()
        self.RecommendationFrame.hide()
        self.HLineSearch.hide()
        self.Search.setAutoDefault(False)
        self.Search.setDefault(False)

    def hideSearch(self):
        self.SearchFrame.hide()
        self.HLineSearch.hide()
        self.Search.setAutoDefault(False)
        self.Search.setDefault(False)

    def showSearch(self):
        self.SearchFrame.show()
        self.HLineSearch.show()
        self.Search.setAutoDefault(True)
        self.Search.setAutoDefault(True)

    def hideRecommendation(self):
        self.RecommendationFrame.hide()

    def showRecommendation(self):
        self.RecommendationFrame.show()

    def movie1(self):
        self.showInformation(self.recommendations[0])
        self.hideHomepage()

    def movie2(self):
        self.showInformation(self.recommendations[1])
        self.hideHomepage()

    def movie3(self):
        self.showInformation(self.recommendations[2])
        self.hideHomepage()

    def search(self):
        self.hideRecommendation()
        self.showSearchResult(self.SearchInput.text())

    def makeRecommendationInfo(self):
        self.recommendations = self.__generateRecommendation()

        pictures = (self.RecommendationPicture1, self.RecommendationPicture2,
                    self.RecommendationPicture3)
        titles = (self.RecommendationTitle1, self.RecommendationTitle2, self.RecommendationTitle3)

        posterFetcher = FilmInterface(False)

        for i in range(3):
            posterFetcher.selectFilm(self.recommendations[i])
            result = posterFetcher.fetchResult()

            if len(result) == 0:
                raise RuntimeError('the recommendation algorithm has suggested a ghost film')

            name = getColumn(result[0], FILM_TABLE.chineseName)
            url = getColumn(result[0], FILM_TABLE.picture)
            titles[i].setText(name)
            pictures[i].clear()

            if url is not None:
                try:
                    res = getURL(url, timeout=20)
                    if res.status_code != 200:
                        raise RequestException()

                    image = QImage.fromData(res.content)
                    pictures[i].setPixmap(QPixmap.fromImage(image))
                except RequestException:
                    pictures[i].setText('海报加载失败')
            else:
                pictures[i].setText('暂无海报')

    def __generateRecommendation(self):
        return self.recommendationSystem.makeRecommendation(3)


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

"""
Split models out of a monolithic models.py and into separate modules. Thanks
to Patrick Altman's tutorial at ...
   http://paltman.com/2008/01/29/breaking-apart-models-in-django/

Thanks also to all Django developers for making such great software.

This script is in the public domain.

Author = Mike Dewhirst 16 Aug 2012
Python = 2.7
Django = 1.4

17 Aug 2012     Adjusted self.writemeta() to stop inserting db_table and
                generated topline from models.py. Thanks Melvyn Sopacua

21 Aug 2012     Extra '\n' in writemeta

There are no unit tests for this. Run your own app unit tests prior to running
this script and again afterwards. That constitutes the essential testing. This
is a script which is intended to be run once per app then thrown away.

To reverse the process: 1. delete models dir 2. rename models.bak to models.py

In my models.py there are only three types of imports: related models, api
calls on imported models and external imports. ymmv.

There may be other classes in models.py - if so this script ignores them. If
you need to find them look in models/__init__.py

Flow of the script:

Rename models.py to models.bak

scan models.bak and collect all the imports into self.imports including the
new dotted notation for the current directory which in Python 2.7 requires
from __future__ import absolute_import so that the various model files can
do ... from .<model-filename> import <model-class>

write out models.sans w/o imports finally closing models.bak as a true copy
and backup of models.py

scan models.sans for model classes
    write out the class
    analyse it for items to be imported and fill a list with those imports
    insert the imports at the top

This script writes implied imports. An implied import looks like this:

    #from .model.lower import model

... and it appears among the imports with the real ones. It represents the
related models which appear within quotes in the model files.

Constants which appear in the models.py file need to be imported from somewhere
or they get omitted from the split-out files. A convenient spot is inside the
<app>/__init__.py file so they can be ... from <app> import CONST1, CONST2 etc

I had to write a "seemsok" method to detect names embedded within other names

"""

import os

app = 'abc'
home = '/users/miked/py'
project = 'xyz'

aggregate = False   # aggregate imports from the same module

startline = 3 # start inserting import lines into .py files below topline

MODEL = 'models.Model'
OBJ = '.objects'

class Exploder(object):

    def __init__(self, home=home, project=project, app=app,
                                        startline=startline, indent='    '):
        monolith = os.path.join(home, project, app, 'models.py')
        self.app = app
        self.startline = startline
        self.indent = indent

        self.modelspath = monolith.replace('.py', '')
        self.init = os.path.join(self.modelspath, '__init__.py')
        self.bak = monolith.replace('.py', '.bak')
        self.sans = monolith.replace('.py', '.sans')
        if not os.path.isfile(self.bak):
            os.rename(monolith, self.bak)
        if not os.path.isdir(self.modelspath):
            os.mkdir(self.modelspath)
        self.imports = dict()
        self.initlines = list()
        self.init__all = list()
        with open(self.bak, 'r') as self.fbak:
            self.topline = self.maketopline()
            self.fbak.seek(0)
            self.finit = open(self.init, 'w')
            self.finit.write(self.topline)
            with open(self.sans, 'w') as self.fsans:
                self.fillinit()
        self.fsrc = open(self.sans, 'r')
        self.thismodule = None

    def maketopline(self):
        """
        Because this is Django 1.4 and Python 2.7 we need the first line in
        every model file (which uses absolute import) to be from future import
        absolute
        """
        futur_ = 'from __future__ import'
        abs_imp = 'absolute_import'
        future = '%s %s' % (futur_, abs_imp)
        coding = '# -*- coding: utf-8 -*-'
        line1 = self.fbak.readline().strip()
        line2 = self.fbak.readline().strip()
        if 'coding:' in line1:
            coding = line1
        elif 'coding:' in line2:
            coding = line2
        if futur_ in line1 and not abs_imp in line1:
            future = '%s, %s' % (line1, abs_imp)
        return '%s\n%s\n\n' % (future, coding)

    def addimport(self, module, item):
        try:
            vals = self.imports[module]
        except KeyError:
            vals = ''
        if not item == 'self':
            if not item in vals:
                vals += ' %s' % item
        if vals:
            vals = vals.lstrip()
            self.imports[module] = vals

    def aggregatefroms(self, cleaner):
        cleanest = list()
        modules = list()
        ind = self.indent
        #cleaner is in the correct sorted sequence
        for item in cleaner:
            bits = item.split()
            if not bits[1] in modules:
                modules.append(bits[1])
                cleanest.append(item)
            else:
                idx = modules.index(bits[1])
                fromline = cleanest[idx].rstrip()
                chunks = fromline.split('\n')
                if len(chunks[-1]) + len(bits[-1]) > 76:
                    fromline = '%s, \\\n%s%s%s%s' % (fromline, ind, ind, ind, ind)
                    fromline = '%s%s\n' % (fromline,bits[-1])
                else:
                    fromline = '%s, %s\n' % (fromline, bits[-1])
                cleanest[idx] = fromline
        return cleanest

    def checkthisimport(self, item):
        for modulekey in self.imports:
            imports = self.imports[modulekey]
            imps = imports.split()
            for imp in imps:
                if imp == item:
                    return modulekey

    def closefiles(self):
        self.fsrc.close()
        self.finit.close()

    def fillinit(self):
        self.fbak.seek(0)
        while True:
            line = self.fbak.readline()
            if line == '':
                break
            module = ''
            item = ''
            if 'import' in line:
                line2 = ''
                line = line.rstrip()
                while line.endswith('\\'):
                    line = line.replace('\\', '')
                    line2 = self.fbak.readline()
                    line = '%s%s' % (line, line2.strip())
                line += '\n'
                bits = line.strip().split()
                if line.startswith('from'):
                    module = bits[1]
                    item = ' '.join(bits[3:])
                elif line.startswith('import'):
                    item = ' '.join(bits[1:])
                if item:
                    item = item.replace(',', '')
                    self.addimport(module, item)
                    line = 'skip'
            elif 'class' in line and MODEL in line:
                klass = line.split('(')[0].split()[-1]
                # will need to be imported so gets a leading dot
                module = '.%s' % klass.lower()
                self.addimport(module, klass)
                fromline = 'from %s import %s\n' % (module, klass)
                if not fromline in self.initlines:
                    self.initlines.append(fromline)
                if not klass in self.init__all:
                    self.init__all.append(klass)
            elif OBJ in line:
                item = line.split(OBJ)[0].split('=')[-1].split('(')[-1].split('.')[-1]
                item = self.seemsok(item, line)
                if item:
                    item = item.strip()
                    module = self.checkthisimport(item)
                    if not module is None:
                        self.addimport(module, item)
            if not line == 'skip' and not line is None:
                self.fsans.write(line)

    def opennewclass(self):
        if not self.thismodule is None:
            return open('%s.py' % os.path.join(self.modelspath, self.thismodule), 'w')

    def removethismodule(self, clean):
        # we don't want to import from the module we are in
        cleaner = list()
        for line in clean:
            bits = line.split()
            module = bits[-1].strip()
            if not module == module.upper():  # if not a conventional const
                if module.lower() == self.thismodule:
                    continue
            cleaner.append(line)
        return cleaner

    def seemsok(self, item, line):
        low = '><"_abcdefghijklmnopqrstuvwxyz'
        high = low.upper()
        bits = line.split(item)
        if bits[0]:
            prior = bits[0][-1]
            if prior in low or prior in high:
                return ''
            if bits[1]:
                post = bits[1][0]
                if post in low or post in high:
                    return ''
            return item

    def writemeta(self, classpy, module, meta=False):
        xtra = ''
        if meta:
            xtra = '\n'
            classpy.write('%sclass Meta:\n' % self.indent)
        classpy.write("%s%sapp_label = '%s'%s\n" % (self.indent, self.indent,
                                                  self.app, xtra))

    def writemodelfile(self, classpy=None):
        """
        called last thing before a new classpy is opened
        first close classpy coz it is in w mode then open it in r mode
        to pick up the items to import then close it and reopen in w mode
        to insert the froms then close it coz we are done.

        At this point we have all the imports in self.imports (dict) and
        all the lines for the __init__.py file in self.initlines (list) and
        all the classnames in self.init__all (list)

        scan classpy for:
            related models
            items matching the values in self.imports
        and
            insert imports at 'startline' in classpy after topline

        """
        if not classpy is None:
            classpy.close()
            pyfile = '%s.py' % os.path.join(self.modelspath, self.thismodule)
            classpy = open(pyfile, 'r')
            lines = classpy.readlines()
            lines.insert(2, '\n')
            classpy.close()
            froms = list()
            for line in lines:
                prefix = ''
                if 'ForeignKey' in line or 'OneToOneField' in line \
                                        or 'ManyToManyField' in line:
                    idx = lines.index(line)
                    third = ''
                    paren = False
                    comma = False
                    first, second = line.split('(', 1)
                    if not 'self' in second:    # do nothing if it is
                        if ',' in second:       # some options exist
                            second, third = second.split(',', 1)
                            third = ', %s' % third
                        if ')' in second:       # that's all in the line
                            paren = True        # so it can be put back
                            second = second.replace(')', '').strip()
                        if "'" in second:
                            second = second.replace("'", '').strip()
                        if '"' in second:
                            second = second.replace('"', '').strip()
                        relatedmodel = second   # totally naked
                        assert len(second.split()) == 1
                        module = self.checkthisimport(relatedmodel)
                        if not module is None:
                            if module.startswith('.'):
                                prefix = '#'
                                line = "%s('%s'%s" % (first, second, third)
                            else:
                                line = "%s(%s%s" % (first, second, third)
                            if paren:
                                line = '%s)\n' % line.rstrip()
                            if not line.endswith('\n'):
                                line = '%s\n' % line
                            if idx:
                                lines[idx] = line
                            if module:
                                impline = '%sfrom %s import %s\n' % (prefix, module,
                                                                     relatedmodel)
                            else:
                                impline = 'import %s\n' % model
                            if not impline in froms:
                                #print(impline)
                                froms.insert(0, impline)
                # now find all the other imported items
                chunk = line.replace('=', ' ')
                chunk = chunk.replace('[', ' ')
                chunk = chunk.replace('(', ' ')
                chunk = chunk.replace(')', ' ')
                chunk = chunk.replace('.', ' ')
                chunk = chunk.replace(']', ' ')
                chunk = chunk.replace(',', ' ')
                bits = chunk.split()
                for bit in bits:
                    if self.seemsok(bit, line):
                        module = self.checkthisimport(bit)
                        if not module is None:
                            if module == '':
                                impline = 'import %s\n' % bit
                            else:
                                impline = 'from %s import %s\n' % (module, bit)
                            if not impline in froms:
                                froms.insert(0, impline)

            clean = list()
            for item in froms:
                if not '__future__' in item:
                    if not item in clean:
                        clean.insert(0, item)
            cleaner = self.removethismodule(clean)
            del(clean)
            cleaner.sort()
            cleaner.reverse()
            if aggregate:
                cleanest = self.aggregatefroms(cleaner)
            else:
                cleanest = cleaner
            for item in cleanest:
                lines.insert(self.startline, item)
            classpy = open(pyfile, 'w')
            classpy.writelines(lines)
            classpy.close()

#########################################################################

if __name__ == '__main__':

    exp = Exploder(home, project, app, startline)

    meta = True         # otherwise write out a class Meta: line
    classpy = None      # the opened class py file in 'w' mode
    classname = None    # case sensitive derived from the class declaration
    scrap = True        # scraps (non-model classes) go into __init__.py
    init = True         # switch to start off with the __init__.py cycle

    exp.fsrc.seek(0)
    for line in exp.fsrc.readlines():
        if "def __unicode__(self):" in line and not meta:
            exp.writemeta(classpy, classname, True)
        if line[0:5] == 'class' and MODEL in line:
            # still on the old class at this point
            # patch in the froms at the top and close classpy
            exp.writemodelfile(classpy)
            # this is a new class so stop adding stuff to __init__.py
            scrap = False
            # start work on the new class just detected
            classname = line.split('(')[0].split()[1]
            exp.thismodule = classname.lower()
            classpy = exp.opennewclass()
            classpy.write(exp.topline)
            meta = False
        if scrap:
            if not 'import' in line:
                if init:
                    init = False
                    exp.initlines.append('\n\n')
                exp.initlines.append(line)
        else:
            # must be a line in a classpy file so classname must be set already
            if 'class Meta:' in line and not meta:
                meta = True
                classpy.write(line)
                line = ''
                exp.writemeta(classpy, classname)
            if line:
                classpy.write(line)
    # just to get the last one done
    exp.writemodelfile(classpy)
    exp.finit.writelines(exp.initlines)
    exp.finit.write('\n__all__ = %s\n' % exp.init__all)
    exp.closefiles()


import numpy as np

data = np.array([1,-2,3,-4,5])

bools = np.dot(data[0:len(data) - 1], data[1:len(data)])

array = []
array.append(bools)

result = []
zc = [0]
for i in array:
    if i <= 0:
        result.append(1)
    else:
        result.append(0)

    zc[0] = sum(result)

print(zc)


from __future__ import annotations
from typing import Optional
from sqlalchemy.orm import Session

from crud.base import CRUDBase
from models.annotations import Annotations
from schemas.annotations import AnnotationsCreate,AnnotationsUpdate

class CRUDAnnotations(CRUDBase[Annotations,AnnotationsCreate,AnnotationsUpdate]):
    def get_by_id(self, db: Session, *, id: str) -> Optional[Annotations]:
        return db.query(Annotations).filter(Annotations.id == id).first()

    def create(self, db: Session, *, obj_in: AnnotationsCreate) -> Annotations:
        obj = db.query(Annotations).order_by(Annotations.id.desc()).first()
        if obj:
            obj_in.id=obj.id+1
        else:
            obj_in.id=1

        db_obj = Annotations(
            id=obj_in.id,
            home=obj_in.home,
            room=obj_in.room,
            start=obj_in.start,
            end=obj_in.end,
            activity_type=obj_in.activity_type,
            status=obj_in.status
        )
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj

annotations = CRUDAnnotations(Annotations)


import discord
from discord.ext import commands
from decimal import *

from ..DB import db
from ..Class.embed_form import embed_factory as ef

class mock_trans(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    async def mock_buy(self, ctx, stock_name, stock_count):
        BUY_FEE = Decimal('0.001') # 0.5%

        user_id = ctx.author.id
        #입력 오류
        if stock_name is None:
            await ctx.send("거래할 주식을 입력해주세요.")
            return
        if not (stock_count.isdigit() or stock_count in ('최대', '풀', '올인','반') or stock_count[-1] in ('%', '퍼', '원')):
            await ctx.send("수량에 숫자를 입력해주세요.")
            return

        serch_stock = self.bot.get_cog('serch_stock')

        serch_result = await serch_stock.serch_stock_by_bot(ctx, stock_name)

        stock_code = serch_result.stock_code
        stock_name = serch_result.stock_name
        alert_info = serch_result.alert_info

        if stock_code is None:
            await ctx.send("올바르지 않는 주식명")
            return

        stock_price = db.KRXRealData().read_price(stock_code)
        stock_price_include_fee = stock_price * (1+BUY_FEE)

        if stock_price is None or alert_info == '매매정지':
            await ctx.send("거래 정지 종목입니다.")
            return

        # 계좌의 돈을 불러온다
        krw_account = db.AccountTable().read(user_id,"KRW")
        if krw_account is None:
            await ctx.send("지원금을 받아주세요.")
            return
        krw_money = int(krw_account[1])

        # stock_count 계산
        if stock_count.isdigit():
            stock_count = int(stock_count)
        elif stock_count in ('최대', '풀', '올인'):
            stock_count = int(krw_money/stock_price_include_fee)
        elif stock_count in ('반',):
            stock_count = int(krw_money/2/stock_price_include_fee)
        elif stock_count[-1] in ('%', '퍼', '원'):
            input_int = stock_count[:-1]
            if not input_int.isdigit():
                await ctx.send("수 입력 오류")
                return
            real_input_int = int(input_int)

            if stock_count[-1] in ('%', '퍼'):
                base_price = krw_money * real_input_int // 100
            elif stock_count[-1] == '원':
                base_price = real_input_int

            if base_price < stock_price:
                await ctx.send("돈 부족")
                return

            stock_count = int(base_price/stock_price_include_fee)

        total_stock_price = stock_price * stock_count
        total_stock_fee = int(total_stock_price * BUY_FEE)

        # 돈이 없으면 취소
        if krw_money < total_stock_price or stock_count == 0:
            await ctx.send("돈 없음")
            await ctx.send(f"최대 {int(krw_money/stock_price_include_fee)}주 가능")
            return

        # 돈이 있으면 계좌 돈 감소, 주식 갯수 증가
        trade_result = db.MockTransection().buy(user_id, stock_code, stock_count, total_stock_price, total_stock_fee)

        if trade_result:
            input_variable={"guild_id" : ctx.guild.id, "channel_id" : ctx.channel.id,
                            "author_id" : ctx.author.id, "stock_code" : stock_code,
                            "stock_value" : stock_price
                            }

            try:
                db.LogTable().insert_mock_log(mock_type="매수",stock_count=stock_count,**input_variable)
            except:
                print("로그 저장 에러")

            await ctx.send(embed=ef("mock_buy", ctx.author, stock_name, stock_count, stock_price, total_stock_price, total_stock_fee).get)
        else:
            await ctx.send('오류 : 거래실패')

    async def mock_sell(self, ctx, stock_name, stock_count):
        SELL_FEE = Decimal('0.001')

        user_id = ctx.author.id
        #입력 오류
        if stock_name is None:
            await ctx.send("거래할 주식을 입력해주세요.")
            return
        if not (stock_count.isdigit() or stock_count in ('최대', '풀', '올인', '반') or stock_count[-1] in ('%', '퍼', '원')):
            await ctx.send("수량에 숫자를 입력해주세요.")
            return

        serch_stock = self.bot.get_cog('serch_stock')
        serch_result = await serch_stock.serch_stock_by_bot(ctx, stock_name)

        stock_code = serch_result.stock_code
        stock_name = serch_result.stock_name
        alert_info = serch_result.alert_info

        if stock_code is None:
            await ctx.send("올바르지 않는 주식명")
            return

        stock_price = db.KRXRealData().read_price(stock_code)

        if stock_price is None or alert_info == '매매정지':
            await ctx.send("거래 정지 종목입니다.")
            return

        # 계좌에 주식이 있는지 확인
        stock_account = db.AccountTable().read(user_id, stock_code)
        if stock_account is None:
            await ctx.send("팔고자 하는 주식이 없습니다.")
            return

        balance = int(stock_account[0])

        # stock_count 계산
        if stock_count.isdigit():
            stock_count = int(stock_count)
        elif stock_count in ('최대', '풀', '올인'):
            stock_count = balance
        elif stock_count in ('반',):
            stock_count = balance//2
        elif stock_count[-1] in ('%', '퍼', '원'):
            input_int = stock_count[:-1]
            if not input_int.isdigit():
                await ctx.send("수 입력 오류")
                return
            real_input_int = int(input_int)

            if stock_count[-1] in ('%', '퍼'):
                stock_count = balance*real_input_int//100
            elif stock_count[-1] == '원':
                stock_count = real_input_int//stock_price

                if stock_count>balance:
                    await ctx.send("수량 부족")
                    return

        total_stock_price = stock_price * stock_count
        total_stock_fee = int(total_stock_price * SELL_FEE)

        sum_value = stock_account[1]
        sell_sum_value = sum_value*stock_count/balance
        profit = total_stock_price - sell_sum_value - total_stock_fee

        # 보유 주식이 팔려는 갯수보다 적으면 취소
        if balance < stock_count:
            await ctx.send("팔고자 하는 주식이 적습니다")
            await ctx.send(f"최대 {balance}주 가능")
            return

        # 갯수가 충분하면 주식 갯수 감소, 계좌 돈 증가
        trade_result = db.MockTransection().sell(user_id, stock_code, stock_count, total_stock_price, total_stock_fee)

        if trade_result:
            input_variable={"guild_id" : ctx.guild.id, "channel_id" : ctx.channel.id,
                            "author_id" : ctx.author.id, "stock_code" : stock_code,
                            "stock_value" : stock_price
                            }

            try:
                db.LogTable().insert_mock_log(mock_type="매도",stock_count=stock_count,**input_variable)
            except:
                print("로그 저장 에러")

            await ctx.send(embed=ef("mock_sell", ctx.author, stock_name, stock_count, stock_price, total_stock_price, total_stock_fee, profit).get)
        else:
            await ctx.send('오류 : 거래실패, 거래가 취소되었습니다.')

    async def mock_sell_all(self, ctx):
        serch_stock = self.bot.get_cog('serch_stock')
        warn_result = await serch_stock.warn_send(ctx, '전량매도')

        if warn_result:
            SELL_FEE = Decimal('0.001')
            user_id = ctx.author.id

            stock_account = db.AccountTable().read_only_tradealbe_stock(self, user_id)

            if stock_account is None:
                await ctx.send("팔고자 하는 주식이 없습니다.")
                return

            trade_list = ['주식명 0주 : 판매금액(이익금)']

            for idx in stock_account.index:
                stock_name = stock_account.iat[idx, 3]
                stock_code = stock_account.iat[idx, 0]
                stock_count = int(stock_account.iat[idx, 1])
                all_buy_price = stock_account.iat[idx, 2]
                all_present_price = stock_account.iat[idx, 4]
                total_stock_fee = int(all_present_price * SELL_FEE)

                profit = all_present_price - all_buy_price - total_stock_fee

                trade_result = db.MockTransection().sell(user_id, stock_code, stock_count, all_present_price, total_stock_fee)

                if trade_result:
                    trade_list.append(f'{stock_name} {stock_count}주 : {all_present_price}({int(profit)})')
                else:
                    trade_list.append(f'{stock_name} {stock_count}주 : 거래실패')

            await ctx.send(embed=ef("mock_sell_all", ctx.author, trade_list).get)

def setup(bot):
    bot.add_cog(mock_trans(bot))


import pickle
from skimage.transform import resize
import numpy as np
import cv2
from PIL import Image

import torch
from model import Net

PATH = "model.pth"

EMPTY = True
NOT_EMPTY = False

# MODEL = pickle.load(open("model.pickle", "rb"))

net_load = Net()
net_load.load_state_dict(torch.load(PATH))

trans = pickle.load(open('transform.pickle', 'rb'))

def empty_or_not(spot_bgr):

    img = Image.fromarray(spot_bgr)
    transformed_img = trans(img)

    tensor = torch.unsqueeze(transformed_img, dim=0)

    out = net_load(tensor)

    _, predicted = torch.max(out.data, 1)

    y_output = predicted.item()

    if y_output == 0:
        return EMPTY
    else:
        return NOT_EMPTY

def get_parking_spots_bboxes(connected_components):
    (totalLabels, label_ids, values, centroid) = connected_components

    slots = []
    coef = 1
    for i in range(1, totalLabels):

        # Now extract the coordinate points
        x1 = int(values[i, cv2.CC_STAT_LEFT] * coef)
        y1 = int(values[i, cv2.CC_STAT_TOP] * coef)
        w = int(values[i, cv2.CC_STAT_WIDTH] * coef)
        h = int(values[i, cv2.CC_STAT_HEIGHT] * coef)

        slots.append([x1, y1, w, h])

    return slots


import tensorflow_cloud as tfc

TF_GPU_IMAGE = "tensorflow/tensorflow:latest-gpu"

GCS_BUCKET = "dl-fp"

tfc.run(
    entry_point="code/main.py",
    entry_point_args=["WORD2VEC"],
    distribution_strategy='auto',
    requirements_txt='requirements.txt',
    docker_image_bucket_name=GCS_BUCKET,
    docker_base_image=TF_GPU_IMAGE,
    chief_config=tfc.COMMON_MACHINE_CONFIGS['K80_1X'],
    worker_config=tfc.COMMON_MACHINE_CONFIGS['K80_1X'],
    job_labels={'job': "my_job"}
)  # Runs your training on Google Cloud!


# coding: utf-8

### ---- THIS FILE WAS PRODUCED BY CONVERTING THE ORIGINAL GC-gna.ipynb NOTEBOOK TO PYTHON ----###
### ---- LINES THAT ADD STIMULATION AND PLOTS WERE COMMENTED OUT ---- ###

# In[1]:

from neuron import h,gui

import matplotlib.pyplot as plt
import numpy as np

# In[2]:

N_sections = 11
h.celsius=22
nlist=[]
gcci = [h.Section() for i in range(N_sections)]
nlist.append(gcci)
gccd = [h.Section() for i in range(N_sections)]
nlist.append(gccd)
gci = [h.Section() for i in range(N_sections)]
nlist.append(gci)
gcd = [h.Section() for i in range(N_sections)]
nlist.append(gcd)

# In[3]:

for i in range(N_sections-1):
    gcci[i+1].connect(gcci[i],1,0)
    gccd[i+1].connect(gccd[i],1,0)

for i in range(N_sections-1):
    gci[i+1].connect(gci[i],1,0)
for i in range(N_sections-1):
    gcd[i+1].connect(gcd[i],1,0)

# In[4]:

for i in nlist:
    i[0].diam=10
    i[0].L=10
    i[0].nseg=3

for i in range(1,N_sections):
    for j in nlist:
        j[i].nseg=3
        j[i].L=20
        j[i].Ra=100
    gcd[i].diam=2-(i-1)*0.088 #(2-1.2)/9
    gci[i].diam=2.7-(i-1)*0.166 #(2.7-1.2)/9

    gccd[i].diam=2-(i-1)*0.088 #(2-1.2)/9
    gcci[i].diam=2.7-(i-1)*0.166 #(2.7-1.2)/9

# In[5]:

for i in range(N_sections):
    for j in nlist:
        j[i].insert('pas')
        j[i].g_pas=0.0002
        j[i].insert('kfast')
        j[i].insert('nat')
        j[i].insert('nadp')
        j[i].TotalPump_nadp=0

gcd[0].gbar_nat=4.1
gcd[0].gbar_kfast=4.1/80

gcd[1].gbar_nat=4.1
gcd[1].gbar_kfast=4.1/80

gci[0].gbar_nat=2.0
gci[0].gbar_kfast=2.0/80

gci[1].gbar_nat=2.0
gci[1].gbar_kfast=2.0/80

gcina=[2,2]
gcdna=[4.1,4.1]

for i in range(2,N_sections):
    gci[i].gbar_nat=(gci[i-1].gbar_nat)+0.05*(gci[i-1].gbar_nat)
    gci[i].gbar_kfast=(gci[i-1].gbar_kfast)+0.05*(gci[i-1].gbar_kfast)
    gcina.append(round(gci[i].gbar_nat,5))

    gcd[i].gbar_nat=(gcd[i-1].gbar_nat)-0.12*(gcd[i-1].gbar_nat)
    gcd[i].gbar_kfast=(gcd[i-1].gbar_kfast)-0.12*(gcd[i-1].gbar_kfast)
    gcdna.append(round(gcd[i].gbar_nat,5))

avnared=2.2*((2.7+2.8+2.2+4.2)/4) #mM
avnablu=2.2*((6.5+6.3+7.2+11)/4) #mM

avnaredn=2.2*((2.7+2.8)/2) #mM
avnablun=2.2*((6.5+6.3+7.2)/3) #mM

# # In[6]:
#
#
# pulscd=h.Ipulse1(0.5,sec=gccd[0])
# pulscd.ton=5
# pulscd.toff=15
# pulscd.num=20
# pulscd.amp=1#na
#
# pulsci=h.Ipulse1(0.5,sec=gcci[0])
# pulsci.ton=5
# pulsci.toff=15
# pulsci.num=20
# pulsci.amp=1#na
#
# pulsd=h.Ipulse1(0.5,sec=gcd[0])
# pulsd.ton=5
# pulsd.toff=15
# pulsd.num=20
# pulsd.amp=1 #na
#
# pulsi=h.Ipulse1(0.5,sec=gci[0])
# pulsi.ton=5
# pulsi.toff=15
# pulsi.num=20
# pulsi.amp=1 #na
#
#
# # In[7]:
#
#
# time_h = h.Vector()
# time_h.record(h._ref_t)
#
# inareci=[h.Vector() for i in range(N_sections)]
# inarecd=[h.Vector() for i in range(N_sections)]
#
# vrec_0=h.Vector()
# vrec_1=h.Vector()
# vrec_2=h.Vector()
# vrec_3=h.Vector()
# vrec_4=h.Vector()
# vrec_5=h.Vector()
#
# vrec_p1=h.Vector()
# vrec_p2=h.Vector()
# vrec_p3=h.Vector()
#
# vrec_0.record(gcd[0](0.5)._ref_v)
# vrec_1.record(gci[0](0.5)._ref_v)
#
# vrec_p1.record(gccd[0](0.5)._ref_v)
#
# vrec_2.record(gcd[1](0.5)._ref_v)
# vrec_3.record(gci[1](0.5)._ref_v)
#
# vrec_p2.record(gccd[1](0.5)._ref_v)
#
# vrec_4.record(gcd[10](0.5)._ref_v)
# vrec_5.record(gci[10](0.5)._ref_v)
#
# vrec_p3.record(gccd[10](0.5)._ref_v)
#
# for i in range(N_sections):
#     inarecd[i].record(gcd[i](0.5)._ref_ina)
#     inareci[i].record(gci[i](0.5)._ref_ina)
#
#
# # In[8]:
#
#
# h.tstop =100
# h.run()
#
#
# # In[9]:
#
#
# plt.suptitle('Vm',fontsize=14)
#
# plt.subplot(321).set_title('decreasing pattern')
# plt.plot(time_h,vrec_0)
# plt.legend(['Soma'])
#
#
# plt.subplot(322).set_title('increasing pattern')
# plt.plot(time_h,vrec_1)
#
# plt.subplot(323)
# plt.plot(time_h,vrec_2)
# plt.legend(['Dend(0)'])
#
# plt.subplot(324)
# plt.plot(time_h,vrec_3)
#
# plt.subplot(325)
# plt.plot(time_h,vrec_4)
# plt.legend(['Dend(1)'])
#
# plt.subplot(326)
# plt.plot(time_h,vrec_5)
#
# plt.show()
#
#
# # In[10]:
#
#
# connai=[]
# for i in range(N_sections):
#    connai.append(round(gci[i](0.5).nai,3))
#
# connad=[]
# for i in range(N_sections):
#     connad.append(round(gcd[i](0.5).nai,3))
#
# connacd=[]
# for i in range(N_sections):
#     connacd.append(round(gccd[i](0.5).nai,3))
#
# connaci=[]
# for i in range(N_sections):
#     connaci.append(round(gcci[i](0.5).nai,3))
#
#
# # In[11]:
#
#
# plt.subplot(2,2,1).set_title('[Na] in decreasing density')
# plt.plot(connad,'b')
#
# plt.subplot(2,2,2).set_title('gnabar in decreasing pattern')
# plt.plot(gcdna,'b')
#
# plt.subplot(2,2,3).set_title('[Na] in increasing density')
# plt.plot(connai,'r')
#
# plt.subplot(2,2,4).set_title('gnabar in increasing pattern')
# plt.plot(gcina,'r')
#
# plt.show()
#
#
# # In[12]:
#
#
# for i in range(N_sections):
#     inareci[i]=np.asarray(inareci[i])
#     inarecd[i]=np.asarray(inarecd[i])
#
# Inabari=[]
# Inabard=[]
# for i in range(N_sections):
#     Inabarii=-1*round(np.mean(inareci[i]),3)
#     Inabari.append(Inabarii)
#     Inabardd=-1*round(np.mean(inarecd[i]),3)
#     Inabard.append(Inabardd)
#
# plt.subplot(211).set_title('Ina,Increasing, mA/cm2')
# plt.plot(Inabari,'r')
#
# plt.subplot(212).set_title('Ina,Decreasing, mA/cm2')
# plt.plot(Inabard,'b')
#
# plt.show()


#
#   This file is part of MiniFluxDiv.

#   MiniFluxDiv is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   any later version.

#   MiniFluxDiv is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with MiniFluxDiv. If not, see <http://www.gnu.org/licenses/>.
#

__author__ = 'edavis'

import io
import re

def isMatch(inStr, pattern):
    return re.search(pattern, inStr, re.I)

def grep(pattern, list, regex=False):
    matches = None

    # Check for negation...
    negate = False
    if pattern[0] == '!':
        pattern = pattern[1:]
        negate = True

    if regex:
        expr = re.compile(pattern, re.IGNORECASE)
        if negate:
            matches = [elem for elem in list if not expr.match(elem)]
        else:
            matches = [elem for elem in list if expr.match(elem)]
    else:
        if negate:
            matches = [elem for elem in list if pattern not in elem]
        else:
            matches = [elem for elem in list if pattern in elem]

    return matches

def fastJoin(list, delim=''):
    output = io.StringIO()

    size = len(list)
    if size > 0:
        i = 0
        output.write(str(list[i]))

        while i < size:
            output.write(delim)
            output.write(str(list[i]))
            i += 1

    contents = output.getvalue()
    output.close()

    return contents

def capFirst(str):
    return ("%s%s") % (str[0:1].upper(), str[1:])


# Licensed to the .NET Foundation under one or more agreements.
# The .NET Foundation licenses this file to you under the Apache 2.0 License.
# See the LICENSE file in the project root for more information.

'''
This is a thin wrapper designed to run all Python tests distributed with IronPython
which do not have external dependencies.

The following options are available:

  -M option (Extension mode)
    -M:0 : launch ip with ""
           this is the default choice if -M: is not specified
    -M:1 : launch ip with "-O -D -X:LightweightScopes -X:MaxRecursion 300"
    -M:2 : launch ip with "-O -D -X:SaveAssemblies"
    -M:D : launch ip with all supported modes (i.e., -M:0, -M:1, ...)
    -M:"-O -D -X:SaveAssemblies" (use DOUBLE QUOTE)

  -O option (to specify output detail)
    -O:min : try to keep the output in one screen
             '.' for pass, 'X' for fail (followed by test name)
    -O:med : show 'PASS' and 'FAIL' for each test
    -O:max : besides showing 'PASS' and 'FAIL' for each test,
             print the exception message at the end

  -T option (to specify time related options)
    -T:min :
    -T:med : this is default
    -T:max :

  -h or -? : to show this help message

Assumptions:
- we start out in the "Tests" directory
- all tests we wish to run are in "Tests"
- the tests are named using the pattern test_*.py
- this is run under IronPython
'''

from sys import argv
from sys import exit
from sys import executable
import sys

from os  import environ
from os  import listdir
from os  import getcwd
import os
from System import Threading
import System

#--GLOBALS---------------------------------------------------------------------

#Flags to be used to run tests
MODES_TO_RUN = []

#Supported test modes
M0 = ""
M1 = "-O -D -X:LightweightScopes -X:MaxRecursion 300"
M2 = "-O -D -X:SaveAssemblies -X:AssembliesDir %s" % environ["TMP"]

#Supported verbosity levels
OUTPUT_MIN = 0
OUTPUT_MED = 1
OUTPUT_MAX = 2

OUTPUT_LVL = OUTPUT_MED

#Supported time levels
TIME_MIN = 0
TIME_MED = 1
TIME_MAX = 2

TIME_LVL = TIME_MED

#list of slow tests that we disable unless -T:max is supplied
SLOW_LIST = [
            "test_numtypes.py",
            "test_fuzz_parser.py"
            ]

#tests we do not wish to run. These should be in the "Tests" directory
EXCLUDE_LIST = [
                "test_dllsite.py",    #disabled for 2.0 branch
                "test_builds.py"      #Silverlight-only
                ]

#List of extra tests in "Tests" which do not follow the "test_*.py" pattern.
#These WILL be run.
EXTRA_INCLUDE_LIST = []

#Debugging...
DEBUG = False
def debug(*args):
    if DEBUG:
        print(args[0], ":", args[1:])

EXCLUDE_LIST = [x.lower() for x in EXCLUDE_LIST]
SLOW_LIST = [x.lower() for x in SLOW_LIST]
EXTRA_INCLUDE_LIST = [x.lower() for x in EXTRA_INCLUDE_LIST]

OUTPUT_COUNT = 0

#------------------------------------------------------------------------------
#--Process sys.argv

#--HELP -h/-?
if '-h' in argv or '-H' in argv or '-?' in argv:
    print(__doc__)
    exit(0)

#--MODES
for temp in argv[1:]:
    #Check if it's user defined
    if temp=="-M:0" or temp=="-M:1" or temp=="-M:2":
        MODES_TO_RUN.append(eval("M" + temp[3:]))
    #All standard modes
    elif temp=="-M:D":
        MODES_TO_RUN.append(M0)
        MODES_TO_RUN.append(M1)
        MODES_TO_RUN.append(M2)
    #Custom modes
    elif temp.startswith("-M:"):
        MODES_TO_RUN += [temp[3:len(temp)]]
#throw away all -M: flags
argv = [x for x in argv if not x.startswith("-M:")]

#If nothing was specified, just use M0
if len(MODES_TO_RUN)==0: MODES_TO_RUN.append(M0)
debug("MODES_TO_RUN", MODES_TO_RUN)

#--OUTPUT LEVEL
for temp in argv[1:]:
    if temp.startswith("-O:"):
        OUTPUT_LVL = eval("OUTPUT_" + temp[3:].upper())
        #take the first instance of -O: only
        break
#throw away all -O: flags
argv = [x for x in argv if not x.startswith("-O:")]
debug("OUTPUT_LVL", OUTPUT_LVL)

#--TIME LEVEL
for temp in argv[1:]:
    if temp.startswith("-T:"):
        TIME_LVL = eval("TIME_" + temp[3:].upper())
        #take the first instance of -T: only
        break
#throw away all -T: flags
argv = [x for x in argv if not x.startswith("-T:")]
debug("TIME_LVL", TIME_LVL)

#get a list of all test_*.py files in the CWD
TEST_LIST = [ x.lower() for x in listdir(getcwd()) if x.startswith("test_") and x.endswith(".py") ]

#add the extra tests
EXTRA_INCLUDE_LIST = [ x for x in EXTRA_INCLUDE_LIST if not x in TEST_LIST ]
TEST_LIST = EXTRA_INCLUDE_LIST + TEST_LIST

#get rid of the skipped tests
TEST_LIST = [ x for x in TEST_LIST if not x in EXCLUDE_LIST ]

#get rid of the slow tests
if TIME_LVL!=TIME_MAX:
    TEST_LIST = [ x for x in TEST_LIST if not x in SLOW_LIST]

TEST_LIST.sort()
debug("TEST_LIST", TEST_LIST)

#List of tests that failed
FAILED_LIST = []

#--FUNCTIONS-------------------------------------------------------------------
def test_exit_code():
    '''
    Verify if we were to fail we would get a good exit code back.
    '''

    exitcode_py = 'exitcode.py'
    f = open(exitcode_py, "w")
    f.writelines(['import sys\n', 'sys.exit(99)\n'])
    f.close()

    process = System.Diagnostics.Process()
    process.StartInfo.FileName = executable
    process.StartInfo.Arguments = exitcode_py
    process.StartInfo.CreateNoWindow = True
    process.StartInfo.UseShellExecute = False
    process.Start()
    process.WaitForExit()

    if process.ExitCode != 99:
        print('SEVERE FAILURE: sys.exit test failed, cannot run tests!')
        System.Environment.Exit(1)

def multireader(*streams):
    """creates multiple threads to read std err/std out at the same time to avoid blocking"""
    class reader(object):
        def __init__(self, stream):
            self.stream = stream
        def __call__(self):
            self.text = self.stream.readlines()

    threads = []
    readers = []
    for stream in streams:
        curReader = reader(stream)
        thread = Threading.Thread(Threading.ThreadStart(curReader))
        readers.append(curReader)
        threads.append(thread)
        thread.Start()

    for thread in threads:
        thread.Join()

    return [curReader.text for curReader in readers]

def run_one_command(*args):
    """runs a single command, exiting if it doesn't return 0, redirecting std out"""
    cmd_line = '"' + executable + '" '.join(args)
    inp, out, err = os.popen3(cmd_line)
    print(cmd_line)
    output, err = multireader(out, err)
    res = out.close()
    if res:
        print('%d running %s failed' % (res, cmd_line))
        print('output was', output)
        print('err', err)
    return output, err, res

def runTestSlow(test_name, mode):
    '''
    Helper function runs a test as a separate process.
    '''
    #run the actual test
    output, errors, ec = run_one_command(mode, test_name)

    return ec, errors

def runTestFast(test_name):
    '''
    Helper function simply imports a test as a module.
    '''
    #backup sys.stderr/sys.stdout
    old_stderr = sys.stderr
    old_stdout = sys.stdout

    #temporary sys.stdout/sys.stderr
    f = open("temp.log", "w")

    #return values
    ec = 0
    errors = ""

    try:
        #take over sys.stdout/sys.stderr and import the test module
        sys.stdout = f
        sys.stderr = f
        __import__(test_name.split(".py")[0])
    except SystemExit:
        ec = int(str(sys.exc_info()[1]))
    except:
        ec = 1
    finally:
        sys.stderr = old_stderr
        sys.stdout = old_stdout
        f.close()

    if ec!=0:
        f = open("temp.log", "r")
        for line in f.readlines():
            errors = errors + line
        f.close()

    return (ec, errors)

def runTest(test_name, mode):
    '''
    Runs an individual IronPython test.
    '''
    global OUTPUT_COUNT
    OUTPUT_COUNT = OUTPUT_COUNT + 1

    if TIME_LVL==TIME_MIN:
        (ec, errors) = runTestFast(test_name)
    else:
        (ec, errors) = runTestSlow(test_name, mode)

    #Error handling
    if ec:
        if OUTPUT_LVL==OUTPUT_MIN:
            print("X" + test_name, end=' ')
        else:
            print("\t", test_name, "FAIL")
            if OUTPUT_LVL==OUTPUT_MAX:
                print(errors, file=sys.stderr)
                print()
        FAILED_LIST.append(test_name + "; Exit Code=" + str(ec))
    else:
        if OUTPUT_LVL==OUTPUT_MIN:
            print(".", end=' ')
        else:
            print("\t", test_name, "PASS")

    if OUTPUT_LVL==OUTPUT_MIN and OUTPUT_COUNT%25==0:
        print()

#--MAIN------------------------------------------------------------------------

#Sanity check.  If sys.exit fails to work properly, there's little point in
#running all the tests
test_exit_code()

#Using each set of flags supplied to ipy.exe...
for mode in MODES_TO_RUN:
    print("-------------------------------------------------------------------")
    print("RUNNING IRONPYTHON TESTS USING THESE FLAGS:", mode)

    #...run all tests.
    for test_name in TEST_LIST:
        runTest(test_name, mode)
    print()

print("-------------------------------------------------------------------")
print("SUMMARY")
print()

if len(EXCLUDE_LIST)!=0:
    print("The following tests were excluded due to bugs:")
    for test_name in EXCLUDE_LIST: print("\t" + test_name)
    print()

if len(SLOW_LIST)!=0 and TIME_LVL!=TIME_MAX:
    print("The following tests were excluded due to slow execution time:")
    for test_name in SLOW_LIST: print("\t" + test_name)
    print()

if  len(FAILED_LIST)==0:
    print("Everything passed!")
    exit(0)
else:
    print("The following tests failed:")
    for test_name in FAILED_LIST: print("\t" + test_name)
    exit(1)


import svgwrite
class drawSVG:
    svg = {
        'text':'fEVR',
        'stroke':'none',
        'insert':(0,20),
        'fill':'#000000',
        'font':{
            'family':'Arial',
            'size':'20px',
            'weight':'bold'
            }
    }
    def toString(svg=svg):
        dwg = svgwrite.Drawing('test2.svg', profile='tiny')
        dwg.add(dwg.text(svg['text'],
                        insert=svg['insert'],
                        stroke=svg['stroke'],
                        fill=svg['fill'],
                        font_size=svg['font']['size'],
                        font_weight=svg['font']['weight'],
                        font_family=svg['font']['family'])
                )
        return dwg.tostring()


import json
import re
import requests
import argparse

var_re = re.compile('var (.+?) = (.+?);')

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('file', help='address file; one address per line')
    ap.add_argument('--coin', required=True, help='e.g. XPM')
    ap.add_argument('--ignore-no-tx', action='store_true')
    args = ap.parse_args()
    for line in open(args.file):
        line = line.strip()
        r = requests.get('https://bchain.info/%s/addr/%s' % (args.coin, line))
        if r.status_code == 404:
            continue
        vs = {}
        for m in var_re.finditer(r.text):
            key, value = m.groups()
            if key == 'startTime':
                continue
            try:
                value = json.loads(value.replace('\'', '"'))
            except json.JSONDecodeError:
                pass
            vs[key] = value
        if args.ignore_no_tx and vs['total_tx'] == 0:
            continue
        print(vs)

if __name__ == '__main__':
    main()


def fibonacci(n):
    a = 0
    b = 1

    if n < 0:
        return "Invalid Input"
    elif n == 0:
        return a
    elif n == 1:
        return b
    else:
        for i in range(2, n+1):
            # c = a + b
            # a = b
            # b = c
            a, b = b, a+b
        return b

def rec_fibonacci(n):
    if (n < 0):
        return  "Invalid Input"
    elif n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        return rec_fibonacci(n-1) + rec_fibonacci(n-2)

print(fibonacci(2))

for i in range(0, 11):
    print(fibonacci(i), end= " ")

print()

for i in range(0, 11):
    print(rec_fibonacci(i), end=" ")


from http import HTTPStatus
from logging import Logger

from flask.json import jsonify
from flask.wrappers import Request, Response

from pbench.server import PbenchServerConfig
from pbench.server.api.resources import (
    API_AUTHORIZATION,
    API_METHOD,
    API_OPERATION,
    APIAbort,
    ApiBase,
    ApiParams,
    ApiSchema,
    Parameter,
    ParamType,
    Schema,
)
from pbench.server.database.models.server_config import (
    ServerConfig,
    ServerConfigBadValue,
    ServerConfigError,
)

class ServerConfiguration(ApiBase):
    """
    API class to retrieve and mutate server configuration settings.
    """

    def __init__(self, config: PbenchServerConfig, logger: Logger):
        super().__init__(
            config,
            logger,
            ApiSchema(
                API_METHOD.PUT,
                API_OPERATION.UPDATE,
                uri_schema=Schema(
                    Parameter("key", ParamType.KEYWORD, keywords=ServerConfig.KEYS)
                ),
                # We aspire to be flexible about how a config option is
                # specified on a PUT. The value of a single config option can
                # be set using the "value" query parameter or the "value" JSON
                # body parameter. You can also specify one config option or
                # multiple config options by omitting the key name from the URI
                # and specifying the names and values in a JSON request body:
                #
                #   PUT /server/configuration/dataset-lifetime?value=2y
                #   PUT /server/configuration/dataset-lifetime
                #       {"value": "2y"}
                #   PUT /server/configuration
                #       {"dataset-lifetime": "2y"}
                query_schema=Schema(Parameter("value", ParamType.STRING)),
                body_schema=Schema(
                    Parameter("value", ParamType.JSON),
                ),
                authorization=API_AUTHORIZATION.ADMIN,
            ),
            ApiSchema(
                API_METHOD.GET,
                API_OPERATION.READ,
                uri_schema=Schema(
                    Parameter("key", ParamType.KEYWORD, keywords=ServerConfig.KEYS)
                ),
                authorization=API_AUTHORIZATION.NONE,
            ),
            always_enabled=True,
        )

    def _get(self, params: ApiParams, request: Request) -> Response:
        """
        Get the values of server configuration parameters.

        GET /api/v1/server/configuration/{key}
            return the value of a single configuration parameter

        or

        GET /api/v1/server/configuration
            return all configuration parameters

        Args:
            params: API parameters
            request: The original Request object containing query parameters

        Returns:
            HTTP Response object
        """

        key = params.uri.get("key")
        try:
            if key:
                s = ServerConfig.get(key)
                return jsonify({key: s.value if s else None})
            else:
                return jsonify(ServerConfig.get_all())
        except ServerConfigError as e:
            raise APIAbort(HTTPStatus.INTERNAL_SERVER_ERROR, str(e)) from e

    def _put_key(self, params: ApiParams) -> Response:
        """
        Implement the PUT operation when a system configuration setting key is
        specified on the URI as /system/configuration/{key}.

        A single system config setting is set by naming the config key in the
        URI and specifying a value using either the "value" query parameter or
        a "value" key in a JSON request body.

        We'll complain about JSON request body parameters that are "shadowed"
        by the "value" query parameter and might represent client confusion.
        We won't complain about unnecessary JSON request body keys if we find
        the "value" in the request body as those would normally have been
        ignored by schema validation.

        Args:
            params: API parameters
            request: The original Request object containing query parameters

        Returns:
            HTTP Response object
        """

        try:
            key = params.uri["key"]
        except KeyError:
            # This "isn't possible" given the Flask mapping rules, but try
            # to report it gracefully instead of letting the KeyError fly.
            raise APIAbort(
                HTTPStatus.INTERNAL_SERVER_ERROR,
                f"Found URI parameters {sorted(params.uri)} not including 'key'",
            )

        # If we have a key in the URL, then we need a "value" for it, which
        # we can take either from a query parameter or from the JSON
        # request payload.
        value = params.query.get("value")
        if value:
            # If we got the value from the query parameter, complain about
            # any JSON request body keys
            if params.body:
                raise APIAbort(
                    HTTPStatus.BAD_REQUEST,
                    "Redundant parameters specified in the JSON request body: "
                    f"{sorted(params.body.keys())!r}",
                )
        else:
            value = params.body.get("value")
            if not value:
                raise APIAbort(
                    HTTPStatus.BAD_REQUEST,
                    f"No value found for key system configuration key {key!r}",
                )

        try:
            ServerConfig.set(key=key, value=value)
        except ServerConfigBadValue as e:
            raise APIAbort(HTTPStatus.BAD_REQUEST, str(e)) from e
        except ServerConfigError as e:
            raise APIAbort(HTTPStatus.INTERNAL_SERVER_ERROR, str(e)) from e
        return jsonify({key: value})

    def _put_body(self, params: ApiParams) -> Response:
        """
        Allow setting the value of multiple system configuration settings with
        a single PUT by specifying a JSON request body with key/value pairs.

        Args:
            params: API parameters
            request: The original Request object containing query parameters

        Returns:
            HTTP Response object
        """
        badkeys = []
        for k, v in params.body.items():
            if k not in ServerConfig.KEYS:
                badkeys.append(k)

        if badkeys:
            raise APIAbort(
                HTTPStatus.BAD_REQUEST,
                f"Unrecognized configuration parameters {sorted(badkeys)!r} specified: valid parameters are {sorted(ServerConfig.KEYS)!r}",
            )

        failures = []
        response = {}
        fail_status = HTTPStatus.BAD_REQUEST
        for k, v in params.body.items():
            try:
                c = ServerConfig.set(key=k, value=v)
                response[c.key] = c.value
            except ServerConfigBadValue as e:
                failures.append(str(e))
            except ServerConfigError as e:
                fail_status = HTTPStatus.INTERNAL_SERVER_ERROR
                self.logger.warning(str(e))
                failures.append(str(e))
        if failures:
            raise APIAbort(fail_status, message=", ".join(failures))
        return jsonify(response)

    def _put(self, params: ApiParams, _) -> Response:
        """
        Set or modify the values of server configuration keys.

        PUT /api/v1/server/configuration
        {
            "dataset-lifetime": 10,
            "server-state": "running"
        }

        PUT /api/v1/server/configuration/dataset-lifetime?value=10

        PUT /api/v1/server/configuration/dataset-lifetime
        {
            "value": "10"
        }

        Args:
            params: API parameters
            request: The original Request object containing query parameters

        Returns:
            HTTP Response object
        """

        if params.uri:
            return self._put_key(params)
        else:
            return self._put_body(params)


import os
import shutil
from tempfile import TemporaryDirectory

import pandas as pd
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry

from bs4 import BeautifulSoup
from constants import (BACKOFF_FACTOR, BASE_URL, SEC_CIK_TXT_URL,
                       STATUS_FORCELIST, TICKER_CIK_CSV_FPATH, TOTAL_RETRIES)
from excel_parsing_utils import (clean_excel,
                                 download_years_in_ticker_folder_from_s3,
                                 filter_s3_urls_to_send,
                                 get_existing_merged_fpaths,
                                 get_existing_years,
                                 get_fpaths_from_local_ticker,
                                 merge_excel_files_across_years,
                                 parse_inputs, upload_files_to_s3)
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from sec_downloader import (SECDownloader, download,
                            update_ticker_cik_df, http_download)

app = FastAPI()

app.add_middleware(CORSMiddleware,
                   allow_origins=["*"], allow_credentials=True,
                   allow_methods=["*"], allow_headers=["*"])

sec_downloader = SECDownloader()

@app.get("/")
def home():
    return {"message":"Health Check Passed!"}

@app.get("/list_sec_filing_10k/")
async def get_list_sec_tickers(ticker):

    cik = sec_downloader.get_ticker_cik(ticker)

    params = {"action": "getcompany", "owner": "exclude",
              "output": "html", "CIK": cik, "type": "10-K"}

    data = http_download(BASE_URL, params)

    soup = BeautifulSoup(data, features="lxml")
    tables = soup.find_all("td")

    tables_10k = [table.text for table in tables if table.text == "10-K"]
    if tables_10k:
        is_ticker_filing_10k = True
    else:
        is_ticker_filing_10k = False

    return {"is_ticker_filing_10k": is_ticker_filing_10k}

@app.get("/list_sec/")
async def get_list_sec_tickers():

    update_ticker_cik_df()
    df_tickers = pd.read_csv(TICKER_CIK_CSV_FPATH)

    list_tickers = list(df_tickers["ticker"].dropna().values)

    return {"tickers": list_tickers}

@app.get("/params/")
async def download_10k(ticker, years, _10k, Proxy, Balance, Income, Cash):

    with TemporaryDirectory() as dirpath:
        s3_urls_to_send_to_user, _ = get_s3_urls_to_send_to_user(
            ticker, years, _10k, Proxy, Balance, Income, Cash, dirpath)

        return {"s3_urls": s3_urls_to_send_to_user}

@app.get("/params_web/")
async def download_10k_web(ticker, years, _10k, Proxy, Balance, Income, Cash):

    with TemporaryDirectory() as dirpath:
        _, ticker_folder = get_s3_urls_to_send_to_user(
            ticker, years, _10k, Proxy, Balance, Income, Cash, dirpath)

        shutil.make_archive(ticker, "zip", ticker_folder)
        response = FileResponse(path=ticker + ".zip",
                                filename=ticker + ".zip")
        return response

def get_s3_urls_to_send_to_user(ticker, years, _10k, Proxy,
                                Balance, Income, Cash, dirpath):

    raw_files_to_send, merged_files_to_send, years = parse_inputs(
        _10k, Proxy, Balance, Income, Cash, years)

    cik = sec_downloader.get_ticker_cik(ticker)

    ticker_folder = os.path.join(dirpath, ticker)
    os.makedirs(ticker_folder)

    existing_s3_urls = download_years_in_ticker_folder_from_s3(
        ticker,  ticker_folder, years)
    created_fpath = create_missing_files(ticker, ticker_folder, cik, years)
    s3_urls = upload_files_to_s3(created_fpath, existing_s3_urls,
                                 ticker, ticker_folder)

    s3_urls_to_send_to_user = filter_s3_urls_to_send(
        s3_urls, raw_files_to_send, merged_files_to_send)

    return s3_urls_to_send_to_user, ticker_folder

def create_missing_files(ticker, ticker_folder, cik, years):

    existing_years = get_existing_years(ticker_folder)
    missing_years = [year for year in years if year not in existing_years]

    if missing_years:
        excel_fpaths_to_clean, created_years = download(
            ticker, cik, missing_years, ticker_folder)
        for excel_fpath in excel_fpaths_to_clean:
            clean_excel(excel_fpath)
    else:
        created_years = []

    local_years = existing_years + created_years

    existing_merged_fpaths = get_existing_merged_fpaths(
        ticker, ticker_folder, local_years)
    if len(existing_merged_fpaths) == 3:
        merged_fpaths = existing_merged_fpaths
    else:
        merged_fpaths = merge_excel_files_across_years(ticker, ticker_folder, local_years)

    raw_fpaths = get_fpaths_from_local_ticker(ticker_folder, local_years)
    created_fpath = raw_fpaths + merged_fpaths

    return created_fpath


"""Sphinx extension for SCXML visualization with Graphviz"""

from pathlib import Path

import docutils.parsers.rst
import docutils.statemachine

from hat import stc

def setup(app):
    app.add_directive('scxml', ScxmlDirective)

class ScxmlDirective(docutils.parsers.rst.Directive):

    required_arguments = 1

    def run(self):
        env = self.state.document.settings.env
        source = self.state_machine.input_lines.source(
            self.lineno - self.state_machine.input_offset - 1)

        path = Path(env.relfn2path(self.arguments[0])[1])
        states = stc.parse_scxml(path)
        dot = stc.create_dot_graph(states)
        text = ('.. graphviz::\n\n' +
                '\n'.join('   ' + i for i in dot.split('\n')))

        lines = docutils.statemachine.string2lines(text)
        self.state_machine.insert_input(lines, source)
        return []


# Author : Kevin Lee
# assignment 3
# Target file : 2008Male00006.txt
# /Users/taesuplee/onepur/class/ABE651/hw/assignment-03

# open file as directed from the book
fin = open( "2008Male00006.txt" , "r" )
header = fin.readline().split( "," )

fileline = fin.readlines()
status = fileline[-1]
fileline = fileline[:-1]
fin.close()

# create data list
data = [ 0 ] * (len( fileline ))
#yes
line: int
for line in range( len( fileline[ 1:15 ] ) ):
    data[ line ] = fileline[ line ].split( "," )
    data[ line ][ 0 ] = int( data[ line ][ 0 ] )
    data[ line ][ 3 ] = int( data[ line ][ 3 ] )
    data[ line ][ 4:6 ] = map( float , data[ line ][ 4:6 ] )
    data[ line ][ 8:15 ] = map( float , data[ line ][ 8:15 ] )
# print(data)
# creating dictionary empty
dic_fin = dict()

data.pop( -1 )
dic_fin = {header[ i ]: [ row[ i ] for row in data ] for i in range( len( header ) )}
import math
import numpy as np

def mean(g):
    mean = np.sum( g ) / len( g )
    return mean

def sum(h):
    sum = np.cumsum( h )
    return ( sum )

def distance(X , Y):
    dist = [0]
    for i in range( len( X ) - 1 ):
        dist.append( np.sqrt( (X[ i ] - X[ i+1 ]) ** 2 + (Y[ i ] - Y[ i+1 ]) ** 2 ) )

    dist = sum(dist)
    return dist

info = fileline[-1].strip().split(",")
dic_fin.update( {'Distance': distance( dic_fin[ ' X' ] , dic_fin[ ' Y' ] )} )
coon_dis = dic_fin['Distance'][-1]
mean_energy=mean( dic_fin[ 'Energy Level' ] )
mean_x =mean( dic_fin[ ' X' ])
mean_y = mean( dic_fin[ ' Y' ] )
fout = open('Georges_life.txt', 'w')
print(dic_fin)
fout.write ('Raccoon name: George \n' )             # Writing header
fout.write ('Average location: X %f, Y %f \n' %(mean_x , mean_y))
fout.write ('Distance traveled: %.2f \n' %coon_dis)
fout.write ('Average energy level: %.2f  \n' %mean_energy)
fout.write ('Raccoon end state: %s \n\n' %status)

# Writing select content
header = ['Date', 'X', 'Y', 'Asleep Flag', 'Behavior Mode', 'Distance Traveled']
fout.write ('%s \t %s \t %s \t %s \t %s \t %s \n'%(header[0], header[1], header[2], header[3], header[4], header[5]))

for i in range(len(dic_fin['Year'])):
    fout.write ('%s \t %f \t %f \t %s \t %s \t %.2f \n'%(dic_fin['Day'][i],dic_fin[' X'][i],dic_fin[' Y'][i],dic_fin[' Asleep'][i],dic_fin['Behavior Mode'][i],dic_fin['Distance'][i]))

fout.close()


import numpy as np
from routines.base_routine import BaseRoutine
from maneuvers.front_flip_maneuver import FrontFlip
from utils.physics_data_object import PDO
from utils.simple_drive import drive
from rlbot.utils.structures.game_data_struct import GameTickPacket
from rlbot.utils.structures.bot_input_struct import PlayerInput
import utils.car as car_module
import utils.game_data as game_data

class ATBA(BaseRoutine):
    def __init__(self, car: car_module.Car, gd: game_data.GameData) -> None:
        super().__init__(car, gd)

    def update(self) -> PlayerInput:
        if self.maneuver and not self.maneuver.finished:
            return self.maneuver.update()
        target = PDO(
            np.array(
                [
                    self.gd.packet.game_ball.physics.location.x,
                    self.gd.packet.game_ball.physics.location.y,
                    self.gd.packet.game_ball.physics.location.z,
                ]
            )
        )
        controls = drive(target, self.car)
        if not self.car.super_sonic and self.car.on_surface and abs(controls.steer) < 0.1:

            if self.car.boost_level > 0:
                controls.boost = True
            elif self.car.current_speed > 1000:
                self.maneuver = FrontFlip(self.car, self.gd)
        return controls