#!/bin/python3

import math
import os
import random
import re
import sys
from itertools import combinations

# Complete the alternate function below.
def alternate(s):

    # 1. get the combinations, s=#unique chars - 2
    # 2. iterrate each combinations
    # 3. deleting characters from string of each iterrate item
    # 4. check the resultant length == 1
    # 5. if 4 is met, count the length of the new string
    # 6. register the longest length so far
    # 7. return the longest length

    longest = 0
    if len(s) > 1 and len(set(s))>1: # if s is like 'a' or 'aaaa', skip below process
        n = len(set(s))-2 # the letters to be removed

        for item in combinations(set(s), n):
            reduced_s = (s+'.')[:-1] #create an independent copy

            for letter in item:
                reduced_s = reduced_s.replace(letter, '')

            if (len(set(reduced_s[::2]))==1) and (len(set(reduced_s[1::2]))==1):
                longest = max(longest, len(reduced_s))

    return longest

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    l = int(input().strip())

    s = input()

    result = alternate(s)

    fptr.write(str(result) + '\n')

    fptr.close()


# Nevan Parsley NRP211 11274655
# Dr. Jeffery Long

import math as m
import numpy as np
import pandas_datareader as pdr
import datetime
import matplotlib.pyplot as mp

userInput = input('Input stock idea you would like to view: ').upper()

print('The YTD closing data as of', datetime.datetime.today(),'is:')

stock_data = pdr.get_data_yahoo(userInput,
                          start=datetime.datetime(datetime.datetime.today().year, 1, 1),
                          end=datetime.datetime.today())

# print(stock_data) # shows the format of
stock = np.array(stock_data)
stk = stock[0:, -1].flatten()
norm_stk = []
norm_stk = np.convolve(stk, [1, -1])

## stock price YTD
mp.plot(stk)
mp.title('YTD value')
mp.xlabel(userInput)
mp.show()
#stock change YTD
mp.plot(norm_stk[1:-1])
mp.title('YTD change per day')
mp.xlabel(userInput)
mp.show()
print("Max increase in close,", max(norm_stk[1:]), "Max Decrease in close,", min(norm_stk[:-1]))
print('Average change in closing price', sum(norm_stk[1:-1])/(len(norm_stk)-2))
if sum(norm_stk[1:-1]) > 0:
    print("The stock value has INCREASED", sum(norm_stk[1:-1]), "so far this year")
else:
    print("The stock value has DECREASED", sum(norm_stk[1:-1]), "so far this year")


#!/usr/bin/python

'''
Written by Matt Fowler (mattf@juniper.net).
Python script to find orgs with non-default idle or session timers.

'''

import requests
import json

api_token = ''
api_url_g01 = 'https://api.mist.com/api/v1'
api_url_g02 = 'https://api.gc1.mist.com/api/v1'
api_url_g03 = 'https://api.ac2.mist.com/api/v1'
api_url_g04 = 'https://api.gc2.mist.com/api/v1'
api_url_eu01 = 'https://api.eu.mist.com/api/v1'

def get_self(session, headers):
	url = '{}/self'.format(api_url)

	result = session.get(url, headers=headers)

	if result.status_code != 200:
		print('Failed to POST')
		print('URL: {}'.format(url))
		print('Response: {} ({})'.format(result.text, result.status_code))

		return (False, None, result)

	result = json.loads(result.text)
	return result

def get_org(session, headers, org_id):
	url = '{}/orgs/{}'.format(api_url, org_id)

	result = session.get(url, headers=headers)

	if result.status_code != 200:
		print('Failed to POST')
		print('URL: {}'.format(url))
		print('Response: {} ({})'.format(result.text, result.status_code))

		return (False, None, result)

	result = json.loads(result.text)
	return result

def get_org_setting(session, headers, org_id):
	url = '{}/orgs/{}/setting'.format(api_url, org_id)

	result = session.get(url, headers=headers)

	if result.status_code != 200:
		print('Failed to POST')
		print('URL: {}'.format(url))
		print('Response: {} ({})'.format(result.text, result.status_code))

		return (False, None, result)

	result = json.loads(result.text)
	return result

session = requests.Session()

# Main
if __name__ == '__main__':

	print ("""
	This script will check timeouts on all Orgs attached to your account.
	""")
	ans = 'invalid'
	while ans == 'invalid':
		ans=input("""
		Which cloud is this for?
		1.Global 01
		2.Global 02
		3.Global 03
		4.Global 04
		5.Europe 01
		""")
		if ans=="1":
			api_url = api_url_g01
		elif ans=="2":
			api_url = api_url_g02
		elif ans=="3":
			api_url = api_url_g03
		elif ans=="4":
			api_url = api_url_g04
		elif ans=="5":
			api_url = api_url_eu01
		elif ans !="":
			print("\n Not Valid Choice Try again")
			ans = 'invalid'

	api_token = input("""
		Please enter your API Token:
		""")

	headers = {
	'Content-Type': 'application/json; charset=utf-8', 'Accept-Encoding': 'gzip, deflate',
	'Authorization': 'Token ' + api_token
	}

	result = get_self(session, headers)
	lowest_idle = 99999999
	lowest_session = 99999999
	non_default_list = []
	for i in result['privileges']:
		if i['scope'] == 'org':
			org_id = i['org_id']
			org_config = get_org(session, headers, org_id)
			org_name = org_config['name']
			session_expiry = org_config['session_expiry']
			org_setting = get_org_setting(session, headers, org_id)
			if 'ui_idle_timeout' in org_setting:
				idle_timeout = org_setting['ui_idle_timeout']
			else:
				idle_timeout = 0
			print('Checked {}'.format(org_name))
			if idle_timeout != 0 or session_expiry != 1440:
				non_default_list.append('{} ({}) Idle: {} Session: {}'.format(org_name, org_id, idle_timeout, session_expiry))
				print('{}\nSession Expiry: {}\nIdle Timeout: {}\n\n'.format(org_name, session_expiry, idle_timeout))
				print('{} NOT STANDARD!! Please Check!\n\n'.format(org_name))
				if 0 < idle_timeout < lowest_idle:
					lowest_idle = idle_timeout
					lowest_idle_org = org_name
				if session_expiry < lowest_session:
					lowest_session = session_expiry
					lowest_session_org = org_name

	if non_default_list:
		print("""\n\n
		##########################################
		Here are the Orgs with one or more non-default timers:
		""")
		print(*non_default_list, sep='\n')
		print("""
		##########################################
		\n\n""")

	if lowest_idle == 99999999:
		print('No org has a non-default idle timeout')
	else:
		print('{} has the lowest idle timeout of {} minutes.'.format(lowest_idle_org, lowest_idle))

	if lowest_session >= 1440:
		print('No org has a session expiry below 1440 minutes.')
	else:
		print('{} has the lowest session expiry of {} minutes.'.format(lowest_session_org, lowest_session))


import csv
import base64
import tkinter as tk
from tkinter import ttk
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from urllib.request import urlopen

window = tk.Tk()
window.title("Resim Seçme Programı")
window.geometry('600x60')

pathLabel = ttk.Label(
    window, text="Lütfen stok bilgisi dosyasının yolunu giriniz: ")
pathLabel.grid(column=0, row=0, padx=(10, 10), pady=(2, 2))

pathEntry = ttk.Entry(window, width=50)
pathEntry.grid(column=1, row=0, padx=(10, 10), pady=(2, 2))
pathEntry.focus()

imageLists = []

def clicked():
    pathEntryText = pathEntry.get()
    window.destroy()
    i = 0
    options = Options()
    options.headless = True
    browser = webdriver.Chrome()
    browser.implicitly_wait(10)
    browser.get("https://www.google.com.tr/imghp?hl=tr&tab=wi&authuser=0&ogbl")
    with open(pathEntryText.replace('"', ''), encoding="utf8") as csv_file:

        resoruceFile = csv.reader(csv_file, delimiter=';')
        for row in resoruceFile:

            print(row[1])
            stockCode = row[0]
            productName = row[1]
            inputElement = browser.find_element_by_name("q")
            inputElement.send_keys(row[1])
            inputElement.submit()

            try:
                browser.find_element_by_xpath(
                    "//*[@id=\"islrg\"]/div[1]/div[1]/a[1]").click()
                img = browser.find_element_by_xpath(
                    "//*[@id=\"Sva75c\"]/div/div/div[3]/div[2]/c-wiz/div[1]/div[1]/div/div[2]/a/img").get_attribute("src")
                imageLists.append(img)

            except:
                pass

            newBrowser = webdriver.Chrome()
            newBrowser.implicitly_wait(10)
            src = newBrowser.get(imageLists[0])
            print(src)
            i += 1

            homeElement = browser.find_element_by_xpath(
                "//*[@id=\"sf\"]/div[1]/div[1]/c-wiz/div/a").click()
            browser.find_element_by_xpath(
                "//*[@id=\"gbw\"]/div/div/div[1]/div[2]/a").click()
            newBrowser.close()

    browser.close()

    imageWindow = tk.Tk()
    imageWindow.title("Resim Seçme Ekranı")
    imageWindow.geometry('1120x280')

    image_byt = urlopen(imageLists[0]).read()
    print(image_byt)
    image_b64 = base64.encodestring(image_byt)
    photo = tk.PhotoImage(data=image_b64)

    cv = tk.Canvas(bg='white')
    cv.pack(side='top', fill='both', expand='yes')
    cv.create_image(10, 10, image=photo, anchor='nw')
    cv.grid(column=0, row=1, padx=(10, 10), pady=(2, 2))

startButon = ttk.Button(window, text="XML Oluştur", command=clicked)
startButon.grid(column=1, row=2, padx=(10, 10), pady=(2, 2))

window.call('wm', 'attributes', '.', '-topmost', '1')
window.mainloop()


import os,csv,re,datetime,itertools
import numpy as np
import pandas as pd
import shapely
import uafgi.data
from uafgi.util import pdutil,functional,shputil

def _parse_daterange(srange):
    return tuple(datetime.datetime.strptime(x,'%d%b%Y') for x in srange.split('-'))

@functional.memoize
def read(map_wkt):
    """Reads annual terminus lines"""

    ddir = uafgi.data.join('measures-nsidc0642')
    terminiRE = re.compile(r'termini_(\d\d)(\d\d)_v01\.2\.shp')
    dfs = list()
    leaves = [list(), list()]    # Format changes between 2012/13 and 2014/15
    for leaf in os.listdir(ddir):
        match = terminiRE.match(leaf)
        if match is not None:
            y0 = 2000+int(match.group(1))
            y1 = 2000+int(match.group(2))
            leaves[0 if y0<2014 else 1].append((leaf,y0,y1))

    all_namecols = ['GlacName', 'GrnlndcNam', 'Name','Official_n', 'AltName', 'GrnlndcNam']
    for leaf,y0,y1 in sorted(leaves[0]):
        df = pd.DataFrame(shputil.read(os.path.join(ddir,leaf), wkt=map_wkt))
        df['year0'] = y0
        df['year1'] = y1
        namecols = [x for x in all_namecols if x in df.columns]
        df['allnames'] = list(zip(*[df[x] for x in (namecols)]))
        df['date'] = df['DateRange'].map(_parse_daterange)
        df = df.drop(['_shape0', 'DateRange'] + namecols, axis=1)
        dfs.append(df)

    # Different data format 2014 and beyond
    for leaf,y0,y1 in sorted(leaves[1]):
        df = pd.DataFrame(shputil.read(os.path.join(ddir,leaf), wkt=map_wkt))
        df['year0'] = y0
        df['year1'] = y1
        namecols = [x for x in all_namecols if x in df.columns]
        df['allnames'] = list(zip(*[df[x] for x in (namecols)]))
        df['date'] = df['DATE'].map(lambda x: datetime.datetime.strptime(x,'%Y-%m-%d'))
        df = df.drop(['_shape0', 'DATE'] + namecols, axis=1)
        dfs.append(df)

    df = pd.concat(dfs)
    df = df.reset_index(drop=True) \
        .rename(columns={'_shape': 'terminus'}) \
        .drop('Id', axis=1)

    return pdutil.ext_df(df, map_wkt,
        add_prefix='ns642_',
        keycols=['GlacierID', 'year1'])

def termini_by_glacier(ns642):
    """Collects rows from original ns642 DataFrame by GlacierID.
    Breaks the terminus lines apart into multiple points."""

    # Create column with value [(date, terminus), ...]
    df2 = pdutil.group_and_tuplelist(ns642.df, ['ns642_GlacierID'],
            [ ('ns642_date_termini', ['ns642_date', 'ns642_terminus']) ])

    xdf = ns642.replace(df=df2, keycols=['ns642_Glacier'])
    xdf.df['ns642_key'] = xdf.df['ns642_GlacierID']
    return xdf

#
#
#
#
#
#    dfg = ns642.df.groupby(by='ns642_GlacierID')
#
#    data = list()
#    for name, gr in dfg:
#        pointss = [list(ls.coords) for ls in gr['ns642_terminus']]
#        points = list(itertools.chain.from_iterable(pointss))    # Join to a single list
#        data.append([name, shapely.geometry.MultiPoint(points)])
#
#    df2 = pd.DataFrame(data=data, columns=['ns642_GlacierID', 'ns642_points'])
#    df2['ns642_key'] = df2['ns642_GlacierID']
#    xdf = ns642.replace(df=df2, keycols=['ns642_GlacierID'])
#    return xdf
#


from bs4 import BeautifulSoup as bs  # import for beautifulsoup\
from bs4 import SoupStrainer as strainer
import requests  # this is so i can use a link to get html output

url = 'https://en.wikipedia.org/wiki/Glossary_of_computer_science'
response = requests.get(url)

only_glossary = strainer(attrs={'class': 'glossary'})
soup = bs(response.content, 'html.parser', parse_only=only_glossary)  # turn html into soup

for dl in soup.find_all('dl'):
    for items in dl.find_all():
        if items.name == 'dt':
            print(f"- {items.text}\n")
        elif items.name == 'dd':
            print(f"> {items.text}\n")


import argparse
import csv
import datetime
import math
import os
import time
import warnings
from functools import partial

import numpy as np
from sklearn.metrics import classification_report, f1_score, make_scorer
from sklearn.model_selection import GridSearchCV, train_test_split, PredefinedSplit
from sklearn.utils import shuffle

import json

import torch
from torch._C import dtype
import torch.nn as nn
import torch.optim as optim

from podium.datasets import SingleBatchIterator
from podium.vectorizers import GloVe

import utils
from metrics import Metrics
from stopping_criteria import QueryCount, VarianceSurge
from acq_models.models import TorchModel, get_model
from acq_functions.samplers import get_AL_sampler
from acq_functions.random_sampler import RandomSampler
from acq_functions.uncertainty_sampler import LeastConfidentSampler

from al_config import STORAGE_PATH
from data import (TorchTM, SklearnTM)

warnings.warn = lambda *a, **kw: None

L = utils.logger('al_experiment')

parser = argparse.ArgumentParser()
parser.add_argument('--dataset-name', type=str, default='imdb',
                    help='Dataset name.')
parser.add_argument('--max-vocab-size', type=int, default=25_000,
                    help='Maximum vocab size.')
parser.add_argument('--acq-model', type=str, default='log_reg',
                    help='AL acqusition model.')
parser.add_argument('--num-epoch', type=int, default=20,
                    help='Number of epoch to train the model in each AL step.')
parser.add_argument('--embedding-dim', type=int, default=100,
                    help='Embedding dimensionality.')
parser.add_argument('--acq-fun', type=str, default='random',
                    help='AL acquisition function.')
parser.add_argument('--al-batch-size', type=int, default=10_000,
                    help='AL batch size.')
parser.add_argument('--warmstart-size', default=20,
                    help=("Can be float or integer. Float indicates percentage of training data "
						  "to use in the initial warmstart model. Use -1 for cold start (one example from each class)."))

# parser.add_argument('--grid-search-step', type=int, default=-1,
#                     help='Perform grid search CV for optimal parameters every n batches. Use -1 to disable.')
# parser.add_argument('--multilabel', type=bool, default=False,
#                   help='True for multilabel data, false otherwise.')
# parser.add_argument('--seed', type=int, default=42,
#                     help='Seed.')

parser.add_argument('--log-every', type=int, default=10,
                    help='Results are logged periodically.')

RESULT_PATH = STORAGE_PATH

'''
Main class that contains functions and variables needed for runnning
the Active Learning experiment.
'''

class AlExperiment():

    def __init__(self,
                 train_manager,            #object that wraps the training parameters and settings
                 dataset_name,             #dataset to test on
                 al_method,                #active learning sampling method used ('entropy', 'margin', 'qbc', 'bald')
                 warmstart_size,           #number of data points used for pretraining the first model
                 al_batch_size,            #number of data points given to annotators in each step
                 grid_search_step=-1,      #step used when optimizing the parameters using grid search
                 seeds=[42],               #random seeds used in each run, to get stochastic results
                 model_name='log_reg',     #ML model used in the experiment ('log_reg', 'svm', 'rnn')
                 model=None,               #ML model object
                 save_seeds=False):

        self.train_manager = train_manager
        self.dataset_name = dataset_name
        self.al_method = al_method
        self.warmstart_size = warmstart_size
        self.al_batch_size = al_batch_size
        self.seeds = seeds
        self.grid_search_step = grid_search_step
        self.model_name = model_name
        self.model = model
        self.info = None
        self.results = []
        self.save_seeds = save_seeds
        self.ml_metrics = Metrics()

    '''
    Runs one iteration of an Active Learning experiment.
    '''
    def run_single(self, seed=42, verbose=False, logiter=5):
        utils.set_seed_everywhere(seed)

        # Torch neural models needs to reset neurons' weights in each step in order to re-train.
        if isinstance(self.model, TorchModel):
            for layer in self.model.children():
                if hasattr(layer, 'reset_parameters'):
                    layer.reset_parameters()

        # Load the train and test data.
        X_train, y_train = self.train_manager.get_numpy_data('train')
        X_test, y_test = self.train_manager.get_numpy_data('test')
        train_size = self.train_manager.dataset_size('train')
        test_size = self.train_manager.dataset_size('test')

        # Get the sampler for this particular active-learning samplin strategy.
        sampler = get_AL_sampler(self.al_method)
        al_batch_size = self.check_percentage(self.al_batch_size, train_size)
        warmstart_size = self.check_percentage(self.warmstart_size, train_size)
        stopping_criterion = QueryCount

        # Load the model.
        model = self.model

        if verbose:
            L.debug(f'train_size: {train_size}, test_size: {test_size}')
            L.debug(f'al_method:{self.al_method}  warmstart_size:{warmstart_size} '
                    f'al_batch_size:{al_batch_size} seed:{seed} model:{self.model_name}')

        results = {}
        metrics_train = []
        metrics_test = []
        predictions_test = []

        # TODO: implement stratified sample for torch
        selected_inds = np.random.choice(np.arange(train_size), warmstart_size, replace=False).tolist()

        # initial sample
        # if warmstart_size == -1:
        #     # cold start - use one example from each class
        #     selected_inds = utils.stratified_sample(
        #         y_train, np.unique(y_train).size)
        # else:
        #     # use warmstart_size/class_count examples from each class
        #     selected_inds = utils.stratified_sample(y_train, warmstart_size)

        seed_batch = len(selected_inds)
        num_labeled = [seed_batch]
        stopping_criterion = stopping_criterion(train_size=train_size,
                                                batch_size=al_batch_size,
                                                seed_batch=seed_batch)
                                                #, X=X_train, y=y_train)
        sampler = sampler(X_train, y_train, seed)

        been = True
        while not stopping_criterion.is_over():
            curr_batch = stopping_criterion.current_batch
            n_train = seed_batch + \
                min(train_size - seed_batch, curr_batch * al_batch_size)

            if verbose:
                L.debug('Training model on %s/%s datapoints',
                        n_train, train_size)

            assert n_train == len(selected_inds)

            # Sort active_ind so that the end results matches that of uniform sampling.
            sorted(selected_inds)
            X_selected_batch = X_train[selected_inds]
            y_selected_batch = y_train[selected_inds]

            # Train the model with selected data points!
            model.al_step(selected_inds, self.train_manager)

            # TODO: transfer to al step
            metrics_train.append(
                self.ml_metrics.eval_metrics(
                    ys_true=y_selected_batch, hs=model.predict_numpy(X_selected_batch)))

            metrics_test.append(
                self.ml_metrics.eval_metrics(
                    ys_true=y_test, hs=model.predict_numpy(X_test)))

            if (curr_batch + 1) % logiter == 0 and verbose:
                L.debug(f'Sampler: {sampler.name}, metrics_train: {metrics_train[-1]}, metrics_test: {metrics_test[-1]}')

            # The data in next steps will be selected from the remainder of unlabeled data points.
            remaining = train_size - len(selected_inds)
            n_sample = min(al_batch_size, remaining)
            if n_sample == remaining:
                all_inds = np.arange(train_size)
                new_batch = np.setdiff1d(all_inds, selected_inds).tolist()
            elif n_sample > 0:
                # These inputs will be provided to various different samplers,
                # depending on their respective method signatures.
                select_args = dict(model=model,
                                sampler=sampler,
                                N=n_sample,
                                labeled=selected_inds,
                                X_test=X_test,
                                y_test=y_test,
                                verbose=verbose)
                #model = model.train()
                new_batch = sampler.select_batch(**select_args).tolist()
            else:
                new_batch = []

            selected_inds.extend(new_batch)
            num_labeled.append(len(selected_inds))

            if verbose:
                L.info('Requested: %d, Selected: %d' %
                        (n_sample, len(new_batch)))
            assert len(new_batch) == n_sample
            assert len(set(selected_inds)) == len(selected_inds)

            stopping_criterion.next_state(annotated_count=n_sample)

        # After the stopping criterion is reached, the active learning process stops and results are ready.
        stopping_criterion.reset()
        results = [{'metrics_train': m_train, 'metrics_test': m_test, 'labeled': labeled}
                   for m_train, m_test, labeled in zip(metrics_train, metrics_test, num_labeled)]

        # Make results readable and save them.
        result = dict(meta=dict(dataset=self.dataset_name,
                                sampler=self.al_method,
                                warmstart_size=warmstart_size,
                                batch_size=al_batch_size,
                                model=self.model_name,
                                grid=self.grid_search_step,
                                seed=seed),
                      results=results)

        if self.save_seeds:
            filepath = RESULT_PATH + \
                f'{self.dataset_name}.{self.al_method}.{self.model_name}.ws={warmstart_size}.bs={al_batch_size}.s={seed}.grid={self.grid_search_step}.{utils.time_string()}.json'
            utils.dump(result, filepath, overwrite=True, mode='json')

            if verbose:
                L.info('Results stored to %s', filepath)

        return result

    '''
    Run multiple AL experiments, once for each seed.
    '''
    def run(self, checkpoint_file=None, verbose=False, logiter=5):
        for seed in self.seeds:
            L.debug('Running experiment : %s' % self.info_string(seed))
            self.start_time()
            result = self.run_single(seed, verbose, logiter)
            self.results.append(result)
            self.end_time()
            L.debug('Finished experiment : %s in %s' %
                    (self.info_string(seed), self.get_duration()))

        if checkpoint_file is not None:
            self.write_to_csv(checkpoint_file)
        self.store_average()

    def check_percentage(self, sample, total_len):
        if sample < 1 and sample != -1:
            return int(sample*total_len)
        else:
            return int(sample)

    '''
    Store the average results of multiple runs (with multiple seeds),
    '''
    def store_average(self, metrics=[(lambda r: r['metrics_test'].aggregated['f1_micro'], 'f1_micro'),
                                     (lambda r: r['metrics_test'].aggregated['f1_macro'], 'f1_macro')]):
        seeds = []
        xs = [r['labeled'] for r in self.results[0]['results']]
        Ys = []
        for result in self.results:
            seeds.append(result['meta']['seed'])
            res = result['results']
            Y_met = [[] for _ in range(len(metrics))]
            for r in res:
                for j, metric in enumerate(metrics):
                    val = metric[0](r)
                    Y_met[j].append(val)
            Ys.append(Y_met)

        Ys = np.array(Ys).swapaxes(0, 1)

        results = dict(labeled=xs)
        for i, metric in enumerate(metrics):
            results[metric[1]] = Ys[i].mean(0)
            results[f'{metric[1]}_var'] = Ys[i].var(0)
            results[f'{metric[1]}_baseline'] = Ys[i][0][-1]

        result_avg = dict(meta=dict(dataset=self.dataset_name,
                                    sampler=self.al_method,
                                    warmstart_size=self.warmstart_size,
                                    batch_size=self.al_batch_size,
                                    model=self.model_name,
                                    grid=self.grid_search_step,
                                    seeds=seeds),
                          results=results)

        filepath = os.path.join(
                        RESULT_PATH,
                        f'avg.{self.dataset_name}.{self.al_method}'
                        f'.ws={self.warmstart_size}'
                        f'.bs={self.al_batch_size}'
                        f'.grid={self.grid_search_step}'
                        f'.{utils.time_string()}.json')
        utils.dump(result_avg, filepath, overwrite=True, mode='json')
        L.info('Average stored to %s', os.path.abspath(filepath))

    def info_string(self, seed):
        self.info = f'(%s, %d, %d, %s, %d)' % \
            (self.al_method, self.warmstart_size,
             self.al_batch_size, self.model_name, seed)
        return self.info

    def start_time(self):
        self.start = time.time()

    def end_time(self):
        self.end = time.time()
        self.duration = str(datetime.timedelta(
            seconds=math.floor(self.end-self.start)))

    def get_duration(self):
        try:
            return self.duration
        except:
            raise Exception(
                'start_time and end_time must be called respectively!')

    def write_to_csv(self, file):
        with open(file, 'a') as f:
            writer = csv.writer(f)
            writer.writerow((self.model_name, self.al_method,
                             self.warmstart_size, self.al_batch_size, len(self.seeds)))

'''
Perform the active learning experiment.

Receives train-validation-test data splits, dataset, and word vocabulary.
'''
def perform(splits, dataset, vocab):
     #splits, fields, vocab = utils.load_trec()
    splits[0].finalize_fields()

    SEED = 42
    utils.set_seed_everywhere(SEED)

    sets = tuple([split.batch() for split in splits])
    vectorizer = GloVe(dim=args.embedding_dim)

    """
    def device_tensor(data):
        return torch.tensor(data, dtype=torch.float).to(torch.device('cpu'))

    # Torch example.
    # ===========================================================
    model_name = 'rnn'
    padding_idx = vocab.get_padding_index()

    device = torch.device('cpu')
    emb_matrix = torch.tensor(vectorizer.load_vocab(vocab),
                              dtype=torch.float,
                              device=device)

    model_params = dict(
        embedding_dim=args.embedding_dim,
        hidden_dim=50,
        output_dim=6,
        pretrained_embeddings=emb_matrix,
        padding_idx=padding_idx,
        device=device
    )

    criterion = nn.CrossEntropyLoss()
    model = get_model(name=model_name, params=model_params, scheme=None)
    model = model.to('cpu')
    optimizer = optim.Adam(model.parameters(), lr=0.001)
    manager = TorchTM(splits, criterion, optimizer, args.num_epoch)
    # ===========================================================

    """
    # Sklearn example.
    # ===========================================================
    model_name = 'svm'
    model_params = {"probability" : True, "C": 100, "gamma": 0.001} #"probability" : True, "C": 100, "gamma": 0.001
    model = get_model(name=model_name, params=model_params, scheme=None)
    emb_matrix = np.array(vectorizer.load_vocab(vocab))
    manager = SklearnTM(splits, emb_matrix)
    # ===========================================================

    AlExperiment(train_manager=manager,
                 dataset_name=dataset,
                 al_method='entropy',
                 warmstart_size=50,
                 al_batch_size=50,
                 grid_search_step=-7,
                 seeds=list(range(5)),
                 model_name=model_name,
                 model=model).run(verbose=True)

if __name__ == '__main__':
    args = parser.parse_args()

    dataset = 'sst'
    splits, fields, vocab = utils.load_data(dataset, field_names=["label", "text"], validation=True)

    perform(splits, dataset, vocab)


import torch
from torch.utils.data import DataLoader, Subset
from sklearn.model_selection import train_test_split
import os.path
import cassavadataloader
import cassava_resnet

BATCH_SIZE = 2

def run(require_gpu=True):
    if not torch.cuda.is_available():
        print('No CUDA-enabled GPU detected.')
        if require_gpu:
            print('GPU required flag is set. Exiting.')
            exit()
        device = torch.device('cpu')
    else:
        device = torch.device('cuda:0')

    print(f'Using CUDA-enabled device: {torch.cuda.get_device_name(device)}')

    full_dataset_train = cassavadataloader.CassavaDataset(images_path=os.path.join('..', 'train_images'),
                                                          validation=False,
                                                          labels_manifest_path=os.path.join('..', 'train.csv'))
    full_dataset_eval = cassavadataloader.CassavaDataset(images_path=os.path.join('..', 'train_images'),
                                                          validation=True,
                                                          labels_manifest_path=os.path.join('..', 'train.csv'))

    train_indices, validation_indices = train_test_split(list(range(len(full_dataset_train))), test_size=.3)

    train_dataset = Subset(full_dataset_train, train_indices)
    validation_dataset = Subset(full_dataset_eval, validation_indices)
    train_eval_dataset = Subset(full_dataset_eval, train_indices[:1000])

    train_dataloader = DataLoader(train_dataset,
                                  batch_size=BATCH_SIZE,
                                  collate_fn=cassavadataloader.custom_collate_wrapper,
                                  pin_memory=True,
                                  shuffle=True)
    validation_dataloader = DataLoader(validation_dataset,
                                       batch_size=BATCH_SIZE,
                                       collate_fn=cassavadataloader.custom_collate_wrapper,
                                       pin_memory=True,
                                       shuffle=False)
    train_eval_dataloader = DataLoader(train_eval_dataset,
                                       batch_size=BATCH_SIZE,
                                       collate_fn=cassavadataloader.custom_collate_wrapper,
                                       pin_memory=True,
                                       shuffle=True)

    model = cassava_resnet.train_model(device, train_dataloader, validation_dataloader, train_eval_dataloader,
                                       model_output_directory=os.path.join('..', 'saved_models'),
                                       epochs=1, max_samples=1000, warm_start_path=None)

if __name__ == '__main__':
    run(require_gpu=False)


import pygame, sys
from dolfin import *
import matplotlib.pyplot as plt
from pygame.locals import *
from audio import *
from strike_drum import strike_drum

import dolfin_solver as dfs

# Point and Line class definitions
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class Line:
    def __init__(self, p1, p2):
        self.p1 = p1
        self.p2 = p2

    def getStartPoint(self):
        return (self.p1.x, self.p1.y)

    def getEndPoint(self):
        return (self.p2.x, self.p2.y)

# Verifies if 3 points are colinear
def onLine(p, q, r):
    if ( (q.x <= max(p.x, r.x)) and (q.x >= min(p.x, r.x)) and
           (q.y <= max(p.y, r.y)) and (q.y >= min(p.y, r.y))):
        return True
    return False

# Finds orientation of 3 points, clockwise, counterclockwise or collinear
def orientation(p, q, r):
    # to find the orientation of 3 points (p, q, r)
    # function returns the following values:
    # 0 : Collinear points
    # 1 : Clockwise points
    # 2 : Counterclockwise

    val = (float(q.y - p.y) * (r.x - q.x)) - (float(q.x - p.x) * (r.y - q.y))
    if (val > 0):

        # Clockwise orientation
        return 1
    elif (val < 0):

        # Counterclockwise orientation
        return 2
    else:

        # Collinear orientation
        return 0

# The main function that returns true if
# the line segment 'p1q1' and 'p2q2' intersect.
def doIntersect(line1, line2):
    # Find the 4 orientations required for
    # the general and special cases

    p1 = line1.p1
    q1 = line1.p2
    p2 = line2.p1
    q2 = line2.p2

    o1 = orientation(p1, q1, p2)
    o2 = orientation(p1, q1, q2)
    o3 = orientation(p2, q2, p1)
    o4 = orientation(p2, q2, q1)

    # General case
    if ((o1 != o2) and (o3 != o4)):
        return True

    # Special Cases

    # p1 , q1 and p2 are collinear and p2 lies on segment p1q1
    if ((o1 == 0) and onLine(p1, p2, q1)):
        return True

    # p1 , q1 and q2 are collinear and q2 lies on segment p1q1
    if ((o2 == 0) and onLine(p1, q2, q1)):
        return True

    # p2 , q2 and p1 are collinear and p1 lies on segment p2q2
    if ((o3 == 0) and onLine(p2, p1, q2)):
        return True

    # p2 , q2 and q1 are collinear and q1 lies on segment p2q2
    if ((o4 == 0) and onLine(p2, q1, q2)):
        return True

    # If none of the cases
    return False

# Simple method to draw a straight line after validation
def drawLine(surface, newLine):
    start = newLine.getStartPoint()
    end = newLine.getEndPoint()
    pygame.draw.line(surface, black, start, end)
    pygame.display.update()

# Return true if line does not intersect, false if it does
def validateLine(newLine, lineList):
    intersect = False

    if(len(lineList) == 0):
        return True
    else:
        for line in lineList:
            if (line == lineList[len(lineList) - 1]):
                return True
            intersect = doIntersect(line, newLine)
            if(intersect):
                return False

    return True

# Validation, called only when trying to exit program
def validateLastLine(newLine, lineList):
    if (len(lineList) == 0):
        return True
    else:
        tempList = [line for line in lineList]
        del tempList[0]
        for line in tempList:
            if (line == tempList[len(tempList) - 1]):
                return True
            intersect = doIntersect(line, newLine)
            if (intersect):
                return False

    return True

# Method that controls program flow
def continueShape(x, y):
    newPoint = Point(x, y)
    if (len(points) == 0):
        points.append(newPoint)
    elif (len(points) == 1):
        newLine = Line(points[len(points) - 1], newPoint)
        points.append(newPoint)
        lines.append(newLine)
        drawLine(grid, newLine)
    else:
        newLine = Line(points[len(points) - 1], newPoint)
        if (validateLine(newLine, lines)):
            points.append(newPoint)
            lines.append(newLine)
            drawLine(grid, newLine)

# Called at the end to finish the shape when user exits
def closeShape(x, y):
    newPoint = Point(x, y)
    if (len(points) == 0):
        points.append(newPoint)
    elif (len(points) == 1):
        newLine = Line(points[len(points) - 1], newPoint)
        points.append(newPoint)
        lines.append(newLine)
        drawLine(grid, newLine)
    else:
        newLine = Line(points[len(points) - 1], newPoint)
        if (validateLastLine(newLine, lines)):
            points.append(newPoint)
            lines.append(newLine)
            drawLine(grid, newLine)

# Returns correctly formatted output: List of (x,y) coordinates of all points
def output(pointList):
    output = [[float(point.x), (gridHeight - point.y)] for point in pointList]
    outputInt = [Point(int(coordinates[0]), int(coordinates[1])) for coordinates in output]
    if (orientation(outputInt[0], outputInt[1], outputInt[2]) == 2):
        return output
    else:
        return output[::-1]

# Color definitions
black = 0, 0, 0
white = 255, 255, 255
red = 255, 0, 0

# Define grid size
gridWidth, gridHeight = 1000, 800
gridSize = gridWidth, gridHeight

# Setting the grid
grid = pygame.display.set_mode(gridSize)

# Getting the Clock object
clock = pygame.time.Clock()

# Settomg a title to the grid
pygame.display.set_caption("Grid")

# Defining lists for all points and all lines
points = []
lines = []

shapeOut = []
impulsePosition = []

def programLoop():
    global shapeOut
    global impulsePosition
    fpsLimit = 60
    runMe = True
    while runMe:
        # Limit the framerate
        clock.tick(fpsLimit)

        # Clear the grid by filling all white
        if (len(points) == 0):
            grid.fill(white)

        # Event handler
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RETURN:
                    numOfPoints = len(points)
                    closeShape(points[0].x, points[0].y)
                    if (numOfPoints == len(points)):
                        continue
                    waiting = True
                    while (waiting):
                        event = pygame.event.wait()
                        if (event.type == MOUSEBUTTONDOWN):
                            x, y = pygame.mouse.get_pos()
                            waiting = False
                    impulsePosition = [float(x), float(gridHeight - y)]
                    shapeOut = output(points)
                    runMe = False
            if event.type == MOUSEBUTTONDOWN:
                x, y = pygame.mouse.get_pos()
                continueShape(x, y)
            if event.type == pygame.QUIT:
                numOfPoints = len(points)
                closeShape(points[0].x, points[0].y)
                if (numOfPoints == len(points)):
                    continue

                # Final output, must decide what to do with it
                output(points)
                runMe = False

        # Display everything
        pygame.display.flip()

programLoop()

# Quit the display
pygame.quit()

print(shapeOut)
print(impulsePosition)

testmesh = dfs.generate_mesh_from_coords(shapeOut, 50)
plot(testmesh)
plt.show()

eigenvals, v = dfs.eigenpair_solver(testmesh, 100)

qquit = False
while (not qquit):
    uinput = input("What eigenfunction would you like? (0-99)\na to animate, q to quit \n")

    if (uinput == "a"):
        strike_drum(impulsePosition, testmesh, v, eigenvals, 3)
    elif (uinput == "q"):
        qquit = True
    else:
        try:
            uinput = int(uinput)

            if (0 <= uinput <= 99):

                plot(v[uinput])

                t_eig_val = eigenvals[uinput]

                print("The Eigenvalue is : ", t_eig_val)

                freq = frequency(t_eig_val)
                print("The harmonic frequency is : ", freq)

                plt.title(str(round(freq, 2)) + "Hz")

                plt.show()

                play_sound(0.5, 44100, 3, freq)

            else:
                print("Bad input")

        except:
            print("Bad input")


import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots
class ExternalDisturbance:
    def __init__(self):
        self.time_prev = 0.0
        self.disturbance_history = {'time': [],
                                    'signal': []}
    def __call__(self, time):
        disturbance = self.ask_for_disturbance(time)
        if self.time_prev == time:
            pass
        else:
            self.disturbance_history['signal'].append(list(disturbance.flatten()))
            self.disturbance_history['time'].append(time)
        self.time_prev = time
        return disturbance

    def ask_for_disturbance(self):
        raise NotImplementedError("Method ask_for_disturbance() should be implemented in child class..")

    def plot_history(self):
        fig = make_subplots(rows=3, cols=1, x_title='Czas [s]',
                            subplot_titles=('Zakłócenie w osi x [N]', 'Zakłócenie w osi y [N]',
                                            'Zakłócenie w osi z [N]'))
        time = self.disturbance_history['time']
        data = np.array(self.disturbance_history['signal'])

        fig.add_trace(go.Scatter(x=time, y=data[:, 0]), row=1, col=1)
        fig.add_trace(go.Scatter(x=time, y=data[:, 1]), row=2, col=1)
        fig.add_trace(go.Scatter(x=time, y=data[:, 2]), row=3, col=1)
        fig.show()

class WindModel(ExternalDisturbance):
    def __init__(self, direction_vector=np.array([0.0, 1.0, 0.0]), strength=1.0):
        super().__init__()
        if isinstance(direction_vector, list):
            direction_vector = np.array(direction_vector)
        direction_vector = direction_vector.astype('float32')
        if np.linalg.norm(direction_vector) != 1.0:
            self.direction_vector = direction_vector / (np.linalg.norm(direction_vector) + 1e-15)
        else:
            self.direction_vector = direction_vector
        print("Wind direction:", self.direction_vector)
        self.strength = strength

    def ask_for_disturbance(self, time):
        wind_force = self.direction_vector * self.strength
        wind_force = wind_force.reshape((3, 1))
        return wind_force

class RandomAdditiveNoiseWind(WindModel):
    def __init__(self, direction_vector=np.array([0.0, 1.0, 0.0]), strength=1.0, scale=1.0):
        super().__init__(direction_vector=direction_vector, strength=strength)
        self.scale = scale
    def ask_for_disturbance(self, time):
        wind_force = self.strength * self.direction_vector + np.random.normal(loc=0.0, scale=self.scale, size=(3))
        wind_force = wind_force.reshape((3, 1))
        return wind_force

class RandomWalkWind(WindModel):
    def __init__(self, direction_vector=np.array([0.0, 1.0, 0.0]), strength=1.0, dir_vec_scale=0.1, strength_scale=0.1, weight=0.5):
        super().__init__(direction_vector=direction_vector, strength=strength)
        self.dir_vec_scale = dir_vec_scale
        self.strength_scale = strength_scale
        self.weight = weight

    def ask_for_disturbance(self, time):
        if self.time_prev == time:
            pass
        else:
            self.direction_vector = self.direction_vector * (1-self.weight) + self.weight * np.random.normal(loc=0.0, scale=self.dir_vec_scale, size=3)
            self.direction_vector = self.direction_vector / (np.linalg.norm(self.direction_vector) + 1e-15)
            self.strength = self.strength + np.random.normal(loc=0.0, scale=self.strength_scale, size=1)
        wind_force = self.strength * self.direction_vector
        wind_force = wind_force.reshape((3, 1))
        return wind_force
class SinusoidalWind(WindModel):
    def __init__(self, sin_f, fs, direction_vector=np.array([0.0, 1.0, 0.0]), max_strength=1.0):
        #doesnt work ATM
        super().__init__(direction_vector=direction_vector, strength=max_strength)
        self.fs = fs
        self.Ts = 1 / fs
        self.sin_f = sin_f
        self.sin_t = 1 / sin_f
    def ask_for_disturbance(self, time):
        wind_force = self.strength * np.sin(2 * np.pi * self.sin_f * time) * self.direction_vector
        wind_force = wind_force.reshape((3, 1))
        return wind_force

if __name__ == "__main__":
    wind = WindModel([0, 0, 1])
    print(wind.ask_for_disturbance())


import requests

def request_jd(keyword):
    url = "https://search.jd.com/Search"
    params = {
        "keyword": keyword
    }
    headers = {
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36"
    }
    response = requests.get(url=url, params=params, headers=headers)
    print(response.text)
      # 获取str类型的响应内容
    # response.content  # 获取bytes类型的响应内容
    # response.json()  # 获取json格式数据

if __name__=="__main__":
    request_jd("鼠标")


import pygame

from shake import WIDTH, HEIGHT, CELL_SIZE, NOT_BIG_FONT, Portal, \
    Wall, Game, BLOCK_SIZE, snake_color, bg_fill_color, \
    wall_color, portals_color

pygame.init()
pygame.display.set_caption('level editor')

single_portal_color = pygame.Color('aquamarine')

def draw_messages(surface):
    render_q = NOT_BIG_FONT.render('Press "q" to save level1',
                                   0, pygame.Color('green'))
    render_w = NOT_BIG_FONT.render('Press "w" to save level2',
                                   0, pygame.Color('green'))
    render_e = NOT_BIG_FONT.render('Press "e" to save level3',
                                   0, pygame.Color('green'))
    render_message1 = NOT_BIG_FONT.render('Press left mouse button',
                                          0, pygame.Color('gray55'))
    render_message2 = NOT_BIG_FONT.render('to draw walls',
                                          0, pygame.Color('gray55'))
    render_message3 = NOT_BIG_FONT.render('Press right mouse button',
                                          0, pygame.Color('red'))
    render_message4 = NOT_BIG_FONT.render('to erase walls',
                                          0, pygame.Color('red'))
    render_message5 = NOT_BIG_FONT.render('Press "d" keyboard button',
                                          0, pygame.Color('white'))
    render_message6 = NOT_BIG_FONT.render('to draw portals',
                                          0, pygame.Color('white'))
    render_message7 = NOT_BIG_FONT.render('Press "s" keyboard button',
                                          0, pygame.Color('orange'))
    render_message8 = NOT_BIG_FONT.render('to draw snake position',
                                          0, pygame.Color('orange'))
    render_message9 = NOT_BIG_FONT.render('Press space to erase all',
                                          0, pygame.Color('red'))

    surface.blit(render_q, (WIDTH + 10, 5))
    surface.blit(render_w, (WIDTH + 10, 30))
    surface.blit(render_e, (WIDTH + 10, 55))
    surface.blit(render_message1, (WIDTH + 10, 100))
    surface.blit(render_message2, (WIDTH + 10, 125))
    surface.blit(render_message3, (WIDTH + 10, 160))
    surface.blit(render_message4, (WIDTH + 10, 185))
    surface.blit(render_message5, (WIDTH + 10, 220))
    surface.blit(render_message6, (WIDTH + 10, 245))
    surface.blit(render_message7, (WIDTH + 10, 280))
    surface.blit(render_message8, (WIDTH + 10, 305))
    surface.blit(render_message9, (WIDTH + 10, 350))

def save_level(level_path, walls, portals, is_snake_add, snake_cords):
    """Function save walls, portals and snake cords to .txt file"""
    with open(level_path, "w") as file:
        for w in walls:
            print('w' + str(w), file=file)
        for p in portals:
            print('p' + str(p), file=file)
        if is_snake_add:
            print('s' + str(snake_cords), file=file)
        print(f'{level_path.split("/")[1]} was saved!')

def is_all_conditions(x, y, block, walls, portals_tmp, portals):
    """Function check that new block in game grid and not in walls, portals"""
    if block[0] < x < block[0] + CELL_SIZE \
            and block[1] < y < block[1] + CELL_SIZE \
            and block not in walls \
            and block not in portals_tmp \
            and block not in [(p[0], p[1]) for p in portals] \
            and block not in [(p[2], p[3]) for p in portals]:
        return True

def main():
    surface = pygame.display.set_mode((WIDTH + 300, HEIGHT))
    _wall = Wall(0, 0, wall_color)
    _portal = Portal(0, 0, 0, 0, portals_color, portals_color)
    cells = []
    walls = []
    portals = []
    portals_temp = []
    snake_cords = ()
    is_snake_add = False
    is_portal_add = False
    # adding all cells cords
    for row in range(int(HEIGHT / CELL_SIZE)):
        for column in range(int(WIDTH / CELL_SIZE)):
            cells.append((column * CELL_SIZE, row * CELL_SIZE))

    while True:
        game = Game()
        surface.fill(bg_fill_color)
        game.draw_bg(surface)
        # draw snake position
        if is_snake_add:
            pygame.draw.rect(surface, snake_color,
                             (snake_cords[0], snake_cords[1],
                              BLOCK_SIZE, BLOCK_SIZE))
        for wall in walls:
            pygame.draw.rect(surface, wall_color,
                             (wall[0], wall[1], BLOCK_SIZE, BLOCK_SIZE))
        for portal in portals:
            pygame.draw.rect(surface, portals_color,
                             (portal[0], portal[1], BLOCK_SIZE, BLOCK_SIZE))
            pygame.draw.rect(surface, portals_color,
                             (portal[2], portal[3], BLOCK_SIZE, BLOCK_SIZE))
        # draw single portal that don't have partner
        if is_portal_add:
            pygame.draw.rect(surface, single_portal_color,
                             (portals_temp[0][0], portals_temp[0][1],
                              BLOCK_SIZE, BLOCK_SIZE))
        # draw help text
        draw_messages(surface)

        pygame.display.flip()
        key = pygame.key.get_pressed()
        mouse = pygame.mouse.get_pressed()
        x, y = pygame.mouse.get_pos()
        for event in pygame.event.get():
            # left mouse button
            if mouse[0]:
                for cell in cells:
                    if is_all_conditions(x, y, cell, walls, portals_temp, portals):
                        walls.append((cell[0], cell[1]))
            # right mouse button
            if mouse[2]:
                for cell in cells:
                    if cell[0] < x < cell[0] + CELL_SIZE \
                            and cell[1] < y < cell[1] + CELL_SIZE:
                        if cell in walls:
                            walls.remove((cell[0], cell[1]))
                        for portal in portals:
                            if cell[0] in portal and cell[1] in portal:
                                portals.remove(portal)
                        if cell == snake_cords:
                            is_snake_add = False
                            snake_cords = ()
            if key[pygame.K_d]:
                for cell in cells:
                    if is_all_conditions(x, y, cell, walls, portals_temp, portals):
                        if is_portal_add:
                            portals_temp.append((cell[0], cell[1]))
                            portals.append((portals_temp[0][0], portals_temp[0][1],
                                            portals_temp[1][0], portals_temp[1][1]))
                            portals_temp.clear()
                            is_portal_add = False
                        else:
                            portals_temp.append((cell[0], cell[1]))
                            is_portal_add = True
            if key[pygame.K_s]:
                for cell in cells:
                    if is_all_conditions(x, y, cell, walls, portals_temp, portals):
                        snake_cords = (cell[0], cell[1])
                        is_snake_add = True
            if event.type == pygame.QUIT:
                exit()
            if key[pygame.K_SPACE]:
                walls.clear()
                portals.clear()
                portals_temp.clear()
                snake_cords = ()
                is_snake_add = False
                is_portal_add = False
            if key[pygame.K_q]:
                save_level('levels/level1.txt', walls, portals, is_snake_add, snake_cords)
            if key[pygame.K_w]:
                save_level('levels/level2.txt', walls, portals, is_snake_add, snake_cords)
            if key[pygame.K_e]:
                save_level('levels/level3.txt', walls, portals, is_snake_add, snake_cords)
        pygame.display.update()

if __name__ == '__main__':
    main()


from requests import get
from io import BytesIO
color="#252626"
from tkinter import BOTTOM, RAISED, RIGHT, Button, Label, Entry, Frame, LEFT, Tk, X
from PIL import Image
from time import sleep, perf_counter
from random import randint
from threading import Thread
from random import randint
from pathlib import Path
import os.path
from os import remove
from imghdr import what
import hashlib

class image_downloader:
    def __init__(self, master):
        self.master = master
        master.configure(bg=color)
        master.geometry('270x90+800+500')
        master.resizable(False, False)
        # Custom title bar so that its dark theme cause yes'nt
        master.overrideredirect(True)
        fake_title_bar = Frame(master, bg=color, relief=RAISED, bd=0.5)
        fake_title_bar.pack(expand=1, fill=X)
        fake_title_label = Label(fake_title_bar, text="\t          Sauce downloader", bg=color, fg="white")
        fake_title_label.pack(side=LEFT)
            #Binding the title bar
        def move_app(e):
            master.geometry(f'+{e.x_root-130}+{e.y_root-10}')
        def minimize():
            master.update_idletasks()
            master.overrideredirect(False)
            master.state('iconic')
        def return_to_normal_state(e="temp"):
            # master.update_idletasks()
            # master.overrideredirect(True)
            # master.deiconify()
            print(perf_counter())
        def bar_check_loop():
            while True:
                if master.state() == 'iconic':
                    master.bind("<Map>", return_to_normal_state)
        fake_title_bar.bind('<B1-Motion>', move_app)
        fake_title_label.bind('<B1-Motion>', move_app)

            #Adding a close button
        fake_title_close_button = Button(fake_title_bar, text="X", bg=color, fg="white", command=master.quit).pack(side=RIGHT)

        # fake_title_min_button = Button(fake_title_bar, text="━", bg=color, fg="white", command=minimize).pack(side=RIGHT)
        #=====================================================
        master.title("Sauce downloader")
        self.label = Label(master, text="Downloader by ~your mother", bg=color, fg="white")
        self.label.pack()
        frame1 = Frame(master,bg=color)
        frame1.pack()
        Label(frame1,text='Query:', bg=color, fg="white").pack(side=LEFT)
        self.querysearch = Entry(frame1,width=10, bg=color, fg="white")
        self.querysearch.pack(side=LEFT)
        Label(frame1,text=' Amount:', bg=color, fg="white").pack(side=LEFT)
        self.number_of_images = Entry(frame1,width=4, bg=color, fg="white")
        self.number_of_images.pack()
        frame2 = Frame(master,bg=color)
        frame2.pack(side=BOTTOM)
        self.close_button = Button(frame2, text="Download!", command=self.download, bg=color, fg="white").pack(side=LEFT)
        Label(frame2,text='   ', bg=color).pack(side=LEFT)
        self.post_cleanup_button = Button(frame2, text="Clean dupes!", command=self.post_cleanup, bg=color, fg="white").pack(side=RIGHT)

    def hash_file(filename):
        """"This function returns the SHA-1 hash
        of the file passed into it"""

        # make a hash object
        h = hashlib.sha1()

        # open file for reading in binary mode
        with open(filename,'rb') as file:

            # loop till the end of the file
            chunk = 0
            while chunk != b'':
                # read only 1024 bytes at a time
                chunk = file.read(1024)
                h.update(chunk)

        # return the hex representation of digest
        return h.hexdigest()

    def download(self):
        try:
            number = int(self.number_of_images.get())
        except:
            self.number_of_images.delete(0, 'end')
            self.number_of_images.insert(10, "Enter valid number")
            return
        try:
            tags=self.querysearch.get().replace('/', '%20')
        except:
            tags="ass%20boobs"
        url = f"https://gelbooru.com/index.php?page=dapi&s=post&q=index&json=1&limit=1&tags={tags}%20sort:random"
        self.master.withdraw()
        sizes=[]
        def thread_func():
            while True:
                try:
                    response = get(url).json()
                    img_url = response['post'][0]['file_url']
                    sleep(0.1)
                    data = BytesIO(get(img_url).content)
                    sleep(0.1)
                    img = Image.open(data)
                    print(f"{Path(__file__).parent.resolve()}\Image{randint(0,1000)}.png")
                    try:
                        img.save(f"{Path(__file__).parent.resolve()}\Image{randint(0,9)}{randint(0,9)}{randint(0,9)}{randint(0,9)}{randint(0,9)}.png")
                        break
                    except:
                        print("Error saving")
                except:
                    print("Error, trying again")
        def main():
            # create threads
            threads = []
            for i in range(number):
                threads.append(Thread(target=thread_func, args=()))

            # start the threads
            for thread in threads:
                thread.start()

            # wait for the threads to complete
            for thread in threads:
                thread.join()

        if __name__ == "__main__":
            start_time = perf_counter()

            main()

            end_time = perf_counter()
            print(f'It took {end_time- start_time :0.2f} second(s) to complete.')
        self.master.deiconify()
        self.master.deiconify()
    def post_cleanup(self):
        directory = Path(__file__).parent.resolve()
        file_sizes = []
        def convert_bytes(size):
            """ Convert bytes to KB, or MB or GB"""
            for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
                if size < 1024.0:
                    return "%3.1f %s" % (size, x)
                size /= 1024.0
        dupes_found = 0
        for filename in os.listdir(directory):
            f = os.path.join(directory, filename)
            # checking if it is a file
            if os.path.isfile(f):
                if what(f) == "png":
                    print(f)
                    f_size = os.path.getsize(f)
                    x = convert_bytes(f_size)
                    print('file size is', x)
                    if x in file_sizes:
                        print(f'file \"{filename}\" is most likely a duplicate')
                        dupes_found+=1
                        remove(f)
                        continue
                    file_sizes.append(x)
        if dupes_found == 0:
            print('There are no duplicate files')
        elif dupes_found == 1:
            print("One duplicate file was deleted")
        else:
            print(f'{dupes_found} duplicate files were deleted')
root = Tk()
downloader = image_downloader(root)

root.mainloop()


from os import write
import json
file_path = "python_cp1_q1_data.txt"

data = {"customers": ["James", "John", "Robert", "Mary", "Patricia", "Jennifer"],
        "salary": [155000, 755000, 455000, 1255000, 635000, 575000],
        "taxes": [55800, 317100, 182000, 451800, 171450, 71400]}
#data = {}

def print_customers_small_tax():
    for c, s, t in zip(data["customers"], data["salary"], data["taxes"]):
        if (t / s) < .3:
            print(c)

print_customers_small_tax()

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

def load_dict():
    try:
        file = open(file_path, "r")
        data = json.load(file)
    except Exception as e:
        print("Load fail: ", e)
    finally:
        file.close()

def save_dict():
    try:
        file = open(file_path, 'w')
        json.dump(data, file)
    except Exception as e:
        print("Save fail: ", e)
    finally:
        file.close()
print("-")
# --------------------------


from flask import Flask, render_template, request
import pandas as pd
import plotly.offline as py
import cufflinks as cf
import numpy as np
import plotly.graph_objs as go
import webbrowser
import folium
from pandas import DataFrame

app = Flask(__name__, static_folder="templates")

# 导入数据
data = pd.read_csv('forbes.csv')
regions_available = list(data.values)
cf.set_config_file(offline=True, theme="ggplot")
py.offline.init_notebook_mode()
N = pd.read_csv('forbes.csv', encoding="utf8",
                keep_default_na=False, na_values='na_rep')
N.head()

# Count crime numbers in each neighborhood
data5 = N.iloc[0:100, :]

disdata5 = pd.DataFrame(data['行业'].value_counts())
disdata5.reset_index(inplace=True)
disdata5.rename(columns={'index': '分类', 'PdDistrict': 'Count'}, inplace=True)

data4 = N.iloc[0:20, :]

disdata4 = pd.DataFrame(data['行业'].value_counts())
disdata4.reset_index(inplace=True)
disdata4.rename(columns={'index': '分类', 'PdDistrict': 'Count'}, inplace=True)

# def entry_page() -> 'html':
#    return render_template('首页.html')

@app.route('/all', methods=['GET'])
def for_bes_2019():
    # def 首页() -> 'html':
    # return render_template('首页.html')
    data_str = data.to_html()
    #fig = data.iplot(kind="bar", x="行业", y="国籍", asFigure=True)
   # py.offline.plot(fig, filename="行业（全部）.html", auto_open=False)
    with open("行业（全部）.html", encoding="utf8", mode="r") as f:
      plot_all = "".join(f.readlines())

    # regions_available = regions_available_loaded  # 下拉选单有内容
    return render_template('results2.html',
                           the_plot_all=plot_all,
                           the_res=data_str,
                           # the_select_region=regions_availa
                           )

@app.route('/city', methods=['POST'])
def star_select() -> 'html':
    the_region = request.form["the_region_selected"]
    print(the_region)  # 检查用户输入
    dfs = disdata4.query("region=='{}'".format(the_region))
    df_summary = dfs.groupby("行业").agg(
        {"数量": "number"}).sort_values(by="数量", ascending=False)
    print(df_summary.head(5))  # 在后台检查描述性统计
    # 显示前100名富豪所在的国籍的地图
    latitude = 39.92
    longitude = 116.46

    from folium import plugins

    # let's start again with a clean copy of the map of San Francisco
    san_map = folium.Map(location=[latitude, longitude], zoom_start=4)

    # instantiate a mark cluster object for the incidents in the dataframe
    incidents = plugins.MarkerCluster().add_to(san_map)

    # loop through the dataframe and add each data point to the mark cluster
    for lat, lng, label, in zip(d2.y, d2.x, N.中文姓名):
        folium.Marker(
            location=[lat, lng],
            icon=None,
            popup=label,
        ).add_to(incidents)

    # add incidents to map
    san_map.add_child(incidents)

@app.route('/forbes', methods=['GET'])
def hu_run_select() -> 'html':
    limit = request.args.get("limit")  # 取得用户交互输入
    print(limit)  # 检查用户输入, 在后台

    if limit == '20':
        data_str = data4.to_html()
        kind_data = disdata4[:20].to_html()
        file = "行业20.html"
    else:
        data_str = data5.to_html()
        kind_data = disdata5[:100].to_html()
        file = "行业100.html"
    print(file)
    with open(file, encoding="utf8", mode="r") as f:  # 把"成果.html"當文字檔讀入成字符串
        plot_all = "".join(f.readlines())

    # regions_available = regions_available_loaded  # 下拉选单有内容
    return render_template('results2.html',
                           the_plot_all=plot_all,
                           the_res=data_str,
                           the_select_region=regions_available,
                           kind_data=kind_data
                           )

@app.route('/allmap')
def allmap() -> 'html':
    return render_template('地图（全部）.html')

@app.route('/map20')
def map20() -> 'html':
    return render_template('地图（20）.html')

@app.route('/map100')
def map100() -> 'html':
    return render_template('地图（100）.html')

@app.route('/')
@app.route('/首页')
def entry_page() -> 'html':
    return render_template('首页.html')

if __name__ == '__main__':
    app.run(port=8000, debug=True)   # debug=True, 在py使用, 在ipynb不使用


import cv2
import time

# Lista de rutas de las imágenes
image_paths = ["clock_anger.png","clock_fear.png","clock_neutral.png"]

# Inicializa el índice de la imagen actual
current_image_index = 0

# Configura la ventana de OpenCV
cv2.namedWindow("Imagen")

while True:
    # Carga la imagen actual
    img_path = image_paths[current_image_index]
    img = cv2.imread(img_path)

    if img is not None:
        # Muestra la imagen
        cv2.imshow("Imagen", img)

        # Espera durante un tiempo (puedes ajustar el tiempo de visualización)
        key = cv2.waitKey(2000)

        # Cierra la ventana
        cv2.destroyWindow("Imagen")

        # Incrementa el índice para pasar a la siguiente imagen
        current_image_index += 1

        # Si alcanza el final de la lista de imágenes, vuelve al principio
        if current_image_index == len(image_paths):
            current_image_index = 0
    else:
        print("Fin de la presentación de imágenes.")
        break

# Cierra la ventana y finaliza el programa
cv2.destroyAllWindows()


from PyQt5.QtWidgets import QTextEdit, QPushButton, QLabel, QHBoxLayout, QVBoxLayout, QWidget, QApplication
from PyQt5.QtGui import QFont, QFocusEvent
from PyQt5.QtCore import Qt, QSize, pyqtSignal, QEvent, QThreadPool
from API.google_trans_API import GoogleTranslate
from database_folder.vocabulary import Vocabulary
from word_definer.definition_finder import DefinitionFinder, GoogleTranslateWorker
class WordDefiner(QWidget):
    word_saved_signal = pyqtSignal()

    def __init__(self):
        super().__init__()
        self.set_up_gui()
        self.unknown_btn.clicked.connect(lambda: self.save_word(confidence="unknown"))
        self.semi_known_btn.clicked.connect(lambda: self.save_word(confidence="semi-known"))
        self.known_btn.clicked.connect(lambda: self.save_word(confidence="known"))
        self.setContentsMargins(0,0,0,0)
        self.setWindowFlag(Qt.WindowStaysOnTopHint)
        self.setGeometry(0,0,300,100)
        self.thread_pool = QThreadPool()

    def set_up_gui(self):
        self.text_editor = QTextEdit()
        self.text_editor.setMinimumHeight(30)
        # self.text_editor.setMaximumHeight(30)
        self.text_editor.setFont(QFont("Arial", 12))

        #display selected word
        self.selected_word_label = QLabel()
        self.selected_word_label.setFont(QFont("Arial",15))
        self.selected_word_label.setMaximumHeight(30)

        #buttons
        self.unknown_btn = QPushButton("Unknown")
        self.semi_known_btn = QPushButton("Semi-Known")
        self.known_btn = QPushButton("Known")
        self.unknown_btn.setStyleSheet(f"background-color : rgb(255,0,0)")
        self.semi_known_btn.setStyleSheet(f"background-color : rgb(255,255,0)")
        self.known_btn.setStyleSheet(f"background-color : rgb(0,255,0)")
        color_btn_layout = QHBoxLayout()
        color_btn_layout.addWidget(self.unknown_btn)
        color_btn_layout.addWidget(self.semi_known_btn)
        color_btn_layout.addWidget(self.known_btn)

        self.main_layout = QVBoxLayout()
        self.main_layout.addWidget(self.selected_word_label)
        self.main_layout.addWidget(self.text_editor)
        self.main_layout.addLayout(color_btn_layout)
        self.main_layout.setContentsMargins(0,0,0,0)
        self.setLayout(self.main_layout)

    def set_definition_text(self, text):
        self.definition_text = text
        self.text_editor.setText(text)

    def look_up_word(self,text):
        self.set_selection_text(text)

        from_db = Vocabulary().fetch_single_exact_vocab(text)
        if from_db != None:
            self.set_definition_text(from_db)
        else:
            google_translate = GoogleTranslateWorker(text)
            google_translate.signals.finished.connect(lambda x : self.set_definition_text(x))
            self.thread_pool.start(google_translate)

    def set_selection_text(self, text):
        self.selected_word = text
        self.selected_word_label.setText(f"<b>{text}</b>")

    def save_word(self,confidence):
        definition = self.text_editor.toPlainText()
        # word = self.selected_word.lower()
        Vocabulary().add_word_to_database(self.selected_word, definition, confidence)
        self.clear_ui()
        self.word_saved_signal.emit()

    def clear_ui(self):
        self.text_editor.clear()
        self.selected_word_label.clear()
        self.selected_word = ""
        self.definition_text = ""
        self.google_suggestion = ""

    def move_to_click_position(self,pos):
        width = self.width()
        height = self.height()
        # make sure it doesn't go off the side
        x = int(pos.x())
        y = int(pos.y())
        dis_cen = width/2 # minimum allowed distance from the center, in other words don't go past this limit otherwise it will be cut off the screen.
        while x <= dis_cen: # if passes the limit add 1 until it is  no longer past the limit.
            x += 1
        if x > dis_cen:
            x = x-dis_cen # center over click pos
        y = y - height/2 # center over click pos
        y = y - 120 # offset above click pos
        self.move(int(x),int(y))


from jax import (
    numpy as jnp,
    random,
    nn
)
import pytest
from mlax.nn import Embed
from mlax._test_utils import layer_test_results, assert_equal_array

def range_initializer(key, shape, dtype):
    assert len(shape) == 2
    assert shape[1] == 1
    return jnp.expand_dims(jnp.arange(shape[0], dtype=dtype), axis=1)

@pytest.mark.parametrize(
    "config,x,expected_embed_kernel,expected_output",
    [
        (
            {
                "rng": random.PRNGKey(0),
                "vocab_size": 10,
                "embed_dim": 8,
                "embed_initializer": nn.initializers.ones,
                "dtype": jnp.float32
            },
            jnp.arange(11),
            jnp.ones((10, 8), dtype=jnp.float32),
            jnp.concatenate(
                [
                    jnp.ones((10, 8), jnp.float32),
                    jnp.full((1, 8), jnp.nan, jnp.float32)
                ]
            )
        ),
        (
            {
                "rng": random.PRNGKey(1),
                "vocab_size": 8,
                "embed_dim": 12,
                "embed_initializer": nn.initializers.zeros,
                "dtype": jnp.int16
            },
            jnp.arange(9, dtype=jnp.int8),
            jnp.zeros((8, 12), jnp.int16),
            jnp.concatenate(
                [
                    jnp.zeros((8, 12), jnp.int16),
                    jnp.full((1, 12), -jnp.inf, jnp.int16)
                ]
            )
        ),
        (
            {
                "rng": random.PRNGKey(2),
                "vocab_size": 16,
                "embed_dim": 1,
                "embed_initializer": range_initializer,
                "dtype": jnp.float16
            },
            jnp.arange(18, dtype=jnp.int16),
            jnp.expand_dims(jnp.arange(16, dtype=jnp.float16), axis=1),
            jnp.expand_dims(
                jnp.concatenate([
                    jnp.arange(16, dtype=jnp.float16),
                    jnp.full(2, jnp.nan, jnp.float16)
                ]),
                axis=1
            )
        )
    ]
)
def test_embed(config, x, expected_embed_kernel, expected_output):
    layer, (t_acts, new_t_layer), (i_acts, new_i_layer) = layer_test_results(
        Embed, config, x
    )
    assert_equal_array(layer.embed_kernel.data, expected_embed_kernel)

    assert_equal_array(t_acts, expected_output)
    assert_equal_array(new_t_layer.embed_kernel.data, expected_embed_kernel)

    assert_equal_array(i_acts, expected_output)
    assert_equal_array(new_i_layer.embed_kernel.data, expected_embed_kernel)


#!/usr/bin/env python
from __future__ import print_function, unicode_literals
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager, Shell, Server
from rq import Worker, Queue, Connection
from trelolo import create_app
from trelolo.extensions import db, rq
from trelolo.worker import unhook_all

def _make_context():
    ctx = {
        'app': app
    }
    return ctx

app = create_app()
migrate = Migrate(app, db)

manager = Manager(app)
manager.add_command('shell', Shell(make_context=_make_context))
manager.add_command(
    'runserver', Server(
        host=app.config['FLASK_HOST'], port=app.config['FLASK_PORT']
    )
)
manager.add_command('db', MigrateCommand)

with app.app_context():
    q = Queue(
        connection=rq,
        default_timeout=app.config.get('QUEUE_TIMEOUT')
    )

@manager.command
def unhookall():
    q.enqueue(unhook_all)

@manager.command
def work():
    with Connection(rq):
        worker = Worker(map(Queue, ['high', 'default', 'low']))
        worker.work()

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


'''
"pubchem_xyzcoord.py"
@h-nabata  (2021/10/07 ver1.0)
A program that obtains the 3D structures of molecules from the compound database "PubChem" and converts them into xyz format.
PubChem:    https://pubchem.ncbi.nlm.nih.gov/
*input:     Compound CID
*output:    xyz-format
'''

import requests
import time
import os

# CIDを指定してsdfファイルの内容を取得（ここだけ入力すればOK）
CID = [10000 + i for i in range(10)]

for i in range(len(CID)):
    url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/CID/" + str(CID[i]) + "/record/SDF/?record_type=3d&response_type=display"
    r = requests.get(url)
    tmp_input_file = "tmp_3DCoordFile.txt"

    with open(tmp_input_file, encoding='utf-8', mode="w") as f:
        f.write(r.text)  # 取得データの書き出し

    # xyz座標の取得
    atomnum = 0; atomname = []; atomcoord = []
    with open(tmp_input_file, encoding='utf-8') as f:
        while True:  # 読み込める行が無くなるまで繰り返す
            line = f.readline()  # ファイル f を1行ずつ読み込んでいく
            elem = line.split()  # 読み込んだ行を要素に分割する
            if len(elem) > 10:  # 要素数が10を超える行のみ処理する
                atomname.append((elem[3]))
                atomcoord.append([float(elem[0]), float(elem[1]), float(elem[2])])
                atomnum += 1
            if not line:
                break

    # 取得データの確認（オプション）
    print(atomnum)
    print(atomname)
    print(atomcoord)

    # xyz形式でファイルに出力
    output_file = str(CID[i]) + ".xyz"
    with open(output_file, mode='w', encoding='utf-8') as outf:
        outf.write(str(atomnum) + "\n" + str(CID[i]) + "\n")
        for i in range(atomnum):
            xc = '{:>17.12f}'.format(float(atomcoord[i][0]))
            yc = '{:>17.12f}'.format(float(atomcoord[i][1]))
            zc = '{:>17.12f}'.format(float(atomcoord[i][2]))
            output_linestr = str(atomname[i]) + xc + yc + zc
            print(output_linestr)
            outf.write(output_linestr + "\n")  # 改行が必要

#     # 全構造をxyz形式でファイルに出力（オプション）
#     outputall_file = "C:/Users/" + str(os.getlogin()) + "/Downloads/mol_xyz/all.xyz"  # パスはご自由に指定して下さい
#     with open(outputall_file, mode='a', encoding='utf-8') as outf2:
#         outf2.write(str(atomnum) + "\n" + str(CID[i]) + "\n")
#         for j in range(atomnum):
#             output_linestr2 = str(atomname[j]) + " " + str(atomcoord[j][0]) + " " + str(atomcoord[j][1]) + " " + str(atomcoord[j][2]) + "\n"
#             outf2.write(output_linestr2)
#         outf2.write("\n")

    time.sleep(0.5)  # 0.5秒sleepする（オプション）


# -*- coding: utf-8 -*-
# 导入sys
import sys
# 任何一个PySide界面程序都需要使用QApplication
# 我们要展示一个普通的窗口，所以需要导入QWidget，用来让我们自己的类继承
from PySide2.QtWidgets import QApplication, QWidget
# 导入我们生成的界面
from ui_hello import Ui_Form

# 继承QWidget类，以获取其属性和方法
class MyWidget(QWidget):
    def __init__(self):
        super().__init__()
        # 设置界面为我们生成的界面
        self.ui = Ui_Form()
        self.ui.setupUi(self)

# 程序入口
if __name__ == "__main__":
    # 初始化QApplication，界面展示要包含在QApplication初始化之后，结束之前
    app = QApplication(sys.argv)

    # 初始化并展示我们的界面组件
    window = MyWidget()
    window.show()

    # 结束QApplication
    sys.exit(app.exec_())
    # 注意，在PySide6中，需要使用app.exec()
    # sys.exit(app.exec())


import pygame
from Dic import *
from Values import *
from System import *

img_HealKit1=pygame.image.load(img_Dic+'HealKit1.png')  # 작은 사이즈
img_HealKit2=pygame.image.load(img_Dic+'HealKit2.png')
img_HealKit3=pygame.image.load(img_Dic+'HealKit3.png') # 큰 사이즈

class HealKit(object):
    def __init__(self,x,y,num):
        self.x = x
        self.y = y
        self.vel = 5
        self.num=num
        self.hitbox = (self.x, self.y, HealKitSize, HealKitSize)  # hit 박스
        self.geted=False
        self.size=HealSize-50*(3-num)

    def draw(self, screen):
        #self.move()
        if not self.geted: # 미획득시
            if self.num == 1:
                img_HealKit=img_HealKit1
            elif self.num == 2:
                img_HealKit = img_HealKit2
            elif self.num == 3:
                    img_HealKit = img_HealKit3

            screen.blit(img_HealKit, (self.x, self.y))
            #color = (0, 128, 0)
            #pygame.draw.rect(screen, color, (self.x, self.y,HealKitSize, HealKitSize))

    #def  move(self):
        #if not self.geted: # 미획득시
            #self.x-=self.vel


## NN_digits_main.py
## Main function to test the Neural Network - digits.
#####################################################

##  4-Layers NN: [28*28, 60, 15, 10].
##  Image size is 28 x 28 pixels.
##

from import_data import load_data;
from NN_Model import NN_Model, one_hot;
from random import randint;
from numpy import save as np_save, load as np_load;

import numpy as np;
import os;
import matplotlib.pyplot as plt;    #   To plot Cost vs. # of iterations.

CURRENT_PATH        =   os.getcwd();
#CURRENT_HOME        =   (os.path.expanduser('~'))

Grad_Descent_Method, Minimize_funct_method    =   True, False;

PLOT_COST           =   True;      ##  Plot J_cost vs. # of iterations to check if J_cost converges to minimum.
LOAD_PREV_THETAS    =   False;      ##  Load the previous trained weights. Otherwise, randomize initial weights.
CONTINUOUS_TRAINING =   True;      ##  If True, then it will train the NN (10k training iterations.)
COUNT_ERROR         =   False;       ##  Compute the error rate of the trained prediction function.
                                    ##      against the test samples (60k images). So far, ~8.5% error.

CLASS_GROUPS = ("Iris Setosa", "Iris Versicolour", "Iris Virginica");

def plot_iris_data(x, y):
    ##  Using matplotlib to display the gray-scaled digit image.

    ## Preparing data by classification groups
    groups_sepal  =   [0]*max(y+1);
    groups_petal  =   [0]*max(y+1);

    for i in range(len(y)):

        if groups_sepal[y[i]] == 0:
            groups_sepal[y[i]]   =   (   [ x[i][0] ], [ x[i][1] ]);
            groups_petal[y[i]]   =   (   [ x[i][2] ], [ x[i][3] ]);

        else:
            groups_sepal[y[i]][0].append(  x[i][0] );
            groups_sepal[y[i]][1].append(  x[i][1] );
            groups_petal[y[i]][0].append(  x[i][2] );
            groups_petal[y[i]][1].append(  x[i][3] );

    ## Setting up the plot variables.
    COLOR_LOOKUP    =   {0:'red', 1:'green', 2:'yellow'};
    colors          =   ('red', 'green', 'blue');

    #fig       =   plt.figure();
    fig, (ax_sepal, ax_petal)    =   plt.subplots(2, sharex = True);

    ## Plotting Sepal length and width.
    for data, color, group in zip(groups_sepal, colors, CLASS_GROUPS):
        x, y    =   data;
        ax_sepal.scatter( x, y , alpha=0.8, c = color, edgecolors='none', s=30, label=group);

    plt.title('Iris Sepal & Petal Length and Width');

    ## Plotting Petal length and width.
    for data, color, group in zip(groups_petal, colors, CLASS_GROUPS):
        x, y    =   data;
        ax_petal.scatter( x, y , alpha=0.8, c = color, edgecolors='none', s=30, label=group);

    plt.legend(loc=1);
    plt.show();
    return;

def main():

    x_data, y_data = load_data();   ##  Set parameter to True for initial download.
                                                    ##  Once data is present, set this to False to
                                                    ##      prevent re-downloading data.

    ## Plotting the Iris Petal and Sepal length and width.
    plot_iris_data(x_data, y_data);

    y_data      =   one_hot(y_data);

    #Split data: 80% test set, 20% validation set.
    i_80   =   int(len(y_data)*0.8);
    x_train, y_train    =   x_data[:i_80], y_data[:i_80];
    x_test, y_test      =   x_data[i_80:], y_data[i_80:];

    iris_nn     =   NN_Model (      x_train,        ## input data.
                                    y_train,        ## output data.
                                    3,              ## 3 NN layers: Input, hidden-layer, output.
                                    [4,4,3] );      ## num of nodes for each layer.

    if Grad_Descent_Method:
        print("\nNeural Network XNOR - using GRADIENT DESCENT ITERATION\n", "#"*30, "\n");

        # File location where learned weight is saved.
        theta_file  =   CURRENT_PATH + r'/' + 'theta.npy';

        if  LOAD_PREV_THETAS:
            flat_thetas =   np_load(    theta_file);
            iris_nn.unflatten_Thetas( flat_thetas);

            if CONTINUOUS_TRAINING:
                iris_nn.train_NN();
                np_save(    theta_file, iris_nn.flatten_Thetas());

        else:
            iris_nn.train_NN();
            np_save(    theta_file, iris_nn.flatten_Thetas());

            # Display final cost after learning iterations.
            print("Final Cost J = ", iris_nn.J_cost(iris_nn.a[-1]));

        if PLOT_COST:

            #   Plot the J Cost vs. # of iterations. J should coverge as iteration increases.
            x_axis  =   range(len(iris_nn.J_cost_values));
            y_axis  =   iris_nn.J_cost_values;

            plt.plot(   x_axis, y_axis, label='J_cost vs. # of Iterations');
            plt.show();

        # Test model accuracy on Validation/Test set.
        acc_count = 0;
        for i in range( len(x_test)):

            x_input     =   x_test[i].flatten();
            y_val       =   np.argmax(y_test[i]);
            y_pred      =   iris_nn.predict(    x_input    )[0];
            #print(y_pred, y_val);

            if y_pred == y_val:   acc_count += 1;

        print(  "Test Accuraccy = {}".format( acc_count/len(x_test)));

    return 0;

if __name__ == "__main__":  main();


"""
Tests for Semantic route
"""
from bson.objectid import ObjectId

from tests.unit.routes.base import BaseRelationshipApiTestSuite

class TestSemanticApi(BaseRelationshipApiTestSuite):
    """
    TestSemanticApi class
    """

    class_name = "Semantic"
    base_route = "/semantic"
    unknown_id = ObjectId()
    semantic_id = ObjectId()
    payload = {"_id": str(semantic_id), "name": "EVENT_TIMESTAMP"}
    semantic_names = []
    quoted_semantic_names = []
    create_conflict_payload_expected_detail_pairs = [
        (payload, f'Semantic (id: "{payload["_id"]}") already exists.')
    ]
    create_unprocessable_payload_expected_detail_pairs = []
    create_parent_unprocessable_payload_expected_detail_pairs = [
        (
            {"id": str(unknown_id)},
            f'Semantic (id: "{unknown_id}") not found. Please save the Semantic object first.',
        )
    ]

    def multiple_success_payload_generator(self, api_client):
        """Post multiple success responses"""
        _ = api_client
        semantic_names = ["EVENT_ID", "EVENT_TIMESTAMP", "ITEM_ID"]
        for semantic in semantic_names:
            payload = self.payload.copy()
            payload["_id"] = str(ObjectId())
            payload["name"] = semantic
            yield payload


import sys

from com.automationpanda.example.calc import Calculator

# Attempt to use back-ported unittest2 for Python 2.6 and earlier
# However, it is strongly recommended to use Python 2.7 or 3.<latest>
try:
    if sys.version_info < (2, 7):
        import unittest2
    else:
        raise ImportError()
except ImportError:
    import unittest

NUMBER_1 = 3.0
NUMBER_2 = 2.0
FAILURE = 'incorrect value'

class CalculatorTest(unittest.TestCase):
    def setUp(self):
        self.calc = Calculator()

    def test_last_answer_init(self):
        value = self.calc.last_answer
        self.assertEqual(value, 0.0, FAILURE)

    def test_add(self):
        value = self.calc.add(NUMBER_1, NUMBER_2)
        self.assertEqual(value, 5.0, FAILURE)
        self.assertEqual(value, self.calc.last_answer, FAILURE)

    def test_subtract(self):
        value = self.calc.subtract(NUMBER_1, NUMBER_2)
        self.assertEqual(value, 1.0, FAILURE)
        self.assertEqual(value, self.calc.last_answer, FAILURE)

    def test_subtract_negative(self):
        value = self.calc.subtract(NUMBER_2, NUMBER_1)
        self.assertEqual(value, -1.0, FAILURE)
        self.assertEqual(value, self.calc.last_answer, FAILURE)

    def test_multiply(self):
        value = self.calc.multiply(NUMBER_1, NUMBER_2)
        self.assertEqual(value, 6.0, FAILURE)
        self.assertEqual(value, self.calc.last_answer, FAILURE)

    def test_divide(self):
        value = self.calc.divide(NUMBER_1, NUMBER_2)
        self.assertEqual(value, 1.5, FAILURE)
        self.assertEqual(value, self.calc.last_answer, FAILURE)

    def test_divide_by_zero(self):
        self.assertRaises(ZeroDivisionError, self.calc.divide, NUMBER_1, 0)

    def test_max_greater(self):
        value = self.calc.maximum(NUMBER_1, NUMBER_2)
        self.assertEqual(value, NUMBER_1, FAILURE)
        self.assertEqual(value, self.calc.last_answer, FAILURE)

    def test_max_less(self):
        value = self.calc.maximum(NUMBER_2, NUMBER_1)
        self.assertEqual(value, NUMBER_1, FAILURE)
        self.assertEqual(value, self.calc.last_answer, FAILURE)

    def test_max_equal(self):
        value = self.calc.maximum(NUMBER_1, NUMBER_1)
        self.assertEqual(value, NUMBER_1, FAILURE)
        self.assertEqual(value, self.calc.last_answer, FAILURE)

    def test_min_greater(self):
        value = self.calc.minimum(NUMBER_1, NUMBER_2)
        self.assertEqual(value, NUMBER_2, FAILURE)
        self.assertEqual(value, self.calc.last_answer, FAILURE)

    def test_min_less(self):
        value = self.calc.minimum(NUMBER_2, NUMBER_1)
        self.assertEqual(value, NUMBER_2, FAILURE)
        self.assertEqual(value, self.calc.last_answer, FAILURE)

    def test_min_equal(self):
        value = self.calc.minimum(NUMBER_2, NUMBER_2)
        self.assertEqual(value, NUMBER_2, FAILURE)
        self.assertEqual(value, self.calc.last_answer, FAILURE)

if __name__ == '__main__':
    import xmlrunner

    unittest.main(
        testRunner=xmlrunner.XMLTestRunner(output='test-reports'),
        failfast=False,
        buffer=False,
        catchbreak=False)


from annotations.bop import get_dict_bop_cpgs
from config.config import *

def save_dict_bop_cpg(config):
    dict_bop_cpgs = get_dict_bop_cpgs(config)

    str_list = []
    for bop in dict_bop_cpgs:
        bop_cpgs = dict_bop_cpgs.get(bop)
        curr_str = bop
        for bop_cpg in bop_cpgs:
            curr_str += ' ' + bop_cpg
        str_list.append(curr_str)

    fn = get_bop_data_path(config, 'dict_bop_cpg.txt')
    np.savetxt(fn, str_list, fmt="%s")

db = DataBaseType.GSE52588
config = Config(
    db=db
)

classes = [ClassType.any, ClassType.class_a, ClassType.class_b, ClassType.class_c, ClassType.class_d]

for class_type in classes:
    print('class: ' + class_type.value)
    config.class_type = class_type
    save_dict_bop_cpg(config)


# 1. Imports
import time
from random import randint
import matplotlib.pyplot as plt
from knapsack import ks_bottom_up, ks_top_down

# Helper function to measure the runtime of a function
def measure_runtime(func, items, capacity):
    start_time = time.time()
    func(items, capacity)
    end_time = time.time()
    return end_time - start_time

# Experiment function to run the knapsack algorithm and collect runtime data
def knapsack_runtime_experiment(func, item_counts, max_capacity,  min_value, max_value, min_weight, max_weight, iterations):
    results = {}
    for count in item_counts:
        average_runtime = 0
        for _ in range(iterations):
            items = [(randint(min_value, max_value), randint(min_weight, max_weight)) for _ in range(count)]
            runtime = measure_runtime(func, items, max_capacity)
            average_runtime += runtime
        average_runtime /= iterations
        results[count] = average_runtime
    return item_counts, [results[count] for count in item_counts]

# Bottom up is better: Large number of items with small weights and high values
def plot1_results():
    item_counts = range(10, 501, 10)  # Varying number of items
    max_capacity = 50  # Maximum capacity of the knapsack
    iterations = 100  # Number of iterations to average out the runtime
    min_weight = 1
    max_weight = 5
    min_value = 50
    max_value = 100

    plt.figure(figsize=(10, 6))

    # Running experiments for both bottom-up and top-down approaches

    x, y = knapsack_runtime_experiment(ks_bottom_up, item_counts, max_capacity,  min_value, max_value, min_weight, max_weight, iterations)
    plt.plot(x, y, label='Bottom-Up')
    x, y = knapsack_runtime_experiment(ks_top_down, item_counts, max_capacity,  min_value, max_value, min_weight, max_weight, iterations)
    plt.plot(x, y, label='Top-Down')

    plt.title('Knapsack Algorithm Runtime Comparison (BU is better)')
    plt.xlabel('Number of Items')
    plt.ylabel('Average Runtime (seconds)')
    plt.legend()
    plt.grid(True)
    plt.tight_layout()
    plt.show()
    plt.close()

# Run the experiment and generate the plot
#plot1_results()

#Top-down is better: Small number of items with weights close to the knapsack's capacity and a smaller value:weight ratio (much more specific because BU is usually better)
def plot2_results():
    item_counts = range(10, 501, 5)
    max_capacity = 50
    iterations = 100
    min_weight = 25
    max_weight = 50
    min_value = 1
    max_value = 10

    plt.figure(figsize=(10, 6))

    x, y = knapsack_runtime_experiment(ks_bottom_up, item_counts, max_capacity,  min_value, max_value, min_weight, max_weight, iterations)
    plt.plot(x, y, label='Bottom-Up')
    x, y = knapsack_runtime_experiment(ks_top_down, item_counts, max_capacity,  min_value, max_value, min_weight, max_weight, iterations)
    plt.plot(x, y, label='Top-Down')

    plt.title('Knapsack Algorithm Runtime Comparison (TD is better)')
    plt.xlabel('Number of Items')
    plt.ylabel('Average Runtime (seconds)')
    plt.legend()
    plt.grid(True)
    plt.tight_layout()
    plt.show()
    plt.close()

# Run the experiment and generate the plot
plot2_results()


"""
This script selects all combinations of MPC optimizers and environments from config.
It runs the controllers for a number of randomized trials using the default parametrization in controller / optimizer config.
You can additionally specify hyperparameters to sweep. Each hyperparameter combination will be run independently.
"""
# 1. Specify the following (can be an empty list)
# Example:
#   parameters_to_sweep = ["config_optimizers.rpgd-tf.learning_rate", "config_optimizers.rpgd-tf.batch_size"]
#   sweep_values = [[0.01, 0.05, 0.2], [1, 5, 10]]
#   -> Creates 3 runs with zipped parameter tuples (0.01, 1), (0.05, 5), (0.2, 10).
#   -> Hint: Make sure that the optimizer you sweep over is also set either here or directly in config

parameters_to_sweep = [
    "config_controllers.mpc.optimizer",  # syntax: <<config_name>>.<<config_entry>>.<<parameter_name>>
]
sweep_values = [
    ["rpgd-tf", "rpgd-me-tf"],
]  # One list per parameter above. All sublists need to have same length
controller_name = "controller_mpc"

### ------------------------------------------------------------------------------------ ###
from datetime import datetime
import os
from itertools import product

import tensorflow as tf
from main import run_data_generator
import ruamel.yaml

from Utilities.utils import ConfigManager, CurrentRunMemory, OutputPath, get_logger, nested_assignment_to_ordereddict

logger = get_logger(__name__)

config_manager = ConfigManager(".", "Control_Toolkit_ASF", "SI_Toolkit_ASF", "Environments")
environment_name = config_manager("config")["environment_name"]

if controller_name != "controller_mpc":
    raise ValueError("This script is designed to run when the config.yml has controller_names=[controller_mpc].")

if __name__ == "__main__":
    datetime_str = datetime.now().strftime('%Y%m%d-%H%M%S')
    # Iterate over all zipped hyperparameter combinations:
    for sweep_value_tuple in zip(*sweep_values):
        OutputPath.collection_folder_name = os.path.join(
            f"{datetime_str}_sweep_{','.join(parameters_to_sweep)}",
            f"{datetime_str}_{controller_name}_{environment_name}",
            f"{datetime_str}_{','.join(parameters_to_sweep)}={','.join(list(map(str, sweep_value_tuple)))}",
        )
        CurrentRunMemory.current_controller_name = controller_name
        CurrentRunMemory.current_environment_name = environment_name

        for param_desc, param_value in zip(parameters_to_sweep, sweep_value_tuple):
            config_name, config_entry, param_name = param_desc.split(".")
            if param_name not in config_manager(config_name)[config_entry]:
                raise ValueError(f"{param_name} is not used in {config_name}")
            # Overwrite with sweep value:
            loader = config_manager.loaders[config_name]
            data: ruamel.yaml.comments.CommentedMap = loader.load()
            nested_assignment_to_ordereddict(data, {config_entry: {param_name: param_value}})
            loader.overwrite_config(data)

        device_name = "/CPU:0"
        if config_manager("config")["use_gpu"]:
            if len(tf.config.list_physical_devices("GPU")) > 0:
                device_name = "/GPU:0"
            else:
                logger.info(
                    "GPU use specified in config but no device available. Using CPU instead."
                )

        with tf.device(device_name):
            run_data_generator(
                CurrentRunMemory.current_controller_name,
                CurrentRunMemory.current_environment_name,
                config_manager,
            )


import numpy as np
import cv2
import matplotlib.pyplot as plt

image = cv2.imread("images/hinh1.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(src = gray, ksize = (5, 5), sigmaX = 0)
# Setup SimpleBlobDetector parameters.
params = cv2.SimpleBlobDetector_Params()  # Cai dat ham detector cham (ham loc, lay cham)

# Filter by Inertia
params.filterByArea = True
params.minArea = 3
params.maxArea = 128*128
params.filterByCircularity = False
params.filterByColor = False
params.filterByConvexity = False
params.filterByInertia = False  # Chon xai cong cu Filter Inertia
params.minInertiaRatio = 0.7  # Chon min do tron cua hinh la 0.7
params.minThreshold = int(0.5*255)
params.maxThreshold = int(0.95*255)
params.thresholdStep = 10

# Create a detector with the parameters (Tao ct con detect)
ver = (cv2.__version__).split('.')
if int(ver[0]) < 3:
    detector = cv2.SimpleBlobDetector(params)
else:
    detector = cv2.SimpleBlobDetector_create(params)

# Binary Picture For Detect Black Pips Of Dice
#binary = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 131, 15)
(_,binary) = cv2.threshold(blurred, 200, 255, cv2.THRESH_BINARY)
cv2.imshow("binary", binary)
# Detect black blobs.
keypoints = detector.detect(binary)
print(keypoints)
tong_cham = len(keypoints)  # so luong cham den

tam = np.zeros(shape=(len(keypoints), 2))  # Tim tam cua nhung cham
for i in range(len(keypoints)):
    tam[i][0] = keypoints[i].pt[0]  # Toa do x
for i in range(len(keypoints)):
    tam[i][1] = keypoints[i].pt[1]  # Toa do y
tam = np.float32(tam)  # Chuyen float 32bit
# Su dung Kmean
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
k = 6
ret, label, center = cv2.kmeans(tam, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
print(tam)
print(label)
count = np.zeros((6, 1), dtype=int)  # Ma tran count luu so cham den cung 1 vung
font = cv2.FONT_HERSHEY_SIMPLEX
for i in label:  # Ma tran chua so vung cua tung xuc xuat
    count[i] = count[i] + 1  # count chu so cham trong tung vung
for i in range(len(count)):
    cv2.putText(image, str(count[i]), (center[i][0], center[i][1]), font, 0.5, (0, 0, 255), 1)

cv2.putText(image, 'Tong cham:' + str(tong_cham), (300, 50), font, 1, (0, 0, 255), 1)
cv2.imshow("ket qua", image)
cv2.waitKey(0)
cv2.destroyAllWindows()


###############################################
# aquire.py
#
# This file is responsible for aquiring data
#  that is to be parsed.
#
# Dependencies:
#  mechanize
#
# 2012-07-19
# Trevor Pottinger
###############################################

import csv
wikibase = 'http://en.wikipedia.org/w/api.php'
wikiargs = '?action=query&format=xml&redirects&titles=%s'
wiki = wikibase + wikiargs

class url_feeder(object):
	def __init__(self, fname):
		"""fname is the name of the file that we will have a url in
		each line representing a page for us to scrape."""
		self.queue = []
		with open(fname) as f:
			reader = csv.DictReader(f)
			for l in reader:
				comp = l['company']
				comp = comp.replace(' ', '_')
				url = wiki % comp
				self.insert((url, l))

	def __iter__(self):
		return self

	def next(self):
		if len(self.queue) != 0:
			return self.queue.pop()
		raise StopIteration

	def insert(self, tup):
		"""tup is a tuple, where tup[0] is a url, tup[1] is a dict"""
		self.queue.insert(0, tup)

import mechanize as mech

class url_grabber(object):
	def __init__(self):
		self.br = mech.Browser()
		self.br.addheaders = [('User-agent', 'PyBro_Slitherer')]
		self.br.set_handle_robots(True)

	def retrieve(self, url):
		"""Attempt to retrieve the html stored at url."""
		try:
			self.br.open(url)
			return self.br.response().read()
		except:
			return 'Failed' # we should probably handle this...

	def toss_salad(self, fname):
		with open(fname) as f:
			pass