from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
import openpyxl
import time

from tkinter import *

jntua = webdriver.Chrome(executable_path="webdrivers/chromedriver.exe")

def fetch():
    xl = openpyxl.Workbook()

    sheet = xl.active

    # ----- year -------

    b_year = year.get()
    # -----------------

    # ------ sem -------

    b_sem = sem.get()

    # -----------------

    # ----- branch -----

    b_branch = branch.get()
    # -----------------

    # ------------ Subjects -----------------

    if b_branch == "CSE":
        if b_year == 1 and b_sem == 1:
            cse = ['CP LAB', 'ELCS LAB', 'ED', 'PHYSICS', 'CP', 'M-1', 'ENGLISH']
        elif b_year == 1 and b_sem == 2:
            cse = ['ENG & IT WORKSHOP', 'CHEMISTRY LAB', 'DS LAB', 'ES', 'CHEMISTRY', 'DS', 'M-2', 'ENGLISH']
        elif b_year == 2 and b_sem == 1:
            cse = ['BEEE LAB', 'BEEE', 'M-3', 'MEFA', 'DBMS LAB', 'DM', 'DBMS', 'DLD']
        elif b_year == 2 and b_sem == 2:
            cse = ['P AND S', 'ONLINE TEST 1', 'JAVA LAB', 'FLAT', 'OOPJ', 'CO', 'SE', 'MPI LAB', 'MPI']
        elif b_year == 3 and b_sem == 1:
            cse = ['SOCIAL VALUES', 'OS LAB', 'OOAD LAB', 'BD', 'ST', 'PPL', 'OOAD', 'CN', 'OS']
        elif b_year == 3 and b_sem == 2:
            cse = ['ENGLISH LAB', 'ONLINE TEST 2', 'DWDM LAB', 'WIT LAB', 'WIT', 'DAA', 'DP', 'DWDM', 'CD',
                   'IPR']  # Subject Names
        elif b_year == 4 and b_sem == 1:
            cse = ['MS', 'MAD LAB', 'GCC LAB', 'RTS', 'SA', 'MAD', 'IS', 'GCC']
        else:
            cse = ['PROJECT WORK', 'TECHNICAL SEMINAR', 'VIVA VOCE', 'CS', 'MC']

        subject=cse.copy()

    # ---------------------------------------

    link = url_link.get()

    rline = 3

    start_hall = hall_ticket = start_hallticket.get()
    end_hall = end_hallticket.get()
    start_limit = int(start_hall[8:])
    end_limit = int(end_hall[8:])
    limit = end_limit - start_limit + 1
    code = int(hall_ticket[7:])

    rows=len(subject)
    column=subject*3

    for i in range(1, rows * 3, 3):
        sheet.cell(row=2, column=i + 1).value = 'MID'
        sheet.cell(row=2, column=i + 2).value = 'SEM'  # sub heading of subjects
        sheet.cell(row=2, column=i + 3).value = 'P/F'

    for i in range(1, rows * 3, 3):
        sheet.cell(row=1, column=i + 2).value = subject.pop()  # Subjects names Entering into Excel file

    for i in range(limit):

        hall_ticket = hall_ticket[:7] + str(code)

        jntua.get(link)
        jntua.find_element_by_class_name('txt').send_keys(hall_ticket)
        jntua.find_element_by_class_name('ci').click()

        code += 1
        try:
            jntua.implicitly_wait(10)
            jntua.find_element_by_xpath('/html/body/div/div[1]/div/div/center/div[1]/table')

        except NoSuchElementException:
            continue

        sheet.cell(row=rline, column=1).value = hall_ticket

        rows = len(jntua.find_elements_by_xpath(
            '//*[@id="rs"]/table/tbody/tr'))  # len of rows in tables also known as Subject length if "rows-2"
        cols = len(jntua.find_elements_by_xpath('//*[@id="rs"]/table/tbody/tr[1]/th'))  # len of the columns

        cline = 2

        for r in range(2, rows):
            for c in range(3, 7):
                if c == 5:
                    continue
                data = jntua.find_element_by_xpath(
                    "//*[@id='rs']/table/tbody/tr[" + str(r) + "]/td[" + str(c) + "]").text
                sheet.cell(row=rline, column=cline).value = data  # storing Marks into Excel file
                cline = cline + 1

        rline = rline + 1

    txt.delete(0.0, 'end')
    txt.insert(0.0, "\nData Entered Successfully....\n")
    txt.insert(0.0, '============ Log =============\n')

    file = "results/" + str(b_year)
    xl.save(file + " Year " + str(b_sem) + " Sem " + b_branch + " Results.xlsx")

def jntuaresults():
    jntua.get("https://jntuaresults.ac.in/")

gui = Tk()

gui.geometry('1000x500+430+250')

gui.title("SVIT JNTUA SEMESTER RESULTS AUTOMATION TOOL")
Label(text="Sri Venkateswara Institute Of Technology (SVIT)", fg="black", font=('Comic Sans MS', 15)).place(x=300, y=1)

# -------- Year ------

Label(text="Year --->  ", font=13).place(x=100, y=100)
year = IntVar()
Radiobutton(gui, text="1", variable=year, value=1, font=10).place(x=220, y=100)
Radiobutton(gui, text="2", variable=year, value=2, font=10).place(x=300, y=100)
Radiobutton(gui, text="3", variable=year, value=3, font=10).place(x=380, y=100)
Radiobutton(gui, text="4", variable=year, value=4, font=10).place(x=460, y=100)
# --------------------

# -------- Sem -------

Label(text="Sem --->  ", font=13).place(x=100, y=150)
sem = IntVar()
Radiobutton(gui, text="1", variable=sem, value=1, font=10).place(x=220, y=150)
Radiobutton(gui, text="2", variable=sem, value=2, font=10).place(x=300, y=150)

# -------------------

# ----------- Branch -------------

branch = StringVar()
branch.set(" ")
Label(text="Branch --->  ", font=13).place(x=100, y=200)
Radiobutton(gui, text="CSE", variable=branch, value="CSE", font=10).place(x=220, y=200)
Radiobutton(gui, text="ECE", variable=branch, value="ECE", font=10).place(x=300, y=200)
Radiobutton(gui, text="EEE", variable=branch, value="EEE", font=10).place(x=380, y=200)
Radiobutton(gui, text="Civil", variable=branch, value="Civil", font=10).place(x=460, y=200)
Radiobutton(gui, text="Mech", variable=branch, value="Mech", font=10).place(x=540, y=200)

# --------------------------------

# -------- Hallticket no. ---------

start_hallticket = StringVar()
end_hallticket = StringVar()

Label(text="Hallticket No. --->", font=13).place(x=100, y=250)

Label(text="Start : ", font=10).place(x=300, y=250)
Entry(gui, justify="center", textvariable=start_hallticket).place(x=380, y=255)

Label(text="End : ", font=10).place(x=520, y=250)
Entry(gui, justify="center", textvariable=end_hallticket).place(x=600, y=255)
# ---------------------------------

# ------- External Entry ---------

ext_entry = StringVar()
Label(text="External Entry (optional) --->", font=13).place(x=100, y=300)
Entry(gui, justify="center", textvariable=ext_entry).place(x=380, y=305)

Button(gui, text="ADD", command=fetch).place(x=550, y=300)
# ---------------------------------

# ---------- Get URl -------------

url_link = StringVar()

Label(text="URL --->", font=13).place(x=100, y=350)
Entry(gui, justify="center", width=50, textvariable=url_link).place(x=200, y=355)

Button(gui, text="Get Link", command=jntuaresults).place(x=550, y=350)

# -------------------------------

# -------- Fetch Button ---------

Button(gui, text="Fetch It", command=fetch).place(x=400, y=400)
# -------------------------------
# ---------- Log ----------------

txt = Text(gui, width=30, height=5)
txt.place(x=740, y=60)
txt.insert(0.0, '============ Log =============')

# -------------------------------

mainloop()
# -------------------------------------------------------------------------------------------------------------------


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun May 27 15:25:11 2018

@author: arent
"""

import numpy as np
import pickle
from sklearn.model_selection import train_test_split

from keras.layers import Input, Dense
from keras.models import Model
from keras.optimizers import SGD, Adam

class Dataset:

    def __init__(self, path_train, path_test):
        self.path_train = path_train
        self.path_test = path_test

        self.x_train, self.y_train = self.load_data_train()
        self.x_test, self.y_test = self.load_data_test()

        self.x_train, self.x_val, self.y_train, self.y_val = self.split()

    def load_data_train(self):
        (T_inf_train,
         T_obs_train,
         beta_MAP_train,
         std_lst_train) = pickle.load(open(self.path_train, 'rb'))

        T_inf_train = np.vstack(T_inf_train).flatten()
        T_obs_train = np.vstack(T_obs_train).flatten()
        beta_MAP_train = np.vstack(beta_MAP_train).flatten()

        x_train = np.concatenate([T_obs_train[:,np.newaxis], T_inf_train[:,np.newaxis]],
                         axis=1)
        y_train = beta_MAP_train
        return x_train, y_train

    def load_data_test(self):
        (T_inf_test,
         T_true_test,
         beta_true_test) = pickle.load(open(self.path_test, 'rb'))

        T_inf_test = np.vstack(T_inf_test).flatten()
        T_true_test = np.vstack(T_true_test).flatten()
        beta_true_test = np.vstack(beta_true_test).flatten()

        x_test = np.concatenate([T_true_test[:,np.newaxis],
                                 T_inf_test[:,np.newaxis]], axis=1)
        y_test = beta_true_test
        return x_test, y_test

    def split(self):
        x_train, x_val, y_train, y_val = train_test_split(self.x_train, self.y_train)
        return x_train, x_val, y_train, y_val

class Network:

    def __init__(self, data, N_epochs, lr, N_hidden, N_nodes):
        self.data = data
        self.N_epochs = N_epochs
        self.lr = lr
        self.N_hidden = N_hidden
        self.N_nodes = N_nodes

        self.model = self.build_model()

    def build_model(self):
        inputs = Input(shape=(2,))
        x = Dense(self.N_nodes, activation='relu')(inputs)
        for i in range(self.N_hidden-1):
            x = Dense(self.N_nodes, activation='relu')(x)
        outputs = Dense(1, activation='linear')(x)

        model = Model(inputs=inputs, outputs=outputs)
        opt = SGD(lr=self.lr)
        model.compile(optimizer=opt, loss='mse')

        return model

    def train(self):
        self.model.fit(self.data.x_train, self.data.y_train,
                       epochs=self.N_epochs,
                       verbose=0,
                       validation_data=(self.data.x_val, self.data.y_val))

        mse = self.model.history.history['loss']
        mse_val = self.model.history.history['val_loss']

        return mse, mse_val

#class GaussianProcess:
#    '''
#    kernel = Kernel class with method kernel_func
#    '''
#
#    def __init__(self, sigma_y, kernel):
#        self.sigma_y = sigma_y
#        self.kernel = kernel
#
#
#
#    def train(self, x_train, y_train):
#        '''
#        Computes the matrices K and K_y for the Gaussian process.
#        '''
#        N = len(x_train)
#
#        self.K = self.compute_K(x_train, x_train)
#        self.K_y = self.K+self.sigma_y**2*np.eye(N)
#        self.invK_y = np.linalg.inv(self.K_y)
#
#        self.x_train = x_train
#        self.y_train = y_train
#
#
#    def compute_K(self, x, xp):
#        '''
#        Returns a matrix of the kernel output of all possible combinations of
#        an observation in array x and an observation in array xp.
#
#        x has shape (N, D)
#        xp has shape (Np, D)
#        '''
#        N = x.shape[0]
#        Np = xp.shape[0]
#
#        K = np.ones((N, Np))
#
#        for i in range(N):
#            for j in range(Np):
#                K[i,j] = self.kernel.kernel_func(x[i,:], xp[j,:])
#
#        return K
#
#
#    def predict(self, x_test):
#        K_s = self.compute_K(self.x_train, x_test)
#        K_ss = self.compute_K(x_test, x_test)
#
#        mu_s = K_s.T.dot(self.invK_y).dot(self.y_train)
#        Sigma_s = K_ss-K_s.T.dot(self.invK_y).dot(K_s)
#
#        return mu_s, Sigma_s
#
#
#class RBF1d:
#
#    def __init__(self, sigma_f, l):
#        self.sigma_f = sigma_f
#        self.l = l
#
#
#    def kernel_func(self, x, xp):
#        return self.sigma_f**2*np.exp(-(x-xp)**2/(2*self.l**2)) # RBF1d
#
#
#
#class RBFnd:
#
#    def __init__(self, h):
#        self.h = h
#
#
#    def kernel_func(self, x, xp):
#        return np.exp(-np.linalg.norm(x-xp)**2/self.h**2)
#
#


from models.Model_Base import Base
from sqlalchemy import Column, Integer,BIGINT, Float, String, DATETIME, TIMESTAMP, func

class WinCPU(Base):
    __tablename__ = 'ds_wincpu'

    seq_id = Column(Integer, primary_key=True, autoincrement=True)
    instance_id = Column(Integer)
    ds_timestamp = Column(BIGINT)
    ds_datetime = Column(DATETIME)
    ProcessorQueueLength = Column(Float)
    CPUBusyPercent = Column(Float)
    Frequency_Sys100NS = Column(Float)
    PercentProcessorTime = Column(Float)

    def __repr__(self):
        return "WinCPU(instance_id='%s', CPUBusyPercent='%s', ds_timestamp='%s', ProcessorQueueLength='%4f'," \
               "Frequency_Sys100NS='%4f', PercentProcessorTime='%4f', ds_datetime='%s')" % (
                   self.instance_id, self.CPUBusyPercent, self.ds_timestamp , self.CPUBusyPercent, self.Frequency_Sys100NS,
                   self.PercentProcessorTime, self.ds_datetime)


#!/usr/bin/python3

import requests
import json
import os
import datetime

PARENT_DIR = "/home/opc/World-Wide-API/Datasets/India"
HEADER_STRING = "Day,Date,Confirmed,Recovered,Deaths\n"

def modifyDate(date_str):
    # date_string 14-Mar-20
    # output: 2020-04-14
    months = {
        "Jan": '01',
        "Feb": '02',
        "Mar": '03',
        "Apr": '04',
        "May": '05',
        "Jun": '06',
        "Jul": '07',
        "Aug": '08',
        "Sep": '09',
        "Oct": '10',
        "Nov": '11',
        "Dec": '12'
    }
    date, month, year = date_str.split('-')

    year += '20'
    new_date = "-".join([year, months[month], date])
    return new_date

def parseCasesInfo(casesInfo):
    try:
        confirmed = casesInfo["confirmed"]
    except:
        confirmed = 0
    try:
        recovered = casesInfo["recovered"]
    except:
        recovered = 0
    try:
        deaths = casesInfo["deceased"]
    except:
        deaths = 0

    return confirmed, recovered, deaths

def stateCodes():
    API_URL = "https://api.covid19india.org/state_district_wise.json"

    filename = "state_codes.json"

    response = requests.get(API_URL)
    states = response.json()

    state_codes = dict()
    for state in states:
        # name = state.replace(' ', '-')
        code = states[state]['statecode']
        state_codes[code.lower()] = state

    fhand = open(filename, 'w')
    json.dump(state_codes, fhand)
    fhand.close()

def statesData():
    STATE_API_URL = "https://api.covid19india.org/states_daily.json"
    codes_file = "/home/opc/World-Wide-API/state_codes.json"
    fhand = open(codes_file)

    all_states = dict()

    state_codes = json.load(fhand)
    fhand.close()

    for code in state_codes:
        state_name = state_codes[code]
        all_states[state_name] = list()

    response = requests.get(STATE_API_URL)
    data = response.json()

    states_info = data["states_daily"]

    for day_data in states_info:
        date = day_data['date']
        status = day_data['status']
        for key in day_data:
            if key in ["date", "status", "dd", "tt"]:
                continue

            state_name = state_codes[key]
            if status == "Confirmed":
                all_states[state_name].append(dict())

            new_date = modifyDate(date)
            all_states[state_name][-1]["Date"] = new_date
            try:
                previous = all_states[state_name][-2][status]
            except:
                previous = 0
            try:
                current = int(day_data[key])
            except:
                current = 0
            all_states[state_name][-1][status] = (current + previous)

    # print(all_states)

    json_states_file = "all_states_time_series.json"
    fhand = open(json_states_file, 'w')

    json.dump(all_states, fhand)
    fhand.close()

    fhand = open(json_states_file)
    data = json.load(fhand)
    day = 1
    for state in data:
        dir_name = state.replace(' ', '-')
        filename = dir_name + "/total.csv"
        try:
            os.mkdir(PARENT_DIR + '/' + dir_name)
        except FileExistsError:
            pass
        except Exception as e:
            print(e, "occured while creating ", PARENT_DIR + '/' + dir_name)
        filename = PARENT_DIR + '/' + filename
        fhand = open(filename, 'w')
        fhand.write(HEADER_STRING)

        for info in data[state]:
            date = info["Date"]
            recovered = info["Recovered"]
            confirmed = info["Confirmed"]
            deaths = info["Deceased"]

            line = ', '.join(
                list(map(str, [day, date, confirmed, recovered, deaths])))
            line += '\n'
            fhand.write(line)
            day += 1
        fhand.close()

def districtsData():
    DISTRICT_API_URL = "https://raw.githubusercontent.com/covid19india/api/gh-pages/v4/data-all.json"
    startDate = "2020-04-21"
    codes_file = "/home/opc/World-Wide-API/state_codes.json"
    fhand = open(codes_file)

    state_codes = json.load(fhand)
    fhand.close()

    response = requests.get(DISTRICT_API_URL)
    jsonData = response.json()

    filenameToDataMap = dict()

    startDateFound = False
    for date in jsonData:
        if startDate == date:
            startDateFound = True
        if startDateFound:
            print(date)
            dayData = jsonData[date]
            for stateCode in dayData:
                if stateCode in ["TT", "tt"]:
                    continue
                stateName = state_codes[stateCode.lower()]
                print("\t", stateName)
                dir_name = stateName.replace(' ', '-')
                try:
                    os.mkdir(PARENT_DIR + '/' + dir_name)
                except FileExistsError:
                    # print("Dir Exists")
                    pass
                except Exception as e:
                    print(e, "occured while creating ",
                          PARENT_DIR + '/' + dir_name, "directory")
                    quit()

                # print(stateName, stateCode, dayData[stateCode])
                if "districts" not in dayData[stateCode]:
                    print(
                        f"\x1b[37mDistricts Data on {date} not available for {stateName}\x1b[0m")
                    continue
                districtsInfo = dayData[stateCode]["districts"]
                for district in districtsInfo:
                    print("\t\t", district)
                    if "total" not in districtsInfo[district]:
                        print(
                            f"Cases info for {stateName} => {district} on {date} isn't available")
                        continue
                    casesInfo = districtsInfo[district]["total"]
                    confirmed, recovered, deaths = parseCasesInfo(casesInfo)
                    itemsToWrite = [0, date, confirmed, recovered, deaths]
                    lineToWrite = ', '.join(list(map(str, itemsToWrite)))
                    print("\t\t\t", lineToWrite)

                    filename = district
                    filename = filename.replace('*', '')
                    filename = filename.replace(' ', '-')
                    filename = dir_name + '/' + filename
                    filename = PARENT_DIR + '/' + filename + ".csv"

                    if filename not in filenameToDataMap:
                        filenameToDataMap[filename] = [lineToWrite + '\n']
                    else:
                        filenameToDataMap[filename].append(lineToWrite + '\n')

    for filename in filenameToDataMap:
        data = filenameToDataMap[filename]
        lastLine = data[-1]
        lastDate = lastLine.split(',')[1].strip()
        today = str(datetime.datetime.today()).split()[0]
        if lastDate == today:
            data.pop()
        fhand = open(filename, 'w')
        fhand.write(HEADER_STRING)
        fhand.writelines(data)

def retrieve():
    stateCodes()
    statesData()
    districtsData()

retrieve()


#!/usr/bin/env python
#
# TP-Link Wi-Fi Smart Plug Protocol Client
# For use with TP-Link HS-100 or HS-110
#
# by Lubomir Stroetmann
# Copyright 2016 softScheck GmbH
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
import socket
import argparse
import time

# Predefined Smart Plug Commands
# For a full list of commands, consult tplink_commands.txt
commands = {'info'     : '{"system":{"get_sysinfo":{}}}',
			'on'       : '{"system":{"set_relay_state":{"state":1}}}',
			'off'      : '{"system":{"set_relay_state":{"state":0}}}',
			'cloudinfo': '{"cnCloud":{"get_info":{}}}',
			'wlanscan' : '{"netif":{"get_scaninfo":{"refresh":0}}}',
			'time'     : '{"time":{"get_time":{}}}',
			'schedule' : '{"schedule":{"get_rules":{}}}',
			'countdown': '{"count_down":{"get_rules":{}}}',
			'antitheft': '{"anti_theft":{"get_rules":{}}}',
			'reboot'   : '{"system":{"reboot":{"delay":1}}}',
                        'reset'    : '{"system":{"reset":{"delay":1}}}',
                        'getvi'    : '{"emeter":{"get_realtime":{}}}',
}

# Encryption and Decryption of TP-Link Smart Home Protocol
# XOR Autokey Cipher with starting key = 171
def encrypt(string):
    key = 171
    result = b"\0\0\0"+ chr(len(string)).encode('latin-1')
    for i in string.encode('latin-1'):
        a = key ^ i
        key = a
        result += chr(a).encode('latin-1')
    return result

def decrypt(string):
    key = 171
    result = ""
    for i in string:
        a = key ^ i
        key = i
        result += chr(a)
    return result

def showlist():
    for i  in commands:
        print(i)

ip = "moeftp.ddns.net"
port = 3055

print("\n")
print("IP : ", ip)
print("PORT : ", port)
print("\n")
ab = encrypt('{"emeter":{"get_realtime":{}}}')
print(ab)
print("\n")

icmd = "getvi"

for var in commands.keys():
    if icmd == var:
        cmd = commands.get(var)

a = 1

while a != 0 :
    try:
        sock_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock_tcp.connect((ip, port))
        sock_tcp.send(b'\x00\x00\x00\x1E\xD0\xf2\x97\xfa\x9F\xeb\x8e\xfc\xde\xe4\x9f\xbd\xda\xbf\xcb\x94\xe6\x83\xe2\x8e\xfa\x93\xfe\x9b\xb9\x83\xf8\x85\xf8\x85')
        data = sock_tcp.recv(2048)
        sock_tcp.close()
        text = ("Received: ", decrypt(data[4:]))
        print(text)
        print("\n")
    except socket.error:
         quit("Cound not connect to host " + ip + ":" + str(port))
         a = 0
    time.sleep(5)


#! /usr/bin/env python3
import numpy as np
import rospy
from std_msgs.msg import String, Int64
from model.msg import model

def cb(msg):
    messagee = msg.data
    messagee = messagee.replace("velocity: ","")
    messagee = messagee.replace(" steering_angle: ","")
    ls = messagee.split(',')
    print("Subscriber data: ")
    rospy.loginfo(msg)

    #Kinematic_Bicycle_Model
    class Bicycle():
        def __init__(self):
            self.xc = 0
            self.yc = 0
            self.theta = 0
            self.beta = 0
            self.xc_dot = 0
            self.yc_dot = 0
            self.theta_dot = 0
            self.L = 2
            self.lr = 1.2
            self.sample_time = 0.01

    class Bicyclee(Bicycle):
        def step(self, v, delta):

            #bicycle Kinematics
            self.xc_dot = v* np.cos(self.theta + delta)
            self.yc_dot = v* np.sin(self.theta + delta)
            self.theta_dot = v* np.cos(self.theta)* np.tan(delta)/self.L

            #update the state variables
            self.xc += self.xc_dot * self.sample_time
            self.yc += self.yc_dot * self.sample_time
            self.theta += self.theta_dot * self.sample_time
            self.beta = np.arctan(self.lr*np.tan(delta)/self.L)

    modell = Bicyclee()
    modell.step(float(ls[0]), float(ls[1]))

    print("Publisher data: ")

    my_msg = model()
    my_msg.velocity   = float(ls[0])
    my_msg.delta      = float(ls[1])
    my_msg.xc_dot     = modell.xc_dot
    my_msg.ycdot      = modell.yc_dot
    my_msg.theta_dot  = modell.theta_dot
    my_msg.beta       = modell.beta
    my_msg.theta      = modell.theta
    my_msg.xc         = modell.xc
    my_msg.yc         = modell.yc
    pup.publish(my_msg)

def sub_pup():
    rospy.init_node('data_processing')
    global pup
    pup = rospy.Publisher('/output_data', model, queue_size=10)
    rospy.Subscriber('/input_data', String, callback=cb)
    rospy.spin()

if __name__ == "__main__":
    try:
        print("Running...")
        sub_pup()
    except rospy.ROSInterruptException:
        pass


# 面试题 02.05. 链表求和.py

# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        carry = 0
        dummy = ListNode(0)
        cur = dummy
        while l1 or l2:
            n1 = l1.val if l1 else 0
            n2 = l2.val if l2 else 0
            carry, val = divmod(n1 + n2 + carry, 10)
            cur.next = ListNode(val)
            cur = cur.next
            l1 = l1.next if l1 else None
            l2 = l2.next if l2 else None
        if carry:
            cur.next = ListNode(1)
        return dummy.next

# 进阶
class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        v1, v2 = 0, 0
        while l1:
            v1 = v1 * 10 + l1.val
            l1 = l1.next
        while l2:
            v2 = v2 * 10 + l2.val
            l2 = l2.next
        val = v1 + v2
        pre, cur = None, None
        while val:
            val, mod = divmod(val, 10)
            cur = ListNode(mod)
            cur.next = pre
            pre = cur
        return cur

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        dummy = ListNode(0)
        cur = dummy
        carry = 0
        while l1 or l2:
            n1, l1 = (l1.val, l1.next) if l1 else (0, l1)
            n2, l2 = (l2.val, l2.next) if l2 else (0, l2)
            carry, mod = divmod(n1 + n2 + carry, 10)
            cur.next = ListNode(mod)
            cur = cur.next
        if carry:
            cur.next = ListNode(1)
        return dummy.next

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        v1, v2 = 0, 0
        while l1:
            v1 = v1 * 10 + l1.val
            l1 = l1.next
        while l2:
            v2 = v2 * 10 + l2.val
            l2 = l2.next
        val = v1 + v2
        pre = cur = None
        while val:
            val, mod = divmod(val, 10)
            cur = ListNode(val)
            cur.next = pre
            pre = cur
        return cur

def main():
    sol = Solution()
    l1 = ListNode(1)
    l1.next = ListNode(2)
    l2 = ListNode(2)
    l2.next = ListNode(8)
    l3 = sol.addTwoNumbers(l1, l2)
    while l3:
        print(l3.val)
        l3 = l3.next

if __name__ == '__main__':
    main()


from django.urls import path
from .views import EditClubHome,EditClubTonight, ClubHomepage, ClubTonightpage,ClubEventspage,ClubContacts
from .views import EditClubEvents

urlpatterns = [

    path("<name>",ClubHomepage,name="clubhome"),
    path("<name>/home/",ClubHomepage,name="clubhome"),
    path("<name>/tonight/",ClubTonightpage,name="clubtonight"),
    path("<name>/events/",ClubEventspage,name="clubevents"),
    path("<name>/contacts/",ClubContacts,name="clubcontacts"),

    path("Edithome/",EditClubHome,name="clubedithome"),
    path("Edittonight/",EditClubTonight,name="clubedittonight"),
    path("Editevents/",EditClubEvents,name="clubeditevents"),
    path("Editcontacts/",EditClubHome,name="clubeditcontacts"),

]


__author__ = 'miko'
from de.hochschuletrier.jpy.overlays.QuestionOverlay import QuestionOverlay
from de.hochschuletrier.jpy.overlays.UsernameOverlay import UsernameOverlay

class OverlayManager:
    def __init__(self, root):
        self.root = root
        self.activeOverlay = 0
        self.overlays = []

        self.generateOverlays()

    def generateOverlays(self):
        self.overlays.append(QuestionOverlay(self.root, overlayName="Frage", id=0))
        self.overlays.append(UsernameOverlay(self.root, overlayName="Username", id=1))

        for overlay in self.overlays:
            overlay.lower()

    def showOverlay(self, overlay):
        if overlay > len(self.overlays) - 1:
            return
        self.overlays[self.activeOverlay].lower()
        self.overlays[overlay].lift(aboveThis=None)
        self.overlays[overlay].isVisible = True
        self.activeOverlay = overlay


# import the libraries
import cv2
import imutils

# initializing the HOGDescriptor for person detection
HOGCV = cv2.HOGDescriptor()
HOGCV.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())

#get the video file by specified path
video = cv2.VideoCapture('human_vid.mp4')

# open the video and check its running
while video.isOpened():
    check, frame = video.read()
    if check:
        # resize the output of video file
        frame = imutils.resize(frame, width=min(800, frame.shape[1]))
        bounding_box_cordinates, weights = HOGCV.detectMultiScale(frame, winStride=(4, 4), padding=(8, 8),
                                                              scale=1.03)
        # create person var for count of people
        person = 0
        # define the dimensions and text of rectangular boxes identifying humans
        for x, y, w, h in bounding_box_cordinates:
            cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
            cv2.putText(frame, f'person {person}', (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)
            person += 1
            cv2.putText(frame, 'Status : Detecting', (40, 40), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
                                                        (255, 255, 0), 1)
            cv2.putText(frame, f'Total People : {person}', (40, 70), cv2.FONT_HERSHEY_SIMPLEX,
                        0.5, (255, 255, 0), 1)
            # get the output video
            cv2.imshow('output', frame)
            key = cv2.waitKey(1)
            if key == ord('q'):
                break
    else:
        break
video.release()
cv2.destroyAllWindows()


from typing import List

class Solution:
    def getPermutation(self, n: int, k: int) -> str:
        nums = [str(i) for i in range(1, n + 1)]
        nums = "".join(nums)
        count = [0]
        res = self.get_kth_permitation(nums, count, "", k)
        return res

    def get_kth_permitation(self, nums, count, permutation, k):
        """找出第k和排列"""
        # print(count)
        if len(permutation) == len(nums):
            count[0] += 1
        if count[0] >= k:
            # print(permutation)
            return permutation
        for i in range(0, len(nums)):
            if nums[i] not in permutation:
                pre_str = f'{permutation}'
                permutation = f'{permutation}{nums[i]}'
                res = self.get_kth_permitation(nums, count, permutation, k)
                permutation = pre_str
                if count[0] >= k:
                    return res

if __name__ == '__main__':
    nums = [1, 2, 3]
    so = Solution()
    res = so.getPermutation(3, 5)
    print(res)


from core.sudokuBoard import SudokuBoard

class SudokuGame(object):

    def __init__(self, boardFile):
        self.boardFile = boardFile
        self.startPuzzle = SudokuBoard(boardFile).board

    def start(self):
        self.gameOver = False
        self.pause = False
        self.puzzle = []

        for i in range(9):
            self.puzzle.append([])
            for j in range(9):
                self.puzzle[i].append(self.startPuzzle[i][j])

    def checkWin(self):

        for row in range(9):
            if (not self.__checkRow(row)):
                return False

        for column in range(9):
            if (not self.__checkColumn(column)):
                return False

        for row in range(3):
            for column in range(3):
                if (not self.__checkSquare(row, column)):
                    return False

        self.gameOver = True
        return True

    def __checkBlock(self, block):
        # Set es usada para guardar múltiples objetos de una
        # variabe
        return set(block) == set(range(1, 10))

    def __checkRow(self, row):
        return self.__checkBlock(self.puzzle[row])

    def __checkColumn(self, column):
        return self.__checkBlock(
            [self.puzzle[row][column] for row in range(9)]
            )

    def __checkSquare(self, row, column):
        return self.__checkBlock(
            [
                self.puzzle[r][c]
                for r in range(row * 3, (row + 1) * 3)
                for c in range(column * 3, (column +1) * 3)
            ]
        )


from re import match

ETIQUETA: None
CODOP: None
OPERANDO: None
resultado= None
sistemaNumerico= " "

def t_COMENTARIO(t):     #Funcion que identifica comentarios
    LineaAnalizada= str(t)
    SiContiene= LineaAnalizada.find(";")

    if len(LineaAnalizada) > 80:    #Valida longitud
        print("Error, longitud de comentario no valida")
    else:
        if SiContiene==2 :  #Si encuentra un ; en la primera posicion lo identifica como comentario
            print( "Comentario ")

def t_ETIQUETA(t):      #Funcion que identifica etiqueta
    LineaAnalizada= str(t)

    Patron_Busqueda= re.compile(r'[\w_]+[\s$]+')  #Expresion regular
    ETIQUETA= re.search(Patron_Busqueda, LineaAnalizada) #Encuentra las coincidencias en la linea
    if ETIQUETA is None:
        print("ETIQUETA = null")
        return None
    Indice=LineaAnalizada.index(ETIQUETA.group())
    Tamaño=ETIQUETA.group().strip()
    if Indice == 2 and LineaAnalizada[Indice].isalpha():
        if len(Tamaño)<=8:
            etq= ETIQUETA.group()
            return etq

        else:
            return "Error, longitud invalida"

    else:
        etq= None
        return etq

def t_CODOP(t):     #Funcion que identifica el CODOP
    LineaAnalizada= str(t)
    SiContiene= LineaAnalizada.find(";")
    if SiContiene!=2:   #Valida que no sea comentario
        PatronCODOP= re.compile(r'[\s][a-zA-Z]{1,5}[.]{0,1}[a-zA-Z]{1,5}[\s]*')#\s concide con espacio en blanco ultimo elemento de la linea y termina con el, tiene que haber 0 o más
        CoincideCODOP = re.search(PatronCODOP, LineaAnalizada)
        if CoincideCODOP is None:
            return None
        Indice=LineaAnalizada.index(CoincideCODOP.group())
        nospace=CoincideCODOP.group().strip()#elimina los espacios de la cadena
        if Indice > 2 and len(nospace)<=5:#Si el CODOP no esta al inicio y la cadena no tiene más de 5 caracteres:
            #print("CODOP= "+ CoincideCODOP.group())
            resultado= CoincideCODOP.group()
        else:
            print("CODOP= Error, longitud invalida")

       # if CoincideCODOP.group().contains("End") or CoincideCODOP.group().contains("end") or CoincideCODOP.group().contains("END"):#Si la coincidencia contiene End:
           # sys.exit() #Finaliza el programa
    else:
        print("CODOP= null") #Si no encuentra un CODOP regresa null

    return resultado

def t_OPERANDO(t, rel, inm,inh):

    LineaAnalizada= str(t)

    #EXPRESIONES REGULARES PARA IDENTIFICAR CADA UNO DE LOS MODOS DE DIRECCIONAMIENTO
    EsOperando= r'[\s]([@]|[%]|[$]|[0-9]|[,]|[-]|[[]|A|B|D|[\w_])'
    Directo=r"[\s]([%][0-1]{1,8}|[$][0-9A-F]{1,2}|[@][0-7]|[@][0-7][0-7]|[@][0-3][0-7][0-7]|\d|\d\d|1[0-9][0-9]|2[0-4][0-9]|2[5][0-5])(')"
    Extendido=(r"[\s]([%][0-1]{9,16}|[$][0]*[1-9A-F]{3,4}|[@][4-7][0-7][0-7]|[@][0-7][0-7][0-7][0-7]|[@][0-7][0-7][0-7][0-7][0-7]|[@][0-1][0-7][0-7][0-7][0-7][0-7]|2[5][6-9]|2[6-9]\d|[3-9]\d\d|[0-9]\d\d\d|[0-5]\d\d\d\d|[0-6][0-4][0-9][0-9][0-9]|[0-6][0-5][0-5][0-3][0-5]|[a-zA-Z]+[\w])(')")
    Indexado5bits=(r'([-]\d?|[-]1[0-5]?|[\s]\d?|1[0-6]?)([,])(?i)(X(?![+-])(?![]])|Y(?![+-])(?![]])|SP(?![+-])(?![]])|PC(?![+-])(?![]]))')
    Indexado9bits=(r'(?i)([-]1[7-9]|[-][2-9]\d|[-]1[0-9]\d|[-]2[0-4][0-9]|[-]2[0-5][0-6]|[\s]1[6-9]|[\s][2-9]\d|[\s]2[0-4][0-9]|[\s]2[0-5][0-5])([,])(X(?![+-])(?![]])|Y(?![+-])(?![]])|SP(?![+-])(?![]])|PC(?![+-])(?![]]))')
    Indexado16bits=(r'(?i)(2[5][6-9]|2[6-9][0-9]|[3-9]\d\d|[0-9]\d\d\d|[0-5]\d\d\d\d|[0-6][0-4][0-9][0-9][0-9]|[0-6][0-5][0-5][0-3][0-5])([,])(X(?![+-])(?![]])|Y(?![+-])(?![]])|SP(?![+-])(?![]])|PC(?![+-])(?![]]))')
    IndexadoIndirecto16bits=(r"\[(\d\d?\d?\d?|[0-5][0-9][0-9][0-9][0-9]|[6][0-4][0-9][0-9][0-9]|[0-6][0-5][0-5][0-3][0-5])(,)(?i)(PC|Y|X|SP)\]")
    AutoPrePostDecrementoIncremento=(r"[\s][1-8](,)(?i)([+|-](X|Y|SP)|(X|Y|SP)[+|-])")
    IndexadoAcum= (r"(A|B|D)(,)(?i)(X(?![]])|Y(?![]])|SP(?![]])|PC(?![]]))")
    IndexadoAcumIndirecto=(r"\[(?i)([D])(,)(?i)(PC|Y|X|SP)\]")
    Relativo8bits=(r"[\s]([\w_]){1,8}(')")
    Relativo16bits=(r"[\s]([\w_]){9,16}(')")
    Inmediato8bits= (r"[\s][#]([%][0-1]{1,8}|[$][0-9A-F]{1,2}|[@][0-3][0-7]?[0-7]?|\d|\d\d|1[0-9][0-9]|2[0-4][0-9]|2[5][0-5])(')")
    Inmediato16bits= (r"[\s][#]([%][0-1]{9,16}|[$][0]*[1-9A-F]{3,4}|[@][4][0-7][0-7]|[@][0-7][0-7][0-7][0-7][0-7]|[@][0-1][0-7][0-7][0-7][0-7][0-7]|2[5][6-9]|2[6-9]\d|[3-9]\d\d|[0-9]\d\d\d|[0-5]\d\d\d\d|[0-6][0-4][0-9][0-9][0-9]|[0-6][0-5][0-5][0-3][0-5])(')")
    Inherente= (r"[\s](')(,)")
    DirectivaFCC= (r"(\")[\x00-\x7F]*(\")")
    #BUSCA SI CONTIENE OPERANDO EN LA LINEA
    OPERAND= re.search(EsOperando, LineaAnalizada)
    INH = re.search(Inherente, LineaAnalizada)
    if OPERAND is None:
         return None
    if OPERAND:
        Indice=LineaAnalizada.index(OPERAND.group())

    #HACE UNA BUSQUEDA PARA ENCONTRAR TODAS LAS COINCIDENCIAS
    if Indice > 0:
        DIRECTOS = re.search( Directo, LineaAnalizada[Indice::])
        EXT = re.search(Extendido, LineaAnalizada[Indice::] )
        IDX5BITS=  re.search(Indexado5bits, LineaAnalizada[Indice::])
        IDX9BITS=  re.search(Indexado9bits, LineaAnalizada[Indice::])
        IDX16BITS=  re.search(Indexado16bits, LineaAnalizada[Indice::])
        IDXIND16BITS=  re.search(IndexadoIndirecto16bits, LineaAnalizada[Indice::])
        APPDI=  re.search(AutoPrePostDecrementoIncremento, LineaAnalizada[Indice::])
        IDXACUM= re.search(IndexadoAcum, LineaAnalizada[Indice::])
        IDXACUMIND=  re.search(IndexadoAcumIndirecto, LineaAnalizada[Indice::])
        REL8= re.search(Relativo8bits, LineaAnalizada[Indice::])
        REL16= re.search(Relativo16bits, LineaAnalizada[Indice::])
        IMM8= re.search(Inmediato8bits, LineaAnalizada[Indice::])
        IMM16= re.search(Inmediato16bits, LineaAnalizada[Indice::])
        FCC = re.search(DirectivaFCC, LineaAnalizada[Indice::])

        #IDENTIFICA A QUE TIPO PERTENECE EL OPERANDO Y DEVUELVE EL RESULTADO
        if DIRECTOS:
            resultado = DIRECTOS.group().replace("'", "")
            tipoDeOperando= "Directo, Dos bytes"
            return resultado, tipoDeOperando

        if EXT and rel != 'x':
            resultado = EXT.group().replace("'", "")
            tipoDeOperando="Extendido, Tres bytes"
            return resultado, tipoDeOperando

        if  IDX5BITS:
            resultado = IDX5BITS.group()
            tipoDeOperando= "Indexado de Cinco bits, (IDX), Dos bytes"
            return resultado, tipoDeOperando

        if  IDX9BITS:
            resultado = IDX9BITS.group()
            tipoDeOperando= "Indexado de Nueve bits, (IDX1), Tres bytes"
            return resultado, tipoDeOperando

        if  IDX16BITS:
            resultado = IDX16BITS.group()
            tipoDeOperando= "Indexado de Dieciseis bits, (IDX2), Cuatro bytes"
            return resultado, tipoDeOperando

        if IDXIND16BITS:
            resultado = IDXIND16BITS.group()
            tipoDeOperando= "Indexado Indirecto de Dieciseis bits, ([IDX2]), Cuatro bytes"
            return resultado, tipoDeOperando

        if  APPDI:
            resultado = APPDI.group()
            tipoDeOperando= "Auto Pre/Post Decremento/Incremento, (IDX), Dos bytes"
            return resultado, tipoDeOperando

        if  IDXACUM:
            resultado = IDXACUM.group()
            tipoDeOperando= "Indexado de acumulador, (IDX), Dos bytes"
            return resultado, tipoDeOperando

        if IDXACUMIND:
            resultado = IDXACUMIND.group()
            tipoDeOperando = "Indexado de acumulador indirecto, ([D,IDX]), Dos bytes"
            return resultado, tipoDeOperando

        if REL8 and rel == 'x':
            resultado = REL8.group().replace("'", "")
            tipoDeOperando= "Relativo de Ocho bits, (REL), Dos bytes"
            return resultado, tipoDeOperando

        if REL16 and rel == 'x':
            resultado = REL16.group().replace("'", "")
            tipoDeOperando= "Relativo de Dieciseis bits, (REL), Cuatro bytes"
            return resultado, tipoDeOperando

        if IMM8 and inm == 'y':
            resultado = IMM8.group().replace("'", "")
            tipoDeOperando= "Inmediato de Ocho bits, Dos bytes"
            return resultado, tipoDeOperando

        if IMM16 and inm == 'y':
            resultado = IMM16.group().replace("'", "")
            tipoDeOperando= "Inmediato de Dieciseis bits, Dos bytes"
            return resultado, tipoDeOperando

        if INH and inh == 'z':
           resultado= INH.group().replace("',","1")
           tipoDeOperando = "Inherente, Un byte"
           return resultado, tipoDeOperando

        if FCC:
            resultado= FCC.group()
            return resultado

#FUNCION QUE NOS PERMITE SABER QUE TIPO DE RELATIVO ES
def Relativo(DataFrame):

    datos_Tabop= pd.read_excel(ruta_Archivo, sheet_name="Hoja1", header=3)
    DataFrame= pd.DataFrame(datos_Tabop)
    DataFrameFiltrado=DataFrame[DataFrame['CODOP'].isin(lista)]

    valorDelRelativo=DataFrameFiltrado['Addr. Mode'].str.contains('REL').sum()

    if  valorDelRelativo > 0:
        return "x"

#FUNCION QUE NOS PERMITE SABER QUE TIPO DE INMEDIATO ES
def Inmediato(Dataframe):

    datos_Tabop= pd.read_excel(ruta_Archivo, sheet_name="Hoja1", header=3)
    DataFrame= pd.DataFrame(datos_Tabop)
    DataFrameFiltrado=DataFrame[DataFrame['CODOP'].isin(lista)]

    valorDelInmediato=DataFrameFiltrado['Addr. Mode'].str.contains('Inmediato').sum()

    if  valorDelInmediato > 0:
        return "y"
#FUNCION QUE NOS PERMITE IDENTIFICAR UN MODO INHERENTE
def Inherente(Dataframe):

    datos_Tabop= pd.read_excel(ruta_Archivo, sheet_name="Hoja1", header=3)
    DataFrame= pd.DataFrame(datos_Tabop)
    DataFrameFiltrado=DataFrame[DataFrame['CODOP'].isin(lista)]

    inherente=DataFrameFiltrado['Addr. Mode'].str.contains('Inherente').sum()

    if  inherente > 0:
        return "z"

    #Los CODOP del txt en el tabot y muestra la informacion
def buscar_enTabop(DataFrame, lista):

    datos_Tabop= pd.read_excel(ruta_Archivo, sheet_name="Hoja1", header=3)
    DataFrame= pd.DataFrame(datos_Tabop)
    DataFrameFiltrado=DataFrame[DataFrame['CODOP'].isin(lista)]     #Busca el codop en el tabop
    if DataFrameFiltrado.dropna().empty:
        print( Fore.RED +  "Error, el CODOP no tiene informacion" )
        init(autoreset=True)
    else:
        print(  DataFrameFiltrado )         #Imprime la info del codop si este tiene

#Nos indica si un codop debe llevar operando o no
def llevaOperando(Dataframe, lista):
    contiene=False
    datos_Tabop= pd.read_excel(ruta_Archivo, sheet_name="Hoja1", header=3)
    DataFrame= pd.DataFrame(datos_Tabop)
    DataFrameFiltrado=DataFrame[DataFrame['CODOP'].isin(lista)]     #Busca el codop en el tabop

    if 'No Operando' in DataFrameFiltrado['Operando'].values:
        contiene=False
        return contiene
    if 'Operando' in DataFrameFiltrado['Operando'].values:
        contiene=True
        return contiene

#Devuelve el valor del ORG
def valorDelORG(t):
    LineaAnalizada= str(t)
    patronBuscarValor= r"ORG\s*(.{1,4})"
    lineaFil= re.search(patronBuscarValor, LineaAnalizada)
    if lineaFil is None:
         return None
    if lineaFil:
        resultado= lineaFil.group()
        resultado1= resultado.split(" ", 1)
        return resultado1[1]

#Escribe los datos en el archivo temporal
def escribirArchivoTemporal(CONTLOC,ETIQUETA,CODOP,result,VALOR_EQU):
    if codop.strip() != "EQU":
        archivoTmp.write("CONTLOC" +  "\t" + str(CONTLOC).strip() + "\t" + str(ETIQUETA).strip() + "\t" + str(CODOP).strip() +  "\t" +  str(result) + "\n")
    else:
        archivoTmp.write("VALOR EQU" + "\t" + str(VALOR_EQU).strip() + "\t" + str(ETIQUETA).strip() + "\t" + str(CODOP).strip() + "\t"+ str(result) + "\n")

#Analiza la directiva y devuelve el valor de bytes para aumentar al contloc
def analizaDirectiva(codop, result,operando):
    #Directivas de constantes
    pequeño=r"[\s][#]?([%][0-1]{1,8}|[$][0-9A-F]{1,2}|[@][0-3][0-7]?[0-7]?|\d|\d\d|1[0-9][0-9]|2[0-4][0-9]|2[5][0-5])(')"
    grande=r"[\s][#]?([%][0-1]{1,16}|[$][0-9A-F]{1,4}|[@][0-3][0-7]?[0-7]?[0-7]?[0-7]?[0-7]?|[@][0-1][0-7][0-7][0-7][0-7][0-7]|\d|\d\d|\d\d\d|\d\d\d\d|[0-5]\d\d\d\d[0-6][0-4][0-9][0-9][0-9]|[0-6][0-5][0-5][0-3][0-5])(')"
    regex = r"(Un|Dos|Tres|Cuatro)"

    PQ= re.search(pequeño, operando)
    GD= re.search(grande, operando)
    inherente= re.search(regex, operando) #Retora el valor de bytes de los operandos inhrentes

    if codop.strip()== "DB" and PQ or codop.strip()== "DC.B" and PQ or codop.strip()== "FCB" and PQ:
        return 1

    if codop.strip()== "DW" and GD or codop.strip()== "DC.W" and GD or codop.strip()== "FDB" and GD:
        return 2

    if codop.strip()== "FCC" and  operando != 'None':
        return len(operando)

    if codop.strip()== "DS" or codop.strip()== "DS.B" or codop.strip()== "RMB":
        return int(result)

    if codop.strip()== "DS.W" or codop.strip()== "RMW":
        return int(result)*2

    if (codop.strip()!= "DB" and codop.strip()!= "DC.B" and codop.strip()!= "FCB" and codop.strip()!= "DW" and codop.strip()!= "DC.W" and codop.strip()!= "FDB"
    and codop.strip()!= "DS" and codop.strip()!= "DS.B" and codop.strip()!= "RMB" and codop.strip()!= "DS.W" and codop.strip()!= "RMW" and codop.strip()!= "FCC" and codop.strip()!= "EQU" and codop.strip()!= "ORG") and result != "":

        if inherente.group() == "Un":
            return 1
        if inherente.group() == "Dos":
            return 2
        if inherente.group() == "Tres":
            return 3
        if inherente.group() == "Cuatro":
            return 4
    else:
        return 0

#Valida las condiciones necesarias de las directivas
def validarDirectivas(aumentocontloc, etiqueta, codop, result, operando):

    pequeño=r"[\s][#]?([%][0-1]{1,8}|[$][0-9A-F]{1,2}|[@][0-3][0-7]?[0-7]?|\d|\d\d|1[0-9][0-9]|2[0-4][0-9]|2[5][0-5])(')"
    grande=r"[\s][#]?([%][0-1]{1,16}|[$][0-9A-F]{1,4}|[@][0-3][0-7]?[0-7]?[0-7]?[0-7]?[0-7]?|[@][0-1][0-7][0-7][0-7][0-7][0-7]|\d|\d\d|\d\d\d|\d\d\d\d|[0-5]\d\d\d\d[0-6][0-4][0-9][0-9][0-9]|[0-6][0-5][0-5][0-3][0-5])(')"

    PQ= re.search(pequeño, operando)
    GD= re.search(grande, operando)

    if codop.strip() == "EQU" and etiqueta != "null" and etiqueta is not 'None' and GD:
        print('enviarlinea')
    elif codop.strip() == "EQU":
        print(Fore.RED + 'ERROR EQU TIENE QUE TENER UNA ETIQUETA Y UN OPERANDO')
    init(autoreset=True)

    if aumentocontloc > 0 and PQ or aumentocontloc > 0 and GD:
        pass

    elif (codop.strip()== "DB" or codop.strip()== "DC.B" or codop.strip()== "FCB"  or codop.strip()== "DW" or codop.strip()== "DC.W" or codop.strip()== "FDB"
    or codop.strip()== "DS" or codop.strip()== "DS.B" or codop.strip()== "RMB" or codop.strip()== "DS.W" or codop.strip()== "RMW"):
        print(Fore.RED + "Error el operando es inválido")
        init(autoreset=True)

    if codop.strip() == "FCC" and operando is None:
        print(Fore.RED + "Error el operando es inválido")
    init(autoreset=True)

#Obtiene el valor numerico del ORG
def limpiaORG(DIR_INIC):
    regexNum= r"[^0-9]"
    subst = ""
    result = re.sub(regexNum, subst, DIR_INIC, 0, re.MULTILINE)
    return int(result)

#Escribe los datos en el archivo TABSIM
def escribeTABSIM(CONTLOC, ETIQUETA, VALOR_EQU, CODOP):
    if codop.strip() != "EQU":
        TABSIM.write("CONTLOC (ETIQUETA RELATIVA) " + "\t" + str(ETIQUETA) + "\t" + str(CONTLOC) + "\n")
    else :
        TABSIM.write("EQU (ETIQUETA ABSOLUTA) " + "\t" + str(ETIQUETA) + "\t" + str(VALOR_EQU) + "\n")

def codigoMaquinaInherente(valor, etiqueta, codop, operando, codigoMaquina):
    print(valor, etiqueta, codop, operando, codigoMaquina )

def codigoMaquinaDirecto(valor, etiqueta, codop, operando, codigoMaquina):

    #Binario
        if operando != '' and sistemaNumerico.strip()== "%":
            op= int(operando, 2)
            operandoHex= hex(op).replace("0x","").upper()
            operandoUnido= str(codigoMaquina)+str(operandoHex).zfill(2)
            print(valor, etiqueta, codop, operando, operandoUnido.replace("[","").replace("]","").replace("'",""))
        else:
            pass
        #Octal
        if operando != '' and sistemaNumerico.strip()== "@":
            op= int(operando, 8)
            operandoHex= hex(op).replace("0x","").upper()
            operandoUnido= str(codigoMaquina)+str(operandoHex).zfill(2)
            print(valor, etiqueta, codop, operando, operandoUnido.replace("[","").replace("]","").replace("'",""))
        else:
            pass
        #Hexadecimal
        if operando != '' and sistemaNumerico.strip()== "$":
            op= int(operando, 16)
            operandoHex= hex(op).replace("0x","").upper()
            operandoUnido= str(codigoMaquina)+str(operandoHex).zfill(2)
            print(valor, etiqueta, codop, operando, operandoUnido.replace("[","").replace("]","").replace("'",""))
        #Decimal
        dec=r'[0-9]'
        deci=re.search(dec, operando)
        if operando != '' and sistemaNumerico.strip() != '%' and sistemaNumerico.strip() != '$' and sistemaNumerico.strip() != '@' and deci:
            op= int(operando, 10)
            operandoHex= hex(op).replace("0x","").upper()
            operandoUnido= str(codigoMaquina)+str(operandoHex).zfill(2)
            print(valor, etiqueta, codop, operando, operandoUnido.replace("[","").replace("]","").replace("'",""))
        else:
            pass

def codigoMaquinaInmediato(valor, etiqueta, codop, operando, codigoMaquina, sistemaNumerico):
    #Binario
    if operando != '' and sistemaNumerico.strip()== "%":
        op= int(operando, 2)
        operandoHex= hex(op).replace("0x","").upper()
        operandoUnido= str(codigoMaquina)+str(operandoHex).zfill(4)
        print(valor, etiqueta, codop, operando, operandoUnido.replace("[","").replace("]","").replace("'",""))
    else:
        pass
    #Octal
    if operando != '' and sistemaNumerico.strip()== "@":
        op= int(operando, 8)
        operandoHex= hex(op).replace("0x","").upper()
        operandoUnido= str(codigoMaquina)+str(operandoHex).zfill(4)
        print(valor, etiqueta, codop, operando, operandoUnido.replace("[","").replace("]","").replace("'",""))
    else:
        pass

    if operando != '' and sistemaNumerico.strip()== "$":
        op= int(operando, 16)
        operandoHex= hex(op).replace("0x","").upper()
        operandoUnido= str(codigoMaquina)+str(operandoHex).zfill(4)
        print(valor, etiqueta, codop, operando, operandoUnido.replace("[","").replace("]","").replace("'",""))
    else:
        pass
    #Decimal
    dec=r'[0-9]'
    deci=re.search(dec, operando)
    if operando != '' and sistemaNumerico.strip() != '%' and sistemaNumerico.strip() != '$' and sistemaNumerico.strip() != '@' and deci:
        op= int(operando, 10)
        operandoHex= hex(op).replace("0x","").upper()
        operandoUnido= str(codigoMaquina)+str(operandoHex).zfill(4)
        print(valor, etiqueta, codop, operando, operandoUnido.replace("[","").replace("]","").replace("'",""))
    else:
        pass

def codigoMaquinaExtendido(valor, etiqueta, codop, operando, codigoMaquina, sistemaNumerico, valorEtiquetaF):

        #Binario
        if operando != '' and sistemaNumerico.strip()== "%" and valorEtiquetaF == 0:
            op= int(operando, 2)
            operandoHex= hex(op).replace("0x","").upper()
            operandoUnido= str(codigoMaquina)+str(operandoHex).zfill(4)
            print(valor, etiqueta, codop, operando, operandoUnido.replace("[","").replace("]","").replace("'",""))
        else:
            pass
        #Octal
        if operando != '' and sistemaNumerico.strip()== "@" and valorEtiquetaF == 0:
            op= int(operando, 8)
            operandoHex= hex(op).replace("0x","").upper()
            operandoUnido= str(codigoMaquina)+str(operandoHex).zfill(4)
            print(valor, etiqueta, codop, operando, operandoUnido.replace("[","").replace("]","").replace("'",""))
        else:
            pass
        if operando != '' and sistemaNumerico=='$' and valorEtiquetaF==0:
            op= int(operando, 16)
            operandoHex= hex(op).replace("0x","").upper()
            operandoUnido= str(codigoMaquina)+str(operandoHex).zfill(4)
            print(valor, etiqueta, codop, operando, operandoUnido.replace("[","").replace("]","").replace("'",""))
        else:
            pass
        if operando != '' and valorEtiquetaF == 0 and sistemaNumerico.strip().isdigit():
            op= int(operando, 10)
            operandoHex= hex(op).replace("0x","").upper()
            operandoUnido= str(codigoMaquina)+str(operandoHex)
            print(valor, etiqueta, codop, operando, operandoUnido.replace("[","").replace("]","").replace("'",""))
        else:
            pass
        if valorEtiquetaF != 0:
            operandoUnido= str(codigoMaquina) + str(valorEtiquetaF)
            print(valor, etiqueta, codop, operando, operandoUnido.replace("[","").replace("]","").replace("'","") )
        else:
            pass
#Calcula el codigo maquina de Los Indexados5bits
def codigoMaquinaIDX5( operando, codigoMaquina):

    formula="rr0nnnnn"
    rr= None

    if operando != None:
        Operando= operando[0:7].replace("(","").replace("'","")

        if Operando.strip() == ",X,":
            Operando= "0,X"

        numDecimal= Operando.replace("X","").replace("Y","").replace("SP","").replace("PC","").replace(",","")
        aBinarioC2 = lambda x, count=8: "".join(map(lambda y:str((x>>y)&1), range(count-1, -1, -1)))
        numeroBinario = aBinarioC2(int(numDecimal,10), 5)
        formula= formula.replace("nnnnn",numeroBinario)

        if Operando.__contains__("X"):
            rr="00"
            formula=formula.replace("rr",rr)
        if Operando.__contains__("Y"):
            rr="01"
            formula=formula.replace("rr",rr)
        if Operando.__contains__("SP"):
            rr="10"
            formula=formula.replace("rr",rr)
        if Operando.__contains__("PC"):
            rr="11"
            formula=formula.replace("rr",rr)
        else:
            pass

        valorCM=hex(int(formula,2)).replace("0x","")
        print(codigoMaquina.replace("[","").replace("]","").replace("'","")+valorCM.zfill(2).upper())

    else:
        pass

def codigoMaquinaIdx9(operando, codigoMaquina):

    formula="111rr0zs"
    operando= operando.strip()

    if operando.__contains__("X'"):
        rr='00'
        formula=formula.replace("rr",rr)
        formula=formula.replace("z",'0')
        formula=formula.replace("s",'0')
    if operando.__contains__("Y'"):
        rr='01'
        formula=formula.replace("rr",rr)
        formula=formula.replace("z",'0')
        formula=formula.replace("s",'0')
    if operando.__contains__("SP'"):
        rr='10'
        formula=formula.replace("rr",rr)
        formula=formula.replace("z",'0')
        formula=formula.replace("s",'0')
    if operando.__contains__("PC'"):
        rr='11'
        formula=formula.replace("rr",rr)
        formula=formula.replace("z",'0')
        formula=formula.replace("s",'0')

    #Hace las operaciones de conversiona binario, luego complemento 2 y al final lo pasa a Hexadecimal y lo concatena
    numeroDecimal= int(operando[0:7].replace("X","").replace("Y","").replace("SP","").replace("PC","").replace(",","").replace("'","").replace("(","").strip())
    aBinarioC2 = lambda x, count=8: "".join(map(lambda y:str((x>>y)&1), range(count-1, -1, -1)))  #Saca el Complemento 2
    numBinario=aBinarioC2(numeroDecimal)
    complementoDOS=hex(int(numBinario,2))

    operandoHex= hex(int(formula,2)).replace("0x","").upper()
    operandoUnido= str(codigoMaquina)+str(operandoHex)+complementoDOS.replace("0x","").replace("-","").upper().zfill(2)
    print(operandoUnido.replace("[","").replace("]","").replace("'",""))

def codigoMaquinaIdx16(operando, codigoMaquina):

    formula="111rr0zs"
    operando= operando.strip()
    if operando.__contains__("X'"):
        rr='00'
        formula=formula.replace("rr",rr)
        formula=formula.replace("z",'1')
        formula=formula.replace("s",'0')
    if operando.__contains__("Y'"):
        rr='01'
        formula=formula.replace("rr",rr)
        formula=formula.replace("z",'1')
        formula=formula.replace("s",'0')
    if operando.__contains__("SP'"):
        rr='10'
        formula=formula.replace("rr",rr)
        formula=formula.replace("z",'1')
        formula=formula.replace("s",'0')
    if operando.__contains__("PC'"):
        rr='11'
        formula=formula.replace("rr",rr)
        formula=formula.replace("z",'1')
        formula=formula.replace("s",'0')

    #Hace las operaciones de conversiona binario, al final lo pasa a Hexadecimal y lo concatena
    numeroDecimal= operando[0:7].replace("X","").replace("Y","").replace("SP","").replace("PC","").replace(",","").replace("'","").replace("(","").strip()
    numeroDecimal= hex(int(numeroDecimal,10))
    aux= int(formula, 2)
    operandoHex= hex(aux).replace("0x","").upper()
    operandoUnido= str(codigoMaquina)+str(operandoHex)+str(numeroDecimal).replace("0x","").upper()
    print(operandoUnido.replace("[","").replace("]","").replace("'",""))

def codigoMaquinaIdxPrePost(operando, codigoMaquina):
    formula="rr1pnnnn"

    operando= operando.strip()

    #REGISTROS
    #X
    if operando.__contains__("+X") or operando.__contains__('-X'):
        rr='00'
        formula=formula.replace("rr",rr)
        p='0'
        formula=formula.replace("p", p)
    elif operando.__contains__("X+") or operando.__contains__('X-'):
        rr='00'
        formula=formula.replace("rr",rr)
        p='1'
        formula=formula.replace("p", p)
    #Y
    if operando.__contains__("+Y") or operando.__contains__('-Y'):
        rr='01'
        formula=formula.replace("rr",rr)
        p='0'
        formula=formula.replace("p", p)
    elif operando.__contains__("Y+") or operando.__contains__('Y-'):
        rr='01'
        formula=formula.replace("rr",rr)
        p='1'
        formula=formula.replace("p", p)
    #SP
    if operando.__contains__("+SP") or operando.__contains__('-SP'):
        rr='10'
        formula=formula.replace("rr",rr)
        p='0'
        formula=formula.replace("p", p)
    elif operando.__contains__("SP+") or operando.__contains__('SP-'):
        rr='10'
        formula=formula.replace("rr",rr)
        p='1'
        formula=formula.replace("p", p)
    #PC
    if operando.__contains__("+PC") or operando.__contains__('-PC'):
        rr='11'
        formula=formula.replace("rr",rr)
        p='0'
        formula=formula.replace("p", p)
    elif operando.__contains__("PC+") or operando.__contains__('PC-'):
        rr='11'
        formula=formula.replace("rr",rr)
        p='1'
        formula=formula.replace("p", p)

    regex= r"[^0-9]"
    subst = ""
    valor= re.sub(regex, subst, operando, 0, re.MULTILINE).strip()

    if operando.__contains__("-"):
        if valor=='8':
            n='1000'
            formula=formula.replace("nnnn", n)
        elif valor=='7':
            n='1001'
            formula=formula.replace("nnnn", n)
        elif valor=='6':
            n='1010'
            formula=formula.replace("nnnn", n)
        elif valor=='5':
            n='1011'
            formula=formula.replace("nnnn", n)
        elif valor=='4':
            n='1100'
            formula=formula.replace("nnnn", n)
        elif valor=='3':
            n='1101'
            formula=formula.replace("nnnn", n)
        elif valor=='2':
            n='1110'
            formula=formula.replace("nnnn", n)
        elif valor=='1':
            n='1111'
            formula=formula.replace("nnnn", n)
    elif operando.__contains__("+"):
        if valor=='8':
            n='0111'
            formula=formula.replace("nnnn", n)
        elif valor=='7':
            n='0110'
            formula=formula.replace("nnnn", n)
        elif valor=='6':
            n='0101'
            formula=formula.replace("nnnn", n)
        elif valor=='5':
            n='0100'
            formula=formula.replace("nnnn", n)
        elif valor=='4':
            n='0011'
            formula=formula.replace("nnnn", n)
        elif valor=='3':
            n='0010'
            formula=formula.replace("nnnn", n)
        elif valor=='2':
            n='0001'
            formula=formula.replace("nnnn", n)
        elif valor=='1':
            n='0000'
            formula=formula.replace("nnnn", n)

    #Hace las operaciones de conversion a binario, al final lo pasa a Hexadecimal y lo concatena
    aux= int(formula, 2)
    operandoHex= hex(aux).replace("0x","").upper()
    operandoUnido= str(codigoMaquina)+str(operandoHex)
    print(operandoUnido.replace("[","").replace("]","").replace("'",""))

def codigoMaquinaIdxAcum(operando, codigoMaquina):

    formula="111rr1aa"
    operando= operando.strip()

    #REGISTROS
    if operando.__contains__("X'"):
        rr='00'
        formula=formula.replace("rr",rr)
    if operando.__contains__("Y'"):
        rr='01'
        formula=formula.replace("rr",rr)
    if operando.__contains__("SP'"):
        rr='10'
        formula=formula.replace("rr",rr)
    if operando.__contains__("PC'"):
        rr='11'
        formula=formula.replace("rr",rr)

    #ACUMULADORES
    if operando.__contains__("'A"):
        aa='00'
        formula=formula.replace("aa",aa)
    if operando.__contains__("'B"):
        aa='01'
        formula=formula.replace("aa",aa)
    if operando.__contains__("'D"):
        aa='10'
        formula=formula.replace("aa",aa)

    #Hace las operaciones de conversion a binario, al final lo pasa a Hexadecimal y lo concatena
    aux= int(formula, 2)
    operandoHex= hex(aux).replace("0x","").upper()
    operandoUnido= str(codigoMaquina)+str(operandoHex)
    print(operandoUnido.replace("[","").replace("]","").replace("'",""))

def codigoMaquina16bitsIndirecto(operando, codigoMaquina):
    formula= "111rr011"
    operando= operando.strip()

    #REGISTROS
    if operando.__contains__("X]"):
        rr='00'
        formula=formula.replace("rr",rr)
    if operando.__contains__("Y]"):
        rr='01'
        formula=formula.replace("rr",rr)
    if operando.__contains__("SP]"):
        rr='10'
        formula=formula.replace("rr",rr)
    if operando.__contains__("PC]"):
        rr='11'
        formula=formula.replace("rr",rr)

    numeroDecimal= operando[0:8].replace("X","").replace("Y","").replace("SP","").replace("PC","").replace(",","").replace("'","").replace("[","").replace("]","").replace("(","").strip()
    numeroDecimal = hex(int(numeroDecimal,10)).upper().replace("0X","")
    aux= int(formula,2)
    operandoHex= hex(aux).replace("0x","").upper()
    operandoUnido= str(codigoMaquina.replace("[","").replace("'","").replace("]","")) + str(operandoHex) + numeroDecimal.zfill(4)
    print(operandoUnido.replace("0x","").upper())

def codigoMaquinaIndexadoAcumD(operando, codigoMaquina):
    formula= "111rr111"
     #REGISTROS
    if operando.__contains__("X]'"):
        rr='00'
        formula=formula.replace("rr",rr)
    if operando.__contains__("Y]'"):
        rr='01'
        formula=formula.replace("rr",rr)
    if operando.__contains__("SP]'"):
        rr='10'
        formula=formula.replace("rr",rr)
    if operando.__contains__("PC]'"):
        rr='11'
        formula=formula.replace("rr",rr)
    print(formula)
    aux= int(formula,2)
    operandoHex= hex(aux).replace("0x","").upper()
    operandoUnido= str(codigoMaquina.replace("[","").replace("'","").replace("]","").zfill(2)) + str(operandoHex)
    print(operandoUnido.replace("0x","").upper())

def valorCodigoMaquina(Dataframe, lista, modoDir):
    datos_Tabop= pd.read_excel(ruta_Archivo, sheet_name="Hoja1", header=3)
    DataFrame= pd.DataFrame(datos_Tabop)
    DataFrameFiltrado=DataFrame[DataFrame['CODOP'].isin(lista)]     #Busca el codop en el tabop

    valor= (DataFrameFiltrado['Código Máquina Calculado'].all()) and (DataFrameFiltrado["Addr. Mode"]== modoDir)
    valorCodigoMaquina= DataFrameFiltrado["Código Máquina Calculado"].loc[valor]
    if valorCodigoMaquina.values.__contains__("Cero"):
        valorCodigoMaquina=0
        return valorCodigoMaquina
    else:
        return str(valorCodigoMaquina.values)

#Valida la exitencia de la eqtiqueta en el tabsim y devileve el valor si lo encuentra
def validarExistenciaEtiqueta( filename,operando):
    opi= operando.split(",")
    valorEtiqueta=opi[0].replace("(","").replace("'","")

    with open(filename, 'r') as read_obj:
        # Lee todas las lineas del archivo de una por una
        for line in read_obj:
            valor= line[-5]+ line[-4] + line[-3] +line[-2]+line[-1]
            if str(valorEtiqueta).strip() in line:
                return valor.strip()
    return False

############################################################# MAIN ##########################################################################

#Importamos librerias y declaramos variables necesariasimport re
import sys
import re
import pandas as pd
from colorama import Back, Fore, Style, init

separador = "\n"
sepTabulador= chr(9)
sepEspacio= chr(32)

#Leemos el archivo excel y lo metemos en un dataframe
ruta_Archivo= "Tabop.xlsx"
datos= pd.read_excel(ruta_Archivo, sheet_name="Hoja1", header=3)
Dataframe= pd.DataFrame(datos)

#Lee el archivo, lo separa y lo mete en una lista linea por linea
with open('P2ASM.txt', 'r') as f:

    lineas = [linea.split(separador) for linea in f]

#Lista para guardar los CODOP
lista=[]
listaEtq= []
archivoTmp= open('P4tmp.txt','r+')
TABSIM= open('TABSIM.txt','r+')

#Obtiene el valor del ORG
for i in range(0, len(lineas)):
    DIR_INIC=valorDelORG(lineas[i])
    if DIR_INIC is not None:
        break

VALOR_EQU= 0000
CONTLOC= 0000
contlocHEX= 0

#For principal que ejecuta el programa
for i in range(0, len(lineas)):
    sin_Espacios=t_CODOP(lineas[i]).strip() #Quitamos los espacios al CODOP para comparar mas facil
    lista.append(sin_Espacios)              #Metemos en la lista
    t_COMENTARIO(lineas[i])
    print("ETIQUETA= " + str(t_ETIQUETA(lineas[i])))
    print( "CODOP= " + t_CODOP(lineas[i]) )
    #buscar_enTabop(Dataframe,lista)
    rel=Relativo(Dataframe)
    inme=Inmediato(Dataframe)
    inh=Inherente(Dataframe)
    print("OPERANDO= " + str(t_OPERANDO(lineas[i], rel, inme,inh)))

    errllevaOp=0
    errNollevaOp=0

    #Identifica si debe lleva operando o no
    if llevaOperando(Dataframe , lista) and t_OPERANDO(lineas[i], rel , inme, inh) is None:
        errllevaOp=1
        print(Fore.RED + "Error, Debe llevar operando")
    init(autoreset=True)

    if llevaOperando(Dataframe , lista) is False and t_OPERANDO(lineas[i], rel, inme, inh).__contains__('1') is False and t_OPERANDO(lineas[i], rel, inme, inh).__contains__('Inherente, Un byte') is False:
        errNollevaOp=1
        print(Fore.RED + "Error, No debe llevar operando")
    init(autoreset=True)

    if llevaOperando(Dataframe , lista) is False and t_OPERANDO(lineas[i], rel, inme, inh).__contains__('1') and t_OPERANDO(lineas[i], rel, inme, inh).__contains__('Inherente, Un byte'):
        errNollevaOp=0

    #Variables con los valores base
    etiqueta= str(t_ETIQUETA(lineas[i])).strip()
    codop= str(t_CODOP(lineas[i])).strip()
    operando= str(t_OPERANDO(lineas[i], rel, inme,inh)).strip()

    #Mete las etiquetas en una lista para despues comparar con el TABSIM
    if t_ETIQUETA(lineas[i]) is not None:
        listaEtq.append(etiqueta)
    else:
        pass

    #Saca el numero limpio del operando
    regex= r"[^0-9]"
    subst = ""
    operandoNumerico = re.sub(regex, subst, operando, 0, re.MULTILINE).strip()

    #Identifica el sistema numerico
    regex = r"(%|@|\$|[0-9])"
    filtrado= re.search(regex, operando, re.MULTILINE)
    if filtrado:
        sistemaNumerico= filtrado.group().strip()

    #Variable que diferencia entre indexados
    indexar='0'

    #Identificar el modo de Direccionamiento del operando
    if str(t_OPERANDO(lineas[i],rel, inme,inh)).__contains__("Inherente"):
        modoDir= "Inherente"
    elif str(t_OPERANDO(lineas[i],rel, inme,inh)).__contains__("Directo"):
        modoDir= "Directo"
    elif str(t_OPERANDO(lineas[i],rel, inme,inh)).__contains__("Extendido"):
        modoDir= "Extendido"
    elif str(t_OPERANDO(lineas[i],rel, inme,inh)).__contains__("Inmediato"):
        modoDir= "Inmediato"
    elif str(t_OPERANDO(lineas[i],rel, inme,inh)).__contains__("Indexado de Cinco bits"):
        modoDir= "IDX"
        indexar='5'
    elif str(t_OPERANDO(lineas[i],rel, inme,inh)).__contains__("Indexado de Nueve bits"):
        modoDir= "IDX1"
        indexar='9'
    elif str(t_OPERANDO(lineas[i],rel, inme,inh)).__contains__("Indexado de Dieciseis bits"):
        modoDir= "IDX2"
        indexar='16'
    elif str(t_OPERANDO(lineas[i],rel, inme,inh)).__contains__("Auto Pre/Post Decremento/Incremento"):
        modoDir= "IDX"
        indexar='+-'
    elif str(t_OPERANDO(lineas[i],rel, inme,inh)).__contains__("Indexado de acumulador indirecto"):
        modoDir= "[D,IDX]"
    elif str(t_OPERANDO(lineas[i],rel, inme,inh)).__contains__("Indexado de acumulador"):
        modoDir= "IDX"
        indexar='AC'
    elif str(t_OPERANDO(lineas[i],rel, inme,inh)).__contains__("[IDX2]"):
        modoDir= "[IDX2]"

    #Comprueba si el valor esta en hexadecimal
    if modoDir =="Extendido" or modoDir == "Directo" or modoDir == "Inmediato":
        recExt=r"\$[0-9A-F]+[$']"
        reconocido=re.search(recExt, operando)
        if reconocido:
            regex=r"[^0-9A-F]"
            subst = ""
            operandoNumerico = re.sub(regex, subst, reconocido.group(), 0, re.MULTILINE).strip()
            hexa=1
        else:
            hexa=0
    else:
        hexa=0

    #Pasa el valor del EQU a hexadecimal
    if operandoNumerico != "" and hexa==0:
        auxEQU= int(operandoNumerico)
        VALOR_EQU= hex(auxEQU).lstrip('0x').zfill(4).upper()

    if operandoNumerico != "" and hexa ==1:
        auxEQU=int(operandoNumerico, 16)
        VALOR_EQU= hex(auxEQU).lstrip('0x').zfill(4).upper()

    #Detecta el org y incia el contloc
    if codop.strip() == "ORG":
        CONTLOC= int(limpiaORG(DIR_INIC))
        archivoTmp.write("DIR_INIC" + "\t" + str(CONTLOC).zfill(4) + "\t" + str(etiqueta) + "\t" + str(codop) + "\t" + str(operandoNumerico) + "\n")
    else:
        pass

        #Escribe en el archivoTMP segun sea necesario
    if codop.strip() != "EQU" and codop.strip() != "ORG" and errllevaOp !=1 and errNollevaOp !=1:
        contlocHEX=hex(CONTLOC).lstrip('0x').zfill(4).upper()
        escribirArchivoTemporal(contlocHEX, etiqueta, codop, operandoNumerico, VALOR_EQU )
        aumentoCONTLOC=int(analizaDirectiva(codop, operandoNumerico,operando))   #Calcula el aumento del contloc
        CONTLOC= int(CONTLOC) + int(aumentoCONTLOC)
        validarDirectivas(aumentoCONTLOC, etiqueta, codop, operandoNumerico, operando)

    elif codop.strip() == "EQU":
        escribirArchivoTemporal(contlocHEX, etiqueta, codop, operandoNumerico, VALOR_EQU )
    elif errllevaOp == 1:
        contlocHEX=hex(CONTLOC).lstrip('0x').zfill(4).upper()
        escribirArchivoTemporal(contlocHEX, etiqueta, codop, 0, VALOR_EQU )
        aumentoCONTLOC=0
        CONTLOC= int(CONTLOC) + int(aumentoCONTLOC)
    elif errNollevaOp == 1:
        contlocHEX=hex(CONTLOC).lstrip('0x').zfill(4).upper()
        escribirArchivoTemporal(contlocHEX, etiqueta, codop, 0, VALOR_EQU )
        aumentoCONTLOC=0
        CONTLOC= int(CONTLOC) + int(aumentoCONTLOC)

    #Escribe los datos necesarios al TABSIM
    if t_ETIQUETA(lineas[i]) is not None:
            escribeTABSIM(contlocHEX, etiqueta, VALOR_EQU, codop)
    else:
        pass

    #Obtiene el valor del codigo maquina y muestra la informacion
    if codop.strip() != "EQU" and modoDir== "Inherente":
        valorCM= valorCodigoMaquina(Dataframe, lista, modoDir)
        valor= 0
        codigoMaquinaInherente(contlocHEX, etiqueta, codop, operandoNumerico, valorCM)
    else:
        pass

    if codop.strip() != "EQU" and modoDir == "Directo":
        valorCM= valorCodigoMaquina(Dataframe, lista, modoDir)
        valor= 0
        codigoMaquinaDirecto(contlocHEX, etiqueta, codop,  operandoNumerico, valorCM  )
    else:
        pass

    if codop.strip() != "EQU" and modoDir == "Inmediato":
        valorCM= valorCodigoMaquina(Dataframe, lista, modoDir)
        valor= 0
        codigoMaquinaInmediato(contlocHEX, etiqueta, codop,  operandoNumerico, valorCM , sistemaNumerico )
    else:
        pass

    if codop.strip() != "EQU" and modoDir == "Extendido":
        valorCM= valorCodigoMaquina(Dataframe, lista, modoDir)
        valor= 0
        filename= "TABSIM.txt"

        if validarExistenciaEtiqueta(filename,operando) and sistemaNumerico.strip() != '':
            valorEtiquetaF=validarExistenciaEtiqueta(filename, operando)
            codigoMaquinaExtendido(contlocHEX, etiqueta, codop, operandoNumerico, valorCM, sistemaNumerico, valorEtiquetaF)
        elif sistemaNumerico.strip() == '%' or sistemaNumerico.strip() == '$' or sistemaNumerico.strip() == '@' or sistemaNumerico.strip().isdigit():
            codigoMaquinaExtendido(contlocHEX, etiqueta, codop,  operandoNumerico, valorCM , sistemaNumerico, 0 )
        else:
            print("La etiqueta no se encuentra en el TABSIM, Error")
    else:
        pass

    if codop.strip() != "EQU" and modoDir == "IDX" and indexar=='5':
        valorCM= valorCodigoMaquina(Dataframe, lista, modoDir)
        valor=0
        codigoMaquinaIDX5(operando, valorCM)
    else:
        pass

    if codop.strip() != "EQU" and modoDir == "IDX1" and indexar=='9':
        valorCM= valorCodigoMaquina(Dataframe, lista, modoDir)
        valor=0
        codigoMaquinaIdx9(operando, valorCM)
    else:
        pass

    if codop.strip() != "EQU" and modoDir == "IDX2" and indexar=='16':
        valorCM= valorCodigoMaquina(Dataframe, lista, modoDir)
        valor=0
        codigoMaquinaIdx16(operando, valorCM)
    else:
        pass

    if codop.strip() != "EQU" and modoDir == "IDX" and indexar=='+-':
        valorCM= valorCodigoMaquina(Dataframe, lista, modoDir)
        valor=0
        codigoMaquinaIdxPrePost(operando, valorCM)
    else:
        pass

    if codop.strip() != "EQU" and modoDir == "[D,IDX]":
        valorCM= valorCodigoMaquina(Dataframe, lista, modoDir="[D,IDX]")
        codigoMaquinaIndexadoAcumD(operando, valorCM)
    else:
        pass

    if codop.strip() != "EQU" and modoDir == "IDX" and indexar=='AC':
        valorCM= valorCodigoMaquina(Dataframe, lista, modoDir)
        codigoMaquinaIdxAcum(operando, valorCM)
    else:
        pass

    if codop.strip() != "EQU" and modoDir == "[IDX2]":
        valorCM= valorCodigoMaquina(Dataframe, lista, modoDir="[IDX2]")
        codigoMaquina16bitsIndirecto(operando, valorCM)
    else:
        pass

    lista=[None]                          #Vaciamos la lista para mayor limpieza
    print(" \n ")

for linea in lineas:
    print(linea)


#Creado por:Efren Jimenez
#Fecha:21/03/2018
#Objetivo: Ejercicio 1

def ObtenerDatos():
    contador=0
    variable1=0
    variable2 = 0
    variable3 = 0
    variable4 = 0
    variable5 = 0

    while contador<5:
        valor=int(input("Digite un numero"))
        if(contador==0):
            variable1=valor
        if (contador == 1):
            variable2 = valor
        if (contador == 2):
            variable3 = valor
        if (contador == 3):
            variable4 = valor
        if (contador == 4):
            variable5 = valor
        contador=contador+1
    retorno=Duplicados(variable1,variable2,variable3,variable4,variable5)
    if retorno==True:
        print("Si hay valores repetidos")
    else:
        print("No hay valores repetidos")

def Duplicados(variable1,variable2,variable3,variable4,variable5):
    if(variable1==variable2) or (variable1==variable3) or (variable1==variable4) \
            or (variable1==variable5) :
        return True
    if (variable2 == variable3) or (variable2 == variable4) or (variable2 == variable5):
        return True
    if (variable3 == variable4) or (variable3 == variable5):
        return True
    if (variable4 == variable5):
        return True
    return False

ObtenerDatos()


from typing import Set, List, Union

import networkx
from flloat.parser.ltlf import LTLfParser
from flloat.semantics.pl import _PLInterpretation
from pythomata.base import DFA

import autograph.lib.hoa as hoa

def style_agraph(network: networkx.MultiDiGraph, currentstates: List[int], layout="dot"):
    """
    Turn an automaton network into a nicely styled agraph (graphviz graph).
    :param network: The network to format
    :param currentstates: A list of states to highlight in the output
    :return: The formatted graph
    """
    graph = networkx.drawing.nx_agraph.to_agraph(network)

    for state in currentstates:
        node = graph.get_node(state)
        node.attr["style"] = "filled"
        node.attr["fillcolor"] = "yellow"

    for state in network:
        acc = network.nodes[state]["acceptance"]
        if acc and len(acc) > 0:
            # graph.get_node(state).attr["label"] = str(state) + "\n" + str(acc)
            graph.get_node(state).attr["shape"] = "doublecircle"
        else:
            graph.get_node(state).attr["shape"] = "circle"

    for u, v, key, data in network.edges(keys=True, data=True):
        graph.get_edge(u, v, key).attr["label"] = " " + data["label"] + " "

    # graph.add_node("start")
    # graph.get_node("start").attr["style"] = "invis"
    # graph.add_edge("start", network.graph["start"])

    if layout:
        graph.layout(prog=layout)

    return graph

class AutomatonSet:
    """
    An automaton, along with one or more states that the automaton is currently in.
    """

    def __init__(self, graph: "AutomatonGraph", states: Set[int]):
        self.states = states
        self.graph = graph

    @staticmethod
    def from_hoa(automaton: hoa.HOA):
        """
        Create an automaton graph from a parsed HOA file
        :param automaton: The HOA file
        :return: An automaton in the start state
        """
        graph, start = AutomatonGraph.from_hoa(automaton)
        return AutomatonSet(graph, {start})

    @staticmethod
    def from_ltlf(ltl: str, apnames: List[str]):
        graph, start = AutomatonGraph.from_ltlf(ltl, apnames)
        return AutomatonSet(graph, {start})

    def _repr_svg_(self):
        return self.graph.to_image(self.states)

    def transition(self, aps):
        """
        Transition an automaton from all the states it might be in now to all the states that
        :param aps: A bitmap of atomic propositions to determine which transitions to take
        """
        states = [self.graph.transition_states(state, aps) for state in self.states]

        return AutomatonSet(self.graph, set().union(*states))

    def acceptance(self):
        """
        Get a set of all acceptances which are currently satisfied by any state that the automaton may be in
        """
        accs = [self.graph.acceptance(state) for state in self.states]

        return set().union(*accs)

    def reaches_acceptance(self):
        return any(map(self.graph.reaches_acceptance, self.states))

    def __eq__(self, other):
        return isinstance(other, AutomatonSet) and self.states == other.states and self.graph == other.graph

def alike(tup1, tup2):
    diff = sum(0 if e1 == e2 else 1 for e1, e2 in zip(tup1, tup2))
    return diff <= 1

def combined_tuple(tup1, tup2):
    return tuple(e1 if e1 == e2 else "X" for e1, e2 in zip(tup1, tup2))

def simplify_conds(conds):
    """
    Combine multiple conditions into as few as possible.
    For example, (1, 0, 1) and (1, 0, 0) become (1, 0, X).
    This process is repeated until it doesn't do anything.
    Note that this may not be a perfect solution (np-complete problem), but it provides a decent approximation.
    :param conds:
    :return:
    """
    conds = sorted(conds)

    lastconds = None
    while lastconds != conds:
        lastconds = conds.copy()
        conds = set()
        for cond in lastconds:
            added = False

            for comp in conds:
                if alike(cond, comp):
                    conds.remove(comp)
                    conds.add(combined_tuple(cond, comp))
                    added = True
                    break

            if not added:
                conds.add(cond)

    return conds

class evaluator():
    def __init__(self, c):
        self.c = c

    def __call__(self, aps):
        return tuple(aps) in self.c

class AutomatonGraph:
    """
    Stateless representation of an automaton which may be non-deterministic
    """

    def __init__(self, network: networkx.MultiDiGraph):
        self.network = network
        accepted_states = [node for node in network.nodes if len(self.acceptance(node)) > 0]
        path_lengths = {fr: to for fr, to in networkx.all_pairs_shortest_path_length(network)}
        self.reachable = {node for node in network.nodes if
                          any(map(lambda dest: dest in path_lengths[node], accepted_states))}

    @staticmethod
    def from_hoa(automaton: hoa.HOA):
        """
        Turn a parse tree of a hoa file into an automaton and extract the starting state
        :return: The graph, and the starting state of the graph
        """
        graph = networkx.MultiDiGraph()

        start = None
        alias = dict()
        apnames = None

        # Process headers
        for headeritem in automaton.header.items:
            if isinstance(headeritem, hoa.StartHeader):  # Starting state of automaton
                start = int(headeritem.startstate)
            elif isinstance(headeritem, hoa.AliasHeader):  # Take care of aliases
                alias[headeritem.name] = headeritem.label
            elif isinstance(headeritem, hoa.APHeader):  # Names of atomic propositions
                apnames = [name.value for name in headeritem.props]

        assert start is not None, "Automaton needs a start value"
        assert apnames is not None, "Automaton needs to have at least one atomic proposition"

        # Add each individual state to graph
        for state in automaton.body:
            id = int(state.id)
            accsig = state.accsig if state.accsig else []
            accsig: Set[int] = {int(condition) for condition in accsig}
            graph.add_node(id, acceptance=accsig)

            for edge in state.edges:
                assert not edge.accsig, "Automaton must use state-based acceptance"
                to = int(edge.dest_state)
                lbl: hoa.LabelExpr = edge.label.value

                # Generate evaluator for edge (accepts array of APs and outputs bool)
                graph.add_edge(id, to, evaluator=lbl.generate_evaluator(alias), label=lbl.str_with_ap_names(apnames))

        graph.graph["start"] = start

        return AutomatonGraph(graph), start

    @staticmethod
    def from_ltlf(ltlf: str, ap_names: List[str]):
        """
        Construct an automaton graph from a DFA
        :param ltlf: The ltlf formula
        :param ap_names: An ordered list of names for the atomic propositions
        """
        ltl_parser = LTLfParser()

        # Parse to DFA
        parsed_formula = ltl_parser(ltlf)
        dfa: DFA = parsed_formula.to_automaton(determinize=True)
        assert 2 ** len(ap_names) == len(dfa.alphabet.symbols), "Alphabet size mismatch- make sure your ap_names are " \
                                                                "the right length"
        graph = networkx.MultiDiGraph()

        for state in dfa.states:
            trans_to = dfa.transition_function[state]
            states_to = dict()

            accsig = {0} if state in dfa.accepting_states else set()
            graph.add_node(state, acceptance=accsig)

            # Go from {set(atomprop):state} to {state:f_set([atomprop-bitmap])}

            # Collect {state:list[set(atomprop)]}
            for cond, dest in trans_to.items():
                if dest not in states_to:
                    states_to[dest] = [cond]
                else:
                    states_to[dest].append(cond)

            # set(atomprop) -> [atomprop-bitmap]
            def bitmap_for_conditions(cond: _PLInterpretation):
                return tuple([name in cond.true_propositions for name in ap_names])

            # Put it all together
            states_to_bitmap = {to: frozenset(map(bitmap_for_conditions, conds)) for to, conds in states_to.items()}

            for to, conds in states_to_bitmap.items():
                graph.add_edge(state, to,
                               evaluator=evaluator(conds),
                               label=str(simplify_conds(conds)).replace("\'X\'", "X").replace("True", "T").replace(
                                   "False", "F"))

        graph.graph["start"] = dfa.initial_state
        return AutomatonGraph(graph), dfa.initial_state

    def transition_states(self, state: int, aps: List[bool]):
        """
        What states can be the direct result of a given transition?
        :param state: The state that the transition starts at
        :param aps: A bitmap of atomic propositions that are True and False
        :return: A set of states that the automaton transitions to
        """
        outstates = set()

        for u, v, data in self.network.edges(state, data=True):
            label: hoa.Evaluator = data["evaluator"]
            if label(aps):
                outstates.add(int(v))

        return outstates

    def reaches_acceptance(self, state):
        return state in self.reachable

    def acceptance(self, state):
        """
        Get the acceptance conditions for a given state
        :return: A set of acceptance conditions
        """
        return self.network.nodes[state]["acceptance"]

    def to_image(self, current_state: Union[int, Set[int]] = None):
        """
        Render an AutomationGraph to an image, used for public access to _repr_svg_
        :param current_state: Either a state number or set of states that the automaton is in
        :return: An svg image
        """
        return self._repr_svg_(current_state)

    def _repr_svg_(self, current_state: Union[int, Set[int]] = None):
        if current_state is None:
            current_state = set()

        if isinstance(current_state, int):
            current_state = [current_state]

        return style_agraph(self.network, current_state).draw(format='svg').decode("utf-8")


#!/usr/bin/env python
from __future__ import print_function

import json
import os
import sys

from unittest import TestCase
import pandas as pd

from utils import TemporaryDirectory, Move, TestData, touch, TemporaryFile
from utils import run_task, check_status
from dammit import common
from dammit import tasks
from dammit.common import run_tasks
from dammit.parsers import hmmscan_to_df_iter

class TestHMMERTasks(TestCase):

    @classmethod
    def setup_class(cls):
        cls.hmmscan_cfg = common.CONFIG['settings']['hmmer']['hmmscan']
        cls.hmmpress_cfg = common.CONFIG['settings']['hmmer']['hmmscan']
        cls.extensions = ['.h3f', '.h3i', '.h3m', '.h3p']

    def test_hmmpress_task(self):
        with TemporaryDirectory() as td:
            with Move(td):
                with TestData('test-profile.hmm', td) as tf:
                    task = tasks.get_hmmpress_task(tf, self.hmmpress_cfg)
                    run_tasks([task], ['run'])
                    status = check_status(task)
                    print(os.listdir(td), file=sys.stderr)

                    for ext in self.extensions:
                        self.assertTrue(os.path.isfile(tf + ext))

                    self.assertEquals(status.status, 'up-to-date')

    def test_hmmpress_task_existing(self):
        with TemporaryDirectory() as td:
            with Move(td):
                with TestData('test-profile.hmm', td) as tf:
                    for ext in self.extensions:
                        touch(tf + ext)

                    task = tasks.get_hmmpress_task(tf, self.hmmpress_cfg)
                    run_tasks([task], ['run'])
                    print(os.listdir(td), file=sys.stderr)
                    print(task, file=sys.stderr)
                    status = check_status(task)

                    self.assertEquals(status.status, 'up-to-date')

    def test_hmmscan_task(self):
        with TemporaryDirectory() as td:
            with Move(td):
                with TestData('test-protein.fa', td) as prot, \
                     TestData('test-profile.hmm', td) as hmm, \
                     TemporaryFile(td) as out:

                    db_task = tasks.get_hmmpress_task(hmm, self.hmmpress_cfg)
                    aln_task = tasks.get_hmmscan_task(prot, out, hmm, 1.0, 1,
                                                      self.hmmscan_cfg)
                    run_tasks([db_task, aln_task], ['run'])
                    print(os.listdir(td), file=sys.stderr)
                    aln = open(out).read()
                    print(aln)

                    self.assertEquals(aln.count('accession'), 2)
                    self.assertIn('i-Evalue', aln)

    def test_hmmscan_task_multithreaded(self):
        with TemporaryDirectory() as td:
            with Move(td):
                with TestData('20aa-alitest.fa', td) as prot, \
                     TestData('20aa.hmm', td) as hmm, \
                     TemporaryFile(td) as out_single,\
                     TemporaryFile(td) as out_multi:

                    for n_threads in (2,3,4,5):
                        db_task = tasks.get_hmmpress_task(hmm, self.hmmpress_cfg)
                        aln_task_single = tasks.get_hmmscan_task(prot, out_single,
                                                                 hmm, 1.0, 1,
                                                                 self.hmmscan_cfg)
                        aln_task_multi = tasks.get_hmmscan_task(prot, out_multi,
                                                                hmm, 1.0, n_threads,
                                                                self.hmmscan_cfg)
                        run_tasks([db_task, aln_task_single], ['run'])
                        run_task(aln_task_multi)
                        print(os.listdir(td), file=sys.stderr)

                        print(open(out_single).read())
                        alns_single = pd.concat(hmmscan_to_df_iter(out_single))
                        alns_multi = pd.concat(hmmscan_to_df_iter(out_multi))

                        self.assertTrue(all(alns_single['domain_i_evalue'].sort_values() == \
                                            alns_multi['domain_i_evalue'].sort_values()))


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

import importlib
import logging

from quart import Quart, jsonify, request

from message_handler import Message_handler

from logging.config import dictConfig

import wfstate as wf

dictConfig({
    'version': 1,
    'loggers': {
        'quart.app': {
            'level': 'INFO',
        },
    },
})

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
    datefmt='%m-%d %H:%M',
    handlers=[
        logging.FileHandler(
            'qqbot.log',
            'a',
            'utf-8')])

app = Quart(__name__)

handler = Message_handler()

@app.route('/', methods=['POST'])
async def post():
    try:
        # POSTed data as json
        j = await request.get_json(force=True)

        if j['message_type'] == 'group':
            if 'card' in j['sender'] and j['sender']['card'] != '':
                app.logger.info('[%s][%s(%s)]:%s' % (j['group_id'], j['sender']['card'], j['sender']['user_id'], j['message']))
            elif 'nickname' in j['sender'] and j['sender']['nickname'] != '':
                app.logger.info('[%s][%s(%s)]:%s' % (j['group_id'], j['sender']['nickname'], j['sender']['user_id'], j['message']))
            else:
                app.logger.info('[%s][%s]:%s' % (j['group_id'], j['sender']['user_id'], j['message']))
        else:
            app.logger.info('[%s]:%s' % (j['sender']['user_id'], j['message']))

        message, status_code = handler.handle(j)

        return jsonify(message), status_code

    except Exception as e:
        print(e)
        return '', 204

@app.route('/', methods=['PATCH'])
async def patch():
    try:
        try:
            request_token = await request.get_json(force=True)['token']
        except BaseException:
            request_token = ''
        handler.reload(request_token)
    except Exception as e:
        return print(e), 500

handler.add_job(wf.get_new_alerts, second='00')
handler.add_job(wf.get_cetus_transition, second='05')
handler.add_job(wf.get_new_acolyte, second='00')

if __name__ == '__main__':
    app.run(debug=False, port=8888)


import re
import json
import time

from django.conf import settings
from django.contrib.staticfiles.storage import staticfiles_storage
from django.utils.module_loading import import_string

__all__ = ('get_assets', 'get_config', 'get_bundle',)

DEFAULT_CONFIG = {
    'DEFAULT': {
        'BUNDLE_DIR_NAME': 'webpack_bundles/',
        'STATS_FILE': 'webpack-stats.json',
        # FIXME: Explore usage of fsnotify
        'POLL_INTERVAL': 0.1,
        'IGNORE': ['.+\.hot-update.js', '.+\.map'],
        'GET_CHUNK_URL': 'webpack_loader.utils.default_chunk_url',
    }
}

user_config = getattr(settings, 'WEBPACK_LOADER', DEFAULT_CONFIG)

user_config = {
    name: dict(DEFAULT_CONFIG['DEFAULT'], **cfg)
    for name, cfg in user_config.items()
}

for entry in user_config.values():
    entry['ignores'] = [re.compile(I) for I in entry['IGNORE']]

class WebpackError(Exception):
    pass

class WebpackLoaderBadStatsError(Exception):
    pass

def get_config(config_name):
    config = user_config[config_name]
    if 'get_chunk_url' not in config:
        config['get_chunk_url'] = config['GET_CHUNK_URL'] if callable(config['GET_CHUNK_URL']) else import_string(config['GET_CHUNK_URL'])
    return config

def get_assets(config):
    try:
        with open(config['STATS_FILE']) as f:
            return json.load(f)
    except IOError:
        raise IOError(
            'Error reading {}. Are you sure webpack has generated the file '
            'and the path is correct?'.format(config['STATS_FILE']))

def filter_files(files, config):
    for F in files:
        filename = F['name']
        ignore = any(regex.match(filename) for regex in config['ignores'])
        if not ignore:
            relpath = '{}{}'.format(config['BUNDLE_DIR_NAME'], filename)
            F['url'] = staticfiles_storage.url(relpath)
            yield F

def get_bundle(bundle_name, config):
    assets = get_assets(config)

    if settings.DEBUG:
        # poll when debugging and block request until bundle is compiled
        # TODO: support timeouts
        while assets['status'] == 'compiling':
            time.sleep(config['POLL_INTERVAL'])
            assets = get_assets(config)

    if assets.get('status') == 'done':
        files = assets['chunks'][bundle_name]
        return filter_files(files, config)

    elif assets.get('status') == 'error':
        if 'file' not in assets:
            assets['file'] = ''
        error = u"""
        {error} in {file}
        {message}
        """.format(**assets)
        raise WebpackError(error)

    raise WebpackLoaderBadStatsError(
        "The stats file does not contain valid data. Make sure "
        "webpack-bundle-tracker plugin is enabled and try to run "
        "webpack again.")

def default_chunk_url(chunk, config):
    url = chunk.get('publicPath') or chunk['url']
    return url


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

import json
from django.core.serializers.json import DjangoJSONEncoder
from django.db import models, migrations
import wagtail.wagtailimages.blocks
import wagtail.wagtailcore.fields
import wagtail.wagtailcore.blocks
import ellen.blocks

def convert_referral_links_to_struct_with_url(apps, schema_editor):
    LandingPage = apps.get_model('ellen', 'LandingPage')

    for page in LandingPage.objects.all():
        new_page_body = []

        for child in page.body:
            prep_value = None

            if child.block_type == 'as_seen_in':
                prep_value = [{
                    'thumbnail': image.pk,
                    'url': 'http://example.com',
                } for image in child.value ]
            else:
                prep_value = child.block.get_prep_value(child.value)

            new_page_body.append({
                'type': child.block_type,
                'value': prep_value
            })

        page.body = wagtail.wagtailcore.blocks.StreamValue(page.body.stream_block, [], raw_text=json.dumps(new_page_body, cls=DjangoJSONEncoder))
        page.save()

class Migration(migrations.Migration):

    dependencies = [
        ('ellen', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(
            convert_referral_links_to_struct_with_url,
        ),
        migrations.AlterField(
            model_name='landingpage',
            name='body',
            field=wagtail.wagtailcore.fields.StreamField((('paragraph', wagtail.wagtailcore.blocks.RichTextBlock()), ('featured_stories', ellen.blocks.FeaturedStoriesBlock(ellen.blocks.StoryChooserBlock())), ('as_seen_in', ellen.blocks.ReferralLinksBlock(wagtail.wagtailcore.blocks.StructBlock((('thumbnail', wagtail.wagtailimages.blocks.ImageChooserBlock()), ('url', wagtail.wagtailcore.blocks.URLBlock())))))), blank=True, null=True),
        ),
    ]


import face_alignment
from skimage import io
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from mpldatacursor import datacursor

fa = face_alignment.FaceAlignment(face_alignment.LandmarksType._3D, device='cpu', flip_input=False)

input = io.imread('test/assets/aflw-test.jpg')
preds = fa.get_landmarks(input)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

def func():
    for i,spot in enumerate(preds[0]):
        print(spot)
        spotX=spot[0]
        spotY=spot[1]
        spotZ=spot[2]
        ax.scatter(spotX,spotY,spotZ,marker='x')
        ax.text(spotX,spotY,spotZ,i)

func()
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()


import numpy as np
from matplotlib import pyplot as plt

def plot_overlay(test_accuracy,
                 training_accuracy,
                 num_epochs,
                 xmin,
                 training_set_size):

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot(np.arange(xmin, num_epochs),
            [accuracy/100.0 for accuracy in test_accuracy],
            color='#2A6EA6',
            label="Accuracy on the test data")
    ax.plot(np.arange(xmin, num_epochs),
            [accuracy*100.0/training_set_size
             for accuracy in training_accuracy],
            color='#FFA933',
            label="Accuracy on the training data")
    ax.grid(True)
    ax.set_xlim([xmin, num_epochs])
    ax.set_xlabel('Epoch')
    ax.set_ylim([90, 100])
    plt.legend(loc="lower right")
    plt.show()