import os
from extract_features import calculate_and_save_features
from extract_features import load_image_features
from compare_features import compare_color_moments
from compare_features import compare_sifts
from extract_features import extract_img_features
import cv2

import operator

def grab_all_images(path):
    """
    Given a path, grab all of the .jpg files & calculate & save their features
    :param path:
    :return:
    """
    try:
        # Clean out any existing pickles for the output
        for file in os.listdir("output"):
            if file.endswith(".pkl"):
                # Clean out old pickles
                os.remove(os.path.join("output", file))
        for file in os.listdir(path):
            if file.endswith(".jpg"):
                print("Extracting features for {}".format(file))
                img_path = os.path.join(path, file)
                calculate_and_save_features(img_path)
                # print(os.path.join(path, file))
    except FileNotFoundError:
        raise FileNotFoundError(
            "Please ensure that the directory you specified exists")

def read_all_images():
    """
    Read all of the images in the output directory and return all
    of their features in a list
    :return: List of images features
    """
    images = []
    for file in os.listdir("./output"):
        if file.endswith(".pkl"):
            images.append(load_image_features(file))
    return images

def find_best_color_moment_image(base_img, images, k, feature):
    """
    Given a base image, find the k most similar images based on the color
    moment specified
    :param base_img: base image we want to compare to
    :param images: our list of images we are comparing against
    :param k: k most similar images
    :param feature: color moment feature: mean, std, or skew
    :return:
    """
    try:
        base_image_features = extract_img_features(base_img)
    except Exception:
        raise Exception("Could not find image. "
                        "Please make sure the image id is correct ie. Hand_0000002")
    color_moment_avgs = []
    for image in images:
        if image[3] == base_img:
            continue
        color_moment_avgs.append(
            (compare_color_moments(base_image_features[2], image[2], feature),
             image[3]))
    color_moment_avgs.sort(key=operator.itemgetter(0))

    rank = 1
    for color_moment in color_moment_avgs[:k]:
        result = cv2.imread(color_moment[1])
        result = cv2.resize(result, (400, 300))
        cv2.imshow("RANK {}: {}".format(rank, color_moment[1]), result)
        print("RANK {}: {} with an distance of {:4.2f}".format(
            rank, color_moment[1], color_moment[0]))
        rank += 1
    print("Press 0 on a window to close all images")
    cv2.waitKey(0)
    cv2.destroyAllWindows()

def find_best_sift_image(base_img, images, k):
    """
    Given a base image, find the k most similar images based on the color
    moment specified
    :param base_img: base image we want to compare to
    :param images: our list of images we are comparing against
    :param k: k most similar images
    :return:
    """
    try:
        base_image_features = extract_img_features(base_img)
    except Exception:
        raise Exception("Could not find image. "
                        "Please make sure the image path is correct")
    base_image_obj = cv2.imread(base_img)
    sift_avgs = []
    for image in images:
        if image[3] == base_img:
            continue
        avg_dist, matches = compare_sifts(base_image_features[1], image[1],
                                          base_image_features[0], image[0])
        sift_avgs.append((avg_dist, matches, image))
    sift_avgs.sort(key=operator.itemgetter(0), reverse=True)

    rank = 1
    for sift_avg in sift_avgs[:k]:
        image_to_compare = cv2.imread(sift_avg[2][3])
        result = cv2.drawMatches(base_image_obj, base_image_features[0],
                                 image_to_compare, sift_avg[2][0], sift_avg[1], None)
        result = cv2.resize(result, (800, 300))
        cv2.imshow("RANK {}: {}".format(rank, sift_avg[2][3]), result)
        print("RANK {}: {} with a matching score of {:4.2f}%".format(rank, sift_avg[2][3], sift_avg[0]))
        rank += 1

    print("Press 0 on a window to close all images")
    cv2.waitKey(0)
    cv2.destroyAllWindows()

if __name__ == "__main__":
    # grab_all_images("./imgs")
    my_images = read_all_images()
    # find_best_color_moment_image("Hand_0000378.jpg.pkl",  my_images, 4, "std")
    find_best_sift_image("Hand_0000002.jpg.pkl", my_images, 4)


def add(*args):
    output = 0
    count = 0
    for arg in args:
        if count == 0:
            output = arg
        else:
            output += arg
        count += 1
    return output

def subtract(*args):
    output = 0
    count = 0
    for arg in args:
        if count == 0:
            output = arg
        else:
            output = output - arg
        count += 1
    return output

def multiply(*args):
    output=1
    for arg in args:
        output*=arg
    return output

def divide(*args):
    count = 0
    output = 0.0
    for arg in args:
        if count == 0:
            output = arg * 1.0
        else:
            output = output / arg
        count += 1
    return output

def plot(*args):
    # OPTIONAL EXTRA CREDIT FUNCTION!
    # See README for info.
    pass

# add your custom operations here


# -*- coding: utf-8 -*-
"""
Created on Thu May  7 12:14:04 2020
@author: Sondr
"""

import numpy as np
import matplotlib.pyplot as plt
import numpy.linalg as la
#from control import *
from casadi import *
from Juan_pnmpc import *
import cvxopt
#this is a small crash course on how to run PNMPC control....

print("If the error IDA_LINESEARCH_FAIL, run the program more times. It comes from the model gets negative values")

#first, we need a system, so I created a discrete linear model as a toy problem.
class linear_discrete(SimulationModel):

    def __init__(self):
        #MODEL CONSTANTS:
        g = 9.81 #Gravity
        Cc = 2*10**(-5) #Chove valve constant
        A1 = 0.008107 #Cross section below ESP
        A2 = 0.008107 #Cross section above ESP
        D1 = 0.1016 #Pipe diameter below ESP
        D2 = 0.1016 #Pipe diameter above ESP
        h1 = 200 #Height from reservoir to ESP
        h2 = 800 #Height ESP up
        hw = 1000 #Total distance in well
        L1 = 500 #Length reservoir to ESP
        L2 = 1200 #Length from ESP to choce
        V1 = 4.054 #Pipe volume below ESP
        V2 = 9.729 #Pipe volum above ESP
        #ESP DATA
        B1 = 1.5*10**9 #Bulk modulus below ESP
        B2 = 1.5*10**9 #Bulk modulus above ESP
        M = 1.992*10**8 #Fluid inertia
        rho = 950 #Density of fluid
        pr = 1.26 * 10 ** 7 #Reservoir pressure
        f0 = 60 # ESP reference freq
        #UNKNOWN
        PI = 2.32*10**(-9) #Well producity index
        pm = 20e5 #Manifold pressure
        my = 0.025 # Vicosity of produced fluid

        # VCF for ESP flow rate
        CQ = 1 - 2.6266*my + 6.0032*my**2 - 6.8104*my**3 + 2.7944*my**4
        CH = 1 - 0.03*my

        #INITIAL VALUES
        self.pbh0 = 70e5
        self.pwh0 = 30e5
        self.q0 = 0.01
        #END CONSTANTS

        #INITIALIZE MODEL
        dae = DaeBuilder()
        # Add input expressions
        pbh = dae.add_x('pbh')
        pwh = dae.add_x('pwh')
        q = dae.add_x('q')

        qr = dae.add_z('qr')
        qc = dae.add_z('qc')

        F1 = dae.add_z('F1')
        F2 = dae.add_z('F2')
        DeltaPp = dae.add_z('DeltaPp')

        u = dae.add_p('u')
        f = dae.add_p('f')

        # Add output expressions
        pbhdot = (B1/V1)*(qr-q)
        pwhdot = (B2/V2)*(q-qc)
        qdot = (1/M)*(pbh-pwh-rho*g*hw - F1 - F2 + DeltaPp)

        dae.add_ode('pbhdot', pbhdot)
        dae.add_ode('pwhdot', pwhdot)
        dae.add_ode('qdot', qdot)

        #Algebraic equation
        dae.add_alg('qr', qr-PI*(pr-pbh))
        dae.add_alg('qc', qc-Cc*(sqrt(fmax(10**-5, pwh-pm))*u))

        dae.add_alg('F1', F1 - 0.158*((rho*L1*q**2)/(D1*A1**2))*(my/(rho*D1*q))**(1/4))
        dae.add_alg('F2', F2 - 0.158*((rho*L2*q**2)/(D2*A2**2))*(my/(rho*D2*q))**(1/4))

        # Algebraic ESP equations:
        dae.add_alg('DeltaPp', DeltaPp - rho*g* (CH*(9.5970e2 + 7.4959e3*((q/CQ)*(f0/f)) - 1.2454e6*((q/CQ)*(f0/f))**2)*(f/f0)**2))
        #CREATE DAE
        dae = {'x': vertcat(*dae.x), 'p': vertcat(*dae.p),'z': vertcat(*dae.z), 'ode': vertcat(*dae.ode), 'alg': vertcat(*dae.alg)}
        ts = np.linspace(0,0.1,3)
        opts = {'grid':ts}
        self.I = integrator('I', 'idas', dae, opts)

    	#START MED INITAL, så gå over til first result
    def model_output(self,u):
        I = self.I
#        print(u[1])
        z = u[0]
        f = u[1]
      #FIRST STEP WITH INPUT z =1 , f = 40
        x0 = vertcat(self.pbh0,self.pwh0,self.q0) #DIFFERENTIAL
#        print(x0)
        p0 = vertcat(z,f) #INPUTS
        res = self.I(x0=x0,p=p0)
        solution = res['xf'].full().T

        self.pbh0 = solution[len(solution)-1,0] #Initalizing model with correct states with new input
        self.pwh0 = solution[len(solution)-1,1]
        self.q0 = fmax(1e-5,solution[len(solution)-1,2])
        y = solution[len(solution)-1,:]
        return y

ESP = linear_discrete()
#------------------------------------------

#we first need to gather data, so we use the built-in RFRAS (Random Frequency Random Amplitude Signal)

#these lines of code create the identificaton signal:
simtime = 2000
u_min = np.array([0.7])
u_max = np.array([1])
some_input_u = RFRAS(u_min,u_max,simtime,30)

f_min = np.array([40])
f_max = np.array([60])
some_input_f = RFRAS(f_min,f_max,simtime,30)
#print(some_input)
#THe data MUST be 2dimensional, and data must organized in row form, so in this case:

some_input_u = np.atleast_2d(some_input_u).T
some_input_f = np.atleast_2d(some_input_f).T

some_input = np.zeros([len(some_input_u),2])

for i in range (len(some_input_u)):
    some_input[i,0] = some_input_u[i]
    some_input[i,1] = some_input_f[i]

#some_input = [*some_input_u , *some_input_f]

#the resulting dimension should always be (number of data x number of features)

#now we need to run the system with that signal to obtain the system response, which is recorded in y_data
y_data = np.empty([simtime,3])
y_data[0] = (70e5,30e5,0.01)
#the simulation and plotting for data gathering is as follows:
for i in range(simtime):
    y = ESP.model_output(some_input[i])
    y_data[i] = y
#print(y_data)

#PLOTS OF THE DATA INCLUDED THE INPUTS
plt.figure(1)
plt.subplot(511)
plt.plot(y_data[:,0]/10**5,color='blue', label='$p_{bh}$')
plt.grid()
plt.legend()
plt.ylabel('$p_{bh} \ [bar]$')

plt.subplot(512)
plt.plot(y_data[:,1]/10**5,color='blue',label='$p_{wh}$')
plt.grid()
plt.legend()
plt.ylabel('$p_{wh} \ [bar]$')

plt.subplot(513)
plt.plot(y_data[:,2]*3600,color='blue',label='$q$')
plt.grid()
plt.legend()
plt.ylabel(r'$q \ [\dfrac{m^3}{h}]$')
plt.xlabel('Time [min]')

plt.subplot(514)
plt.plot(some_input[:,0],color='red',label='$valve$')
plt.grid()
plt.legend()
plt.xlabel('Time [min]')

plt.subplot(515)
plt.plot(some_input[:,1],color='red',label='$frekvens$')
plt.grid()
plt.legend()
plt.xlabel('Time [min]')

##plt.plot(y_data)
##------------------------------------------------------------

#next step is to normalize the data using feature scaling, so we need to use
#a minimum value and a maximum value, even better if it ties to the constraints of your problem.
#
##The scaling is done as follows, using the built_in function from esn_pnmpc_library:
u_data_normal = feature_scaling(some_input,u_max,u_min)
y_max = np.max(y_data,axis=0)
y_min = np.min(y_data,axis=0)
y_data_normal = feature_scaling(y_data,y_max,y_min)

u_data_normal = np.zeros([len(some_input_u),2])
y_data_normal = np.zeros([len(some_input_u),2])

u_data_normal[:,0] = feature_scaling(some_input[:,0],u_max,u_min)
u_data_normal[:,1] = feature_scaling(some_input[:,1],f_max,f_min)

#y_max = np.max(y_data,axis=0)
#y_min = np.min(y_data,axis=0)
#y_data_normal = feature_scaling(y_data,y_max,y_min)
#

##---------------------------------------------------------------------------------------------------
#
##Now, ater obtaining a set of normalized inputs and outputs, we shall instantiate and train a black-box model:
#
##in this case, an ESN is used, with the parameters arbitrariely selected.
##Obviously, the ESN is a bit overkill for the problem of training a linear third order system...
##

toy_esn = EchoStateNetwork(neu = 100,
                           n_in = 2,
                           n_out = 3,
                 gama=0.8,
                 ro=0.99,
                 psi=0.0,
                 in_scale=0.1,
                 bias_scale=0.1,
                 initial_filename="initial",
                 load_initial = False,
                 save_initial = False)
#                 noise_amplitude = 5e-3)
#toy_esn = RNN.EchoStateNetwork(neu = 100,n_in = 2,n_out = 3,gama = 0.14,ro = 0.99,psi = 0.0,in_scale = 0.1,bias_scale = 0.1, initial_filename = "initial", load_initial = True, save_initial = False,output_feedback = False)
#-----------------------------------------------------------------------------------------------

#now, we need to train it, by first feeding the ESN with the normalized data.
#the warmupdrop means that the first few [warmupdrop] examples will the dropped.
#In this case, the first few examples are outliers and have a high probability of corrupting the data.

#the function add data serves to gather data of one simulation run to the class "database".
#Multiples simulation could also be absorbed by multiple runs of the command.

#now, we train. The training function also returns the best regularization parameter while insternally changing the weights.
y_data_normal = feature_scaling(y_data,y_max,y_min)
regularization = 1e-8
drop = 200

warmupdrop = 200

#offline_training(self,X,Y,regularization,warmupdrop):
toy_esn.offline_training(u_data_normal,y_data_normal,regularization,warmupdrop)

#print("TEST")

#error, reg = toy_esn.cum_train_cv(min_reg,max_reg)

#adter training the ESN, it is recommended you generate another input signal to test the ESN:

simtime = 500

#
#CREATING TEST INPUT WITH RANDOM IN
test_input_u = RFRAS(u_min,u_max,simtime,30)
test_input_f = RFRAS(f_min,f_max,simtime,30)

test_input = np.zeros([len(test_input_u),2])

for i in range (len(test_input_u)):
    test_input[i,0] = test_input_u[i]
    test_input[i,1] = test_input_f[i]

#CREATING THE PREDICTION WITH ESN
y_pred_test = np.empty([simtime,3])
y_test = np.empty_like(y_pred_test)

for k in range(simtime):
    y_test[k] = ESP.model_output(test_input[k])

test_input[:,0] = feature_scaling(test_input[:,0],u_max,u_min)
test_input[:,1] = feature_scaling(test_input[:,1],f_max,f_min)

for k in range(simtime):
    y_pred_test[k] = toy_esn.update(test_input[k]).flatten()
    y_pred_test[k] = feature_descaling(y_pred_test[k],y_max,y_min)

#PLOTS WITH REAL AND PREDICTED VALUES
plt.figure(2)
plt.subplot(511)
plt.plot(y_test[:,0]/10**5,color='blue', label='$p_{bh}$')
plt.plot(y_pred_test[:,0]/10**5,color='orange', label='$pred$')
plt.grid()
plt.legend()
plt.ylabel('$p_{bh} \ [bar]$')

plt.subplot(512)
plt.plot(y_test[:,1]/10**5,color='blue', label='$p_{wh}$')
plt.plot(y_pred_test[:,1]/10**5,color='orange', label='$pred$')
plt.grid()
plt.legend()
plt.ylabel('$p_{wh} \ [bar]$')

plt.subplot(513)
plt.plot(y_test[:,2]*3600,color='blue', label='$q$')
plt.plot(y_pred_test[:,2]*3600,color='orange', label='$pred$')
plt.grid()
plt.legend()
plt.ylabel(r'$q \ [\dfrac{m^3}{h}]$')

plt.subplot(514)
plt.plot(test_input[:,0],color='red',label='$valve$')
plt.grid()
plt.legend()

plt.subplot(515)
plt.plot(test_input[:,1],color='red',label='$frekvens$')
plt.grid()
plt.legend()
plt.xlabel('Time [min]')
#from the plot it seems the esn can easily copy the system behavior, therefore we are ready to instantiate the predictor:

u_max = np.max(some_input,axis=0)
u_min = np.min(some_input,axis=0)

a = 0.5 #forcing the pole of the filter.

toy_predictor = PNMPCPredictor(control_horizon = 5,
                               prediction_horizon = 30,
                               bb_model = toy_esn,
                               filter_constants = a**2,
                               K = (a**2 - 2.0*a +1)/(1 - a**2))

#now that we just created the predictor, we need to create the control instance....
initial_u = [[0.7],[40]]
initial_u = [0.7,40]
print("test",initial_u)
control = PNMPCController(n_cv = 2,
                 u_max = u_max,
                 u_min = u_min,
                 y_max = y_max,
                 y_min = y_min,
                 initial_u = initial_u,
                 Q = np.eye(3),
                 R = np.eye(2),
                 du_max_c = 0.6,
                 output_constraints_max = 1*y_max[1:],
                 output_constraints_min = 1*y_min[1:],
                 predictor = toy_predictor,
                 simulation_model = ESP)

#running the controller is simple, you just have to define a proper reference signal for it, of dimension n_cv
pnmpc_time = 500
#y_ref = RFRAS(y_min[0],y_max[0],pnmpc_time,20)
#reference should be organized just like the data matrices, this is needed because there is only one controlled variable:
#y_ref = np.atleast_2d(y_ref).T

y_ref = np.zeros([pnmpc_time,2])

for i in range (pnmpc_time):
    y_ref[i,0] = 50e5
    y_ref[i,1] = 25e5
#    y_ref[i,2] = 0.02

warm_up_time = 200

output_dict = control.run_controller(y_ref) #THE ERROR COMES HERE
#

plt.figure(1)
plt.subplot(411)
plt.plot(y_ref,color='blue', label='$reference$')
plt.grid()
plt.legend()
plt.ylabel('$p_{bh} \ [bar]$')

plt.subplot(412)
plt.plot(output_dict['y_plot'][:,0],color='blue',label='$p_{wh}$')
plt.grid()
plt.legend()
plt.ylabel('$p_{wh} \ [bar]$')

plt.subplot(413)
plt.plot(output_dict['y_plot'][:,1],color='blue',label='$p_{bh}$')
plt.grid()
plt.legend()
plt.ylabel('$p_{wh} \ [bar]$')

plt.subplot(414)
plt.plot(output_dict['y_plot'][:,2],color='blue',label='$q$')
plt.grid()
plt.legend()
plt.ylabel('$p_{wh} \ [bar]$')

sub[0].plot(y_ref)
sub[0].plot(output_dict['y_plot'][:,0])

plt.plot(output_dict['correction_plot'])

#sub[1].plot(output_dict['y_plot'][:,1])
#sub[2].plot(output_dict['y_plot'][:,2])
ax = plt.gca()
ax.set_xlabel("time")
sub[0].set_ylabel("CV 1")
sub[1].set_ylabel("constraint 1")
sub[2].set_ylabel("constraint 2")

plt.show()

print("IAE:",output_dict['IAE'])


# -*- coding: utf-8 -*-
#
# Swiss Open Access Repository
# Copyright (C) 2021 RERO
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""SONAR resources responses."""

from flask import Response, make_response
from flask_resources.responses import Response as ResourceResponse

class StreamResponse(ResourceResponse):
    """Stream response."""

    filename = None

    def __init__(self, serializer=None, **kwargs):
        """Stream response initialization.

        Sets the filename for attachment if present in kwargs.

        :param serializer: Record serializer.
        """
        self.filename = kwargs.pop('filename', 'records')
        super().__init__(serializer)

    def make_list_response(self, content, code=200):
        """Builds a response for a list of objects.

        :param content: Content to send.
        :param code: Status code.
        :returns: Response object.
        """
        response = make_response(
            "" if content is None else Response(
                self.serializer.serialize_object_list(content)),
            code,
            self.make_headers(),
        )
        response.headers[
            'Content-Disposition'] = f'attachment; filename={self.filename}'
        return response


from transformers import DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DISTILBERT_PRETRAINED_MODEL_ARCHIVE_MAP
from transformers.tokenization_distilbert import PRETRAINED_VOCAB_FILES_MAP
from transformers.file_utils import get_from_cache
from pathlib import Path
import shutil
import os
import numpy as np
import torch
import subprocess

config_path = DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP["distilbert-base-uncased-finetuned-sst-2-english"]
vocab_path = PRETRAINED_VOCAB_FILES_MAP["vocab_file"]["distilbert-base-uncased"]
weights_path = DISTILBERT_PRETRAINED_MODEL_ARCHIVE_MAP["distilbert-base-uncased-finetuned-sst-2-english"]

target_path = Path.home() / 'rustbert'

temp_config = get_from_cache(config_path)
temp_vocab = get_from_cache(vocab_path)
temp_weights = get_from_cache(weights_path)

os.makedirs(target_path, exist_ok=True)
shutil.copy(temp_config, target_path / 'config.json')
shutil.copy(temp_vocab, target_path / 'vocab.txt')
shutil.copy(temp_weights, target_path / 'model.bin')

weights = torch.load(temp_weights)
nps = {}
for k, v in weights.items():
    nps[k] = v.cpu().numpy()

np.savez(target_path / 'model.npz', **nps)

source = str(target_path / 'model.npz')
target = str(target_path / 'model.ot')

toml_location = (Path(__file__).resolve() / '..' / '..' / 'Cargo.toml').resolve()

subprocess.call(
    ['cargo', '+nightly', 'run', '--bin=convert-tensor', f'--manifest-path={toml_location}', '--', source,
     target])


import requests
import gzip
import shutil
import os
import subprocess

class ThreeDid:

    version_url = 'https://interactome3d.irbbarcelona.org/api/getVersion'
    db_url = 'https://3did.irbbarcelona.org/download/current/3did.sql.gz'

    def __init__(self):
        self.version = None

    # retrieve database version
    def get_version(self):
        self.version = requests.get(ThreeDid.version_url).content

    # download database on disk
    def get_db(self):
        # download archive
        archive_filename = os.path.basename(ThreeDid.db_url)
        archive = requests.get(ThreeDid.db_url)

        # write to disk
        open(archive_filename, 'wb').write(archive.content)

        # extract
        with gzip.open(archive_filename, 'rb') as f_in:
            with open('3did.sql', 'wb') as f_out:
                shutil.copyfileobj(f_in, f_out)

    # import database into mysql
    def import_db(self, db):

        # recreate database
        db.execute('drop database if exists 3did')
        db.execute('create database 3did')

        # import downloaded database
        out = subprocess.check_output(['mysql', '-u', 'root', '--show-warnings', '-e', 'use 3did; source 3did.sql;'])
        print(out.decode())

    def test_db(self, db):
        db.execute('use 3did')
        db.execute('show tables')
        for row in db.fetchall():
            print(row)


import time
import os

def run(game, start_time):
    if ( game.time_limit < 100.0 and os.path.isfile('nodetemp.txt') ) :
        fp = open('nodetemp.txt','r')
        preCheckList = fp.readline().rstrip().split()
        preCheckList = preCheckList + game.G.nodes()
    else :
        preCheckList = game.G.nodes()

    rival_list = [0,2,1]
    my_id      = game.player_id
    rival_id   = rival_list[my_id]

    dd = {} # {node} =  [ ddv , tv ]

    for node in preCheckList :
        if ( game.time_limit >= 100.0 ) :
            if ( time.time() - start_time >= game.time_limit - 15.0 ):
                break
        else:
            if ( time.time() - start_time >= game.time_limit - 8.0 ) :
                break

        if ( node in dd.keys() ) :
            continue
        if ( node in game.selectNodeslist[my_id]  or  node in game.activeNodeslist[my_id] ):
            continue
        if ( node in game.selectNodeslist[rival_id]  or  node in game.activeNodeslist[rival_id] ):
            continue

        nodeac = 0
        for succ in game.G.successors(node) :
            if ( succ in game.selectNodeslist[my_id]  or  succ in game.activeNodeslist[my_id] )  :
                continue
            if ( succ in game.selectNodeslist[rival_id]  or  succ in game.activeNodeslist[rival_id] )  :
                continue
            invalue_m = 0.0
            invalue_r = 0.0
            for pre in game.G.predecessors(succ) :
                if ( pre in game.selectNodeslist[my_id]  or  pre in game.activeNodeslist[my_id] )  :
                    invalue_m = invalue_m + game.G.edge[pre][succ]['lt_influence']
                if ( pre in game.selectNodeslist[rival_id]  or  pre in game.activeNodeslist[rival_id] ) :
                    invalue_r = invalue_r + game.G.edge[pre][succ]['lt_influence']

            if ( invalue_m + game.G.edge[node][succ]['lt_influence']  >= invalue_r and invalue_m + game.G.edge[node][succ]['lt_influence'] >= game.G.node[succ]['lt_threshold']) :
                nodeac = nodeac + 1
        dd.setdefault( node , [ nodeac  , 0.0 ] )

    max_nodes_key_list = sorted( dd.keys() , key = lambda x : dd[x][0]  , reverse = True )

    # Output to Selected Node
    bufsize = 4
    print('Writing Files')

    fp = open (game.selected_file,'w',bufsize)
    for node in max_nodes_key_list[0:10] :
        print ( '%d' % ( int(node) ) , end = ' ' , file = fp )
    fp.close()

    fp = open ('nodetemp.txt','w',bufsize)
    print('Writing to temp')

    if ( game.time_limit >=100.0 ) :
        for node in max_nodes_key_list :
            print ( '%d' % ( int(node) ) , end = ' ' , file = fp )
    else :
        for node in max_nodes_key_list[10:200] :
            print ( '%d' % ( int(node) ) , end = ' ' , file = fp )
    fp.close()


from django.shortcuts import render, redirect, get_object_or_404
from .models import Article, Hashtag
from .forms import ArticleForm, CommentForm
from IPython import embed
from django.http import Http404, HttpResponse
from django.views.decorators.http import require_POST
from django.contrib.auth.decorators import login_required
from itertools import chain

# Create your views here.
@login_required
def index(request):
    visits_num = request.session.get('visits', 0)
    request.session['visits'] = visits_num + 1
    request.session.modified = True
    followings = request.user.followings.all()
    followings_and_me = chain(followings, [request.user])
    articles = Article.objects.filter(user__in=followings_and_me)
    # my_articles = request.user.article_set.all()
    context = {
        'articles': articles,
        'visits': visits_num
    }
    return render(request, 'articles/index.html', context)

# detail
def detail(request, article_pk):
    article = get_object_or_404(Article, pk=article_pk)
    # 만약에 Article.objects.get(pk=article_pk)
    # try:
    #     article = Article.objects.get(pk=article_pk)
    # except Article.DoesNotExist:
    #     raise Http404('해당하는 id의 글이 존재하지 않습니다.')
    comment_form = CommentForm()

    context = {
        'article': article,
        'comment_form': comment_form,
        'comments': article.comment_set.all(),
    }
    return render(request, 'articles/detail.html', context)

@login_required
def create(request):
    if not request.user.is_authenticated:
        return redirect('accounts:login')

    if request.method == 'POST':

        form = ArticleForm(request.POST)
        # 전송된 데이터가 유효한 값인지 검사
        if form.is_valid():
            # title = form.cleaned_data.get('title')
            # content = form.cleaned_data.get('content')
            # article = Article.objects.create(title=title, content=content)
            article = form.save(commit=False)
            article.user = request.user
            article.save()

            # hashtag
            for word in article.content.split():
                if word.startswith('#'):
                    hashtag, created = Hashtag.objects.get_or_create(content=word)
                    article.hashtags.add(hashtag)
            return redirect(article)
        else:
            return redirect('articles:create')
    else:
        form = ArticleForm()
        context = {
            'form': form,
        }
        return render(request, 'articles/create.html', context)

# UPDATE -> articles/:id/update | (PUT) articles/:id
@login_required
def update(request, article_pk):
    article = get_object_or_404(Article, pk=article_pk)

    if article.user == request.user:
        if request.method == 'POST':
            # 실제 DB의 데이터를 수정
            form = ArticleForm(request.POST, instance=article)
            if form.is_valid():
                form.save()
                return redirect(article)

        # 편집 화면
        form = ArticleForm(instance=article)
    else:
        return redirect('articles:index')
    context = {
        'article': article,
        'form': form,
    }
    return render(request, 'articles/update.html', context)

# DELETE -> articles/:id/delete
@require_POST
def delete(request, article_pk):
    if request.user.is_authenticated:
        article = get_object_or_404(Article, pk=article_pk)

        if article.user == request.user:
            if request.method == 'POST':
                article.delete()
                return redirect('articles:index')
        else:
            return redirect(article)
    return HttpResponse('검증되지 않은 유저정보', status=401)

@login_required
def create_comment(request, article_pk):
    article = Article.objects.get(pk=article_pk)

    if request.method == 'POST':
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            comment = comment_form.save(commit=False)
            # comment.article_id = article_pk
            # comment.save()
            comment.user = request.user
            comment.article = article
            comment.save()

    # return redirect('articles:detail', article_pk)
    return redirect(article)

def send_cookie(request):
    # return render() -> html 페이지를 만들어 주는 것.
    # return redirect()
    # return reverse()
    # return HttpResponse()
    res = HttpResponse('과자 받아라')
    res.set_cookie('mycookie', 'oreo')
    return res

def like(request, article_pk):
    # article_pk로 넘어온 글의 like_users에 현재 접속중인 유저를 추가한다.
    article = Article.objects.get(pk=article_pk)
    user = request.user
    # 만약 좋아요 리스트에 현재 접속중인 유저가 있다면,
    # -> 해당 유저는 좋아요를 했다
    # if request.user in article.like_users.all():
    if article.like_users.filter(pk=user.pk).exists():
        article.like_users.remove(user)
    else:
        article.like_users.add(user)

    return redirect(article)
    # request.user.like_articles.add(article)

def explore(request):
    articles = Article.objects.all()
    context = {
        'articles': articles
    }
    return render(request, 'articles/explore.html', context)

def tags(request):
    tags = Hashtag.objects.all()
    context = {
        'tags': tags,
    }
    return render(request, 'articles/tags.html', context)

def hashtag(request, hashtag_pk):
    hashtag = get_object_or_404(Hashtag, pk=hashtag_pk)
    articles = hashtag.article_set.all()
    context = {
        'hashtag': hashtag,
        'articles': articles,
    }
    return render(request, 'articles/hashtag.html', context)


"""
Definition of views.
"""

from django.shortcuts import render
from django.http import HttpRequest
from django.template import RequestContext
from django.utils import timezone
from datetime import timedelta, date
from django.shortcuts import redirect
from datetime import datetime
from .models import apiKey
from .forms import apiKeyForm
from django.contrib.auth.decorators import login_required

import logging

logger = logging.getLogger(__name__)

@login_required
def home(request):
    """Renders the home page."""
    assert isinstance(request, HttpRequest)
    logger.debug('home')
    return render(
        request,
        'app/index.html',
        {
            'title':'Accueil',
            'year':datetime.now().year,
        }
    )

@login_required
def manage_key(request):
    if request.method == "POST":
        form = apiKeyForm(request.POST)
        if form.is_valid():
            apiKey.objects.all().delete()
            key = form.save(commit=False)
            key.date_creation = datetime.now()
            current_year = datetime.now().year
            now = datetime.now()
            key.date_expiration = datetime(current_year + 1, now.month, now.day, now.hour, now.minute, now.second)
            key.save()
            return redirect('manage_key')
    else:
        form = apiKeyForm()
    keys = apiKey.objects.all()
    return render(
        request,
        'app/manage_key.html',
        {
            'keys': keys,
            'form': form,
            'year':datetime.now().year,
        }
    )

def delete_key(request):
    if request.method == "POST":
        key_value = request.POST.get('api_key')
        nb_del, _ = apiKey.objects.get(api_key=key_value).delete()
    return redirect('manage_key')

@login_required
def support(request):
    """Render the Support page."""
    assert isinstance(request, HttpRequest)
    logger.debug('support')
    return render(
        request,
        'app/support.html',
        {
            'title': 'Support',
            'message': '',
        }
    )


def solver(cases):
	with open("codejam-b-large.out", "w") as f:
		for i, c in enumerate(cases, start=1):
			f.write("Case #%d: %d\n" % (i, helper(c)))
		f.close()

def helper(stack):
	flips = stack.count("+-") * 2
	if stack[0] == "-":
		flips += 1
	return flips

if __name__ == "__main__":
	with open('B-large.in', 'r') as f:
		f.readline()
		cases = f.readlines()
		solver(cases)
		f.close()


from datetime import datetime

from . import db

class Blacklist(db.Model):
    '''
    Model to keep track of blacklisted tokens
    '''

    __tablename__ = 'blacklist'
    id = db.Column(db.Integer, primary_key=True)
    token = db.Column(db.String, unique=True, nullable=False)
    blacklisted_on = db.Column(db.DateTime, nullable=False, default=datetime.now())

    @classmethod
    def check_blacklist(cls, token):
        token = cls.query.filter_by(token=token).first()
        if token:
            return True
        return False


import logging
from typing import Optional, Tuple, cast

from confuse.core import ConfigView

from servicex.ConfigSettings import ConfigSettings
from servicex.utils import ServiceXException

class ServiceXConfigAdaptor:
    '''Contains the logic to extract all the configuration information needed, as driven from
    things the user has given us and program parameters. This concentrates all the complex config
    logic in on place, and, hopefully, leaves the logic out of all the other code.
    '''
    def __init__(self, config: Optional[ConfigView] = None):
        '''The config needed for the app.

        Note: The config is held onto and only queired when the information is required.

        Args:
            config (ConfigView): The config information for the app. If null, then we just use the
                                 standard servicex name.
        '''
        self._settings = config if config is not None else ConfigSettings('servicex', 'servicex')

    @property
    def settings(self) -> ConfigView:
        '''Return the config settings.

        Eventually this should not be used other than for testing!

        Returns:
            ConfigSettings: The config settings that gives us a view on everything the user wants
        '''
        return self._settings

    def get_default_returned_datatype(self, backend_type: Optional[str]) -> str:
        '''Return the default return data type, given the backend is a certian type.

        Args:
            backend_type (Optional[str]): The backend type string (`xaod`, `uproot`, etc)

        Returns:
            str: The backend datatype, like `root` or `parquet`.
        '''
        # Check to see if we know about the backend info
        if backend_type is not None:
            info = self.get_backend_info(backend_type, 'return_data')
            if info is not None:
                return info

        if self._settings['default_return_data'].exists():
            return cast(str, self._settings['default_return_data'].as_str_expanded())

        raise ServiceXException('A default default_return_data is missing from config files - is '
                                'servicex installed correctly?')

    def get_backend_info(self, backend_type: str, key: str) -> Optional[str]:
        '''Find an item in the backend info, searching first the backend settings and then
           searching the defaults.

        Args:
            backend_type (str): Backend name
            key (str): The key for the info we are after

        Returns:
            Optional[str]: Return a string for the info we are after, or return None if we can't
                           find it.
        '''

        def find_in_list(c, key) -> Optional[str]:
            if c.exists():
                for ep in c:
                    if ep['type'].exists():
                        if ep['type'].as_str() == backend_type:
                            if key in ep:
                                return ep[key].as_str_expanded()
            return None

        a = find_in_list(self._settings['api_endpoints'], key)
        a = find_in_list(self._settings['backend_types'], key) if a is None else a
        return a

    def get_servicex_adaptor_config(self, backend_type: Optional[str] = None) -> \
            Tuple[str, Optional[str]]:
        '''Return the servicex (endpoint, username, email) from a given backend configuration.

        Args:
            backend_type (str): The backend name (like `xaod`) which we hopefully can find in the
            configuration file.

        Returns:
            Tuple[str, str]: The tuple of info to create a `ServiceXAdaptor`: end point,
            token (optionally).
        '''
        # Find a list of all endpoints.
        # It is an error if this is not specified somewhere.
        endpoints = self._settings['api_endpoints']

        def extract_info(ep) -> Tuple[str, Optional[str]]:
            endpoint = ep['endpoint'].as_str_expanded()
            token = ep['token'].as_str_expanded() if 'token' in ep else None

            # We can default these to "None"
            return (endpoint, token)  # type: ignore

        # If we have a good name, look for exact match
        if backend_type is not None:
            for ep in endpoints:
                if ep['type'].exists() and ep['type'].as_str_expanded() == backend_type:
                    return extract_info(ep)

        # See if one is unlabeled.
        log = logging.getLogger(__name__)
        for ep in endpoints:
            if not ep['type'].exists():
                if backend_type is None:
                    log.warning('No backend type requested, '
                                f'using {ep["endpoint"].as_str_expanded()} - please be explicit '
                                'in the ServiceXDataset constructor')
                else:
                    log.warning(f"No '{backend_type}' backend type found, "
                                f'using {ep["endpoint"].as_str_expanded()} - please add to '
                                'the configuration file (e.g. servicex.yaml)')
                return extract_info(ep)

        if backend_type is not None:
            # They have a labeled backend, and all the end-points are labeled. So that means
            # there really is not match. So throw!
            seen_types = [str(ep['type'].as_str_expanded()) for ep in endpoints
                          if ep['type'].exists()]
            raise ServiceXException(f'Unable to find type {backend_type} '
                                    'in .servicex configuration file. Saw only types'
                                    f': {", ".join(seen_types)}')

        # Nope - now we are going to have to just use the first one there.
        for ep in endpoints:
            log.warning('No backend type requested, '
                        f'using {ep["endpoint"].as_str_expanded()} - please be explicit '
                        'in the ServiceXDataset constructor')
            return extract_info(ep)

        # If we are here - then... it just isn't going to work!
        raise ServiceXException('Not even a default set of configurations are here! Bad install '
                                ' of the servicex package!')


from math import pi, exp

from config import *

sqrt_pi = pi ** 0.5

def gaussian(x, mu, sigma):
    return exp(-(x - mu) ** 2 / (2 * sigma ** 2)) / (sqrt_pi * sigma)

def gaussian_maximum_likelihood(category, n_category, dim, n_dim, mu=None, sigma=None):

    if mu is None:
        mu = [0 for _ in range(n_category)]
        for c in range(n_category):
            mu[c] = sum([_x[dim] for _x in category[c]]) / len(category[c])

    if sigma is None:
        sigma = [0 for _ in range(n_category)]
        for c in range(n_category):
            sigma[c] = sum([(_x[dim] - mu[c]) ** 2 for _x in category[c]]) / (len(category[c]) - 1)

    def func(_c):
        def sub(_x):
            return gaussian(_x, mu[_c], sigma[_c])
        return sub

    return [func(_c=c) for c in range(n_dim)]

def estimate(x, xy_zip, category, lb=1, func=None, discrete_data=None):
    """
    :param x:               input matrix     :  x = (x1, ..., xn)                       (xi is a vector)
    :param xy_zip:          list             :  list(zip(x, y))
           y:               target vector    :  y = (ω1, ..., ωn)                       (ωi = 1, ..., m)(i = 1, ..., n)
    :param category:        list             :  [ [x that belongs to ωi] ]              (len(category) = m)
    :param lb:              lambda           :  lambda = 1 -> Laplace Smoothing
    :param func:            function         :  None or func(x, tar_category) = p(x|tar_category)
    :param discrete_data:   list             :  If ωi is discrete, discrete_data[i] = n_possibilities
                                                else, discrete_data[i] = None or pre_configured_function
    :return:                function         :  func(x, tar_category) = p(x|tar_category)
    """

    n_category = len(category)
    n_dim = len(discrete_data)

    # Prior probability
    p_category = [0 for _ in range(n_category)]
    for w, x_lst in enumerate(category):
        p_category[w] = (len(x_lst) + lb) / (len(x) + lb * n_category)

    if func is None:
        data = [None for _ in range(n_dim)]
        for dim, n_possibilities in enumerate(discrete_data):
            if not isinstance(n_possibilities, int):
                if n_possibilities is None:
                    data[dim] = gaussian_maximum_likelihood(category, n_category, dim, n_dim, MU[dim], SIGMA[dim])
                else:
                    data[dim] = n_possibilities(category, n_category, dim, n_dim)
            else:
                new_category = [[0 for _ in range(n_possibilities)] for _ in range(n_category)]
                for xx, yy in xy_zip:
                    new_category[yy][xx[dim]] += 1
                data[dim] = [[
                     (new_category[c][p] + lb) / (len(category[c]) + lb * n_possibilities)
                     for p in range(n_possibilities)] for c in range(n_category)
                ]

        def func(input_x, tar_category):
            rs = 1
            for d, _x in enumerate(input_x):
                if discrete_data[d] is None:
                    rs *= data[d][tar_category](_x)
                else:
                    rs *= data[d][tar_category][_x]
            return rs * p_category[tar_category]

    return func

def predict(x, func, categories):
    m_arg, m_possibility = 0, 0
    for i, category in enumerate(categories):
        p = func(x, category)
        if p > m_possibility:
            m_arg, m_possibility = i, p

    return m_arg


#!/usr/bin/env python3
import eval_utils
import conlleval_py
import os

import shutil
from collections import OrderedDict
import argparse

def read_sentence(ip_file):
	sentences=[]
	current_sentence = []
	for line in open(ip_file):
		line=line.strip()

		if line=="" and len(current_sentence)>0:
			sentences.append(current_sentence)

			current_sentence=[]
			continue
		line_values = line.split()

		if len(line_values)==2:
			current_sentence.append(line_values)

	return sentences

def print_result(eval_result, perf_file):

	result={}
	result["header"]=["", "Precision", "Recall", "F1"]
	result["rows"]=[]

	over_all_result= eval_result['overall']

	by_category_result = eval_result['by_category']

	for entity in sorted(by_category_result):
		l = [entity, by_category_result[entity]["P"], by_category_result[entity]["R"], by_category_result[entity]["F1"]]
		result["rows"].append(l)

	l=["overall",over_all_result["P"],over_all_result["R"], over_all_result["F1"]]
	result["rows"].append(l)

	eval_utils.tolatex(result)
	eval_utils.save_perf_in_tex(result, perf_file)

def compare_prediction(conll_file_gold, conll_file_pred, perf_file, to_latex):

	gold_sentences = read_sentence(conll_file_gold)
	pred_sentences = read_sentence(conll_file_pred)

	pred_file= "prediction.txt"

	fout=open(pred_file,"w")

	for gold_sent_index in range(len(gold_sentences)):
		gold_sent_info =  gold_sentences[gold_sent_index]
		pred_sent_info = pred_sentences[gold_sent_index]

		for word_index in range(len(gold_sent_info)):
			gold_word_info = gold_sent_info[word_index]
			pred_word_info = pred_sent_info[word_index]

			word=gold_word_info[0]
			gold_tag=gold_word_info[1]
			pred_tag=pred_word_info[1]
			base_tag = gold_tag.replace("I-","").replace("B-","")
			op_line=word+" "+base_tag+" "+gold_tag+" "+pred_tag+"\n"
			fout.write(op_line)
		fout.write("\n\n")
	fout.write("\n\n")
	fout.close()

	eval_result = conlleval_py.evaluate_conll_file(inputFile=pred_file)

	if to_latex:
		print_result(eval_result, perf_file)

	os.remove(pred_file)

def evaluate(input_gold_folder="../../data/test_data/Standoff_Format/", input_pred_folder="../baseline_CRF/Standoff_Outputs/", to_latex=False, pref_file=None):
	conll_folder_gold = "Conll_Format_Data/gold/"
	conll_file_gold = 'Conll_Format_Data/gold.txt'

	conll_folder_pred = "Conll_Format_Data/pred/"
	conll_file_pred = 'Conll_Format_Data/pred.txt'

	eval_utils.preprocess_data_to_merge(input_gold_folder, conll_folder_gold, conll_file_gold,input_pred_folder, conll_folder_pred, conll_file_pred)

	compare_prediction(conll_file_gold, conll_file_pred, pref_file, to_latex)

	shutil.rmtree('Conll_Format_Data/')

if __name__ == '__main__':
	parser = argparse.ArgumentParser()

	parameters_eval = OrderedDict()

	parser.add_argument(
	    "-gold_data", default="../../data/test_data/Standoff_Format/",
	    help="Standoff_Format gold labeled files"
	)

	parser.add_argument(
	    "-pred_data", default="../baseline_CRF/Standoff_Outputs/",
	    help="Standoff_Format prediction files"
	)

	parser.add_argument(
	    "-perf_file", default="performance.tex",
	    help="Output file to store the final latex table"
	)

	parser.add_argument(
	    "-to_latex", default="0",
	    help="if print in latex format (1 to enable, 0 to disable)"
	)

	opts = parser.parse_args()

	parameters_eval["gold_data"]=opts.gold_data
	parameters_eval["pred_data"]=opts.pred_data
	parameters_eval["perf_file"]=opts.perf_file

	if opts.to_latex=="0":
	    parameters_eval["print_latex_format"]=False
	else:
	    parameters_eval["print_latex_format"]=True

	input_gold_folder = parameters_eval["gold_data"]

	input_pred_folder = parameters_eval["pred_data"]

	print_latex_format=parameters_eval["print_latex_format"]

	perf_file = parameters_eval["perf_file"]

	evaluate(input_gold_folder, input_pred_folder, print_latex_format, perf_file)


from PIL import ImageGrab
from pynput.keyboard import Key, Controller
import time
Keyboard = Controller()

uniy1=148
uniy2=150
presstime=.06

def countdown(sec):

    while sec > 0:
        print(sec)
        time.sleep(1)
        sec-=1

def grabdat():
    countdown(3)

    #leftA = ImageGrab.grab(bbox=(1090,uniy1,1092,uniy2))
    downA = ImageGrab.grab(bbox=(1280,uniy1,1282,uniy2))
    #upA = ImageGrab.grab(bbox=(1455,uniy1,1457,uniy2))
    #rightA = ImageGrab.grab(bbox=(1640,uniy1,1642,uniy2))
    return downA

grab = True

if grab:
    RefD= grabdat()

countdown(1)

while True:
    #leftA = ImageGrab.grab(bbox=(1090,uniy1,1092,uniy2))
    downA = ImageGrab.grab(bbox=(1280,uniy1,1282,uniy2))
    #upA = ImageGrab.grab(bbox=(1455,uniy1,1457,uniy2))
    #rightA = ImageGrab.grab(bbox=(1640,uniy1,1642,uniy2))

    if not(downA==RefD):
        print("down")
        Keyboard.press(Key.down)
        time.sleep(presstime)
        Keyboard.release(Key.down)

'''
while True:
    time.sleep(.01)
    leftA = ImageGrab.grab(bbox=(1090,uniy1,1100,uniy2))
    downA = ImageGrab.grab(bbox=(1280,uniy1,1290,uniy2))
    upA = ImageGrab.grab(bbox=(1455,uniy1,1465,uniy2))
    rightA = ImageGrab.grab(bbox=(1640,uniy1,1650,uniy2))

    leftA.save("leftA.jpg")
    rightA.save("rightA.jpg")
    upA.save("upA.jpg")
    downA.save("downA.jpg")

    if not(filecmp.cmp("leftA.jpg",".Refleft.jpg")):
        #print("left")
        Keyboard.press(Key.left)
        time.sleep(presstime)
        Keyboard.release(Key.left)
    if not(filecmp.cmp("rightA.jpg",".Refright.jpg")):
        #print("right")
        Keyboard.press(Key.right)
        time.sleep(presstime)
        Keyboard.release(Key.right)
    if not(filecmp.cmp("upA.jpg",".Refup.jpg")):
        #print("up")
        Keyboard.press(Key.up)
        time.sleep(presstime)
        Keyboard.release(Key.up)
    if not(filecmp.cmp("downA.jpg",".Refdown.jpg")):
        #print("down")
        Keyboard.press(Key.down)
        time.sleep(presstime)
        Keyboard.release(Key.down)

'''


import re
import urllib.request

from bs4 import BeautifulSoup

def clean_html(raw_source):
    clean = re.compile("<.*?>")
    clean_text = re.sub(clean, ' ' ,raw_source)
    return clean_text

no_right_url = "https://post.naver.com/viewer/postView.nhn?volumeNo=21251585&memberNo=16485321"
data1 = urllib.request.urlopen(no_right_url).read()

yes_right_url = "https://news.naver.com/main/read.nhn?mode=LSD&mid=shm&sid1=100&oid=025&aid=0002916700"
data2 = urllib.request.urlopen(yes_right_url)

soup = BeautifulSoup(data1, "html.parser")
new_soup = BeautifulSoup(data2, "html.parser")

soup_body = soup.html.body

with open("tagRemoved.txt", mode = "w") as f:
    f.write(clean_html(str(soup_body)))
    print("tagRemoved saved")

#textList = soup.find_all("span").text
#parsed = soup.body.find('span', attrs={'class':'container'}).text
with open("wordScrap.txt", mode = "w") as f:
    textList = soup.find_all(re.compile("<([A-Z][A-Z0-9]*)\b[^>]*>(.*?)</\1>"))
    f.write(str(textList))
    #use soup.find_all(re.compile("(a|div)")) to use regular expression function
    print("wordScrap saved")

#will not work properly
with open("useBeautiful.txt", mode = "w") as f:
    filtered_h1 = soup.html.body.h1
    f.write("h1: " + filtered_h1.string)
    filtered_p = soup.html.body.div
    f.write("p: " + filtered_p.string)
    #filtered_p2 = filtered_p.next_sibling
    #f.write("p2: " + filtered_p2.string)
    print("useBeautiful saved")

#find by ID
with open("useBeautiful_withID.txt", mode = "w") as f:
    filtered_wrap = soup.find(id="wrap")
    f.write("wrap: " + str(filtered_wrap))
    filtered_body = soup.find(id="body")
    f.write("body: " + str(filtered_body))
    #filtered_p2 = filtered_p.next_sibling
    #f.write("p2: " + filtered_p2.string)
    print("useBeautiful_withID saved")

#find all tag
with open("useBeautiful_findAll.txt", mode = "w") as f:
    filtered_hyperLink = soup.find_all("a")
    for a in filtered_hyperLink:
        href = a.attrs['href']
        text = a.string
        f.write(str(text) + " > " + str(href) + "\n")
    f.write("\n\n")
    print("useBeautiful_findAll saved")

#test
with open("useBeautiful_findAllImg.txt", mode = "w") as f:
    filtered_src = soup.findAll('img')
    for src in filtered_src:
        try:
            print(a.attrs['src'])
        except:
            print("attribution does not match")
        v = src.get('src', src.get('dfr-src'))
        f.write(str(v)+ "\n")
        if v is None:
            continue
    f.write("\n\n")
    print("useBeautiful_findAllImg saved")

#this will not work - use data frame
with open("scraping b.txt", mode = "w") as f:
    filtered_text = soup.find_all("b")
    f.write("text: " + str(filtered_text))
    """
    values = [(p.find('b').string, p.find('span').string)
             for p in soup.find_all('p', class_='info')]
    value_df = pandas.DataFrame.from_items(values)

    or use

    pandas.DataFrame
    """
    print("scraping b saved")

with open("selectUse.txt", mode = "w") as f:
    start = soup.select("#cont")
    end = start[0].findAll('div', attrs={'class' : 'SEDOC-1560934137262--1172937716'})
    f.write("text: " + str(end))
    print("selectUse saved")

with open("New_soup.txt", mode = "w") as f:
    start = new_soup.select_one("#wrap")
    #<[^>]*>|(.)
    pattern1 = re.compile(']*>(.+)
]*')
    pattern2 = re.compile("<[^>]*>|(.)")
    text_set = pattern1.findall(str(start))
    text_set = ''.join(text_set)
    final_string = pattern2.findall(str(text_set))
    final_string = ''.join(final_string)
    print(type(final_string))
    f.write(final_string)

with open("New_soup.txt", mode = "w") as f:
    start = new_soup.select_one("#wrap")
    #<[^>]*>|(.)
    pattern1 = re.compile(']*>(.+)
]*')
    pattern2 = re.compile("<[^>]*>|(.)")
    text_set = pattern1.findall(str(start))
    text_set = ''.join(text_set)
    final_string = pattern2.findall(str(text_set))
    final_string = ''.join(final_string)
    print(type(final_string))
    f.write(final_string)


from odoo import models, fields, api, _
from datetime import datetime, timedelta
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
import pytz

class ImportLeave(models.TransientModel):

    _name = 'import.leave'
    _description = "Import Leave"

    name = fields.Char('File name')
    file = fields.Binary('File')
    state = fields.Selection([('init', 'init'), ('done', 'done')],
                             string='Status', readonly=True, default='init')
    type = fields.Selection([("xlsx", "XLSX")],
                            default="xlsx", string="File type.")
    operation = fields.Selection(
        [('create', 'Create Record'), ('update', 'Update Record')],
        default='create')

    def import_data_through_cron_leave(self):
        self.ensure_one()
        cron_obj = self.env['ir.cron']
        now_time = datetime.now() + timedelta(seconds=1)
        leave_master = self.env['import.leave.master'].create({
            'file': self.file,
            'filename': self.name,
            'type': self.type,
            'file_updated': True,
            'user_id': self._uid,
            'status': 'in_process',
            'operation': self.operation,
        })

        user_tz = self.env.user.tz or str(pytz.utc)
        local = pytz.timezone(user_tz)
        user_time_zone = datetime.strftime(pytz.utc.localize(
            datetime.strptime(datetime.strftime(now_time, '%Y-%m-%d %H:%M:%S'),
                              DEFAULT_SERVER_DATETIME_FORMAT)).astimezone(local),
            DEFAULT_SERVER_DATETIME_FORMAT)
        self.state = 'done'
        self.pool.get("hr.leave").import_data(self,leave_master.id)
        return {
            'name': _('Import Leave'),
            'view_type': 'form',
            'view_mode': 'form',
            'view_id': False,
            'res_model': 'import.leave',
            'domain': [],
            'context': dict(self._context, active_ids=self.ids),
            'type': 'ir.actions.act_window',
            'target': 'new',
            'res_id': self.id,
        }


#
# @lc app=leetcode id=438 lang=python
#
# [438] Find All Anagrams in a String
#
# https://leetcode.com/problems/find-all-anagrams-in-a-string/description/
#
# algorithms
# Easy (36.92%)
# Total Accepted:    116.9K
# Total Submissions: 316.2K
# Testcase Example:  '"cbaebabacd"\n"abc"'
#
# Given a string s and a non-empty string p, find all the start indices of p's
# anagrams in s.
#
# Strings consists of lowercase English letters only and the length of both
# strings s and p will not be larger than 20,100.
#
# The order of output does not matter.
#
# Example 1:
#
# Input:
# s: "cbaebabacd" p: "abc"
#
# Output:
# [0, 6]
#
# Explanation:
# The substring with start index = 0 is "cba", which is an anagram of "abc".
# The substring with start index = 6 is "bac", which is an anagram of "abc".
#
#
#
# Example 2:
#
# Input:
# s: "abab" p: "ab"
#
# Output:
# [0, 1, 2]
#
# Explanation:
# The substring with start index = 0 is "ab", which is an anagram of "ab".
# The substring with start index = 1 is "ba", which is an anagram of "ab".
# The substring with start index = 2 is "ab", which is an anagram of "ab".
#
#
#
class Solution(object):
    # Your runtime beats 52.57 % of python submissions
    def findAnagrams(self, s, p):
        if not p:
            return True
        if not s:
            return False

        sWindow, tCount = {},{}
        for ch in p:
            tCount[ch] = tCount.get(ch, 0) +1

        valid, n = 0, len(s)
        # 记录最小覆盖子串的起始索引及长度
        left, ans = 0, []
        for right, c in enumerate(s):
            # 进行窗口内数据的一系列更新
            if c in tCount:
                sWindow[c] = sWindow.get(c, 0) + 1
                if sWindow[c] == tCount[c]:
                    valid += 1
            # 在这里更新window
            while right - left + 1 >= len(p):
                if valid == len(tCount):
                    ans.append(left)

                # d 是将移出窗口的字符
                d = s[left]
                left +=1 # 左移窗口
                # 进行窗口内数据的一系列更新
                if d in tCount:
                    if sWindow[d] == tCount[d]:
                        valid -=1
                    sWindow[d] -= 1

        # 返回最小覆盖子串
        return ans

    # Your runtime beats 63.32 % of python submissions
    def findAnagrams01(self, s, p):
        """
        :type s: str
        :type p: str
        :rtype: List[int]
        """
        ls, lp = len(s), len(p)
        if lp > ls:
            return []

        det = [0] * 256
        for i in range(lp):
            det[ord(p[i])] -= 1
            det[ord(s[i])] += 1

        ans, abs_sum = [], 0
        for item in det:
            abs_sum += abs(item)

        if abs_sum == 0:
            ans.append(0)

        i = lp
        while(i< ls):
            r, l = s[i], s[i-lp]
            abs_sum = abs_sum - abs(det[ord(r)]) - abs(det[ord(l)])
            det[ord(r)] += 1
            det[ord(l)] -= 1

            abs_sum = abs_sum + abs(det[ord(r)]) + abs(det[ord(l)])
            if abs_sum == 0:
                ans.append(i - lp +1)

            i+=1

        return ans

    def isAnagrams(self, s, t):
        count_s = [0] * 256
        for ss in s:
            count_s[ord(ss)] += 1

        for tt in t:
            count_s[ord(tt)] -= 1

        for v in count_s:
            if v != 0:
                return False

        return True


import asyncio
import aiohttp
import os, time, sys

# 20 个国家的 Country Code 列表
POP20CC = ('AA AC AG AJ AM AN AO AQ AR AS '
           'AU AX BA BB BF BH BG BK CH WZ').split()

# 创建保存图片的目录
if not os.path.isdir('flags_img'):
    os.makedirs('flags_img')
IMG_DIR = os.path.join(os.getcwd(), 'flags_img')

async def get_flag(cc):
    url_tmp = ('https://www.cia.gov/library/publications/'
        'the-world-factbook/attachments/flags/{}-flag.gif')
    async with aiohttp.ClientSession() as session:
        async with session.get(url_tmp.format(cc)) as resp:
            print('----------------------')
            print(await resp.text())
    async with aiohttp.request('GET', url_tmp.format(cc)) as r:
        resp = await r.text(encoding='UNICODE')
    image = await resp.read()
    return image

@asyncio.coroutine
def download_one(cc):
    image = yield from get_flag(cc)
    path = os.path.join(IMG_DIR, '{}.png'.format(cc))
    with open(path, 'wb') as f:
        f.write(response.content)
    print(cc, end=' ', flush=True)
    return cc

def main(cc_list):
    start_time = time.time()
    loop = asyncio.get_event_loop()
    tasks = [download_one(cc) for cc in cc_list]
    wait_coro = asyncio.wait(tasks)
    res, _ = loop.run_until_complete(wait_coro)
    end_time = time.time()
    print('\n下载 {} 个国旗，耗时 {:.2f} 秒。'.format(
        len(cc_list), end_time - start_time))

if __name__ == '__main__':
    main(POP20CC)


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

"""
Simplify (AWT) CKAN JSON files to a format more suitable for data.gov.be.
"""

__author__ = "Bart Hanssens <bart.hanssens@fedict.be>"

import argparse, os, logging
import json

logging.basicConfig(filename='awt-simplify.log', level=logging.DEBUG)

def ckanparse(infile, outfile):
	"""Parse CKAN JSON file and store it in a new (simplified) JSON file."""
	logging.info('Parsing ' + str(infile))

	data = {}

	with open(infile, 'r') as f:
		d = json.load(f)
		res = d['result']

		data['title'] = res['title']
		data['body'] = ''

		if 'author' in res and res['author']:
			data['source'] = res['author']

		for k in ('contexts', 'urls', 'fmts', 'tags', 'license'):
			data[k] = set()

		if 'notes' in res and res['notes']:
			data['body'] = '\n'.join((data['body'], res['notes']))

		if 'isopen' in res and res['isopen']:
			data['license'].add('Libre')
		else:
			data['license'].add('Voir le site du fournisseur de données')

		if 'organization' in res:
			if res['organization'] and res['organization']['name']:
				data['org'] = res['organization']['name']

		if 'name' in res:
			data['contexts'].add('http://opendata.awt.be/dataset/' + res['name'])

		for r in res['resources']:
			if 'format' in r:
				data['fmts'].add(r['format'])
			if 'url' in r and r['url']:
				data['urls'].add(r['url'])

		for r in res['tags']:
			if 'name' in r:
				data['tags'].add(r['name'])

	# Copy formats to media, for additional mapping
	data['media'] = list(data['fmts'])

	# Add defaults for required fields
	if not 'org' in data:
		data['org'] = 'andere'
	if not data['body']:
		data['body'] = data['title']
	data['body'] = data['body'].strip()

	if not data['tags']:
		data['tags'] = ['']

	# make entries JSON serializable
	for k in ('contexts', 'urls', 'tags', 'fmts', 'license'):
		data[k] = list(data[k])

	with open(outfile, 'w') as f:
		json.dump(data, f, indent=4, encoding='iso-8859-1')

def main():
	parser = argparse.ArgumentParser(description='Simplify AWT CKAN JSON files')
	parser.add_argument('--indir', help='Input directory', required=True)
	parser.add_argument('--outdir', help='Output directory', required=True)

	args = parser.parse_args()

	for f in os.listdir(args.indir):
		ckanparse(os.path.join(args.indir, f), os.path.join(args.outdir, f))

if __name__ == "__main__":
	main()


# PCA method:-

import pandas as pd
from sklearn.decomposition import PCA

# load data
filename = 'indians-diabetes.data.csv'
names = ['preg', 'plas', 'pres', 'skin', 'test',
         'mass', 'pedi', 'age', 'class']

dataframe = pd.read_csv(filename, names=names)

array = dataframe.values
X = array[:, 0:8]
Y = array[:, 8]

# feature extraction
pca = PCA(n_components=3)

fit = pca.fit(X)

resultX = pca.transform(X)
print("\nResult : \n", resultX)

# summarize components
print("Explained Variance:", fit.explained_variance_ratio_)

5. machine learning/1. Data Preprocessing/4. feature selection/3. Principle Component Analysis.py


# coding: utf-8

# Deep Learning
# =============
#
# Assignment 4
# ------------
#
# Previously in `2_fullyconnected.ipynb` and `3_regularization.ipynb`, we trained fully connected networks to classify [notMNIST](http://yaroslavvb.blogspot.com/2011/09/notmnist-dataset.html) characters.
#
# The goal of this assignment is make the neural network convolutional.

# In[ ]:

# These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
from __future__ import print_function
import numpy as np
import tensorflow as tf
from six.moves import cPickle as pickle
from six.moves import range
import argparse
import regularization_nn as nn
import os
import vtk
import glob

print("Tensorflow version:", tf.__version__)

parser = argparse.ArgumentParser()
parser.add_argument('--model', help='Model file computed with regularization_train.py', required=True)
parser.add_argument('--sampleMesh', help='Evaluate an image sample in vtk format')
parser.add_argument('--sampleDir', help='Evaluate a directory with vtk files')
parser.add_argument('--out', help='Write output of evaluation', default=None, type=str)

args = parser.parse_args()

sampleMesh = args.sampleMesh
sampleDir = args.sampleDir
outfilename = args.out
model = args.model
num_labels = 8
num_features = 3 + num_labels + 4
batch_size = 1

def load_features(shape):

  try:
      print("Reading:", shape)
      reader_poly = vtk.vtkPolyDataReader()
      reader_poly.SetFileName(shape)
      # print "shape : " + shape

      reader_poly.Update()
      geometry = reader_poly.GetOutput()

      # --------------------------------- #
      # ----- GET ARRAY OF FEATURES ----- #
      # --------------------------------- #

      # *****
      # ***** Get normals (3 useful components) - already normalized *****
      normalArray = geometry.GetPointData().GetNormals()
      nbCompNormal = normalArray.GetElementComponentSize() - 1  # -1 car 4eme comp = 1ere du pt suivant

      # ***** Get distances to each mean group (nbGlicroups components) and normalization *****
      listGroupMean = list()
      for i in range(0, num_labels):
          name = "distanceGroup" + str(i)
          temp = geometry.GetPointData().GetScalars(name)
          temp_range = temp.GetRange()
          temp_min, temp_max = temp_range[0], temp_range[1]
          for j in range(0, geometry.GetNumberOfPoints()):
              if temp_max:
                  temp.SetTuple1(j, 2 * (temp.GetTuple1(j) - temp_min) / (temp_max) - 1)
              else:
                  temp.SetTuple1(j, 2 * (temp.GetTuple1(j) - temp_min) / (1) - 1)     # CHANGEEEER
          listGroupMean.append(temp)

      # ***** Get Curvatures and value for normalization (4 components) *****
      meanCurvName = "Mean_Curvature"
      meanCurvArray = geometry.GetPointData().GetScalars(meanCurvName)
      meanCurveRange = meanCurvArray.GetRange()
      meanCurveMin, meanCurveMax = meanCurveRange[0], meanCurveRange[1]
      meanCurveDepth = meanCurveMax - meanCurveMin

      maxCurvName = "Maximum_Curvature"
      maxCurvArray = geometry.GetPointData().GetScalars(maxCurvName)
      maxCurveRange = maxCurvArray.GetRange()
      maxCurveMin, maxCurveMax = maxCurveRange[0], maxCurveRange[1]
      maxCurveDepth = maxCurveMax - maxCurveMin

      minCurvName = "Minimum_Curvature"
      minCurvArray = geometry.GetPointData().GetScalars(minCurvName)
      minCurveRange = minCurvArray.GetRange()
      minCurveMin, minCurveMax = minCurveRange[0], minCurveRange[1]
      minCurveDepth = minCurveMax - minCurveMin

      gaussCurvName = "Gauss_Curvature"
      gaussCurvArray = geometry.GetPointData().GetScalars(gaussCurvName)
      gaussCurveRange = gaussCurvArray.GetRange()
      gaussCurveMin, gaussCurveMax = gaussCurveRange[0], gaussCurveRange[1]
      gaussCurveDepth = gaussCurveMax - gaussCurveMin

      # For each point of the current shape
      currentData = np.ndarray(shape=(geometry.GetNumberOfPoints(), num_features), dtype=np.float32)
      for i in range(0, geometry.GetNumberOfPoints()):

          # Stock normals in currentData
          for numComponent in range(0, nbCompNormal):
              currentData[i, numComponent] = normalArray.GetComponent(i, numComponent)

          for numComponent in range(0, num_labels):
              currentData[i, numComponent + nbCompNormal] = listGroupMean[numComponent].GetTuple1(i)

          value = 2 * (meanCurvArray.GetTuple1(i) - meanCurveMin) / meanCurveDepth - 1
          currentData[i, num_labels + nbCompNormal] = value

          value = 2 * (maxCurvArray.GetTuple1(i) - maxCurveMin) / maxCurveDepth - 1
          currentData[i, num_labels + nbCompNormal + 1] = value

          value = 2 * (minCurvArray.GetTuple1(i) - minCurveMin) / minCurveDepth - 1
          currentData[i, num_labels + nbCompNormal + 2] = value

          value = 2 * (gaussCurvArray.GetTuple1(i) - gaussCurveMin) / gaussCurveDepth - 1
          currentData[i, num_labels + nbCompNormal + 3] = value

  except IOError as e:
      print('Could not read:', shape, ':', e, '- it\'s ok, skipping.')

  # print('Full dataset tensor:', dataset.shape)
  # print('Mean:', np.mean(dataset))
  # print('Standard deviation:', np.std(dataset))
  return currentData

# Reformat into a TensorFlow-friendly shape:
# - convolutions need the image data formatted as a cube (width by height by #channels)
# - labels as float 1-hot encodings.

# In[ ]:

# in_depth = img_size[3] #zdim
# in_height = img_size[2] #ydim
# in_width = img_size[1] #xdim
# num_channels = img_size[0] #numchannels
# num_channels_labels = 1

# Reformat into a TensorFlow-friendly shape:
# - convolutions need the image data formatted as a cube (depth * width * height * channels)
# - We know that nrrd format
# - labels as float 1-hot encodings.

if sampleMesh != None:
  valid_dataset = load_features(sampleMesh)
  valid_dataset = valid_dataset.reshape(1, -1)
  batch_size = 1
else:
  vtklist = glob.glob(os.path.join(sampleDir, "*.vtk"))
  valid_dataset = []
  for vtkfile in vtklist:
    print("Reading:", vtkfile)
    valid_dataset.append(load_features(vtkfile))
  valid_dataset = np.array(valid_dataset)
  valid_dataset = valid_dataset.reshape(valid_dataset.shape[0], -1)
  batch_size = valid_dataset.shape[0]

size_features = valid_dataset.shape[1]

print('Validation set', valid_dataset.shape)

# Let's build a small network with two convolutional layers, followed by one fully connected layer. Convolutional networks are more expensive computationally, so we'll limit its depth and number of fully connected nodes.

# In[ ]:

#batch_size = 64
# patch_size = 8
# depth = 32
# depth2 = 64
# num_hidden = 256
# stride = [1, 1, 1, 1]

# def evaluate_accuracy(prediction, labels):
#   accuracy = tf.reduce_sum(tf.squared_difference(prediction, labels))
#   return accuracy.eval()

graph = tf.Graph()

with graph.as_default():

# run inference on the input data
  x = tf.placeholder(tf.float32,shape=(batch_size, size_features))

  keep_prob = tf.placeholder(tf.float32)

  #tf_valid_dataset = tf.constant(valid_dataset)
  # tf_test_dataset = tf.constant(test_dataset)

  y_conv = nn.inference(x, size_features, num_labels, keep_prob, batch_size)
  predict = tf.argmax(y_conv, 1)

# calculate the loss from the results of inference and the labels
  #loss = nn.loss(y_conv, y_)

  #accuracy_eval = nn.evaluation(y_conv, y_)

  #tf.summary.scalar(loss.op.name, loss)

  #intersection_sum, label_sum, example_sum, precision = nn.evaluation(y_conv, y_)

  #tf.summary.scalar ("Precision op", precision)

# setup the training operations
  #train_step = nn.training(loss, learning_rate, decay_steps, decay_rate)
  # setup the summary ops to use TensorBoard

  # setup the training operations
  #train_step = nn.training(loss, learning_rate, decay_steps, decay_rate)
  #train_step = nn.training(loss, learning_rate, decay_steps, decay_rate)

  # intersection_sum, label_sum, example_sum = evaluation(y_conv, y_)

  # valid_prediction = model(tf_valid_dataset)
  #cross_entropy = tf.reduce_sum(tf.squared_difference(y_conv, y_))

  #regularizers = tf.nn.l2_loss(W_fc1) + tf.nn.l2_loss(W_fc2)
  #cross_entropy += 0.1 * regularizers

  #cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(y_conv, y_))
  #train_step = tf.train.GradientDescentOptimizer(1e-4).minimize(cross_entropy)

  # accuracy = cross_entropy

  # valid_prediction = model(tf_valid_dataset)
  # evaluation(valid_prediction)
  # test_prediction = model(tf_test_dataset)

  with tf.Session() as sess:
    sess.run(tf.initialize_all_variables())
    saver = tf.train.Saver()
    saver.restore(sess, model)

    pred = sess.run([predict], feed_dict={x: valid_dataset, keep_prob: 1})

    if outfilename != None:
      with open(outfilename, "w") as outfile:
        for pr in pred[0]:
          outfile.write(str(pr))
          outfile.write("\n")
    else:
      for pr in pred[0]:
        print(pr)

    #test_accuracy = evaluate_accuracy(test_prediction.eval(feed_dict={keep_prob: 1.0}), test_labels)
    #print("test accuracy %g"%test_accuracy)


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Orden',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('fecha', models.DateField(auto_now=True)),
            ],
        ),
        migrations.CreateModel(
            name='Producto',
            fields=[
                ('codigo', models.CharField(max_length=10, serialize=False, primary_key=True)),
                ('descripcion', models.CharField(max_length=100)),
                ('cantidad', models.IntegerField(default=0)),
                ('orden', models.ForeignKey(to='compras_app.Orden')),
            ],
        ),
        migrations.CreateModel(
            name='Proveedor',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('codigo', models.IntegerField()),
                ('nombre', models.CharField(max_length=50)),
                ('productos', models.ManyToManyField(to='compras_app.Producto')),
            ],
        ),
        migrations.AddField(
            model_name='orden',
            name='proveedor',
            field=models.ForeignKey(to='compras_app.Proveedor'),
        ),
    ]


"""CSC148 Assignment 1: Tests for Customer

=== CSC148 Fall 2019 ===
Department of Computer Science,
University of Toronto

=== Module description ===
This module contains starter code for testing the Customer class.

This code is provided solely for the personal and private use of
students taking the CSC148 course at the University of Toronto.
Copying for purposes other than this use is expressly prohibited.
All forms of distribution of this code, whether as given or with
any changes, are expressly prohibited.

Author: Jacqueline Smith

All of the files in this directory and all subdirectories are:
Copyright (c) 2019 Jacqueline Smith
"""
from store import Customer, Item

# TODO: write your test functions for Customer here

def test_customer_no_item() -> None:
    """test for customer with no item"""
    customer1 = Customer("bruce", [])
    assert customer1.name == "bruce"
    assert customer1.arrival_time == -1
    assert customer1._items == []

def test_customer_one_item() -> None:
    """check for customer with one item"""
    item1 = Item("banana",10)
    customer1 = Customer("bruce", [item1])
    assert customer1.name == "bruce"
    assert customer1.arrival_time == -1
    assert customer1._items == [item1]

def test_customer_multi_item() -> None:
    """check for customer with several items"""
    item1 = Item("banana", 10)
    item2 = Item("apple", 2)
    item3 = Item("orange", 9)
    customer1 = Customer("bruce", [item1, item2, item3])
    assert customer1.name == "bruce"
    assert customer1.arrival_time == -1
    assert customer1._items == [item1, item2, item3]

def test_customer_num_items_with_no_item() -> None:
    """check num item method with no item"""
    customer1 = Customer("bruce", [])
    assert customer1.arrival_time == -1
    assert customer1.num_items() == 0

def test_customer_num_items_with_one_item() -> None:
    """check num item method with one item"""
    item1 = Item("banana", 10)
    customer1 = Customer("bruce", [item1])
    assert customer1.num_items() == 1

def test_customer_num_items_with_multi_item() -> None:
    """check num item method with several items"""
    item1 = Item("banana", 10)
    item2 = Item("apple", 2)
    item3 = Item("orange", 9)
    customer1 = Customer("bruce", [item1, item2, item3])
    assert customer1.num_items() == 3

def test_get_item_time_with_no_item() -> None:
    """check get item time method with no item"""
    customer1 = Customer("bruce", [])
    assert customer1.get_item_time() == 0

def test_get_item_time_with_one_item() -> None:
    """check get item time method with one item"""
    item1 = Item("banana", 10)
    customer1 = Customer("bruce", [item1])
    assert customer1.get_item_time() == 10

def test_get_item_time_with_multi_item() -> None:
    """check get item time method with several items"""
    item1 = Item("banana", 10)
    item2 = Item("apple", 2)
    item3 = Item("orange", 9)
    customer1 = Customer("bruce", [item1, item2, item3])
    assert customer1.get_item_time() == 21

if __name__ == '__main__':
    import pytest
    pytest.main(['test_customer.py'])


"""MooseCanvas.py:

Here is my Canvas.

"""

__author__ = "Dilawar Singh"
__copyright__ = "Copyright 2016, Dilawar Singh"
__credits__ = ["NCBS Bangalore"]
__license__ = "GNU GPL"
__version__ = "1.0.0"
__maintainer__ = "Dilawar Singh"
__email__ = "dilawars@ncbs.res.in"
__status__ = "Development"

import sys
import random
import os

try:
    import Tkinter as tk
except ImportError as e:
    import tkinter as tk

import logging

class MooseCanvas( tk.Frame ):

    def __init__(self, root = None):

        self.canvas = tk.Canvas( root , width=800, height=800 )
        self.canvas.create_line( 0, 0, 200, 200 );

        '''
        self.xsb = tk.Scrollbar( self.canvas,
            orient="horizontal", command=self.canvas.xview
            )

        self.ysb = tk.Scrollbar( self.canvas, orient="vertical",
            command=self.canvas.yview
            )
        self.canvas.configure(
            yscrollcommand=self.ysb.set,
            xscrollcommand=self.xsb.set
            )

        self.xsb.grid(row=1, column=0, sticky="ew")
        self.ysb.grid(row=0, column=1, sticky="ns")
        # self.grid_rowconfigure(0, weight=1)
        # self.grid_columnconfigure(0, weight=1)
        '''

        # This is what enables using the mouse:
        self.canvas.bind("<ButtonPress-1>", self.move_start)
        self.canvas.bind("<B1-Motion>", self.move_move)
        # linux scroll
        self.canvas.bind("<Button-4>", self.zoomerP)
        self.canvas.bind("<Button-5>", self.zoomerM)
        # windows scroll
        self.canvas.bind("<MouseWheel>", self.zoomer)
        # self.canvas.bind( "<Key>", self.keyboard )
        self.canvas.bind( "Move", self.keyboard )
        self.canvas.bind( "<Button-1>", self.mouseCallback )
        self.canvas.grid( row = 0, column = 0, sticky = 'news' )
        # self.canvas.pack( )

    # move
    def move_start(self, event):
        self.canvas.scan_mark(event.x, event.y)

    def move_move(self, event):
        self.canvas.scan_dragto(event.x, event.y, gain=1)

    # windows zoom
    def zoomer(self, event):
        if (event.delta > 0):
            self.canvas.scale("all", event.x, event.y, 1.1, 1.1)
        elif (event.delta < 0):
            self.canvas.scale("all", event.x, event.y, 0.9, 0.9)
        self.canvas.configure(scrollregion=self.canvas.bbox("all"))

    # linux zoom
    def zoomerP(self, event):
        self.canvas.scale("all", event.x, event.y, 1.1, 1.1)
        self.canvas.configure(scrollregion=self.canvas.bbox("all"))

    def zoomerM(self, event):
        self.canvas.scale("all", event.x, event.y, 0.9, 0.9)
        self.canvas.configure(scrollregion=self.canvas.bbox("all"))

    def mouseCallback(self, event ):
        logging.info( 'Button pressed %s %s' % ( event.x, event.y ) )

    def keyboard(self, event ):
        logging.info( 'Key pressed %s' % ( event.char ) )

if __name__ == "__main__":
    root = tk.Tk()
    a = MooseCanvas( root )
    # a.plot_random_rects( )
    a.pack(fill="both", expand=True)
    root.mainloop()


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('users', '0002_studentuser_teacheruser'),
    ]

    operations = [
        migrations.CreateModel(
            name='Address',
            fields=[
                ('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),
                ('num', models.IntegerField()),
                ('street', models.CharField(max_length=100)),
                ('city', models.CharField(max_length=100)),
                ('state', models.CharField(max_length=2)),
                ('zipcode', models.CharField(max_length=5)),
            ],
        ),
        migrations.CreateModel(
            name='Certification',
            fields=[
                ('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),
                ('name', models.CharField(max_length=255)),
                ('description', models.TextField()),
            ],
        ),
        migrations.CreateModel(
            name='Course',
            fields=[
                ('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),
                ('catalog_id', models.CharField(max_length=255)),
                ('name', models.CharField(max_length=255)),
                ('description', models.TextField()),
                ('online', models.BooleanField(default=False)),
                ('weekly_work_hours', models.IntegerField()),
                ('weekly_sessions', models.IntegerField()),
                ('start_date', models.DateField()),
                ('end_date', models.DateField()),
                ('prerequisites', models.TextField()),
                ('max_num_students', models.IntegerField()),
            ],
        ),
        migrations.CreateModel(
            name='CourseCertificationRelationship',
            fields=[
                ('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),
                ('certification', models.ForeignKey(to='courses.Certification')),
                ('course', models.ForeignKey(to='courses.Course')),
            ],
        ),
        migrations.CreateModel(
            name='CourseStudentRelationship',
            fields=[
                ('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),
                ('course', models.ForeignKey(to='courses.Course')),
                ('student', models.ForeignKey(to='users.StudentUser')),
            ],
        ),
        migrations.CreateModel(
            name='CourseSubjectRelationship',
            fields=[
                ('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),
                ('course', models.ForeignKey(to='courses.Course')),
            ],
        ),
        migrations.CreateModel(
            name='Price',
            fields=[
                ('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),
                ('value', models.FloatField()),
                ('currency', models.CharField(max_length=255)),
            ],
        ),
        migrations.CreateModel(
            name='Subject',
            fields=[
                ('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),
                ('name', models.CharField(max_length=255)),
                ('description', models.TextField()),
            ],
        ),
        migrations.AddField(
            model_name='coursesubjectrelationship',
            name='subject',
            field=models.ForeignKey(to='courses.Subject'),
        ),
        migrations.AddField(
            model_name='course',
            name='cost',
            field=models.ForeignKey(to='courses.Price'),
        ),
        migrations.AddField(
            model_name='course',
            name='location',
            field=models.ForeignKey(to='courses.Address'),
        ),
        migrations.AddField(
            model_name='course',
            name='teacher',
            field=models.ForeignKey(to='users.TeacherUser'),
        ),
    ]


#!/usr/bin/python3
import sys

def safe_print_integer_err(value):
    p = False
    m = "Exception: Unknown format code 'd' for object of type 'str'\n"
    try:
        print("{:d}".format(value))
        p = True
    except (ValueError, TypeError) as m:
        print("Exception: {}".format(m), file=sys.stderr)
    return p