# -*- coding: iso-8859-1 -*-

##############################################################################
#                                                                            #
#  Copyright (C) 2012 Proge Informática Ltda (<http://www.proge.com.br>).    #
#                                                                            #
#  Author Daniel Hartmann <daniel@proge.com.br>                              #
#                                                                            #
#  This program is free software: you can redistribute it and/or modify      #
#  it under the terms of the GNU Affero General Public License as            #
#  published by the Free Software Foundation, either version 3 of the        #
#  License, or (at your option) any later version.                           #
#                                                                            #
#  This program is distributed in the hope that it will be useful,           #
#  but WITHOUT ANY WARRANTY; without even the implied warranty of            #
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             #
#  GNU Affero General Public License for more details.                       #
#                                                                            #
#  You should have received a copy of the GNU Affero General Public License  #
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.     #
#                                                                            #
##############################################################################

from util import Ocorrencia
from Registro import Registro

class RegistroX990(Registro):
    '''
    Classe para Registros X990 do layout EFD-PIS/COFINS. Representa o
    encerramento do bloco X, sendo X igual a 0, A, C, D, F, M, P, 1 ou 9.
    '''

    def __init__(self):
        self.QTD_LIN = '0'
        self.nivel = 1
        self.ocorrencia = Ocorrencia.UM
        self.registros_filhos = []


from lesson_8.graph import Graph

"""
def solution(graph, city):
	first_stops = graph.get(city)
	second_stops = [graph.get(val) for val in first_stops]

	print(Graph(zip([city], [first_stops])))
	print(Graph(zip(first_stops, second_stops)))
"""

def print_solution(dist, n, src):
	for node in range(n):
		print('from', src, 'to', node, '-', dist[node])

def task_1():
	data = [
		'Львів', 'Київ', 'Мукачево', 'Ужгород', 'Івано-Франківськ', 'Тернопіль'
	]

	grouped = []
	for x in range(len(data)):
		grouped.append(
			(
				data[x],
				[data[(k + x + 3) % len(data)] for k in range(len(data)) if data[x] != data[(k + x + 3) % len(data)]]
			)
		)

if __name__ == '__main__':
	matrix = [
		[0, 2, 0, 0, 0, 0, 1],
		[0, 0, 10, 0, 0, 0, 3],
		[0, 0, 0, 6, 0, 0, 0],
		[0, 0, 0, 0, 1, 0, 0],
		[0, 0, 0, 0, 0, 0, 0],
		[4, 0, 0, 0, 5, 0, 0],
		[0, 0, 2, 4, 8, 2, 0]
	]

	src_vertex = 2

	g = Graph(matrix)

	solution = g.dijkstra(src_vertex)

	print_solution(solution, len(matrix), src_vertex)


import FWCore.ParameterSet.Config as cms

process = cms.Process("analyzeGenPtHat")

process.load('Configuration.StandardSequences.Services_cff')
process.load('SimGeneral.HepPDTESSource.pythiapdt_cfi')
process.load('FWCore.MessageService.MessageLogger_cfi')
process.load('Configuration.Geometry.GeometryExtended2026D49Reco_cff')
process.load('Configuration.StandardSequences.MagneticField_cff')
process.load('Configuration.StandardSequences.Reconstruction_cff')
process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff')

process.maxEvents = cms.untracked.PSet(
    input = cms.untracked.int32(-1)
)

process.source = cms.Source("PoolSource",
    fileNames = cms.untracked.vstring(
        'file:/home/veelken/Phase2HLT/CMSSW_11_1_0/src/HLTrigger/Phase2HLTPFTaus/test/step3_RAW2DIGI_RECO.root'
    ),
##    eventsToProcess = cms.untracked.VEventRange(
##        '1:262:90464'
##    )
)

inputFilePath = '/hdfs/cms/store/user/rdewanje/MinBias_TuneCP5_14TeV-pythia8/HLTConfig_MinBias_TuneCP5_14TeV-pythia8_wOfflineVtx_wDeepTau3/'
#inputFilePath = '/hdfs/cms/store/user/rdewanje/QCD_Pt_30to50_TuneCP5_14TeV_pythia8/HLTConfig_QCD_Pt_30to50_TuneCP5_14TeV_pythia8_wOfflineVtx_wDeepTau3/'
#inputFilePath = None
inputFileNames = []
sampleName = "minbias"
#sampleName = "qcd_pt30to50"
outputFileName = "analyzeGenPtHat_%s_DEBUG.root" % sampleName

##inputFilePath = None
##inputFileNames = $inputFileNames
##sampleName = "$sampleName"
##lumiScale = $lumiScale
##outputFileName = "$outputFileName"

#--------------------------------------------------------------------------------
# set input files
if inputFilePath:
    from HLTrigger.TallinnHLTPFTauAnalyzer.tools.jobTools import getInputFileNames
    print("Searching for input files in path = '%s'" % inputFilePath)
    inputFileNames = getInputFileNames(inputFilePath)
    print("Found %i input files." % len(inputFileNames))
    process.source.fileNames = cms.untracked.vstring(inputFileNames)
elif len(inputFileNames) > 0:
    print("Processing %i input files: %s" % (len(inputFileNames), inputFileNames))
    process.source.fileNames = cms.untracked.vstring(inputFileNames)
#--------------------------------------------------------------------------------

from Configuration.AlCa.GlobalTag import GlobalTag
process.GlobalTag = GlobalTag(process.GlobalTag, 'auto:phase2_realistic', '')

process.analysisSequence = cms.Sequence()

process.genPtHatAnalzer = cms.EDAnalyzer("GenPtHatAnalyzer",
   src_genEventInfo = cms.InputTag('generator'),
   src_genJets = cms.InputTag('ak4GenJetsNoNu'),
   src_pileupSummaryInfo = cms.InputTag('addPileupInfo'),
   lumiScale = cms.double(1.),
   dqmDirectory = cms.string("GenPtHatAnalyzer/%s" % sampleName)
)
process.analysisSequence += process.genPtHatAnalzer

process.dumpGenPtHat = cms.EDAnalyzer("DumpGenPtHat",
   src_genEventInfo = cms.InputTag('generator'),
   src_genJets = cms.InputTag('ak4GenJetsNoNu'),
   src_pileupSummaryInfo = cms.InputTag('addPileupInfo')
)
##process.analysisSequence += process.dumpGenPtHat

process.load("DQMServices.Core.DQMStore_cfi")

process.savePlots = cms.EDAnalyzer("DQMSimpleFileSaver",
    outputFileName = cms.string(outputFileName)
)

process.p = cms.Path(process.analysisSequence + process.savePlots)


# -*- coding: utf-8 -*-
"""DNACenterAPI Networks API fixtures and tests.

Copyright (c) 2019 Cisco and/or its affiliates.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

import click
import pytest
from json import loads
from tests.environment import DNA_CENTER_VERSION

pytestmark = pytest.mark.skipif(DNA_CENTER_VERSION != '1.3.0', reason='version does not match')

def is_valid_get_vlan_details(result):
    data = result.output.strip()
    return True if data else False

@pytest.mark.networks
def test_get_vlan_details(runner, cli, auth_options):
    result = runner.invoke(cli, ['-v', '1.3.0', *auth_options,
                                 'networks', 'get-vlan-details',
                                 """--"""])
    assert not result.exception
    assert is_valid_get_vlan_details(result)

def is_valid_get_site_topology(result):
    data = result.output.strip()
    return True if data else False

@pytest.mark.networks
def test_get_site_topology(runner, cli, auth_options):
    result = runner.invoke(cli, ['-v', '1.3.0', *auth_options,
                                 'networks', 'get-site-topology',
                                 """--"""])
    assert not result.exception
    assert is_valid_get_site_topology(result)

def is_valid_get_physical_topology(result):
    data = result.output.strip()
    return True if data else False

@pytest.mark.networks
def test_get_physical_topology(runner, cli, auth_options):
    result = runner.invoke(cli, ['-v', '1.3.0', *auth_options,
                                 'networks', 'get-physical-topology',
                                 """--node_type='string'"""])
    assert not result.exception
    assert is_valid_get_physical_topology(result)

def is_valid_get_topology_details(result):
    data = result.output.strip()
    return True if data else False

@pytest.mark.networks
def test_get_topology_details(runner, cli, auth_options):
    result = runner.invoke(cli, ['-v', '1.3.0', *auth_options,
                                 'networks', 'get-topology-details',
                                 """--vlan_id='string'"""])
    assert not result.exception
    assert is_valid_get_topology_details(result)

def is_valid_get_l3_topology_details(result):
    data = result.output.strip()
    return True if data else False

@pytest.mark.networks
def test_get_l3_topology_details(runner, cli, auth_options):
    result = runner.invoke(cli, ['-v', '1.3.0', *auth_options,
                                 'networks', 'get-l3-topology-details',
                                 """--topology_type='string'"""])
    assert not result.exception
    assert is_valid_get_l3_topology_details(result)

def is_valid_get_overall_network_health(result):
    data = result.output.strip()
    return True if data else False

@pytest.mark.networks
def test_get_overall_network_health(runner, cli, auth_options):
    result = runner.invoke(cli, ['-v', '1.3.0', *auth_options,
                                 'networks', 'get-overall-network-health',
                                 """--timestamp=0"""])
    assert not result.exception
    assert is_valid_get_overall_network_health(result)


#!/usr/bin/env python
import numpy as np
# scipy version stuff
try:
    from scipy.misc import imread
except:
    from scipy.ndimage import imread
import pandas as pd

def construct_training_data(data_directory, number_data_train=-1, number_data_test=-1, binary_classification=False):
    """Returns training labels and array of images

    Params
    ------
    catalog_path : string path to csv file of catalog
    image_directory : string path to directory containing images
    number_data_train, _test : number of images we want to load. Default to all

    Returns
    -------
    train_images : (Ntrain,color,y,x) array of floats
    train_labels : (Ntrain,) array of ints
        0: dud, 1: sim lens galaxy, 2: sim lens quasar, 3: sim lens cluster

    And test

    Notes
    -----
    Training objects are objects in catalog with split_test_train == 0.
    split_test_train == 1 are the test objects
    split_test_train == -1 are the unknown objects where we want to find lenses

    """
    catalog_path = data_directory + '/sw_data/cutout_catalog/catalog.csv'
    image_directory = data_directory + '/sw_data/cutout_catalog/cutouts'

    catalog = pd.read_csv(catalog_path, index_col=0)

    if 'split_test_train' not in catalog:
        # assign split_test_train
        training_labels = ['dud', 'simulated lensed galaxy', 'simulated lensed quasar', 'simulated lensing cluster', 'known lens']
        catalog['split_test_train'] = -1
        cat_traintest = catalog['object_flavor'].isin(training_labels)
        # TODO: set a seed to make this part reproducible?
        catalog['split_test_train'][cat_traintest] = np.random.randint(2, size=len(catalog[cat_traintest]))

    train_info = catalog[catalog['split_test_train'] == 0][
        ['object_name', 'object_flavor']].values

    if number_data_train > 0:
        choices = np.random.choice(len(train_info), number_data_train, replace=False)
        train_info = train_info[choices]

    train_images = np.zeros((len(train_info), 96, 96, 3))
    train_labels = np.zeros((len(train_info),))
    for ii, training_info in enumerate(train_info):
        image_file = image_directory + '/' + training_info[0]
        train_images[ii] = imread(image_file).astype(np.float32) / 255.0
        if binary_classification:
            if training_info[1] == 'dud':
                train_labels[ii] = 0
            else:
                train_labels[ii] = 1
        else:
            if training_info[1] == 'dud':
                train_labels[ii] = 0
            elif training_info[1] == 'simulated lensed galaxy':
                train_labels[ii] = 1
            elif training_info[1] == 'simulated lensed quasar':
                train_labels[ii] = 2
            elif training_info[1] == 'simulated lensing cluster':
                train_labels[ii] = 3
            elif training_info[1] == 'known lens':
                train_labels[ii] = 4
            else:
                print('training label ' + str(ii) + ' not determined')
                print(training_info[2])

    train_images = np.swapaxes(train_images, 1, 3).astype(np.float32)
    train_labels = train_labels.astype(np.float32)

    test_info = catalog[catalog['split_test_train'] == 1][
        ['object_name', 'object_flavor']].values

    if number_data_test > 0:
        choices = np.random.choice(len(test_info), number_data_test, replace=False)
        test_info = test_info[choices]

    test_images = np.zeros((len(test_info), 96, 96, 3))
    test_labels = np.zeros((len(test_info),))
    for ii, testing_info in enumerate(test_info):
        image_file = image_directory + '/' + testing_info[0]
        test_images[ii] = imread(image_file).astype(np.float32) / 255.0
        if binary_classification:
            if testing_info[1] == 'dud':
                test_labels[ii] = 0
            else:
                test_labels[ii] = 1
        else:
            if testing_info[1] == 'dud':
                test_labels[ii] = 0
            elif testing_info[1] == 'simulated lensed galaxy':
                test_labels[ii] = 1
            elif testing_info[1] == 'simulated lensed quasar':
                test_labels[ii] = 2
            elif testing_info[1] == 'simulated lensing cluster':
                test_labels[ii] = 3
            elif testing_info[1] == 'known lens':
                test_labels[ii] = 4
            else:
                print('testing label ' + str(ii) + ' not determined')
                print(testing_info[2])

    test_images = np.swapaxes(test_images, 1, 3).astype(np.float32)
    test_labels = test_labels.astype(np.float32)

    return train_images, train_labels, test_images, test_labels

if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser(description='run the jobs!')
    parser.add_argument('--catalog',
                        action='store',
                        dest='catalog',
                        default='/farmshare/user_data/ajmcleod/' +
                                'machine_learning/galzoo/strongcnn/catalog/' +
                                'catalog.csv',
                        help='location of catalog csv')
    parser.add_argument('--images',
                        action='store',
                        dest='images',
                        default='/farmshare/user_data/ajmcleod/' +
                                'machine_learning/galzoo/image_files',
                        help='location of directory containing images')
    args = parser.parse_args()

    train_images, train_labels, test_images, test_labels = \
        construct_training_data(args.catalog, args.images)


import dbcon
import mysql.connector

class getmusiclist:
    def __init__(self, tablename):
        self.con=dbcon.Connection()
        self.cnx = self.con.function()
        self.cursorcnx = self.cnx.cursor()
        try:
            self.Table_name = tablename
            self.query = "select * from " + self.Table_name
            print(self.Table_name)
            self.cursorcnx.execute(self.query)
            self.rows = self.cursorcnx.fetchall()
            self.musiclist = []

            for row in self.rows:
                self.musiclist.append(row)

        except mysql.connector.Error as err:
            print(err.msg)
    def getlist(self):
        return self.musiclist

if __name__=="__main__":
    obj=getmusiclist("sadtable")
    obj.getlist()


from tree import *
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.datasets import make_moons, make_circles, make_classification

x, y = make_circles(noise = 0.02, random_state=0)
fil = y == 0
y[fil] = -1
x = x.astype(np.float64)
y = y.astype(np.float64)

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.5, random_state=0)

tree = Tree()
tree.train(x_train,y_train)#make_circles用
tree.graph()

point = 0
for i in range(x_test.shape[0]):
    d = x_test[i]
    o = tree.inference(d)
    if y_test[i] == float(o):
        point += 1

point = (float(point)/float(x_test.shape[0])) * 100.0
print("成功率="+str(point)+"%")#成功率=82.0%


#Write a function that takes a list of strings an prints them, one per line, in a rectangular frame.
#For example the list ["Hello", "World", "in", "a", "frame"] gets printed as:
'''
*******
*Hello*
*world*
*in   *
*a    *
*frame*
*******
'''

sentence = input("\nEnter the list of strings : ")
sen_list = []
new_lis = []
y=0
x = sentence.split()
t = len(x)
for i in x:
    if len(i) > y:
        y=len(i)
#print(y)
#print("*" * (y+2))
new_lis.append("*" * (y+2))
for i in range(t):
    new_lis.append("*"+ x[i]+ (" " * ((y) - len(x[i]))) +"*")
new_lis.append("*" * (y+2))
#print(new_lis)
print("\n\n")
for i in range(len(new_lis)):
    print(new_lis[i])


from macros.libs import wap
from macros.settings import local_settings as app_settings
from xml.etree.ElementTree import parse, fromstring

class WolframProcessor():

    def __init__(self, wolfram_alpha_engine_name):
        self.wolfram_alpha_engine_name = wolfram_alpha_engine_name

    def parse_query(self, query_string, response_text=None):

        if response_text is not None:
            root = fromstring(response_text.encode("ascii", "ignore"))
            pods = response_text
        else:
            pods, is_error = self.query_api(query_string)
            root = fromstring(pods)
        macros = [["Calories", "total calories", "mean value"], \
                  ["Protein and amino acids", "protein", "mean value"], \
                  ["Carbohydrates", "total carbohydrates", "mean value"], \
                  ["Fats and fatty acids", "total fat", "mean value"] \
            ]
        data = {}
        for macro in macros:
            # Return a string from the XML
            plaintext = self.extract_plaintext_from_pods(root, macro[0])
            # Convert the string to an array
            matrix = self.plaintext_to_matrix(plaintext)
            # convert the array to a dictionary
            dictionary = self.matrix_to_dict(matrix)
            value = self.value_string_to_number(dictionary[macro[1]][macro[2]])
            data[macro[1]] = value
        return data, pods

    def query_api(self, queryString):
        """
        Query wolframalpha with a string
        Return the pods
        """

        server = app_settings.WOLFRAM_SERVER
        app_id = app_settings.WOLFRAM_APPID
        waeo = self.wolfram_alpha_engine_name(app_id, server)
        query = waeo.CreateQuery(queryString)
        query_result = waeo.PerformQuery(query)
        waeqr = wap.WolframAlphaQueryResult(query_result)
        is_error = waeqr.IsError()
        xml_result = waeqr.XmlResult
        pods = xml_result
        return pods, is_error

    def extract_plaintext_from_pods(self, root, pod_name):
        """
        Take pods and extract the plaintext strings for given pod names
        """
        try:
            found_element = root.findall("./pod[@title='%s']/subpod/plaintext" % pod_name)
            plaintext = found_element[0].text.replace("rangeprotein", r"range\nprotein")
            return plaintext
        except:
            raise Exception('Could not get data from Wolfram Alpha')

    def plaintext_to_matrix(self, plaintext):
        """
        Take the plaintext table and convert it to a dict
        """

        matrix = list()

        table_rows = plaintext.split("\n")

        for row in table_rows:
            matrix.append(row.split(" | "))

        return matrix

    def matrix_to_dict(self, matrix):

        result = dict()

        for x in range(1, len(matrix)):
            zipped = dict(zip(matrix[0], matrix[x]))
            result[zipped[""]] = zipped
            # Remove the empty cell in the upper-left corner of table
            del result[zipped[""]][""]

        return result

    def value_string_to_number(self, value_string):
        if value_string[-2:] == " g":
            return float(value_string[:-2])
        elif value_string[-2:] == 'mg':
            return 0
        elif value_string[-3:] == 'Cal':
            return float(value_string[:-3])
        else:
            return 0


# Window constants

SCREEN_HEIGHT = 500
SCREEN_WIDTH = 500
TITRE_WIN = "Mario"

# Path of Blocks image

blocks_path = "Images\Blocs_images"

# Path of Decors

decors_path = "Images\Decor_Images"

# Path of Level

levels_path = "Images\Level_Image"

# Path of Musics

musics_path = "Musics"

# Path of Sounds

sounds_path = "Sounds"

# Path of mario images

mario_path = "Images\Mario_Images"

# Ennemies path

ennemy_path = "Images\Ennemies_Images"

# Image of the player

img_mario_standingD = "Images\Mario_Images\MarioStandingD.gif"
img_mario_standingG = "Images\Mario_Images\MarioStandingG.gif"
img_mario_jumpingG = "Images\Mario_Images\MarioJumpingG.gif"
img_mario_jumpingD = "Images\Mario_Images\MarioJumpingD.gif"
img_mario_dead = "Images\Mario_Images\MarioDead.gif"

# Image of the enemie

goomba_img = ennemy_path + "\Goomba0.gif"
pyrhana_img = ennemy_path + "\Pyrhana0.gif"
koopaG_img = ennemy_path + "\koopaG0.gif"
koopa_redG = ennemy_path + "\koopa_redG0.gif"

# Images of blocks

block_img = blocks_path + "\Block.gif"
bricks_img = blocks_path + "\Bricks.gif"
bridge_img = blocks_path + "\Bridge.gif"
cloud_img = blocks_path + "\Coin Heaven Cloud.gif"
pipe_img = blocks_path + "\Pipe.gif"
ground_img = blocks_path + "\Ground.gif"
bridge_bottom = blocks_path + "\Bridge_bottom.gif"
mush_top = blocks_path + "\Giant Mushroom_top.gif"
move_pltf = blocks_path + "\Moving Platform3.gif"

# Images of decors

Bush_one_img = decors_path + "\Bush - Single.gif"
Bush_two_img = decors_path + "\Bush - Double.gif"
Bush_tree_img = decors_path + "\Bush - Triple.gif"
cloud_tow_img = decors_path + "\Cloud - Double.gif"
waves_img = decors_path + "\Waves.gif"
cloud_tree_img = decors_path + "\Cloud - Triple.gif"
bridge_top = decors_path + "\Bridge_top.gif"
mush_bottom = decors_path + "\Giant Mushroom_bottom.gif"
large_hill = decors_path + "\Hill - Large.gif"
small_hill = decors_path + "\Hill - Small.gif"
large_tree = decors_path + "\Tree - Large.gif"
small_tree = decors_path + "\Tree - Small.gif"

# Musics

overworld_music = musics_path + "\Overworld Theme - Super Mario World.mp3"
underground_music = musics_path + "Underground Theme - Super Mario World.mp3"

# Sounds

koopa_snd = sounds_path + "\smb_kick.wav"
coin_snd = sounds_path + "\smw_coin.wav"
course_clear_snd = sounds_path + "\smw_course_clear.wav"
jump_snd = sounds_path + "\smw_jump.wav"
lost_life_snd = sounds_path + "\smw_lost_a_life.wav"
goomba_snd = sounds_path + "\smw_yoshi_stomp.wav"
die_snd = sounds_path + "\smb_mariodie.wav"


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

import pytest

from vmaas.rest import schemas, tools

ERRATA = [
    'RHBA-2016:2858',
    'RHSA-2017:1931',
]

class TestErrataQuery(object):
    def test_post_multi(self, rest_api):
        """Tests multiple errata using POST."""
        request_body = tools.gen_errata_body(ERRATA)
        errata = rest_api.get_errata(body=request_body).response_check()
        schemas.errata_schema.validate(errata.raw.body)
        assert len(errata) == len(ERRATA)
        for erratum_name in ERRATA:
            assert erratum_name in errata

    @pytest.mark.parametrize('erratum_name', ERRATA)
    def test_post_single(self, rest_api, erratum_name):
        """Tests single erratum using POST."""
        request_body = tools.gen_errata_body([erratum_name])
        errata = rest_api.get_errata(body=request_body).response_check()
        schemas.errata_schema.validate(errata.raw.body)
        assert len(errata) == 1
        erratum, = errata
        assert erratum.name == erratum_name

    @pytest.mark.parametrize('erratum_name', ERRATA)
    def test_get(self, rest_api, erratum_name):
        """Tests single erratum using GET."""
        errata = rest_api.get_erratum(erratum_name).response_check()
        schemas.errata_schema.validate(errata.raw.body)
        assert len(errata) == 1
        erratum, = errata
        assert erratum.name == erratum_name


from cs50 import get_float

while True:
    #Get user input for change owed
    change = get_float("change owed: ")
    if change > 0:
        break

cents = round(change * 100)
coins = 0

#Iterates through the change owed, always looking for the largest coin that will fit
while cents > 0:
    if cents > 24:
        coins += cents // 25
        cents = cents % 25
    elif cents < 25 and cents > 9:
        coins += cents // 10
        cents = cents % 10
    elif cents < 10 and cents > 4:
        coins += cents // 5
        cents = cents % 5
    elif cents < 5 and cents > 0:
        coins += cents // 1
        cents = cents % 1

print(coins)

#Alternative implementation

#while cents > 0:
#    if cents >= 25:
#        cents -= 25
#        coins += 1
#    elif cents < 25 and cents >= 10:
#        cents -= 10
#        coins += 1
#    elif cents < 10 and cents >= 5:
#        cents -= 5
#        coins += 1
#    elif cents < 5 and cents > 0:
#        cents -= 1
#        coins += 1

#print(coins)


import numpy as np
import argparse
import socket
import time
import os
import scipy.misc
import sys
import glob
import matplotlib.pyplot as plt
from sklearn import datasets, decomposition, manifold, preprocessing

import os,sys,inspect
currentdir = "/usr/local/featureExtractionParty/external/pointnet_spine_ae"
sys.path.insert(0,currentdir)
import importlib

import pandas as pd
from sklearn.cluster import KMeans

import meshparty
import time
from meshparty import trimesh_io, trimesh_vtk, trimesh_repair
import trimesh
from trimesh.primitives import Sphere
import os
import h5py
from meshparty import skeleton, skeleton_io
import json
import math
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from scipy import sparse
from meshparty import mesh_filters
from meshparty import utils
import numpy as np
import pickle
import pandas
import cloudvolume
from meshparty import skeletonize
from trimesh.ray import ray_pyembree
from multiprocessing import Pool
from functools import partial
from scipy import sparse
from meshparty import skeleton_io
from annotationframeworkclient import infoservice
import trimesh
from meshparty import skeletonize
from meshparty import mesh_skel_utils
from scipy.sparse import csgraph
print("Finished imports")

# Import full classifications dataframe
classes_file = 'synapses_PSS.pkl'
classes_df = pd.read_pickle(classes_file)

# Import dually innervated spines list
spines_file = 'dually-innervated_reindexed.pkl'
spines_df = pd.read_pickle(spines_file)

# Choose which pair of meshes to work with (i corresponds to index in list of pairs)
i = 39344

# Load meshes and create mesh actors for each mesh
spine1_file = r'Meshes/' + str(spines_df['cell id'][i]) + '/' + str(i) + '/spine_' + str(spines_df['spine 1 index'][i]) + '.off'
spinemesh1 = trimesh.exchange.load.load_mesh(spine1_file)
spinemesh1_mp = meshparty.trimesh_io.Mesh(vertices=spinemesh1.vertices, faces=spinemesh1.faces)
spinemesh1_actor = trimesh_vtk.mesh_actor(spinemesh1, color=(0,0,1), opacity=0.2)
spine2_file = r'Meshes/' + str(spines_df['cell id'][i]) + '/' + str(i) + '/spine_' + str(spines_df['spine 2 index'][i]) + '.off'
spinemesh2 = trimesh.exchange.load.load_mesh(spine2_file)
spinemesh2_mp = meshparty.trimesh_io.Mesh(vertices=spinemesh2.vertices, faces=spinemesh2.faces)
spinemesh2_actor = trimesh_vtk.mesh_actor(spinemesh2, color=(1,0,0), opacity=0.2)

# Find synapse location and make a point cloud actor for the synapse of each mesh
synapse1_loc = [spines_df['spine 1 synapse'][i][0]*4,spines_df['spine 1 synapse'][i][1]*4,spines_df['spine 1 synapse'][i][2]*40]
synapse2_loc = [spines_df['spine 2 synapse'][i][0]*4,spines_df['spine 2 synapse'][i][1]*4,spines_df['spine 2 synapse'][i][2]*40]
synapse1_actor = trimesh_vtk.point_cloud_actor([synapse1_loc],size=100,color=(0,0,1),opacity=1)
synapse2_actor = trimesh_vtk.point_cloud_actor([synapse2_loc],size=100,color=(1,0,0),opacity=1)

# Skeletonize and create a skeleton actor for each mesh
skeleton1 = meshparty.skeletonize.skeletonize_mesh(spinemesh1_mp,compute_radius=False,cc_vertex_thresh=0)
skeleton1_actor = meshparty.trimesh_vtk.skeleton_actor(skeleton1,color=(0,0,1),opacity=1)
skeleton2 = meshparty.skeletonize.skeletonize_mesh(spinemesh2_mp,compute_radius=False,cc_vertex_thresh=0)
skeleton2_actor = meshparty.trimesh_vtk.skeleton_actor(skeleton2,color=(1,0,0),opacity=1)

# Find opening and point on skeleton closest to opening for each mesh
spine1broken = trimesh.repair.broken_faces(spinemesh1_mp)
spine1openings = spinemesh1_mp.submesh([spine1broken], append=True)
spine1openings = meshparty.trimesh_io.Mesh(vertices=spine1openings.vertices, faces=spine1openings.faces)
print(spine1openings)
if spine1openings.body_count == 1:
    path_opening1_a = meshparty.mesh_skel_utils.point_to_skel_meshpath(spinemesh1_mp,skeleton1,spine1openings.vertices[0])
    opening_ind1_a = np.where(skeleton1.vertices == spinemesh1.vertices[path_opening1_a[-1]])
    opening_ind1_a = opening_ind1_a[0][0]
    opening_ind1_b = -1
elif spine1openings.body_count == 2:
    mask1 = mesh_filters.filter_largest_component(spine1openings)
    spine1openings_a = spine1openings.apply_mask(mask1)
    spine1openings_b_vertices = []
    for i in spine1openings.vertices:
        if i not in spine1openings_a.vertices:
            spine1openings_b_vertices.append(i.tolist())
    path_opening1_a = meshparty.mesh_skel_utils.point_to_skel_meshpath(spinemesh1_mp,skeleton1,spine1openings.vertices[0])
    path_opening1_b = meshparty.mesh_skel_utils.point_to_skel_meshpath(spinemesh1_mp,skeleton1,spine1openings_b_vertices[0])
    opening_ind1_a = np.where(skeleton1.vertices == spinemesh1.vertices[path_opening1_a[-1]])
    opening_ind1_a = opening_ind1_a[0][0]
    opening_ind1_b = np.where(skeleton1.vertices == spinemesh1.vertices[path_opening1_b[-1]])
    opening_ind1_b = opening_ind1_b[0][0]
else:
    mask1 = mesh_filters.filter_largest_component(spine1openings)
    spine1openings = spine1openings.apply_mask(mask1)
    path_opening1_a = meshparty.mesh_skel_utils.point_to_skel_meshpath(spinemesh1_mp,skeleton1,spine1openings.vertices[0])
    opening_ind1_a = np.where(skeleton1.vertices == spinemesh1.vertices[path_opening1_a[-1]])
    opening_ind1_a = opening_ind1_a[0][0]
    opening_ind1_b = -1

spine2broken = trimesh.repair.broken_faces(spinemesh2_mp)
spine2openings = spinemesh2_mp.submesh([spine2broken], append=True)
spine2openings = meshparty.trimesh_io.Mesh(vertices=spine2openings.vertices, faces=spine2openings.faces)
print(spine2openings)
if spine2openings.body_count == 1:
    path_opening2_a = meshparty.mesh_skel_utils.point_to_skel_meshpath(spinemesh2_mp,skeleton2,spine2openings.vertices[0])
    opening_ind2_a = np.where(skeleton2.vertices == spinemesh2.vertices[path_opening2_a[-1]])
    opening_ind2_a = opening_ind2_a[0][0]
    opening_ind2_b = -1
elif spine2openings.body_count == 2:
    mask2 = mesh_filters.filter_largest_component(spine2openings)
    spine2openings_a = spine2openings.apply_mask(mask2)
    spine2openings_b_vertices = []
    for i in spine2openings.vertices:
        if i not in spine2openings_a.vertices:
            spine2openings_b_vertices.append(i.tolist())
    path_opening2_a = meshparty.mesh_skel_utils.point_to_skel_meshpath(spinemesh2_mp,skeleton2,spine2openings.vertices[0])
    path_opening2_b = meshparty.mesh_skel_utils.point_to_skel_meshpath(spinemesh2_mp,skeleton2,spine2openings_b_vertices[0])
    opening_ind2_a = np.where(skeleton2.vertices == spinemesh2.vertices[path_opening2_a[-1]])
    opening_ind2_a = opening_ind2_a[0][0]
    opening_ind2_b = np.where(skeleton2.vertices == spinemesh2.vertices[path_opening2_b[-1]])
    opening_ind2_b = opening_ind2_b[0][0]
else:
    mask2 = mesh_filters.filter_largest_component(spine2openings)
    spine2openings = spine2openings.apply_mask(mask2)
    path_opening2_a = meshparty.mesh_skel_utils.point_to_skel_meshpath(spinemesh2_mp,skeleton2,spine2openings.vertices[0])
    opening_ind2_a = np.where(skeleton2.vertices == spinemesh2.vertices[path_opening2_a[-1]])
    opening_ind2_a = opening_ind2_a[0][0]
    opening_ind2_b = -1

# Create a path from the synapse to the opening for each mesh/synapse
# The path consists of two parts: (1) a path from the synapse to the nearest point on the skeleton, and
#                                 (2) a path along the skeleton to the opening
path1_1 = meshparty.mesh_skel_utils.point_to_skel_meshpath(spinemesh1_mp,skeleton1,synapse1_loc)
meshverts1 = spinemesh1.vertices.tolist()
skelverts1 = skeleton1.vertices.tolist()
inds1_a = path1_1
inds1_b = path1_1[1:]
index = np.where(skeleton1.vertices == spinemesh1.vertices[path1_1[-1]])
index = index[0][0]
if opening_ind1_b == -1:
    opening_ind1 = opening_ind1_a
    skeleton1.reroot(opening_ind1_a)
    path1_2 = skeleton1.path_to_root(index)
    for i in path1_2[1:]:
        mesh_ind = np.where(spinemesh1.vertices == skeleton1.vertices[i])
        mesh_ind = mesh_ind[0][0]
        inds1_a.append(mesh_ind)
        inds1_b.append(mesh_ind)
    inds1_b = np.append(inds1_b,inds1_b[-1])
    line1 = meshparty.trimesh_vtk.linked_point_actor(np.array(meshverts1),np.array(meshverts1),inds_a=inds1_a,inds_b=inds1_b,opacity=1,line_width=5,color=(0,0,1))
else:
    skeleton1_a = skeleton1
    skeleton1_a.reroot(opening_ind1_a)
    path1_2a = skeleton1_a.path_to_root(index)
    skeleton1_b = skeleton1
    skeleton1_b.reroot(opening_ind1_b)
    path1_2b = skeleton1_b.path_to_root(index)
    if len(path1_2a) > len(path1_2b) and len(path1_2b) > 1:
        path1_2 = path1_2b
        opening_ind1 = opening_ind1_b
    else:
        path1_2 = path1_2a
        opening_ind1 = opening_ind1_a
    for i in path1_2[1:]:
        mesh_ind = np.where(spinemesh1.vertices == skeleton1.vertices[i])
        mesh_ind = mesh_ind[0][0]
        inds1_a.append(mesh_ind)
        inds1_b.append(mesh_ind)
    inds1_b = np.append(inds1_b,inds1_b[-1])
    line1 = meshparty.trimesh_vtk.linked_point_actor(np.array(meshverts1),np.array(meshverts1),inds_a=inds1_a,inds_b=inds1_b,opacity=1,line_width=5,color=(0,0,1))

path2_1 = meshparty.mesh_skel_utils.point_to_skel_meshpath(spinemesh2_mp,skeleton2,synapse2_loc)
meshverts2 = spinemesh2.vertices.tolist()
skelverts2 = skeleton2.vertices.tolist()
inds2_a = path2_1
inds2_b = path2_1[1:]
index = np.where(skeleton2.vertices == spinemesh2.vertices[path2_1[-1]])
index = index[0][0]
if opening_ind2_b == -1:
    opening_ind2 = opening_ind2_a
    skeleton2.reroot(opening_ind2_a)
    path2_2 = skeleton2.path_to_root(index)
    for i in path2_2[1:]:
        mesh_ind = np.where(spinemesh2.vertices == skeleton2.vertices[i])
        mesh_ind = mesh_ind[0][0]
        inds2_a.append(mesh_ind)
        inds2_b.append(mesh_ind)
    inds2_b = np.append(inds2_b,inds2_b[-1])
    line2 = meshparty.trimesh_vtk.linked_point_actor(np.array(meshverts2),np.array(meshverts2),inds_a=inds2_a,inds_b=inds2_b,opacity=1,line_width=5,color=(1,0,0))
else:
    skeleton2_a = skeleton2
    skeleton2_a.reroot(opening_ind2_a)
    path2_2a = skeleton2_a.path_to_root(index)
    skeleton2_b = skeleton2
    skeleton2_b.reroot(opening_ind2_b)
    path2_2b = skeleton2_b.path_to_root(index)
    if len(path2_2a) > len(path2_2b) and len(path2_2b) > 1:
        path2_2 = path2_2b
        opening_ind2 = opening_ind2_b
    else:
        path2_2 = path2_2a
        opening_ind2 = opening_ind2_a
    for i in path2_2[1:]:
        mesh_ind = np.where(spinemesh2.vertices == skeleton2.vertices[i])
        mesh_ind = mesh_ind[0][0]
        inds2_a.append(mesh_ind)
        inds2_b.append(mesh_ind)
    inds2_b = np.append(inds2_b,inds2_b[-1])
    line2 = meshparty.trimesh_vtk.linked_point_actor(np.array(meshverts2),np.array(meshverts2),inds_a=inds2_a,inds_b=inds2_b,opacity=1,line_width=5,color=(1,0,0))

end_actor1 = trimesh_vtk.point_cloud_actor([skelverts1[opening_ind1]],size=100,color=(0.7,0.9,1),opacity=1)
end_actor2 = trimesh_vtk.point_cloud_actor([skelverts2[opening_ind2]],size=100,color=(0.9,0.7,0.6),opacity=1)

# Compare the two lines
line1points = []
verts_ind1 = 0
for i in meshverts1:
    if verts_ind1 in inds1_a:
        line1points.append(i)
    verts_ind1 += 1
line2points = []
verts_ind2 = 0
for i in meshverts2:
    if verts_ind2 in inds2_a:
        line2points.append(i)
    verts_ind2 += 1
class Linemesh:
    def __init__(self, vertices):
        self.vertices = vertices
line1mesh = Linemesh(line1points)
#cloud = trimesh.PointCloud(line1points)
#line1mesh = cloud.convex_hull
compare = meshparty.mesh_filters.filter_spatial_distance_from_points(line1mesh,line2points,200)
print(compare)
numTrue = 0
for i in compare:
    if i == True:
        numTrue += 1
if numTrue > len(compare)/2:
    print("one head")
else:
    print("two heads")

#print(synapse1_loc)
#print(synapse2_loc)
syn1loc_array = np.array(synapse1_loc)
syn2loc_array = np.array(synapse2_loc)
squared_dist = np.sum((syn1loc_array-syn2loc_array)**2,axis=0)
syn_dist = np.sqrt(squared_dist)
print(syn_dist)

# Visualize the meshes, synapses, skeletons, and lines
renderer1 = trimesh_vtk.render_actors(actors=[spinemesh1_actor,spinemesh2_actor,synapse1_actor,synapse2_actor,skeleton1_actor,skeleton2_actor,end_actor1,end_actor2,line1,line2],do_save=False)

# Visualize the meshes, synapses, and lines (no skeletons)
renderer2 = trimesh_vtk.render_actors(actors=[spinemesh1_actor,spinemesh2_actor,synapse1_actor,synapse2_actor,line1,line2],do_save=False)


"""DFS
"""
from string import ascii_lowercase as alphabets

N = int(input())

def dfs(s, used):
    if len(s) == N:
        print(s)
        return
    # 今まで使った文字種＋次の文字まで
    for i in range(used+2):
        t = s
        t += alphabets[i]
        dfs(t, max(used, i))

dfs("a", 0)


# SETTINGS ----------------------------------------------------------------- #
class Settings():
    def __init__(self):
        # BACKGROUND AND WINDOW
        # window dimensions
        self.window_dim = (1000, 500)
        self.window_caption = 'Sorting Algorithms Visualization'

        # ALGORITHMS
        self.alg_list = ['selection_sort',
                         'bubble_sort',
                         'insertion_sort',
                         'quick_sort',
                         'heap_sort',
                         'radix_sort',
                         'shell_sort',
                         'comb_sort',
                         'cocktail_sort']
        # delay
        self.sleep_time = 0.01

        # ARRAY
        self.color_lenght = 1500
        self.lenght = 500
        self.line_width = 2
        #background's color
        self.black = (0,0,0)


import os
from flask import Flask, send_from_directory, jsonify, request, Response
from flask_cors import CORS
import json
import numpy as np
import pandas as pd
import pytz
from datetime import datetime, timedelta
import time
import requests
import math
import sys
from models import metrics, util, arrival_history, wait_times, trip_times, nextbus, constants, errors

"""
This is the app's main file!
"""

# configuration
DEBUG = os.environ.get('FLASK_DEBUG') == '1'

# Create the app
app = Flask(__name__, static_folder='../frontend/build')
CORS(app)

# Test endpoint
@app.route('/api/ping', methods=['GET'])
def ping():
    return "pong"

@app.route('/api/metrics', methods=['GET'])
def metrics_page():
    metrics_start = time.time()
    route_id = request.args.get('routeId')
    if route_id is None:
        route_id = '12'
    start_stop_id = request.args.get('startStopId')
    if start_stop_id is None:
        start_stop_id = '3476'
    end_stop_id = request.args.get('endStopId')

    direction_id = request.args.get('directionId')

    start_date_str = request.args.get('startDate')
    end_date_str = request.args.get('endDate')
    date_str = request.args.get('date')

    if date_str is not None:
        start_date_str = end_date_str = date_str
    else:
        if start_date_str is None:
            start_date_str = '2019-04-08'
        if end_date_str is None:
            end_date_str = start_date_str

    start_time_str = request.args.get('startTime') # e.g. "14:00" (24h time of day)
    end_time_str = request.args.get('endTime') # e.g. "18:00" or "03:00+1" (24h time of day)

    params = {
        'startStopId': start_stop_id,
        'endStopId': end_stop_id,
        'routeId': route_id,
        'directionId': direction_id,
        'startDate': start_date_str,
        'endDate': end_date_str,
        'startTime': start_time_str,
        'endTime': end_time_str,
    }

    data = {
        'params': params
    }

    try:
        route_config = nextbus.get_route_config('sf-muni', route_id)

        start_stop_info = route_config.get_stop_info(start_stop_id)
        if start_stop_info is None:
            raise errors.ValidationError(f"Stop {start_stop_id} is not on route {route_id}")

        data['startStopTitle'] = start_stop_info.title

        if end_stop_id:
            end_stop_info = route_config.get_stop_info(end_stop_id)
            if end_stop_info is None:
                raise errors.ValidationError(f"Stop {end_stop_id} is not on route {route_id}")
            data['endStopTitle'] = end_stop_info.title

        rng = metrics.Range(
            util.get_dates_in_range(start_date_str, end_date_str),
            start_time_str,
            end_time_str,
            pytz.timezone('US/Pacific')
        )

        route_metrics = metrics.RouteMetrics('sf-muni', route_id)

        keys = ['count','avg','min','median','max','percentiles','histogram']

        data['waitTimes'] = route_metrics.get_wait_time_stats(
            direction_id, start_stop_id,
            rng, keys
        )

        data['tripTimes'] = route_metrics.get_trip_time_stats(
            direction_id, start_stop_id, end_stop_id,
            rng, keys
        )

        data['headwayMin'] = route_metrics.get_headway_min_stats(
            direction_id, start_stop_id,
            rng, keys
        )

    except errors.ArrivalHistoryNotFoundError as ex:
        return make_error_response(params, str(ex), 404)
    except errors.ValidationError as ex:
        return make_error_response(params, str(ex), 400)

    metrics_end = time.time()
    data['processingTime'] = (metrics_end - metrics_start)

    res = Response(json.dumps(data, indent=2), mimetype='application/json')
    if not DEBUG:
        res.headers['Cache-Control'] = 'max-age=60'
    return res

def make_error_response(params, error, status):
    data = {
        'params': params,
        'error': error,
    }
    return Response(json.dumps(data, indent=2), status=status, mimetype='application/json')

@app.route('/api/metrics_by_interval', methods=['GET'])
def metrics_by_interval():
    route_id = request.args.get('routeId')
    if route_id is None:
        route_id = '12'
    start_stop_id = request.args.get('startStopId')
    if start_stop_id is None:
        start_stop_id = '3476'
    end_stop_id = request.args.get('endStopId')

    direction_id = request.args.get('directionId')

    start_date_str = request.args.get('startDate')
    end_date_str = request.args.get('endDate')
    date_str = request.args.get('date')

    if date_str is not None:
        start_date_str = end_date_str = date_str
    else:
        if start_date_str is None:
            start_date_str = '2019-04-08'
        if end_date_str is None:
            end_date_str = start_date_str

    start_time_str = request.args.get('startTime') # e.g. "14:00" (24h time of day)
    end_time_str = request.args.get('endTime') # e.g. "18:00" (24h time of day)

    params = {
        'startStopId': start_stop_id,
        'endStopId': end_stop_id,
        'routeId': route_id,
        'directionId': direction_id,
        'startDate': start_date_str,
        'endDate': end_date_str,
        'date': date_str,
        'startTime': start_time_str,
        'endTime': end_time_str,
    }

    data = {
        'params': params
    }

    if start_time_str is not None and end_time_str is not None:
        # round start_time down and end_time up to allow for even intervals
        start_time = datetime.strptime(start_time_str, '%H:%M').replace(microsecond=0, second=0, minute=0)
        end_time = datetime.strptime(end_time_str, '%H:%M').replace(microsecond=0, second=0, minute=0) - timedelta(hours=1)

        time_str_intervals = []
        while start_time.hour != end_time.hour + 1:
            time_str_intervals.append((
                start_time.strftime('%H:%M'),
                (start_time + timedelta(seconds=3600)).strftime('%H:%M')
            ))
            start_time += timedelta(seconds=3600)
    else:
        if start_time_str or end_time_str:
            return make_error_response(params, f'Need both a start and end time', 404)

        time_str_intervals = constants.DEFAULT_TIME_STR_INTERVALS

    try:
        route_metrics = metrics.RouteMetrics('sf-muni', route_id)

        dates = util.get_dates_in_range(start_date_str, end_date_str)

        keys = ['count','avg','min','median','max','percentiles']

        tz = pytz.timezone('US/Pacific')

        def get_interval_stats(start_time_str, end_time_str):

            rng = metrics.Range(dates, start_time_str, end_time_str, tz)

            return {
                    'startTime': start_time_str,
                    'endTime': end_time_str,
                    'waitTimes': route_metrics.get_wait_time_stats(
                        direction_id, start_stop_id,
                        rng, keys
                    ),
                    'tripTimes': route_metrics.get_trip_time_stats(
                        direction_id, start_stop_id, end_stop_id,
                        rng, keys
                    ),
            }

        data['intervals'] = [
            get_interval_stats(start_time_str, end_time_str)
            for start_time_str, end_time_str in time_str_intervals
        ]
    except errors.ArrivalHistoryNotFoundError as ex:
        return make_error_response(params, str(ex), 404)
    except errors.ValidationError as ex:
        return make_error_response(params, str(ex), 400)

    return Response(json.dumps(data, indent=2), mimetype='application/json')

@app.route('/api/config', methods=['GET'])
def config():
    res = Response(json.dumps({"mapbox_access_token": os.environ.get('MAPBOX_ACCESS_TOKEN')}), mimetype='application/json')
    if not DEBUG:
        res.headers['Cache-Control'] = 'max-age=3600'
    return res

if os.environ.get('METRICS_ALL_IN_ONE') == '1':
    @app.route('/frontend/build/<path:path>')
    def frontend_build(path):
        return send_from_directory('../frontend/build', path)

    @app.route('/', defaults={'path': ''})
    @app.route('/<path:path>')
    def wildcard(path):
        return send_from_directory('../frontend/build', 'index.html')
else:
    @app.route('/')
    def root():
        return """
Hello!

This is the API server Go to port 3000 to see the real app.
"""

if __name__ == '__main__':
    # Bind to PORT if defined, otherwise default to 5000.
    port = int(os.environ.get('PORT', 5000))
    app.run(use_reloader=True, threaded=True, host='0.0.0.0', port=port)


from typing import Sequence, Mapping

def maximum_value(max_weight: int, items: Sequence[Mapping[str, int]]) -> int:

    items = [i for i in items if i["weight"] <= max_weight]
    count = len(items)
    knapsack = [[0 for c in range(max_weight + 1)] for r in range(count + 1)]

    for index, item in enumerate(items, start=1):
        for capacity in range(1, max_weight + 1):
            value_without_item = knapsack[index - 1][capacity]
            if item["weight"] > capacity:
                knapsack[index][capacity] = value_without_item
                continue
            running_value = knapsack[index - 1][capacity - item["weight"]]
            value_with_item = running_value + item["value"]
            knapsack[index][capacity] = max(value_without_item, value_with_item)
    return knapsack[count][max_weight]


import random, numpy as np, cv2
from tensorflow.keras.callbacks import TensorBoard, ModelCheckpoint, Callback

from trainers.trainer_base import TrainerBase

class AugmentionTrainer(TrainerBase):
    def __init__(self, model, data, config):
        super(AugmentionTrainer, self).__init__(model, data, config)
        self.model = model
        self.data = data
        self.config = config
        self.callbacks = []
        self.init_callbacks()

    def init_callbacks(self):
        self.callbacks.append(
            ModelCheckpoint(
                filepath=self.config.hdf5_path + self.config.exp_name + '_best_weights.h5',
                verbose=1,
                monitor='val_loss',
                mode='auto',
                save_best_only=True
            )
        )

        self.callbacks.append(
            TensorBoard(
                log_dir=self.config.checkpoint,
                write_images=True,
                write_graph=True,
            )
        )

    def train(self):
        no_train, no_test, lower_train, lower_test, full_train, full_test = self.data
        hist = self.model.fit([no_train, lower_train], [full_train],
                              batch_size=self.config.batch_size,
                              epochs=self.config.epochs,
                              verbose=1,
                              callbacks=self.callbacks,
                              validation_data=([no_test, lower_test], [full_test]),
                              )
        self.model.save_weights(self.config.hdf5_path + self.config.exp_name + '_last_weights.h5', overwrite=True)


#!/usr/bin/python
import re
import urllib
import urllib2

opener = urllib2.build_opener()
opener.addheaders = [('User-Agent', 'Mozilla/5.0')]
state = opener.open("https://www.daneshjooyar.com/security-on-php-websites/")

code = state.read()

User_list = re.findall('''"name">(.+)</span>''',code,re.M)

f = open('Users','w')

for i in User_list:
	f.write(i)

f.close()

Project one/daneshjooyar/Part 3/Extracting Users.py


class Solution:
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        nums_len = len(nums)
        flag = 0
        for num in nums:
            if num != 0:
                nums[flag] = num
                flag += 1
        for i in range(flag, nums_len):
            nums[i] = 0

if __name__ == '__main__':
    a = Solution()
    nums = [0, 1, 0, 3, 12]
    a.moveZeroes(nums)
    print(nums)


import time
import datetime
# [START pubsub_quickstart_sub_deps]
from google.cloud import pubsub_v1
# [END pubsub_quickstart_sub_deps]

import os
import sqlalchemy
from sqlalchemy import Table, Column, Integer, String, MetaData
from sqlalchemy import create_engine

engine = create_engine('mysql+pymysql://alvarov:lata5comprar@35.198.8.176:3306/prueba_appengine', echo=True)
#engine = create_engine('mysql+pymysql://alvarov:lata5comprar@/prueba_appengine?unix_socket=/cloudsql/asistente-180018:southamerica-east1:bd-bsa-chequeo-planta', echo=True)
metadata = MetaData()
users = Table('datosConsumo', metadata,
   Column('id', Integer, primary_key=True),
   Column('dispositivo', String(250)),
   Column('valor', String(50)),
   Column('fecha',String(100)),
   Column('fechanow',sqlalchemy.types.DateTime(timezone=True),default=datetime.datetime.utcnow)
)
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'key.json'
#variables

proyecto='asistente-180018'
topico='casa1-consumo-sub1'

def sub(project_id, subscription_name):
    """Receives messages from a Pub/Sub subscription."""
    # [START pubsub_quickstart_sub_client]
    # Initialize a Subscriber client
    client = pubsub_v1.SubscriberClient()
    # [END pubsub_quickstart_sub_client]
    # Create a fully qualified identifier in the form of
    # `projects/{project_id}/subscriptions/{subscription_name}`
    subscription_path = client.subscription_path(
        project_id, subscription_name)

    def callback(message):
        #print(message['PublishTime'])
        print('Received message {} of message ID {}'.format(
            message, message.message_id))

        # Acknowledge the message. Unack'ed messages will be redelivered.
        message.ack()

        print('Acknowledged message of message ID {}\n'.format(
            message.message_id))

        ins = users.insert().values(valor=str(message.data),fecha=str(message.publish_time))
        conn = engine.connect()
        result = conn.execute(ins)

    client.subscribe(subscription_path, callback=callback)
    print('Listening for messages on {}..\n'.format(subscription_path))

    while True:
        time.sleep(60)

if __name__ == '__main__':
    sub(proyecto, topico)


import logging
import os
import subprocess

from pyramid.response import Response
from pyramid.response import FileResponse
from pyramid.view import view_config

from sqlalchemy.exc import DBAPIError
from sqlalchemy import and_

from .models import (
    DBSession, BallotMeasure, Committee, Contract, Stance
    )

BUILD_DIR = 'build'

logger = logging.getLogger(__name__)

class BaseView(object):
    def __init__(self, request):
        self.request = request

    @view_config(route_name='open_ballot', renderer='templates/index.pt')
    def my_view(self):
        return {'one': 'one', 'project': 'open_ballot'}

def app(request):
    logger.info('Building app...')
    if not os.path.exists(BUILD_DIR):
        os.mkdir(BUILD_DIR)
    subprocess.call(['browserify',
                     'open_ballot/js/app.js',
                     '-o', 'build/bundle.js'])
    return FileResponse('build/bundle.js', request=request)

class BallotAjaxView(BaseView):
    @view_config(route_name='ajax_get_ballot', renderer='json',
        request_method='GET')
    def get_ballot(self):
        '''
        Returns a single ballot.  Called with GET /ajax/ballots/{id}
        Note that some ballot measures are missing a ballot type.
        '''

        ballot_measure = BallotMeasure.get_by_id(self.request.matchdict['id'])
        ballot_measure_json = {
            'id': ballot_measure.id,
            'name': ballot_measure._name,
            'prop_id': ballot_measure.prop_id,
            'description': ballot_measure.description,
            'num_yes': ballot_measure.num_yes,
            'num_no': ballot_measure.num_no,
            'passed': ballot_measure.passed,
            'election': {
                'date': ballot_measure.election.date.isoformat()
            }
        }

        if ballot_measure.ballot_type:
            ballot_measure_json.update({'ballot_type': {
                'name': ballot_measure.ballot_type.name,
                'percent_required':\
                    float(ballot_measure.ballot_type.percent_required)
                }
            }
        )

        return ballot_measure_json

    @view_config(route_name='ajax_get_ballots', renderer='json',
        request_method='GET')
    def get_ballots(self):
        '''
        Returns a list of all ballots.  Called with GET /ajax/ballots
        Note that some ballot measures are missing a ballot type.
        '''

        ballot_measure_jsons = []

        for ballot_measure in BallotMeasure.all():
            ballot_measure_json = {
                'id': ballot_measure.id,
                'name': ballot_measure._name,
                'prop_id': ballot_measure.prop_id,
                'description': ballot_measure.description,
                'num_yes': ballot_measure.num_yes,
                'num_no': ballot_measure.num_no,
                'passed': ballot_measure.passed,
                'election': {
                    'date': ballot_measure.election.date.isoformat()
                }
            }

            if ballot_measure.ballot_type:
                ballot_measure_json.update({'ballot_type': {
                    'name': ballot_measure.ballot_type.name,
                    'percent_required':\
                        float(ballot_measure.ballot_type.percent_required)
                    }
                }
            )

            ballot_measure_jsons.append(ballot_measure_json)

        return ballot_measure_jsons

    @view_config(route_name='ajax_get_donations', renderer='json',
        request_method='GET')
    def get_committees(self):
        '''
        Get the committees working on a ballot measure, with their stance.
        Called by GET /ajax/ballots/{id}/committees
        '''
        committee_jsons = []

        ballot_measure = BallotMeasure.get_by_id(self.request.matchdict['id'])
        committees = DBSession.query(Committee).join(
            Stance, and_(
                Stance.ballot_measure_id==ballot_measure.id,
                Stance.committee_id==Committee.id)
            ).join(
                Contract, and_(
                    Contract.committee_id==Committee.id
                )
            )

        for committee in committees:
            # Sum the contracts
            total_spend = sum(map(lambda contract: contract.payment,
                committee.contracts))

            committee_json = {
                'id': committee.id,
                'name': committee.name,
                'election': {
                    'date': committee.election.date.isoformat()
                },
                'stance': {
                    #TODO: Rename this to "supported"?
                    'voted_yes': committee.stance.voted_yes
                },
                'total_spend': total_spend
            }

            committee_jsons.append(committee_json)

        return committee_jsons


"""TO-DO: Write a description of what this XBlock is."""

import pkg_resources

from xblock.core import XBlock
from xblock.fields import Scope, String, Integer, Float, Boolean, DateTime
from xblock.fragment import Fragment

from random import choice

class ShowLessonInIframeXBlock(XBlock):
    """
    TO-DO: document what your XBlock does.
    """

    # Fields are defined on the class.  You can access them in your code as
    # self.<fieldname>.

    score = Float(
        values={"min": 0},
        default=None, scope=Scope.user_state,
        help="User answer score",
    )

    state = String(
        default=None, scope=Scope.user_state,
        help="State of xblock",
    )

    href = String(
        display_name="src for IFrame",
        help=("lesson url"),
        default=None,
        scope=Scope.settings,
    )

    width = String(
        display_name="IFrame width",
        help=("IFrame width"),
        default='100%',
        scope=Scope.settings,
    )

    height = String(
        display_name="IFrame Height",
        help=("IFrame Height"),
        default='500px',
        scope=Scope.settings,
    )

    maxscore = Float(
        values={"min": 1},
        default=1, scope=Scope.settings,
        help=("Max score"),
    )

    has_score = True

    def resource_string(self, path):
        """Handy helper for getting resources from our kit."""
        data = pkg_resources.resource_string(__name__, path)
        return data.decode("utf8")

    def studio_view(self, context=None):
        """
        Create a fragment used to display the edit view in the Studio.
        """
        html = self.resource_string("static/html/slif_studio_edit.html")
        frag = Fragment(html.format(self=self))
        frag.add_javascript(self.resource_string("static/js/src/slif_studio_edit.js"))
        frag.initialize_js('SlifStudioEdit')

        return frag

    # TO-DO: change this view to display your data your own way.
    def student_view(self, context=None):
        """
        The primary view of the ShowLessonInIframeXBlock, shown to students
        when viewing courses.
        """
        if not self.href:
            html = self.resource_string("static/html/slif_student_empty.html")
            frag = Fragment(html.format(self=self))
            frag.add_css(self.resource_string("static/css/slif_empty.css"))
            return frag
        else:
            html = self.resource_string("static/html/slif.html")
            frag = Fragment(html.format(self=self))
            frag.add_javascript_url(self.runtime.local_resource_url(self, 'public/js/jschannel.js'))
            frag.add_javascript(self.resource_string("public/js/production.js"))
            frag.add_javascript(self.resource_string("static/js/src/slif.js"))
            # frag.add_css(self.resource_string("public/css/style.css"))
            frag.initialize_js('ShowLessonInIframeXBlock', {'state': self.state,
                                                            'answer': self.score})
        return frag

    @XBlock.json_handler
    def studio_submit(self, data, suffix=''):
        """
        Called when submitting the form in Studio.
        """
        self.href = data.get('href')
        self.width  = data.get('width')
        self.height = data.get('height')

        try:
            m = float(data.get('maxscore'))
            if m >= 1:
                self.maxscore = m
        except:
            pass

        return {'result': 'success'}

    @XBlock.json_handler
    def save_x_state(self, data, suffix=''):
        out = {}

        # save it in string format. Dont need to unpack it
        if 'state' in data['values']:
            self.state = data['values']['state']
            out['state'] = 'ok'

        if 'score' in data['values']:
            score = data['values']['score']
            if score.isdigit():
                self.score = float(score)

                if self.score <= self.maxscore:
                    grade_event = {'value': self.score, 'max_value': self.maxscore}
                    self.runtime.publish(self, 'grade', grade_event)

                out['score'] = self.score

            else:
                out['error'] = 'score: bad type'

        return out

    # TO-DO: change this to create the scenarios you'd like to see in the
    # workbench while developing your XBlock.
    @staticmethod
    def workbench_scenarios():
        """A canned scenario for display in the workbench."""
        return [
            ("ShowLessonInIframeXBlock",
             """<slif/>
             """),
            ("Multiple ShowLessonInIframeXBlock",
             """<vertical_demo>
                <slif/>
                </vertical_demo>
             """),
        ]

    # Everything below is stolen from
    # https://github.com/edx/edx-ora2/blob/master/apps/openassessment/
    #        xblock/lms_mixin.py
    # It's needed to keep the LMS+Studio happy.
    # It should be included as a mixin.

    display_name = String(
        default="SLIFtest!", scope=Scope.settings,
        help="Display name"
    )

    start = DateTime(
        default=None, scope=Scope.settings,
        help="ISO-8601 formatted string representing the start date "
             "of this assignment. We ignore this."
    )

    due = DateTime(
        default=None, scope=Scope.settings,
        help="ISO-8601 formatted string representing the due date "
             "of this assignment. We ignore this."
    )

    weight = Float(
        display_name="Problem Weight",
        help=("Defines the number of points each problem is worth. "
              "If the value is not set, the problem is worth the sum of the "
              "option point values."),
        values={"min": 0, "step": .1},
        scope=Scope.settings
    )

    def has_dynamic_children(self):
        """Do we dynamically determine our children? No, we don't have any.
        """
        return False

    def max_score(self):
        """The maximum raw score of our problem.
        """
        return self.maxscore


import numpy as np
import csv
from sklearn.utils import shuffle
from keras import models
from keras import layers
from keras import optimizers
from numpy.lib.npyio import savetxt
from tensorflow.python.keras.layers.embeddings import Embedding
from tensorflow.python.keras.layers.recurrent import SimpleRNN

file = open('df_text_eng.csv', 'r')
file = file.readlines()

"""
Creates vocabulary from training data. Will condense the vocabulary to a user-specified minimum number of
occurances for each word. A non-condensed vocabulary would be far too large given the number of training
data samples.
"""
def generateVocabulary(minOccurances):
    vocabulary = {}
    for line in file:
        line = line.split()
        for word in line[1:-1]:
            if word in vocabulary.keys():
                vocabulary[word] += 1
            else:
                vocabulary[word] = 1

    vocabulary_refined = []
    for word in vocabulary.keys():
        if vocabulary[word] > minOccurances:
            vocabulary_refined.append(word)
    return vocabulary_refined

"""
Creates 2D numpy array which will hold the labels for each sample.
"""
def createMatrix(vocab, cutoff):
    return np.zeros((cutoff, len(vocab)), dtype = int)

def condenseData(m, t):
    print("condensing")
    matrix = []
    targets = []
    for i in range(len(m)):
        has1 = False
        for num in m[i]:
            if num == 1:
                has1 = True
        if has1:
            matrix.append(m[i])
            targets.append(t[i])
    return np.asarray(matrix), np.asarray(targets)

def populateTrainMatrix(vocab, matrix):
    targets = []
    for i in range(len(matrix)):
        line = file[i].split("\",\" ")
        targets.append(-1)
        try:
            for word in line[1].split():
                if word in vocab:
                    matrix[i][vocab.index(word)] = 1
            if line[2][:-2] == 'failed':
                targets[i] = 0
            else:
                targets[i] = 1
        except IndexError:
            continue
    return condenseData(matrix, targets)

def createTestMatrix(vocab, cutoff):
    return np.zeros((len(file) - cutoff, len(vocab)), dtype = int)

def populateTestMatrix(vocab, matrix, cutoff):
    targets = []
    for i in range(len(file) - len(matrix)):
        line = file[i + len(matrix)].split("\",\" ")
        targets.append(-1)
        try:
            for word in line[1].split():
                if word in vocab:
                    matrix[i][vocab.index(word)] = 1
            if line[2][:-2] == 'failed':
                targets[i] = 0
            else:
                targets[i] = 1
        except IndexError:
            continue
    return condenseData(matrix, targets)

"""
Creates keras model
"""
def createModel(cutoff, vocab_length):
    model = models.Sequential()

    model.add(layers.Dense(16, activation = 'relu', input_shape = (cutoff,vocab_length)))
    model.add(layers.Dense(8, activation = 'relu'))
    model.add(layers.Dense(1, activation = 'sigmoid'))
    """
    model.add(Embedding(vocab_length, 32))
    model.add(SimpleRNN(32))
    model.add(layers.Dense(1, activation = 'sigmoid'))
    """

    model.compile(optimizer = 'rmsprop', loss = 'binary_crossentropy', metrics = ['accuracy'])

    return model

"""
Trains keras model with the training data and evaluates with the test data
"""
def trainAndEvaluate(model, train_matrix, train_targets, test_matrix, test_targets):
    history = model.fit(train_matrix, train_targets, epochs = 15, batch_size = 500, validation_data = (train_matrix, train_targets))
    results = model.evaluate(test_matrix, test_targets)

def main():
    vocab = generateVocabulary(300)
    print(len(vocab))
    cutoff = int(len(file) * 0.7)
    train_matrix = createMatrix(vocab, cutoff)
    train_matrix, train_targets = populateTrainMatrix(vocab, train_matrix)
    print("1")

    test_matrix = createTestMatrix(vocab, cutoff)
    test_matrix, test_targets = populateTestMatrix(vocab, test_matrix, cutoff)
    print("2")

    model = createModel(cutoff, len(vocab))

    trainAndEvaluate(model, train_matrix, train_targets, test_matrix, test_targets)

main()


#!/usr/bin/env python

import re
import sys

regexs = { r'^\w{3}$' : 'three letters',
           r'.*t' : 'ends in t',
           r'.*k.*': 'contains a k'
           }

for line in map(str.strip, sys.stdin):
    matches = [ desc for regex,desc in regexs.items() if re.match(regex,line) ]
    sys.stdout.write("{0}: {1}\n".format(line, ",".join(matches)))

## Generally if you eliminated the "i" variable and replaced the while
## loop with a for each loop, and turned the regex/descriptions lists
## into a dict you received full credit. Still be sure to understand
## these solutions and come to your own conclusion about which you
## think are better.

## Also, be descriptive with your variables.

if False:
    for i in regexs:
        ##what is i?
        re.match(i, 'some text')
    for regex in regexs:
        ##ah, this makes more sense
        re.match(regex, 'some text')
## likewise

if False:
    for key,value in regexs.items():
        ## all I know is that I have a 'key' and a 'value'
        if re.match(key, 'some text'):
            matches.append(value)
    for regex,description in regex.items():
        ## a tad more typing, but now I know exactly what is going on when I use the unpacked variables later.
        if re.match(regex, 'some text'):
            matches.append(description)


"""Support for getting status from a Pi-hole system."""
from homeassistant.components.binary_sensor import BinarySensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_NAME
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback

from . import PiHoleEntity
from .const import DATA_KEY_API, DATA_KEY_COORDINATOR, DOMAIN as PIHOLE_DOMAIN

async def async_setup_entry(
    hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
    """Set up the Pi-hole binary sensor."""
    name = entry.data[CONF_NAME]
    hole_data = hass.data[PIHOLE_DOMAIN][entry.entry_id]
    binary_sensors = [
        PiHoleBinarySensor(
            hole_data[DATA_KEY_API],
            hole_data[DATA_KEY_COORDINATOR],
            name,
            entry.entry_id,
        )
    ]
    async_add_entities(binary_sensors, True)

class PiHoleBinarySensor(PiHoleEntity, BinarySensorEntity):
    """Representation of a Pi-hole binary sensor."""

    @property
    def name(self) -> str:
        """Return the name of the sensor."""
        return self._name

    @property
    def unique_id(self) -> str:
        """Return the unique id of the sensor."""
        return f"{self._server_unique_id}/Status"

    @property
    def is_on(self) -> bool:
        """Return if the service is on."""
        return self.api.data.get("status") == "enabled"  # type: ignore[no-any-return]


#   Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# 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.

import unittest
import sys

sys.path.append('..')
import numpy as np
from op_test import OpTest
import paddle.fluid as fluid
import paddle

paddle.enable_static()

def test_class1(op_type, typename):
    class TestExpandAsBasic(OpTest):
        def setUp(self):
            self.set_mlu()
            self.op_type = "expand_as_v2"
            self.python_api = paddle.expand_as
            x = np.random.rand(100).astype(typename)
            target_tensor = np.random.rand(2, 100).astype(typename)
            self.inputs = {'X': x}
            self.attrs = {'target_shape': target_tensor.shape}
            bcast_dims = [2, 1]
            output = np.tile(self.inputs['X'], bcast_dims)
            self.outputs = {'Out': output}

        def set_mlu(self):
            self.__class__.use_mlu = True
            self.place = paddle.device.MLUPlace(0)
            self.__class__.no_need_check_grad = True

        def test_check_output(self):
            self.check_output_with_place(self.place)

    cls_name = str(op_type) + "_" + str(typename) + "_1"
    TestExpandAsBasic.__name__ = cls_name
    globals()[cls_name] = TestExpandAsBasic

def test_class2(op_type, typename):
    class TestExpandAsOpRank2(OpTest):
        def setUp(self):
            self.set_mlu()
            self.op_type = "expand_as_v2"
            self.python_api = paddle.expand_as
            x = np.random.rand(10, 12).astype(typename)
            target_tensor = np.random.rand(10, 12).astype(typename)
            self.inputs = {'X': x}
            self.attrs = {'target_shape': target_tensor.shape}
            bcast_dims = [1, 1]
            output = np.tile(self.inputs['X'], bcast_dims)
            self.outputs = {'Out': output}

        def set_mlu(self):
            self.__class__.use_mlu = True
            self.place = paddle.device.MLUPlace(0)
            self.__class__.no_need_check_grad = True

        def test_check_output(self):
            self.check_output_with_place(self.place)

    cls_name = str(op_type) + "_" + str(typename) + "_2"
    TestExpandAsOpRank2.__name__ = cls_name
    globals()[cls_name] = TestExpandAsOpRank2

def test_class3(op_type, typename):
    class TestExpandAsOpRank3(OpTest):
        def setUp(self):
            self.set_mlu()
            self.op_type = "expand_as_v2"
            self.python_api = paddle.expand_as
            x = np.random.rand(2, 3, 20).astype(typename)
            target_tensor = np.random.rand(2, 3, 20).astype(typename)
            self.inputs = {'X': x}
            self.attrs = {'target_shape': target_tensor.shape}
            bcast_dims = [1, 1, 1]
            output = np.tile(self.inputs['X'], bcast_dims)
            self.outputs = {'Out': output}

        def set_mlu(self):
            self.__class__.use_mlu = True
            self.place = paddle.device.MLUPlace(0)
            self.__class__.no_need_check_grad = True

        def test_check_output(self):
            self.check_output_with_place(self.place)

    cls_name = str(op_type) + "_" + str(typename) + "_3"
    TestExpandAsOpRank3.__name__ = cls_name
    globals()[cls_name] = TestExpandAsOpRank3

def test_class4(op_type, typename):
    class TestExpandAsOpRank4(OpTest):
        def setUp(self):
            self.set_mlu()
            self.op_type = "expand_as_v2"
            self.python_api = paddle.expand_as
            x = np.random.rand(1, 1, 7, 16).astype(typename)
            target_tensor = np.random.rand(4, 6, 7, 16).astype(typename)
            self.inputs = {'X': x}
            self.attrs = {'target_shape': target_tensor.shape}
            bcast_dims = [4, 6, 1, 1]
            output = np.tile(self.inputs['X'], bcast_dims)
            self.outputs = {'Out': output}

        def set_mlu(self):
            self.__class__.use_mlu = True
            self.place = paddle.device.MLUPlace(0)
            self.__class__.no_need_check_grad = True

        def test_check_output(self):
            self.check_output_with_place(self.place)

    cls_name = str(op_type) + "_" + str(typename) + "_4"
    TestExpandAsOpRank4.__name__ = cls_name
    globals()[cls_name] = TestExpandAsOpRank4

# Test python API
class TestExpandAsV2API(unittest.TestCase):
    def test_api(self):
        input1 = np.random.random([12, 14]).astype("float32")
        input2 = np.random.random([2, 12, 14]).astype("float32")
        x = fluid.layers.data(
            name='x', shape=[12, 14], append_batch_size=False, dtype="float32"
        )

        y = fluid.layers.data(
            name='target_tensor',
            shape=[2, 12, 14],
            append_batch_size=False,
            dtype="float32",
        )

        out_1 = paddle.expand_as(x, y=y)

        exe = fluid.Executor(place=fluid.MLUPlace(0))
        res_1 = exe.run(
            fluid.default_main_program(),
            feed={"x": input1, "target_tensor": input2},
            fetch_list=[out_1],
        )
        assert np.array_equal(res_1[0], np.tile(input1, (2, 1, 1)))

for _typename in {
    'float16',
    'float32',
    'int64',
    'int32',
    'int8',
    'uint8',
    'bool',
}:
    test_class1('expand_as_v2', _typename)
    test_class2('expand_as_v2', _typename)
    test_class3('expand_as_v2', _typename)
    test_class4('expand_as_v2', _typename)

if __name__ == "__main__":
    unittest.main()


from django.urls import path
from homepage import views

urlpatterns = [
    path('', views.homepage, name='homepage'),
    path('signup/', views.signup, name = 'signup'),
    path('login/', views.login, name = 'login'),
    path('logout-request/', views.logout_request, name = 'logout_request'),
    path('activate/<uidb64>/<token>/', views.activate, name='activate'),
    path('reset-password/<uidb64>/<token>/', views.reset_password, name='reset_password'),
    path('email-input/', views.email_input, name='email_input'),
    path('tnc/', views.tnc, name='tnc'),
    path('glucose-input/', views.glucose_input, name='glucose_input'),
    path('carbs-input/', views.carbs_input, name='carbs_input'),
    path('insulin-input/', views.insulin_input, name='insulin_input'),
    path('profile-page/', views.profile_page, name='profile_page'),
    path('dashboard/', views.dashboard, name='dashboard'),
    path('dashboard-data/<start_date>/<end_date>/', views.dashboard_data, name='dashboard_data'),
    path('api-glucose/', views.GlucoseView.as_view(), name='GlucoseView'),
    path('api-carbs/', views.CarbsView.as_view(), name='CarbsView'),
    path('api-insulin/', views.InsulinAPIView.as_view(), name='InsulinAPIView'),
    path('analytics-data/<start_date>/<end_date>/', views.analytics_data, name='analytics_data'),
    path('analytics', views.analytics, name='analytics'),
    path('glossary/', views.glossary, name='glossary'),
    path('analytics-trend-data/<day>/<glucose_bool>/', views.analytics_trend_data, name='analytics_trend_data'),
]


from platform import mac_ver
@require(platform=MACOS)
@plugin('os')
def Os__MAC(jarvis, s):
    #Displays information about your operating system
    print(
        Style.BRIGHT
        + '[!] Operating System Information'
        + Style.RESET_ALL,
        Fore.BLUE)
    print('[*] Kernel: ' + sys(), Fore.GREEN)
    print('[*] Kernel Release Version: ' + release(), Fore.GREEN)
    print('[*] macOS System version: ' + mac_ver()[0], Fore.GREEN)
    for _ in architecture():
        if _ is not '':
            print('[*] ' + _, Fore.GREEN)

@require(platform=MACOS, native="pmset")
@plugin('screen off')
def screen_off__MAC(jarvis, s):
    #Turn of screen instantly
    os.system('pmset displaysleepnow')

@require(platform=MACOS, native="screenfetch")
@plugin('systeminfo')
def systeminfo__MAC(jarvis, s):
    #Display system information with distribution logo
    os.system("screenfetch")

@require(platform=MACOS)
@plugin("update system")
def update_system__macos(jarvis, s):
    os.system('brew upgrade && brew update')

@require(platform=MACOS)
@plugin('shutdown')
def shutdown_MACOS(jarvis, s):
    """
    Shutdown the system
    Uses:
    shutdown : asks for time
    shutdown -c : cancels shutdown
    """
    if s == '':
        s = jarvis.input('In how many minutes?: ')
    if s == '-c':
        os.system('sudo killall shutdown')
        jarvis.say('Shutdown operation cancelled')
        return
    string = 'sudo shutdown -h +' + str(s)
    os.system(string)

# Mac
def increase_volume__MAC():
    #Increases your speaker's sound.
    system(
        'osascript -e "set volume output volume '
        '(output volume of (get volume settings) + 10) --100%"'
    )

def decrease_volume__MAC():
    #Decreases your speaker's sound.
    system(
        'osascript -e "set volume output volume '
        '(output volume of (get volume settings) - 10) --100%"'
    )

import re
import subprocess

def get_speaker_output_volume():
    """
    Get the current speaker output volume from 0 to 100.

    Note that the speakers can have a non-zero volume but be muted, in which
    case we return 0 for simplicity.

    Note: Only runs on macOS.
    """
    cmd = "osascript -e 'get volume settings'"
    process = subprocess.run(cmd, stdout=subprocess.PIPE, shell=True)
    output = process.stdout.strip().decode('ascii')

    pattern = re.compile(r"output volume:(\d+), input volume:(\d+), "
                         r"alert volume:(\d+), output muted:(true|false)")
    volume, _, _, muted = pattern.match(output).groups()

    volume = int(volume)
    muted = (muted == 'true')

    return 0 if muted else volume

    #
    vol = get_speaker_output_volume()
    print(f'Volume: {vol}%')
    #output = 'volume: 80%'
get_speaker_output_volume()


from tr_option.base import KWTR
from copy import deepcopy

# [ opt10052 : 거래원순간거래량요청 ]
class Opt10052(KWTR):

    def __init__(self, core):
        super().__init__(core)

        self.rq_name = self.tr_code = 'opt10052'

        self.record_name_multiple = '거래원순간거래량'
        self.header_multiple = [
            '시간', '종목코드', '종목명', '거래원명', '구분', '순간거래량', '누적순매수', '현재가', '전일대비기호', '전일대비', '전일대비',
        ]

    def tr_opt(self, input0, code, input2, input3, input4, prev_next, screen_no):
        # 회원사코드 = 888:외국계 전체, 나머지 회원사 코드는 OPT10042 조회 또는 GetBranchCodeName()함수사용
        # SetInputValue("종목코드"	,  "입력값 2");
        # 시장구분 = 0:전체, 1:코스피, 2:코스닥, 3:종목
        # 수량구분 = 0:전체, 1:1000주, 2:2000주, 3:, 5:, 10:10000주, 30: 30000주, 50: 50000주, 100: 100000주
        # 가격구분 = 0:전체, 1:1천원 미만, 8:1천원 이상, 2:1천원 ~ 2천원, 3:2천원 ~ 5천원, 4:5천원 ~ 1만원, 5:1만원 이상

        self.core.set_input_value('회원사코드', input0)
        self.core.set_input_value('종목코드', code)
        self.core.set_input_value('시장구분', input2)
        self.core.set_input_value('수량구분', input3)
        self.core.set_input_value('가격구분', input4)
        self.core.comm_rq_data(self.rq_name, self.tr_code, prev_next, screen_no)

        self.tr_data = deepcopy(self.core.receive_tr_data_handler[self.tr_code][screen_no])

        return self.tr_data


# MIT License
#
# Copyright (c) 2019 Red Hat, Inc.

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

import logging

import click
from pkg_resources import get_distribution

from packit.cli.build import build
from packit.cli.copr_build import copr_build
from packit.cli.create_update import create_update
from packit.cli.init import init
from packit.cli.local_build import local_build
from packit.cli.push_updates import push_updates
from packit.cli.srpm import srpm
from packit.cli.status import status
from packit.cli.sync_from_downstream import sync_from_downstream
from packit.cli.update import update
from packit.cli.validate_config import validate_config
from packit.config import Config, get_context_settings
from packit.utils.logging import set_logging

logger = logging.getLogger("packit")

class AliasedGroup(click.Group):
    def get_command(self, ctx, cmd_name):
        if cmd_name == "generate":
            click.secho(
                "WARNING: 'packit generate' is deprecated and it "
                "is going to be removed. Use 'packit init' instead.",
                fg="yellow",
            )
            return click.Group.get_command(self, ctx, "init")
        else:
            return click.Group.get_command(self, ctx, cmd_name)

@click.group("packit", cls=AliasedGroup, context_settings=get_context_settings())
@click.option("-d", "--debug", is_flag=True, help="Enable debug logs.")
@click.option("--fas-user", help="Fedora Account System username.")
@click.option("-k", "--keytab", help="Path to FAS keytab file.")
@click.option(
    "--remote",
    default=None,
    help=(
        "Name of the remote to discover upstream project URL, "
        "If this is not specified, default to the first remote."
    ),
)
@click.option(
    "--dry-run",
    is_flag=True,
    help="Do not perform any remote changes (pull requests or comments).",
)
@click.version_option(
    version=get_distribution("packitos").version, message="%(version)s"
)
@click.pass_context
def packit_base(ctx, debug, fas_user, keytab, dry_run, remote):
    """Integrate upstream open source projects into Fedora operating system."""
    if debug:
        # to be able to logger.debug() also in get_user_config()
        set_logging(level=logging.DEBUG)

    c = Config.get_user_config()
    c.debug = debug or c.debug
    c.dry_run = dry_run or c.dry_run
    c.fas_user = fas_user or c.fas_user
    c.keytab_path = keytab or c.keytab_path
    c.upstream_git_remote = remote or c.upstream_git_remote
    ctx.obj = c

    if ctx.obj.debug:
        set_logging(level=logging.DEBUG)
        set_logging(logger_name="sandcastle", level=logging.DEBUG)
    else:
        set_logging(level=logging.INFO)

    packit_version = get_distribution("packitos").version
    logger.debug(f"Packit {packit_version} is being used.")

packit_base.add_command(update)
packit_base.add_command(sync_from_downstream)
packit_base.add_command(build)
packit_base.add_command(copr_build)
packit_base.add_command(create_update)
packit_base.add_command(push_updates)
packit_base.add_command(srpm)
packit_base.add_command(status)
packit_base.add_command(init)
packit_base.add_command(local_build)
packit_base.add_command(validate_config)

if __name__ == "__main__":
    packit_base()


#!/usr/bin/env python
"""
A custom class to send logs to rabbitMQ
"""
__author__ = "Lloyd McCarthy"
__license__ = "MIT"

import logging
import kombu

class RabbitMQHandler(logging.Handler):
    """
    Handler that sends message to RabbitMQ using kombu.
    """
    def __init__(self, uri=None, queue='logstash'):
        logging.Handler.__init__(self)
        connection = kombu.Connection(uri, connect_timeout=1)
        connection.connect()
        self.queue = connection.SimpleQueue(queue)

    def emit(self, record):
        """
        Puts the record on a logging queue.
        Arguments:
            record {[type]} -- [description]
        """
        self.queue.put(record.msg)

    def close(self):
        """
        Closes the queue.
        """
        try:
            self.queue.close()
        except AttributeError:
            return None


from solvertools.wordlist import WORDS
from solvertools.normalize import slugify, sanitize
from solvertools.util import data_path
from whoosh.index import open_dir
from whoosh import qparser
import re

INDEX = None
QUERY_PARSER = None

def search(pattern=None, clue=None, length=None, count=20):
    """
    Find words and phrases that match various criteria: a regex pattern,
    a clue phrase, and/or a length.

    >>> search('.a.b.c..')[0][1]
    'BARBECUE'
    >>> search('.a....e.', clue='US President')[0][1]
    'VAN BUREN'
    >>> search(clue='lincoln assassin', length=15)[0][1]
    'JOHN WILKES BOOTH'
    """
    global INDEX, QUERY_PARSER
    if clue is None:
        if pattern is None:
            return []
        else:
            return WORDS.search(pattern, count=count, use_cromulence=True)

    if pattern is not None:
        pattern = pattern.lstrip('^').rstrip('$').lower()
        pattern = re.compile('^' + pattern + '$')

    if INDEX is None:
        INDEX = open_dir(data_path('search'))
        QUERY_PARSER = qparser.SimpleParser(
            "definition", schema=INDEX.schema,
            group=qparser.OrGroup.factory(0.9)
        )
        QUERY_PARSER.add_plugin(qparser.GroupPlugin())
        QUERY_PARSER.add_plugin(qparser.BoostPlugin())

    matches = []
    with INDEX.searcher() as searcher:
        results = searcher.search(QUERY_PARSER.parse(clue), limit=20)
        # half-assed query expansion
        clue_parts = set([sanitize(result['text']) for result in results])
        expanded_clue = ", ".join(clue_parts)
        new_clue = '%s, (%s)^0.01' % (clue, expanded_clue)
        results = searcher.search(QUERY_PARSER.parse(new_clue), limit=None)
        seen = set()
        for i, result in enumerate(results):
            text = result['text']
            slug = slugify(text)
            if slug not in seen:
                if length is None or length == len(slug):
                    if pattern is None or pattern.match(slug):
                        seen.add(slug)
                        #crom, text = WORDS.cromulence(slug)
                        score = results.score(i)
                        matches.append((score, text))
                        if len(matches) >= count:
                            break
        return matches


print("welcome to water ride ticker counter.!!")
h=int(input("mention your height in cm : "))
a = int(input("mention your age : "))
bill = 0;
if h>=120:
    print("\nyou are eligible to enter water ride.")
    if a<18:
        bill=130;
        print(f"You need to  pay {bill} rupees to generate ticket.\n")

    elif a>=18:
        bill =150;
        print(f"You need to  {bill} rupees to generate ticket.\n")

    else:
        bill = 100;
        print("You need to  {bill} rupees to generate ticket.\n")

    pic=input("do you want pictures of your water ride.? Y or N :")
    if pic =="y":
       bill=bill+50;
       print(f"\ttotal amount to be paid {bill}")
       print("\n\t STAY SAFE AND ENJOY THE RIDE")
    else:
        print(f"\n\ttotal amount to be paid {bill}")
        print("\t STAY SAFE AND ENJOY THE RIDE")
else:
    print("better luck next year kiddo")


from MatrixClassOOP import *

f = open("p1data.txt", "r")
x = None
class1 = []
class2 = []
for line in f:
    x = line.split("\t")
    if x[3][-1:] == '\n':
        x[3] = x[3][:-1]
    class1.append([float(x[0]), float(x[1])])
    class2.append([float(x[2]), float(x[3])])

a = matrix(1, 1)

def dataToMatrix(dataSet):
    dataMatrices = []
    for item in dataSet:
        x = matrix(2, 1)
        x.matrix[0][0] = item[0]
        x.matrix[1][0] = item[1]
        dataMatrices.append(x)
    return dataMatrices

class1_matrices = dataToMatrix(class1)
class2_matrices = dataToMatrix(class2)

sum_matrix = matrix(2, 1)

for item in class1_matrices:
    sum_matrix = sum_matrix.addition(item)

sum_matrix.display_Matrix()
mean_matrix = sum_matrix.scalar_multi(1 / 110)
mean_matrix.display_Matrix()


import config
import logging
import asyncio
from aiogram import Bot, Dispatcher, executor, types
from selenium import webdriver
import os

options = webdriver.ChromeOptions()
options.binary_location = os.environ.get('GOOGLE_CHROME_BIN')
options.add_argument('--headless')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--no-sandbox')

br = webdriver.Chrome(executable_path=os.environ.get('CHROMEDRIVER_PATH'), options=options)

logging.basicConfig(level=logging.INFO)

bot = Bot(token=config.TOKEN)
dp = Dispatcher(bot)

users = []

@dp.message_handler(commands=['userlist'])
async def start(message: types.Message):
	mess = ''
	for i in range(len(users)):
		mess = mess + str(i+1) + ' '+ str(users[i][0]) + ' ' + str(users[i][1]) + '\n'
	if mess == '':
		await message.answer('список пуст')
	else:
		await message.answer(mess)

@dp.message_handler(commands=['start'])
async def start(message: types.Message):
	global users, last_check
	sub = 0
	for i in range(len(users)):
		if users[i][0] == message.from_user.id:
			pos_user = i
			sub = 1
			break
	if sub == 0:
		users.append([message.from_user.id,True])
		await message.answer('Старт')
	else:
		users[pos_user][1] = True
		await message.answer('Старт')
	last_check = None

@dp.message_handler(commands=['stop'])
async def stop(message: types.Message):
	global users
	sub = 0
	for i in range(len(users)):
		if users[i][0] == message.from_user.id:
			pos_user = i
			sub = 1
			break
	if sub == 0:
		await message.answer('Вы и так не нажали старт')
		users.append([message.from_user.id,False])
	else:
		users[pos_user][1] = False
		await message.answer('Стоп')

async def parse():
	global last_check
	last_check = None
	while True:
		br.refresh()
		br.get('https://www.epicgames.com/store/ru/free-games')
		html = br.find_element_by_class_name('css-1442lgn-CardGrid-styles__group').text
		if last_check != html:
			last_check = html
			for i in range(len(users)):
				if users[i][1] == True:
					await bot.send_message(users[i][0],html)
		await asyncio.sleep(600)

if __name__ == '__main__':
	loop = asyncio.get_event_loop()
	loop.create_task(parse())
	executor.start_polling(dp, skip_updates=True, loop=loop)


"""
The problem needs you to calculate all the cases that N = sum(Xi).
Let N = 10, and the list 1,2,3,4,5,6,7,8,9, then choose any numbers from the
list to let sum of the numbers equal to 10. How many combination it is?

Use DP, it is similar with the backpack problem. Let dp(i,n) is the count of
combination of choosing number from [1...i] whose sum is n.
dp(i,n) = dp(i-1,n) + dp(i-1,n-i) while i = 1 -> n-1

Initially, dp(1,i) = 0 except dp(1,1) = 1
"""

def answer(n):
    dp = [0] * (n + 1)
    dp[1] = 1
    for i in range(2, n):
        new_dp = [0] * (n + 1)
        for j in range(1, n + 1):
            new_dp[j] = dp[j]
            if j - i == 0:
                new_dp[j] += 1
            if j - i > 0:
                new_dp[j] += dp[j - i]
        dp = new_dp

    return dp[n]

print(answer(7))
print(answer(200))