# Set up version information immediately
from ._version import get_versions  # isort:skip

__version__ = get_versions()["version"]  # isort:skip
del get_versions  # isort:skip

# 20210401 Will - Temporary fix to warn users against current incompatibility with Sqlalchemy 1.4.0
# To be removed once a better fix is implemented

from packaging.version import parse as parse_version

from great_expectations.exceptions.exceptions import GreatExpectationsError

try:
    import sqlalchemy as sa

    if parse_version(sa.__version__) >= parse_version("1.4.0"):
        raise GreatExpectationsError(
            f"""

        Great Expectations version {__version__} is currently incompatible with SqlAlchemy 1.4.0 and higher.
        You currently have SqlAlchemy version {sa.__version__}. Please downgrade SqlAlchemy to < 1.4.0 while we work on a proper fix.
        """
        )
except (ImportError, ModuleNotFoundError):
    pass

from great_expectations.data_context import DataContext

from .util import (
    from_pandas,
    get_context,
    measure_execution_time,
    read_csv,
    read_excel,
    read_feather,
    read_json,
    read_parquet,
    read_pickle,
    read_table,
    validate,
)

# from great_expectations.expectations.core import *
# from great_expectations.expectations.metrics import *

rtd_url_ge_version = __version__.replace(".", "_")


import os
import time
import sys

import random
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
plt.switch_backend('agg')

from mil import MIL
from tensorflow.examples.tutorials.mnist import input_data
from utils import np_sigmoid
from utils import print_metrics

os.environ["CUDA_VISIBLE_DEVICES"] = "3"
flags = tf.app.flags
FLAGS = flags.FLAGS
def get_data():
    path = "/home/wykgroup/seongok/ml_study/mnist_mlp/mnist/"
    mnist = input_data.read_data_sets(path, one_hot=False)
    train_set = mnist.train
    valid_set = mnist.validation
    test_set = mnist.test
    return train_set, valid_set, test_set

def instances_to_bag(ds, n_inst, target, n_bags=None):
    x = np.asarray([img.reshape(28,28) for img in ds.images])
    y = ds.labels

    n_total = x.shape[0]
    indices = np.random.randint(n_total, size=n_total)
    if n_bags is None:
        n_bags = n_total//n_inst

    x = x[indices]
    y = y[indices]

    x_bag = []
    y_bag = []
    for i in range(n_bags):
        xi = x[i*n_inst:(i+1)*n_inst]
        yi = y[i*n_inst:(i+1)*n_inst]

        label = 0.0
        if target in yi:
            label = 1.0
        x_bag.append(xi)
        y_bag.append(label)
    return np.asarray(x_bag), np.asarray(y_bag)

def train(opt_dict):
    train_set, valid_set, test_set = get_data()
    x_train, y_train = instances_to_bag(
        train_set, FLAGS.n_inst, FLAGS.target, n_bags=FLAGS.n_train_bags)
    x_valid, y_valid = instances_to_bag(valid_set, FLAGS.n_inst, FLAGS.target)
    x_test, y_test = instances_to_bag(valid_set, FLAGS.n_inst, FLAGS.target)

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())

        for epoch in range(FLAGS.n_epoches):
            # Train
            true_train = np.empty([0,])
            pred_train = np.empty([0,])
            for i in range(x_train.shape[0]):
                st_i = time.time()
                xi = x_train[i]
                yi = np.asarray([y_train[i]])

                feed_dict = {opt_dict.x:xi, opt_dict.y:yi}
                ops = [opt_dict.train_op, opt_dict.loss, opt_dict.logits]
                _, loss, logits = sess.run(ops, feed_dict=feed_dict)
                et_i = time.time()
                print ("Training", epoch, "-th epoch\t", \
                       i, "-th bag\t Loss=", loss,
                       "\t Time:", round(et_i-st_i,3), "(s)")

                true_train = np.concatenate([true_train, yi], axis=0)
                pred_train = np.concatenate([pred_train, np_sigmoid(logits)], axis=0)

            # Validation
            true_valid = np.empty([0,])
            pred_valid = np.empty([0,])
            for i in range(x_train.shape[0]):
                st_i = time.time()
                xi = x_valid[i]
                yi = np.asarray([y_valid[i]])

                feed_dict = {opt_dict.x:xi, opt_dict.y:yi}
                ops = [opt_dict.loss, opt_dict.logits]
                loss, logits = sess.run(ops, feed_dict=feed_dict)
                et_i = time.time()
                print ("Validation", epoch, "-th epoch\t", \
                       i, "-th bag\t Loss=", loss,
                       "\t Time:", round(et_i-st_i,3), "(s)")

                true_valid = np.concatenate([true_valid, yi], axis=0)
                pred_valid = np.concatenate([pred_valid, np_sigmoid(logits)], axis=0)
            print_metrics(true_train, pred_train)
            print_metrics(true_valid, pred_valid)

        # Test
        true_test = np.empty([0,])
        pred_test = np.empty([0,])
        for i in range(x_train.shape[0]):
            st_i = time.time()
            xi = x_test[i]
            yi = np.asarray([y_test[i]])

            feed_dict = {opt_dict.x:xi, opt_dict.y:yi}
            ops = [opt_dict.loss, opt_dict.logits]
            loss, logits = sess.run(ops, feed_dict=feed_dict)
            et_i = time.time()
            print ("Validation", epoch, "-th epoch\t", \
                   i, "-th bag\t Loss=", loss,
                   "\t Time:", round(et_i-st_i,3), "(s)")

            true_test = np.concatenate([true_test, yi], axis=0)
            pred_test = np.concatenate([pred_test, np_sigmoid(logits)], axis=0)
        print_metrics(true_test, pred_test)
        print ("Finish training and test")
    return

def main():
    model = MIL(hw=FLAGS.hw,
                ch=FLAGS.ch,
                attn_dim=FLAGS.attn_dim,
                use_attn=FLAGS.use_attn,
                use_gate=FLAGS.use_gate,
                wd=FLAGS.wd,
                lr=FLAGS.lr)
    opt_dict = model.get_opt_dict()
    train(opt_dict)
    return

if __name__ == '__main__':
    flags.DEFINE_integer('hw', 28, 'height and width')
    flags.DEFINE_integer('ch', 1, 'channel')
    flags.DEFINE_integer('attn_dim', 128, 'hidden dimension of attention')
    flags.DEFINE_integer('n_inst', 50, 'number of instances per bag')
    flags.DEFINE_integer('n_train_bags', 100, 'number of instances per bag')
    flags.DEFINE_integer('target', 9, 'target integer')
    flags.DEFINE_bool('use_attn', True, 'Whether to use the attn mechanism')
    flags.DEFINE_bool('use_gate', False, 'Whether to use the gate mechanism')
    flags.DEFINE_float('wd', 1e-4, 'weight_decay')
    flags.DEFINE_float('lr', 5e-4, 'Initial learning rate')
    flags.DEFINE_integer('n_epoches', 100, 'Epoch size')
    flags.DEFINE_bool('save_model', False, '')
    main()


import numpy as np

def system_simulate(state):
    """
    Simulation of poisson process on the system ->
    Poisson distributed number of trips out of each cluster, markov chain decides where the trip goes
    :param state: current state
    :return: flows generated by the system simulation
    """
    flow_counter = {
        (start, end): 0
        for start in np.arange(len(state.clusters))
        for end in np.arange(len(state.clusters))
        if start != end
    }
    trips = []
    lost_demand = []
    cluster_indices = np.arange(len(state.clusters))
    for i, start_cluster in enumerate(state.clusters):
        # poisson process to select number of trips in a iteration
        number_of_trips = round(
            np.random.poisson(start_cluster.trip_intensity_per_iteration)
        )

        # if there is more trips than scooters available, the system has lost demand
        valid_scooters = start_cluster.get_available_scooters()
        if number_of_trips > len(valid_scooters):
            lost_demand.append(number_of_trips - len(valid_scooters))
            number_of_trips = len(valid_scooters)

        leave_distribution = start_cluster.get_leave_distribution()
        end_cluster_indices = np.random.choice(
            cluster_indices, p=leave_distribution, size=number_of_trips
        )
        # loop to generate trips from the cluster
        for j, end_cluster_index in enumerate(end_cluster_indices):
            trips.append(
                (
                    start_cluster,
                    state.clusters[end_cluster_index],
                    valid_scooters.pop(0),
                )
            )
            flow_counter[(start_cluster.id, end_cluster_index)] += 1

    # compute trip after all trips are generated to avoid handling inflow in cluster
    for start_cluster, end_cluster, scooter in trips:
        start_cluster.scooters.remove(scooter)
        trip_distance = state.get_distance_locations(start_cluster, end_cluster)
        scooter.travel(trip_distance)
        end_cluster.add_scooter(scooter)

    return (
        [(start, end, flow) for (start, end), flow in list(flow_counter.items())],
        trips,
        sum(lost_demand),
    )


#!/usr/bin/env python3

"""
Internet Programming in Python: Session 01

Homework

Your homework assignment for this week is to take what you've learned here and
build a simple "echo" server.

The server should automatically return to any client that connects exactly what
it receives (it should echo all messages).

You will also write a python script that, when run, will send a message to the
server and receive the reply, printing it to stdout.

Finally, you'll do all of this so that it can be tested.

Notes:

    - Server will echo but not accumulate messages
    - KeyboardInterrupt works with control-c
    - More comments than code :-P

"""

import socket

import sys

def server(log_buffer=sys.stderr):
    # set an address for our server
    address = ('127.0.0.1', 10000)
    # xTODO: Replace the following line with your code which will instantiate
    #       a TCP socket with IPv4 Addressing, call the socket you make 'sock'
    # sock = None

    # socket family for IPV4 is "AF_INET"
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)

    # xTODO: You may find that if you repeatedly run the server script it
    #   fails,
    #       claiming that the port is already used.  You can set an option on
    #       your socket that will fix this problem. We DID NOT talk about this
    #       in class. Find the correct option by reading the very end of the
    #       socket library documentation:
    #       http://docs.python.org/3/library/socket.html#example

    # "This is because the previous execution has left the socket in a
    #   TIME_WAIT state, and can’t be immediately reused.
    # There is a socket flag to set, in order to prevent this,
    #   socket.SO_REUSEADDR:
    # s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    # s.bind((HOST, PORT))"

    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # log that we are building a server
    print("making a server on {0}:{1}".format(*address), file=log_buffer)

    # xTODO: bind your new sock 'sock' to the address above and begin to listen
    #       for incoming connections

    sock.bind(address)

    sock.listen(1)

    try:
        # the outer loop controls the creation of new connection sockets. The
        # server will handle each incoming connection one at a time.
        while True:
            print('waiting for a connection', file=log_buffer)

            # xTODO: make a new socket when a client connects, call it 'conn',
            #       at the same time you should be able to get the address of
            #       the client so we can report it below.  Replace the
            #       following line with your code. It is only here to prevent
            #       syntax errors
            # addr = ('bar', 'baz')

            conn, addr = sock.accept()

            try:
                print('connection - {0}:{1}'.format(*addr), file=log_buffer)

                # the inner loop will receive messages sent by the client in
                # buffers.  When a complete message has been received, the
                # loop will exit
                while True:
                    # xTODO: receive 16 bytes of data from the client. Store
                    #       the data you receive as 'data'.  Replace the
                    #       following line with your code.  It's only here as
                    #       a placeholder to prevent an error in string
                    #       formatting
                    # data = b''

                    data = conn.recv(16)

                    print('received "{0}"'.format(data.decode('utf8')))

                    # xTODO: Send the data you received back to the client, log
                    # the fact using the print statement here.  It will help in
                    # debugging problems.

                    conn.sendall(data)

                    print('sent "{0}"'.format(data.decode('utf8')))

                    # xTODO: Check here to see if the message you've received
                    #   is
                    # complete.  If it is, break out of this inner loop.

                    if len(data) < 16:
                        break

            finally:
                # xTODO: When the inner loop exits, this 'finally' clause will
                #       be hit. Use that opportunity to close the socket you
                #       created above when a client connected.

                # sock.close()
                # If I close this here, it never gets re-established

                # @christy
                # Line 123 of echo_server - Looks like you were trying to
                #   close the socket here, but you should close the connection
                #   here (the conn variable).

                # This doesn't stop the tests from passing, but the server
                #   connection never closes.

                # Otherwise, looks good!

                conn.close()

                print(
                    'echo complete, client connection closed', file=log_buffer
                )

    except KeyboardInterrupt:
        # xTODO: Use the python KeyboardInterrupt exception as a signal to
        #       close the server socket and exit from the server function.
        #       Replace the call to `pass` below, which is only there to
        #       prevent syntax problems
        # pass

        sock.close()

        print('quitting echo server', file=log_buffer)

if __name__ == '__main__':
    server()
    sys.exit(0)


#!/usr/bin/env python

from datetime import datetime

import setuptools # have to do this to be able to setup.py develop
from numpy.distutils.core import setup
from numpy import get_include

DESCRIPTION=""
LONG_DESCRIPTION="""
"""

DISTNAME = 'pymaclab'
LICENSE = 'BSD'
AUTHOR = "Skipper Seabold, E.M. Scheffel"
MAINTAINER = "Skipper Seabold"
MAINTAINER_EMAIL = "jsseabold@gmail.com"
URL = ''
DOWNLOAD_URL=""
CLASSIFIERS=[]

MAJOR = 0
MINOR = 0
MICRO = 1
ISRELEASED = False
VERSION = '%d.%d.%d' % (MAJOR, MINOR, MICRO)
FULLVERSION = VERSION
if not ISRELEASED:
    FULLVERSION += '.dev'

def write_version_py(filename='./version.py'):
    cnt = """\
from datetime import datetime

version = '%s'
"""
    a = open(filename, 'w')
    try:
        a.write(cnt % FULLVERSION)
    finally:
        a.close()

def configuration(parent_package='', top_path=None, package_name=DISTNAME):
#    write_version_py()

    from numpy.distutils.misc_util import Configuration
    config = Configuration(None, parent_package, top_path,
                           version=FULLVERSION)
    config.set_options(ignore_setup_xxx_py=True,
                       assume_default_configuration=True,
                       delegate_options_to_subpackages=True,
                       quiet=True)

    config.add_subpackage('pymaclab')
    return config

if __name__ == '__main__':
    setup(name=DISTNAME,
          maintainer=MAINTAINER,
          maintainer_email=MAINTAINER_EMAIL,
          description=DESCRIPTION,
          license=LICENSE,
          url=URL,
          download_url=DOWNLOAD_URL,
          long_description=LONG_DESCRIPTION,
          classifiers=CLASSIFIERS,
          platforms='any',
          configuration=configuration)


"""
Tokyo Quantopian User Group handson Vol1
アルゴリズムその2：単純な先物の取引
continuous_future つなぎ足 を使って取引
"""

def initialize(context):
    # 原油期近つなぎ足
    context.my_future = continuous_future('CL',
                                          offset=0, # 限月．期近＝0，2番限＝1，3番限=2，・・・
                                          roll='calendar', # ロールするタイミング
                                          adjustment='mul' # アジャスト方法
                                         )
    schedule_function(my_rebalance,
                      date_rule=date_rules.every_day(),
                      time_rule=time_rules.market_open(hours=1))

    log.info(context.my_future.to_dict())

def my_rebalance(context, data):
    """
    過去2日間の価格を取得して，前日比マイナスであればショート
    """
    cl_price = data.history(context.my_future,
                            fields ='price',
                            bar_count = 2,
                            frequency = '1d')

    # コントラクト
    cl_contract = data.current(context.my_future, 'contract')
    log.info(cl_price.pct_change()[1])

    if cl_price.pct_change()[1] < 0:
        log.info("order short %s" % cl_price.pct_change()[1])
        order_target_percent(cl_contract, -1)

    else:
        order_value(cl_contract, 0)

algorithms/TQUG Vol4 #1/backtests/Backtest 2-5b2ee16be2858842ffa56261.py


import datetime

class Denarnica:

    def __init__(self, stanje = 0):
        self.stanje = stanje
        self.slovar = {}

    def __repr__(self):
        return 'Denarnica(stanje = {})'.format(self.stanje)

    def __str__(self):
        return 'Denarnica z {}€ '.format(self.stanje)

    def dodaj_v_slovar(self, ime_izdelka, cena, kolicina):
        if self.slovar.get(ime_izdelka) == None :
            self.slovar[ime_izdelka] = [kolicina * cena, kolicina]
        else:
            self.slovar[ime_izdelka][0] += kolicina * cena
            self.slovar[ime_izdelka][1] += kolicina

    def kupi_izdelek(self, ime_izdelka, cena, kolicina):
        if ime_izdelka == '':
            return 'Ups, prišlo je do napake, ime izdelka mora vsebovati vsaj en znak.'
        elif cena <= 0 or kolicina <= 0:
            return 'Ups, prišlo je do napake, cena in količina morata biti večji od 0.'
        elif kolicina * cena > self.stanje:
            return 'Žal nimate dovolj denarja za ta nakup!'
        else:
            self.stanje -= kolicina * cena
            x = datetime.datetime.now().strftime("%d.%m.%Y %H:%M:%S")
            self.dodaj_v_slovar(ime_izdelka, cena, kolicina)
            with open('denarnica.txt', 'a') as dat:
                print(ime_izdelka, '-' +  str(kolicina * cena) + '€', x, sep = ', ', file = dat)
            return 'Izdelek ste uspešno kupili.'

    def placaj_poloznico(self, namen_poloznice, znesek):
        if namen_poloznice == '':
            return 'Ups, prišlo je do napake, namen položnice mora vsebovati vsaj en znak.'
        elif znesek <= 0:
            return 'Ups, prišlo je do napake, znesek položnice mora biti večji od 0 €.'
        elif znesek > self.stanje:
            return 'Ups, te položnice pa ne morete plačati!'
        else:
            self.stanje -= znesek
            x = datetime.datetime.now().strftime("%d.%m.%Y %H:%M:%S")
            self.dodaj_v_slovar(namen_poloznice, znesek, 1)
            with open('denarnica.txt', 'a') as dat:
                print(namen_poloznice, '-' +  str(znesek) + '€', x, sep = ', ', file = dat)
            return 'Položnico ste uspešno plačali.'

    def prihodek(self, opis_prihodka, velikost_prihodka):
        if opis_prihodka == '':
            return 'Ups, prišlo je do napake, opis prihodka mora vsebovati vsaj en znak.'
        elif velikost_prihodka <= 0:
            return 'Ups, prišlo je do napake, velikost prihodka mora biti večja od 0 €.'
        self.stanje += velikost_prihodka
        x = datetime.datetime.now().strftime("%d.%m.%Y %H:%M:%S")
        with open('denarnica.txt', 'a') as dat:
            print(opis_prihodka,'+' + str(velikost_prihodka) + '€', x, sep = ', ', file = dat)
        return 'Vaše stanje se je povišalo na {}€'.format(self.stanje)

    def poraba_na_izdelek(self, ime_izdelka):
        if self.slovar.get(ime_izdelka) == None:
            return 'Tega izdelka še niste kupili.'
        else:
            return 'Za ta izdelek ste porabili {} €.'.format(self.slovar[ime_izdelka][0])

    def kolicina_na_izdelek(self, ime_izdelka):
        if self.slovar.get(ime_izdelka) == None:
            return 'Tega izdelka še niste kupili.'
        else:
            return 'Kupili ste {} izdelkov.'. format(self.slovar[ime_izdelka][1])

def izpis_prihodkov_in_dohodkov():
    izpis = ''
    with open('denarnica.txt') as dat:
        for vrstica in dat:
            izpis += vrstica
    return izpis

import pickle

def shrani_denarnico(denarnica):
    '''shrani podatke denarnice za prihodno uporabo'''
    with open('denarnice_podatki.pkl', 'wb') as output:
        pickle.dump(denarnica,output)

def nalozi_denarnico():
    '''nalozi podatke denarnice od predhodnje uporabe'''
    with open('denarnice_podatki.pkl', 'rb') as input:
        denarnica = pickle.load(input)
    return denarnica


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

<DefineSource>
@Date : Fri Nov 14 13:20:38 2014 \n
@Author : Erwan Ledoux \n\n
</DefineSource>

A Structurer

"""

#<DefineAugmentation>
import ShareYourSystem as SYS
BaseModuleStr="ShareYourSystem.Standards.Itemizers.Connecter"
DecorationModuleStr="ShareYourSystem.Standards.Classors.Classer"
SYS.setSubModule(globals())
SYS.addDo('Structurer','Structure','Structuring','Structured')
#</DefineAugmentation>

#<ImportSpecificModules>
Connecter=BaseModule
#</ImportSpecificModules>

#<DefineLocals>
StructureOutPrefixStr='_Struc_'
StructureInTeamKeyStr='Structures'
#</DefineLocals>

#<DefineClass>
@DecorationClass()
class StructurerClass(BaseClass):

	def default_init(
					self,
					_StructureTagStr='Top',
					_StructureTopDeriveStructurerRigidVariable=None,
					_StructureTeamerCommandKeyRigidVariable=None,
					_StructureManagerCommandKeyRigidVariable=None,
					_StructureTeamerCommandSetRigidList=None,
					_StructureManagerCommandSetRigidList=None,
					_StructureTargetStr='Top',
					_StructureConnectPrefixStrsList=None,
					_StructureFilterTeamTagStrsList=None,
					_StructuringTeamerCommandKeyVariable=None,
					_StructuringManagerCommandKeyVariable=None,
					_StructuringBeforeCommandSetList=None,
					_StructuringTeamerCommandSetList=None,
					_StructuringManagerCommandSetList=None,
					_StructuringSingPluralVariable=None,
					_StructuringTagStr="",
					_StructuringClassBool=True,
					_StructuringFlatBool=False,
					_StructuredTeamKeyStrsList=None,
					_StructuredOnceBool=False,
					**_KwargVariablesDict
				):

		#Call the parent init method
		BaseClass.__init__(self,**_KwargVariablesDict)

		#init
		self.StructureTopDeriveStructurerRigidVariable=self

	def do_structure(self):

		#/###################/#
		# Check the level
		#

		#debug
		'''
		self.debug(
			[
				'We structure here',
				'self.StructureTopDeriveStructurerRigidVariable==self is ',
				str(self.StructureTopDeriveStructurerRigidVariable==self)
			]
		)
		'''

		#set
		self.StructureTopDeriveStructurerRigidVariable=self

		#debug
		'''
		self.debug(
			[
				'We are in the top structurer',
			]
		)
		'''

		#debug
		'''
		self.debug(
				[
					'We structure top here',
					('self.',self,[
							'StructuringTeamerCommandKeyVariable',
							'StructuringManagerCommandKeyVariable'
						])
				]
			)
		'''

		#/###################/#
		# Set the structure of singular team if not already
		#

		#Check
		if self.StructuredOnceBool==False:

			#Check
			if self.StructuringSingPluralVariable!=None:

				#debug
				'''
				self.debug(
					[
						'we structure for the first time here',
						('self.',self,['StructuringSingPluralVariable'])
					]
				)
				'''

				#map add the sing plurals
				map(
					lambda __ItemTuple:
					SYS.addSingPlural(
						*__ItemTuple
					),
					SYS.SetList(self.StructuringSingPluralVariable)
				)

				#Define a class
				class StructureClass(StructurerClass):pass
				StructureClass.__name__=self.NameStr+'s'
				StructureClass.ManagingValueClass=self.__class__

				#set
				setattr(
					self.Module,
					StructureClass.__name__,
					StructureClass
				)

				#dict
				ClassesDict=dict(
						map(
							lambda __ItemTuple:
							(__ItemTuple[1],StructureClass),
							_SingPluralVariable
						)
					)

				#Check
				if self.StructuringClassBool:

					#map
					if _Class.TeamingClassesDict==None:
						_Class.TeamingClassesDict=ClassesDict
					else:
						_Class.TeamingClassesDict.update(
							ClassesDict
						)

					#set
					self.__class__.StructuringOnceBool=True

				else:

					#map
					if self.TeamingClassesDict==None:
						self.TeamingClassesDict=ClassesDict
					else:
						self.TeamingClassesDict.update(
							ClassesDict
						)

				#set
				self.StructuredOnceBool=True

		#Check
		if self.StructuringFlatBool:

			#/##################/#
			# prepare the struc teams
			#

			#map
			self.StructuredTeamKeyStrsList=map(
					lambda __StructuringTeamOrManagementStr:
					StructureOutPrefixStr+self.StructuringTagStr+'_'+__StructuringTeamOrManagementStr,
					(self.StructuringTeamerCommandKeyVariable if self.StructuringTeamerCommandKeyVariable!=None else [])+
					(self.StructuringManagerCommandKeyVariable if self.StructuringManagerCommandKeyVariable!=None else [])
				)

			#debug
			'''
			self.debug(
					[
						'We are going to make team the StructuredTeamKeyStrsList',
						('self.',self,['StructuredTeamKeyStrsList'])
					]
				)
			'''

			#map
			map(
					lambda __StructuredTeamKeyStr:
					self.team(__StructuredTeamKeyStr),
					self.StructuredTeamKeyStrsList
				)

		#/##################/#
		# we make the top parent and structure
		#

		#set
		self.StructureTopDeriveStructurerRigidVariable=self
		self.parent()

		#/##################/#
		# command
		#

		#debug
		'''
		self.debug(
			[
				'Before command we set the arg'
			]
		)
		'''

		#link for setCommandingKeyVariable
		self.StructureTeamerCommandKeyRigidVariable=self.StructuringTeamerCommandKeyVariable
		self.StructureManagerCommandKeyRigidVariable=self.StructuringManagerCommandKeyVariable
		self.setCommandingKeyVariable()

		#link for setCommandingSetVariable
		self.CommandTopDeriveCommanderRigidVariable=self
		self.StructureTeamerCommandSetRigidList=self.StructuringTeamerCommandSetList
		self.StructureManagerCommandSetRigidList=self.StructuringManagerCommandSetList
		self.setCommandingSetVariable()

		#Other
		self.CommandingAfterWalkRigidBool=True
		self.CommandingGetRigidBool=False
		self.CommandingSetRigidBool=False
		self.CommandingSetAttrOrCallRigidBool=True

		#debug
		'''
		self.debug(
			[
				'we are going to command',
				('self.',self,[
					'CommandingKeyVariable',
					'CommandingSetVariable'
				])
			]
		)
		'''

		#command
		self.command()

		#debug
		'''
		self.debug(
			[
				'Ok we have commanded'
			]
		)
		'''

	def setCommandingKeyVariable(self):

		#/##################/#
		# Switch case depending on the team or manage level
		#

		#debug
		'''
		self.debug(
			[
				'We setCommandingKeyVariable here',
				('self.',self,[
					'TeamedOnceBool',
					'StructureTeamerCommandKeyRigidVariable',
					'StructureManagerCommandKeyRigidVariable'
				]),
				'We get the good team or management keys'
			]
		)
		'''

		#Check
		if self.TeamedOnceBool:

			#/##################/#
			#  get
			#

			#get
			StructureTeamerCommandKeyRigidVariable=getattr(
				self,
				'StructureTeamerCommandKeyRigidVariable'
			)

			#debug
			'''
			self.debug(
				[
					'StructureTeamerCommandKeyRigidVariable is ',
					SYS._str(StructureTeamerCommandKeyRigidVariable)
				]
			)
			'''

			#/###############/#
			# Determine the CommandedLiargVariablesList
			#

			#Check
			if StructureTeamerCommandKeyRigidVariable==None:

				#all the key
				StructureKeyStrsList=[]

			#Check
			elif type(StructureTeamerCommandKeyRigidVariable)==list and len(
				StructureTeamerCommandKeyRigidVariable
			)>0 and type(
				StructureTeamerCommandKeyRigidVariable[0]
			)==str:

				#alias
				StructureKeyStrsList=StructureTeamerCommandKeyRigidVariable

			#Check
			elif StructureTeamerCommandKeyRigidVariable=="#all":

				#all the key
				StructureKeyStrsList=self.TeamDict.keys()

			else:

				#mapCondition
				StructureKeyStrsList=self.mapCondition(
					StructureTeamerCommandKeyRigidVariable,
					self.TeamDict.keys(),
					_SetAttrOrCallBool=True
				)

			#/###############/#
			# Now get and filter in the team
			#

			#debug
			'''
			self.debug(
				[
					'We get the managed values in the Teamer',
					'StructureKeyStrsList is ',
					SYS._str(StructureKeyStrsList)
				]
			)
			'''

			#set
			setattr(
				self,
				'CommandingKeyVariable',
				SYS.filterNone(
				map(
					lambda __KeyStr:
					self.TeamDict[__KeyStr]
					if __KeyStr in self.TeamDict
					else None,
					StructureKeyStrsList
					)
				)
			)

		else:

			#/###############/#
			# Determine the CommandedLiargVariablesList
			#

			#debug
			'''
			self.debug(
				[
					'We setCommandingKeyVariable in a manager',
					('self.',self,['StructuringManagerCommandKeyVariable'])
				]
			)
			'''

			#/##################/#
			#  get
			#

			#get
			StructureManagerCommandKeyRigidVariable=getattr(
				self,
				'StructureManagerCommandKeyRigidVariable'
			)

			#/##################/#
			# Sort the dict
			#

			#debug
			'''
			self.debug(
				[
					'before sort',
					'self.ManagementDict.keys() is ',
					SYS._str(self.ManagementDict.keys())
				]
			)
			'''

			#sort
			self.ManagementDict.sort()

			#debug
			'''
			self.debug(
				[
					'after sort',
					'self.ManagementDict.keys() is ',
					SYS._str(self.ManagementDict.keys())
				]
			)
			'''

			#/##################/#
			# determine the StructureKeyStrsList
			#

			#Check
			if StructureManagerCommandKeyRigidVariable==None:

				#all the key
				StructureKeyStrsList=[]

			#Check
			elif type(StructureManagerCommandKeyRigidVariable
			)==list and len(StructureManagerCommandKeyRigidVariable
				)>0 and type(StructureManagerCommandKeyRigidVariable[0])==str:

				#alias
				StructureKeyStrsList=StructureManagerCommandKeyRigidVariable

			#Check
			elif StructureManagerCommandKeyRigidVariable=="#all":

				#all the key
				StructureKeyStrsList=self.ManagementDict.keys()

			else:

				#mapCondition
				StructureKeyStrsList=self.mapCondition(
					StructureManagerCommandKeyRigidVariable,
					self.ManagementDict.keys(),
					_SetAttrOrCallBool=True
				)

			#/###############/#
			# Now get and filter in the management
			#

			#debug
			'''
			self.debug(
				[
					'We get the teamed values in the Manager',
					'StructureKeyStrsList is ',
					str(StructureKeyStrsList)
				]
			)
			'''

			#filterNone
			CommandingKeyVariable=SYS.filterNone(
						map(
							lambda __KeyStr:
							self.ManagementDict[__KeyStr]
							if __KeyStr in self.ManagementDict
							else None,
							StructureKeyStrsList
						)
					)

			#/##################/#
			# Maybe sort
			#

			"""
			#debug
			self.debug(
				[
					'before sort',
					'CommandingKeyVariable is ',
					SYS._str(CommandingKeyVariable)
				]
			)

			#sort
			CommandingKeyVariable=SYS.sort(
					CommandingKeyVariable
				)

			#debug
			self.debug(
				[
					'after sort',
					'CommandingKeyVariable is ',
					SYS._str(CommandingKeyVariable)
				]
			)
			"""

			#set
			setattr(
				self,
				'CommandingKeyVariable',
				CommandingKeyVariable
			)

	def setCommandingSetVariable(self):

		#/##################/#
		# Switch case depending on the team or manage level
		#

		#debug
		'''
		self.debug(
			[
				'We setCommandingSetVariable here',
				('self.',self,[
					'TeamedOnceBool',
					'StructuringTeamerCommandSetList',
					'StructuringManagerCommandSetList'
				])
			]
		)
		'''

		#Check
		if self.TeamedOnceBool:

			#alias
			self.CommandingSetVariable=self.StructureTeamerCommandSetRigidList

		else:

			#alias
			self.CommandingSetVariable=self.StructureManagerCommandSetRigidList

		#debug
		'''
		self.debug(
			[
				'Now we add the before with the special',
				'self.CommandTopDeriveCommanderRigidVariable==self is ',
				str(self.CommandTopDeriveCommanderRigidVariable==self)
			]
		)
		'''

		#init
		CommandingSetVariable=[
					('StructureTopDeriveStructurerRigidVariable',self.CommandTopDeriveCommanderRigidVariable),
					('StructureTeamerCommandKeyRigidVariable',self.StructureTeamerCommandKeyRigidVariable),
					('StructureManagerCommandKeyRigidVariable',self.StructureManagerCommandKeyRigidVariable),
					('StructureTeamerCommandSetRigidList',self.StructureTeamerCommandSetRigidList),
					('StructureManagerCommandSetRigidList',self.StructureManagerCommandSetRigidList),
					('parent')
		]

		#add
		self.CommandingSetVariable=CommandingSetVariable+self.CommandingSetVariable+[
			('setCommandingKeyVariable'),
			('setCommandingSetVariable'),
			('StructureTopDeriveStructurerRigidVariable',None),
			('StructureTeamerCommandKeyRigidVariable',None),
			('StructureManagerCommandKeyRigidVariable',None),
			('StructureTeamerCommandSetRigidList',None),
			('StructureManagerCommandSetRigidList',None),
		]

		#debug
		'''
		self.debug(
			[
				'In the end',
				('self.',self,['CommandingSetVariable'])
			]
		)
		'''

	def propertize_setWatchAfterParentWithParenterBool(self,_SettingValueVariable):

		#/##################/#
		# Call the base method
		#

		#debug
		'''
		self.debug(
			[
				'First we call the base method',
				('self.',self,[
							'StructuringTeamerCommandKeyVariable',
							'StructuringManagerCommandKeyVariable'
						])
			]
		)
		'''

		#call the base method
		BaseClass.propertize_setWatchAfterParentWithParenterBool(self,_SettingValueVariable)

		#debug
		'''
		self.debug(
			[
				'We have called the base method',
				('self.',self,[
							'StructuringTeamerCommandKeyVariable',
							'StructuringManagerCommandKeyVariable'
						])
			]
		)
		'''

		#/##################/#
		# Set the StructureTagStr
		#

		#debug
		'''
		self.debug(
				[
					'We have parented',
					'we set the control path str',
					('self.',self,[
							'ParentedTotalPathStr',
							'ManagementTagStr'
						])
				]
			)
		'''

		#Check
		if self.ManagementTagStr!='':

			#get
			self.StructureTagStr=(
					self.ParentedTotalPathStr+'/'+self.ManagementTagStr
				).replace('/','_')

		#remove
		if self.StructureTagStr[0]=='_':
			self.StructureTagStr=self.StructureTagStr[1:]

		#/##################/#
		# Maybe do some connections
		#

		#debug
		'''
		self.debug(
			[
				'We do here maybe some connections',
				('self.',self,['StructureConnectPrefixStrsList'])
			]
		)
		'''

		#Check
		if self.StructureConnectPrefixStrsList!=None:

			#debug
			'''
			self.debug(
				[
					'We do here some connections',
					('self.',self,['StructureConnectPrefixStrsList'])
				]
			)
			'''

			#map
			map(
				lambda __StructureConnectPrefixStr:
				self.mapConnect(__StructureConnectPrefixStr),
				self.StructureConnectPrefixStrsList
			)

	def mimic__print(self,**_KwargVariablesDict):

		#/##################/#
		# Modify the printing Variable
		#

		#Check
		if self.PrintingSelfBool:

			#/##################/#
			# Simplify the repr of the flatted teams
			#

			#Check
			if type(self.StructuredTeamKeyStrsList)==list:

				#map
				map(
					lambda __StructuredTeamKeyStr:
					self.PrintingCopyVariable.TeamDict.__setitem__(
						__StructuredTeamKeyStr,
						"Pointer with "+str(
							len(
								self.PrintingCopyVariable.TeamDict[
									__StructuredTeamKeyStr
								].ManagementDict
							)
						)+" managed encapsulations"
					),
					self.StructuredTeamKeyStrsList
				)

			#/##################/#
			# Simplify also the repr of the structures team
			#

			#Check
			if StructureInTeamKeyStr in self.TeamDict:

				#set
				self.PrintingCopyVariable.TeamDict[
					StructureInTeamKeyStr
				]="Pointer with "+str(
							len(
								self.PrintingCopyVariable.TeamDict[
									StructureInTeamKeyStr
								].ManagementDict
							)
						)+" managed encapsulations"

		#/##################/#
		# Call the base method
		#

		#call
		BaseClass._print(self,**_KwargVariablesDict)

#</DefineClass>

#<DefineLocals>

#set
StructurerClass.ManagingValueClass=StructurerClass
StructurerClass.TeamingValueClass=StructurerClass

#</DefineLocals>

#</DefinePrint>
StructurerClass.PrintingClassSkipKeyStrsList.extend(
	[
		'StructureTagStr',
		'StructureTopDeriveStructurerRigidVariable',
		'StructureTeamerCommandKeyRigidVariable',
		'StructureManagerCommandKeyRigidVariable',
		'StructureTeamerCommandSetRigidList',
		'StructureManagerCommandSetRigidList',
		'StructureTargetStr',
		'StructureConnectPrefixStrsList',
		'StructureFilterTeamTagStrsList',
		'StructuringTeamerCommandKeyVariable',
		'StructuringManagerCommandKeyVariable',
		'StructuringBeforeCommandSetList',
		'StructuringTeamerCommandSetList',
		'StructuringManagerCommandSetList',
		'StructuringSingPluralVariable',
		'StructuringTagStr',
		'StructuringClassBool',
		'StructuringFlatBool',
		'StructuredTeamKeyStrsList',
		'StructuredOnceBool'
	]
)
#<DefinePrint>


# -*- coding: utf-8 -*-
"""
Created on Tue Apr 28 17:09:06 2020

@author: Radovan
"""

from objfun import ObjFun
import numpy as np

class MMM(ObjFun):

    def __init__(self, dim):
        self.dim = dim or 2
        self.fstar = -4.97750248659 * self.dim
        self.a = -2 * np.ones(self.dim)
        self.b = 2 * np.ones(self.dim)

    def generate_point(self, num=1):
        return self.a + np.random.rand(num, self.dim) * (self.b - self.a)

    def evaluate(self, x):
        xx = x.reshape([-1, self.dim])
        y = -(3*xx**2*np.cos(xx)+xx**2*np.cos(4*xx)-xx**2*np.cos(8*xx))+(12*np.cos(2)+4*np.cos(8)-4*np.cos(16))
        y = np.sum(y, axis=1)
        return y


#!/usr/bin/env python3
import time, sys, os
from scripts.pscreen import Screen
from scripts.game import Game

################################
# CONSTANTS
WIDTH = 80
HEIGHT = 24
LOG_MAX = 8
STEP = 1/10

################################
# Main app
class App:
	def __init__(self):
		# Set working directory
		os.chdir(sys.path[0])

		# Create screen
		self.screen = Screen(WIDTH, HEIGHT)

		# Debug text log
		self.log_text = []

	def main(self):
		# Create game
		self.speed = 1.0
		self.game = Game(self, WIDTH, HEIGHT-2)

		# Main loop
		while True:
			self.update()
			self.render()
			time.sleep(STEP*self.speed)

	def update(self):
		# Update keyboard events
		self.screen.update()

		# ESC = quit
		if self.screen.down("esc"): self.quit()

		# Update game
		self.game.update()

	def render(self):
		# Clear screen
		self.screen.clear()

		# Render game
		self.game.render()

		# Render screen
		self.screen.render()

	def quit(self, exit_py=True):
		# Destructor
		self.screen.destroy()
		if exit_py: sys.exit()

	def log(self, *args):
		# Add text to debug logs
		self.log_text.append(" ".join([str(x) for x in args]))
		if len(self.log_text) > LOG_MAX:
			self.log_text.pop(0)

################################
# Application start
if __name__ == "__main__":
	try:
		app = App()
		app.main()
	except KeyboardInterrupt:
		pass
	finally:
		if app: app.quit(False)


# _author: tao wang
# _date: 2019/5/20
from Android_tapai.businessView.PostView import EnterPost
from Android_tapai.common.Android_Main import appium_desired
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
import logging
import random
import time

class VideoView(EnterPost):
    __recordMBtn = (By.ID, "com.maibo.android.tapai:id/recordIMBtn")  # 录制button
    __tabTV = (By.ID, "com.maibo.android.tapai:id/tabTV")  # 切换相册
    __draft = (By.ID, "com.maibo.android.tapai:id/draft_thumbnail")  # 选择视频
    __musicIMG = (By.ID, "com.maibo.android.tapai:id/selectMusicIMG")  # 拍摄页面音乐
    __propsIMG = (By.ID, "com.maibo.android.tapai:id/ivSelectSticker")  # 拍摄页面道具
    __next = (By.ID, "com.maibo.android.tapai:id/nextTv")  # 下一步按钮
    __recordBtn = (By.ID, "com.maibo.android.tapai:id/recordBtn")  # 结束录制
    __propsBtn = (By.ID, "com.maibo.android.tapai:id/videoPublish_ivSelectSticker")  # 道具
    __describeBtn = (By.ID, "com.maibo.android.tapai:id/video_deseTv")  # 描述
    __musicBtn = (By.ID, "com.maibo.android.tapai:id/video_musicIm")  # 音乐
    __coverBtn = (By.ID, "com.maibo.android.tapai:id/video_coverTv")  # 封面
    __saveBtn = (By.ID, "com.maibo.android.tapai:id/video_save")  # 保存
    __publishBtn = (By.ID, "com.maibo.android.tapai:id/publishBtn")  # 发布
    __anonymousBtn = (By.ID, "com.maibo.android.tapai:id/anonymous_tv")  # 匿名
    __coverIMG = (By.ID, "com.maibo.android.tapai:id/coverIMG")  # 选择道具
    __useBtn = (By.ID, "com.maibo.android.tapai:id/useTV")  # 使用
    __mood_video = (By.ID, "com.maibo.android.tapai:id/video_cover_item_tv")  # 选择文字
    __nextBtn = (By.ID, "com.maibo.android.tapai:id/nextTv")  # 完成
    __ediTextBtn = (By.ID, "com.maibo.android.tapai:id/default_editext")  # 文本区域
    __thumbnailBtn = (By.ID, "com.maibo.android.tapai:id/iv_thumbnail")  # 选择封面
    __text_style = (By.ID, "com.maibo.android.tapai:id/ci_text_style")  # 选择文本
    __add_text = (By.ID, "com.maibo.android.tapai:id/add_text")  # 封面文字
    __useIMG = (By.ID, "com.maibo.android.tapai:id/tv_use")  # 封面的使用

    def video_picture(self, video_type, props_type, video_time=3, line_number=1):
        self.choose_video()

        if video_type == 0:
            logging.info('选择拍摄普通视频')
            if props_type == 0:
                logging.info('准备选择道具')
                self.driver.find_element(*self.__propsIMG).click()
                for i in range(2):
                    self.driver.find_elements(*self.__coverIMG)[1].click()
                    time.sleep(2)
                self.get_swipe(0.5, 0.5, 0.5, 0.5, 50)

                logging.info('准备选择音乐')
                self.driver.find_element(*self.__musicIMG).click()
                for i in range(2):
                    self.driver.find_elements(*self.__coverIMG)[2].click()
                    time.sleep(2)
                self.driver.find_element(*self.__useBtn).click()
            else:
                logging.info('不选择音乐和道具')

        elif video_type == 1:
            logging.info('选择拍摄心情视频')
            self.driver.find_elements(*self.__tabTV)[1].click()

        elif video_type == 2:
            logging.info('选择拍摄本地视频')
            self.driver.find_elements(*self.__tabTV)[0].click()
            draft_random = random.choice(range(8))
            self.driver.find_elements(*self.__draft)[draft_random].click()
            self.driver.find_element(*self.__next).click()

        else:
            logging.info('请输入正确的值')

        if video_type == 0 or video_type == 1:
            logging.info('开始录制%s秒' % video_time)
            self.driver.find_element(*self.__recordMBtn).click()
            time.sleep(video_time)
            try:
                self.driver.find_element(*self.__recordBtn)
            except NoSuchElementException:
                logging.info('这个页面又超时了')
            else:
                self.driver.find_element(*self.__recordBtn).click()

        if props_type == 0:

            logging.info('选择道具')
            self.driver.find_element(*self.__propsBtn).click()
            for i in range(2):
                self.driver.find_elements(*self.__coverIMG)[3].click()
                time.sleep(2)
            self.get_swipe(0.5, 0.5, 0.5, 0.5, 50)

            logging.info('选择音乐')
            self.driver.find_element(*self.__musicBtn).click()
            for i in range(2):
                self.driver.find_elements(*self.__coverIMG)[4].click()
                time.sleep(2)
            self.driver.find_element(*self.__useBtn).click()

            logging.info('点击保存')
            self.driver.find_element(*self.__saveBtn).click()

            try:
                self.driver.find_element(*self.__describeBtn)
            except NoSuchElementException:
                logging.info('选择封面')
                self.driver.find_element(*self.__coverBtn).click()
                self.driver.find_element(*self.__mood_video).click()
                self.driver.find_element(*self.__nextBtn).click()
            else:
                logging.info('选择描述')
                self.driver.find_element(*self.__describeBtn).click()
                self.driver.find_element(*self.__ediTextBtn).click()
                self.driver.find_element(*self.__ediTextBtn).clear()
                text_path = self.get_path('data', 'video_number.csv')
                text_file = self.get_csv_data(text_path, line_number)[0]
                self.driver.find_element(*self.__ediTextBtn).send_keys(text_file)
                self.driver.find_element(*self.__nextBtn).click()

                logging.info('选择封面')
                self.driver.find_element(*self.__coverBtn).click()
                random_file = random.choice(range(9))
                self.driver.find_elements(*self.__thumbnailBtn)[random_file].click()

                text_random = random.choice(range(6))
                self.driver.find_elements(*self.__text_style)[text_random].click()

                self.driver.find_element(*self.__add_text).click()
                self.driver.find_element(*self.__add_text).clear()
                self.driver.find_element(*self.__add_text).send_keys(text_file)

                self.get_swipe(0.5, 0.5, 0.2, 0.2, 100)
                self.driver.find_element(*self.__useIMG).click()

        logging.info('点击发布')
        self.driver.find_element(*self.__publishBtn).click()

if __name__ == '__main__':
    obj = VideoView(appium_desired())
    obj.video_picture(2, 0, 10)


Import("env")
import os
import requests
import zipfile
import tempfile
import shutil

url = "https://github.com/makerbase-mks/Mks-Robin-Nano-Marlin2.0-Firmware/archive/master.zip"
zip_path = os.path.join(env.Dictionary("PROJECT_LIBDEPS_DIR"), "mks-assets.zip")
assets_path = os.path.join(env.Dictionary("PROJECT_BUILD_DIR"), env.Dictionary("PIOENV"), "assets")

def download_mks_assets():
	print("Downloading MKS Assets")
	r = requests.get(url, stream=True)
	# the user may have a very clean workspace,
	# so create the PROJECT_LIBDEPS_DIR directory if not exits
	if os.path.exists(env.Dictionary("PROJECT_LIBDEPS_DIR")) == False:
		os.mkdir(env.Dictionary("PROJECT_LIBDEPS_DIR"))
	with open(zip_path, 'wb') as fd:
		for chunk in r.iter_content(chunk_size=128):
			fd.write(chunk)

def copy_mks_assets():
	print("Copying MKS Assets")
	output_path = tempfile.mkdtemp()
	zip_obj = zipfile.ZipFile(zip_path, 'r')
	zip_obj.extractall(output_path)
	zip_obj.close()
	if os.path.exists(assets_path) == True and os.path.isdir(assets_path) == False:
		os.unlink(assets_path)
	if os.path.exists(assets_path) == False:
		os.mkdir(assets_path)
	base_path = ''
	for filename in os.listdir(output_path):
		base_path = filename
	for filename in os.listdir(os.path.join(output_path, base_path, 'Firmware', 'mks_font')):
		shutil.copy(os.path.join(output_path, base_path, 'Firmware', 'mks_font', filename), assets_path)
	for filename in os.listdir(os.path.join(output_path, base_path, 'Firmware', 'mks_pic')):
		shutil.copy(os.path.join(output_path, base_path, 'Firmware', 'mks_pic', filename), assets_path)
	shutil.rmtree(output_path, ignore_errors=True)

if os.path.exists(zip_path) == False:
	download_mks_assets()

if os.path.exists(assets_path) == False:
	copy_mks_assets()


# -*- coding: utf-8 -*-
import pygame
from pygame.locals import *
from sys import exit
from Roslina import *
import random
class Guarana(Roslina):
	def __init__(self, x, y, swiat):
		self.foto = pygame.image.load('guarana.jpg')
		self.X = x
		self.Y = y
		self.sw = swiat
		self.sila = 0
		self.nazwa = 'guarana'
		self.znak = 'G'
		self.usuniety = 0

	def ruch(self):
		self.akcja()

	def kolizja(self, o):
		pass

	def akcja(self):
		random.seed()
		szansa = random.randint(0, 4)
		tmpX = random.randint(-1,1) + self.X
		tmpY = random.randint(-1,1) + self.Y
		if self.sw.organizmy[tmpX][tmpY] == None and tmpX < 21 and tmpX > 0 and tmpY < 21 and tmpY > 0 and szansa == 0:
			guarana = Guarana(tmpX, tmpY, self.sw)
			self.sw.organizmy[guarana.X][guarana.Y] = guarana
			self.sw.nowy[self.sw.zliczNowy()] = guarana


"""sina.com bounces"""

import re

from email.iterators import body_line_iterator
from flufl.bounce.interfaces import (
    IBounceDetector, NoFailures, NoTemporaryFailures)
from public import public
from zope.interface import implementer

acre = re.compile(r'<(?P<addr>[^>]*)>')

@public
@implementer(IBounceDetector)
class Sina:
    """sina.com bounces"""

    def process(self, msg):
        """See `IBounceDetector`."""
        if msg.get('from', '').lower() != 'mailer-daemon@sina.com':
            return NoFailures
        if not msg.is_multipart():
            return NoFailures
        # The interesting bits are in the first text/plain multipart.
        part = None
        try:
            part = msg.get_payload(0)
        except IndexError:
            pass
        if not part:
            return NoFailures
        addresses = set()
        for line in body_line_iterator(part):
            mo = acre.match(line)
            if mo:
                addresses.add(mo.group('addr').encode('us-ascii'))
        return NoTemporaryFailures, addresses


import numpy as np
import os

import dataprovider3.emio as emio

# Basil dataset
data_dir = 'basil/ground_truth'
basil_dir = 'mip1/padded_x512_y512_z32'
basil_keys = [f"basil{i+1:03d}" for i in range(11)]
basil_info = {
    'img': 'img.h5',
    'seg': 'seg.h5',
    'msk': 'msk.h5',
    'mye': 'mye.h5',
    'blv': 'blv.h5',
    'loc': True,
}

def load_data(base_dir, data_ids=None, **kwargs):
    if data_ids is None:
        return {}

    base_dir = os.path.expanduser(base_dir)
    base_dir = os.path.join(base_dir, data_dir)

    data = {}
    for data_id in data_ids:
        if data_id == 'basil_superset':
            # Superset
            superset = {}
            for dkey in basil_keys:
                dpath = os.path.join(base_dir, basil_dir, dkey)
                if os.path.exists(dpath):
                    superset[dkey] = load_dataset(dpath, tag=dkey, **kwargs)
            data['basil_superset'] = superset
        else:
            # Individual dataset
            if data_id in basil_keys:
                dpath = os.path.join(base_dir, basil_dir, data_id)
                assert os.path.exists(dpath)
                data[data_id] = load_dataset(dpath, tag=data_id, **kwargs)
    return data

def load_dataset(dpath, tag, class_keys=[], **kwargs):
    assert len(class_keys) > 0
    dset = {}

    # Image
    fpath = os.path.join(dpath, basil_info['img'])
    print(fpath)
    dset['img'] = emio.imread(fpath).astype(np.float32)
    dset['img'] /= 255.0

    # Mask
    if tag in ['basil001','basil002']:
        fpath = os.path.join(dpath, 'msk.d128.h5')
    else:
        fpath = os.path.join(dpath, basil_info['msk'])
    print(fpath)
    dset['msk'] = emio.imread(fpath).astype(np.uint8)

    # Segmentation
    if 'aff' in class_keys or 'long' in class_keys:
        fpath = os.path.join(dpath, basil_info['seg'])
        print(fpath)
        dset['seg'] = emio.imread(fpath).astype(np.uint32)

    # Myelin (optional)
    if 'mye' in class_keys:
        fpath = os.path.join(dpath, basil_info['mye'])
        if os.path.exists(fpath):
            print(fpath)
            dset['mye'] = emio.imread(fpath).astype(np.uint8)
        else:
            assert 'msk' in dset
            dset['mye'] = np.zeros_like(dset['msk'])

    # Blood vessel (optional)
    if 'blv' in class_keys:
        fpath = os.path.join(dpath, basil_info['blv'])
        if os.path.exists(fpath):
            print(fpath)
            dset['blv'] = emio.imread(fpath).astype(np.uint8)
        else:
            assert 'msk' in dset
            dset['blv'] = np.zeros_like(dset['msk'])

    # Additoinal info
    dset['loc'] = basil_info['loc']

    return dset


from keras.callbacks import TensorBoard, CSVLogger, ModelCheckpoint
from keras.layers import Dense, Embedding, CuDNNLSTM, Bidirectional
from keras.models import Sequential
from sklearn.model_selection import StratifiedKFold
from pandas import get_dummies

from Embedding_Utilities import load_data

util = load_data('TL_BI_cuDNNLSTM_L2_N196_GloVe_5f_final')

lstm_out = 196

model = Sequential()
model.add(Embedding(util.NB_WORDS, util.EMBEDDING_DIM,input_length = util.TWEET_LENGTH,
                    dropout=0.2,weights=[util.embedding_matrix], trainable=False))
model.add(Bidirectional(CuDNNLSTM(lstm_out, return_sequences=True)))
model.add(Bidirectional(CuDNNLSTM(lstm_out, go_backwards=True)))
model.add(Dense(util.NUM_CLASSES,activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='nadam',metrics = ['accuracy'])
print(model.summary())
kfold = StratifiedKFold(n_splits=5,shuffle=True,random_state=util.RANDOM_SEED)
cvscores = []
X = util.X
Y = util.Y
Data_X = X
Data_Y = Y
batch_size = 256
i=0
for train,test in kfold.split(X,Y):
    fold = str(i+1)
    csv_logger = CSVLogger(util.LOG_DIR, append=True)
    foldY_train = get_dummies(Y[train]).values
    foldY_test = get_dummies(Y[test]).values
    checkpoint_name = util.MODEL_DIR + '/' + fold + '.{epoch:02d}-{loss:.2f}-{val_loss:.2f}.hdf5'
    checkpoint = ModelCheckpoint(checkpoint_name, monitor='val_loss',
                                 verbose=0, save_best_only=False,
                                 save_weights_only=False, mode='auto', period=1)
    tb = TensorBoard(log_dir=util.SUMMARY_DIR+fold, histogram_freq=1, batch_size=batch_size, write_graph=True,
                     write_grads=False,write_images=False, embeddings_freq=0, embeddings_layer_names=None, embeddings_metadata=None)
    hist = model.fit(X[train],foldY_train,batch_size=batch_size,
                     epochs=2,verbose=1,callbacks=[csv_logger,tb,checkpoint],validation_data=(X[test],foldY_test))
    i += 1
Data_Y = get_dummies(Data_Y).values
score,acc = model.evaluate(Data_X, Data_Y, verbose = 1, batch_size = batch_size)
print("score: %.2f" % (score))
print("acc: %.2f" % (acc))

Sentiment Analysis POC/BI-cuDnnLSTM 5 Fold.py


from unittest.mock import Mock, patch

from django.conf import settings
from django.test import TestCase
from rest_framework import status

from Chat.utils.error_messages import CHAT_ACCESS_MESSAGE
from Chat.utils.helpers import preprocess_count, return_error, check_access_to_chat

class HelpersTestCase(TestCase):

    def test_preprocess_count_none(self):
        output_count = preprocess_count(None)
        self.assertEqual(
            output_count,
            int(settings.CHAT_CONFIGURATION['max_messages_count']))

    def test_preprocess_count_positive_int(self):
        output_count = preprocess_count('10')
        self.assertEqual(output_count, 10)

    def test_return_error(self):
        expected_message = '{"error": {"status": 200, "message": "My message"}}'
        output_message = return_error('My message', 200).content.decode("utf-8")
        self.assertEqual(output_message, expected_message)

    @patch('django.db.models.query.QuerySet.exists')
    def test_check_access_to_chat_accessible(self, mock_exists):
        user_id = 3
        chat_uuid = 'd65d0970-1933-11eb-adc1-0242ac120002'
        mock_func = Mock()
        mock_request = Mock()
        mock_request.user.id = user_id
        mock_exists.return_value = True
        check_access_to_chat(mock_func)(mock_request, chat_uuid)
        mock_func.assert_called_once_with(mock_request, chat_uuid)

    @patch('Chat.utils.helpers.return_error')
    def test_check_access_to_chat_inaccessible(self, mock_return_error):
        user_id = 1
        chat_uuid = 'd65d0970-1933-11eb-adc1-0242ac120002'
        mock_func = Mock()
        mock_request = Mock()
        mock_request.user.id = user_id
        check_access_to_chat(mock_func)(mock_request, chat_uuid)
        mock_return_error.assert_called_once_with(
            CHAT_ACCESS_MESSAGE, status.HTTP_403_FORBIDDEN)


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

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html

import pymongo
import os

from scrapy import Item

from airticket import constant
from airticket import control

class AirticketMongoPipeline(object):
    """
    存储在mongo
    """

    def process_item(self, item, spider):
        """
        每个item pipeline组件都需要调用该方法
        这个方法必须返回一个Item对象，或是抛出DropItem异常
        :param item: 被爬取的item
        :param spider: 爬取该item的spider
        :return:
        """
        self.insert_db(item)
        return item

    def open_spider(self, spider):
        """
        在spider开启的时候自动被调用，在此可做一些初始化的操作
        :return:
        """
        # 数据库配置
        my_db = control.MyMongo()
        self.db_client = my_db.db_client
        self.db = my_db.db
        # db_uri = spider.settings.get('MONGODB_URI', 'mongodb://localhost:27017')
        # db_name = spider.settings.get('MONGODB_DB_NAME', 'airticketdb')

        # self.db_client = pymongo.MongoClient(db_uri)
        # self.db = self.db_client[db_name]

    def close_spider(self, spider):
        """
        当spider被关闭时，这个方法被调用
        :return:
        """
        self.db_client.close()

    def insert_db(self, item):
        """
        插入数据
        :param item:
        :return:
        """
        if isinstance(item, Item):
            item = dict(item)
            item['search_time'] = constant.NOW_STR_TIME_SS
        self.db.ticket.insert(item)


import pygame
import random
import time
import pickle

pygame.init()

sound = pygame.mixer.Sound('eaten.mp3')

width = 800
height = 600
size = width, height

screen = pygame.display.set_mode(size)
pygame.display.set_caption("Змейка")
clock = pygame.time.Clock()

snake_head = (0, 255, 0)
snake_tail = (0, 153, 0)
fruit = (255, 0, 0)

clock = pygame.time.Clock()

snake_speed = 10
snake_size = 10

def snake(snake_size, snake_lst):
    for i in snake_lst:
        pygame.draw.rect(screen, snake_tail, [i[0], i[1], snake_size, snake_size])

def score(score):
    font = pygame.font.Font(None, 50)
    text = font.render('Счёт:' + str(score), True, (0, 153, 0))
    screen.blit(text, [0, 0])

def loss(message):
    font = pygame.font.Font(None, 50)
    text = font.render(message, True, (0, 100, 100))
    text_x = width // 2 - text.get_width() // 2
    text_y = height // 2 - text.get_height() // 2
    text_w = text.get_width()
    text_h = text.get_height()
    screen.blit(text, (text_x, text_y))
    pygame.draw.rect(screen, (0, 255, 0), (text_x - 10, text_y - 10,
                                           text_w + 20, text_h + 20), 1)

def main():
    game_over = False
    game_close = False

    x = width / 2
    y = height / 2
    x_shift = 0
    y_shift = 0

    snake_lst = []
    snake_length = 1

    food_x = round(random.randrange(0, width - snake_size) / 10.0) * 10
    food_y = round(random.randrange(0, width - snake_size) / 10.0) * 10

    while not game_over:
        while game_close == True:
            screen.fill((0, 0, 0))
            loss("Вы проиграли <3")
            score(snake_length - 1)
            pygame.display.update()

            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        game_over = True
                        game_close = False
                    if event.key == pygame.K_e:
                        main()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_over = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT and x_shift == 0:
                    x_shift = -snake_size
                    y_shift = 0
                elif event.key == pygame.K_RIGHT and x_shift == 0:
                    x_shift = snake_size
                    y_shift = 0
                elif event.key == pygame.K_UP and y_shift == 0:
                    y_shift = -snake_size
                    x_shift = 0
                elif event.key == pygame.K_DOWN and y_shift == 0:
                    y_shift = snake_size
                    x_shift = 0

        if x >= width or y >= height or x < 0 or y < 0:
            game_close = True

        x += x_shift
        y += y_shift
        screen.fill((0, 0, 0))
        pygame.draw.rect(screen, snake_head, [x, y, snake_size, snake_size])
        pygame.draw.rect(screen, fruit, [food_x, food_y, snake_size, snake_size])
        pygame.display.update()
        snake_head1 = []
        snake_head1.append(x)
        snake_head1.append(y)
        snake_lst.append(snake_head1)
        if len(snake_lst) > snake_length:
            del snake_lst[0]

        for i in snake_lst[:-1]:
            if i == snake_head1:
                game_close = True

        snake(snake_size, snake_lst)
        score(snake_length - 1)
        pygame.display.update()

        if x == food_x and y == food_y:
            food_x = round(random.randrange(1, width - snake_size) / 10.0) * 10
            food_y = round(random.randrange(1, height - snake_size) / 10.0) * 10
            snake_length += 1
            sound.play()
            print('<3')
        clock.tick(30)

    pygame.quit()
    quit()

if __name__ == '__main__':
    main()


import scrapy
from pixelimg.items import PixelimgItem

class pixelimgSpider(scrapy.Spider):
    name = "pixelimg"
    start_urls = [
        "http://pixeljoint.com/pixels/new_icons.asp?ob=rating",
    ]
    web_url = 'http://pixeljoint.com'
    oldpages = start_urls
    star = 0
    def parse(self, response):
        url = response.xpath('//*[@class="tooltip"]/strong/a/@href').extract()
        for x in url:
            yield scrapy.Request(self.web_url+x, callback=self.parse_content)

        next_pages = response.xpath('//*[@id="leftblockspan"]/div[1]/div/div[50]/a[3]/@href').extract()

        # if next_pages[0] != self.oldpages[self.star]:
        #     self.oldpages[self.star] = next_pages[0]
        # #     ## 将 「下一页」的链接传递给自身，并重新分析
        #     yield scrapy.Request(self.web_url + self.oldpages[self.star], callback=self.parse)

    def parse_content(self, response):
        item = PixelimgItem()
        # //*[@id="leftblockspan"]/div[1]/div/div[50]/a[3]
        item['Title'] = response.xpath('//*[@id="leftblockspan"]/div[1]/div/table/tr[1]/td/table/tr[1]/td[2]/text()').extract()[0]
        item['Artist'] = response.xpath('//*[@id="leftblockspan"]/div[1]/div/table/tr[1]/td/table/tr[2]/td[2]/a/text()').extract()[0]
        item['Posted'] = response.xpath('//*[@id="leftblockspan"]/div[1]/div/table/tr[1]/td/table/tr[3]/td[2]/text()').extract()[0]
        item['Artist_url'] = self.web_url+response.xpath('//*[@id="leftblockspan"]/div[1]/div/table/tr[1]/td/table/tr[2]/td[2]/a/@href').extract()[0]
        item['Pic_url'] = response.xpath('//*[@id="mainimg"]/@src').extract()[0]
        # i = 0
        # for x in lists:
        #     lists[i] = self.web_url + x
        #     i +=1
        # item['image_urls'] = lists

        yield item


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

"""
@License: Copyright(C) 2019-2020, South China Normal University.
@File   : MySymbolTable.py
@Version: 1.0
@Author : 罗佳海
@Date   : 2020/4/7 12:05
@Desc   : 符号表的实现（最近嵌套作用域）
"""
from collections import OrderedDict

scope_map = {}  # 作用域集合，便于快速获取作用域对象

class Symbol(object):
    """符号类

    主要用于创建符号对象

    Attributes:
        name: 变量名（符号名）字符串
        lines: 保存列号的列表
        mem_loc: 内存位置整型数
        id_kind: NodeKind类的枚举类型（func\var）
        basic_type: BasicType类的枚举类型（arr指针，其引用的memloc与原指针memloc相同）
        size: 数组大小/函数参数个数
        included_scope: 函数声明下的作用域引用
    """
    name = None
    lines = None
    mem_loc = None
    id_kind = None
    basic_type = None
    size = None
    included_scope = None

    def __init__(self, symbol_name, mem_loc, id_kind, basic_type, size, lineno):
        self.name = symbol_name
        self.mem_loc = mem_loc
        self.id_kind = id_kind
        self.basic_type = basic_type
        self.size = size
        self.lines = []
        self.lines.append(lineno)

class SymbolTable(object):
    """符号表类

    主要用于管理符号对象

    Attributes:
        symbols: 符号字典
    """
    symbols = None

    def __init__(self):
        self.symbols = OrderedDict()  # 顺序字典帮助定位函数声明中的参数

    def insert_symbol(self, symbol):
        """向符号表插入符号

        :param symbol: 符号对象引用
        :return:
        """
        st_symbol = self.symbols.get(symbol.name)
        if st_symbol is None:
            self.symbols[symbol.name] = symbol
        else:
            st_symbol.lines.extend(symbol.lines)
            self.symbols[st_symbol.name] = st_symbol

    def lookup_symbol(self, symbol_name):
        """在符号表查找符号并返回其引用

        :param symbol_name: 符号名
        :return: 符号对象引用
        """
        return self.symbols.get(symbol_name)

    def lookup_symbol_by_index(self, index):
        """在符号表查找符号并返回其引用

        :param index: 索引
        :return: 符号对象引用
        """
        return list(self.symbols.values())[index]

class Scope(object):
    """作用域类

    主要用于管理符号表对象

    Attributes:
        id: 作用域id
        level: 作用域级别（最外层到最内层递增）
        symbol_table: 符号表对象的引用（每个作用域维护一个符号表）
        enclosing_scope: 包围当前作用域的外层作用域对象的引用（即最近嵌套）
    """
    id = None
    level = None
    symbol_table = None
    enclosing_scope = None

    def __init__(self, scope_id, scope_level, enclosing_scope=None):
        self.id = scope_id
        self.level = scope_level
        self.symbol_table = SymbolTable()
        self.enclosing_scope = enclosing_scope
        scope_map[self.id] = self  # 维护scope_map

    def insert_symbol(self, symbol_name, mem_loc, id_kind, basic_type, size, lineno):
        """向符号表插入符号"""
        symbol = Symbol(symbol_name, mem_loc, id_kind, basic_type, size, lineno)
        self.symbol_table.insert_symbol(symbol)
        return symbol

    def lookup_symbol(self, symbol_name):
        """在符号表查找符号并返回其引用"""
        return self.symbol_table.lookup_symbol(symbol_name)

    def lookup_symbol_by_index(self, index):
        """在符号表查找符号并返回其引用"""
        return self.symbol_table.lookup_symbol_by_index(index)

    def print_symbol_table(self):
        """打印作用域信息和符号表信息"""
        print("##################################################################")
        print("# Scope")
        print("# Scope Id  Scope Level  Enclosing Scope Id  Enclosing Scope Level")
        print("# --------  -----------  ------------------  ---------------------")
        print("# %8s" % self.id, end="")
        print("%13s" % self.level, end="")
        enclosing_scope_id = None if self.enclosing_scope is None else \
            str(self.enclosing_scope.id)
        enclosing_scope_level = None if self.enclosing_scope is None else \
            str(self.enclosing_scope.level)
        print("%20s" % enclosing_scope_id, end="")
        print("%23s" % enclosing_scope_level)
        print("# \n# Symbol Table")
        print("# Variable Name  Location  Id Kind  Basic Type  Size  Line Numbers")
        print("# -------------  --------  -------  ----------  ----  ------------")
        for symbol in self.symbol_table.symbols.values():
            print("# %13s" % symbol.name, end="")
            print("%10d" % symbol.mem_loc, end="")
            print("%9s" % symbol.id_kind.value, end="")
            print("%12s" % symbol.basic_type.value, end="")
            print("%6d  " % symbol.size, end="")
            for lineno in symbol.lines:
                print("%4d " % lineno, end="")
            print("")
        print("##################################################################\n")

def init_scope_map():
    """初始化作用域集合"""
    global scope_map
    scope_map = {}

def get_scope(scope_id):
    """获取作用域

    :param scope_id: 作用域id
    :return: 作用域对象的引用或None
    """
    return scope_map.get(scope_id)

def update_scope(scope_id, scope_level, enclosing_scope=None):
    """更新作用域

    当作用域在作用域集合里已创建时，仅更新相关属性并返回作用域的引用
    未创建时就创建新作用域对象，并添加到作用域集合中

    :param scope_id: 作用域id
    :param scope_level: 作用域级别
    :param enclosing_scope: 外层作用域对象的引用
    :return: 作用域对象的引用
    """
    if scope_map.__contains__(scope_id):  # not None
        scope_map[scope_id].level = scope_level
        if enclosing_scope is not None:  # 仅在非空时更新
            scope_map[scope_id].enclosing_scope = enclosing_scope
        return scope_map[scope_id]
    scope_map[scope_id] = Scope(scope_id, scope_level, enclosing_scope)  # 维护scope_map
    return scope_map[scope_id]

def st_insert(symbol_name, mem_loc, id_kind, basic_type, size, lineno, scope_id, scope_level):
    """向指定作用域的符号表插入符号

    :param symbol_name: 变量名
    :param mem_loc: 内存位置
    :param id_kind: NodeKind枚举类型
    :param basic_type: BasicType枚举类型
    :param size: 数组大小/函数参数个数
    :param lineno: 行号
    :param scope_id: 作用域id
    :param scope_level: 作用域级别
    :return: 由symbol对象引用和scope对象引用组成的元组
    """
    scope = update_scope(scope_id, scope_level)
    symbol = scope.insert_symbol(symbol_name, mem_loc, id_kind, basic_type, size, lineno)
    return symbol, scope

def st_lookup(symbol_name, scope_id):
    """查找符号

    根据scope_name和scope_level确定scope对象，在scope对象中的符号表进行搜索，找不到再向外层搜索

    :param symbol_name:
    :param scope_id:
    :return: 由symbol对象引用和scope对象引用组成的元组
    """
    scope = scope_map.get(scope_id)
    symbol = None
    while scope is not None:
        symbol = scope.lookup_symbol(symbol_name)
        if symbol is not None:
            break
        scope = scope.enclosing_scope
    return symbol, scope

def print_scope():
    """打印作用域信息和符号表信息"""
    # 按作用域级别排序
    ordered_map = OrderedDict(sorted(scope_map.items(), key=lambda t: t[1].level))
    for scope in ordered_map.values():
        # if len(scope.symbol_table.symbols) > 0:
            scope.print_symbol_table()

# 测试
if __name__ == '__main__':
    from MyTreeNode import NodeKind, BasicType

    scope1 = update_scope(10000, 0)

    scope2 = update_scope(10001, 1)
    scope2.enclosing_scope = scope1

    scope3 = update_scope(10002, 0)

    # Variable Name  Location  Id Kind  Basic Type  Size  Line Numbers
    st_insert("input", 0, NodeKind.FUNC_K, BasicType.INT, 1, 3, 10000, 0)
    st_insert("x", 1, NodeKind.VAR_K, BasicType.INT, 1, 4, 10000, 1)

    st_insert("output", 2, NodeKind.FUNC_K, BasicType.VOID, 1, 6, 10001, 0)
    st_insert("y", 3, NodeKind.VAR_K, BasicType.INT, 1, 7, 10002, 1)

    # print(scope_map)
    print_scope()
    symbol, scope = st_lookup("x", 10000)
    print(scope.lookup_symbol_by_index(0))


"""
Author: Kaushik Bhimraj
Desc:   The program looks at the point dictionary and will change the suffix in the point database to reflect Desigo
        standards.
"""

import xlrd
import json

def spcheck():

    with open("C:/Users/Z003VVKY/Desktop/44OP-245233_Gainsville_Panel_Upgrade/PointName.json") as ptd:
        data = json.load(ptd)

    file = "C:/Users/Z003VVKY/Desktop/44OP-245233_Gainsville_Panel_Upgrade/PointsCompare1.xlsx"
    wb = xlrd.open_workbook(file)
    ss = wb.sheet_by_index(0)
    rw = ss.nrows

    for val in range(1, rw):
        x = ss.cell(val, 0).value
        bits = x.split('.')
        for n, bit in enumerate(bits):
            try:
                if type(data[bit]) is list:
                    bits[n] = data[bit][0]
                else:
                    bits[n] = data[bit]
                    print(bits)
            except KeyError:
                pass
        if 'BLDG' in bits:
            num1 = bits.index('BLDG')  # Checked whether 'BLDG' is present in spl
            bits.pop(num1)

        if '11' in bits:
            num1 = bits.index('11')  # Checked whether '11' is present in spl
            bits.pop(num1)

        if 'VA' in bits:
            num1 = bits.index('VA')  # Checked whether 'VA' is present in spl
            bits.pop(num1)

        point = "_".join(bits)
        x = point.replace('AC9', 'AC9_')
        x = x.replace('A01', 'A01_')
        x = x.replace('EF1', 'EF1_')
        x = x.replace('EF3', 'EF3_')
        x = x.replace('EF4', 'EF4_')
        x = x.replace('FFS', 'FFS_')
        x = x.replace('A03', 'A03_')
        x = x.replace('A04', 'A04_')
        x = x.replace('A06', 'A06_')
        x = x.replace('A07', 'A07_')
        x = x.replace('P09', 'P09_')
        x = x.replace('P10', 'P10_')
        x = x.replace('RF1', 'RF1_')
        x = x.replace('RF3', 'RF3_')
        x = x.replace('RF6', 'RF6_')
        x = x.replace('P12', 'P12_')
        x = x.replace('SF7', 'SF7_')
        x = x.replace('SF8', 'SF8_')
        x = x.replace('MBC', 'MBC_')
        x = x.replace(' ', '_')
        x = x.replace('/', '_')
        x = x.replace('__', '_')
        if bits[0] != 'GVL':
            print('GVL_' + x)
        else:
            print(x)

spcheck()


numeros = [54, 58+5, 45, 12, 57, 84, 64, 25]

i = 0
while i < len(numeros):
    print(numeros[i])
    i+=1

# print("\nimpares")
# i = 0
# while(i < len(numeros)):
#     if numeros[i] % 2 == 1:
#         print(numeros[i])
#     i += 1

# while i < len(numeros1):
#     if numeros1[i] < 60:
#         print (numeros1[i])
#     i += 1


import re
import turtle
import sys

class Token:
    def __init__(self, direction, length):
        self.direction = direction
        self.length = length

class Tokenizer:
    def __init__(self):
        self.syntax = {
            'direction': re.compile(r'^U|R|L|D'),
            'number': re.compile(r'\d+')
        }

        self.tokens = list()

    def tokenize_file(self, file):
        with open(file, "r") as f:
            lines = f.readlines()

            for line in lines:
                direction = self.syntax['direction'].search(line)
                number = self.syntax['number'].search(line)
                assert direction.group(0) is not None, "error line {}: missing directional statement".format(
                    lines.index(line) + 1)
                assert number.group(0) is not None, "error line {}: missing numerical value".format(
                    lines.index(line) + 1)
                self.tokens.append(Token(direction.group(0), int(number.group(0))))

class Compiler:
    def __init__(self):
        self.previousDirection = 'U'

    def compile_tokens(self, tokens=[], turtle=turtle.Turtle()):
        turtle.left(90)

        for token in tokens:
            print("move {} for a distance of {}".format(token.direction, token.length))

            # oh god kill me now

            if token.direction == 'U':
                turtle.setheading(90)
                turtle.forward(token.length)
            elif token.direction == 'L':
                turtle.setheading(180)
                turtle.forward(token.length)
            elif token.direction == 'R':
                turtle.setheading(0)
                turtle.forward(token.length)
            elif token.direction == 'D':
                turtle.setheading(270)
                turtle.forward(token.length)

def main(file):
    compiler = Compiler()
    tokenizer = Tokenizer()
    window = turtle.Screen()
    tokenizer.tokenize_file(file)
    compiler.compile_tokens(tokenizer.tokens)
    window.mainloop()

if __name__ == "__main__":
    main(sys.argv[1])
    sys.exit()


# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@

from datetime import date
from dateutil.relativedelta import relativedelta

import mc_unittest

from rogerthat.rpc import users
from rogerthat.models import UserProfile
from rogerthat.models.news import NewsItem
from rogerthat.utils import get_epoch_from_datetime, now

class TestNewsItem(mc_unittest.TestCase):

    def test_news_item_target_audience(self):
        today = date.today()
        date_old = today + relativedelta(years=-40)
        date_ancient = today + relativedelta(years=-500)
        date_young = today + relativedelta(years=-10)

        empty_profile = UserProfile(birthdate=None, gender=None)
        profile_old_male = UserProfile(birthdate=get_epoch_from_datetime(date_old),
                                       gender=UserProfile.GENDER_MALE)
        profile_old_female = UserProfile(birthdate=get_epoch_from_datetime(date_old),
                                         gender=UserProfile.GENDER_FEMALE)
        profile_ancient_female = UserProfile(birthdate=get_epoch_from_datetime(date_ancient),
                                             gender=UserProfile.GENDER_FEMALE)
        young_female = UserProfile(birthdate=get_epoch_from_datetime(date_young),
                                   gender=UserProfile.GENDER_FEMALE)

        news_item0 = NewsItem(sticky=False,
                              sender=users.User('hello@mail.com'),
                              app_ids=['rogerthat'],
                              timestamp=now(),
                              rogered=False,
                              target_audience_enabled=False)

        self.assertTrue(news_item0.match_target_audience(profile_old_male))
        self.assertTrue(news_item0.match_target_audience(young_female))
        self.assertTrue(news_item0.match_target_audience(empty_profile))

        news_item1 = NewsItem(sticky=False,
                              sender=users.User('hello@mail.com'),
                              app_ids=['rogerthat'],
                              timestamp=now(),
                              rogered=False,
                              target_audience_enabled=True,
                              target_audience_min_age=0,
                              target_audience_max_age=100,
                              target_audience_gender=UserProfile.GENDER_FEMALE)

        self.assertFalse(news_item1.match_target_audience(empty_profile))
        self.assertFalse(news_item1.match_target_audience(profile_old_male))
        self.assertTrue(news_item1.match_target_audience(profile_old_female))
        self.assertFalse(news_item1.match_target_audience(profile_ancient_female))
        self.assertTrue(news_item1.match_target_audience(young_female))

        news_item2 = NewsItem(sticky=False,
                              sender=users.User('hello@mail.com'),
                              app_ids=['rogerthat'],
                              timestamp=now(),
                              rogered=False,
                              target_audience_enabled=True,
                              target_audience_min_age=18,
                              target_audience_max_age=99,
                              target_audience_gender=UserProfile.GENDER_MALE_OR_FEMALE)

        self.assertFalse(news_item2.match_target_audience(empty_profile))
        self.assertTrue(news_item2.match_target_audience(profile_old_male))
        self.assertTrue(news_item2.match_target_audience(profile_old_female))
        self.assertFalse(news_item2.match_target_audience(profile_ancient_female))
        self.assertFalse(news_item2.match_target_audience(young_female))


#!/usr/bin/env python

from test_policy import run_policy
from safe_rl.utils.load_utils import load_policy
import xml.etree.ElementTree as ET
import joblib
import time

def shift_dynamics(dynamic, xml, new_val):
    '''
    Shifts some value in a specified mujoco xml file, and then it writes the
    new value to the xml fileself.

    Args:
        dynamic: A string representing a the certain field in the xml that
                 represents a dynamic that will be shifted
        xml: A string that is a file path to an XML that will be edited
        new_val: A float that will be the new value for that dynamic
    '''
    tree = ET.parse(xml)
    root = tree.getroot()
    if dynamic == 'motor':
        x = [i.attrib for i in root.iter('motor')]
        x[0]['forcerange'] = '-' + str(new_val) + ' ' + str(new_val)
        i = 0
        for motor in root.iter('motor'):
            motor.attrib = x[i]
            i += 1
        tree.write(xml)
    elif dynamic == 'joint':
        # TODO: implement joint
        raise NotImplementedError('Have not implemented switch for joint')
    elif dynamic == 'velocity':
        x = [i.attrib for i in root.iter('velocity')]
        x[0]['forcerange'] = '-' + str(new_val) + ' ' + str(new_val)
        i = 0
        for veloc in root.iter('velocity'):
            veloc.attrib = x[i]
            i += 1
        tree.write(xml)
        print("Updated dynamics for", dynamic)

def get_range_vals(dynamic):
    '''
    Returns the list of new values that will be written to an XML file

    Args:
        dynamics: A string representing the dynamic to shift

    Returns:
        The list of floats of the new values
    '''
    if dynamic == 'motor' or dynamic == 'velocity':
        return [0.0025, 0.002, 0.001, 0.0005, 0.0001, 0.005, 0.01, 0.02, 0.03,
                0.04, 0.05, 0.06, 0.07, 0.08, 0.09,
                0.1, 0.125, 0.15, 0.175, 0.2, 0.225, 0.25, 0.275, 0.3, 0.35,
                0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9,
                0.95, 1.0, 0.035, 0.0325, 0.0375, 0.041, 0.042, 0.043, 0.044,
                0.045, 0.046, 0.047, 0.048, 0.049, 0.051, 0.052, 0.053, 0.054,
                0.055, 0.056, 0.057, 0.058, 0.059, 0.055, 0.0575, 0.0625, 0.065,
                0.0675]
        # return [0.005]
    elif dynamic == 'joint':
        return [0.001]
    elif dynamic == 'size':
        return [0.001, 0.0005, 0.0001, 0.0025, 0.005, 0.0075, 0.01, 0.0125,
                0.015, 0.0175, 0.02, 0.021, 0.022, 0.0225, 0.023, 0.024,
                0.025, 0.026, 0.027, 0.028, 0.029, 0.03, 0.031, 0.033, 0.034,
                0.036, 0.037, 0.038, 0.039, 0.0325, 0.032, 0.035, 0.0375, 0.04,
                0.0425, 0.045, 0.0475, 0.041, 0.042, 0.043, 0.044, 0.046,
                0.047, 0.048, 0.049, 0.05, 0.0525, 0.055, 0.0575, 0.06,
                0.0625, 0.065, 0.0675, 0.07, 0.0725, 0.075, 0.0775, 0.08, 0.825,
                0.085, 0.0875, 0.09, 0.0925, 0.095, 0.0975, 1.0]

def test_dynamics(env, get_action, dynamic, xml_file, episodes=20):
    '''
    It shifts a certain dynamic value to a new one, and it then tests a policy
    against these new values for a specified number of episodes. It then
    collects the average episodic returns of each episode for each policy, and
    then dumps the collected data to a pickle file that can be used later for
    visualizations or other analysis.

    Args:
        env: The openAI gym environment
        get_action: An openAI policy function that consumes obseravtions and returns actions
        dynamic: A string representing the dynamic to shift
        xml_file: A string of a path to a XML file to edit
        episodes: The number of episodes to run a policy for

    Returns:
        Nothing, but dumps a pickle file with the collected data
    '''
    assert dynamic != "", "You did not specify a dynamic"
    points = {}
    forcerange_vals = get_range_vals(dynamic)
    for x_val in forcerange_vals:
        shift_dynamics(dynamic, xml_file, x_val)
        y_vals = run_policy(env, get_action, 0, episodes, False)
        points[x_val] = y_vals
    pkl_name = str("shift_data_" + str(dynamic) + '_point_' + str(time.strftime("%Y-%m-%d")) + ".pkl")
    joblib.dump(points, pkl_name)

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('fpath', type=str)
    parser.add_argument('--len', '-l', type=int, default=0)
    parser.add_argument('--episodes', '-n', type=int, default=20)
    parser.add_argument('--itr', '-i', type=int, default=-1)
    parser.add_argument('--deterministic', '-d', action='store_true')
    parser.add_argument('--dynamic', '-dn', type=str, default="")
    parser.add_argument('--xml_file', '-xf', type=str, default="")
    args = parser.parse_args()
    env, get_action, _ = load_policy(args.fpath,
                                     args.itr if args.itr >= 0 else 'last',
                                     args.deterministic)
    test_dynamics(env, get_action, args.dynamic, args.xml_file, args.episodes)


import dash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output
import altair as alt
import pandas as pd

# Read in global data
df = pd.read_csv("data/processed/clean_data.csv",  index_col=0)

# Setup app and layout/frontend
app = dash.Dash(
    __name__, external_stylesheets=["https://codepen.io/chriddyp/pen/bWLwgP.css"]
)
server = app.server
app.layout = html.Div(
    [
        html.Iframe(
            id="scatter",
            style={"border-width": "0", "width": "100%", "height": "400px"},
        ),

        html.Label([
            'Year range',
            dcc.RangeSlider(
                id="yrange",
                min=1975,
                max=2015,
                value=[1975, 2015],  # REQUIRED to show the plot on the first page load
                marks={1975: '1975', 2015: '2015'},
            ),
        ]),

        html.Label([
            'State',
            dcc.Dropdown(
                id="state",
                value="California",  # REQUIRED to show the plot on the first page load
                options=[{"label": st_name, "value": st_name} for st_name in df["state_name"].unique()],
            ),
            ]),

        html.Label([
            'City',
            dcc.Dropdown(
                id="city",
                value="Los Angeles",  # REQUIRED to show the plot on the first page load
                options=[{"label": col, "value": col} for col in df[df["state_name"] == "California"]["city_name"].unique()],
            ),
            ]),

        html.Label([
            'Year',
            dcc.Dropdown(
                id="year",
                value=2014,  # REQUIRED to show the plot on the first page load
                options=[{"label": col, "value": col} for col in df["year"].unique()],
            ),
            ])

    ]
)

@app.callback(
    Output("city", "options"),
    Input("state", "value"),
)
def city(state):
    opts=[{"label": col, "value": col} for col in df[df["state_name"] == state]["city_name"].unique()]
    return opts

# Set up callbacks/backend
@app.callback(Output("scatter", "srcDoc"),
              Input("state", "value"),
              Input("city", "value"),
              Input("year", "value"),
              Input("yrange","value"))
def plot_altair(state,city,year,yrange):

    df_select = df.loc[(df.city_name == city)
    & (df.state_name == state)
    & (df.year == year)]
    df_data_plot=df_select.loc[:, "homs_per_100k":"agg_ass_per_100k"]
    df_data_plot=df_data_plot.mean(axis=0).to_frame().reset_index()
    df_data_plot.columns=["type", "value"]
    df_data_plot['type']=df_data_plot['type'].replace(
        ['homs_per_100k', 'rape_per_100k', 'rob_per_100k', 'agg_ass_per_100k'],
        ['Homicide', 'Rape', 'Robbery', 'Aggravated Assault'])

    df_select_line = df.loc[(df.city_name == city)
                     & (df.state_name == state)
                     & (df.year >= yrange[0])
                     & (df.year <= yrange[1])]

    bar = alt.Chart(df_data_plot,title = "City violent crime in 4 categories at year of interest").mark_bar(
        ).encode(alt.X ( "type" , title = "Violent Crime"),
                alt.Y ( "value", title = "Crime per 100K"),
                alt.Color ("type", title = "Crime type")).properties(height = 250,width = 280)

    line = alt.Chart(df_select_line, title = "Total  violent crimes at city of interest V.S. Years").mark_line(
        interpolate='monotone').encode(
        alt.X('year:O', title="Year"),
        alt.Y('violent_per_100k', title="Violent crime per 100k")).properties(height = 250,width = 700)

    chart = line | bar

    return chart.to_html()

if __name__ == "__main__":
    app.run_server(debug=True)


from . import exceptions
from . import jose
from .jws import JWS
import uuid

__all__ = ['Token']

class Token(JWS):
    def __init__(self, payload=None, header=None, signature=None,
            generate_jti=False, **kwargs):
        header = self._validate_header(header)
        header = self._validate_and_set_typ(header)

        payload = self._validate_payload(payload)
        payload = self._validate_and_set_jti(payload, generate_jti)
        # expire time
        # cty - content type
        # ...

        super(Token, self).__init__(payload, header, signature, **kwargs)

    def get_claim_from_namespace(self, namespace, name, uuid_version=5):
        return self.get_claim(_create_uuid_name(namespace, name, uuid_version))

    def get_claim(self, name):
        return self.payload.get(name)

    def _validate_payload(self, payload):
        if isinstance(payload, jose.JOSEDictionary):
            return payload

        elif isinstance(payload, dict):
            return jose.JOSEDictionary(payload)

        else:
            raise TypeError('"payload" must be a dict or JOSEDictionary')

    def _validate_and_set_jti(self, payload, generate_jti):
        if generate_jti:
            if 'jti' in payload:
                raise exceptions.InvalidClaim(
                    'Cannot specify "generate_jti" with existing "jti" claim.')

            else:
                payload['jti'] = _generate_jti()

        return payload

    def _validate_and_set_typ(self, header):
        if 'typ' in header and header['typ'].upper() != 'JWT':
            raise exceptions.InvalidHeader('"typ" parameter must be "JWT"')

        header['typ'] = 'JWT'

        return header

def _generate_jti():
    return uuid.uuid4().hex

_UUID_VERSIONS = {
    3: uuid.uuid3,
    5: uuid.uuid5,
}
def _create_uuid_name(namespace, name, uuid_version):
    name_creator = _UUID_VERSIONS.get(uuid_version)
    if name_creator is None:
        raise exceptions.InvalidUUIDType(
                'Invalid uuid_version specified (%s).  Valid values: %s'
                % (uuid_version, _UUID_VERSIONS.keys()))
    return str(name_creator(namespace, name))


import heapq

class GridWithWeights_3D():
    def __init__(self, width, height, time_length, wall_wind):
        self.width = width
        self.height = height
        self.time_length = time_length
        self.wall_wind = wall_wind
        self.weights = []

    def in_bounds(self, id):
        (x, y, t) = id
        return 0 <= x < self.width and 0 <= y < self.height and 0 <= t < self.time_length

    def in_wind(self, id):
        (x, y, t) = id
        return self.weights[x, y, t] < self.wall_wind

    def neighbors(self, id):
        (x, y, t) = id
        # Voila, time only goes forward, but we can stay in the same position
        results = [(x + 1, y, t+1), (x, y - 1, t+1), (x - 1, y, t+1), (x, y + 1, t+1), (x, y, t+1)]
        #if (x + y) % 2 == 0 : results.reverse()  # aesthetics
        results = filter(self.in_bounds, results)
        # we also need within the wall wind limit
        # results = filter(self.in_wind, results)  # However, with this condition, we might never find a route
        return results

    def cost(self, to_node):
        return self.weights[to_node]

class PriorityQueue:
    def __init__(self):
        self.elements = []

    def empty(self):
        return len(self.elements) == 0

    def put(self, item, priority):
        heapq.heappush(self.elements, (priority, item))

    def get(self):
        return heapq.heappop(self.elements)[1]

def heuristic(a, b):
    """
    https://en.wikipedia.org/wiki/A*_search_algorithm
     For the algorithm to find the actual shortest path, the heuristic function must be admissible,
     meaning that it never overestimates the actual cost to get to the nearest goal node.
     That's easy!
    :param a:
    :param b:
    :return:
    """
    if len(a) == 3:
        (x1, y1, t1) = a
        (x2, y2, t2) = b
    elif len(a) == 2:
        (x1, y1) = a
        (x2, y2) = b
    return abs(x1 - x2) + abs(y1 - y2)

def a_star_search_3D(graph, start, goals):
    """
    :param graph:
    :param start: 3D, (x,y,0)
    :param goal: 2D, spam 3D space
    :return:
    """
    frontier = PriorityQueue()
    frontier.put(start, 0)
    came_from = {}
    cost_so_far = {}
    came_from[start] = None
    cost_so_far[start] = 0

    while not frontier.empty():
        current = frontier.get()

        # we change to in because the goals are in time span now
        if current in goals:
            break

        for next in graph.neighbors(current):
            #print(str(current) + '   ->   ' + str(next))
            new_cost = cost_so_far[current] + graph.cost(next)
            if next not in cost_so_far or new_cost < cost_so_far[next]:
                cost_so_far[next] = new_cost
                # we use the x,y for goals because if admissible criterion is met, we are A OK!
                priority = new_cost + heuristic(goals[0], next)
                frontier.put(next, priority)
                came_from[next] = current

    return came_from, cost_so_far


import time

class BaseMonitor:
	'''
	basic general-purpose monitor.

	executes `function`
	with `parameters`
	every `sleeptime`
	returning response via `signal`
	'''
	def __init__(self,**kwargs):
		self._func = kwargs.get('function')
		self._params = kwargs.get('parameters',{})
		self._st = kwargs.get('sleeptime',1)
		self._sig = kwargs.get('signal')
		self._pause_flag = kwargs.get('pause_flag',{'pause':False})

	def run(self):
		'''
		does _function
		returns via _output
		'''
		while True:
			if not self._pause_flag['pause']:
				response = self._function()
				self._output(response)
			time.sleep(self._st)

	def _function(self):
		if self._func:
			return self._func(*self._params.get('args',[]),**self._params.get('kwargs',{}))
		else:
			return None

	def _output(self, response):
		if self._sig:
			self._sig.emit(response)


import numpy as np
import random
import networkx as nx
from matplotlib import pyplot as plt
import pandas as pd
import copy
import os
import sys
import networkx as nx
from scipy.io import mmread

# 一つ上の階層のmoduleをインポートできるようにする
current_dir = os.path.dirname(os.path.abspath("__file__"))
sys.path.append( str(current_dir) + '/../' )

from setting_param import MakeSample_attribute_prediction_new_PROSER_InputDir as InputDir
from setting_param import MakeSample_attribute_prediction_new_PROSER_OutputDir as OutputDir
from setting_param import Evaluation_prediction_num_of_node_new_LSTM_InputDir as predicted_num_InputDir
from setting_param import L
from setting_param import attribute_prediction_new_PROSER_threshold as threshold
from sklearn.metrics.pairwise import cosine_similarity as cosine_similarity

os.mkdir(OutputDir)
os.mkdir(OutputDir + "/input/")
os.mkdir(OutputDir + "/label/")
os.mkdir(OutputDir + "/input_num/")

# READ EXIST_TABLE
EXIST_TABLE = np.load(InputDir + '/exist_table.npy')

n_node = EXIST_TABLE.shape[0]

def ExistNodeList(ts):
    assert ts >= 0, "ts < 0 [referrence error]"
    return np.where(EXIST_TABLE[:, ts]==1)[0]

def GetAppearedNodes(ts):
    return set(ExistNodeList(ts)) - set(ExistNodeList(ts-1))

def GetObservedNodes(ts, L):
    U = set()
    for i in range(L):
        U |= set(ExistNodeList(ts-i))
    return U

def GetNodes(ts, L, node_type):
    if node_type=='all':
        node_set = set(ExistNodeList(ts))
    elif node_type=='stay':
        node_set = set(ExistNodeList(ts-1)) & set(ExistNodeList(ts))
    elif node_type=='lost':
        node_set = set(ExistNodeList(ts-1)) - set(ExistNodeList(ts))
    elif node_type=='return':
        node_set = GetAppearedNodes(ts) - (GetAppearedNodes(ts) - GetObservedNodes(ts-1, L))
    elif node_type=='new':
        node_set = GetAppearedNodes(ts) - GetObservedNodes(ts-1, L)
        node_set |= GetNodes(ts, L, 'return')
    return node_set

def NodeAttribute(ts):
    return  np.load(InputDir + '/node_attribute' + str(ts) + '.npy')

def TsSplit(ts, L):
    ts_train = [(ts+l) for l in range(L)]
    ts_test = ts_train[-1]+1
    ts_all = ts_train.copy()
    ts_all.extend([ts_test])
    return ts_train, ts_test, ts_all

# predicted_new_node_numの最大値を取得
predicted_new_node_num_list = []
for ts in range(L, EXIST_TABLE.shape[1]-L):
    predicted_new_node_num = int(np.load(predicted_num_InputDir + '/output/pred' + str(ts) + '.npy')[0])
    predicted_new_node_num_list.append(predicted_new_node_num)
max_predicted_new_node_num = max(predicted_new_node_num_list)

# new_node_numの最大値を取得
new_node_num_list = []
for ts in range(L, EXIST_TABLE.shape[1]-L):
    ts_train, ts_test, ts_all = TsSplit(ts, L)
    new_node_num = len(GetNodes(ts_test, L, 'new'))
    new_node_num_list.append(new_node_num)
max_new_node_num = max(new_node_num_list)

for ts in range(L, EXIST_TABLE.shape[1] - L):
    ts_train, ts_test, ts_all = TsSplit(ts, L)

    # ラベルの作成
    node_attribute_new = NodeAttribute(ts_train[-1])[sorted(GetNodes(ts_train[-1], L, 'new'))]  # (921, 300)
    node_attribute_teacher = NodeAttribute(ts_test)[sorted(GetNodes(ts_test, L, 'new'))]  # (1023, 300)
    sim_matrix = cosine_similarity(node_attribute_new, node_attribute_teacher)  # (921, 1023)
    sim_matrix_min = sim_matrix.min(axis=1) > threshold
    sim_matrix_25 = np.percentile(sim_matrix, 25, axis=1) > threshold
    sim_matrix_50 = np.percentile(sim_matrix, 50, axis=1) > threshold
    sim_matrix_75 = np.percentile(sim_matrix, 75, axis=1) > threshold
    sim_matrix_max = sim_matrix.max(axis=1) > threshold
    sim_matrix_stats = np.array([sim_matrix_min, sim_matrix_25, sim_matrix_50, sim_matrix_75, sim_matrix_max]).transpose((1, 0))  # (921, 5)
    label_matrix = np.zeros((max_new_node_num, 5))
    label_matrix[:sim_matrix_stats.shape[0]] = sim_matrix_stats
    np.save(OutputDir + "/label/" + str(ts), label_matrix)

    # 入力の作成
    node_attribute_new_mean = node_attribute_new.mean(axis=0)
    node_attribute_new_mean = np.tile(node_attribute_new_mean, (node_attribute_new.shape[0], 1))
    node_attribute_new = np.append(node_attribute_new, node_attribute_new_mean, axis=1)  # (921, 600)
    input_matrix = np.zeros((max_new_node_num, node_attribute_new.shape[1]))
    input_matrix[:node_attribute_new.shape[0]] = node_attribute_new
    np.save(OutputDir + "/input/" + str(ts), input_matrix)

    # マスクの作成
    np.save(OutputDir + "/input_num/" + str(ts), node_attribute_new.shape[0])