'''
Created on Feb 25, 2010

'''
from math import pi as Pi, cos, sin, exp, sqrt as scalar_sqrt

from ibvpy.tmodel.mats2D.mats2D_eval import MATS2DEval
from numpy import \
     array, zeros, dot, \
     float_, \
     sign
from traits.api import \
     Array, Enum, \
     Event, provides, \
     Dict, Property, cached_property
import bmcs_utils.api as bu

#---------------------------------------------------------------------------
# Material time-step-evaluator for Scalar-Damage-Model
#---------------------------------------------------------------------------
class MATS2D5PlasticBond(MATS2DEval):
    '''
    Elastic Model.
    '''

    #---------------------------------------------------------------------------
    # Parameters of the numerical algorithm (integration)
    #---------------------------------------------------------------------------

    stress_state = Enum("plane_stress", "plane_strain")

    #---------------------------------------------------------------------------
    # Material parameters
    #---------------------------------------------------------------------------

    E_m = bu.Float(1.,  # 34e+3,
                 label="E_m",
                 desc="Young's Modulus",
                 auto_set=False)
    nu_m = bu.Float(0.2,
                 label='nu_m',
                 desc="Poison's ratio",
                 auto_set=False)

    E_f = bu.Float(1.,  # 34e+3,
                 label="E_f",
                 desc="Young's Modulus",
                 auto_set=False)
    nu_f = bu.Float(0.2,
                 label='nu_f',
                 desc="Poison's ratio",
                 auto_set=False)

    G = bu.Float(1.,  # 34e+3,
                 label="G",
                 desc="Shear Modulus",
                 auto_set=False)

    sigma_y = bu.Float(.5,  # 34e+3,
                label="s_y",
                desc="Yield stress",
                auto_set=False)

    K_bar = bu.Float(0.,  # 34e+3,
                label="K",
                desc="isotropic hardening",
                auto_set=False)

    H_bar = bu.Float(0.,  # 34e+3,
                   label="H",
                   desc="kinematic hardening",
                   auto_set=False)

    D_el = Property(Array(float), depends_on='E_f, nu_f,E_m,nu_f,G, stress_state')

    @cached_property
    def _get_D_el(self):
        if self.stress_state == "plane_stress":
            return self._get_D_plane_stress()
        else:
            return self._get_D_plane_strain()

    # This event can be used by the clients to trigger an action upon
    # the completed reconfiguration of the material model
    #
    changed = Event

    #---------------------------------------------------------------------------------------------
    # View specification
    #---------------------------------------------------------------------------------------------

    view_traits = bu.View(
        bu.Item('E_m'),
        bu.Item('nu_m'),
        bu.Item('E_f'),
        bu.Item('nu_f'),
        bu.Item('G')
    )

    def get_corr_pred(self, eps_app_eng, tn1, eps_p_n, q_n, alpha_n):
        '''
        Corrector predictor computation.
        @param eps_app_eng input variable - engineering strain
        '''
        sigma = dot(self.D_el[:], eps_app_eng)

        # You print the stress you just computed and the value of the apparent E
        eps_n1 = float(eps_app_eng[6])  # hack for this particular case
        G = self.G

        eps_avg = eps_n1

        # print 'state array ', sctx.mats_state_array
        sigma_trial = self.G * (eps_n1 - eps_p_n)
        xi_trial = sigma_trial - q_n
        f_trial = abs(xi_trial) - (self.sigma_y + self.K_bar * alpha_n)
        # f_trial = -xi_trial - ( self.sigma_y + self.K_bar * alpha_n )

        sig_n1 = zeros((1,), dtype='float_')
        D_n1 = zeros((1, 1), dtype='float_')
        if f_trial <= 1e-8:
            sig_n1[0] = sigma_trial
            D_n1[0, 0] = G
        else:
            # print 'plastic'
            d_gamma = f_trial / (self.G + self.K_bar + self.H_bar)
            sig_n1[0] = sigma_trial - d_gamma * self.G * sign(xi_trial)
            D_n1[0, 0] = (self.G * (self.K_bar + self.H_bar)) / \
                            (self.G + self.K_bar + self.H_bar)
            # print 'stress ', sig_n1[0]
        sigma[6] = sig_n1[0]
        self.D_el[6, 6] = D_n1[0, 0]
        return  sigma, self.D_el

    def _get_D_plane_stress(self):
        E_m = self.E_m
        nu_m = self.nu_m
        E_f = self.E_f
        nu_f = self.nu_f
        G = self.G
        D_stress = zeros([8, 8])
        D_stress[0, 0] = E_m / (1.0 - nu_m * nu_m)
        D_stress[0, 1] = E_m / (1.0 - nu_m * nu_m) * nu_m
        D_stress[1, 0] = E_m / (1.0 - nu_m * nu_m) * nu_m
        D_stress[1, 1] = E_m / (1.0 - nu_m * nu_m)
        D_stress[2, 2] = E_m / (1.0 - nu_m * nu_m) * (1.0 / 2.0 - nu_m / 2.0)

        D_stress[3, 3] = E_f / (1.0 - nu_f * nu_f)
        D_stress[3, 4] = E_f / (1.0 - nu_f * nu_f) * nu_f
        D_stress[4, 3] = E_f / (1.0 - nu_f * nu_f) * nu_f
        D_stress[4, 4] = E_f / (1.0 - nu_f * nu_f)
        D_stress[5, 5] = E_f / (1.0 - nu_f * nu_f) * (1.0 / 2.0 - nu_f / 2.0)

        D_stress[6, 6] = G
        D_stress[7, 7] = G
        return D_stress

    def _get_D_plane_strain(self):
        # TODO: adapt to use arbitrary 2d model following the 1d5 bond
        E_m = self.E_m
        nu_m = self.nu_m
        E_f = self.E_f
        nu_f = self.nu_f
        G = self.G
        D_strain = zeros([8, 8])
        D_strain[0, 0] = E_m * (1.0 - nu_m) / (1.0 + nu_m) / (1.0 - 2.0 * nu_m)
        D_strain[0, 1] = E_m / (1.0 + nu_m) / (1.0 - 2.0 * nu_m) * nu_m
        D_strain[1, 0] = E_m / (1.0 + nu_m) / (1.0 - 2.0 * nu_m) * nu_m
        D_strain[1, 1] = E_m * (1.0 - nu_m) / (1.0 + nu_m) / (1.0 - 2.0 * nu_m)
        D_strain[2, 2] = E_m * (1.0 - nu_m) / (1.0 + nu_m) / (2.0 - 2.0 * nu_m)

        D_strain[3, 3] = E_f * (1.0 - nu_f) / (1.0 + nu_f) / (1.0 - 2.0 * nu_f)
        D_strain[3, 4] = E_f / (1.0 + nu_f) / (1.0 - 2.0 * nu_f) * nu_f
        D_strain[4, 3] = E_f / (1.0 + nu_f) / (1.0 - 2.0 * nu_f) * nu_f
        D_strain[4, 4] = E_f * (1.0 - nu_f) / (1.0 + nu_f) / (1.0 - 2.0 * nu_f)
        D_strain[5, 5] = E_f * (1.0 - nu_f) / (1.0 + nu_f) / (2.0 - 2.0 * nu_f)

        D_strain[6, 6] = G
        D_strain[7, 7] = G
        return D_strain

    #---------------------------------------------------------------------------------------------
    # Response trace evaluators
    #---------------------------------------------------------------------------------------------

    def get_sig_norm(self, sctx, eps_app_eng):
        sig_eng, D_mtx = self.get_corr_pred(sctx, eps_app_eng, 0, 0, 0)
        return array([ scalar_sqrt(sig_eng[0] ** 2 + sig_eng[1] ** 2) ])

    def get_eps_app_m(self, sctx, eps_app_eng):
        return self.map_eps_eng_to_mtx((eps_app_eng[:3]))

    def get_eps_app_f(self, sctx, eps_app_eng):
        return self.map_eps_eng_to_mtx((eps_app_eng[3:6]))

    def get_sig_app_m(self, sctx, eps_app_eng, *args, **kw):
        sig_eng, D_mtx = self.get_corr_pred(sctx, eps_app_eng, 0, 0, 0)
        return self.map_sig_eng_to_mtx((sig_eng[:3]))

    def get_sig_app_f(self, sctx, eps_app_eng, *args, **kw):
        sig_eng, D_mtx = self.get_corr_pred(sctx, eps_app_eng, 0, 0, 0)
        return self.map_sig_eng_to_mtx((sig_eng[3:6]))

    def get_sig_b(self, sctx, eps_app_eng, *args, **kw):
        sig_eng, D_mtx = self.get_corr_pred(sctx, eps_app_eng, 0, 0, 0)
        return array([[sig_eng[6], 0.], [0., sig_eng[7]]])

    # Declare and fill-in the rte_dict - it is used by the clients to
    # assemble all the available time-steppers.
    #
    rte_dict = Trait(Dict)

    def _rte_dict_default(self):
        return {
                'eps_app_f'  : self.get_eps_app_f,
                'eps_app_m'  : self.get_eps_app_m,
                'sig_app_f'  : self.get_sig_app_f,
                'sig_app_m'  : self.get_sig_app_m,
                'sig_norm'   : self.get_sig_norm,
                'sig_b'      : self.get_sig_b, }


import webapp2
import jinja2
import os
import json
import logging
import datetime
import csv
from StringIO import StringIO
from urllib import quote, urlencode
from google.appengine.api import urlfetch

from models import TrackedUser, Followers

import headers

jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), "templates")))

class MainPage(webapp2.RequestHandler):
	def get(self):
		template = jinja_environment.get_template('index.html')

		template_values = {}

		self.response.out.write(template.render(template_values))

class TrackedUserList(webapp2.RequestHandler):
	def get(self):
		template = jinja_environment.get_template('user-listing.html')

		template_values = {'tracked_users' : TrackedUser.query().order(TrackedUser.username)}

		self.response.out.write(template.render(template_values))

class UserDetails(webapp2.RequestHandler):
	def get(self, username):
		template = jinja_environment.get_template('user-data.html')

		now = datetime.datetime.now()
		two_days_ago = now - datetime.timedelta(days=2)

		follower_data = [f for f in Followers.query(Followers.username == username, Followers.when >= two_days_ago).order(-Followers.when)]

		followers = [f.followers for f in follower_data]

		follower_change = max_followers = min_followers = 0
		if len(follower_data) > 1:
			follower_change = followers[0] - followers[-1]
			max_followers = max(followers)
			min_followers = min(followers)

		template_values = {'username' : username,
			'follower_data' : follower_data,
			'follower_change' : follower_change,
			'max_followers' : max_followers,
			'min_followers' : min_followers,}

		self.response.out.write(template.render(template_values))

class CsvDump(webapp2.RequestHandler):
	def get(self, username):
		follower_data = [f for f in Followers.query(Followers.username == username).order(-Followers.when)]

		headers.csv(self.response)
		buffer = StringIO()
		csv_writer = csv.writer(buffer)
		for f in follower_data:
			csv_writer.writerow([f.when.strftime("%Y-%m-%d %H:%M:%S"), f.followers])

		self.response.out.write(buffer.getvalue())

app = webapp2.WSGIApplication([('/', MainPage),
	('/tracked-users', TrackedUserList),
	('/user/(.*)/csv', CsvDump),
	('/user/(.*)', UserDetails)],
                              debug=True)


"""https://web3py.readthedocs.io/en/stable/"""
from typing import Union, Any

from eth_typing import URI
from web3.contract import Contract
from web3.types import Wei, Address, HexStr, TxParams

from .reader import Reader

class Transactor(Reader):
    def __init__(self, provider: Union[URI, str], timeout: int = 60) -> None:
        super().__init__(provider, timeout)

    def launch_transaction(
        self,
        private_key: Union[HexStr, str],
        to: Union[Address, str],
        value: Wei = 0,
        max_price: Wei = None,
        nonce: int = None,
    ) -> HexStr:
        sender = self.get_address(private_key)
        params = self.get_params(sender, max_price, nonce, value)
        transaction = {**params, "to": self.to_checksum(to)}
        transaction["gas"] = self.web3.eth.estimateGas(transaction)
        return self.send_raw(private_key, transaction)

    def launch_function(
        self,
        instance: Contract,
        private_key: Union[HexStr, str],
        function_name: str,
        *args: Any,
        value: Wei = 0,
        max_price: Wei = None,
        nonce: int = None
    ) -> HexStr:
        sender = self.get_address(private_key)
        params = self.get_params(sender, max_price, nonce, value)
        transaction = instance.functions.__dict__[function_name](
            *args
        ).buildTransaction(params)
        return self.send_raw(private_key, transaction)

    def send_raw(
        self, private_key: Union[HexStr, str], transaction: TxParams
    ) -> HexStr:
        raw_tx = self.sign_transaction(private_key, transaction)
        return self.to_hex(self.web3.eth.sendRawTransaction(raw_tx))


# Definition for singly-linked list.

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution:
    def oddEvenList(self, head):
        i = j = 1
        nodelist = []
        temp1 = temp2 = head

        while temp1 != None:
            if i%2 != 0:
                nodelist.append(temp1.val)
            temp1 = temp1.next
            i+=1

        while temp2 != None:
            if j%2 == 0:
                nodelist.append(temp2.val)
            temp2 = temp2.next
            j+=1

        dummy = ListNode("dummy")
        prev = dummy
        for k in range(len(nodelist)):
            temp = ListNode(nodelist[k])
            prev.next = temp
            prev = temp
        return dummy.next

head = node1 = ListNode(10)
node2 = node1.next = ListNode(20)
node3 = node2.next = ListNode(30)
node4 = node3.next = ListNode(40)

s = Solution()
newhead = s.oddEvenList(head)

while newhead != None:
    print(newhead.val)
    newhead = newhead.next


from fastapi import FastAPI
from fastapi.openapi.utils import get_openapi

from starlette.middleware.cors import CORSMiddleware
from app.core.config import ALLOWED_HOSTS, PROJECT_NAME

from app.api.endpoints import router as api_router

# create the app
app = FastAPI(title=PROJECT_NAME)

if not ALLOWED_HOSTS:
    ALLOWED_HOSTS = ['*']

app.add_middleware(
    CORSMiddleware,
    allow_origins=ALLOWED_HOSTS,
    allow_credentials=True,
    allow_methods=['*'],
    allow_headers=['*'],
)

# add endpoints to app
app.include_router(api_router)

# customize openapi documentation
def custom_openapi():
    """Customize openapi documentation page."""
    if app.openapi_schema:
        return app.openapi_schema
    openapi_schema = get_openapi(
        title="pollination.cloud",
        version="0.0.1",
        description="This page only documents %s endpoints."
        " See the link below for full API documentation." % PROJECT_NAME,
        routes=app.routes,
    )
    openapi_schema["info"]["x-logo"] = {
        "url": "https://user-images.githubusercontent.com/2915573/53690998-7239bb00-3d43-11e9-85b1-d9ac9d140c0f.png"
    }

    openapi_schema["info"]["license"] = {
        "name": "AGPL",
        "url": "https://www.gnu.org/licenses/agpl-3.0.en.html"
    }

    openapi_schema["externalDocs"] = {
        "description": "Pollination Cloud full API documentation.",
        "url": "https://pollination.cloud/api"
    }

    # openapi_schema["servers"] =  [{"url": "http://api.pollination.cloud"}]

    app.openapi_schema = openapi_schema
    return app.openapi_schema

app.openapi = custom_openapi


import asyncio

async def square(num):
    await asyncio.sleep(num)
    # print(f"tasks {num} compute value is {num * num}")
    return num

async def main():
    tasks = []
    for i in range(10, 0, -1):
        t1 = asyncio.create_task(square(i))
        tasks.append(t1)

    results = await asyncio.gather(*tasks)
    for result in results:
        print(result)

asyncio.run(main())


#!/usr/bin/env python3

"""
Unreal Engine 5: Plugin Manager
"""
import os
import json
import tkinter
from tkinter import ttk, messagebox
from ttkwidgets import CheckboxTreeview

script_directory = os.path.dirname(os.path.abspath(__file__))
uproject_files = [f for f in os.listdir(script_directory) if f.endswith('.uproject')]
if not uproject_files:
    messagebox.showerror("Error", "No .uproject found!")
    exit(1)

project_path = os.path.join(script_directory, uproject_files[0])

window = tkinter.Tk()
window.title("UE5 Plugin Manager")
window.minsize(320, 480)

tree = CheckboxTreeview(window)
tree.pack(expand=True, fill=tkinter.BOTH)

with open(project_path, "r") as f:
    uproject_json = json.load(f)

checkboxes = {}
plugins = uproject_json.get("Plugins", [])
for plugin in plugins:
    plugin_name = plugin.get("Name", "")
    checkboxes[plugin_name] = plugin.get("Enabled", False)

for plugin_name in sorted(checkboxes.keys(), reverse=True):
    enabled = checkboxes[plugin_name]
    tree.insert("", 0, iid=plugin_name, text=plugin_name, tags=("checked" if enabled else "unchecked"))

select_all_button = ttk.Button(window, text="All", command=tree.check_all)
select_all_button.pack(side=tkinter.LEFT, padx=5, pady=5)

deselect_all_button = ttk.Button(window, text="None", command=tree.uncheck_all)
deselect_all_button.pack(side=tkinter.LEFT, padx=0, pady=5)

def save_plugins():
    for item in tree.get_children(""):
        checkboxes[item] = tree.tag_has("checked", item)

    for plugin in plugins:
        plugin_name = plugin.get("Name", "")
        plugin["Enabled"] = checkboxes[plugin_name]

    with open(project_path, "w") as f:
        json.dump(uproject_json, f, indent=4)

save_button = ttk.Button(window, text="Save", command=save_plugins)
save_button.pack(side=tkinter.RIGHT, padx=5, pady=5)

window.mainloop()


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

import gzip
import scipy.io as sio
from utils.utils import Utils

class GenericSparseDB(Utils):

   def init(self):
      self.data = sio.mmread(gzip.open(self._matrix_fn)).tolil()
      self.factors = self._load_pickle(self._factors_fn)
      self.fac_len = len(self.factors)
      self.col_names = self.factors + self._load_pickle(self._colnames_fn)
      assert self.data.shape[1] == len(self.col_names),\
                 'Mismatch between the number of columns: %s - %s.'\
                     % (self.data.shape[1], len(self.col_names))

   def reset(self):
      self.init()


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

import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from recommender.models import Movie

class ContentSimilarity:
    # MELHORIA FUTURA: SALVAR MOST SIMILAR NO BD E ATUALIZAR SOMENTE QDO NECESSÁRIO
    def content_similarity(self, movie_id):
        #transform the Movie QuerySet into a pandas DataFrame
        movies = pd.DataFrame(list(Movie.objects.all().values()))

        #model instantiation
        vectorizer = TfidfVectorizer(min_df=1)

        #tokenize and compute tf-idf weights
        tfidf = vectorizer.fit_transform(movies.movie_description)

        #compute the similarity between movies
        similar = cosine_similarity(tfidf)

        #take the top-5 most similar movies
        most_similar = similar.argsort()[:,::-1][:,:6]

        most_similar = pd.DataFrame(most_similar)

        list_similar_movies = []

        #make a list of top-k recommended movies
        for i in range (1,most_similar.shape[1]):
            sim_movie_id = most_similar.iloc[int(movie_id),i]
            list_similar_movies.append(Movie.objects.get(pk=sim_movie_id))
            # print ("Name: %s" %movies.title.iloc[most_similar[movie_id,i]])
            # print ("Cosine similarity score: %f \n" %similar[movie_id,most_similar[movie_id,i]])
        return list_similar_movies

    # def __call__(movie_id):
    #     print ('called')


# 파이썬에서 while문은 조건문이 참(True)일 동안
# 반복적으로 코드를 실행합니다. 다음은 while문의 기본 구조입니다.

# while 조건문:
#     실행할 코드1
#     실행할 코드2
#     ...

i = 0
while i < 5:
    print(i)
    i += 1

# 짝수인 경우에는
while i < 10:
    if i == 5:
        break
    if i % 2 == 0:
        i += 1
        continue
    print(i)
    i += 1


import pandas as pd
import numpy as np
import csv as csv
from sklearn.ensemble import RandomForestClassifier

# CON ESTO GENERAMOS EL VECTOR DE BING
# HAY QUE GENERAR el FICHERO

df = pd.read_csv("./trafico-DATA-GDOT2.csv", sep=';')

df = df.sort_index(by=['Fecha Hora'], ascending=[True])

# print (df)

print ("Dia,Hora,ValorMedio,Indice,Valor")
horaAnterior = 0
valorMedio = 0
indiceMedio = 0
npValores = []
for index, row in df.iterrows():
    fechahora = row['Fecha Hora']
    dia = (int)((fechahora-5000000)/10000)
    hora = (int)((fechahora-5000000-dia*10000)/100)
    valor = row['Valor Estimado']
    # print (str(dia) + " " + str(hora) + " " + str(valor))
    if (hora == horaAnterior):
        valorMedio = valor + valorMedio;
        indiceMedio = indiceMedio + 1
        npValores.append(valor)
    else:
        valor = 0
        if (indiceMedio>0):
            valor = np.sum(npValores)
        print (str(dia) + "," + str(hora) + "," + str(valorMedio)+ "," + str(indiceMedio)+ "," + str(valor))
        horaAnterior = hora;
        indiceMedio = 0;
        valorMedio = 0;
        npValores = [];


def license(age, hours):
    if age >= 16 and hours >= 200:
        print('issue license')
    else:
        print('dont issue license')

license(18,250)
license(15,192)
license(16,199)
license(16,201)
license(16,200)


"""
	Functions for temperature conversions
	from farenheight to celcius
	and vice versa.
"""
def convert(cel):

    if cel <= -273.15:
        return "that temperature cannot exist"
    else:
        far = cel* 9/5 + 32
    return far

def calCLen (string):
    if type(string) == 'str':
        length = len(string)
        return length
    else:
        print("other types do not have length")

temperatures=[10,-20,-289,100]
def create():

    with open("temperature",'w+') as file:

        for temp in temperatures:
            convert(temp)
            file.write(str(temp) + '\n')


import torch
import numpy as np
import torch.nn.functional as F

from models import GetModel
from datagen import DataPool
from WGRutils import WGREnv, WandBScatterMaxlinePlot

import os
import wandb
import argparse
from datetime import datetime
from termcolor import colored

EPS = 1e-8

def temperature_schedule(args, timestep):
    normalized_time = timestep / args.timesteps
    return args.invtemp_min + normalized_time * (args.invtemp_max - args.invtemp_min)

def query_score(env, seq):
    return env.getEnergy(seq, False)

def init_wandb(args):
    run = wandb.init(project="WGR-DMGIBBS", config=args)
    return run

def main(args):

    # Set the device
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

    # Initialize the data pool
    print(colored("[INFO] Initializing the data pool...", "green"))
    pool = DataPool(args.batch_size, args.seq_length, args.timesteps)
    env = WGREnv(args, args.seq_length)
    # pool.initialize()

    # Initialize the model
    print(colored("[INFO] Initializing the model...", "green"))
    forwarder, critic = GetModel(args)

    print(colored("[MODEL] Forward generator:", "red"))
    print(forwarder)
    print(colored("[MODEL] Score / entropy critic:", "red"))
    print(critic)

    # Move the model to the device
    print(colored("[INFO] Moving the model to the device...", "green"))
    forwarder = forwarder.to(device)
    critic = critic.to(device)

    if args.resume is not None:

        print(colored("[INFO] Resuming from checkpoint %s..." % args.resume, "green"))

        checkpoint = torch.load(args.resume)

        forwarder.load_state_dict(checkpoint["forwarder"])
        critic.load_state_dict(checkpoint["critic"])

        print(colored("[INFO] Resumed from checkpoint %s." % args.resume, "yellow"))

    else:

        print(colored("[ERROR] No checkpoint assigned! aborting ...", "red"))
        exit()

    print(colored("[INFO] Finished initialization.", "yellow"))

    forwarder.eval()
    critic.eval()

    ###############################################################################
    # Data preparation
    ###############################################################################

    # Obtain a batch to start
    uniform_batch = pool.get_and_store_uniform_batch(args.batch_size)
    uniform_batch = uniform_batch.to(device)
    uniform_batch = F.one_hot(uniform_batch, num_classes=args.num_alphabet).float()

    previous_batch = uniform_batch

    for it in range(args.timesteps):

        ###############################################################################
        # Feed-forward
        ###############################################################################

        temperature = temperature_schedule(args, it)

        # Obtain forwarder output (probablities)
        generated_batch, _ = forwarder(previous_batch, temperature)

        # Sample a batch of sequences with torch.distribution from forwarder output logits
        sampled_batch_seq = torch.distributions.Categorical(logits=generated_batch).sample()

        # One-hot encode the sampled batch sequence
        sampled_batch = F.one_hot(sampled_batch_seq, num_classes=args.num_alphabet).float()

        sampled_batch_seq = sampled_batch_seq.cpu()

        # Obtain energy from the scoring server
        true_energy = query_score(env, sampled_batch_seq.numpy()).to(device)
        print(
            colored(
                "[EVALUATION] Time: {:3d}, Energy: {:9.6f}"
                .format(it, true_energy.mean()),
            "blue"
        ))

        previous_batch = sampled_batch

    # Visualization thru WGR
    print(sampled_batch_seq)
    env.getEnergy(sampled_batch_seq.numpy(), True)

    # Press any key to exit
    input("Visualization in progress. \nPress any key to exit...")

if __name__ == "__main__":

    parser = argparse.ArgumentParser(description='WGR-DMGIBBS')

    parser.add_argument('--serverIP', type=str, default='127.0.0.1')
    parser.add_argument('--serverPort', type=int, default=4445)
    parser.add_argument('--env', type=str, default='testCity')

    parser.add_argument('--seq_length', type=int, default=4096)
    parser.add_argument('--timesteps', type=int, default=25)
    parser.add_argument('--delta_time', type=int, default=1)
    parser.add_argument('--num_alphabet', type=int, default=256)

    parser.add_argument('--invtemp_min', type=float, default=0.0)
    parser.add_argument('--invtemp_max', type=float, default=1.0)
    parser.add_argument('--energy_scale', type=float, default=0.001)
    parser.add_argument('--dont_invert_score', action='store_true')

    parser.add_argument('--batch_size', type=int, default=64)

    parser.add_argument('--modelname', type=str, default='placeholder')

    parser.add_argument('--resume', type=str, default=None)

    args = parser.parse_args()

    # Get a unique name by datetime
    args.savedir = "saved_models/%s/%s[%s]" % (args.env, args.modelname, datetime.now().strftime("%Y%m%d-%H%M%S"))
    args.savepath = os.path.join(args.savedir, "latest.pt")

    main(args)


import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

f ="../test_batch.bin"
def read_img(file,k):
    file_=open(file, 'rb')
    val=int.from_bytes (file_.read(3073*k), byteorder='big')
    label=int.from_bytes (file_.read(1), byteorder='big') # Correspond au label de l'ima
    R=np.frombuffer(file_.read(1024), dtype=np. uint8)
    G=np.frombuffer(file_.read(1024), dtype=np. uint8)
    B=np.frombuffer(file_.read(1024), dtype=np. uint8)
    l_pixel=[]
    for i in range(1024) :
        l_pixel.append( [R[i], G[i], B[i]])
    return l_pixel
print(len(read_img(f,100)))

def write_image_ppm(image_data, output_file):
    with open(output_file, 'w') as f:
        f.write('P3\n')
        f.write('32 32\n')
        f.write('255\n')
        n=0
        for pixel in image_data:
            for color in pixel:
                    f.write(str(color) + ' ')
            n+=1
            if n==32 :
                f.write('\n')
                n=0
    f.close()
pic="pic.ppm"
write_image_ppm(read_img(f,4),pic)

#Read the image file
img = mpimg.imread(pic)

#Show the image
plt.imshow(img)
plt.show()
from PIL import Image
with Image.open(pic) as im:
     im.save("your_jpg_file.jpg")


from adr.World import Ambient
import numpy.testing as npt
import pytest

@pytest.fixture
def base_ambient():
    base_ambient = Ambient(temperature=288.15, pressure=101325, humidity=30)
    return base_ambient

def test_instantiation(base_ambient):
    assert base_ambient.temperature == 288.15
    assert base_ambient.pressure == 101325
    assert base_ambient.humidity == 30

def test_air_density(base_ambient):
    npt.assert_almost_equal(base_ambient.air_density, 1.224, decimal=3)

def test_instantiation_error():
    ambient = Ambient(temperature=0)
    with pytest.raises(ValueError) as e_info:
        air_density = ambient.air_density

    ambient = Ambient(humidity=104)
    with pytest.raises(ValueError) as e_info:
        air_density = ambient.air_density

    ambient = Ambient(pressure=-3)
    with pytest.raises(ValueError) as e_info:
        air_density = ambient.air_density


'''
https://www.codewars.com/kata/5277c8a221e209d3f6000b56

Write a function that takes a string of braces, and determines if the order of the braces is valid. It should return true if the string is valid, and false if it's invalid.

This Kata is similar to the Valid Parentheses Kata, but introduces new characters: brackets [], and curly braces {}. Thanks to @arnedag for the idea!

All input strings will be nonempty, and will only consist of parentheses, brackets and curly braces: ()[]{}.

What is considered Valid?
A string of braces is considered valid if all braces are matched with the correct brace.

Examples
"(){}[]"   =>  True
"([{}])"   =>  True
"(}"       =>  False
"[(])"     =>  False
"[({})](]" =>  False
'''

# my solution
def valid_braces(s):
    starting_braces = ['(', '[', '{']
    closing_braces = [')', ']', '}']
    braces = {'(':')', '[':']', '{':'}'}
    arr = []

    for i in range(len(s)):
        if s[i] in starting_braces:
            arr.append(s[i])
        else:
            if len(arr) == 0 and s[i] in closing_braces:
                return False
            elif braces[arr[-1]] == s[i]:
                arr.pop()

    return len(arr) == 0


# Given a list of words, list of  single letters (might be repeating) and score of every character.

# Return the maximum score of any valid set of words formed by using the given letters (words[i] cannot be used two or more times).

# It is not necessary to use all characters in letters and each letter can only be used once. Score of letters 'a', 'b', 'c', ... ,'z' is given by score[0], score[1], ... , score[25] respectively.

# Example 1:

# Input: words = ["dog","cat","dad","good"], letters = ["a","a","c","d","d","d","g","o","o"], score = [1,0,9,5,0,0,3,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0]
# Output: 23
# Explanation:
# Score  a=1, c=9, d=5, g=3, o=2
# Given letters, we can form the words "dad" (5+1+5) and "good" (3+2+2+5) with a score of 23.
# Words "dad" and "dog" only get a score of 21.
# Example 2:

# Input: words = ["xxxz","ax","bx","cx"], letters = ["z","a","b","c","x","x","x"], score = [4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,10]
# Output: 27
# Explanation:
# Score  a=4, b=4, c=4, x=5, z=10
# Given letters, we can form the words "ax" (4+5), "bx" (4+5) and "cx" (4+5) with a score of 27.
# Word "xxxz" only get a score of 25.
# Example 3:

# Input: words = ["leetcode"], letters = ["l","e","t","c","o","d"], score = [0,0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0]
# Output: 0
# Explanation:
# Letter "e" can only be used once.

# Constraints:

# 1 <= words.length <= 14
# 1 <= words[i].length <= 15
# 1 <= letters.length <= 100
# letters[i].length == 1
# score.length == 26
# 0 <= score[i] <= 10
# words[i], letters[i] contains only lower case English letters.

from collections import Counter
class Solution:
    def maxScoreWords(self, words: List[str], letters: List[str], score: List[int]) -> int:
        def toind(char):
            return ord(char)-ord('a')
        def help(start,remaining):
            if (start,remaining) in cache:
                return cache[(start,remaining)]
            if start==len(words):
                return 0
            letter_cnt = list(remaining)
            cur_word = words[start]
            cur_word_cnt = Counter(cur_word)
            if all((letter_cnt[toind(char)]>=cur_word_cnt[char] for char in cur_word_cnt)):
                for char in cur_word_cnt:
                    letter_cnt[toind(char)]-=cur_word_cnt[char]
                cur_score = sum(map(lambda char: score[toind(char)],cur_word))
                next_score = help(start+1,tuple(letter_cnt))
                score1 = cur_score+next_score
            else:
                score1 = 0

            score2 = help(start+1,remaining)
            ans =  max(score1,score2)
            cache[(start,remaining)] = ans
            return ans

        cache = {}
        letter_cnt = [0]*26
        for letter in letters:
            letter_cnt[toind(letter)]+=1
        return help(0,tuple(letter_cnt))

1255 Maximum Score Words Formed by Letters.py


# bsp name
BSP = 'lm3s8962'

# toolchains
EXEC_PATH 	= 'C:/Program Files/CodeSourcery/Sourcery G++ Lite/bin'
PREFIX = 'arm-none-eabi-'
CC = PREFIX + 'gcc'
CXX = PREFIX + 'g++'
AS = PREFIX + 'gcc'
AR = PREFIX + 'ar'
LINK = PREFIX + 'gcc'
TARGET_EXT = 'so'
SIZE = PREFIX + 'size'
OBJDUMP = PREFIX + 'objdump'
OBJCPY = PREFIX + 'objcopy'

DEVICE = ' -mcpu=cortex-m3'
CFLAGS = DEVICE + ' -mthumb -mlong-calls -Dsourcerygxx -O0 -fPIC'
AFLAGS = ' -c' + DEVICE + ' -x assembler-with-cpp'
LFLAGS = DEVICE + ' -mthumb -Wl,-z,max-page-size=0x4 -shared -fPIC -e main -nostdlib'

CPATH = ''
LPATH = ''


from sqlalchemy import create_engine
from sqlalchemy import Table, Column, MetaData, Index
from sqlalchemy.types import DateTime, Integer, Float

class SQLDriver:
    """This SQLAlchemy wrapper exposes only those functions
    that are used by pysatel, and hides all database interaction
    details.

    """
    def __init__(self, dialect, args, driver=""): # params is a dict
        if driver != "":
            dialect = "%s+%s" % (dialect, driver)
        self.meta = MetaData()
        self.engine = create_engine("%s://%s:%s@%s:%s/%s" % (dialect,
            args["user"], args["passwd"], args["host"], args["port"],
            args["db"]), pool_recycle = 3600)
        self.meta.bind = self.engine
        #self.maxself.maxAllowedPacked = int(dict(self.cursor.fetchall())["max_allowed_packet"])

    def __del__(self):
        del self.meta
        del self.engine

    def createtable(self, header, spacecraft, instrument, session = ""):
        """Create a new instrument table"""
        tablename = "%s_%s" % (spacecraft, instrument)
        args = [
            Column("dt_record", DateTime, nullable=False, primary_key=True),
            Column("microsec", Integer, default=0, primary_key=True)]
        for col in header:
            args.append(Column(col, Float, default=None))
        tbl = Table(tablename, self.meta, *args)
        tbl.create()
        i = Index('%s_index' % tablename, tbl.c.dt_record)
        i.create()

    def droptable(self, spacecraft, instrument, session = ""):
        """Drop a table"""
        tablename = "%s_%s" % (spacecraft, instrument)
        tbl = Table(tablename, self.meta, autoload=True)
        tbl.drop()

    def insert(self, header, values, spacecraft, instrument, session = ""):
        """Insert new measurements into connected SQL databases."""
        tablename = "%s_%s" % (spacecraft, instrument)
        conn = self.engine.connect()
        tbl = Table(tablename, self.meta, autoload=True)
        statements = []
        for val in values:
            statements.append(dict([(header[i], val[i])
                for i in range(len(header))]))
            if len(statements) == 500:
                conn.execute(tbl.insert(), statements)
            statements = []
        conn.close()


from config import bot, chat_id
from telebot import types
import requests
from bs4 import BeautifulSoup
from plugins.error import in_chat

@in_chat()
def cats(m):
    bot.delete_message(m.chat.id, m.message_id)
    keyboard = types.InlineKeyboardMarkup() #Добавляем кнопки
    cats = types.InlineKeyboardButton(text="Еще хочу котейку", callback_data="cats")
    keyboard.add(cats) #Добавляем кнопки для вывода
    user_agent = {
                    'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36'
                }

    search = "https://theoldreader.com/kittens/1366/768/js" #Запрашиваем у юзера, что он хочет найти
    url = requests.get(search, headers=user_agent) #Делаем запрос
    soup = BeautifulSoup(url.text, features="lxml") #Получаем запрос
    result = soup.find("img").get("src") #Ищем тег <img src="ссылка.png"
    result = "https://theoldreader.com" + result
    bot.send_photo(m.chat.id,photo=result, reply_markup=keyboard, parse_mode= "Markdown")


""""
AutoMap class
"""

# import
import os
import joblib
import pandas as pd
from datetime import datetime
from sklearn.preprocessing import LabelEncoder

from sklearn.model_selection import GridSearchCV
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import SGDClassifier
from sklearn.pipeline import Pipeline

import nltk
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import RegexpTokenizer

class AutoMap:
    """
    :params:
    train_files: list of files to load for training the prediction pipeline on
    predict_files: list of files to read and predict the parameters for
    output_files: list of files to save the predictions to, where length equals length of predict_files
    pipe_file: Previously created compatible pickled tuple of fitted (Pipeline, LabelEncoder) objects

    :args:

    """

    def __init__(self,
                 train_files: list = None,
                 predict_files: list = None,
                 output_files: list = None,
                 pipe_file: str = None):
        self.__version__ = '0.2.2'
        self.pipe_version = self.__version__
        self.datetime_created = datetime.utcnow().strftime("%Y%m%dT%H%M%S")
        nltk.download('punkt')
        nltk.download('wordnet')
        nltk.download('omw-1.4')  # hidden in Pipe creation

        if pipe_file:
            try:
                self.pipe, self.le, self.pipe_version, self.datetime_created = joblib.load(pipe_file)
                print(f'Loaded pipeline: {self.pipe}')
            except OSError:
                raise
        else:
            try:
                hard_coded_pipe = '../data/pipes/pipeline.pipe'
                if os.path.isfile(hard_coded_pipe):
                    self.pipe, self.le, self.pipe_version, self.datetime_created = joblib.load(hard_coded_pipe)
                else:
                    self.pipe = None
                    self.le = LabelEncoder()
            except:
                self.pipe = None
                self.le = LabelEncoder()

        if train_files is None:
            hard_coded_file = '../data/input/combined.csv'
            if os.path.isfile(hard_coded_file):
                self.df = pd.read_csv(hard_coded_file)

        # column names to use in training/predicting
        self.source = 'parameter_name'
        self.target = 'pacmed_subname'
        self.pred = 'predicted_subname'

        # if no label is given, impute with index[0] (unmapped)
        self.unlabeled = ['unmapped', 'microbiology']  # used for validation to filter out unlabeled

        # initial r'\w+' but 5% performance gain when underscores are omitted
        self.preprocess_text_regex_expression = r'[a-zA-Z0-9]+'
        return

    def preprocess_text(self, text):
        # Tokenise words while ignoring punctuation
        tokeniser = RegexpTokenizer(self.preprocess_text_regex_expression)
        tokens = tokeniser.tokenize(text)

        # Lowercase and lemmatise
        lemmatiser = WordNetLemmatizer()
        lemmas = [lemmatiser.lemmatize(token.lower(), pos='v') for token in tokens]

        # Remove stop words
        # keywords= [lemma for lemma in lemmas if lemma not in stopwords.words('english')]
        # return keywords
        return lemmas

    def create_pipe(self,
                    X=pd.Series(),
                    y=pd.Series(),
                    estimator=SGDClassifier(random_state=123),
                    grid: dict = None,
                    cv: int = 10,
                    n_jobs: int = None,
                    save: bool = False,
                    prefix=None):
        """
        Create the pipe object used to train and test text data
        """

        if y.isna().sum() > 0:
            y = y.fillna(self.unlabeled[0])

        # ensure labels are encoded
        self.le = LabelEncoder()
        self.le.fit(y=y.unique())

        # Create an instance of TfidfVectorizer
        vectoriser = TfidfVectorizer(analyzer=self.preprocess_text)

        # Fit to the data and transform to feature matrix
        X_train_tfidf = vectoriser.fit_transform(X)

        # try an initial accuracy before hyperparameter optimization
        clf = estimator
        # clf = SGDClassifier(random_state=123)
        # clf_scores = cross_val_score(clf, X_train_tfidf, self.y_train, cv=10)
        # print(clf_scores)
        # print("SGDClassfier Accuracy: %0.2f (+/- %0.2f)" % (clf_scores.mean(), clf_scores.std() * 2))

        if grid is None:
            grid = {'fit_intercept': [True, False],
                    'early_stopping': [True, False],
                    'loss': ['log', 'modified_huber', 'perceptron', 'huber', 'squared_loss', 'epsilon_insensitive',
                             'squared_epsilon_insensitive'],
                    # ['hinge', 'log', 'squared_hinge'], #PM squared_loss --> squared_error in v1.2
                    'penalty': ['l2', 'l1', 'none']}

            # Reduce to optimal grid for rerunning code
            grid = {'fit_intercept': [True],
                    'early_stopping': [False],
                    'loss': ['modified_huber'],
                    'penalty': ['l2']}

        # retry the SGDClassifier training with param_grid
        search = GridSearchCV(estimator=clf, param_grid=grid, cv=cv, n_jobs=n_jobs)
        search.fit(X_train_tfidf, y)

        # grid_sgd_clf_scores = cross_val_score(search.best_estimator_, X_train_tfidf, self.y_train, cv=5)
        # print(grid_sgd_clf_scores)
        # print("SGDClassifier optimal grid Accuracy: %0.2f (+/- %0.2f)" % (
        # grid_sgd_clf_scores.mean(), grid_sgd_clf_scores.std() * 2))

        # create Pipeline with vectoriser and optimal classifier
        self.pipe = Pipeline([('vectoriser', vectoriser),
                              ('classifier', search)])  # clf

        # fit the pipeline to the full training data
        self.pipe.fit(X, self.le.transform(y.values))

        # save pipe to file to prevent rerunning the same pipelines
        if prefix is None:
            prefix = ''
        if save:
            f_name = f'./data/pipes/{prefix}__{datetime.now().strftime("%Y%m%d%H%M%S")}.pipe'
            joblib.dump((self.pipe,
                         self.le,
                         self.pipe_version,
                         self.datetime_created,
                         ),
                        f_name,
                        compress=('gzip', 3),
                        protocol=5)
            print(f"Pipeline saved to: {f_name}")

        return self.pipe

    def save_pipe(self, f_name):
        joblib.dump((self.pipe, self.le), f_name)
        print(f"Pipeline saved to: {f_name}")

    def load_pipe(self, f_name):
        if os.path.isfile(f_name):
            self.pipe, self.le = joblib.load(f_name)
        else:
            self.pipe = None
            self.le = LabelEncoder()
        print(f"Pipeline loaded from: {f_name}")

    def predict_proba_transformed(self, X, **predict_proba_params):

        if isinstance(X, pd.Series):
            probs = self.pipe.predict_proba(X, **predict_proba_params)
            id_vars = [X.name]
            X = pd.DataFrame(X)
        else:
            probs = self.pipe.predict_proba(X[X.columns[1]], **predict_proba_params)
            id_vars = list(X.columns)

        df_probs = X.copy()
        df_probs[self.le.classes_] = probs
        # df_probs = pd.concat([X, pd.DataFrame(data=probs, columns=self.le.classes_)], axis=1, ignore_index=True)

        df_probs_melt = pd.melt(df_probs, id_vars=id_vars, value_vars=self.le.classes_, var_name='label')
        return df_probs_melt.loc[df_probs_melt['value'] > 0].sort_values(id_vars + ['value']).copy()

if __name__ == '__main__':
    am = AutoMap()
    df_full = pd.read_csv('../data/input/archive/combined_mappings_covid.csv')
    df = df_full.head(1000)
    am.create_pipe(X=df['parameter_name'], y=df['pacmed_subname'])
    a = am.predict_proba_transformed(X=df['parameter_name'])
    print('done')


import pandas as pd

# Read the CSV file
df = pd.read_csv('tracks_features.csv')

# Select only the desired columns
columns_to_keep = ['energy', 'speechiness', 'instrumentalness']
df = df[columns_to_keep]

# Write the result to a new CSV file
df.to_csv('song_data.csv', index=False)


# 큐 : 선입선출
import sys
input = sys.stdin.readline

n = int(input())
from collections import deque
queue = deque()

for _ in range(n):
    data = input().split()

    # push : x를 큐에 넣는 연산
    if data[0] == 'push':
        queue.append(data[1])

    # pop : 큐 가장 앞 정수 빼고 출력, 큐에 들어있는 정수가 없는 경우 -1 출력
    elif data[0] == 'pop':
        if len(queue) != 0:
            print(queue.popleft())
        else:
            print(-1)

    # size : 큐에 들어있는 정수 개수 출력
    elif data[0] == 'size':
        print(len(queue))

    # empty : 큐가 비어있으면 1, 아니면 0 출력
    elif data[0] == 'empty':
        if len(queue) == 0:
            print(1)
        else:
            print(0)

    # front : 큐 가장 앞 정수 출력, 큐에 들어있는 정수가 없는 경우 -1
    elif data[0] == 'front':
        if len(queue) != 0:
            print(queue[0])
        else:
            print(-1)

    # back : 큐 가장 뒤 정수 출력, 큐에 들어있는 정수가 없는 경우 -1
    elif data[0] == 'back':
        if len(queue) != 0:
            print(queue[-1])
        else:
            print(-1)


from flask import Flask, render_template, url_for, request, redirect, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from datetime import datetime
from netmiko import Netmiko
import util
import json
from ntc_templates.parse import parse_output
# Init app
app = Flask(__name__)
# Database
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///bgp_asn.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# Init db
db = SQLAlchemy(app)
# Init Marshmallow
ma = Marshmallow(app)
# BGP Database Class/Model
class BGP(db.Model):
    number = db.Column(db.String(5), nullable=False, primary_key=True)
    desc = db.Column(db.String(140), nullable=False)
    date_created = db.Column(db.DateTime, default=datetime.utcnow)
    def __repr__(self):
        return '<%r>' % self.number
# BGP Schema for Marshmallow API Functionality
class BGPSchema(ma.Schema):
    class Meta:
        fields = ('number', 'desc', 'date_created')
# Init Schema
BGP_schema = BGPSchema()
BGPs_schema = BGPSchema(many=True)
"""
To build/rebuild a db, execute the following after stopping the app, closing the python console and deleting the old .db file:
from app import db
db.create_all()
"""
@app.route('/', methods=['POST', 'GET'])
def index():
    if request.method == 'POST':
        asn_number = request.form['number']
        asn_desc = request.form['desc']
        new_asn = BGP(number=asn_number, desc=asn_desc)
        if int(asn_number) >= 64512 and int(asn_number) <= 65535:
            try:
                db.session.add(new_asn)
                db.session.commit()
                return redirect('/')
            except:
                return 'There was an issue adding your ASN, it probably already exists in Database'
        else:
            return 'ASN out of Range'
    else:
        asns = BGP.query.order_by(BGP.number).all()
        used = len(asns)
        util = ("{0:.0%}".format(int(used)/1024))
        return render_template('index.html', asns=asns, used=used, util=util)

@app.route('/delete/<string:number>')
def delete(number):
    asn_to_delete = BGP.query.get_or_404(number)

    try:
        db.session.delete(asn_to_delete)
        db.session.commit()
        return redirect('/')
    except:
        return 'There was a problem deleting that ASN'

@app.route('/update/<string:number>', methods=['GET', 'POST'])
def update(number):
    asn = BGP.query.get_or_404(number)
    if request.method == 'POST':
        asn.number = request.form['number']
        asn.desc = request.form['desc']

        try:
            db.session.commit()
            return redirect('/')
        except:
            return 'There was an issue updating your asn'

    else:
        return render_template('update.html', asn=asn)

@app.route('/import/', methods=['POST', 'GET'])
def import_asns():
    if request.method == 'GET':
        devices = ['DC1-coresw', 'DC2-coresw', 'DC3-coresw']
        aslist = []
        for dev in devices:
            device = util.CiscoDeviceRO(host=dev)
            dev_connect = Netmiko(**device.__dict__)
            bgp_out = dev_connect.send_command("show ip bgp vrf all all")
            bgp_parsed = parse_output(platform="cisco_nxos", command="show ip bgp", data=bgp_out)
            dev_connect.disconnect()
            print ("Collected BGP table for " + dev)
            print ('<br />')
            bgpasns = [ sub['as_path'] for sub in bgp_parsed ]
            for asn in bgpasns:
                asnsplit = asn.split()
                for asnum in asnsplit:
                    if asnum not in aslist and int(asnum) >=64512 and int(asnum) <=65535:
                        aslist.append(asnum)
        as_map = map(int, aslist)
        as_sort = sorted(as_map)
        for sort in as_sort:
            asn_status = BGP.query.get(sort)
            if asn_status == None:
                new_asn = BGP(number=sort, desc='Imported from Core BGP Table')
                try:
                    db.session.add(new_asn)
                    db.session.commit()
                except:
                    continue
        return redirect('/')

@app.route('/query', methods=['GET', 'POST'])
def top5():
    bgpnext = []
    avail = 64512
    avail_count = 5
    while avail_count > 0:
        result = BGP.query.get(avail)
        if result is None:
            bgpnext.append(avail)
            avail_count = avail_count -1
        else:
            print ('ASN used')
        avail = avail +1
    return render_template('query.html', bgpnext=bgpnext)

# API Routes
# API Create ASN
@app.route('/api', methods = ['POST'])
def add_asn():
    asn_number = request.json['number']
    asn_desc = request.json['desc']
    new_asn = BGP(number=asn_number, desc=asn_desc)
    if int(asn_number) >= 64512 and int(asn_number) <= 65535:
        db.session.add(new_asn)
        db.session.commit()
        return BGP_schema.jsonify(new_asn)
    else:
        return {"message": "Requested ASN is outside of Private Range (64512 - 65535) "}, 403
# API Get ASN
@app.route('/api/<number>', methods = ['GET'])
def get_asn(number):
    asn = BGP.query.get(number)
    return BGP_schema.jsonify(asn)
# API Get All ASNs
@app.route('/api', methods = ['GET'])
def get_all_asns():
    asns = BGP.query.order_by(BGP.number).all()
    result = BGPs_schema.dump(asns)
    return jsonify(result)
# API Update ASN
@app.route('/api/<number>', methods = ['PUT'])
def update_asn(number):
    asn = BGP.query.get(number)
    asn_desc = request.json['desc']
    asn.desc = asn_desc
    db.session.commit()
    return BGP_schema.jsonify(asn)
# API Delete ASN
@app.route('/api/<number>', methods = ['DELETE'])
def delete_asn(number):
    asn = BGP.query.get(number)
    db.session.delete(asn)
    db.session.commit()
    return BGP_schema.jsonify(asn)
#API Single Query
@app.route('/api/querynext', methods=['GET'])
def avail_asn():
    avail = 64512
    avail_count = 1
    while avail_count > 0:
        result = BGP.query.get(avail)
        if result is None:
            avail_count = avail_count -1
            return json.dumps(avail)
        avail = avail +1

# Run App
if __name__ == "__main__":
    app.run(host='0.0.0.0')


import os
import sys
sys.path.append(os.getcwd())
from functools import partial
import os
import pickle
import sys
import torch
from copy import deepcopy
import numpy as np
import matplotlib.pyplot as plt
import csv
from collections import defaultdict
import math
import glob
import re

from safe_control_gym.utils.configuration import ConfigFactory
from safe_control_gym.utils.plotting import plot_from_logs, window_func, load_from_log_file, COLORS, LINE_STYLES
from safe_control_gym.utils.registration import make
from safe_control_gym.utils.utils import mkdirs, set_dir_from_config, set_device_from_config, set_seed_from_config, save_video

from eval_utils import *

##############################################################################################
#############################   Constants   ##################################################
##############################################################################################

# quadrotor controller time interval
dt = 1.0 / 50.0

##############################################################################################
#############################   Testing Functions   ##########################################
##############################################################################################

def test_policy(config):
    """Run the (trained) policy/controller for evaluation.

    Saves test trajectories to csv files.
    Supports evaluation with fixed initial conditions.

    """
    assert config.restore is not None, "must specify --restore for policy evaluation."
    assert config.task_config.done_on_out_of_bound is False, "post-evaluation should disable early termination."
    # Evaluation setup.
    set_device_from_config(config)
    if config.set_test_seed:
        # seed the evaluation (both controller and env) if given
        set_seed_from_config(config)
        env_seed = config.seed
    else:
        env_seed = None
    # Define function to create task/env.
    env_func = partial(make, config.task, seed=env_seed, output_dir=config.output_dir, **config.task_config)
    # Create the controller/control_agent.
    control_agent = make(config.algo,
                         env_func,
                         training=False,
                         checkpoint_path=os.path.join(config.output_dir, "model_latest.pt"),
                         output_dir=config.output_dir,
                         device=config.device,
                         seed=config.seed,
                         **config.algo_config)
    control_agent.reset()
    if config.restore:
        control_agent.load(os.path.join(config.restore, config.restore_model_file))

    # Test controller.
    if config.fix_env_init:
        n_episodes = 1
        # quad has default 0 for initial states
        init_state = {}
        env = make_fixed_init_env(config, init_state=init_state,
                                  env_seed=env_seed, n_episodes=n_episodes)
    else:
        n_episodes = config.algo_config.eval_batch_size
        env = control_agent.env
    results = run_with_env(config, control_agent, env, n_episodes=n_episodes,
                           render=config.render, verbose=config.verbose)

    # Save evalution results.
    if hasattr(config, "eval_output_dir") and config.eval_output_dir is not None:
        eval_output_dir = config.eval_output_dir
    else:
        eval_output_dir = os.path.join(config.output_dir, "eval")
    os.makedirs(eval_output_dir, exist_ok=True)
    # test trajs and statistics
    eval_path = os.path.join(eval_output_dir, config.eval_output_path)
    os.makedirs(os.path.dirname(eval_path), exist_ok=True)
    with open(eval_path, "wb") as f:
        pickle.dump(results, f)
    # time and phase trajs for better visualization & plotting
    save_traj_to_csv(config, env, results, os.path.join(eval_output_dir, "eval_trajs"))
    plot_time_traj(env, results,
                   output_path=os.path.join(eval_output_dir, "time_trajectory.png"),
                   max_episode_plot=config.max_episode_plot)
    plot_phase_traj(env, results,
                   output_path=os.path.join(eval_output_dir, "phase_trajectory.png"),
                   max_episode_plot=config.max_episode_plot)
    control_agent.close()
    print("Evaluation done.")

def test_from_checkpoints(config):
    """Use saved checkpoints to test policy throughout training.

    This function is used when evaluation uses different settings to that during training.
    Hence, we use saved checkpoints to run test episodes with the modified settings,
    e.g. here we calculate the normalized metrics, including the RMSE as a common metric
    to compare fairly with other control baselines.

    """
    assert config.restore is not None, "must specify --restore for policy evaluation."
    assert config.task_config.done_on_out_of_bound is False, "post-evaluation should disable early termination."
    # Get all checkpoints
    checkpoint_dir_full = os.path.join(config.restore, config.checkpoint_dir)
    assert os.path.exists(checkpoint_dir_full), "checkpoint_dir does not exist in {}".format(config.restore)
    checkpoint_re = re.compile("model_(.*)\.pt")
    checkpoints = [
        [float(checkpoint_re.search(pt).group(1)), pt]
        for pt in os.listdir(checkpoint_dir_full)
    ]
    checkpoints = sorted(checkpoints, key=lambda x: x[0])

    # Evaluation setup.
    set_device_from_config(config)
    if config.set_test_seed and config.set_test_seed_as_training_eval:
        raise ValueError("Can only enable either `set_test_seed` or `set_test_seed_as_training_eval`.")
    elif config.set_test_seed:
        set_seed_from_config(config)
        env_seed = config.seed
    elif config.set_test_seed_as_training_eval:
        # algo seeding uses seed for original training
        set_seed_from_config(config)
        # env seeding uses seed for eval_env back in during training
        env_seed = config.seed * 111
    else:
        env_seed = None

    # Define function to create task/env.
    env_func = partial(make, config.task, seed=env_seed, output_dir=config.output_dir, **config.task_config)
    # create env and send to .run() explicitly
    # since if not, the default self.env has infinit buffer but not of size eval_batch_size
    env = env_func()
    # Create the controller/control_agent.
    control_agent = make(config.algo,
                         env_func,
                         training=False,
                         checkpoint_path=os.path.join(config.output_dir, "model_latest.pt"),
                         output_dir=config.output_dir,
                         device=config.device,
                         seed=config.seed,
                         **config.algo_config)
    control_agent.reset()

    # Test on each checkpoint
    test_results = defaultdict(list)
    for i, (step, checkpoint) in enumerate(checkpoints):
        print("Progress {}, step {} evaluating...".format(i / len(checkpoints), step))
        checkpoint_path_full = os.path.join(checkpoint_dir_full, checkpoint)
        control_agent.load(checkpoint_path_full)
        results = control_agent.run(env=env, n_episodes=config.algo_config.eval_batch_size)

        test_results["step"].append(step)
        ep_lengths = results["ep_lengths"]
        for k, v in results.items():
            if not isinstance(v, np.ndarray):
                pass
            # raw mean over n_episodes
            test_results[k].append(v.mean())
            # normalized mean
            if k is not "ep_lengths":
                assert len(v) == len(ep_lengths)
                # don't use `v / ep_lengths`, in case v is more than 1 dim
                normalized_v = np.asarray([v[i] / ep_lengths[i] for i in range(len(v))])
                if "mse" in k:
                    # convert mse cost to rmse (as we desired for common metric across baselines)
                    stat = np.mean(np.sqrt(normalized_v))
                    name = k.replace("mse", "rmse")
                else:
                    # take simple mean for other metrics such as constrasint violations
                    stat = np.mean(normalized_v)
                    name = k
                test_results["normalized_" + name].append(stat)

    # Save evalution results.
    checkpoint_eval_dir_full = os.path.join(config.restore, "logs", config.checkpoint_eval_dir)
    os.makedirs(checkpoint_eval_dir_full, exist_ok=True)
    steps = test_results.pop("step")

    for k, v in test_results.items():
        scalar_name = "{}/{}".format(config.checkpoint_eval_dir, k)
        header = ["step", scalar_name]
        stat_mtx = np.array([steps, v]).transpose()
        rows = stat_mtx.tolist()

        csv_path = os.path.join(checkpoint_eval_dir_full, "{}.log".format(k))
        with open(csv_path, "w") as f:
            writer = csv.writer(f)
            writer.writerow(header)
            writer.writerows(rows)
    control_agent.close()
    print("Checkpoint evaluation done.")

##############################################################################################
#############################   Performance   ##################################################
##############################################################################################

def plot_performance(config):
    """Gets the plot and csv for performance (in RMSE)."""
    legend_map = {
        "ppo": "ppo",
        "sac": "sac",
    }
    algo_name_map = {
        "ppo": "PPO",
        "sac": "SAC",
    }
    scalar_name_map = {
        "checkpoint_eval/normalized_rmse": "Cost",
    }

    # Collect results.
    spec = {}
    for d, legend in legend_map.items():
        seed_dirs = os.listdir(os.path.join(config.plot_dir, d))
        spec[legend] = [os.path.join(config.plot_dir, d, sd) for sd in seed_dirs]

    # Collective plot (mean only).
    scalar_stats = plot_from_exps(
        spec,
        out_path=os.path.join(config.plot_dir, "performance.jpg"),
        scalar_names=["checkpoint_eval/normalized_rmse"],
        title="Learning Curves",
        sub_titles=["Average RMSE"],
        xlabel="Training Time (s)",
        ylabels=["Cost"],
        window=None,
        x_num_max=None,
        x_rescale_factor=dt,
        num_std=0,
        use_median_quantile=True,
        cols_per_row=3
    )

    # Save stats to CSV.
    save_stats_to_csv(
        scalar_stats,
        algo_name_map=algo_name_map,
        scalar_name_map=scalar_name_map,
        csv_path=os.path.join(config.plot_dir, "performance.csv")
    )
    print("Performance plotting done.")

##############################################################################################
#############################   Constraint   ##################################################
##############################################################################################

def plot_constraint(config):
    """"""
    legend_map = {
        "ppo": "ppo",
        "safe_explorer_ppo/slack0.02": "seppo_0.02",
        # "safe_explorer_ppo/slack0.02_lr0.0001": "seppo_0.02_lr0.0001",
    }
    name_map = {
        "ppo": "PPO",
        "safe_explorer_ppo/slack0.02": "PPO safety_layer slack0.02",
        # "safe_explorer_ppo/slack0.02_lr0.0001": "PPO safety_layer slack0.02 lr 0.0001",
    }
    scalar_name_map = {
        "checkpoint_eval/normalized_constraint_violation": "Constraint Violations",
    }

    # Collect results.
    spec = {}
    for d, legend in legend_map.items():
        seed_dirs = os.listdir(os.path.join(config.plot_dir, d))
        spec[legend] = [os.path.join(config.plot_dir, d, sd) for sd in seed_dirs]

    # Collective plot (mean only).
    scalar_stats = plot_from_exps(
        spec,
        out_path=os.path.join(config.plot_dir, "constraint_performance.jpg"),
        scalar_names=["checkpoint_eval/normalized_constraint_violation"],
        title="Learning Curves",
        sub_titles=["Average Normalized Constraint Violations"],
        xlabel="Training Time (s)",
        ylabels=["Constraint Violations"],
        window=None,
        x_num_max=None,
        x_rescale_factor=dt,
        num_std=0,
        use_median_quantile=True,
        cols_per_row=3
    )

    # Save stats to CSV.
    save_stats_to_csv(
        scalar_stats,
        algo_name_map,
        scalar_name_map,
        csv_path=os.path.join(config.plot_dir, "constraint_performance.csv")
    )
    print("Constraint plotting done.")

##############################################################################################
#############################   Mains   ######################################################
##############################################################################################

MAIN_FUNCS = {
    "test_policy": test_policy,
    "test_from_checkpoints": test_from_checkpoints,
    "plot_performance": plot_performance,
    "plot_constraint": plot_constraint,
}

if __name__ == "__main__":
    # Make config.
    fac = ConfigFactory()
    fac.add_argument("--func", type=str, default="test", help="main function to run.")
    fac.add_argument("--thread", type=int, default=0, help="number of threads to use (set by torch).")
    fac.add_argument("--render", action="store_true", help="if to render in policy test.")
    fac.add_argument("--verbose", action="store_true", help="if to print states & actions in policy test.")
    fac.add_argument("--set_test_seed", action="store_true", help="if to set seed when testing policy.")
    fac.add_argument("--eval_output_dir", type=str, help="folder path to save evaluation results.")
    fac.add_argument("--eval_output_path", type=str, default="test_results.pkl", help="file path to save evaluation results.")

    # testing args
    fac.add_argument("--restore_model_file", type=str, default="model_latest.pt", help="file name to restore the model.")
    fac.add_argument("--fix_env_init", action="store_true", help="if to test policy using env with fixed initial conditions.")
    fac.add_argument("--max_episode_plot", type=int, default=1, help="max number of test episode to plot.")
    fac.add_argument("--checkpoint_dir", type=str, default="checkpoints", help="folder where training checkpoints are saved.")
    fac.add_argument("--set_test_seed_as_training_eval", action="store_true", help="if to set seed same as eval_env during training.")
    fac.add_argument("--checkpoint_eval_dir", type=str, default="checkpoint_eval", help="where to save csv logs evaluated on checkpoints")

    # plotting args
    fac.add_argument("--plot_dir", type=str, help="folder path to save the plots.")

    config = fac.merge()
    # System settings.
    if config.thread > 0:
        # E.g. set single thread for less context switching
        torch.set_num_threads(config.thread)
    # Execute.
    func = MAIN_FUNCS.get(config.func, None)
    if func is None:
        raise Exception("Main function {} not supported.".format(config.func))
    func(config)


from AirportVisit import AirportVisit

class ImpossibleRouteError(Exception):
    def __init__(self, message):
        self.message = message

class Route:
    """
    Route: Contains information about a possible route.
    Includes a method for calculating the cheapest places to refuel along the route.
    Also includes a method that generates a line for the csv file, and methods for
    printing information to the console.
    """
    def __init__(self, route, aircraft_range, airport_atlas, currency_table,
                 empty_tank=False, total_cost_of_stopovers=0):
        self.__fuel_capacity = aircraft_range
        self.airport_atlas = airport_atlas
        self.currency_table = currency_table
        self.__empty_tank = empty_tank
        self.__total_cost_of_stopovers = total_cost_of_stopovers
        self.__list_of_stops = self.__build_list_of_stops(route)
        self.__total_cost, self.__unused_fuel, self.__net_cost = self.calculate_cheapest_place_to_refuel()

    def __build_list_of_stops(self, route):
        output = []
        for i in range(len(route)):
            airport_code = route[i]
            country = self.airport_atlas.get_country(airport_code)
            fuel_price = self.currency_table.get_exchange_rate(country)
            if i == len(route) - 1:
                distance_to_next_airport = self.airport_atlas.get_distance_between_airports(route[i], route[0])
            else:
                distance_to_next_airport = self.airport_atlas.get_distance_between_airports(route[i], route[i + 1])
            if distance_to_next_airport > self.__fuel_capacity:
                return []
            output.append(AirportVisit(airport_code, fuel_price, distance_to_next_airport, self.__fuel_capacity))
        if output == []:
            raise ImpossibleRouteError("Cannot complete this route")
        return output

    def calculate_cheapest_place_to_refuel(self):
        if self.__list_of_stops == []:
            raise ImpossibleRouteError("Cannot complete this route")
        total_cost = 0
        valid_airports = []

        for i in range(len(self.__list_of_stops)):
            current_stop = self.__list_of_stops[i]
            valid_airports += [current_stop]          # the set of airports from which we can buy fuel for the next leg
            fuel_needed = current_stop.distance_to_next_airport

            # buy enough fuel for next leg
            while True:
                lowest_fuel_price = 10 ** 10
                for airport in valid_airports:
                    if airport.fuel_price <= lowest_fuel_price:
                        cheapest_airport = airport
                        lowest_fuel_price = airport.fuel_price
                        spare_fuel_capacity = airport.get_spare_fuel_capacity()

                if spare_fuel_capacity >= fuel_needed:
                    quantity_purchased = fuel_needed
                    cheapest_airport.buy_fuel(quantity_purchased)
                    for airport in valid_airports:
                        airport.add_fuel(quantity_purchased)
                    # eliminate airports where tank is full
                    valid_airports = [x for x in valid_airports if float(x.get_spare_fuel_capacity()) > 0]
                    total_cost += quantity_purchased * cheapest_airport.fuel_price
                    break

                else:                                                              # spare_fuel_capacity < fuelNeeded
                    quantity_purchased = spare_fuel_capacity
                    cheapest_airport.buy_fuel(quantity_purchased)
                    total_cost += quantity_purchased * cheapest_airport.fuel_price
                    fuel_needed -= quantity_purchased
                    for airport in valid_airports:
                        airport.add_fuel(quantity_purchased)
                    # eliminate airports where tank is full
                    valid_airports = [x for x in valid_airports if float(x.get_spare_fuel_capacity()) > 0]

        if self.__empty_tank:
            net_cost = total_cost + self.__total_cost_of_stopovers
            return total_cost, 0, net_cost + self.__total_cost_of_stopovers
        else:
            # buy extra fuel at cheapest airports
            extra_fuel = 0
            home_airport = self.__list_of_stops[0]
            while True:
                lowest_fuel_price = 10 ** 10
                for airport in valid_airports:
                    if airport.fuel_price <= lowest_fuel_price:
                        cheapest_airport = airport
                        lowest_fuel_price = airport.fuel_price
                        spare_fuel_capacity = airport.get_spare_fuel_capacity()
                if cheapest_airport.fuel_price < home_airport.fuel_price:
                    # print("buying from ", cheapest_airport.airport_code)
                    quantity_purchased = spare_fuel_capacity
                    cheapest_airport.buy_fuel(quantity_purchased)
                    extra_fuel += quantity_purchased
                    total_cost += quantity_purchased * cheapest_airport.fuel_price
                    for airport in valid_airports:
                        airport.add_fuel(quantity_purchased)
                    # eliminate airports where tank is full on departure
                    valid_airports = [x for x in valid_airports if float(x.get_spare_fuel_capacity()) > 0]
                    if len(valid_airports) == 0:
                        break
                else:
                    break
            net_cost = total_cost - (extra_fuel * home_airport.fuel_price) + self.__total_cost_of_stopovers
            return total_cost, extra_fuel, net_cost

    def get_cost_of_route(self):
        return self.__net_cost

    def __str__(self):
        output = "\n              Distance to          Fuel             Fuel           Total Fuel  \n"
        output += "  Airport     Next Airport       Purchase           Price            Spend\n"
        output += "                                                   (euros)          (euros)\n"
        for i in self.__list_of_stops:
            output += str(i) + "\n"
        return output

    def print_costs(self):
        print()
        print("Total fuel spend:                     €", "{:11,.2f}".format(self.__total_cost))
        print("Total cost of extra stopovers:        €", "{:11,.2f}".format(self.__total_cost_of_stopovers))
        print("Minus value of fuel brought home:     €", "{:11,.2f}".format(self.__unused_fuel * -1 *
                                                                            self.__list_of_stops[0].fuel_price)), ")"
        print("                                      =============")
        print("Net cost:                             €", "{:11,.2f}".format(self.__net_cost))

    def make_csv_row(self):
        row = []
        row.append("{:,.2f}".format(self.__net_cost))
        row.append("{:,.2f}".format(self.__unused_fuel * self.__list_of_stops[0].fuel_price))
        row.append("{:,.2f}".format(self.__total_cost_of_stopovers))
        row.append("{:,.2f}".format(self.__total_cost))
        for airport in self.__list_of_stops:
            row.append(airport.airport_code)
            row.append("{:,.2f}".format(airport.get_total_fuel_purchase()))
        return row


import numpy as np
import random
import pickle
import os.path as osp
import pyflex
from softgym.envs.cloth_env import ClothEnv
import copy
from copy import deepcopy

class ClothDropEnv(ClothEnv):
    def __init__(self, cached_states_path='cloth_drop_init_states.pkl', **kwargs):
        """
        :param cached_states_path:
        :param num_picker: Number of pickers if the aciton_mode is picker
        :param kwargs:
        """
        self.vary_cloth_size = kwargs['vary_cloth_size']
        self.vary_stiffness = kwargs['vary_stiffness']
        self.vary_orientation = kwargs['vary_orientation']
        self.env_shape = kwargs['env_shape']

        super().__init__(**kwargs)
        self.get_cached_configs_and_states(cached_states_path, self.num_variations)

        assert self.action_tool.num_picker == 2  # Two drop points for this task
        self.prev_dist = None  # Should not be used until initialized

    def generate_env_variation(self, num_variations=1):
        """ Generate initial states. Note: This will also change the current states! """
        max_wait_step = 500  # Maximum number of steps waiting for the cloth to stablize
        stable_vel_threshold = 0.1  # Cloth stable when all particles' vel are smaller than this
        generated_configs, generated_states = [], []
        default_config = self.get_default_config()

        for i in range(num_variations):
            config = deepcopy(default_config)
            self.update_camera(config['camera_name'], config['camera_params'][config['camera_name']])
            if self.vary_cloth_size:
                cloth_dimx, cloth_dimy = self._sample_cloth_size()
                config['ClothSize'] = [cloth_dimx, cloth_dimy]
            else:
                cloth_dimx, cloth_dimy = config['ClothSize']

            if self.vary_stiffness:
                config['ClothStiff'] = [np.random.uniform(0.5, 2.0), np.random.uniform(0.5, 2.0),
                                                np.random.uniform(0.5, 2.0)]
            self.set_scene(config)
            self.action_tool.reset([0., -1., 0.])

            if self.vary_orientation:
                orientation_angle = np.random.uniform(-np.pi/6, np.pi/6)
            else:
                orientation_angle = 0

            config['env_shape'] = self.env_shape
            delta_x = np.random.uniform(0.1, 0.3)
            if self.env_shape == 'platform':

                box_size = np.array([0.20, 0.02, 0.20])
                box_pos =  np.array([delta_x + cloth_dimx * self.cloth_particle_radius / 2, 0, 0])
                box_quat = np.array([0, np.sin(orientation_angle / 2), 0, np.cos(orientation_angle / 2)])

                rot_mat = np.array([[np.cos(orientation_angle), 0, -np.sin(orientation_angle)],
                                    [0, 1, 0],
                                    [np.sin(orientation_angle), 0, np.cos(orientation_angle)]])
                box_pos = np.matmul(box_pos, rot_mat)

                box_size, box_pos, box_quat = self._add_box(box_size = box_size, box_pos = box_pos, box_quat = box_quat)

                delta_z_initial = box_size[1] + 0.3
                delta_z_target = box_size[1]

                config['shape_pos'] = box_pos
                config['shape_size'] = box_size
                config['shape_quat'] = box_quat

            elif self.env_shape == 'sphere':
                sphere_radius = 0.08
                sphere_position = np.array([0.25, 0.0, 0.0])
                sphere_random_pos = self._add_sphere(sphere_radius=sphere_radius, sphere_position=sphere_position, sphere_quat= np.array([0., 0., 0., 1.]), random_pos=True)
                delta_x = sphere_random_pos - cloth_dimx * self.cloth_particle_radius / 2
                delta_z_initial = sphere_radius
                delta_z_target = sphere_radius

                config['shape_pos'] = sphere_random_pos
                config['shape_size'] = sphere_radius
                config['shape_quat'] = np.array([sphere_random_pos, 0, 0])

            elif self.env_shape == 'rod':
                rod_size = np.array([0.004, 0.004, 0.2])
                rod_position = np.array([0.25, 0.1, 0.0])
                rod_random_pos = self._add_rod(rod_size=rod_size, rod_position=rod_position, rod_quat= np.array([0., 0., 0., 1.]), random_pos=True)
                delta_x = rod_random_pos - cloth_dimx * self.cloth_particle_radius / 2
                delta_z_initial = 0.4
                delta_z_target = rod_position[1] + rod_size[1]

                config['shape_pos'] = rod_random_pos
                config['shape_size'] = rod_size
                config['shape_quat'] = np.array([rod_random_pos, rod_position[1], rod_position[2]])

            else:
                delta_z_initial = 0.3 + np.random.uniform(-0.02, 0.02)
                delta_z_target = 0

            ## Set the cloth to horizontal position and wait to stablize

            flat_pos = self._set_to_flat(delta_x=delta_x, delta_z=delta_z_target, orientation_angle=orientation_angle)

            pickpoints = self._get_drop_point_idx()[:2]  # Pick two corners of the cloth and wait until stablize
            config['delta_x'] = delta_x
            config['target_picker_pos'] = flat_pos[pickpoints, :3]

            # while True:
            #     pyflex.step()
            #     pyflex.render()

            # wait to stablize
            for _ in range(max_wait_step):
                pyflex.step()
                pyflex.render()
                curr_vel = pyflex.get_velocities().reshape((-1, 3))
                if np.alltrue(curr_vel < stable_vel_threshold) and _ > 100:
                    break

            curr_pos = pyflex.get_positions().reshape((-1, 4))
            config['target_pos'] = curr_pos[:, :3]

            ## Set the cloth to initial position and wait to stablize
            self._set_to_vertical(x_low=np.random.uniform(-0.05,0.05), height_low=0.0, height_high= delta_z_initial)

            curr_pos = pyflex.get_positions().reshape(-1, 4)
            # curr_pos[0] += np.random.random() * 0.001  # Add small jittering
            original_inv_mass = curr_pos[pickpoints, 3]
            curr_pos[pickpoints, 3] = 0  # Set mass of the pickup point to infinity so that it generates enough force to the rest of the cloth
            pickpoint_pos = curr_pos[pickpoints, :3]
            pyflex.set_positions(curr_pos.flatten())

            picker_radius = self.action_tool.picker_radius
            self.action_tool.update_picker_boundary([-0.3, 0.01, -0.5], [0.5, 2, 0.5])
            self.action_tool.set_picker_pos(picker_pos=pickpoint_pos + np.array([0., picker_radius, 0.]))

            # Pick up the cloth and wait to stablize
            for j in range(0, max_wait_step):
                pyflex.step()
                pyflex.render()
                curr_pos = pyflex.get_positions().reshape((-1, 4))
                curr_vel = pyflex.get_velocities().reshape((-1, 3))
                if np.alltrue(curr_vel < stable_vel_threshold) and j > 300:
                    break
                curr_pos[pickpoints, :3] = pickpoint_pos
                pyflex.set_positions(curr_pos)
            curr_pos = pyflex.get_positions().reshape((-1, 4))
            curr_pos[pickpoints, 3] = original_inv_mass
            pyflex.set_positions(curr_pos.flatten())
            generated_configs.append(deepcopy(config))
            print('config {}: {}'.format(i, config['camera_params']))
            generated_states.append(deepcopy(self.get_state()))

        return generated_configs, generated_states

    def _set_to_flat(self, delta_x=0, delta_y=0, delta_z=0, orientation_angle=0):
        curr_pos = pyflex.get_positions().reshape((-1, 4))
        flat_pos = self._get_flat_pos(delta_x=delta_x, delta_z=delta_z, orientation_angle=orientation_angle)
        curr_pos[:, :3] = flat_pos
        pyflex.set_positions(curr_pos)
        pyflex.step()

        return flat_pos

    def _get_flat_pos(self, delta_x=0, delta_y=0, delta_z=0, orientation_angle=0):
        config = self.get_current_config()
        dimx, dimy = config['ClothSize']

        x = np.array([i * self.cloth_particle_radius for i in range(dimx)])
        y = np.array([i * self.cloth_particle_radius for i in range(dimy)])
        y = y - np.mean(y)

        x += delta_x
        # print(x.mean(),delta_x)
        xx, yy = np.meshgrid(x, y)
        curr_pos = np.zeros([dimx * dimy, 3], dtype=np.float32)
        curr_pos[:, 0] = xx.flatten()
        curr_pos[:, 2] = yy.flatten()
        curr_pos[:, 1] = 5e-3 + delta_z  # Set specifally for particle radius of 0.00625

        # Rotate the cloth
        rot_mat = np.array([[np.cos(orientation_angle), 0, -np.sin(orientation_angle)],
                            [0, 1, 0],
                            [np.sin(orientation_angle), 0, np.cos(orientation_angle)]])
        curr_pos = np.matmul(curr_pos, rot_mat)

        return curr_pos

    def _set_to_vertical(self, x_low, height_low, height_high):
        curr_pos = pyflex.get_positions().reshape((-1, 4))
        vertical_pos = self._get_vertical_pos(x_low, height_low)
        curr_pos[:, :3] = vertical_pos
        max_height = np.max(curr_pos[:, 1])
        if max_height < height_high:
            curr_pos[:, 1] += height_high - max_height
        pyflex.set_positions(curr_pos)
        pyflex.step()

    def _get_vertical_pos(self, x_low, height_low):
        config = self.get_current_config()
        dimx, dimy = config['ClothSize']

        x = np.array([i * self.cloth_particle_radius for i in range(dimx)])
        x = np.array(list(reversed(x)))
        y = np.array([i * self.cloth_particle_radius for i in range(dimy)])
        y = y - np.mean(y)
        xx, yy = np.meshgrid(x, y)

        curr_pos = np.zeros([dimx * dimy, 3], dtype=np.float32)
        curr_pos[:, 0] = x_low
        curr_pos[:, 2] = yy.flatten()
        curr_pos[:, 1] = xx.flatten() - np.min(xx) + height_low
        return curr_pos

    def _reset(self):
        """ Right now only use one initial state"""
        self.prev_dist = self._get_current_dist(pyflex.get_positions())
        if hasattr(self, 'action_tool'):
            particle_pos = pyflex.get_positions().reshape(-1, 4)
            drop_point_pos = particle_pos[self._get_drop_point_idx(), :3]
            middle_point = np.mean(drop_point_pos, axis=0)
            self.action_tool.reset(middle_point)  # middle point is not really useful
            picker_radius = self.action_tool.picker_radius
            self.action_tool.update_picker_boundary([-0.3, 0, -0.5], [0.5, 2, 0.5])
            self.action_tool.set_picker_pos(picker_pos=drop_point_pos + np.array([0., picker_radius, 0.]))
            # self.action_tool.visualize_picker_boundary()
        if self.env_shape == 'platform':
            self._add_box(box_size=self.current_config['shape_size'],
                                           box_pos=self.current_config['shape_pos'], box_quat=self.current_config['shape_quat'])

        if self.env_shape == 'sphere':
            sphere_radius = self.current_config['sphere_radius']
            sphere_position = self.current_config['sphere_position']
            self._add_sphere(sphere_radius=sphere_radius, sphere_position=sphere_position,
                                                 sphere_quat=np.array([0., 0., 0., 1.]), random_pos=False)

        if self.env_shape == 'rod':
            rod_size = self.current_config['rod_size']
            rod_position = self.current_config['rod_position']
            self._add_rod(rod_size=rod_size, rod_position=rod_position, rod_quat=np.array([0., 0., 0., 1.]), random_pos=False)

        self.performance_init = None
        info = self._get_info()
        self.performance_init = info['performance']
        return self._get_obs()

    def _step(self, action):
        self.action_tool.step(action)
        pyflex.step()
        return

    def _get_current_dist(self, pos):
        target_pos = self.get_current_config()['target_pos']
        curr_pos = pos.reshape((-1, 4))[:, :3]
        curr_dist = np.mean(np.linalg.norm(curr_pos - target_pos, axis=1))
        return curr_dist

    def compute_reward(self, action=None, obs=None, set_prev_reward=True):
        particle_pos = pyflex.get_positions()
        curr_dist = self._get_current_dist(particle_pos)
        r = - curr_dist
        return r

    def _get_info(self):
        particle_pos = pyflex.get_positions()
        curr_dist = self._get_current_dist(particle_pos)
        performance = -curr_dist
        performance_init = performance if self.performance_init is None else self.performance_init  # Use the original performance
        return {
            'performance': performance,
            'normalized_performance': (performance - performance_init) / (0. - performance_init)}

    def get_default_config(self):
        """ Set the default config of the environment and load it to self.config """
        config = {
            'ClothPos': [-1.6, 2.0, -0.8],
            'ClothSize': [32, 32],
            'ClothStiff': [0.9, 1.0, 0.9],  # Stretch, Bend and Shear
            'camera_name': 'default_camera',
            # 'camera_params': {'default_camera':
            #                       {'pos': np.array([1.07199, 0.94942, 1.15691]),
            #                        'angle': np.array([0.633549, -0.397932, 0]),
            #                        'width': self.camera_width,
            #                        'height': self.camera_height}},
            'camera_params': {'default_camera':
                                  {'pos': np.array([1.2,0.4, 0]),
                                   'angle': np.array([1.57, -0.2, 0]),
                                   'width': self.camera_width,
                                   'height': self.camera_height}},
            'flip_mesh': 0
        }
        return config

    def _get_drop_point_idx(self):
        return self._get_key_point_idx()[:2]

    def _sample_cloth_size(self):
        return np.random.randint(25, 40), np.random.randint(25, 40)

    def _add_rod(self, rod_size, rod_position, rod_quat, random_pos=False):
        if random_pos:
            rod_position[0] += np.random.uniform(-0.05, 0.05)
        pyflex.add_box(rod_size, rod_position, rod_quat)

        return rod_position[0]

    def _add_box(self, box_size, box_pos, box_quat):

        pyflex.add_box(box_size, box_pos, box_quat)

        return box_size, box_pos, box_quat

    def _add_sphere(self, sphere_radius, sphere_position, sphere_quat, random_pos=False):

        if random_pos:
            sphere_position[0] += np.random.uniform(-0.15, 0.15)
        pyflex.add_sphere(sphere_radius, sphere_position, sphere_quat)

        return sphere_position[0]


"""A number-guessing game."""

# Put your code here
import random

name = input("Howdy, what's your name?\n(type in your name) ")
number_guessed = int(input(f"{name}, I'm thinking of a number between 1 and 100.\nTry to guess my number.\nYour guess? "))

number = random.randint(1, 101)

counter = 0
# Create function for guessing

def guess_num(number_guessed):
    while number_guessed != number:
        if number_guessed > number:
            counter += 1
            number_guessed = input('Your guess is too high, try again. \n Your guess?')
        elif  number_guessed < number:
            counter += 1
            number_guessed = input("Your guess is too low, try again. \n Your guess?")

    print(f"Well done,{name}. You found my number in {counter} tries.")


# 곱하기 혹은 더하기

s = input()

ints = []
for i in s:
    if i != '0':
        ints.append(int(i))

ints.sort()
ans = ints[0]
for i in range(1, len(ints)):
    if ans == 1:
        ans += ints[i]
    if ints[i] == 1:
        ans += ints[i]
    else:
        ans *= ints[i]
print(ans)

# 풀이

data = input()

result = int(data[0])

for i in range(1, len(data)):
    num = int(data[i])
    if num <= 1 or result <= 1:
        result += num
    else:
        result *= num

print(result)


# Code by : Sam._.072

import sys
def MCM(a,s,e,dp):
    if s==e:
        return 0
    ans=sys.maxsize
    for k in range(s,e):
        if dp[s][k]==-1:
            ans1 = MCM(a, s, k, dp)
            dp[s][k] = ans1
        else:
            ans1 = dp[s][k]
        if dp[k+1][e]==-1:
            ans2 = MCM(a, k+1, e, dp)
            dp[k+1][e] = ans2
        else:
            ans2 = dp[k+1][e]

        t=ans1 + ans2 + a[s-1]*a[k]*a[e]
        ans = min(ans,t)
    return ans

if __name__=='__main__':
    n=int(input())
    a=list(map(int, input().split()))
    dp = [[-1 for j in range(n+1)] for i in range(n+1)]
    print(MCM(a, 1, n, dp))

Dynamic programming/Matrix Chain Multiplication.py