deck = "a and can down".split(" ")

from PyQt4 import QtGui
from PyQt4 import QtCore

prevb = QtGui.QPushButton("prev")
nextb = QtGui.QPushButton("next")

prevb.show()
nextb.show()

card = QtGui.QWidget()
card.show()

cardLay = QtGui.QVBoxLayout()
card.setLayout(cardLay)

cardDisplay = QtGui.QLabel(deck[0])

cardLay.addWidget(cardDisplay)

font = cardDisplay.font()
font.pointSize()
font.setPointSize(60)
cardDisplay.setFont(font)
font.setWeight(72)
cardDisplay.setFont(font)

cardLay.alignment()
cardLay.setAlignment(QtCore.Qt.AlignJustify)

##

# card.deleteLater()
# cardDisplay = QtGui.QLabel("<h1>{0}</h1>".format(deck[0]))

# cardDisplay.text()
# cardDisplay.setText('a')
#
# font = cardDisplay.font()
# font.weight()
# font.setWeight(72)
# cardDisplay.setFont(font)
#
# font.pointSize()
# font.setPointSize(30)
#
# cardDisplay.setFont(font)

# def nextCard():
#     card_cur = cardDisplay.text()
#     card_index = (deck.index(card_cur)+1)%len(deck)
#     cardDisplay.setText(deck[card_index])
#
# nextb.clicked.connect(nextCard)
#
# def prevCard():
#     card_cur = cardDisplay.text()
#     card_index = (deck.index(card_cur)-1)%len(deck)
#     cardDisplay.setText(deck[card_index])
#
# prevb.clicked.connect(prevCard)

prevb.clicked.disconnect(prevCard)
nextb.clicked.disconnect(nextCard)

def deck_card_adjoining(current, direction):
    card_index = (deck.index(current)+direction)%len(deck)
    return deck[card_index]

def nextCard():
    card_cur = cardDisplay.text()
    card_next = deck_card_adjoining(card_cur, 1)
    cardDisplay.setText(card_next)

nextb.clicked.connect(nextCard)

def prevCard():
    card_cur = cardDisplay.text()
    card_prev = deck_card_adjoining(card_cur, -1)
    cardDisplay.setText(card_prev)

prevb.clicked.connect(prevCard)


import numpy as np
import constants as c
from heuristics.Config import Config

class ShipmentTW:
    def __init__(self, id: str, earliest_start_time: float, latest_start_time: float,
                 earliest_end_time: float, latest_end_time: float, start_location: str, end_location: str, type: str):
        # diff = earliest_end_time - earliest_start_time - (latest_end_time - latest_start_time)
        # if diff >= 0.01:
        #     print('wrong: ' + str(diff))

        self.id = id
        self.earliest_start_time = earliest_start_time
        self.latest_start_time = latest_start_time
        self.earliest_end_time = earliest_end_time
        self.latest_end_time = earliest_end_time + (latest_start_time - earliest_start_time)
        self.start_location = start_location
        self.end_location = end_location
        self.type = type

    def __str__(self):
        return 'id: ' + str(self.id) + '\n' + \
               'start window: [' + str(self.earliest_start_time) + ', ' + str(self.latest_start_time) + ']' + '\n' + \
               'end window: [' + str(self.earliest_end_time) + ', ' + str(self.latest_end_time) + ']' + '\n' + \
               'locations: ' + str(self.start_location) + ' --> ' + str(self.end_location) + '\n' + \
               'type: ' + self.type + '\n'

    def get_length(self):
        length = self.earliest_end_time - self.earliest_start_time
        return round(length, 3)

    def discretize_time_windows(self, config: Config):
        """
        Make list of regular shipments in a certain interval.
        :return:
        """
        discretized_shipments = []
        interval = int(config.time_window_interval_in_minutes * 1 / .6)
        length = int((self.latest_start_time - self.earliest_start_time) * 100)
        if config.max_number_shipment_multiplication == 1:
            if 'IB' in self.type:
                shipment = Shipment(id=self.id + '.1', input_shipment=self)
                shipment.set_start_time(self.earliest_start_time)
            else:  # 'OB' must be in self.type
                if 'OB' not in self.type:
                    raise ValueError('Neither IB nor OB is in self.type')
                shipment = Shipment(id=self.id + '.1', input_shipment=self)
            discretized_shipments.append(shipment)
        elif config.max_number_shipment_multiplication == 2:
            if 'IB' in self.type:
                shipment = Shipment(id=self.id + '.1', input_shipment=self)
                shipment.set_start_time(self.earliest_start_time)
                discretized_shipments.append(shipment)
                if length > interval:
                    shipment = Shipment(id=self.id + '.2', input_shipment=self)
                    shipment.set_start_time(round((self.earliest_start_time + self.latest_start_time) / 2, 3))
                    discretized_shipments.append(shipment)
            if 'OB' in self.type:
                shipment = Shipment(id=self.id + '.1', input_shipment=self)
                shipment.set_start_time(round((self.earliest_start_time + self.latest_start_time) / 2, 3))
                discretized_shipments.append(shipment)
                if length > interval:
                    shipment = Shipment(id=self.id + '.2', input_shipment=self)
                    shipment.set_start_time(self.latest_start_time)
                    discretized_shipments.append(shipment)
        elif config.max_number_shipment_multiplication > 2:
            i = 1
            if np.ceil(length / interval) + 1 <= config.max_number_shipment_multiplication:
                pass
            else:
                interval = np.floor(length / (config.max_number_shipment_multiplication - 2))
            for minutes in list(range(0, length + 1, int(interval))):
                key = self.id + '.' + str(i)
                shipment = Shipment(id=key,
                                    start_time=self.earliest_start_time + minutes * 0.01,
                                    end_time=self.earliest_end_time + minutes * 0.01,
                                    start_location=self.start_location,
                                    end_location=self.end_location,
                                    type=self.type,
                                    input_shipment=self)
                discretized_shipments.append(shipment)
                i += 1
        return discretized_shipments

class Shipment:
    def __init__(self, id: str = '', start_time: float = 0, end_time: float = 0, start_location: str = '',
                 end_location: str = '', type: str = '', input_shipment: ShipmentTW = None):
        self.start_time = 0
        if input_shipment is not None:
            self.input_shipment = input_shipment
            if id != '':
                self.id = id
            else:
                self.id = input_shipment.id
            self.set_start_time(start_time)
            self.start_location = input_shipment.start_location
            self.end_location = input_shipment.end_location
            self.type = input_shipment.type
        else:
            self.input_shipment = None
            self.id = id
            self.set_start_time(start_time)
            self.end_time = end_time
            self.start_location = start_location
            self.end_location = end_location
            self.type = type

    def set_start_time(self, start_time: float):
        self.start_time = round(start_time, 3)
        if self.input_shipment is not None:
            self.end_time = round(start_time + self.input_shipment.get_length(), 3)

    def get_length(self):
        length = self.end_time - self.start_time
        return length

    def __str__(self):
        return 'id: ' + str(self.id) + '\n' + \
               'start time: ' + str(self.start_time) + ' end time: ' + str(self.end_time) + '\n' + \
               'locations: ' + str(self.start_location) + ' --> ' + str(self.end_location) + '\n' + \
               'type: ' + self.type + '\n' + \
               'input shipment: ' + self.input_shipment.id + '\n'

# -------------------------------------------- Help Functions ----------------------------------------------------

def are_compatible(ship1: Shipment, ship2: Shipment):
    compatibility = False
    if ship1.end_time + c.time_diff_matrix.at[ship1.end_location, ship2.start_location] <= ship2.start_time:
        compatibility = True
    return compatibility


from PyQt5.QtWidgets import (QWidget, QLCDNumber, QSlider, QMainWindow,
                             QGridLayout, QApplication, QPushButton, QLabel, QLineEdit)

from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
from PyQt5.QtCore import Qt
# from predictsingle import predict
from PIL import Image
import predictclass

class Ui_example(QWidget):
    def __init__(self):
        super().__init__()  # 主函数了

        self.layout = QGridLayout(self)  # 创建一个整体界面
        self.setStyleSheet('background:green')
        self.label_image = QLabel(self)  # 选择图片后显示图片的标签
        self.label_predict_result = QLabel('识别结果', self)  # 识别结果文本提示标签
        self.label_predict_result_display = QLabel(self)  # 识别结果标签
        self.label_predict_acc = QLabel('识别准确率', self)  # 识别准确率文本提示标签
        self.label_predict_acc_display = QLabel(self)  # 识别准确率结果标签

        self.button_search_image = QPushButton('选择图片', self)  # 选择图片的文本提示标签
        self.button_run = QPushButton('运行', self)  # 运行标签
        self.setLayout(self.layout)  # 设置程序界面,并将创建的界面添加到这里
        self.initUi()  # 调用下面的方法,将初始化函数中的这个self传进去

    def initUi(self):
        self.layout.addWidget(self.label_image, 1, 1, 3, 2)  # 将上面创建的一系列标签按追加到界面中,并设置显示位置
        self.layout.addWidget(self.button_search_image, 1, 3, 1, 2)
        self.layout.addWidget(self.button_run, 3, 3, 1, 2)
        self.layout.addWidget(self.label_predict_result, 4, 3, 1, 1)
        self.layout.addWidget(self.label_predict_result_display, 4, 4, 1, 1)
        self.layout.addWidget(self.label_predict_acc, 5, 3, 1, 1)
        self.layout.addWidget(self.label_predict_acc_display, 5, 4, 1, 1)

        self.button_search_image.clicked.connect(self.openimage)  # 对选择图片按钮设置点击操作,点击后执行openimage操作
        self.button_run.clicked.connect(self.run)  # 对运行按钮执行运行函数 self.openimage self.run指的应该是本类函数

        self.setGeometry(300, 300, 300, 300)
        self.setWindowTitle('flowers-10十分类')
        self.show()

    def openimage(self):
        global fname
        imgName, imgType = QFileDialog.getOpenFileName(self, "选择图片", "", "*.jpg;;*.png")  # imgName返回文件绝对路径
        # imgType返回文件类型即拓展名
        print('imgName:{}'.format(imgName))
        print('imgType:{}'.format(imgType))
        jpg = QPixmap(imgName).scaled(self.label_image.width(), self.label_image.height())
        self.label_image.setPixmap(jpg)
        fname = imgName

    def run(self):
        global fname
        print('type(fname):{}'.format(type(fname)))
        # file_name = str(fname) #下面去掉了对fname的强转str的操作，因为上面打印fname类型发现已经是str了
        file_name = fname
        img = Image.open(file_name)

        a, b = predictclass.predict(img)
        self.label_predict_result_display.setText(a)
        self.label_predict_acc_display.setText(str(b))

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Ui_example()
    sys.exit(app.exec_())


import pickle

class Result:
    def __init__(self, t1, t2, final) -> None:
        self.t1 = t1
        self.t2 = t2
        self.final = final

class Student:
    def __init__(self, id, mis, email, result) -> None:
        self.id = id
        self.mis = mis
        self.email = email
        self.result = result

def update(records, stuId):
    attrs = ['id', 'mis', 'email', 't1', 't2', 'final']
    print('Enter the attribute you wish to change')
    print(f'Choices are {attrs}')
    attr = input('Your choice: ').lower()
    for record in records:
        if record.id == stuId:
            found_record = record
            break
    else:
        print('The ID is not in the database')
        return
    val = input('Enter the value: ')
    if attr in ('t1', 't2', 'final'):
        setattr(found_record.result, attr, int(val))
    else:
        setattr(found_record, attr, val)

    with open('file', 'wb') as f:
        pickle.dump(records, f)

def display(records):
    print(f'\n{"ID":^20}{"MIS":^20}{"Email":^20}{"T1":^20}{"T2":^20}{"final":^20}')
    for record in records:
        print(f'{record.id:^20}{record.mis:^20}{record.email:^20}{record.result.t1:^20}{record.result.t2:^20}{record.result.final:^20}')

if __name__ == '__main__':
    exams = ['t1', 't2', 'final']
    records = []
    for _ in range(5):
        stuId = input('\nEnter the student ID: ')
        stuMis = input('Enter the student MIS: ')
        email = input('Enter the student email: ')
        d = {}
        for exam in exams:
            marks = int(input(f'Enter {exam} marks: '))
            d[exam] = (marks)
        result = Result(**d)
        records.append(Student(stuId, stuMis, email, result))
    with open('file', 'wb') as f:
        pickle.dump(records, f)
    stuId = input('Enter the ID of the record you wish to update: ')
    update(records, stuId)
    display(records)


# 14161 5209. [파이썬 S/W 문제해결 구현] 5일차 - 최소 생산 비용
def dfs(y,Sum):
    global Min
    if Sum > Min: return            # 언제든지 Sum 값이 크면 다시 back!!!!!!!!!!!!
    if y==N:                        # 만약 y가 N 과 같다면 최소값 갱신
        Min = min(Sum,Min)
        return

    for x in range(N):
        if used[x]==0:
            used[x] = 1             # used를 사용하여 행에서 사용한 것들 표시
            dfs(y+1,Sum+lst[y][x])
            used[x] = 0

T = int(input())
for tc in range(1,T+1):
    N = int(input())
    lst = [list(map(int,input().split())) for _ in range(N)]
    used = [0] * N
    Min = 21e8
    dfs(0,0)
    print(f"#{tc} {Min}")

# 14160 5차시 5일차 - 전기버스2
def dfs(idx,cnt):
    global Min
    if cnt >= Min: return   # 백트랙킹!!!! 만약 dfs 돌다가 cnt가 이미 최소값 보다 크거나 같은 경우 볼 필요 없으므로 return
    if idx >= ed-1:         # 만약 idx가 마지막에 도달하거나 마지막보다 크다면
        if cnt < Min:       # 만약 최소값보다 더 작다면
            Min = cnt       # 최소값 갱신
        return

    for i in range(lst[idx]):   # lst배열의 idx에 있는 배열 값만큼 갈 수 있음
        dfs(idx+i+1,cnt+1)

T = int(input())
for tc in range(1,T+1):
    lst = list(map(int,input().split()))
    ed = lst.pop(0)         # 배열의 맨 처음은 원소의 갯수이므로 pop해서 따로 빼냄
    Min = 21e8
    dfs(0,0)
    print(f"#{tc} {Min-1}") # 출발지에서의 배터리 장착은 교환횟수에서 제외하므로 -1


from detectron2.data import DatasetCatalog, MetadataCatalog
from detectron2.data.datasets import load_coco_json, load_sem_seg
from detectron2.data.datasets.coco_panoptic import merge_to_panoptic

from dt2.visualize import STUFF_COLORS, THING_COLORS

def register_my_dataset(
    name,
    metadata,
    image_root,
    panoptic_root,
    sem_seg_root,
    instances_json,
):
    DatasetCatalog.register(
        name,
        lambda: merge_to_panoptic(
            load_coco_json(instances_json, image_root, name),
            load_sem_seg(sem_seg_root, image_root, image_ext="png"),
        ),
    )
    MetadataCatalog.get(name).set(
        panoptic_root=panoptic_root,
        image_root=image_root,
        panoptic_json="/tmp/placeholder/",
        sem_seg_root=sem_seg_root,
        json_file=instances_json,
        evaluator_type="coco",
        ignore_label=255,
        thing_colors=THING_COLORS,
        stuff_colors=STUFF_COLORS,
        stuff_classes=["AlternativeRailPolygon", "MainRailPolygon", "Train"],
        **metadata,
    )


import string

'''
  filename: char_string specifing the data file to read. For example, 'ATNT_face_image.txt'
  class_ids:  array/list that contains the classes to be pick. For example: (3, 5, 8, 9)
  Returns: an multi-dimension array or a file, containing the data (both attribute vectors and class labels)
           of the selected classes
  We use this subroutine to pick a small part of the data to do experiments. For example for handwrittenletter data,
  we can pick classes "C" and "F" for a 2-class experiment. Or we pick "A,B,C,D,E" for a 5-class experiment.
'''
def pickDataClass(filename, class_ids):
    with open(filename) as f:
        flag = True
        lables = []
        data = []
        for line in f:
            raw_data = line[:-1].split(',')
            if flag:
                lables = raw_data
                flag = False
            row = []

            for i in range(len(raw_data)):
                if int(lables[i]) in class_ids:
                    row.append(int(raw_data[i]))
            data.append(row)

        return data

def getLabels(filename, class_ids):
    with open(filename) as f:
        flag = True
        lables = []
        for line in f:
            if flag:
                raw_data = line[:-1].split(',')
                lables = raw_data
                flag = False
        return lables

def splitData2TestTrain(data, number_per_class,  test_instances):
    trainX = []
    testX = []
    trainY = []
    testY = []
    flag = True
    number_of_classes = len(data[0])//number_per_class
    for row in data:
        train_row = []
        test_row = []
        for j in range(number_of_classes):
            for i in range(number_per_class):
                index = j*number_per_class
                if  index+i in range(index + test_instances[0], index + test_instances[1]+1):
                    test_row.append(row[index+i])
                else:
                    train_row.append(row[index+i])

        if flag:
            trainY = train_row
            testY = test_row
            flag = False
        else:
            trainX.append(train_row)
            testX.append(test_row)

    return [trainX, trainY, testX, testY]

def write_2_file(trainX, trainY, testX, testY):
    trainX.insert(0 , trainY)
    testX.insert(0, testY)

    train = ""
    test = ""
    for i in range(len(trainX)):
        string = ""
        for j in trainX[i]:
            string += str(j) + ","
        train += string[:-1] + "\n"

    with open('TrainingData.txt', 'w') as f:
        f.write(train)
    f.close()

    for i in range(len(testX)):
        string = ""
        for j in testX[i]:
            string += str(j) + ","
        test += string[:-1] + "\n"

    with open('TestingData.txt', 'w') as f:
        f.write(test)
    f.close()

def letter_2_digit_convert(letters):
    letters = letters.upper()
    a2z = string.ascii_uppercase

    converted_digits = []

    for letter in letters:
        converted_digits.append(a2z.index(letter) + 1)

    return converted_digits

# This is how you can use the Data Handler to create Train and test dataset and splitting the data.
def run(filename):
    # filename = "trainDataXY.txt"
    class_ids = [1, 3, 5]
    data = pickDataClass(filename, class_ids)
    # print(len(data), data)

    number_per_class = data[0].count(class_ids[0])
    test_instances = [1,3]
    trainX, trainY, testX, testY = splitData2TestTrain(data, number_per_class, test_instances)

    write_2_file(trainX, trainY, testX, testY)

    print(letter_2_digit_convert('EADFBTGH'))

if __name__ == "__main__":
    run("HandWrittenLetters.txt")


import scrapy
import os
### THIS FILE IS COMPLETE
counter = 0
class imdbSpider(scrapy.Spider):

    def stringGen():
        toReturn = []
        minUserrtg = 1.0
        maxUserrtg = 1.0
        BASE_STRING = 'https://www.imdb.com/search/title?title_type=feature&user_rating='
        REST_OF_STRING = '&count=10000&sort=alpha,asc'

        while minUserrtg <4:

            maxUserrtg = min(maxUserrtg, 10)
            minUserrtg = min(minUserrtg, 10)
            toReturn.append(BASE_STRING +(str)(minUserrtg) + ',' + (str)(maxUserrtg) + REST_OF_STRING)
            minUserrtg += 0.1
            maxUserrtg += 0.1

        return toReturn

    name = 'imdb'
    start_urls = stringGen()
    print(start_urls)
    handle_httpstatus_list = [404]

    def parse(self, response):

        SET_SELECTOR = '.lister-item-content'
        global counter
        for object in response.css(SET_SELECTOR):

            NAME_SELECTOR = 'a ::text'
            YEAR_SELECTOR = '.lister-item-year ::text'
            GENRE_SELECTOR = '.genre ::text'
            yield{

                 'name': object.css(NAME_SELECTOR).extract_first().encode('utf-8'),

                 'imdbRating': object.xpath(".//strong/text()").extract_first().encode('utf-8'),
                 'year': object.css(YEAR_SELECTOR).extract_first().strip("()").encode('utf-8'),
                 'genre': [x.strip() for x in object.css(GENRE_SELECTOR).extract()],
                 'BoxOffice': object.xpath('//span[5]/@data-value').extract_first().strip(",")
            }

        NEXT_PAGE_SELECTOR = 'a ::attr(href)'
        if(counter == 0):
            next_page = response.xpath("//*[@id='main']/div/div/div[4]/div/a/@href").extract_first()
        else:
            next_page = response.xpath("//*[@id='main']/div/div/div[4]/div/a[2]/@href").extract_first()
        counter = counter + 1
        if next_page:
            yield scrapy.Request(
                response.urljoin(next_page),
                callback=self.parse
            )


import pygame
from pygame.locals      import *
from utils              import my_quit

class KeyboardEvent:

    def __init__(self):
        self.x = 0
        self.y = 0
        self.game_speed = 0.5
        self.disco = 0

    def key_callback(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                my_quit()
            elif event.type == pygame.KEYDOWN:
                self.key_down(event)
            elif event.type == pygame.KEYUP:
                self.key_up(event)
        self.key_pressed()

    def key_pressed(self):
        keys_pressed = pygame.key.get_pressed()
        if keys_pressed[K_a]:
            self.x += 0.10
        if keys_pressed[K_d]:
            self.x -= 0.10
        if keys_pressed[K_w]:
            self.y -= 0.10
        if keys_pressed[K_s]:
            self.y += 0.10
        if keys_pressed[K_LSHIFT]:
            self.game_speed = 1.5

    def key_up(self, event):
        if event.key == pygame.K_a or event.key == pygame.K_d:
            self.x = 0
        if event.key == pygame.K_w or event.key == pygame.K_s:
            self.y = 0
        if event.key == pygame.K_LSHIFT:
            self.game_speed = 0.5

    def key_down(self, event):
        if event.key == pygame.K_ESCAPE:
            my_quit()
        if event.key == pygame.K_SPACE:
            if self.disco == 1:
                self.disco = 0
            else:
                self.disco = 1


# Given an array of integers and an integer k, you need to find the total number of continuous subarrays
# whose sum equals to k.
#
# Example 1:
#
# Input:nums = [1,1,1], k = 2
# Output: 2
# Input : arr[] = {10, 2, -2, -20, 10},
# k = -10
# Output : 3
# Subarrays: arr[0...3], arr[1...4], arr[3..4]
# have sum exactly equal to -10.
#
# Input : arr[] = {9, 4, 20, 3, 10, 5},
# k = 33
# Output : 2
# Subarrays : arr[0...2], arr[2...4] have sum
# exactly equal to 33.
#
#
# Constraints:
#
# The length of the array is in range [1, 20,000].
# The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].

# An efficient solution is while traversing the array, store sum so far in currsum. Also, maintain the count of
# different values of currsum in a map. If the value of currsum is equal to the desired sum at any instance
# increment count of subarrays by one. The value of currsum exceeds the desired sum by currsum – sum. If this
# value is removed from currsum then the desired sum can be obtained. From the map find the number of subarrays
# previously found having sum equal to currsum-sum. Excluding all those subarrays from the current subarray,
# gives new subarrays having the desired sum. So increase count by the number of such subarrays. Note that
# when currsum is equal to the desired sum then also check the number of subarrays previously having a sum
# equal to 0. Excluding those subarrays from the current subarray gives new subarrays having the desired sum.
# Increase count by the number of subarrays having sum 0 in that case.

def find_sum_k_integers(arr, k):

    # traversing the array
    # store sum so far in currsum
    # maintain the count of different values of currsum in a map.
    # if currsum is equal to k at any instance increment count of subarrays
    # if currsum > currsum – k
    # find in map the previously found sum equal to currsum - k
    # increase count by the number of such subarrays, excluding all those subarrays in the current subarray
    # currsum is equal to the desired sum, then also need to check the number of subarrays previously having a sum of 0

    current_sum = 0
    occurances = 0
    sums_so_far = {}

    for i in range(len(arr)):

        current_sum += arr[i]

        if current_sum == k:
            occurances += 1

        if current_sum - k in sums_so_far:
            occurances += sums_so_far[current_sum - k]

        if current_sum in sums_so_far:
            sums_so_far[current_sum] += 1
        else:
            sums_so_far[current_sum] = 1

    return occurances

if __name__ == '__main__':

    results = find_sum_k_integers([1, 1, 1], 2)
    print(results)


import os
import pickle
import time

import numpy as np
from get_data import get_data
from make_learner import make_learner

def fit_model(config):
    X, y = get_data(config['id'])
    learner = make_learner(config['algorithm'], config['hyperparams'])

    start = time.clock()
    model = learner.fit(X, y)
    fit_time = time.clock() - start

    if not os.path.exists('models'):
        os.makedirs('models')

    with open('models/model_{id}.pickle'.format(id=config['id']), 'wb') as f:
        pickle.dump(model, f, protocol=pickle.HIGHEST_PROTOCOL)

    return {
        "time": round(fit_time, 2),
        "rows": np.array(X).shape[0],
        "size": os.path.getsize('models/model_{id}.pickle'.format(id=config['id']))/1000
    }


from django.shortcuts import render
from realtys.models import Realty, RealtyType, Bill, RealtyManager, Usd
from django.db.models import Q
from django import template

# Create your views here.

def index(request):
    title = 'Агенство недвижимости'
    managers = RealtyManager.objects.all()[:3]
    realtys = Realty.objects.all()[:5]
    return render(request, 'index.html', {'realtys': realtys, 'managers': managers, 'title': title})

def contacts(request):
    title = 'Контакты'
    if request.method == 'POST':
        name = request.POST.get('name')
        email = request.POST.get('email')
        subject = request.POST.get('subject')
        message = request.POST.get('message')
        from_email = 'plotnikov-d@bk.ru'
        email_manager = 'menedger@mail.ru'
        bill_obj = Bill(name=name, email=email, subject=subject, message=message, from_email=from_email,
                        email_manager=email_manager)
        bill_obj.save()
    return render(request, 'contacts.html', {'title': title})

def search(request):
    usd = Usd.objects.last()
    rate_usd = round(1/usd.usd_now, 2)
    title = 'Поиск'
    text_q = request.GET.get('text')
    price1_q = request.GET.get('price1')
    price2_q = request.GET.get('price2')
    s1_q = request.GET.get('s1')
    s2_q = request.GET.get('s2')
    type_q = request.GET.get('type')

    if text_q:
        text = text_q.split()
        q_object = Q()
        for i in text:
            q_object &= (Q(info__iregex=i) | Q(header__iregex=i))
        realtys = Realty.objects.filter(q_object)
    else:
        realtys = Realty.objects.all()

    if price1_q:
        realtys = realtys.filter(cost__gte=price1_q)

    if price2_q:
        realtys = realtys.filter(cost__lte=price2_q)

    if s1_q:
        realtys = realtys.filter(s__gte=s1_q)

    if s2_q:
        realtys = realtys.filter(s__lte=s2_q)

    if type_q:
        realtys = realtys.filter(type=type_q)

    types = RealtyType.objects.all()

    return render(request, 'search.html', {'realtys': realtys, 'types': types, 'title': title, 'rate_usd': rate_usd})

def detail(request, id):
    realty = Realty.objects.get(id=id)
    title = realty.header
    if realty.sale:
        new_cost = int(realty.cost  - (realty.cost * realty.sale))
    else:
        new_cost = 0

    return render(request, 'detail.html', {'realty': realty, 'title': title, 'new_cost': new_cost})


import sys
from cs50 import get_string

if len(sys.argv) == 2:
    if sys.argv[1].isalpha():
        key = sys.argv[1]
        key_len = len(sys.argv[1])
        i = 0
        plain = get_string("plaintext: ")
        print("ciphertext: ", end="")
        for letter in plain:
            if not letter.isalpha():
                print(letter, end="")
                continue
            else:
                # setting key
                key_letter = key[i % key_len]
                if key_letter.isupper():
                    k = ord(key_letter) - 65
                else:
                    k = ord(key_letter) - 97
                i += 1
                if not letter.isupper():  # male literki
                    letter = chr(97 + (ord(letter)+k-97) % 26)
                    print(letter, end="")
                else:  # duze literki
                    letter = chr(65 + (ord(letter)+k-65) % 26)
                    print(letter, end="")
        print("")
    else:
        sys.exit(1)
else:
    print("inappropriate number of arguments!")
    sys.exit(1)


import logging
from typing import Dict, List, Optional, Any

from langchain.callbacks.manager import (
    AsyncCallbackManagerForChainRun,
    CallbackManagerForChainRun,
)

from ix.chains.callbacks import IxHandler
from langchain.chains.base import Chain
from pydantic import BaseModel

from ix.chat.models import Chat
from ix.task_log.models import Task
from ix.task_log.tasks.agent_runner import start_agent_loop

logger = logging.getLogger(__name__)

MODERATOR_PROMPT = """
You are Ix, an AI assistant. You assist you user with requests by delegating work
to your team of agents.

Respond to all questions for help about Ix and how you work with links to discord and github.
The github includes documentation and source code.

discord: https://discord.gg/jtrMKxzZZQ
github: https://github.com/kreneskyp/ix

AGENTS:
{agents}

CHAT_HISTORY:
{chat_history}

INSTRUCTION:
- Choose the agent from AGENTS who can best process the user request.
- If no AGENT can process then respond as best you can.
- You must choose an agent or respond to the user request.
- Consider the CHAT_HISTORY in your decisions.
"""

CHOOSE_AGENT_PARAMS = {
    "type": "object",
    "properties": {
        "agents": {
            "type": "string",
        }
    },
    "required": ["agents"],
}

class ChooseAgent(BaseModel):
    agent_id: int

CHOOSE_AGENT_FUNC = {
    "class_path": "ix.chains.functions.FunctionSchema",
    "config": {
        "name": "delegate_to_agent",
        "description": "delegate the user request to this agent.",
        "parameters": ChooseAgent.schema_json(indent=4),
    },
}

LLM_CHOOSE_AGENT_CONFIG = {
    "class_path": "ix.chains.llm_chain.LLMChain",
    "config": {
        "verbose": True,
        "output_key": "delegation_or_text",
        "llm": {
            "class_path": "langchain.chat_models.openai.ChatOpenAI",
            "config": {
                "model": "gpt-4-0613",
                "request_timeout": 240,
                "temperature": 0,
                "verbose": True,
                "max_tokens": 1000,
                "streaming": True,
            },
        },
        "prompt": {
            "class_path": "langchain.prompts.chat.ChatPromptTemplate",
            "config": {
                "messages": [
                    {
                        "role": "assistant",
                        "template": MODERATOR_PROMPT,
                        "input_variables": ["agents", "chat_history"],
                    },
                    {
                        "role": "user",
                        "template": "{user_input}",
                        "input_variables": ["user_input"],
                    },
                ]
            },
        },
        "functions": [CHOOSE_AGENT_FUNC],
        "output_parser": {
            "class_path": "ix.chains.functions.OpenAIFunctionParser",
            "config": {
                "parse_json": True,
            },
        },
    },
}

class ChatModerator(Chain):
    """
    Chain that compares user input to a list of agents and chooses the best agent to handle the task
    """

    selection_chain: Chain

    @property
    def _chain_type(self) -> str:
        return "ix_chat_moderator"

    @property
    def output_keys(self) -> List[str]:
        """Outputs task_id of spawned subtask"""
        return ["task_id"]

    @property
    def input_keys(self) -> List[str]:
        """Input keys this chain expects."""
        return ["user_input", "chat_id"]

    def agent_prompt(self, chat: Chat) -> str:
        """build prompt for configured tools"""
        lines = []
        agents = chat.agents.all().order_by("alias")
        for i, agent in enumerate(agents):
            lines.append(f"{i}. {agent.alias}: {agent.purpose}")
        return "\n".join(lines)

    def _call(
        self,
        inputs: Dict[str, Any],
        run_manager: Optional[CallbackManagerForChainRun] = None,
    ) -> Dict[str, Any]:
        # 0. get chat and agents
        chat_id = inputs["chat_id"]
        chat = Chat.objects.get(id=chat_id)
        agents = list(chat.agents.order_by("alias"))

        # 1. select agent
        agent_prompt = "\n".join(
            [f"{i}. {agent.alias}: {agent.purpose}" for i, agent in enumerate(agents)]
        )
        user_input = inputs["user_input"]
        logger.debug(f"Routing user_input={user_input}")
        inputs_mutable = inputs.copy()
        inputs_mutable["agents"] = agent_prompt
        response = self.selection_chain(
            inputs=inputs_mutable, callbacks=run_manager.get_child()
        )
        delegation_or_text = response["delegation_or_text"]
        logger.debug(f"Moderator returned response={delegation_or_text}")

        # response is either a delegation or a direct text response
        if isinstance(delegation_or_text, dict):
            agent_index = delegation_or_text["arguments"]["agent_id"]
            delegate_to = agents[agent_index].alias
            text = f"Delegating to @{delegate_to}"
        else:
            text = delegation_or_text
            delegate_to = None

        # 2. send message to chat
        ix_handler = IxHandler.from_manager(run_manager)
        ix_handler.send_agent_msg(text)

        # 3. delegate to the agent
        task_id = None
        if delegate_to is not None:
            agent = chat.agents.get(alias=delegate_to)
            subtask = chat.task.delegate_to_agent(agent)
            logger.debug(
                f"Delegated to agent={agent.alias} task={subtask.id} input={inputs}"
            )
            start_agent_loop.delay(
                task_id=str(subtask.id), chain_id=str(agent.chain_id), inputs=inputs
            )
            task_id = str(subtask.id)

        return {"text": text, "task_id": task_id}

    async def _acall(
        self,
        inputs: Dict[str, str],
        run_manager: Optional[AsyncCallbackManagerForChainRun] = None,
    ) -> Dict[str, str]:
        # 0. get chat and agents
        chat_id = inputs["chat_id"]
        chat = await Chat.objects.aget(id=chat_id)
        agents = [value async for value in chat.agents.order_by("alias").aiterator()]

        # 1. select agent
        agent_prompt = "\n".join(
            [f"{i}. {agent.alias}: {agent.purpose}" for i, agent in enumerate(agents)]
        )
        user_input = inputs["user_input"]
        logger.debug(f"Routing user_input={user_input}")
        inputs_mutable = inputs.copy()
        inputs_mutable["agents"] = agent_prompt
        response = await self.selection_chain.acall(
            inputs=inputs_mutable, callbacks=run_manager.get_child()
        )
        delegation_or_text = response["delegation_or_text"]
        logger.debug(f"Moderator returned response={delegation_or_text}")

        # response is either a delegation or a direct text response
        if isinstance(delegation_or_text, dict):
            agent_index = delegation_or_text["arguments"]["agent_id"]
            delegate_to = agents[agent_index].alias
            text = f"Delegating to @{delegate_to}"
        else:
            text = delegation_or_text
            delegate_to = None

        # 2. send message to chat
        ix_handler = IxHandler.from_manager(run_manager)
        await ix_handler.send_agent_msg(text)

        # 3. delegate to the agent
        task_id = None
        if delegate_to is not None:
            task = await Task.objects.aget(id=chat.task_id)
            agent = await chat.agents.aget(alias=delegate_to)
            subtask = await task.adelegate_to_agent(agent)
            logger.debug(
                f"Delegated to agent={agent.alias} task={subtask.id} input={inputs}"
            )
            start_agent_loop.delay(
                task_id=str(subtask.id), chain_id=str(agent.chain_id), inputs=inputs
            )
            task_id = str(subtask.id)

        return {"text": text, "task_id": task_id}


import sys
import os

inname = sys.argv[1]

nuc = ['A', 'C', 'G', 'T']
comp = [dict(), dict(), dict()]

for pos in range(3):
    for n in nuc:
        comp[pos][n] = 0

with open(inname, 'r') as infile:
    fields = infile.readline().rstrip('\n').split()
    ntaxa = int(fields[0])
    nsite = int(fields[1])
    ncodon = nsite // 3
    for line in infile:
        fields = line.rstrip('\n').split()
        if len(fields) == 2:
            name = fields[0]
            seq = fields[1]
            for i in range(ncodon):
                c = seq[3*i:3*(i+1)]
                for pos in range(3):
                    if c[pos] in nuc:
                        comp[pos][c[pos]] = comp[pos][c[pos]] + 1

for pos in [2]:
# for pos in range(3):
    tot = 0
    for n in nuc:
        tot = tot + comp[pos][n]
    print("pos : ", pos)
    for n in nuc:
        print(n, comp[pos][n] / tot)
    print()


import os
import sys
import argparse
import numpy as np
import time

# Still TODO: optimize, write outputfile function, account for unknown words

def init_training(training_list):
    '''Given a list of training files, parse through each file to create a list
    of lists, where each list is a sentence. Each element in each sentence is a
    mini-list where the 1st element is the word, and the 2nd element is the tag.

    The format of the each training file in the list is:
    word1 : tag1
    word2 : tag2 and so on.'''

    big_list = [] # list of lists, where each list is a sentence

    for train_file in training_list:

        f = open(train_file, 'r')
        words = f.readlines() # words is a list, every element being: "word : tag"
        # remove any empty lines:
        # words = [w for w in words if w != '\n']
        tmp_sentence = [] # list of word, tag pairs (temporary; overwritten after every sentence found)

        for w in words: # w has format: "word : tag"

            #if it's a blank line, ignore it:
            if w == '\n':
                continue

            w = w.split(" : ") # split w into a list with format: w = ["word", "tag"]

            # if the tag has a newline character in it (e.g. "NP0\n"), remove it
            if w[1][-1:] == '\n':
                w[1] = w[1][:-1]
            tmp_sentence.append(w)

            # if the word is "." or "!" or "?" or ";" then it's the end of a sentence, so restart the sentence list
            if w[0] == "." or w[0] == "!" or w[0] == "?" or w[0] == ";":
                big_list.append(tmp_sentence)
                tmp_sentence = []

        # if finished the file and still contents in tmp_sentence, append the last "sentence" anyway
        if len(tmp_sentence) != 0:
            big_list.append(tmp_sentence)
            tmp_sentence = []

        f.close()

    return big_list

def init_I(training_data, all_tags):
    '''Given a big list of lists (each list is a sentence, each elem in the list
    is a ["word", "tag"] pair), initialize the I matrix, which is row containing
    the probability of each tag for the first word (s0) in the sentence.'''

    first_tags = [] # list of the first tags for the first word of each sentence (evidence for s0)

    for sentence in training_data:
        first_tags.append(sentence[0][1])

    # print("first tags: ", first_tags)
    first_tags = np.array(first_tags)

    # initialize the I matrix as a numpy list of 0's, the same length as all_tags:
    I = np.zeros(len(all_tags))

    # for each tag in all_tags, count how many times it appears in first_tags and give its probability using numpy
    for i in range(len(all_tags)):
        I[i] = np.count_nonzero(first_tags == all_tags[i]) # len(first_tags) is the total number of sentences

    # add a small number to each elem in I to prevent 0 rows, and renormalize
    I = I + 0.01
    I = I / np.sum(I)
    # print(I)
    return I # each index in I corresponds to the index of the tag in all_tags

def init_T(training_data, all_tags):
    '''Given the big list of lists, initialize the T (state transition) matrix,
    which is an n x n numpy array where n is the number of all tags. Each elem
    in the matrix is the probability of transition from tag [row] to tag [col].
    In other words, the elem at index ["NPO"]["ADJ"] is the probability of transitioning
    from an NPO tag to an ADJ tag.'''

    # initialize T as a numpy 2D array of 0.000001's, the same size as all_tags:
    T = np.full((len(all_tags), len(all_tags)), 0.01) # to prevent 0 rows
    # print(len(all_tags))

    for sentence in training_data:
        # count every transition from one tag to another in the sentence.
        # Add 1 to the corresponding elem in T for each transition
        for i in range(len(sentence) - 1):
            T[all_tags.index(sentence[i][1])][all_tags.index(sentence[i+1][1])] += 1

    # divide each elem in T by the total number of transitions FROM that tag
    for i in range(len(all_tags)):
        if np.sum(T[i]) != 0: # to prevent dividing
            T[i] = T[i] / np.sum(T[i])

    return T

def init_M(training_data, all_tags):
    '''Initialize the M (observation probabilities) dictionary, where each key
    is a word that has been encountered in training, and each value is a list
    (length = 91) of probabilities of each tag for that word. These numbers
    are normalized by the total number of times that TAG has appeared. P(ek | sk)'''

    M = {}
    tag_count = np.zeros(len(all_tags)) # list of the number of times each tag has appeared

    for sentence in training_data:
        for word in sentence:
            if word[0] not in M:
                M[word[0]] = np.zeros(len(all_tags))
            M[word[0]][all_tags.index(word[1])] += 1 # add 1 to the corresponding tag (word[1]) in the list at the correct index
            tag_count[all_tags.index(word[1])] += 1 # add 1 to the corresponding tag counter list at the correct index

    # Normalize numbers in M by the total number of times that TAG has appeared (not the word)
    for word in M:
        for i in range(len(all_tags)):
            if tag_count[i] != 0:
                M[word][i] = M[word][i] / tag_count[i]

    return M

def init_E(test_file):
    '''Given the test file, create a list of lists of all the sentences and words
    in the test file.'''
    E = [] # list of lists
    f = open(test_file, 'r')
    W = list(map(str.rstrip, f.readlines())) # remove the newline characters too. list of all words
    f.close()

    tmp_sentence = [] # list of words in the current sentence
    for w in W:
        if w != "." and w != "!" and w != "?" and w != ";":
            tmp_sentence.append(w)
        else:
            tmp_sentence.append(w)
            E.append(tmp_sentence)
            tmp_sentence = []

    # account for last sentence anyway if doesn't end in proper punctuation
    if len(tmp_sentence) != 0:
        E.append(tmp_sentence)

    # for sentence in E:
    #     print(sentence)
    #     print()

    return E

def viterbi(E, S, I, T, M): #TODO - make faster (vectorize?) and account for never seen before words
    '''Execute the Viterbi algorithm to predict the most likely sequence of tags.
    The inputs to the function are:
    - E: list of observations (all words in ONE sentence; test sentence); e.g.  ["she", "walked", "downstairs", "."]
    - S: set of hidden state values (set of all tags)
    - I: initial probabilities row vector; P(s0)
    - T: transition matrix; P(S_k+1 | S_k)
    - M: observation dictionary; P(E_k | S_k)'''

    prob = np.zeros((len(E), len(S)))
    prev = np.zeros((len(E), len(S)))

    # determine values for time step 0 (base case):
    if E[0] not in M.keys():
        # at first, just assume a uniform distribution for all tags (since I should be good enough)
        prob[0] = I*1/len(S)
        pass
    else:
        # print("base case M[E[0]]: ", M[E[0]])
        prob[0] = I*M[E[0]]

    prev[0] = None
    x = np.argmax(prob[0])

    # create distribution (array with 91 elems) for unseen words;
    unknown_tagp = np.zeros(len(S))
    unknown_tagp[S.index("NP0")] = 0.1 # proper nouns
    unknown_tagp[S.index("AJ0")] = 0.1 # adjectives
    unknown_tagp[S.index("NN2")] = 0.1 # plural common nouns
    unknown_tagp[S.index("NN1")] = 0.1 # singular common nouns
    # make the remaining values equal so it adds to 1:
    unknown_tagp[unknown_tagp == 0] = 0.6 / (len(S) - 2)

    # time steps 1 to length(E) (recursive case):
    for t in range(1, len(E)): # t is the index of the current word
        for i in range(0, len(S)): # i is the index of the current tag

            # if it's a word that hasn't been seen before: TODO. Also TODO - deal with tags never appearing (don't make 0)
            if E[t] not in M.keys():
                # print("word not in M: ", E[t])
                #TODO - set prob[t][i] and prev[t][i] to something
                x = np.argmax(prob[t-1]*T.T[i]*unknown_tagp[i]) # or * 1/len(S))
                prob[t][i] = prob[t-1][x] * T[x][i] * unknown_tagp[i] # the probability of the current tag given the previous tag
                prev[t][i] = x # the previous tag that maximizes the probability

            else:
                x = np.argmax(prob[t-1]*T.T[i]*M[E[t]][i])
                prob[t][i] = prob[t-1][x] * T[x][i] * M[E[t]][i] # the probability of the current tag given the previous tag
                prev[t][i] = x # the previous tag that maximizes the probability

        # normalize to prevent probabilities from getting too small:
        if np.sum(prob[t]) != 0:
            prob[t] = prob[t] / np.sum(prob[t])
        else:
            print("PROBLEM: all of prob[t] is 0 for E[t] = ", E[t]) # TODO - fix this
            pass

    # for l in prev:
    #     print(l)
    #     print()

    tag_sequence = []

    # Backtrack to find the most likely sequence of tags:
    x = np.argmax(prob[len(E)-1]) # in the last row of prob, get the index of the max probability:
    # in the last row of prev, get the tag corresponding to that maxp index:
    tag_sequence = np.concatenate((int(x), tag_sequence), axis=None)

    # now backtrack through prev to get the rest of the tags:
    for t in range(len(E)-1, 0, -1): # go backwards from the last to the first row of prev
        tag_sequence = np.concatenate((prev[t][int(x)], tag_sequence), axis=None)
        x = prev[t][int(x)]

    # print("tag_sequence: ", tag_sequence)
    # show tags corresponding to each tag in tag sequence:
    # for i in range(len(tag_sequence)):
        # print(S[int(tag_sequence[i])])

    return tag_sequence

def get_accuracy(tag_guesses, answerfile, all_tags):
    '''After running Viterbi, compare the predicted tag sequence to the actual
    tag sequence in the test file. Return the accuracy. The inputs are:
    - tag_guesses: list of lists of the predicted tags for each sentence in the test file
    - answerfile: the test file with the answers
    - all_tags: list of all possible tags'''

    f = open(answerfile, 'r')
    W = list(map(str.rstrip, f.readlines())) # remove the newline characters too. list of all words
    f.close()

    # get the true tag sequence:
    true_tag_sequence = []
    f = open(answerfile, 'r')
    words = f.readlines() # words is a list, every element being: "word : tag"
    tmp_sentence = [] # list of word, tag pairs (temporary; overwritten after every sentence found)

    for w in words: # w has format: "word : tag"
        w = w.split(" : ") # split w into a list with format: w = ["word", "tag"]

        # if there's no index error and has a newline character in it (e.g. "NP0\n"), remove it
        if w[1] != '' and w[1][-1:] == '\n':
            w[1] = w[1][:-1]
        tmp_sentence.append(w)

        # if the word is "." or "!" or "?" or ";" then it's the end of a sentence, so restart the sentence list
        if w[0] == "." or w[0] == "!" or w[0] == "?" or w[0] == ";":
            true_tag_sequence.append(tmp_sentence)
            tmp_sentence = []

    # if finished the file and still contents in tmp_sentence, append the last "sentence" anyway
    if len(tmp_sentence) != 0:
        true_tag_sequence.append(tmp_sentence)
        tmp_sentence = []
    f.close()

    # format of true_tag_sequence: list of lists of word, tag pairs

    # for sentence in true_tag_sequence:
    #     print(sentence)
    #     print()

    # for every sentence and every tag, compare and get accuracy:
    correct = 0
    total = 0
    for i in range(len(true_tag_sequence)):
        for j in range(len(true_tag_sequence[i])):
            total += 1
            # compare the actual tag to the predicted tag:
            # print(tag_guesses)
            if true_tag_sequence[i][j][1] == all_tags[int(tag_guesses[i][j])]:
                correct += 1
            else:
                # print("wrong guess for this word: ", true_tag_sequence[i][j][0], "expected tag: ", true_tag_sequence[i][j][1])
                pass

    return correct/total

def write_output(tag_guesses, E, outputfile, all_tags):
    '''Write the predicted tag sequence to a file. The inputs are:
    - tag_guesses: list of lists of the predicted tags for each sentence in the test file
    - E: the test list of lists (just the words to add the tags to with format word : tag)
    - outputfile: the file to write the output to with formaat word : tag on each line
    - all_tags: list of all possible tags'''

    # Read through every word (line) in the test file and add the : tag from the tag_guesses list:
    # f = open(testfile, 'r')
    # testwords = f.readlines() # words is a list, every element being: "word : tag"
    # # remove the newline characters too:
    # testwords = list(map(str.rstrip, testwords))
    # f.close()

    # Write in the output file the word corresponding to the tag:
    f = open(outputfile, 'w')
    for sentence_i in range(len(tag_guesses)):
        for word_i in range(len(tag_guesses[sentence_i])):
            # hardcode to ensure all punctuation correct:
            if E[sentence_i][word_i] == "." or E[sentence_i][word_i] == "!" or E[sentence_i][word_i] == "?" \
                or E[sentence_i][word_i] == ";" or E[sentence_i][word_i] == "," or E[sentence_i][word_i] == ":":
                # print("replaced punctuation")
                f.write(E[sentence_i][word_i] + " : " + "PUN" + "\n")
            elif E[sentence_i][word_i] == '"':
                # print("replaced quotation")
                f.write(E[sentence_i][word_i] + " : " + "PUQ" + "\n")
            else:
                f.write(E[sentence_i][word_i] + " : " + all_tags[int(tag_guesses[sentence_i][word_i])] + "\n")

    f.close()

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--trainingfiles",
        action="append",
        nargs="+",
        required=True,
        help="The training files."
    )
    parser.add_argument(
        "--testfile",
        type=str,
        required=True,
        help="One test file."
    )
    parser.add_argument(
        "--outputfile",
        type=str,
        required=True,
        help="The output file."
    )
    args = parser.parse_args()

    training_list = args.trainingfiles[0]
    print("training files are {}".format(training_list))
    print("test file is {}".format(args.testfile))
    print("output file is {}".format(args.outputfile))

    time1 = time.time()

    print("************************* INITIALIZING DATA ************************")

    all_tags = ["AJ0", "AJC", "AJS", "AT0", "AV0", "AVP", "AVQ", "CJC", "CJS", "CJT", "CRD",
        "DPS", "DT0", "DTQ", "EX0", "ITJ", "NN0", "NN1", "NN2", "NP0", "ORD", "PNI",
        "PNP", "PNQ", "PNX", "POS", "PRF", "PRP", "PUL", "PUN", "PUQ", "PUR", "TO0",
        "UNC", 'VBB', 'VBD', 'VBG', 'VBI', 'VBN', 'VBZ', 'VDB', 'VDD', 'VDG', 'VDI',
        'VDN', 'VDZ', 'VHB', 'VHD', 'VHG', 'VHI', 'VHN', 'VHZ', 'VM0', 'VVB', 'VVD',
        'VVG', 'VVI', 'VVN', 'VVZ', 'XX0', 'ZZ0', 'AJ0-AV0', 'AJ0-VVN', 'AJ0-VVD',
        'AJ0-NN1', 'AJ0-VVG', 'AVP-PRP', 'AVQ-CJS', 'CJS-PRP', 'CJT-DT0', 'CRD-PNI', 'NN1-NP0', 'NN1-VVB',
        'NN1-VVG', 'NN2-VVZ', 'VVD-VVN', 'AV0-AJ0', 'VVN-AJ0', 'VVD-AJ0', 'NN1-AJ0', 'VVG-AJ0', 'PRP-AVP',
        'CJS-AVQ', 'PRP-CJS', 'DT0-CJT', 'PNI-CRD', 'NP0-NN1', 'VVB-NN1', 'VVG-NN1', 'VVZ-NN2', 'VVN-VVD']

    # initialize the training data
    training_data = init_training(training_list)

    # training_data = training_data[0:2] # shorten training to 2 sentences for testing
    # for sentence in training_data:
    #     print(sentence)
    #     print("")
    # initialize the 3 probability matrices
    I = init_I(training_data, all_tags)
    # print(I)
    T = init_T(training_data, all_tags)
    # for line in T:
    #     print(line)
    M = init_M(training_data, all_tags)
    # print(M)

    # initialize the other inputs to viterbi:
    E = init_E(args.testfile)

    print("*************************** TAGGING ********************************")

    tag_guesses = []
    for i in range(len(E)): # for every sentence
        tag_guesses.append(viterbi(E[i], all_tags, I, T, M))

    # answerfile = training_list[0] #  for now, test on the same file that was used to train
    answerfile = "training2.txt" # for testing on a specific dataset - MODIFY depending on what answers are

    # write to output file:
    write_output(tag_guesses, E, args.outputfile, all_tags)

    time2 = time.time()
    print("time taken is {}\n".format(time2-time1))
    # print("accuracy is {}".format(get_accuracy(tag_guesses, answerfile, all_tags))) #TODO  - comment out later


from gpiozero import LED, Button
import time
from random import uniform
from os import _exit

leftName = input("Left player, Type Name: ")
rightName = input("Right player, Type Name: ")
led = LED(4)
rightBTN = Button(15)
leftBTN = Button(14)

led.on()
time.sleep(uniform(5,10))
led.off()

def pressed(button):
    if button.pin.number == 14:
        print(leftName + " won the game!")
    else:
        print(rightName + " won the game!")
    _exit(0)

rightBTN.when_pressed = pressed
leftBTN.when_pressed = pressed


import random

import numpy as np
import os
from dotenv import load_dotenv

load_dotenv()

L = int(os.getenv("L"))
# Space between next car
S0 = int(os.getenv("S0"))
# Reaction time
T = int(os.getenv("T"))
# Max speed between V_MAX1 et V_MAX2 (m/s)
V_MAX1, V_MAX2 = float(os.getenv("V_MAX1")), float(os.getenv("V_MAX2"))
# Acceleration max between A_MAX1 and A_MAX2 (m/s^^2)
A_MAX1, A_MAX2 = float(os.getenv("A_MAX1")), float(os.getenv("A_MAX2"))
# Max brake between B_MAX1 and B_MAX2 (m/s^^2)
B_MAX1, B_MAX2 = float(os.getenv("B_MAX1")), float(os.getenv("B_MAX2"))
# 1/TRUCK_RATE will be a truck
TRUCK_RATE = int(os.getenv("TRUCK_RATE"))
# Same goes for motorcycles
MOTOR_RATE = int(os.getenv("MOTOR_RATE"))

checkpoint1 = int(os.getenv("CHECKPOINT1"))
checkpoint2 = int(os.getenv("CHECKPOINT2"))
checkpoint3 = int(os.getenv("CHECKPOINT3"))
checkpoint4 = int(os.getenv("CHECKPOINT4"))

class Vehicle:
    def __init__(self, config={}):
        self.type = "car"  # Or "Truck" or "Motorcycle"
        self.checkpoints = {checkpoint1: False, checkpoint2: False, checkpoint3: False, checkpoint4: False}
        self.last_time_lane_change = 0
        self.started_insertion = 0
        self.position = 0
        self.stopped = False
        self.a = 0
        self.x = 0
        self.adj = []
        self.path = []
        self.b_max = random.uniform(B_MAX1, B_MAX2)
        self.a_max = random.uniform(A_MAX1, A_MAX2)
        self.v_max = random.uniform(V_MAX1, V_MAX2)
        self.v = self.v_max
        self.T = T
        self.s0 = S0
        self.timeline = 0
        self.l = L
        self.h = 2
        self.color = (0, 0, 255)
        # Calculate properties
        self.sqrt_ab = 2 * np.sqrt(self.a_max * self.b_max)
        self._v_max = self.v_max

        # Update configuration
        for attr, val in config.items():
            setattr(self, attr, val)

        self.current_road_index = self.path[0]

        self.init_type()

    # Generates buses and motorcycles
    def init_type(self):
        # Generate randomly bus
        random_number = random.randint(1, TRUCK_RATE)
        if random_number == TRUCK_RATE:
            self.type = "truck"
            self.l = 8
            self.a_max = 1.2
            self.v_max = 18
            self.color = (255, 0, 0)
            return
        random_number = random.randint(1, MOTOR_RATE)
        if random_number == MOTOR_RATE:
            self.l = 3
            self.h = 1
            self.a_max = 4
            self.v_max = 48
            self.color = (255,255,0)

    def set_started_insertion(self, time):
        self.started_insertion = time

    def update(self, lead, dt):

        # Update position and velocity
        if self.v + self.a * dt < 0:
            self.x -= 1 / 2 * self.v * self.v / self.a
            self.v = 0
        else:
            self.v += self.a * dt
            self.x += self.v * dt + self.a * dt * dt / 2

        # Update acceleration
        alpha = 0
        if lead:
            delta_x = lead.x - self.x - lead.l
            delta_v = self.v - lead.v

            alpha = (self.s0 + max(0, self.T * self.v + delta_v * self.v / self.sqrt_ab)) / delta_x

        self.a = self.a_max * (1 - (self.v / self.v_max) ** 4 - alpha ** 2)

        if self.stopped:
            self.a = -self.b_max * self.v / self.v_max

    def stop(self):
        self.stopped = True

    def unstop(self):
        self.stopped = False

    def slow(self, v):
        self.v_max = v

    def unslow(self):
        self.v_max = self._v_max

    def set_pos(self, position):
        self.position = position


import numpy as np

def mask2bbox(mask):
    x0 = np.where(mask)[0].min()
    x1 = np.where(mask)[0].max()
    y0 = np.where(mask)[1].min()
    y1 = np.where(mask)[1].max()

    return np.array([x0, x1, y0, y1])

def bbox_ratio(bbox, ratio=1.):
    x0, x1, y0, y1 = bbox.tolist()
    h = x1 - x0
    w = y1 - y0
    cx = float(x0 + x1) / 2
    cy = float(y0 + y1) / 2

    h_new = h * float(ratio)
    w_new = w * float(ratio)

    x0_new = np.round(cx - h_new / 2)
    x1_new = np.round(cx + h_new / 2)
    y0_new = np.round(cy - w_new / 2)
    y1_new = np.round(cy + w_new / 2)

    return np.array([x0_new, x1_new, y0_new, y1_new])

def carve_bbox_to_im(bbox, imshape):
    H, W = imshape

    x0, x1, y0, y1 = bbox.tolist()

    x0_new = max(x0, 0)
    x1_new = min(x1, H)
    y0_new = max(y0, 0)
    y1_new = min(y1, W)

    return np.array([x0_new, x1_new, y0_new, y1_new])

def bbox_area(bbox):
    return (bbox[1] - bbox[0]) * (bbox[3] - bbox[2])


import sys
import heapq

input = sys.stdin.readline
INF = sys.maxsize
heap = []

N = int(input())
M = int(input())

graph = [[] for _ in range(N+1) ]
table = [INF] * (N+1)

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

table[vs] = 0
heapq.heappush(heap, ((0, vs)))

while heap:
    wei, now_node = heapq.heappop(heap)
    if now_node == vd: break
    if len(graph[now_node]) == 0: continue
    for new_node, w in graph[now_node]:
        new_w = wei+w
        if table[new_node] > new_w:
            table[new_node] = new_w
            heapq.heappush(heap, (new_w, new_node))
print(table[vd])

2023 Spring/Week 7 DijkstraFloyd/1916_최소비용 구하기/1916_안지완.py


import random  # 导入随机模块

# 班级学生名单列表
class_list = [
    "01张晴晴",
    "02吴佳煜",
    "03钱秋萍",
    "04陆诗颖",
    "05邹佳芸",
    "06朱蒋岚",
    "07赵怡月",
    "08游欣悦",
    "09沈雨洋",
    "10徐佳雨",
    "11王欣怡",
    "12陈皖晴",
    "13朱辰媛",
    "14孙俏",
    "15李宜霏",
    "16任煜霏",
    "17台育蕊",
    "18陈慧",
    "19何雪",
    "20莫佳妮",
    "21顾心怡",
    "22杨钰雯",
    "23苏雨欣",
    "24曾海瑞",
    "25张权凯",
    "26江宇轩",
    "27陈晨",
    "28陈浩",
    "29蒋熠晨",
    "30张思诚",
    "31罗一鸣",
    "32杨熠恒",
    "33周昊天",
    "34曹国梁",
    "35王奇",
    "36沈心源",
    "37沈振亓",
    "38周顺利",
    "39康治坤",
    "40周杰",
    "41陆小凡",
    "42沈航宇",
    "43徐天成",
    "44鲍宇",
    "45王缪丞",
    "46庞宇帆"
    ]

def luck(_number):
    # 创建幸运儿空列表
    _luck = []
    for _ in range(_number):
        item = random.choice(class_list)
        _luck.append(item)
        class_list.remove(item)
    return _luck

def luck2(_number):
    _luck = []
    for _ in range(_number):
        idx = random.randint(0, len(class_list) - 1)
        item = class_list.pop(idx)
        _luck.append(item)
    return _luck

def luck3(_number):
    random.shuffle(class_list)  # 乱序
    return class_list[:_number]

luck_list = luck3(5)  # 获取5位幸运儿
# luck_list.sort()  # 排序
print('幸运儿是：')
for i in luck_list:  # 遍历输出幸运名单
    print('  ', i)

第1学期/【第15-16课】数据与结构/Luck幸运儿.py


import requests
import data.get_Spotify_token as get_Spotify_token

# Get top 10 most listened songs on Spotify

access_token = get_Spotify_token.get_token()
base_url = 'https://api.spotify.com/v1/'

headers = {
    'Authorization': 'Bearer {}'.format(access_token)
}

featured_playlists_endpoint = \
    'playlists/2YRe7HRKNRvXdJBp9nXFza/tracks?offset=0&limit=10'
featured_playlists_url = ''.join([base_url, featured_playlists_endpoint])

def get_most_popular_songs():
    response = requests.get(featured_playlists_url, headers=headers)
    songs = response.json().get('items')
    return songs


from dolfin import *
import ufl

def gamma(theta, w):
    r"""Return shear strain vector calculated from primal variables:

    .. math::
        \gamma = \nabla w - \theta
    """
    return grad(w) - theta

def psi_T(gamma, **kwargs):
    r"""Returns transverse shear energy density calculated using:

    Isotropic case:
    .. math::
        \psi_T(\gamma, \ldots) = \frac{E \kappa t}{4(1 + \nu))}\gamma**2

    Args:
        gamma: Shear strain, typically UFL form with shape (2,).
        **kwargs: Isotropic case:
            E: Young's modulus, Constant or Expression.
            nu: Poisson's ratio, Constant or Expression.
            t: Thickness, Constant or Expression.
            kappa: Shear correction factor, Constant or Expression.

    Returns:
        UFL expression of transverse shear stress vector.
    """
    if 'E' in kwargs and 'kappa' in kwargs and 't' in kwargs and 'nu' in kwargs:
        E = kwargs['E']
        kappa = kwargs['kappa']
        t = kwargs['t']
        nu = kwargs['nu']

        T = ((E*kappa*t)/(4.0*(1.0 + nu)))*inner(gamma, gamma)
    else:
        raise ArgumentError("Invalid set of kwargs to specify transverse shear stress vector.")

    return T

def inner_e(x, y, restrict_to_one_side=False, quadrature_degree=1):
    r"""The inner product of the tangential component of a vector field on all
    of the facets of the mesh (Measure objects dS and ds).

    By default, restrict_to_one_side is False. In this case, the function will
    return an integral that is restricted to both sides ('+') and ('-') of a
    shared facet between elements. You should use this in the case that you
    want to use the 'projected' version of DuranLibermanSpace.

    If restrict_to_one_side is True, then this will return an integral that is
    restricted ('+') to one side of a shared facet between elements. You should
    use this in the case that you want to use the `multipliers` version of
    DuranLibermanSpace.

    Args:
        x: DOLFIN or UFL Function of rank (2,) (vector).
        y: DOLFIN or UFL Function of rank (2,) (vector).
        restrict_to_one_side (Optional[bool]: Default is False.
        quadrature_degree (Optional[int]): Default is 1.

    Returns:
        UFL Form.
    """
    dSp = Measure('dS', metadata={'quadrature_degree': quadrature_degree})
    dsp = Measure('ds', metadata={'quadrature_degree': quadrature_degree})
    n = ufl.geometry.FacetNormal(x.ufl_domain())
    t = as_vector((-n[1], n[0]))
    a = (inner(x, t)*inner(y, t))('+')*dSp + \
        (inner(x, t)*inner(y, t))*dsp
    if not restrict_to_one_side:
        a += (inner(x, t)*inner(y, t))('-')*dSp
    return a


import time
from urllib.parse import urlparse, urlunparse

def check_http(url: str):
    if url.split(':')[0] in ['http', 'https']:
        return url
    return "http://" + url

def check_http_alternative(url: str):
    parsed_url = urlparse(url)
    if not parsed_url.scheme:
        parsed_url = parsed_url._replace(scheme='http')
        return urlunparse(parsed_url)
    return url

with open("../data/domains_for_test_check_http.txt", 'r') as file:
    domains = [line.strip() for line in file]

    start_time = time.time()
    for domain in domains:
        check_http(domain)
    original_time = time.time() - start_time

    start_alt_time = time.time()
    for domain in domains:
        check_http_alternative(domain)
    alternative_time = time.time() - start_alt_time

print(f"Original function execution time: {original_time:.6f} seconds")
print(f"Alternative function execution time: {alternative_time:.6f} seconds")

# check_http = 0.005257 seconds
# check_http_alternative = 0.082233 seconds


from collections import defaultdict

def change(s):
    # '{'와 '}'를 제거한 뒤 ','단위로 잘라 리스트 반환
    s = s.lstrip('{')
    s = s.rstrip('}')
    return s.split(',')

def solution(s):
    answer = []
    # 중복 방지를 위한 used dict
    used = defaultdict(lambda: 0)
    # s를 '},'단위로 잘라 리스트로 변환 후 각 항목 마다 change 실행
    ns = list(map(change, s.split('},')))
    # 길이 순서로 오름차순 정렬
    # ns.sort(key=len)
    ns.sort(key=lambda x: len(x))

    # 순서에 맞춰 answer 배열에 값 추가
    for t in ns:
        for i in range(len(t)):
            if used[t[i]]:
                continue
            used[t[i]] = 1
            answer.append(int(t[i]))

    return answer

print(solution('{{2},{2,1},{2,1,3},{2,1,3,4}}'))


"""
------------------------------------------
File name: utilities.py
Author: Clare Huang
"""
import numpy as np
from math import pi, exp

def static_stability(height, area, theta, s_et=None, n_et=None):
    """
    The function "static_stability" computes the vertical gradient (z-derivative)
    of hemispheric-averaged potential temperature, i.e. d\tilde{theta}/dz in the def-
    inition of QGPV in eq.(3) of Huang and Nakamura (2016), by central differencing.
    At the boundary, the static stability is estimated by forward/backward differen-
    cing involving two adjacent z-grid points:

        i.e. stat_n[0] = (t0_n[1] - t0_n[0]) / (height[1] - height[0])
            stat_n[-1] = (t0_n[-2] - t0_n[-1]) / (height[-2] - height[-1])

    Please make inquiries and report issues via Github: https://github.com/csyhuang/hn2016_falwa/issues

    Parameters
    ----------
    height : numpy.array
        Array of z-coordinate [in meters] with dimension = (kmax), equally spaced
    area : numpy.ndarray
        Two-dimension numpy array specifying differential areal element of each grid point;
        dimension = (nlat, nlon).
    theta : numpy.ndarray
        Matrix of potential temperature [K] with dimension (kmax,nlat,nlon) or (kmax,nlat)
    s_et : int, optional
        Index of the latitude that defines the boundary of the Southern hemispheric domain;
        initialized as nlat/2 if not input
    n_et : int, optional
        Index of the latitude that defines the boundary of the Southern hemispheric domain;
        initialized as nlat/2 if not input

    Returns
    -------
    t0_n : numpy.array
        Area-weighted average of potential temperature (\tilde{\theta} in HN16)
        in the Northern hemispheric domain with dimension = (kmax)
    t0_s : numpy.array
        Area-weighted average of potential temperature (\tilde{\theta} in HN16)
        in the Southern hemispheric domain with dimension = (kmax)
    stat_n : numpy.array
        Static stability (d\tilde{\theta}/dz in HN16) in the Northern hemispheric
        domain with dimension = (kmax)
    stat_s : numpy.array
        Static stability (d\tilde{\theta}/dz in HN16) in the Southern hemispheric
        domain with dimension = (kmax)

    """

    nlat = theta.shape[1]
    if s_et is None:
        s_et = nlat // 2
    if n_et is None:
        n_et = nlat // 2

    stat_n = np.zeros(theta.shape[0])
    stat_s = np.zeros(theta.shape[0])

    if theta.ndim == 3:
        zonal_mean = np.mean(theta, axis=-1)
    elif theta.ndim == 2:
        zonal_mean = theta

    if area.ndim == 2:
        area_zonal_mean = np.mean(area, axis=-1)
    elif area.ndim == 1:
        area_zonal_mean = area

    csm_n_et = np.sum(area_zonal_mean[-n_et:])
    csm_s_et = np.sum(area_zonal_mean[:s_et])

    t0_n = np.sum(zonal_mean[:, -n_et:] * area_zonal_mean[np.newaxis, -n_et:],
                  axis=-1) / csm_n_et
    t0_s = np.sum(zonal_mean[:, :s_et] * area_zonal_mean[np.newaxis, :s_et],
                  axis=-1) / csm_s_et

    stat_n[1:-1] = (t0_n[2:] - t0_n[:-2]) / (height[2:] - height[:-2])
    stat_s[1:-1] = (t0_s[2:] - t0_s[:-2]) / (height[2:] - height[:-2])
    stat_n[0] = (t0_n[1] - t0_n[0]) / (height[1] - height[0])
    stat_n[-1] = (t0_n[-2] - t0_n[-1]) / (height[-2] - height[-1])
    stat_s[0] = (t0_s[1] - t0_s[0]) / (height[1] - height[0])
    stat_s[-1] = (t0_s[-2] - t0_s[-1]) / (height[-2] - height[-1])

    return t0_n, t0_s, stat_n, stat_s

def compute_qgpv_givenvort(omega, nlat, nlon, kmax, unih, ylat, avort,
                           potential_temp, t0_cn, t0_cs, stat_cn,
                           stat_cs, nlat_s=None, scale_height=7000.):
    """
    The function "compute_qgpv_givenvort" computes the quasi-geostrophic potential vorticity based on the absolute vorticity, potential temperature and static stability given in a *hemispheric domain*.

    Please make inquiries and report issues via Github: https://github.com/csyhuang/hn2016_falwa/issues

    Parameters
    ----------
    omega : float, optional
        Rotation rate of the planet.
    nlat : int
        Latitudinal dimension of the latitude grid.
    nlon : int
        Longitudinal dimension of the longitude grid.
    kmax : int
        Vertical dimension of the height grid.
    unih : numpy.array
        Numpy array of height in [meters]; dimension = (kmax)
    ylat : numpy.array
        Numpy array of latitudes in [degrees]; dimension = (nlat)
    avort : numpy.ndarray
        Three-dimension numpy array of absolute vorticity (i.e. relative vorticity
        + 2*Omega*sin(lat)) in [1/s]; dimension = (kmax x nlat x nlon)
    potential_temp : numpy.ndarray
        Three-dimension numpy array of potential temperature in [K];
        dimension = (kmax x nlat x nlon)
    t0_cn : numpy.array
        Area-weighted average of potential temperature (\tilde{\theta} in HN16)
        in the Northern hemispheric domain with dimension = (kmax)
    t0_cs : numpy.array
        Area-weighted average of potential temperature (\tilde{\theta} in HN16)
        in the Southern hemispheric domain with dimension = (kmax)
    stat_cn : numpy.array
        Static stability (d\tilde{\theta}/dz in HN16) in the Northern hemispheric
        domain with dimension = (kmax)
    stat_cs : numpy.array
        Static stability (d\tilde{\theta}/dz in HN16) in the Southern hemispheric
        domain with dimension = (kmax)
    scale_height : float
        Scale height of the atmosphere in [m] with default value 7000.

    Returns
    -------
    QGPV : numpy.ndarray
        Three-dimension numpy array of quasi-geostrophic potential vorticity;
        dimension = (kmax x nlat x nlon)
    dzdiv : numpy.ndarray
        Three-dimension numpy array of the stretching term in QGPV;
        dimension = (kmax x nlat x nlon)

    """

    if nlat_s is None:
        nlat_s = nlat // 2

    # --- Next, calculate PV ---
    qgpv = np.empty_like(potential_temp)  # av1+av2+av3+dzdiv

    av1 = np.ones((kmax, nlat, nlon)) * \
        2*omega*np.sin(np.deg2rad(ylat[np.newaxis, :, np.newaxis]))

    # Calculate the z-divergence term
    zdiv = np.empty_like(potential_temp)
    dzdiv = np.empty_like(potential_temp)
    for kk in range(kmax):  # This is more efficient
        zdiv[kk, :nlat_s, :] = exp(-unih[kk]/scale_height)*(
            potential_temp[kk, :nlat_s, :] - t0_cs[kk]
        )/stat_cs[kk]
        zdiv[kk, -nlat_s:, :] = exp(-unih[kk]/scale_height)*(
            potential_temp[kk, -nlat_s:, :] - t0_cn[kk]
        )/stat_cn[kk]

        dzdiv[1:kmax-1, :, :] = np.exp(
            unih[1:kmax-1, np.newaxis, np.newaxis]/scale_height
        ) * (zdiv[2:kmax, :, :]-zdiv[0:kmax-2, :, :]) \
            / (unih[2:kmax, np.newaxis, np.newaxis] -
               unih[0:kmax-2, np.newaxis, np.newaxis])

        dzdiv[0, :, :] = exp(unih[0]/scale_height) *\
            (zdiv[1, :, :]-zdiv[0, :, :]) /\
            (unih[1, np.newaxis, np.newaxis] - unih[0, np.newaxis, np.newaxis])
        dzdiv[kmax-1, :, :] = exp(unih[kmax-1]/scale_height) *\
            (zdiv[kmax-1, :, :]-zdiv[kmax-2, :, :]) /\
            (unih[kmax-1, np.newaxis, np.newaxis] -
             unih[kmax-2, np.newaxis, np.newaxis])

        qgpv = avort + dzdiv * av1
    return qgpv, dzdiv

def zonal_convergence(field, clat, dlambda, planet_radius=6.378e+6, tol=1.e-5):

    """
    The function "zonal_convergence" computes the zonal component of the convergence operator of an arbitrary field f(lat, lon), i.e. it computes on the spherical surface:
    -1/(planet_radius * cos(lat)) * partial d(f(lat, lon))/partial d(lon)

    Please make inquiries and report issues via Github: https://github.com/csyhuang/hn2016_falwa/issues

    Parameters
    ----------
    field : numpy.ndarray
        An arbitrary field that one needs to compute zonal divergence with dimension [nlat, nlon]

    clat : numpy.array
        Numpy array of cosine latitude; dimension [nlat]

    dlambda : float
        Differential element of longitude

    planet_radius : float, optional
        Radius of the planet in meters.
        Default = 6.378e+6 (Earth's radius)

    tol : float, optional
        Tolerance below which clat is considered infinitely small that the corresponding grid points will have returned result = 0 (to avoid division by zero). Default = 1.e-5

    Returns
    -------
    ans : numpy.ndarray
        Zonal convergence of field with the dimension same as field, i.e. [nlat, nlon]

    """

    zonal_diff = np.zeros_like(field)
    zonal_diff[:, 1:-1] = field[:, 2:] - field[:, :-2]
    zonal_diff[:, 0] = field[:, 1] - field[:, -1]
    zonal_diff[:, -1] = field[:, 0] - field[:, -2]

    # This is to avoid divided by zero
    finite_clat = np.abs(clat) > tol

    zonal_diff[finite_clat, :] = zonal_diff[finite_clat, :] * \
                                 (-1./(planet_radius * clat[finite_clat, np.newaxis] * 2. * dlambda))

    return zonal_diff

def curl_2d(ufield, vfield, clat, dlambda, dphi, planet_radius=6.378e+6):
    """
    Assuming regular latitude and longitude [in degree] grid, compute the curl
    of velocity on a pressure level in spherical coordinates.
    """

    ans = np.zeros_like(ufield)
    ans[1:-1, 1:-1] = (vfield[1:-1, 2:] - vfield[1:-1, :-2])/(2.*dlambda) - \
                      (ufield[2:, 1:-1] * clat[2:, np.newaxis] -
                       ufield[:-2, 1:-1] * clat[:-2, np.newaxis])/(2.*dphi)
    ans[0, :] = 0.0
    ans[-1, :] = 0.0
    ans[1:-1, 0] = ((vfield[1:-1, 1] - vfield[1:-1, -1]) / (2. * dlambda) -
                    (ufield[2:, 0] * clat[2:] -
                     ufield[:-2, 0] * clat[:-2]) / (2. * dphi))
    ans[1:-1, -1] = ((vfield[1:-1, 0] - vfield[1:-1, -2]) / (2. * dlambda) -
                     (ufield[2:, -1] * clat[2:] -
                      ufield[:-2, -1] * clat[:-2]) / (2. * dphi))
    ans[1:-1, :] = ans[1:-1, :] / planet_radius / clat[1:-1, np.newaxis]
    return ans


import urllib.request
import json
import pprint

# write a program that:
# 1. Prompts the user for a search term
# 2. Queries Twitter for status updates based on the search term
# 3. Iterates through the resulting data dictionary and
# 4. Prints the text of the status with the most retweets,
#    along with the number of times the status has been retweeted.

search_term = input('Please enter a search term: ')
url = 'https://eecs110-twitter-proxy.herokuapp.com/1.1/search/tweets.json?q='
url += search_term
request = urllib.request.urlopen(url)
data = json.loads(request.read().decode())

pprint.pprint(data, depth=1) # dictionary with 2 entries
pprint.pprint(data, depth=2) # The first value is another dictionary, the second is a list of dictionaries
#pprint.pprint(data, depth=3)


###### Voice Comparison Engine ######

# imports
from sklearn.manifold import TSNE, MDS
from keras.models import load_model
from IPython.display import SVG, Audio, display
from keras.utils.vis_utils import model_to_dot
import numpy as np
import matplotlib.pyplot as plt
from keras.models import Model
from keras.layers import Input
import soundfile as sf
import os
import sys

# session controll parameters to keep keras from hogging all the GPU memory
from keras.backend.tensorflow_backend import set_session
import tensorflow as tf
config = tf.ConfigProto()
config.gpu_options.allow_growth = True  # dynamically grow the memory used on the GPU
config.log_device_placement = True  # to log device placement (on which device the operation ran)

sess = tf.Session(config=config)

set_session(sess)  # set this TensorFlow session as the default session for Keras

# load model
model_path = 'models/siamese_voice.hdf5'
siamese = load_model(model_path)
siamese = load_model(model_path)
siamese._make_predict_function()

def whiten(batch, rms=0.038021):
    """This function whitens a batch so each sample has 0 mean and the same root mean square amplitude """

    if len(batch.shape) != 3:
        raise(ValueError, 'Input must be a 3D array of shape (n_segments, n_timesteps, 1).')

    # Subtract mean
    sample_wise_mean = batch.mean(axis=1)
    whitened_batch = batch - np.tile(sample_wise_mean, (1, 1, batch.shape[1])).transpose((1, 2, 0))

    # Divide through
    sample_wise_rescaling = rms / np.sqrt(np.power(batch, 2).mean())
    whitened_batch = whitened_batch * np.tile(sample_wise_rescaling, (1, 1, batch.shape[1])).transpose((1, 2, 0))

    return whitened_batch

def preprocessor(downsampling, whitening=True):
    """ Downsample and fix RMS for inference """
    def preprocessor_(batch):
        ([i_1, i_2], labels) = batch
        i_1 = i_1[:, ::downsampling, :]
        i_2 = i_2[:, ::downsampling, :]
        if whitening:
            i_1, i_2 = whiten(i_1), whiten(i_2)

        return [i_1, i_2], labels

    return preprocessor_

downsampling = 4
whiten_downsample = preprocessor(downsampling, whitening=True)

def embedings(file_path_list):
    """ Make embedings from a list of audio files"""

    X=[]
    Z=[]
    for file_path in file_path_list:
        instance,samperate=sf.read(file_path)
        instance=instance[:48000]
        Z.append([instance,samperate])
    X_ = np.stack(list(zip(*Z))[0])[:, :, np.newaxis]
    [X_, _], _ = whiten_downsample(([X_, X_], []))

    X.append(X_)
    X = np.concatenate(X)
    return X

def average_distance(audio_list1,audio_list2):
    """ Calculate distance between list of two audio sample/s """

    voice_saved=embedings(audio_list1)
    voice_captured=embedings(audio_list2)
    all_distances=siamese.predict([voice_saved,voice_captured])
    avg_dist=np.average(all_distances)
    return avg_dist


"""Datenbanken.

Author:
    Felix Karg <felix.karg@uranus.uni-freiburg.de>

"""

from copy import deepcopy

# from typing import Dict, List, Set

#   project(tbl: List[Dict[str, str]], keys: Set[str]) -> List[Dict[str, str]]:
def project(tbl, keys):
    """Projection of given table to possibly subset of it,
        excluding not named ones.

    Args:
        tbl (List[Dict[str, str]]): The table where parts might be stripped
        keys (Set[str]): The set of Keys which are supposed to stay

    Returns:
        List[Dict[str, str]]: new table, which is now possibly a subset of the
            first given table (tbl), excluding items not listed in keys.

    """
    ret = deepcopy(tbl)

    for i, item in enumerate(tbl):
        for k, e in item.items():
            if k not in keys:
                del(ret[i][k])

    return ret

#   select(tbl: List[Dict[str, str]], **kwargs) -> List[Dict[str, str]]:
def select(tbl, **kwargs):
    """Selecting only those items, in which a given attribute-value pair is
        included.

    Args:
        tbl (List[Dict[str, str]]): The table elements are being selected from.
        **kwargs (Dict[str, str]): The to be matched key-value pair.

    Returns:
        List[Dict[str, str]]: Returns only the sublist with the given
            key-value pairs.

    """

    ret = []

    for item in tbl:
        add = True
        for k, v in kwargs.items():
            if not item.get(k, None) == v:
                add = False
        if add:
            ret.append(item)

    return ret

#   join(tbl1: List[Dict[str, str]], tbl2: List[Dict[str, str]],
#       *args: Tuple[List[Dict[str, str]]]) -> List[Dict[str, str]]:
def join(tbl1, tbl2, *args):
    """Join of two or more tables. Recursive calls for more than two.
    The idea is that for an item a matching 'partner' is being searched for
    and joined. Otherwise the item's being ignored in the further process.

    Args:
        tbl1 (List[Dict[str, str]]): Table1, to be joined with
        tbl2 (List[Dict[str, str]]): Table2
        args Tuple[List[Dict[str, str]]]: More tables to be joined,
            there are recursive calls for that.

    Returns:
        List[Dict[str, str]]: The joined Table.

    """

    if tbl1 is None:
        return tbl2
    if tbl2 is None:
        return tbl1

    inp1 = deepcopy(tbl1)
    inp2 = deepcopy(tbl2)
    ret = []
    keysinboth = None

    # Fails if table is empty. return empty table.
    try:
        keysinboth = set(tbl1[0].keys()) & set(tbl2[0].keys())
    except IndexError:
        return ret
    except:
        raise

    # merge fitting items.
    for k in keysinboth:
        for item in inp1:
            for etem in inp2:
                # print(etem, item)
                if item.get(k) == etem.get(k):
                    etem.update(item)
                    ret.append(etem)

    # for some reason a recursive call doesn't work ...
    # tuple slicing does, however xD
    if len(args) > 0:
        for e in args:
            ret = join(ret, e)

    return ret

series = [
        {'s_id': 'bb', 'title': 'Breaking Bad'},
        {'s_id': 'bcs', 'title': 'Better Call Saul'}]

characters = [
        {'c_id': 'ww', 'family_name': 'White', 'given_name': 'Walter'},
        {'c_id': 'sw', 'family_name': 'White', 'given_name': 'Skyler'},
        {'c_id': 'sg', 'family_name': 'Goodman', 'given_name': 'Saul'}]

series_characters = [
        {'c_id': 'ww', 's_id': 'bb'},
        {'c_id': 'sw', 's_id': 'bb'},
        {'c_id': 'sg', 's_id': 'bb'},
        {'c_id': 'sg', 's_id': 'bcs'}]


# When a function calls itself, it is called recursion.
# Binary recursion is when a function calls itself twice.

def binary_sum(sequence):
    """Return the sum of the sequence"""
    if len(sequence) == 1:
        return sequence[0]
    else:
        mid = len(sequence) // 2
        return binary_sum(sequence[:mid]) + binary_sum(sequence[mid:])

# Non recursive Implementation of binary search
def binary_search(sequence, target):
    """Return true if target is found in the sequence"""
    low = 0
    high = len(sequence) - 1
    while low <= high:
        mid = low+high//2
        if sequence[mid] == target:
            return True
        elif sequence[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return False

# Recursive Implementation of binary search
def binary_search(sequence, target, low, high):
    """Return true if target is found in the sequence"""
    if low > high:
        return False
    else:
        mid = low + high // 2
        if sequence[mid] == target:
            return True
        elif sequence[mid] < target:
            return binary_search(sequence, target, mid+1, high)
        else:
            return binary_search(sequence, target, low, mid-1)