from base.kmeans import KMEANS
import numpy as np
from scipy.spatial import distance
import random
import warnings

class PCKmeans(KMEANS):
    distOrder = False  # valor p de la formula de la distancia de Minkowsky
    w = False  # Peso de las restricciones.

    def __init__(self, distOrder: int = 2, w: int = 1, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.w = w
        self.distOrder = distOrder

    def initialize_prototypes(self) -> list:
        """
        Inicializacion de los centroides basandonos en los veciones creados por las restricciones.
        Incializacion propuesta por los autores de PCKmeans.
        :return: list -> centroides.
        """
        # Calculamos el centro de cada vecindario (centroides de los vecindarios)
        nhCenters = np.array([self.data[nh].mean(axis=0) for nh in self.neighborhoods])
        # calculamos el tamaño de cada vecindario
        nhSizes = np.array([len(nh) for nh in self.neighborhoods])

        # Ordenamos los centroides de cada vecindario en orden decreciente.
        prototypes = nhCenters[np.argsort(nhSizes)]

        # SI hay más vecindarios(grupos de restricciones) que k
        if len(self.neighborhoods) > self.k:
            # Seleccionamos los k vecindarios(grupos de restricciones) más grandes.
            prototypes = prototypes[-self.k:]
        # SI hay menos vecindarios(grupos de restricciones) que k
        elif len(self.neighborhoods) < self.k:
            # Si no hay restriciones
            if len(self.neighborhoods) == 0:
                # Seleccionamos aleatoriamente los centroides.
                rs = np.random.RandomState()
                prototypes = self.data[rs.permutation(self.data.shape[0])[:self.k]]
            # Si hay al menos un centroide, se seleccionan aleatoriamente el resto
            else:
                rcc = self.data[np.random.choice(self.data.shape[0], self.k - len(self.neighborhoods), replace=False),
                      :]
                prototypes = np.concatenate([prototypes, rcc])

        return prototypes

    def assign_clusters(self, prototypes: list, cluster: list) -> list:
        """
        Funcion para asignar a cada instancia un cluster, se asigna el cluster que minimize la funcion objetivo

        :param prototypes: el valor actual de los centroides
        :param cluster: lista de etiquetas de asignación a cada cluster
        :return: lista de etiquetas de asignación a cada cluster actualizada
        """

        for j in range(self.maxTry):
            try:
                # Asignamos el Cluster
                r = list(range(self.data.shape[0]))
                random.shuffle(r)
                for x_i in r:
                    distances = [self.objective_function(x_i, c_i, cluster, prototypes) for c_i in range(self.k)]
                    # Distancia absoluta
                    cluster[x_i] = np.argmin(np.absolute(distances))

                #self.plot_me(cluster, prototypes)

                # Comprobacion clusters vacios.
                samplesInCLuster = np.bincount(cluster, minlength=self.k)
                emptyCluster = np.where(samplesInCLuster == 0)[0]

                if len(emptyCluster) > 0:
                    warnings.warn('PCKmeans: [W] Cluster sin instancias, reiniciando asignacion ...')
                    raise Exception()

                return cluster

            except:
                cluster = np.array([-1 for i in range(len(self.data))])
                prototypes = self.initialize_prototypes()

        return 0

    def objective_function(self, id: int, value: int, cluster: list, prototypes: list) -> float:
        """
        Funcion objetivo a minimizar, es la suma de la distanca de cada punto a un centroide junto con
        una penalización asociada a la violacion de alguna restricción

        :param id: id de la instancia sobre la que calculamos la funcion objetivo
        :param value: id del cluster al que queremos asignar la instancia
        :param cluster: lista de etiquetas de asignación a cada cluster
        :param prototypes: lista con los centroides
        :return: valor de la funcion objteivo a minimizar
        """

        # Distancia del cluster al centroide
        if self.monotonic:
            # Con restriccion de monotonia.
            dist = np.subtract(self.data[id], prototypes[value]).sum()
            # Distancia absoluta
            dist = abs(dist)
        else:
            # Sin restriccion de monotonia.
            dist = distance.minkowski(self.data[id], prototypes[value], p=self.distOrder)
            # Distancia absoluta
            dist = abs(dist)

        # Suma de W por cada restriccion que viole
        mlp = sum([self.w for element in self.mustLink[id] if cluster[element] > 0 and cluster[element] != value])
        clp = sum([self.w for element in self.cannotLink[id] if cluster[element] == value])

        return dist + mlp + clp

    def __str__(self):
        if self.monotonic:
            return "PC-MONO: K = {}".format(self.k)
        else:
            return "PC: K = {}".format(self.k)


#!/usr/bin/env python
import numpy
import sys
import matplotlib
matplotlib.use("agg") # Change to "agg" to run on FRI
from pylab import *
import tsase
import ase
import math
from numpy.linalg import inv
#from scipy import linalg as LA

def HessianEigenvalues(atomsinHessian, dr, curvatureguess):
    HM = hessian_compare(dr, atomsinHessian, curvatureguess)
    Eigenvalue, Eigenvector = numpy.linalg.eig(HM)
    return Eigenvalue, Eigenvector

def hessian_compare(d, atomsinhessian, curvatureguess):
    H = numpy.zeros((3*len(p.get_positions()), 3*len(p.get_positions())))
    pos = p.get_positions()
    for i in range(len(pos)):
        for j in range(len(pos[0])):
            if i in atomsinhessian:
                H_r = []
                pos[i][j] += d
                p.set_positions(pos)
                d1 = p.get_forces()
                pos[i][j] -= 2 * d
                p.set_positions(pos)
                d2 = p.get_forces()
                H_i = (d2 - d1)/2/d
                H_r = numpy.reshape(H_i, 3*len(p.get_positions()))
                H[3*i+j] = H_r
                pos[i][j] += d
            else:
                H_r = numpy.zeros(3*len(p.get_positions()))
                H_r[3*i+j] = curvatureguess
                H[3*i+j] = H_r
    for i in atomsinhessian:
        for j in range(3):
            H[:, int(3*i+j)] = H[int(3*i+j)]
    return(H)

def mag(a):
        return numpy.linalg.norm(a)

def gradient_descent(alpha, CC, maxstep, atomsh, curvatureguess):
    f = p.get_forces()
    step = 0
    newPos = p.get_positions()
    running = True
    while (mag(f) > CC and running):
        step += 1
        dr = p.get_forces() * alpha
        if(mag(dr) > maxstep):
            dr = maxstep*dr/mag(dr)
        p.set_positions(p.get_positions() + dr)
        f = p.get_forces()
        #print 'step:',step,'forces:', mag(f),'PE:',p.get_potential_energy()
        if(step == 1000000):
            return False
    print((mag(f)))
    e_val, e_vec = HessianEigenvalues(atomsh, 0.00000001, curvatureguess)
    for eigen in e_val:
        if(eigen + 0.0005 < 0):
            return False
    return True

def plotResults(measurement, fileNums, yLab, figSave, name):
    figure()
    xlabel("File Number")
    ylabel(yLab)
    bar(fileNums, measurement, align="center" )
    title(name)
    savefig(figSave)

numSuccesses = 0.
numFailures = 0.
numCalls = 0.
atomsh = []
for j in range(30):
    atomsh = numpy.append(atomsh, j)

for i in range(100):
    print(i)
    clusterName = "lj38-clusters/" + str(i) + ".con"
    p = tsase.io.read_con(clusterName)
    lj = tsase.calculators.lj(cutoff=3.5)
    p.center(50.0)
    p.set_calculator(lj)
    worked = gradient_descent(0.001, 0.01, 0.2, atomsh, 1000)
    if(worked):
        numSuccesses += 1
        numCalls += lj.force_calls
    else:
        numFailures += 1
    print("For file", i, "there was", lj.force_calls, "calls")
print("Average force calls:", numCalls / numSuccesses)
print("Success to failure ratio --  ", numSuccesses, ":", numFailures)
sys.exit()


import tkinter as tk
import pyautogui
import os
import datetime
import time
import pytesseract
from PIL import Image
import util

ITEM_IMAGE_WIDTH = 110
ITEM_IMAGE_HEIGHT = 170
INCREASE_X = 195
INCREASE_Y = 235
START_X = 158
START_Y = 195
GAME_WIDTH = 2560
GAME_HEIGHT = 1600

def start():
    # 创建窗口
    window = tk.Tk()
    window.title("切图工具")
    # 窗口定位到屏幕中间位置
    screen_width = window.winfo_screenwidth()
    screen_height = window.winfo_screenheight()
    x = int((screen_width - 500) / 2)
    y = int((screen_height - 400) / 2)
    window.geometry("500x400+{}+{}".format(x, y))

    cute_btn = tk.Button(window, text="开始切图", command=cute)
    cute_btn.place(relx=0.5, rely=0.5, anchor="center")

    # 进入消息循环
    window.mainloop()

def cute():
    screenshot()
    download_folder = os.path.join(os.path.expanduser("~"), "Downloads/vision")
    im = Image.open(download_folder + "/temp.png")
    x = 760
    y = 1300
    for i in range(8):
        for j in range(5):
            x = START_X + INCREASE_X * i
            y = START_Y + INCREASE_Y * j
            box = (x, y, x + ITEM_IMAGE_WIDTH, y + ITEM_IMAGE_HEIGHT)
            region = im.crop(box)
            region.save(os.path.join(download_folder, f"{i}_{j}.png"))
    pyautogui.alert(title="提示", text="完成")

def screenshot():
    download_folder = os.path.join(os.path.expanduser("~"), "Downloads/vision")
    if not os.path.exists(download_folder):
        os.makedirs(download_folder)
    # 指定坐标位置
    location = util.get_game_location()
    if location is None:
        return
    x = location[0]
    y = location[1]
    screenshot_pic = pyautogui.screenshot(
        region=(x, y, GAME_WIDTH, GAME_HEIGHT))
    screenshot_pic.save(os.path.join(download_folder, "temp.png"))
    print("截图生成成功")

start()


import sys
def backtrack(idx, k):
    if k == n//2:
        global res
        start, link = 0, 0
        for i in range(n):
            for j in range(n):
                if isused[i] and isused[j]:
                    start += graph[i][j]
                elif not isused[i] and not isused[j]:
                    link += graph[i][j]
        res = min(res, abs(start - link))
        return
    for i in range(idx, n):
        if not isused[i]:
            isused[i] = 1
            backtrack(i+1, k+1)
            isused[i] = 0

n = int(input())
graph = [list(map(int, sys.stdin.readline().split())) for _ in range(n)]
isused = [0] * (n)
res = 100000000
backtrack(0, 0)
print(res)


import torch
import torch.nn as nn
import numpy as np
from PIL import Image
from wand.image import Image, Color
from itertools import chain
from utils import e2eKRR, createSyntheticData, remap, griddify, shape_to_rect, grid_to_mesh
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import matplotlib.pyplot as plt

def repr_fig6_plotly(num_data_points=10, num_epochs=2000):
    # check for cuda
    device = 'cuda' if torch.cuda.is_available() else 'cpu'
    #device = 'cpu'
    print('Using {} device'.format(device))

    _,ranges,data_x,data_y_h1, data_y_h2 = createSyntheticData(num_data_points)
    data_x = data_x.to(device)
    data_y_h1 = data_y_h1.to(device)
    data_y_h2 = data_y_h2.to(device)*1.0
    data_y_h1 = data_y_h1.to(device)*1.0

    # calculating the models for constructing h1 and h2 functions.
    first_layer_poly_kernel_degree = 2
    model_comp_h1_v1 = e2eKRR(data_x, data_y_h1, ranges, first_layer_poly_kernel_degree, device, num_epochs, model_path='model_ckpt.pth', save_model=True, retain_layer_outputs=True)
    layer_outputs = model_comp_h1_v1.layer_outputs

    l0_out = layer_outputs[0].detach() # layer 0 outputs
    l0_out = l0_out.cpu().detach().numpy()

    x = data_x[:, 0].cpu().detach().numpy()
    y = data_x[:, 1].cpu().detach().numpy()
    z = data_y_h1[:,0].cpu().detach().numpy()
    intensity = remap(z, np.min(z), np.max(z), 0.0, 1.0)

    l0_x = l0_out[:, 0]
    l0_y = l0_out[:, 1]

    fig = make_subplots(
    rows=1, cols=2,
    specs=[[{'type': 'mesh3d'}, {'type': 'mesh3d'}],
           ])

    mesh_plot_00 = go.Mesh3d(x=x, y=y, z=z,
                    alphahull=5,
                    opacity=1.0,
                    color='cyan',
                    colorscale=[[0.0, 'blue'],
                                [0.5, 'magenta'],
                                [1.0, 'green']],
                    intensity = intensity
                    )

    mesh_plot_01= go.Mesh3d(x=l0_x, y=l0_y, z=z,
                    alphahull=5,
                    opacity=1.0,
                    color='cyan',
                    colorscale=[[0.0, 'blue'],
                                [0.5, 'magenta'],
                                [1.0, 'green']],
                    intensity = intensity
                    )

    fig.add_trace(mesh_plot_00, row=1, col=1)
    fig.add_trace(mesh_plot_01, row=1, col=2)

    fig.update_layout(
        title_text='Representation learning in deep kernel ridge regression',
        height=800,
        width=800*2
    )
    fig.show()

def repr_fig6_exp(num_data_points=10, num_epochs=10000):
    # check for cuda
    device = 'cuda' if torch.cuda.is_available() else 'cpu'
    #device = 'cpu'
    print('Using {} device'.format(device))

    _,ranges,data_x,data_y_h1, data_y_h2 = createSyntheticData(num_data_points)
    data_x = data_x.to(device)
    data_y_h1 = data_y_h1.to(device)
    data_y_h2 = data_y_h2.to(device)*1.0

    # calculating the models for constructing h1 and h2 functions.
    first_layer_poly_kernel_degree = 2
    model_comp_h1_v1 = e2eKRR(data_x, data_y_h1, ranges, first_layer_poly_kernel_degree, device, num_epochs, retain_layer_outputs=True)
    layer_outputs = model_comp_h1_v1.layer_outputs

    l0_out = layer_outputs[0].detach() # layer 0 outputs
    l0_out = l0_out.cpu().detach().numpy()

    # convert data_y into rgb image data
    data_y_h1 = data_y_h1.squeeze(1)
    data_y_h2 = data_y_h2.squeeze(1)
    data_y_h1_grid = np.reshape(data_y_h1, [num_data_points, num_data_points, 1])
    data_y_rgb = np.concatenate([data_y_h1_grid, data_y_h1_grid, data_y_h1_grid], 2)

    # convert array into image
    img = Image.from_array(data_y_rgb)

    # image utils for easier viewing.
    img.background_color = Color('skyblue')
    img.virtual_pixel = 'background'
    dist_img = img.clone()
    print('l0: ', l0_out, torch.min(data_x), torch.max(data_x))

    bins = num_data_points
    # NOTE: here, first index = column and second index traverse rows

    # source and dest points for experiment
    source_points = (
        (0, 0),
        (0, bins),
        (bins, 0),
        (bins, bins)
    )
    destination_points = (
        (0,0),
        (0 ,bins+2),
        (bins, 0),
        (bins, bins)
    )

    # source points = input data.
    # destination points = input data after rkhs layer to see how this layer morph the input data.
    data_x = data_x.cpu().detach().numpy()
    data_x_new = remap(data_x, np.min(data_x), np.max(data_x), 0, num_data_points)
    l0_out = remap(l0_out, np.min(l0_out), np.max(l0_out), np.min(l0_out)*(num_data_points/2), np.max(l0_out)*(num_data_points/2)) + num_data_points/2
    source_points = data_x_new
    destination_points = l0_out

    print('data_x_new', data_x, np.min(l0_out), np.max(l0_out))

    # gives the effect of zoom and pan.
    dist_img.artifacts['distort:viewport'] = '500x500-250-250'

    # prepare the args and distorting.
    order = chain.from_iterable(zip(source_points, destination_points))
    dist_args = list(chain.from_iterable(order))
    dist_img.distort('bilinear_forward', dist_args)

    #plotting...
    fig, axs = plt.subplots(2,2)
    axs[0,0].imshow(data_y_rgb)
    axs[0,1].imshow(dist_img)
    plt.show()

def repr_fig6(num_data_points=10, num_epochs=10000):
    # check for cuda
    device = 'cuda' if torch.cuda.is_available() else 'cpu'
    device = 'cpu'
    print('Using {} device'.format(device))

    _,ranges,data_x,data_y_h1, data_y_h2 = createSyntheticData(num_data_points)
    data_x = data_x.to(device)
    data_y_h1 = data_y_h1.to(device)
    data_y_h2 = data_y_h2.to(device)*1.0

    # calculating the models for constructing h1 and h2 functions.
    first_layer_poly_kernel_degree = 2
    model_comp_h1_v1 = e2eKRR(data_x, data_y_h1, ranges, first_layer_poly_kernel_degree, device, num_epochs, retain_layer_outputs=True)

    layer_outputs = model_comp_h1_v1.layer_outputs
    #print(layer_outputs)

    l0 = layer_outputs[0].detach()
    data_y_h1 = data_y_h1.squeeze(1)
    data_y_h2 = data_y_h2.squeeze(1)

    #data_y_h1 = data_y_h1.reshape([10, 10])
    mask = torch.abs(data_x - l0).less(1)
    mask = mask.sum(1).bool()
    masked_y_h1 = data_y_h1*mask

    l0_grid = l0.reshape([ int(data_x.shape[0]**(1/2)), int(data_x.shape[0]**(1/2)), data_x.shape[1]])

    print(data_y_h1.shape, data_y_h2.shape, data_y_h2.reshape(10, 10))

    data_x_grid = data_x.reshape([ int(data_x.shape[0]**(1/2)), int(data_x.shape[0]**(1/2)), data_x.shape[1]])
    dx1 = dx2 = data_x_grid[:, :, 1][:1, :].squeeze().cpu().detach().numpy()
    data_y_h1 = data_y_h1.reshape(data_x_grid.shape[:2])
    data_y_h1 = data_y_h1.cpu().detach().numpy()
    data_y_h2 = data_y_h2.reshape(data_x_grid.shape[:2])
    data_y_h2 = data_y_h2.cpu().detach().numpy()
    masked_y_h1 = masked_y_h1.reshape(data_x_grid.shape[:2])
    masked_y_h1 = masked_y_h1.cpu().detach().numpy()

    print("dx1: ", dx1,"dx2: ", dx2,"data_y_h2: ", data_y_h2, 'masked_y1: ', masked_y_h1, 'l0: ', l0, l0_grid)
    #data_y_h2 = torch.ones_like(data_y_h2)

    fig, axs = plt.subplots(2,2)

    img = data_y_h1.copy()
    A = img.shape[0] / 3.0
    w = 2.0 / img.shape[1]

    shift = lambda x: A * np.sin(2.0*np.pi*x * w)

    print(img[:,0], img.shape)

    for i in range(img.shape[0]):
        img[:,i] = np.roll(img[:,i], int(shift(i)))

    axs[0,0].imshow(data_y_h1)
    axs[0,1].imshow(data_y_h2)
    axs[1,0].imshow(masked_y_h1)
    axs[1,1].imshow(img)

    plt.subplot_tool()
    #plt.show()

    bins = num_data_points

    im = Image.fromarray(data_y_h1)
    dst_grid = griddify(shape_to_rect(im.size), bins - 1, bins -1)

    l0min = l0.min(0).values
    l0max = l0.max(0).values

    linspace_x = np.linspace(l0min[0], l0max[0], bins)
    linspace_y = np.linspace(l0min[1], l0max[1], bins)
    catgor_x = np.digitize(l0[:, 0], linspace_x)
    catgor_y = np.digitize(l0[:, 1], linspace_y)
    catgor_x = np.expand_dims(catgor_x, 1)
    catgor_y = np.expand_dims(catgor_y, 1)

    print(linspace_x.shape, catgor_x.shape, catgor_y.shape)
    catgor = np.concatenate([catgor_x, catgor_y], 1)
    catgor_grid = catgor.reshape([ int(bins**(1)), int(bins**(1)), data_x.shape[1]])

    # converting category to index
    index_grid = catgor_grid - 1
    index_grid = np.abs((index_grid >= 0)*index_grid)

    print('min&max: ', torch.min(l0_grid), torch.max(l0_grid), catgor.shape, np.min(dst_grid), dst_grid.shape, index_grid.shape)

    # TODO: Convert category to index and map them to dst_grid.
    # this will give us the grid coordinates of the transformed( transformed by our network layer ) input data grid.

    #src_grid = distort_grid(dst_grid, 1)

    mesh = grid_to_mesh(index_grid, dst_grid)

    #print('dst_grid: ', dst_grid, 'src_grid: ', src_grid, 'mesh: ', mesh, len(mesh), len(mesh[8]), len(mesh[8][0]))
    im = im.transform(im.size, Image.MESH, mesh)

    axs[1,1].imshow(np.array(im))
    plt.show()


"""
A python class to read Volume 1 and Volume 2 formatted strong motion data files
as used by the strong motion working group at GNS Science, New Zealand.
"""
import os
from obspy.core import Trace, UTCDateTime, Stream
import numpy as np

class Vol12Error(Exception): pass
"""
Raised if inconsistencies in the file reading occur.
"""

class Vol12Reader(object):
    """
    Main class containing the routines to read Volume 1 and Volume 2 records.
    """
    def __init__(self,filename=None,headonly=False,dummy=False):
        if dummy:
            self.stream = self.set_dummy()
        else:
            if not os.path.isfile(filename):
                raise Vol12Error("Can't find file %s."%filename)
            self.fn = filename
            self.f = open(self.fn, 'r')
            self.stream = Stream()
            self.headonly = headonly
            for i in xrange(3):
                self.stream += self.read_comp(self.f)
            self.f.close()

    def read_comp(self,f):
        """
        Read all time series for one sensor orientation. Can be called several
        times to read data from all three sensor orientations.
        """
        smdict = {}
        # read alphanumeric header
        f.readline()#skip one line
        a = f.readline().split()
        latitude = float(a[2])+float(a[3])/60. +float(a[4][0:-1])/(60.*60.)
        longitude = float(a[5])+float(a[6])/60.+float(a[7][0:-1])/(60.*60.)
        smdict['lat'] = latitude
        smdict['lon'] = longitude
        smdict['site'] = a[1]
        smdict['site-name'] = f.readline().rstrip()
        smdict['instrument'] = f.readline().rstrip()
        f.readline()#skip one line
        a = f.readline().split()
        site = a[1]
        for i in xrange(6): f.readline()#skip six lines
        comp = f.readline().split()[1]
        for i in xrange(3): f.readline()#skip three lines
        # read integer header
        # first line
        a = map(int,f.readline().split())
        year, month, day, hour, minute, sec = a[0:6]
        nsec, microsec = divmod(sec,10)
        microsec *= 1e5
        smdict['eventtime'] = UTCDateTime(year, month, day, hour, minute, nsec, int(microsec))
        bfyear, bfmonth = a[8:10]
        # second line
        a = map(int,f.readline().split())
        smdict['hypodep'] = a[6]
        smdict['centdep'] = a[7]
        bfday,bfhour = a[8:10]
        # third line
        a = map(int,f.readline().split())
        smdict['lilax'] = a[-4]
        smdict['compdir'] = a[-3]
        smdict['epicdist'] = a[-1]
        # fourth line
        a = map(int,f.readline().split())
        smdict['prepend'] = a[1]
        smdict['append'] = a[2]
        nptsa = a[3]
        nptsv = a[4]
        nptsd = a[5]
        bfmin,bfsec = a[8:10]
        bfnsec, bfmicrosec = divmod(bfsec,1000)
        bfmicrosec *= 1e3
        # Currently the buffer start time is not stored in Volume 2 files
        # replace it with the event time in this case
        try:
            buftime = UTCDateTime(bfyear, bfmonth, bfday, bfhour, bfmin, bfnsec, int(bfmicrosec))
        except:
            buftime = smdict['eventtime']
        listnpts = [nptsa,nptsv,nptsd]
        # read floating-point header
        f.readline() #skip one line
        a = map(float,f.readline().split())
        smdict['Ml'] = a[4]
        smdict['Ms'] = a[5]
        smdict['Mw'] = a[6]
        smdict['Mb'] = a[7]
        a = map(float,f.readline().split())
        delta = a[5]
        for i in xrange(3): f.readline() #skip three lines
        st = Stream()
        for i,npts in enumerate(listnpts):
            if npts < 1: break
            stats = {'network': '', 'delta': delta,
                     'station': site, 'location': '',
                     'starttime': buftime,
                     'npts': npts, 'calib': 1.0,
                     'sampling_rate': 1./delta, 'channel': comp,'smdict':smdict}
            if self.headonly:
                # number of full lines
                nl = npts/10
                # number of remaining entries in last line
                nr = npts%10
                # one full line contains 80 characters plus the end-of-line character
                f.read(nl*(10*8+1))
                f.read(nr*8+1)
                st.append(Trace(header=stats))
            else:
                cnt = 0
                data = []
                intv = 8
                while cnt < npts:
                    a = f.readline()
                    a = a.rstrip()
                    old = 0
                    while True:
                        val = a[old:old+intv]
                        if not val: break
                        if float(val) > 999999.:
                            data.append(0.)
                        else:
                            data.append(float(val))
                        cnt += 1
                        old += intv
                if cnt != npts:
                    raise Vol12Error("Number of samples in header inconsistent with number of samples in trace: %s"%self.fn)
                data = np.array(data)
                st.append(Trace(data,stats))

        return st

    def set_dummy(self):
        """
        Create a dummy stream object. This is used by the sm_gui.py script
        in case no data is found.
        """
        smdict = {}
        smdict['lat'] = 0.
        smdict['lon'] = 0.
        smdict['site'] = 'None'
        smdict['site-name'] = 'None'
        smdict['instrument'] = 'None'
        smdict['eventtime'] = UTCDateTime(1970, 1, 1, 0, 0, 0, 0)
        smdict['hypodep'] = 0.
        smdict['centdep'] = 0.
        smdict['lilax'] = 0.
        smdict['compdir'] = 0.
        smdict['epicdist'] = 0.
        smdict['prepend'] = 0.
        smdict['append'] = 0.
        smdict['Ml'] = 0.
        smdict['Ms'] = 0.
        smdict['Mw'] = 0.
        smdict['Mb'] = 0.
        st = Stream()
        stats = {'network': '', 'delta': 1.0,
                 'station': 'No data available', 'location': '',
                 'starttime': UTCDateTime(1970, 1, 1, 0, 0, 0, 0),
                 'npts': 100, 'calib': 1.0,
                 'sampling_rate': 1.0, 'channel': 'None','smdict':smdict}
        data = np.zeros(100)
        for i in xrange(9):
            st.append(Trace(data,stats))
        return st

if __name__ == '__main__':
    pass


import json
import demistomock as demisto
import pytest

def util_open_file(path):
    with open(path, mode='r') as f:
        return f.read()

def util_load_json(path):
    with open(path, mode='r') as f:
        return json.loads(f.read())

def test_set_email_reply():
    """Unit test
        Given
        - Email author, email recipients and email cc.
        When
        - Setting the email reply.
        Then
        - Validate that the email reply is in the correct format.
        """
    from PreprocessEmail import set_email_reply
    expected_result = util_open_file('test_data/email_reply.txt')
    result = set_email_reply('test@gmail.com', '["test1@gmail.com"]', 'test2@gmail.com', 'test',
                             [{'name': 'image.png'}])
    assert result in expected_result

EMAIL_HTML = """
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
image 1:

image 2:

On Thu, Oct 22, 2020 at 1:56 AM Avishai Brandeis <
avishai@demistodev.onmicrosoft.com> wrote:

please add multiple inline images

"""

EMAIL_HTML_NO_ALT = """

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

"""

EXPECTED_RESULT_1 = """
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
image 1:

image 2:

"""

EXPECTED_RESULT_2 = """
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
image 1:

image 2:

"""

EXPECTED_RESULT_3 = """
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
image 1:

image 2:

"""

EXPECTED_RESULT_NO_ALT = """

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

"""

@pytest.mark.parametrize(
    "email_html,entry_id_list,expected",
    [(EMAIL_HTML, [('image_1.png', '37@119')], EXPECTED_RESULT_1),
     (EMAIL_HTML, [], EXPECTED_RESULT_2),
     (EMAIL_HTML, [('image_1.png', '37@119'), ('image_2.png', '38@120')], EXPECTED_RESULT_3),
     (EMAIL_HTML_NO_ALT, [('image_1.png', '37@119'), ('image_2.png', '38@120')], EXPECTED_RESULT_NO_ALT),
     ]
)
def test_create_email_html(email_html, entry_id_list, expected):
    """
        Given
        - The email's Html representation.
        When
        1. Only one of the images were uploaded to the server hence only one entry id exists within the entry id list.
        2. None of the images were uploaded to the server -> an empty entry_id_list.
        3. All images were uploaded to the server.
        Then
        - The images' src attribute would be replaced as expected.
    """
    from PreprocessEmail import create_email_html
    result = create_email_html(email_html, entry_id_list)
    assert result == expected

def test_get_entry_id_list():
    """
        Given
        - List of the email's attachments, List of files of the email's related incident.
        When
        - building an entry id list in order to replace the email's attachments source path.
        Then
        - Ensures that only the email attachments entry id's were returned and not all files entries.
    """
    from PreprocessEmail import get_entry_id_list
    attachments = [
        {
            "description": "",
            "name": "image_1.png",
            "path": "131_dd98957a-d5c3-42e0-8a81-f3ce7fa68215",
            "showMediaFile": False,
            "type": ""
        },
        {
            "description": "",
            "name": "image_2.png",
            "path": "131_17545998-4b16-4e58-8e6c-2221ada856d4",
            "showMediaFile": False,
            "type": ""
        }
    ]
    files = [
        {
            "EntryID": "30@119",
            "Extension": "png",
            "Info": "image/png",
            "MD5": "md5",
            "Name": "attachment_1.png",
            "SHA1": "sha1",
            "SHA256": "sha256",
            "SHA512": "sha512",
            "SSDeep": "ssdeep",
            "Size": 63111,
            "Type": "PNG image data, 1209 x 398, 8-bit/color RGBA, non-interlaced"
        },
        {
            "EntryID": "34@119",
            "Extension": "png",
            "Info": "image/png",
            "MD5": "md5",
            "Name": "attachment_2.png",
            "SHA1": "4sha1",
            "SHA256": "sha256",
            "SHA512": "sha512",
            "SSDeep": "ssdeep",
            "Size": 9580,
            "Type": "PNG image data, 264 x 60, 8-bit/color RGBA, non-interlaced"
        },
        {
            "EntryID": "35@119",
            "Extension": "png",
            "Info": "image/png",
            "MD5": "md5",
            "Name": "image_1.png",
            "SHA1": "4sha1",
            "SHA256": "sha256",
            "SHA512": "sha512",
            "SSDeep": "ssdeep",
            "Size": 9580,
            "Type": "PNG image data, 264 x 60, 8-bit/color RGBA, non-interlaced"
        },
        {
            "EntryID": "36@119",
            "Extension": "png",
            "Info": "image/png",
            "MD5": "md5",
            "Name": "image_2.png",
            "SHA1": "4sha1",
            "SHA256": "sha256",
            "SHA512": "sha512",
            "SSDeep": "ssdeep",
            "Size": 9580,
            "Type": "PNG image data, 264 x 60, 8-bit/color RGBA, non-interlaced"
        }]
    expected = [('image_1.png', '35@119'), ('image_2.png', '36@119')]
    assert expected == get_entry_id_list(attachments, files)

FILES = [
    {
        "SHA256": "SHA256"
    },
    {
        "EntryID": "4@131",
        "Extension": "png",
        "Info": "image/png",
        "MD5": "605ebf7bc83a00840a3ea90c8ed56515",
        "Name": "image_1.png",
        "SHA1": "SHA1",
        "SHA256": "SHA256",
        "SHA512": "SHA512",
        "SSDeep": "SSDeep",
        "Size": 127884,
        "Type": "PNG image data, 275 x 184, 8-bit/color RGBA, non-interlaced"
    },
    {
        "SHA256": "SHA256"
    },
    {
        "EntryID": "5@131",
        "Extension": "png",
        "Info": "image/png",
        "MD5": "fe96373473915fea94980b588de5fbb6",
        "Name": "image_1.png",
        "SHA1": "SHA1",
        "SHA256": "SHA256",
        "SHA512": "SHA512",
        "SSDeep": "SSDeep",
        "Size": 107596,
        "Type": "PNG image data, 225 x 224, 8-bit/color RGBA, non-interlaced"
    }
]

def test_main(mocker):
    """
        Given
        - A new incident of type Email Communication
        When
        - An email reply to an existing incident was sent
        Then
        - Return False to drop the newly created incident and attach the relevant data to the existing
        email related incident.
    """
    import PreprocessEmail
    from PreprocessEmail import main
    incident = util_load_json('test_data/get_incident_details_result.json')
    mocker.patch.object(demisto, 'incident', return_value=incident)
    mocker.patch.object(PreprocessEmail, 'get_email_related_incident_id', return_value='123')
    mocker.patch.object(PreprocessEmail, 'get_incident_by_query',
                        return_value=[util_load_json('test_data/email_related_incident_response.json')])
    mocker.patch.object(PreprocessEmail, 'get_attachments_using_instance')
    mocker.patch.object(PreprocessEmail, 'get_incident_related_files', return_value=FILES)
    mocker.patch.object(demisto, 'results')
    main()
    assert not demisto.results.call_args[0][0]

def test_get_email_related_incident_id(mocker):
    """
        Given
        - Multiple incidents with the same identifying code
        When
        - Making a query for all incidents with a certain identifying code but with different subjects
        Then
        - Validate that the correct incident is returned (the one with the matching subject)
    """
    import PreprocessEmail
    from PreprocessEmail import get_email_related_incident_id
    mocker.patch.object(PreprocessEmail, 'get_incident_by_query',
                        return_value=[{'emailsubject': 'subject 1', 'id': '1'},
                                      {'emailsubject': 'subject 2', 'id': '2'}])
    id = get_email_related_incident_id('12345678', 'subject 2')
    assert id == '2'


import pygame
import random

# 初始化
pygame.init()

# 創建視窗
WIDTH = 1000
HIGH = 1000
screen = pygame.display.set_mode((WIDTH, HIGH))

# 標題
pygame.display.set_caption('First Game By York')

# 時間管理
clock = pygame.time.Clock()

# 遊戲幀數
FPS = 60

# 各類顏色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
ORANGE = (255, 97, 0)
Green = (255, 0, 255)
# 字體載入
font_name = pygame.font.match_font('arial')

def draw_text(surf, text, size, x, y):
    font = pygame.font.Font(font_name, size)
    text_surface = font.render(text, True, BLACK)
    text_rect = text_surface.get_rect()
    text_rect.centerx = x
    text_rect.top = y
    surf.blit(text_surface, text_rect)

def draw_health(surf, hp, x, y):
    if hp < 0:
        hp = 0
    BAR_LENGTH = 100
    BAR_HIGHT = 10
    fill = (hp/100)*BAR_LENGTH
    outline_recy = pygame.Rect(x, y, BAR_LENGTH, BAR_HIGHT)
    fill_rect = pygame.Rect(x, y, fill, BAR_HIGHT)
    pygame.draw.rect(surf, Green, fill_rect)
    pygame.draw.rect(surf, Green, outline_recy, 2)

# 物件
class Player(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((10, 10))
        self.image.fill(BLACK)
        self.rect = self.image.get_rect()
        self.rect.centerx = WIDTH / 2
        self.rect.bottom = HIGH - 10
        self.speed = 10
        self.helf = 100

    def update(self):
        key_pressed = pygame.key.get_pressed()
        if key_pressed[pygame.K_d]:
            self.rect.x += self.speed
        if key_pressed[pygame.K_a]:
            self.rect.x -= self.speed
        if key_pressed[pygame.K_w]:
            self.rect.y -= self.speed
        if key_pressed[pygame.K_s]:
            self.rect.y += self.speed

        if self.rect.right > WIDTH:
            self.rect.right = WIDTH
        if self.rect.left < 0:
            self.rect.left = 0
        if self.rect.top < 0:
            self.rect.top = 0
        if self.rect.bottom > HIGH:
            self.rect.bottom = HIGH

    def shoot(self):
        bullet = Bullet(self.rect.centerx, self.rect.top)
        all_sprites.add((bullet))
        bullets.add(bullet)

class Rock(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.n = 0
        self.width = 30
        self.high = 30
        self.image = pygame.Surface((self.width, self.high))
        self.image.fill(RED)
        self.rect = self.image.get_rect()
        self.rect.x = random.randrange(0, WIDTH - self.width)
        self.rect.y = random.randrange(-100, -40)
        self.speedy = random.randrange(2, 10)
        self.speedx = random.randrange(-2, 2)

    def update(self):
        self.rect.y += self.speedy
        self.rect.x += self.speedx
        if self.rect.top > HIGH:
            self.rect.x = random.randrange(0, WIDTH - self.width)
            self.rect.y = random.randrange(-100, -40)
            self.speedy = random.randrange(2, 10)
            self.speedx = random.randrange(-2, 2)

class Bullet(pygame.sprite.Sprite):
    def __init__(self, x, y):
        pygame.sprite.Sprite.__init__(self)
        self.n = 0
        self.width = 10
        self.high = 30
        self.image = pygame.Surface((self.width, self.high))
        self.image.fill(ORANGE)
        self.rect = self.image.get_rect()
        self.rect.centerx = x
        self.rect.bottom = y
        self.speed = -10

    def update(self):
        self.rect.y += self.speed
        if self.rect.bottom < 0:
            self.kill()

# 物件群組，所有物件聽命於此
all_sprites = pygame.sprite.Group()
rocks = pygame.sprite.Group()
bullets = pygame.sprite.Group()
players = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
players.add(player)
for i in range(20):
    rock = Rock()
    all_sprites.add(rock)
    rocks.add(rock)

# 遊戲狀態
running = True
# 遊戲迴圈

score = 0

while running:
    clock.tick(FPS)  # 遊戲FPS
    # 取得輸入
    for event in pygame.event.get():  # 如果點擊右上角的叉叉則結束遊戲
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                player.shoot()
    # 更新遊戲
    all_sprites.update()
    hits = pygame.sprite.groupcollide(rocks, bullets, True, True)
    for hit in hits:
        score += 100
        r = Rock()
        all_sprites.add(r)
        rocks.add(r)

    hits = pygame.sprite.groupcollide(players, rocks, False, True)
    for hit in hits:
        player.helf -= 10
        if player.helf <= 0:
            running = False

    # 畫面顯示
    screen.fill(WHITE)
    all_sprites.draw(screen)
    draw_text(screen, str(score), 18, WIDTH / 2, 10)
    draw_health(screen, player.helf, 5, 10)
    pygame.display.update()

# 遊戲結束
pygame.quit()


# coding: utf-8

# In 3c66b paper, equation for total residual (1). Try setting phi and theta_n equal to 0, and orbital inclination angle equal to 90', for edge-on. Try to find maximum amplitude? (Also need to calculate amplitudes A (9) and B (10). For now set eccentricity to 0, eventually add it in cuz life's not always circular.

import numpy as np
import scipy as sci
import astropy.constants as const

map = np.transpose(np.genfromtxt("11yr_skymap_v4.txt", skip_header=1))

#raj = input("Raj: ")
#dec = input("Dec: ")

ul_col = map[3]
theta_col = map[1]
phi_col = map[2]

"""
theta_dict = {}
for i in range(len(phi_col)):
    #print(theta_col[i])
    if not theta_col[i] in theta_dict:
        theta_dict[theta_col[i]] = {}
    theta_dict[theta_col[i]][phi_col[i]] = ul_col[i]
    #print(theta_dict[theta_col[i]][phi_col[i]])
print(theta_dict)
"""

theta_dict = {}
#for i in range(len(map[4])):
for i in range(10):
    theta_dict.setdefault(theta_col[i], {})[phi_col[i]] = ul_col[i]
print(theta_dict)

def convert_angles(raj, dec):
    # For now
    return raj, dec

def binary_search(array, value):
    mid = (len(array))/2
    if value == array[mid]:
        return mid
    elif len(array) < 2:
        return array
    elif value > array[mid]:
        return binary_search(array[mid:], value)
    elif value < array[mid]:
        return binary_search(array[:mid], value)

def find_ul(theta, phi):
    target_theta = theta
    target_phi = phi

    theta_array = np.array(list(theta_dict.keys()))
    #print(theta_array)

    theta_arg = np.argmin(abs(theta_array - target_theta))
    best_theta = theta_array[theta_arg]
    print("The closest theta value to {0}, is {1}".format(theta, best_theta))
    #print(theta_dict)
    #print(theta_dict[best_theta])

    phi_array = np.array(list(theta_dict[best_theta].keys()))
    phi_arg = np.argmin(abs(phi_array - target_phi))
    best_phi = phi_array[phi_arg]
    print("The closest phi value to {0}, given theta ~ {1}, is {2}".format(target_phi, best_theta, best_phi))

    print("Given the best values of theta and phi, the continuous source upper limit in the region given is: {0}".format(theta_dict[best_theta][best_phi]))
    #for theta, phi in theta_dict.items():
        #print(phi)
        #print(np.array(list(phi.keys())))
        #print(np.array(list(phi.values())))

    #for theta in theta_dict.items
    #nested = list(theta_dict.values())
    #print(nested)

    #phi_array = nested.keys()

    #ul_array = phi_array(list(phi_array.values()))
    #dist_theta = abs(ul_array - target_phi)
    #arg = np.argmin(dist_theta)
    #answer(k[arg])
    #return binary_search(theta_row, theta)

def strain_approx(Distance, Radius, Frequency, Mass):
    return (32*(np.pi**2)*const.G.value)/(Distance*const.c.value**4)* Mass*(Radius**2)*(Frequency**2)

print(strain_approx(4.5e20, 20, 1/(1.05*3.154e+7), 6e30))

find_ul(.2, .3)


"""functions for cleaning lfb data"""

import pandas as pd
from datetime import datetime

def convert_date_time(df):
    """convert time to time stamp object"""
    df['DDDateTimeOfCall'] = df['DDDateTimeOfCall'].apply(str)
    df['DDDateTimeOfCall'] = df["DDDateTimeOfCall"].apply(lambda x: datetime.strptime(x,"%Y-%m-%d %H:%M:%S"))
    return df

def drop_columns(df):
    """remove columns that are noisy or do not provide useful information"""
    df = df.drop('IncidentType', 1)
    df = df.drop('FireInvestigationAttendanceID', 1)
    df = df.drop('LocationOfFirestartOther', 1)
    df = df.drop('OrganisationName', 1)
    df = df.drop('maincausemodel', 1)
    df = df.drop('maincauseappliancemanufacturerother', 1)
    return df

def drop_rows(df):
    """remove rows that are not geolocated"""
    df = df[df['PropertyClass'].notnull()]
    df = df[df['PropertyCategory'].notnull()]
    df = df[df['ParentPropertyType'].notnull()]
    df = df[df['PropertyType'].notnull()]
    df = df[df['PostCode'].notnull()]
    df = df[df['IncGeo_BoroughCode'].notnull()]
    df = df[df['IncGeo_BoroughName'].notnull()]
    df = df[df['IncGeo_WardCode'].notnull()]
    df = df[df['IncGeo_WardName'].notnull()]
    return df

def fill_missing_values(df):
    """handle rows with incomplete or missing values"""
    df['IgnitionToDiscovery'] = df['IgnitionToDiscovery'].fillna('Not known')
    df['DiscoveryToCall'] = df['DiscoveryToCall'].fillna('Not known')
    df['Action'] = df['Action'].fillna('Not known')
    df['ActionParent'] = df['ActionParent'].fillna('None')
    df['FloorOrDeckOfOrigin'] = df['FloorOrDeckOfOrigin'].fillna(0)
    df['TenureDescription'] = df['TenureDescription'].fillna('Not \
                                                             applicable')
    df['PossibleMentalHealthIssues'] = df['PossibleMentalHealthIssues'].fillna(0)
    df['PossibleMobilityIssues'] = df['PossibleMobilityIssues'].fillna(0)
    df['EvidenceOfAlcoholConsumption'] = df['EvidenceOfAlcoholConsumption'].fillna(0)
    df['EvidenceOfPrescriptionDrugUse'] = df['EvidenceOfPrescriptionDrugUse'].fillna(0)
    df['EvidenceOfRecreationalDrugUse'] = df['EvidenceOfRecreationalDrugUse'].fillna(0)
    df['socialcarebeingreceived'] = df['socialcarebeingreceived'].fillna(0)
    df['OtherHumanFactor'] = df['OtherHumanFactor'].fillna('Not known')
    df['PropertyCoveredByRro'] = df['PropertyCoveredByRro'].fillna(0)
    df['NumPumps'] = df['NumPumps'].fillna(1)
    df['MainCause'] = df['MainCause'].fillna('Not applicable')
    df['ParentMainCause'] = df['ParentMainCause'].fillna('Motive: Not known')
    df['IgnitionSourcePower'] = df['IgnitionSourcePower'].fillna('Unknown')
    df['ParentIgnSource'] = df['ParentIgnSource'].fillna('Unknown')
    df['IgnitionSource'] = df['IgnitionSource'].fillna('Unknown')
    df['ItemFirstIgnited'] = df['ItemFirstIgnited'].fillna('Not known')
    df['ParentItemFirstIgnited'] = df['ParentItemFirstIgnited'].fillna('Other/Not known')
    df['LocationFireStarted'] = df['LocationFireStarted'].fillna('Not known')
    df['HouseholdOccupancy'] = df['HouseholdOccupancy'].fillna('Other')
    df['OccupationStatus'] = df['OccupationStatus'].fillna('Not known')
    df['CausedBy'] = df['CausedBy'].fillna('Not known')
    return df

def all_cleaning(df):
    """perform all cleaning operations"""
    df = convert_date_time(df)
    df = drop_columns(df)
    df = drop_rows(df)
    df = fill_missing_values(df)
    return df


import json
import logging
import os
import sys
from argparse import ArgumentParser

import torch
from nni.algorithms.nas.pytorch.proxylessnas import ProxylessNasTrainer
from torchvision import transforms

import datasets
from model import SearchMobileNet
from nni.algorithms.nas.pytorch.proxylessnas import ProxylessNasTrainer
from putils import LabelSmoothingLoss, accuracy, get_parameters
from retrain import Retrain

logger = logging.getLogger('nni_proxylessnas')

if __name__ == "__main__":
    parser = ArgumentParser("proxylessnas")
    # configurations of the model
    parser.add_argument("--n_cell_stages", default='4,4,4,4,4,1', type=str)
    parser.add_argument("--stride_stages", default='2,2,2,1,2,1', type=str)
    parser.add_argument("--width_stages", default='24,40,80,96,192,320', type=str)
    parser.add_argument("--bn_momentum", default=0.1, type=float)
    parser.add_argument("--bn_eps", default=1e-3, type=float)
    parser.add_argument("--dropout_rate", default=0, type=float)
    parser.add_argument("--no_decay_keys", default='bn', type=str, choices=[None, 'bn', 'bn#bias'])
    # configurations of imagenet dataset
    parser.add_argument("--data_path", default='/data/imagenet/', type=str)
    parser.add_argument("--train_batch_size", default=256, type=int)
    parser.add_argument("--test_batch_size", default=500, type=int)
    parser.add_argument("--n_worker", default=32, type=int)
    parser.add_argument("--resize_scale", default=0.08, type=float)
    parser.add_argument("--distort_color", default='normal', type=str, choices=['normal', 'strong', 'None'])
    # configurations for training mode
    parser.add_argument("--train_mode", default='search', type=str, choices=['search_v1', 'search', 'retrain'])
    # configurations for search
    parser.add_argument("--checkpoint_path", default='./search_mobile_net.pt', type=str)
    parser.add_argument("--arch_path", default='./arch_path.pt', type=str)
    parser.add_argument("--no-warmup", dest='warmup', action='store_false')
    # configurations for retrain
    parser.add_argument("--exported_arch_path", default=None, type=str)

    args = parser.parse_args()
    if args.train_mode == 'retrain' and args.exported_arch_path is None:
        logger.error('When --train_mode is retrain, --exported_arch_path must be specified.')
        sys.exit(-1)

    model = SearchMobileNet(width_stages=[int(i) for i in args.width_stages.split(',')],
                            n_cell_stages=[int(i) for i in args.n_cell_stages.split(',')],
                            stride_stages=[int(i) for i in args.stride_stages.split(',')],
                            n_classes=1000,
                            dropout_rate=args.dropout_rate,
                            bn_param=(args.bn_momentum, args.bn_eps))
    logger.info('SearchMobileNet model create done')
    model.init_model()
    logger.info('SearchMobileNet model init done')

    # move network to GPU if available
    if torch.cuda.is_available():
        device = torch.device('cuda')
    else:
        device = torch.device('cpu')

    logger.info('Creating data provider...')
    data_provider = datasets.ImagenetDataProvider(save_path=args.data_path,
                                                  train_batch_size=args.train_batch_size,
                                                  test_batch_size=args.test_batch_size,
                                                  valid_size=None,
                                                  n_worker=args.n_worker,
                                                  resize_scale=args.resize_scale,
                                                  distort_color=args.distort_color)
    logger.info('Creating data provider done')

    if args.no_decay_keys:
        keys = args.no_decay_keys
        momentum, nesterov = 0.9, True
        optimizer = torch.optim.SGD([
            {'params': get_parameters(model, keys, mode='exclude'), 'weight_decay': 4e-5},
            {'params': get_parameters(model, keys, mode='include'), 'weight_decay': 0},
        ], lr=0.05, momentum=momentum, nesterov=nesterov)
    else:
        optimizer = torch.optim.SGD(get_parameters(model), lr=0.05, momentum=momentum, nesterov=nesterov, weight_decay=4e-5)

    if args.train_mode == 'search':
        from nni.retiarii.trainer.pytorch import ProxylessTrainer
        from torchvision.datasets import ImageNet
        normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                         std=[0.229, 0.224, 0.225])
        dataset = ImageNet(args.data_path, transform=transforms.Compose([
            transforms.RandomResizedCrop(224),
            transforms.RandomHorizontalFlip(),
            transforms.ToTensor(),
            normalize,
        ]))
        trainer = ProxylessTrainer(model,
                                   loss=LabelSmoothingLoss(),
                                   dataset=dataset,
                                   optimizer=optimizer,
                                   metrics=lambda output, target: accuracy(output, target, topk=(1, 5,)),
                                   num_epochs=120,
                                   log_frequency=10)
        trainer.fit()
        print('Final architecture:', trainer.export())
        json.dump(trainer.export(), open('checkpoint.json', 'w'))
    elif args.train_mode == 'search_v1':
        # this is architecture search
        logger.info('Creating ProxylessNasTrainer...')
        trainer = ProxylessNasTrainer(model,
                                      model_optim=optimizer,
                                      train_loader=data_provider.train,
                                      valid_loader=data_provider.valid,
                                      device=device,
                                      warmup=args.warmup,
                                      ckpt_path=args.checkpoint_path,
                                      arch_path=args.arch_path)

        logger.info('Start to train with ProxylessNasTrainer...')
        trainer.train()
        logger.info('Training done')
        trainer.export(args.arch_path)
        logger.info('Best architecture exported in %s', args.arch_path)
    elif args.train_mode == 'retrain':
        # this is retrain
        from nni.nas.pytorch.fixed import apply_fixed_architecture
        assert os.path.isfile(args.exported_arch_path), \
            "exported_arch_path {} should be a file.".format(args.exported_arch_path)
        apply_fixed_architecture(model, args.exported_arch_path)
        trainer = Retrain(model, optimizer, device, data_provider, n_epochs=300)
        trainer.run()


"""
Functions used in n01_fd_comparison.py
"""

import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from pymer4.stats import perm_test, boot_func
from pymer4.utils import _sig_stars
from tqdm.auto import tqdm
from itertools import combinations
import matplotlib as mpl

mpl.rcParams["font.family"] = "Avenir"
sns.set_context("paper")

def tost_upper(x, y, bound=1, paired=False, correction=False):
    """Modified tost for just upper bound"""
    from pingouin.parametric import ttest

    x = np.asarray(x)
    y = np.asarray(y)
    assert isinstance(bound, (int, float)), "bound must be int or float."

    df_b = ttest(x - bound, y, paired=paired, correction=correction, tail="less")
    pval = df_b.at["T-test", "p-val"]
    t = df_b.at["T-test", "T"]

    # Create output dataframe
    stats = {"bound": bound, "dof": df_b.at["T-test", "dof"], "t-stat": t, "pval": pval}
    return pd.DataFrame.from_records(stats, index=["TOST"])

def format_summary_file_for_comparisons(df, exclude=[]):
    """
    Given a long format summary file add sample_ids and remove subjects without headcases from f18. Optionally exclude other subjects
    """

    subset = df.query(
        "not (headcase == 'no_case' and data_id == 'fnl_f18' and condition == 'recall')"
    ).assign(
        sample=df.data_id.map(
            {"fnl_f18": "fnl", "fnl_f17": "fnl", "sherlock": "sherlock"}
        )
    )
    if exclude:
        subset = subset.query("subject_id not in @exclude")

    return subset.reset_index(drop=True)

def get_groups(condition, measure, data, excluded=False):
    """
    Given a dataframe query it based on the desired groups and return two numpy arrays.
    """
    if condition == "view":
        if not excluded:
            expected_N = [26, 37, 17]
        else:
            expected_N = [24, 37, 17]
        has_case = data.query(
            "condition == @condition and headcase == 'has_case' and sample == 'fnl' and measure == @measure"
        ).val.values
        assert (
            len(has_case) == expected_N[0]
        ), f"Expected {expected_N[0]} found {len(has_case)}"
        no_case_fnl = data.query(
            "condition == @condition and headcase == 'no_case' and sample == 'fnl' and measure == @measure"
        ).val.values
        assert (
            len(no_case_fnl) == expected_N[1]
        ), f"Expected {expected_N[1]} found {len(no_case_fnl)}"
        no_case_sherlock = data.query(
            "condition == @condition and headcase == 'no_case' and sample == 'sherlock' and measure == @measure"
        ).val.values
        assert (
            len(no_case_sherlock) == expected_N[2]
        ), f"Expected {expected_N[2]} found {len(no_case_sherlock)}"

        return {
            "fnl_no_case": no_case_fnl,
            "sherlock_no_case": no_case_sherlock,
            "fnl_has_case": has_case,
        }

    elif condition == "recall":
        if not excluded:
            expected_N = [26, 17]
        else:
            expected_N = [24, 17]
        has_case = data.query(
            "condition == @condition and headcase == 'has_case' and sample == 'fnl' and measure == @measure"
        ).val.values
        assert (
            len(has_case) == expected_N[0]
        ), f"Expected {expected_N[0]} found {len(has_case)}"
        no_case = data.query(
            "condition == @condition and headcase == 'no_case' and sample == 'sherlock' and measure == @measure"
        ).val.values
        assert (
            len(no_case) == expected_N[1]
        ), f"Expected {expected_N[1]} found {len(no_case)}"

        return {"sherlock_no_case": no_case, "fnl_has_case": has_case}

def _mean_diff(x, y):
    "Local function used by boot_func in compare_two_samples"
    return x.mean() - y.mean()

def compare_two_samples(
    x, y, comparison_name="result", n_perm=5000, seed=0, n_jobs=-1, pval_correction=None
):
    """
    Runs non-equal variance permuted independence t-test and computed boostrapped CIs around mean difference between two arrays. Mean difference always reflects x - y. Optionally name the comparison which a column of returned single row dataframe.
    """

    # Run perm test(s)
    stat, perm_p = perm_test(
        x, y, equal_var=False, n_perm=n_perm, seed=seed, n_jobs=n_jobs
    )

    # Get condition means, sds
    x_mean, x_std = np.mean(x), np.std(x, ddof=1)
    y_mean, y_std = np.mean(y), np.std(y, ddof=1)

    # Get bootstrapped CIs around mean difference
    mean_diff, (ci_lower, ci_upper) = boot_func(
        x, y, func=_mean_diff, n_boot=n_perm, seed=seed, n_jobs=n_jobs,
    )

    return pd.DataFrame(
        {
            "comparison": comparison_name,
            "x_mean": x_mean,
            "x_std": x_std,
            "y_mean": y_mean,
            "y_std": y_std,
            "mean_diff": mean_diff,
            "ci_lower": ci_lower,
            "ci_upper": ci_upper,
            "t-stat": stat,
            "perm_p": perm_p,
            "sig": _sig_stars(perm_p),
        },
        index=[0],
    )

def calc_results_table(df, excluded=False, n_perm=5000, seed=0, n_jobs=8):
    """
    Compares all subsets of headcase comparisons across all conditions for a given dataframe and returns a dataframe of results.

    Uses:
    get_groups
    compare_two_samples

    """

    results = pd.DataFrame()
    for condition in tqdm(df.condition.unique(), desc="condition"):
        for measure in tqdm(df.measure.unique(), desc="measure", leave=False):
            groups = get_groups(condition, measure, df, excluded=excluded)
            for comparison in tqdm(
                combinations(groups.keys(), 2), desc="comparison", leave=False
            ):
                result = compare_two_samples(
                    groups[comparison[0]],
                    groups[comparison[1]],
                    comparison_name="__".join(comparison),
                    n_perm=n_perm,
                    n_jobs=n_jobs,
                    seed=seed,
                )
                result["condition"] = condition
                result["measure"] = measure
                results = results.append(result, ignore_index=True)
    # Sort rows
    results = results.sort_values(by=["condition", "measure"]).reset_index(drop=True)
    # Sort columns
    results = results[
        ["comparison", "condition", "measure", "sig", "perm_p"]
        + list(results.columns[1:9])
    ]
    return results

def stripbarplot(
    data,
    ax,
    condition,
    measure,
    pointcolor="black",
    order=None,
    xlabel=None,
    ylabel=None,
    yticks=[],
    yticklabels=[],
    xticks=[],
    xticklabels=[],
    colors=None,
):
    """
    Overlay a stripplot on a barplot give a matplotlib axis handle using seaborn, provided a dataframe, axis, and query on that dataframe. Optionally set other matplotlib axis properties.
    """

    subset = data.query("condition == @condition and measure == @measure")
    if subset.data_id.nunique() == 3:
        palette = sns.color_palette(colors)
    elif subset.data_id.nunique() == 2:
        palette = [sns.color_palette(colors)[0]] + [sns.color_palette(colors)[2]]

    ax = sns.barplot(
        x="data_id", y="val", order=order, data=subset, ax=ax, palette=palette
    )

    ax = sns.stripplot(
        x="data_id", y="val", order=order, color=pointcolor, data=subset, ax=ax,
    )

    if xlabel is not None:
        ax.set_xlabel(xlabel)
    if ylabel is not None:
        ax.set_ylabel(ylabel)
    if len(xticklabels):
        ax.set_xticklabels(xticklabels)
    if len(yticklabels):
        ax.set_yticklabels(yticklabels)
    if len(xticks):
        ax.set_xticks(xticks)
    if len(yticks):
        ax.set_yticks(yticks)
    _ = ax.set(
        xlabel=xlabel,
        xticklabels=xticklabels,
        ylabel=ylabel,
        yticks=yticks,
        ylim=(0, max(yticks)),
    )
    return ax

def make_comparison_figure(
    df,
    exclude=[],
    view_order=["sherlock", "fnl_f17", "fnl_f18"],
    view_order_labels=[
        "Sherlock\n(No headcase)",
        "FNL\n(No headcase)",
        "FNL\n(With headcase)",
    ],
    recall_order=["sherlock", "fnl_f18"],
    recall_order_labels=["Sherlock\n(No headcase)", "FNL\n(With headcase)"],
    measure_order=["fd_mean", "fd_median", "perc_spikes"],
    measure_labels=[
        "mean FD (mm)",
        "median FD (mm)",
        "Proportion of scans\nover FD=0.3 mm",
    ],
    color_names=["#A9A9A9", "#54c5eb", "#E6377D"],
    title_fontsize=14,
    view_range=np.arange(0, 0.5, 0.1),
    recall_range=np.arange(0, 1.1, 0.1),
    figsize=(8.5, 10),
    tight=True,
    rows=3,
    cols=2,
    **kwargs,
):
    """
    Make a 3 row by 2 column figure of all pairwise comparisons

    Uses:
    stripbarplot
    format_summary_file_for_comparisons

    """

    plotting_df = format_summary_file_for_comparisons(df, exclude=exclude)
    f, axs = plt.subplots(rows, cols, figsize=figsize, sharex=False, sharey=False)

    # Viewing
    for i, (ax, measure, label) in enumerate(
        zip(axs[:, 0], measure_order, measure_labels)
    ):
        ax = stripbarplot(
            plotting_df,
            ax,
            "view",
            measure,
            order=view_order,
            ylabel=label,
            xlabel="",
            yticks=view_range,
            xticklabels=[],
            colors=color_names,
            **kwargs,
        )
        if i == (rows - 1):
            ax.set(xticklabels=view_order_labels)
    # Talking
    for i, (ax, measure, label) in enumerate(
        zip(axs[:, 1], measure_order, measure_labels)
    ):
        ax = stripbarplot(
            plotting_df,
            ax,
            "recall",
            measure,
            order=recall_order,
            ylabel="",
            xlabel="",
            yticks=recall_range,
            xticklabels=[],
            colors=color_names,
            **kwargs,
        )
        if i == (rows - 1):
            ax.set(xticklabels=recall_order_labels)
    sns.despine()
    _ = axs[0, 0].text(
        x=0.4, y=1, s="Viewing", transform=axs[0, 0].transAxes, fontsize=title_fontsize,
    )
    _ = axs[0, 1].text(
        x=0.4, y=1, s="Talking", transform=axs[0, 1].transAxes, fontsize=title_fontsize,
    )
    if tight:
        plt.tight_layout()
    return f, axs

def calc_tost_table(
    formatted_comparisons,
    results_table,
    metrics,
    conditions,
    excluded=False,
    func=tost_upper,
):
    tost_results = pd.DataFrame()
    for metric in metrics:
        for condition in conditions:
            groups = get_groups(
                condition, metric, formatted_comparisons, excluded=excluded
            )
            y = groups["fnl_has_case"]
            x = (
                groups["fnl_no_case"]
                if condition == "view"
                else groups["sherlock_no_case"]
            )
            comparison = (
                "fnl_no_case__fnl_has_case"
                if condition == "view"
                else "sherlock_no_case__fnl_has_case"
            )
            bound = 0.05
            tost_result = func(x, y, correction=True, bound=bound)
            mean_diffs = results_table.query(
                "comparison == @comparison and condition == @condition and measure == @metric"
            ).reset_index(drop=True)[["mean_diff", "ci_lower", "ci_upper"]]
            tost_result = tost_result.assign(
                comparison=comparison,
                measure=metric,
                condition=condition,
                mean_diff=mean_diffs.mean_diff.values,
                ci_lower=mean_diffs.ci_lower.values,
                ci_upper=mean_diffs.ci_upper.values,
            )
            tost_results = tost_results.append(tost_result, ignore_index=True)
    tost_results = tost_results[
        [
            "comparison",
            "condition",
            "measure",
            "mean_diff",
            "ci_lower",
            "ci_upper",
            "bound",
            "dof",
            "pval",
        ]
    ]
    return tost_results

def make_tost_figure(
    tost_results,
    metrics=["fd_mean", "fd_median", "fd_mean_filter", "fd_median_filter"],
    conditions=["view", "recall"],
    condition_labels=["Viewing", "Talking"],
    xlims=[(-0.1, 0.1), (-0.25, 0.25)],
    tost_bounds=[(-0.05, 0.05), (-0.05, 0.05)],
    palette=None,
    markersize=10,
    linewidth=3,
    figsize=(8.6, 4.5),
):

    view_tost = (
        tost_results.query("condition == 'view'")
        .sort_values(by="measure", ascending=False)
        .reset_index(drop=True)
    )
    recall_tost = (
        tost_results.query("condition == 'recall'")
        .sort_values(by="measure", ascending=False)
        .reset_index(drop=True)
    )
    if palette is None:
        palette = [
            sns.color_palette("Reds")[3],
            sns.color_palette("Blues")[3],
            sns.color_palette("Reds")[1],
            sns.color_palette("Blues")[1],
        ]

    f, axs = plt.subplots(1, 2, figsize=figsize)

    for i, row in view_tost.iterrows():
        axs[0].plot(
            row["mean_diff"],
            0.1 + (0.1 * i),
            "o",
            markersize=10,
            color=palette[i],
            label=row["comparison"],
        )
        axs[0].hlines(
            y=0.1 + (0.1 * i),
            xmin=row["ci_lower"],
            xmax=row["ci_upper"],
            linestyle="-",
            linewidth=linewidth,
            color=palette[i],
        )

    for i, row in recall_tost.iterrows():
        axs[1].plot(
            row["mean_diff"],
            0.1 + (0.1 * i),
            "o",
            markersize=10,
            color=palette[i],
            label=row["comparison"],
        )
        axs[1].hlines(
            y=0.1 + (0.1 * i),
            xmin=row["ci_lower"],
            xmax=row["ci_upper"],
            linestyle="-",
            linewidth=linewidth,
            color=palette[i],
        )

    for i, ax in enumerate(axs):
        ax.vlines(x=tost_bounds[i][0], ymin=-1, ymax=1, linestyles="--", linewidth=2)
        ax.vlines(x=tost_bounds[i][1], ymin=-1, ymax=1, linestyles="--", linewidth=2)
        ax.vlines(x=0, ymin=-1, ymax=1, linestyles="--", linewidth=2, alpha=0.5)
        _ = ax.set(
            xlim=xlims[i],
            ylim=(0, 1),
            xlabel="",
            ylabel="",
            yticks=[],
            yticklabels=[],
            xticks=np.linspace(xlims[i][0], xlims[i][1], 5),
        )
        ax.text(
            x=0.4, y=1.07, s=condition_labels[i], transform=ax.transAxes, fontsize=14
        )
        ax.text(x=-.05, y=-0.1, s="Headcases worse", transform=ax.transAxes, fontsize=10)
        ax.text(x=.7, y=-0.1, s="Headcases better", transform=ax.transAxes, fontsize=10)

    sns.despine(left=True)
    handles, labels = plt.gca().get_legend_handles_labels()
    handles = handles[::-1]
    labels = ["FD Mean", "FD Mean (excluded)", "FD Median", "FD Median (excluded)"]
    f.legend(
        handles=handles, labels=labels, loc=(0.13, 0.87), ncol=4, prop={"size": 9},
    )
    plt.suptitle(
        "Mean Difference\n(No headcase - With headcase)",
        y=-0.08,
        x=0.52,
        fontsize=14,
        va="bottom",
        ha="center",
    )
    return f, axs


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

"""
@author OwarMag1c
@desc 客户端图形界面模块
@date 2022/3/17
说明: 展示图形界面
"""
from cgi import test
from cgitb import reset
from distutils.command.config import config
from distutils.log import error
from email import message
from ipaddress import collapse_addresses
from logging import root
import socket
from sre_parse import State
from this import s
from tkinter import *
import time
from tkinter import messagebox
import tkinter
from tkinter.tix import COLUMN
from turtle import bgcolor, window_height, window_width
import ast

LOG_LINE_NUM = 0

class tag_films_recommend_gui():
  def __init__(self, init_window_name):
    self.init_window = init_window_name
    self.tag_state = [False] * 50
    self.time_text = StringVar()
    self.time_text.set('当前时间：' + self.get_current_time())
    self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    self.socket.connect(('175.27.135.19', 9997))
    self.tag_map = {0:'恐怖', 1:'剧情', 2:'爱情', 3:'同性', 4:'动画', 5:'奇幻', 6:'战争', 7:'历史', 8:'科幻', 9:'悬疑', 10:'冒险',
      11:'音乐', 12:'喜剧', 13:'歌舞', 14:'传记', 15:'家庭', 16:'运动', 17:'惊悚', 18:'武侠', 19:'古装', 20:'儿童', 21:'灾难',
      22:'犯罪', 23:'纪录片'
    }

  # 计算窗口居中坐标
  def center_window(self, master, width, height):
    ws = master.winfo_screenwidth()
    hs = master.winfo_screenheight()
    x = (ws / 2) - (width / 2)
    y = (hs / 2) - (height / 2)
    return (x, y)

  # 标签选择命令
  def rb_command(self, tag_index):
    if(self.tag_state[tag_index]):
      self.tag_state[tag_index] = False
    else:
      self.tag_state[tag_index] = True

  # 设置标签图形
  def set_tag(self, text, command, row, column):
    self.rb = Checkbutton(self.tag_frame, text=text, command=command, relief=RAISED, height=2, width=5, bd=5, cursor='circle', font=('幼圆', 13), bg='pink')
    self.rb.grid(row=row, column=column, padx=20, pady=10)

  # 设置窗口
  def set_init_window(self, width, height):
    self.init_window.title("优质电影推荐_v0.1")           # 窗口名

    self.window_width = width
    self.window_height = height
    coordinate = self.center_window(self.init_window, self.window_width, self.window_height)
    self.init_window.geometry('%dx%d+%d+%d' % (self.window_width, self.window_height, coordinate[0], coordinate[1]))
    self.init_window.resizable(False, False)
    self.init_window['bg'] = 'pink'                                    # 窗口背景色

    # 标签
    self.title_label = Label(self.init_window, text='电  影  推  荐  系  统', bg='pink', bd=5, font=('幼圆', 35), justify=CENTER, padx=100)
    self.title_label.grid(row=0, column=2)

    self.tag_title_label = Label(self.init_window, text='TAG选择', bg='pink', bd=5, font=('幼圆', 25), justify=CENTER)
    self.tag_title_label.grid(row=1, column=2 ,padx=10)

    # TAG选择框
    self.tag_frame = Frame(width=600, height=700,bg='pink')
    self.tag_frame.grid(row=2, column=2)
    self.set_tag('恐怖', lambda: self.rb_command(0), 3, 4)
    self.set_tag('剧情', lambda: self.rb_command(1), 3, 6)
    self.set_tag('爱情', lambda: self.rb_command(2), 3, 8)
    self.set_tag('同性', lambda: self.rb_command(3), 4, 4)
    self.set_tag('动画', lambda: self.rb_command(4), 4, 6)
    self.set_tag('奇幻', lambda: self.rb_command(5), 4, 8)
    self.set_tag('战争', lambda: self.rb_command(6), 5, 4)
    self.set_tag('历史', lambda: self.rb_command(7), 5, 6)
    self.set_tag('科幻', lambda: self.rb_command(8), 5, 8)
    self.set_tag('悬疑', lambda: self.rb_command(9), 6, 4)
    self.set_tag('冒险', lambda: self.rb_command(10), 6, 6)
    self.set_tag('音乐', lambda: self.rb_command(11), 6, 8)
    self.set_tag('喜剧', lambda: self.rb_command(12), 7, 4)
    self.set_tag('歌舞', lambda: self.rb_command(13), 7, 6)
    self.set_tag('传记', lambda: self.rb_command(14), 7, 8)
    self.set_tag('家庭', lambda: self.rb_command(15), 8, 4)
    self.set_tag('运动', lambda: self.rb_command(16), 8, 6)
    self.set_tag('惊悚', lambda: self.rb_command(17), 8, 8)
    self.set_tag('武侠', lambda: self.rb_command(18), 9, 4)
    self.set_tag('古装', lambda: self.rb_command(19), 9, 6)
    self.set_tag('儿童', lambda: self.rb_command(20), 9, 8)
    self.set_tag('灾难', lambda: self.rb_command(21), 10, 4)
    self.set_tag('犯罪', lambda: self.rb_command(22), 10, 6)
    self.set_tag('纪录片', lambda: self.rb_command(23), 10, 8)

    # 推荐按钮
    self.tag_select_button = Button(self.tag_frame, text='已选TAG的交集推荐', bg='pink', bd=5, font=('幼圆', 25), justify=CENTER, cursor='circle', command=self.tag_select_button_intersection_command)
    self.tag_select_button.grid(row=24, column=6, pady=20, padx=20)

    self.tag_select_button = Button(self.tag_frame, text='已选TAG的并集推荐', bg='pink', bd=5, font=('幼圆', 25), justify=CENTER, cursor='circle', command=self.tag_select_button_union_command)
    self.tag_select_button.grid(row=26, column=6, pady=20, padx=20)

    self.response_frame = Frame(width=670, height=670, bg='pink')
    self.response_frame.grid(row=2, column=3)
    self.output_time_label = Label(self.response_frame, bg='pink', textvariable=self.time_text, bd=5, font=('幼圆', 15), justify=LEFT, anchor='sw')
    self.output_time_label.grid(row=0, column=0)
    self.scroll = Scrollbar()
    self.output_text = Text(self.response_frame, bg='pink', bd=5, font=('幼圆', 15), width=50, height=30, yscrollcommand=self.scroll.set)
    self.output_text.grid(row=4, column=0)

  # 应答包处理函数
  def rsp_handle(self):
    recv = self.socket.recv(1024)
    # 自定义tcp协议包, 用@分割, 前面为总长，后面为主体
    recv_vec = recv.split(b'@')
    recv_len = recv_vec[0]
    recv_len = int(recv_len.decode())
    rsp = recv_vec[1]
    # file = open('rsp', 'a')
    # file.write(str(recv) + '\n')
    # file.close()
    if(recv_len == 0 or recv_len == 2):
      messagebox.showinfo(title='提示', message='没有包括这些标签的电影！', )
      return
    now_len = len(rsp)
    while(now_len < recv_len):
      recv = self.socket.recv(1024)
      if not recv or len(recv) == 0:
        break
      rsp += recv
      now_len += len(recv)
    rsp_str = rsp.decode('utf-8')
    rsp_list = rsp_str[2: -2].split('}, {')
    show_str = ''
    no_index = 1
    for rsp_film in rsp_list:
      rsp_film = '{' + rsp_film + '}'
      film_dict = ast.literal_eval(rsp_film)
      show_str += 'No' + str(no_index) + '. ' + film_dict['name'] + '\n'
      show_str += '加权得分: ' + str(film_dict['film_weighted_value']) + '\n'
      show_str += '上映年份: ' + str(film_dict['film_dates']) + ', 标签: ' + str(film_dict['film_tags']) + '\n'
      show_str += '地区: ' + film_dict['film_areas'] + '\n'
      show_str += film_dict['film_directors_and_actors'] + '\n'
      show_str += '简评: ' + film_dict['film_quote'] + '\n\n'
      no_index += 1
    self.output_text.delete(1.0, END)
    self.output_text.insert(INSERT, show_str)

  # 并集按钮构造并发送请求
  def tag_select_button_intersection_command(self):
    self.time_text.set('当前时间：' + self.get_current_time())
    tag_list_req = ''
    flag = 0
    for index in range(24):
      if(self.tag_state[index]):
        if(flag == 1):
          tag_list_req += ','
        tag_list_req += self.tag_map[index]
        flag = 1
    tag_list_req += '&intersection'
    print(tag_list_req)
    if(len(tag_list_req) == 0):
      messagebox.showinfo(title='提示', message='请选择标签！', )
      return
    self.socket.send(tag_list_req.encode())
    self.rsp_handle()

    # 交集按钮构造并发送请求
  def tag_select_button_union_command(self):
    self.time_text.set('当前时间：' + self.get_current_time())
    tag_list_req = ''
    flag = 0
    for index in range(24):
      if(self.tag_state[index]):
        if(flag == 1):
          tag_list_req += ','
        tag_list_req += self.tag_map[index]
        flag = 1
    tag_list_req += '&union'
    print(tag_list_req)
    if(len(tag_list_req) == 0):
      messagebox.showinfo(title='提示', message='请选择标签！', )
      return
    self.socket.send(tag_list_req.encode())
    self.rsp_handle()

  # 获取当前时间
  def get_current_time(self):
    current_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
    return current_time

def gui_start():
  # 实例化出一个父窗口
  init_window = Tk()
  recommend_gui = tag_films_recommend_gui(init_window)
  # 设置根窗口默认属性
  recommend_gui.set_init_window(1400, 920)
  # 父窗口进入事件循环，可以理解为保持窗口运行，否则界面不展示
  init_window.mainloop()


import json
import concurrent.futures
import os
import sys

def create_schema(file_name):

    file_name_and_ext = os.path.basename(file_name)
    basename = os.path.splitext(file_name_and_ext)[0]

    strings = ['nvarchar',
               'char',
               'nchar',
               'varchar',
               'ntext']

    integers = ['mediumint',
                'smallint',
                'tinyint',
                'int']

    floats = ['decimal',
              'float',
              'real']

    json_schema = []
    with open(file_name, 'r') as sql_file:
        for line in sql_file:
            json_dict = {}
            if 'NULL' in line or 'NOT NULL' in line:
                if 'SET' not in line:
                    line_split = line.strip().split(']')

                    name = line_split[0]

                    if '[' in name:
                        name = name.strip('[')
                        if ']' in name:
                            name = name.strip(']')
                            if '(%)' in name:
                                name = name.strip('%')

                    if len(name.split()) > 1:
                        name = f'{name[0]}_{name[1]}'

                    data_type = line_split[1].split('[')[1]

                    if data_type in integers:
                        data_type = 'integer'
                        json_dict['name'] = name
                        json_dict['type'] = data_type
                        json_schema.append(json_dict)

                    if data_type in strings:
                        data_type = 'string'
                        json_dict['name'] = name
                        json_dict['type'] = data_type
                        json_schema.append(json_dict)

                    if data_type in floats:
                        data_type = 'float'
                        json_dict['name'] = name
                        json_dict['type'] = data_type
                        json_schema.append(json_dict)

                    if data_type == 'bit':
                        data_type = 'boolean'
                        json_dict['name'] = name
                        json_dict['type'] = data_type
                        json_schema.append(json_dict)

    with open(os.path.abspath(f'../P53_Database/P53_data_schema/{basename}.json'), 'w') as out_file:

        json.dump(json_schema,
                   out_file,
                   indent=4
                   )

def main():

    arg = input('Would you like to run this in parallel? (Y/n): ')

    file_names =  [
        '../P53_Database/P53/dbo.FUNCTION_ISHIOKA.Table.sql',
                # '../P53_Database/P53/dbo.AA_change.Table.sql',
                # '../P53_Database/P53/dbo.AA_codes.Table.sql',
                #    '../P53_Database/P53/dbo.GermlineRefView.Table.sql',
                #    '../P53_Database/P53/dbo.GermlineView.Table.sql',
                #    '../P53_Database/P53/dbo.SomaticView.Table.sql'
                ]

    abs_path = [os.path.abspath(a_file) for a_file in file_names]

    # Synchronous
    if arg.lower() == 'n' or arg.lower() == 'no':
        for a_file in abs_path:
            create_schema(a_file)

    # Parallelized
    if arg.lower() == 'y' or arg.lower() == 'yes':
        with concurrent.futures.ProcessPoolExecutor() as executor:
            executor.map(create_schema, abs_path)

if __name__ == '__main__':
    main()


import numpy as np
from flask import Flask,request,jsonify,render_template
import pickle

from google_trans_new import google_translator
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer

translator = google_translator()

app= Flask(__name__)
@app.route('/',methods=['GET','POST'])

def main():
    if request.method=="POST":
        sentence=request.form.get("inp")
        translation = translator.translate(sentence.encode('unicode-escape').decode('ASCII'), lang_tgt='en')
        analyser = SentimentIntensityAnalyzer()
        result = analyser.polarity_scores(translation)
        if(result["compound"] < 0):
            return render_template("index.html",message="Negativeâ˜¹")
        if(result["compound"] == 0):
            return render_template("index.html",message="NeutralðŸ˜�")
        if(result["compound"] > 0):
            return render_template("index.html",message="PositiveðŸ˜Š  ")
    return render_template("index.html")


import scrapy
from scrapy.http import FormRequest, Request
import csv
import itertools
from scrapy.utils.response import open_in_browser
from urllib.parse import urlencode
from ..items import GoogleShoppingItem
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
import itertools

class ShgSpider(scrapy.Spider):
    name = 'shg'
    start_urls = ['https://shopping.google.com/']
    gtin = ''
    sku = ''
    header = {
        "user-agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1"}

    def parse(self, response):
        sku = ['LSN120HEV2 lg']
        with open('/home/nisl/Downloads/Google Shopping SKUs - Sheet1.csv', 'r') as file:
            reader = csv.reader(file)
            for line in itertools.islice(reader, 10):
        # for i in sku:
                ved = response.xpath('//*[@id="kO001e"]/c-wiz/form/@data-ved').extract_first()
                params = {
                    'psb': '1',
                    'tbm': 'shop',
                    'q': str(line[0]) + ' ' + str(line[2]),
                    # 'q': str(line[0]),
                    'hl': 'en-US',
                    'ved': str(ved)
                }
                self.sku = str(line[0]) + ' ' + str(line[2])
                # self.sku = str(i)
                url = "https://www.google.com/search?" + urlencode(params)
                print(url)
                yield scrapy.Request(url, callback=self.parse2, meta={'dont_redirect': True,
                                                                      'handle_httpstatus_list': [302],
                                                                      'sku': str(line[0]) + ' ' + str(line[2])})

    def parse2(self, response):
        url = response.xpath('/html/body/div[6]/div[2]/div/a/@href').extract_first()
        if not url:
            url = response.xpath('/html/body/div[5]/div[2]/div/a/@href').extract_first()
        print(url)
        if url:
            link = 'https://www.google.com' + str(url)
            yield response.follow(link, callback=self.final_data, meta={'link': link, 'sku': response.meta['sku']})

    def final_data(self, response):
        item = GoogleShoppingItem()

        driver = webdriver.Chrome(executable_path='/home/nisl/WORKING_DIRECTORY/New folder/chromedriver')
        driver.get(response.meta['link'])
        time.sleep(8)
        try:
            gtin = driver.find_element(By.XPATH, '//*[@id="specs"]/div[2]/table/tbody/tr[4]/td[2]').text
            title = driver.find_element(By.XPATH, '//*[@id="sg-product__pdp-container"]/div/div[3]/div[1]/span').text
            google_part_numbers = driver.find_element(By.XPATH, '//*[@id="specs"]/div[2]/table/tbody/tr[3]/td[2]').text
            google_brand_name = driver.find_element(By.XPATH, '//*[@id="specs"]/div[2]/table/tbody/tr[2]/td[2]').text
            brand = driver.find_element(By.XPATH, '//*[@id="specs"]/div[2]/table/tbody/tr[2]/td[2]').text
            page_url = driver.current_url

            item['gtin'] = gtin
            item['title'] = title
            item['google_part_numbers'] = google_part_numbers
            item['google_brand_name'] = google_brand_name
            item['brand'] = brand
            item['page_url'] = page_url
            item['sku'] = response.meta['sku']
            yield item
        except Exception as e:
            gtin = ''

        all_data = response.xpath('//*[@id="online"]/div')
        i = 1
        for data in all_data:
            i = i + 1
            sold_by = data.xpath('./div[2]/a/text()').extract_first()
            item_price = data.xpath('./div[1]/div[1]/b/text()').extract_first()
            shipping_price = data.xpath('./div[1]/div[3]/text()').extract_first()
            tax_price = data.xpath('./div[1]/div[2]/text()').extract_first()
            url = data.xpath('./div[2]/a/@href').extract_first()
            if item_price:
                if '$' in item_price:
                    item_price = item_price.replace('$', '')
            if tax_price:
                if "+$ tax" in tax_price:
                    tax_price = str(tax_price).replace('+$', '')
                    tax_price = str(tax_price).replace('tax', '')
            # next_page = data.xpath('./div[1]/div[2]/a/text()').extract_first()

            # if next_page == "Next >":
            #     next_page_url = data.xpath('./div[1]/div[2]/a/@href').extract_first()
            #     link = 'https://www.google.com' + str(next_page_url)
            #     yield response.follow(link, callback=self.final_data, meta={'link': response.meta['link'],
            #                                                                 'sku': response.meta['sku']})
            if sold_by:
                item['sold_by'] = sold_by
                item['item_price'] = item_price
                if "Free shipping" in shipping_price:
                    item['shipping_price'] = 0.0
                else:
                    item['shipping_price'] = shipping_price
                item['tax_price'] = tax_price
                item['url'] = url

                yield item


from django.shortcuts import render, get_object_or_404
from django.db.models.functions import Coalesce
from django.conf import settings
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.db.models import Q
from ustmenu.models import UstMenu
from .models import Urun
from kategori.models import Kategori, AltKategori
from marka.models import Marka

# Create your views here.
def magaza(request, takma_kategori_adi=None, takma_alt_kategori_adi=None):
    ust_menu = UstMenu.objects.all().order_by('menu_adi')
    ust_menu_alt_kategoriler = AltKategori.objects.all().filter(ust_kategori__in=ust_menu.values_list('menu_adi'))

    kategori_adi = None

    if takma_kategori_adi is not None and takma_alt_kategori_adi is None:
        kategoriler = get_object_or_404(Kategori, takma_kategori_adi=takma_kategori_adi)
        urunler = Urun.objects.all().filter(kategori=kategoriler, mevcut=True)
        kategori_adi = kategoriler.kategori_adi
    elif takma_kategori_adi is not None and takma_alt_kategori_adi is not None:
        kategoriler = get_object_or_404(Kategori, takma_kategori_adi=takma_kategori_adi)
        alt_kategoriler = get_object_or_404(AltKategori, takma_alt_kategori_adi=takma_alt_kategori_adi)
        urunler = Urun.objects.all().filter(kategori=kategoriler, alt_kategori=alt_kategoriler, mevcut=True)
        kategori_adi = kategoriler.kategori_adi + ' / ' + alt_kategoriler.alt_kategori_adi
    else:
        urunler = Urun.objects.all().filter(mevcut=True)

    arama = request.GET.get('arama')

    if arama:
        urunler = urunler.all().filter(Q(urun_adi__icontains=arama) | Q(etiketler__icontains=arama)
                                       | Q(stok_kodu__icontains=arama) | Q(kategori__kategori_adi__icontains=arama)
                                       | Q(alt_kategori__alt_kategori_adi__icontains=arama))

    siralama = request.GET.get('sirala', default='maxtarih')

    if siralama == 'maxtarih':
        urunler = urunler.all().order_by('-eklenme_tarihi')
    elif siralama == 'mintarih':
        urunler = urunler.all().order_by('eklenme_tarihi')
    elif siralama == 'maxfiyat':
        urunler = urunler.all().annotate(son_fiyat=Coalesce('indirimli_fiyat', 'fiyat')).order_by('-son_fiyat')
    elif siralama == 'minfiyat':
        urunler = urunler.all().annotate(son_fiyat=Coalesce('indirimli_fiyat', 'fiyat')).order_by('son_fiyat')

    urun_sayisi = urunler.count()

    paginator = Paginator(urunler, 9)
    sayfa = request.GET.get('sayfa')
    sayfa_urunleri = paginator.get_page(sayfa)

    icerik = {
        'ust_menu': ust_menu,
        'ust_menu_alt_kategoriler': ust_menu_alt_kategoriler,
        'urunler': sayfa_urunleri,
        'urun_sayisi': urun_sayisi,
        'siralama': siralama,
        'kategori_adi': kategori_adi,
        'arama': arama
    }
    icerik.update(settings.GLOBAL_SETTINGS)
    return render(request, 'magaza/magaza.html', icerik)

def urun_detayi(request, takma_kategori_adi=None, takma_alt_kategori_adi=None, takma_urun_adi=None):
    ust_menu = UstMenu.objects.all().order_by('menu_adi')
    ust_menu_alt_kategoriler = AltKategori.objects.all().filter(ust_kategori__in=ust_menu.values_list('menu_adi'))

    try:
        urun = Urun.objects.get(kategori__takma_kategori_adi=takma_kategori_adi, alt_kategori__takma_alt_kategori_adi=takma_alt_kategori_adi, takma_urun_adi=takma_urun_adi)
    except Exception as e:
        raise e

    icerik = {
        'ust_menu': ust_menu,
        'ust_menu_alt_kategoriler': ust_menu_alt_kategoriler,
        'takma_kategori_adi': takma_kategori_adi,
        'takma_alt_kategori_adi': takma_alt_kategori_adi,
        'urun': urun
    }
    return render(request, 'magaza/urun_detayi.html', icerik)


"""BERT and RNN model for sentence pair classification.

Author: Yixu GAO (yxgao19@fudan.edu.cn)

Used for SMP-CAIL2020-Argmine.
"""
import torch

from torch import nn
from torch.nn.utils.rnn import pack_padded_sequence, PackedSequence
from transformers.modeling_bert import BertModel

class BertForClassification(nn.Module):
    """BERT with simple linear model."""
    def __init__(self, config):
        """Initialize the model with config dict.

        Args:
            config: python dict must contains the attributes below:
                config.bert_model_path: pretrained model path or model type
                    e.g. 'bert-base-chinese'
                config.hidden_size: The same as BERT model, usually 768
                config.num_classes: int, e.g. 2
                config.dropout: float between 0 and 1
        """
        super().__init__()
        self.bert = BertModel.from_pretrained(config.bert_model_path)
        for param in self.bert.parameters():
            param.requires_grad = True
        self.linear = nn.Linear(config.hidden_size, config.num_classes)
        self.dropout = nn.Dropout(config.dropout)
        self.num_classes = config.num_classes

    def forward(self, input_ids, attention_mask, token_type_ids):
        """Forward inputs and get logits.

        Args:
            input_ids: (batch_size, max_seq_len)
            attention_mask: (batch_size, max_seq_len)
            token_type_ids: (batch_size, max_seq_len)

        Returns:
            logits: (batch_size, num_classes)
        """
        batch_size = input_ids.shape[0]
        bert_output = self.bert(
            input_ids,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids,
            encoder_hidden_states=False)
        # bert_output[0]: (batch_size, sequence_length, hidden_size)
        # bert_output[1]: (batch_size, hidden_size)
        pooled_output = bert_output[1]
        pooled_output = self.dropout(pooled_output)
        logits = self.linear(pooled_output).view(batch_size, self.num_classes)
        logits = nn.functional.softmax(logits, dim=-1)
        # logits: (batch_size, num_classes)
        return logits

class RnnForSentencePairClassification(nn.Module):
    """Unidirectional GRU model for sentences pair classification.
    2 sentences use the same encoder and concat to a linear model.
    """
    def __init__(self, config):
        """Initialize the model with config dict.

        Args:
            config: python dict must contains the attributes below:
                config.vocab_size: vocab size
                config.hidden_size: RNN hidden size and embedding dim
                config.num_classes: int, e.g. 2
                config.dropout: float between 0 and 1
        """
        super().__init__()
        self.embedding = nn.Embedding(
            config.vocab_size, config.hidden_size, padding_idx=0)
        self.rnn = nn.GRU(
            config.hidden_size, hidden_size=config.hidden_size,
            bidirectional=False, batch_first=True)
        self.linear = nn.Linear(config.hidden_size * 2, config.num_classes)
        self.dropout = nn.Dropout(config.dropout)
        self.num_classes = config.num_classes

    def forward(self, s1_ids, s2_ids, s1_lengths, s2_lengths):
        """Forward inputs and get logits.

        Args:
            s1_ids: (batch_size, max_seq_len)
            s2_ids: (batch_size, max_seq_len)
            s1_lengths: (batch_size)
            s2_lengths: (batch_size)

        Returns:
            logits: (batch_size, num_classes)
        """
        batch_size = s1_ids.shape[0]
        # ids: (batch_size, max_seq_len)
        s1_embed = self.embedding(s1_ids)
        s2_embed = self.embedding(s2_ids)
        # embed: (batch_size, max_seq_len, hidden_size)
        s1_packed: PackedSequence = pack_padded_sequence(
            s1_embed, s1_lengths, batch_first=True, enforce_sorted=False)
        s2_packed: PackedSequence = pack_padded_sequence(
            s2_embed, s2_lengths, batch_first=True, enforce_sorted=False)
        # packed: (sum(lengths), hidden_size)
        self.rnn.flatten_parameters()
        _, s1_hidden = self.rnn(s1_packed)
        _, s2_hidden = self.rnn(s2_packed)
        s1_hidden = s1_hidden.view(batch_size, -1)
        s2_hidden = s2_hidden.view(batch_size, -1)
        hidden = torch.cat([s1_hidden, s2_hidden], dim=-1)
        hidden = self.linear(hidden).view(-1, self.num_classes)
        hidden = self.dropout(hidden)
        logits = nn.functional.softmax(hidden, dim=-1)
        # logits: (batch_size, num_classes)
        return logits


#!/usr/bin/python3
"""Change comes from within"""

def makeChange(coins, total):
    """This function determines the fewest number of coins needed
    to meet a given amount

    Args:
        coins: A list of coins which are just numbers in a list
        total: The total amount to be obtained by the coins

    Returns:
        - The fewest number of coins that add up to the total
    """

    if total <= 0:
        return 0

    # Sort the array of coins in decresing order
    coins.sort(reverse=True)

    # Initialize variables
    num_coins = 0
    remaining_total = total

    # Iterate through each denomination of coin
    for coin in coins:
        while remaining_total >= coin:
            remaining_total -= coin
            num_coins += 1

    # If remaining_total becomes 0, return the no. of coins used
    if remaining_total == 0:
        return num_coins
    else:
        return -1  # Cannot make the total with the given coins


import os
import webbrowser
import time
import functions as fun
import tec_functions as tec

totalProgramas = 0
interruptor = 0
exit = 0
dvs = 0
print("El programa inicia a las " + time.ctime())
device = str(input('Estas en Mac o PC? ', ))
if device == 'mac' or device == 'Mac' or device == '1':
    dvs = 1
    interruptor = str(input('¿Qué vamos a hacer hoy? '))
elif device == 'pc' or device == 'PC' or device == '2':
    dvs = 2
    interruptor = str(input('¿Qué vamos a hacer hoy? '))
else:
    dvs = 3
    print("Introduzca una opcion válida")

while(exit == 0):

    fun.returnToDocuments(dvs)

    if interruptor == 'Salir' or interruptor == 'No' or interruptor == 'no' or interruptor == 'salir':
        print('Gracias por usar Ready 2 Go')
        exit = 1
        break
    else:
        print('Buena suerte con ' + interruptor)
        totalProgramas = 0

    if interruptor == 'bloque' or interruptor == 'Bloque':
        totalProgramas = fun.bloque2(dvs)

    elif interruptor == 'progra' or interruptor == 'Progra':
        totalProgramas = tec.progra(dvs)

    if interruptor == 'quantitative' or interruptor == 'quantum':
        totalProgramas = tec.qmas(dvs)

    elif interruptor == 'R2G':
        totalProgramas = fun.readyconf(dvs)

    elif interruptor == 'Relax' or interruptor == 'relax':
        if dvs ==1:
            os.system('open -a "/Applications/Spotify.app"')
        elif dvs ==2:
            print('Falta investigar como abrir Spotify desde PC')
        webbrowser.open_new('https://www.youtube.com')
        webbrowser.open_new('https://www.twitch.tv')
        totalProgramas = 2

    elif interruptor == 'ldaw' or interruptor == 'Ldaw':
        print('Lanzando sus programas...')
        webbrowser.open_new_tab('https://www.youtube.com/watch?v=bmVKaAV_7-A')
        if dvs == 1:
            os.chdir('LDAW')
        elif dvs == 2:
            os.chdir(r'C:/Users/ferva/Documents/LDAW')
        os.system('code .')
        if dvs ==1:
            os.chdir('/Users/fhva/Documents')
        elif dvs ==2:
            os.chdir(r'C:/Users/ferva/Documents')
        totalProgramas = 3

    elif interruptor == 'verano' or interruptor == 'Verano' or interruptor == 'porvenir':
        print('Lanzando sus programas...')
        webbrowser.open_new_tab('https://www.youtube.com/watch?v=bmVKaAV_7-A')
        webbrowser.open_new_tab('https://drive.google.com/drive/u/2/folders/15ooSk6lyx34iuYV2k-WEvrinTOLzwtrQ')
        if dvs == 1:
            os.chdir('ProyectoVerano')
        elif dvs == 2:
            os.chdir(r'C:/Users/ferva/Documents/ProyectoVerano')
        os.system('code .')
        if dvs ==1:
            os.chdir('/Users/fhva/Documents')
        elif dvs ==2:
            os.chdir(r'C:/Users/ferva/Documents')
        totalProgramas = 3

    elif interruptor == 'spotify' or interruptor == 'spotify':
        if dvs == 1:
            print('Lanzando Spotify')
            os.chdir('../../../..')
            os.chdir('Applications/')
            os.system('open Spotify.app')

    #https://www.youtube.com/playlist?list=PLmNaBlhoxd8ncktaL4G9X7MPBUnJTf-Pj
    elif interruptor == 'django' or interruptor == 'Django' or interruptor == 'dj'or interruptor == 'Dj':
        print('Lanzando sus programas...')
        webbrowser.open_new_tab('https://www.youtube.com/watch?v=JT80XhYJdBw')
        webbrowser.open_new_tab('http://127.0.0.1:8000/')
        if dvs == 1:
            os.chdir('DjangoP')
        elif dvs == 2:
            os.chdir(r'C:/Users/ferva/Documents/DjangoP')
        os.system('code .')
        if dvs ==1:
            os.chdir('/Users/fhva/Documents')
        elif dvs ==2:
            os.chdir(r'C:/Users/ferva/Documents')
        totalProgramas = 3

    else:
        print('Comando no reconocido por el sistema, intente otra vez.')
        breakpoint
    totalProgramas = str(totalProgramas)

    print("Se han abierto " + totalProgramas + " programas" )

    print("El programa termina a las " + time.ctime())

    newint = str(input('Algo más? '))
    interruptor = newint


# Develop a python program to subtract two matrices
row  = int(input("Enter the number of rows : "))
col = int(input("Enter the number of cols : "))
mat=[]
mata=[]
matb=[]
matc=[]
for i in range(col):
    mat.append(0)
#creating matrix structure
for i in range(row):
    mata.append(mat.copy())
    matb.append(mat.copy())
    matc.append(mat.copy())
print("Enter the elements of matrix A : ")
for i in range(row):
    for j in range(col):
        mata[i][j] = int(input())
print("Enter the elements of matrix B : ")
for i in range(row):
    for j in range(col):
        matb[i][j] = int(input())

# subtracting two matrices
for i in range(row):
    for j in range(col):
        matc[i][j] = mata[i][j] - matb[i][j]
print("The resultant matrix is : ")
for i in range(row):
    for j in range(col):
        print(matc[i][j],end='\t')
    print()