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

import logging
import importlib
import sys
import time
import os
import signal
import errno

def initlogger(config_basic):
    leveldict = {
        'CRITICAL' : logging.CRITICAL,
        'ERROR'    : logging.ERROR,
        'WARNING'  : logging.WARNING,
        'INFO'     : logging.INFO,
        'DEBUG'    : logging.DEBUG,
        'NOTSET'   : logging.NOTSET}
    defaultlogformat = \
        '%(asctime)s - %(levelname)s - %(name)s : %(message)s'
    # considering it is already in a daemon process which stdin/out/err has
    # been redirected, the info out put will be meaning less
    # however, you can still redirect stderr to a file to record any error
    # logging.info('...setting logger in main_job')
    logfilename = config_basic['filename'] # must specify one
    loglevel    = leveldict[config_basic.get('level','WARNING')]
    logformat    = config_basic.get('format',defaultlogformat)
    # logging.info("filename: {}, level: {}".format(logfilename,loglevel))
    name = config_basic.get('name','default')
    name = 'main_job.' + name
    logger = logging.getLogger(name)
    logger.setLevel(loglevel)
    filehandler = logging.FileHandler(logfilename)
    formatter = logging.Formatter(logformat)
    filehandler.setFormatter(formatter)
    logger.addHandler(filehandler)
    #prevent logger from propagating to parent
    logger.propagate = False
    ##set file handler to root so there will be no extra message in stderr
    #logging.getLogger('root').addHandler(filehandler)
    #set logging level to warning in prevention of too much
    #logging.basicConfig(level = logging.WARNING)
    return logger

#def killwait(interval, maxcnt) -> bool:
#    """kill-wait loop until it die
#delay

# Main job will fork a child to do main work and the sleep.
# When parent is awake but child still hasn't exited,
# it will try to kill the child process.
# Each kill happens between each wait(sec)
# and wait for at most maxwait times.
# Child process still not exit now?
# Parent process exits 1 then.
maxwait = 20
eachwait = 0.25

class main_job:
    def main_clean(self):
        pass

    # the main job to do
    def main_do(self):
        config = self.config
        logger = self.logger
        start_delay   = config['basic']['start_delay']
        repeat_time   = config['basic']['repeat_time']
        restart_delay = config['basic']['restart_delay']
        nodeconfig    = config['spec']
        mod = importlib.import_module(\
            "mod_" + config['basic']['nodetype'])
        handler_run = getattr(mod, "run")
        handler_fix = getattr(mod, "fix")

        logger.info('ready to start')
        #   wait a moment
        time.sleep(start_delay)

        logger.info('now fork for work process')
        #   fork for work process
        cnt = 0
        while cnt < repeat_time or repeat_time < 0:
            cnt = cnt + 1
            # fork for work func
            try:
                pid = os.fork()
                assert pid >= 0
            except Exception as e:
                logger.exception('failed to fork for work func')
                raise e
            # the child process
            if pid == 0:
                exitcode = 0
                logger = logging.getLogger(logger.name + '.' + hex(cnt))
                logger.info('forked for work process')
                try:
                    # don't care return value, if error happened, just raise it
                    handler_run(nodeconfig, logger, cnt)
                except SystemExit as e:
                    # although invode sys.exit is not recommended, but still
                    # ignore Exception raised by sys.exit(0)
                    logger.info('invoked sys.exit or just exit is \
not recommeneded in fun run')
                    if e.code!=0:
                        logger.exception('work fun exit {}'.format(e.code))
                        exitcode = e.code
                    else:
                        pass # invoked exit(0), which mean ok
                except:#except other error
                    logger.exception('a no-exit raise in work fun')
                logger.info('exit work process')
                os._exit(exitcode)# ensure 1-2-4-8...will not happen

            # parent process
            #logger.info('#{}: sleep now'.format(cnt))
            time.sleep(restart_delay)

            pidwait, status = os.waitpid(pid, os.WNOHANG)
            if pidwait != pid:
                #child process still not finished???
                logger.warning('parent awake now, but child havn\'t exited')
                logger.info('try to kill it')
                for waitcnt in range(0, maxwait):
                    if pidwait != 0:
                        break
                    try:
                        os.kill(pid, signal.SIGTERM)
                    except Exception as e:
                        if type(e) == OSError and e.errno == errno.ESRCH:
                            break
                    time.sleep(eachwait)
                pidwait, status = os.waitpid(pid, os.WNOHANG)
            if pidwait == pid:
                exitcode = int(status >> 8)
                if exitcode != 0:
                    logger.warning('work process exited {}'.format(exitcode))
                else:
                    logger.info('work process exited 0')
            else:
                logging.error('failed to terminate work process')
                sys.exit(1)
        # end of while

        logger.info('exit daemon process now')
        # this is a child process, thus just os._exit it
        os._exit(0)

    def start(self):
        self.main_clean()
        self.main_do()
    def stop(self):
        self.main_clean()

    def __init__(self, config):
        self.config = config
        self.logger = initlogger(config['basic'])

    def __enter__(self):
        self.start()

    def __exit__(self,exc_type, exc_val, exc_tb):
        self.stop()

#import sys
#import os
#import os.path
#if __name__ == '__main__':
#    modpath = os.path.abspath(sys.argv[0])
#    modpath = os.path.dirname(modpath)
#    modpath = os.path.join(modpath, "./mods")
#    sys.path.append(modpath)
#    nodeconfig = {"nodetype": "test",
#                  "start_delay": 2,
#                  "restart_delay": 2,
#                  "repeat_time": 5,
#                  "logpath": "./__pycache__/",
#                  "logformat": "%(asctime)s - %(levelname)s - %(name)s : %(message)s",
#                  "pidfile": "/temp/project_sperm_test0.pid",
#                  "dpidfile": "/temp/project_sperm_test0d.pid",
#                  "stdout": "/dev/null",
#                  "stdin": "/dev/null",
#                  "stderr": "/dev/null",
#\
#                  "exitcode": 1, "fixexitcode": 0}
#    nodeconfig['nodename'] = 'test0'
#    daemon_start(nodeconfig)
#
#   "test0":
#   {
#       "nodetype":"test",
#       "start_delay":5,
#       "restart_delay":5,
#       "repeat_time":5,
#       "logpath":"/var/log/project_sperm/",
#       "logformat":"%(asctime)s - %(levelname)s - %(name)s : %(message)s",
#       "pidfile":"/temp/project_sperm_test0.pid",
#       "dpidfile":"/temp/project_sperm_test0d.pid",
#       "stdout":"/dev/null",
#       "stdin":"/dev/null",
#       "stderr":"/dev/null",
#
#       "exitcode":0
#   }
#
#
#
#
#            # fork for fix func
#            try:
#                pid = os.fork()
#            except:
#                logger.exception('failed to fork to fix problems')
#            if pid == 0:
#                # child
#                handler_fix(nodeconfig, logger, exitcode)
#                logger.warning('fix func return')
#                exit(0)
#            # parent
#            pid, status = os.wait()
#            exitcode = int(status >> 8)
#            logger.info('fix process exited with {}'.format(exitcode))
#            if exitcode != 0:
#                # failed to fix problem
#                logger.error('failed to fix problems')
#                break
#            else:
#                logger.info('successfully fixed problems')
#


from task import Task
import tensorflow as tf
from keras.layers import Input, Conv2D, Dense, GRU, LSTM, Activation, Flatten, ZeroPadding2D
from keras.layers.normalization import BatchNormalization
from keras.layers.core import Dropout, Reshape
from keras.models import Model, Sequential, load_model
from keras.layers.pooling import GlobalAveragePooling2D, MaxPool2D
from keras.optimizers import Adam, SGD
from keras.callbacks import TensorBoard

import time
from monitor import Monitor
import matplotlib.pyplot as plt
import config as cfg
import argparse

def describe(model):
    description = 'Model layers / shapes / parameters:\n'
    total_params = 0

    for layer in model.layers:
        layer_params = layer.count_params()
        description += '- {}'.format(layer.name).ljust(20)
        description += '{}'.format(layer.input_shape).ljust(20)
        description += '{0:,}'.format(layer_params).rjust(12)
        description += '\n'
        total_params += layer_params

    description += 'Total:'.ljust(30)
    description += '{0:,}'.format(total_params).rjust(22)

    print(description)

def convolution_block(x, filters):
    x = ZeroPadding2D()(x)
    x = Conv2D(filters, (3, 3), kernel_initializer='he_uniform')(x)
    x = BatchNormalization(axis=1)(x)
    x = Activation('relu')(x)
    x = Dropout(0.5)(x)
    x = ZeroPadding2D()(x)
    x = Conv2D(filters, (3, 3), kernel_initializer='he_uniform')(x)
    x = BatchNormalization(axis=1)(x)
    x = Activation('relu')(x)
    x = Dropout(0.5)(x)
    return x

def train(args):
    # arg parameters
    batch_size = args.batch_size
    epochs = args.epochs
    patience = args.patience

    task = Task(64, args)
    task.load_dataset()
    task.prepare_data()

    # model = Sequential()

    input = Input(shape=(64, 334, 1))
    x = convolution_block(input, 32)
    # x = convolution_block(x, 64)
    # x = convolution_block(x, 128)
    # x = convolution_block(x, 128)
    x = GlobalAveragePooling2D()(x)
    x = Dense(60, activation='relu')(x)
    x = BatchNormalization(axis=1)(x)
    x = Activation('relu')(x)
    x = Dense(10, activation='softmax')(x)
    model = Model(input=[input], outputs=[x])

    # model.add(GlobalAveragePooling2D())

    # model.add(Dense(512, activation='relu', kernel_initializer='he_uniform', ))
    # model.add(Dropout(0.5))
    # model.add(Dense(10, activation='softmax', kernel_initializer='he_uniform'))
    #
    # model.add(Dropout(0.5))

    # reshape (1,500,96)
    # model.add(Reshape(target_shape=(286, 32)))
    #
    # # three layers of GRU
    # model.add(GRU(32, dropout=0.2, bias_initializer='ones', return_sequences=True, activation='tanh'))
    # model.add(GRU(32, dropout=0.2, kernel_initializer='he_uniform', bias_initializer='ones', activation='tanh'))
    #
    # # FC
    # model.add(Dense(16))
    # model.add(BatchNormalization(axis=1))
    # model.add(Dropout(0.2))
    # model.add(Dense(10, activation='softmax', kernel_initializer='he_uniform'))

    model.compile(loss='categorical_crossentropy', optimizer=Adam(),
                  metrics=['accuracy'])
    describe(model)

    steps_per_epoch = len(task.train[0]) // batch_size

    tensorBoard = TensorBoard()

    current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

    checkpoint_path = "/data/check_points/2018_task1_cp/" + str(current_time) + "_cp-{epoch:04d}.ckpt"
    # checkpoint_dir = os.path.dirname(checkpoint_path)

    cp_callback = tf.keras.callbacks.ModelCheckpoint(
        checkpoint_path, verbose=1, save_weights_only=True,
        # Save weights, every 5-epochs.
        period=10)
    estop = tf.keras.callbacks.EarlyStopping(patience=patience)

    #   Keras的生成器要求是死循环，也就是说永远都有next元素可以抛出。在适当位置添加while True
    history = model.fit_generator(generator=task.iterbatches(batch_size, task.train, True),
                                  steps_per_epoch=steps_per_epoch, epochs=epochs,
                                  callbacks=[Monitor(1, model, task, args)],
                                  validation_data=task.iterbatches(batch_size, task.validation, False),
                                  validation_steps=len(task.validation[0]) // batch_size,
                                  )

    # model.save(os.path.join(MODEL_PATH, 'crnn_model_{}.h5'.format(time.time())))

    # score = model.evaluate_generator(task.iterbatches(batch_size, task.test, False),
    #                                  steps=len(task.test) // batch_size)
    # print('acc: {}'.format(score[1]))
    # print('loss: {}'.format(score[0]))
    # plot(history)
    # finish_instance()

def finish_instance():
    import os
    os.system('sh /data/stop_instance.sh')

def plot(history):
    plt.figure()
    plt.subplot(2, 1, 1)
    plt.plot(history.history['acc'], color="blue", linewidth=1.0)
    plt.plot(history.history['val_acc'], color="blue", linewidth=1.0, linestyle="-")
    plt.title('model acc')
    plt.xlabel('epoch')
    plt.ylabel('acc')
    plt.legend(['train', 'test'], loc='upper left')
    plt.subplot(2, 1, 2)
    plt.plot(history.history['loss'], color="red", linewidth=1.0)
    plt.plot(history.history['val_loss'], color="red", linewidth=1.0, linestyle="-")
    plt.title('val_loss')
    plt.xlabel('epoch')
    plt.ylabel('loss')
    plt.legend(['train', 'test'], loc='upper left')
    plt.show()
    plt.savefig('/data/dl-result-image/2018_task_1_result')

if __name__ == '__main__':
    arg = argparse.ArgumentParser(description='')
    arg.add_argument('--batch_size', type=int, default=32)
    arg.add_argument('--epochs', type=int, default=40)
    arg.add_argument('--patience', type=int, default=10)
    arg.add_argument('--model_path', type=str, default=cfg.MODEL_PATH)
    arg.add_argument('--feature_path', type=str, required=True)
    # arg.add_argument('--plot_image_path', type=str)

    arg = arg.parse_args()

    train(arg)


# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np

#Paths
#KalaForosh = r"C:\Users\a.alizadeh\Desktop\علیزاده عادل\DataCenter\98\Kala-Forosh98.xlsx"
#KalaAnbar = r"C:\Users\a.alizadeh\Desktop\علیزاده عادل\DataCenter\98\Kala-Anbar98.xlsx"
#GoalsCategory = r"C:\Users\a.alizadeh\Desktop\علیزاده عادل\LookupTables\GoalsCategory.xlsx"

def raw1(KalaForosh,KalaAnbar,GoalsCategory) :
    print("***raw1 executed***")
    #Product ProductCategories
    df0 = pd.read_excel(KalaForosh,usecols = ["تولید کننده","نام تجاری","گروه کالا","کد کالا","نام کالا"])
    print("***raw1 df0 obtaiend***")
    df1 = pd.read_excel(GoalsCategory)
    print("***raw1 df1 obtaiend***")
    df2 = pd.read_excel(KalaAnbar,usecols = ["کد کالا","تعداد در کارتن"])
    print("***raw1 df2 obtaiend***")
    df3 = pd.merge(df0,df1,how = "left", on = "کد کالا")
    df3 = pd.merge(df3,df2,how = "left", on = "کد کالا")
    ProductCategories = df3[["گروه کالا","نام تجاری","تولید کننده","GoalsCategory"]]
    ProductCategories.drop_duplicates(subset = None,keep = "first",inplace = True)
    Product = df3[["کد کالا","نام کالا","GoalsCategory","تعداد در کارتن"]]
    print("***raw1 finished***")
    return Product,ProductCategories


import asyncio
import json
from django.http import JsonResponse
from rest_framework import generics
from Ptt_Crawlers.ptt_search import Base_Crawler

# Create your views here.

def search_result(request):
    json_data = json.loads(request.body.decode('utf-8'))
    q = json_data.get('q', '')
    if q:
        query_string = q.replace(' ', '+')
        crawler = Base_Crawler(query_str=query_string)
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        loop.run_until_complete(crawler.parse())
        loop.close()

        items = crawler.items
        return JsonResponse(items, safe=False,  json_dumps_params={'ensure_ascii': False})


from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.shortcuts import render, redirect
from django.views.generic import TemplateView

from .forms import ContactForm
from .models import Contact

class Contactview(TemplateView):
    """ View for contact us
    """
    template_name = 'pages/contact.html'

    def get(self, *args, **kwargs):
        form = ContactForm()
        return render(self.request, self.template_name, {'form': form})

    def post(self, *args, **kwargs):
        form = ContactForm(self.request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            name = form.cleaned_data['name']
            subject_title = form.cleaned_data['subject']

            subject, from_email, to = subject_title, settings.EMAIL_HOST_USER, email
            text_content = 'Thank you for reaching us.'
            html_content = '
Hello, thank you for reaching swiftkind
'
            msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
            msg.attach_alternative(html_content, "text/html")
            msg.send()
            form.save()
            return redirect('contact')
        return render(self.request, self.template_name, {'form': form})


#%% 0. Housekeeping

# =============================================================================
# 0.1 Import packages
# =============================================================================

import pandas as pd
import numpy as np
from datetime import datetime

# =============================================================================
# 0.2 Import data
# =============================================================================

train = pd.read_csv('data/train.csv', low_memory=False)
store = pd.read_csv('data/store.csv', low_memory=False)

#%% 1. Merging store to train data

# =============================================================================
# 1.1 Since data has to has the same size as 'train', a container is created
# =============================================================================

# Creating dataframe
expanded_store = train.loc[:,['Date','Store']]

# =============================================================================
# 1.2 Merging variables which do not have to be changed
# =============================================================================

# Variables which can be merged right away
easy = store.loc[:,['Store','StoreType','Assortment','CompetitionDistance']]

# Variables which can be simply merged
expanded_store = pd.merge(expanded_store, easy, on=['Store'])

# =============================================================================
# 1.3 Creating a dummy variable since when competition is open for every store
# =============================================================================

# Dataset of the variables which have to be transformed
competition = store.loc[:,['Store',
                           'CompetitionOpenSinceMonth','CompetitionOpenSinceYear']]

# For easier looping
competition.set_index('Store', inplace=True)

# Finding stores which have competition openend
open_comp = competition.any(axis=1)

# Stores with competition
open_stores = competition.loc[open_comp].index.unique()

# Generating Date when opened
for store_id in open_stores:
    year = competition.loc[store_id,'CompetitionOpenSinceYear'].astype(int)
    month = competition.loc[store_id,'CompetitionOpenSinceMonth'].astype(int)
    competition.loc[store_id,'CompetitionDate'] = datetime(year,month,1)

# Creating a dummy variable for whether competition openend for each store
expanded_store.loc[:,'CompetitionOpened'] = 0

for store_id in open_stores:

    # Getting the date when competition openend
    date = competition.loc[store_id,'CompetitionDate']
    date_str= date.strftime("%Y-%m-%d")

    store_number = expanded_store.loc[:,'Store'] == store_id

    maximum_date = expanded_store.loc[store_number,'Date'].max()

    # Whether it falls in time frame
    competition_existing = (expanded_store.loc[:,'Date'].between(date_str,maximum_date)) &  (expanded_store.loc[:,'Store'] == store_id)

    # Indicating whether competition is around
    expanded_store.loc[competition_existing, 'CompetitionOpened'] = 1

#%% Join


#!/home/pi/.virtualenvs/blinka/bin/python
"""
Starwars banner

Usage:
Execute in a terminal with command: ./starwars.py

Notes:
File starwars.py must have eXecute mode
   $ chmod +x starwars.py
It doesn't work at Windesheim (websocket port 23 closed)

2020-11-03 PP updated for Raspberry PI
2019 PP smart devices - sample code for websockets example
"""
import socket

# get address information of site
url = 'towel.blinkenlights.nl'
addr_info = socket.getaddrinfo(url, 23)

# get IP and port
# 2020-1103 PP changed for Raspberry PI
# addr = addr_info[0][-1]
addr = addr_info[5][4]

# connect to it via socket
s = socket.socket()
s.connect(addr)

# print content/animation in console
# use Ctrl-C to interrupt
while True:
    data = s.recv(500)
    print(str(data, 'utf8'), end='')


aluno = list()
dados = dict()

while True:
    dados["nome"] = str(input("Nome: "))
    dados["media"] = float(input("Média: "))
    if dados["media"] < 5:
        dados["sit"] = "Reprovado"
    elif 7 > dados["media"] >= 5:
        dados["sit"] = "Recuperação"
    else:
        dados["sit"] = "Aprovado"
    aluno.append(dados.copy())
    dados.clear()

    n = str(input("Continuar [S/N]? "))
    if n in "Nn":
        break

print()
print(f"{' BOLETIM ':=^30}")
print(f"{'NOME':<10}{'MÉDIA':<5}{'SITUAÇÃO':>15}")
print("-" * 30)
for i in aluno:
    print(f"""{i['nome']:<10}{f"{i['media']:.1f}":<5}{i['sit']:>15}""")
print("-" * 30)
print()


###.1 재귀 알고리즘의 응용

# 재귀적 알고리즘이 사람의 생각을 코드로 옮기기에 직관적인 측면이 있지만, 항상 반복적인 방법에 비해 효율적인 측면에서 비효율적일 수 있다.

# 재귀함수란 하나의 함수에서 자신을 다시 호출하여 작업을 수행하는 함수를 말한다.

##.1 조합의 표현

from math import factorial as f

def combi(n,m):

    return f(n)/ (f(m)*f(n-m))

print(combi(5,2))

#. m개에서 n개를 택하는 조합의 개념은 특정한 한개를 포함하여 n개를 택하는 조합과 특정한 한개를 포함하지 않고 n개를 택하는 두가지의 방법으로 나누어 생각해볼 수 있다.

def combi(n,m):

    if n == m:

        return 1

    elif m == 0:

        return 1

    else:

        return combi(n-1,m) + combi(n-1,m-1)

import time

def rec(n):

    if n <= 1:

        return n

    else:

        return rec(n -1) + rec(n - 2)

def iter(n):

    if n <= 1:

        return n

    else:

        i = 2
        t0 = 0
        t1 = 1

        while i <= n:

            t0, t1 = t1, t0+t1

            i += 1

        return t1

while True:

    nbr = int(input("Enter a number: "))
    if nbr == -1:

        break

    ts = time.time()
    fibo = iter(nbr)
    ts = time.time() - ts
    print("Iterative version: %d (%.3f)" %(fibo, ts))

    ts = time.time()
    fibo = rec(nbr)
    ts = time.time() - ts
    print("Recursive version: %d (%.3f)" %(fibo, ts))

# 피보나치 수열의 재귀함수 버전과 반복버전의 시간차이가 얼마나 발생하는지를 확인할 수 있는 코드이다.
# 여기에서 확인할 수 있는 것처럼 재귀적인 방법에는 시간 성능적인 한계가 존재할 수 있다.


import pytest
pytestmark = [pytest.mark.setone, pytest.mark.working]

@pytest.fixture
def biosample_1(biosample_cc_wo_diff, GM12878_biosource, award, lab):
    return{
        "schema_version": '1',
        "award": award['@id'],
        "lab": lab['@id'],
        "cell_culture_details": biosample_cc_wo_diff['@id'],
        "biosource": [GM12878_biosource['@id']]
    }

def test_biosample_1_2(
        app, biosample_1, biosample_cc_wo_diff):
    migrator = app.registry['upgrader']
    value = migrator.upgrade('biosample', biosample_1, current_version='1', target_version='2')
    assert value['schema_version'] == '2'
    assert value['cell_culture_details'][0] == biosample_cc_wo_diff['@id']


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

import EllipticCurves as ec
from random import randint
from utils import prime_relative, is_divisor, has_modinv
from fractions import gcd

def lenstra(n):
    """
    Implementación del algoritmo de Lenstra para encontrar los factores
    primos de un número n de la forma n = p*q. Se asume que la proposición
    anterior es cierta, es decir, que en efecto n = p*q, regresando ambos
    factores de n.
    """
    a, x, y = randint(1,n-1), randint(1,n-1), randint(1,n-1)
    b = (pow(y,2) - pow(x,3) - (a * x)) % n
    E = ec.Curve(a, b, n)
    while not prime_relative(E.determinant(), n):
    	a, x, y = randint(1,n-1), randint(1,n-1), randint(1,n-1)
    	b = (pow(y,2) - pow(x,3) - (a * x)) % n
    	E = ec.Curve(a, b, n)
    p = (x, y)
    while not E.is_on_curve(p):
    	p = (randint(1,n), randint(1,n))
    lamb = calculate_lambda(p, p)
    point_aux = p
    while has_modinv(lamb, n):
    	point_aux = ec.add_points(p, point_aux, E)
    	lamb = calculate_lambda(p, point_aux)
    p = gcd(lamb, n)
    q = n/p
    if p==1 or q==1:
    	return lenstra(n)
    return (p, q)

def calculate_lambda(p, q):
	if p==q:
		return 2*p[1]
	return p[0]-q[0]


#!/usr/bin/env python3
# -*- encoding: utf-8; py-indent-offset: 4 -*-

# (c) Andreas Doehler <andreas.doehler@bechtle.com/andreas.doehler@gmail.com>

# This is free software;  you can redistribute it and/or modify it
# under the  terms of the  GNU General Public License  as published by
# the Free Software Foundation in version 2.  check_mk is  distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY;  with-
# out even the implied warranty of  MERCHANTABILITY  or  FITNESS FOR A
# PARTICULAR PURPOSE. See the  GNU General Public License for more de-
# ails.  You should have  received  a copy of the  GNU  General Public
# License along with GNU Make; see the file  COPYING.  If  not,  write
# to the Free Software Foundation, Inc., 51 Franklin St,  Fifth Floor,
# Boston, MA 02110-1301 USA.

# Example Output:
#
#
from cmk.base.plugins.agent_based.agent_based_api.v1.type_defs import (
    CheckResult,
    DiscoveryResult,
)

from cmk.base.plugins.agent_based.agent_based_api.v1 import (
    register,
    Result,
    State,
    Service,
)

from .utils.redfish import parse_redfish_multiple, redfish_health_state

register.agent_section(
    name="redfish_drives",
    parse_function=parse_redfish_multiple,
)

def discovery_redfish_drives(section) -> DiscoveryResult:
    for key in section.keys():
        item = section[key]["Name"]
        yield Service(item=item)

def check_redfish_drives(item: str, section) -> CheckResult:
    data = None
    for key in section.keys():
        if item == section[key]["Name"]:
            data = section.get(key, None)
    if data is None:
        return

    disc_msg = "Size: %0.0fGB, Speed %s Gbs" % (
        data.get("CapacityBytes", 0) / 1024 / 1024 / 1024,
        data.get("CapableSpeedGbs", 0),
    )

    if data.get("MediaType") == "SSD":
        if data.get("PredictedMediaLifeLeftPercent"):
            disc_msg = disc_msg + ", Media Life Left: %d%%" % (
                int(data.get("PredictedMediaLifeLeftPercent", 0))
            )
        else:
            disc_msg = disc_msg + ", no SSD Media information available"

    yield Result(state=State(0), summary=disc_msg)

    dev_state, dev_msg = redfish_health_state(data["Status"])
    yield Result(state=State(dev_state), notice=dev_msg)

register.check_plugin(
    name="redfish_drives",
    service_name="Drive %s",
    sections=["redfish_drives"],
    discovery_function=discovery_redfish_drives,
    check_function=check_redfish_drives,
)


import requests
from bs4 import BeautifulSoup
from pymongo import MongoClient           # pymongo를 임포트 하기(패키지 인스톨 먼저 해야겠죠?)
client = MongoClient('localhost', 27017)  # mongoDB는 27017 포트로 돌아갑니다.
db = client.dbsparta

headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
data = requests.get('https://www.genie.co.kr/chart/top200?ditc=D&rtm=N&ymd=20190715',headers=headers)

soup = BeautifulSoup(data.text, 'html.parser')

tr_result =soup.select('#body-content > div.newest-list > div > table > tbody > tr')

# 순위
#body-content > div.newest-list > div > table > tbody > tr:nth-child(1) > td.number
# 곡제목
#body-content > div.newest-list > div > table > tbody > tr:nth-child(1) > td.info > a.title.ellipsis
# 가수
#body-content > div.newest-list > div > table > tbody > tr:nth-child(1) > td.info > a.artist.ellipsis
rank = 0
docs = []
for song in tr_result:
    rank += 1
    title = song.select_one('td.info > a.title.ellipsis')
    title_song = title.text.strip()
    artist = song.select_one('td.info > a.artist.ellipsis')
    artist_song = artist.text.strip()
    doc = {'rank':rank, 'title':title_song, 'artist':artist_song}
    docs.append(doc)

db.song_genie.insert_many(docs)


#!/usr/bin/python

# import guacamole libraries
import avango
import avango.gua

class Arm:

    ### class variables ###

    # Number of Hinge instances that have already been created.
    number_of_instances = 0

    # constructor
    def __init__(self,
        PARENT_NODE = None,
        DIAMETER = 0.1, # in meter
        LENGTH = 0.1, # in meter
        ROT_OFFSET_MAT = avango.gua.make_identity_mat(), # the rotation offset relative to the parent coordinate system
        ):

        ## get unique id for this instance
        self.id = Arm.number_of_instances
        Arm.number_of_instances += 1

        ### resources ###

        self.arm_start_node = avango.gua.nodes.TransformNode(Name = "arm{0}_start_node".format(str(self.id)))
        self.arm_start_node.Transform.value = ROT_OFFSET_MAT
        PARENT_NODE.Children.value.append(self.arm_start_node)

        self.arm_end_node = avango.gua.nodes.TransformNode(Name = "arm{0}_end_node".format(str(self.id)))
        self.arm_end_node.Transform.value = avango.gua.make_trans_mat(0.0, LENGTH, 0.0)
        self.arm_start_node.Children.value.append(self.arm_end_node)

        _loader = avango.gua.nodes.TriMeshLoader() # get trimesh loader to load external tri-meshes

        self.arm_geometry = _loader.create_geometry_from_file("arm{0}_geometry".format(str(self.id)), "data/objects/cylinder.obj", avango.gua.LoaderFlags.DEFAULTS)
        self.arm_geometry.Transform.value = \
            avango.gua.make_trans_mat(0.0, LENGTH * 0.5, 0.0) * \
            avango.gua.make_scale_mat(DIAMETER, LENGTH, DIAMETER)
        self.arm_geometry.Material.value.set_uniform("Color", avango.gua.Vec4(0.45,0.45,0.45,1.0))
        self.arm_start_node.Children.value.append(self.arm_geometry)


import numpy as np

# Abstract model object
class Model(object):

    def __init__(self, nfeatures, lmbda):
        self.num_input_features = nfeatures
        self.lmbda = lmbda

    # Fitting the model
    def fit(self, *, X, y):
        """ Fit.

        Args:
            X: A compressed sparse row matrix of floats with shape
                [num_examples, num_features].
            y: A dense array of ints with shape [num_examples].
        """
        raise NotImplementedError()

    def predict(self, X):
        """ Predict.

        Args:
            X: A compressed sparse row matrix of floats with shape
                [num_examples, num_features].

        Returns:
            A dense array of ints with shape [num_examples].
        """
        #raise NotImplementedError()

    # Fixes some feature disparities between datasets
    # Call this before performing inference to
    # make sure X features match the weights
    def _fix_test_feats(self, X):

        num_examples, num_input_features = X.shape
        if num_input_features < self.num_input_features:
            X = X.copy()
            X._shape = (num_examples, self.num_input_features)
        if num_input_features > self.num_input_features:
            X = X[:, :self.num_input_features]
        return X

class Pegasos(Model):

    def __init__(self, *, nfeatures, lmbda):
        """
        Args:
            nfeatures: size of feature space
            lmbda: regularizer term (lambda)

        Sets:
            W: weight vector
            t: current iteration
        """
        super().__init__(nfeatures=nfeatures, lmbda=lmbda)
        self.W = np.zeros((nfeatures, 1))
        self.t = 1

    def fit(self, *, X, y):
        """ Fit the model.

        Args:
            X: A compressed sparse row matrix of floats with shape
                [num_examples, num_features].
            y: A dense array of ints with shape [num_examples].
        """

        # Compute y_hat's by using the predict function and
        # convert x from sparse row matrix to numpy array
        y_hat = self.predict(X)
        X = X.toarray()

        for i in range(0, len(X)):

            # Convert class labels
            if y[i] == 0:
                y[i] = -1
            elif y[i] == 1:
                y[i] = 1

            # Obtain values for indicator function,
            # weight coefficient, and learning rate
            dot_prod = np.dot(self.W.T, X[i].T)
            if y[i] * dot_prod < 1:
                indicator = 1
            else:
                indicator = 0

            coeff_w_t = (1.0 - 1.0 / self.t)
            lr_t = 1.0 / (self.lmbda * self.t)

            # Weight update step
            update = coeff_w_t * self.W.T + lr_t * indicator * y[i] * X[i]
            update = update.T
            self.W += update

            # Increment time step
            self.t += 1

            # Gradient projection after each time step t to prevent overfitting:
            # Further regularize learned parameters by limiting the set of
            # candidate solutions to a ball of radius 1 / sqrt(λ)
            self.W = min(1, (1/ (self.lmbda**1/2))/np.linalg.norm(self.W) ) * self.W

    def predict(self, X):
        """ Predict.

        Args:
            X: A compressed sparse row matrix of floats with shape
                [num_examples, num_features].

        Returns:
            A dense array of ints with shape [num_examples].
        """

        # Ensure x features match the weights, then
        # convert to array
        X = self._fix_test_feats(X)
        X = X.toarray()
        y_hat = []

        # Make predictions of y_hat
        # if X[i] * W >= 0, then y_hat = 1
        for i in range(0, len(X)):
            m = np.dot(X[i], self.W)
            margin = np.asscalar(m)

            if margin >= 0:
                y_hat.append(1)
            else:
                y_hat.append(0)
        return y_hat


from sys import pycache_prefix
import tensorflow as tf
import pydub
import wave
import scipy as sp
import matplotlib.pyplot as plt

mmodel=tf.keras.models.load_model('music_emotion.h5')

mdic={0:"Happy", 1:"Sad", 2:"Neutral", 3:"Happy"}
def mpredict(filepath:str):
    if ".mp3" in filepath:
        pydub.AudioSegment.from_mp3(filepath).export(filepath.replace('32kps/', 'wav/').replace('.mp3', '.wav'), format="wav")
        print(filepath)
    if ".wav" in filepath:
        wo = wave.open(filepath, 'rb' )
        chunk = 65536
        data = sp.fromstring(wo.readframes(chunk), sp.int16)
        srate = wo.getframerate()
        nFFT = 1024
        window = sp.hamming(nFFT)

        fig, ax = plt.subplots(1)
        fig.subplots_adjust(left=0,right=1,bottom=0,top=1)
        ax.set_axis_off()
        Pxx, freq, bins, im = ax.specgram(data,
                                        NFFT=nFFT,
                                        Fs=srate,
                                        noverlap=512,
                                        window=window)
        plt.savefig(filepath.replace('wav', 'png'))
        plt.close(fig)


# -*- coding: UTF-8 -*-
from il.Congestion_controller.congestionController import CongestionController
# import matplotlib.pyplot as plt
import numpy as np
import datetime
# from main_multi import stop_time
stop_time = 10000000

S_LEN = 4
INPUT_LEN = 15
ROW_DATA_LEN = INPUT_LEN * (S_LEN * 2 + 1)

FLOOR_BITRATE_M = 0.01
CEIL_BITRATE_M = 2.5

def rectificate_bitrate(bitrate):
        """
        矫正速率
        :param bitrate:
        :return:
        """
        bitrate = bitrate // 1e5 * 0.1
        bitrate = min(CEIL_BITRATE_M, bitrate)
        bitrate = max(FLOOR_BITRATE_M, bitrate)
        return bitrate

class DaggerMasterController(CongestionController):
    """
    收集数据
    """

    def __init__(self):
        self.start_bitrate_bps = 1e6
        self.rate, self.lbrates, self.dbrates, self.delay, self.loss, self.delay_diff, self.bandwidth = \
            [], [], [], [], [], [], []
        self.ts_delta, self.t_delta, self.trendline, self.mt, self.threashold = [], [], [], [], []
        self.time = []
        self.inuse = []
        self.rate.append(self.start_bitrate_bps)

        # mz
        # 获取当前时间
        self.start_time = datetime.datetime.now()

        # 初始化
        # 保存路径
        self.save_path = './data_ver/D.npy'

        # 初始配置
        self.start_bitrate = 0.7  # 初始速率
        # self.codec_bitrate = 0  # 初始编码速率
        self.send_time_last_state = 0  # 上一次发送时间的状态
        self.arrival_time_last_state = 0  # 达到发送时间的状态
        self.start_arrival_time = 0  # 开始到达的时间

        self.count = 0  # 计数
        # 三输入的数组维度为  1 X (INPUT_LEN * (S_LEN * 2 + 1) + 1)
        raw = INPUT_LEN * (S_LEN * 2 + 1) + 1
        self.save_data_one = np.zeros((1, raw))  # len+1  初始化 save_data_one 数组维度为

        # 数组维度为 (stop_time // 1000) X (INPUT_LEN * (S_LEN))
        self.save_data = np.zeros((stop_time // 1000, raw))  # len+1

        # 丢包窗口 (INPUT_LEN X SLEN)
        self.save_loss_windows = np.zeros((INPUT_LEN, S_LEN))
        # 吞吐量窗口   INPUT_LEN X 1
        self.save_throughput_windows = np.zeros((INPUT_LEN, 1))
        # 延迟窗口      INPUT_LEN X S_LEN
        self.save_delay_interval_windows = np.zeros((INPUT_LEN, S_LEN))

        self.start_time = 0
        self.bitrate_lable = self.start_bitrate
        self.loss_windows = []
        self.throughput_windows = []
        self.delay_interval_windows = []

    def estimate(self, feedback):
        if not feedback:
            return self.start_bitrate_bps
        target_bitrate = feedback.bandwidth[-1]

        self.time.append(feedback.arrival_time_ms[-1] / 1000.0)
        self.rate.append(target_bitrate)
        self.loss.extend(feedback.loss)
        self.delay.extend([feedback.arrival_time_ms[i] - feedback.send_time_ms[i]
                           for i in range(len(feedback.arrival_time_ms))])
        self.bandwidth.append(feedback.average_bandwidth)
        self.save_master_data(feedback)
        return target_bitrate

    def compute_throught(self, feedbackPacket):
        """
        计算吞吐量
        :param feedbackPacket:
        :return:
        """
        arrival_time = feedbackPacket.arrival_time_ms
        payload_size = feedbackPacket.payload_size
        # 计算吞吐量
        intervals = arrival_time[-1] - self.start_arrival_time
        throughput = np.sum(payload_size) / intervals / 1000.0
        self.start_arrival_time = arrival_time[-1]
        return throughput

    def compute_delay_interval(self, feedbackPacket):
        """
        计算时延
        :param feedbackPacket:
        :return:
        """
        send_time = feedbackPacket.send_time_ms
        arrival_time = feedbackPacket.arrival_time_ms

        # 需要计算时延，这些是输出
        delay_send = []
        delay_arrival = []
        delay_interval = []

        # 初始时间间隔
        # delay_interval.append(
        #     (send_time[0] - self.send_time_last_state) - (arrival_time[0] - self.arrival_time_last_state))
        delay_interval.append((arrival_time[0] - self.arrival_time_last_state) -(send_time[0] -
                                                                                self.send_time_last_state))

        # 计算时间间隔
        for i in range(1, S_LEN):
            delay_send.append(send_time[i] - send_time[i - 1])
            delay_arrival.append(arrival_time[i] - arrival_time[i - 1])
            delay_interval.append(delay_arrival[i - 1] - delay_send[i - 1])  # 2

        self.send_time_last_state = send_time[-1]
        self.arrival_time_last_state = arrival_time[-1]
        # print(self.send_time_last_state)
        # print(self.arrival_time_last_state)
        return delay_interval

    def save_master_data(self, feedbackPacket):
        """
        保存数据
        :param feedbackPacket:
        :return:
        """
        self.bitrate_lable = feedbackPacket.average_bandwidth // 1e6  # M

        loss = feedbackPacket.loss[:S_LEN]  # 1
        now_time = (feedbackPacket.arrival_time_ms[-1] - 4) // 1000

        # 如果发送时间是 0 ，那么初始化这些列表
        if self.send_time_last_state == 0:
            self.start_time = now_time

        delay_interval = self.compute_delay_interval(feedbackPacket)
        throughput = self.compute_throught(feedbackPacket)

        # 保存
        if now_time != self.start_time:
            np_loss_windows = np.array(self.loss_windows)
            np_throughput_windows = np.array(self.throughput_windows)
            np_throughput_windows = np_throughput_windows[:, np.newaxis]
            np_delay_interval_windows = np.array(self.delay_interval_windows)

            #  如果累计的值达到 INPUT_LEN，开始
            #  shape[0] 存放了数组的一维大小
            if np_delay_interval_windows.shape[0] >= INPUT_LEN:
                self.save_delay_interval_windows = np_delay_interval_windows[-INPUT_LEN:, :]
                self.save_throughput_windows = np_throughput_windows[-INPUT_LEN:, :]
                self.save_loss_windows = np_loss_windows[-INPUT_LEN:, :]
            else:
                # row_stack() 列数不变，合并
                self.save_loss_windows = np.row_stack(
                    (self.save_loss_windows[-(INPUT_LEN - np_delay_interval_windows.shape[0]):, :], np_loss_windows))
                self.save_throughput_windows = np.row_stack((self.save_throughput_windows[
                                                             -(INPUT_LEN - np_delay_interval_windows.shape[0]):, :],
                                                             np_throughput_windows))
                self.save_delay_interval_windows = np.row_stack((self.save_delay_interval_windows[
                                                                 -(INPUT_LEN - np_delay_interval_windows.shape[0]):, :],
                                                                 np_delay_interval_windows))

            # print(self.bitrate_lable)
            # 保存一行
            self.save_one_row()

            self.start_time = now_time
            self.loss_windows = []
            self.throughput_windows = []
            self.delay_interval_windows = []

            self.count = self.count + 1

            # 每过一段时间缓存或者是快到达临界值的时候
            if now_time % 3600 == 0 or stop_time // 1000 - now_time < 5:
                print(stop_time // 1000 - now_time)
                print(self.save_data[0:self.count, :].shape)
                np.save(self.save_path, self.save_data[0:self.count, :])

        self.loss_windows.append(loss)  # 1  append
        self.delay_interval_windows.append(delay_interval)  # 2 append
        self.throughput_windows.append(throughput)  # 3 append

    def save_one_row(self):
        """
        保存一行数据，[loss, delay, throughput, bitrate_label]
        :return:
        """
        # reshape(-1) 将二维数组展开成一维数组
        self.save_data_one[0, 0:INPUT_LEN * S_LEN] = self.save_loss_windows.reshape(-1)
        self.save_data_one[0, INPUT_LEN * S_LEN:INPUT_LEN * S_LEN * 2] = self.save_delay_interval_windows.reshape(
            -1)
        self.save_data_one[0,
        INPUT_LEN * S_LEN * 2:INPUT_LEN * (S_LEN * 2 + 1)] = self.save_throughput_windows.reshape(-1)
        self.save_data_one[0, -1] = self.bitrate_lable
        self.save_data[self.count, :] = self.save_data_one

    def plot_target_send_rate(self, ip):
        """
        用来绘制图像
        :return:
        """
        pass
        # print(self.time[-1])
        # plt.figure()
        # plt.suptitle(ip + ', avg_loss:' + str(round(np.mean(self.loss), 2)) + '%'
        #              + ', delay:' + str(round(np.mean(self.delay), 2)) + 'ms'
        #              )
        #
        # plt.subplot(511)
        # # plt.plot(self.time, self.bandwidth)
        # plt.plot(self.bandwidth)
        # plt.ylabel('Bitrate (bps)')
        # # plt.plot(self.time, self.rate[:-1])
        # plt.plot(self.rate[:-1])
        # plt.legend(['bandwidth', 'target send rate'])
        #
        # plt.subplot(512)
        # plt.ylabel('Delay (ms)')
        # plt.ylim((0, 200))
        # plt.plot(self.delay)
        #
        # plt.subplot(513)
        # plt.ylabel('Loss (%)')
        # plt.plot(self.loss)
        #
        # plt.subplot(514)
        # plt.ylabel('Deltas(ms)')
        # plt.plot(self.ts_delta)
        # plt.plot(self.t_delta)
        # plt.legend(['send deltas', 'arrival deltas'])
        #
        # plt.subplot(515)
        # plt.ylabel('m(t)')
        # plt.ylim((-10, 10))
        # plt.plot(self.mt)
        # plt.plot(self.threashold)
        # plt.legend(['m(t)', 'threashold'])
        # plt.show()


import re
import sys

import cv2

from algo import tools
from settings import *

if __name__ == '__main__':
    try:
        folder = os.path.join(LOG_DIR, sys.argv[1])
        assert os.path.isdir(folder), 'invalid folder path given: %s'%(folder,)
        regex = sys.argv[2]
        target_file = sys.argv[3]
        framerate = int(sys.argv[4])
    except Exception as e:
        print(str(e))
        print('\nUSAGE: %s <log-dir relative input-dir> <img_regex> <target_file> <framerate>'%(sys.argv[0],))
        quit()

    test = re.compile(regex)
    img_files = []
    for file in os.listdir(folder):
        if test.match(file):
            img_files.append(file)

    img_files = sorted(img_files)
    assert len(img_files)>3, 'too few images found: %s'%(img_files,)

    img0 = cv2.imread(os.path.join(folder, img_files[0]), cv2.IMREAD_COLOR)
    h, w, c = img0.shape
    writer = cv2.VideoWriter(target_file, cv2.VideoWriter_fourcc(*'DIVX'), framerate, (w, h))
    try:
        for i, f in enumerate(img_files):
            tools.show_progress(len(img_files), i)
            img = cv2.imread(os.path.join(folder, f), cv2.IMREAD_COLOR)
            writer.write(img)
    finally:
        writer.release()


#encoding:utf-8
import os,xlrd,time
#from AutoTestSdap.TestComponent.SdapLogin import SdapLogin
from Testcore.TestCaseComponent import TestCaseComponent
from Testcore.TestCase import TestCase
from Testcore.TestSuite import TestSuite
from Testcore.TestPlan import TestPlan
from Testcore.TestStep import TestStep

fpath=os.path.abspath("..")+u"\Testplan\测试执行计划.xls"
testplan=TestPlan()
testsuite=TestSuite()
testplan.__TestPlan__(fpath)
testsuiteList=testplan.__gettestsuiteList__()
testsuite=testsuiteList[0]
testcaseList=testsuite.__gettestcaseList__()
testcase=testcaseList[0]
testcaseStepList=testcase.__gettestcaseStepList__()
testcasestep=testcaseStepList[0]
testcomponentlist=TestCaseComponent().__getcomponentList__()
t=TestCaseComponent()
t.__TestCaseComponent__()
testcomponentlist=t.__getcomponentList__()
str1=testcomponentlist.get(testcasestep.__getcomponentName__()).split('->')
moduleName=str1[0]
className=str1[1]
methodName=str1[2]
#利用python的反射机制
m=__import__(moduleName)
s=getattr(m, className)
k=getattr(s(), methodName)
k()


# -------------------------------------------------------------------
# Modified from densepose(https://github.com/facebookresearch/DensePose)
# -------------------------------------------------------------------
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# -------------------------------------------------------------------
import numpy as np
import cv2
import paddle.fluid.dygraph as dg

import densepose.utils.boxes as box_utils
from densepose.modeling.proposal_generator import map_rois_to_fpn_levels

def get_boxes(rois, cls_score, bbox_deltas, im_shape):
    pred_boxes = box_utils.bbox_transform(rois, bbox_deltas, weights=(10, 10, 5, 5))
    pred_boxes = box_utils.clip_tiled_boxes(pred_boxes, im_shape)

    scores, boxes, cls_boxes = box_results_with_nms_and_limit(cls_score, pred_boxes)

    return scores, boxes, cls_boxes

def box_results_with_nms_and_limit(scores, boxes):
    num_classes = 2 # for body and non-body
    score_thresh = 0.05
    cls_boxes = [[] for _ in range(num_classes)]

    for j in range(1, num_classes): # skip j = 0 for background
        inds = np.where(scores[:, j] > score_thresh)[0]
        scores_j = scores[inds, j]
        boxes_j = boxes[inds, j * 4: (j + 1) * 4]
        dets_j = np.hstack((boxes_j, scores_j[:, np.newaxis])).astype(
            np.float32, copy=False
        )
        keep = box_utils.nms(dets_j, 0.5)
        nms_dets = dets_j[keep, :]
        cls_boxes[j] = nms_dets

    im_results = np.vstack([cls_boxes[j] for j in range(1, num_classes)])
    boxes = im_results[:, :-1]
    scores = im_results[:, -1]
    return scores, boxes, cls_boxes

def get_body_rois(im_rois, im_scale):
    """
    Converts RoIs into network inputs.

    Arguments:
        im_rois (ndarray): R x 4 matrix of RoIs in original image coordiantes
        im_scale_factors (list): scale factors as returned by _get_image_blob

    Returns:
        blob (ndarray): R x 5 matrix of RoIs in the image pyramid with columns
                        [level, x1, y1, x2, y2]
    """
    rois, levels = _project_im_rois(im_rois, im_scale)
    rois_blob = np.hstack((levels, rois))
    rois_blob = rois_blob.astype(np.float32, copy=False)
    lvl_min = 2
    lvl_max = 5
    target_lvls = map_rois_to_fpn_levels(rois_blob[:,1:5])

    body_rois = []
    rois_idx_order = []
    for lvl in range(lvl_min, lvl_max + 1):
        idx_level = np.where(target_lvls == lvl)[0]
        rois_level = rois_blob[idx_level, :][:, 1:]
        batch_idx = np.zeros((len(rois_level), 1)) # assume only one test image in batch
        rois_level = np.hstack((batch_idx, rois_level))
        # rois_level = dg.to_variable(rois_level.astype('float32'))
        body_rois.append(rois_level)
        rois_idx_order.append(idx_level)

    return body_rois, rois_idx_order

def _project_im_rois(im_rois, scales):
    """
    Project image RoIs into the image pyramid.
    """
    rois = im_rois.astype(np.float, copy=False) * scales
    levels = np.zeros((im_rois.shape[0], 1), dtype=np.int)
    return rois, levels

def get_body_part(boxes, ann_index, index_uv, u, v):
    # In case of 1
    if len(ann_index.shape) == 3:
        ann_index = np.expand_dims(ann_index, axis=0)
    if len(index_uv.shape) == 3:
        index_uv = np.expand_dims(index_uv, axis=0)
    if len(u.shape) == 3:
        u = np.expand_dims(u, axis=0)
    if len(v.shape) == 3:
        v = np.expand_dims(v, axis=0)

    K = 24 + 1
    outputs = []
    for ind, entry in enumerate(boxes):
        # Compute ref box width and height
        bx = max(entry[2] - entry[0], 1)
        by = max(entry[3] - entry[1], 1)

        # preds[ind] axes are CHW; bring p axes to WHC
        cur_ann_index = np.swapaxes(ann_index[ind], 0, 2)
        cur_index_uv = np.swapaxes(index_uv[ind], 0, 2)
        cur_u = np.swapaxes(u[ind], 0, 2)
        cur_v = np.swapaxes(v[ind], 0, 2)

        # Resize p from (HEATMAP_SIZE, HEATMAP_SIZE, c) to (int(bx), int(by), c)
        cur_ann_index = cv2.resize(cur_ann_index, (by, bx))
        cur_index_uv = cv2.resize(cur_index_uv, (by, bx))
        cur_u = cv2.resize(cur_u, (by, bx))
        cur_v = cv2.resize(cur_v, (by, bx))

        # Bring cur_preds axes back to CHW
        cur_ann_index = np.swapaxes(cur_ann_index, 0, 2)
        cur_index_uv = np.swapaxes(cur_index_uv, 0, 2)
        cur_u = np.swapaxes(cur_u, 0, 2)
        cur_v = np.swapaxes(cur_v, 0, 2)

        # Removed squeeze calls due to singleton dimension issues
        cur_ann_index = np.argmax(cur_ann_index, axis=0)
        cur_index_uv = np.argmax(cur_index_uv, axis=0)
        cur_index_uv = cur_index_uv * (cur_ann_index > 0).astype(np.float32)

        output = np.zeros([3, int(by), int(bx)], dtype=np.float32)
        output[0] = cur_index_uv

        for part_id in range(1, K):
            part_u = cur_u[part_id]
            part_v = cur_v[part_id]
            output[1, cur_index_uv == part_id] = part_u[cur_index_uv == part_id]
            output[2, cur_index_uv == part_id] = part_v[cur_index_uv == part_id]

        outputs.append(output)

    return outputs


print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
name1.lower()
name2.lower()
true=str(name1.count("t")+name1.count("r")+name1.count("u")+name1.count("e")+name2.count("t")+name2.count("r")+name2.count("u")+name2.count("e"))
love=str(name2.count("l")+name2.count("o")+name2.count("v")+name2.count("e")+name1.count("l")+name1.count("o")+name1.count("v")+name1.count("e"))
love_score=int(true+love)

if love_score<10 or love_score>90:
  print("Your score is ",love_score,",you go together like coke and mentos.")
elif love_score>40 and love_score<50:
  print("Your score is ",love_score, ",you are alright together.")
else:
  print("Your score is ",love_score)

# #  Another similar program
# import random
# love_score= random.randint(1,100)
# print("Your score is ",love_score)


from binary_heap import *
from basic_array import Array
from new_sorting import *

print("Lab 10 solution\n")

print("First constructor")
H = BinaryHeap()
H.insert(5)
H.insert(2)
H.insert(8)
H.insert(1)
H.insert(9)
H.insert(5)
H.insert(3)
print(H)
while not H.empty():
	print(H.remove())
print()

print("Second constructor")
A = Array(100)
A[0] = 3
A[1] = 1
A[2] = 6
A[3] = 4
A[4] = 2
A[5] = 6
A[6] = 4
A[7] = 2
H2 = BinaryHeap(A, 8)
print(H2)
while not H2.empty():
	print(H2.remove())
print()

print("heap sort")
A = Array(100)
A[0] = 3
A[1] = 1
A[2] = 6
A[3] = 4
A[4] = 2
A[5] = 6
A[6] = 4
A[7] = 2
heap_sort(A, 8)
for i in range(8):
	print(A[i], end = " ")
print()

CS112/Lab 10 - Heap Sort/Homework/test.py


import datetime
import dateutil.parser
import pytz
from datetime import timedelta

import refill_api

def main_menu():
    print("#################################")
    print("### Pharmacy Refill Placement ###")
    print("#################################")
    print("#################################")

    pharmacy_id = str(promptForValue("pharmacy id"))

    client_health_id = str(promptForValue("client health id"))

    client_name = str(promptForValue("clien name & lastname"))

    client_email = str(promptForValue("client email"))

    medicine = str(promptForValue("medicine name"))

    rx_num = str(promptForValue("Rx number"))

    numRefills = str(promptForValue("number of refills allowed"))

    day_ordered = str(datetime.datetime.now().isoformat())

    numDaysAfter = promptForValue("the number of days after which a refill is allowed")
    day_refill_available = str((datetime.datetime.now() + timedelta(days = int(numDaysAfter))).isoformat())

    employee_id = str(promptForValue("your employee id"))

    pharmacy_email = str(promptForValue("the email of your pharmacy"))

    # place the order
    key = refill_api.makeOrder(pharmacy_id, client_health_id, client_name, client_email, medicine, rx_num, numRefills, day_ordered, day_refill_available, employee_id, pharmacy_email)

    print("\nOkay. All done now. Here is the key for the client.\n")
    print(key)
    print("\nThey can order their refill with this key after " + numDaysAfter + " days.")

def promptForValue(variable: str):
    print("\nType q and press Enter to quit")

    print("\nEnter " + variable + ": ", end = '')
    userIn = input()

    if(userIn.lower() == "q" or userIn.lower() == "quit" or userIn.lower() == "close"):
        exit()

    return userIn

main_menu()


#!/usr/bin/python

# Copyright (C) 2010 McAfee, Inc.  All rights reserved.
# TestcaseID: 16459
# TestcaseDescription: Enable prompt options and try to install few applications.

import sys
import logging
import threading
import time
import subprocess
import os.path

# Import CommonTest module into current namespace
common_path=os.path.dirname(os.path.abspath(sys.argv[0])) + "/../"
sys.path.append(common_path + "/Common")

# Import CommonTest module into current namespace
from CommonTest import *
import commonFns
import CommonAppProFns
# Get testcase name
testcaseName = sys.argv[0][:-3]

class TestCase(BaseTest):
    def __init__(self):
        logging.info("TestcaseID : 16459")
        logging.info("Description : Enable prompt options and try to install few applications.")

    def init(self):
        logging.info("Initializing testcase %s" % testcaseName)
        # Call the base initialization
        _retval = BaseTest.init(self)
        if _retval != 0:
            return 1
        self.appPath = os.path.dirname(os.path.abspath(sys.argv[0]))\
                        + "/data/SampleCocoaCarbonApps/80mac_eval_en.app"
        self.cmd = "open" + " " + self.appPath
        self.appName = "Meeting Maker Evaluation"
        self.sleep_time=10
        self.m_launch_app = TestCase._launch_app

        if CommonAppProFns.installAppProtTestTool() != True :
            logging.error("Failed to install appProtTestTool")
            return 1
        CommonAppProFns.resetAppProtToDefaults()

        # Exclude APTT
        exclusionList = [os.path.dirname(os.path.abspath(sys.argv[0])) + "/data/aptt/appProtTestTool" ]
        retval = CommonAppProFns.setAppProExclusions(exclusionList)
        if retval == False:
            logging.error("Failed to add the app to exclusions")
            return 1
        return 0

    def execute(self):
        """Executes the test and returns 0 for pass and 1 for fail"""
        logging.info("Executing testcase %s" % testcaseName)

        logging.debug("Setting unknown app action to 'Prompt'")
        if CommonAppProFns.setUnknownAppAction(3) == False :
            logging.error("Failed to set unknown app action to 'Prompt'")
            return 1
        try :
            logging.debug("launching %s in new thread" % self.appPath)
            self.thread_return = None
            _thread = threading.Thread(target=self.m_launch_app,args=[self] )
            _thread.start()
        except :
            logging.error("Failed to start the thread")
            return 1

        time.sleep(self.sleep_time)
        # deny the execution of the app
        retval = CommonAppProFns.alertDenyOnce()
        if(retval == True):
            logging.debug("Prompt appeared and Deny was chosen")
        else:
            logging.error("Error in selecting option")
            return 1
        # Wait for thread to join
        logging.debug("Waiting for thread to join")
        _thread.join()
        logging.debug("Thread joined")
        return self.thread_return

    def _launch_app(self):
        """Callback function which launches application.
            Called by Thread.run
        """
        logging.debug("Launching application %s" % self.appPath)
        try :
            retval = subprocess.call(self.cmd, shell=True)
            if retval != None :
                logging.error("Application launched")
                self.thread_return = 1
        except :
            logging.debug("Failed to launch application")
            self.thread_return = 0

    def verify(self):
        logging.info("Verifying testcase %s" % testcaseName)
        regex = "Denied " + self.appPath +"/Contents/MacOS/80mac_eval_en" + " from executing because  unknown applications are blocked as per the settings"
        if commonFns.searchProductLog(regex) != True:
            logging.error("Failed to find the regular expression in log")
            return 1
        logging.debug("Application denied of executing")
        return 0

    def cleanup(self):
        logging.info("Performing cleanup for testcase %s" % testcaseName)
        # Copy logs and clean them.
        logging.debug("Copying logs")
        foundCrash = 0
        foundCrash = commonFns.copyLogs()

        # part of our clean Up
        CommonAppProFns.resetAppProtToDefaults()

        if commonFns.isProcessRunning(self.appName) != True :
            logging.error("Application :%s is not running", self.appName)
        else:
            Cmd = "killall -9 " + self.appName
            retval = subprocess.call(Cmd, shell=True)
            if(retval != 0):
                logging.error("unable to kill %s application", self.appName)

        logging.debug("Cleaning the logs")
        commonFns.cleanLogs()

        if foundCrash != 0:
            logging.error("copylogs returned failure status.  Maybe a product crash")

        return foundCrash

    def __del__(self):
        pass

if __name__ == "__main__":
    # Setup testcase
    setupTestcase(sys.argv)

    testObj = TestCase()

    # Perform testcase operations
    retVal = testObj.init()

    # Perform execute once initialization succeeds...
    if(retVal == 0):
        testObj.execute()

    # Once execution succeeds, perform verification...
    if(retVal == 0):
        retVal = testObj.verify()

    # Perform testcase cleanup
    retVal += testObj.cleanup()

    if(retVal == 0):
        resultString = "PASS"
    else:
        resultString = "FAIL"

    logging.info("Result of testcase %s: %s" % (testcaseName, resultString) )
    sys.exit(retVal)


import numpy as np
from mlxtend.data import loadlocal_mnist

def import_mnist_data():

	X_train_old, y_train_old = loadlocal_mnist(
		images_path='../data/mnist/train-images.idx3-ubyte',
		labels_path='../data/mnist/train-labels.idx1-ubyte')

	X_train = np.zeros((X_train_old.shape[0], int(np.sqrt(X_train_old.shape[1])), int(np.sqrt(X_train_old.shape[1]))))

	for i in range(0,X_train_old.shape[0]):
	    X_train[i] = np.reshape(X_train_old[i], (int(np.sqrt(X_train_old.shape[1])), int(np.sqrt(X_train_old.shape[1]))))

	X_test_old, y_test_old = loadlocal_mnist(
		images_path='../data/mnist/t10k-images.idx3-ubyte',
		labels_path='../data/mnist/t10k-labels.idx1-ubyte')

	X_test = np.zeros((X_test_old.shape[0], int(np.sqrt(X_test_old.shape[1])), int(np.sqrt(X_test_old.shape[1]))))

	for i in range(0,X_test_old.shape[0]):
	    X_test[i] = np.reshape(X_test_old[i], (int(np.sqrt(X_test_old.shape[1])), int(np.sqrt(X_test_old.shape[1]))))

	#Data pre-processing reshape data to fit model
	X_train = X_train.reshape(60000,28,28,1)
	X_test = X_test.reshape(10000,28,28,1)

	return [X_train, y_train, X_test, y_test]


import pandas as pd
import numpy as np
import json

# df = pd.read_csv('../Data/HouseholdQuestions_Cities_Districts_040119_1300.csv',encoding='cp1252')
df = pd.read_csv('../Data/PIT2020_FEB26,2020.csv')

df = df.loc[lambda df: (df['P_Living_Situation'] != 'Couch'), :]

#! SCRIPT CHECKED 02/26/2020 11:27 JSON FINISHED

jsonFile = []

# read file
try:
    with open('./JSON/2019/CityTotalsByYear.json', 'r') as myfile:
        data=myfile.read()

    jsonData = json.loads(data)

except(FileNotFoundError):
    print("[OLD JSON FILE NOT FOUND, GENERATING NEW ONE]")
    jsonData = []

year = input("Input Year: ")
model = 'backend.CityTotalsByYear' + year
data = []
count = len(jsonData)

print("[CREATING NEW JSON FILE]")

df_d1 = df.loc[lambda df: df['DISTRICT'] == 1, :]
df_d2 = df.loc[lambda df: df['DISTRICT'] == 2, :]
df_d3 = df.loc[lambda df: df['DISTRICT'] == 3, :]
df_d4 = df.loc[lambda df: df['DISTRICT'] == 4, :]
df_d5 = df.loc[lambda df: df['DISTRICT'] == 5, :]

cities_d1 = ['RIVERSIDE', 'LAKE ELSINORE', 'UNINCORPORATED DISTRICT 1', 'WILDOMAR',"CANYON LAKE"]
cities_d2 = ['NORCO', 'CORONA', 'RIVERSIDE', 'JURUPA VALLEY', 'UNINCORPORATED DISTRICT 2',"EASTVALE"]
cities_d3 = ['TEMECULA', 'UNINCORPORATED DISTRICT 3', 'MURRIETA', 'HEMET', 'SAN JACINTO']
cities_d4 = ['DESERT HOT SPRINGS', 'UNINCORPORATED DISTRICT 4', 'LA QUINTA', 'COACHELLA', 'INDIAN WELLS', 'INDIO', 'PALM SPRINGS', 'CATHEDRAL CITY', 'BLYTHE', 'PALM DESERT', 'RANCHO MIRAGE',"MECCA"]
cities_d5 = ['MENIFEE', 'PERRIS', 'UNINCORPORATED DISTRICT 5', 'BEAUMONT', 'MORENO VALLEY', 'CALIMESA', 'BANNING']

class NpEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        else:
            return super(NpEncoder, self).default(obj)

def get_Total_CityByYear(in_df, city, year, district = None):
    total =  in_df.loc[lambda df: (df['CITYNAME'] == city), ['ParentGlobalID']].shape[0]

    citytitle = city
    if city == "RIVERSIDE":
        citytitle += "*"
    elif 'UNINCORPORATED' in city:
        citytitle = 'Unincorporated'

    return {"year": str(year), "district": str(district), "sheltered": "False", "city": citytitle.title(),"total": str(total), "volunteers": ""}

for city in cities_d1:
    data.append({
    "fields":  get_Total_CityByYear(df_d1,city, year, 1)
    })

for city in cities_d2:
    data.append({
    "fields":  get_Total_CityByYear(df_d2,city, year, 2)
    })

for city in cities_d3:
    data.append({
    "fields":  get_Total_CityByYear(df_d3,city, year, 3)
    })

for city in cities_d4:
    data.append({
    "fields":  get_Total_CityByYear(df_d4,city, year, 4)
    })

for city in cities_d5:
    data.append({
    "fields":  get_Total_CityByYear(df_d5,city, year, 5)
    })

for x in jsonData:
    x['model'] = model
    x['fields']['_type'] = 'Unsheltered'

jsonFields = [ x["fields"] for x in jsonData]

for d in data:
    if d['fields'] not in jsonFields:
        print("not found: ", d['fields'])
        count +=1
        d["pk"] = count
        d["model"] = model
        d['fields']['_type'] = 'Unsheltered'
        jsonData.append(d)

out = open('./JSON/2020/CityTotalsByYear.json','w')

out.write (json.dumps(jsonData, cls=NpEncoder, indent=4))
out.close()


import abc
import sys
import reframe.core.debug as debug
import reframe.core.logging as logging

from reframe.core.environments import EnvironmentSnapshot
from reframe.core.exceptions import (
    ReframeFatalError, ReframeError, SanityError
)
from reframe.core.fields import StringField, TypedField
from reframe.core.pipeline import RegressionTest
from reframe.frontend.printer import PrettyPrinter
from reframe.frontend.statistics import TestStats
from reframe.utility.sandbox import Sandbox

class TestCase:
    """Test case result placeholder class."""
    STATE_SUCCESS = 0
    STATE_FAILURE = 1

    def __init__(self, executor):
        self._executor = executor
        self._result = None
        self._failed_stage = None
        self._exc_info = None

    def __repr__(self):
        return debug.repr(self)

    @property
    def executor(self):
        return self._executor

    @property
    def result(self):
        return self._result

    @property
    def failed_stage(self):
        return self._failed_stage

    @property
    def exc_info(self):
        return self._exc_info

    def valid(self):
        return self._result is not None

    def success(self):
        self._result = TestCase.STATE_SUCCESS

    def fail(self, exc_info=None):
        self._result = TestCase.STATE_FAILURE
        self._failed_stage = self.executor.current_stage
        self._exc_info = exc_info

    def failed(self):
        return self._result == TestCase.STATE_FAILURE

class RegressionTestExecutor:
    """Responsible for the execution of `RegressionTest`'s pipeline stages.

    Keeps track of the current stage and implements relaxed performance
    checking logic."""
    _check = TypedField('_check', RegressionTest)
    _current_stage = StringField('_current_stage')

    def __init__(self, check, strict_check=False):
        self._current_stage = 'init'
        self._check = check
        if strict_check:
            self._check.strict_check = True

    def __repr__(self):
        return debug.repr(self)

    @property
    def check(self):
        return self._check

    @property
    def current_stage(self):
        return self._current_stage

    def setup(self, partition, environ, **job_opts):
        self._current_stage = 'setup'
        with logging.logging_context(check=self._check) as logger:
            logger.debug('entering setup stage')
            self._check.setup(partition, environ, **job_opts)

    def compile(self):
        self._current_stage = 'compile'
        with logging.logging_context(check=self._check) as logger:
            logger.debug('entering compilation stage')
            self._check.compile()

    def run(self):
        self._current_stage = 'run'
        with logging.logging_context(check=self._check) as logger:
            logger.debug('entering running stage')
            self._check.run()

    def wait(self):
        self._current_stage = 'wait'
        with logging.logging_context(check=self._check) as logger:
            logger.debug('entering waiting stage')
            self._check.wait()

    def poll(self):
        with logging.logging_context(check=self._check) as logger:
            logger.debug('polling check')
            ret = self._check.poll()
            return ret

    def check_sanity(self):
        # check_sanity() may be overriden by the user tests; we log this phase
        # here then
        self._current_stage = 'sanity'
        with logging.logging_context(check=self._check) as logger:
            logger.debug('entering sanity checking stage')
            ret = self._check.check_sanity()

        return ret

    def check_performance(self):
        # check_performance() may be overriden by the user tests; we log this
        # phase here then
        self._current_stage = 'performance'
        try:
            # FIXME: the logic has become a bit ugly here in order to support
            # both sanity syntaxes. It should be simplified again as soon as
            # the old syntax is dropped.
            with logging.logging_context(check=self._check) as logger:
                logger.debug('entering performance checking stage')
                ret = self._check.check_performance()
        except SanityError:
            # This is to handle the new sanity systax
            if self._check.strict_check:
                raise
            else:
                return True
        else:
            return True if not self._check.strict_check else ret

    def cleanup(self, remove_files=False, unload_env=True):
        self._current_stage = 'cleanup'
        with logging.logging_context(check=self._check) as logger:
            logger.debug('entering cleanup stage')
            self._check.cleanup(remove_files, unload_env)

        self._current_stage = 'completed'

class Runner:
    """Responsible for executing a set of regression tests based on an execution
    policy."""

    def __init__(self, policy, printer=None):
        self._printer = printer or PrettyPrinter()
        self._policy = policy
        self._policy.printer = self._printer
        self._policy.runner = self
        self._sandbox = Sandbox()
        self._stats = None

    def __repr__(self):
        return debug.repr(self)

    @property
    def policy(self):
        return self._policy

    @property
    def stats(self):
        return self._stats

    def runall(self, checks, system):
        try:
            self._printer.separator('short double line',
                                    'Running %d check(s)' % len(checks))
            self._printer.timestamp('Started on', 'short double line')
            self._printer.info()
            self._runall(checks, system)
        finally:
            # Always update statistics and print the summary line
            self._stats = self._policy.getstats()
            num_failures = self._stats.num_failures()
            self._printer.status(
                'FAILED' if num_failures else 'PASSED',
                'Ran %d test case(s) from %d check(s) (%d failure(s))' %
                (self._stats.num_cases(), len(checks), num_failures),
                just='center'
            )
            self._printer.timestamp('Finished on', 'short double line')

    def _partition_supported(self, check, partition):
        if self._policy.skip_system_check:
            return True

        return check.supports_system(partition.name)

    def _environ_supported(self, check, environ):
        precond = True
        if self._policy.only_environs:
            precond = environ.name in self._policy.only_environs

        if self._policy.skip_environ_check:
            return precond
        else:
            return precond and check.supports_progenv(environ.name)

    def _runall(self, checks, system):
        self._policy.enter()
        for c in checks:
            self._policy.enter_check(c)
            for p in system.partitions:
                if not self._partition_supported(c, p):
                    self._printer.status('SKIP',
                                         'skipping %s' % p.fullname,
                                         just='center',
                                         level=logging.VERBOSE)
                    continue

                self._policy.enter_partition(c, p)
                for e in p.environs:
                    if not self._environ_supported(c, e):
                        self._printer.status('SKIP',
                                             'skipping %s for %s' %
                                             (e.name, p.fullname),
                                             just='center',
                                             level=logging.VERBOSE)
                        continue

                    self._sandbox.system  = p
                    self._sandbox.environ = e
                    self._sandbox.check   = c
                    self._policy.enter_environ(self._sandbox.check,
                                               self._sandbox.system,
                                               self._sandbox.environ)
                    self._policy.run_check(self._sandbox.check,
                                           self._sandbox.system,
                                           self._sandbox.environ)
                    self._policy.exit_environ(self._sandbox.check,
                                              self._sandbox.system,
                                              self._sandbox.environ)

                self._policy.exit_partition(c, p)

            self._policy.exit_check(c)

        self._policy.exit()

class ExecutionPolicy:
    """Base abstract class for execution policies.

    An execution policy implements the regression check pipeline."""

    def __init__(self):
        # Options controlling the check execution
        self.skip_system_check = False
        self.force_local = False
        self.skip_environ_check = False
        self.skip_sanity_check = False
        self.skip_performance_check = False
        self.keep_stage_files = False
        self.only_environs = None
        self.printer = None
        self.environ_snapshot = EnvironmentSnapshot()
        self.strict_check = False

        # Scheduler options
        self.sched_account = None
        self.sched_partition = None
        self.sched_reservation = None
        self.sched_nodelist = None
        self.sched_exclude_nodelist = None
        self.sched_options = []

    def __repr__(self):
        return debug.repr(self)

    def enter(self):
        pass

    def exit(self):
        pass

    def enter_check(self, check):
        self.printer.separator(
            'short single line',
            'started processing %s (%s)' % (check.name, check.descr)
        )

    def exit_check(self, check):
        self.printer.separator(
            'short single line',
            'finished processing %s (%s)\n' % (check.name, check.descr)
        )

    def enter_partition(self, c, p):
        pass

    def exit_partition(self, c, p):
        pass

    def enter_environ(self, c, p, e):
        pass

    def exit_environ(self, c, p, e):
        pass

    @abc.abstractmethod
    def run_check(self, c, p, e):
        """Run a check with on a specific system partition with a specific environment.

        Keyword arguments:
        c -- the check to run.
        p -- the system partition to run the check on.
        e -- the environment to run the check with.
        """

    @abc.abstractmethod
    def getstats(self):
        """Return test case statistics of the run."""


#!/usr/bin/env python
from xml.etree import ElementTree as etree
import pygame
import os

TITLE = "PySnake"

WORKDIR = os.path.abspath(os.path.dirname(__file__))
IMAGEPATH = "../images"
SOUNDPATH = "../sounds"
LEVELPATH = "../levels"
SAVESPATH = "../saves"
LANGUAGEPATH = "../languages"

_factor = 1.0
def _load_image(name, width, height=None):
    if height is None:
        height = width
    width, height = int(width * _factor), int(height * _factor)
    path = os.path.join(WORKDIR, os.path.abspath(IMAGEPATH), name)
    return pygame.transform.scale(pygame.image.load(path), (width, height))

def _load_sound(name):
    path = os.path.join(WORKDIR, os.path.abspath(SOUNDPATH), name)
    return pygame.mixer.Sound(path)

IMAGE_DEFAULT  = _load_image("x.png", 18)
IMAGE_HEAD     = _load_image("head.png", 18)
IMAGE_BODYPART = _load_image("part.png", 16)
IMAGE_BRICK    = _load_image("brick.png", 20)
IMAGE_PIT      = _load_image("pit.png", 24)

IMAGE_FEED_ACORN       = _load_image("feed_acorn.png", 24)
IMAGE_FEED_APPLE       = _load_image("feed_apple.png", 32)
IMAGE_FEED_BLUEBERRIES = _load_image("feed_blueberries.png", 24)
IMAGE_FEED_CHERRY      = _load_image("feed_cherry.png", 24)
IMAGE_FEED_CHICKENLEG  = _load_image("feed_chickenleg.png", 36)
IMAGE_FEED_PEAR        = _load_image("feed_pear.png", 24)
IMAGE_FEED_PLUM        = _load_image("feed_yellow_plum.png", 24)

pygame.mixer.init()
SOUNDS_EAT     = [_load_sound("eat1.ogg"), _load_sound("eat2.ogg"),
                  _load_sound("eat3.ogg")]
SOUNDS_WRIGGLE = [_load_sound("wriggle1.ogg"), _load_sound("wriggle2.ogg")]
SOUND_DIE      = _load_sound("die.wav")
SOUND_START    = _load_sound("start.wav")
pygame.mixer.quit()

_language = {"wins_player" : "{0} wins.",
             "wins_no_one" : "No one has won.",
             "window_main" : "Game menu",
             "window_sigleplayer" : "Singleplayer menu",
             "window_multiplayer" : "Multiplayer menu",
             "window_campaign" : "Campaign menu",
             "window_options" : "Graphic, audio and language menu",

             "button_ok" : "#OK",
             "button_apply" : "#Apply",
             "button_cancel" : "#Cancel",
             "button_sigleplayer" : "S#ingleplayer",
             "button_multiplayer" : "M#ultiplayer",
             "button_campaign" : "Ca#mpaign",
             "button_continue" : "Co#ntinue",
             "button_option" : "#Settings",
             "button_start" : "Let's #go!",
             "button_quit" : "#Quit",
             "button_save" : "Sa#ve",
             "button_load" : "#Load",

             "label_language" : "Language",
             "label_resolution" : "Resolution",
             "label_width" : "Width",
             "label_height" : "Height",
             "label_color_depth" : "Color depth",
             "label_fullscreen" : "Fullscreen",
             "label_hwsurface" : "Hardware acceleration",
             "label_sound_volume" : "Sound volume",
             "label_musik_volume" : "Music volume",

             "radio_16_bit" : "16 bit",
             "radio_24_bit" : "24 bit",
             "radio_32_bit" : "32 bit",

             "hint_only_fullscreen" : "(only in fullscreen mode!)",
             "error_title" : "error!",
             "error_invalid_resolution" : "This resolution can not be set."
             }

def _create_language_object(language_dict):
    class Language(object): pass
    for key, value in language_dict.iteritems():
        setattr(Language, key.upper(), value)
    return Language()

def _parse_languagefile(filename):
    language_dict = {}
    root = etree.parse(os.path.join(LANGUAGEPATH, filename)).getroot()
    for string in root:
        language_dict[string.tag] = string.text
    return filename.split(".")[0], root.attrib.get("label"), language_dict

def _load_languages():
    names, language_dicts = {}, {}
    for filename in os.listdir(LANGUAGEPATH):
        if not filename.startswith("_"):
            name, label, language_dict = _parse_languagefile(filename)
            names[name] = label
            language_dicts[name] = language_dict
    return names, language_dicts

def get_language(language):
    language_dict = _language
    names, language_dicts = _load_languages()

    if language in names:
        language_dict.update(language_dicts[language])
    elif language != "english":
        print("Warning: Languagefile could not be found.")

    names["english"] = "English"
    return names, _create_language_object(language_dict)


#!/usr/bin/python3
# query starwars api with requests

if __name__ == '__main__':
    import requests
    from sys import argv
    url = 'https://swapi.co/api/people/'
    string = '{}'.format(argv[1])
    post = {'search': string}
    r = requests.get(url, params=post)
    result = dict(r.json())
    rlist = result['results']
    print('Number of results: {}'.format(result['count']))
    for d in rlist:
        print('{}'.format(d['name']))


from datetime import date

class Person():
    '''A class representing a person, used to show a simple example
    of OOP concepts'''

    def __init__(self, name, dob, gender):
        '''(Person, str, str, str) -> NoneType
        Set up a new person with a name dob (date of birth) and gender
        REQ: dob is formatted as "YYYY-MM-DD" all numeric values
        REQ: gender is one of "Male","Female"
        '''
        self._name = name
        year = int(dob[0:4])
        month = int(dob[5:7])
        day = int(dob[8:10])
        self._dob = date(year, month, day)
        self.is_male = (gender == "Male")

    def __str__(self):
        '''(Person) -> str
        Return a string representing this person
        '''
        return ("Hi, my name is " + self._name + " and I am " +
                str(self.get_age()) + " years old")

    def get_age(self):
        '''(Person) -> int
        Return this person's current age in years
        '''
        total_age = date.today() - self._dob
        age_years = total_age.total_seconds() // (365 * 24 * 60 * 60)
        return int(age_years)

class Student(Person):
    '''A class representing a student, created by inheritence
    inheriting attributes/methods from person and only extending
    the ones we need to make this a student'''

    def __init__(self, name, dob, gender, student_num, gpa):
        '''(Student, str, str, float) -> NoneType
        Set up a new student with a name dob (date of birth), gender,
        student_num, and their current gpa
        REQ: dob is formatted as "YYYY-MM-DD" all numeric values
        REQ: gender is one of "Male","Female"
        REQ: 0 <= gpa <= 4
        '''
        self._name = name
        year = int(dob[0:4])
        month = int(dob[5:7])
        day = int(dob[8:10])
        self._dob = date(year, month, day)
        self.is_male = (gender == "Male")
        self._student_num = student_num
        self._gpa = gpa

    def __str__(self):
        '''(Student) -> NoneType
        Return a string representing this student
        '''
        # get the result of my parent class's string method, and add to it
        ret = ("Hi, my name is " + self._name + " and I am " +
               str(self.get_age()) + " years old")
        if(self._gpa >= 3.5):
            ret += " and I'm on the honours list"
        elif(self._gpa < 2):
            ret += " and I need to study harder"
        return ret

    def raise_gpa(self, raise_amount):
        '''(Student, float) -> NoneType
        Increase the student's GPA by raise_amount
        '''
        self._gpa += raise_amount
        # Cap the GPA at 4
        if(self._gpa > 4):
            self._gpa = 4

if (__name__ == "__main__"):
    alice = Person("Alice Jones", "1978-03-05", "Female")
    bob = Student("Robert Smith", "1995-01-01", "Male", "1234", 3.6)
    print(alice)
    print(bob)
    # we cah get both of their ages
    print(alice.get_age())
    print(bob.get_age())
    # but only students have a raise_gpa method
    # alice.raise_gpa(0.1) #<-- this will cause a crash
    bob.raise_gpa(0.1)


#!/usr/bin/env python3

from distutils.core import setup, Extension

DESCRIPTION = "Generalized ufunc module"
LONG_DESCRIPTION = ""

def corefuncs_ext():
    depends = []
    sources = ['corefuncs.c']
    define_macros = []
    undef_macros = []
    extra_compile_args = ['-Wextra', '-Wunused-result']
    extra_link_args = []
    extra_objects = []

    # Uncomment for a debug build:
    # extra_compile_args.extend(['-O0', '-g'])

    return Extension (
        'corefuncs',
        define_macros=define_macros,
        undef_macros=undef_macros,
        depends=depends,
        extra_compile_args=extra_compile_args,
        extra_link_args=extra_link_args,
        sources=sources,
        extra_objects=extra_objects
    )

setup (
    name = 'corefuncs',
    version = '0.01',
    description = DESCRIPTION,
    long_description = LONG_DESCRIPTION,
    url = '',
    author = 'Stefan Krah',
    author_email = 'skrah@bytereef.org',
    license = 'BSD License',
    download_url = '',
    keywords = ["numpy", "gufuncs"],
    platforms = ["Many"],
    classifiers = [
        "Development Status :: 0 - Experimental/Unstable",
        "Intended Audience :: Developers",
        "Intended Audience :: Science/Research",
        "License :: OSI Approved :: BSD License",
        "Programming Language :: C",
        "Programming Language :: Python :: 3",
        "Operating System :: OS Independent",
        "Topic :: Scientific/Engineering :: Mathematics",
        "Topic :: Software Development"
    ],
    ext_modules = [corefuncs_ext()]
)


__author__ = 'linweizhong'
"""
Binary Tree Right Side View
Given a binary tree, imagine yourself standing on the right side of it,
return the values of the nodes you can see ordered from top to bottom.

For example:
Given the following binary tree,
   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---
You should return [1, 3, 4].
"""
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
from  node import  *
class Solution:
    # @param {TreeNode} root
    # @return {integer[]}
    def rightSideView(self, root):
        if root ==None :
            return []
        nodes1 = []
        nodes2 = []
        result = []
        nodes1.append(root)
        while len(nodes1) != 0  or  len(nodes2) != 0  :
            if  len(nodes1) != 0  :
                result.append(nodes1[-1].val)
                for node in nodes1 :
                    if node.left != None :
                        nodes2.append(node.left)
                    if node.right != None :
                        nodes2.append(node.right)
                nodes1=[]
            elif len(nodes2) !=  0  :
                result.append(nodes2[-1].val)
                for node in nodes2 :
                    if node.left != None :
                        nodes1.append(node.left)
                    if node.right != None :
                        nodes1.append(node.right)
                nodes2 = []
        return  result


from django.contrib.auth.models import User
from django.db import models

# Create your models here.

class Lenguaje(models.Model):
    nombre = models.CharField(max_length=30)
    version = models.CharField(max_length=12)
    entorno = models.CharField(max_length=10)
    logo = models.ImageField(upload_to='lenguajes/')
    def __unicode__(self):
        return u'{0} {1} en {2}'.format(self.nombre,self.version,self.entorno)

class Framework(models.Model):
    nombre = models.CharField(max_length=40)
    version = models.CharField(max_length=10)
    lenguaje = models.ForeignKey(Lenguaje)

    def __unicode__(self):
        return u'{0} {1} Framework de {2}'.format(self.nombre,self.version,self.lenguaje)

class Snippet(models.Model):
    usuario = models.ForeignKey(User)
    nombre = models.CharField(max_length=140)
    lenguaje = models.ForeignKey(Lenguaje)
    framework = models.ForeignKey(Framework,null=True,blank=True)
    snippet = models.TextField()

    def __unicode__(self):
        return u'{0} por {1}'.format(self.nombre, self.usuario.username)

    class Meta:
        verbose_name = 'Snippet'
        verbose_name_plural = 'Snippets'

class ComentarioSnippet(models.Model):
    usuario = models.ForeignKey(User)
    snippet = models.ForeignKey(Snippet)
    contenido = models.TextField()

    class Meta:
        verbose_name_plural = 'Comentarios de Snippets'


import sensenet.importers
np = sensenet.importers.import_numpy()
tf = sensenet.importers.import_tensorflow()

import json
import gzip

from sensenet.constants import CATEGORICAL, IMAGE_PATH, BOUNDING_BOX

from sensenet.accessors import get_image_shape
from sensenet.load import load_points
from sensenet.models.image import pretrained_image_model, image_feature_extractor
from sensenet.models.image import image_layers, get_pretrained_network
from sensenet.models.settings import Settings, ensure_settings
from sensenet.preprocess.image import make_image_reader

from .utils import TEST_DATA_DIR, TEST_IMAGE_DATA

EXTRA_PARAMS = {
    'bounding_box_threshold': 0.5,
    'image_path_prefix': TEST_IMAGE_DATA,
    'input_image_format': 'file',
    'load_pretrained_weights': True
}

def create_image_model(network_name, additional_settings):
    extras = dict(EXTRA_PARAMS)

    if additional_settings:
        extras.update(additional_settings)

    return pretrained_image_model(network_name, Settings(extras))

def reader_for_network(network_name, additional_settings):
    extras = dict(EXTRA_PARAMS)

    if additional_settings:
        extras.update(additional_settings)

    image_shape = get_image_shape(get_pretrained_network(network_name))
    return make_image_reader(Settings(extras), image_shape, False)

def check_image_prediction(prediction, index, pos_threshold, neg_threshold):
    for i, p in enumerate(prediction.flatten().tolist()):
        if i == index:
            assert p > pos_threshold, str((i, p))
        else:
            assert p < neg_threshold, str((i, p))

def classify(network_name, accuracy_threshold):
    pixel_input = {'input_image_format': 'pixel_values'}

    network = get_pretrained_network(network_name)
    nlayers = len(network['image_network']['layers'])
    noutputs = network['image_network']['metadata']['outputs']
    preprocessors = network['preprocess']

    image_model = create_image_model(network_name, None)
    pixel_model = create_image_model(network_name, pixel_input)
    read = reader_for_network(network_name, None)

    assert len(image_layers(pixel_model)) == nlayers

    # Just check if this is possible
    image_feature_extractor(pixel_model)
    ex_mod = image_feature_extractor(image_model)

    for image, cidx in [('dog.jpg', 254), ('bus.jpg', 779)]:
        point = load_points(preprocessors, [[image]])
        file_pred = image_model.predict(point)

        img_px = np.expand_dims(read(image).numpy(), axis=0)
        pixel_pred = pixel_model.predict(img_px)

        for pred in [file_pred, pixel_pred]:
            check_image_prediction(pred, cidx, accuracy_threshold, 0.02)

    outputs = ex_mod(load_points(preprocessors, [['dog.jpg'], ['bus.jpg']]))
    assert outputs.shape == (2, noutputs)

def test_resnet50():
    classify('resnet50', 0.99)

def test_mobilenet():
    classify('mobilenet', 0.97)

def test_xception():
    classify('xception', 0.88)

def test_resnet18():
    classify('resnet18', 0.96)

def test_mobilenetv2():
    classify('mobilenetv2', 0.88)

def detect_bounding_boxes(network_name, nboxes, class_list, threshold):
    file_input = {'bounding_box_threshold': threshold}

    pixel_input = {
        'input_image_format': 'pixel_values',
        'bounding_box_threshold': threshold
    }

    image_detector = create_image_model(network_name, file_input)
    pixel_detector = create_image_model(network_name, pixel_input)
    read = reader_for_network(network_name, {'rescale_type': 'pad'})

    file_pred = image_detector.predict([['pizza_people.jpg']])
    img_px = np.expand_dims(read('pizza_people.jpg').numpy(), axis=0)
    pixel_pred = pixel_detector.predict(img_px)

    for pred in [file_pred, pixel_pred]:
        boxes, scores, classes = pred[0][0], pred[1][0], pred[2][0]

        assert len(boxes) == len(scores) == nboxes, len(boxes)
        assert sorted(set(classes)) == sorted(class_list), classes

def test_tinyyolov4():
    detect_bounding_boxes('tinyyolov4', 5, [0, 53], 0.4)

def test_empty():
    detector = create_image_model('tinyyolov4', None)
    boxes, scores, classes  = detector.predict([['black.png']])

    assert len(boxes[0]) == 0
    assert len(scores[0]) == 0
    assert len(classes[0]) == 0

def test_scaling():
    detector = create_image_model('tinyyolov4', None)
    boxes, scores, classes  = detector.predict([['strange_car.png']])

    assert 550 < boxes[0, 0, 0] < 600,  boxes[0, 0]
    assert 220 < boxes[0, 0, 1] < 270,  boxes[0, 0]
    assert 970 < boxes[0, 0, 2] < 1020,  boxes[0, 0]
    assert 390 < boxes[0, 0, 3] < 440,  boxes[0, 0]

    assert scores[0] > 0.9
    assert classes[0] == 2


'''
    3번째 코드 : python 3 로 합격!!
    원리 :
        일단 1, 2번 코드에서 하듯이 해당 빈칸에 어떤 숫자가 들어갈 수 있는지 배열에 저장한다.

        빈칸 좌표 = blank배열
        들어갈 수 있는 숫자 = prob배열
        첫번째 빈칸 blank[0]에 들어갈 수 있는 숫자는 prob[0]에 저장되있는 숫자....
        ...
        N번재 빈칸 blank[N]에 들어갈 수 있는 숫자는 prob[N]

        inputNumber 함수에서 0번째 부터 시작한다
        blank[0]에 있는 x, y 값 좌표를 가져오고, 9개의 3x3 사각형 중에 몇번째인지도 알아낸다(=quad)

        그러고나서 number에 prob에 있는 값을 차례차례 불러오는데 불러와서 다음 단계로 넘어가기 전에
        이미 들어가있는 숫자인지를 검사한다.

        검사하는 방식은 다음과 같다. 예를들어 (0, 6)에 9라는 숫자를 이전 단계에서 집어넣었다면
        가로배열(wid), 세로배열(hei), 3x3배열(sq)에 저장을 하는데
        wid[0][9] = 1  // wid[x좌표][숫자값]
        hei[6][9] = 1 // hei[y좌표][숫자값]
        sq[2][9] = 1 // sq[몇번째 네모][숫자값]
        이렇게 저장을 해놓는다. 그러면 다음에 확인을 할때 굳이 for문을 쓰지 않고 해당 x좌표에 이 숫자값이 있다면
        1로 표시되기 때문에 바로 구분을 할 수 있다.

        그러고 blankCnt에서 총 빈칸갯수를 세고, inputNumber함수가 blankCnt만큼 호출되게 되면
        if문에서 조건을 확인하고 스도쿠를 출력한뒤 함수를 exit()로 종료한다.
'''
from sys import stdin

def checkNum(x, y) :
    temp = [0]
    quadX = (x // 3) * 3
    quadY = (y // 3) * 3
    pos = 0
    for i in range(1, 10) :
        cnt = 0

        for j in range(9) :
            if sudoku[x][j] == i :
                cnt += 1
                break
            elif sudoku[j][y] == i :
                cnt += 1
                break
            elif sudoku[quadX + (j // 3)][quadY + (j % 3)] == i:
                cnt += 1
                break

        if cnt == 1 :
            continue
        else :
            pos += 1
            temp[0] = pos
            temp.append(i)

    prob.append(temp)

def inputNumber(location) :
    if location == blankCnt :
        for i in sudoku:
            for j in i:
                print(j, end=" ")
            print("")
        exit()

    x = blank[location][0]
    y = blank[location][1]
    quad = ((x // 3) * 3) + (y // 3)

    for i in range(1, prob[location][0] + 1) :
        number = prob[location][i] - 1
        if wid[x][number] == 1 or hei[y][number] == 1 or sq[quad][number] == 1 :
            continue
        else :
            sudoku[x][y] = number + 1
            wid[x][number] = 1
            hei[y][number] = 1
            sq[quad][number] = 1
            inputNumber(location + 1)
            sudoku[x][y] = 0
            wid[x][number] = 0
            hei[y][number] = 0
            sq[quad][number] = 0

wid = [[0 for _ in range(9)] for _ in range(9)]
hei = [[0 for _ in range(9)] for _ in range(9)]
sq = [[0 for _ in range(9)] for _ in range(9)]

sudoku = [list(map(int, stdin.readline().split())) for _ in range(9)]

blank = []
prob = []
blankCnt = 0

for i in range(9) :
    for j in range(9) :
        k = sudoku[i][j]
        temp = ((i // 3) * 3) + (j // 3)
        if sudoku[i][j] == 0 :
            blankCnt += 1
            blank.append([i, j])
            checkNum(i, j)

inputNumber(0)