import timeit
from random import randint
import matplotlib.pyplot as plt

def geraLista(tam):
    lista = []
    while tam:
        lista.append(tam)
        tam-=1
    return lista

def desenhaGrafico(x,lista,xl = "Entradas", yl = "Y",nam="out"):
    plt.plot(x,lista, label = "Bubble Sort")
    plt.legend(bbox_to_anchor=(1, 1),bbox_transform=plt.gcf().transFigure)
    plt.ylabel(yl)
    plt.xlabel(xl)
    plt.savefig(nam)

graf_operacoes =[]
def bb(lista):
    count = 0
    for i in range(len(lista)):
        for k in range(i, len(lista)):
            count+=1
            if lista[i] > lista[k]:
                lista[i], lista[k] = lista[k], lista[i]
    graf_operacoes.append(count)

quant = [10000, 20000, 50000, 100000]
graf_tempo = []

for i in range(len(quant)):
    print(quant[i])
    lista = geraLista(quant[i])
    graf_tempo.append(timeit.timeit("bb({})".format(lista),setup="from __main__ import bb",number=1))

desenhaGrafico(quant,graf_tempo,"Tamanho", "Tempo", "saida_time")
desenhaGrafico(quant,graf_operacoes , "Tamanho", "Operações", "saida_operacoes")


class Solution:
    def validSquare(self, p1: List[int], p2: List[int], p3: List[int], p4: List[int]) -> bool:
        points = [p1,p2,p3,p4]

        def dist(a, b):
            return (a[0] - b[0])**2 + (a[1] - b[1])**2

        res = []

        for i in range(4):
            for j in range(i+1, 4):
                res.append(dist(points[i], points[j]))

        res.sort()

        return res[0] > 0 and res[0] == res[1] and res[0] == res[2] and res[0] == res[3] and res[4] == res[5]


# You'll need to use a couple of built in functions to alphabetize a string.
# Try to avoid looking up the exact answer and look at built in functions for
# lists and strings instead.

# def alphabetize(string):
#     new_list = list(string)
#     new_list.sort()

#     new_string = ""
#     for letter in new_list:
#         new_string = new_string + letter
#     return new_string

# print(alphabetize("supercalifragilisticexpialidocious"))

word = "supercalifragilisticexpialidocious"

#conver string to list
word_li = list(word)

# sort list
word_li.sort()

# convert list to string
new_string = ''
for char in word_li:
    new_string += char

print(new_string)
# print(dir(list))

# my_li


import pandas as pd

pd.options.mode.chained_assignment = None  # default='warn'
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import glob
import os

from sklearn.metrics import confusion_matrix
from sklearn.preprocessing import scale, StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.metrics import (
    recall_score,
    accuracy_score,
    precision_score,
    precision_recall_curve,
    f1_score,
    roc_curve,
)
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.decomposition import PCA
from sklearn.calibration import CalibratedClassifierCV
from sklearn.neural_network import MLPClassifier
from xgboost import XGBClassifier

import warnings
from sklearn.exceptions import DataConversionWarning

warnings.filterwarnings(action="ignore", category=DataConversionWarning)

def mvp_predict():
    """ Returns: mvp_summary - pandas dataframe containing players with the
                               top MVP probabilities
    """
    player_df = pd.read_json("data/1980-2018-per100-labeled.json")
    player_df19 = pd.read_json("data/2019-per-100.json")
    combined_df = pd.read_json("data/combined-player-team-stats.json")
    combined_df19 = pd.read_json("data/2019-combined.json")
    y_features = "MVP"
    x_features = [
        "Player",
        "Year",
        "Tm",
        "MP",
        "FG",
        "FGA_x",
        "3P",
        "3PA",
        "2P",
        "2PA",
        "FT",
        "FTA_x",
        "ORB",
        "DRB",
        "TRB",
        "AST_x",
        "STL_x",
        "BLK_x",
        "TOV_x",
        "PF_x",
        "PTS_x",
        "ORtg",
        "DRtg",
        "WIN_PCT",
        "CONF_RANK",
        "USG%",
        "WS",
    ]
    x_all = combined_df[x_features]
    y_all = combined_df[y_features]
    # Drop the columns containing text data, leaving only numerical data
    drop_txt = lambda x: x.drop(columns=["Player", "Year", "Tm"])
    x_all_num = drop_txt(x_all)

    x_old = x_all.loc[x_all.Year > 1980]
    y_old = y_all.loc[x_all.Year > 1980]
    x_19 = combined_df19[x_features]
    x_train, x_test, y_train, y_test = train_test_split(x_old, y_old, test_size=0.3)

    x_train_num = drop_txt(x_train)
    x_test_num = drop_txt(x_test)
    x_old_num = drop_txt(x_old)
    x_new_num = drop_txt(x_19)
    testing = False
    show_pr_curves = testing
    if not testing:
        x_train_num = x_old_num
        y_train = y_old

    scale_pipe = lambda x: Pipeline([("scaler", StandardScaler()), x])
    calibrate = lambda x: CalibratedClassifierCV(x, method="isotonic", cv=5)

    xgb_calib = calibrate(XGBClassifier(learning_rate=0.1, n_jobs=2, n_estimators=100))
    xgb_clf = scale_pipe(("xgb", xgb_calib))
    xgb_clf.fit(x_train_num, y_train)
    if show_pr_curves:
        precf_gb, recf_gb, thrf_gb = precision_recall_curve(
            y_test, xgb_clf.predict_proba(x_test_num).transpose()[1], pos_label=1
        )
        plt.plot(recf_gb, precf_gb)

    xgb_pred_prob = xgb_clf.predict_proba(x_new_num).transpose()[1]
    xgb_pred_indices = np.where(xgb_pred_prob > 0.1)

    rf_calib = calibrate(
        RandomForestClassifier(n_jobs=2, n_estimators=300, max_features="auto")
    )
    rf_clf = scale_pipe(("forest", rf_calib))
    rf_clf.fit(x_train_num, y_train)
    rf_pred_prob = rf_clf.predict_proba(x_new_num).transpose()[1]
    if show_pr_curves:
        precf_rf, recf_rf, thrf_rf = precision_recall_curve(
            y_test, rf_clf.predict_proba(x_test_num).transpose()[1], pos_label=1
        )
        plt.plot(recf_rf, precf_rf)

    mlp = calibrate(
        MLPClassifier(
            solver="lbfgs", alpha=1e-5, hidden_layer_sizes=(100, 100, 100, 100)
        )
    )
    mlp_clf = scale_pipe(("mlp", mlp))
    mlp_clf.fit(x_train_num, y_train)
    mlp_pred_prob = mlp_clf.predict_proba(x_new_num).transpose()[1]
    if show_pr_curves:
        precf_rf, recf_rf, thrf_rf = precision_recall_curve(
            y_test, mlp_clf.predict_proba(x_test_num).transpose()[1], pos_label=1
        )
        plt.plot(recf_rf, precf_rf)

    stacked_prob = np.mean(
        [1 * xgb_pred_prob, 1 * rf_pred_prob, 2 * mlp_pred_prob], axis=0
    )
    stacked_indices = np.where(stacked_prob > 0.01)
    sum_prob = stacked_prob.sum()
    x_19["Probability"] = stacked_prob / sum_prob
    mvp_candiates = x_19.iloc[stacked_indices]
    mvp_candidates = x_19.loc[x_19.Probability > 0.01]
    mvp_candidates.to_json("data/mvp-prediction-2019.json")

    mvp_summary = mvp_candiates.sort_values(by="Probability", ascending=False)[
        ["Player", "Probability"]
    ]
    return mvp_summary


# -*-coding:utf-8 -*-
__author__ = 'Yemilice_lau'
import re
def re_demo():
    txt = 'IF nmow dad fvda d adada 100 sets,the da $9.90'
    m = re.search(r'(\d).*\$(\d+\.?\d*)',txt)
    print(m.group())

if __name__ == '__main__':
    re_demo()


# -*- coding: utf-8 -*-
"""
Project: PyQt5
Creator: zhangqiang
Create time: 2019-10-14 10:48
IDE: PyCharm
Introduction:
"""

class Person1(object):
    country = 'china'  # 类属性
    __language = "Chinese"  # 私有类属性也不能直接外部调用

    def __init__(self, name, age):
        self.name = name
        self.__age = age  # 使用__下划线表示私有属性，对象不能直接调用，要通过方法调调用

    def getAge(self):
        return self.__age

    def setAge(self, age):
        if age > 100 or age < 0:
            print("age is not true")
        else:
            self.__age = age

    def __str__(self):
        info = "name :" + self.name + ",age(保密):" + str(self.__age)  # 注意这里不是self.age
        return info

# ------创建对象,调用方法，属性测试-------------------------------------------------------
stu1 = Person1("tom", 18)
print("修改前的结果：", stu1.__str__())
stu1.name = "tom_2"  # 修改stu1的name属性
print("修改name后的结果：", stu1.__str__())
# print(stu1.__age)  #直接调用私有属性__age报错，'Person1' object has no attribute '__age'

print("打印私有age内存地址：", id(stu1.getAge()))
stu1.__age = 19  # 如果这样赋值的话，不会报错，因为系统找不到这个变量，直接新建了一个。但是实际没有修改对象的属性值
print(stu1.__age)  # 有值，但是没有 实际修改stu1对象的age属性值
print("打印stu1.__age的内存地：", id(stu1.__age))  # 两个内存地址值不一样。
print("错误修改age后的值", stu1.__str__())  # 实际值没有变

stu1.setAge(22)  # 只有调用才可以修改age的值
print("正确修改age后的值", stu1.__str__())


from matplotlib import pyplot as plt
import numpy as np
students = {
    'Gautam':40,
    'Ashu':60,
    'Gaurav':50,
}
names = list(students.keys())
values = list(students.values())
plt.bar(names,values,color="green")
plt.title("Student Marks")
plt.xlabel("Names")
plt.ylabel("Marks")
plt.grid(True)
plt.show()


def read_file(file_name):
    file_obj = open(file_name, "r")  # opens the file in read mode
    words = file_obj.read().splitlines()  # puts the file into an array
    file_obj.close()
    return words

def count_increases(arr, window):
    count = 0
    last = 0
    for i in range(len(arr) - window):
        window_sum = 0
        for j in range(window):
            window_sum += int(arr[i + j])
        if last < window_sum:
            count += 1
        last = window_sum
    return count

def count_increase_circular_approach(arr, window):
    count = 0
    current_value = 0
    queue = []
    for i in range(len(arr) - window):
        if len(queue) == window:
            last_value = current_value
            current_value -= queue.pop()
            queue.append(arr[i])
            current_value += arr[i]
            if last_value < current_value:
                count += 1

array = read_file("input01.txt")
print("Count of increase times is ", count_increases(array, 1))
print("Count of increase times in circular approach is ", count_increases(array, 1))
print("Count of increase in 3 number window", count_increases(array, 3))
print("Count of increase in 3 number window in circular approach is ", count_increases(array, 3))


def unikati(s):
    t = []
    for i in s:
        if i not in t:
            t.append(i)
    return t

def avtor(tvit):
    a = tvit.split(": ")
    return a[0]

def vsi_avtorji(tviti):
    t = []
    a = [i.split(': ')[0] for i in tviti]
    for name in a:
        if name not in t:
            t.append(name)
    return t

def izloci_besedo(beseda):
    s = 0
    z = 1
    y = ""
    x = ""
    g = ""
    for b in beseda:
        if b.isalnum() == False:
            s += 1
        elif b.isalnum() == True:
            break
    y += beseda[s:]
    for d in y[::-1]:
        if d.isalnum() == False:
            z += 1
        elif d.isalnum() == True:
            break
    x += beseda[:-z]
    for i in y:
        if i in x:
            g += i
    return g

def se_zacne_z(tvit, c):
    n = []
    a = tvit.split(" ")
    while (True):
        for i in a:
            if i.isalnum() == False and i[0][:1] == c:
                n.append(i[1:])
        for d in n:
            if d.isalnum() == False:
                n.append(d[:-1])
                n.remove(d)
                n.sort()
        return n

def zberi_se_zacne_z(tviti, c):
    n = []
    s = []
    a = [i.split(' ') for i in tviti]
    for e in a:
        for d in e:
            if d[0] == c:
                n.append(d[1:])
            for k in n:
                if k.isalnum() == False:
                    n.append(k[:-1])
                    n.remove(k)
    for i in n:
        if i not in s:
            s.append(i)
    return s

def vse_afne(tviti):
    n = []
    s = []
    a = [i.split(" ") for i in tviti]
    while (True):
        for tvit in a:
            for e in tvit:
                if e[0] == "@":
                    n.append(e[1:])
                for d in n:
                    if d.isalnum() == False:
                        n.append(d[:-1])
                        n.remove(d)
        for i in n:
            if i not in s:
                s.append(i)

        break
    return s

def vsi_hashtagi(tviti):
    a = [i.split(" ") for i in tviti]
    n = []
    s = []
    while (True):
        for tvit in a:
            for e in tvit:
                if e[0] == "#":
                    n.append(e[1:])
            for d in n:
                if d.isalnum() == False:
                    n.append(d[:-1])
                    n.remove(d)
        for i in n:
            if i not in s:
                s.append(i)
        break
    return s

def vse_osebe(tviti):
    a = vse_afne(tviti)
    b = vsi_avtorji(tviti)
    return sorted(unikati(a+b))

import unittest

class TestTviti(unittest.TestCase):
    tviti = [
        "sandra: Spet ta dež. #dougcajt",
        "berta: @sandra Delaj domačo za #programiranje1",
        "sandra: @berta Ne maram #programiranje1 #krneki",
        "ana: kdo so te @berta, @cilka, @dani? #krneki",
        "cilka: jst sm pa #luft",
        "benjamin: pogrešam ano #zalosten",
        "ema: @benjamin @ana #split? po dvopičju, za začetek?",
    ]

    def test_unikat(self):
        self.assertEqual(unikati([1, 2, 1, 1, 3, 2]), [1, 2, 3])
        self.assertEqual(unikati([1, 3, 2, 1, 1, 3, 2]), [1, 3, 2])
        self.assertEqual(unikati([1, 5, 4, 3, 2]), [1, 5, 4, 3, 2])
        self.assertEqual(unikati([1, 1, 1, 1, 1]), [1])
        self.assertEqual(unikati([1]), [1])
        self.assertEqual(unikati([]), [])
        self.assertEqual(unikati(["Ana", "Berta", "Cilka", "Berta"]), ["Ana", "Berta", "Cilka"])

    def test_avtor(self):
        self.assertEqual(avtor("janez: pred dvopičjem avtor, potem besedilo"), "janez")
        self.assertEqual(avtor("ana: malo krajse ime"), "ana")
        self.assertEqual(avtor("benjamin: pomembne so tri stvari: prva, druga in tretja"), "benjamin")

    def test_vsi_avtorji(self):
        self.assertEqual(vsi_avtorji(self.tviti), ["sandra", "berta", "ana", "cilka", "benjamin", "ema"])
        self.assertEqual(vsi_avtorji(self.tviti[:3]), ["sandra", "berta"])

    def test_izloci_besedo(self):
        self.assertEqual(izloci_besedo("ana?"), "ana")
        self.assertEqual(izloci_besedo("!#$%\"=%/%()/Ben-jamin'"), "Ben-jamin")
        self.assertEqual(izloci_besedo("@ana"), "ana")

        self.assertEqual(izloci_besedo("@@ana!!!"), "ana")

    def test_vse_na_crko(self):
        self.assertEqual(se_zacne_z("ana: kdo so te @berta, @cilka, @dani? #krneki", "@"), ["berta", "cilka", "dani"])
        self.assertEqual(se_zacne_z("Benjamin $je $skocil! Visoko!", "$"), ["je", "skocil"])
        self.assertEqual(se_zacne_z("Benjamin $je $skocil! #Visoko!", "$"), ["je", "skocil"])

    def test_zberi_na_crko(self):
        self.assertEqual(zberi_se_zacne_z(self.tviti, "@"), ['sandra', 'berta', 'cilka', 'dani', 'benjamin', 'ana'])
        self.assertEqual(zberi_se_zacne_z(self.tviti, "#"), ['dougcajt', 'programiranje1', 'krneki', 'luft', 'zalosten', 'split'])

    def test_vse_afne(self):
        self.assertEqual(vse_afne(self.tviti), ['sandra', 'berta', 'cilka', 'dani', 'benjamin', 'ana'])

    def test_vsi_hashtagi(self):
        self.assertEqual(vsi_hashtagi(self.tviti), ['dougcajt', 'programiranje1', 'krneki', 'luft', 'zalosten', 'split'])

    def test_vse_osebe(self):
        self.assertEqual(vse_osebe(self.tviti), ['ana', 'benjamin', 'berta', 'cilka', 'dani', 'ema', 'sandra'])

class TestDodatna(unittest.TestCase):
    tviti = [
        "sandra: Spet ta dež. #dougcajt",
        "berta: @sandra Delaj domačo za #programiranje1",
        "sandra: @berta Ne maram #programiranje1 #krneki",
        "ana: kdo so te @berta, @cilka, @dani? #krneki",
        "cilka: jst sm pa #luft",
        "benjamin: pogrešam ano #zalosten",
        "ema: @benjamin @ana #split? po dvopičju, za začetek?",
    ]

    def test_custva(self):
        self.assertEqual(custva(self.tviti, ["dougcajt", "krneki"]), ["ana", "sandra"])
        self.assertEqual(custva(self.tviti, ["luft"]), ["cilka"])
        self.assertEqual(custva(self.tviti, ["meh"]), [])

    def test_se_poznata(self):
        self.assertTrue(se_poznata(self.tviti, "ana", "berta"))
        self.assertTrue(se_poznata(self.tviti, "ema", "ana"))
        self.assertFalse(se_poznata(self.tviti, "sandra", "ana"))
        self.assertFalse(se_poznata(self.tviti, "cilka", "luft"))
        self.assertFalse(se_poznata(self.tviti, "cilka", "balon"))

if __name__ == "__main__":
    unittest.main()


import pytorch_lightning as lightning
import torch
from misc.eer import compute_eer, compute_scores, read_trials

class SVSystem(lightning.LightningModule):
    def __init__(
        self,
        fbank,
        embedding,
        loss,
        dev_trials=None,
        test_trials=None,
    ) -> None:
        super().__init__()

        self.fbank = fbank
        self.embedding = embedding
        self.loss = loss

        self.dev_trials = dev_trials
        self.test_trials = test_trials

    def forward(self, x) -> torch.Tensor:
        x = self.fbank(x)
        x = self.embedding(x)
        return x

    def configure_optimizers(self):
        optimizer = torch.optim.AdamW(self.parameters(), lr=1e-3)
        lr_scheduler = torch.optim.lr_scheduler.CyclicLR(
            optimizer,
            base_lr=1e-8,
            max_lr=1e-3,
            step_size_up=130_000 // 2,
            step_size_down=130_000 // 2,
            mode='triangular2',
            cycle_momentum=False
        )

        lr_scheduler = {
            "scheduler": lr_scheduler,
            "interval": "step"
        }

        return [optimizer], [lr_scheduler]

    def training_step(self, batch, batch_idx):
        x, y = batch
        emb = self(x)
        loss = self.loss(emb, y)
        self.log("train_loss", loss)
        return loss

    def validation_step(self, batch, batch_idx):
        x, key = batch
        emb = self(x)
        emb = {key[i]: emb[i] for i in range(len(x))}
        return emb

    def validation_epoch_end(self, output_results):
        # merge all dicts in `emb`
        emb = {}
        for output in output_results:
            emb |= output

        labels, trials = read_trials(self.dev_trials)
        scores = compute_scores(emb, trials)
        eer, threshold = compute_eer(scores, labels)

        self.log('val_eer', eer)

    def test_step(self, batch, batch_idx):
        x, key = batch
        emb = self(x)
        emb = {key[i]: emb[i] for i in range(len(x))}
        return emb

    def test_epoch__end(self, output_results):
        # merge all dicts in `emb`
        emb = {}
        for output in output_results:
            emb |= output

        labels, trials = read_trials(self.dev_trials)
        scores = compute_scores(emb, trials)
        eer, threshold = compute_eer(scores, labels)

        self.log('test_eer', eer)


import sys, threading, resource
sys.setrecursionlimit(800000)
threading.stack_size(97108864)

file = sys.argv[1]
def alg(file):
    '''Finds strongly connected components (SCCs) of a graph'''
    class Node:
        def __init__(self, name, points_to, pointed_by, fin_time=0, not_explored=True, leader=0):
            self.name = name
            self.points_to = points_to
            self.pointed_by = pointed_by
            self.fin_time = fin_time
            self.not_explored = not_explored
            self.leader = leader

    def DFS_loop1(graph):
        def DFS(graph, i):
            graph[i].not_explored = False
            for node in graph[i].pointed_by:
                if graph[node].not_explored:
                    DFS(graph, node)
            global t
            t += 1
            graph[i].fin_time = t
        global t
        t = 0
        for i in range(len(graph), 0, -1):
            if graph[i].not_explored:
                DFS(graph, i)

    def DFS_loop2(graph):
        def DFS(graph, i):
            graph[i].not_explored = False
            graph[i].leader = s
            for node in graph[i].points_to:
                if graph[node].not_explored:
                    DFS(graph, node)
        global s
        s = None
        for i in range(len(graph), 0, -1):
            if graph[G_by_fin_time[i]].not_explored:
                s = G_by_fin_time[i]
                DFS(graph, G_by_fin_time[i])

    # create graph (dict of all nodes)
    G = {}

    with open(file) as f:
        for line in f:
            temp = line.rstrip('\n').split(' ')
            temp[0], temp[1] = int(temp[0]), int(temp[1])
            if temp[0] not in G:
                G[temp[0]] = Node(temp[0], points_to=[temp[1]], pointed_by=[])
            elif temp[0] in G:
                G[temp[0]].points_to.append(temp[1])
            if temp[1] not in G:
                G[temp[1]] = Node(temp[1], points_to=[], pointed_by=[temp[0]])
            elif temp[1] in G:
                G[temp[1]].pointed_by.append(temp[0])

    # first pass
    DFS_loop1(G)

    # make fin_time to name dict
    G_by_fin_time = {}
    for node in range(len(G), 0, -1):
        G[node].not_explored = True
        G_by_fin_time[G[node].fin_time] = G[node].name

    DFS_loop2(G)

    count_dict = {}

    for node in G:
        if G[node].leader in count_dict:
            count_dict[G[node].leader] += 1
        else:
            count_dict[G[node].leader] = 1
    #    print(G[node].name, "leader=", G[node].leader)
    print(list(sorted(count_dict.values(), reverse=True))[:5])

if __name__ == '__main__':
    thread = threading.Thread(target=alg, args=(file,))
    thread.start()


from sqlalchemy import inspect
from sqlalchemy.ext.asyncio import AsyncEngine

def ok_response(data: dict):
    return {
        "status": "ok",
        "data": data,
    }

def error_response(status: str, message: str, data: dict):
    return {
        "status": status,
        "message": message,
        "data": data,
    }

def use_inspector(conn):
    inspector = inspect(conn)
    return inspector.get_table_names()

async def check_empty_table_exists(cli, tablename: str):
    engine: AsyncEngine = cli.app.database._engine
    async with engine.begin() as conn:
        tables = await conn.run_sync(use_inspector)

    assert tablename in tables


# -*- coding: utf-8 -*-
"""
Created on Sat Feb 22 23:17:49 2020

@author: Alex

code for windows
"""

class Solution:
    def numberOfSubstrings(self, s: str) -> int:
        lengh = len(s)
        count = 0
        if lengh < 3:
            return 0
        for i in range(lengh-2):
            List = ['a', 'b', 'c']
            List.remove(s[i])
            for j in range(i+1,lengh):
                if s[j] in List:
                    List.remove(s[j])
                if not List:
                    break
            if not List:
                #print(i,j,s[i:j+1])
                count += lengh - j
        return count

if __name__ == "__main__":
    s = Solution()
    a1 = "ababbbc"
    #a2 =
    print(s.numberOfSubstrings(a1))


# Verify Huang Paper Interactions

def verify(huang, union):
	"""
		Check that every interaction in huang is found in the unionized version
	"""
	fh = open(huang, 'r')
	fu = open(union, 'r')
	huang_list = []
	union_list = []
	for line in fh:
		interaction_type = line.strip().split("@")[1]
		gpcrdb1, gpcrdb2 = line.split("@")[0].split(" -- ")
		huang_list.append((gpcrdb1, gpcrdb2, interaction_type))

	for line in fu:
		interaction_type = line.strip().split("@")[1]
		gpcrdb1, gpcrdb2 = line.split("@")[0].split(" -- ")
		union_list.append((gpcrdb1, gpcrdb2, interaction_type))

	# print(union_list)
	# print(huang_list, len(huang_list), len(union_list))

	### Verify
	mismatch = []
	found = []
	for h1, h2, itype in huang_list:
		k1 = (h1, h2, itype)
		k2 = (h2, h1, itype)
		if(k1 not in union_list and k2 not in union_list):
			if(itype in ["wb", "wb2", "lwb", "lwb2"]):
				mismatch.append((h1, h2, itype))
		else:
			found.append((h1, h2, itype))

	for h1, h2, itype in mismatch:
		print("mismatch: ", h1, h2, itype)

	for h1, h2, itype in found:
		print("found: ", h1, h2, itype)

	# print(union_list)
	print("Num Mismatch: " +  str(len(mismatch)) + " Num Found: " + str(len(found)) + "\n\n")

if __name__ == "__main__":
	huang_active_path = "/scratch/PI/rondror/akma327/DynamicNetworks/data/crystal-analysis/polar-networks/b2ar_mor/huang_active.txt"
	# union_active_path = "/scratch/PI/rondror/akma327/DynamicNetworks/data/crystal-analysis/polar-networks/102716/active_polar_network.txt"
	# union_active_path = "/scratch/PI/rondror/akma327/DynamicNetworks/data/crystal-analysis/polar-networks/b2ar_mor/b2ar_mor_active.txt"
	union_active_path = "/scratch/PI/rondror/akma327/DynamicNetworks/data/crystal-analysis/polar-networks/110416/active_polar_network.txt"

	huang_inactive_path = "/scratch/PI/rondror/akma327/DynamicNetworks/data/crystal-analysis/polar-networks/b2ar_mor/huang_inactive.txt"
	# union_inactive_path = "/scratch/PI/rondror/akma327/DynamicNetworks/data/crystal-analysis/polar-networks/102716/inactive_polar_network.txt"
	# union_inactive_path = "/scratch/PI/rondror/akma327/DynamicNetworks/data/crystal-analysis/polar-networks/b2ar_mor/b2ar_mor_inactive.txt"
	union_inactive_path = "/scratch/PI/rondror/akma327/DynamicNetworks/data/crystal-analysis/polar-networks/110416/inactive_polar_network.txt"

	print("Verify active polar network")
	verify(huang_active_path, union_active_path)
	print("Verify inactive polar netork")
	verify(huang_inactive_path, union_inactive_path)


import pytest
import numpy as np
from gsp.glm import scalar, vec2, vec3, vec4

def test_ordered():
    Z1 = vec2(10)
    Z1.xy = 1,2
    Z2 = np.ones((10,2), dtype=np.float32)
    Z2[:,0], Z2[:,1] = 1, 2
    assert(np.array_equal(Z1, Z2))

def test_unordered():
    Z1 = vec2(10)
    Z1.yx = 2,1
    print(Z1)
    Z2 = np.ones((10,2), dtype=np.float32)
    Z2[:,0], Z2[:,1] = 1, 2
    assert(np.array_equal(Z1, Z2))

def test_rgba():
    Z1 = vec4(10)
    Z1.rgba = 1,2,3,4
    Z2 = np.ones((10,4), dtype=np.float32)
    Z2[:] = 1, 2,3,4
    assert(np.array_equal(Z1, Z2))

def test_mix():
    Z1 = vec4(10)
    Z1.xyba = 1,2,3,4
    Z2 = np.ones((10,4), dtype=np.float32)
    Z2[:] = 1, 2,3,4
    assert(np.array_equal(Z1, Z2))

def test_repeated_target():
    Z1 = vec2(10)
    Z1.xy = 1,2
    Z1.xy = Z1.yy
    Z2 = np.ones((10,2), dtype=np.float32)
    Z2[:,0], Z2[:,1] = 2, 2
    assert(np.array_equal(Z1, Z2))

def test_repeated_source():
    Z1 = vec2(10)
    Z1.xxy = 1,2,0
    Z2 = np.ones((10,2), dtype=np.float32)
    Z2[:,0], Z2[:,1] = 2, 0
    assert(np.array_equal(Z1, Z2))

def test_multidimensional():

    Z = vec4(10)
    Z[1].z = 1


#!/usr/bin/python
# -*- coding: iso-8859-1 -*-
#
# updated by ...: Loreto Notarantonio
# Version ......: 11-12-2017 08.25.25
#
# ######################################################################################

import os, sys
import Source as Prj
import LnLib as Ln

# from Source.Setup import GlobalVars_Module as projectGlobalVars
# gV = projectGlobalVars

################################################################################
# - M A I N
# - Prevede:
# -  2 - Controllo parametri di input
# -  5 - Chiamata al programma principale del progetto
################################################################################
def Main(gv):
    logger      = Ln.SetLogger(package = __package__)

    iniMain     = gv.iniFile.MAIN
    relay       = gv.iniFile.ARDUINO_RELAY_PORT
    monitor     = gv.iniFile.OTHER_MONITOR_PORT
    rs485Prot   = gv.iniFile.RS485_PROTOCOL
    myCMD       = gv.iniFile.MAIN_COMMAND
    mySubCMD    = gv.iniFile.SUB_COMMAND

    # convert payload fields in integer value
    fld = Ln.Dict()
    for key,val in gv.iniFile.RS485_PAYLOAD_FIELD.items(): fld[key] = int(val)
    rs485Prot.payloadFieldName = fld

    for key, val in myCMD.items():      logger.debug('command     {0:<15}: {1}'.format(key, val))
    for key, val in mySubCMD.items():   logger.debug('sub_command {0:<15}: {1}'.format(key, val))

        # ==========================================
        # = Preparazione del PAYLOAD
        # ==========================================
    payload                 = bytearray(len(fld))
    payload[fld.SRC_ADDR]   = int(rs485Prot.MasterAddress, 16)

        # ==========================================
        # = Apertura porta seriale
        # = e process del comando
        # ==========================================
    if gv.args.firstPosParameter in ['digital']:
        myPort = Prj.openRs485Port(relay, rs485Prot)
        if gv.args.secondPosParameter == 'read':
            Prj.digitalRead(myPort, gv.iniFile, srcAddress=rs485Prot.MasterAddress, destAddr=gv.args.slave_address, pinNO=gv.args.pin_number)

        elif gv.args.secondPosParameter == 'toggle':
            # Prj.digitalToggle(myPort, gv.iniFile, srcAddress=rs485Prot.MasterAddress, destAddr=gv.args.slave_address, pinNO=gv.args.pin_number)
            Prj.digitalToggle(gv, myPort, payload=payload)

        elif gv.args.secondPosParameter == 'write':
            Prj.digitalWrite(myPort, gv.args.slave_address, gv.iniFile)

    elif gv.args.firstPosParameter in ['monitor']:
        if gv.args.port: monitor.port = gv.args.port
        myPort = Prj.openRs485Port(monitor, rs485Prot)
        if gv.args.secondPosParameter == 'rs485':
            Prj.monitorRS485(myPort)

        elif gv.args.secondPosParameter == 'raw':
            Prj.monitorRaw(myPort, inpArgs=gv.args)

    else:
        errMsg = 'comando primario non previsto'
        myPort.Close()
        Ln.Exit(101, errMsg)

    myPort.Close()

    Ln.Exit(0)


# JORDAN BUCKINDALE [251246279]

# The program will compute and display the cost of electricity (including discounts and tax).
# The program will prompt the user for the information of power usage.

# Determine constants and set variables

OFF_PEAK_RATE = float(0.085)
ON_PEAK_RATE = float(0.176)
MID_PEAK_RATE = float(0.119)
TAXRATE = float(1.13)                    # Amount total cost plus tax

TOTAL_USAGE_LIMIT = 400.0
ON_PEAK_MINIMUM = 150.0

# Set discounts
totalUsageLimitDiscount = float(.96)    # amount cost after discount
onPeakDiscount = float(.95)
seniorDiscount = float(.89)

# Set prompt for input data.
while True:
        offPeakPeriod = float(input("Enter kwh during Off Peak period: "))
        if offPeakPeriod == 0:
            break
        onPeakPeriod = float(input("Enter kwh during On Peak period: "))
        midPeakPeriod = float(input("Enter kwh during Mid Peak period: "))

# Determine if residence belongs to senior
        senior = input("Is the owner a senior?(Y,y,N,n): ")

# Set variable for total kwh used
        totalKilowatts = offPeakPeriod + onPeakPeriod + midPeakPeriod

# Get subtotals of each peak period
        offPeakPeriodCost = offPeakPeriod * OFF_PEAK_RATE
        onPeakPeriodCost = onPeakPeriod * ON_PEAK_RATE
        midPeakPeriodCost = midPeakPeriod * MID_PEAK_RATE

# Set subtotal of peak periods without discount
        peakTotalCost = offPeakPeriodCost + onPeakPeriodCost + midPeakPeriodCost

# Set up specifications for discount
        if totalKilowatts < TOTAL_USAGE_LIMIT:
            totalUsageSavings = peakTotalCost - (peakTotalCost * totalUsageLimitDiscount)
        else:
            totalUsageSavings = 0

        if (0 < onPeakPeriod < ON_PEAK_MINIMUM) and totalUsageSavings == 0:
            onPeakSavings = onPeakPeriodCost - (onPeakPeriodCost * onPeakDiscount)
        else:
            onPeakSavings = 0

# Set up variable
        seniorSavings = 0
        seniorTotal = peakTotalCost - (totalUsageSavings + onPeakSavings)

# Calculate Senior Discount
        if senior == "y":
            seniorSavings = seniorTotal - (seniorTotal * seniorDiscount)
        if senior == "Y":
            seniorSavings = seniorTotal - (seniorTotal * seniorDiscount)

# Set up variables
        totalSavings = totalUsageSavings + onPeakSavings + seniorSavings

# Calculate total cost
        totalCost = (peakTotalCost - totalSavings) * TAXRATE

# Display electricity cost
        print("Electricity cost: $%.2f" % totalCost)


import sys
import collections
sys.stdin = open('5427_input.txt')

def bfs(x, y, z):
    global w, h
    q = collections.deque([])
    dx = [0, 0, 1, -1]
    dy = [1, -1, 0, 0]
    if z == 0:
        # print(x, y)
        visited[x][y] = 0
        q.append((y, x, 1))
        cnt = 1
        while q:
            x, y, ncnt = q.popleft()
            # print(x,y)
            for i in range(4):
                nx = x + dx[i]
                ny = y + dy[i]

                if nx < 0 or nx >= w:
                    continue
                if ny < 0 or ny >= h:
                    continue

                if g[ny][nx] == '@' or g[ny][nx] == '.':
                    if visited[ny][nx] > ncnt:
                        visited[ny][nx] = ncnt
                        # cnt += 1
                        q.append((nx, ny, ncnt + 1))

    elif z == 1:
        visitedMe[y][x] = 0
        q.append((x, y, 1))
        cnt = 1
        while q:
            x, y, ncnt = q.popleft()
            # print(x, y)
            for i in range(4):
                nx = x + dx[i]
                ny = y + dy[i]

                if nx < 0 or nx >= w:
                    continue
                if ny < 0 or ny >= h:
                    continue

                if g[ny][nx] == '@' or g[ny][nx] == '.':
                    if visitedMe[ny][nx] > ncnt:
                        visitedMe[ny][nx] = ncnt
                        # cnt += 1
                        q.append((nx, ny, ncnt+1))

    return 0

t = int(input())

for case in range(t):
    # print('-------------case---------------------')
    w, h = map(int, input().split())
    g = []
    visited = [[1000000 for _ in range(w)]for _ in range(h)]
    visitedMe = [[1000000 for _ in range(w)] for _ in range(h)]
    for i in range(h):
        g.append(list(str(input())))

    # for i in range(h):
    #     print(g[i])

    fire = []
    goal = []
    for i in range(h):
        for j in range(w):
            if g[i][j] == '@':
                myX, myY = j, i
            if g[i][j] == '*':
                fire.append([i, j])

            if g[i][j] == '.' or g[i][j]:
                if i == 0 or i == h-1 or j == 0 or j == w-1:
                    goal.append((j, i))

    # print(myX, myY)
    # if case == 2:
    #     print(fire)
    for i in range(len(fire)):
        bfs(fire[i][0], fire[i][1], 0)

    # for i in range(h):
    #     print(visited[i])

    bfs(myX, myY, 1)
    # print('---------------------')
    # for i in range(h):
    #     print(visitedMe[i])

    # print(goal)
    # print(goalX, goalY)
    lastx = 1000001
    lasty = 1000001
    zxc = 999999999
    if goal:
        for i in range(len(goal)):
            if visitedMe[goal[i][1]][goal[i][0]] < visited[goal[i][1]][goal[i][0]]:
                lastx = goal[i][0]
                lasty = goal[i][1]
                if visitedMe[goal[i][1]][goal[i][0]] < zxc:
                    zxc = visitedMe[goal[i][1]][goal[i][0]]

    # print(lastx, lasty)
    # if case == 2:
    #     print(goal)

    if lastx < 1000001:
        print(zxc+1)
    else:
        print('IMPOSSIBLE')


"""
Code from RealPython, I am gonna tinker with this a bit
and add comments to this.

Uses one of the pre-trained HAAR Cascades.
"""

import cv2
import sys

cascPath = sys.argv[1] # Gets the argument for the cascade path from cmdline
faceCascade = cv2.CascadeClassifier(cascPath) # Initialise HAAR cascade

video_capture = cv2.VideoCapture(0) # Capture video from video device

while True:
    # Capture frame-by-frame
    ret, frame = video_capture.read()   # Read video frame

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)  # Get greyscale version

    faces = faceCascade.detectMultiScale(
        gray, # Use greyscale version to detect things
        scaleFactor=1.1, # Change scale factor of image
        minNeighbors=5, # Minium face detections nearby to be recognised
        minSize=(30, 30), # Minimum face detection size px
        flags=cv2.CASCADE_SCALE_IMAGE # Get the xml flags for image recog
        # I had to fix the flags thing as cv2.cv is deprecated.
    )

    # Draw a rectangle around the faces
    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

    # Display the resulting frame
    cv2.imshow('Video', frame)

    # What does this memory address looking thing do?
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break   # Quit if q pressed

# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()


class Solution:
    def minDeletionSize(self, strs: List[str]) -> int:
        m = len(strs)
        n = len(strs[0])
        words = ["" for x in strs]
        res = 0

        for i in range(n):
            for index, word in enumerate(strs):
                words[index] += word[i]

            if any(A > B for A, B in zip(words, words[1:])):
                res += 1
                for index in range(m):
                    words[index] = words[index][:-1]

        return res


from django.contrib import admin
from .models import Project, Target
from .forms import AddTargetForm
import re
from import_export.admin import ExportMixin, ImportExportActionModelAdmin
from libs.common import get_domain_icp

# Register your models here.
@admin.register(Project)
class ProjectAdmin(admin.ModelAdmin):
    fields = ['project_name', 'project_description', 'create_time', 'update_time']
    readonly_fields = ['create_time', 'update_time']
    list_display = ['project_name', 'project_description', 'create_time', 'update_time']

@admin.register(Target)
class TargetAdmin(ExportMixin, admin.ModelAdmin):
    list_display = ['project', 'target_type', 'target_name', 'target_description', 'target_icp', 'create_time',
              'update_time']
    readonly_fields = ['last_scan_time', 'create_time', 'update_time']
    list_filter = ['project', 'target_type', ]
    search_fields = ['target_name', 'target_icp']
    list_per_page = 20

    form = AddTargetForm

    def save_model(self, request, obj, form, change):
        # 对target_name字段进行换行分割
        # 并且通过正则判断是ip还是域名然后分别进行匹配插入
        targets = obj.target_name
        for target in list(set(targets.splitlines())):
            if len(target) == 0:
                continue
            # if re.match('((?:(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d?\d))', target):
            if re.match('(?:[0-9]{1,3}\.){3}(?:[0-9]){1,3}(?:\/\d*)?(?:\-\d*)?', target):
                # 所有IP的情况
                obj.target_type = 'ip'
            else:
                obj.target_type = 'domain'
                domain = target if not target[0] == '.' else target[1:]
                obj.target_icp = get_domain_icp(domain)
            obj.target_name = target
            Target.objects.create(project=obj.project, target_type=obj.target_type, target_icp=obj.target_icp,
                                  target_name=target, target_description=obj.target_description)


import pygame

from Gambar import *

class Button:
    def __init__(self, x , y ,image , scale):
        self.__width = image.get_width()
        self.__height = image.get_height()
        self.__x = x
        self.__y = y
        self.__x_s = x
        self.__y_s = y
        self.image = pygame.transform.scale(image, (int(self.__width * scale) , int(self.__height * scale)))
        self.rect = self.image.get_rect(center=(self.__x, self.__y))
        self.clicked = False
        self.__count=0

    def draw(self):
        action = False
        pos = pygame.mouse.get_pos()
        if self.rect.collidepoint(pos):
            if self.__count<3:
                self.__x+=1
                self.__y+=1
                self.rect = self.image.get_rect(center=(self.__x, self.__y))
                self.__count+=1

            if pygame.mouse.get_pressed()[0] == 1 and self.clicked == False:
                self.clicked = True
                action = True
        else:
            self.__x = self.__x_s
            self.__y = self.__y_s
            self.rect = self.image.get_rect(center=(self.__x_s, self.__y_s))
            self.__count = 0

        if pygame.mouse.get_pressed()[0] == 0:
            self.clicked = False

        screen.blit(self.image,(self.rect.x , self.rect.y))
        return action

#PILIHAN KARAKTER
#Gambar Dino di pilihan karakter
game_dino = pygame.image.load('Folkit and rocca/Gambarrr/rakun_idle.png')
#game_dino = pygame.transform.scale(game_dino,(150,150))
dino_game = Button(715,560,game_dino,1.15)

#Gambar beruang di pilihan karakter
game_beruang = pygame.image.load('Folkit and rocca/Gambarrr/rubah_idle.png')
beruang_game = Button(200,560,game_beruang,1.5)

#Tombol Start
button_start = pygame.image.load('Folkit and rocca/Gambarrr/tombol/button_start.png')
start_button = Button(480,450,button_start,0.8)

#Tombol How to play
how_to = pygame.image.load('Folkit and rocca/Gambarrr/tombol/howtoplay_button.png')
button_how_to = Button(480,530,how_to,0.15)

#Tombol Credits
credits = pygame.image.load('Folkit and rocca/Gambarrr/tombol/CREDITS.png')
button_credits = Button(480,610,credits,0.18)

#Tombol Exit
button_end = pygame.image.load('Folkit and rocca/Gambarrr/tombol/exitt.png')
end_button = Button(480,690,button_end,0.8)

#PILIHAN KETIKA GAME OVER
#Tombol Play Again
gameover_button = pygame.image.load('Folkit and rocca/Gambarrr/tombol/PlayAgain.png')
button_gameover = Button(480,600,gameover_button,0.18)

#Tombol Exit
gameover_button_exit = pygame.image.load('Folkit and rocca/Gambarrr/tombol/button_exit.png')
button_gameover_exit = Button(480,680,gameover_button_exit,0.18)

#Gambar Dino mati
gameover = pygame.image.load('Folkit and rocca/Gambarrr/Background/gameover.png')
gameover = pygame.transform.scale(gameover,(950,836))

Data kodingan/Folkit and rocca/Tombol.py


import json
import os
import uuid
from datetime import datetime
from io import BytesIO

import boto3
from botocore.exceptions import ClientError

s3 = boto3.client('s3')
BUCKET_NAME = os.environ['BUCKET_NAME']
EXPIRATION = int(os.environ.get('EXPIRATION', 60))  # default: 1 min

def presign_upload(key):
    return s3.generate_presigned_post(
        BUCKET_NAME,
        key,
        ExpiresIn=EXPIRATION,
    )

def upload_lambda_handler(event, context):
    now = datetime.now()
    key = f'{now.year}/{now.month}/{now.day}/{uuid.uuid4()}/save.zip'

    response = presign_upload(key)

    return {
        'statusCode': 200,
        'headers': {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Allow-Methods': 'GET',
        },
        'body': json.dumps(response),
    }

def get_s3_file_content(key):
    with BytesIO() as f:
        try:
            s3.download_fileobj(BUCKET_NAME, key, f)
        except ClientError:
            return None
        f.seek(0)
        return f.read().decode()

def presign_download(key):
    return s3.generate_presigned_url(
        'get_object',
        Params={
            'Bucket': BUCKET_NAME,
            'Key': key,
        },
        ExpiresIn=EXPIRATION,
    )

def check(key):
    dirname = os.path.dirname(key)
    err_msg = get_s3_file_content(f'{dirname}/ERROR')
    if err_msg is not None:
        return {
            'status': 'error',
        }

    success_msg = get_s3_file_content(f'{dirname}/SUCCESS')
    if success_msg is not None:
        return {
            'status': 'success',
            'url': presign_download(success_msg),
        }

    return {
        'status': 'processing',
    }

def download_lambda_handler(event, context):
    data = event['queryStringParameters']

    key = data['key']
    result = check(key)

    return {
        'statusCode': 200,
        'headers': {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Allow-Methods': 'GET',
        },
        'body': json.dumps(result),
    }


"""Collection of useful functions"""
from json.decoder import JSONDecodeError
from typing import Union
from pathlib import Path
import json
import logging
import socket
import time
from math import floor

def next_free_port(port, quiet=False):
    max_ports_to_test = 200
    for i in range(port, port + max_ports_to_test):
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            if not quiet:
                print("trying out port", i, "...")
            try:
                s.bind(('localhost', i))
                return i
            except:
                pass
    raise Exception(
        f"cannot find any available port in range {port} - {port + max_ports_to_test}")

def set_logging(log_file: Union[None, str], log_level: str, output_stdout: bool) -> None:
    """configures logging module.

    Args:
        log_file (str): path to log file. if omitted, logging will be forced to stdout.
        log_level (str): string name of log level (e.g. 'debug')
        output_stdout (bool): toggles stdout output. will be activated automatically if no log file was given.
            otherwise if activated, logging will be outputed both to stdout and log file.
    """
    logger = logging.getLogger()

    log_level_name = log_level.upper()
    log_level = getattr(logging, log_level_name)
    logger.setLevel(log_level)

    logging_format = logging.Formatter(
        '%(asctime)s - %(levelname)s [%(filename)s : %(funcName)s() : l. %(lineno)s]: %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S')

    if log_file:
        log_file_path = Path(log_file)
        log_file_path.parent.mkdir(parents=True, exist_ok=True)
        file_handler = logging.FileHandler(log_file_path)
        file_handler.setLevel(log_level)
        file_handler.setFormatter(logging_format)
        logger.addHandler(file_handler)
    else:
        output_stdout = True

    if output_stdout:
        stream = logging.StreamHandler()
        stream.setLevel(log_level)
        stream.setFormatter(logging_format)
        logger.addHandler(stream)

def check_paths(*args, names=None):
    """checks if the given paths exist.

    Args:
        args (list of paths): the paths to be checked

    Raises:
        ValueError: thrown if one of the given paths does not exist
    """
    for idx, path in enumerate(args):
        path = Path(path)
        if not path.exists():
            if names is not None and idx < len(names):
                raise ValueError(f"{str(names[idx])}: {str(path)} does not exist!")
            else:
                raise ValueError(f"file {str(path)} does not exist!")

def seconds_to_timestamp(seconds):
    """Converts the given seconds into a valid timestamp

    Args:
        seconds (float): the number of seconds

    Returns:
        str: the formated time string, format: hours:minutes:seconds
    """
    hours = floor(seconds / 3600)
    minutes = floor((seconds % 3600) / 60)
    seconds = round(seconds % 60, 3)
    return f"{str(hours)}h {str(minutes)}m {str(seconds)}s"

def read_json(path):
    """reads a json and converts it to dict

    Args:
        path (Path): path to json to be read

    Raises:
        JSONDecodeError: thrown if given json invalid

    Returns:
        dict: the parsed json fields
    """
    try:
        path = Path(path)
        with path.open() as jsonfile:
            content = json.load(jsonfile)
    except JSONDecodeError as e:
        logging.error(f"cannot parse json {path}: {e}")
        raise JSONDecodeError from e

    return content

class TimeMeasurement():
    """Wrapper for automatic time measurement. converted timestamp string can be outputed using custom functions."""

    def __init__(self, name, output_func=logging.debug):
        """initializes time measurement fields

        Args:
            name (str): name of function to measure time of. only used for output.
            output_func (callable, optional): function for time stamp output. Defaults to logging.debug.
        """
        self.name = name
        self.output_func = output_func
        self.start_time = 0

    def __enter__(self):
        """starts the timer when used in with-block"""
        self.start_time = time.time()

    def __exit__(self, *args):
        """outputs the time stamp"""
        diff = time.time() - self.start_time
        self.output_func(f"{self.name} took {seconds_to_timestamp(diff)} time!")

def fraction_to_percent(fraction, decimal_count=3):
    """converts a decimal number into percent representation. decimal places can be configured

    Args:
        fraction (float): number to convert into percentage
        decimal_count (int, optional): number of decimal places. Defaults to 3.

    Returns:
        float: percentage with given count of decimal places
    """
    return floor(fraction * 100 * (10 ** decimal_count)) / (10 ** decimal_count)

def file_size_megabytes(file_path):
    """computes the file size in megabytes

    Args:
        file_path (Path): path to file to compute the size of

    Returns:
        int: rounded file size in megabytes
    """
    file_path = Path(file_path)
    check_paths(file_path)

    return round(file_path.stat().st_size/1024**2)


import json

with open("datasets/sarcasm/Sarcasm_Headlines_Dataset.json", 'r') as f:
    datastore = json.load(f)

data = {
    'sentences': [],
    'labels': [],
    'urls': []
}

for item in datastore:
    data['sentences'].append(item['headline'])
    data['labels'].append(item['is_sarcastic'])
    data['urls'].append(item['article_link'])


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

import RPi.GPIO as GPIO
import time

__author__ = 'Gus (Adapted from Adafruit)'
__license__ = "GPL"
__maintainer__ = "pimylifeup.com"

GPIO.setmode(GPIO.BOARD)

pin_to_circuit = 7 #to control photoresistor
led_pin = 13

#For LED
GPIO.setup(led_pin, GPIO.OUT) #set pin 11 to output
p = GPIO.PWM(led_pin,100) #set the PWM for LED to 50%
p.start(100) #I don’t remember what this does but trust me, you need it.

def rc_time (pin_to_circuit):
    count = 0

    #Output on the pin for photoresistor
    GPIO.setup(pin_to_circuit, GPIO.OUT)
    GPIO.output(pin_to_circuit, GPIO.LOW)
    time.sleep(0.1)

    #Change the pin back to input for photoresistor
    GPIO.setup(pin_to_circuit, GPIO.IN)

    #Count until the pin goes high
    while (GPIO.input(pin_to_circuit) == GPIO.LOW):
        count += 1

    return count

#Catch when script is interupted, cleanup correctly
try:
    # Main loop
    while True:
        light_value = rc_time(pin_to_circuit)

        if light_value > 1000:
            p.ChangeDutyCycle(100)
        elif light_value > 200:
            p.ChangeDutyCycle(30)
        else:
            p.ChangeDutyCycle(10)

        time.sleep(1)
        #print light_value

except KeyboardInterrupt:
    pass

p.stop()
GPIO.cleanup()

Smart Light Project/Python Scripts/photoresistor_w_led.py


"""
@file trajectory.py

@brief Contains trajectory class used to predict object trajectories

Uses Points locations from n-previous frames to approximate a line of the
current object trajectory. Trajectory estimation is using numpy.polyfit with
a dimension of 1. Trajectories are created in the direction of the robot_axis

For multiple bounces, trajectory estimation will produce a list of Line objects
representing each 'bounce.' The last element of this list is the line of the
final predicted trajectory (after n bounces)

Note that a larger number of frames means a slower reaction - prediction will
not occur until n frames have been added to the list.

If an object is stationary, noise in the video or location feed may cause
noisy points to be added, resulting in incorrect and/or highly skewed best fit
lines.

The trajectory planner will also not directly handle switching to a new object
to track for the goalie. A few frames of noise (n frames) will occur while the
old location points are in the list with the newer ones.

Standard usage for a 3-frame best fit model (pseudocode example)::

planner = TrajectoryPlanner(3)
while True:
  frame = get_video_frame()
  point = frame.get_object_location() # point is a shapes.Point object
  # Every frame, add the newest point
  planner.add_point(point)
  # Returns None until 3 frames have been added, then returns shapes.Line
  traj = planner.get_trajectory()

@author Neil Jassal
"""
import math

import cv2 # 3rd party imports
import numpy as np
from IPython import embed

import shapes
import colors
import utils

class TrajectoryPlanner:
    def __init__(self, frames=5, bounce=0, walls=[], robot_axis=None):
      """
      @brief Initializes parameters

      @param frames The number of previous points to fit the trajectory to
      @param bounces How many bounces off of walls to predict
      @param walls A list of Line objects representing walls to bounce off of
      @param robot_axis The robot axis to be used
      """
      self.num_frames = frames
      self.bounce = bounce

      ######## SCENE DEFINITION PARAMETERS #########
      # Line objects representing walls for bounce prediction
      self.walls = walls
      # Line representing robot axis
      self.robot_axis = robot_axis

      ######### BEST FIT PARAMETERS ########
      # Index of most recent frame in pt_list. Iterated with modulo operator
      # to wrap properly and always use
      self.index = None
      self.pt_list = [None] * self.num_frames # list of Points
      # Separate x and y list are kept for convenience when fitting line
      self.x_list = [None] * self.num_frames  # list of x-values for best fit
      self.y_list = [None] * self.num_frames # list of y-values for best fit

      self.curr_index = None # Index of most recent point
      self.last_index = None # Index of oldest point

      ######## OUTPUT PARAMETERS ########
      # The final line of the trajectory, extending to the robot axis
      self.traj = None
      # List of lines representing all bounces of the trajectory prediction
      self.traj_list = []

      ######## DEBUG PARAMETERS ########
      self.debug_line=None
      self.debug_pt = None

    def add_point(self, point):
      """
      @brief Adds current point to list of points, overwriting the oldest value

      For optimal usage, it is generally recommended to add a point denoting
      the updated location at every frame. A Point contains an x and y value

      @param The Point or Circle object to add as the current frame
      """
      if point is None:
        return

      if self.index is None: # first time
        self.index = 0
        self.curr_index = 0
      else:
        # increment index so it wraps, as well as current and last index
        self.index = (self.index + 1) % self.num_frames
        self.curr_index = self.index
        self.last_index = (self.index + 1) % self.num_frames

      self.pt_list[self.index] = point
      self.x_list[self.index] = point.x
      self.y_list[self.index] = point.y

    def add_wall(self, wall):
      """
      @brief Adds a wall to the trajectory's list
      @param wall A Line object representing the wall
      """
      if wall is None:
        return
      self.walls.append(wall)
      return

    def add_walls(self, wall_list):
      """
      @brief Adds a set of walls to the trajectory's list
      @param wall_list A list of Line objects representing walls
      """
      if wall_list is None:
        return
      for wall in wall_list:
        if wall is None:
          continue
        self.walls.append(wall)
      return

    def get_best_fit_line(self, color=colors.Cyan):
      """
      @brief Gets and returns a Line object representing the best fit line
      @param The color for the best fit line
      @return A Line object
      """
      # get best fit line
      fit = np.polyfit(self.x_list, self.y_list, 1, full=True)
      m = fit[0][0] # slope of best fit line
      b = fit[0][1] # intercept of best fit line

      x1 = self.x_list[self.index] # most recent x
      x2 = x1 + 1.0
      y1 = m * x1 + b
      y2 = m * x2 + b

      ln = shapes.Line(x1=x1, y1=y1, x2=x2, y2=y2, color=color)
      return ln

    def get_trajectory_list(self, color=colors.Cyan):
      """
      @brief Gets best fit traj from n-previous points and predicts bounces

      Uses np.polyfit with dimension 1. Creates line from two points. Points
      are generated using closest point to most recent frame (x1,y1) and
      a point (x1 + 1.0, y2). This works as a line can be represented by any
      arbitrary two points along it. The actual points do not matter here or
      for the goalie, unless specified/calculated otherwise.

      self.traj is always the farthest-predicted line between the last impact
      point or object location and the robot axis

      self.traj_list contains, from oldest to farthest predicted, a list of
      Lines representing each bounce. The lines go obj->wall, wall->wall, ...,
      wall->robot_axis.

      @param color The color to be used in the trajectory lines

      @return list of Line objects representing trajectory path
      """
      # Not enough frames collected
      if None in self.pt_list:
        return []

      # reset and get best fit line
      self.traj_list = []
      ln = self.get_best_fit_line()

      # get trajectory towards robot axis, line from obj to axis
      # if trajectory not moving towards robot axis, no prediction
      if not self.traj_dir_toward_line(self.robot_axis):
        ln = None
      start_pt = self.pt_list[self.curr_index]
      traj_int_pt = utils.line_intersect(ln, self.robot_axis) # Point object
      traj = utils.get_line(start_pt, traj_int_pt, color=colors.Blue)
      self.traj = traj

      # return straight-line trajectory (as a 1-elem list for consistency) if
      # no bounces to be predicted
      if self.bounce is 0: # no bounce prediction
        self.traj_list.append(self.traj)
        return self.traj_list

      #### BOUNCE (broken) ####
      for wall in self.walls:
        # Determine where bounce occurs and add line up to bounce
        bounce_pt = utils.line_segment_intersect(self.traj, wall)
        if bounce_pt is None:
          continue

        bounce_ln = utils.get_line(self.pt_list[self.curr_index],
          bounce_pt, color=colors.Blue)
        self.traj_list.append(bounce_ln)
        self.debug_pt = bounce_pt

        ### THIS IS BROKEN
        # Reflect line across wall and project to next wall or axis
        # incoming d, normal n: outgoing r = d - 2(d dot n)*n
        normal_dx = -wall.dy*1.0
        normal_dy = wall.dx*1.0
        normal_len = math.sqrt(normal_dx*normal_dx + normal_dy*normal_dy)

        d = shapes.Point(bounce_ln.dx, bounce_ln.dy)
        n = shapes.Point(normal_dx/normal_len, normal_dy/normal_len)
        self.debug_line = shapes.Line(x1=bounce_pt.x, y1=bounce_pt.y,
          x2=bounce_pt.x+n.x*20,y2=bounce_pt.y+n.y*20,color=colors.Red)

        reflect_dx = (d.x - 2 * utils.dot(d, n) * n.x)
        reflect_dy = (d.y - 2 * utils.dot(d, n) * n.y)

        #### ONCE NEW DX AND DY ARE FOND, IT WORKS. GETTING DX/DY FAILS ####
        new_x = bounce_pt.x + reflect_dx * 0.001
        new_y = bounce_pt.y + reflect_dy * 0.001
        new_pt = shapes.Point(new_x, new_y)

        new_ln = utils.get_line(bounce_pt, new_pt) # small line
        final_int = utils.line_intersect(new_ln, self.robot_axis)
        final_ln = shapes.Line(
          x1=bounce_pt.x, y1=bounce_pt.y,
          x2=final_int.x, y2=final_int.y, color=colors.Cyan)

        self.traj = final_ln
        self.traj_list.append(final_ln)

        # only one bounce
        break

      return self.traj_list

    def get_trajectory(self, calculate=1, color=colors.Cyan):
      """
      @brief Gets the full list of trajectory prediction lines, and returns
      a line for the final trajectory

      @param calculate Whether to compute the trajectory or take from list
      @param color The color of trajectory lines

      @return The last predicted trajectory line
      """
      if calculate is 1:
        self.traj_list = self.get_trajectory_list(color)

      # if failed to get trajectory list
      if self.traj_list is None:
        return None
      if len(self.traj_list) < 1:
        return None

      # return last predicted line - best prediction
      return self.traj_list[len(self.traj_list) - 1]

    def traj_dir_toward_line(self, line):
      """
      @brief Determines if the current trajectory is moving toward the line

      Takes the most and least recent points, and determines if the overall
      direction of the trajectory is generally toward the given Line or away.
      This is done by comparing the distance between the current point and
      oldest point.

      In context of the robot goalie, will determine if the robot is currently
      moving towards the robot axis, irrespective of bounces. Used to tell
      if the ball is generally moving towards or away from the axis

        if dist(curr_pt to line) < dist(old_pt to line):
          return 1
        else return 0

      @param line The Line object used

      @return 1 if moving towards line, 0 if not
      """
      if None in self.pt_list or line is None:
        return 0

      curr_pt = self.pt_list[self.curr_index]
      last_pt = self.pt_list[self.last_index]

      unused, distances = utils.distance_from_line(
        [curr_pt, last_pt], line, squared=1)

      # current point is closer to line than last point
      if distances[0] < distances[1]:
        return 1

      return 0


import pandas as pd
from data_description import DataDescription

class EncodingCategoricalData:

    tasks = [
        "Show Categorical Columns",
        "Performing One Hot Encoding",
        "Show the Dataset"
    ]

    def __init__(self, dataframe):
        self.dataframe = dataframe

    def show_categorical_columns(self):
        print("\n{0: <20}".format("Categorica Column") + "{0: <5}".format("Unique Values"))
        for column in self.dataframe.select_dtypes(include="onject"):
            print('{0: <20}'.format(column) + '{0: <5}'.format(self.dataframe[column].nuinque()))

    def performing_one_hot_encoding(self):
        categorical_columns = self.dataframe.select_dtypes(include="object")
        while True:
            column = input('\nWhich column would you like to one hot encode? (Press -1 to go back)').lower()
            if column == "-1":
                break
            if column in categorical_columns:
                self.dataframe = pd.get_dummies(data = self.dataframe, columns = [column])
                print("Encoding is done")

                choice = input("Do you  want more columns to be encoded? (y/n)").lower()
                if choice == "y":
                    continue
                else:
                    self.show_categorical_columns()
                    break
            else:
                print("Wrong column name. Try Again")

    def handle_tasks(self):
        while True:
            print("\nTasks")
            for index, value in enumerate(self.tasks):
                print(f"{index + 1}. {value}")
            while True:
                try:
                    choice = int(input("\Whta you want to do? (Press -1 to go back)"))
                except ValueError as error:
                    print(error)
                    continue
                break
            if choice == "-1":
                break
            elif choice == 1:
                self.show_categorical_columns()
            elif choice == 2:
                self.show_categorical_columns()
                self.performing_one_hot_encoding()
            elif choice == 3:
                DataDescription.show_dataset(self)
            else:
                print("Wrong Value! Try Again!")
        return self.dataframe


import pathlib

# Projects requiring docs
projects = ["artificial_hes"]

# Constant paths
this_path = pathlib.Path(__file__)
template_path = this_path.parent / "create_user_docs_template.py"
docs_path = this_path.parent.parent
projects_root = this_path.parent.parent.parent / "projects"

def replace_template_variable(template: str, token_value: str, new_value: str) -> str:
  filled_template = template.replace("".join(["{{", token_value, "}}"]), new_value)
  return filled_template

for project_name in projects:
  project_path = projects_root / project_name
  notebook_path = project_path / "schemas" / "create_user_docs.py"

  # Read the template content
  with template_path.open("r") as template_file:
    notebook_content = template_file.read()

  # Populate placeholders in the template
  for doc_file_path in docs_path.glob("**/*.md"):
    with doc_file_path.open("r") as doc_file:
      doc_file_content = doc_file.read()

    notebook_content = replace_template_variable(notebook_content, doc_file_path.name, doc_file_content)
    notebook_content = replace_template_variable(notebook_content, "database_name", project_name)

  # Write the full content
  with notebook_path.open("w+") as notebook_file:
    notebook_file.write(notebook_content)


def MRNA(s):

        '''Input:  A protein string of length at most 1000 aa.

        Output: The total number of different RNA strings from
        which the protein could have been translated, modulo 1,000,000'''

        revDict={'M':1,'L':6,'S':6,'A':4,'P':4,'T':4,'F':2,'I':3,'V':4,
                'Y':2,'H':2,'N':2,'D':2,'Q':2,'K':2,'E':2,'R':6,'G':4,
                'C':2,'W':1}

        totalNum=3

        for AA in s:
                totalNum*=revDict[AA]

        print(totalNum%1000000)

protString=''
f=open('rosalind_mrna.txt','r')

for eachLine in f:
        protString+=eachLine

protString=protString.rstrip()

MRNA(protString)

f.close()


#!/usr/bin/env python
import io
import re
from pathlib import Path

from setuptools import setup, find_packages

# Configs ##########

# Core dependencies
REQUIRED = [
    "scikit-learn>=1.0",
    "requests>=2.21.0",
    "eia-python>=1.22",
    "pyproj>=3.5",
    "shapely>=1.8",
    "numpy>=1.24",
    "pandas>=2.0",
    "pygam>=0.9.0",
    "scipy>=1.7",
    "statsmodels>=0.11",
    "tqdm>=4.28.1",
    "matplotlib>=3.6",
    "bokeh>=2.4",
    "attrs>=22",
    "pytz",
    "h5pyd",
    "pyyaml",
    "pyspark",
    "tabulate",
    "statsmodels",
    "jupyterlab",
    "xarray",
    "dask",
    "netcdf4",
    "cdsapi",
]

# Testing-only dependencies
TESTS = ["pytest>=5.4.2", "pytest-cov>=2.8.1"]

# All extra dependencies (see keys for breakdown by purpose)
EXTRAS = {
    "docs": [
        "ipython",
        "Sphinx>=5.0,!=7.2.0",
        "pydata-sphinx-theme",
        "sphinx_design>=0.3",
        "sphinxcontrib-bibtex",
        "myst-nb",
        "myst-parser",
    ],
    "develop": [
        "pre-commit",
        "black",
        "isort",
        "flake8",
        "flake8-docstrings",
    ],
}
EXTRAS["develop"] += TESTS

# Read the version from the __init__.py file without importing it
def read(*names, **kwargs):
    directory = Path(__file__).resolve().parent
    with io.open(Path(directory, *names), encoding=kwargs.get("encoding", "utf8")) as fp:
        return fp.read()

def find_version(*file_paths):
    version_file = read(*file_paths)
    version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M)
    if version_match:
        return version_match.group(1)
    raise RuntimeError("Unable to find version string.")

def read_file(filename):
    this_directory = Path(__file__).resolve().parent
    with open(this_directory / filename, encoding="utf-8") as f:
        f_text = f.read()
    return f_text

# setup.py main ##########

setup(
    name="OpenOA",
    version=find_version("openoa", "__init__.py"),
    description="A package for collecting and assigning wind turbine metrics",
    long_description=read_file("readme.md"),
    long_description_content_type="text/markdown",
    author="NREL PRUF OA Team",
    author_email="openoa@nrel.gov",
    url="https://github.com/NREL/OpenOA",
    packages=find_packages(exclude=["test", "examples"]),
    include_package_data=True,
    install_requires=REQUIRED,
    extras_require=EXTRAS,
    tests_require=TESTS,
    python_requires=">=3.8, <3.11",
)


from plugin import BotPlugin, DanmakuMessage
from datetime import datetime

class TimeChecker(BotPlugin):
    async def on_command_received(self, cmd, data):
        if cmd != 'DANMU_MSG':
            return
        danmu = DanmakuMessage.from_command(data['info'])
        if danmu.msg != '!时间':
            return
        now = datetime.now()
        show = now.strftime('%Y{y}%m{m}%d{d}').format(y='年', m='月', d='日')
        await self.send_message(f'现在的时间为: {show}')


import matplotlib.pyplot as plt
from pandas import DataFrame

Products = {'Product': ['Tablet','iPhone','Laptop','Monitor'],
            'Price': [250,800,1200,300]
            }

df = DataFrame(Products, columns= ['Product', 'Price'])

Products_list = df.values.tolist()
print (Products_list)

print(df.Price)

x = df.Product
y = df.Price

# plotting the points
plt.plot(x, y, color='green', linestyle='dashed', linewidth = 3,
         marker='o', markerfacecolor='blue', markersize=12)

# setting x and y axis range
plt.ylim(1,2000)
plt.xlim(1,2000)

# naming the x axis
plt.xlabel('x - axis')
# naming the y axis
plt.ylabel('y - axis')

# giving a title to my graph
plt.title(partner_name)

# function to show the plot
plt.show()


def _findDuplicate(array):

    # initialise pointers
    slow = array[0]
    fast = array[slow]

    # loop until slow = fast
    while slow != fast:
        slow = array[slow]
        fast = array[array[fast]]

    # find cycle length
    current = array[array[slow]]
    length = 1
    while current != array[slow]:
        current = array[current]
        length += 1

    # find start of cycle (start slow at 0, fast at length, loop until slow = fast, return value)
    pointerA = array[0]
    pointerB = array[0]

    while length > 0:
        pointerB = array[pointerB]
        length -= 1

    while pointerA != pointerB:
        pointerA = array[pointerA]
        pointerB = array[pointerB]

    return pointerA

def findDuplicate(array):

    # initialise pointers. treat values in the array as pointers
    slow = array[0]
    fast = array[slow]

    # find where slow meets fast
    while slow != fast:
        slow = array[slow] # slow.next
        fast = array[array[fast]] # fast.next.next

    # find start of cycle
    slow = 0
    while slow != fast:
        slow = array[slow] # slow.next
        fast = array[fast] # fast.next

    # return slow
    return slow

print(findDuplicate([1, 4, 4, 3, 2])) # 4
print(findDuplicate([2, 1, 3, 3, 5, 4])) # 3
print(findDuplicate([2, 4, 1, 4, 4])) # 4


# -*- coding: utf-8 -*-
"""
Created on Sat Nov 14 23:07:40 2015

@author: Isaac
"""

def cipher(p, n, k):
    return (n*p+k)%26

alpha = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]

plaintext = ""
while not (plaintext=="exit"):
    plaintext = input("New plaintext:")
    n=int(input("Cipher parameters?<n>x"))
    k=int(input("Cipher parameters?+<k>"))
    p = []
    c = []
    ciphertext = ""
    for letter in plaintext:
        p.append(alpha.index(letter.lower()))
        c.append(cipher(p[len(p)-1],n,k))
        ciphertext += alpha[c[len(c)-1]]
    print(ciphertext)


from flask import Flask, render_template, request
from transformers import DistilBertTokenizer, DistilBertForQuestionAnswering
import torch

app = Flask(__name__)
app.config["TEMPLATES_AUTO_RELOAD"] = True
bert_model = DistilBertTokenizer.from_pretrained('distilbert-base-uncased',return_token_type_ids = True)
bert_tokenizer = DistilBertForQuestionAnswering.from_pretrained('distilbert-base-uncased-distilled-squad')

def answer_question(question, context):

    input_ids = torch.tensor(bert_tokenizer.encode(question, context))

    print('Query has {:,} tokens.\n'.format(len(input_ids)))

    sep_index = input_ids.index(bert_tokenizer.sep_token_id)

    num_seg_a = sep_index + 1

    num_seg_b = len(input_ids) - num_seg_a

    segment_ids = [0] * num_seg_a + [1] * num_seg_b

    assert len(segment_ids) == len(input_ids)

    start_scores, end_scores = bert_model(torch.tensor([input_ids]), token_type_ids=torch.tensor([segment_ids]))

    ans_tokens = input_ids[torch.argmax(start_scores): torch.argmax(end_scores) + 1]

    answer_tokens = bert_tokenizer.convert_ids_to_tokens(ans_tokens, skip_special_tokens=True)

    answer_tokens_to_string = bert_tokenizer.convert_tokens_to_string(answer_tokens)

    return answer_tokens_to_string

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

@app.route('/submit', methods=['POST'])
def submit():
    if request.method == 'POST':
        ques = request.form['question']
        cont = request.form['context']
        return render_template('index.html', print=answer_question(ques, cont))


import csv
import math

# Report functions

def get_most_played(file_name):
    stats = open(file_name, 'r')
    read_stats = csv.reader(stats, delimiter='\t')
    most_played_num = 0
    most_played = ""
    for row in read_stats:
        float(row[1])
        if float(row[1]) > most_played_num:
            most_played_num = float(row[1])
            most_played = row[0]
    return(most_played)

def sum_sold(file_name):
    stats = open(file_name, 'r')
    read_stats = csv.reader(stats, delimiter='\t')
    sold_sum = 0
    sold_sum = float(sold_sum)
    for row in read_stats:
        sold_sum += float(row[1])
    return sold_sum

def get_selling_avg(file_name):
    stats = open(file_name, 'r')
    read_stats = csv.reader(stats, delimiter='\t')
    selling = []
    for row in read_stats:
        row[1] = float(row[1])
        selling.append(row[1])
    selling_sum = sum(selling)
    all_selling = len(selling)
    avg_selling = selling_sum / all_selling
    return avg_selling

def count_longest_title(file_name):
    stats = open(file_name, 'r')
    read_stats = csv.reader(stats, delimiter='\t')
    titles = []
    for row in read_stats:
        titles.append(row[0])
    max_length = max(titles, key=len)
    return len(max_length)

def get_date_avg(file_name):
    stats = open(file_name, 'r')
    read_stats = csv.reader(stats, delimiter='\t')
    rls_list = []
    for row in read_stats:
        rls_list.append(int(row[2]))
    rls_sum = sum(rls_list)
    num_titles = len(rls_list)
    avg_date = rls_sum / num_titles
    avg_date = math.ceil(avg_date)
    return avg_date

def get_game(file_name, title):
    stats = open(file_name, 'r')
    read_stats = csv.reader(stats, delimiter='\t')
    game = []
    for row in read_stats:
        if title == row[0]:
            row[1] = float(row[1])
            row[2] = int(row[2])
            return row

def count_grouped_by_genre(file_name):
    stats = open(file_name, 'r')
    read_stats = csv.reader(stats, delimiter='\t')
    genre_dict = {}
    for row in read_stats:
        if row[3] not in genre_dict:
            genre_dict.update({row[3]: 1})
        elif row[3] in genre_dict:
            genre_dict[row[3]] += 1
    return genre_dict


from django.core.exceptions import ObjectDoesNotExist
from rest_framework.decorators import api_view, permission_classes
from rest_framework.generics import ListAPIView
from rest_framework import status
from rest_framework.response import Response

from actors.api.v1.permissions import CheckDevGroup
from actors.models import Actor
from actors.api.v1.serializers import ActorSerializer, GetActorsSerializer

class GetAllActors(ListAPIView):
    queryset = Actor.objects.all()
    serializer_class = GetActorsSerializer

    @api_view(['GET'])
    def get_one_actor(request, actor_id):
        response = {'data': {}, 'status': status.HTTP_404_NOT_FOUND}
        try:
            actor = Actor.objects.get(id=actor_id)
            serializer = GetActorsSerializer(actor, many=False)
            response['data'] = serializer.data
            response['status'] = status.HTTP_200_OK
        except ObjectDoesNotExist:
            response['data'] = {'not found'}
            response['status'] = status.HTTP_204_NO_CONTENT
        except:
            response['data'] = {'server error'}
            response['status'] = status.HTTP_500_INTERNAL_SERVER_ERROR
        finally:
            return Response(**response)
@permission_classes([CheckGroup])
@api_view(['POST'])
def post_actor(request):
    response = {'data': {}, 'status': status.HTTP_400_BAD_REQUEST}
    try:
        serializer = ActorSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            response['data'] = serializer.data
            response['status'] = status.HTTP_200_OK
        else:
            response['data'] = serializer.errors
    except:
        response['data'] = {'server error'}
        response['status'] = status.HTTP_500_INTERNAL_SERVER_ERROR
    finally:
        return Response(**response)

@permission_classes([CheckGroup])
@api_view(['PUT', 'PATCH'])
def update_actor(request, actor_id):
    response = {'data': {}, 'status': status.HTTP_400_BAD_REQUEST}
    try:
        movie_instance = Actor.objects.get(id=actor_id)

        if request.method == 'PUT':
            serializer = ActorSerializer(instance=movie_instance, data=request.data)
        else:  # PATCH
            serializer = ActorSerializer(instance=movie_instance, data=request.data, partial=True)

        if serializer.is_valid():
            serializer.save()
            response['data'] = serializer.data
            response['status'] = status.HTTP_200_OK
        else:
            response['data'] = serializer.errors
    except:
        response['data'] = {'bad request'}
        response['status'] = status.HTTP_400_BAD_REQUEST
    finally:
        return Response(**response)

@permission_classes([CheckGroup])
@api_view(['DELETE'])
def delete_actor(request, actor_id):
    response = {'data': {}, 'status': status.HTTP_400_BAD_REQUEST}
    try:
        Actor.objects.get(id=actor_id).delete()
        response['data'] = {'deleted'}
        response['status'] = status.HTTP_204_NO_CONTENT
    except ObjectDoesNotExist:
        response['data'] = {'not found'}
        response['status'] = status.HTTP_404_NOT_FOUND
    finally:
        return Response(**response)


import numpy as np
from matplotlib import pyplot
from numbers import Number

class Grid:
    """Grid class that initialises the grid for cellular automata model.

    Parameters
    ----------
    attribute_grid : array
        The array same dimension as plane, with each space containing tuple
        giving details about different square attributes.

        In first tuple position, gives detail about square type:
        1 = seat
        2 = wall/toilet
        3 = aisle
        4 = exit

        In second position, integer denoting shortest distance to exit from
        that square is given, this is a hard coded input(for now).

    agent_positions : array
        The list of initial position tuples (column, row) for agents on plane.

    Attributes
    ----------
    agent_grid : array
        The grid of current positions of agents in plane.

    """

    def __init__(self, attribute_grid, agent_positions):
        self.type_grid = attribute_grid[:,:, 0]
        agent_grid = np.zeros(np.shape(attribute_grid[:,:,0]))
        for pos in agent_positions:
            if not attribute_grid[pos[0],pos[1]][0] == 2:
                agent_grid[pos[0],pos[1]] = 1
            else:
                raise ValueError(f"Grid position {pos} cannot contain agent.")
        self.agent_grid = agent_grid
        self.distance_grid = attribute_grid[:,:,1]
        self.decision_order = [None]*(np.amax(attribute_grid[:,:,1])+1)
        for i in range(np.amax(attribute_grid[:,:,1])+1):
            self.decision_order[i] = np.argwhere(attribute_grid[:,:,1] == i)

    def move(self):
        for i in range(len(self.decision_order)):
            np.random.shuffle(self.decision_order[i])

            if i == 0:
                for j in self.decision_order[i]:
                    #agent in exit position now leaves plane
                    if self.agent_grid[j[0], j[1]] == 1:
                        self.agent_grid[j[0], j[1]] = 0

            else:

                for j in self.decision_order[i]:

                    if self.agent_grid[j[0],j[1]] == 1:
                        if self.type_grid[j[0],j[1]] == 1: #if agent is currently in a seat
                            options = []
                            for k in [[0,1], [0,-1]]:
                                if ((not self.type_grid[j[0] + k[0], j[1] + k[1]] == 2)
                                    and (self.agent_grid[j[0] + k[0], j[1] + k[1]] == 0) and
                                    (self.distance_grid[j[0] + k[0], j[1] + k[1]] <
                                    self.distance_grid[j[0],j[1]])):
                                    options.append(k) #append empty neighbouring seats with
                            if options:                         #a shorter distance to the exit
                                np.random.shuffle(options)
                                print(options) #randomly choose one of equally good seats to move to
                                print((j[0] + options[0][0] ,j[1] + options[0][1]))
                                self.agent_grid[j[0] + options[0][0], j[1] + options[0][1]] = 1
                                self.agent_grid[j[0],j[1]] = 0
                        elif self.type_grid[j[0],j[1]] == 3: #if agent is currently in aisle
                            options = []
                            for k in [[-1, 0], [1, 0], [0, -1], [0, 1]]:
                                if (not self.type_grid[j[0] + k[0], j[1] + k[1]] == 2 and
                                    not self.type_grid[j[0] + k[0], j[1] + k[1]] == 1
                                    and self.agent_grid[j[0] + k[0], j[1] + k[1]] == 0 and
                                    self.distance_grid[j[0] + k[0], j[1] + k[1]] <
                                    self.distance_grid[j[0],j[1]]):
                                    options.append(k) #append empty neighbouring seats with
                                                    #a shorter distance to the exit
                            if options:
                                np.random.shuffle(options) #randomly choose one of equally good seats to move to
                                self.agent_grid[j[0] + options[0][0], j[1] + options[0][1]] = 1
                                self.agent_grid[j[0],j[1]] = 0

def visualise(grid):
    """Function to visualise the cellular automata evacuation model.

    Parameters
    ----------
    grid: Grid
        Initialised grid ready to have evacuation run on.

    t: Integer or "completion"
        Represents how many time steps to run model for.

        If t is integer run t times.

        If t = "completion", run until all agents have left plane.

    Return
    ----------
    Return visualisation of evacuation model simulation.

    """
    while sum(sum(grid.agent_grid)) > 0:
        pyplot.ion()
        pyplot.clf()
        pyplot.matshow(grid.agent_grid, fignum=0, cmap='binary')
        pyplot.show()
        grid.move()
        pyplot.pause(0.5)


"""Example Implementation of NEAT algorithm from
see http://nn.cs.utexas.edu/downloads/papers/stanley.ec02.pdf

Note: The we use restricted networks in the sense all edges point forwards.
"""

import sys
import os

DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))  # noqa
sys.path.insert(0, DIR)  # noqa

from gerel.algorithms.NEAT.population import NEATPopulation
from gerel.algorithms.NEAT.mutator import NEATMutator
from gerel.algorithms.NEAT.metric import generate_neat_metric
from gerel.populations.genome_seeders import curry_genome_seeder
from gerel.util.datastore import DataStore
from gerel.genome.factories import minimal
from examples.utils import build_env, make_counter_fn

def neat_bipedal_walker():
    pop_size = 400
    mutator = NEATMutator(
        new_edge_probability=0.1,
        new_node_probability=0.05
    )
    genome = minimal(
        input_size=24,
        output_size=4,
        depth=5
    )
    seeder = curry_genome_seeder(
        mutator=mutator,
        seed_genomes=[genome]
    )
    metric = generate_neat_metric(
        c_1=1,
        c_2=1,
        c_3=3
    )
    population = NEATPopulation(
        population_size=pop_size,
        delta=4,
        genome_seeder=seeder,
        metric=metric
    )

    ds = DataStore(name='bip_walker_NEAT_data')

    assign_population_fitness = build_env(
        env_name='BipedalWalker-v3',
        num_steps=200,
        repetition=1)
    counter_fn = make_counter_fn()

    for i in range(500):
        success = assign_population_fitness(population)
        if success and counter_fn():
            break
        population.speciate()
        data = population.to_dict()
        mutator(population)
        ds.save(data)
        print_progress(data)
    return True

def print_progress(data):
    data_string = ''
    for val in ['generation', 'best_fitness', 'worst_fitness', 'mean_fitness']:
        data_string += f' {val}: {data[val]}'
    print(data_string)

if __name__ == "__main__":
    neat_bipedal_walker()


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

import sys
import os

def walklevel(some_dir, level=1):
    some_dir = some_dir.rstrip(os.path.sep)
    assert os.path.isdir(some_dir)
    num_sep = some_dir.count(os.path.sep)
    for root, dirs, files in os.walk(some_dir):
        num_sep_this = root.count(os.path.sep)
        if num_sep + level <= num_sep_this:
            return
        yield (root, dirs, files)

# e.g., home/eduardo/proj/DBN/data/raw/ADNI
data_dir = sys.argv[1]
# e.g., home/eduardo/poj/DBN/data/raw/ADNI/subjects.txt
out_file = sys.argv[2]

# x = (root, dirs, files)
IDList = [x[1] for x in walklevel(data_dir, level=1)]
# Flattening the list of IDs
IDList = [x for ID in IDList for x in ID]
IDList.sort()
if not os.path.exists(out_file):
    with open(out_file, 'w+') as outFile:
        outFile.writelines("%s\n" % ID for ID in IDList)


#导入可视化雷达的库
from pyecharts.charts import Radar
from pyecharts import options as opts
from pyecharts.faker import Faker

#雷达各方面的数值
sc = [{'name':x} for x in Faker.choose()]
radar = (
    Radar(init_opts=opts.InitOpts(width='1000px'))
    #雷达各个角的名字
    .add_schema(
        sc,
        #改变整个雷达的形状
        shape='circle',
        radius='80%'

    )
    #销量的x，y值
    .add(
        '销量',
        [Faker.values(),Faker.values()],
        #改变节点的形状
        symbol='roundRect',
        #改变线的粗细
        linestyle_opts=opts.LineStyleOpts(
            type_='dash'
        )
    )
    # .set_global_opts(legend_opts=opts.LegendOpts(selected_mode='single'))
    #给雷达添加填充
    .set_series_opts(areastyle_opts=opts.AreaStyleOpts(opacity=0.1))
    .render()
)

可视化案例/可视化雷达图/main.py


from unittest import TestCase

from codechef.practice.easy.carvans import CarVans

class TestCarVans(TestCase):
    def test_moving_maximum_speed(self):
        arr = [4, 5, 1, 2, 3]
        cv = CarVans()
        actual_result = cv.maximum_speed(arr)
        expected_result = 2
        self.assertEqual(actual_result, expected_result)


from django.db import models
from moondance.meta_models import MetaModel
from simple_history.models import HistoricalRecords
from operations.models import Product

class Nexternal_Product(MetaModel):
    history = HistoricalRecords()

    sku = models.CharField(max_length=200, unique=True)
    sku_description = models.CharField(max_length=200)
    product = models.ForeignKey(
        Product,
        blank=True,
        null=True,
        on_delete=models.PROTECT,
        related_name="nexternal_product_product_fk",
    )

    def __str__(self):
        return "{}".format(self.sku_description)

    class Meta:
        verbose_name = "Nexternal Product"
        verbose_name_plural = "Nexternal Products"
        ordering = (
            "product__sku",
            "sku",
        )

class Amazon_Product(MetaModel):
    history = HistoricalRecords()

    asin = models.CharField(max_length=200, unique=True)
    sku_description = models.CharField(max_length=200)
    product = models.ForeignKey(
        Product,
        blank=True,
        null=True,
        on_delete=models.PROTECT,
        related_name="amazon_product_product_fk",
    )

    def __str__(self):
        return "{}".format(self.sku_description)

    class Meta:
        verbose_name = "Amazon Product"
        verbose_name_plural = "Amazon Products"
        ordering = (
            "product__sku",
            "asin",
        )

class Shopify_Product(MetaModel):
    history = HistoricalRecords()

    shopify_id = models.BigIntegerField()
    variant_id = models.BigIntegerField(unique=True)
    shopify_sku = models.CharField(max_length=200)
    status = models.CharField(max_length=200, blank=True, null=True)
    title = models.CharField(max_length=200)
    inventory_policy = models.CharField(max_length=200, blank=True, null=True)
    inventory_management = models.CharField(max_length=200, blank=True, null=True)
    grams = models.IntegerField(blank=True, null=True)
    price = models.DecimalField(max_digits=12, decimal_places=2)
    inventory_quantity = models.IntegerField(null=True, blank=True)
    customer_type = models.CharField(max_length=200)
    barcode = models.CharField(max_length=100, blank=True, null=True)
    tags = models.CharField(max_length=1000, blank=True, null=True)
    handle = models.CharField(max_length=200, blank=True, null=True)
    product = models.ForeignKey(
        Product,
        on_delete=models.PROTECT,
        null=True,
        blank=True,
        related_name="shopify_product_sku_fk",
    )

    def __str__(self):
        return "{}".format(self.title)

    class Meta:
        verbose_name = "Shopify Product"
        verbose_name_plural = "Shopify Products"
        ordering = (
            "product__sku",
            "variant_id",
        )

class Product_Missing_SKU(MetaModel):
    source_system_choices = (
        ("Amazon", "Amazon"),
        ("Shopify", "Shopify"),
        ("Nexternal", "Nexternal"),
    )
    source_system = models.CharField(max_length=200, choices=source_system_choices)
    product_description = models.CharField(max_length=200)
    product = models.ForeignKey(
        Product,
        on_delete=models.PROTECT,
        related_name="Product_Missing_SKU_product_fk",
    )

    def __str__(self):
        return "{} ({})".format(self.source_system, self.product_description)

    class Meta:
        verbose_name = "Product Description Mapping"
        verbose_name_plural = "Product Description Mappings"
        unique_together = (
            "source_system",
            "product_description",
        )


from django.conf.urls import include, url
from django.contrib import admin
admin.autodiscover()

urlpatterns = [
    #admin documentation
    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    url(r'^admin/', include(admin.site.urls)),

    #view url, con esto automaticamente carga todas las url que asignemos en urls.py de cada modulo
    url(r'', include('blog.urls')),

]


import logging
import re
from typing import Dict, Iterator, NamedTuple, Optional, Tuple

import pandas as pd

import gluonts  # noqa
from gluonts import transform
from gluonts.core.serde import load_code
from gluonts.dataset.common import DataEntry, Dataset
from gluonts.dataset.stat import (
    DatasetStatistics,
    calculate_dataset_statistics,
)
from gluonts.evaluation import Evaluator
from gluonts.model.estimator import Estimator
from gluonts.model.forecast import Forecast
from gluonts.model.predictor import Predictor
from gluonts.support.util import maybe_len
from gluonts.transform import TransformedDataset

def make_evaluation_predictions(
    dataset: Dataset, predictor: Predictor, num_samples: int
) -> Tuple[Iterator[Forecast], Iterator[pd.Series]]:
    """
    Return predictions on the last portion of predict_length time units of the
    target. Such portion is cut before making predictions, such a function can
    be used in evaluations where accuracy is evaluated on the last portion of
    the target.

    Parameters
    ----------
    dataset
        Dataset where the evaluation will happen. Only the portion excluding
        the prediction_length portion is used when making prediction.
    predictor
        Model used to draw predictions.
    num_samples
        Number of samples to draw on the model when evaluating.

    Returns
    -------
    """

    prediction_length = predictor.prediction_length
    freq = predictor.freq
    lead_time = predictor.lead_time

    def add_ts_dataframe(
        data_iterator: Iterator[DataEntry],
    ) -> Iterator[DataEntry]:
        for data_entry in data_iterator:
            data = data_entry.copy()
            index = pd.date_range(
                start=data["start"],
                freq=freq,
                periods=data["target"].shape[-1],
            )
            data["ts"] = pd.DataFrame(
                index=index, data=data["target"].transpose()
            )
            yield data

    def ts_iter(dataset: Dataset) -> pd.DataFrame:
        for data_entry in add_ts_dataframe(iter(dataset)):
            yield data_entry["ts"]

    def truncate_target(data):
        data = data.copy()
        target = data["target"]
        assert (
            target.shape[-1] >= prediction_length
        )  # handles multivariate case (target_dim, history_length)
        data["target"] = target[..., : -prediction_length - lead_time]
        return data

    # TODO filter out time series with target shorter than prediction length
    # TODO or fix the evaluator so it supports missing values instead (all
    # TODO the test set may be gone otherwise with such a filtering)

    dataset_trunc = TransformedDataset(
        dataset, transformation=transform.AdhocTransform(truncate_target)
    )

    return (
        predictor.predict(dataset_trunc, num_samples=num_samples),
        ts_iter(dataset),
    )

train_dataset_stats_key = "train_dataset_stats"
test_dataset_stats_key = "test_dataset_stats"
estimator_key = "estimator"
agg_metrics_key = "agg_metrics"

def serialize_message(logger, message: str, variable):
    logger.info(f"gluonts[{message}]: {variable}")

def backtest_metrics(
    test_dataset: Dataset,
    predictor: Predictor,
    evaluator=Evaluator(
        quantiles=(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)
    ),
    num_samples: int = 100,
    logging_file: Optional[str] = None,
):
    """
    Parameters
    ----------
    test_dataset
        Dataset to use for testing.
    predictor
        The predictor to test.
    evaluator
        Evaluator to use.
    num_samples
        Number of samples to use when generating sample-based forecasts.
    logging_file
        If specified, information of the backtest is redirected to this file.

    Returns
    -------
    tuple
        A tuple of aggregate metrics and per-time-series metrics obtained by
        training `forecaster` on `train_dataset` and evaluating the resulting
        `evaluator` provided on the `test_dataset`.
    """

    if logging_file is not None:
        log_formatter = logging.Formatter(
            "[%(asctime)s %(levelname)s %(thread)d] %(message)s",
            datefmt="%m/%d/%Y %H:%M:%S",
        )
        logger = logging.getLogger(__name__)
        handler = logging.FileHandler(logging_file)
        handler.setFormatter(log_formatter)
        logger.addHandler(handler)
    else:
        logger = logging.getLogger(__name__)

    test_statistics = calculate_dataset_statistics(test_dataset)
    serialize_message(logger, test_dataset_stats_key, test_statistics)

    forecast_it, ts_it = make_evaluation_predictions(
        test_dataset, predictor=predictor, num_samples=num_samples
    )

    agg_metrics, item_metrics = evaluator(
        ts_it, forecast_it, num_series=maybe_len(test_dataset)
    )

    # we only log aggregate metrics for now as item metrics may be very large
    for name, value in agg_metrics.items():
        if not name[0].isdigit():
            serialize_message(logger, f"metric-{name}", value)

    if logging_file is not None:
        # Close the file handler to avoid letting the file open.
        # https://stackoverflow.com/questions/24816456/python-logging-wont-shutdown
        logger.removeHandler(handler)
        del logger, handler

    return agg_metrics, item_metrics

# TODO does it make sense to have this then?
class BacktestInformation(NamedTuple):
    train_dataset_stats: DatasetStatistics
    test_dataset_stats: DatasetStatistics
    estimator: Estimator
    agg_metrics: Dict[str, float]

    @staticmethod
    def make_from_log(log_file):
        with open(log_file, "r") as f:
            return BacktestInformation.make_from_log_contents(
                "\n".join(f.readlines())
            )

    @staticmethod
    def make_from_log_contents(log_contents):
        messages = dict(re.findall(r"gluonts\[(.*)\]: (.*)", log_contents))

        # avoid to fail if a key is missing for instance in the case a run did
        # not finish so that we can still get partial information
        try:
            return BacktestInformation(
                train_dataset_stats=eval(
                    messages[train_dataset_stats_key]
                ),  # TODO: use load
                test_dataset_stats=eval(
                    messages[test_dataset_stats_key]
                ),  # TODO: use load
                estimator=load_code(messages[estimator_key]),
                agg_metrics={
                    k: load_code(v)
                    for k, v in messages.items()
                    if k.startswith("metric-") and v != "nan"
                },
            )
        except Exception as error:
            logging.error(error)
            return None


#coding:utf-8
import glob
import xml.etree.ElementTree as ET
from kmeans import kmeans, avg_iou
import numpy as np

def load_dataset(path, dirlist):
    dataset = []
    for dirname in dirlist:
        print(dirname)
        for xml_file in glob.glob("{}/*.xml".format(path + dirname)):
            print("--------------------")
            tree = ET.parse(xml_file)

            height = int(tree.findtext("./size/height"))
            width = int(tree.findtext("./size/width"))

            for obj in tree.iter("object"):
                xmin = int(obj.findtext("bndbox/xmin")) / width
                ymin = int(obj.findtext("bndbox/ymin")) / height
                xmax = int(obj.findtext("bndbox/xmax")) / width
                ymax = int(obj.findtext("bndbox/ymax")) / height
                print("------------------------------------------")
                dataset.append([xmax - xmin, ymax - ymin])

    return np.array(dataset)

if __name__ == "__main__":
        data = load_dataset("./", ['0', '1'])
        print(data.shape)
        print(data)
        print("Start Cluster:")
        out = kmeans(data, k=5)
        print("5 Clusters is: ")
        print(out)

        print("Start Cluster:")
        out = kmeans(data, k=7)
        print("7 Clusters is: ")
        print(out)

        print("Start CLuster:")
        out = kmeans(data, k=9)
        print("9 Clusters is: ")
        print(out)


with open("F1.txt", "w") as f1:
    while 1:
        user_input = input("Введите данные (пустая строка для завершения ввода): ")
        if user_input == "":
            break
        f1.write(user_input + "\n")
with open("F1.txt", "r") as f1, open("F2.txt", "w") as f2:
    for line in f1:
        words = line.strip().split()
        if len(words) == 1:
            f2.write(line)
with open("F2.txt", "r") as f2:
    longest_word = ""
    for line in f2:
        word = line.strip()
        if len(word) > len(longest_word):
            longest_word = word
print(f"Самое длинное слово в файле F2: {longest_word}")