import argparse
import os
# from partition_baseline_support import *
import graph_tool.all as gt
import pandas as pd # for writing output graph TSV files
import math
import networkx as nx
import numpy as np
import random
import scipy.stats as stats

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("-n", "--numvertices", type=int, default=40, help="Number of vertices in graph")
    parser.add_argument("-c", "--communities", type=int, default=4, help="Number of communities in graph. If -1, uses communityexponent argument instead.")
    parser.add_argument("-o", "--overlap", type=float, default=0.05, help="0.0 < o < 1.0; o% of the intra-block edges will be added between blocks.")
    parser.add_argument("--biasblocks", type=int, default=2, help="biasblocks < communities; the number of blocks that have a higher chance of forming inter-block edges.")
    parser.add_argument("-b", "--blockbias", type=float, default=0.5, help="0.0 < b < 1.0; the chance that an interblock edge is formed between the biased blocks.")
    parser.add_argument("--biasvertices", type=int, default=2, help="The number of vertices in each block that have a higher chance of forming inter-block edges.")
    parser.add_argument("--vertexbias", type=float, default=1.0, help="0.0 <= vertexbias <= 1.0; the chance that an interblock edge is formed between the biased blocks.")
    parser.add_argument("--explicitoverlap", type=float, default=-1, help="If > 0, will use this value as the explicit number of edges b/n blocks.")
    parser.add_argument("-s", "--blocksizevariation", type=float, default=1.0, help="Power law exponent for block sizes. s > 1")
    parser.add_argument("-e", "--powerlawexponent", type=float, default=2.1, help="The power law exponent. e > 1")
    parser.add_argument("-d", "--density", type=float, default=1.0, help="1 - d fraction of edges will be removed")
    parser.add_argument("--directory", type=str, default="/mnt/d/workspace/graph_data")
    return parser.parse_args()
# Generate the graph according to the blockmodel and parameters

args = parse_args()
N = args.numvertices
N_adjusted = int(args.numvertices * 1.13)
C = args.communities
ratio_within_over_between = args.overlap
block_size_heterogeneity = args.blocksizevariation
powerlaw_exponent = args.powerlawexponent
density = args.density
num_blocks = C
print('Number of blocks: {}'.format(num_blocks))

save_graph = True
tag = "test_{0}_{1}_{2}_{3}_{4}".format(num_blocks, args.biasblocks, args.blockbias, args.biasvertices, args.vertexbias)
overlap = "low"
if args.overlap < 5:
    overlap = "high"
block_size_variation = "low"
if args.blocksizevariation > 1.0:
    block_size_variation = "high"
file_name = "{4}/{3}/{0}Overlap_{1}BlockSizeVar/{3}_{0}Overlap_{1}BlockSizeVar_{2}_nodes".format(
    args.overlap, args.blocksizevariation, N, tag, args.directory)
os.makedirs(os.path.dirname(file_name), exist_ok=True)

bias_vertices = np.random.choice(np.arange(N), args.biasvertices, False)
vertex_degrees = np.zeros(N)

graph = gt.Graph(directed=True)
start = 0
end = math.ceil(N / num_blocks)
blocks = list()
while start < N:
    print("start: {0} end: {1}".format(start, end))
    # build a fully connected component
    blocks.append(list(range(start, end)))
    for i in range(start, end):

        # if i in bias_vertices and random.random() < 0.5
        if i in bias_vertices and vertex_degrees[i] > len(blocks[-1])/2:
            continue
        for j in range(i+1, end):
            if i == j:
                continue
            # if j in bias_vertices and random.random() < 0.5:
            if j in bias_vertices and vertex_degrees[j] > len(blocks[-1])/2:
                continue
            if random.random() < 0.5:
                graph.add_edge(i, j)
            else:
                graph.add_edge(j, i)
            vertex_degrees[i] += 1
            vertex_degrees[j] += 1
    start = end
    end += int(N / num_blocks)
    end = min(end, N)

# TODO: deterministic bias_vertex selection (find all community combinations, then loop over those)

# add edges between components
block_indices = np.arange(num_blocks)
true_assignment = list()
for b in block_indices:
    true_assignment.extend([b] * len(blocks[b]))
true_assignment = np.asarray(true_assignment)

for vertex in bias_vertices:
    vertex_block = true_assignment[vertex]
    # expected_edges = 2
    # expected_edges = len(blocks[vertex_block]) - 1
    print("vertex degrees: ", graph.get_total_degrees([vertex]))
    # missing_edges = int(expected_edges) - int(graph.get_total_degrees([vertex])[0])
    missing_edges = int(graph.get_total_degrees([vertex])[0] - 1)
    b = np.random.choice(block_indices)
    while b == true_assignment[vertex]:
        b = np.random.choice(block_indices)
    for i in range(missing_edges):
        # b = np.random.choice(block_indices)
        # while b == true_assignment[vertex]:
        #     b = np.random.choice(block_indices)
        v_b = np.random.choice(blocks[b])
        if random.random() < 0.5:
            while v_b in graph.get_out_neighbors(vertex):
                v_b = np.random.choice(blocks[b])
            graph.add_edge(vertex, v_b)
        else:
            while v_b in graph.get_in_neighbors(vertex):
                v_b = np.random.choice(blocks[b])
            graph.add_edge(v_b, vertex)

    # out_edges = graph.get_out_edges(vertex)
    # for edge in out_edges:
    #     if random.random() < 0.5:
    #         graph.remove_edge(edge)
    #         b = np.random.choice(block_indices)
    #         while b == true_assignment[vertex]:
    #             b = np.random.choice(block_indices)
    #         v_b = np.random.choice(blocks[b])
    #         while v_b in graph.get_out_neighbors(vertex):
    #             v_b = np.random.choice(blocks[b])
    #         graph.add_edge(vertex, v_b)
    # in_edges = graph.get_out_edges(vertex)
    # for edge in in_edges:
    #     if random.random() < 0.5:
    #         graph.remove_edge(edge)
    #         b = np.random.choice(block_indices)
    #         while b == true_assignment[vertex]:
    #             b = np.random.choice(block_indices)
    #         v_b = np.random.choice(blocks[b])
    #         while v_b in graph.get_in_neighbors(vertex):
    #             v_b = np.random.choice(blocks[b])
    #         graph.add_edge(v_b, vertex)

for i in range(int(args.overlap * graph.num_edges())):
    if random.random() < args.blockbias:
        a, b = np.random.choice(block_indices[:args.biasblocks], 2, False)
    else:
        # block_probs = np.ones(num_blocks)
        # block_probs[0] = args.blockbias
        # block_probs[1] = args.blockbias
        # block_probs /= block_probs.sum()
        a, b = np.random.choice(block_indices, 2, False)  # , block_probs)
    # if random.random() < args.vertexbias:
    #     v_a = np.random.choice(blocks[a][:args.biasvertices])
    # else:
    v_a = np.random.choice(blocks[a])
    v_b = np.random.choice(blocks[b])
    while v_b in graph.get_out_neighbors(v_a):
        # if random.random() < args.vertexbias:
        #     v_a = np.random.choice(blocks[a][:args.biasvertices])
        # else:
        v_a = np.random.choice(blocks[a])
        v_b = np.random.choice(blocks[b])
    graph.add_edge(v_a, v_b)

# gt.remove_self_loops(g_sample)
# gt.remove_parallel_edges(g_sample)
#
# # remove (1-density) percent of the edges
# edge_filter = g_sample.new_edge_property('bool')
# edge_filter.a = stats.bernoulli.rvs(density, size=edge_filter.a.shape)
# # print("edge filter: ", edge_filter.a)
# g_sample.set_edge_filter(edge_filter)
# g_sample.purge_edges()
#
# # remove all island vertices
# print('Filtering out zero vertices...')
# degrees = g_sample.get_total_degrees(np.arange(g_sample.num_vertices()))
# vertex_filter = g_sample.new_vertex_property('bool', vals=degrees > 0.0)
# g_sample.set_vertex_filter(vertex_filter)
# g_sample.purge_vertices()
#
# # store the nodal block memberships in a vertex property
# block_membership_vector = block_membership_vector[degrees > 0.0]
# true_partition = block_membership_vector
# assert block_membership_vector.size == g_sample.num_vertices()
# block_membership = g_sample.new_vertex_property("int",
#                                                 vals=block_membership_vector)
#
# # compute and report basic statistics on the generated graph
# bg, bb, vcount, ecount, avp, aep = gt.condensation_graph(g_sample, block_membership, self_loops=True)
# edge_count_between_blocks = np.zeros((num_blocks, num_blocks))
# for e in bg.edges():
#     edge_count_between_blocks[bg.vertex_index[e.source()], bg.vertex_index[e.target()]] = ecount[e]
# num_within_block_edges = sum(edge_count_between_blocks.diagonal())
# num_between_block_edges = g_sample.num_edges() - num_within_block_edges
# print count statistics
# print('Number of nodes: {} expected {} filtered % {}'.format(
#       graph.num_vertices(), N, (N_adjusted - .num_vertices()) / N_adjusted))
# print('Number of edges: {} expected number of edges: {}'.format(
#     g_sample.num_edges(), expected_e))
print('Number of vertices: {0} number of edges: {1}'.format(graph.num_vertices(), graph.num_edges()))
degrees = graph.get_total_degrees(np.arange(graph.num_vertices()))
print('Vertex degrees: [{},{},{}]'.format(
    np.min(degrees), np.mean(degrees), np.max(degrees)))
unique_degrees, counts = np.unique(degrees, return_counts=True)
print("degrees: {}\ncounts: {}".format(unique_degrees[:20], counts[:20]))
print('Avg. Number of nodes per block: {}'.format(graph.num_vertices() / num_blocks))
# print('# Within-block edges / # Between-blocks edges: {}'.format(num_within_block_edges / num_between_block_edges))

if save_graph:  # output the graph and truth partition to TSV files with standard format
    # graph.save('{}.gt.bz2'.format(file_name))  # save graph-tool graph object
    # store edge list
    edge_list = np.zeros((graph.num_edges(), 3), dtype=int)
    # populate the edge list.
    counter = 0
    for e in graph.edges():  # iterate through all edges (edge list access is not available in all versions of graph-tool)
        edge_list[counter, 0] = int(e.source()) + 1;  # nodes are indexed starting at 1 in the standard format
        edge_list[counter, 1] = int(e.target()) + 1;  # nodes are indexed starting at 1 in the standard format
        edge_list[counter, 2] = 1;  # all edges are weighted equally at 1 in this generator
        counter += 1
    # write graph TSV file using pandas DataFrame
    df_graph = pd.DataFrame(edge_list)
    df_graph.to_csv('{}.tsv'.format(file_name), sep='\t', header=False, index=False)
    # write truth partition TSV file using pandas DataFrame; nodes and blocks are indexed starting at 1 in the standard format
    df_partition = pd.DataFrame(np.column_stack((np.arange(graph.num_vertices()) + 1, true_assignment + 1)))
    if graph.num_vertices() < 500:
        gt.graph_draw(graph, vertex_fill_color=graph.new_vertex_property("int", true_assignment), output="{}_view.png".format(file_name))
    df_partition.to_csv('{}_truePartition.tsv'.format(file_name), sep='\t', header=False, index=False)
    print("Graph saved to {}".format(file_name))


# print("this is a debug message")

def solution(N):
    alpha__dic = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
    response = ''
    # Implement your solution here
    if N <= 1:
        return 'a'
    string = 'a' * N

    for idx, i in enumerate(alpha__dic):

        count_len = len(alpha__dic)
        if idx == count_len -1:
            return string
        string_to_search = i * 2
        string_for_replace = alpha__dic[idx +1]
        # print(string_to_search)
        # print(string_for_replace)

        string = string.replace(string_to_search, string_for_replace)
    return string

print(solution(11))
print(solution(1))
print(solution(67108876))


from django.urls import path
from django.contrib.auth import views as auth_views
from django.views.generic import DetailView
from . import views

urlpatterns = [
    path('', views.Home, name='garage-home'),
    path('about/', views.About, name='garage-about'),
    path('service/', views.Service, name='garage-service'),
    path('history/<int:pk>', views.ServiceDetailView.as_view(), name='garage-history-detail'),
    path('print/<int:pk>', views.GeneratePDF.as_view(), name='print-pdf'),
    path('history/', views.History, name='garage-history'),
    path('login/', auth_views.LoginView.as_view(template_name='login.html'), name='garage-login'),
    path('logout/', auth_views.LogoutView.as_view(template_name='home.html'), name='garage-logout'),
    path('register/', views.Register, name='garage-register'),
    path('jobs/', views.JobListView.as_view(), name='garage-jobs'),
    path('jobs/<int:pk>', views.JobUpdateView.as_view(), name='garage-jobs-update'),
]


from modules.ObjectDetection.opencvdnn import do_object_detection as detect
import os

def obj_dection(path, network="MobileNet", dir=""):
    import requests
    if network == "MobileNet":
        prototxt = dir + "MobileNetSSD_deploy.prototxt.txt"
        model = dir + "MobileNetSSD_deploy.caffemodel"
    else:
        raise Exception("Network not provided")

    if not os.path.exists(prototxt):
        file_url = "http://media.liontao.xin/MobileNetSSD_deploy.prototxt.txt?attname=&e=1545901370&token=8D-fPY7fZfvNQ_YlcCHphmf-beQ7s5-ahx1C_WJ4:eJEMiBlqucJesL3efchu7cHW7gU"
        file_path = prototxt

        from contextlib import closing
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"}
        with closing(requests.get(file_url, headers=headers, stream=True)) as response:
            chunk_size = 100
            content_size = int(response.headers['content-length'])
            data_count = 0
            with open(file_path, "wb") as file:
                for data in response.iter_content(chunk_size=chunk_size):
                    file.write(data)
                    data_count = data_count + len(data)
                    now_jd = (data_count / content_size) * 100
                    print("\r Progress: {:.2f}% ({:d}/{:d}) - {}".format(now_jd, data_count, content_size, file_path),
                          end="")
            print("\r\n[INFO]Download Completed.")

    if not os.path.exists(model):
        file_url = "http://media.liontao.xin/MobileNetSSD_deploy.caffemodel?attname=&e=1545901361&token=8D-fPY7fZfvNQ_YlcCHphmf-beQ7s5-ahx1C_WJ4:8DDL7DJyP0qnQt4b-tHBx9OsHS4"
        file_path = model

        from contextlib import closing
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"}
        with closing(requests.get(file_url, headers=headers, stream=True)) as response:
            chunk_size = 1024
            content_size = int(response.headers['content-length'])
            data_count = 0
            with open(file_path, "wb") as file:
                for data in response.iter_content(chunk_size=chunk_size):
                    file.write(data)
                    data_count = data_count + len(data)
                    now_jd = (data_count / content_size) * 100
                    print("\r Progress: {:.2f}% ({:d}/{:d}) - {}".format(now_jd, data_count, content_size, file_path),
                          end="")
            print("\r\n[INFO]Download Completed.")

    if os.path.exists(path) and os.path.isfile(path) and os.path.isfile(prototxt) and os.path.isfile(model):
        image, category = detect(path, prototxt=prototxt, model=model)
        return image, category
    else:
        raise FileNotFoundError

if __name__ == '__main__':
    _, r = obj_dection(path="image.jpg")
    print(r)


from copy import copy
from typing import Optional

from common.constants import *

def get_document(id: str) -> Optional[dict]:
    return HTTP_CLIENT.get(
        f"{API_BASE_URL}/v1/documents/{id}",
        headers=API_HEADERS,
        params=API_BASE_PARAMS,
    )

def get_document_previews(id: str) -> Optional[dict]:
    return HTTP_CLIENT.get(
        f"{API_BASE_URL}/v1/documents/{id}/previewInfo",
        headers=API_HEADERS,
        params=API_BASE_PARAMS,
    )

def get_search(query: str) -> Optional[dict]:
    data = {
        "client": "ios",
        "client_id": API_CLIENT_ID,
        "client_secret": API_CLIENT_SECRET,
        "filters[type][]": ["document"],
        "limit": "20",
        "location[auto]": "1",
        "offset": "0",
        "query": query,
        "sort": "relevancy",
        "trigger": "ios_app",
        "view": "list_m",
    }
    response = HTTP_CLIENT.post(
        f"{API_BASE_URL}/v2/search/",
        headers=API_HEADERS,
        data=data,
    )
    if response.status_code == 200:
        return response.json()

def get_search_suggestions(query: str) -> Optional[dict]:
    params = copy(API_BASE_PARAMS)
    params["query"] = query
    response = HTTP_CLIENT.get(
        f"{API_BASE_URL}/v1/search/suggest",
        headers=API_HEADERS,
        params=params,
    )
    if response.status_code == 200:
        return response.json()


import math

def is_perfect_cube(n):
    c = int(n ** (1 / 3.))
    return (c ** 3 == n) or ((c + 1) ** 3 == n)

def isqrt(n):
    x = n
    y = (x + 1) // 2
    while y < x:
        x = y
        y = (x + n // x) // 2
    return x

my_setting = {'cycle': 0,
              'true': 0,
              'false': 0}

on_off = {'square': False,
          'cube': True}

range_number = {'x': 2,
                'y': 10}

my_list = []
for number in range(range_number['x'], range_number['y']):
    if number == 0:
        continue
    my_list.append(number)

my_setting['false'], my_setting['true'], my_setting['cycle'] = 0, 0, 0,
if on_off['square']:
    for a in my_list:
        for b in my_list:
            my_setting['cycle'] += 1
            c = a ** 2 + b ** 2
            if a ** 2 + b ** 2 == c and math.sqrt(c) == isqrt(c):
                print(a ** 2, '+', b ** 2, '=', c)
                print('Числа:', a, ',', b, ',', isqrt(c))
                my_setting['true'] += 1
            else:
                my_setting['false'] += 1
    print('Вывод: ')
    print('Успешных вариантов было обнаружено ', my_setting['true'])
    print('Не успешных вариантов было обнаружено ', my_setting['false'])
    print('Общее колличество вариантов было вопроизведено ', my_setting['cycle'])

if on_off['cube']:
    for a in my_list:
        for b in my_list:
            my_setting['cycle'] += 1
            c = a ** 3 + b ** 3
            if a ** 3 + b ** 3 == c and is_perfect_cube(c):
                print(a ** 3, '+', b ** 3, '=', c)
                print('Числа:', a, ',', b, ',', pow(c, 1 / 3))
                my_setting['true'] += 1
            else:
                my_setting['false'] += 1
    print('Вывод: ')
    print('Успешных вариантов было обнаружено ', my_setting['true'])
    print('Не успешных вариантов было обнаружено ', my_setting['false'])
    print('Общее колличество вариантов было вопроизведено ', my_setting['cycle'])


from ray.rllib.algorithms import ppo
from ray.rllib.env.env_context import EnvContext
import argparse
import os
#import yaml
import ruamel.yaml as yaml
import sys

print("Training automatically with Ray Tune")
#results = tune.run(args.run, config=config, stop=stop)

#tuner = tune.Tuner(
#    args.run, param_space=config, run_config=air.RunConfig(stop=stop)
#)
#results = tuner.fit()

#ray.shutdown()

import argparse
import os

from ray.rllib.utils.test_utils import check_learning_achieved
from helper_config import convert_yaml_into_readable_format, convert_runable_into_2_0_format, register_custom_env, \
    register_algorithm_from_config, register_custom_action_distribution, register_custom_model, update_GPU_resources, \
    set_experiment_name, check_for_non_config_callbacks, check_for_custom_callbacks, check_for_custom_eval_function, \
    check_for_constraint_amount_lambda_model

parser = argparse.ArgumentParser()
parser.add_argument(
    "--run", type=str, default="PPO", help="The RLlib-registered algorithm to use."
)
parser.add_argument("--num-cpus", type=int, default=0)
parser.add_argument(
    "--framework",
    choices=["tf", "tf2", "tfe", "torch"],
    default="torch",
    help="The DL framework specifier.",
)
parser.add_argument("--eager-tracing", action="store_true")
parser.add_argument("--use-prev-action", action="store_true")
parser.add_argument("--use-prev-reward", action="store_true")
parser.add_argument(
    "--as-test",
    action="store_true",
    help="Whether this script should be run as a test: --stop-reward must "
    "be achieved within --stop-timesteps AND --stop-iters.",
)
parser.add_argument(
    "--stop-iters", type=int, default=200, help="Number of iterations to train."
)
parser.add_argument(
    "--stop-timesteps", type=int, default=100000, help="Number of timesteps to train."
)
parser.add_argument(
    "--stop-reward", type=float, default=150.0, help="Reward at which we stop training."
)

if __name__ == "__main__":
    import ray
    from ray import air, tune

    #args = parser.parse_args()

    ray.init()#num_cpus=args.num_cpus or None)
    """
    configs = {
        "PPO": {
            "num_sgd_iter": 5,
            "model": {
                "vf_share_layers": True,
            },
            "vf_loss_coeff": 0.0001,
        },
        "IMPALA": {
            "num_workers": 2,
            "num_gpus": 0,
            "vf_loss_coeff": 0.01,
        },
    }

    config = dict(
        configs[args.run],
        **{
            "env": StatelessCartPole,
            # Use GPUs iff `RLLIB_NUM_GPUS` env var set to > 0.
            "num_gpus": int(os.environ.get("RLLIB_NUM_GPUS", "0")),
            "model": {
                "use_lstm": True,
                "lstm_cell_size": 256,
                "lstm_use_prev_action": args.use_prev_action,
                "lstm_use_prev_reward": args.use_prev_reward,
            },
            "framework": args.framework,
            # Run with tracing enabled for tfe/tf2?
            "eager_tracing": args.eager_tracing,
        }
    )

    stop = {
        "training_iteration": args.stop_iters,
        "timesteps_total": args.stop_timesteps,
        "episode_reward_mean": args.stop_reward,
    }

    # To run the Algorithm without ``Tuner.fit``, using our LSTM model and
    # manual state-in handling, do the following:

    # Example (use `config` from the above code):
    # >> import numpy as np
    # >> from ray.rllib.algorithms.ppo import PPO
    # >>
    # >> algo = PPO(config)
    # >> lstm_cell_size = config["model"]["lstm_cell_size"]
    # >> env = StatelessCartPole()
    # >> obs = env.reset()
    # >>
    # >> # range(2) b/c h- and c-states of the LSTM.
    # >> init_state = state = [
    # ..     np.zeros([lstm_cell_size], np.float32) for _ in range(2)
    # .. ]
    # >> prev_a = 0
    # >> prev_r = 0.0
    # >>
    # >> while True:
    # >>     a, state_out, _ = algo.compute_single_action(
    # ..         obs, state, prev_a, prev_r)
    # >>     obs, reward, done, _ = env.step(a)
    # >>     if done:
    # >>         obs = env.reset()
    # >>         state = init_state
    # >>         prev_a = 0
    # >>         prev_r = 0.0
    # >>     else:
    # >>         state = state_out
    # >>         prev_a = a
    # >>         prev_r = reward
    """ or None
    #print(config)

    if len(sys.argv) > 1:
        yaml_file_name = sys.argv[1]
    elif os.environ.get("YAML_FILE_NAME", None) is not None:
        yaml_file_name = os.environ.get("YAML_FILE_NAME", None)
    else:
        # yaml_file_name = "finance-ppo.yaml" # "custom-gridworld-riskppo.yaml"#"cartpole-ppo-test.yaml"  # "cartpole-ppo-test.yaml"
        # yaml_file_name = "finance-ppo-12.yaml"
        # yaml_file_name = "finance-ppo-2-working-12-12-21.yaml"
        # yaml_file_name = "finance-ppo-2-one-state.yaml"
        # yaml_file_name = "finance-ppo-penalty-state.yaml"
        #yaml_file_name = "finance-ppo-38.yaml"#"finance-ppo-36.yaml"#"finance-ppo-34.yaml"
        #yaml_file_name = "finance-ppo-36.yaml"
        #yaml_file_name = "cartpole-ddpg.yaml"

        #yaml_file_name = "finance-ddpg-4.yaml"
        #yaml_file_name = "finance-ppo-43.yaml"
        #yaml_file_name = "finance-ppo-47.yaml"
        #yaml_file_name = "finance-ppo-2-interval.yaml"
        #yaml_file_name = "pendulum-td3.yaml"
        #yaml_file_name = "pendulum-td3-custom.yaml"
        #yaml_file_name = "finance-td3-1.yaml"
        #yaml_file_name = "finance-ppo-57.yaml"
        #yaml_file_name = "finance-ppo-classic-1.yaml"
        #yaml_file_name = "finance-ddpg-1-interval.yaml"
        #yaml_file_name = "short-ppo-38.yaml"#"short-ppo-30.yaml"#"short-ppo-15.yaml"#"short-ppo-2.yaml"#"short-ppo-2.yaml"
        #yaml_file_name = "cartpole-stateless-lstm-2.yaml"
        #yaml_file_name = "short-ppo-155.yaml"#"short-ppo-141.yaml"#"short-ppo-101.yaml"#"short-ppo-90.yaml"#"short-ppo-85.yaml"#"short-ppo-85.yaml" #"short-ppo-69.yaml"#"short-ppo-53.yaml"#"short-ppo-51.yaml"#"short-ppo-49.yaml"#"short-ppo-44.yaml" #41 is working with custom_dirichlet distribution
        #yaml_file_name = "cartpole-stateless-lstm-1.yaml"
        #yaml_file_name = "ppo-autoreg-test-4.yaml"
        #yaml_file_name = "ppo-autoreg-test-6.yaml"
        #yaml_file_name = "ppo-autoreg-test-9.yaml"
        #yaml_file_name = "ppo-autoreg-test-12.yaml"
        #yaml_file_name = "ppo-autoreg-test-13.yaml"
        #yaml_file_name = "ppo-autoreg-const-20.yaml"
        #yaml_file_name = "ppo-autoreg-const-37.yaml"
        #yaml_file_name = "ppo-autoreg-const-40.yaml"
        #yaml_file_name = "ppo-autoreg-const-54.yaml"
        yaml_file_name = "ppo-autoreg-const-372.yaml"#"ppo-autoreg-const-354.yaml"#"ppo-autoreg-const-344.yaml"#"ppo-autoreg-const-155.yaml"

    print("RAY INIT")

    #yaml_file_name = "cartpole-stateless-framestacking.yaml"
    #yaml_file_name = "cartpole-stateless-lstm.yaml"
    #yaml_file_name = "cartpole-stateless-attention.yaml"

    with open(f"run_config/{yaml_file_name}", "r") as stream:
        try:
            run_config_raw = next(iter(yaml.safe_load(stream).values()))
        except yaml.YAMLError as exc:
            print(exc)

    run_name = yaml_file_name.replace(".yaml", "")

    PROJECT_NAME = "const_autoreg_2"
    print(run_config_raw)

    run_config_readable = convert_yaml_into_readable_format(run_config_input=run_config_raw)
    run_config_readable = register_custom_env(run_config_readable)
    run_config_readable = register_custom_action_distribution(run_config_readable)
    run_config_readable = register_algorithm_from_config(run_config_readable)
    run_config_readable = register_custom_model(run_config_readable)
    run_config_readable = check_for_constraint_amount_lambda_model(run_config_readable)
    run_config_readable = update_GPU_resources(run_config_readable)
    run_config_readable = check_for_custom_eval_function(run_config_readable)
    run_config_readable = check_for_custom_callbacks(run_config_readable)
    run_config_readable = check_for_non_config_callbacks(run_config_readable, group_name=run_name, project_name=PROJECT_NAME)
    run_config_readable = set_experiment_name(run_config_readable, run_name=run_name)

    print(run_config_readable)
    #must be last
    trainable, dict_param_space, dict_run_config = convert_runable_into_2_0_format(run_config_readable)

    #print(dict_run_config)

    #tuner = tune.Tuner(
    #    trainable=args.run, param_space=config, run_config=air.RunConfig(stop=stop, verbose=2)
    #)

    tuner = tune.Tuner(
        trainable=trainable, param_space=dict_param_space, run_config=air.RunConfig(**dict_run_config)
    )

    results = tuner.fit()

    ray.shutdown()


from flask import Flask, request, jsonify
from flask_cors import CORS

import logging

from custom_exceptions.reimbursement_exceptions import NegativeValueReimbursementRequestException, \
    NonNumericValueReimbursementRequestException, NonUpdatedStatusException
from custom_exceptions.user_exceptions import DuplicateCreateUserNameException, DuplicateUpdateUserNameException
from data_access_layer.implementation_classes.reimbursement_postgres_dao import ReimbursementPostgresDAO
from data_access_layer.implementation_classes.user_postgres_dao import UserPostgresDAO
from entities.reimbursement import Reimbursement
from entities.user import User
from service_layer.implementation_services.reimbursement_postgres_service import ReimbursementPostgresService
from service_layer.implementation_services.user_postgres_service import UserPostgresService

logging.basicConfig(filename="records.log", level=logging.DEBUG, format=f"%(asctime)s %(levelname)s %(message)s")
app: Flask = Flask(__name__)
CORS(app)

reimbursement_dao = ReimbursementPostgresDAO()
reimbursement_service = ReimbursementPostgresService(reimbursement_dao)
user_dao = UserPostgresDAO()
user_service = UserPostgresService(user_dao)

@app.get("/")
def landing_page():
    return "This is the landing page"

# Reimbursement
@app.post("/reimbursement")
def create_reimbursement():
    try:
        reimbursement_data = request.get_json()
        new_reimbursement = Reimbursement(
            0,
            int(reimbursement_data["userId"]),
            reimbursement_data["expenseName"],
            float(reimbursement_data["expenseAmount"]),
            reimbursement_data["expenseDetail"],
            reimbursement_data["status"],
            reimbursement_data["userComment"]
        )
        reimbursement_to_return = reimbursement_service.service_create_reimbursement(new_reimbursement)
        reimbursement_as_dictionary = reimbursement_to_return.create_reimbursement_dictionary()
        account_as_json = jsonify(reimbursement_as_dictionary)
        return account_as_json, 200
    except NegativeValueReimbursementRequestException as e:
        exception_dictionary = {"message": str(e)}
        exception_json = jsonify(exception_dictionary)
        return exception_json, 400
    except NonNumericValueReimbursementRequestException as e:
        exception_dictionary = {"message": str(e)}
        exception_json = jsonify(exception_dictionary)
        return exception_json, 400

@app.get("/reimbursement/<request_id>")
def get_reimbursements_by_request_id(request_id: str):
    result = reimbursement_service.service_get_reimbursements_by_request_id(int(request_id))
    result_as_dictionary = result.create_reimbursement_dictionary()
    account_as_json = jsonify(result_as_dictionary)
    return account_as_json

@app.get("/reimbursement/user/<user_id>")
def get_all_reimbursements_by_employee_id(user_id: str):
    reimbursements_as_reimbursements = reimbursement_service.service_get_all_reimbursements_by_employee_id(int(user_id))
    reimbursements_as_dictionary = []
    for reimbursements in reimbursements_as_reimbursements:
        dictionary_reimbursement = reimbursements.create_reimbursement_dictionary()
        reimbursements_as_dictionary.append(dictionary_reimbursement)
    return jsonify(reimbursements_as_dictionary)

@app.get("/reimbursement")
def get_all_reimbursements():
    reimbursements_as_reimbursements = reimbursement_service.service_get_all_reimbursements()
    reimbursements_as_dictionary = []
    for reimbursements in reimbursements_as_reimbursements:
        dictionary_reimbursement = reimbursements.create_reimbursement_dictionary()
        reimbursements_as_dictionary.append(dictionary_reimbursement)
    return jsonify(reimbursements_as_dictionary)

@app.patch("/reimbursement/<request_id>")
def update_reimbursement(request_id: str):
    try:
        body = request.get_json()
        update_info = Reimbursement(
            int(request_id),
            int(body["userId"]),
            body["expenseName"],
            float(body["expenseAmount"]),
            body["expenseDetail"],
            body["status"],
            body["userComment"]
        )
        updated_reimbursement = reimbursement_service.service_update_reimbursements_by_id(update_info)
        updated_reimbursement_as_dictionary = updated_reimbursement.create_reimbursement_dictionary()
        return jsonify(updated_reimbursement_as_dictionary), 200
    except NonUpdatedStatusException as e:
        error_message = {"errorMessage": str(e)}
        return jsonify(error_message), 400

@app.delete("/reimbursement/<request_id>")
def delete_reimbursement_by_request_id(request_id: str):
    result = reimbursement_service.service_delete_reimbursement_by_request_id(int(request_id))
    if result:
        return "Reimbursement with ID {} was deleted successfully".format(request_id)
    else:
        return "Something went wrong: Reimbursement with ID {} was not deleted".format(request_id)

# User
# LOGGING IN
@app.post("/login")
def login():
    body = request.get_json()
    login_credentials = (body["userName"], body["userPassword"], body["userRole"])
    validated = user_service.service_login_into_account(login_credentials[0], login_credentials[1], login_credentials[2])
    if validated:
        message = {"validated": True}
        return jsonify(message), 200
    else:
        message = {"validated": False}
        return jsonify(message), 400

@app.post("/user")
def create_user():
    try:
        body = request.get_json()
        new_user = User(
            body["firstName"],
            body["lastName"],
            body["userRole"],
            0,
            body["userName"],
            body["userPassword"]
        )
        created_user = user_service.service_create_user(new_user)
        created_user_as_dictionary = created_user.create_user_dictionary()
        return jsonify(created_user_as_dictionary), 200
    except DuplicateCreateUserNameException as e:
        error_message = {"errorMessage": str(e)}
        return jsonify(error_message), 400

@app.get("/user/<user_id>")
def get_user_by_id(user_id: str):
    user = user_service.service_get_user_by_id(int(user_id))
    user_as_dictionary = user.create_user_dictionary()
    return jsonify(user_as_dictionary), 200

@app.get("/user")
def get_all_user_by_id():
    users = user_service.service_get_all_user_by_id()
    users_as_dictionaries = []
    for user in users:
        dictionary_user = user.create_user_dictionary()
        users_as_dictionaries.append(dictionary_user)
    return jsonify(users_as_dictionaries), 200

@app.patch("/user/<user_id>")
def update_user(user_id: str):
    try:
        body = request.get_json()
        update_info = User(
            body["firstName"],
            body["lastName"],
            body["userRole"],
            int(user_id),
            body["userName"],
            body["userPassword"]
        )
        updated_user = user_service.service_update_user_information(update_info)
        updated_user_as_dictionary = updated_user.create_user_dictionary()
        return jsonify(updated_user_as_dictionary), 200
    except DuplicateUpdateUserNameException as e:
        return str(e), 400

@app.delete("/user/<user_id>")
def delete_user(user_id: str):
    result = user_service.service_delete_user_by_id(int(user_id))
    if result:
        return f"User with ID {user_id} was deleted successfully"
    else:
        return f"Something went wrong. User with ID {user_id} was not deleted"

app.run()


from sqlalchemy import engine_from_config
from settings import get_config_dict
from mapping import DBSession, PlanetOsmLine, PlanetOsmPolygon
from geojson import Feature, FeatureCollection, dump, dumps
from sqlalchemy.sql import func
import json

settings = get_config_dict()

engine = engine_from_config(settings, 'sqlalchemy.', echo=True)
planet_engine = engine_from_config(settings, 'osm.', echo=False)
DBSession.configure(binds={
    PlanetOsmLine:planet_engine,
    PlanetOsmPolygon:planet_engine
    })
ses = DBSession

def group(inputfile, outputfile):
    """This reads exported file from dataset.freeze

    Data consists of all the streets in Maribor grouped by streets and years
    Data looks like {"results": [ {"leto_odtujitve":string, "cnt":number,
    "tekst_odseka_ulice": ""}]}

    Output is JSON file with streets in first layer and years with counts in
    second: { "street name":{"year": number of occurences}}
    """

    d = defaultdict(lambda: defaultdict(int))
    maxSteals = 0
    with open(inputfile, "r") as f:
        json_data = json.load(f)
        for result in json_data["results"]:
            ulica = result["tekst_odseka_ulice"]
            leto = result["leto_odtujitve"]
            stevilo_kraj = result["cnt"]
            d[ulica][leto]=stevilo_kraj
            if stevilo_kraj > maxSteals:
                maxSteals = stevilo_kraj
        d["max_steals"] = maxSteals
    json.dump(d, open(outputfile, "w"))

def get_street_geometries(cache_file):
    """Gets distinct list of all street names from DB

    And for each of street those streets search for same named street in OSM DB

    If it is found geometry geojson part is saved in file based dict keyed as
    street name
    """
    found,missing = (0,0)
    with shelve.open(cache_file) as streets_geo_db:
        db = dataset.connect('sqlite:///kraje.db')
        streets = db.query('SELECT distinct(tekst_odseka_ulice) FROM kraje WHERE ' +
            'tekst_ceste_naselja == "MARIBOR"')
        for street in streets:
            street_name = street["tekst_odseka_ulice"]
            #Skips already inserted streets
            if street_name in streets_geo_db:
                continue
            geo_streets = PlanetOsmLine.get_street(street_name)
            geo = {
                    "type": "GeometryCollection",
                    "geometries": []
                    }
            name = None
            #Geometry collection of all the parts of street with same name in
            #OSM
            for geo_street in geo_streets:
                name = geo_street.name
                geo["geometries"].append(json.loads(geo_street.geodata));
            if (found+missing)%100 == 0:
                print ("O")
            elif (found+missing)%20 == 0:
                print (".")
            #Skips streets which weren't found in geo_streets
            if name is not None:
                streets_geo_db[street_name] = geo
                found +=1
            else:
                missing += 1
        print ("Found {}/{} {.2f}% streets".format(found, found+missing,
            found/(found+missing)*100))

if __name__ == "__main__":
    #from collections import defaultdict
    #group("./maribor_group.json", "./kraje_tmp.json")
    #import dataset
    import shelve
    cache_file = "./streets_maribor_geo"
    #get_street_geometries(cache_file)
    min_year = 2008
    max_year = 2014
    range_years = range(min_year, max_year+1)
    with shelve.open(cache_file) as streets_geo_db, \
            open("./kraje_tmp.json", "r") as city_grouped:
        data = json.load(city_grouped);
        max_steals = data["max_steals"]
        del data["max_steals"]
        features = []
        for street_name, years in data.items():
            geo = None
            if street_name in streets_geo_db:
                geo = streets_geo_db[street_name]
            else:
                continue
            prop = {'name': street_name}
            for year in range_years:
                if str(year) in years:
                    value = years[str(year)]/max_steals*8
                    value_normal = years[str(year)]
                else:
                    value = 0
                    value_normal = 0
                prop["{}_class".format(year)] = value
                prop[year] = value_normal
            print(prop)
            fet = Feature(geometry=geo, properties=prop)
            features.append(fet)
        vse = FeatureCollection(features)
        dump(vse, open("maribor_class.geojson", "w"))


# Honey
from collections import deque

bees = deque(int(x) for x in input().split())
nectars = deque(int(x) for x in input().split())
operation = deque(input().split())

function = {
    "*": lambda x, y: x * y,
    "/": lambda x, y: x / y,
    "-": lambda x, y: x - y,
    "+": lambda x, y: x + y,
}

honey = 0

while bees and nectars:
    bee = bees.popleft()
    nectar = nectars.pop()

    if nectar < bee:
        bees.appendleft(bee)
    elif nectar > bee:
        honey += abs(function[operation.popleft()](bee, nectar))

print(f"Total honey made: {honey}")

if bees:
    print(f"Bees left: {', '.join(str(x) for x in bees)}")
if nectars:
    print(f"Nectar left: {', '.join(str(x) for x in nectars)}")


import esp
import uctypes

def main():

    ROM = uctypes.bytearray_at(0x40200000, 16)
    fid = esp.flash_id()

    print("Flash ID: %x (Vendor: %x Device: %x)" % (fid, fid & 0xff, fid & 0xff00 | fid >> 16))

    print("Flash bootloader data:")
    SZ_MAP = {0: "512KB", 1: "256KB", 2: "1MB", 3: "2MB", 4: "4MB"}
    FREQ_MAP = {0: "40MHZ", 1: "26MHZ", 2: "20MHz", 0xf: "80MHz"}
    print("Byte @2: %02x" % ROM[2])
    print("Byte @3: %02x (Flash size: %s Flash freq: %s)" % (ROM[3], SZ_MAP.get(ROM[3] >> 4, "?"), FREQ_MAP.get(ROM[3] & 0xf)))

main()


from tkinter import *
from tkinter import ttk
import numpy as np

def homogenize(coords: list)-> list:
    for i in range(len(coords)):
        coords[i].append(1)
    return coords

def dehomogenize(coords:list)-> list:
    for i in range(len(coords)):
        coords[i][0] = coords[i][0] / coords[i][2]
        coords[i][1] = coords[i][1] / coords[i][2]
        del coords[i][2]

def gettranslation(tx:float, ty=float)-> list:
    return [[1, 0, 0], [0, 1, 0], [tx, ty, 1]]

def getrotation(deg:float)-> list:
    rad = np.radians(deg)
    return [[np.cos(rad), np.sin(rad), 0], [-np.sin(rad), np.cos(rad),0],[0, 0, 1]]

triangle = [[25, 50],[60, 75],[60, 25]]

window = Tk()
f = ttk.Frame()
f.pack()
window.columnconfigure(0,weight=1)
canvas = Canvas(window,relief = RAISED)
canvas.pack()
points = [20,20,20,200,100,200]
cnv = canvas.create_polygon(triangle,fill = "green")
print(gettranslation(50,50))
print(np.array(gettranslation(50,50)))
print(triangle)
homogenize(triangle)
print(triangle[0])
print(np.dot(triangle[0].gettra))

print(triangle)
print(homogenize(triangle))
print(getrotation(cnv))

window.mainloop()


import shutil
import tempfile
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import Client, TestCase, override_settings
from django.urls import reverse

from posts.models import Group, Post, Comment

User = get_user_model()

TEMP_MEDIA_ROOT = tempfile.mkdtemp(dir=settings.BASE_DIR)

@override_settings(MEDIA_ROOT=TEMP_MEDIA_ROOT)
class PostCreateEditFormTests(TestCase):
    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.user = User.objects.create_user(username='test_author')
        cls.group = Group.objects.create(
            title='TestGroup1',
            slug='TestGroup1',
            description='TestGroup1'
        )
        cls.test_post = Post.objects.create(
            text='Тест №0',
            group=cls.group,
            author=cls.user
        )
        cls.test_post_2 = Post.objects.create(
            text='Тест №0_1',
            group=cls.group,
            author=cls.user
        )
        cls.test_comment = Comment.objects.create(
            text='Тестовый комментарий №0 к тестовому посту',
            author=cls.user,
            post=cls.test_post
        )

    @classmethod
    def tearDownClass(cls):
        super().tearDownClass()
        shutil.rmtree(TEMP_MEDIA_ROOT, ignore_errors=True)

    def setUp(self):
        self.user_1_client = Client()
        self.user_1_client.force_login(PostCreateEditFormTests.user)

    def test_create_post(self):
        """
        Проверим формы создания поста.
        """
        post_count = Post.objects.count()
        form_data = {
            'text': 'Тест №1',
            'group': PostCreateEditFormTests.group.pk
        }
        response = self.user_1_client.post(
            reverse(
                'posts:post_create'
            ),
            data=form_data,
            follow=True
        )
        self.assertRedirects(
            response,
            reverse(
                'posts:profile',
                kwargs={'username': self.user}
            )
        )
        self.assertEqual(
            Post.objects.count(),
            post_count + 1
        )
        self.assertTrue(
            Post.objects.filter(
                text=form_data['text'],
                group=form_data['group'],
                author=PostCreateEditFormTests.user
            ).exists()
        )

    def test_edit_post(self):
        """
        Проверим формы редактирования поста.
        """
        post_count = Post.objects.count()
        form_data = {
            'text': 'Тест №2',
            'group': PostCreateEditFormTests.group.pk
        }
        response = self.user_1_client.post(
            reverse(
                'posts:post_edit',
                kwargs={'post_id': PostCreateEditFormTests.test_post.id}
            ),
            data=form_data,
            follow=True
        )
        self.assertRedirects(
            response,
            reverse(
                'posts:post_detail',
                kwargs={'post_id': PostCreateEditFormTests.test_post.id}
            )
        )
        self.assertEqual(
            Post.objects.count(),
            post_count
        )
        self.assertTrue(
            Post.objects.filter(
                text=form_data['text'],
                group=form_data['group'],
                author=PostCreateEditFormTests.user
            ).exists()
        )

    def test_image_form_context(self):
        """
        Проверим, что в базе данных создаётся
        корректный пост с картинкой.
        """
        post_count = Post.objects.count()
        small_gif = (
            b'\x47\x49\x46\x38\x39\x61\x02\x00'
            b'\x01\x00\x80\x00\x00\x00\x00\x00'
            b'\xFF\xFF\xFF\x21\xF9\x04\x00\x00'
            b'\x00\x00\x00\x2C\x00\x00\x00\x00'
            b'\x02\x00\x01\x00\x00\x02\x02\x0C'
            b'\x0A\x00\x3B'
        )
        uploaded = SimpleUploadedFile(
            name='small.gif',
            content=small_gif,
            content_type='image/gif'
        )
        form_data = {
            'text': 'Тест №3',
            'group': PostCreateEditFormTests.group.pk,
            'image': uploaded
        }
        self.user_1_client.post(
            reverse(
                'posts:post_create'
            ),
            data=form_data,
            follow=True
        )
        self.assertEqual(
            Post.objects.count(),
            post_count + 1
        )
        self.assertTrue(
            Post.objects.filter(
                text=form_data['text'],
                group=form_data['group'],
                author=PostCreateEditFormTests.user,
                image='posts/small.gif'
            ).exists()
        )

    def test_comment_create(self):
        """
        Проверим, что при что при создании комментария, он начинает
        отображаться на странице post_detail.
        """
        comment_count = Comment.objects.count()
        form_data = {
            'text': 'Тестовый комментарий №1 к тестовому посту',
        }
        self.user_1_client.post(
            reverse(
                'posts:add_comment',
                kwargs={'post_id': PostCreateEditFormTests.test_post.id}
            ),
            data=form_data,
            follow=False
        )
        self.assertEqual(comment_count + 1, Comment.objects.count())
        self.assertTrue(
            Comment.objects.filter(
                post=PostCreateEditFormTests.test_post,
                text=form_data['text'],
                author=PostCreateEditFormTests.user
            ).exists()
        )


from datetime import datetime, date, timedelta

di = date(2021,3,1)
df = date(2021,11,8)

T = df-di
print('total time:', T)    # 252 d = 8 m
print('event to event time:', T/4 - timedelta(days=7))  #  d = 2 m

T4 = T/4
for i in range(4):
    d = di+i*T4
    print(f"e{i}: {d}")


import tensorflow as tf

xx = [1, 2, 3]  # train data
y = [1, 2, 3]  # traget data

# 가중치, 균등분포로 랜덤하게 숫자를 만들기 위함
w = tf.Variable(tf.random_uniform([1], -1, 1))
b = tf.Variable(tf.random_uniform([1], -1, 1))
x = tf.placeholder(tf.float32)

x_test = [5, 7, 20]  # test data

# hypothesis 설정
hypothesis = w * x + b

# 오차를 계산하는 평균 제곱 오차 방법을 사용(경사 하강법에 사용하기 위해 계산)
cost = tf.reduce_mean(0.5 * (hypothesis - y) ** 2)  # cost function

# 옵티마이저 설정(학습 방법을 설정)
# 경사 하강법, w = w - a(d'E/d'w)     d'는 편미분을 뜻함
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)
# 학습률이 작을경우 움직이는 거리가 작기 때문에 최적의 점으로 찾는데 오래걸림
# 학습률이 클경우 움직이는 거리가 크기 때문에 최적의 점을 찾지 못하고 넘어가서 발산할 수 있다.

# 학습을 시작
train = optimizer.minimize(loss=cost)

sess = tf.Session()
sess.run(tf.global_variables_initializer())

# epoch 를 10번 수행
for i in range(10000):
    sess.run(train, feed_dict={x: xx})

print('w :', sess.run(w, feed_dict={x: xx}), 'b :',
      sess.run(b, feed_dict={x: xx}), 'cost :', sess.run(cost, feed_dict={x: xx}))

for i in x_test:
    print('x =', i, 'predict =', sess.run(w * i + b, feed_dict={x: xx}))

sess.close()


#!/usr/bin/env python3
import sys,math,copy

def orecost(produce,rlist):
    reactions=copy.deepcopy(rlist)
    ore= 0
    while len(produceList) != 0:
        request= None
        reqi= 0
        for i in range(len(produceList)):
            p= produceList[i]
            inLHS=False
            for r in reactions:
                for j in r[0]:
                    if j[1] == p[1]:
                        inLHS=True
                        break
                    if inLHS:
                        break
            if not inLHS:
                request=p
                reqi=i
                break
        if request == None:
            print ("Oh oh, we're in trouble")
        produceList.pop(reqi)
        (ingredients,i)=recipe(request,reactions)
        #print(ingredients,i)
        reactions.pop(i)
        for r in ingredients:
            if r[1] == 'ORE':
                ore+= r[0]
            else:
                found=False
                for p in produceList:
                    #print("Produce",p)
                    if p[1] == r[1]:
                        p[0]+= r[0]
                        found= True
                        break
                if not found:
                    produceList.append(r)

    return ore

def parseChem(string):
	parts=string.strip().split(" ")
	num=int(parts[0])
	return([num,parts[1]])

def recipe(request,reactions):
	ingredients=[]
	for i in range(len(reactions)):
		r= reactions[i]
		if r[1][1] == request[1]:
			amount= int(math.ceil(request[0]/r[1][0]))
			#print("Recipe selected",r,amount)
			for j in r[0]:
				ingredients.append([amount*j[0],j[1]])
			#print("Ingr",ingredients)
			return (ingredients,i)
	#print("Recipe incomplete", request,reactions)
	return []

fp= open("rgcinput.txt","r")
lines= fp.readlines()
fp.close()
reactions=[]
for l in lines:
	sides=l.split("=>")
	rhs=sides[1]
	lhs=sides[0]
	inputs=sides[0].split(", ")
	output=parseChem(rhs)
	allinp=[]
	for i in inputs:
		allinp.append(parseChem(i))
	reactions.append((allinp,output))
#print(reactions)

produceList=[[1,'FUEL']]
ore= orecost(produceList,reactions)

print("Part1",ore)

totore=1000000000000
initguess= int(totore/ore)

lb= initguess
ub= initguess*2
print(lb,ub)
#crude binary search
while True:
    step= int((ub-lb)/2)
    #print(step,ub,lb)
    if step == 0:
        break
    produceList=[[lb+step,'FUEL']]
    ore= orecost(produceList,reactions)
    if (ore > totore):
        ub= lb+step
    elif (ore == totore):
        lb= lb+step
        ub= lb+step
        break
    else:
        lb= lb+step
print ("Part2",lb)


import warnings

import joblib
from django.shortcuts import render

from .forms import TextForm

warnings.filterwarnings('ignore')
import re

import joblib
import scipy
import torch
from torch.utils.data import Dataset

TOKEN_RE = re.compile(r'[\w\d]+')

def tokenize_text_simple_regex(txt, min_token_size=4):
    txt = txt.lower()
    all_tokens = TOKEN_RE.findall(txt)
    return [token for token in all_tokens if len(token) >= min_token_size]

def character_tokenize(txt):
    return list(txt)

def tokenize_corpus(texts, tokenizer=tokenize_text_simple_regex, **tokenizer_kwargs):
    return [tokenizer(text, **tokenizer_kwargs) for text in texts]

def vectorize_texts(tokenized_texts, word2id, word2freq, mode='tfidf', scale=True):
    assert mode in {'tfidf', 'idf', 'tf', 'bin'}

    result = scipy.sparse.dok_matrix((len(tokenized_texts), len(word2id)), dtype='float32')
    for text_i, text in enumerate(tokenized_texts):
        for token in text:
            if token in word2id:
                result[text_i, word2id[token]] += 1

    if mode == 'bin':
        result = (result > 0).astype('float32')

    elif mode == 'tf':
        result = result.tocsr()
        result = result.multiply(1 / result.sum(1))

    elif mode == 'idf':
        result = (result > 0).astype('float32').multiply(1 / word2freq)

    elif mode == 'tfidf':
        result = result.tocsr()
        result = result.multiply(1 / result.sum(1))
        result = result.multiply(1 / word2freq)

    if scale:
        result = result.tocsc()
        result -= result.min()
        result /= (result.max() + 1e-6)

    return result.tocsr()

class SparseFeaturesDataset(Dataset):
    def __init__(self, features):
        self.features = features

    def call(self):
        return torch.from_numpy(self.features.toarray()).float()

VECTORIZATION_MODE = 'tfidf'
model = joblib.load("model.pkl")
dataset = joblib.load("test_dataset.pkl")
vocabulary = joblib.load("vocabulary.pkl")
word_doc_freq = joblib.load("word_doc_freq.pkl")
new_model = joblib.load("model_new.pkl")

def basic(request):
    form = TextForm(request.GET)
    text = request.GET.get('text')
    if text:
        text = [tokenize_text_simple_regex(text)]
        text = vectorize_texts(text, vocabulary, word_doc_freq, mode=VECTORIZATION_MODE)
        object = SparseFeaturesDataset(text).call()
        prediction = int(model(object).argmax())
        from_0_to_10 = int(new_model(object).argmax())
    else:
        prediction = 'пока нет предсказаний'
        from_0_to_10 = 'пока нет предсказаний'
    context = {
        'form': form,
        'prediction': prediction,
        'from_0_to_10': from_0_to_10,
    }
    return render(request, 'form.html', context)


def rec(h):
    stack = list()
    ma, i = 0, 0
    while i < len(h):
        if (len(stack) == 0) or (h[stack[-1]] <= h[i]):
            stack.append(i)
            i += 1
        else:
            t_stack = stack.pop()
            pow = (h[t_stack] * ((i - stack[-1] - 1) if len(stack) != 0 else i))
            ma = max(ma, pow)

    while len(stack) != 0:
        t_stack = stack.pop()
        pow = (h[t_stack] * ((i - stack[-1] - 1) if len(stack) != 0 else i))
        ma = max(ma, pow)
    return ma

n = int(input())
wy = []
for i in range(n):
    wy.append(int(input()))

print(rec(wy))


from langchain.agents import Tool
from langchain.chains import RetrievalQA
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.llms import OpenAI
from langchain.text_splitter import CharacterTextSplitter
from langchain.vectorstores import Chroma

def setup_knowledge_base(product_catalog: str = None):
    """
    We assume that the product catalog is simply a text string.
    """
    # load product catalog
    with open(product_catalog, "r") as f:
        product_catalog = f.read()

    text_splitter = CharacterTextSplitter(chunk_size=10, chunk_overlap=0)
    texts = text_splitter.split_text(product_catalog)

    llm = OpenAI(temperature=0)
    embeddings = OpenAIEmbeddings()
    docsearch = Chroma.from_texts(
        texts, embeddings, collection_name="product-knowledge-base"
    )

    knowledge_base = RetrievalQA.from_chain_type(
        llm=llm, chain_type="stuff", retriever=docsearch.as_retriever()
    )
    return knowledge_base

def get_tools(knowledge_base):
    # we only use one tool for now, but this is highly extensible!
    tools = [
        Tool(
            name="ProductSearch",
            func=knowledge_base.run,
            description="useful for when you need to answer questions about product information",
        )
    ]

    return tools


"""
This is how you want to use the logging module in a small script.

NOTES:
- if you don"t configure logging through other means, or call
"basicConfig" you will get warnings when you try to log (no handlers).
- if you dont pass the "level" parameter to "basicConfig" you
will get the default level which is WARNING (pretty good).
- don"t do "logger.setLevel". This is contrary to logging philosophy.
"""

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

logger.debug("before")
logger.info("before")
logger.warning("before")
logger.error("before")

# logging.basicConfig(level=logging.WARNING)
logging.basicConfig()

logger.debug("after")
logger.info("after")
logger.warning("after")
logger.error("after")


import numpy as np, pandas as pd

class MassMedia():
    def __init__(self, c, p,  s,id, n=100):
        self.c = c
        self.p = p
        self.id = id
        self.audience = np.random.choice(np.arange(n), int(np.floor(n*s)), replace = False).tolist()
        #self.meta = {"c{}p{}s{}".format(str(c).strip("."), str(p).strip("."), str(s).strip(".")): self.audience}

    def media_message(self, d = .25):
        #d = .3
        if np.random.rand() < self.p:
            v = self.c + d*(np.random.rand()*2 -1)
            post = pd.DataFrame({"original_poster": [self.id], "rt_poster": [self.id], "content": [v], "rt_status":[False]})
            return post
        else:
            return None
#MassMedia(0, .5, .6,  "test", 100 ).audience


#%%
def convertnum(romnum):
    x = 0
    for num in romnum:
        if(num == "X"):
            x += 10
        elif(num == "V"):
            x += 5
        elif(num == "I"):
            if(romnum[-1] == "V" or romnum[-1] == "X"):
                x -= 1
            else:
                x += 1
        else:
            x = "invalid"
    return print(x)

#%%
def convertrom(num):
    y = ""
    if(num >= 10):
        y += int(num/10)*"X"
    if(9 > num%10 >= 5):
        y += "V"
    if(num%10 == 9):
        y += "IX"
    if(num%10 == 4):
        y += "IV"
    if(num%5 != 0 and num%5 != 4):
        y += num%5*"I"
    return print(y)

School_work1/Roman and Arabic numerals.py


# 守护线程
# 守护线程，程序结束时，线程跟着结束

import threading
import time
import sys

def install():
    print("开始安装")
    time.sleep(10)
    print()
    print("安装完成")

def until():
    while True:
        sys.stdout.write("###")
        time.sleep(0.5)
        sys.stdout.flush()

t_install = threading.Thread(target=install)
t_install.start()
time.sleep(0.01)
t_until = threading.Thread(target=until, daemon=True) # 开启守护线程
t_until.start()


import logging
import time
from typing import Dict

import pika

def rabbit_mq_heartbeat():
    while True:
        try:
            connection = pika.BlockingConnection(
                pika.ConnectionParameters(host="rabbitmq")
            )
            return connection
        except pika.exceptions.AMQPConnectionError:
            print("AMQPConnectionError trying again")
            time.sleep(5)
            continue

class MessageQueue:
    """
    Class to configure message queue
    """

    def __init__(self) -> None:
        self.connection = rabbit_mq_heartbeat()

    def publish(self, payload: Dict) -> Dict:
        logging.info("Connected to rabbitmq server......")
        channel = self.connection.channel()
        channel.queue_declare(queue="checkin_queue", durable=True)
        channel.basic_publish(
            exchange="",
            routing_key="checkin_queue",
            body=payload,
            properties=pika.BasicProperties(
                delivery_mode=2,  # make message persistent
            ),
        )


from collections import deque

#Start(sx, sy)から各頂点への最短距離を求める

def bfs(sx, sy):
    cnt = 0
    f_inf = float('inf')
    dist = [[f_inf] * m for _ in range(n)]

    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]

    #Start地点を0にする
    que = deque([])
    que.append((sx, sy))
    dist[sx][sy] = 0

    while que:
        p = que.popleft()

        for i in range(4):
            #移動した点を(nx, ny)とする
            nx = p[0] + dx[i]
            ny = p[1] + dy[i]

            #移動可能かと既に訪れたかの判定
            #dist[nx][ny] != f_infなら既に訪れた
            if n > nx >= 0 and \
               m > ny >= 0 and \
               s[nx][ny] != '#' and \
               dist[nx][ny] == f_inf:
                que.append((nx, ny))
                dist[nx][ny] = dist[p[0]][p[1]] + 1
                cnt = dist[nx][ny]

    return cnt

n, m = map(int, input().split())
s = [input() for _ in range(n)]

ans = 0
for i in range(n):
    for j in range(m):
        if s[i][j] == '#':
            continue
        ans = max(ans, bfs(i, j))
print(ans)

#n = 3
#m = 5
#s =['...#.', '.#.#.', '.#...']


"""2563 색종이"""

def paper_init(width: int = 100, height: int = 100) -> list:
    return [[0] * (width + 1) for _ in range(height + 1)]

def glue_paper(n: int) -> list:
    paper = paper_init()
    for _ in range(n):
        x, y = map(int, input().split())
        for i in range(y, y + 10):
            for j in range(x, x + 10):
                if paper[i][j] == 0:
                    paper[i][j] = 1
    return paper

def colored_paper(n: int) -> int:
    area, paper = 0, glue_paper(n)
    for p in paper:
        area += sum(p)
    return area

if __name__ == "__main__":
    print(colored_paper(int(input())))


import random

MAX_DEPTH = 1

def think(state, quip):

	moves = state.get_moves()

	best_move = moves[0]
	best_expecation = float('-inf')

	me = state.get_whos_turn()

	def outcome(score):
		if me == 'red':
			return score['red'] - score['blue']
		else:
			return score['blue'] - score['red']

	for move in moves:

		total_score = 0.0

		greedy_state = state.copy()

		greedy_state.apply_move(move)

		total_score += outcome(greedy_state.get_score())

		expectation = float(total_score)

		if expectation > best_expecation:
			best_expecation = expectation
			best_move = move

	#print "Picking %s with expected score %f" % (str(best_move), best_expecation)
	return best_move


project = ''
copyright = '2022, Oscar Cortez'
author = 'Oscar Cortez'
release = ''

extensions = [
    'sphinx_mdinclude',
]
html_theme_options = {
    "sidebar_hide_name": True,
}
html_static_path = ['_static']
html_css_files = [
    'css/custom.css',
]
html_theme = 'furo'


from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from helpers import render_to_json, jsonResponse
from django.forms.models import modelformset_factory
from django.template import RequestContext
from models import PaymentRequest

@login_required
@render_to_json
def get(req, payment_request_id):
    if payment_request_id:
        payment_request = PaymentRequest.objects.get(id=payment_request_id)
        return payment_request.serialize()
    else:
        return [payment_request.serialize()
                for payment_request in PaymentRequest.objects.all()]

@login_required
def create(req):
    PaymentRequestFormSet = modelformset_factory(PaymentRequest)
    if req.method == 'POST':
        formset = PaymentRequestFormSet(req.POST)
        if formset.is_valid():
            payment_request = formset.save()
            # do something.
            return jsonResponse(payment_request[0].serialize())
    else:
        formset = PaymentRequestFormSet(queryset=PaymentRequest.objects.none())
    return render_to_response("payment_request.html",
            {"formset": formset},
            context_instance=RequestContext(req))

@login_required
@render_to_json
def update(req, payment_request_id):
    pass

@login_required
@render_to_json
def delete(req, payment_request_id):
    PaymentRequest.objects.get(id=payment_request_id).delete()
    return {'success': True}


def merge_the_tools(string, k):
    for a in range(0,string,k):
        store= string[i,i+k]

def removeDuplicate(str, n):

    # Used as index in the modified string
    index = 0

    # Traverse through all characters
    for i in range(0, n):

        # Check if str[i] is present before it
        for j in range(0, i + 1):
            if (str[i] == str[j]):
                break

        # If not present, then add it to
        # result.
        if (j == i):
            str[index] = str[i]
            index += 1

    return "".join(str[:index])

if __name__ == '__main__':
    string, k = input(), int(input())
    merge_the_tools(string, k)


def queen(level=0):
    global ans
    if level == N:
        ans += 1
        return
    for n in range(N):
        for y,x in xy:
            if x == n or abs(x-n) == abs(y-level):
                break
        else:
            xy.append((level,n))
            queen(level+1)
            xy.pop()

N = int(input())

ans = 0
xy = []
queen()
print(ans)


from django.conf import settings
import requests

class StackOverflowMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        return self.get_response(request)

    def process_exception(self, request, exception):
        if settings.DEBUG:
            error = '{}: {}'.format(exception.__class__.__name__, exception)
            print(error)

            url = 'https://api.stackexchange.com/2.2/search'
            headers = { 'User-Agent': 'github.com/vitorfs/seot' }
            params = {
                'order': 'desc',
                'sort': 'votes',
                'site': 'stackoverflow',
                'pagesize': 3,
                'tagged': 'python;django',
                'intitle': error
            }

            r = requests.get(url=url, params=params, headers=headers)
            questions = r.json()

            print('')

            for question in questions['items']:
                print(question['title'])
                print(question['link'])
                print('')

        return None


'''
@author: Merijn de Bakker, Utrecht University 2016

Module helper contains helper functions used in the mapalgebra module.
'''
import numpy as np
import math
import types
import matplotlib.pyplot as plt
import os
import random

def create_domain(dom, f, phen_name, pset_name, p_name):

    #get a list with item ids
    item_ids = f.item_ids(phen_name, pset_name)

    #check whether the property is a field
    ps_is_field = is_field(f, phen_name, pset_name)

    #iterator counter
    counter = 0

    if ps_is_field:
        spatial_extent = np.asarray(f.get_spatial_extent_pset(phen_name,
                  pset_name))

        for i in item_ids:
            dom.set_as_current_domain_for_id(i, spatial_extent)
            counter += 1

    else:
        locations = f.get_locations(phen_name, pset_name, p_name)

        for i in item_ids:
            [locations[counter][0], locations[counter][1]]
            dom.set_as_current_domain_for_id(i, np.asarray(
                       [locations[counter][0], locations[counter][1]]))
            counter += 1

    return dom

def create_value(v, f, phen_name, pset_name, p_name):

    # get a list with item ids
    item_ids = f.item_ids(phen_name, pset_name)

    # iterator counter
    counter = 0

    retrieved_data = f.get_property_value(phen_name, pset_name, p_name).astype(
               float)

    if is_field(f, phen_name, pset_name):
        for i in item_ids:
            v.set_as_current_value_for_id(i, retrieved_data)
            counter += 1
    else:
        for i in item_ids:
            v.set_as_current_value_for_id(i, np.asarray(
                        [retrieved_data[counter]]))
            counter += 1

    return v

def get_datatype(val):
    if val.get_current_value_for_id(0).ndim >= 2:
        return datatypes.field
    else:
        return datatypes.agent

def is_field(f, phen_name, pset_name):

    p_list = f.list_property_sets_prop(phen_name, pset_name)

    return f.is_field(phen_name, pset_name, p_list[0])

def get_cell_at_loc(cells_domain, cells_discretization, location):
    x_min, y_min, x_max, y_max = cells_domain
    x_coord = location[0]
    y_coord = location[1]
    west = x_min
    north = y_max
    cell_size = get_cellsize(x_max, x_min, cells_discretization[0])

    x_col = (x_coord - west) / cell_size
    y_row = (north - y_coord) / cell_size

    row_idx = int(math.floor(y_row))
    col_idx = int(math.floor(x_col))

    nr_rows = int(math.floor((y_max - y_min) / cell_size))
    nr_cols = int(math.floor((x_max - x_min) / cell_size))

    if (col_idx + 1) > nr_cols or (col_idx) <= 0:
        msg = "Column index ({0}) out of range (from 1 to {1}))".format(
                    col_idx + 1, nr_cols)
        raise ValueError(msg)

    if (row_idx + 1) > nr_rows or (row_idx) <= 0:
        msg = "Row index ({0}) out of range (from 1 to {1})".format(
                    row_idx + 1, nr_rows)
        raise ValueError(msg)

    return row_idx, col_idx

def get_cell_value_at_location(cells, cells_domain, cells_discretization,
                               location):

    row_idx, col_idx = get_cell_at_loc(cells_domain, cells_discretization,
                                       location)

    return [row_idx, col_idx, cells[row_idx, col_idx]]

def get_new_random_loc(current_x, current_y, sigma):
    return [random.normalvariate(current_x, sigma),
                    random.normalvariate(current_y, sigma)]

# assumes square cells
def get_cellsize(x_max, x_min, nr_cols):

    return (x_max - x_min) / nr_cols

def create3Darray(data):
    if data.ndim == 1:
        data = np.expand_dims(data, 2)

    return np.expand_dims(data, 3)

class datatypes:
    scalar_types = (types.IntType, types.LongType, types.FloatType,
                    types.ListType, np.ndarray)
    field, agent = range(2)

    @staticmethod
    def get_type_string(phenomenon):
        if phenomenon == datatypes.field:
            return 'Raster'
        if phenomenon == datatypes.agent:
            return 'Agent'
        else:
            return ''

def transform(values):
    nr_rows = 100  # 6
    nr_cols = 100  # 4
    cellsize = 25
    """ Transforms x,y PCRaster coordindates to plot canvas coordinates """
    xfac = nr_cols / float(nr_cols * cellsize)
    yfac = nr_rows / float(nr_rows * cellsize)

    x = values[0] * xfac - 0.5
    y = -1.0 * values[1] * yfac - 0.5

    return x, y

def make_png(field, agents, timestep):
    plt.rcParams.update({'font.size': 22})
    plt.figure(figsize=(8, 8), dpi=80)
    plt.imshow(field, interpolation="none",
               extent=[0, 100, 100, 0], origin='upper',
               cmap=plt.get_cmap("Greens"), label='biomass')
    plt.title("timestep {0}".format(timestep))

    plt.colorbar(shrink=0.7)

    locs = []
    for a in agents:
        locs.append(transform(a))
    x, y = zip(*locs)

    plt.plot(x, y, 'ro', color='red', markersize=4, label='cows')
    plt.ylim(len(field), 0)

    # min/max biomass values...
    plt.clim(0, 20)

    plt.xticks([])
    plt.yticks([])

    plt.legend(loc='upper right')

    plt.savefig(os.path.join("../data/model_t{:05d}.png".format(timestep)),
                transparent=False, bbox_inches='tight')
    plt.close()


# -*- coding: utf-8 -*-

import mock
from completor import Completor, load_completer, get

class HelloCompleter(Completor):
    filetype = 'hello'

def test_disabled(vim_mod):
    com = HelloCompleter()
    vim_mod.vars = {'completor_disable_hello': 1}
    assert com.disabled
    vim_mod.vars = {'completor_disable_hello': [b'hello']}
    com.ft = 'hello'
    assert com.disabled
    vim_mod.vars = {}
    assert not com.disabled

def test_load(vim_mod, monkeypatch):
    vim_mod.eval = mock.Mock(return_value={})
    vim_mod.vars = {
        'completor_filetype_map': {
            b'python.django': b'python'
        }
    }
    assert get('python') is None
    c = load_completer(b'python', b'os.')
    assert c.input_data == 'os.'
    assert get('python') is c

    c = load_completer(b'python', b'#')
    assert c is get('common')

    c = load_completer(b'python.django', b'os.')
    assert c is get('python')

    vim_mod.current.buffer.options.update({
        'omnifunc': b'csscomplete#CompleteCSS'})
    vim_mod.vars = {
        'completor_css_omni_trigger': br'([\w-]+|@[\w-]*|[\w-]+:\s*[\w-]*)$'
    }
    assert load_completer(b'css', b'text') is get('omni')

def test_parse_config():
    h = HelloCompleter()
    args = h.parse_config('tests/test_config')
    assert args == ['-I/home/hello', '-x', '--std=c11', '-hello=world',
                    'abcd', '-a', '123']
    args = h.parse_config(['tests/invalid', 'tests/args',
                           'tests/tests_config'])
    assert args == ['-x', 'c', '-D/usr/lib/', '123']


# {"name":"%s","x":%f,"y":%f,"w":%f,"h":%f}
import json
import base64
import wget
import zipfile
from pyiotown import post
import os

num = 0
category = {}
annodict = {}
def make_label(file_name, label, bbox):
    img_file = open("./upload_data/coco2017/train2017/" + file_name , 'rb')
    message = '{"image":"'
    message += base64.b64encode(img_file.read()).decode('UTF-8')
    img_file.close()
    message += '","type":"jpg","labels":['
    first = True
    for box in bbox:
        if first:
            first = False
        else:
            message += ','
        message += '{"name":"%s","x":%f,"y":%f,"w":%f,"h":%f}' % (label,box[0],box[1],box[2],box[3])
    message += ']}'
    return message

def sendToIoTown(json_data, url, token, label):
    global category, annodict, num
    #init category
    for cat in json_data['categories']:
        category[cat['name']] = cat['id']
    if label not in category:
        print("coco 2017 has no label [",label,"]")
        exit()

    #Save Annotation Dictionary
    for anno in json_data['annotations']:
        if anno['iscrowd'] == 1:
            continue
        if category[label] == anno['category_id']:
            image_id = anno['image_id']
            if (image_id not in annodict):
                annodict[image_id] = []
                annodict[image_id].append(anno)
            else:
                annodict[image_id].append(anno)
    print(len(annodict.keys()), "images will be uploaded")
    for image in json_data['images']:
        file_name = image['file_name']
        width = image['width']
        height = image['height']
        image_id = image['id']
        if (image_id not in annodict):
            continue
        annolist = annodict[image_id]
        bbox = []
        for anno in annolist:
            x = ( float(anno['bbox'][0]) + ( float(anno['bbox'][2]) / 2) ) / width
            y = ( float(anno['bbox'][1]) + ( float(anno['bbox'][3]) / 2) ) / height
            w = float(anno['bbox'][2]) / width
            h = float(anno['bbox'][3]) / height
            bbox.append([x,y,w,h])
        payload = make_label(file_name, label, bbox)
        r = post.uploadImage(url, token, payload)
        if r:
            num += 1
            print("Upload Success ./upload_data/coco2017/train2017/%s" % file_name)
        else:
            print("Upload Fail.")

def upload_dataset(url, token, label):
    print("Coco Dataset 2017 Image Download")
    download_url = ["http://images.cocodataset.org/zips/train2017.zip"]
    tar_url = ["./upload_data/train2017.zip"]
    for down_url in download_url:
        if not os.path.isfile("./upload_data/train2017.zip"):
            wget.download(down_url, out="./upload_data/")
        else:
            print(down_url,"is already exist!")
    print("\n Downloaded OK. Unzip Dataset....")
    for tarURL in tar_url:
        zip_ref = zipfile.ZipFile(tarURL, 'r')
        zip_ref.extractall("./upload_data/coco2017/")
        zip_ref.close()
    print("extract OK.")
    print("Coco Dataset 2017 Annotation Download")
    if not os.path.isfile("./upload_data/annotations_trainval2017.zip"):
        wget.download("http://images.cocodataset.org/annotations/annotations_trainval2017.zip", out="./upload_data/")
    else:
        print("annotation already exist!")
    print("\n download OK. Unzip Annotation...")
    zip_ref = zipfile.ZipFile("./upload_data/annotations_trainval2017.zip", 'r')
    zip_ref.extractall("./upload_data/coco2017/")
    zip_ref.close()
    with open("./upload_data/coco2017/annotations/instances_train2017.json", 'r') as f:
        json_data = json.load(f)
        sendToIoTown(json_data, url, token, label)
    print("total",num,"file upload ok")


from game import *
from player import Player
from enemy import Enemy
import os

os.environ['SDL_VIDEO_CENTERED'] = '1'
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
game = Game(pause=True, screen_display=screen)
playerObj = Player(screen)
timer = pygame.time.Clock()

while game.running:
    timer.tick(FPS)
    screen.fill('black')

    # Event Handling
    pressed = pygame.key.get_pressed()
    if not game.pause:
        playerObj.check_pressed(pressed)
    else:
        if pressed[pygame.K_SPACE]:
            # Restart game
            playerObj = Player(screen)
            game = Game(pause=False, screen_display=screen, sound=game.sound)

    for event in pygame.event.get():
        if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
            game.running = False
        if event.type == pygame.KEYUP and event.key == pygame.K_s:
            game.toggle_sound()
        if event.type == pygame.KEYUP and game.pause is False:
            playerObj.check_keyup(event.key)

    game.display_info()

    if game.pause:
        continue

    # Generate enemies
    if len(game.enemy_list) < game.enemy_count:
        enemy = Enemy(speed=5, size=game.enemy_size)
        game.enemy_list.append(enemy.generate_enemy())
        game.points += 1
        game.enemy_size = max(game.points // 2, 3)
    game.move_enemies()
    enemy_hitboxes = game.draw_enemies(screen)

    # Move Player
    playerObj.move_player()
    playerObj.draw_player(screen)

    pygame.display.flip()

    # Check for collusions
    if playerObj.collide_enemies(enemy_hitboxes):
        if game.sound:
            pygame.mixer.Sound.play(game.crash_sound)
            pygame.mixer.music.stop()
        game.check_highscore()
        game.pause = True

pygame.quit()


# -*- coding:UTF-8 -*-
import requests
import json

class DoubanSpider():
    def __init__(self):
        self.url = {
            "url_temp": "https://m.douban.com/rexxar/api/v2/subject_collection/tv_domestic/items?&start={}&count=18&loc_id=108288",

            "country": "us"}
        self.headers = {"Referer": "https://m.douban.com/tv/chinese",

                        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"

                        }

    def parse_url(self, url):  # 发送请求，获取响应
        print(url)
        response = requests.get(url, headers=self.headers)
        return response.content.decode()

    def get_content_list(self, json_str):  # 提取数据

        dict_ret = json.loads(json_str)  # 转化为python字典对象
        content_list = dict_ret["subject_collection_items"]  # 通过字典的键得到相应的值，从而获取页面数据列表

        for a in content_list:
            print(a['title'])
        return content_list

    def save_content_list(self, content_list, country):  # 保存数据
        for content in content_list:
            with open('douban_my.txt', 'a', encoding='UTF-8') as f:
                content["country"] = country
                f.write(json.dumps(content, ensure_ascii=False))
                f.write('\n')
        print('保存成功')

    def run(self):  # 实现主要逻辑
        num = 0
        while True:
            # 1、获取第一页url
            start_url = self.url["url_temp"].format(num)
            # 2、发送请求，获取响应
            json_str = self.parse_url(start_url)
            # 3、提取数据
            content_list = self.get_content_list(json_str)
            # # 4、保存
            #self.save_content_list(content_list, self.url["country"])
            # 5、获取第二页url
            if len(content_list) < 18:  # 判断是否到了最后一页
                break
            num += 18

if __name__ == '__main__':
    doubanspider = DoubanSpider()
    doubanspider.run()


# Source: https://pymotw.com/2/socket/udp.html
import json
import socket, sys, time, random

host = sys.argv[1]
textport = sys.argv[2]
n = 10
a = 0
x = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
port = int(textport)
server_address = (host, port)

while n is not 0:
    # Convert dict to json
    if n is not 10:
        x['age'] = x['age'] + 1
    y = json.dumps(x)
    print ("Sending " + y)
    s.sendto(y.encode('utf-8'), server_address)
    n -= 1

s.shutdown(1)


import xarray as xr
from metpy.units import units
import metpy.calc as mpcalc
import numpy as np

def mask_below_terrain(spres,data,levs):
    '''
    Given a surface pressure, return data only above that pressure.

    Needs spres, a surface pressure (float)
    Needs data, a pint quantity array of temps/dew point/rh/whatever
    Needs levs, a pint quantity array of pressures
    '''
    above_ground = []
    for i in range(len(levs)):
        diff = levs[i]-spres
        if diff <0:
            above_ground.append(levs[i])
    pres_abv_ground = above_ground*units.hPa
    num_points_abv_ground = len(above_ground)
    data_abv_ground = data[-num_points_abv_ground:]
    return [data_abv_ground,pres_abv_ground]


"""
This solution uses an iterative approach to solve the problem. It adds all the
nodes' value in reverse of the postorder, then reverse the list back when
returning.
"""
from typing import List

class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children

class Solution:
    def postorder(self, root: "Node") -> List[int]:
        # check if the tree is empty
        if not root:
            return []

        # create a list to store the answer
        lst = []
        # create a list that is used as a stack
        stack = [root]

        # add all the nodes' value in the reverse order of postorder
        while stack:
            # get the node
            node = stack.pop()

            # if the node has children, add them to the stack
            if node.children:
                stack.extend(node.children)

            # add the node's value to the list
            lst.append(node.val)

        # reverse the list to get the postorder traversal
        return lst[::-1]


'''
연산자 우선 순위를 무시하고 앞에서부터 진행
음수를 양수로 나눌 때는 양수로 바꾼 뒤 몫을 취하고,그 몫을 음수로 바꾼 것
결과가 최대인 것과 최소인 것

첫째 줄에 수의 개수 N(2 ≤ N ≤ 11)가 주어진다. 둘째 줄에는 A1, A2, ..., AN이 주어진다.
(1 ≤ Ai ≤ 100) 셋째 줄에는 합이 N-1인 4개의 정수가 주어지는데,
차례대로 덧셈(+)의 개수, 뺄셈(-)의 개수, 곱셈(×)의 개수, 나눗셈(÷)의 개수이다.

'''

n = int(input())
array = list(map(int, input().split()))
operator = list(map(int, input().split()))  # +, -, *, //
str_operator = []
for idx, i in enumerate(operator):
    if idx == 0:
        for j in range(i):
            str_operator.append('+')
            continue
    elif idx == 1:
        for j in range(i):
            str_operator.append('-')
            continue
    elif idx == 2:
        for j in range(i):
            str_operator.append('*')
            continue
    elif idx == 3:
        for j in range(i):
            str_operator.append('//')
            continue

answer = set()
operator_len = len(str_operator)
visited = [0 for _ in range(operator_len)]
now = array[0]

def cal(n1, n2, oper):
    if oper == '+':
        return n1 + n2
    elif oper == '-':
        return n1 - n2
    elif oper == '*':
        return n1 * n2
    else:
        if n1 < 0:
            n1 = -n1
            return -(n1 // n2)
        else:
            return n1 // n2

def dfs(depth, now):
    if operator_len == depth:
        # 끝에 다다른 경우
        answer.add(now)
        return
    for i in range(operator_len):
        if visited[i]:  # 이미 방문했을 경우 = 건너뛰기 과정
            continue
        visited[i] = 1
        temp = now
        now = cal(temp, array[depth+1], str_operator[i])
        dfs(depth + 1, now)
        visited[i] = 0
        now = temp

dfs(0, now)
print(max(answer))
print(min(answer))


from core.utils import ViewDecorators
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_protect
from dashboard import forms, models

@csrf_protect
@ViewDecorators.require_user
def index(request):
    activity_type_list = models.ActivityType.get_user_activity_type_list(request.user['email'])

    if request.method == 'GET':
        form = forms.CreateActivityForm()
        form.prepare(activity_type_list)
    else:
        form = forms.CreateActivityForm(request.POST)
        form.prepare(activity_type_list)
        if form.is_valid():
            resp = models.Activity.create_activity(request.user['email'], form.cleaned_data)
    return render(request, 'index.html', locals())

@csrf_protect
@ViewDecorators.require_user
def create_activity_type(request):
    if request.method == 'GET':
        form = forms.AddActivityTypeForm()
    else:
        form = forms.AddActivityTypeForm(request.POST)
        if form.is_valid():
            resp = models.ActivityType.create_activity_type(request.user['email'], form.cleaned_data['name'])
            if resp['status'] == 'ActivityCreated':
                return redirect('dashboard')
    return render(request, 'create_type.html', locals())