#!/usr/bin/python3
import requests

## Define NEOW URL
NEOURL = "https://api.nasa.gov/neo/rest/v1/feed?"

def main():
    ## first I want to grab my credentials
    with open("/home/student/nasa.creds", "r") as mycreds:
        nasacreds = mycreds.read()
    ## remove any newline characters from the api_key
    nasacreds = nasacreds.strip("\n")

    ## update the date below, if you like
    startdate = "start_date=" + getUserDate()

    ## the value below is not being used in this
    ## version of the script
    ## enddate can't be more than 7 days different from start
    ##NEED TO VALIDATE END DATE IF ENTERED TO ENSURE NOT MORE THAN 7 DAY DIFF
    isEndDate = inclEndDate()
    enddate = "&end_date=" + getUserDate() + "&" if isEndDate else "&"

    # make a request with the request library
    neowrequest = requests.get(NEOURL + startdate + enddate + nasacreds)

    # strip off json attachment from our response
    neodata = neowrequest.json()

    #get list of neos
    neos = neodata.get("near_earth_objects")

    #call find largest
    findLargest(neos)

    #call find hazard
    findHazard(neos)

##get date from user
def getUserDate():
    date = ""
    while True:
        print("""
        Enter date you'd like to search asteroids from
        format must be yyyy-mm-dd
        """)
        date = input("> ").strip()
        if isValidDate(date):
            break
        else:
            print("Invalid format, please try again")

    return date

##validate user input
def isValidDate(dateStr):
    isValid = True
    dateArr = dateStr.split("-")
    if len(dateArr) != 3:
        isValid = False
    if len(dateArr[0]) != 4 or len(dateArr[1]) != 2 or len(dateArr[2]) != 2:
        isValid = False
    for numStr in dateArr:
        try:
           dateNum = int(numStr)
           if dateArr[1] == numStr and dateNum > 12:
               isValid = False
               break
        except:
            isValid = False
            break

    return isValid

# ask user if they would like to include an end date
def inclEndDate():
    isEnd = False
    while True:
        user_res = input("Would you like to include a cutoff date of where to stop searching? (y/n) ").strip().lower()
        if user_res == "y":
            isEnd = True
            break
        elif user_res == "n":
            isEnd = False
            break
        else:
            print("please type 'y' or 'n'")

    return isEnd

## display largest neo in range specified
def findLargest(neoData):
    largest = 0
    name = ""
    for date in neoData:
        for neo in neoData[date]:
            neoSize = float(neo["estimated_diameter"]["miles"]["estimated_diameter_max"])
            if neoSize > largest:
                largest = neoSize
                name = neo["name"]

    print(f"{name} is the largest asteroid at an estimated {largest} miles in diameter")

## display total number of potentially hazardous neos in range
def findHazard(neoData):
    hazardous = []
    for date in neoData:
        for neo in neoData[date]:
            if neo["is_potentially_hazardous_asteroid"] == True:
                hazardous.append(neo["name"])

    if len(hazardous) == 0:
        print("There were no potentially hazardous asteroids during this time")
    else:
        print(f"There were {len(hazardous)} hazardous asteroids during this time, the names of these are:")
        for name in hazardous:
            if name == hazardous[-1]:
                print(name)
            else:
                print(name, end=", ")

if __name__ == "__main__":
    main()


import unittest
from unittest.mock import patch, call

from decentralized_smart_grid_ml.exceptions import NotValidAggregationMethod
from decentralized_smart_grid_ml.federated_learning.contributions_extractor import ContributionsExtractorCreator, \
    ContributionsExtractor, ContributionsExtractorEnsembleGeneral, ContributionsExtractorSimpleAverage

class TestContributionsExtractor(unittest.TestCase):

    def test_factory_method(self):
        contributions_extractor_method = ContributionsExtractorCreator.factory_method(
            "ensemble_general",
            "test_model",
            "x_validation",
            "y_validation"
        )
        self.assertIsInstance(contributions_extractor_method, ContributionsExtractorEnsembleGeneral)
        contributions_extractor_method = ContributionsExtractorCreator.factory_method(
            "simple_average",
            "test_model",
            "x_validation",
            "y_validation"
        )
        self.assertIsInstance(contributions_extractor_method, ContributionsExtractorSimpleAverage)
        with self.assertRaises(NotValidAggregationMethod):
            ContributionsExtractorCreator.factory_method(
                "not_existing_method",
                "test_model",
                "x_validation",
                "y_validation"
            )

    def test_contributions_extractor_creation_not_valid_arguments(self):
        with self.assertRaises(ValueError):
            ContributionsExtractor(None, None, None)

    # test added only for coverage
    def test_compute_contribution(self):
        contributions_extractor = ContributionsExtractor("model", "x_validation", "y_validation")
        contributions_extractor.compute_contribution(None, None)

    @patch("tensorflow.keras.Sequential")
    def test_compute_contribution_ensemble_general(self, model_mock):
        x_val = [[1, 2], [2, 3]]
        y_val = [0, 1]
        participants_weights = [[1, 2], [3, 4]]
        contributions_extractor = ContributionsExtractorEnsembleGeneral(model_mock, x_val, y_val)
        models_evaluation = [1.0, 0.0]
        model_mock.evaluate.side_effect = [
            ["loss0", models_evaluation[0]],
            ["loss1", models_evaluation[1]],
        ]
        alpha_expected = [1.0, 0.0]
        alpha = contributions_extractor.compute_contribution(participants_weights, 0.5)
        model_mock.set_weights.assert_has_calls([
            call(participants_weights[0]),
            call(participants_weights[1])
        ])
        model_mock.evaluate.assert_has_calls([
            call(x_val, y_val),
            call(x_val, y_val)
        ])
        self.assertListEqual(alpha_expected, alpha)

    def test_compute_contribution_simple_average(self):
        x_val = [[1, 2], [2, 3]]
        y_val = [0, 1]
        participants_weights = [[1, 2], [3, 4]]
        contributions_extractor = ContributionsExtractorSimpleAverage(None, x_val, y_val)
        alpha_expected = [0.5, 0.5]
        alpha = contributions_extractor.compute_contribution(participants_weights, 0)
        self.assertListEqual(alpha_expected, alpha)


import socket

# a funcao gethostname retorna o nome da maquina
#host = ''socket.gethostname()
host=''
port = 9999
addr=(host,port)

# criando o socket TCP
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#Essa linha serve para zerar o TIME_WAIT do Socket
serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# bind to the port
serversocket.bind(addr)

# limite de conexoes
serversocket.listen(5)
msgclient='teste'

#estabelece conexao
clientsocket,client = serversocket.accept()
print("Conexao com: " + str(client))

while msgclient!='0':

	receive=clientsocket.recv(1024)
	msgclient=str(receive.decode('ascii'))
	print("Mensagem recebida: "+msgclient)
	if msgclient=='0':
		break

	msg=input("Digite a mensagem que deseja enviar: ")
	clientsocket.send(msg.encode('ascii'))

serversocket.close()


import sys
import random
import string
import time
import math

def show_progress_bar(bar_length, completed, total):
    bar_length_unit_value = (total / bar_length)
    completed_bar_part = math.ceil(completed / bar_length_unit_value)
    progress = "*" * completed_bar_part
    remaining = " " * (bar_length - completed_bar_part)
    percent_done = "%.2f" % ((completed / total) * 100)
    print(f'[{progress}{remaining}] {percent_done}%', end='\r')

def gen(name, Mb, K=(10, 100), L=(3,10)):
    file = open(name + '.txt', 'w')
    size = Mb * 1024**2
    text = ''
    while sys.getsizeof(text) < size:
        num1 = random.randint(*K)
        for i in range(num1):
            num2 = random.randint(*L)
            word = ''.join(random.choice(string.ascii_lowercase) for i in range(num2))
            text += word + ' '
        text += '\n'
        show_progress_bar(50,sys.getsizeof(text),size)
    file.write(text)
    file.close()
    if sys.getsizeof(text) >= size:
        print("\n"+ "Your file is ready")

#запуск функции и взаимодействие с пользователем
def main():
    while True:
        name = input("Enter file name: ")
        try:
            Mb = float(input("Enter size of the file: "))
            K = tuple(int(x.strip()) for x in input("Enter number of words(interval): ").split(','))
            L = tuple(int(x.strip()) for x in input("Enter length of words(interval): ").split(','))
            break
        except ValueError:
            print("Wrong input")
    gen(name, Mb, K, L)

if __name__ == "__main__":
    main()


import sys
import cv2
import getopt
import numpy as np
import ArducamDepthCamera as ac

MAX_DISTANCE = 4

def process_frame(depth_buf: np.ndarray, amplitude_buf: np.ndarray) -> np.ndarray:

    depth_buf = np.nan_to_num(depth_buf)

    amplitude_buf[amplitude_buf<=7] = 0
    amplitude_buf[amplitude_buf>7] = 255

    depth_buf = (1 - (depth_buf/MAX_DISTANCE)) * 255
    depth_buf = np.clip(depth_buf, 0, 255)
    result_frame = depth_buf.astype(np.uint8)  & amplitude_buf.astype(np.uint8)
    return result_frame

class UserRect():
    def __init__(self) -> None:
        self.start_x = 0
        self.start_y = 0
        self.end_x = 0
        self.end_y = 0

selectRect = UserRect()

followRect = UserRect()

def on_mouse(event, x, y, flags, param):
    global selectRect,followRect

    if event == cv2.EVENT_LBUTTONDOWN:
        pass

    elif event == cv2.EVENT_LBUTTONUP:
        selectRect.start_x = x - 4 if x - 4 > 0 else 0
        selectRect.start_y = y - 4 if y - 4 > 0 else 0
        selectRect.end_x = x + 4 if x + 4 < 240 else 240
        selectRect.end_y=  y + 4 if y + 4 < 180 else 180
    else:
        followRect.start_x = x - 4 if x - 4 > 0 else 0
        followRect.start_y = y - 4 if y - 4 > 0 else 0
        followRect.end_x = x + 4 if x + 4 < 240 else 240
        followRect.end_y = y + 4 if y + 4 < 180 else 180

def usage(argv0):
    print("Usage: python "+argv0+" [options]")
    print("Available options are:")
    print(" -d        Choose the video to use")

if __name__ == "__main__":

    if(len(sys.argv) < 2):
        usage(sys.argv[0])
        sys.exit()
    opts, arg = getopt.getopt(sys.argv[1:], 'hd:', ['help'])
    for option, value in opts:
        if option in ['-d']:
            if value.isdigit() == True:
                select_video = int(value)
            else:
                usage(sys.argv[0])
                sys.exit()
        else:
            usage(sys.argv[0])
            sys.exit()

    cam = ac.ArducamCamera()
    if cam.open(ac.TOFConnect.USB,select_video) != 0 :
        print("initialization failed")
        sys.exit()
    if cam.start(ac.TOFOutput.DEPTH) != 0 :
        print("Failed to start camera")
        sys.exit()
    cam.setControl(ac.TOFControl.RANG,MAX_DISTANCE)
    cv2.namedWindow("preview", cv2.WINDOW_AUTOSIZE)
    cv2.setMouseCallback("preview",on_mouse)
    while True:
        frame = cam.requestFrame(200)
        if frame != None:
            depth_buf = frame.getDepthData()
            amplitude_buf = frame.getAmplitudeData()
            cam.releaseFrame(frame)
            amplitude_buf*=(255/1024)
            amplitude_buf = np.clip(amplitude_buf, 0, 255)

            cv2.imshow("preview_amplitude", amplitude_buf.astype(np.uint8))

            result_image = process_frame(depth_buf,amplitude_buf)
            result_image = cv2.applyColorMap(result_image, cv2.COLORMAP_JET)
            cv2.rectangle(result_image,(selectRect.start_x,selectRect.start_y),(selectRect.end_x,selectRect.end_y),(128,128,128), 1)
            cv2.rectangle(result_image,(followRect.start_x,followRect.start_y),(followRect.end_x,followRect.end_y),(255,255,255), 1)
            print("select Rect distance:",np.mean(depth_buf[selectRect.start_x:selectRect.end_x,selectRect.start_y:selectRect.end_y]))
            cv2.imshow("preview",result_image)

            key = cv2.waitKey(1)
            if key == ord("q"):
                exit_ = True
                cam.stop()
                cam.close()
                sys.exit(0)


from itertools import filterfalse
from IO.matrix_reader import read_matrix
import time

from determinanat_calc.util import measure_exec_time

def minor_calc(matrix, begin_row_index, column_indexes, measure_parallel_code = False):
    """
    Calculates an arbitrary minor of given matrix. The original matrix is accessed
    for calculation (only the necessary rows and columns). Returns two values:
        1. the value of the minor
        2. time in milliseconds spent executing code that can be parallelized if argument
        measure_parallel_code is True, and zero otherwise (it will not be measured)

    Args:
        matrix (list(list(float))): matrix containing the submatrix of the minor
        begin_row_index (int): index of the first row of the submatrix for the minor, in the original matrix
        column_indexes (list(int)): indexes of columns of the submatrix for the minor, in the original matrix
        measure_parallel_code (bool): indicates whether the execution time for code that can be parallelized
        should be measured, it is False by default for better performance

    Return:
        value of the given minor, time spent executing code that can be parallelized ( (float, float) )
    """

    # order of submatrix
    n = len(column_indexes)

    # if order is one, return the only element of the submatrix as the minor
    if n == 1:
        return matrix[begin_row_index][column_indexes[0]], 0.0

    # initialize the values to calculate the determinant
    result = 0
    minors = [0 for i in range(n)]
    sgn = 1

    # expansion over first row
    parallel_code_exec_time = 0
    for idx, col in enumerate(column_indexes):
        minor_cols = list(filterfalse(lambda el: el == col, column_indexes))
        # calculate required minors (this can be done in parallel)
        if measure_parallel_code:
            start_time = time.time()
            minor, _ = minor_calc(matrix, begin_row_index + 1, minor_cols)
            end_time = time.time()
            minor_calc_time = (end_time - start_time) * 1000
            minors[idx] = minor
            parallel_code_exec_time += minor_calc_time
        else:
            minor, _ = minor_calc(matrix, begin_row_index + 1, minor_cols)
            minors[idx] = minor

    for j in range(n):
        result += sgn * matrix[begin_row_index][column_indexes[j]] * minors[j]
        sgn *= -1

    return result, parallel_code_exec_time

@measure_exec_time
def det_serial(matrix):
    """
    Calculates and returns the determinant of given matrix using serial implementation, as well
    as time in milliseconds, spent executing code that can be parallelized.
    Since it is decorated with measure_exec_time, the execution time in milliseonds is also returned.

    Args:
        matrix (list(list(float)): matrix for which the determinant is calculated.

    Return:
        value of the determinant, time spent executing code that can be parallelized
        and total execution time in milliseconds ( (float, float, float) )
    """
    n = len(matrix)
    cols = list([i for i in range(n)])
    determinant, parallel_code_exec_time = minor_calc(matrix, 0, cols, measure_parallel_code=True)
    return determinant, parallel_code_exec_time

if __name__ == "__main__":
    test_matrix = read_matrix("../../test_data/matrica5x5.txt")
    determinant, parallel_code_exec_time, exec_time_ms = det_serial(test_matrix)
    print('det(matrix) =', determinant)
    print('Execution time was: {} ms.'.format(exec_time_ms))


import time
from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()

driver.get('C:/Users/Sergio Vegue/Desktop/URJC/4/2o cuatri/MDS/index.html')
time.sleep(5)

frase = ""
for i in range(1, 21):
    palabra = driver.find_element(By.ID, "word_"+str(i)).text
    frase += palabra+" "
escribir = driver.find_element(By.XPATH, '//*[@id="textInput"]')
escribir.send_keys(frase)
time.sleep(10)


n = int(input("n = "))
prime = True
f = 2

while (f*f <= n):

    if n % f == 0:
        prime = False

    f += 1

print(prime)

"""
x = 0
y = 0

a = 0
b = 0
c = 0

while (a < 5):

    c += 1
    if a == b:
        b = 0
        a += 1

    if c % 2 == 0:
        b += 1

    print(a, b)

x = 0

step = 0
counter = 0
turn = 0

while(step <= 10):

    if counter % 2 == 0:
        step += 1

    print(step)
    counter += 1
"""


fib = [1,1]
i = 0

# appends next fibonacci number until the length is 1000
while True:
    fib.append(fib[i]+fib[i+1])
    if len(str(fib[i] + fib[i+1])) == 1000:
        break
    i+=1

print(fib[-1])
print(len(fib))


import os
import subprocess as sp
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

BASE_PATH = "/cs/usr/ehassid/Downloads/"
SCRIPT_DIR = "/cs/usr/ehassid/PycharmProjects/proteins_hackathon/"
sh2_ref_path = "pdb6pxc.A.pdb"
sh2_predicted_files = ["/cs/usr/ehassid/Downloads/actual_data/pdb1bmb/pdb1bmb_SH2_A.pdb", "pdb6pxc.A.pdb"]
pred_dir = os.path.join(BASE_PATH, "pred_pdbs")
reference_dir = os.path.join(BASE_PATH, "actual_data")
ALIGN = "/cs/usr/ehassid/PycharmProjects/proteins_hackathon/alignMPtrans.pl"

def get_data():
    """
    returns a list [match_num, transition, RMSD] taken from "2_sol.res" in the current dir
    """
    if not os.path.exists(os.path.join(BASE_PATH,"2_sol.res")):
        return None
    output_file = open(os.path.join(BASE_PATH,"2_sol.res"))
    content = output_file.readlines()
    RMSD = float((content[12].split()[-1]))
    return RMSD

def check_alignment_in_dir(dir_path, match_num_threshold, ref_path):
    """
    gets a dir path, returns a dictionary with key filename.pdb, and value- [match_num, transition, RMSD]
    In the dir- a file for every chain in a larger pdb file
    """
    data_dict = dict()
    os.chdir(dir_path)
    for f in os.listdir():
        if f[:-4] == os.path.basename(dir_path):
            continue
        if f.endswith(".pdb"):
            sp.run([ALIGN, ref_path, f, "out"], stdout=sp.DEVNULL, stderr=sp.DEVNULL)
            data_list = get_data()  # get relevant data from 2_sol.res
            if data_list[0] > match_num_threshold:
                data_dict[f] = data_list

    os.chdir("..")
    return data_dict

def get_pred_sh2_rmsds():
    """
    returns a list of all predicted peptides RMSD from alignment against the reference peptide
    """
    sh2_rmsds = []
    os.chdir(BASE_PATH)
    for pdb_dir in os.listdir(pred_dir):
        # print("----- checking RMSD for SH2: ", pdb_dir)
        for pdb_file in os.listdir(os.path.join(pred_dir,pdb_dir)):
            if pdb_file.find("SH2") != -1:
                sh2_pred_path = os.path.join(pred_dir,pdb_dir,pdb_file)
                pdb_ref_path = os.path.join(reference_dir, pdb_dir)
                sh2_ref_path = ""
                for ref_file in os.listdir(pdb_ref_path):
                    if pdb_file.find("SH2") != -1:
                        sh2_ref_path = os.path.join(pdb_ref_path, ref_file)
                sp.run([ALIGN, sh2_ref_path, sh2_pred_path, "out"], stdout=sp.DEVNULL, stderr=sp.DEVNULL)
                rmsd = get_data()  # get relevant data from 2_sol.res
                if (rmsd == None):
                    print("No RMSD for file: ", pdb_file)
                sh2_rmsds.append(rmsd)
    return sh2_rmsds

def get_pred_peptide_rmsds():
    """
    returns a list of all predicted peptides RMSD from alignment against the reference peptide
    """
    peptide_rmsds = []
    os.chdir(BASE_PATH)
    for pdb_dir in os.listdir(pred_dir):
        # print("----- checking RMSD for peptide: ", pdb_dir)
        for pdb_file in os.listdir(os.path.join(pred_dir,pdb_dir)):
            if pdb_file.find("peptide") != -1:
                pept_pred_path =os.path.join(pred_dir,pdb_dir,pdb_file)
                pdb_ref_path = os.path.join(reference_dir, pdb_dir)
                pept_ref_path = ""
                for ref_file in os.listdir(pdb_ref_path):
                    if pdb_file.find("SH2") != -1:
                        pept_ref_path = os.path.join(pdb_ref_path, ref_file)
                sp.run([ALIGN, pept_ref_path, pept_pred_path, "out"], stdout=sp.DEVNULL, stderr=sp.DEVNULL)
                rmsd = get_data()  # get relevant data from 2_sol.res
                if (rmsd == None):
                    print("No RMSD for file: ", pdb_file)
                peptide_rmsds.append(rmsd)
    return peptide_rmsds

if __name__ == "__main__":
    sh2_rmsds = get_pred_sh2_rmsds()
    peptide_rmsds = get_pred_peptide_rmsds()
    print(len(sh2_rmsds))
    print(len(peptide_rmsds))

    df = pd.DataFrame(data=[sh2_rmsds, peptide_rmsds], index=['SH2', 'Peptide'])
    fig = plt.figure(figsize=(10, 7))
    ax = fig.add_subplot(111)
    # Creating plot
    ax.boxplot(df)
    plt.xticks([1, 2], ["SH2", "Peptide"])
    ax.set_xlabel('protein')
    ax.set_ylabel('RMSD')
    plt.show()


from colorama import Fore, Back, Style
from data import *
from fire_beam import *
import sys

bullets = []

class Bullet:
    def __init__(self, x, y, bullet_number):
        self.__x = x
        self.__y = y
        self.__bullet_number = bullet_number
        self.__display = bullet_display
        self.__present = True

        bullets.append(self)

    def erase(bullet_number, board):

        for i in bullets:
            if i.__bullet_number == bullet_number:
                i.__present = False
                board.grid[i.__x][i.__y].display = base_display
                board.grid[i.__x][i.__y].isBullet = False
                break

    def move(board, mandalorian, boss, first_time):

        for i in bullets:

            if i.__present:
                x = i.__x
                y = i.__y

                if board.grid[x][y].isCoin:
                    display = coin_display

                elif board.grid[x][y].isBoost:
                    display = boost_display

                else:
                    display = base_display

                board.grid[x][y].display = display
                board.grid[x][y].isBullet = False

                y += 1

                if y == columns - 1:
                    Bullet.erase(i.__bullet_number, board)

                elif y > (board.curPos + columnsAtATime):
                    Bullet.erase(i.__bullet_number, board)

                elif board.grid[x][y].isEnemy:
                    boss.lives -= 1
                    mandalorian.score += 15

                    if boss.lives <= 0:
                        boss.erase(board)
                        mandalorian.move_end(board, boss, first_time)
                        boss.game_over(mandalorian)
                        # sys.exit(0)

                    Bullet.erase(i.__bullet_number, board)

                elif board.grid[x][y].isIceBall:
                    Bullet.erase(i.__bullet_number, board)

                elif board.grid[x][y].obstacle:
                    FireBeam.erase(board.grid[x][y].beam_number, board)
                    Bullet.erase(i.__bullet_number, board)
                    mandalorian.score += 10

                else:
                    board.grid[x][y].display = bullet_display
                    board.grid[x][y].isBullet = True
                    board.grid[x][y].bullet_num = i.__bullet_number
                    i.__y += 1


from flask_sqlalchemy import SQLAlchemy
from flask import Flask,url_for,redirect,render_template,request
import os
import webbrowser
import bs4 as bs
import requests

#os.system('database.py')

def log(x):
    filee=open("log.dat","w")
    filee.writeline(x)
    filee.close()

global results
results=[]

#flasking starts here
app=Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = 'sqlite:///./test.db'
app.config["secret_key"]="very_secret"
app.config['TESTING'] = True
db=SQLAlchemy(app)

class accessdb:
    def __init__(self):
        pass

    def writeindb(self,name,link):
            try:
                link=linkholder(name=name,link=link)
                db.session.add(link)
                db.session.commit()
                return True
            except:
                return False

    def readindb(self):
        try:
            link=linkholder(name=None,link=None)
            links=link.query.all()
            return links
        except:
            return False

class linkholder(db.Model):
    idd = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), unique=True, nullable=False)
    link = db.Column(db.String(250), unique=True, nullable=False)

    def __repr__(self):
        return "User \n name "+self.name+" link "+self.link

access=accessdb()

def checkindb(query):

    if "--ignore-database" in query:

        return None

    try:
        links=access.readindb()
        query=query.lower()

        for linked in links:
            linkofsite=linked.link
            nameofsite=linked.name
            if (nameofsite.lower()==query):
                print(linkofsite)
                return linkofsite
            else:
                pass
    except:
        return None

def getlink(query):
    link_predict=checkindb(query)

    if link_predict:
        print("Using database")
        print(link_predict)
        result={}
        result["query"]=query
        result["link"]=link_predict
        results.insert(0,result)
    else:

        try:
            result={}
            q=query
            headers={}
            q=q.replace(" ","+")
            headers['User-Agent'] = 'Mozilla/5.0 (X11; Li5nux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17'
            url="https://www.google.com.np/search?q="+q
            sauce=requests.get(url,headers=headers)
            sauce=sauce.content
            soup=bs.BeautifulSoup(sauce,'html.parser')
            links=soup.find_all('a')
            a=0
            for j in links:
                a+=1
                if a>20:
                    link = (str(j.get('href')))
                    if (link!=None and len(link)>20 and link.startswith("http")):

                        if "--ignore-database" in query:
                            query=query.replace("--ignore-database","")
                        else:
                            access.writeindb(query,link)

                        result["query"]=query
                        result["link"]=link
                        break

            results.insert(0,result)
        except Exception as e:
            print (e)

@app.route("/database")
def database():
    links=access.readindb()
    return render_template("database.html",links=links)

@app.route("/",methods=["POST","GET"])
@app.route("/homepage",methods=["POST","GET"])
def home():

    if request.method=="GET":
        return render_template("home.html",results=results)

    else:
        if request.method=="POST":
            query=request.form["comm"]
            getlink(query)
            return redirect(url_for("home"))

if __name__=='__main__':
    webbrowser.open("http://127.0.0.1:5000/")
    app.run(debug=True,port=5000)


#!/usr/bin/python3

class LinkedList:
    def __init__(self, nodes=None):
        self.head = None
        if nodes is not None:
            node = Node(data=nodes.pop(0))
            self.head = node
            for elem in nodes:
                node.next = Node(data=elem)
                node = node.next

    def __iter__(self):
        node = self.head
        while node is not None:
            yield node
            node = node.next

    def __repr__(self):
        node = self.head
        nodes = []
        while node is not None:
            nodes.append(str(node.data))
            node = node.next
        nodes.append("None")
        return " -> ".join(nodes)

    def add_first(self, node):
        node.next = self.head
        self.head = node

    def add_last(self, node):
        if self.head is None:
            self.head = node
            return
        for currentNode in self:
            pass
        currentNode.next = node

    def add_after(self, targetNodeData, newNode):
        if self.head is None:
            raise Exception("List is empty")

        for node in self:
            if node.data == targetNodeData:
                newNode.next = node.next
                node.next = newNode
                return

        raise Exception("Node with data '%s' not found" % str(targetNodeData))

    def add_before(self, targetNodeData, newNode):
        if self.head is None:
            raise Exception("List is empty")

        if self.head.data == targetNodeData:
            return self.add_first(newNode)

        prevNode = self.head
        for node in self:
            if node.data == targetNodeData:
                prevNode.next = newNode
                newNode.next = node
                return

            prevNode = node

        raise Exception("Node with data '%s' not found" % str(targetNodeData))

    def remove_node(self, targetNodeData):
        if self.head is None:
            raise Exception("List is empty")

        if self.head.data == targetNodeData:
            self.head = self.head.next
            return

        prevNode = self.head
        for node in self:
            if node.data == targetNodeData:
                prevNode.next = node.next
                return
            prevNode = node

        raise Exception("Node with data '%s' not found" % str(targetNodeData))

    def get_last(self):
        if self.head is None:
            raise Exception("List is empty")

        node = self.head
        while node.next is not None:
            node = node.next

        return node

    def rotate_right(self, movePostions):
        if self.head is None:
            raise Exception("List is empty")

        for postion in range(0, movePostions):
            lastNode = self.get_last()
            self.remove_node(lastNode.data)
            self.add_first(Node(lastNode.data))

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

    def __repr__(self):
        return str(self.data)

llist = LinkedList([7, 7, 3, 5])
print(llist)

# llist.remove_node(7)

# llist.add_after(3, Node(4))
# print(llist)

# llist.add_before(3, Node(8))
# print(llist)

# for node in llist:
#     print(node)

# print(llist.get_last())

llist.rotate_right(2)
print(llist)

llist = LinkedList([1, 2, 3, 4, 5])
print(llist)
llist.rotate_right(3)
print(llist)


# Author: Jerry Xia <jerry_xiazj@outlook.com>

import time
import tensorflow as tf
from config import CFG
from core.utils import draw_class
from core.model import MobileNetv3_small
from core.dataset import Dataset

tf.keras.backend.set_learning_phase(False)

####################################
#          Generate Dataset        #
####################################
test_set = Dataset(CFG.test_file, CFG.batch_size, 1, train=False)

####################################
#           Create Model           #
####################################
tf.print("Start creating model.")
input_tensor = tf.keras.layers.Input(shape=(224, 224, 3))
output_tensor = MobileNetv3_small(CFG.num_classes)(input_tensor)
model = tf.keras.Model(inputs=input_tensor, outputs=output_tensor)

ckpt = tf.train.Checkpoint(model=model)
manager = tf.train.CheckpointManager(ckpt, CFG.checkpoint_dir, max_to_keep=3)
if manager.latest_checkpoint:
    ckpt.restore(manager.latest_checkpoint)
    tf.print("Restored from ", manager.latest_checkpoint)
else:
    tf.print("Initializing from scratch.")
tf.print("Finish creating model.")

####################################
#             Predict              #
####################################

start = time.time()

test_img = test_set.generate_batch()
pred = model(test_img)
index = tf.argmax(pred, axis=-1).numpy()

for i, img in enumerate(test_set.generate_origin()):
    classes = CFG.classes[index[i]]
    print(classes)
    score = pred[i, index[i]].numpy()
    print(score)
    path = CFG.log_dir + "test/" + str(i)+".png"
    draw_class(img, classes, score, path)

tf.print("Finish predicting. Time taken:", time.time()-start, "sec.")


# Q.10804
order_list = []
for i in range(10):
    a, b = map(int, input().split())
    order_list.append([a,b])

base_list = [i for i in range(1,21)]

for a in order_list:
    base_list = base_list[:a[0]-1] + base_list[a[0]-1:a[1]][::-1] + base_list[a[1]:]

print(' '.join(list(map(str, base_list))))

# Q.15552
import sys

T = int(input())

for i in range(T):
    a,b = map(int, sys.stdin.readline().split())
    print(a+b)

# Q. 별그리기 -> 너무기본이라 하나만

N = int(input())

for i in range(N):
    print((" ")*i +"*"*(N-i))

# Q.10807
import sys

N = int(input())
num_list = list(map(int, sys.stdin.readline().split()))
find_num = int(input())
print(num_list.count(find_num))

# Q.13300

from collections import defaultdict

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

room_dict = defaultdict(int)

for i in range(N):
    sex, grade = input().split()
    room_dict[sex+grade] += 1

cnt = 0
for i in room_dict:
    if room_dict[i] % 2 == 0:
        cnt += room_dict[i] // K
    else:
        cnt += room_dict[i] // K + 1

print(cnt)


names = ['Michael', 'Bob', 'Tracy']
for name in names:
    print(name)

sum = 0
for x in [1,2,3,4,5,6,7,8,9,10]:
    sum += x
print(sum)

print(list(range(100)))

sum = 0
for x in range(101):
    sum += x
print(sum)

sum = 0
n = 99
while n > 0:
    sum += n
    n -= 2
print(sum)

L = ['Bart', 'Lisa', 'Adam']
for name in L:
    print('Hello, %s!' % name)
    print('Hello, {0}!'.format(name))
    print(f'Hello, {name}!')

n = 1
while n <= 100:
    if n > 10:
        break
    print(n)
    n += 1
print('END')

n = 0
while n < 10:
    n += 1
    if n % 2 == 0:
        continue
    print(n)


""" Statistics Test file for Multi_Maths Package """
# __doc__ (Statistics Test file for testing modules and packages)

import configparser
from importlib.resources import files
import unittest

from multi_maths.mm_statistics.mm_statistics import MM_Statistics

class TestStatistics(unittest.TestCase):
    """
    Class for unittest Statistics
    """

    def setUp(self):
        """
        Instance the MM_Statistics()
        """

        lang_file = files("multi_maths").joinpath('languages/en.ini')  # noqa: E501  # pylint: disable=C0301
        self.lang = configparser.ConfigParser()
        self.lang.sections()
        self.lang.read(lang_file, 'UTF-8')

        self.statistics = MM_Statistics(self.lang, 'digit')
        self.data_list = [8, 17, 41, 3, 21, 30, 11, 9]

    def test_standard_deviation(self):
        """
        standard_deviation() test for unittest
        """

        test = self.statistics.standard_deviation(self.data_list, 7)
        resolve = 16.978978599601163

        self.assertEqual(test, resolve)

    def test_mean(self):
        """
        mean() test for unittest
        """

        test = self.statistics.mean(self.data_list)
        resolve = 17.5

        self.assertEqual(test, resolve)

    def test_median(self):
        """
        median() test for unittest
        """

        test = self.statistics.median(self.data_list)
        resolve = 14.0

        self.assertEqual(test, resolve)

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


import time
import urllib
from os import path
from feed import atom
from mpx.componentry import adapts
from mpx.componentry import implements
from mpx.componentry import register_adapter
from mpx.service.alarms2.interfaces import IAlarmManager
from mpx.service.alarms2.interfaces import IFlatAlarmManager
from mpx.www.w3c.syndication.atom.interfaces import IAtomDocument

class AtomSyndicator(object):
    implements(IAtomDocument)
    adapts(IAlarmManager)
    xml_declaration = '<?xml version="1.0" encoding="utf-8"?>'

    def __init__(self, manager):
        self.manager = manager
        self.flattened = IFlatAlarmManager(manager)
        self.uri_base = self.manager.nodespace.url
        self.manager_url = urllib.quote(self.manager.url)
        self.feed_id = self.uri_base + self.manager_url
        self.link_base = self.uri_base + '/syndication' + self.manager_url
        self.categories = {
            'raised': atom.Category("Raised"),
            'inactive': atom.Category("Inactive"),
            'accepted': atom.Category("Accepted"),
            'cleared': atom.Category("Cleared"),
            'closed': atom.Category("Closed")
        }
        super(AtomSyndicator, self).__init__(manager)

    def render(self, request_path = None, cache_id = None):
        return str(self.get(request_path, cache_id))

    def get(self, request_path, cache_id):
        output = self.xml_declaration + '\n'
        xmldoc = self.setup_xmldoc(request_path)
        feed = xmldoc.root_element
        entries = self.setup_entries(request_path, cache_id)
        map(feed.entries.append, entries)
        return xmldoc

    def setup_xmldoc(self, request_path):
        xmldoc = atom.XMLDoc()
        feed = atom.Feed()
        feed.title = atom.Title(self.manager.name)
        feed.id = atom.Id(self.feed_id)
        xmldoc.root_element = feed
        return xmldoc

    def setup_entries(self, request_path, cache_id):
        entries = []
        content = "Alarm %s switched to %s state at %s.\n\n"
        content += "Please visit the Alarm Management link provided "
        content += "in this entry to view details and make modifications."
        t_update = time.time()
        updated = atom.Updated(t_update)
        for event in self.flattened:
            if event.state == 'inactive':
                continue
            entry = atom.Entry()
            entry.title = atom.Title(event.name)
            entry.id = atom.Id(event.id)
            entry.summary = atom.Summary('Alarm %s' % event.state)
            entry.published = atom.Published(event.timestamp)
            entry.updated = updated
            entry_content = content % (event.name, event.state.upper(),
                                       entry.published.text)
            entry.content = atom.Content(entry_content)
            entry.categories.insert(0, self.categories[event.state])
            entry.link = atom.Link(
                path.join(self.link_base, urllib.quote(event.name), event.id))
            entries.append(entry)
        return entries

register_adapter(AtomSyndicator)


#!/bin/python3

import os
import re
import sys
import time
import math
import random

#-------------------------- Example 1: Basic example of iterators
class FirstHundredNumber:

    def __init__(self):
        self.number = 0

    ### iterators are those which have next() function;
    def __next__(self):
        if(self.number < 100):
            pre = self.number
            self.number += 1
            return pre
        else:
            raise StopIteration()

    ### Iterables are used to return iterator obj
    def __iter__(self):
        return self

class EvenOddNumber:

    def __init__(self,Flag=True):
        self.cur = 0

    def __next__(self):
        if(self.cur < 100):
            if(self.flag):
                if(self.cur % 2 == 0):
                    pre = self.cur
                    self.cur += 2
                    return pre
            else:
                if(x%2 != 0):
                    pre = self.cur
                    self.cur += 1
                    return pre
        else:
            raise StopIteration()

def example1():
   num = FirstHundredNumber()
   print(list(num))
   # print(num.__name__)
   # print(next(num))
   # print(next(num))

#-------------------------- /Example 1;;

##---Main Execution;;
def main():
    example1()

if __name__ == '__main__':
    print("#------------ Code Start --------------#")
    startTime = time.time()
    main()
    endTime = time.time()
    print("Run Time:",endTime-startTime,"ms")
    print("#------------ Code Stop ----------------#")


# -*- coding: utf-8 -*-
"""
Utilities for data collection and analysis.

@author: stewart
"""
import os
import re
from pysocialwatcher import watcherAPI
from pysocialwatcher.constants import TOKENS
import json

def query_facebook_audience(access_token, user_id, query_file, extra_auth_data=[], response_file=None):
    """
    Build manual query and execute request.

    access_token :: FB access token
    user_id :: FB user ID
    query_file :: JSON file containing query
    extra_auth_data :: List of auth data pairs.
    response_file :: Name of existing response file, if needed.

    response :: DataFrame with query response(s) => one response per row
    """
    watcher = watcherAPI()
    if(not (access_token, user_id) in TOKENS):
        watcher.add_token_and_account_number(access_token, user_id)
    for (access_token_i, user_id_i) in extra_auth_data:
        if(not (access_token_i, user_id_i) in TOKENS):
            watcher.add_token_and_account_number(access_token_i, user_id_i)
    print('%d FB tokens'%(len(TOKENS)))

    ## execute data collection
    if(response_file is not None and os.path.exists(response_file)):
        print('using response file %s'%(response_file))
        response = watcher.load_data_and_continue_collection(response_file)
    else:
        response = watcher.run_data_collection(query_file)

    ## clean up temporary dataframes
    file_matcher = re.compile('dataframe_.*.csv')
    tmp_files = filter(lambda f: file_matcher.search(f) is not None, os.listdir('.'))
    for f in tmp_files:
        os.remove(f)

    return response

def load_facebook_auth(auth_file='data/facebook_auth.csv'):
    """
    Load Facebook ad API authentication from file.

    auth_file :: File name.

    access_token :: Access token.
    user_id :: User ID.
    app_id :: App ID.
    app_secret :: Secret app ID.
    """
    auth_data = list(open(auth_file))[0].strip().split(',')
    if(len(auth_data) == 2):
        access_token, user_id = auth_data
        app_id = None
        app_secret = None
    elif(len(auth_data) == 4):
        access_token, user_id, app_id, app_secret = auth_data
#    access_token, user_id = list(open(auth_file))[0].strip().split(',')[:2]
    return access_token, user_id, app_id, app_secret

def query_and_write(query_file, out_dir, extra_auth_files=[], response_file=None):
    """
    Query Facebook for specified JSON target and
    write results to out_dir as .tsv.

    query_file :: JSON file containing query
    out_dir :: Output directory.
    extra_auth_files :: Extra FB auth data files.
    response_file :: Name of existing response file, if needed.
    """
    access_token, user_id, _, _ = load_facebook_auth()
    query_base = os.path.basename(query_file).replace('.json', '')

    ## issue query
    extra_auth_data = [load_facebook_auth(auth_file=f)[:2] for f in extra_auth_files]
    results = query_facebook_audience(access_token, user_id, query_file, extra_auth_data=extra_auth_data, response_file=response_file)

    ## clean up JSON cols
    json_cols = filter(lambda x: type(results.loc[:, x].iloc[0]) is dict, results.columns)
    for c in json_cols:
        results.loc[:, c] = results.loc[:, c].apply(json.dumps)

    ## write to file
    out_file = os.path.join(out_dir, '%s.tsv'%(query_base))
    results.to_csv(out_file, sep='\t', index=False)


from .abstract_model import AbstractModel
import numpy as np
import scipy as sp
from warnings import warn

class CoxModel(AbstractModel):

    def __init__(self, event_time, censoring_time, design):
        """

        Parameters
        ----------
        event_time : numpy array
            The lowest values indicate the earliest events. float('inf')
            indicates right-censoring.
        censoring_time : numpy array
            float('inf') indicates uncensored observations.
        """

        if np.any(event_time[:-1] > event_time[1:]):
            raise ValueError(
                "The observations need to be sorted so that the event times are "
                "in the increasing order, from the earliest to last events."
            )

        if np.any(censoring_time[:-1] < censoring_time[1:]):
            raise ValueError(
                "The observations need to be sorted so that the censoring times "
                "are in the decreasing order, from uncensored, last censored, "
                "to the earliest censored."
            )

        n_event = len(event_time) - np.sum(np.isinf(event_time))
        risk_set_start_index, risk_set_end_index = \
            self._find_risk_set_index(
                event_time[:n_event],
                np.flip(censoring_time[n_event:])
            )
        n_appearance = CoxModel.count_risk_set_appearance(
            len(event_time), risk_set_start_index, risk_set_end_index
        )
        if not np.all(n_appearance >= 1):
            raise ValueError(
                "Some individuals never appear in the risk set. They have to be"
                "removed before using the CoxModel class.")

        self.n_event = n_event
        self.event_time = event_time
        self.censoring_time = censoring_time
        self.n_appearance_in_risk_set = n_appearance
        self.risk_set_start_index = risk_set_start_index
        self.risk_set_end_index = risk_set_end_index
        self.design = design
        self.name = 'cox'

    @staticmethod
    def preprocess_data(event_time, censoring_time, X):
        event_time, censoring_time, X = \
            CoxModel._permute_observations_by_event_and_censoring_time(
                event_time, censoring_time, X
            )
        event_time, censoring_time, X = \
            CoxModel._drop_uninformative_observations(
                event_time, censoring_time, X
            )
        return event_time, censoring_time, X

    @staticmethod
    def _permute_observations_by_event_and_censoring_time(
            event_time, censoring_time, X):
        """
        Permute the observations so that they are ordered from the earliest
        to the last to experience events, followed by the last censored to the
        earliest censored.

        Params
        ------
        event_time : numpy array
            The lowest values indicate the earliest events. float('inf')
            indicates right-censoring.
        X : numpy array or scipy sparse matrix
        """
        if not np.all(np.equal(
                event_time == float("inf"),
                censoring_time < float('inf')
            )):
            raise ValueError(
                "Either event or censoring time must be infinity for each "
                "observation."
            )

        is_sorted = (
            np.all(event_time[:-1] <= event_time[1:])
            and np.all(censoring_time[:-1] >= censoring_time[1:])
        )
        if is_sorted:
            return event_time, censoring_time, X

        warn(
            "The observations and design matrix will be sorted so that the event "
            "times are in the ascending order and censoring times in the descending order."
        )

        n_event = np.sum(event_time < float('inf'))
        event_rank = CoxModel.np_rank_by_value(event_time)
        censoring_rank = CoxModel.np_rank_by_value(censoring_time)
        sort_ind = np.concatenate((
            np.argsort(event_rank)[:n_event],
            np.argsort(- censoring_rank)[n_event:]
        ))
        assert len(np.unique(sort_ind)) == len(sort_ind)

        event_time = event_time[sort_ind]
        censoring_time = censoring_time[sort_ind]
        if sp.sparse.issparse(X):
            X = X.tocsr()[sort_ind, :]
        else:
            X = X[sort_ind, :]

        return event_time, censoring_time, X

    @staticmethod
    def _drop_uninformative_observations(event_time, censoring_time, X):

        finite_event_time = event_time[event_time < float('inf')]
        finite_censoring_time = censoring_time[censoring_time < float('inf')]

        # Exclude those censored before the first event.
        is_uninformative = (censoring_time < np.min(event_time))

        if np.any(is_uninformative):
            warn(
                "Some observations do not contribute to the likelihood, so "
                "they are being removed."
            )
            is_informative = np.logical_not(is_uninformative)
            event_time = event_time[is_informative]
            censoring_time = censoring_time[is_informative]
            X = X[is_informative, :]

        return event_time, censoring_time, X

    @staticmethod
    def np_rank_by_value(arr):
        sort_arguments = np.argsort(arr)
        rank = np.arange(len(arr))[np.argsort(sort_arguments)]
        return rank.astype('float')

    @staticmethod
    def count_risk_set_appearance(n_obs, start_index, end_index):
        """ This function assumes that the observations are already sorted in
        the way required by the class. """

        # The calculation can be done more efficiently.
        n_appearance = np.zeros(n_obs, dtype=np.int)
        for i in range(len(start_index)):
            if start_index[i] <= end_index[i]:
                n_appearance[start_index[i]:(end_index[i] + 1)] += 1
        return n_appearance

    def _find_risk_set_index(self, event_time, censoring_time):
        """ The parameters are assumed to have 'inf' removed and in the ascending order. """

        n_event = len(event_time)
        start_index = np.zeros(n_event, dtype=np.int)
        for i in range(1, n_event):
            if event_time[i - 1] == event_time[i]:
                start_index[i] = start_index[i - 1]
            else:
                start_index[i] = i

        n_censored = np.array([
            np.searchsorted(censoring_time, t) for t in event_time
        ], dtype=np.int) # Tied censoring time is considered to be in the risk set.
        end_index = len(event_time) + len(censoring_time) - 1 - n_censored

        return start_index, end_index

    def compute_loglik_and_gradient(self, beta, loglik_only=False):

        grad = None # defalt return value

        log_rel_hazard, rel_hazard, hazard_sum_over_risk_set \
            = self._compute_relative_hazard(beta)
        if np.any(hazard_sum_over_risk_set == 0.):
            loglik = - float('inf')
            return loglik, grad

        loglik = np.sum(
            log_rel_hazard[:self.n_event] - np.log(hazard_sum_over_risk_set)
        )

        if not loglik_only:
            hazard_matrix = self._HazardMultinomialProbMatrix(
                rel_hazard, hazard_sum_over_risk_set,
                self.risk_set_start_index, self.risk_set_end_index, self.n_appearance_in_risk_set
            )
            v = np.zeros(self.design.shape[0])
            v[:self.n_event] = 1
            v -= hazard_matrix.sum_over_events()
            grad = self.design.Tdot(v)

        return loglik, grad

    def _compute_relative_hazard(self, beta):

        log_rel_hazard = self.design.dot(beta)
        log_rel_hazard = CoxModel._shift_log_hazard(log_rel_hazard)

        rel_hazard = np.exp(log_rel_hazard)

        hazard_sum_over_risk_set = self._sum_over_start_end(
            rel_hazard, self.risk_set_start_index, self.risk_set_end_index
        )

        return log_rel_hazard, rel_hazard, hazard_sum_over_risk_set

    @staticmethod
    def _sum_over_start_end(arr, start_index, end_index):
        """
        Returns
        -------
        numpy array whose k-th element equals
            np.sum(arr[start_index[k]:(1 + end_index[k])])
        """
        sum_from_right = \
            np.cumsum(arr[start_index[-1]:])[end_index - start_index[-1]]
        sum_from_left = np.concatenate((
            CoxModel.np_reverse_cumsum(arr[:start_index[-1]]), [0]
        ))
        total_sum = sum_from_right + sum_from_left
        return total_sum

    @staticmethod
    def np_reverse_cumsum(arr):
        return np.cumsum(arr[::-1])[::-1]

    @staticmethod
    def _shift_log_hazard(log_hazard_rate, log_offset=0):
        """
        Shift the values so that the max value equals 'log_offset' to
        prevent numerical under / over-flow before taking exponential.
        """
        log_hazard_rate += log_offset - np.max(log_hazard_rate)
        return log_hazard_rate

    def compute_hessian(self, beta):
        raise NotImplementedError()

    def get_hessian_matvec_operator(self, beta):

        _, rel_hazard, hazard_sum_over_risk_set \
            = self._compute_relative_hazard(beta)
        if np.any(hazard_sum_over_risk_set == 0.):
            raise ValueError(
                'Hessian operator cannot be computed likely due to an '
                'unreasonable value of regression coefficients. This could '
                'be caused by the likelihood and prior both being too weak '
                'or by a poor initialization of the Markov chain.'
            )
        W = self._HazardMultinomialProbMatrix(
            rel_hazard, hazard_sum_over_risk_set,
            self.risk_set_start_index, self.risk_set_end_index, self.n_appearance_in_risk_set
        )
        def hessian_op(beta):
            X_beta = self.design.dot(beta)
            result_vec = - self.design.Tdot(
                W.sum_over_events() * X_beta - W.Tdot(W.dot(X_beta))
            )
            return result_vec

        return hessian_op

    @staticmethod
    def simulate_outcome(X, beta, censoring_frac=.9, seed=None):
        """
        Simulate an outcome from a constant baseline hazard model i.e. the
        survival time is exponential.
        """
        if seed is not None:
            np.random.seed(seed)

        log_hazard_rate = X.dot(beta)
        log_hazard_rate = CoxModel._shift_log_hazard(log_hazard_rate)
        hazard_rate = np.exp(log_hazard_rate)
        event_time = np.random.exponential(scale=hazard_rate ** -1)

        scale = CoxModel._solve_for_exp_scale(
            np.quantile(event_time, 1 - censoring_frac), 1 - censoring_frac
        )
        censoring_time = np.random.exponential(
            scale=scale * np.ones(len(hazard_rate))
        )
        censoring_time[event_time < censoring_time] = float("inf")
        event_time[event_time >= censoring_time] = float('inf')

        return event_time, censoring_time

    @staticmethod
    def _solve_for_exp_scale(t, prob):
        """
        Computes the scale of an exponential random variable Z such that
            P(Z < t) == prob
        """
        return - t / np.log(1 - prob)

    class _HazardMultinomialProbMatrix():
        """
        Defines operations by a matrix whose each row represents the conditional
        probabilities of the event happening to the individuals in the risk set.
        """

        def __init__(self, rel_hazard, hazard_sum_over_risk_set,
                     risk_set_start_index, risk_set_end_index, n_appearance_in_risk_set):
            self.rel_hazard = rel_hazard
            self.hazard_sum_over_risk_set = hazard_sum_over_risk_set
            self.risk_set_start_index = risk_set_start_index
            self.risk_set_end_index = risk_set_end_index
            self.n_appearance_in_risk_set = n_appearance_in_risk_set
            self.n_event = len(hazard_sum_over_risk_set)

        def sum_over_events(self):
            """
            Returns the same value as the row sum of the explicitly computed
            the matrix (e.g. via the 'compute_matrix' method) but do it more
            efficiently.
            """
            normalizer_cumsum = np.cumsum(self.hazard_sum_over_risk_set ** -1)
            row_sum = normalizer_cumsum[self.n_appearance_in_risk_set - 1] \
                      * self.rel_hazard
            return row_sum

        def dot(self, v):
            return self.hazard_sum_over_risk_set ** - 1 * CoxModel._sum_over_start_end(
                self.rel_hazard * v, self.risk_set_start_index, self.risk_set_end_index
            )

        def Tdot(self, v):
            partial_inner_prod = np.cumsum(self.hazard_sum_over_risk_set ** -1 * v)
            return self.rel_hazard \
                   * partial_inner_prod[self.n_appearance_in_risk_set - 1]

        def compute_matrix(self):
            multinomial_prob = np.outer(
                self.hazard_sum_over_risk_set ** -1,
                self.rel_hazard
            )
            multinomial_prob = np.triu(multinomial_prob)
            for i in range(1, multinomial_prob.shape[0] + 1):
                if (self.risk_set_end_index[-i] + 1) >= len(self.rel_hazard):
                    break
                multinomial_prob[-i, (self.risk_set_end_index[-i] + 1):] = 0

            return multinomial_prob


# -*- encoding: utf-8 -*-
# @Time    :   2020/12/4
# @Author  :   Xiaolei Wang
# @email   :   wxl1999@foxmail.com

# UPDATE
# @Time   : 2020/1/3, 2021/1/4
# @Author : Xiaolei Wang, Yuanhang Zhou
# @email  : wxl1999@foxmail.com, sdzyh002@gmail.com

r"""
KBRD
====
References:
    Chen, Qibin, et al. `"Towards Knowledge-Based Recommender Dialog System."`_ in EMNLP 2019.

.. _`"Towards Knowledge-Based Recommender Dialog System."`:
   https://www.aclweb.org/anthology/D19-1189/

"""

import torch
import torch.nn.functional as F
from loguru import logger
from torch import nn
from torch_geometric.nn import RGCNConv

from crslab.model.base import BaseModel
from crslab.model.utils.functions import edge_to_pyg_format
from crslab.model.utils.modules.attention import SelfAttentionBatch
from crslab.model.utils.modules.transformer import TransformerDecoder, TransformerEncoder

class KBRDModel(BaseModel):
    """

    Attributes:
        vocab_size: A integer indicating the vocabulary size.
        pad_token_idx: A integer indicating the id of padding token.
        start_token_idx: A integer indicating the id of start token.
        end_token_idx: A integer indicating the id of end token.
        token_emb_dim: A integer indicating the dimension of token embedding layer.
        pretrain_embedding: A string indicating the path of pretrained embedding.
        n_entity: A integer indicating the number of entities.
        n_relation: A integer indicating the number of relation in KG.
        num_bases: A integer indicating the number of bases.
        kg_emb_dim: A integer indicating the dimension of kg embedding.
        user_emb_dim: A integer indicating the dimension of user embedding.
        n_heads: A integer indicating the number of heads.
        n_layers: A integer indicating the number of layer.
        ffn_size: A integer indicating the size of ffn hidden.
        dropout: A float indicating the dropout rate.
        attention_dropout: A integer indicating the dropout rate of attention layer.
        relu_dropout: A integer indicating the dropout rate of relu layer.
        learn_positional_embeddings: A boolean indicating if we learn the positional embedding.
        embeddings_scale: A boolean indicating if we use the embeddings scale.
        reduction: A boolean indicating if we use the reduction.
        n_positions: A integer indicating the number of position.
        longest_label: A integer indicating the longest length for response generation.
        user_proj_dim: A integer indicating dim to project for user embedding.

    """

    def __init__(self, opt, device, vocab, side_data):
        """

        Args:
            opt (dict): A dictionary record the hyper parameters.
            device (torch.device): A variable indicating which device to place the data and model.
            vocab (dict): A dictionary record the vocabulary information.
            side_data (dict): A dictionary record the side data.

        """
        self.device = device
        self.gpu = opt.get("gpu", [-1])
        # vocab
        self.pad_token_idx = vocab['pad']
        self.start_token_idx = vocab['start']
        self.end_token_idx = vocab['end']
        self.vocab_size = vocab['vocab_size']
        self.token_emb_dim = opt.get('token_emb_dim', 300)
        self.pretrain_embedding = side_data.get('embedding', None)
        # kg
        self.n_entity = vocab['n_entity']
        entity_kg = side_data['entity_kg']
        self.n_relation = entity_kg['n_relation']
        self.edge_idx, self.edge_type = edge_to_pyg_format(entity_kg['edge'], 'RGCN')
        self.edge_idx = self.edge_idx.to(device)
        self.edge_type = self.edge_type.to(device)
        self.num_bases = opt.get('num_bases', 8)
        self.kg_emb_dim = opt.get('kg_emb_dim', 300)
        self.user_emb_dim = self.kg_emb_dim
        # transformer
        self.n_heads = opt.get('n_heads', 2)
        self.n_layers = opt.get('n_layers', 2)
        self.ffn_size = opt.get('ffn_size', 300)
        self.dropout = opt.get('dropout', 0.1)
        self.attention_dropout = opt.get('attention_dropout', 0.0)
        self.relu_dropout = opt.get('relu_dropout', 0.1)
        self.embeddings_scale = opt.get('embedding_scale', True)
        self.learn_positional_embeddings = opt.get('learn_positional_embeddings', False)
        self.reduction = opt.get('reduction', False)
        self.n_positions = opt.get('n_positions', 1024)
        self.longest_label = opt.get('longest_label', 1)
        self.user_proj_dim = opt.get('user_proj_dim', 512)

        super(KBRDModel, self).__init__(opt, device)

    def build_model(self, *args, **kwargs):
        self._build_embedding()
        self._build_kg_layer()
        self._build_recommendation_layer()
        self._build_conversation_layer()

    def _build_embedding(self):
        if self.pretrain_embedding is not None:
            self.token_embedding = nn.Embedding.from_pretrained(
                torch.as_tensor(self.pretrain_embedding, dtype=torch.float), freeze=False,
                padding_idx=self.pad_token_idx)
        else:
            self.token_embedding = nn.Embedding(self.vocab_size, self.token_emb_dim, self.pad_token_idx)
            nn.init.normal_(self.token_embedding.weight, mean=0, std=self.kg_emb_dim ** -0.5)
            nn.init.constant_(self.token_embedding.weight[self.pad_token_idx], 0)
        logger.debug('[Build embedding]')

    def _build_kg_layer(self):
        self.kg_encoder = RGCNConv(self.n_entity, self.kg_emb_dim, self.n_relation, num_bases=self.num_bases)
        self.kg_attn = SelfAttentionBatch(self.kg_emb_dim, self.kg_emb_dim)
        logger.debug('[Build kg layer]')

    def _build_recommendation_layer(self):
        self.rec_bias = nn.Linear(self.kg_emb_dim, self.n_entity)
        self.rec_loss = nn.CrossEntropyLoss()
        logger.debug('[Build recommendation layer]')

    def _build_conversation_layer(self):
        self.register_buffer('START', torch.tensor([self.start_token_idx], dtype=torch.long))
        self.dialog_encoder = TransformerEncoder(
            self.n_heads,
            self.n_layers,
            self.token_emb_dim,
            self.ffn_size,
            self.vocab_size,
            self.token_embedding,
            self.dropout,
            self.attention_dropout,
            self.relu_dropout,
            self.pad_token_idx,
            self.learn_positional_embeddings,
            self.embeddings_scale,
            self.reduction,
            self.n_positions
        )
        self.decoder = TransformerDecoder(
            self.n_heads,
            self.n_layers,
            self.token_emb_dim,
            self.ffn_size,
            self.vocab_size,
            self.token_embedding,
            self.dropout,
            self.attention_dropout,
            self.relu_dropout,
            self.embeddings_scale,
            self.learn_positional_embeddings,
            self.pad_token_idx,
            self.n_positions
        )
        self.user_proj_1 = nn.Linear(self.user_emb_dim, self.user_proj_dim)
        self.user_proj_2 = nn.Linear(self.user_proj_dim, self.vocab_size)
        self.conv_loss = nn.CrossEntropyLoss(ignore_index=self.pad_token_idx)
        logger.debug('[Build conversation layer]')

    def encode_user(self, entity_lists, kg_embedding):
        user_repr_list = []
        for entity_list in entity_lists:
            if entity_list is None:
                user_repr_list.append(torch.zeros(self.user_emb_dim, device=self.device))
                continue
            user_repr = kg_embedding[entity_list]
            user_repr = self.kg_attn(user_repr)
            user_repr_list.append(user_repr)
        return torch.stack(user_repr_list, dim=0)  # (bs, dim)

    def recommend(self, batch, mode):
        context_entities, item = batch['context_entities'], batch['item']
        kg_embedding = self.kg_encoder(None, self.edge_idx, self.edge_type)
        user_embedding = self.encode_user(context_entities, kg_embedding)
        scores = F.linear(user_embedding, kg_embedding, self.rec_bias.bias)
        loss = self.rec_loss(scores, item)
        return loss, scores

    def _starts(self, batch_size):
        """Return bsz start tokens."""
        return self.START.detach().expand(batch_size, 1)

    def decode_forced(self, encoder_states, user_embedding, resp):
        bsz = resp.size(0)
        seqlen = resp.size(1)
        inputs = resp.narrow(1, 0, seqlen - 1)
        inputs = torch.cat([self._starts(bsz), inputs], 1)
        latent, _ = self.decoder(inputs, encoder_states)
        token_logits = F.linear(latent, self.token_embedding.weight)
        user_logits = self.user_proj_2(torch.relu(self.user_proj_1(user_embedding))).unsqueeze(1)
        sum_logits = token_logits + user_logits
        _, preds = sum_logits.max(dim=-1)
        return sum_logits, preds

    def decode_greedy(self, encoder_states, user_embedding):

        bsz = encoder_states[0].shape[0]
        xs = self._starts(bsz)
        incr_state = None
        logits = []
        for i in range(self.longest_label):
            scores, incr_state = self.decoder(xs, encoder_states, incr_state)  # incr_state is always None
            scores = scores[:, -1:, :]
            token_logits = F.linear(scores, self.token_embedding.weight)
            user_logits = self.user_proj_2(torch.relu(self.user_proj_1(user_embedding))).unsqueeze(1)
            sum_logits = token_logits + user_logits
            probs, preds = sum_logits.max(dim=-1)
            logits.append(scores)
            xs = torch.cat([xs, preds], dim=1)
            # check if everyone has generated an end token
            all_finished = ((xs == self.end_token_idx).sum(dim=1) > 0).sum().item() == bsz
            if all_finished:
                break
        logits = torch.cat(logits, 1)
        return logits, xs

    def decode_beam_search(self, encoder_states, user_embedding, beam=4):
        bsz = encoder_states[0].shape[0]
        xs = self._starts(bsz).reshape(1, bsz, -1)  # (batch_size, _)
        sequences = [[[list(), list(), 1.0]]] * bsz
        for i in range(self.longest_label):
            # at beginning there is 1 candidate, when i!=0 there are 4 candidates
            if i != 0:
                xs = []
                for d in range(len(sequences[0])):
                    for j in range(bsz):
                        text = sequences[j][d][0]
                        xs.append(text)
                xs = torch.stack(xs).reshape(beam, bsz, -1)  # (beam, batch_size, _)

            with torch.no_grad():
                if i == 1:
                    user_embedding = user_embedding.repeat(beam, 1)
                    encoder_states = (encoder_states[0].repeat(beam, 1, 1),
                                      encoder_states[1].repeat(beam, 1, 1))

                scores, _ = self.decoder(xs.reshape(len(sequences[0]) * bsz, -1), encoder_states)
                scores = scores[:, -1:, :]
                token_logits = F.linear(scores, self.token_embedding.weight)
                user_logits = self.user_proj_2(torch.relu(self.user_proj_1(user_embedding))).unsqueeze(1)
                sum_logits = token_logits + user_logits

            logits = sum_logits.reshape(len(sequences[0]), bsz, 1, -1)
            scores = scores.reshape(len(sequences[0]), bsz, 1, -1)
            logits = torch.nn.functional.softmax(logits)  # turn into probabilities,in case of negative numbers
            probs, preds = logits.topk(beam, dim=-1)
            # (candeidate, bs, 1 , beam) during first loop, candidate=1, otherwise candidate=beam

            for j in range(bsz):
                all_candidates = []
                for n in range(len(sequences[j])):
                    for k in range(beam):
                        prob = sequences[j][n][2]
                        score = sequences[j][n][1]
                        if score == []:
                            score_tmp = scores[n][j][0].unsqueeze(0)
                        else:
                            score_tmp = torch.cat((score, scores[n][j][0].unsqueeze(0)), dim=0)
                        seq_tmp = torch.cat((xs[n][j].reshape(-1), preds[n][j][0][k].reshape(-1)))
                        candidate = [seq_tmp, score_tmp, prob * probs[n][j][0][k]]
                        all_candidates.append(candidate)
                ordered = sorted(all_candidates, key=lambda tup: tup[2], reverse=True)
                sequences[j] = ordered[:beam]

            # check if everyone has generated an end token
            all_finished = ((xs == self.end_token_idx).sum(dim=1) > 0).sum().item() == bsz
            if all_finished:
                break
        logits = torch.stack([seq[0][1] for seq in sequences])
        xs = torch.stack([seq[0][0] for seq in sequences])
        return logits, xs

    def converse(self, batch, mode):
        context_tokens, context_entities, response = batch['context_tokens'], batch['context_entities'], batch[
            'response']
        kg_embedding = self.kg_encoder(None, self.edge_idx, self.edge_type)
        user_embedding = self.encode_user(context_entities, kg_embedding)
        encoder_state = self.dialog_encoder(context_tokens)
        if mode != 'test':
            self.longest_label = max(self.longest_label, response.shape[1])
            logits, preds = self.decode_forced(encoder_state, user_embedding, response)
            logits = logits.view(-1, logits.shape[-1])
            labels = response.view(-1)
            return self.conv_loss(logits, labels), preds
        else:
            _, preds = self.decode_greedy(encoder_state, user_embedding)
            return preds

    def forward(self, batch, mode, stage):
        if len(self.gpu) >= 2:
            self.edge_idx = self.edge_idx.cuda(torch.cuda.current_device())
            self.edge_type = self.edge_type.cuda(torch.cuda.current_device())
        if stage == "conv":
            return self.converse(batch, mode)
        if stage == "rec":
            return self.recommend(batch, mode)

    def freeze_parameters(self):
        freeze_models = [self.kg_encoder, self.kg_attn, self.rec_bias]
        for model in freeze_models:
            for p in model.parameters():
                p.requires_grad = False


class Solution:
    ''' Given an array nums of n integers, are there elements
        a, b, c in nums such that a + b + c = 0? Find all
        unique triplets in the array which gives the sum of zero.

        Note:
        The solution set must not contain duplicate triplets.
    '''
    def threeSum(self, nums: List[int]) -> List[List[int]]:

        n = len(nums)
        if n < 3:
            return []
        if set(nums) == set((0,)):
            return [[0,0,0]]
        nmin, nmax = min(nums), max(nums)

        dnums = dict.fromkeys(nums, 0)

        res = {}
        pairs = {}
        for i in range(n-1):
            a = nums[i]
            for j in range(i+1, n):
                b = nums[j]
                s = a+b
                if s > nmax or s < nmin: continue
                if -s not in dnums: continue
                if s not in pairs: pairs[s] = []
                pairs[s].append((i,j))

        if not pairs:
            return []
        res = {}

        for i, num in enumerate(nums):
            #if not nmin <= num <= nmax: continue
            target = -num
            if target in pairs:
                for ii,jj in pairs[target]:
                     if i not in (ii,jj):
                        key = tuple(sorted([nums[ii], nums[jj], num]))
                        res[key] = True

        return res.keys()


# -*- coding: utf-8 -*-
"""
Created on Mon Aug 17 15:38:04 2020

@author: USER
"""

mathscore = int(input("what is your math score?:"))
englishscore = int(input("what is your  english score?:"))

if mathscore >= 0 and mathscore <=100 and englishscore >= 0 and englishscore <=100:
    if mathscore >=90 and englishscore >=90:
        print("you will have a prize")
    elif mathscore <60 and englishscore <60:
        print("you will be punish")
    elif  mathscore  or englishscore <60:
        print("再加油")
else:
    print("that's wrong")


"""Code for TCLR method."""

from os.path import isfile

import torch
import torch.nn as nn
import torchvision.models.video as models

from slowfast.models import head_helper
from slowfast.models.r2plus1d import video_resnet

class TCLR(nn.Module):
    """TCLR"""

    def __init__(self, cfg):
        """
        The `__init__` method of any subclass should also contain these
            arguments.

        Args:
            cfg (CfgNode): model building configs, details are in the
                comments of the config file.
        """
        super(TCLR, self).__init__()
        self.num_pathways = 1
        self._construct_network(cfg)

    def _construct_network(self, cfg):
        """
        TCLR network.

        Args:
            cfg (CfgNode): model building configs, details are in the
                comments of the config file.
        """

        # define the encoder
        pretrained = cfg.MODEL.PRETRAINED
        self.encoder = video_resnet.__dict__[cfg.MODEL.ARCH](pretrained=pretrained)
        self.encoder.layer4[0].conv1[0] = nn.Conv3d(256, 512, kernel_size=(3, 3, 3),\
                                    stride=(1, 2, 2), padding=(2, 1, 1),dilation = (2,1,1), bias=False)
        self.encoder.layer4[0].downsample[0] = nn.Conv3d(256, 512,\
                            kernel_size = (1, 1, 1), stride = (1, 2, 2), bias=False)

        self.init_weights_from_checkpoint(cfg.MODEL.CKPT)

        # add K = 2 heads (noun and verb prediction)
        # temporary hardcoding
        # this needs (8, 7, 7) pooling instead of (4, 7, 7) due to the change in the last conv layer
        pool_size=[
            [8, 7, 7]
        ]

        # temporary hardcoding
        self.head = head_helper.ResNetBasicHead(
            dim_in=[512],
            num_classes=cfg.MODEL.NUM_CLASSES,
            pool_size=pool_size,
            dropout_rate=cfg.MODEL.DROPOUT_RATE,
        )

    def forward(self, x):

        for pathway in range(self.num_pathways):
            x[pathway] = self.encoder(x[pathway])

        x = self.head(x)
        return x

    def init_weights_from_checkpoint(self, checkpoint_file):
        """Inits weights from given checkpoint."""
        ckpt = torch.load(checkpoint_file, map_location="cpu")
        csd = ckpt["state_dict"]

        csd_items = csd.items()
        csd_subset = dict()
        for layer_name, weights in csd_items:
            if 'module.1.' in layer_name:
                continue
            elif '1.' == layer_name[:2]:
                continue
            if 'module.0.' in layer_name:
                layer_name = layer_name.replace('module.0.','')
            if 'module.' in layer_name:
                layer_name = layer_name.replace('module.','')
            elif '0.' == layer_name[:2]:
                layer_name = layer_name[2:]
            if 'fc' in layer_name:
                continue
            csd_subset[layer_name] = weights

        msg = self.encoder.load_state_dict(csd_subset, strict=False)

        print(":::::::::::::::::::::: Loaded pretrained checkpoint from ::::::::::::::::::::::")
        print(f"Path:\t {checkpoint_file}")
        print(f"Message:\t {msg}")

    def freeze_fn(self, freeze_mode):

        if freeze_mode == 'bn_parameters':
            print("Freezing all BN layers\' parameters.")
            for m in self.modules():
                if isinstance(m, nn.BatchNorm3d):
                    # shutdown parameters update in frozen mode
                    m.weight.requires_grad_(False)
                    m.bias.requires_grad_(False)
        elif freeze_mode == 'bn_statistics':
            print("Freezing all BN layers\' statistics.")
            for m in self.modules():
                if isinstance(m, nn.BatchNorm3d):
                    # shutdown running statistics update in frozen mode
                    m.eval()

if __name__ == "__main__":
    from tools.run_net import parse_args, load_config

    # load cfg
    args = parse_args()
    args.cfg_file = "../../../configs/EPIC-KITCHENS/TCLR/tclr_32x112x112_R18_K400_LR0.0025.yaml"
    cfg = load_config(args)

    # load model
    model = TCLR(cfg)

    # test with sample inputs
    x = torch.randn(1, 3, 32, 112, 112)
    y = model([x])

    assert y[0].shape == (1, 97)
    assert y[1].shape == (1, 300)


# encoding: utf-8
"""

"""
__author__ = 'Rhys Evans'
__date__ = '01 Jan 2022'
__copyright__ = 'Copyright 2018 United Kingdom Research and Innovation'
__license__ = 'BSD - see LICENSE file in top-level package directory'
__contact__ = 'rhys.r.evans@stfc.ac.uk'

from setuptools import setup, find_namespace_packages

with open("README.md") as readme_file:
    _long_description = readme_file.read()

setup(
    name='stac_vocab_api',
    description='stac-vocab-api',
    author='Richard Smith',
    url='https://github.com/cedadev/stac-vocab-api/',
    long_description=_long_description,
    long_description_content_type='text/markdown',
    license='BSD - See asset_extractor/LICENSE file for details',
    packages=find_namespace_packages(),
    python_requires='>=3.5',
    package_data={
        'stac_vocab_api': [
            'LICENSE'
        ]
    },
    install_requires=[
        'attrs',
        'fastapi',
    ],
    extras_require={
        'server': ["uvicorn[standard]>=0.12.0,<0.14.0"],
        'dev': [
            'pytest',
            'requests'
        ]
    },
    entry_points={
    }
)


import csv
import json

fileWriteDir = "tinkersConstructMaterials.csv"

fieldNames = [
    "material",
    "level",
    "speed",
    "damage",
    "modifier",
    "durability",
    "traits",
    "part"
]

handlesFile = open("tinkersHandles.json")
headFile = open("tinkersHead.json")
extrasFile = open("tinkersExtras.json")

handles = json.load(handlesFile)
head = json.load(headFile)
extras = json.load(extrasFile)

data = {}

dataPos = 0

for i in extras:
    data[dataPos] = ({k.lower():v for k, v in i.items()})
    data[dataPos]["part"] = "extra"
    dataPos += 1

for i in head:
    data[dataPos] = ({k.lower():v for k, v in i.items()})
    data[dataPos]["part"] = "head"
    dataPos += 1

for i in handles:
    data[dataPos] = ({k.lower():v for k, v in i.items()})
    data[dataPos]["part"] = "handles"
    dataPos += 1

handlesFile.close()
headFile.close()
extrasFile.close()

# csv write
with open(fileWriteDir, 'w', newline = '', encoding = "utf-8") as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames = fieldNames)
    writer.writeheader()
    for i in range(len(data)):
        writer.writerow(data[i])


import sys
input = sys.stdin.readline

s = input().strip()

def flip_string(s):
    start = s[0]
    cnt0, cnt1 = 0, 0 # 전부 0으로 바꾸는 경우 & 전부 1로 바꾸는 경우

    if s[0] == '1': # 전부 0으로 바꾸는 경우 시작부터 +1
        cnt0 += 1
    else:
        cnt1 += 1

    for i in range(len(s)-1): # 두 번째 원소부터 확인
        if s[i] != s[i+1]: # 바뀌는 지점
            if s[i+1] == '1': # 0에서 1로 바뀐다
                cnt0 += 1 # 최소 1 번은 더 뒤집어야 함
            else:
                cnt1 += 1

    return min(cnt0, cnt1)
print(flip_string(s))


import torch
model = torch.hub.load('pytorch/vision:v0.10.0', 'alexnet', pretrained=True)
model.eval()

import urllib
url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg")
try: urllib.URLopener().retrieve(url, filename)
except: urllib.request.urlretrieve(url, filename)

from PIL import Image
from torchvision import transforms
input_image = Image.open(filename)
preprocess = transforms.Compose([
    transforms.Resize(256),
    transforms.CenterCrop(224),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
input_tensor = preprocess(input_image)
input_batch = input_tensor.unsqueeze(0)

with torch.no_grad():
    output = model(input_batch)

print(output[0])

probabilities = torch.nn.functional.softmax(output[0], dim=0)
print(probabilities)

with open("imagenet_classes.txt", "r") as f:
    categories = [s.strip() for s in f.readlines()]
# Show top categories per image
top5_prob, top5_catid = torch.topk(probabilities, 5)
for i in range(top5_prob.size(0)):
    print(categories[top5_catid[i]], top5_prob[i].item())


# Make matplotlib static. Use notebook instead of inline to make interactive
get_ipython().run_line_magic('matplotlib', 'inline')

# Import required libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Load part of the dataset to have a look
df = pd.read_csv('kickstarter-projects/ks-projects-201801.csv', nrows=10)

# Let's have a look
df.head()

# We see that there are two date/time columns, we'll tell pandas to parse them when loading the full file.
df = pd.read_csv('kickstarter-projects/ks-projects-201801.csv',
                 parse_dates=['deadline', 'launched'],
                 encoding = "ISO-8859-1")

# Get some general info on the dataset.
# Int is for integer, float for floating point (number with decimal), object for string (text) or mixed types.
df.info()

# Describe is the basic summary stats function for numerical values.
df.describe()

stats_cols = ['backers', 'usd_pledged_real', 'usd_goal_real']
df[stats_cols].describe()

df.columns

df.main_category.unique()

df.state.unique()

df.groupby('main_category')['ID'].count()

df.groupby('state')['ID'].count()

# It would be nicer if those states were capitalized. We can easily do that
df['state'] = df['state'].str.capitalize()
df.groupby('state')['ID'].count()

# We'll also rename some of the columns so that the output is cleaner.
df.columns = ['ID', 'name', 'category', 'Main category', 'currency', 'deadline',
              'goal', 'launched', 'pledged', 'State', 'Backers', 'country',
              'usd pledged', 'Pledged (USD)', 'Goal (USD)']

# Let's add a column that compute the funding percentage
df['Funding %'] = df['pledged'] / df['goal']

stats_cols = ['Backers', 'Pledged (USD)', 'Goal (USD)', 'Funding %']
desc_stats = df[df.State.isin(['Successful', 'Failed'])].groupby('State')[stats_cols].describe()
desc_stats

desc_stats.transpose()

desc_stats.transpose().unstack(level=0)

# This here is what we want!
desc_stats = desc_stats.transpose().unstack(level=0).transpose()
desc_stats

# We still need to rename the columns
desc_stats.columns = ['Count', 'Mean', 'Std. Dev.', 'Min.', '25th Pct.', 'Median', '75th Pct.', 'Max']
desc_stats

# We can export that to Excel
desc_stats.to_excel('DescStats_v1.xlsx')

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('DescStats_v2.xlsx', engine='xlsxwriter')
desc_stats.to_excel(writer, sheet_name='Sheet1')

# Get the xlsxwriter objects from the dataframe writer object.
workbook  = writer.book
worksheet = writer.sheets['Sheet1']

# Add some cell formats.
format1 = workbook.add_format({'num_format': '#,##0.00'})
format2 = workbook.add_format({'num_format': '#,##0'})

# Set the column width.
worksheet.set_column('B:B', 18, None)

# Set the column format.
worksheet.set_column('D:D', None, format1)
worksheet.set_column('F:I', None, format1)
worksheet.set_column('C:C', None, format2)

# Set the column width and format.
worksheet.set_column('E:E', 12, format1)
worksheet.set_column('J:J', 14, format1)

# Close the Pandas Excel writer and output the Excel file.
writer.save()

# First, create new columns with the year of each date columns
df['launched_year'] = df['launched'].dt.year
df['deadline_year'] = df['deadline'].dt.year

# Next, compute the duration of the campain, in weeks
df['duration'] = np.round((df['deadline'] - df['launched']).dt.days / 7)

df['duration'].describe()

pd.crosstab(df.launched_year, df.State)

# We can safely drop all events with a 1970 start date.
df = df[df.launched_year != 1970]

pd.crosstab(df.launched_year, df.State)

# Say we only want to compare fails and success, we can create a separate view of the dataset that
# contains only those states
df_result = df[df.State.isin(['Failed', 'Successful'])]
pd.crosstab(df_result.launched_year, df_result.State)

# Let's plot this instead
pd.crosstab(df_result.launched_year, df_result.State).plot()

# Ok, but maybe a bar plot would be better.
pd.crosstab(df_result.launched_year, df_result.State).plot.bar()

# Some additional imports - usually you would put these at the top of the notebook.
from matplotlib.ticker import FuncFormatter

# First change, let's capture the axis and set colors and hatches
# For the list of xkcd colors see https://xkcd.com/color/rgb/
ax = pd.crosstab(df_result.launched_year, df_result.State).plot.bar(
    color=['xkcd:dark gray', 'xkcd:light blue'])

# Set the label formatter of the y-axis to have thousand commas.
ax.yaxis.set_major_formatter(FuncFormatter(lambda x, p: format(int(x), ',')))

# Rotate the year labels
ax.xaxis.set_tick_params(rotation=0)

# Add some labels
ax.set_xlabel('Year', fontsize=13)
ax.set_ylabel('Number of projects', fontsize=13)
# Add a title
ax.set_title('Number of failed and successful projects per year', fontsize=14)

# Set the location of the legend
ax.legend(loc='upper left')

# Tell matplotlib to make it look sharp
plt.tight_layout()

# Export to pdf
plt.savefig('BarPlot_States.pdf')


import sublime
import sublime_plugin

class ScrollToBofCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        # self.view.run_command('move', {'by': 'lines', 'forward': False})
        # 移动到指定位置，使用下面的方法，先使用text_point方法定位位置，在使用sel().clear()清除当前选区
        # 接着使用sel().add(sublime.Region(pt))增加当前点到选区，最后显示选区完成移动操作。
        pt = self.view.text_point(2, 0)
        self.view.sel().clear()
        self.view.sel().add(sublime.Region(pt))
        self.view.show(pt)


"""A simple wrapper to call sendmail-like binary."""
# =============================================================================
# CONTENTS
# -----------------------------------------------------------------------------
# phlsys_sendmail
#
# Public Classes:
#   Sendmail
#    .set_default_binary
#    .set_default_params_from_type
#    .send
#
# -----------------------------------------------------------------------------
# (this contents block is generated, edits will be lost)
# =============================================================================

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import phlsys_subprocess

class Sendmail():

    _default_binary = 'sendmail'
    _default_params = ['-t']

    @classmethod
    def set_default_binary(cls, binary):
        cls._default_binary = binary

    @classmethod
    def set_default_params_from_type(cls, sendmail_type):
        if "sendmail" == sendmail_type:
            cls._default_params = ["-t"]
        elif "catchmail" == sendmail_type:
            cls._default_params = []
        else:
            raise TypeError(str(sendmail_type) + " is not a type of sendmail")

    def __init__(self, binary=None, params=None):
        """Simply copy the supplied parameters and store in the object.

        :binary: the binary to execute, 'sendmail' if None

        Note that other binaries that are sendmail-compatabile, like
        'catchmail' can be used here instead.

        """
        self._binary = binary if binary is not None else self._default_binary
        self._params = params if params is not None else self._default_params

    # def call(*args, stdin=None): <-- supported in Python 3
    def send(self, stdin):
        result = phlsys_subprocess.run(
            self._binary, *self._params, stdin=stdin)
        return result.stdout

# -----------------------------------------------------------------------------
# Copyright (C) 2013-2014 Bloomberg Finance L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ------------------------------ END-OF-FILE ----------------------------------


import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from n_pnd import *

n_two = 25
N = [n_two, n_two] # number of linked pendulums
SLOW_MOTION = 1 # slow motion factor in animation
dt = 0.001 # infinitesimal time increment in seconds
T = 35 # length of time to be simulated
L = 50.0
G = 9.8/L # effective gravity
coef = setup_coef(N)

# initial conditions
theta0 = []
omega0 = []
for i in range(len(N)):
    theta0.append(np.tile(2.0, N[i])) # counterclockwise angle relative to the vertical for each rod
    omega0.append(np.tile(0.0, N[i])) # counterclockwise angular velocity for each rod
theta0[1] += 1.0e-15

print("INITIAL THETA")
print(theta0[0])
print(theta0[1])

coef = setup_coef(N)

fig, ax = plt.subplots()
time_text = ax.text(-0.9*max(N), 0.9*max(N), "t=0")
data = []
init_data = [np.copy(theta0), np.copy(omega0)]
for i in range(len(N)):
    data.append(evolve_pnd(init_data[0][i], init_data[1][i], T, dt, G, coef))
lines = [ax.plot(data[i][0][0], data[i][1][0])[0] for i in range(len(data))]
draw = lines + [time_text]
nframes = int(len(data[0][0])*dt*SLOW_MOTION/0.02-1)
def animate(i):
    for j in range(len(lines)):
        lines[j].set_xdata(data[j][0][int(i*0.02/dt/SLOW_MOTION)])
        lines[j].set_ydata(data[j][1][int(i*0.02/dt/SLOW_MOTION)])
    time_text.set_text("t="+str(int(i*20)/SLOW_MOTION/1000.0))
    return draw
ani = animation.FuncAnimation(fig, animate, frames=nframes, interval=20, save_count=nframes)
plt.xlim([-1.1, 1.1])
plt.ylim([-1.1, 1.1])

if len(N) >= 2:
    fig2, ax2 = plt.subplots()
    print("Calculating Lyapunov")
    print(theta0)
    data_t_0 = [data[0][2], data[0][3]]
    data_t_1 = [data[1][2], data[1][3]]
    lyap = lyapunov(data_t_0, data_t_1, dt)
    print(lyap[1].shape)
    print(lyap[2])
    ax2.plot(lyap[0], lyap[1])
    fig3, ax3 = plt.subplots()
    ax3.plot(np.append(np.tile(0, int(T/dt)-lyap[0].size), lyap[0]), np.log(np.abs(np.asarray(data[0][2]).T[0] - np.asarray(data[1][2]).T[0])))

plt.show()


"""
About Writer

The About Writer is a Python script that adds an "about" statement to the specified files.
It is designed to help add metadata information, such as author and timestamp, to source code files.
The script supports various file formats and can recursively process files in a specified folder.

Author: ZION

Usage:
    python about_writer.py [-h] [-x EXTS] [-v] path name

Arguments:
    path: The path to the file or folder.
    name: The name to be set as the author of the file.

Options:
    -x EXTS: Only modify files with the given extension(s). Separate multiple extensions with a comma (,).
    -v: Show verbose output.

Supported File Formats:
    - Python (.py)
    - Java (.java)
    - C (.c)
    - PHP (.php)
    - HTML (.html)
    - JSON (.json)
    - CSS (.css)
    - JavaScript (.js)
    - Perl (.pl)
    - Shell Script (.sh)
    - C++ (.cpp)
    - C# (.cs)
    - R (.r)
    - Text (.txt)
"""

import subprocess
import pathlib
import os
import argparse
import re

INCLUDED_EXTS = {
    "*.py": ("\"\"\"", "\"\"\""),
    "*.java": ("/*", "*/"),
    "*.c": ("/*", "*/"),
    "*.php": ("/*", "*/"),
    "*.html": ("<!--", "-->"),
    "*.json": ("/*", "*/"),
    "*.css": ("/*", "*/"),
    "*.js": ("/*", "*/"),
    "*.pl": ("=pod", "=cut"),
    "*.sh": (": '", "'"),
    "*.cpp": ("/*", "*/"),
    "*.cs": ("/*", "*/"),
    "*.r": ("#", ""),
    "*.txt": ("", ""),
}

EXCLUDED_EXTS = ["exe", "class", "pickle"]
FILES_LIST = []

def get_folder(foldername, exts=["*"], verbose=False):
    """
    Recursively gets all the files in the specified folder with the given extensions.

    :param foldername: The folder name
    :type foldername: str
    :param exts: The extensions of files to include, defaults to ["*"]
    :type exts: list, optional
    :param verbose: Flag to print verbose output, defaults to False
    :type verbose: bool, optional
    """
    for i in exts:
        for child in pathlib.Path(foldername).rglob(i):
            if child not in FILES_LIST and child.is_file():
                FILES_LIST.append(child)
                print(f"[*] Appended {child} to files_list") if verbose else print("")
            elif child.is_dir():
                get_folder(child, exts, verbose)

def perm_edit(name, verbose=False):
    """
    Applies the about statement to all the files in the files_list.

    :param name: The name to be set as the author of the file
    :type name: str
    :param verbose: Flag to print verbose output, defaults to False
    :type verbose: bool, optional
    """
    for child in FILES_LIST:
        if child.is_file():
            print(str(child).center(75, "="))
            try:
                edit_file(child, name, verbose)
            except Exception:
                ext = "*." + str(child).suffix
                print(f"[!] Couldn't write to \"{child}\" because file format \"{ext}\" is not supported") if verbose else print("")

def edit_file(filepath, name, verbose=False):
    """
    Edits the specified file to add the about statement.

    :param filepath: The path of the file to edit
    :type filepath: str
    :param name: The name to be set as the author of the file
    :type name: str
    :param verbose: Flag to print verbose output, defaults to False
    :type verbose: bool, optional
    """
    if os.sep in str(filepath):
        filepath = str(filepath).replace(os.sep, os.altsep)
    filename = str(filepath).split(os.altsep)[-1].upper()
    with open(filepath, "r") as file:
        content = file.read()
    print(f"[*] Reading content of \"{filepath}\"") if verbose else print("")
    if filename not in content:
        get_date_time_info = subprocess.run(["dir", "/Tc", filepath], shell=True, capture_output=True, text=True).stdout
        date = re.search(r"\r\n(\d+\W\w+\W\d+)", get_date_time_info)
        time = re.search(r"(\d+\W\d+\W+\w+)", get_date_time_info)
        ext = "*." + str(filepath).split(os.altsep)[-1].split(".")[-1]
        if ext not in INCLUDED_EXTS.keys():
            print(f"[!] Couldn't write to \"{filepath}\" because file format \"{ext}\" is not supported")
        else:
            for i in INCLUDED_EXTS:
                if i == ext:
                    print(f"[*] Writing about statement to \"{filepath}\"") if verbose else print("")
                    if "<DOCTYPE html>".lower() not in content.lower() and ext != "*.r":
                        text = f"{INCLUDED_EXTS[i][0]}\n{filename} Source Code\n{name}, {date[0].strip()} @ {time[0].strip()}.\n{INCLUDED_EXTS[i][-1]}\n\n\n"
                    elif ext == "*.r":
                        text = f"{INCLUDED_EXTS['*.r'][0]}\t{filename} Source Code\n{INCLUDED_EXTS['*.r'][0]}\t{name}, {date[0].strip()} @ {time[0].strip()}.\n\n\n"
                    else:
                        text = f"{INCLUDED_EXTS['*.html'][0]}\n{filename} Source Code\n{name}, {date[0].strip()} @ {time[0].strip()}.\n{INCLUDED_EXTS['*.html'][-1]}\n\n\n"
                    with open(filepath, "r", encoding="utf-8") as file:
                        if ext == "*.php":
                            if "<DOCTYPE html>".lower() not in content.lower():
                                file.seek(5)
                        content = file.read()
                    with open(filepath, "w", encoding="utf-8") as file:
                        if ext == "*.php":
                            if "<DOCTYPE html>".lower() not in content.lower():
                                text = "<?php\n" + text
                        content = text + content
                        file.write(content)
                    print(f"[*] Finished writing about statement to \"{filepath}\"") if verbose else print("")
    else:
        print(f"[!] About statement has already been written to \"{filepath}\"")

def main():
    parser = argparse.ArgumentParser(description="About Writer")
    parser.add_argument("path", help="Path to the file or folder")
    parser.add_argument("name", help="Value to be set as the author of the file")
    parser.add_argument("-x", "--exts", help="Only modify files with the given extension(s). Separate multiple extensions with comma (,)")
    parser.add_argument("-v", "--verbose", action="store_true", help="Show verbose output")
    args = parser.parse_args()

    if os.path.isdir(args.path):
        exts = ["*"] if not args.exts else args.exts.split(",")
        get_folder(foldername=args.path, exts=exts, verbose=args.verbose)
        perm_edit(name=args.name, verbose=args.verbose)
    elif os.path.isfile(args.path):
        edit_file(filepath=args.path, name=args.name, verbose=args.verbose)

if __name__ == "__main__":
    main()