def crear_lista_una_dim():
    parar = False
    lista = []
    while not parar:
        element = input("Elemento (-1 para salir): ")
        if not element == "-1":
            lista.append(element)
        else:
            parar = True
    return lista

def crear_lista_varias_dim(dim):
    lista = []
    if dim == 1:
        return crear_lista_una_dim()
    else:
        parar = False
        while not parar:
            s = input("Crear elemento para dimensión "+ str(dim) +"(s ó n): ")
            if s == "s":
                lis = crear_lista_varias_dim(dim-1)
                lista.append(lis)
            else:
                parar = True
        return lista

def borrar_elemento(element, lista, dim):
    if dim == 1:
        while element in lista:
            lista.remove(element)
    else:
        for sublist in lista:
            borrar_elemento(element, sublist, dim-1)

def contar_elemento(element, lista, dim):
    contador = 0
    if dim == 1:
        return lista.count(element)
    else:
        for sublist in lista:
            contador += contar_elemento(element, sublist, dim-1)
        return contador

dimensiones = int(input("Introduzca el número de dimensiones: "))
if dimensiones < 1:
    print("Error. Número de dimensiones debe ser > 1")
else:
    lista = crear_lista_varias_dim(dimensiones)
    print(lista)
    element = input("Introduzca el elemento a borrar: ")
    borrar_elemento(element, lista, dimensiones)
    print(lista)
    element = input("Introduzca el elemento a contar: ")
    print(contar_elemento(element, lista, dimensiones))


#This script was used to analyze the data in Figure 2c.
#It reads in the data from the high throughput B->A pegRNA screen, then obtains counts of each insertion sequence at the genomic target site.
#Toward obtaining enrichment scores, we used two different scripts, mnp_insertion_grab.py and mnp_pivot.py, on HTS data for the raw hp-miniprep pool. This generated the data needed to make PER17_hpm_reads.txt (an input file below; lists each pegRNA in the hp-miniprep pool and the corresponding number of counts in the miniprep)
#Counts of each insertion sequence in the genome are tabulated alongside counts of the corresponding pegRNA in the hp-miniprep pool.  The resulting table enabled calculation of enrichment scores using equation (1) in the main text.

import sys
import os
import re
import numpy as np
import collections
from collections import defaultdict
import os.path
import pandas as pd
import Bio
from Bio.Seq import Seq

### USER INPUTS: ###

ins_location = 127                 #how far from the 5' end of the read is the 1st nt of the insertion?
upstream_seq = 'CATCA'             #what's the sequence immediately upstream of the prime editing target site?
min_distance1 = 7                  #what's the minimum allowable Hamming distance between a real insertion sequence and the site3 sequence?
min_distance2 = 7                  #what's the minimum allowable Hamming distance between a real insertion seequence and the 6xHis sequence (site3 and 6xHis sequences are both present in unedited cells because our starting cell line isn't homozygous for the 6xHis insertion)?
n_top_hits = 500000                #how many top hits (insertion seqs) do you want to report at the end?
lines_iterator = 10000000          #after how many lines should the memory be purged (to avoid memory errors while running the script)?

### DEFINING FUNCTIONS ###

def calc_H_dist(seq1,seq2): #calculates Hamming distance between two sequences
    distance = 0
    for a,b in zip(seq1,seq2):
        if a != b:
            distance += 1
    return distance

def check_distances (dist1,min_dist1,dist2,min_dist2,ins,hpm_dict): #compares the Hamming distances to their allowed values and prepares to make a dataframe of insertions
    list_for_dataframe = ['Hamming D too low', 1, 0, 0, 'N/A'] #reports to the dataframe if the insertion doesn't pass this filter
    if (dist1>=min_dist1) and (dist2>=min_dist2):
        list_for_df = []
        number = 1 #counter for n insertions of each sequence
        if ins in hpm_dict.keys(): #checks if the insertion sequence is in the hpm dictionary so we can calculate the enrichment scores
            hpm_counts = hpm_dict[ins]
        else:
            hpm_counts = 1
        list_for_dataframe = [insertion, number, distance1, distance2, hpm_counts]
    return(list_for_dataframe)

### GRABBING INSERTION SEQUENCES ###

site3 = 'CGTGCTCAGTCTGGGCCCCA' #sequence expected for unedited loci with wt site3
his6 = 'ATGATGGTGATGATGGCTTG' #sequence expected for unedited loci with 6xHis insertion only (no B->A edit)

ins_columns = ['ins seq', 'number', 'site3_HD', 'his6_HD', 'hpm_counts']  #creating a dataframe that will hold all the insertions
ins_df = pd.DataFrame(columns = ins_columns)

dna_seqs = [] #creating a list to hold all the DNA sequences (full reads)
ins_seqs = [] #creating a list to hold the 20-bp "insertion" sequences, including wt site3 and 1533 sequences
ins_for_df = [] #creating a list that will be used to make a dataframe to count hits

hpm_file = open("PER17_hpm_reads.txt") #input file name here (info about each pegRNA in the hp-miniprep pool and n reads from NGS on the miniprep pool)

hpm_dict = {} #making a dictionary where keys = hp-miniprep insertion sequences and values = number of reads in the hp-miniprep pool
for line in hpm_file:
    stripped_hpm_info = line.strip('\n').split('\t')
    hpm_upper = stripped_hpm_info[0].upper() #grabbing the 20-bp variable sequence from the pegRNA plasmid
    if hpm_upper not in hpm_dict:
        hpm_dict[hpm_upper] = stripped_hpm_info[1]
    else:
        print('Error: duplicate hpm insertion sequences are present in the hpm file')

hpm_file.close()

with open("PER17_1_CKDL200162679-1a-D702-AK1681_HCJLGCCX2_L1_2.fq",'r') as sample_file: #input HTS data fastq file here
    counter = 0 #will keep track of total n reads
    L = -1  #will keep track of which lines in the fastq are DNA seqs and will tell the program when to purge the memory
    for line in sample_file:
        counter += 1
        L += 1
        if L%lines_iterator != (lines_iterator - 1): #the loop will start over after a user-defined n reads, to avoid memory errors
            if L%4 == 1:
                dna_seqs.append(line) #needs to cut off the line return at the end of the line

        else: #once the counter gets up to lines_iterator, tabulate the insertions, purge the memory, and restart the counter

            print('TOTAL n READS PARSED: ' + str(counter/4))
            print('dna seqs: ' + str(len(dna_seqs)))
            print('ins seqs: ' + str(len(ins_seqs)))
            print('ins_for_df: ' + str(len(ins_for_df)))

            nts_upstream = len(upstream_seq)
            for seq in dna_seqs:
                align_upstream = ins_location - nts_upstream - 1
                align_downstream = ins_location - 1

                if seq[align_upstream:align_downstream] == upstream_seq: #checks for the expected sequence upstream of the target site
                    insertion = seq[ins_location-1:ins_location+19] #grabs the 20-bp insertion

                    distance1 = calc_H_dist(insertion,site3) #compares the 20-bp insertion to site3 seq and 6xHis seq
                    distance2 = calc_H_dist(insertion,his6)
                    list_for_df = check_distances (distance1,min_distance1,distance2,min_distance2,insertion,hpm_dict)
                    ins_for_df.append(list_for_df)

                elif seq[align_upstream + 1:align_downstream + 1] == upstream_seq: #adjusts target site position for reads that had a longer barcode on the illumina primer
                    insertion = seq[ins_location:ins_location+20]

                    distance1 = calc_H_dist(insertion,site3) #compares the 20-bp insertion to site3 seq and his6 seq
                    distance2 = calc_H_dist(insertion,his6)
                    list_for_df = check_distances (distance1,min_distance1,distance2,min_distance2,insertion,hpm_dict)
                    ins_for_df.append(list_for_df)

                else:
                    continue

            sub_ins_df = pd.DataFrame(ins_for_df, columns = ins_columns) #makes a dataframe that will be purged repeatedly
            combined_df = pd.concat([ins_df, sub_ins_df]) #adds the dataframe that is about to be purged to the master dataframe
            counts_ins_df = combined_df.groupby(['ins seq','site3_HD','his6_HD','hpm_counts'], as_index=False)['number'].sum() #adds together n each insertion in the master dataframe, so it takes up less memory

            dna_seqs = [] #purging lists to prevent memory issues
            ins_seqs = []
            ins_for_df = []
            L = L%4 #restarts the iterator (to keep track of when memory should be purged)
            ins_df = counts_ins_df #updates the overall dataframe, so it holds the collapsed data set (identical insertions merged)

#this adds the "leftover" reads to the master dataframe once the memory purge iterator has gotten to the end of the input file
nts_upstream = len(upstream_seq)
for seq in dna_seqs:
    align_upstream = ins_location - nts_upstream - 1
    align_downstream = ins_location - 1

    if seq[align_upstream:align_downstream] == upstream_seq: #checks for the expected sequence upstream of the target
        insertion = seq[ins_location-1:ins_location+19] #grabs the 20-bp insertion

        distance1 = calc_H_dist(insertion,site3) #compares the 20-bp insertion to site3 seq and his6 seq
        distance2 = calc_H_dist(insertion,his6)
        list_for_df = check_distances (distance1,min_distance1,distance2,min_distance2,insertion,hpm_dict)
        ins_for_df.append(list_for_df)

    elif seq[align_upstream + 1:align_downstream + 1] == upstream_seq: #adjusts target site position for reads that had a longer barcode on the illumina primer
        insertion = seq[ins_location:ins_location+20]

        distance1 = calc_H_dist(insertion,site3) #compares the 20-bp insertion to site3 seq and his6 seq
        distance2 = calc_H_dist(insertion,his6)
        list_for_df = check_distances (distance1,min_distance1,distance2,min_distance2,insertion,hpm_dict)
        ins_for_df.append(list_for_df)

    else:
        continue

sub_ins_df = pd.DataFrame(ins_for_df, columns = ins_columns) #makes a dataframe with the "leftover" data
combined_df = pd.concat([ins_df, sub_ins_df]) #adds the new dataframe to the master dataframe
counts_ins_df = combined_df.groupby(['ins seq','site3_HD','his6_HD','hpm_counts'], as_index=False)['number'].sum() #adds together n each insertion in the master dataframe

sorted_df = counts_ins_df.sort_values(by=['number','his6_HD'],ascending=[False,False])
total_ins = sorted_df['number'].sum() #adds up total number of insertions in the dataframe

final_df = sorted_df.head(n_top_hits) #only take the top n hits and export them to an excel sheet
final_df.to_csv('PER17_dataframe_counted_insertions_GitHubtest.csv')

print('total n reads inputted: ' + str(counter/4))
print('total n insertions grabbed: ' + str(total_ins))


import signal
import sys
from time import time

from pyqcd.algorithms import GA, GLOA, MC, MLOA
from pyqcd.alphabet import Alphabet
from pyqcd.gates import CX, U3, I
from pyqcd.logger import Logger
from pyqcd.matrices import QFT, random_unitary

def main():
    start = time()
    # Quantum Fourier Transform on 4 qubits
    target = random_unitary(Q=4)

    # Instantiate a custom set of gates, an alphabet whose words are gates
    alphabet = Alphabet(Q=4)
    alphabet.register_gates([I, U3, CX])

    # Instantiate the search class
    solver = MLOA(target=target, alphabet=alphabet,
                  n_groups=5, group_size=5, circuit_size=50)

    # Instantiate the logger class to keep track of fitness evolution
    logger = Logger("data/%s_%srandom.pickle" %
                    (int(time()), solver.__class__.__name__), True)
    logger.add_variables(*solver.stats().keys())

    def exit_handler(sig, frame):
        solver.end()
        sys.exit(0)

    signal.signal(signal.SIGINT, exit_handler)

    # Main loop
    while solver.n_evals < 500000:
        # One step evolution
        solver.evolve()

        # Gather and save statistics
        logger.register(**solver.stats())

    solver.end()
    print("Time elapsed %d s" % (time() - start))

if __name__ == "__main__":
    main()


from PIL import Image
from torch.utils.tensorboard import SummaryWriter
from torchvision import transforms

writer = SummaryWriter("logs")
img = Image.open("dataset/train/ants/460874319_0a45ab4d05.jpg")

# ToTensor
trans_totensor = transforms.ToTensor()
img_tensor = trans_totensor(img)
writer.add_image("Totensor", img_tensor)

# Normalize
print(img_tensor[0][0][0])
trans_norm = transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
img_norm = trans_norm(img_tensor)
print(img_norm[0][0][0])
writer.add_image("normalize", img_norm)

# Resize
print(img.size)
trans_resize = transforms.Resize((512,512))
img_resize = trans_resize(img)
img_resize = trans_totensor(img_resize)
writer.add_image("resize", img_resize,0)

# compose
trans_compose = transforms.Compose([trans_resize,trans_totensor])
img_resize_2 = trans_compose(img)
writer.add_image("resize", img_resize_2, 1)

# randomcrop
trans_randomcrop = transforms.RandomCrop((300,200))
trans_compose_2 = transforms.Compose([trans_randomcrop, trans_totensor])
for i in range(10):
    img_crop = trans_compose_2(img)
    writer.add_image("randomHW", img_crop, i)

writer.close()


import pyowm
city=input('Sizi hansi sher maraglandirir? : ')
owm=pyowm.OWM('e4b796328673811095c29edf76bf2e36')
observation = owm.weather_at_place(city)
w = observation.get_weather()
temperature=w.get_temperature('celsius')['temp']
wind=w.get_wind() ['speed']
humidity=w.get_humidity()
detalied=w.get_detailed_status()
print("bu sherde " + city + " tempuraturu ise " + str(temperature) + " Selsiya " + " Kuleyin sureti ise " + str(wind) + " Rutubeti ise " + str(humidity))
print("secdiyiniz seherde " + str(detalied))


import os
import json
import time
from typing import Dict, List, Any

from jinja2 import Environment, PackageLoader

from pygwalker._constants import BYTE_LIMIT, ROOT_DIR
from pygwalker.utils.randoms import rand_str
from pygwalker.utils.display import display_html
from pygwalker import __version__, __hash__
from pygwalker_utils.config import get_config
from .global_var import GlobalVarManager

jinja_env = Environment(
    loader=PackageLoader("pygwalker"),
    autoescape=(()),  # select_autoescape()
)

class DataFrameEncoder(json.JSONEncoder):
    def default(self, o):
        try:
            return str(o)
        except TypeError:
            pass
        return json.JSONEncoder.default(self, o)

def gwalker_script() -> str:
    with open(os.path.join(ROOT_DIR, 'templates', 'dist', 'pygwalker-app.iife.js'), 'r', encoding='utf8') as f:
        gwalker_js = f.read()
    return gwalker_js

def _rand_slot_id():
    return __hash__ + '-' + rand_str(6)

def _send_js(js_code: str, slot_id: str):
    display_html(
        f"""""",
        GlobalVarManager.get_env(),
        slot_id=slot_id
    )

def _send_upload_data_msg(gid: int, msg: Dict[str, Any], slot_id: str):
    msg = json.dumps(msg, cls=DataFrameEncoder)
    js_code = (
        f"document.getElementById('gwalker-{gid}')?"
        ".contentWindow?"
        f".postMessage({msg}, '*');"
    )
    _send_js(js_code, slot_id)

def get_max_limited_datas(datas: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
    if len(datas) > 1024:
        smp0 = datas[::len(datas)//32]
        smp1 = datas[::len(datas)//37]
        avg_size = len(json.dumps(smp0, cls=DataFrameEncoder)) / len(smp0)
        avg_size = max(avg_size, len(json.dumps(smp1, cls=DataFrameEncoder)) / len(smp1))
        n = int(BYTE_LIMIT / avg_size)
        if len(datas) >= 2 * n:
            return datas[:n]
    return datas

class BatchUploadDatasTool:
    """Upload data in batches."""
    def __init__(self) -> None:
        self._caution_id = __hash__ + rand_str(6)
        self._progress_id = __hash__ + rand_str(6)

    def init(self) -> None:
        display_html("", GlobalVarManager.get_env(), slot_id=self._caution_id)
        display_html("", GlobalVarManager.get_env(), slot_id=self._progress_id)

    def run(
        self,
        *,
        data_source_id: str,
        gid: int,
        tunnel_id: str,
        records: List[Dict[str, Any]],
        sample_data_count: int,
        slot_count: int = 2
    ) -> None:
        progress_hint = "Dynamically loading into the frontend..."
        env = GlobalVarManager.get_env()
        chunk = 1 << 12
        cur_slot = 0
        display_slots = [_rand_slot_id() for _ in range(slot_count)]

        tips_title = (
            f'
Dataframe is too large for ipynb files. '
            f'Only {sample_data_count} sample items are printed to the file.
'
        )

        display_html(tips_title, env, slot_id=self._caution_id)
        display_html(f"{progress_hint} {sample_data_count}/{len(records)}", env, slot_id=self._progress_id)

        for i in range(sample_data_count, len(records), chunk):
            data = records[i: min(i+chunk, len(records))]
            msg = {
                'action': 'postData',
                'tunnelId': tunnel_id,
                'dataSourceId': data_source_id,
                'data': data,
            }
            _send_upload_data_msg(gid, msg, display_slots[cur_slot])
            cur_slot += 1
            cur_slot %= slot_count
            display_html(f"{progress_hint} {min(i+chunk, len(records))}/{len(records)}", env, slot_id=self._progress_id)

        finish_msg = {
            'action': 'finishData',
            'tunnelId': tunnel_id,
            'dataSourceId': data_source_id,
        }
        time.sleep(1)
        _send_upload_data_msg(gid, finish_msg, display_slots[cur_slot])
        display_html("", env, slot_id=self._progress_id)
        display_html("", env, slot_id=self._caution_id)

        for slot_id in display_slots:
            display_html("", env, slot_id=slot_id)

def render_gwalker_iframe(gid: int, srcdoc: str) -> str:
    return jinja_env.get_template("pygwalker_iframe.html").render(
        gid=gid,
        srcdoc=srcdoc,
    )

def render_gwalker_html(gid: int, props: Dict) -> str:
    ds = props.get('dataSource', [])

    props['len'] = len(ds)
    walker_template = jinja_env.get_template("walk.js")
    props['version'] = __version__
    props['hashcode'] = __hash__
    if 'spec' in props:
        props['visSpec'] = props.get('spec', None)
        del props['spec']
    props['userConfig'], _ = get_config()

    props['dataSourceProps'] = {
        'tunnelId': 'tunnel!',
        'dataSourceId': f'dataSource!{rand_str(4)}',
    }

    js = walker_template.render(gwalker={'id': gid, 'props': json.dumps(props, cls=DataFrameEncoder)})
    js = "var exports={}, module={};" + gwalker_script() + js

    template = jinja_env.get_template("index.html")
    html = f"{template.render(gwalker={'id': gid, 'script': js})}"
    return html


#!/usr/bin/env python3
from functools import reduce
from operator import mul
def read_input():
    inp = []
    with open('input', 'r') as f:
        for line in f.readlines():
            line = line.strip('\n')
            row = []
            for c in line:
                row.append(c)
            inp.append(row)
    return inp

def count_trees(stepx, stepy):
    treemap = read_input()
    x = 0
    y = 0
    count = 0
    while y < len(treemap):
        if x >= len(treemap[y]):
            x -= len(treemap[y])
        if treemap[y][x] == '#':
            count += 1
        x += stepx
        y += stepy

    return count

def solve1():
    return count_trees(3, 1)

def solve2():
    slopes = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]
    counts = [count_trees(*x) for x in slopes]
    return reduce(mul, counts, 1)

if __name__ == "__main__":
    print(solve1())
    print(solve2())


import sys

def Bullseye(fname,sname):
    with open(fname) as file:
        with open(sname,'w') as salida:
            line = file.readline()
            T=int(line)
            for case in range(1,T+1):
                [r,t]=[int(i) for i in file.readline().split()]
                k=int(((1-2*r)+((2*r-1)**2+8*t)**0.5)/4.0)
                area=0
                while area<=t:
                    k+=1
                    area=(2*r-3)*k+2*k*k+2*k
                while area>t:
                    k-=1
                    area=(2*r-3)*k+2*k*k+2*k
                salida.write("Case #{0}: {1}\n".format(case,(k)))
        salida.close()
    file.close()


import traceback
class Students(object):
  @property
  def score(self):
    return self._score

  @score.setter
  def score(self,value):
    if not isinstance(value,int):
      raise ValueError('not int')
    elif(value<0) or (value>100):
      raise ValueError('not between 0~100')

    self._score = value
  @property
  def double_score(self):
    return self._score * 2

sa = Students()
sa.score = 75
print(sa.score)
try:
  sa.score = 10212
except ValueError:
  traceback.print_exc()
try:
  sa.score = 'asd'
except:
  traceback.print_exc()
print(sa.double_score)
try:
  sa.double_score = 160
except AttributeError:
  traceback.print_exc()


"""
virtstrap.commands.install
--------------------------

The 'install' command
"""
import tempfile
import subprocess
from contextlib import contextmanager
from virtstrap import commands
from virtstrap import constants
from virtstrap.requirements import RequirementSet
from virtstrap.locker import RequirementsLocker

def process_requirements_config(raw_requirements):
    requirement_set = RequirementSet.from_config_data(raw_requirements)
    return requirement_set

class InstallationError(Exception):
    pass

class InstallCommand(commands.ProjectCommand):
    name = 'install'
    description = "Installs the project's python requirements"

    def run(self, project, options, **kwargs):
        requirement_set = self.get_requirement_set(project)
        if requirement_set:
            temp_reqs_path = self.write_temp_requirements_file(requirement_set)
            self.run_pip_install(project, temp_reqs_path)
            self.freeze_requirements(project, requirement_set)

    def get_requirement_set(self, project):
        requirement_set = project.process_config_section('requirements',
                                process_requirements_config)
        return requirement_set

    def write_temp_requirements_file(self, requirement_set):
        requirements_write = requirement_set.to_pip_str()
        os_handle, temp_reqs_path = tempfile.mkstemp()
        temp_reqs_file = open(temp_reqs_path, 'w')
        temp_reqs_file.write(requirements_write)
        temp_reqs_file.close()
        return temp_reqs_path

    def run_pip_install(self, project, requirements_path):
        logger = self.logger
        logger.info('Building requirements in "%s"' % project.config_file)
        pip_bin = project.bin_path('pip')
        pip_command = 'install'
        self.logger.debug('Running pip at %s' % pip_bin)
        return_code = subprocess.call([pip_bin, pip_command, '-r',
            requirements_path])
        if return_code != 0:
            raise InstallationError('An error occured during installation')

    def freeze_requirements(self, project, requirement_set):
        locker = RequirementsLocker()
        lock_str = locker.lock(requirement_set)
        requirements_lock = open(project.path(constants.VE_LOCK_FILENAME), 'w')
        requirements_lock.write(lock_str)
        requirements_lock.close()

    def freeze_requirements_old(self, project, requirement_set):
        pip_bin = project.bin_path('pip')
        process = subprocess.Popen([pip_bin, 'freeze'],
                stdout=subprocess.PIPE)
        requirements = process.stdout.read()
        requirements_lock = open(project.path(constants.VE_LOCK_FILENAME), 'w')
        requirements_lock.write(requirements)
        requirements_lock.close()


import sys

input_filename = sys.argv[1]

with open(input_filename, "r") as infile:
    with open("out.txt", "w") as outfile:
        t = infile.readline()
        t = 0
        for line in infile:
            t+=1
            K, C, S = map(int, line.split())
            kk = K**(C-1)
            outfile.write("Case #%d:" % t)
            i = kk
            while i<kk*K+1:
                outfile.write(" %d" % i)
                i+=kk
            outfile.write("\n")


import sys
import math
import numpy # http://www.numpy.org/
import string
import tkinter as tk
from tkinter.filedialog import askopenfilename

root = tk.Tk()
root.withdraw()

filename = askopenfilename()

fInput = open(filename, 'r')
fOutput = open(filename.replace('.in', '.txt'), 'w+')

cases = int(fInput.readline())

def BaseConvert(value, base):
    number = 0
    power = 1

    for i in range(len(value)):
        if(value[-1-i] != 0):
            number += value[-1-i]*power
        power *= base
    return number

for i in range(cases):
    info = fInput.readline().rstrip()
    infoList = info.split(' ')

    K = int(infoList[0])
    C = int(infoList[1])
    S = int(infoList[2])

    if S < math.ceil(K/C):
        result = 'IMPOSSIBLE'
        fOutput.write('Case #{}: {}\n'.format(i+1, result))
        print('Case #{}: {}'.format(i+1, result))
    elif K == 1:
        result = 1
        fOutput.write('Case #{}: {}\n'.format(i+1, result))
        print('Case #{}: {}'.format(i+1, result))
    else:
        index = 0

        result = []
        for j in range(math.ceil(K/C)):
            inBase= []
            for k in range(C):
                inBase.append(index)
                index += 1
                if index >= K:
                    index = 0

            result.append(BaseConvert(inBase,K)+1)
        fOutput.write('Case #{}: {}\n'.format(i+1, ' '.join(map(str,result))))
        print('Case #{}: {}'.format(i+1, ' '.join(map(str,result))))

fInput.close()
fOutput.close()


from AppKit import NSWindowController
import objc
dockingSplitOptions = {
    'top' : (0, True),
    'bottom' : (-1, True),
    'left' : (0, False),
    'right' : (-1, False),
    'center' : None, # special option that later would create tabbed window
}

class DockingWindowsList(object):
    '''
        List that contains windows, that are included into docking
        It is only used inside of the WindowDockReciever class.
        Its main purpose is to inform this class whenever this list changes.
    '''
    def __init__(self, WindowDockReciever, windowList):
        self.windowList = windowList
        self.WindowDockReciever = WindowDockReciever
        for obj in self.windowList:
            self.__callEvent(obj, True)

    def __callEvent(self, windowObj, bind):

        # MouseDownWindowController.alloc().initWithWindow_(windowObj.getNSWindow())
        if bind:
            windowObj.bind('move', self.WindowDockReciever._dockingWindowMoveCallback)
        else:
            windowObj.unbind('move', self.WindowDockReciever._dockingWindowMoveCallback)

        self.WindowDockReciever._dockingWindowsUpdateEvent(self)

    def append(self, arg):
        self.__callEvent(arg, True)
        self.windowList.append(arg)

    def __iadd__(self, args):
        for obj in args:
            self.__callEvent(obj, True)
        self.windowList += args
        return self

    def __len__(self):
        return len(self.windowList)

    def remove(self, obj):
        self.__callEvent(obj, False)
        self.windowList.remove(obj)


# © 2020 io mintz <io@mintz.cc>

import os.path
import time

# pylint: disable=dangerous-default-value
def load_cached(path, callback, *, duration=23 * 60 * 60, binary=False, _cache={}):
	now = time.time()

	def refresh_cache():
		rv = callback()
		with open(path, 'wb' if binary else 'w') as f:
			f.write(rv)
		_cache[path] = rv, now
		return rv

	try:
		rv, last_modified = _cache[path]
	except KeyError:
		pass
	else:
		if now - last_modified > duration:
			return refresh_cache()
		return rv

	# not in cache

	try:
		last_modified = os.stat(path).st_mtime
	except FileNotFoundError:
		return refresh_cache()

	# not in cache but file exists

	if now - last_modified > duration:
		return refresh_cache()

	# not in cache, file exists, and the file is young enough

	with open(path, 'rb' if binary else 'r') as f:
		rv = f.read()
	_cache[path] = rv, now
	return rv

def chunked(seq, n):
	length = len(seq)
	for i in range(0, length - (n - 1), n):
		yield seq[i:i+n]
	mod = len(seq) % n
	if mod:
		yield seq[-mod:]


# Ex 2
def tarifs():
    origine = input("Pays d'origine de l'appel (France ou Estonie): ")
    destination = input("Pays de destination de l'appel (France ou Estonie): ")
    if origine == "France" and destination == "Estonie":
        print("Le tarif est de 0.3€ par minutes.")
    elif origine == "Estonie" and destination == "France":
        print("Le tarif est de O.7€ par minutes")
    elif origine == "France" and destination == "France":
        print("Gratuit")
    else:
        print("Veuillez consulter la brochure tarifaire.")

import random as rd

# Ex 3
def jeux_devinette():
    a = 40
    nb = 1
    b = int(input("Entrer un nombre: "))
    while b != a:
        if b < a:
            print("a est plus grand")
        else:
            print("a est plus petit")
        nb += 1
        b = int(input("Entrer un nombre: "))
    print(nb)

def devinette_random(n):
    a = rd.randint(0, n)
    nb = 1
    b = int(input("Entrer un nombre: "))
    while b != a:
        if b < a:
            print("a est plus grand")
        else:
            print("a est plus petit")
        nb += 1
        b = int(input("Entrer un nombre: "))
    print(nb)

if __name__ == "__main__":
    # tarifs()
    jeux_devinette()


# %% Imports and global variables
print("\033[32m Loading python backend - pbarlike 1.0")

import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
import gc
import numpy as np
import tensorflow as tf
for gpu in tf.config.experimental.list_physical_devices('GPU'):
    tf.config.experimental.set_memory_growth(gpu, True)
from iminuit import Minuit
import sys
print("\033[32m Imported required python modules - numpy, tensorflow, iminuit.Minuit")

script_directory = os.path.dirname(os.path.realpath(__file__))
m_p = 0.9382720881604903  # Mass of proton in GeV (938.2720881604903 MeV)

# %% Loading and preparing data
# # Loading AMS Data for antiproton flux:
# ## pbar_ams02_7y.txt
# - Column 1: Rigidity [GV] from
# - Column 2: Rigidity [GV] to
# - Column 3: Number of antiprotons
# - Column 4: pbar/p ratio
# - Column 5: sigma stat
# - Column 6: sigma sys (on ratio)              !!not given
# - Column 7: sigma sys (on folded acceptance)  !!not given
# - Column 8: sigma sys (on Rigidity scale)     !!not given
# - Column 9: sigma sys (total)
# - Column10: Factor (for columns 3-9)
# - Column11: Antiproton flux in m-2 sr-1 s-1 GV-1
# - Column12: sigma stat
# - Column13: sigma sys
# - Column14: Factor (for columns 11-13)

# # Preparing data
# ## Converting R to kinetic energy per nucleon:
# $$ E_k / A = \sqrt{(RZ/A)^2 + m^2} $$
#
# ## Converting flux in R to flux in E :
# $$ \frac{d \phi}{d R} \frac{d R}{d (E_k/A)} = \frac{d \phi}{d R} \frac{1}{R} (\frac{A}{Z})^2 \sqrt{( \frac{RA}{Z})^2 + m^2} $$

# %%

# Loading 7 year ams02_data which has columns as above :
ams_data = np.genfromtxt(script_directory+'/dependencies/pbar_ams02_7y.txt')
R_ams = (ams_data[:,0]+ams_data[:,1])/2
phi_in_R = ams_data[:,10] * ams_data[:,13]
error_R_ams = np.sqrt(ams_data[:,11]**2+ams_data[:,12]**2)*ams_data[:,13]

# Loading ams02 covariance matrix (58,58) for the 7-year antiproton data:
ams_cov = np.matrix(np.genfromtxt(script_directory+'/dependencies/covariance_pbar_AMS.dat'))[14:,14:]
ams_7y_cov = np.matrix(np.genfromtxt(script_directory+'/dependencies/CovMatrix_AMS02_pbar_7y.txt'))[14:,14:]

# R - array with rigidity values in GV; outputs array of E_k in GeV
def R_to_Ekin(R,z = -1, A = 1, m = m_p ):
    Z = np.abs(z)
    return np.sqrt(R**2 * (Z/A)**2 + m**2) - m

# flux_in_R - array of flux values measured at different rigidities in m-2 sr-1 s-1 GV-1; outputs array of flux values measured at
# different energies in m-2 sr-1 s-1 GeV-1
def flux_in_Ekin(flux_in_R,R,z=-1,A=1,m=m_p):
    Z = np.abs(z)
    return flux_in_R /R * (A/Z)**2 * np.sqrt((R*Z/A)**2 + m**2)

# E_ams -(58,) array of KE per nucleon values at which AMS02 flux measurements are recorded for pbar
E_ams = np.array(R_to_Ekin(R_ams))
# phi_ams - (58,) array of flux values measured at E_ams
phi_ams = np.array(flux_in_Ekin(phi_in_R,R_ams))
# Error propagation gives the error of flux in E_k as follows:
# error_ams - (58,) array of error values of flux values measured at E_ams
error_ams = np.array(flux_in_Ekin(error_R_ams,R_ams))
# ams_cov = np.diag(error_ams**2)
# ams_cov_inv = np.matrix(ams_cov).I

# E_drn - (28,) array of KE per nucleon values at which sNet predicts flux values (same values at which training data are given to the sNet)
E_drn = np.array(np.load(script_directory+'/dependencies/E.npy'))
print("\033[32m Loaded and processed AMS-02 dataset")


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

import os
import re
import tempfile
from time import time
from .basecache import BaseCache
from .posixemulation import rename, _items
try:
    import cPickle as pickle
except ImportError:
    import pickle
try:
    from hashlib import md5
except ImportError:
    from md5 import new as md5

_test_memcached_key = re.compile(r'[^\x00-\x21\xff]{1,250}$').match

class MemcachedCache(BaseCache):
    """A cache that uses memcached as backend.

    The first argument can either be an object that resembles the API of a
    :class:`memcache.Client` or a tuple/list of server addresses. In the
    event that a tuple/list is passed, Werkzeug tries to import the best
    available memcache library.

    Implementation notes:  This cache backend works around some limitations in
    memcached to simplify the interface.  For example unicode keys are encoded
    to utf-8 on the fly.  Methods such as :meth:`~BaseCache.get_dict` return
    the keys in the same format as passed.  Furthermore all get methods
    silently ignore key errors to not cause problems when untrusted user data
    is passed to the get methods which is often the case in web applications.

    :param servers: a list or tuple of server addresses or alternatively
                    a :class:`memcache.Client` or a compatible client.
    :param default_timeout: the default timeout that is used if no timeout is
                            specified on :meth:`~BaseCache.set`.
    :param key_prefix: a prefix that is added before all keys.  This makes it
                       possible to use the same memcached server for different
                       applications.  Keep in mind that
                       :meth:`~BaseCache.clear` will also clear keys with a
                       different prefix.
    """

    def __init__(self, servers=None, default_timeout=300, key_prefix=None):
        BaseCache.__init__(self, default_timeout)
        if servers is None or isinstance(servers, (list, tuple)):
            if servers is None:
                servers = ['127.0.0.1:11211']
            self._client = self.import_preferred_memcache_lib(servers)
            if self._client is None:
                raise RuntimeError('no memcache module found')
        else:
            # NOTE: servers is actually an already initialized memcache
            # client.
            self._client = servers

        self.key_prefix = key_prefix

    def get(self, key):
        if isinstance(key, unicode):
            key = key.encode('utf-8')
        if self.key_prefix:
            key = self.key_prefix + key
        # memcached doesn't support keys longer than that.  Because often
        # checks for so long keys can occour because it's tested from user
        # submitted data etc we fail silently for getting.
        if _test_memcached_key(key):
            return self._client.get(key)

    def get_dict(self, *keys):
        key_mapping = {}
        have_encoded_keys = False
        for key in keys:
            if isinstance(key, unicode):
                encoded_key = key.encode('utf-8')
                have_encoded_keys = True
            else:
                encoded_key = key
            if self.key_prefix:
                encoded_key = self.key_prefix + encoded_key
            if _test_memcached_key(key):
                key_mapping[encoded_key] = key
        d = rv = self._client.get_multi(key_mapping.keys())
        if have_encoded_keys or self.key_prefix:
            rv = {}
            for key, value in d.iteritems():
                rv[key_mapping[key]] = value
        if len(rv) < len(keys):
            for key in keys:
                if key not in rv:
                    rv[key] = None
        return rv

    def add(self, key, value, timeout=None):
        if timeout is None:
            timeout = self.default_timeout
        if isinstance(key, unicode):
            key = key.encode('utf-8')
        if self.key_prefix:
            key = self.key_prefix + key
        self._client.add(key, value, timeout)

    def set(self, key, value, timeout=None):
        if timeout is None:
            timeout = self.default_timeout
        if isinstance(key, unicode):
            key = key.encode('utf-8')
        if self.key_prefix:
            key = self.key_prefix + key
        self._client.set(key, value, timeout)

    def get_many(self, *keys):
        d = self.get_dict(*keys)
        return [d[key] for key in keys]

    def set_many(self, mapping, timeout=None):
        if timeout is None:
            timeout = self.default_timeout
        new_mapping = {}
        for key, value in _items(mapping):
            if isinstance(key, unicode):
                key = key.encode('utf-8')
            if self.key_prefix:
                key = self.key_prefix + key
            new_mapping[key] = value
        self._client.set_multi(new_mapping, timeout)

    def delete(self, key):
        if isinstance(key, unicode):
            key = key.encode('utf-8')
        if self.key_prefix:
            key = self.key_prefix + key
        if _test_memcached_key(key):
            self._client.delete(key)

    def delete_many(self, *keys):
        new_keys = []
        for key in keys:
            if isinstance(key, unicode):
                key = key.encode('utf-8')
            if self.key_prefix:
                key = self.key_prefix + key
            if _test_memcached_key(key):
                new_keys.append(key)
        self._client.delete_multi(new_keys)

    def clear(self):
        self._client.flush_all()

    def inc(self, key, delta=1):
        if isinstance(key, unicode):
            key = key.encode('utf-8')
        if self.key_prefix:
            key = self.key_prefix + key
        self._client.incr(key, delta)

    def dec(self, key, delta=1):
        if isinstance(key, unicode):
            key = key.encode('utf-8')
        if self.key_prefix:
            key = self.key_prefix + key
        self._client.decr(key, delta)

    def import_preferred_memcache_lib(self, servers):
        """Returns an initialized memcache client.  Used by the constructor."""
        try:
            import pylibmc
        except ImportError:
            pass
        else:
            return pylibmc.Client(servers)

        try:
            from google.appengine.api import memcache
        except ImportError:
            pass
        else:
            return memcache.Client()

        try:
            import memcache
        except ImportError:
            pass
        else:
            return memcache.Client(servers)

# backwards compatibility
GAEMemcachedCache = MemcachedCache


from __future__ import print_function
import os
import sys
import re
from threading import Thread
import subprocess

try:
    # This environment variable is expected on the host machine
    test_fw_path = os.getenv("TEST_FW_PATH")
    if test_fw_path and test_fw_path not in sys.path:
        sys.path.insert(0, test_fw_path)
    import IDF
except ImportError as e:
    print(e)
    print("Try `export TEST_FW_PATH=$IDF_PATH/tools/tiny-test-fw` for resolving the issue")
    print("Try `pip install -r $IDF_PATH/tools/tiny-test-fw/requirements.txt` for resolving the issue")
    import IDF

try:
    import lib_ble_client
except ImportError:
    lib_ble_client_path = os.getenv("IDF_PATH") + "/tools/ble"
    if lib_ble_client_path and lib_ble_client_path not in sys.path:
        sys.path.insert(0, lib_ble_client_path)
    import lib_ble_client

import Utility

# When running on local machine execute the following before running this script
# > make app bootloader
# > make print_flash_cmd | tail -n 1 > build/download.config
# > export TEST_FW_PATH=~/esp/esp-idf/tools/tiny-test-fw

def bleprph_client_task(dut_addr, dut):
    interface = 'hci0'
    ble_devname = 'nimble-bleprph'
    srv_uuid = '2f12'

    # Get BLE client module
    ble_client_obj = lib_ble_client.BLE_Bluez_Client(interface, devname=ble_devname, devaddr=dut_addr)
    if not ble_client_obj:
        raise RuntimeError("Failed to get DBus-Bluez object")

    # Discover Bluetooth Adapter and power on
    is_adapter_set = ble_client_obj.set_adapter()
    if not is_adapter_set:
        raise RuntimeError("Adapter Power On failed !!")

    # Connect BLE Device
    is_connected = ble_client_obj.connect()
    if not is_connected:
        Utility.console_log("Connection to device ", ble_devname, "failed !!")
        # Call disconnect to perform cleanup operations before exiting application
        ble_client_obj.disconnect()
        return

    # Check dut responses
    dut.expect("GAP procedure initiated: advertise;", timeout=30)

    # Read Services
    services_ret = ble_client_obj.get_services(srv_uuid)
    if services_ret:
        print("\nServices\n")
        print(services_ret)
    else:
        print("Failure: Read Services failed")
        ble_client_obj.disconnect()
        return

    # Read Characteristics
    chars_ret = {}
    chars_ret = ble_client_obj.read_chars()
    if chars_ret:
        Utility.console_log("\nCharacteristics retrieved")
        for path, props in chars_ret.items():
            print("\n\tCharacteristic: ", path)
            print("\tCharacteristic UUID: ", props[2])
            print("\tValue: ", props[0])
            print("\tProperties: : ", props[1])
    else:
        print("Failure: Read Characteristics failed")
        ble_client_obj.disconnect()
        return

    '''
    Write Characteristics
    - write 'A' to characteristic with write permission
    '''
    chars_ret_on_write = {}
    chars_ret_on_write = ble_client_obj.write_chars('A')
    if chars_ret_on_write:
        Utility.console_log("\nCharacteristics after write operation")
        for path, props in chars_ret_on_write.items():
            print("\n\tCharacteristic:", path)
            print("\tCharacteristic UUID: ", props[2])
            print("\tValue:", props[0])
            print("\tProperties: : ", props[1])
    else:
        print("Failure: Write Characteristics failed")
        ble_client_obj.disconnect()
        return

    # Call disconnect to perform cleanup operations before exiting application
    ble_client_obj.disconnect()

@IDF.idf_example_test(env_tag="Example_WIFI_BT")
def test_example_app_ble_peripheral(env, extra_data):
    """
        Steps:
            1. Discover Bluetooth Adapter and Power On
            2. Connect BLE Device
            3. Read Services
            4. Read Characteristics
            5. Write Characteristics
    """
    try:

        # Acquire DUT
        dut = env.get_dut("bleprph", "examples/bluetooth/nimble/bleprph")

        # Get binary file
        binary_file = os.path.join(dut.app.binary_path, "bleprph.bin")
        bin_size = os.path.getsize(binary_file)
        IDF.log_performance("bleprph_bin_size", "{}KB".format(bin_size // 1024))
        IDF.check_performance("bleprph_bin_size", bin_size // 1024)

        # Upload binary and start testing
        Utility.console_log("Starting bleprph simple example test app")
        dut.start_app()

        subprocess.check_output(['rm','-rf','/var/lib/bluetooth/*'])

        # Get device address from dut
        dut_addr = dut.expect(re.compile(r"Device Address: ([a-fA-F0-9:]+)"), timeout=30)[0]

        # Starting a py-client in a separate thread
        thread1 = Thread(target=bleprph_client_task, args=(dut_addr,dut,))
        thread1.start()
        thread1.join()

        # Check dut responses
        dut.expect("connection established; status=0", timeout=30)
        dut.expect("disconnect;", timeout=30)
    except Exception as e:
        sys.exit(e)

if __name__ == '__main__':
    test_example_app_ble_peripheral()


# encoding=utf-8
# -*- coding: utf-8 -*- vim:encoding=utf-8:
# vim: tabstop=4:shiftwidth=4:softtabstop=4:expandtab
import warnings
warnings.simplefilter("ignore", DeprecationWarning)
import sys
import locale
import codecs
# Printing unicode: WAS: https://wiki.python.org/moin/PrintFails
# But now rather follow:
#    https://docs.djangoproject.com/en/1.9/howto/custom-management-commands/#management-commands-and-locales
# I.e., set leave_locale_alone and let the system locale handle things.
# Django 1.8 now uses unicode by default - so all works well without modifying the codecs.

from optparse import make_option
from django.core.management.base import BaseCommand
from accounts.models import User
from django.utils.translation import get_language, to_locale, ugettext as _
from utils.locale import setlocale, compat_strxfrm

class Command(BaseCommand):

    help = 'Prints institution contacts in CSV format'

    leave_locale_alone = True

    def add_arguments(self, parser):
        parser.add_argument(
            '--mail-list',
            action='store_true',
            dest='maillist',
            default=False,
            help='Return only emails (output suitable for a mailing list)'
        )

    def handle(self, *args, **options):
        users = User.objects.all()
        if not options['maillist']:
            self.stdout.write(
                u'{},{},{}'.format(
                    _('Institution'),
                    _('Administrator'),
                    "email"
                )
                + "\n"
            )
        data = [
            (
                u.userprofile.institution.get_name(get_language()),
                u.first_name + " " + u.last_name,
                m
            ) for u in users if (
                u.registrationprofile
                and u.registrationprofile.activation_key == "ALREADY_ACTIVATED"
            ) for m in u.email.split(';')
        ]
        with setlocale((to_locale(get_language()), 'UTF-8'),
                       locale.LC_COLLATE):
            data.sort(key=lambda d: compat_strxfrm(d[0]))
        for (foreas, onoma, email) in data:
            if options['maillist']:
                self.stdout.write(
                    u'{email}\t{onoma}'.format(
                        email=email,
                        onoma=onoma
                    )
                    + "\n")
            else:
                self.stdout.write(
                    u'"{foreas}","{onoma}","{email}"'.format(
                        onoma=onoma,
                        email=email,
                        foreas=foreas
                    )
                    + "\n"
                )


import cv2

# To capture video from webcam
# Might have to use 1 or 2 for parameter depending on if it's an integrated or usb webcam
cap = cv2.VideoCapture(0)

# Load Trained CascadeClassifier XML
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

while True:
    # Read the frame
    ret, img = cap.read()
    # Convert to grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # Detect the faces
    faces = face_cascade.detectMultiScale(gray, 1.2, 5)
    # Draw the rectangle around each face
    for (x, y, w, h) in faces:
        cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2)
    # Display
    cv2.imshow('img', img)
    # Stop if escape key is pressed
    k = cv2.waitKey(1) & 0xff
    if k==27:
        break
# Release the VideoCapture object
cap.release()
#Delete any windows created
cv2.destroyallwindows()


import os
from obspy.core import *

# parallel params
start_date = '20160901'
end_date   = '20180901'
num_thread = 20

# divide by time
ts = UTCDateTime(start_date)
te = UTCDateTime(end_date)
dt = (te-ts) /num_thread
for i in range(num_thread):
    t0 = str((ts + i*dt).date)
    t1 = str((ts + (i+1)*dt).date)
    os.system("python mkctlg.py --time_range={},{} \
               --sta_file=/data3/XJ_SAC/header/station_ZSY.dat \
               --out_pha=./output/phase_{}_{}.dat \
               --out_ctlg=./output/catalog_{}_{}.dat &"\
               .format(t0,t1,t0,t1,t0,t1))


import click
import boto3

from decouple import config
from prettytable import PrettyTable

@click.command()
@click.argument('resource')
@click.option('--profile', default=config('DEFAULT_AWS_PROFILE', None),
              help='AWS CLI Profile to use.')
def main(resource, profile):
    if profile:
        boto3.setup_default_session(profile_name=profile)

    if resource == 'ec2':
        list_aws_instances()
    elif resource == 'rds':
        list_aws_rds()
    else:
        with click.get_current_context() as ctx:
            click.echo(ctx.get_help())
            ctx.exit()

def list_aws_instances():
    ec2 = boto3.resource('ec2')
    table = PrettyTable(align='l')
    table.field_names = ['State', 'Name', 'ID', 'Key Pair', 'Public IP',
                         'Public Address']

    for instance in ec2.instances.all():
        try:
            instance_name = [x for x in instance.tags if x['Key'] == 'Name']
            instance_name = instance_name[0]['Value']
        except TypeError:
            instance_name = '-'

        table.add_row([
            instance.state['Name'].title(),
            instance_name,
            instance.id,
            instance.key_name,
            instance.public_ip_address,
            instance.public_dns_name
        ])

    print(table)

def list_aws_rds():
    resource = boto3.client('rds')
    instances = resource.describe_db_instances()

    table = PrettyTable(align='l')
    table.field_names = ['State', 'Engine', 'Name', 'Type', 'Address',
                         'MasterUser']

    for instance in instances['DBInstances']:
        table.add_row([
            instance['DBInstanceStatus'].title(),
            instance['Engine'],
            instance['DBInstanceIdentifier'],
            instance['DBInstanceClass'],
            instance['Endpoint']['Address'],
            instance['MasterUsername']
        ])

    print(table)

if __name__ == '__main__':
    main()


from __future__ import annotations

import importlib
import sys
from copy import copy
from pathlib import Path

import mock
import pytest

from volttron.utils import get_class, get_module, get_subclasses

# sys_path_with holds a sys.path that includes the path to
# tests directory on the path.

sys_path_with = copy(sys.path)
sys_path_with.insert(0, str(Path(__file__).parent.parent))

def test_get_module_import_error_raised():
    with pytest.raises(ModuleNotFoundError):
        get_module("non_existing_module.module_data")

def test_get_class_import_error_raised():
    with pytest.raises(ModuleNotFoundError):
        get_class("non_existing_module.module_data", 'SecondaryClass')

def test_get_module():
    with mock.patch('sys.path', sys_path_with):
        module_name = "module_for_testing.module_data"
        actual_module = get_module("module_for_testing.module_data")

        assert actual_module.__name__ == module_name

def test_get_klass_str():
    with mock.patch('sys.path', sys_path_with):
        klass = get_class("module_for_testing.module_data", 'SecondaryClass')
        assert klass.__name__ == 'SecondaryClass'

def test_get_klass_mod():
    with mock.patch('sys.path', sys_path_with):
        module = importlib.import_module("module_for_testing.module_data")
        klass = get_class(module, "MyHelperClass")
        assert klass.__name__ == 'MyHelperClass'

def test_get_klass_attribute_error_raised():
    with pytest.raises(AttributeError) as err:
        get_class("module_for_testing.module_data", 'RandomClass')

def test_get_subclasses_value_error_raised():
    with mock.patch('sys.path', sys_path_with):
        with pytest.raises(ValueError) as err:

            module = importlib.import_module("module_for_testing.module_no_classes_data")
            klass = getattr(importlib.import_module("module_for_testing.module_data"),
                            "MyHelperClass")
            get_subclasses(module, klass)

@pytest.mark.parametrize("return_all, expected_len", [(False, 1), (True, 2)])
def test_get_subclasses_on_all_str(return_all, expected_len):
    with mock.patch('sys.path', sys_path_with):
        expected_subclasses = ['SecondaryClass', 'ThirdClass']
        module = "module_for_testing.module_data"
        parent_class = "MyHelperClass"

        subclasses = get_subclasses(module, parent_class, return_all)

        assert len(subclasses) == expected_len
        for subclass in subclasses:
            assert subclass.__name__ in expected_subclasses

@pytest.mark.parametrize("return_all, expected_len", [(False, 1), (True, 2)])
def test_get_subclasses_on_all_mod(return_all, expected_len):
    with mock.patch('sys.path', sys_path_with):
        expected_subclasses = ['SecondaryClass', 'ThirdClass']
        module = importlib.import_module("module_for_testing.module_data")
        parent_class = getattr(module, "MyHelperClass")

        subclasses = get_subclasses(module, parent_class, return_all=return_all)

        assert len(subclasses) == expected_len
        for subclass in subclasses:
            assert subclass.__name__ in expected_subclasses

@pytest.mark.parametrize("return_all, expected_len", [(False, 1), (True, 2)])
def test_get_subclasses_on_module_str_parent_class_mod(return_all, expected_len):
    with mock.patch('sys.path', sys_path_with):
        expected_subclasses = ['SecondaryClass', 'ThirdClass']
        module = "module_for_testing.module_data"
        parent_class = getattr(importlib.import_module(module), "MyHelperClass")

        subclasses = get_subclasses(module, parent_class, return_all=return_all)

        assert len(subclasses) == expected_len
        for subclass in subclasses:
            assert subclass.__name__ in expected_subclasses

@pytest.mark.parametrize("return_all, expected_len", [(False, 1), (True, 2)])
def test_get_subclasses_on_module_mod_parent_class_str(return_all, expected_len):
    with mock.patch('sys.path', sys_path_with):
        expected_subclasses = ['SecondaryClass', 'ThirdClass']
        module = importlib.import_module("module_for_testing.module_data")
        parent_class = "MyHelperClass"

        subclasses = get_subclasses(module, parent_class, return_all=return_all)

        assert len(subclasses) == expected_len
        for subclass in subclasses:
            assert subclass.__name__ in expected_subclasses


import os
import numpy as np
import nibabel as nib
from tqdm import tqdm
import argparse
import monai

def nifti_to_2d_slices(input_folder: str, output_folder: str, axis: int, filtered, resize):
    for fname in tqdm(sorted(os.listdir(input_folder))):

        if not fname.endswith("nii.gz"):
            continue

        n_file = os.path.join(input_folder, fname)
        nifti = nib.load(n_file)

        np_data = nifti.get_fdata()
        np_data = np_data.astype(np.float16)

        f_basename = fname.split(".")[0]

        for i in range(np_data.shape[axis]):
            slc = [slice(None)] * len(np_data.shape)
            slc[axis] = i
            image = np_data[slc]

            if resize:
                tr = monai.transforms.Resize((resize, resize))
                image = tr(image[None])[0]

            if filtered:
                brain_mask = image > 0
                if brain_mask.sum() < 4000:
                    continue

            np.save(os.path.join(output_folder, f"{f_basename}_{i}.npy"), image)

if __name__ == "__main__":

    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument("-i", "--input_dir",
                        default='./data/original/brain_train/',
                        help='input_dir')
    parser.add_argument("-o", "--output_dir",
                        default='./data/preprocessed/brain_train/2d_axis_2',
                        help='input_dir')
    parser.add_argument("-a", "--axis", type=int,
                        default=2,
                        help='axis')
    parser.add_argument("-f", "--do_not_filter", action='store_true',
                        default=False,
                        help='Default behavior: do not save slices where # of non zero pixels < 4000. \n'
                             'Use this flag to disable this behavior')
    parser.add_argument("-r", "--resize", type=int,
                        default=256,
                        help='Resize image while saving')

    args = parser.parse_args()

    input_dir = args.input_dir
    output_dir = args.output_dir
    axis = args.axis
    do_filter = (args.do_not_filter == False)
    resize = args.resize
    os.makedirs(output_dir, exist_ok=True)

    nifti_to_2d_slices(input_dir, output_dir, axis, do_filter, resize)


s = str(input('Enter the string to be capitalized: '))

def solve(s):
  for word in s.split(): #splits the string into a list where default separator is space
    s = s.replace(word,word.capitalize()) #replaces all incidences of word with word that is capitalized
  print(s)

solve(s)

# prints out for s.split : ['alison hack']
# prints out for s: alison hack, Alison hack, Alison Hack


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

"""
@Author: lyzhang
@Date:
@Description:
"""
import torch
from config import *
import torch.nn as nn
torch.manual_seed(SEED)

class MLP(nn.Module):
    def __init__(self, input_size=None, output_size=None, hidden_size=None, num_layers=None, use_sig=True):
        nn.Module.__init__(self)
        input_size = input_size if input_size is not None else mlp_input_size
        hidden_size = hidden_size if hidden_size is not None else int(input_size / 2)
        num_layers = num_layers if num_layers is not None else MLP_LAYERS
        output_size = output_size if output_size is not None else Transition_num
        self.use_sig = use_sig

        # part one
        # linear probability
        self.linear_logits = nn.Linear(input_size, output_size)

        # part two
        # input to first hidden
        self.input_linear = nn.Linear(input_size, hidden_size)
        self.input_dropout = nn.Dropout(p=mlp_dropout)
        self.input_activation = nn.ReLU()

        # multi hidden layers
        self.linears = nn.ModuleList([nn.Linear(hidden_size, hidden_size) for _ in range(num_layers - 2)])
        self.dropouts = nn.ModuleList([nn.Dropout(p=mlp_dropout) for _ in range(num_layers - 2)])
        self.activations = nn.ModuleList([nn.ReLU() for _ in range(num_layers - 2)])

        # probabilities
        self.logits = nn.Linear(hidden_size, output_size)

    def forward(self, input_values):
        if MLP_LAYERS == 1:
            output = self.linear_logits(input_values)
        else:
            hidden = self.input_linear(input_values)
            hidden = self.input_dropout(hidden)
            hidden = self.input_activation(hidden)
            # hidden layers
            for linear, dropout, activation in zip(self.linears, self.dropouts, self.activations):
                hidden = linear(hidden)
                hidden = dropout(hidden)
                hidden = activation(hidden)
            # sigmoid output layer
            output = self.logits(hidden)
        sig_output = output if not self.use_sig else torch.tanh(output)
        return sig_output


import matplotlib.pyplot as plt
import numpy as np
import math
from PIL import Image
#import cPickle as pkl
import _pickle as cPickle
import time
import tensorflow as tf
import tensorflow.examples.tutorials.mnist.input_data as input_data
import glob
#%matplotlib inline
print ("Packages loaded")

############ LOAD DATASET #############################################

dirpath = "/home/saurabh/Documents/data/iccv09Data/images/"
height = 240
width  = 320
resize_ratio = 3
nr_img = 0
fileList = glob.glob(dirpath + '*.jpg')
for i, file in enumerate(fileList):
    img = Image.open(file)
    array = np.array(img)
    if array.shape[0] == height and array.shape[1] == width:
        nr_img = nr_img + 1
        rgb = array.reshape(1, height, width, 3)
        imglow = img.resize((int(width/resize_ratio)
                ,int(height/resize_ratio)), Image.BICUBIC)
        imglow = imglow.resize((width, height), Image.BICUBIC)
        rgblow = np.array(np.float32(imglow)/255.)
        rgblow = rgblow.reshape(1, height, width, 3)
        rgb = np.reshape(rgb, [1, -1])
        rgblow = np.reshape(rgblow, [1, -1])
        if nr_img == 1:
            data = rgb
            datalow = rgblow
        else:
            data = np.concatenate((data, rgb), axis=0)
            datalow = np.concatenate((datalow, rgblow), axis=0)

print ("nr_img is %d" % (nr_img))
print ("Shape of 'data' is %s" % (data.shape,))
print ("Shape of 'datalow' is %s" % (datalow.shape,))

########################## DIVIDE in 2 TRAIN/ TEST SETS ##########################
##########################(xtrain, ytrain) and (xtest, ytest) ####################

randidx = np.random.permutation(nr_img)
nrtrain = int(nr_img*0.7)
nrtest  = nr_img - nrtrain
xtrain  = datalow[randidx[0:nrtrain], :]
ytrain  = data[randidx[0:nrtrain], :]
xtest   = datalow[randidx[nrtrain:nr_img], :]
ytest   = data[randidx[nrtrain:nr_img], :]
print ("Shape of 'xtrain' is %s" % (xtrain.shape,))
print ("Shape of 'ytrain' is %s" % (ytrain.shape,))
print ("Shape of 'xtest' is %s" % (xtest.shape,))
print ("Shape of 'ytest' is %s" % (ytest.shape,))

########################## DEFINE THE NETWORK #####################################

n1 = 32
n2 = 64
n3 = 64
n4 = 64
n5 = 64
n6 = 3
ksize = 3
weights = {
    'ce1': tf.Variable(tf.random_normal([ksize, ksize, 3, n1],  stddev=0.01)),
    'ce2': tf.Variable(tf.random_normal([ksize, ksize, n1, n2], stddev=0.01)),
    'ce3': tf.Variable(tf.random_normal([ksize, ksize, n2, n3], stddev=0.01)),
    'ce4': tf.Variable(tf.random_normal([ksize, ksize, n3, n4], stddev=0.01)),
    'ce5': tf.Variable(tf.random_normal([ksize, ksize, n4, n5], stddev=0.01)),
    'ce6': tf.Variable(tf.random_normal([ksize, ksize, n5, n6],  stddev=0.01))
}
biases = {
    'be1': tf.Variable(tf.random_normal([n1], stddev=0.01)),
    'be2': tf.Variable(tf.random_normal([n2], stddev=0.01)),
    'be3': tf.Variable(tf.random_normal([n3], stddev=0.01)),
    'be4': tf.Variable(tf.random_normal([n4], stddev=0.01)),
    'be5': tf.Variable(tf.random_normal([n5], stddev=0.01)),
    'be6': tf.Variable(tf.random_normal([n6], stddev=0.01))
}
def srn(_X, _W, _b, _keepprob):
    _input_r = tf.reshape(_X, shape=[-1, height, width, 3])
    # Encoder
    _ce1 = tf.nn.relu(tf.add(tf.nn.conv2d(_input_r, _W['ce1']
        , strides=[1, 1, 1, 1], padding='SAME'), _b['be1']))
    _ce1 = tf.nn.dropout(_ce1, _keepprob)
    _ce2 = tf.nn.relu(tf.add(tf.nn.conv2d(_ce1, _W['ce2']
        , strides=[1, 1, 1, 1], padding='SAME'), _b['be2']))
    _ce2 = tf.nn.dropout(_ce2, _keepprob)
    _ce3 = tf.nn.relu(tf.add(tf.nn.conv2d(_ce2, _W['ce3']
        , strides=[1, 1, 1, 1], padding='SAME'), _b['be3']))
    _ce3 = tf.nn.dropout(_ce3, _keepprob)

    _ce4 = tf.nn.relu(tf.add(tf.nn.conv2d(_ce3, _W['ce4']
        , strides=[1, 1, 1, 1], padding='SAME'), _b['be4']))
    _ce4 = tf.nn.dropout(_ce4, _keepprob)
    _ce5 = tf.nn.relu(tf.add(tf.nn.conv2d(_ce4, _W['ce5']
        , strides=[1, 1, 1, 1], padding='SAME'), _b['be5']))
    _ce5 = tf.nn.dropout(_ce5, _keepprob)
    _ce6 = tf.nn.relu(tf.add(tf.nn.conv2d(_ce5, _W['ce6']
        , strides=[1, 1, 1, 1], padding='SAME'), _b['be6']))
    _out = _ce6 + _input_r
    return {'input_r': _input_r, 'ce1': _ce1, 'ce2': _ce2, 'ce3': _ce3
        , 'ce4': _ce4, 'ce5': _ce5, 'ce6': _ce6
        , 'layers': (_input_r, _ce1, _ce2, _ce3, _ce4, _ce5, _ce6)
        , 'out': _out}
print ("Network ready")

########################## DEFINE THE FUNCTIONS #####################################

dim = height*width*3
x = tf.placeholder(tf.float32, [None, dim])
y = tf.placeholder(tf.float32, [None, dim])
keepprob = tf.placeholder(tf.float32)
pred = srn(x, weights, biases, keepprob)['out']
cost = tf.reduce_mean(tf.square(srn(x, weights, biases, keepprob)['out']
            - tf.reshape(y, shape=[-1, height, width, 3])))
learning_rate = 0.001
optm = tf.train.AdamOptimizer(learning_rate, 0.9).minimize(cost)
init = tf.initialize_all_variables()
print ("Functions ready")

########################## RUN TF ###################################################

sess = tf.Session()
sess.run(init)
# Fit all training data
batch_size = 1
n_epochs   = 10000
recon_images = []
train_error = []
test_error = []
print("Strart training..")
randidx = np.random.randint(nrtrain, size=batch_size)
batch_xs = xtrain[randidx, :]
batch_ys = ytrain[randidx, :]
for epoch_i in range(n_epochs):
    for batch_i in range(nrtrain // batch_size):
        randidx = np.random.randint(nrtrain, size=batch_size)
        batch_xs = xtrain[randidx, :]
        batch_ys = ytrain[randidx, :]
        sess.run(optm, feed_dict={x: batch_xs
            , y: batch_ys, keepprob: 0.7})
    #if (epoch_i % 10) == 0:
        #print("==========>")
        #print ("[%02d/%02d] cost: %.4f" % (epoch_i, n_epochs
         #   , sess.run(cost, feed_dict={x: batch_xs
        #  , y: batch_ys, keepprob: 1.})))

        # TO DO : Put the epoch no and Cost in a dict and plot via matplot
    if (epoch_i % 10) == 0:
        print ("[%02d/%02d] cost: %.4f" % (epoch_i, n_epochs
            , sess.run(cost, feed_dict={x: batch_xs
            , y: batch_ys, keepprob: 1.})))
        n_examples = 2
        print ("Training dataset")
        randidx = np.random.randint(nrtrain, size=n_examples)
        train_xs = xtrain[randidx, :]
        train_ys = ytrain[randidx, :]
        recon = sess.run(pred, feed_dict={x: train_xs, keepprob: 1.})

        ##### Training error ################
        #err1 = sess.run(cost, feed_dict = {x:batch_xs, y: batch_ys, keepprob: 1.})
        err1 = sess.run(cost, feed_dict = {x:train_xs, y: train_ys, keepprob: 1.})
        train_error.append(err1)
        #print("The train error is:", train_error)

        fig, axs = plt.subplots(3, n_examples, figsize=(15, 20))
        for example_i in range(n_examples):
            axs[0][example_i].imshow(np.reshape(
                train_xs[example_i, :], (height, width, 3)))
            axs[1][example_i].imshow(np.reshape(
                recon[example_i, :], (height, width, 3)))
            axs[2][example_i].imshow(np.reshape(
                train_ys[example_i, :], (height, width, 3)))
        plt.show()

        print ("Test dataset")
        randidx = np.random.randint(nrtest, size=n_examples)
        test_xs = xtest[randidx, :]
        test_ys = ytest[randidx, :]
        recon = sess.run(pred, feed_dict={x: test_xs, keepprob: 1.})

        # Test Error
        err2 = sess.run(cost, feed_dict = {x: test_xs, y: test_ys, keepprob: 1.})
        test_error.append(err2)
        #print("The test err is:",test_error)

        fig, axs = plt.subplots(3, n_examples, figsize=(15, 20))
        for example_i in range(n_examples):
            axs[0][example_i].imshow(np.reshape(
                test_xs[example_i, :], (height, width, 3)))
            axs[1][example_i].imshow(np.reshape(
                recon[example_i, :], (height, width, 3)))
            #recon_images.append(axs[1])
            axs[2][example_i].imshow(np.reshape(
                test_ys[example_i, :], (height, width, 3)))
        plt.show()
        #for i in range(0, recon_images):
            #print(recon_images[i])
            #print(i)
print("Training done. ")
print("the train error is......", err1)
plt.plot(train_error)
print("the TEST error is:......", err2)
plt.plot(test_error)
plt.grid(True)
plt.show()


from fastapi import APIRouter, Depends, Response
from fastapi_jwt_auth import AuthJWT

from server.models import User, UserOut, UserUpdate
from server.utils.current_user import current_user

router = APIRouter(
    prefix="/users",
    tags=["users"]
)

@router.get("", response_model=UserOut)
async def get_user(user: User = Depends(current_user)):
    return user

@router.patch("", response_model=UserOut)
async def update_user(update: UserUpdate, user: User = Depends(current_user)):
    user = user.copy(update=update.dict(exclude_unset=True))
    await user.save()
    return user

@router.delete("")
async def delete_user(auth: AuthJWT = Depends()):
    auth.jwt_required()
    await User.find_one(User.email == auth.get_jwt_subject()).delete()
    return Response(status_code=204)


import json.decoder

import grpc
import bankingsystem_pb2
import bankingsystem_pb2_grpc
from concurrent import futures
import multiprocessing
from google.protobuf.json_format import MessageToDict
import json
from BankingSystemUtility import log_msg, initializeLogging, parseInputFile, getProcessId, parseLocalArgs, \
    translateEntityToEnum
from time import sleep

class Branch(bankingsystem_pb2_grpc.TransactionServicer):
    # constants for sub-events names
    WITHDRAW_REQUEST = 'withdraw_request'
    WITHDRAW_EXECUTE = 'withdraw_execute'
    WITHDRAW_PROPAGATE_REQUEST = 'withdraw_propagate_request'
    WITHDRAW_PROPAGATE_EXECUTE = 'withdraw_propagate_execute'
    WITHDRAW_PROPAGATE_RESPONSE = 'withdraw_propagate_response'
    WITHDRAW_RESPONSE = 'withdraw_response'

    DEPOSIT_REQUEST = 'deposit_request'
    DEPOSIT_EXECUTE = 'deposit_execute'
    DEPOSIT_PROPAGATE_REQUEST = 'deposit_propagate_request'
    DEPOSIT_PROPAGATE_EXECUTE = 'deposit_propagate_execute'
    DEPOSIT_PROPAGATE_RESPONSE = 'deposit_propagate_response'
    DEPOSIT_RESPONSE = 'deposit_response'

    def __init__(self, id, balance, branches):
        # unique ID of the Branch
        self.id = id
        # replica of the Branch's balance
        self.balance = balance
        # the list of process IDs of the branches
        self.branches = branches
        # the list of Client stubs to communicate with the branches
        self.stubList = list()
        # a list of received messages used for debugging purpose
        self.recvMsg = list()
        # This will keep track of the branch's internal logical clock as per Lamport algorithm.
        self.clock = 0
        # This dictionary will record all the sub-events happening on the incoming requests along with the timestamps.
        self.branchSubEventData = {'pid': self.id, 'data': list()}

    def MsgDelivery(self, request, context):
        """
        The RPC call to handle the incoming requests.
        :param request: un-marsheled BankRequest received by the RPC call.
        :param context: Server context
        :return: BankResponse
        """
        log_msg('request::' + json.dumps(MessageToDict(request)))
        responseList = list()
        # protobuf does not translate ZERO values. This is to make sure if that happens we have a default request
        # clock value so we can increment it.
        if not request.clock:
            request.clock = 0
        eventId = 0
        eventInterface = 0
        for event in request.events:
            # we are only interested in deposit and withdraw interface for propagation. This will keep track of that
            if bankingsystem_pb2.deposit == event.interface or bankingsystem_pb2.withdraw == event.interface:
                eventInterface = event.interface
                eventId = event.id
            # Query interface
            if bankingsystem_pb2.query == event.interface:
                # Mandatory sleep after query interface so the results can be propagated.
                sleep(3)
                responseList.append(self.query())
            # deposit interface
            elif bankingsystem_pb2.deposit == event.interface:
                # syncing clock on the eventReceive sub-event
                self.clockEventRequest(request.clock)
                # logging the sub-event
                self.logBranchSubEventData(eventId=event.id, subEventName=self.DEPOSIT_REQUEST)
                # executing the deposit interface
                depositResponse = self.deposit(event)
                # adding the response of deposit to list to construct the final response for this request
                responseList.append(depositResponse)
                # calling the function to propagate if the response of the deposit was successful.
                self.propagateIfOperationSuccessful(depositResponse, event, bankingsystem_pb2.propagate_deposit)
            # withdraw interface
            elif bankingsystem_pb2.withdraw == event.interface:
                # syncing clock on the eventReceive sub-event
                self.clockEventRequest(request.clock)
                # logging the sub-event
                self.logBranchSubEventData(eventId=event.id, subEventName=self.WITHDRAW_REQUEST)
                # executing the withdraw interface
                withdrawRes = self.withdraw(event)
                # adding the response of withdraw to list to construct the final response for this request
                responseList.append(withdrawRes)
                # calling the function to propagate if the response of the deposit was successful.
                self.propagateIfOperationSuccessful(withdrawRes, event, bankingsystem_pb2.propagate_withdraw)
            # propagate deposit interface
            elif bankingsystem_pb2.propagate_deposit == event.interface:
                # syncing clock on the Propagate_Request sub-event
                self.clockPropagateRequest(request.clock)
                # logging the sub-event
                self.logBranchSubEventData(eventId=event.id, subEventName=self.DEPOSIT_PROPAGATE_REQUEST)
                # adding the response to list to construct the final response for this request
                responseList.append(self.handlePropagateDeposit(event))
            # propagate withdraw interface
            elif bankingsystem_pb2.propagate_withdraw == event.interface:
                # syncing clock on the Propagate_Request sub-event
                self.clockPropagateRequest(request.clock)
                # logging the sub-event
                self.logBranchSubEventData(eventId=event.id, subEventName=self.WITHDRAW_PROPAGATE_REQUEST)
                # adding the response to list to construct the final response for this request
                responseList.append(self.handlePropagateWithdraw(event))

        log_msg('going to log {0} for event id {1}'.format(str(eventInterface), str(eventId)))
        # if the interface is withdraw or deposit then we sync the clock for eventResponse and log the sub-events
        if bankingsystem_pb2.withdraw == eventInterface:
            log_msg('Logging withdraw')
            self.clockEventResponse()
            self.logBranchSubEventData(eventId=eventId, subEventName=self.WITHDRAW_RESPONSE)
        elif bankingsystem_pb2.deposit == eventInterface:
            log_msg('Logging deposit')
            self.clockEventResponse()
            self.logBranchSubEventData(eventId=eventId, subEventName=self.DEPOSIT_RESPONSE)

        # writing the branch output to the file as json
        self.writeServerOutPut()
        # constructing the final response
        bankResponse = bankingsystem_pb2.BankResponse(id=request.id, recv=responseList, clock=self.clock)

        log_msg('Response from Branch#{0}:{1}'.format(self.id, json.dumps(MessageToDict(bankResponse))))
        log_msg('*' * 20)
        log_msg(json.dumps(self.branchSubEventData))
        log_msg('*' * 20)
        return bankResponse

    def writeServerOutPut(self):
        """
        Writes the subevent data is desired format to the output json file.
        :return: None
        """
        log_msg('^' * 20)
        dataToWrite = list()
        outFileName = "serverOut.json"
        branchFound = False
        # this list will contain all the subevents fro the branches, we can sort it later on based on clock values
        events = list()
        try:
            with open(outFileName, "r") as file:
                existingData = json.load(file)
                log_msg('Existing data in {0} file ->{1}'.format(outFileName, existingData))
                for d in existingData:
                    # the output json file can contain two type of objects, one for branches and other for events
                    # at this point we are trying to gather the branch data only. We can construct
                    # the event data based on the branch data later on
                    if 'pid' in d:
                        # update the 'data' field only if the branch id is same as pid
                        if d['pid'] == self.id:
                            d['data'] = self.branchSubEventData['data']
                            branchFound = True
                        dataToWrite.append(d)
                        # add to list so we can construct event data later on
                        events.extend(d['data'])
                    else:
                        log_msg('Not branch data{0}'.format(d))
                # it means the existing data in json file is not for the branch currently running. We need to
                # add it to final data
                if not branchFound:
                    dataToWrite.append(self.branchSubEventData)
                    events.extend(self.branchSubEventData['data'])
        except Exception as err:
            # First time around we might not have the file, so will get file not found exception here
            log_msg('------>{0}'.format(err))
            # but we need to add data so we can write it for the first time
            dataToWrite.append(self.branchSubEventData)
            events.extend(self.branchSubEventData['data'])
            pass
        # adding the subevent data sorted by clock to the final dict to be written to the file
        dataToWrite.extend(self.makeSortedEventData(events))
        # writing to file
        outfile = open(outFileName, 'w')
        json.dump(dataToWrite, outfile)
        outfile.close()
        log_msg('^' * 20)
        # cautionary sleep after writing to the file
        sleep(1)

    def makeSortedEventData(self, events):
        """
        This function will receive the subevents data from the all the branches happened so far read from the output
        json file. We will sort the available data as per the clock values and group them by the event IDs
        :param events: List of all the subevents
        :return: list of dictionaries grouped by events and sorted by clock values
        """
        finalResult = {}
        # sorting the subevents by the clock values regardless to the eventIds
        events = sorted(events, key=lambda i: i['clock'])
        for eventData in events:
            # making the event Id as key in order to create the unique entries
            mainKey = str(eventData['id'])
            # if a event was not already in the list we will need to create it
            if mainKey not in finalResult:
                finalResult[mainKey] = {'eventid': eventData['id'], 'data': list()}

            # adding the subevent data
            finalResult[mainKey]['data'].append({'clock': eventData['clock'], 'name': eventData['name']})

        return list(finalResult.values())

    def logBranchSubEventData(self, eventId, subEventName):
        """
        This will populate the self.branchSubEventData for all the subevents along with the eventId and clock details
        :param eventId: Unique ID of the event
        :param subEventName: Name of sub event
        :return: None
        """
        self.branchSubEventData['data'].append({'id': eventId, 'name': subEventName, 'clock': self.clock})
        self.branchSubEventData['data'] = sorted(self.branchSubEventData['data'], key=lambda i: i['clock'])

    def query(self):
        """

        :return:
        """
        log_msg('-----QUERY-------')
        res = {'interface': bankingsystem_pb2.query, 'result': bankingsystem_pb2.success, 'money': self.balance}
        return res

    def deposit(self, event):
        """
        Depositing the money to the branch. And calling the eventExecute sub-interface. This function will also log the
        subevent.
        :param event: The incoming event which contains the money and event IDs
        :return: outputEvent in dictionary form
        """
        log_msg('-----DEPOSIT-------')
        if event.money > 0:
            self.balance += event.money
            opResult = bankingsystem_pb2.success
        else:
            log_msg('Deposit amount negative.Operation failed.')
            opResult = bankingsystem_pb2.failure

        # logging and calling the eventExecute interface
        self.clockEventExecute()
        self.logBranchSubEventData(eventId=event.id, subEventName=self.DEPOSIT_EXECUTE)

        return {'interface': bankingsystem_pb2.deposit, 'result': opResult}

    def withdraw(self, event):
        """
        Withdrawing money from the branch. And calling the eventExecute sub-interface. This function will also log the
        subevent.
        :param event: The incoming event which contains the money and event IDs
        :return: outputEvent in dictionary form
        """
        log_msg('-----WITHDRAW-------')
        if event.money < 0 or self.balance - event.money < 0:
            log_msg('Insufficient funds for Withdraw.Operation failed.')
            opResult = bankingsystem_pb2.failure
        else:
            self.balance -= event.money
            opResult = bankingsystem_pb2.success

        # logging and calling the eventExecute interface
        self.clockEventExecute()
        self.logBranchSubEventData(eventId=event.id, subEventName=self.WITHDRAW_EXECUTE)

        return {'interface': bankingsystem_pb2.withdraw, 'result': opResult}

    def propagateIfOperationSuccessful(self, operationResponse, event, propagateOperation):
        """
        Propage the interface if operation was successful. And advances the clock
        :param operationResponse:
        :param event:
        :param propagateOperation:
        :return:
        """
        if operationResponse['result'] == bankingsystem_pb2.success:
            self.propagateEvent(propagateOperation, event.money, event.id)
        else:
            log_msg('{0} operation failed. No propagation required.'.format(event.interface))

    def handlePropagateDeposit(self, event):
        """
        Handle the deposit propagation request and call the subevent Propagate_Execute.It will also log
            deposit_propagate_execute
        :param event:
        :return:
        """
        log_msg('-----Handling Propagated Deposit-------')
        self.balance += event.money
        # calling and logging Propagate_Execute
        self.clockPropagateExecute()
        self.logBranchSubEventData(eventId=event.id, subEventName=self.DEPOSIT_PROPAGATE_EXECUTE)
        return {'interface': bankingsystem_pb2.propagate_deposit, 'result': bankingsystem_pb2.success}

    def handlePropagateWithdraw(self, event):
        """
        Handle the withdraw propagation request and call the subevent Propagate_Execute.It will also log
        withdraw_propagate_execute
        :param event:
        :return:
        """
        log_msg('-----Handling Propagated Withdraw-------')
        self.balance -= event.money
        # calling and logging Propagate_Execute
        self.clockPropagateExecute()
        self.logBranchSubEventData(eventId=event.id, subEventName=self.WITHDRAW_PROPAGATE_EXECUTE)
        return {'interface': bankingsystem_pb2.propagate_withdraw, 'result': bankingsystem_pb2.success}

    def propagateEvent(self, eventType, amount, eventId):
        """
        This function is called when withdraw or deposit operation is successful. This will propagate that operation
        to other branches. This function will also call and log the subinterface PROPAGATE_RESPONSE when response is
        received from propagation.
        :param eventType:
        :param amount:
        :return:
        """
        log_msg(f'-----Propagating Event {eventType} for amount {amount}-------')
        for bid in self.branches:
            portId = getProcessId(bid)

            log_msg('Propagating to branch {0} on port {1}'.format(bid, portId))
            with grpc.insecure_channel(f'localhost:{str(portId)}') as channel:
                stub = bankingsystem_pb2_grpc.TransactionStub(channel)
                req = [{"id": eventId, "interface": eventType, "money": amount}]
                response = stub.MsgDelivery(
                    bankingsystem_pb2.BankRequest(id=bid, type=bankingsystem_pb2.branch, events=req,
                                                  clock=self.clock))
                log_msg('Response on propagation {0} from branch {1}'.format(json.dumps(MessageToDict(response)), bid))

                # calling the PROPAGATE_RESPONSE sub event and loggin it
                self.clockPropagateResponse(response.clock)
                if eventType == bankingsystem_pb2.propagate_withdraw:
                    self.logBranchSubEventData(eventId=eventId, subEventName=self.WITHDRAW_PROPAGATE_RESPONSE)
                elif eventType == bankingsystem_pb2.propagate_deposit:
                    self.logBranchSubEventData(eventId=eventId, subEventName=self.DEPOSIT_PROPAGATE_RESPONSE)

    def __str__(self):
        return "BRANCH[id = {0}, balance = {1} , branches = {2} , tick={3}".format(self.id,
                                                                                self.balance,
                                                                                str(self.branches), str(self.clock))

    def clockEventRequest(self, remoteClock):
        """
        This is implementation of first subinterface Event_Request and propagationRecieved. This subevent happens
        when the Branch process receives a request from the Customer process.
        The Branch process selects the larger value between the local clock
        and the remote clock from the message, and increments one from the selected value.
        :param remoteClock: Remote clock
        :return: None
        """
        self.selectMaxClockAndAdvance(remoteClock=remoteClock, subEventName="Event_Request")

    def clockEventExecute(self):
        """
        This is implementation of second subinterface Event_Execute.This subevent happens when the Branch process
        executes the event after the subevent  “Event Request”. The Branch process increments one from its local clock.
        :return: None
        """
        self.advanceClock("Event_Execute")

    def clockPropagateRequest(self, remoteClock):
        """
        Implantation of third subinterface Propagate_Request.This subevent happens when the
        Branch process recieves the propagation request from its fellow branch processes.
        The Branch process selects the larger value between the local clock
        and the remote clock from the message, and increments one from the selected value.
        :param remoteClock: Remote clock
        :return: None
        """
        self.selectMaxClockAndAdvance(remoteClock=remoteClock, subEventName="Propagate_Request")

    def clockPropagateResponse(self, remoteClock):
        """
        Implantation of fourth subinterface Propagate_Response.
        This subevent happens when the Branch receives the result of the subevent
        “Propogate_Execute” from its fellow branches.
        The Branch process selects the biggest value between the
        local clock and the remote clock from the message, and increments one from the selected value.
        :param remoteClock: Remote clock
        :return: None
        """
        self.selectMaxClockAndAdvance(remoteClock=remoteClock, subEventName="Propagate_Response")

    def clockPropagateExecute(self):
        """
        Implantation of fifth subinterface Propogate_Execute.
        This subevent happens when the Branch process executes the event after the subevent “Propogate_Request”.
        The Branch process increments one from its local clock.
        :return: None
        """
        self.advanceClock("Propogate_Execute")

    def clockEventResponse(self):
        """
        Implantation of sixth subinterface Event_Response.
        This subevent happens after all the propagation responses are returned from the branches.
        The branch returns success / fail back to the Customer process.
        The Branch process increments one from its local clock.
        :return: None
        """
        self.advanceClock("Event_Response")

    def advanceClock(self, subEventName):
        """
        Advance the clock by 1 tick
        :param subEventName: sub-event name for logging purposes
        :return: None
        """
        self.clock += 1
        log_msg("CLOCK:{0}:{1}".format(subEventName, str(self.clock)))

    def selectMaxClockAndAdvance(self, remoteClock, subEventName):
        """
        Take the maximum of the remote clock and local clock and advance by 1 tick.
        :param remoteClock: Remote clock value
        :param subEventName: sub-event name for logging purposes
        :return: None
        """
        self.clock = max(self.clock, remoteClock)
        self.advanceClock(subEventName)

def extractBranchData(parsedData):
    branches = list()
    branchIds = list()
    for data in parsedData:
        log_msg(data)
        if bankingsystem_pb2.branch == translateEntityToEnum(data['type']):
            log_msg('its a branch with id : %s' % data['id'])
            branches.append(Branch(id=data['id'], balance=data['balance'], branches=None))
            branchIds.append(data['id'])

    for branch in branches:
        branch.branches = [id for id in branchIds if branch.id != id]
        log_msg(branch)

    return branches

def startBranch(branch):
    portNumber = getProcessId(branch.id)
    log_msg(
        'Starting Branch server for {0} with balance {1} on port {2}'.format(branch.id, branch.balance, portNumber))
    options = (('grpc.so_reuseport', 1),)
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10), options=options)
    bankingsystem_pb2_grpc.add_TransactionServicer_to_server(branch, server)
    server.add_insecure_port('[::]:{0}'.format(portNumber))
    server.start()
    server.wait_for_termination()
    log_msg("--------" * 40)
    log_msg(branch.branchEventData)
    log_msg("--------" * 40)

if __name__ == '__main__':
    initializeLogging()
    inputFile = parseLocalArgs()
    branches = extractBranchData(parseInputFile(inputFile[0]))

    workers = []
    for branch in branches:
        # NOTE: It is imperative that the worker subprocesses be forked before
        # any gRPC servers start up. See
        # https://github.com/grpc/grpc/issues/16001 for more details.
        worker = multiprocessing.Process(target=startBranch,
                                         args=(branch,))
        worker.start()
        workers.append(worker)
    for worker in workers:
        worker.join()


import pyzbar.pyzbar as pyzbar
from gtts import gTTS
from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import os
import pandas as pd

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

def say(visitor):
    ss2 = gTTS(text=visitor.name.get_values()[0], lang='vi')
    with open('name.mp3', 'wb') as f:
        ss2.write_to_fp(f)
    os.system("mpg321 hello.mp3")
    os.system("mpg321 name.mp3")
    if visitor.gender.get_values()[0] == 'male':
        os.system("mpg321 boy.mp3")
    else:
        os.system("mpg321 girl.mp3")
    os.system("mpg321 welcomes.mp3")

df = pd.read_csv('visitors.csv')
csv_edit_time = os.path.getmtime('visitors.csv')
camera = PiCamera()
camera.resolution = (480, 320)
rawCapture = PiRGBArray(camera)
privious_data = []
camera.start_preview(fullscreen=False, window=(100,20,480,320))
for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
    try:
        if os.path.getmtime('visitors.csv') > csv_edit_time:
            df = pd.read_csv('visitors.csv')
            csv_edit_time = os.path.getmtime('visitors.csv')
        frame = rawCapture.array
        decodedObjects = pyzbar.decode(frame)
        if decodedObjects != []:
            for obj in decodedObjects:
                if obj.data != privious_data:
                    print('Type : ', obj.type)
                    print('Data : ', obj.data, '\n')
                    qr_id = obj.data.decode('utf8')
                    visitor = df.query("qr_id == @qr_id")
                    say(visitor)
                    privious_data = obj.data
        rawCapture.truncate(0)
    except:
        camera.stop_preview()
        break


from sourpea.primitives import *
from sourpea.util import *
import pandas as pd
import os
_dir=os.path.dirname(__file__)
### DERIVED FACTORS
fmq = Factor("fmq", ["cvsb","yerlnd","bbnyn","jfg","ivw"])
def auxcng(fmq):
    return fmq != "cvsb" or fmq != "yerlnd"
def xxv(fmq):
    return fmq == "cvsb" and fmq == "yerlnd"
nemurp = DerivedLevel("xldt", WithinTrial(auxcng, [fmq]))
rbseii = DerivedLevel("fxq", WithinTrial(xxv, [fmq]))
rxlaam = Factor("kkvmaj", [nemurp, rbseii])

### EXPERIMENT
design=[fmq,rxlaam]
crossing=[rxlaam]
### APPENDIX
block=Block(design,crossing,[])
sequence_code_1=trials_from_csv(os.path.join(_dir,"out_code_1/2_1_2_0.csv"))
nr_input_factors=1
nr_output_levels=2
test_code_1=block.test(sequence_code_1)
try:
	sequence_code_2=trials_from_csv(os.path.join(_dir,"out_code_2/2_1_2_0.csv"))
	test_code_2=block.test(sequence_code_2)
except:
	test_code_2={"pValue":0}
df=pd.read_csv(os.path.join(_dir,"result_sour.csv"))
df.loc[len(df.index)] = [test_code_1["pValue"], test_code_2["pValue"], test_code_1["levels"], test_code_2["levels"], nr_input_factors, nr_output_levels]
df.to_csv(os.path.join(_dir,"result_sour.csv"), index=False)


"""Publicly accessible classes/routines."""

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from . import ensembles, lnpienergy, segment  # noqa: TCH004
    from .lnpidata import lnPiMasked  # noqa: TCH004
    from .lnpiseries import lnPiCollection  # noqa: TCH004
    from .options import OPTIONS, set_options  # noqa: TCH004
    from .segment import PhaseCreator  # noqa: TCH004
else:
    import lazy_loader as lazy

    __getattr__, __dir__, _ = lazy.attach(
        __name__,
        submodules=["ensembles", "lnpienergy", "segment"],
        submod_attrs={
            "lnpidata": ["lnPiMasked"],
            "lnpiseries": ["lnPiCollection"],
            "options": ["OPTIONS", "set_options"],
            "segment": ["PhaseCreator"],
        },
    )

# updated versioning scheme
try:
    from ._version import __version__
except Exception:
    __version__ = "999"

__author__ = """William P. Krekelberg"""
__email__ = "wpk@nist.gov"

__all__ = [
    "__author__",
    "__email__",
    "__version__",
    "lnPiMasked",
    "lnPiCollection",
    "segment",
    "ensembles",
    "lnpienergy",
    "PhaseCreator",
    "set_options",
    "OPTIONS",
]


import logging

from funcy import log_calls, log_errors

from server.apps.products.models import ProductAllotment, ProductAvailability

@log_calls(logging.info, errors=False)
@log_errors(logging.exception)
def delete_availability_records(allotment_record: ProductAllotment):
    logging.info(
        f"Deleting availabilities for allotment {allotment_record.allotment_id}"
    )
    _delete_availabilities_from_deleted_allotment(allotment_record)

    logging.info(f"Availability {allotment_record.allotment_id} deleted")

def _delete_availabilities_from_deleted_allotment(allotment_record: ProductAllotment):
    ProductAvailability.objects.filter(
        allotments_id__contains=[allotment_record.allotment_id]
    ).delete()


from django.urls import path

from .views import StuffList, RentalList, StuffDetailView, RentalDetailView, StuffCreateView, \
    MyRentalListView, MyStuffListView, index, categories_posts, StuffUpdateView, StuffDeleteView, RentalDeleteView, \
    RentalUpdateView, RequestRentalList

app_name = 'bilyeo'

urlpatterns = [
    path('', index, name='index'),
    path('stuff_list/', StuffList.as_view(), name='stuff_list'),
    path('stuff/create/', StuffCreateView.as_view(), name='stuff_create'),
    path('stuff/<int:pk>/', StuffDetailView.as_view(), name='stuff_detail'),
    path('stuff/<int:pk>/update/', StuffUpdateView.as_view(), name='stuff_update'),
    path('stuff/<int:pk>/delete/', StuffDeleteView, name='stuff_delete'),
    path('stuff/category/<str:slug>/', categories_posts, name='category_list'),
    path('rental/<int:pk>/', RentalDetailView.as_view(), name='rental_detail'),
    path('rental/<int:pk>/delete/', RentalDeleteView, name='rental_delete'),
    path('rental/<int:pk>/update/', RentalUpdateView.as_view(), name='rental_update'),
    path('rental_list/', RentalList.as_view(), name='rental_list'),
    path('request_list/', RequestRentalList.as_view(), name='request_list'),
    path('my_rental_list/', MyRentalListView.as_view(), name='my_rental_list'),
    path('my_stuff_list/', MyStuffListView.as_view(), name='my_stuff_list'),
]


class MinStack:

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.stk = []
        self.mstk = []

    def push(self, x: int) -> None:
        self.stk.append(x)
        if not self.mstk or self.mstk[-1] >= x:
            self.mstk.append(x)

    def pop(self) -> None:
        res = self.stk.pop()
        if self.mstk and res == self.mstk[-1]:
            self.mstk.pop()

    def top(self) -> int:
        return self.stk[-1]

    def min(self) -> int:
        return self.mstk[-1]

# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.min()

def test1():
    mstk = MinStack()
    mstk.push(-2)
    mstk.push(0)
    mstk.push(-3)
    res1 = mstk.min()  # -3
    mstk.pop()
    res2 = mstk.top()  # 0
    res3 = mstk.min()  # -2

    if (res1, res2, res3) == (-3, 0, -2):
        print('test1 success.')
    else:
        print('test1 failed.')

if __name__ == "__main__":
    test1()

# 定义栈的数据结构，请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中，
# 调用 min、push 及 pop 的时间复杂度都是 O(1)。

# 示例:

# MinStack minStack = new MinStack();
# minStack.push(-2);
# minStack.push(0);
# minStack.push(-3);
# minStack.min();   --> 返回 -3.
# minStack.pop();
# minStack.top();      --> 返回 0.
# minStack.min();   --> 返回 -2.

# 提示：

# 各函数的调用总次数不超过 20000 次