""" Test async track """
import os
from io import BytesIO

import mutagen
import pytest
import pytest_asyncio

from sclib.asyncio import SoundcloudAPI, Track

TEST_TRACK_URL = 'https://soundcloud.com/mt-marcy/cold-nights'
TEST_TRACK_TITLE = 'cold nights'
TEST_TRACK_ARTIST = 'mt. marcy'

@pytest.fixture(scope='session', name='async_api')
def async_client():
    """ client fixture """
    return SoundcloudAPI()

@pytest_asyncio.fixture(name='test_track')
async def track_fixture(async_api):
    """ Track fixture """
    return await async_api.resolve(TEST_TRACK_URL)

@pytest.mark.asyncio
async def test_resolve_track(async_api:SoundcloudAPI):
    """ test resolve """
    track = await async_api.resolve(TEST_TRACK_URL)
    assert type(track) is Track

@pytest.mark.asyncio
async def test_track_has_correct_attributes(test_track:Track):
    """ test correct attrs """
    assert test_track.title == TEST_TRACK_TITLE
    assert test_track.artist == TEST_TRACK_ARTIST

@pytest.mark.asyncio
async def test_track_accepts_correct_file_objects(async_api):
    """ test correct file objs """
    track = await async_api.resolve(TEST_TRACK_URL)
    filename = os.path.realpath('/tmp/faksjhflaksjfhlaksjfdhlkas.mp3')
    with open(filename, 'wb+') as mp3:
        await track.write_mp3_to(mp3)
    os.remove(filename)

    # Create file then open in rb+
    with open(filename, 'w'):  # pylint: disable=unspecified-encoding
        pass

    with open(filename, 'rb+') as mp3:
        await track.write_mp3_to(mp3)
    os.remove(filename)

    try:
        with open(filename, 'w') as file:  # pylint: disable=unspecified-encoding
            await track.write_mp3_to(file)
    except TypeError:
        pass

    try:
        with open(filename, 'wb') as file:
            await track.write_mp3_to(file)
    except ValueError:
        pass

    file = BytesIO()
    await track.write_mp3_to(file)
    assert file.__sizeof__() > 0

@pytest.mark.asyncio
async def test_track_writes_mp3_metadata(test_track:Track):
    """ test mp3 metadata """
    filename = 'test_track.mp3'
    with open(filename, 'wb+') as file:
        await test_track.write_mp3_to(file)

    mp3 = mutagen.File(filename)
    tags = mp3.tags

    #Check Title and Artist
    assert tags['TIT2'] == TEST_TRACK_TITLE
    assert tags['TPE1'] == TEST_TRACK_ARTIST

    # Check Cover Art
    cover_art = tags['APIC:Cover']  # type: mutagen.id3.APIC
    cover_art_data_actual = cover_art.data
    assert cover_art_data_actual.__sizeof__() > 0
    os.remove(filename)

@pytest.mark.asyncio
async def test_fetch_track_by_id_in_order(async_api: SoundcloudAPI):
    """ Test resolve in order """
    expected = [222820656, 153576776, 289589592, 268448230]
    tracks = await async_api.get_tracks(*expected)
    actual = [t['id'] for t in tracks]
    assert expected == actual


"""
Code example for publishing data to the Brewblox eventbus

Dependencies:
- paho-mqtt
"""

import json
import re
import subprocess
from random import random
from time import sleep

from paho.mqtt import client as mqtt

# 172.17.0.1 is the default IP address for the host running the Docker container
# Change this value if Brewblox is installed on a different computer
HOST = '172.17.0.1'

# 80 is the default port for HTTP, but this can be changed in brewblox env settings.
PORT = 80

# This is a constant value. You never need to change it.
HISTORY_TOPIC = 'brewcast/history'

# The history service is subscribed to all topics starting with 'brewcast/history'
# We can make our topic more specific to help debugging
TOPIC = HISTORY_TOPIC + '/pi-temperature'

# Create a websocket MQTT client
client = mqtt.Client(transport='websockets')
client.ws_set_options(path='/eventbus')

def check_cpu_temperature():
    raw_output = subprocess.check_output(
        ["/opt/vc/bin/vcgencmd", "measure_temp"]
    ).decode()
    output_matching = re.search("temp=([\d\.]+)'C", raw_output)
    return float(output_matching.group(1))

try:
    client.connect_async(host=HOST, port=PORT)
    client.loop_start()

    while True:
        message = {
            'key': 'pi-temperature',
            'data': {'temperature[degC]': check_cpu_temperature()}
        }

        client.publish(TOPIC, json.dumps(message))
        sleep(10)

finally:
    client.loop_stop()


import sys
import telnetlib
import subprocess
import ftplib

line4 = subprocess.check_output(["cmd","/c","chcp","437","&","tracert","-d","-h","1","1.1.1.1"]).decode().split("\r\n")[4].strip().split(" ")

for data in line4:
	if len(data.split(".")) == 4:
		router_ip_address = data
		break

try:
	ftp=ftplib.FTP(router_ip_address)
except:
	print ("ftp server not found")
	sys.exit(1)
try:
	file=open('data/ubootR4AGE.bin', 'rb')
except:
	print ("ubootR4AGE.bin not found")
	sys.exit(1)
print ("Uploading ubootR4AGE.bin ...")
ftp.storbinary(f'STOR /tmp/ubootR4AGE.bin', file)
file.close()
ftp.quit()
print ("Upload done")

tn = telnetlib.Telnet(router_ip_address)
tn.read_until(b"login:")
tn.write(b"root\n")
tn.read_until(b"root@XiaoQiang:~#")
print ("Writing Bootloader...")
tn.write(b"mtd -e Bootloader write /tmp/ubootR4AGE.bin Bootloader\n")
tn.read_until(b"root@XiaoQiang:~#")
tn.write(b"exit\n")
print ("Done")


# This script uses bmesh operators to make 2 links of a chain.

import bpy
import bmesh
import math
import mathutils
from mathutils import Vector
import os.path
import sys
from . import support

from .. import ROOT

# Make a new BMesh
bm = bmesh.new()

# ROOT = os.path.dirname(__file__)
print(ROOT)

PI = 3.14159265359

def create_te():
    bpy.ops.group.create(name="te1g")
    bpy.ops.mesh.primitive_uv_sphere_add(segments=32, ring_count=16, size=1)
    obj = bpy.context.object
    obj.name = 'te1'
    dim = obj.dimensions

    mat_high = bpy.data.materials.new("highlight")
    mat_high.diffuse_color = (float(.5), 0.0, 1.0)
    mat_origin = bpy.data.materials.new("highlight_origin")
    mat_origin.diffuse_color = (float(1.0), 0.0, 0.5)
    mat_norm = bpy.data.materials.new("normal")
    mat_norm.diffuse_color = (0.5, 0.5, 0.5)

    obj.active_material = mat_norm

    n = 1
    nsph = 4
    child = None
    all_child = []

    for z in range(0, nsph):
        for y in range(0, nsph):
            for x in range(0, nsph):
                if y%2 == 0:
                    iy = 0.0
                    ix = 0.0
                    iz = 0.0
                else:
                    iy = (dim.y/2.0) * y # + (dim.y * (y-1))
                    ix = 0.0
                    iz = 0.0
                ix = ((dim.x) * x) + ((dim.x/2.0) * y) + ((dim.x/2.0) * z)
                iy = ((dim.y/2.0) * y) + ((math.sqrt(dim.y)/2.0) * y) +  ((math.sqrt(dim.x)/2.0) * z)
                print(dim.z, math.sqrt(dim.z), dim.z/2.0)
                # FIXME: find correct height
                iz = (1.6 * z)

                if x >= nsph - y or \
                   x >= (nsph - y - z):
                    print("skip z:%s y:%s x:%s" % (z, y, x))
                    continue
                # if
                # if x <= y:
                #    continue

                bpy.ops.object.duplicate_move()
                child = bpy.context.object
                child.name = 'te1-%s' % n
                child.location = Vector((ix, iy, iz))
                bpy.ops.object.group_link(group="te1g")
                all_child.append(child)
                n += 1
                # https://de.wikipedia.org/wiki/F%C3%BCnfeck
                # we use the scalefactor a/2 ~ ri math.cos(54°)
                ri = (dim.x/2) / math.cos(0.942477796) #(dim.x)*math.sqrt((5-math.sqrt(5))/2)
                # FIXME: 0.08 is strange :)
                bpy.context.scene.cursor_location = (ix, iy + (ri/2)+0.08, iz + ri)

    child.active_material = mat_origin

    child.select = False
    obj.select = True
    child.name = 'te1'

    bpy.ops.object.delete()
    # change color of first one
    all_child[0].active_material = mat_high
    for child in all_child:
        child.select = True
    bpy.ops.object.join()
    bpy.ops.object.group_link(group="te1g")
    bpy.ops.object.origin_set(type='ORIGIN_CURSOR')
    # bpy.ops.object.name = "qp1"

    # bpy.scene.objects.unlink(obj)
    # bpy.data.objects.remove(obj)

def create_qp(common_gap=False):
    pass
    obj = bpy.data.objects['te1']
    obj.select = True

    obj.location = Vector((0.0, 0.0, 0.0))

    numseg = 5
    all_child = []

    for i in range(1, 6):
        bpy.ops.object.duplicate_move_linked()
        child = bpy.context.object
        all_child.append(child)

        child.rotation_mode = 'XYZ'

        # Euler((0.7545587420463562, 0.023988142609596252, 1.02032470703125), 'XYZ')
        # Vector((-1.4611425399780273, 0.9822003841400146, 0.7421605587005615))

        # ix = (obj.dimensions.x/1.3) * i * -1 #0.0 # 2.0 * i
        # iy = (obj.dimensions.x/3.0) * i # 2.0 * i
        ix = 0.0
        # ix = (dim.x/2) / math.cos(0.942477796)
        iy = 0.0
        cfact = 0.0
        if common_gap:
            # 0.128368966
            # 7.35500 deg = 0.128368966 radians
            # negative here as it is reduced rotation around the axis
            cfact = -(0.1283/numseg) * (i)
        angle_z =  (2.0*PI/float(numseg)) * (i) #(i*-1) * ((2 * pi)/5)
        angle_y =  (2.0*PI/float(numseg)) * (i) + cfact #(i*-1) * ((2 * pi)/5)
        angle_x =  (2.0*PI/float(numseg)) * (i)
        child.location = Vector((ix, iy, 0))
        # FIXME: the is strange
        child.rotation_euler = ( 1.013, angle_y, 0)
        # child.select = False
    child.select = False
    obj.select = True
    bpy.ops.object.delete()

    for c in all_child:
        c.select = True
    bpy.ops.object.join()
    child.name = 'qp1'

    # obj.delete()
def create_qb():
    obj = bpy.data.objects['qp1']
    obj.select = True

    obj.location = Vector((0.0, 0.0, 0.0))

    numseg = 12
    all_child = []

    return

    for i in range(1, 2):
        bpy.ops.object.duplicate_move_linked()
        child = bpy.context.object
        all_child.append(child)

        child.rotation_mode = 'XYZ'

        ix = 0.0
        # ix = (dim.x/2) / math.cos(0.942477796)
        iy = 0.0
        cfact = 0.0
        angle_z =  (2.0*PI/float(numseg)) * (i) #(i*-1) * ((2 * pi)/5)
        angle_y =  (2.0*PI/float(numseg)) * (i) + cfact #(i*-1) * ((2 * pi)/5)
        angle_x =  (2.0*PI/float(numseg)) * (i)
        child.location = Vector((ix, iy, 0))
        # FIXME: the is strange
        child.rotation_euler = ( angle_x, 0.0, 0)
        #bpy.context.scene.cursor_location = (ix, iy + (ri/2)+0.08, iz + ri)
        # child.select = False

def create_prism():
    support.clear_scene()
    create_te()
    create_qp(True)
    create_qb()

"""
# Add a circle XXX, should return all geometry created, not just verts.
bmesh.ops.create_circle(
        bm,
        cap_ends=False,
        diameter=0.2,
        segments=8)

# Spin and deal with geometry on side 'a'
edges_start_a = bm.edges[:]
geom_start_a = bm.verts[:] + edges_start_a
ret = bmesh.ops.spin(
        bm,
        geom=geom_start_a,
        angle=math.radians(180.0),
        steps=8,
        axis=(1.0, 0.0, 0.0),
        cent=(0.0, 1.0, 0.0))
edges_end_a = [ele for ele in ret["geom_last"]
               if isinstance(ele, bmesh.types.BMEdge)]
del ret

# Extrude and create geometry on side 'b'
ret = bmesh.ops.extrude_edge_only(
        bm,
        edges=edges_start_a)
geom_extrude_mid = ret["geom"]
del ret

# Collect the edges to spin XXX, 'extrude_edge_only' could return this.
verts_extrude_b = [ele for ele in geom_extrude_mid
                   if isinstance(ele, bmesh.types.BMVert)]
edges_extrude_b = [ele for ele in geom_extrude_mid
                   if isinstance(ele, bmesh.types.BMEdge) and ele.is_boundary]
bmesh.ops.translate(
        bm,
        verts=verts_extrude_b,
        vec=(0.0, 0.0, 1.0))

# Create the circle on side 'b'
ret = bmesh.ops.spin(
        bm,
        geom=verts_extrude_b + edges_extrude_b,
        angle=-math.radians(180.0),
        steps=8,
        axis=(1.0, 0.0, 0.0),
        cent=(0.0, 1.0, 1.0))
edges_end_b = [ele for ele in ret["geom_last"]
               if isinstance(ele, bmesh.types.BMEdge)]
del ret

# Bridge the resulting edge loops of both spins 'a & b'
bmesh.ops.bridge_loops(
        bm,
        edges=edges_end_a + edges_end_b)

# Now we have made a links of the chain, make a copy and rotate it
# (so this looks something like a chain)

ret = bmesh.ops.duplicate(
        bm,
        geom=bm.verts[:] + bm.edges[:] + bm.faces[:])
geom_dupe = ret["geom"]
verts_dupe = [ele for ele in geom_dupe if isinstance(ele, bmesh.types.BMVert)]
del ret

# position the new link
bmesh.ops.translate(
        bm,
        verts=verts_dupe,
        vec=(0.0, 0.0, 2.0))
bmesh.ops.rotate(
        bm,
        verts=verts_dupe,
        cent=(0.0, 1.0, 0.0),
        matrix=mathutils.Matrix.Rotation(math.radians(90.0), 3, 'Z'))

# Done with creating the mesh, simply link it into the scene so we can see it

# Finish up, write the bmesh into a new mesh
me = bpy.data.meshes.new("Mesh")
bm.to_mesh(me)
bm.free()

# Add the mesh to the scene
scene = bpy.context.scene
obj = bpy.data.objects.new("Object", fpl)
scene.objects.link(obj)

# Select and make active
scene.objects.active = obj
obj.select = True
"""


import re
#Verificador de CPF

#Input cpf
cpf_digitado = re.sub(r'[^0-9]', '', input ('Insert your CPF(without dots or hyphen ): ') )
print(f'You typed: {cpf_digitado}')

if cpf_digitado == cpf_digitado[0]*len(cpf_digitado):
    print('Você digitou apenas dígitos iguais')

#length verification

elif(len(cpf_digitado)!=11):
    print('O CPF digitado é inválido')
else:
    cpf_nove_digitos = cpf_digitado[:9]
    #verificacao digito
    multiplicador=10
    indice = 0
    digito1 = 0
    while multiplicador>1:
        digito1+= int(cpf_nove_digitos[indice])*multiplicador
        indice+=1
        multiplicador-=1
    digito1 = (digito1*10)%11
    if digito1 > 9:
        digito1 = 0
    print(digito1)

    indice = 0
    multiplicador = 11
    digito2=0
    cpf_dez_digitos = cpf_nove_digitos + str(digito1)
    while multiplicador>1:
        digito2+= int(cpf_dez_digitos[indice])*multiplicador
        indice+=1
        multiplicador-=1
    digito2 = (digito2*10)%11
    digito2 = digito2 if digito2 <= 9 else 0
    print(digito2)

    cpf_gerado = cpf_nove_digitos + str(digito1) + str(digito2)
    if cpf_gerado == cpf_digitado:
        print('O CPF digitado é válido')
    else:
        print('O CPF digitado é inválido')


import turtle

t = turtle.Turtle()
t.color("blue")	# 터틀 및 터틀이 그리는 선의 색상
t.pensize(3)	# 터틀이 그리는 선의 두께
t.hideturtle()  # 터틀 숨기기(t.showturtle() 하면 터틀 보이기)

# 터틀 그래픽으로 학번, 이름 출력하는 함수 정의
def writeName() :
    t.penup()
    t.goto(-300, 400)
    t.pendown()
    t.write("20194146 이승진", font = ('맑은 고딕', 16, 'bold'))

# 그래프 그리기
def drawBar(height) :
    if height < 100 :	# 매개변수의 값이 100 미만이면
        t.fillcolor("blue")	# 터틀의 채우기 색상 설정(파랑)
    elif height < 300 :	# 300 미만이면
        t.fillcolor("yellow")	# 터틀의 채우기 색상 설정(노랑)
    else : 		# 300 이상이면
        t.fillcolor("red")	# 터틀의 채우기 색상 설정(빨강)

    t.begin_fill()	# 채우기 시작
    t.left(90)
    t.forward(height)
    t.write(str(height), font = ('Times New Roman', 16, 'bold'))
    t.right(90)
    t.forward(40)
    t.right(90)
    t.forward(height)
    t.left(90)
    t.end_fill()	# 채우기 종료

data = [120, 56, 309, 220, 156, 23, 98]
for d in data:
    drawBar(d)	# 그래프 그리기 함수 호출(리스트 내 요소를 차례대로 대입)
writeName()    # 학번 이름 출력하는 함수 호출


import sys
input = sys.stdin.readline
N = int(input())
scores = []
for _ in range(N):
    A, B, C = map(int, input().split())
    if A != B and B != C and C != A:
        scores.append(max([A, B, C]) * 100)
    elif A == B == C:
        scores.append(10000 + 1000 * A)
    else:
        if A == B or A == C:
            scores.append(1000 + 100 * A)
        elif B == C:
            scores.append(1000 + 100 * B)
print(max(scores))


__author__ = "byteme8bit"
import os
import cat_service
import subprocess
import platform

def main():
    print_header()
    print()

    folder = get_or_create_output_folder()
    print('Found or created folder: ' + folder)
    print()

    download_cats(folder)
    print()

    display_cats(folder)
    print()

    print("All done! Enjoy your cats!")
    quit()

def print_header():
    """
    Prints program title header
    :return: Prints program title header
    """

    print('--------------------------------------')
    print('                LOL CATS              ')
    print('--------------------------------------')
    print()

def get_or_create_output_folder():
    """
    Checks for existing output folder, creates if not found or uses found folder
    :return: Checks for existing output folder, creates if not found or uses found folder
    """

    base_folder = os.path.dirname(__file__)
    folder = 'cats_pictures'
    full_path = os.path.join(base_folder, folder)
    print(full_path)

    if not os.path.exists(full_path) or not os.path.isdir(full_path):
        print('Creating new directory at {}'.format(full_path))
        os.mkdir(full_path)

    return full_path

def download_cats(folder):
    """
    Grabs cats from intrawebz
    :param folder: This parameter is the cats_pictures folder found/made in the directory where this program ran from
    :return: Grabs cats from intrawebz
    """

    print('Contacting server to download cats...')
    cat_count = 8

    for i in range(1, cat_count + 1):
        name = 'lolcat_{}'.format(format(i))
        print('Downloading cat ' + name)
        cat_service.get_cat(folder, name)

    print('Done.')

def display_cats(folder):
    """
    Calls the folder with the cat pictures to open
    :param folder: This parameter is the cats_pictures folder found/made in the directory where this program ran from
    :return: Calls the folder with the cat pictures to open
    """

    print('Displaying cats in OS window...')

    if platform.system() == 'Darwin':
        subprocess.call(['open', folder])

    elif platform.system() == 'Windows':
        subprocess.call(['explorer', folder])

    elif platform.system() == 'Linux':
        subprocess.call(['xdg-open', folder])

    else:
        print("We don't support your OS: " + platform.system())

if __name__ == '__main__':
    main()


#!/usr/bin/env python

"""
Usage ::

    import psana.graphqt.UtilsWebServ as uws

Created on 2021-08-09 by Mikhail Dubrovin
"""

import logging
logger = logging.getLogger(__name__)

import sys
import requests
import json
import kerberos
from krtc import KerberosTicket
logger = logging.getLogger(__name__)

def kerberos_headers(serv='HTTP@pswww.slac.stanford.edu'):
    try:
      krbheaders = KerberosTicket(serv).getAuthHeaders()
    except kerberos.GSSError as err:
      logger.warning(str(err))
      msg = '\nEXIT: CHECK VALIDITI OF KERBEROS TICKET (commands klist, kinit)'
      print(msg)
      sys.exit()
    except err:
      logger.warning(str(err))
      msg = '\nEXIT: UNSPECIFIED ERROR at getting KerberosTicket'
      print(msg)
      sys.exit()
    return krbheaders

def json_pro(r):
    if r: return r.json()
    logger.warning('unexpected responce from requests.get:\n%s' % str(r))
    return None

def value_from_json(jo):
    if jo is None: return None
    if jo['success']:
        return jo['value']
    else:
        logger.warning('unsuccessful responce from requests.get:\n%s' % json.dumps(jo, indent=2))
        return None

def value_from_responce(r):
    return value_from_json(json_pro(r))

def value_for_request(ws_url, params={}):
    logger.debug('ws_url: %s' % ws_url)
    # cpo: add timeout here to debug intermittent hang in github actions
    r = requests.get(ws_url, headers=kerberos_headers(), params=params, timeout=180)
    return value_from_responce(r)

# curl -s "https://pswww.slac.stanford.edu/ws/lgbk/lgbk/xpptut15/ws/files_for_live_mode_at_location?location=SLAC"
def json_runs(expname, location='SLAC'):
    assert isinstance(expname, str)
    assert len(expname) in (8,9)
    ws_url = "https://pswww.slac.stanford.edu/ws-kerb/lgbk/lgbk/%s/ws/files_for_live_mode_at_location?location=%s"%\
             (expname, location)
    # cpo: add timeout here to debug intermittent hang in github actions
    r = requests.get(ws_url, headers=kerberos_headers(), timeout=180)
    return value_from_responce(r)

def run_info_selected(expname, location='SLAC'):
    joruns = json_runs(expname, location)
    if joruns is None: return None
    return {d['run_num']: (d['begin_time'], d['end_time'], d['is_closed'], d['all_present']) for d in joruns}

def runnums_with_tag(expname, tag='DARK'):
    ws_url = "https://pswww.slac.stanford.edu/ws/lgbk/lgbk/%s/ws/get_runs_with_tag?tag=%s" % (expname, tag)
    return value_for_request(ws_url)

def run_table_data(expname):
    ws_url = "https://pswww.slac.stanford.edu/ws-kerb/lgbk/lgbk/%s/ws/run_table_data" % expname
    return value_for_request(ws_url, params={"tableName": "Scan Table"})

def run_parameters(expname, runnum):
    ws_url = "https://pswww.slac.stanford.edu/ws-kerb/lgbk/lgbk/%s/ws/runs/%d" % (expname, runnum)
    return value_for_request(ws_url)

def detnames(expname, runnum):
    jo = run_parameters(expname, runnum)
    return [k.split('/')[-1] for k, v in jo.get("params", {}).items() if k.startswith("DAQ Detectors/")]

def runinfo_for_params(expname, params={"includeParams": "true"}):
    ws_url = "https://pswww.slac.stanford.edu/ws-kerb/lgbk/lgbk/%s/ws/runs" % (expname)
    return value_for_request(ws_url, params=params)

def run_numbers_at_location(expname, location='SLAC'):
    joruns = json_runs(expname, location)
    if joruns is None: return None
    return sorted([d['run_num'] for d in joruns])

def run_numbers(expname):
    jo = runinfo_for_params(expname, params={"includeParams": "false"})
    if jo is None: return None
    return sorted([d['num'] for d in jo])

def run_files(expname, runnum):
    ws_url = "https://pswww.slac.stanford.edu/ws-kerb/lgbk/lgbk/%s/ws/%d/files" % (expname, runnum)
    return value_for_request(ws_url)

def exp_tags(expname):
    ws_url = "https://pswww.slac.stanford.edu/ws-kerb/lgbk/lgbk/%s/ws/get_elog_tags" % expname
    return value_for_request(ws_url)

def runs_to_tags(expname):
    ws_url = "https://pswww.slac.stanford.edu/ws-kerb/lgbk/lgbk/%s/ws/get_runs_to_tags" % expname
    return value_for_request(ws_url)

def tags_to_runs(expname):
    ws_url = "https://pswww.slac.stanford.edu/ws-kerb/lgbk/lgbk/%s/ws/get_tags_to_runs" % expname
    return value_for_request(ws_url)

def tags_for_run(expname, runnum):
    ws_url = "https://pswww.slac.stanford.edu/ws-kerb/lgbk/lgbk/%s/ws/%d/get_tags_for_run" % (expname, runnum)
    return value_for_request(ws_url)

def exprun_tags(expname):
    """returns dict {runnum: <list-of-tags>}"""
    d = {k:[] for k in run_numbers(expname)}
    tags = exp_tags(expname)
    if tags:
      for tag in tags:
        if tag:
         for rnum in runnums_with_tag(expname, tag=tag):
           d[rnum].append(tag)
    return d

def is_lcls2(expname, runnum=None):

    rnum1 = runnum
    if runnum is None:
      rnums = run_numbers(expname)
      if not rnums:
        logger.warning('issue with run_numbers("%s"): %s' % (expname, str(rnums)))
        return None
      rnum1 = rnums[0]

    files = run_files(expname, rnum1)
    if not files:
        logger.warning('issue with run_files("%s", %d): %s' % (expname, rnum1, str(files)))
        return None
    if len(files)<1:
        logger.warning('issue with run_files("%s", %d) length: %s' % (expname, rnum1, str(files)))
        return None
    dicfile = files[0]
    path = dicfile.get('path',None)
    logger.debug('expname:%s runnum:%d path:%s extension:%s' % (expname, rnum1, path, path[-4:]))
    if not path:
        logger.warning('expname:%s runnum:%d issue with path:%s' % (expname, rnum1, str(path)))
    return path[-4:]=='xtc2'

if __name__ == "__main__":

  def test_run_parameters(expname, runnum):
    jo = run_parameters(expname, runnum)
    if jo: print(json.dumps(jo, indent=2))

  def test_all_runs_with_par_value():
    ws_url = "https://pswww.slac.stanford.edu/ws-kerb/lgbk/lgbk/{experiment_name}/ws/get_runs_matching_params".format(experiment_name="xcsdaq13")
    krbheaders = KerberosTicket("HTTP@pswww.slac.stanford.edu").getAuthHeaders()
    r = requests.post(ws_url, headers=krbheaders, json={"USEG:UND1:3250:KACT": "3.47697", "XCS:R42:EVR:01:TRIG7:BW_TDES": "896924"})
    if r: print(r.json())

  def test_jsinfo_runs(expname, location='SLAC'):
    jo = json_runs(expname, location)
    print(json.dumps(jo, indent=2) if jo else str(jo))

  def test_run_numbers_at_location(expname, location='SLAC'):
    print('test_run_numbers_at_location:', run_numbers_at_location(expname, location))

  def test_run_numbers(expname):
    print('run numbers:', run_numbers(expname))

  def test_exp_tags(expname):
    print(exp_tags(expname))

  def test_exprun_tags(expname):
    print(exprun_tags(expname))

  def test_runnums_with_tag(expname, tag='DARK'):
    print(runnums_with_tag(expname, tag))

  def test_run_table_data(expname):
    jo = run_table_data(expname)
    if jo: print(json.dumps(jo, indent=2))

  def test_runinfo_for_params(expname, params={"includeParams": "true"}):
    jo = runinfo_for_params(expname, params)
    print('runinfo_for_params raw json:', jo)
    if jo: print(json.dumps(jo, indent=2))

  def test_run_table_data_resp(expname):
    ws_url = "https://pswww.slac.stanford.edu/ws-kerb/lgbk/lgbk/%s/ws/run_table_data" % expname
    krbheaders = kerberos_headers()
    # cpo: add timeout here to debug intermittent hang in github actions
    r = requests.get(ws_url, headers=krbheaders, params={"tableName": "Scan Table"}, timeout=180)
    print(r)

  def test_run_files(expname, runnum):
    jo = run_files(expname, runnum)
    if jo: print(json.dumps(jo, indent=2))

  def test_runs_to_tags(expname):
    jo = runs_to_tags(expname)
    if jo: print(json.dumps(jo, indent=2))

  def test_tags_to_runs(expname):
    jo = tags_to_runs(expname)
    if jo: print(json.dumps(jo, indent=2))

  def test_tags_for_run(expname, runnum):
    jo = tags_for_run(expname, runnum)
    if jo: print(json.dumps(jo, indent=2))

  def test_detnames(expname='xpplw2619', runnum=203):
    lst = detnames(expname, runnum)
    print('detnames:\n ', '\n  '.join(lst))

  def test_is_lcls2(expname):
    status = is_lcls2(expname)
    print('is_lcls2("%s"): %s' % (expname, str(status)))

if __name__ == "__main__":

    logging.basicConfig(format='[%(levelname).1s] L:%(lineno)03d %(name)s %(message)s', level=logging.DEBUG)

    tname = sys.argv[1] if len(sys.argv) > 1 else '0'
    print(50*'_', '\nTest %s' % tname)
    if   tname == '0': test_run_parameters('xcsdaq13', 200)
    elif tname == '1': test_all_runs_with_par_value()
    elif tname == '2': test_run_numbers('xpplw3319')
    elif tname == '3': test_run_numbers('xpptut15')
    elif tname == '4': test_run_numbers_at_location('xpplw3319', location='SLAC') #'NERSK'
    elif tname == '5': test_jsinfo_runs('xpptut15', location='SLAC')
    elif tname == '6': test_exp_tags('xpptut15') #xcsdaq13') #cxi78513')
    elif tname == '7': test_exprun_tags('tmox45719') #xcsdaq13')
    elif tname == '8': test_runnums_with_tag('xcsdaq13', tag='SCREENSHOT') # DARK')
    elif tname == '9': test_run_table_data(expname='xcsdaq13')
    elif tname =='10': test_run_table_data_resp(expname='xpplw3319')
    elif tname =='11': test_run_files('xcsdaq13', 200)
    elif tname =='12': test_runinfo_for_params('xcsdaq13', params={"includeParams": "true"})
    elif tname =='13': test_runinfo_for_params('xpplw3319', params={"includeParams": "true"})
    elif tname =='14': test_runinfo_for_params('xpptut15', params={"includeParams": "true"})
    elif tname =='15': test_runs_to_tags('xcsdaq13')
    elif tname =='16': test_tags_to_runs('xcsdaq13')
    elif tname =='17': test_tags_for_run('tmolw8819', 111)
    elif tname =='18': test_is_lcls2('xpplw3319')
    elif tname =='19': test_is_lcls2('tmolw8819')
    elif tname =='20': test_detnames(expname='xpplw2619', runnum=203)
    elif tname =='21': test_detnames(expname='tmolv3919', runnum=11)
    elif tname =='22': test_run_parameters('tmolv3919', 11)
    else: print('test %s is not implemented' % tname)

    sys.exit('End of Test %s' % tname)

# EOF


"""
Leia um valor em metros quadrados m² (M) e apresente-o convertido em hectares (H).
A fórmula de conversão é:
H = M * 0.0001

"""

# Entradas

m = float(input('Informe o valor em m²: '))

# Processamento

h = m * 0.0001

# Saída

print(f'{m} m² equivalem a {h} hectares.')


# February 22nd, 2022

file = open("input.txt", "r")
moves = file.readline().strip().split(",")
file.close()

line = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p' ]
for move in moves:
	if move[0] == 's':
		# Spin
		for i in range(0, int(move[1:])):
			t = line[15]
			for j in range(0, 15):
				line[15 - j] = line[14 - j]
			line[0] = t
	elif move[0] == 'x':
		# Exchange
		split = [int(x) for x in move[1:].split("/")]
		t = line[split[0]]
		line[split[0]] = line[split[1]]
		line[split[1]] = t
	else:
		# Partner
		split = move[1:].split("/")
		a = line.index(split[0])
		b = line.index(split[1])
		t = line[a]
		line[a] = line[b]
		line[b] = t
print("".join(line))


t=int(input())
for _ in range(t):
    s=input()
    l=0
    r=1
    B=list()
    B.append(0)
    for i in range(0,len(s)):
        if(s[i]=='L'):
            l+=1
        else:
            r+=1
            B.append(i+1)
    B.append(len(s)+1)
    c=0
    for i in range(0,len(B)-1):
        c=max(c,B[i+1]-B[i])
    print(c)


def request_logger(environ, start_response):
    method = environ['REQUEST_METHOD']
    path = environ['PATH_INFO']
    query_string = environ['QUERY_STRING']
    content_length = int(environ.get('CONTENT_LENGTH', '0'))
    post_data = environ['wsgi.input'].read(content_length) if content_length > 0 else b''

    log_message = f'{method} {path}?{query_string} {post_data.decode()}'
    print(log_message)

    status = '200 OK'
    headers = [('Content-type', 'text/plain; charset=utf-8')]
    response_body = b'OK\n'

    start_response(status, headers)
    return [response_body]


from KnuthMorrisPratt import KMP

# def isRotated(string1, string2):
# 	'''returns True if string2 is a rotation of string1, else False'''
# 	N = len(string1)
# 	if N != len(string2):
# 		return False
# 	index = 1 # index into string1; length of pattern from string1
# 	while index < N - 1:
# 		pat = string1[:index]
# 		kmp = KMP(pat)
# 		offset = kmp.search(string2)
# 		if (offset + index) == N:
# 			suffix1 = string1[index:]
# 			prefix2 = string2[:offset]
# 			return suffix1 == prefix2
# 		else:
# 			index += 1
# 	return False

def isRotated(string1, string2):
	'''returns True if string2 is a rotation of string1, else False'''
	if len(string1) != len(string2):
		return False
	text = string1 + string2
	N = len(text)
	kmp = KMP(string1)
	offset = kmp.search(text)
	if offset < N:
		return True
	else:
		False


#!/usr/bin python3
# -*- coding: utf-8 -*-
import json
import re

import scrapy
from scrapy import FormRequest
from scrapy import Request
from scrapy import Selector

from nstad.items import *

class NstadSpider(scrapy.Spider):
    name = 'nstad'

    allowed_domains = ['nstad.cn']

    def start_requests(self):
        # 成果项
        for x in range(684):
            params = {
                'pageIndex': str(x),
                'pageSize': '20',
                'cgly': '',
                'hy': '',
                'cgDQ': '',
                'year': ''
            }

            yield FormRequest(
                url='http://www.nstad.cn/ashx/SearchList.ashx',
                formdata=params,
                callback=self.parse_result
            )

        # 工作动态, 暂时只有一页，所以只爬一页,页数通过pageIndex循环
        work_params = {
            'action': 'NewsList',
            'pageIndex': '1',
            'type': 'Work',
            'time': '',
            'title': ''
        }

        yield FormRequest(
            url='http://www.nstad.cn/ashx/Policy.ashx',
            formdata=work_params,
            callback=self.parse_news_list
        )

        # 新闻动态, 5页
        for x in range(1, 6):
            news_params = {
                'action': 'NewsList',
                'pageIndex': str(x),
                'type': 'News',
                'time': '',
                'title': ''
            }

            yield FormRequest(
                url='http://www.nstad.cn/ashx/Policy.ashx',
                formdata=news_params,
                callback=self.parse_news_list
            )

        # 政策
        for x in range(1, 23):
            policy_params = {
                'action': 'InitTable',
                'pageIndex': str(x),
                'kw': 'null',
                'dq': 'null',
                'hy': 'null'
            }

            yield FormRequest(
                url='http://www.nstad.cn/ashx/Policy.ashx',
                formdata=policy_params,
                callback=self.parse_policy_list
            )

    def parse_policy_list(self, response):
        data = response.body.decode()
        sel = Selector(text=data)
        info_divs = sel.xpath('//tr')
        for info_div in info_divs:
            td_divs = info_div.xpath('./td')
            title = td_divs[1].xpath('./a').xpath('string(.)').extract_first()
            href = td_divs[1].xpath('./a/@href').extract_first()
            category = td_divs[2].xpath('string(.)').extract_first()
            date = td_divs[3].xpath('string(.)').extract_first()

            yield Request(
                url=response.urljoin('/' + href),
                callback=self.parse_policy,
                meta={
                    'title': title,
                    'category': category,
                    'date': date
                }
            )

    def parse_policy(self, response):
        title = response.meta['title']
        category = response.meta['category']
        date = response.meta['date']

        policy_item = PolicyItem()
        policy_item['title'] = title
        policy_item['category'] = category
        policy_item['date'] = date

        sel = Selector(response)

        source_div = sel.xpath('//div[@class="time"]').extract_first()
        try:
            p_str = '来源：(.*)'
            p = re.compile(p_str)
            source = p.search(source_div.strip()).group(0).split('：')[-1].strip()
            policy_item['source'] = source
        except:
            raise ValueError(response.url)

        content = sel.xpath('//div[@class="txt"]').xpath('string(.)').extract_first()
        policy_item['content'] = content

        yield policy_item

    def parse_news_list(self, response):
        data = response.body.decode()
        sel = Selector(text=data)

        info_divs = sel.xpath('//ul[@class="list_ul1"]/li')
        for info_div in info_divs:
            href = info_div.xpath('./div[@class="aa2"]/a/@href').extract_first()
            text = info_div.xpath('./div[@class="aa2"]/a').xpath('string(.)').extract_first()
            date = info_div.xpath('./span[@class="time"]/text()').extract_first()

            yield Request(
                url=response.urljoin('/' + href),
                callback=self.parse_news,
                meta={
                    'text': text,
                    'date': date
                }
            )

    def parse_news(self, response):
        title = response.meta['text']
        date = response.meta['date']

        sel = Selector(response)

        news_item = NewsItem()

        news_item['date'] = date
        news_item['title'] = title

        source_div = sel.xpath('//div[@class="time"]').extract_first()
        try:
            p_str = '来源：(.*)'
            p = re.compile(p_str)
            source = p.search(source_div.strip()).group(0).split('：')[-1].strip()
            news_item['source'] = source
        except:
            raise ValueError(response.url)

        content = sel.xpath('//div[@class="txt"]').xpath('string(.)').extract_first()
        news_item['content'] = content

        yield news_item

    def parse_result(self, response):
        data = response.body.decode().split('&&')[0]
        p_str = '{.*?}'
        p = re.compile(p_str)
        values = p.findall(data)

        for value in values:
            p_id_str = 'pid\s*:\s*\'(.*?)\''
            p_date_str = 'lxtime\s*:\s*\'(.*?)\''

            p_id = re.compile(p_id_str)
            p_date = re.compile(p_date_str)

            _id = p_id.search(value).group(0).split(':')[-1][1:-1]
            date = p_date.search(value).group(0).split(':')[-1][1:-1]

            if _id:
                yield Request(
                    url='http://www.nstad.cn/detail.aspx?pid=' + _id,
                    callback=self.parse_result_date,
                    meta={
                        'pid': _id,
                        'date': date
                    }
                )

    def parse_result_date(self, response):
        date = response.meta['date']
        pid = response.meta['pid']
        sel = Selector(response)
        result_item = ResultItem()
        result_item['date'] = date
        result_item['pid'] = pid

        tds = sel.xpath('//table/tr/td')
        for x in range(0, len(tds), 2):
            text = tds[x].xpath('string(.)').extract_first()
            next_text = tds[x + 1].xpath('string(.)').extract_first().strip()

            if '成果名称' in text:
                result_item['title'] = next_text
            elif '关键词' in text:
                result_item['key_words'] = next_text
            elif '成果简介' in text:
                result_item['desc'] = next_text
            else:
                raise ValueError(response.url)

        yield result_item


import scipy
from scipy import signal
from astropy.timeseries import LombScargle
from .gausswin import gausswin
from .slidingwin import *
import numpy as np

def blink_spectrogram(Fss, x0):
    isfirst = True
    # Spectrogram parameters
    Tmax = 30 # From Cho 2021: "The first cutoff frequency determines the upper time limit of blinking (30 seconds)"
    lag = Tmax * Fss

    # Windowing
    overlap_sec = 1
    window_list = overlap_windows_sec(x0, Fss, overlap_sec, lag)

    s_PSD_1 = []

    # Building blink spectrograms
    for i in range(len(window_list)):

        # Min-max normalise signal data
        data_use = window_list[i]
        data_info = data_use.copy()  # shallow copy

        max_data = max(data_info)
        min_data = min(data_info)
        for j in range(len(data_info)):
            data_info[j] = (data_info[j] - min_data) / (max_data - min_data)

        # BPF paramters
        filterN = 3
        Wn1 = 0.033
        Wn2 = 0.4167
        Fn = Fss / 2

        # Band pass filtering with Elliptic filter
        filter_b, filter_a = scipy.signal.ellip(filterN, 3, 6, [Wn1 / Fn, Wn2 / Fn], btype='bandpass')
        filtered_featurescaled_data = scipy.signal.lfilter(filter_b, filter_a, data_info, axis=0)
        w = gausswin(lag)

        gaussian_final_window = np.array(filtered_featurescaled_data * w.T, dtype='float64')

        # Compute periodogram of signal data
        t = np.arange(0, (len(gaussian_final_window)) / Fss, 1 / Fss)
        dy = 0.1
        frequency, freq_amplitude = LombScargle(t, gaussian_final_window, dy).autopower(samples_per_peak=10)

        # accumulate power distributions
        if isfirst:
            range1 = np.where(frequency < Wn1)
            range2 = np.where(frequency > Wn2)
            isfirst = False

        s_PSD_1.append(freq_amplitude[np.max(range1):np.min(range2)])

    s_PSD_1 = np.array(s_PSD_1).T

    return s_PSD_1


"""This problem was asked by Facebook.
There is an N by M matrix of zeroes. Given N and M, write a function to count the
number of ways of starting at the top-left corner and getting to the bottom-right corner.
You can only move right or down.
For example, given a 2 by 2 matrix, you should return 2, since there are two ways
to get to the bottom-right:
•	Right, then down
•	Down, then right
Given a 5 by 5 matrix, there are 70 ways to get to the bottom-right.
"""

def main():
    N = 5
    M = 5
    print(number_ways(N, M, 0, 0))

def number_ways(n, m, i, j):
    if i + 1 == n and j + 1 == m:
        return 1
    if i + 1 == n:
        return number_ways(n, m, i, j + 1)
    elif j + 1 == m:
        return number_ways(n, m, i + 1, j)
    else:
        return number_ways(n, m, i + 1, j) + number_ways(n, m, i, j + 1)

main()


units_digit  = ['','one','two','three','four','five','six','seven','eight','nine']
tens_digit = ['','ten','twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety']

def reading(number):
    unit= (int((str(number))[1]))
    tens = (int((str(number))[0]))
    return tens_digit[tens] , units_digit[unit]

print(reading(46))

Finding the reading of a two-digit number.py


import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
import matplotlib.pyplot as plt
import torch.nn.functional as F
import numpy as np
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"

from utils import make_model
from cmd_line import parse_args

# plots a grid of one example for each of the 10 digits
def test(net, device, test_loader, fig_path):
    net.eval()

    # get 1 example for each digit
    x_found = []
    x, y = next(iter(test_loader))
    digits = [i for i in range(10)]
    while len(digits) != 0:
        curr_digit = digits.pop(0)
        # keep iterating until we get a batch with the current digit
        while curr_digit not in y:
            x, y = next(iter(test_loader))
        # store the first x for the current digit
        x_curr_digit = x[y == curr_digit]
        x_found.append(x_curr_digit[0])

    # stack along batch dimension so shape is b x 1 x 28 x 28
    x = torch.stack(x_found, dim=0)
    x = x.type(torch.FloatTensor).to(device)

    # forward
    _,_, x_ts, x_t_patches, x_orig_patches = net(x)
    # sum patches to create image
    x_hat = torch.sum(x_t_patches, dim=1)

    #x_hat = net(x)

    # plot
    """
    fig, axes = plt.subplots(10, 2, figsize=(5, 20))
    for i in range(10):
        axes[i][0].imshow(x_hat[i].reshape(28, 28).detach().cpu().numpy(), cmap='gray')
        axes[i][1].imshow(x[i].reshape(28, 28).detach().cpu().numpy(), cmap='gray')
    plt.savefig(fig_path)
    plt.close()
    """

    # plot
    """
    num_iters = x_hat.size(1)
    fig, axes = plt.subplots(10, num_iters, figsize=(5, 20))
    for i in range(10):
        for j in range(num_iters):
            axes[i][j].imshow(x_hat[i][j].reshape(28, 28).detach().cpu().numpy(), cmap='gray')
    plt.savefig(fig_path)
    plt.close()
    """

    #"""
    # plot
    fig, axes = plt.subplots(10 * 3, 5, figsize=(5, 20))
    for i in range(10):
        for j in range(4):
            axes[i * 3][j].imshow(x_t_patches[i][j].reshape(28, 28).detach().cpu().numpy(), cmap='gray')
            axes[i * 3 + 1][j].imshow(x_ts[i][j].reshape(28, 28).detach().cpu().numpy(), cmap='gray')
            axes[i * 3 + 2][j].imshow(x_orig_patches[i][j].reshape(28, 28).detach().cpu().numpy(), cmap='gray')
        axes[i * 3][-1].imshow(x_hat[i].reshape(28, 28).detach().cpu().numpy(), cmap='gray')
        axes[i * 3 + 1][-1].imshow(np.zeros([28, 28]), cmap='gray')
        axes[i * 3 + 2][-1].imshow(x[i].reshape(28, 28).detach().cpu().numpy(), cmap='gray')
    plt.subplots_adjust(hspace=None)

    # save or show
    if fig_path is not None:
        plt.savefig(fig_path)
        plt.close()
    else:
        plt.show()
    #"""

def main():
    # Load args
    args = parse_args()

    # Load data
    transform = transforms.Compose([transforms.ToTensor()])
    testset = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=transform)
    test_loader = torch.utils.data.DataLoader(testset, batch_size=args.batch_size,
                                            shuffle=True, num_workers=1)

    # paths
    cp_path = args.net_folder + "/" + args.model + "/" + args.session_name + "/"
    exp_path = args.exp_folder + "/" + args.model + "/" + args.session_name + "/"
    if not os.path.isdir(cp_path):
        os.system("mkdir -p " + cp_path)
    if not os.path.isdir(exp_path):
        os.system("mkdir -p " + exp_path)
    if args.print_folder == 1:
        print(cp_path)
        print(exp_path)
    cp_path += "checkpoint.pt"

    # device
    torch.cuda.set_device(args.device)
    device = torch.cuda.current_device()

    # load model
    net = make_model(args).to(device)
    checkpoint = torch.load(cp_path, map_location="cuda:" + str(device))
    net.load_state_dict(checkpoint['model'])
    net.to(device)

    # evaluates
    test(net, device, test_loader, exp_path + "grid.png")

if __name__ == "__main__":
    main()


"""
This module contains base models for objects.
"""
from __future__ import annotations

import pydantic
from pydantic import ConfigDict

__all__ = (
    "BaseModel",
    "FrozenModel",
)

class BaseModel(pydantic.BaseModel):
    model_config = ConfigDict(arbitrary_types_allowed=True, populate_by_name=True)

    @classmethod
    def model_validate_file(cls, path: str) -> BaseModel:
        """Validates a model from a file.

        :param path: The path to the file
        :type path: str
        :raises TypeError: If the file is not a JSON file
        :return: The validated model
        :rtype: aiosu.models.base.BaseModel
        """
        with open(path) as f:
            return cls.model_validate_json(f.read())

class FrozenModel(BaseModel):
    model_config = ConfigDict(
        arbitrary_types_allowed=True,
        populate_by_name=True,
        frozen=True,
    )


from bs4 import BeautifulSoup
import urllib.request
import pandas as pd
import datetime

def Pascucci_store(result):
    for page_idx in range(0,54):
        Pascucci_url = 'https://www.caffe-pascucci.co.kr/store/storeList.asp?page=%s' % str(page_idx + 1)
        print(Pascucci_url)
        html = urllib.request.urlopen(Pascucci_url)
        soupPascucci = BeautifulSoup(html, 'html.parser')
        tag_tbody = soupPascucci.find('tbody')
        for store in tag_tbody.find_all('tr'):

            store_td = store.find_all('td')
            store_name = store_td[1].string
            store_address_list = list(store_td[4])
            store_address = store_address_list[1].string
            store_phone_list = list(store_td[5])
            store_phone = store_phone_list[1].string
            result.append([store_name]+[store_address]+[store_phone])

    return

def main():
    result = []
    print('Pascucci store crawling >>>>>>>>>>>>>>>>>>>>>>>>>')
    Pascucci_store(result)
    Pascucci_tbl = pd.DataFrame(result, columns = ('store', 'address', 'phone'))
    Pascucci_tbl.to_csv('D:/pascucci2.csv', encoding = 'cp949', mode = 'w', index = True)
    del result[:]

if __name__ == '__main__':
    main()


import sklearn.naive_bayes as nb
import matplotlib.pyplot as plt
import sklearn.metrics as skm
import matplotlib as mpl
import rust_bayes as rb
import pandas as pd
import numpy as np

# Setup classifiers
bayes = rb.GaussianOptimal()
naive = nb.GaussianNB()

# Parameters for for generation
spreading = 5
classes = 5

def posdefizer(M) :
    return M*M.T

X = pd.read_csv('python/X_export.csv')
y = pd.read_csv('python/y_export.csv')

# USING SELF-MADE
bayes.fit(X,y)
y_pred = bayes.predict(X)
conf = skm.confusion_matrix(y.unstack(),y_pred)
accuracy1 = np.sum(np.diag(conf))/np.sum(conf)*100

## USING SKLEARN
naive.fit(np.array(X),np.array(y.unstack()))
y_pred2 = naive.predict(np.array(X))
conf2 = skm.confusion_matrix(np.array(y.unstack()),np.array(y_pred2))
accuracy2 = np.sum(np.diag(conf2))/np.sum(conf2)*100

# Plot of optimal bayes classifier
fig,axs = plt.subplots(1,2,figsize=(10,5))

# Hack for getting natural x and y limits
for c in range(classes):
    axs[0].scatter(X[y['target']==c]['x'],X[y['target']==c]['y'],alpha=0.5,s = 15,color = mpl.cm.get_cmap('tab20')((c*2)/20))
    x_lim = axs[0].get_xlim()
    y_lim = axs[0].get_ylim()

# Setup classification region grid
N = 2000
grid_X,grid_Y = np.meshgrid(np.linspace(x_lim[0], x_lim[1], N), np.linspace(y_lim[0], y_lim[1], N))

grid = np.array([np.ravel(grid_X),np.ravel(grid_Y)]).T
grid_pred = bayes.predict(grid)
grid_pred2 = naive.predict(grid)

# For optimal bayes, plot background and points
axs[0].set_title(f"Optimal Bayes prediction ({round(accuracy1,2)}% accurate)")
for c in range(classes):
    axs[0].scatter(grid[grid_pred==c][:,0],grid[grid_pred==c][:,1],alpha=1, s = .025, color = mpl.cm.get_cmap('tab20')((c*2 + 1)/20))
for c in range(classes):
    axs[0].scatter(X[y['target']==c]['x'],X[y['target']==c]['y'],alpha=0.5,s = 15,color = mpl.cm.get_cmap('tab20')((c*2)/20))

# For naive bayes, plot background and points
axs[1].set_title(f"Naive Bayes prediction ({round(accuracy2,2)}% accurate)")
for c in range(classes):
    axs[1].scatter(grid[grid_pred2==c][:,0],grid[grid_pred2==c][:,1],alpha=1, s = .025, color = mpl.cm.get_cmap('tab20')((c*2 + 1)/20))
for c in range(classes):
    axs[1].scatter(X[y['target']==c]['x'],X[y['target']==c]['y'],alpha=0.5,s = 15, color = mpl.cm.get_cmap('tab20')((c*2)/20))

# Remove unneeded ticks
axs[0].tick_params(left = False , bottom = False,labelleft = False ,labelbottom = False)
axs[1].tick_params(left = False , bottom = False,labelleft = False ,labelbottom = False)

# Apply axis limits
axs[0].set_ylim(y_lim)
axs[0].set_xlim(x_lim)
axs[1].set_ylim(y_lim)
axs[1].set_xlim(x_lim)

# Export
fig.tight_layout()
plt.savefig(f"image/comparison_export.png",bbox_inches=0)
plt.show()


import json

import classify_all_original_records
from company_alias_grouper import get_company_alias_groups
from data_wrangler import wrangle_data, dedup_exactly_same_records

def main():
    #  extract interesting columns and write them into a new csv file
    wrangle_data(['contracts_prime_transactions_%d.csv' % d for d in range(1, 6)], final_csv_file='final.csv')
    # dedup those records that are exactly the same (dup definition: every column of one row equals the other row's)
    uniq_records = dedup_exactly_same_records('final.csv', 'dedup_final.csv')
    # with open('dedup_final.csv', 'rb') as rf:
    #     rf.readline()
    #     csv_reader = csv.reader(rf, delimiter=',')
    #     uniq_records = map(tuple, csv_reader)
    #     sample_companies = random.sample(uniq_records, 10)
    #
    confident_company_aliases = get_company_alias_groups(uniq_records, False)
    with open('confident_company_aliases', 'wb') as f:
        f.write(json.dumps(confident_company_aliases))

    inconfident_company_aliases = get_company_alias_groups(uniq_records, True)
    with open('inconfident_company_aliases', 'wb') as f:
        f.write(json.dumps(inconfident_company_aliases))

    # alias_finder = AliasGroupFinder('confident_company_aliases')
    # for company in sample_companies:
    #     alias_group_id, aliases = alias_finder.find_alias_group_by_company_record(company)
    #     print('It matches alias group %s. We found those records that may represent the same company you provided: %s' % (alias_group_id, json.dumps(aliases)))

    classify_all_original_records.multipro_add_group_id(
        ['contracts_prime_transactions_%d.csv' % d for d in range(1, 6)], final_csv_file='final.csv')
    # write_2_db.copy_from_csv_to_db('final.csv')

if __name__ == '__main__':
    main()


from collections import namedtuple

Image = namedtuple('Image', {
    # '_id',
    'userId',
    'photo',
    'imageId',
    'control',
    'exposed',
    'exposedAt',
    'age',
    'generation',
    'mm',
    'pixels',
    'time',
    'type'
})

Image.__new__.__defaults__ = (None,) * len(Image._fields)

PredictionTask = namedtuple('Task', {
    'id',
    'userId',
    'date',
    'percentage',
    'comments',
    'predictionId',
    'error',
    'finishedWithError'
})

PredictionTask.__new__.__defaults__ = (None,) * len(Image._fields)

Prediction = namedtuple('Prediction', {
    'id'
    'userId',
    'imageId',
    'date',
    'control',
    'exposed',
    'exposedAt',
    'age',
    'generation',
    'measurementsPhotoId',
    'tailLength',
    'totalLength',
    'abdomenPhotoId',
    'heartPhotoId',
    'abdomen5',
    'abdomen3',
    'heart3'
})

Prediction.__new__.__defaults__ = (None,) * len(Image._fields)

# CanProceed = namedtuple('CanProceed', [
#     'userid',
#     'proceed'
# ])
#
# ErrorReport = namedtuple('ErrorReport', [
#     'message',
#     'status'
# ])


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

import os
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(71)

class BernoulliBanditBase(object):
    def __init__(self, arm_num):
        self.arm_num = arm_num
        #self.history = np.zeros((self.arm_num, 2))
        self.params = np.zeros(self.arm_num)
        self.trials = np.zeros(self.arm_num)
        self.total_trial = 0
        self.history = []

    def ucb(self):
        return self.params + np.sqrt(np.log(self.total_trial) / (2*self.trials) )

    def kl(self, p, q):
        return p *  np.log(p/q) + (1-p) * np.log((1-p)/(1-q))

    def kl_grad(self, p, q):
        return (q-p)  / (q * (1-q))

    def kl_ucb(self, c = 0, delta = 1e-8, eps = 1e-12, max_iter = 1e2):
        upperbounds = (np.log(self.total_trial) + c * np.log(np.log(self.total_trial)) )/ self.trials
        upperbounds = np.maximum(delta, upperbounds)
        klucb_results = np.zeros(self.arm_num)
        for k in range(self.arm_num):
            p = self.params[k]
            if p >= 1:
                klucb_results[k] = 1
                continue
            q = p + delta
            for i in range(int(max_iter)):
                f = upperbounds[k] - self.kl(p,q)
                if ( f * f < eps):
                    break
                df = - self.kl_grad(p,q)
                q = min(1 - delta, max(q - f / df, p + delta))
            klucb_results[k] = q
        return klucb_results

    def thompson_sampling(self, prior_alpha, prior_beta):
        ts_results = np.zeros(self.arm_num)
        for k in range(self.arm_num):
            alpha_k = self.trials[k] * self.params[k]
            ts_results[k] = np.random.beta(alpha_k + prior_alpha, self.trials[k] - alpha_k + prior_beta)
        return ts_results

    def random_arm(self):
        return np.random.choice(self.arm_num)

    def update_one_arm(self, index, reward):
        #self.history[index] += 1
        self.params[index] = ( self.trials[index] * self.params[index] + reward ) / (self.trials[index] + 1)
        self.trials[index] += 1
        self.total_trial += 1

class BernoulliBandit(BernoulliBanditBase):
    def __init__(self, arm_num, strategy, eps_greedy = 0.01, c = 0, delta = 1e-12, eps = 1e-8, max_iter = 1e3
        , prior_alpha = 0.5, prior_beta = 0.5):
        super(BernoulliBandit, self).__init__(arm_num)
        self.strategy = strategy
        self.eps_greedy = eps_greedy
        self.c = c
        self.eps = eps
        self.delta = delta
        self.max_iter = max_iter
        self.prior_alpha = prior_alpha
        self.prior_beta = prior_beta

    def select_arm(self):
        if self.total_trial == 0:
            return self.random_arm()

        if self.strategy == "egreedy":
            random_search_flg = np.random.binomial(1, self.eps_greedy) #np.random.uniform < self.eps_greedy
            if random_search_flg:
                return self.random_arm()
            else:
                return np.argmax(self.params)

        elif self.strategy =="ucb":
            ucb_results = self.ucb()
            return np.argmax(ucb_results)

        elif self.strategy == "kl_ucb":
            klucb_results = self.kl_ucb(self.c, self.delta, self.eps, self.max_iter)
            return np.argmax(klucb_results)

        elif self.strategy == "ts":
            ts_results = self.thompson_sampling(self.prior_alpha, self.prior_beta)
            return np.argmax(ts_results)

        else:
            print("Sorry, the strategy is not defined yet.")
            return None

    def save_history(self, index, reward):
        self.history.append([index,reward])

    def update_arm(self):
        self.update_one_arm(self.history[-1][0], self.history[-1][1])

    def print_params(self):
        print(self.strategy + "params ={}".format(self.params))

def tmp_reward(arm):
    # temporary reward function
    return np.random.binomial(1, true_params[arm])

def get_regret():
    indices = np.array(agent.history)[:,0]
    expected_rewards = true_params[indices]
    best_reward = np.max(true_params)
    regrets = best_reward - expected_rewards
    return regrets

def get_asymptoic_lower_bound(mode):
    if mode == "simple":
        return [0.1*(arm_num - 1)/agent.kl(0.4,0.5) * (np.log(t) - np.log(100)) for t in range(int(T))]
    else:
        return [sum([(true_params[0] - true_params[k]) * (np.log(t) - np.log(100))/ (agent.kl(true_params[k], true_params[0]) ) for k in range(1,arm_num)]) for t in range(int(T))]

def visualize_regret(mode):
    max_num = 0
    for strategy in strategy_list:
        cum_regrets = np.load("results/regret_" + strategy + ".npy")
        plt.plot(cum_regrets, label = strategy)
        max_num = max(max_num, cum_regrets[-1])
    #asymptoic_lower_bounds = [sum([(true_params[0] - true_params[k]) * (np.log(t) - np.log(100))/ (kl(true_params[k], true_params[0]) ) for k in range(1,arm_num)]) for t in range(1, int(T))]
    #ab=[0.1*99/kl(0.4,0.5) * (np.log(t) - np.log(100)) for t in range(int(T))]
    ab = get_asymptoic_lower_bound(mode)
    max_num = max(ab[-1], max_num)
    plt.plot(ab, label = "asymptoic bound")
    #plt.xticks([1e2,1e3,1e4,1e5], ["1e2", "1e3", "1e4", "1e5"])
    xticks_name = ["1e" + str(t) for t in range(2, int(np.log10(T)))]
    xticks = [float(xtick) for xtick in xticks_name]
    plt.xticks(xticks, xticks_name)
    plt.xlim(xmin = 100)
    #plt.ylim(0,10000)
    plt.ylim(0,max_num*2)
    plt.xscale("log")
    plt.legend(loc="best")
    #plt.show()
    plt.savefig("figures/regret_bernoulli.png")

# simple model test
T = 1e4
arm_num = 10
#true_params = np.random.uniform(0.05, 0.2 ,size = arm_num)
#true_params = 0.1 + np.arange(arm_num) / (arm_num * 5.0)
true_params = np.ones(arm_num) * 0.4
true_params[0] += 0.1
strategy_list = ["egreedy", "ucb", "ts","kl_ucb"]
#eps_greedy_optimal = (2.0 * arm_num * np.log(T) ) / ( 0.005 * T)

print("true_params = {}".format(true_params))

for strategy in strategy_list:
    agent = BernoulliBandit( arm_num, strategy)
    t = 0
    while t < T:
        arm = agent.select_arm()
        reward = tmp_reward(arm)
        agent.save_history(arm, reward)
        agent.update_arm()
        t += 1
    agent.print_params()

    regrets = get_regret()
    cum_regrets = np.cumsum(regrets)
    np.save("results/regret_" + strategy , cum_regrets)
    #plt.plot(cum_regrets, label = strategy)

visualize_regret("simple")


import sys
N,M,V = map(int,sys.stdin.readline().rstrip().split())
matrix = [[0]*(N+1) for _ in range(N+1)]
for i in range(M):
    link = list(map(int,sys.stdin.readline().split()))
    matrix[link[0]][link[1]] =1
    matrix[link[1]][link[0]] = 1

def dfs(cur,foot):
    foot += [cur]
    for search in range(len(matrix[cur])):
        if matrix[cur][search] == 1 and search not in foot:
            foot = dfs(search,foot)
    return foot

def bfs(start):
    queue = [start]
    foot=[start]
    while queue:
        cur = queue.pop(0)
        for search in range(len(matrix[cur])):
            if matrix[search][cur] and search not in foot:
                foot += [search]
                queue += [search]
    return foot
print(*dfs(V,[]))
print(*bfs(V))


from django.urls import path

from . import views

app_name ="encyclopedia"
urlpatterns = [
    path("", views.index, name="index")
    ,path(f"wiki/<str:wikiname>", views.wikiname, name="wikiname")
    ,path("create", views.create_wiki, name="create_wiki")
    ,path(f"edit/<str:wikiname>", views.edit_wiki, name="edit_wiki")
]


from nose.tools import *

import numpy as np
import pixelhouse as ph
import tempfile
import itertools
import cv2

class Canvas_Test:
    def blank_doesnt_modify_in_place_test(self):

        """ blank_doesnt_modify_in_place_test:
            If the canvas has not had anything painted on it, its sum is 0
            If the canvas has been blanked out, its sum is 0
            Otherwise, its sum should be > 0
        """

        canvas = ph.Canvas()
        assert_true(canvas.img.sum() == 0)
        canvas += ph.circle()
        assert_true(canvas.img.sum() > 0)
        canvas.blank()
        assert_true(canvas.img.sum() > 0)
        assert_true(canvas.blank().img.sum() == 0)

    def hstack_test(self):

        """ hstack_test:
            Draw an image, stack it, and make sure it's the same as the
            numpy operation.
        """

        C1 = ph.Canvas()
        C2 = ph.Canvas()

        C1 += ph.circle()
        C2 += ph.rectangle()

        # Make sure something was drawn
        assert_true(C1.img.sum() != 0)
        assert_true(C2.img.sum() != 0)

        X = ph.hstack([C1, C2])

        img_stack = np.hstack([C1.img, C2.img])
        assert_true(np.isclose(img_stack, X.img).all())

    def vstack_test(self):

        """ vstack_test:
            Draw an image, stack it, and make sure it's the same as the
            numpy operation.
        """

        C1 = ph.Canvas()
        C2 = ph.Canvas()

        C1 += ph.circle()
        C2 += ph.rectangle()

        # Make sure something was drawn
        assert_true(C1.img.sum() != 0)
        assert_true(C2.img.sum() != 0)

        X = ph.vstack([C1, C2])

        img_stack = np.vstack([C1.img, C2.img])
        assert_true(np.isclose(img_stack, X.img).all())

    def gridstack_test(self):

        """ dstack_test:
            Draw an image, stack it, and make sure it's the same as the
            numpy operation.
        """

        C1 = ph.Canvas()
        C2 = ph.Canvas()
        C3 = ph.Canvas()

        C1 += ph.circle()
        C2 += ph.rectangle()
        C3 += ph.circle(x=1)

        # Make sure something was drawn
        assert_true(C1.img.sum() != 0)
        assert_true(C2.img.sum() != 0)
        assert_true(C3.img.sum() != 0)

        X = ph.gridstack([[C1, C2], [C2, C3]])

        img_stack = np.vstack(
            [np.hstack([C1.img, C2.img]), np.hstack([C2.img, C3.img])]
        )

        assert_true(np.isclose(img_stack, X.img).all())

    def get_set_item_test(self):
        """ get_set_item_test:
            Test pixel access like a numpy array.
        """

        C = ph.Canvas(bg="k")

        assert_true(C[20:30, 50:60].sum() == 0)

        # Set a 10x10 block red
        C[20:30, 50:60] = [255, 0, 0, 0]
        assert_equal(C[20:30, 50:60].sum(), 255 * 100)

    def print_statement_test(self):
        """ print_statement_test:
            Make sure we can print the object
        """
        width, height, extent = 105, 207, 3

        C = ph.Canvas(width, height, extent=extent)
        s1 = C.__repr__()
        s2 = f"Canvas (w/h) {height}x{width}, extent {extent}"
        assert_equal(s1, s2)

    def layer_test(self):
        """ layer_test:
            Test if layers work by testing order of operations
        """
        C1 = ph.Canvas()
        C2 = ph.Canvas()

        C1 += ph.circle(color="r")
        C1 += ph.circle(y=1, color="b")
        C1 += ph.transform.translate(x=1)

        C2 += ph.circle(color="r")
        with C2.layer() as CX:
            CX += ph.circle(y=1, color="b")
            CX += ph.transform.translate(x=1)

        img1, img2 = C1.img, C2.img

        # First make sure something was drawn in each case
        assert_true(img1.sum() > 0)
        assert_true(img2.sum() > 0)

        # Now check that they aren't equal
        assert_false((img1 == img2).all())

    def grid_coordinates_test(self):
        """ grid_coordinates_test:
            Test if we can get the grid coordinates, do twice to test cache.
        """
        C = ph.Canvas()
        coords = C.grid_coordinates()
        coords = C.grid_coordinates()

        assert_true(len(coords), 3)

    def grid_points_test(self):
        """ grid_points_test:
            Test if we can get the grid coordinates, do twice to test cache.
        """
        C = ph.Canvas()
        pts = C.grid_points()
        pts = C.grid_points()

        assert_true(len(pts), 2)

    @raises(FileNotFoundError)
    def load_missing_file_test(self):
        """ load_missing_file_test
            Raise an exception if a file is missing
        """
        C = ph.load("THIS_IS_A_MISSING_FILE.png")
        alpha = C.alpha.sum()

        assert alpha.sum() > 0

    def load_transparent_test(self):
        """ load_transparent_test:
            Load an image with a known transparent channel.
        """
        C = ph.load("tests/tree.png")
        alpha = C.alpha.sum()

        assert alpha.sum() > 0

    def set_alpha_value_test(self):
        """ set_alpha_value_test
            Set the alpha channel to a specific value
        """
        C = ph.Canvas()
        C.alpha = 120

        assert_equal(C.alpha.mean(), 120)

    def set_rgb_value_test(self):
        """ set_rgb_value_test
            Set the rgb channel to a specific value
        """
        C = ph.Canvas()
        C.rgb = 120

        assert_equal(C.alpha.mean(), 0)
        assert_equal(C.rgb.mean(), 120)

    def set_img_value_from_string_test(self):
        """ set_rgb_value_from_string_test
            Set the rgb channel to a specific value from a string
        """
        C = ph.Canvas()
        C.img = "r"

        assert_equal(C[:, :, 0].mean(), 255)
        assert_equal(C[:, :, 1].mean(), 0)
        assert_equal(C[:, :, 2].mean(), 0)
        assert_equal(C[:, :, 3].mean(), 255)

        C.img = 32
        assert_equal(C.img.mean(), 32)

    def set_img_value_from_vector_test(self):
        """ set_rgb_value_from_vector_test
            Set the rgb channel to a specific value from a vector
        """
        C = ph.Canvas()
        C.img = [1, 2, 3, 4]

        assert_equal(C[:, :, 0].mean(), 1)
        assert_equal(C[:, :, 1].mean(), 2)
        assert_equal(C[:, :, 2].mean(), 3)
        assert_equal(C[:, :, 3].mean(), 4)

    def save_load_test(self):
        """ save_load_test:
            Create an image, save it to a tmp location and try to load it
            back in. Make sure we check in PNG (lossless) and don't try to
            check the alpha channel.
        """
        C = ph.Canvas(bg="yellow")
        C += ph.circle(color="g")

        C2 = ph.Canvas()

        with tempfile.NamedTemporaryFile(suffix=".png") as F:
            C.save(F.name)
            C2.load(F.name)

        dist = C.img[:, :, :3] - C2.img[:, :, :3]
        dist = dist.astype(float) / 255
        assert_equal(dist.sum(), 0)

    def direct_load_test(self):
        """ direct_load_test:
            Load an image without creating a canvas.
        """
        C = ph.Canvas(bg="yellow")
        C += ph.circle(color="g")

        C2 = ph.Canvas()

        with tempfile.NamedTemporaryFile(suffix=".png") as F:
            C.save(F.name)
            C2 = ph.load(F.name)

        dist = C.img[:, :, :3] - C2.img[:, :, :3]
        dist = dist.astype(float) / 255
        assert_equal(dist.sum(), 0)

    def combine_canvas_test(self):
        """ combine_canvas_test:
            Try to add two canvas together with blend, add, subtract modes.
        """
        C1 = ph.Canvas()
        C1 += ph.circle(color="w")

        C2 = ph.Canvas()
        C2 += ph.circle(x=-0.5, color="b")

        C3 = C1.copy().combine(C2, mode="blend")
        C4 = C1.copy().combine(C2, mode="add")
        C5 = C1.copy().combine(C2, mode="subtract")

        # Now check that none of them are equal
        for x, y in itertools.combinations([C1, C3, C4, C5], r=2):
            assert_false((x.img == y.img).all())

    def check_length_test(self):
        """ check_length_test:
            For animation reasons, a canvas should always have a length of 2.
        """
        canvas = ph.Canvas()
        assert_true(len(canvas), 2)

    def draw_mode_using_add_test(self):
        """ draw_mode_using_add_test:
            Make sure we can draw with the "add" or "subtract" modes
        """
        canvas = ph.Canvas()
        canvas += ph.circle(mode="add")

    def check_non_antialiased_linetype_test(self):
        """ check_non_antialiased_linetype_test:
            Check the defaults for CV2 antialiasing.
        """
        assert_true(ph.Canvas.get_lineType(True), cv2.LINE_AA)
        assert_true(ph.Canvas.get_lineType(False), 8)

    @raises(ValueError)
    def bad_width_combine_canvas_test(self):
        C1 = ph.Canvas(100, 200)
        C2 = ph.Canvas(150, 200)
        C1.combine(C2)

    @raises(ValueError)
    def bad_height_combine_canvas_test(self):
        C1 = ph.Canvas(100, 200)
        C2 = ph.Canvas(100, 250)
        C1.combine(C2)

    @raises(ValueError)
    def bad_mode_combine_canvas_test(self):
        C1 = ph.Canvas()
        C2 = ph.Canvas()
        C1.combine(C2, mode="NothingToSeeHere")

    @raises(TypeError)
    def bad_type_iadd_canvas_test(self):
        C1 = ph.Canvas(100, 200)
        C1 += 3

    def resize_up_test(self):
        """ resize_up_test:
            After scaling by 2x, it should be 400 pixels.
        """
        C = ph.Canvas(width=200, height=200)
        C += ph.rectangle(x=0.5, y=0.25, x1=0.75, y1=0.75)

        assert_true(C.width == 200)
        assert_true(C.height == 200)
        C.resize(fx=2)

        assert_true(C.width == 400)
        assert_true(C.height == 400)

    def resize_exact_test(self):
        """ resize_exact_test:
            After scaling, it should have these exact dimensions
        """
        C = ph.Canvas(width=200, height=200)
        C += ph.rectangle(x=0.5, y=0.25, x1=0.75, y1=0.75)
        C.resize(output_size=(100, 50))

        assert_true(C.width == 100)
        assert_true(C.height == 50)

    def resize_animation_test(self):
        """ resize_animation_test:
            Check that resizing an animation doesn't fail
        """
        C = ph.Animation()
        C.resize(2.0)

    @raises(ValueError)
    def resize_set_both_exact_and_scale_test(self):
        """ resize_set_both_exact_and_scale_test:
         Raise an error if both values are set
        """
        C = ph.Canvas()
        C.resize(fx=2.0, output_size=(100, 50))

    def create_from_single_channel_img_test(self):
        """ create_from_single_channel_img_test:
         Create a canvas from a single channel image
        """
        img = 37 * np.ones(shape=(100, 200)).astype(np.uint8)
        C = ph.Canvas(img=img)

        assert_equal(C.rgb.mean(), 37)
        assert_equal(C.alpha.mean(), 0)

    def create_from_rgb_channel_img_test(self):
        """ create_from_rgb_channel_img_test:
         Create a canvas from a rgb channel image
        """
        img = 37 * np.ones(shape=(100, 200, 3)).astype(np.uint8)
        C = ph.Canvas(img=img)

        assert_equal(C.rgb.mean(), 37)
        assert_equal(C.alpha.mean(), 0)

    def create_from_rgba_channel_img_test(self):
        """ create_from_rgba_channel_img_test:
         Create a canvas from a rgba channel image
        """
        img = 37 * np.ones(shape=(100, 200, 4)).astype(np.uint8)
        C = ph.Canvas(img=img)

        assert_equal(C.rgb.mean(), 37)
        assert_equal(C.alpha.mean(), 37)


# Implicit class
class MyFirstClass:
    pass

c1 = MyFirstClass()

class Person:
    # init variables' class
    def __init__(self, name):
        self.name = name
        print(self.name)

    # add a print_name() method
    def print_name(self):
        print(self.name)

p1 = Person("Ionut")
print(p1.name)
p1.print_name()

class Person2:
    # init variables' class
    def __init__(self, name):
        self.name = name
        print(self.name)

    # add a print_name() method
    def print_name(self):
        print(self.name)

p2 = Person2("Sorin")
print(p2)  # it tells us is an object - the usual toString() output before modifying it

# Form of a class / object for class
class ViaStudent:
    where = "VIA"

    def __init__(self):
        self.where = "VIA-Horsens"

print(ViaStudent.where) # output: VIA
print(ViaStudent().where) # output VIA-Horsens

print("\n \nUsing class method")
# using @classmethod
class PersonClassMethod:
    TITLES = ("Software Engr", "Systems analyst", "Business Analyst")
    def __init__(self, firstname, lastname):
        self.firstname = firstname
        self.lastname = lastname
    def fullname(self): # instance method
        return "%s %s" % (self.firstname, self.lastname)

    # The @classmethod decorator is used to decorate an ordinary method
    # sometimes we write classes to group related constants together
    # with functions which act on them and we may never instantiate inside the class object
    @classmethod
    def allowed_titles_starting_with(cls, startswith): # class method
        return [t for t in cls.TITLES if t.startswith(startswith)]
pcm = PersonClassMethod("Ion", "Rokas")
print(pcm.fullname())
print(PersonClassMethod.fullname(pcm))
print(pcm.allowed_titles_starting_with("S"))
print(PersonClassMethod.allowed_titles_starting_with("S"))

print("\n \nUsing static method")
# using @staticmethod
class PersonStaticMethod:
    TITLES = ("Software Engr", "Systems analyst", "Business Analyst")
    def __init__(self, firstname, lastname):
        self.firstname = firstname
        self.lastname = lastname
    def fullname(self): # instance method
        return "%s %s" % (self.firstname, self.lastname)

    # a static method doesn't have the calling object passed into it as the parameter
    # it doesn't have access to the rest of the class of instance
    # are most commonly used from class objects, like class methods
    @staticmethod
    def allowed_titles_ending_with(endswith):  # class method
        return [t for t in PersonStaticMethod.TITLES if t.endswith(endswith)]
psm = PersonStaticMethod("Lucian", "Abdul")
print(psm.fullname())
print(PersonStaticMethod.fullname(psm))
print(psm.allowed_titles_ending_with("t"))
print(PersonStaticMethod.allowed_titles_ending_with("t"))

print("\n \nUsing property and setter")
# using @property
class Car(object):
    def __init__(self):
        self._speed = 50

    @property
    def speed(self):
        print("The Speed is ", self._speed)
        return self._speed
    @speed.setter
    def speed(self, newSpeed):
        print("Setting to ", newSpeed)
        self._speed = newSpeed
mikkels_car = Car()
mikkels_car._speed = 120
m_speed = mikkels_car.speed

print("\n \nUsing Inheritance")
class PersonInheritance:
    def speak(self):
        print("I can speak many languages, including PYTHON :-)")

class Student(PersonInheritance):
    #redefine speak method from person object
    def speak(self):
        print("I can speak all languages")
    def watch_movie(self):
        print("I like to watch marvel movies")

class Staff(PersonInheritance):
    def watch_movie(self):
        print("I like to watch science fiction")

student = Student()
student.speak()
student.watch_movie()
staff = Staff()
staff.speak()
staff.watch_movie()


class TaTeTi():
    def __init__(self):
        self.board = self.definir_board()
        self.valid = self.definir_valid()
        self.piece = ' x '

    def __str__(self):
        tablero = str('1.1|1.2|1.3\n---+---+---\n2.1|2.2|2.3\n---+---+---\n'
                      '3.1|3.2|3.3')
        return tablero

    def definir_board(self):
        board = dict()
        board['1.1'] = '1.1'
        board['1.2'] = '1.2'
        board['1.3'] = '1.3'
        board['2.1'] = '2.1'
        board['2.2'] = '2.2'
        board['2.3'] = '2.3'
        board['3.1'] = '3.1'
        board['3.2'] = '3.2'
        board['3.3'] = '3.3'
        return board

    def definir_valid(self):
        valid = []
        for key in self.definir_board():
            valid.append(key)
        return valid

    def input_position(self):
        validos = self.valid
        flag = False
        while flag is False:
            posicion = input(str('Posicion'))
            if posicion in validos:
                flag = True
        self.valid.remove(posicion)
        return posicion

    def win(self):
        # verificar filas
        for f in range(1, 4):
            primer_valor = '{}.1'.format(f)
            comparador1 = '{}.{}'.format(f, 2)
            comparador2 = '{}.{}'.format(f, 3)
            if (self.board[primer_valor] == self.board[comparador1] and
               self.board[primer_valor] == self.board[comparador2]):
                return True
        # verficiar columnas
        for f in range(1, 3):
            primer_valor = '1.{}'.format(f)
            comparador1 = '{}.{}'.format(2, f)
            comparador2 = '{}.{}'.format(3, f)
            if (self.board[primer_valor] == self.board[comparador1] and
               self.board[primer_valor] == self.board[comparador2]):
                return True
        # verificar diagonales
        if (self.board['1.1'] == self.board['2.2'] and
           self.board['1.1'] == self.board['3.3']):
            return True
        if (self.board['1.3'] == self.board['2.2'] and
           self.board['1.3'] == self.board['3.1']):
            return True
        return False

    def game(self):
        print(self)
        while not self.win() and len(self.valid) > 0:
            self.board[self.input_position()] = ' ' + self.piece + ' '
            print(self)
            winner = self.piece
            self.piece = 'o' if self.piece == 'x' else 'x'
        if len(self.valid) == 0:
            winner = 'Ninguno'
        return winner

if __name__ == '__main__':
    game = TaTeTi()
    print(game.valid)
    print('Ganó ' + game.game())


import paho.mqtt.client as mqtt
from random import uniform
import time
import json
import threading

nclients = 20
clients = []

def new_point():
    # New lat/lng position.
   return uniform(-180,180), uniform(-90, 90)

def create_clients():
    for i in range(nclients):
        print(f'client created {i}')
        client_name = str(i)
        client = mqtt.Client(client_name)
        client.will_set('mdn', 'LOST_CONNECTION', 0, False)
        client.connect('0.tcp.ngrok.io', 11756)
        clients.append(client)

def simulate_gps(client, client_number):
    while True:
        lat, lng = new_point()
        print(f'driver {client_number} sending new location {lat}, {lng}')
        payload = json.dumps({'driver_id': client_number, 'lat': lat, 'lng': lng})
        client.publish('mdn', payload)
        time.sleep(5)

if __name__ == '__main__':
    create_clients()
    for i in range(nclients):
        client = clients[i]
        # For each client throw a thread that simulates the GPS.
        thread = threading.Thread(target=simulate_gps, args=(client, i))
        thread.start()


from matplotlib import pyplot as plt
from moviepy.editor import *
import os
import moviepy.video.fx.all as vfx
from moviepy.video.tools.drawing import color_gradient
import numpy as np

duration = 0.1

def make_frame(t):
    #make the background color black 2c2f33"
    clip = ColorClip((1080,1920), color=(44,47,51))
    images_folder = os.listdir("assets/backgrounds")
    #get the amount of images in the folder
    images_amount = len(images_folder)
    if (images_amount == 0):
        print("No images in folder")
        return clip.get_frame(t)
    elif (images_amount == 1):
        square1 = ColorClip((1080,1920), color=(255,255,255)).set_position((0,0))
        final = CompositeVideoClip([clip, square1])

        #get the first image in the folder
        image = images_folder[0]
        #load the image and place it in the center of the square (the image is 300x300)
        image = ImageClip("assets/backgrounds/" + image).set_position((390,810))
        #overlay the image on the background
        final = CompositeVideoClip([final, image])
        return final.get_frame(t)

    elif (images_amount == 2):
        square1 = ImageClip("assets/backs/gradient.png").set_position((0,0))
        square2 = ImageClip("assets/backs/gradient.png").set_position((0,960))
        final = CompositeVideoClip([clip, square1, square2])

        #get the first image in the folder
        image = images_folder[0]
        #load the image and place it in the center top of the square (the image is 270x270)
        image = ImageClip("assets/backgrounds/" + image).set_position((405,345))
        #overlay the image on the background
        image2 = images_folder[1]
        #load the image and place it in the center bottom of the square (the image is 270x270)
        image2 = ImageClip("assets/backgrounds/" + image2).set_position((405,1305))
        #make the images rounded
        final = CompositeVideoClip([final, image, image2])

        return final.get_frame(t)

def AudioGetter(video):
    #get the audio streams provided as mp3 from the folder assets/audio
    audio_folder = os.listdir("assets/audio")
    images_folder = os.listdir("assets/backgrounds")
    #get the amount of audio files in the folder
    audio_amount = len(audio_folder)
    if (audio_amount == 0):
        print("No audio in folder")
        return video
    elif (audio_amount == 1):
        #get the first mp3 in the folder
        audio1 = audio_folder[0]
        #load the audio
        audio1 = AudioFileClip("assets/audio/" + audio1)
        #set the audio to the video
        video = video.set_audio(audio1)
        for chunk in audio1.iter_chunks():
            # chunk is a tuple of (time, data)
            t = chunk[0]
            # create a green circle at the center of the image
            circle = (ImageClip("assets/circle.png")
                      .resize(height=100)
                      .set_position(("center", "center"))
                      .set_duration(0.2)
                      .set_start(t)
                      .fx(vfx.colorx, "#00FF00"))
            # composite the circle on top of the image
            image = CompositeVideoClip([image, circle])

        # make the final video by compositing the image on the background clip
        background = ColorClip((1080,1920), color=(44,47,51))
        final = CompositeVideoClip([background, image])
        return final.set_audio(audio1)
    elif (audio_amount == 2):
        audio1 = audio_folder[0]
        audio2 = audio_folder[1]

        audio1 = AudioFileClip("assets/audio/" + audio1)
        audio2 = AudioFileClip("assets/audio/" + audio2)

        video = video.set_audio(audio1)
        video = video.set_audio(audio2)

        for chunk in audio1.iter_chunks():
            # chunk is a tuple of (time, data)
            t = chunk[0]
            # create a green circle at the center of the image
            circle = (ImageClip("assets/circle.png")
                      .resize(height=100)
                      .set_position(("center", "center"))
                      .set_duration(0.2)
                      .set_start(t)
                      .fx(vfx.colorx, "#00FF00"))
            # composite the circle on top of the image
            image = CompositeVideoClip([image, circle])

        # make the final video by compositing the image on the background clip
        background = ColorClip((1080,1920), color=(44,47,51))
        final = CompositeVideoClip([background, image])
        return final.set_audio(audio1)

clip = VideoClip(make_frame, duration = duration)
#add the audio to the video
clip = AudioGetter(clip)

#make the background color black
clip = clip.on_color(size=(1080,1920), color=(0,0,0))
#make the text clip
#overlay the text clip on the background clip
#write the result to a file

# saving Video Clip
clip.write_videofile("sine_wave.mp4", fps = 60)


"""
Runs corner detection
Author: Landon Wiedenman
"""

import sys
sys.path.append('/usr/local/Cellar/opencv/3.3.1_1/lib/python3.6/site-packages')
import cv2
import numpy as np

def detect_corner(image_path):
    """ Receives an image and shows image with corners detected """

    filename = image_path
    img = cv2.imread(filename)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    gray = np.float32(gray)
    dst = cv2.cornerHarris(gray, 2, 3, 0.04)

    # result is dilated for marking the corners, not important
    dst = cv2.dilate(dst, None)

    # Threshold for an optimal value, it may vary depending on the image.
    img[dst > 0.01*dst.max()] = [0, 0, 255]

    cv2.imshow('dst', img)
    if cv2.waitKey(0) & 0xff == 27:
        cv2.destroyAllWindows()


import pygame
import random

from pygame.mask import from_surface

pygame.init()
dis = pygame.display.set_mode((800,600))
pygame.display.set_caption("Little Snake")
dis.fill((255,255,255))
pygame.display.update()
f_st = pygame.font.SysFont(None,50)
f_st1 = pygame.font.SysFont(None,40)
f_st2 = pygame.font.SysFont(None,30)
f_st3 = pygame.font.SysFont(None,30)

def snake(s_l):
    for i in s_l:
        pygame.draw.rect(dis,(0,0,255),[i[0],i[1],10,10])
    pygame.display.update()
def message():
    msg = "GAME OVER"
    msg2 = "press SPACE for PLAY again"
    msg3 = "press ESC for QUIT"
    k = f_st.render(msg,True,(255,0,0))
    p = f_st2.render(msg2,True,(0,255,0))
    q = f_st3.render(msg3,True,(0,0,255))
    dis.blit(k,[290,200])
    dis.blit(p,[270,250])
    dis.blit(q,[300,270])
    pygame.display.update()
def c_score(l):
    msg = "Score :"+str(l)
    k = f_st1.render(msg,True,(0,255,0))
    dis.blit(k,[0,0])
    pygame.display.update()

def h_score(h):
    msg = "High Score :"+str(h)
    k = f_st1.render(msg,True,(0,255,0))
    dis.blit(k,[600,0])
    pygame.display.update()

HIGH = 1
def main():
    x = 300
    y = 300
    xc = 0
    yc = 0

    s_l = []

    l = 1
    global HIGH

    fx = int(random.randrange(10,780))
    fy = int(random.randrange(30,580))

    clk = pygame.time.Clock()
    speed = 15
    gameover = False
    while not gameover:
        for i in pygame.event.get():

            if i.type==pygame.QUIT:
                gameover = True

            if i.type == pygame.KEYDOWN:
                if i.key == pygame.K_LEFT:
                    xc = -10
                    yc = 0
                elif i.key == pygame.K_RIGHT:
                    xc = 10
                    yc = 0
                elif i.key == pygame.K_DOWN:
                    xc = 0
                    yc = 10
                elif i.key == pygame.K_UP:
                    xc = 0
                    yc = -10
        if x>780 or x<10 or y>580 or y<30:
            sub_main()

        dis.fill((255,255,255),(0,0,800,30))
        c_score(l)

        h_score(HIGH)

        x+=xc
        y+=yc
        s_l.append([x,y])

        if len(s_l) > l:
            del s_l[0]
        dis.fill((0,0,0),(10,30,790,590))
        dis.fill((255,255,255),(0,30,10,600))
        dis.fill((255,255,255),(790,30,800,600))
        dis.fill((255,255,255),(0,590,800,600))
        pygame.draw.circle(dis,(255,0,0),[fx,fy],10)
        snake(s_l)

        if x in range(fx-10,fx+10) and y in range(fy-10,fy+10):
            fx = int(random.randrange(10,780))
            fy = int(random.randrange(30,580))
            l+=1
            speed+=1

        clk.tick(speed)
        if HIGH <l:
            HIGH = l

def sub_main():

    dis.fill((0,0,0),(10,30,780,560))
    message()
    gameover = True
    while gameover:
        for i in pygame.event.get():
            print(i)
            if i.type == pygame.KEYDOWN:
                if i.type==pygame.QUIT:
                    pygame.quit()
                    quit()
                if i.key == pygame.K_ESCAPE:
                    pygame.quit()
                    quit()
                elif i.key == pygame.K_SPACE:
                    main()

main()
pygame.quit()
quit()


import time
import numpy as np
import pandas as pd
from aloha.network import Network
from alive_progress import alive_bar
from aloha.head_node import HeadNode
from aloha.member_node import MemberNode
from aloha.aloha_logging import init_log, log_line, custom_log

class Aloha:
    def __init__(
        self,
        subnets: int,
        nodes_per_subnet: int,
        max_loop: int,
        generate_interval: int,
        head_node_generate: bool,
        head_node_coin: bool,
        time_sleep: int = 1,
    ):
        self.generate_interval = generate_interval
        self.nodes_per_subnet = nodes_per_subnet
        self.subnets = subnets
        self.loops = max_loop
        self.head_node_generate = head_node_generate
        self.head_node_coin = head_node_coin
        self.time_sleep = time_sleep

    def generate_packets(self):
        for subnet in self.subnet_list:
            if self.head_node_generate:
                subnet.head_node.generate()
            for node_index in range(self.nodes_per_subnet):
                subnet.members[node_index].generate()
        log_line()

    def create(self):
        """
        Create network structure
        """
        init_log()
        self.main_network = Network("BASE_STATION")
        self.subnet_list = []

        for i in range(self.subnets):
            subnet = Network(f"SUBNET_{i}")

            head_node = HeadNode(self.main_network, subnet, self.head_node_coin)

            subnet.head_node = head_node

            for node_index in range(self.nodes_per_subnet):
                subnet.members.append(MemberNode(subnet, node_index))

            self.subnet_list.append(subnet)
            self.main_network.members.append(head_node)

        if self.generate_interval < 0:
            self.generate_packets()
        return self

    def start(self):
        """
        Run aloha simulation
        """
        loop_index = 0

        # Geração de semente aleatória para cada execução
        self.seed = np.random.randint(1, 100)
        np.random.seed(self.seed)

        # Salva valor de semente nos logs
        custom_log(f"SEED: {self.seed}")

        packets_per_subnet = self.nodes_per_subnet
        if self.head_node_generate:
            packets_per_subnet += 1

        total_packts = self.subnets * packets_per_subnet
        with alive_bar() as bar:
            while True:
                if self.loops > 0 and self.loops == loop_index:
                    return self

                time.sleep(self.time_sleep)
                bar()
                network_status = self.main_network.get_status()
                # All packets was received
                if len(network_status["memory"]) == total_packts:
                    return self

                # Generate packets
                if (
                    self.generate_interval > 0
                    and loop_index % self.generate_interval == 0
                ):
                    self.generate_packets()
                    loop_index += 1
                    continue

                for subnet in self.subnet_list:
                    for node in subnet.members:
                        node.submit()

                    subnet.head_node.submit()
                    status = subnet.get_submission_status()
                    subnet.notify(status)

                # Analyse main network collision
                status = self.main_network.get_submission_status()
                self.main_network.notify(status)

                loop_index += 1
                log_line()

    def analyse(self):
        columns = ["timestamp", "network", "node", "type", "message"]
        log_df = pd.read_csv("data/aloha.log", skiprows=1, header=None)
        log_df.columns = columns
        log_df["type"] = log_df["type"].str.strip()

        has_debug = log_df["timestamp"].str.contains("DEBUG:root")
        log_df = log_df[has_debug].copy()

        log_df["timestamp"] = log_df["timestamp"].apply(
            lambda t: t.split("DEBUG:root:").pop()
        )
        log_df["timestamp"] = pd.to_datetime(log_df["timestamp"])

        log_df.to_csv("data/log.csv", index=False)

        print(f"Estatísticas gerais: (SEMENTE: {self.seed})")
        df = (
            log_df.groupby(["network", "type"], as_index=False)
            .agg({"timestamp": "count"})
            .pivot(index="network", columns="type", values="timestamp")
            .fillna(0)
        )

        if "IDLE" not in df.columns:
            df["IDLE"] = 0

        if "SUCCESS" not in df.columns:
            df["SUCCESS"] = 0

        if "PARTIAL_NODE_COLISION" not in df.columns:
            df["PARTIAL_NODE_COLISION"] = 0

        if "NODE_COLLISION" not in df.columns:
            df["NODE_COLLISION"] = 0

        if "COLLISION" not in df.columns:
            df["COLLISION"] = df["PARTIAL_NODE_COLISION"] + df["NODE_COLLISION"]

        df["BUSY"] = df["COLLISION"] + df["SUCCESS"]
        df["THROUGHPUT"] = df["SUCCESS"] / (df["IDLE"] + df["BUSY"])

        print(df)
        df.to_csv("data/metrics.csv")


from flask import Flask, request, jsonify
from flask_cors import CORS
import sqlite3
import os
import pandas as pd
import numpy as np
# import model.pkl
import pickle

clf = pickle.load(open('model.pkl', 'rb'))
clf2 = pickle.load(open('model2.pkl', 'rb'))

l1 = ['back_pain', 'constipation', 'abdominal_pain', 'diarrhoea', 'mild_fever', 'yellow_urine',
      'yellowing_of_eyes', 'acute_liver_failure', 'fluid_overload', 'swelling_of_stomach',
      'swelled_lymph_nodes', 'malaise', 'blurred_and_distorted_vision', 'phlegm', 'throat_irritation',
      'redness_of_eyes', 'sinus_pressure', 'runny_nose', 'congestion', 'chest_pain', 'weakness_in_limbs',
      'fast_heart_rate', 'pain_during_bowel_movements', 'pain_in_anal_region', 'bloody_stool',
      'irritation_in_anus', 'neck_pain', 'dizziness', 'cramps', 'bruising', 'obesity', 'swollen_legs',
      'swollen_blood_vessels', 'puffy_face_and_eyes', 'enlarged_thyroid', 'brittle_nails',
      'swollen_extremeties', 'excessive_hunger', 'extra_marital_contacts', 'drying_and_tingling_lips',
      'slurred_speech', 'knee_pain', 'hip_joint_pain', 'muscle_weakness', 'stiff_neck', 'swelling_joints',
      'movement_stiffness', 'spinning_movements', 'loss_of_balance', 'unsteadiness',
      'weakness_of_one_body_side', 'loss_of_smell', 'bladder_discomfort', 'foul_smell_of urine',
      'continuous_feel_of_urine', 'passage_of_gases', 'internal_itching', 'toxic_look_(typhos)',
      'depression', 'irritability', 'muscle_pain', 'altered_sensorium', 'red_spots_over_body', 'belly_pain',
      'abnormal_menstruation', 'dischromic _patches', 'watering_from_eyes', 'increased_appetite', 'polyuria', 'family_history', 'mucoid_sputum',
      'rusty_sputum', 'lack_of_concentration', 'visual_disturbances', 'receiving_blood_transfusion',
      'receiving_unsterile_injections', 'coma', 'stomach_bleeding', 'distention_of_abdomen',
      'history_of_alcohol_consumption', 'fluid_overload', 'blood_in_sputum', 'prominent_veins_on_calf',
      'palpitations', 'painful_walking', 'pus_filled_pimples', 'blackheads', 'scurring', 'skin_peeling',
      'silver_like_dusting', 'small_dents_in_nails', 'inflammatory_nails', 'blister', 'red_sore_around_nose',
      'yellow_crust_ooze']
d1 = {0: 'Fungal infection', 1: 'Allergy', 2: 'GERD', 3: 'Chronic cholestasis', 4: 'Drug Reaction', 5: 'Peptic ulcer diseae', 6: 'AIDS', 7: 'Diabetes ', 8: 'Gastroenteritis', 9: 'Bronchial Asthma', 10: 'Hypertension ', 11: 'Migraine', 12: 'Cervical spondylosis',
      13: 'Paralysis (brain hemorrhage)', 14: 'Jaundice', 15: 'Malaria', 16: 'Chicken pox', 17: 'Dengue', 18: 'Typhoid', 19: 'hepatitis A', 20: 'Hepatitis B', 21: 'Hepatitis C', 22: 'Hepatitis D', 23: 'Hepatitis E', 24: 'Alcoholic hepatitis', 25: 'Tuberculosis', 26: 'Common Cold', 27: 'Pneumonia', 28: 'Dimorphic hemmorhoids(piles)', 29: 'Heart attack', 30: 'Varicose veins', 31: 'Hypothyroidism', 32: 'Hyperthyroidism', 33: 'Hypoglycemia', 34: 'Osteoarthristis', 35: 'Arthritis', 36: '(vertigo) Paroymsal  Positional Vertigo', 37: 'Acne', 38: 'Urinary tract infection', 39: 'Psoriasis', 40: 'Impetigo'}

def predict(lis):
    yData = [0 for i in range(len(l1))]
    for i in range(len(l1)):
        if(l1[i] in lis):
            yData[i] = 1
    pred = clf.predict([yData])[0]
    return [d1[pred]]

def predict2(lis):
    yData = [0 for i in range(len(l1))]
    for i in range(len(l1)):
        if(l1[i] in lis):
            yData[i] = 1
    data = pd.DataFrame(data=[yData], columns=l1)
    pred = clf.predict_proba(data)[0]
    sorted = np.sort(pred)
    pred1 = d1[np.where(pred == sorted[-1])[0][0]] + \
        " " + str(int(sorted[-1]*100)) + "%"
    pred2 = ''
    if (sorted[-2] > 0.4):
        pred2 = d1[np.where(pred == sorted[-2])[0][0]] + \
            " " + str(int(sorted[-2]*100))+"%"
    return [pred1, pred2]

app = Flask(__name__)
CORS(app)

# Flask maps HTTP requests to Python functions.
# The process of mapping URLs to functions is called routing.

@app.route('/', methods=['GET'])
def home():
    return "
Distant Reading Archive

This is a prototype API
"

# A route to return all of available entries i our catalog.

@app.errorhandler(404)
def page_not_found(e):
    return "
404

The resource could not be found
", 404

@app.route('/api/predict', methods=['POST'])
def add_predict():
    # Receives the data in JSON format in a HTTP POST request
    if not request.is_json:
        return "
The content isn't of type JSON<\p>"
    else:
        data = request.get_json()
        lis = data['symptoms']
        return jsonify({"Prediction": predict(lis)})

@app.route('/api/predict2', methods=['POST'])
def add_predict2():
    # Receives the data in JSON format in a HTTP POST request
    if not request.is_json:
        return "
The content isn't of type JSON<\p>"
    else:
        data = request.get_json()
        lis = data['symptoms']
        return jsonify({"Prediction": predict2(lis)})

# A method that runs the application server.
if __name__ == "__main__":
    # Threaded option to enable multiple instances for multiple user access support
    app.run(debug=False, threaded=True)