from typing import List, Optional, Tuple, Union

from arcade import Window

from spg.core.view import View

class ViewManager:
    def __init__(
        self,
        background: Optional[
            Union[Tuple[int, int, int], List[int], Tuple[int, int, int, int]]
        ] = None,
        **_
    ):

        if not background:
            background = (0, 0, 0, 255)

        if len(background) == 3:
            background = (*background, 255)

        self.background = background

        self.views: List[View] = []

        self._window = Window(1, 1, visible=False, antialiasing=False)  # type: ignore

    @property
    def ctx(self):
        return self._window.ctx

    @property
    def window(self):
        return self._window

    def add_view(self, view):

        if view in self.views:
            raise ValueError("View already added")

        self.views.append(view)

        for element in self.elements:
            view.add(element)

        for agent in self.agents:
            view.add(agent)

    def remove_view(self, view):
        self.views.remove(view)

    # @property
    # def ray_compute(self):

    #     if not self._ray_compute:
    #         assert self._size
    #         self._ray_compute = RayCompute(
    #             self, self._size, self._center, zoom=1, use_shader=self._use_shaders
    #         )

    #     return self._ray_compute

    # if self._ray_compute:
    #     self._ray_compute.update_sensors()

    # def add_view(self, view):
    #
    #     for entity in self.elements:
    #         view.add(entity)
    #
    #         if isinstance(entity, PhysicalElement):
    #             for interactive in entity.interactives:
    #                 view.add(interactive)
    #
    #     for agents in self.agents:
    #         for part in agents.parts:
    #             view.add(part)
    #
    #             for device in part.devices:
    #                 view.add(device)
    #
    #     self._views.append(view)


import sys
import networkx as nx
from collections import OrderedDict
import time

class myGraph:
	totalVertices = -1
	totalEdges = -1
	edgeList = [] #consists of two values , u and v

def readInputs(G,inputFile):
	graphData = inputFile.readline().split(" ")
	G.totalVertices = int(graphData[0])
	G.totalEdges = int(graphData[1])
	graphData = inputFile.readlines()

	for currEdge in graphData:
		currEdge = currEdge.split(" ")
		l = (int(currEdge[0]),int(currEdge[1]))
		G.edgeList.append(l)

def readQuery(queries):
	queryFile = open(sys.argv[2],'r')
	totalQuery = queryFile.readline()
	queries = queryFile.readlines()

def getCutVertices(G):
	return list(nx.articulation_points(G))

def getBridges(G):
	return list(nx.bridges(G))

def getBiconnectedComponents(currG):
	G = nx.Graph()
	G.add_edges_from(currG.edgeList)
	# print(G.number_of_nodes())
	# print(G.number_of_edges())
	return nx.biconnected_components(G)

def printComponents(Components):
	vertexList = []
	currComponentNumber = 1
	totalCount = 0
	for c in Components:
		totalCount += 1
		s = ""
		for v in c:
			s = s+str(v)+" "
		vertexList.append(s)

	vertexList.sort()
	print(len(vertexList))
	for item in vertexList:
		print(item)
	# print(totalCount)
	# print(len(vertexList))

def main():
	inputFile = open(sys.argv[1],'r')
	currG = myGraph()
	readInputs(currG,inputFile) #reads data correctly
	G = nx.Graph()
	G.add_edges_from(currG.edgeList)

	start_time = time.time()
	cutVertices = getCutVertices(G)
	bridges = getBridges(G)
	end_time = time.time() - start_time;

	cutVertices.sort()

	# print(len(bridges))
	# print(len(cutVertices))
	# print(bridges)
	# print(cutVertices)
	print(nx.is_connected(G))
	print("Bridges")
	bridgesList = []
	for i in bridges:
		bridgesList.append(str(i[0])+" "+str(i[1]))
	bridgesList.sort()
	for i in bridgesList:
		print(i)
	print("Cut Vertices")
	# print(type(cutVertices))
	for i in cutVertices:
		print(i)
	print("")
	print("Time taken: "+str(end_time/1000)+" milliseconds")

	queries = open(sys.argv[2],'r').readlines()
	totalBatch = int(queries[0])
	currLine = 0
	# print(len(queries))
	while(currLine < len(queries)):
		currLine += 1
		if(currLine >= len(queries)):
			break
		# print(currLine)
		type = int(queries[currLine].split()[0])
		totalQuery = int(queries[currLine].split()[1])
		# print(str(type)+" "+str(totalQuery))
		for q in range(totalQuery):
			currLine += 1
			curr = queries[currLine].split()
			u = int(curr[0])
			v = int(curr[1])
			# print("Curr Query "+str(type)+" "+str(u)+" "+str(v))
			if type == 1:
				G.add_edge(u,v)
			else:
				G.remove_edge(u,v)

		start_time = time.time()
		cutVertices = getCutVertices(G)
		bridges = getBridges(G)
		cutVertices.sort()
		end_time = time.time() - start_time;
		print(nx.is_connected(G))
		print("Bridges")
		bridgesList = []
		for i in bridges:
			bridgesList.append(str(i[0])+" "+str(i[1]))
		bridgesList.sort()
		for i in bridgesList:
			print(i)
		print("Cut Vertices")

		for i in cutVertices:
			print(i)
		print("")
		print("Time taken: "+str(end_time/1000)+" milliseconds")

main()


import tkinter as tk
frm=tk.Tk()
w=500
h=500
sw=frm.winfo_screenwidth()
sh=frm.winfo_screenheight()
x=(sw-w)/2
y=(sh-h)/2
frm.geometry('%dx%d+%d+%d'%(w,h,x,y))
frm.mainloop()


def premozenje(oseba, denar):
    if not otroci[oseba]:
        return denar[oseba]
    vsota = denar[oseba]
    for otrok in otroci[oseba]:
        vsota += premozenje(otrok, denar)
    return vsota

def najbogatejsi(oseba, denar):
    najvecji = (oseba, denar[oseba])
    for otrok in otroci[oseba]:
        temp = najbogatejsi(otrok, denar)
        if temp[1] > najvecji[1]:
            najvecji = temp
    return najvecji

def uravnotezeni(oseba, denar):
    if not otroci[oseba]:
        return True
    for otrok in otroci[oseba]:
        if not uravnotezeni(otrok, denar):
            return False
    temp = premozenje(otroci[oseba][0], denar)
    for otrok in otroci[oseba]:
        if premozenje(otrok, denar) != temp:
            return False
    return True

def neuravnotezeni(oseba, denar):
    if not otroci[oseba]:
        return None
    if uravnotezeni(oseba, denar):
        return None
    for otrok in otroci[oseba]:
        if not uravnotezeni(otrok, denar):
            return neuravnotezeni(otrok, denar)
    return oseba

otroci = {
    "Adam": ["Matjaž", "Cilka", "Daniel"],
    "Aleksander": [],
    "Alenka": [],
    "Barbara": [],
    "Cilka": [],
    "Daniel": ["Elizabeta", "Hans"],
    "Erik": [],
    "Elizabeta": ["Ludvik", "Jurij", "Barbara"],
    "Franc": [],
    "Herman": ["Margareta"],
    "Hans": ["Herman", "Erik"],
    "Jožef": ["Alenka", "Aleksander", "Petra"],
    "Jurij": ["Franc", "Jožef"],
    "Ludvik": [],
    "Margareta": [],
    "Matjaž": ["Viljem"],
    "Petra": [],
    "Tadeja": [],
    "Viljem": ["Tadeja"],
}


# Bir liste içindeki tekrar eden elemanları bulmak için Python'da bir algoritma nasıl tasarlanır? (Zaman ve bellek karmaşıklığı optimize edilmelidir)

# Set kullanarak tekrar eden elemanları bulmak:
def tekrar_edenler(liste):
    tekrar_edenler = set()
    onceki_elemanlar = set()

    for eleman in liste:
        if eleman in onceki_elemanlar:
            tekrar_edenler.add(eleman)
        else:
            onceki_elemanlar.add(eleman)

    return list(tekrar_edenler)

# Dictionary kullanarak tekrar eden elemanları bulmak:

def tekrar_edenler(liste):
    tekrar_edenler = []
    elemanlar_sayisi = {}

    for eleman in liste:
        if eleman in elemanlar_sayisi:
            elemanlar_sayisi[eleman] += 1
        else:
            elemanlar_sayisi[eleman] = 1

    for eleman, sayi in elemanlar_sayisi.items():
        if sayi > 1:
            tekrar_edenler.append(eleman)

    return tekrar_edenler


name_1=input("enter your first name   : " ).strip().lower()
n_1=[a for a in name_1 if a!=' ']
name_2=input("enter your second name  : " ).strip().lower()
n_2=[b for b in name_2 if b!=' ']
t=len(n_1)+len(n_2)
for i in range(0,len(n_1)):
    for j in  range(0,len(n_2)):
        if n_1[i]!='*' and n_1[i]==n_2[j]:
            t=t-2
            n_1[i],n_2[j]='*','*'
r=['Friendship','Love','Affection','Married','Enemy','Sister and Br0ther ']
while len(r)>=2:
    a=t%len(r)-1
    if a<0:
        ri=r[:a]
        r=ri
    else:
        ri=r[a+1:]
        le=r[:a]
        r=ri+le
print(name_1 ,'and ',name_2, r[0])


import itertools
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from prettytable import PrettyTable

def graph_order(matrix):
    if len(matrix) != len(matrix[0]):
        return -1
    else:
        return len(matrix)

def matrix_degrees(matrix):
    degrees = []
    for i in range(len(matrix)):
        degrees.append(sum(matrix[i]))
    degrees.sort(reverse=True)
    return degrees

def permutations(matrix):
    if graph_order(matrix) > 8:
        return -1
    all_matrix = []
    idx = list(range(len(matrix)))
    possible_combinations = [list(i)
                             for i in itertools.permutations(idx, len(idx))]
    for i in possible_combinations:
        a = matrix
        a = a[i]
        a = np.transpose(np.transpose(a)[i])
        all_matrix.append({"perm_vertex": i, "adj_matrix": a})

    return all_matrix

def graph_isomporphism(first_matrix, second_matrix):
    first_matrix_degrees = matrix_degrees(first_matrix)
    second_matrix_degrees = matrix_degrees(second_matrix)
    if graph_order(first_matrix) != graph_order(first_matrix):
        return 'НЕ ІЗОМОРФІЧНИМИ'
    elif np.array_equal(first_matrix_degrees, second_matrix_degrees) == False:
        return 'НЕ ІЗОМОРФІЧНИМИ'
    else:
        for i in list(map(lambda matrix: matrix["adj_matrix"], permutations(second_matrix))):
            if np.array_equal(first_matrix, i) == True:
                return 'ІЗОМОРФІЧНИМИ'
    return False

if __name__ == '__main__':
    fig = plt.figure()

    with open('matrix_a.txt', 'r') as f:
        a_matrix = np.loadtxt(f)

    with open('matrix_b.txt', 'r') as f:
        b_matrix = np.loadtxt(f)

    print('Мaтриця A:')
    print(a_matrix)
    arrA = nx.Graph()
    resA = np.where(a_matrix != 0)
    oneArrayA = np.column_stack((resA[0], resA[1]))
    for i in oneArrayA:
        arrA.add_edge(i[0], i[1])

    ax1 = fig.add_subplot(121)
    ax1.set_title('Мaтриця A')
    nx.draw(arrA, with_labels=True, font_weight='bold', node_color='yellow')

    print('Мaтриця B:')
    print(b_matrix)
    arrB = nx.Graph()
    resB = np.where(b_matrix != 0)
    oneArrayB = np.column_stack((resB[0], resB[1]))
    for i in oneArrayB:
        arrB.add_edge(i[0], i[1])

    ax2 = fig.add_subplot(122)
    ax2.set_title('Мaтриця B')
    nx.draw(arrB, with_labels=True, font_weight='bold', node_color='orange')

    print('Результат вручну: Дані графи є',
          graph_isomporphism(a_matrix, b_matrix))
    if nx.is_isomorphic(arrA, arrB) == True:
        print('NetworkX: Дані графи є ізоморфічними')
    else:
        print('NetworkX: Дані графи є НЕ ізоморфічними')

    plt.show()


from textual.app import ComposeResult
from textual.screen import Screen
from textual.widgets import Static, Button, Header
from pathlib import Path

tp = Path(__file__).resolve().parent

class GameOverButtonBox(Static):
    def compose(self) -> ComposeResult:
        yield Button("Yes", id="yes", variant="success", classes='confirm_button')
        yield Button("No", id="no", variant="error", classes='cancel_button')

class GameOverScreen(Screen):
    def __init__(self, winner:str|None, *args, **kwargs):
        super(GameOverScreen, self).__init__(*args, **kwargs)
        self.winner = winner

    def compose(self) -> ComposeResult:
        yield Header(id='asscheecks')
        if self.winner is not None:
            ste = f'\n \n \n Congratulations! \n {self.winner} is the winner!'
        else:
            ste = 'Game Over! You\'re both losers!'
        yield Static(ste + f' \n \n \n \n \n Play again?', id='label_play_again')
        yield GameOverButtonBox()

    def on_button_pressed(self, event: Button.Pressed) -> None:
        button_id = event.button.id
        if event.button.id == "yes":
            self.add_class("yes_accept")
        elif event.button.id == "no":
            self.add_class("no_return")


import os
import json
import click
import dpath.util

class BaseHelper(object):

    def __init__(self):
        pass

    def get_version(self):
        version = None
        if os.path.isfile('VERSION'):
            with click.open_file('VERSION', 'r') as f:
                version = f.read().strip()
        return version

    def output(self, value=None, format=None, jsonpath=None, source_json_file=None, in_place=False):
        if format == 'json':
            if source_json_file:
                d = json.load(source_json_file)
            else:
                d = {}
            dpath.util.new(d, list(jsonpath) or '/value', value)
            if in_place:
                source_json_file.seek(0)
                json.dump(d, source_json_file, indent=2, sort_keys=True)
            else:
                print(json.dumps(d, indent=2, sort_keys=True))
        elif format == 'text':
            print(value)


import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from CodOpY.optimise import opt_seq
from CodOpY.misc import load_from_Data

def translate(seq):
    '''
    Returns an amino acid sequence translated for an input DNA
    sequence.

    Parameters
    ==========
    seq : str
        The DNA sequence to be translated.

    Returns
    str
        The amino acid sequence translated from seq.
    '''

    codedict = {'AAA':'K','AAC':'N','AAG':'K','AAT':'N','ACA':'T','ACC':'T',
                'ACG':'T','ACT':'T','AGA':'R','AGC':'S','AGG':'R','AGT':'S',
                'ATA':'I','ATC':'I','ATG':'M','ATT':'I','CAA':'Q','CAC':'H',
                'CAG':'Q','CAT':'H','CCA':'P','CCC':'P','CCG':'P','CCT':'P',
                'CGA':'R','CGC':'R','CGG':'R','CGT':'R','CTA':'L','CTC':'L',
                'CTG':'L','CTT':'L','GAA':'E','GAC':'D','GAG':'E','GAT':'D',
                'GCA':'A','GCC':'A','GCG':'A','GCT':'A','GGA':'G','GGC':'G',
                'GGG':'G','GGT':'G','GTA':'V','GTC':'V','GTG':'V','GTT':'V',
                'TAA':'*','TAC':'Y','TAG':'*','TAT':'Y','TCA':'S','TCC':'S',
                'TCG':'S','TCT':'S','TGA':'*','TGC':'C','TGG':'W','TGT':'C',
                'TTA':'L','TTC':'F','TTG':'L','TTT':'F'}

    if type(seq) == str and all([n in ['A','C','T','G'] for n in seq.upper()]):
        seq = [seq[i:i+3] for i in range(0,len(seq),3) if len(seq[i:i+3]) == 3]
    elif type(seq) == list and all([len(c) == 3 for c in seq]):
        pass
    else:
        raise ValueError('This sequence is not recognised as a valid DNA or' +
                          ' codon sequence.')

    return ''.join([codedict[c] for c in seq])

#================================================================================

def time_seq(input_seq,ref_table='Scer'):
    '''time_seq calculates the time it takes to decode a DNA or RNA sequence.

    Parameters
    ----------
    input_seq : str
        The DNA or RNA sequence for which the tiem properties are beiing returned.
    ref_table : str
        The name of the reference table to be used, eg 'Scer' for S. cerevisiae

    Returns
    -------
    dict
        A dictionary containing the overall Decoding time in seconds,
        the Average decoding time per codon in seconds, and the CV
        (coefficient of variation of the decoding time per codon)
    '''

    #convert the input sequence to DNA if RNA
    input_seq = input_seq.replace('U','T')
    #make a look-up dictionary of the decoding times available for an amino acid
    #from the reference table
    ref = load_from_Data(ref_table)
    ref['codon'] = ref['codon'].str.replace('U','T')
    time_dict_by_codon = dict(zip(ref['codon'], ref['decoding.time']))
    #add pseudo data for stop codons
    time_dict_by_codon['TGA'] = 0
    time_dict_by_codon['TAA'] = 0
    time_dict_by_codon['TAG'] = 0
    #calculate the decoding time properties of the sequence
    codon_seq = [input_seq[n:n+3] for n in range(0,len(input_seq),3)]
    times_vec = [time_dict_by_codon[codon] for codon in codon_seq]
    results = {}
    results['Decoding time'] = np.sum(times_vec)
    results['Average decoding time per codon'] = results['Decoding time'] / len(codon_seq)
    results['CV'] = np.std(times_vec, ddof=1) / np.mean(times_vec) * 100
    return results

#================================================================================

def report_repeats(seq, threshold=4):
    '''
    Reports the repeat length for any single amino acid repeat longer than the threshold value.

    Parameters
    ==========
    seq : str
        The amino acid sequence to be analysed
    threshold : int
        The minimum number of consecutive amino acids reported as a repeat. Default = 4.

    Returns
    =======

    dict
        A dictionary of amino acids for which repeats were found and the longest repeat length.
        Returns an empty dictionary if no repeats were found.
    '''

    ret_dict = {}
    for aa in seq:
        l = threshold
        while aa * l in seq:
            ret_dict[aa] = (l,'@')
            l += 1
    for key,value in ret_dict.items():
        ret_dict[key] = (value[0],value[1] + str(seq.index(key*value[0]) + 1))
    return ret_dict

#================================================================================

def test_RE(RE, test_seq):
    '''
    Tests whether an RE site is present in a sequence.

    Parameters
    ==========
    REs : str
        The name of the enzyme, or the sequence, to be tested.

    test_seq : str
        The DNA sequence to be tested.

    Returns
    =======
    list
        A list of names of those enzymes for which sites were found in
        test_seq, or an empty list of none of the enzyme sites was found.
    '''

    RE_ref = load_from_Data('RE_List')

    #convert RE names to upper case for comparison to 'RE' variable
    RE_ref.Name = RE_ref.Name.str.upper()

    #is site a restriction enzyme name?
    RE = RE.upper()
    if RE in RE_ref.Name.values:
        RE_seq = RE_ref.loc[RE_ref['Name'] == RE]['Motif'].values[0]
    #else is site a valid DNA sequence?
    elif not 0 in [c in ['A','C','T','G','W','S','M','K','R','Y','N'] for c in RE]:
        RE_seq = RE
    else:
        print('No known Restriction enzyme site or valid DNA sequence specified.')
        return
    #remove leading or trailing Ns from RE site
    while RE_seq[0] == 'N':
        RE_seq = RE_site[1:]
    while RE_seq[-1] == 'N':
        RE_seq = RE_site[:-1]
    #does RE_site now have more than 5 'N' (this becomes very inefficient)
    if RE_seq.count('N') > 5:
        print('Too many N - the maximum number of N allowed in the RE sequence is 5')
        return

    #does the RE site contain ambiguous nucleotide symbols?
    #If so list all corresponding unambiguous sequences
    ambiguous_bases = {'W':['A','T'],'S':['G','C'],'M':['A','C'],'K':['G','T'],'R':['A','G'],'Y':['C','T'],
                       'B':['C','G','T'],'D':['A','G','T'],'H':['A','C','T'],'V':['A','C','G'],'N':['A','C','G','T']}
    unamb_RE_seqs = [RE_seq]
    while 0 in [c in ['A','C','T','G'] for c in unamb_RE_seqs[0]]:
        new_options = []
        for seq in unamb_RE_seqs:
            for idx, nt in enumerate(seq):
                if nt in ambiguous_bases.keys():
                    for nt in ambiguous_bases[nt]:
                        new_options.append(seq[:idx] + nt + seq[idx+1:])
                    break
        unamb_RE_seqs = new_options

    #convert sequence to valid uppercase DNA sequence
    test_seq = test_seq.upper().replace('U','T')

    #is site in seq?
    if not 1 in [R in test_seq for R in unamb_RE_seqs]:
        print(RE + ' not found in this sequence. \n')
        return
    #if yes go through the sequence and record all sites of occurrence
    else:
        found_sites = []
        sub_seq = test_seq
        while 1 in [R in sub_seq for R in unamb_RE_seqs]:
            for R in unamb_RE_seqs:
                if R in sub_seq:
                    if len(found_sites) >= 1:
                        index_shift = found_sites[-1]
                    else:
                        index_shift = 0
                    found_sites.append(sub_seq.find(R)+ index_shift)
                    sub_seq = sub_seq[found_sites[-1]+1:]
        print(RE + ' found at the following site(s): ' + str(found_sites).replace('[','').replace(']','') + '\n')
        return
#================================================================================

def count_aas(seq):
    '''Produces a bar graph of amino acid counts in a protein sequence'''

    aas = ['A','C','D','E','F','G','H','I','K','L','M','N','P','Q','R','S','T','V','W','Y']
    counts = []
    for aa in aas:
        counts.append(seq.count(aa))
    fig,ax = plt.subplots()
    ax.bar(aas,counts)
    ax.set_ylabel('counts')
    ax.set_xlabel('amino acid')
    return fig,ax

#==================================================================================================

def plot_opt(seq, ref_table = 'Scer', plot_par = 'decoding.time',window=25,plot_colors = ['gold','cornflowerblue','mediumpurple']):

    #convert sequence to DNA
    seq = seq.upper()
    seq = seq.replace('U','T')

    parameterset = load_from_Data(ref_table)

    #generate a lookup dictionary for the plotted parameter
    pardict = {}
    for c in parameterset['codon']:
        this_par = parameterset.loc[parameterset['codon'] == c][plot_par].values[0]
        this_c= c.replace('U','T')
        pardict[this_c] = this_par
    #make the extreme arameter sequences
    aaseq = translate(seq)
    max_seq = opt_seq(aaseq,ref_table = ref_table,optimise_by = [plot_par,max],diversify = [])
    min_seq = opt_seq(aaseq,ref_table = ref_table,optimise_by = [plot_par,min], diversify = [])

    codon_seq = [seq[i:i+3] for i in range(0,len(seq),3) if len(seq[i:i+3]) == 3]
    max_codon_seq = [max_seq[i:i+3] for i in range(0,len(max_seq),3) if len(max_seq[i:i+3]) == 3]
    min_codon_seq = [min_seq[i:i+3] for i in range(0,len(min_seq),3) if len(min_seq[i:i+3]) == 3]

    #prepare vectors of the codon parameter for each sequence:
    seq_pars = [pardict[c] for c in codon_seq]
    max_pars = [pardict[c] for c in max_codon_seq]
    min_pars = [pardict[c] for c in min_codon_seq]
    x = list(range(len(seq_pars)))

    smooth_seq_pars = [sum(seq_pars[i:i+window])/window for i in range(len(seq_pars) - window)]
    smooth_max_pars = [sum(max_pars[i:i+window])/window for i in range(len(max_pars) - window)]
    smooth_min_pars = [sum(min_pars[i:i+window])/window for i in range(len(min_pars) - window)]

    smooth_x_offset = int(window/2)
    smooth_x = list(range(smooth_x_offset,smooth_x_offset + len(smooth_min_pars)))
    #prepare the plot
    fig,ax = plt.subplots()
    ax.scatter(x, seq_pars,c=plot_colors[0],s=5,alpha=0.5)
    ax.plot(smooth_x,smooth_seq_pars,c=plot_colors[0],label='actual')
    ax.plot(smooth_x,smooth_max_pars,c=plot_colors[1],label='max')
    ax.plot(smooth_x,smooth_min_pars,c=plot_colors[2],label='min')

    ax.set_xlabel('Codon No')
    ax.set_ylabel(plot_par)

    plt.legend(loc='upper right')

    return fig,ax


cores = {'padrao': '\033[m', 'negrito': '\033[1m', 'verde': '\033[1;32m', 'vermelho': '\033[1;31m'}

def deco():
    print(f'{cores["verde"]}-{cores["padrao"]}'*70)

deco()
print(f'{cores["negrito"]}Analisando notas através de funções e resultando em bibliotecas!'.center(72))
deco()

def notas(*string, sit=False):
    """
    -> Efetua a leitura das notas realizando calculos em bibliotecas!
    :param string: Os valores das notas recebidas
    :param sit: A condição para implantar a situação
    :return: Retorno do dicionario a variavel.
    """
    dicio = dict()
    dicio['Total'] = len(string)
    dicio['Maior'] = max(string)
    dicio['Menor'] = min(string)
    dicio['Média'] = sum(string) / len(string)

    if sit:
        if dicio['Média'] >= 7:
            dicio['Situação'] = 'BOA'

        elif dicio['Média'] >= 5 < 7:
            dicio['Situação'] = 'RAZOÁVEL'

        else:
            dicio['Situação'] = 'RUIM'

    return dicio

# MAIN
resp = notas(5.5, 5, 0, 6.5, sit=True)

for keys, values in resp.items():
    print('{} = {} | '.format(keys, values), end='')
print()
deco()

help(notas)
deco()


# coding=utf-8
import json
from unittest import TestCase

from veriso.base.utils.module import (get_baselayers, get_checks_from_files,
                                      get_check_topics, get_layers_from_topic)
from veriso.test.utilities import get_data_content

class TestUtils(TestCase):
    def test_get_baselayers(self):
        expected = get_data_content('base_layers_vd.txt')
        self.assertIsNotNone(expected)

        returned = get_baselayers('veriso_v_d')

        self.assertEqual(str(expected), str(returned))

    def test_get_checks_from_files(self):
        expected = [
            {
                u'file': u'alle_checks',
                u'id': u'alle_checks',
                u'shortcut': u'',
                u'name': {
                    u'fr': u'Touts les Checks',
                    u'de': u'Alle Checks'
                }
            },
            {
                u'file': u'alle_checks_separator',
                u'id': u'alle_checks_separator',
                u'shortcut': u'',
                u'name': u'separator'
            },
            {
                u'file': u'basislayer',
                u'id': u'basislayer',
                u'shortcut': u'',
                u'name': {
                    u'fr': u'Couche de base',
                    u'de': u'Basislayer'
                }
            },
            {
                u'file': u'checklayer',
                u'id': u'checklayer',
                u'shortcut': u'',
                u'name': u'Checklayer'
            },
            {
                u'file': u'lokalisation',
                u'id': u'lokalisation',
                u'shortcut': u'F12',
                u'name': {
                    u'fr': u'Localisation',
                    u'de': u'Lokalisation'
                }
            }]

        checks = get_checks_from_files('veriso_ee', 'gebaeudeadressen')
        checks_list = json.loads(json.dumps(checks))
        self.assertListEqual(checks_list, expected)

    def test_get_check_topics(self):
        expected = {
            u'FixpunkteKategorie3': {
                u'topic': u'FixpunkteKategorie3', u'topic_dir': u'fp3',
                u'checks': [{
                    u'file': u'fp3', u'id': u'fp3',
                    u'shortcut': u'', u'name': {
                        u'fr': u"Vue d'ensemble", u'de': u'\xdcbersicht'
                    }
                }]
            }, u'Gebaeudeadressen': {
                u'topic': u'Gebaeudeadressen',
                u'topic_dir': u'gebaeudeadressen', u'checks': [{
                    u'file':
                        u'alle_checks',
                    u'id':
                        u'alle_checks',
                    u'shortcut': u'',
                    u'name': {
                        u'fr': u'Touts les Checks',
                        u'de': u'Alle Checks'
                    }
                }, {
                    u'file': u'alle_checks_separator',
                    u'id': u'alle_checks_separator',
                    u'shortcut': u'',
                    u'name': u'separator'
                }, {
                    u'file': u'basislayer',
                    u'id': u'basislayer',
                    u'shortcut': u'',
                    u'name': {
                        u'fr': u'Couche de base',
                        u'de': u'Basislayer'
                    }
                }, {
                    u'file': u'checklayer',
                    u'id': u'checklayer',
                    u'shortcut': u'',
                    u'name': u'Checklayer'
                }, {
                    u'file': u'lokalisation',
                    u'id': u'lokalisation',
                    u'shortcut': u'F12',
                    u'name': {
                        u'fr': u'Localisation',
                        u'de': u'Lokalisation'
                    }
                }]
            }
        }

        topics = get_check_topics('veriso_ee')
        topics_list = json.loads(json.dumps(topics))
        self.assertDictEqual(topics_list, expected)


def gcd(a, b):
    if a % b == 0:
        return b
    return gcd(b, a % b)

def hasCommonPrimeDivisor(a, b):
    while a > 1:
        div = gcd(a, b)
        if div == 1:
            break

        a /= div

    return a == 1

def solution(A, B):
    N = len(A)
    result = 0

    for i in range(0, N):
        if hasCommonPrimeDivisor(A[i], B[i]) and hasCommonPrimeDivisor(B[i], A[i]):
            result += 1

    return result

if True:
    A = [15, 10, 3]
    B = [75, 30, 5]

    result = solution(A, B)
    print("Result ", result)


while True:
    number = input("请输入一个正数")
    if number in ['q', 'Q']:
        break
    elif not float(number) > 0:
        print("请输入一个正数")
    else:
        number = float(number)
        array1 = []
        array2 = []
        integer = int(number)
        floa = number - integer
        while integer != 0:
            array1.append(integer % 2)
            integer = integer // 2
        else:
            array1.append(0)
        array1.reverse()
        while floa > 0.00001:
            array2.append(int(2 * floa))
            floa = floa * 2 - int(floa * 2)
        else:
            array2.append(0)
        array1.append(".")
        array = array1 + array2
        for x in array:
            print(x, end="")
        print("\n")


from . import *
from pya import *

class Waveguide_SBend(pya.PCellDeclarationHelper):
  """
  Input:
  """
  def __init__(self):

    # Important: initialize the super class
    super(Waveguide_SBend, self).__init__()
    TECHNOLOGY = get_technology_by_name('EBeam')

    # declare the parameters
    self.param("length", self.TypeDouble, "Waveguide length", default = 10.0)
    self.param("height", self.TypeDouble, "Waveguide offset height", default = 2)
    self.param("wg_width", self.TypeDouble, "Waveguide width (microns)", default = 0.5)
#    self.param("radius", self.TypeDouble, "Waveguide bend radius (microns)", default = 5)
    self.param("layer", self.TypeLayer, "Layer", default = TECHNOLOGY['Si'])
    self.param("pinrec", self.TypeLayer, "PinRec Layer", default = TECHNOLOGY['PinRec'])
    self.param("devrec", self.TypeLayer, "DevRec Layer", default = TECHNOLOGY['DevRec'])

  def display_text_impl(self):
    # Provide a descriptive text for the cell
    return "Waveguide_SBend_%s-%.3f" % \
    (self.length, self.wg_width)

  def coerce_parameters_impl(self):
    pass

  def can_create_from_shape(self, layout, shape, layer):
    return False

  def produce_impl(self):

    # fetch the parameters
    dbu = self.layout.dbu
    ly = self.layout
    shapes = self.cell.shapes

    from SiEPIC.utils.layout import layout_waveguide_sbend, layout_waveguide_sbend_bezier
    from SiEPIC.extend import to_itype

    LayerSi = self.layer
    LayerSiN = ly.layer(LayerSi)
    LayerPinRecN = ly.layer(self.pinrec)
    LayerDevRecN = ly.layer(self.devrec)

    length = to_itype(self.length,dbu)
    w = to_itype(self.wg_width,dbu)
    h = to_itype(self.height,dbu)

#    waveguide_length = layout_waveguide_sbend(self.cell, LayerSiN, pya.Trans(Trans.R0, 0,0), w, r, h, length)
    waveguide_length = to_itype(layout_waveguide_sbend_bezier(self.cell, LayerSiN, pya.Trans(), self.wg_width, self.wg_width, self.height,self.length), dbu)

    from SiEPIC._globals import PIN_LENGTH as pin_length

    # Pins on the waveguide:
    x = length
    t = Trans(Trans.R0, x,h)
    pin = Path([Point(-pin_length/2,0), Point(pin_length/2,0)], w)
    pin_t = pin.transformed(t)
    shapes(LayerPinRecN).insert(pin_t)
    text = Text ("pin2", t)
    shape = shapes(LayerPinRecN).insert(text)
    shape.text_size = to_itype(0.4,dbu)
    shape.text_halign = 2

    x = 0
    t = Trans(Trans.R0, x,0)
    pin = Path([Point(pin_length/2,0), Point(-pin_length/2,0)], w)
    pin_t = pin.transformed(t)
    shapes(LayerPinRecN).insert(pin_t)
    text = Text ("pin1", t)
    shape = shapes(LayerPinRecN).insert(text)
    shape.text_size = to_itype(0.4,dbu)

    # Compact model information
    t = Trans(Trans.R0, 0, 0)
    text = Text ('Lumerical_INTERCONNECT_library=Design kits/EBeam', t)
    shape = shapes(LayerDevRecN).insert(text)
    shape.text_size = to_itype(0.1,dbu)
    t = Trans(Trans.R0, 0, w*2)
    text = Text ('Component=ebeam_wg_integral_1550', t)
    shape = shapes(LayerDevRecN).insert(text)
    shape.text_size = to_itype(0.1,dbu)
    t = Trans(Trans.R0, 0, -w*2)
    text = Text \
      ('Spice_param:wg_length=%.3fu wg_width=%.3fu' %\
      (waveguide_length*dbu, self.wg_width), t )
    shape = shapes(LayerDevRecN).insert(text)
    shape.text_size = to_itype(0.1,dbu)
#    t = Trans(Trans.R0, 0, -w*3)
#    text = Text ('Extra length = %.4fu, Shortest length = %.4fu' % (straight_l*dbu, (length-2*straight_l)*dbu), t )
#    shape = shapes(LayerDevRecN).insert(text)
#    shape.text_size = 0.1/dbu

    # Create the device recognition layer -- make it 1 * wg_width away from the waveguides.
    box1 = Box(0, min(-w*3,h-w*3), length, max(w*3,h+w*3))
    shapes(LayerDevRecN).insert(box1)

#    print('2020/11/28 update')


# CSV-to-JSON translator that expects a path to a CSV file as argument, and for each line, prints out a JSON object encapsulating that record
import csv, json, sys
import os

try:
    # retrieve the path from the command line
    path = sys.argv[1]
    # retrieve the extension from the path
    name, extension = os.path.splitext(path)
    # Check that it is a .csv file
    if extension != ".csv":
        raise FileNotFoundError
    csvFilePath = path
    # save the new json file the same name and path of the csv file
    jsonFilePath = path.replace(".csv",".json")

    # Read csv file and add it to data as dictionary
    data = {}
    with open(csvFilePath) as csvFile:
        csvReader = csv.DictReader(csvFile)
        for i,rows in enumerate(csvReader):
            id = i
            data[id] = rows

    # create new json file
    with open(jsonFilePath, 'w') as jsonFile:
        jsonFile.write(json.dumps(data, indent=4))

except IndexError:
    print("Please enter a file path in the command line")
except FileNotFoundError:
    print("Please enter a correct file path to a .csv file")


"""
程序名：回答问卷请求接口
功能：回答问卷后台处理函数
"""
from django.shortcuts import HttpResponse
import json
from myAdmin.models import *
from django.db import transaction
import datetime

############################################################
#功能：问卷回答者操作主入口
#最后更新：2019-05-24
############################################################
def opera(request):
    response={'code':0,'msg':'success'}
    if request.method=='POST':
        body=str(request.body,encoding='utf-8')
        print(body)
        try:
            info = json.loads(body)#解析json报文
        except:
            response['code'] = '-2'
            response['msg'] = '请求格式有误'
        opera_type=info.get('opera_type')#获取操作类型
        if opera_type:
            if opera_type=='get_info':#获取问卷信息
                response=getInfo(info,request)
            elif opera_type=='get_temp_info':#获取问卷信息
                response=getTempInfo(info,request)
            elif opera_type=='submit_wj':#提交问卷
                response=submitWj(info,request)
            else:
                response['code'] = '-7'
                response['msg'] = '请求类型有误'
        else:
            response['code'] = '-3'
            response['msg'] = '确少必要参数'
    else:
        response['code']='-1'
        response['msg']='请求方式有误'

    return HttpResponse(json.dumps(response))

############################################################
#功能：获取问卷信息
#最后更新：2019-05-24
############################################################
def getInfo(info,request):
    response = {'code': 0, 'msg': 'success'}
    wjId=info.get('wjId')
    username = request.session.get('username')
    if wjId:
        try:#判断问卷id是否存在
            res=Wj.objects.get(id=wjId)#查询id为wjId
            response['title']=res.title
            response['desc']=res.desc
        except:
            response['code'] = '-10'
            response['msg'] = '问卷不存在'
        else:
            if res.username==username or res.status==1:#只有问卷发布者或者此问卷为已发布才能查看
                obj = Question.objects.filter(wjId=wjId)
                detail = []
                for item in obj:
                    temp = {}
                    temp['title'] = item.title
                    temp['type'] = item.type
                    temp['id'] = item.id  # 问题id
                    temp['row'] = item.row
                    temp['must'] = item.must
                    # 获取选项
                    temp['options'] = []
                    if temp['type'] in ['radio', 'checkbox']:  # 如果是单选或者多选
                        optionItems = Options.objects.filter(questionId=item.id)
                        for optionItem in optionItems:
                            temp['options'].append({'title':optionItem.title,'id':optionItem.id})
                    temp['radioValue'] = -1  # 接收单选框的值
                    temp['checkboxValue'] = []  # 接收多选框的值
                    temp['textValue'] = ''  # 接收输入框的值
                    detail.append(temp)
                response['detail'] = detail
            else:
                response['code'] = '-10'
                response['msg'] = '问卷尚未发布'
    else:
        response['code'] = '-3'
        response['msg'] = '确少必要参数'
    return response

############################################################
#功能：获取模板问卷信息
#最后更新：2019-06-16
############################################################
def getTempInfo(info,request):
    response = {'code': 0, 'msg': 'success'}
    wjId=info.get('wjId')
    username = request.session.get('username')
    if wjId:
        try:#判断问卷id是否存在
            res=TempWj.objects.get(id=wjId)#查询id为wjId
            response['title']=res.title
            response['desc']='问卷描述'
        except:
            response['code'] = '-10'
            response['msg'] = '模板不存在'
        else:
            obj = TempQuestion.objects.filter(wjId=wjId)
            detail = []
            for item in obj:
                temp = {}
                temp['title'] = item.title
                temp['type'] = item.type
                temp['id'] = item.id  # 问题id
                temp['row'] = item.row
                temp['must'] = item.must
                # 获取选项
                temp['options'] = []
                if temp['type'] in ['radio', 'checkbox']:  # 如果是单选或者多选
                    optionItems = TempOptions.objects.filter(questionId=item.id)
                    for optionItem in optionItems:
                        temp['options'].append({'title':optionItem.title,'id':optionItem.id})
                temp['radioValue'] = -1  # 接收单选框的值
                temp['checkboxValue'] = []  # 接收多选框的值
                temp['textValue'] = ''  # 接收输入框的值
                detail.append(temp)
            response['detail'] = detail
    else:
        response['code'] = '-3'
        response['msg'] = '确少必要参数'
    return response

############################################################
#功能：提交问卷
#最后更新：2019-06-08
############################################################
@transaction.atomic
def submitWj(info,request):
    response = {'code': 0, 'msg': 'success'}
    wjId = info.get('wjId')
    useTime=info.get('useTime')
    detail=info.get('detail')
    if 'HTTP_X_FORWARDED_FOR' in request.META:
        ip = request.META.get('HTTP_X_FORWARDED_FOR')
    else:
        ip = request.META.get('REMOTE_ADDR')

    s1 = transaction.savepoint()#设置事务保存点 回滚使用
    if wjId:

        try:  # 判断问卷id是否存在
            res = Wj.objects.get(id=wjId)  # 查询id为wjId
            response['title'] = res.title
            response['desc'] = res.desc
        except:
            response['code'] = '-10'
            response['msg'] = '问卷不存在'
            return response
        if res.status==0:#当问卷状态为1(已发布)时才可回答
            response['code'] = '-10'
            response['msg'] = '问卷尚未发布'
            return response

        #记录提交信息
        submitInfo=Submit.objects.create(
            wjId=wjId,
            submitTime=datetime.datetime.now(),
            submitIp=ip,
            useTime=useTime
        )
        qItems=Question.objects.filter(wjId=wjId,must=True)#查询所有必填题目
        musts=[]
        for qItem in qItems:
            musts.append(qItem.id)#记录所有必填题目的题目id
        #记录答案
        for item in detail:
            # print(item)
            if item['type']=='radio':#单选题
                if item['id'] in musts and item['radioValue']==-1:#此必填选项未填 回滚
                    print('开始回滚')
                    transaction.savepoint_rollback(s1)
                    print('已回滚')
                    response['code'] = '-11'
                    response['msg'] = '有必答题目未回答'
                    break
                Answer.objects.create(
                    questionId=item['id'],
                    submitId=submitInfo.id,
                    wjId=wjId,
                    type=item['type'],
                    answer=item['radioValue']
                )
            elif item['type']=='checkbox':#多选题
                if item['id'] in musts and len(item['checkboxValue'])==0:#此必填选项未填 回滚
                    print('开始回滚')
                    transaction.savepoint_rollback(s1)
                    print('已回滚')
                    response['code'] = '-11'
                    response['msg'] = '有必答题目未回答'
                    break
                for value in item['checkboxValue']:
                    Answer.objects.create(
                        questionId=item['id'],
                        submitId=submitInfo.id,
                        wjId=wjId,
                        type=item['type'],
                        answer=value
                    )
            elif item['type']=='text':#填空题
                if item['id'] in musts and item['textValue']=='':#此必填选项未填 回滚
                    print('开始回滚')
                    transaction.savepoint_rollback(s1)
                    print('已回滚')
                    response['code'] = '-11'
                    response['msg'] = '有必答题目未回答 '
                    break
                Answer.objects.create(
                    questionId=item['id'],
                    submitId=submitInfo.id,
                    wjId=wjId,
                    type=item['type'],
                    answerText=item['textValue']
                )
    else:
        response['code'] = '-3'
        response['msg'] = '确少必要参数'

    return response


#small number in list
def small(lis):
    sm = lis[0]
    for i in range(len(lis)):
        if sm>lis[i]:
            sm = lis[i]
    return sm

#large number in list

def high(lis):
    sm = lis[0]
    for i in range(len(lis)):
        if sm<lis[i]:
            sm = lis[i]
    return sm

lis = [1, 3, 5, 7, 10]
missing_num = []
start = small(lis)
finish = high(lis)

#find out missing number
for i in range(start,finish):
    if i in lis:
        continue
    missing_num.append(i)

#summing all missing number
summ = 0
for i in missing_num:
    summ += i

print("Missing number sum : ",summ)

python/python_problem_solving/71 To 81/77 missing number um/missing_sum.py


import collections
import time

from acts import signals
from acts.test_decorators import test_tracker_info
from acts_contrib.test_utils.tel.TelephonyBaseTest import TelephonyBaseTest
from acts_contrib.test_utils.tel.tel_data_utils import wifi_tethering_setup_teardown
from acts_contrib.test_utils.tel.tel_defines import CAPABILITY_VOLTE
from acts_contrib.test_utils.tel.tel_defines import CAPABILITY_WFC
from acts_contrib.test_utils.tel.tel_defines import CAPABILITY_OMADM
from acts_contrib.test_utils.tel.tel_defines import MAX_WAIT_TIME_TETHERING_ENTITLEMENT_CHECK
from acts_contrib.test_utils.tel.tel_defines import NETWORK_SERVICE_DATA
from acts_contrib.test_utils.tel.tel_defines import GEN_4G
from acts_contrib.test_utils.tel.tel_defines import TETHERING_MODE_WIFI
from acts_contrib.test_utils.tel.tel_defines import WAIT_TIME_AFTER_FDR
from acts_contrib.test_utils.tel.tel_test_utils import call_setup_teardown
from acts_contrib.test_utils.tel.tel_test_utils import ensure_phone_subscription
from acts_contrib.test_utils.tel.tel_test_utils import get_model_name
from acts_contrib.test_utils.tel.tel_test_utils import get_outgoing_voice_sub_id
from acts_contrib.test_utils.tel.tel_test_utils import is_droid_in_network_generation
from acts_contrib.test_utils.tel.tel_test_utils import mms_send_receive_verify
from acts_contrib.test_utils.tel.tel_test_utils import fastboot_wipe
from acts_contrib.test_utils.tel.tel_test_utils import sms_send_receive_verify
from acts_contrib.test_utils.tel.tel_test_utils import wait_for_network_generation
from acts_contrib.test_utils.tel.tel_test_utils import verify_internet_connection
from acts_contrib.test_utils.tel.tel_test_utils import wait_for_state
from acts_contrib.test_utils.tel.tel_voice_utils import is_phone_in_call_3g
from acts_contrib.test_utils.tel.tel_voice_utils import is_phone_in_call_csfb
from acts_contrib.test_utils.tel.tel_voice_utils import is_phone_in_call_volte
from acts_contrib.test_utils.tel.tel_voice_utils import phone_idle_volte
from acts_contrib.test_utils.tel.tel_voice_utils import phone_setup_voice_3g
from acts_contrib.test_utils.tel.tel_voice_utils import phone_setup_csfb
from acts_contrib.test_utils.tel.tel_voice_utils import phone_setup_volte

from acts.utils import get_current_epoch_time
from acts.utils import rand_ascii_str

class TelLiveStressFdrTest(TelephonyBaseTest):
    def setup_class(self):
        TelephonyBaseTest.setup_class(self)

        self.stress_test_number = int(
            self.user_params.get("stress_test_number", 100))
        self.skip_reset_between_cases = False

        self.dut = self.android_devices[0]
        if len(self.android_devices) > 1:
            self.ad_reference = self.android_devices[1]
        else:
            raise signals.TestSkip("Single DUT is not supported")
        self.user_params["check_crash"] = False
        self.skip_reset_between_cases = False

        # self.dut_capabilities = self.dut.telephony.get("capabilities", [])
        sub_id = get_outgoing_voice_sub_id(self.dut)
        self.dut_capabilities = self.dut.telephony["subscription"][sub_id].get("capabilities", [])
        self.dut.log.info("dut_capabilitiese: %s", self.dut_capabilities)

        self.dut_wfc_modes = self.dut.telephony.get("wfc_modes", [])
        self.default_testing_func_names = []
        for method in ("_check_volte", "_check_csfb",
                       "_check_tethering", "_check_3g"):
            func = getattr(self, method)
            try:
                check_result = func()
            except Exception as e:
                self.dut.log.error("%s failed with %s", method, e)
                check_result = False
            self.dut.log.info("%s is %s before tests start", method,
                              check_result)
            if check_result:
                self.default_testing_func_names.append(method)
        self.dut.log.info("To be tested: %s", self.default_testing_func_names)

    def teardown_test(self):
        self._set_volte_provisioning()

    def feature_validator(self, *args):
        failed_tests = []
        for method in ("_check_subscription", "_check_data", "_check_mms_mt",
                       "_check_sms_mt", "_check_call_setup_teardown",
                       "_check_sms", "_check_mms"):
            func = getattr(self, method)
            if not func():
                self.log.error("%s failed", method)
                failed_tests.append(method)
        for method in args:
            func = getattr(self, method)
            try:
                func_result = func()
            except Exception as e:
                self.log.error("%s check failed with %s", method, e)
                func_result = False
            if not func_result:
                self.log.error("%s failed", method)
                failed_tests.append(method)
            else:
                self.log.info("%s succeeded", method)
        if failed_tests:
            self.log.error("%s failed", failed_tests)
        return failed_tests

    def _check_subscription(self):
        if not ensure_phone_subscription(self.log, self.dut):
            self.dut.log.error("Subscription check failed")
            return False
        else:
            return True

    def _check_volte_provisioning(self):
        if CAPABILITY_OMADM in self.dut_capabilities:
            if not wait_for_state(self.dut.droid.imsIsVolteProvisionedOnDevice,
                                  True):
                self.dut.log.error("VoLTE provisioning is disabled.")
                return False
            else:
                self.dut.log.info("VoLTE provision is enabled")
                return True
        return True

    def _set_volte_provisioning(self):
        if CAPABILITY_OMADM in self.dut_capabilities:
            provisioned = self.dut.droid.imsIsVolteProvisionedOnDevice()
            if provisioned:
                self.dut.log.info("Volte is provioned")
                return
            self.dut.log.info("VoLTE provisioning is not set, setting\
                VoLTE provision")
            self.dut.droid.imsSetVolteProvisioning(True)

    def _check_call_setup_teardown(self):
        if not call_setup_teardown(self.log, self.dut, self.ad_reference,
                                   self.dut):
            self.log.error("Phone call test failed.")
            return False
        return True

    def _check_sms(self):
        if not sms_send_receive_verify(self.log, self.dut, self.ad_reference,
                                       [rand_ascii_str(180)]):
            self.log.error("SMS send test failed")
            return False
        else:
            self.log.info("SMS send test passed")
            return True

    def _check_mms(self):
        message_array = [("Test Message", rand_ascii_str(180), None)]
        if not mms_send_receive_verify(self.log, self.dut, self.ad_reference,
                                       message_array):
            self.log.error("MMS test sendfailed")
            return False
        else:
            self.log.info("MMS send test passed")
            return True

    def _check_sms_mt(self):
        if not sms_send_receive_verify(self.log, self.ad_reference, self.dut,
                                       [rand_ascii_str(180)]):
            self.log.error("SMS receive test failed")
            return False
        else:
            self.log.info("SMS receive test passed")
            return True

    def _check_mms_mt(self):
        message_array = [("Test Message", rand_ascii_str(180), None)]
        if not mms_send_receive_verify(self.log, self.ad_reference, self.dut,
                                       message_array):
            self.log.error("MMS receive test failed")
            return False
        else:
            self.log.info("MMS receive test passed")
            return True

    def _check_data(self):
        if not verify_internet_connection(self.log, self.dut):
            self.dut.log.error("Data connection is not available.")
            return False
        return True

    def _check_lte_data(self):
        if not is_droid_in_network_generation(self.log, self.dut, GEN_4G,
                                              NETWORK_SERVICE_DATA):
            self.dut.log.error("Data is not on 4G network")
            return False
        if not verify_internet_connection(self.log, self.dut):
            self.log.error("Data not available on cell.")
            return False
        return True

    def _check_volte(self):
        if CAPABILITY_VOLTE in self.dut_capabilities:
            self._set_volte_provisioning()
            if not self._check_volte_provisioning():
                return False
            self.log.info("Check VoLTE")
            if not wait_for_state(self.dut.droid.imsIsVolteProvisionedOnDevice,
                                  True):
                self.dut.log.error("VoLTE provisioning is disabled.")
                return False
            if not phone_setup_volte(self.log, self.dut):
                self.log.error("Failed to setup VoLTE.")
                return False
            time.sleep(5)
            if not call_setup_teardown(self.log, self.dut, self.ad_reference,
                                       self.dut, is_phone_in_call_volte):
                self.log.error("VoLTE Call Failed.")
                return False
            if not self._check_lte_data():
                return False
        else:
            self.dut.log.info("VoLTE is not supported")
            return False
        return True

    def _check_csfb(self):
        if not phone_setup_csfb(self.log, self.dut):
            self.log.error("Failed to setup CSFB.")
            return False
        if not call_setup_teardown(self.log, self.dut, self.ad_reference,
                                   self.dut, is_phone_in_call_csfb):
            self.dut.log.error("CSFB Call Failed.")
            return False
        if not wait_for_network_generation(
                self.log, self.dut, GEN_4G,
                voice_or_data=NETWORK_SERVICE_DATA):
            self.dut.log.error("Data service failed to camp to 4G")
            return False
        if not verify_internet_connection(self.log, self.dut):
            self.log.error("Data not available on cell.")
            return False
        return True

    def _check_volte_enabled(self):
        if phone_idle_volte(self.log, self.dut):
            self.dut.log.info("VoLTE is enabled")
        else:
            self.dut.log.error("VoLTE is not enabled")
            return False
        if not call_setup_teardown(self.log, self.dut, self.ad_reference,
                                   self.dut, is_phone_in_call_volte):
            self.log.error("VoLTE Call Failed.")
            return False
        if not self._check_lte_data():
            return False
        return True

    def _check_csfb_enabled(self):
        if not call_setup_teardown(self.log, self.dut, self.ad_reference,
                                   self.dut, is_phone_in_call_csfb):
            self.log.error("CSFB Call Failed.")
            return False
        if not wait_for_network_generation(
                self.log, self.dut, GEN_4G,
                voice_or_data=NETWORK_SERVICE_DATA):
            self.dut.log.error("Data service failed to camp to 4G")
            return False
        if not verify_internet_connection(self.log, self.dut):
            self.log.error("Data not available on cell.")
            return False
        return True

    def _check_3g(self):
        self.log.info("Check 3G data and CS call")
        if not phone_setup_voice_3g(self.log, self.dut):
            self.log.error("Failed to setup 3G")
            return False
        if not verify_internet_connection(self.log, self.dut):
            self.log.error("Data not available on cell.")
            return False
        if not call_setup_teardown(self.log, self.dut, self.ad_reference,
                                   self.dut, is_phone_in_call_3g):
            self.log.error("WFC Call Failed.")
            return False
        if not sms_send_receive_verify(self.log, self.dut, self.ad_reference,
                                       [rand_ascii_str(50)]):
            self.log.error("SMS failed in 3G")
            return False
        return True

    def _check_tethering(self):
        self.log.info("Check tethering")
        for retries in range(3):
            try:
                if not self.dut.droid.carrierConfigIsTetheringModeAllowed(
                        TETHERING_MODE_WIFI,
                        MAX_WAIT_TIME_TETHERING_ENTITLEMENT_CHECK):
                    self.log.error("Tethering Entitlement check failed.")
                    if retries == 2: return False
                    time.sleep(10)
            except Exception as e:
                if retries == 2:
                    self.dut.log.error(e)
                    return False
                time.sleep(10)
        if not wifi_tethering_setup_teardown(
                self.log,
                self.dut, [self.ad_reference],
                check_interval=5,
                check_iteration=1):
            self.log.error("Tethering check failed.")
            return False
        return True

    def _fdr_stress_test(self, *args):
        """Fdr Reliability Test

        Arguments:
            function_name: function to be checked

        Expected Results:
            No crash happens in stress test.

        Returns:
            True is pass, False if fail.
        """
        self.number_of_devices = 2
        fail_count = collections.defaultdict(int)
        test_result = True

        for i in range(1, self.stress_test_number + 1):
            begin_time = get_current_epoch_time()
            test_name = "%s_iteration_%s" % (self.test_name, i)
            log_msg = "[Test Case] %s" % test_name
            self.log.info("%s begin", log_msg)
            self.dut.droid.logI("%s begin" % log_msg)
            test_msg = "FDR Stress Test %s Iteration <%s> / <%s>" % (
                self.test_name, i, self.stress_test_number)
            self.log.info(test_msg)
            fastboot_wipe(self.dut)
            self.log.info("%s wait %s secs for radio up.",
                self.dut.serial, WAIT_TIME_AFTER_FDR)
            time.sleep(WAIT_TIME_AFTER_FDR)
            failed_tests = self.feature_validator(*args)
            for test in failed_tests:
                fail_count[test] += 1

            crash_report = self.dut.check_crash_report(
                "%s_%s" % (self.test_name, i),
                begin_time,
                log_crash_report=True)
            if crash_report:
                fail_count["crashes"] += 1
            if failed_tests or crash_report:
                self.log.error("%s FAIL with %s and crashes %s", test_msg,
                               failed_tests, crash_report)
                self._take_bug_report(test_name, begin_time)
            else:
                self.log.info("%s PASS", test_msg)
            self.log.info("Total failure count: %s", dict(fail_count))
            self.log.info("%s end", log_msg)
            self.dut.droid.logI("%s end" % log_msg)

        for failure, count in fail_count.items():
            if count:
                self.log.error("%s failure count = %s in total %s iterations",
                               failure, count, self.stress_test_number)
                test_result = False
        return test_result

    """ Tests Begin """

    @test_tracker_info(uuid="a09a5d44-ffcc-4890-b0ba-a30a75e05fbd")
    @TelephonyBaseTest.tel_test_wrap
    def test_fdr_stress_volte(self):
        """FDR with VoLTE Test

        Steps:
            1. Fdr DUT.
            2. Wait for DUT to camp on LTE, Verify Data.
            3. Check VoLTE is enabled by default, check IMS registration.
               Wait for DUT report VoLTE enabled, make VoLTE call.
               And verify VoLTE SMS. (if support VoLTE)
            4. Check crashes.
            5. Repeat Step 1~4 for N times.

        Expected Results:
            No crash happens in stress test.

        Returns:
            True is pass, False if fail.
        """
        if CAPABILITY_VOLTE not in self.dut_capabilities:
            raise signals.TestSkip("VOLTE is not supported")
        if not self._check_volte():
            self.dut.log.error("VoLTE test failed before fdr test")
            return False
        func_names = ["_check_volte_enabled"]
        return self._fdr_stress_test(*func_names)

    """ Tests End """


from flask import Flask, render_template, request, redirect, url_for, flash
from flask_mysqldb import MySQL

app = Flask(__name__)
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'dbseguros'
mysql = MySQL(app)

app.secret_key = 'mysecret'

@app.route('/')
def Index():
    return render_template('index.html')

## INICIO LALO ##

@app.route('/indexSeguro')
def indexSeguro():
    return render_template('indexSeguro.html')

@app.route('/requisito')
def Requisito():
    return render_template('requisito.html')

@app.route('/observacion')
def Observacion():
    return render_template('observacion.html')

@app.route('/objetivo')
def Objetivo():
    return render_template('objetivo.html')

@app.route('/banco')
def banco():
    return render_template('banco.html')

@app.route('/terminos')
def terminos():
    return render_template('terminos.html')

@app.route('/privacidad')
def privacidad():
    return render_template('privacidad.html')

@app.route('/verificacion_edad')
def verificacion_edad():
    return render_template('verificacion_edad.html')

@app.route('/seguro')
def seguro():
    cur = mysql.connection.cursor()
    cur.execute('SELECT * FROM tbl_seguro')
    data = cur.fetchall()
    print(data)
    return render_template('seguro.html', contacts = data)

@app.route('/beneficiario/<id>/<secure>')
def beneficiario(id, secure):

    cur = mysql.connection.cursor()
    cur.execute('SELECT * FROM tbl_parentesco')
    data = cur.fetchall()

    dtTitular = mysql.connection.cursor()
    # dtTitular.execute(("""SELECT id_usuario_cotiza, nombre, apellido_paterno, apellido_materno, CURP, telefono, email, tbl_cat_seguro.precio, tbl_seguro.nombre_seguro
    #                      FROM tbl_usuario
    #                      INNER JOIN tbl_cat_seguro ON tbl_cat_seguro.id_cat_seguro = tbl_usuario.tbl_cat_seguro_id_cat_seguro
    #                      INNER JOIN tbl_seguro ON tbl_seguro.id_seguro = tbl_cat_seguro.tbl_seguro_id_seguro
    #                      WHERE id_usuario_cotiza = {} LIMIT 1 """).format(secure))
    # datos = dtTitular.fetchall()
    dtTitular.execute("""SELECT id_usuario_cotiza, nombre, apellido_paterno, apellido_materno, CURP, telefono, email, tbl_cat_seguro.precio, tbl_seguro.nombre_seguro
                         FROM tbl_usuario
                         INNER JOIN tbl_cat_seguro ON tbl_cat_seguro.id_cat_seguro = tbl_usuario.tbl_cat_seguro_id_cat_seguro
                         INNER JOIN tbl_seguro ON tbl_seguro.id_seguro = tbl_cat_seguro.tbl_seguro_id_seguro
                         WHERE id_usuario_cotiza = {} """.format(str(id)))
    datos = dtTitular.fetchall()
    print(datos)

    titular = mysql.connection.cursor()
    titular.execute('SELECT * FROM tbl_usuario LIMIT 1')
    titularData = titular.fetchone()

    seguro = mysql.connection.cursor()
    seguro.execute(('SELECT tbl_cat_seguro.*, tbl_seguro.nombre_seguro AS secure_name FROM tbl_cat_seguro INNER JOIN tbl_seguro ON tbl_seguro.id_seguro = tbl_cat_seguro.tbl_seguro_id_seguro WHERE id_cat_seguro = {} LIMIT 1').format(secure))
    seguroData = seguro.fetchone()
    # print(seguroData)

    return render_template('beneficiario.html', parentesco = data, seguro = seguroData, titular = titularData, datoTitular = datos)

@app.route('/verseguro/<id>', methods=['GET'])
def pagina3(id):
    cur = mysql.connection.cursor()
    cur.execute('SELECT tbl_cat_seguro.*, tbl_seguro.img_seguro, tbl_seguro.id_seguro FROM tbl_cat_seguro INNER JOIN tbl_seguro ON tbl_cat_seguro.tbl_seguro_id_seguro = tbl_seguro.id_seguro WHERE tbl_seguro_id_seguro = {}'.format(str(id)))
    seguros = cur.fetchall()
    data = []
    for seguro in seguros:
        print('******')
        print(seguro)
        print('******')
        json_data = {
            'id_cat_seguro':seguro[0],
            'nombre_cat':seguro[1],
            'precio':seguro[2],
            'descripcion':seguro[3],
            'fk_seguro':seguro[4],
            'img_seguro':seguro[5],
            'id_seguro':seguro[6]
            }
        data.append(json_data)

    response = {'seguros':data}
    return jsonify(response)

@app.route('/titular/<id>', methods=['GET'])
def cotizar(id):

    cur = mysql.connection.cursor()
    cur.execute('SELECT * FROM tbl_genero')
    data = cur.fetchall()

    curs = mysql.connection.cursor()
    curs.execute('SELECT * FROM tbl_profesion')
    datas = curs.fetchall()

    cursr = mysql.connection.cursor()
    cursr.execute('SELECT * FROM tbl_cat_seguro WHERE id_cat_seguro = {}'.format(str(id)))
    datasr = cursr.fetchall()
    return render_template('titular.html', cotiz = data, prof = datas, seguro_id = datasr[0], id_seguro = id)

@app.route('/add_titular', methods=["POST","GET"])
def add_titular():
    if request.method == 'POST':
        nombre = request.form['nombre'].upper()
        apellido_paterno = request.form['apellido_paterno'].upper()
        apellido_materno = request.form['apellido_materno'].upper()
        sexo = request.form['sexo'].upper()
        email = request.form['email'].upper()
        telefono = request.form['telefono']
        profesion = request.form['profesion'].upper()
        fecha_nacimiento = request.form['fecha_nacimiento']
        curp = request.form['curp'].upper()
        precio_seguro = request.form['precio_seguro']

        verifyTitular = mysql.connection.cursor()
        verifyTitular.execute(("SELECT * FROM tbl_usuario WHERE CURP = '{}'").format(curp))
        verifyTitular = verifyTitular.fetchall()
        existsTitular = len(verifyTitular)

        if(existsTitular > 0):
            json_data = {'id':0}
            return jsonify(json_data)

        cur = mysql.connection.cursor()

        cur.execute('INSERT INTO tbl_usuario (nombre, apellido_paterno, apellido_materno, fecha_nacimiento, telefono, email, CURP, tbl_genero_id_genero, tbl_profesion_id_profesion, tbl_cat_seguro_id_cat_seguro) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)',
        (nombre, apellido_paterno, apellido_materno, fecha_nacimiento, telefono, email, curp, sexo, profesion, precio_seguro))
        mysql.connection.commit()

        extractTitular = mysql.connection.cursor()
        extractTitular.execute(("SELECT id_usuario_cotiza FROM tbl_usuario WHERE CURP = '{}'").format(curp))
        extractTitular = extractTitular.fetchall()
        idTitular = extractTitular[0][0]
        idTitular = str(idTitular)
        json_data = {'id':idTitular}
        return jsonify(json_data)

@app.route('/verdtatitular/<id>', methods=['POST'])
def verdtatitular(id):
    titular = id
    # CURL to generate payment order n' show url to pay
    response = requests.post('https://api.conekta.io/checkouts',headers={'Accept':'application/vnd.conekta-v2.0.0+json','Content-Type':'application/json','Authorization':'Basic a2V5X3FiSzZ6ZmVIdEFIU1hKeHNNSGNpTHc='}, json={
        "name": request.form['product_name'],
        "type": "PaymentLink",
        "recurrent": False,
        "expires_at": request.form['expires_at'],
        "allowed_payment_methods": ["card"],
        "needs_shipping_contact": True,
        "monthly_installments_enabled": False,
        "order_template": {
            "line_items": [{
                "name": request.form['product_name'],
                "unit_price": request.form['secure_price'],
                "quantity": 1
            }],
            "currency": "MXN",
            "customer_info": {
                "name": request.form['titular_name'],
                "email": request.form['titular_email'],
                "phone": request.form['titular_phone']
            }
        }
    })
    json_response = response.json()
    return jsonify(json_response)
    # Hasta aquí se realiza la generación de orden de PAGO POR TARJETA
    # Debes continuar tu proceso por aquí con el o los beneficiarios aquí

    # Me marcaba error y lo realice por aparte, es el que está aquí abajo
    # cur = mysql.connection.cursor()
    # cur.execute(""" SELECT tbl_usuario.*, tbl_cat_seguro.nombre_cat, tbl_cat_seguro.precio, tbl_seguro.img_seguro
    #                 FROM tbl_usuario
    #                 INNER JOIN tbl_cat_seguro ON tbl_usuario.tbl_cat_seguro_id_cat_seguro = tbl_cat_seguro.id_cat_seguro
    #                 INNER JOIN tbl_seguro ON tbl_cat_seguro.tbl_seguro_id_seguro = tbl_seguro.id_seguro WHERE CURP = %s """, (id,))
    # datas = cur.fetchall()

    # data = []
    # for seguro in datas:
    #     print('******')
    #     # print(seguro)
    #     print('******')
    #     json_data = {
    #         'id_usuario_cotiza':seguro[0],
    #         'nombre':seguro[1],
    #         'apellido_paterno':seguro[2],
    #         'apellido_materno':seguro[3],
    #         'precio':seguro[13],
    #         'img_seguro':seguro[14],
    #         'CURP':seguro[8]
    #         }
    #     data.append(json_data)
    # responses = {'datas':data}
    # return jsonify(responses)
@app.route('/verdtatitu/<id>', methods=['POST'])
def verdtatitu(id):
    titular = id

    cur = mysql.connection.cursor()
    cur.execute(""" SELECT tbl_usuario.*, tbl_cat_seguro.nombre_cat, tbl_cat_seguro.precio, tbl_seguro.img_seguro
                    FROM tbl_usuario
                    INNER JOIN tbl_cat_seguro ON tbl_usuario.tbl_cat_seguro_id_cat_seguro = tbl_cat_seguro.id_cat_seguro
                    INNER JOIN tbl_seguro ON tbl_cat_seguro.tbl_seguro_id_seguro = tbl_seguro.id_seguro WHERE CURP = %s """, (id,))
    datas = cur.fetchall()

    data = []
    for seguro in datas:
        print('******')
        # print(seguro)
        print('******')
        json_data = {
            'id_usuario_cotiza':seguro[0],
            'nombre':seguro[1],
            'apellido_paterno':seguro[2],
            'apellido_materno':seguro[3],
            'precio':seguro[13],
            'img_seguro':seguro[14],
            'CURP':seguro[8]
            }
        data.append(json_data)
    responses = {'datas':data}
    return responses

@app.route('/add_beneficiario', methods=["POST"])
def add_beneficiario():
    if request.method == 'POST':

        nombre_beneficiario = request.form['nombre_beneficiario'].upper()
        apellido_p_beneficiario = request.form['apellido_p_beneficiario'].upper()
        apellido_m_beneficiario = request.form['apellido_m_beneficiario'].upper()
        porcentaje_beneficiario = request.form['porcentaje_beneficiario'].upper()
        parentesco_beneficiario = request.form['parentesco_beneficiario'].upper()
        titular_veri = request.form['titular_veri']

        nombre_beneficiario_dina = request.form['nombre_beneficiario_dina'].upper()
        apellido_p_beneficiario_dina = request.form['apellido_p_beneficiario_dina'].upper()
        apellido_m_beneficiario_dina = request.form['apellido_m_beneficiario_dina'].upper()
        porcentaje_beneficiario_dina = request.form['porcentaje_beneficiario_dina'].upper()
        parentesco_beneficiario_dina = request.form['parentesco_beneficiario_dina'].upper()

        nombre_beneficiario_dina3 = request.form['nombre_beneficiario_dina3'].upper()
        apellido_p_beneficiario_dina3 = request.form['apellido_p_beneficiario_dina3'].upper()
        apellido_m_beneficiario_dina3 = request.form['apellido_m_beneficiario_dina3'].upper()
        parentesco_beneficiario_dina3 = request.form['parentesco_beneficiario_dina3'].upper()
        porcentaje_beneficiario_dina3 = request.form['porcentaje_beneficiario_dina3'].upper()

        nombre_beneficiario_dina4 = request.form['nombre_beneficiario_dina4'].upper()
        apellido_p_beneficiario_dina4 = request.form['apellido_p_beneficiario_dina4'].upper()
        apellido_m_beneficiario_dina4 = request.form['apellido_m_beneficiario_dina4'].upper()
        parentesco_beneficiario_dina4 = request.form['parentesco_beneficiario_dina4'].upper()
        porcentaje_beneficiario_dina4 = request.form['porcentaje_beneficiario_dina4'].upper()

        if nombre_beneficiario_dina == "" and apellido_p_beneficiario_dina == "" and apellido_m_beneficiario_dina == "" and porcentaje_beneficiario_dina != "" and parentesco_beneficiario_dina != "":
            cur = mysql.connection.cursor()
            cur.execute('INSERT INTO tbl_beneficiario (nombre, apellido_paterno, apellido_materno, porcentaje, tbl_parentesco_id_parentesco, tbl_usuario_id_usuario_cotiza) VALUES (%s, %s, %s, %s, %s, %s)',
            (nombre_beneficiario, apellido_p_beneficiario, apellido_m_beneficiario, porcentaje_beneficiario, parentesco_beneficiario, titular_veri))
            mysql.connection.commit()
            return render_template('banco.html')

        elif nombre_beneficiario_dina3 == "" and apellido_p_beneficiario_dina3 == "" and apellido_m_beneficiario_dina3 == "" and porcentaje_beneficiario_dina3 != "" and parentesco_beneficiario_dina3 != "":
            curd = mysql.connection.cursor()
            curd.execute('INSERT INTO tbl_beneficiario (nombre, apellido_paterno, apellido_materno, porcentaje, tbl_parentesco_id_parentesco, tbl_usuario_id_usuario_cotiza) VALUES (%s, %s, %s, %s, %s, %s)',
            (nombre_beneficiario_dina, apellido_p_beneficiario_dina, apellido_m_beneficiario_dina, porcentaje_beneficiario_dina, parentesco_beneficiario_dina, titular_veri))
            mysql.connection.commit()

            cur = mysql.connection.cursor()
            cur.execute('INSERT INTO tbl_beneficiario (nombre, apellido_paterno, apellido_materno, porcentaje, tbl_parentesco_id_parentesco, tbl_usuario_id_usuario_cotiza) VALUES (%s, %s, %s, %s, %s, %s)',
            (nombre_beneficiario, apellido_p_beneficiario, apellido_m_beneficiario, porcentaje_beneficiario, parentesco_beneficiario, titular_veri))
            mysql.connection.commit()
            return render_template('banco.html')

        elif nombre_beneficiario_dina4 == "" and apellido_p_beneficiario_dina4 == "" and apellido_m_beneficiario_dina4 == "" and porcentaje_beneficiario_dina4 != "" and parentesco_beneficiario_dina4 != "":
            curdn = mysql.connection.cursor()
            curdn.execute('INSERT INTO tbl_beneficiario (nombre, apellido_paterno, apellido_materno, porcentaje, tbl_parentesco_id_parentesco, tbl_usuario_id_usuario_cotiza) VALUES (%s, %s, %s, %s, %s, %s)',
            (nombre_beneficiario_dina3, apellido_p_beneficiario_dina3, apellido_m_beneficiario_dina3, porcentaje_beneficiario_dina3, parentesco_beneficiario_dina3, titular_veri))
            mysql.connection.commit()

            curd = mysql.connection.cursor()
            curd.execute('INSERT INTO tbl_beneficiario (nombre, apellido_paterno, apellido_materno, porcentaje, tbl_parentesco_id_parentesco, tbl_usuario_id_usuario_cotiza) VALUES (%s, %s, %s, %s, %s, %s)',
            (nombre_beneficiario_dina, apellido_p_beneficiario_dina, apellido_m_beneficiario_dina, porcentaje_beneficiario_dina, parentesco_beneficiario_dina, titular_veri))
            mysql.connection.commit()

            cur = mysql.connection.cursor()
            cur.execute('INSERT INTO tbl_beneficiario (nombre, apellido_paterno, apellido_materno, porcentaje, tbl_parentesco_id_parentesco, tbl_usuario_id_usuario_cotiza) VALUES (%s, %s, %s, %s, %s, %s)',
            (nombre_beneficiario, apellido_p_beneficiario, apellido_m_beneficiario, porcentaje_beneficiario, parentesco_beneficiario, titular_veri))
            mysql.connection.commit()
            return render_template('banco.html')

        elif nombre_beneficiario_dina4 != "" and apellido_p_beneficiario_dina4 != "" and apellido_m_beneficiario_dina4 != "" and porcentaje_beneficiario_dina4 != 0 and parentesco_beneficiario_dina4 != 0:
            # else:
            curdni = mysql.connection.cursor()
            curdni.execute('INSERT INTO tbl_beneficiario (nombre, apellido_paterno, apellido_materno, porcentaje, tbl_parentesco_id_parentesco, tbl_usuario_id_usuario_cotiza) VALUES (%s, %s, %s, %s, %s, %s)',
            (nombre_beneficiario_dina4, apellido_p_beneficiario_dina4, apellido_m_beneficiario_dina4, porcentaje_beneficiario_dina4, parentesco_beneficiario_dina4, titular_veri))
            mysql.connection.commit()

            curdn = mysql.connection.cursor()
            curdn.execute('INSERT INTO tbl_beneficiario (nombre, apellido_paterno, apellido_materno, porcentaje, tbl_parentesco_id_parentesco, tbl_usuario_id_usuario_cotiza) VALUES (%s, %s, %s, %s, %s, %s)',
            (nombre_beneficiario_dina3, apellido_p_beneficiario_dina3, apellido_m_beneficiario_dina3, porcentaje_beneficiario_dina3, parentesco_beneficiario_dina3, titular_veri))
            mysql.connection.commit()

            curd = mysql.connection.cursor()
            curd.execute('INSERT INTO tbl_beneficiario (nombre, apellido_paterno, apellido_materno, porcentaje, tbl_parentesco_id_parentesco, tbl_usuario_id_usuario_cotiza) VALUES (%s, %s, %s, %s, %s, %s)',
            (nombre_beneficiario_dina, apellido_p_beneficiario_dina, apellido_m_beneficiario_dina, porcentaje_beneficiario_dina, parentesco_beneficiario_dina, titular_veri))
            mysql.connection.commit()

            cur = mysql.connection.cursor()
            cur.execute('INSERT INTO tbl_beneficiario (nombre, apellido_paterno, apellido_materno, porcentaje, tbl_parentesco_id_parentesco, tbl_usuario_id_usuario_cotiza) VALUES (%s, %s, %s, %s, %s, %s)',
            (nombre_beneficiario, apellido_p_beneficiario, apellido_m_beneficiario, porcentaje_beneficiario, parentesco_beneficiario, titular_veri))
            mysql.connection.commit()
            return render_template('banco.html')

## FIN LALO ##

@app.route('/producto/1')
def productoOne():
    return render_template('producto1.html')

@app.route('/producto/2')
def productoTwo():
    return render_template('producto2.html')

@app.route('/producto/3')
def productoThree():
    return render_template('producto3.html')

@app.route('/producto/4')
def productoFour():
    return render_template('producto4.html')

@app.route('/producto/5')
def productoFive():
    return render_template('producto5.html')

@app.route('/producto/6')
def productoSix():
    return render_template('producto6.html')

@app.route('/producto/7')
def productoSeven():
    return render_template('producto7.html')

@app.route('/conocer_producto/1')
def ConocerproductoOne():
    return render_template('conocer_producto1.html')

@app.route('/conocer_producto/2')
def ConocerproductoTwo():
    return render_template('conocer_producto2.html')

@app.route('/conocer_producto/3')
def ConocerproductoThree():
    return render_template('conocer_producto3.html')

@app.route('/conocer_producto/4')
def ConocerproductoFour():
    return render_template('conocer_producto4.html')

@app.route('/conocer_producto/5')
def ConocerproductoFive():
    return render_template('conocer_producto5.html')

@app.route('/conocer_producto/6')
def ConocerproductoSix():
    return render_template('conocer_producto6.html')

@app.route('/conocer_producto/7')
def ConocerproductoSeven():
    return render_template('conocer_producto7.html')

@app.route('/sucursales')
def sucursales():
    return render_template('sucursales.html')

@app.route('/simulator')
def simulator():
    return render_template('simulator.html')

if __name__ == '__main__':
    app.run(port = 3000, debug = True)


import os
from data_loader import WikiDataset
from torch.utils.data import DataLoader
import torch
import torch.optim as optim
from model import HyperParameters, load_pretrained_embeddings, BiLSTM_CRF
from utilities import configure_workspace

if __name__ == "__main__":
    configure_workspace()
    DATA_PATH = os.path.join(os.getcwd(), 'data')
    RESOURCES_PATH = os.path.join(os.getcwd(), 'resources')

    file_path = os.path.join(DATA_PATH, 'en.wiki.sentences.train')
    dev_file_path = os.path.join(DATA_PATH, 'en.wiki.sentences.dev')
    gold_file_path = os.path.join(DATA_PATH, 'en.wiki.gold.train')
    dev_gold_file_path = os.path.join(DATA_PATH, 'en.wiki.gold.dev')

    print('========== Training Dataset ==========')
    train_dataset = WikiDataset(file_path, gold_file_path, is_crf=True)
    train_dataset.vectorize_data()

    train_x = torch.LongTensor(train_dataset.train_x)
    print(f'train_x shape is: {train_x.shape}')
    # x.shape = [number of samples, max characters/sentence] = [31_553, 256]
    train_y = torch.LongTensor(train_dataset.train_y)
    print(f'train_y shape is: {train_y.shape}')
    # y.shape = [number of samples, max characters/sentence] = [31_553, 256]

    dev_dataset = WikiDataset(dev_file_path, dev_gold_file_path, is_crf=True)
    dev_dataset.char2idx = train_dataset.char2idx
    dev_dataset.idx2char = train_dataset.idx2char
    dev_dataset.label2idx = train_dataset.label2idx
    dev_dataset.idx2label = train_dataset.idx2label
    dev_dataset.vectorize_data()

    hyperparams = HyperParameters()
    hyperparams.vocab_size = train_dataset.vocab_size
    hyperparams.num_classes = train_dataset.out_vocab_size

    # mask tensor with shape (batch_size, max_sent_size)
    # mask = (x_tags != Const.PAD_TAG_ID).float()

    # see bilstm_crf.py
    model = BiLSTM_CRF(hyperparams)
    opt = optim.SGD(model.parameters(), lr=0.01, weight_decay=1e-4)
    train_dataset_ = DataLoader(train_dataset, batch_size=hyperparams.batch_size, shuffle=True)
    model.train_(optimizer=opt, epochs=1, train_dataset=train_dataset_)

    save_model_path = os.path.join(RESOURCES_PATH, 'bilstm_crf_model.pt')
    torch.save(model.state_dict(), save_model_path)
    # model.load_state_dict(torch.load(save_model_path))

    model.predict(dev_dataset.train_x, train_dataset.idx2label)


"""cambie nombre de tabla

Revision ID: 920235e63caa
Revises: 98bdf34b0b01
Create Date: 2023-05-28 19:11:42.199348

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '920235e63caa'
down_revision = '98bdf34b0b01'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('areas',
    sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
    sa.Column('name', sa.Text(), nullable=False),
    sa.Column('floor', sa.Integer(), nullable=True),
    sa.PrimaryKeyConstraint('id')
    )
    op.drop_table('area_model')
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('area_model',
    sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False),
    sa.Column('name', sa.TEXT(), autoincrement=False, nullable=False),
    sa.Column('floor', sa.INTEGER(), autoincrement=False, nullable=True),
    sa.PrimaryKeyConstraint('id', name='area_model_pkey')
    )
    op.drop_table('areas')
    # ### end Alembic commands ###


import turtle

num_sides = int(input("Enter number of sides: "))
num_length = int(input("Enter total length of the polygon: "))

angle = 360/num_sides

for i in range (0, num_sides, 1):
    turtle.forward(num_length)
    turtle.right(angle)


#!/usr/bin/env python

import sys, os
import itertools, operator
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np

def get_params_from_output_file(output_file):
	results_tuples = []
	time = 0
	fp = open(output_file, "r")
	line = fp.readline()
	while line:
		tokens = line.split('-')
		mechanism = tokens[0].split('.')[0]
		threads = int(tokens[1].split('_')[0])
		grain = int(tokens[2])
		line = fp.readline()
		time = float(line.split()[2])
		results_tuples.append((mechanism, threads, time))
		line = fp.readline()
		line = fp.readline()
	fp.close()
	return (results_tuples, grain)

def tuples_by_mechanism(tuples):
	ret = []
	tuples_sorted = sorted(tuples, key=operator.itemgetter(0))
	for key,group in itertools.groupby(tuples_sorted,operator.itemgetter(0)):
		ret.append((key, tuple(zip(*map(lambda x: x[1:], list(group))))))
	return ret

global_threads = [1, 2, 4, 8]

if len(sys.argv) < 2:
	print ("usage:", sys.argv[0], "<output_directories>")
	sys.exit(1)

for dirname in sys.argv[1:]:
	results = []
	if dirname.endswith("/"):
		dirname = dirname[0:-1]
	basename = os.path.basename(dirname)
	output_file = dirname
	(results, grain) = get_params_from_output_file(output_file)

markers = ['.', 'v', 's', 'h', '^']
fig = plt.figure()
plt.grid(True)
ax = plt.subplot(111)
ax.set_xlabel("$Threads$")
ax.set_ylabel("$Time(sec)$")

i = 0
tuples_by_mech = tuples_by_mechanism(results)
for tuple in tuples_by_mech:
	mechanism = tuple[0]
	threads_axis = tuple[1][0]
	time_axis = tuple[1][1]
	x_ticks = np.arange(0, len(global_threads))
	x_labels = map(str, global_threads)
	ax.xaxis.set_ticks(x_ticks)
	ax.xaxis.set_ticklabels(x_labels)

	print (x_ticks)
	print (time_axis)
	ax.plot(x_ticks, time_axis, label=str(mechanism), marker=markers[i%len(markers)], markersize=3)
	i = i + 1

plt.title("Grain size = " + str(grain))
lgd = ax.legend(ncol=len(tuples_by_mech), bbox_to_anchor=(0.9, -0.1), prop={'size':8})
plt.savefig('Grain'+str(grain)+'.realtime.png', bbox_extra_artists=(lgd,), bbox_inches='tight')


from selenium import webdriver
import time, re
from PIL import Image

def QR_login():

    def getGTK(cookie):
        """ 根据cookie得到GTK """
        hashes = 5381
        for letter in cookie['p_skey']:
            hashes += (hashes << 5) + ord(letter)

        return hashes & 0x7fffffff

    browser = webdriver.PhantomJS()
    url = "https://qzone.qq.com/"#QQ登录网址

    browser.get(url)
    browser.maximize_window()

    time.sleep(3)
    print("---------")
    browser.get_screenshot_as_file('QR.png')
    print("=============")
    img = Image.open('QR.png')
    img.show()

    time.sleep(30)
    print(browser.title)

    cookie = {}
    for elem in browser.get_cookies():
        cookie[elem['name']] = elem['value']

    print('Get the cookie of QQlogin successfully!(共%d个键值对)' % (len(cookie)))

    html = browser.page_source
    g_qzonetoken=re.search(r'window\.g_qzonetoken = \(function\(\)\{ try\{return (.*?);\} catch\(e\)',html)#从网页源码中提取g_qzonetoke

    gtk = getGTK(cookie)
    browser.quit()

    return cookie, gtk , g_qzonetoken.group(1)

if __name__ == '__main__':
    s1, s2,s3 = QR_login()
    print(s1)
    print(s2)
    print(s3)


# PyQt6/Qt
from PyQt6.QtCore import pyqtSlot  # @UnresolvedImport

# UM/Cura
from UM.Logger import Logger  # @UnresolvedImport

# CIU
from .Compat import Deprecations

class PreferencesAdvanced:
    def __init__(self, namespace):
        self.namespace = namespace
        self.type_storage = {}

    def addPreference(self, name, default):
        if default is None:
            raise ValueError("NoneType default values are not allowed. Use either False or 0!")
        self.type_storage[name] = type(default)
        Deprecations.getPreferences().addPreference("{}/{}".format(self.namespace, name), default)

    def getValue(self, name, forced_type=None):
        result = Deprecations.getPreferences().getValue("{}/{}".format(self.namespace, name))  # Received as a string
        target_type = self.determineTargetType(name, forced_type)

        # Forcing type conversion when the type is known. Should be normally the case.
        if target_type:
            # Corrections if the result out of Cura's preference storage is a string..
            if type(result) is str:
                # Special steps for booleans
                if target_type is bool:
                    if result.lower() == "true":
                        result = True
                    elif result.lower() == "false":
                        result = False
                    else:
                        # Assuming that the text is an int or float from now..
                        result = float(result)  # "1.2"
                        result = int(result)  # 1.2

            # Special steps for integers
            if target_type is int and type(result) is not int:
                # Giving a stored int a last chance if the value has been saved as float
                result = float(result)
            result = target_type(result)

        return result

    def setValue(self, name, value, forced_type=None):
        target_type = self.determineTargetType(name, forced_type)  # Received as a string

        # Special conversion of some data types
        # if target_type:
        #    if target_type == foo_type:
        #        value = foo(bar)
        value = str(value)

        # Passing all as strings as it will be stored and restored in strings into the config file later
        result = Deprecations.getPreferences().setValue("{}/{}".format(self.namespace, name), value)

        return None

    def determineTargetType(self, name, forced_type=None):
        "Checking for the targetted type of data"

        target_type = None
        stored_type = None
        if name in self.type_storage.keys():
            stored_type = self.type_storage[name]
            target_type = stored_type
        if forced_type:
            if stored_type and forced_type is not stored_type:
                Logger.log("w", "Stored type as set by default value does not fit to forced type!")
            target_type = forced_type
        return target_type


import encoding
import protein_translation
import sys

switch = sys.argv[1]
filename = sys.argv[2]

with open(filename, 'r') as f:
    if switch == 'encoding':
        text = f.readline().strip()
        peptide = f.readline().strip()
        print('\n'.join(encoding.encode(text, peptide)))

    else:
        input = f.readline().strip()
        print(protein_translation.translate(input))


import logging
import os

import networkx as nx
import pandas as pd

from kwnlp_preprocessor import argconfig

logger = logging.getLogger(__name__)

# TODO: centralize this in argconfig
# have to change in task 39p1 create article too
ROOT_NQIDS = [
    17442446,  # Wikimedia internal item
    14795564,  # point in time with respect to recurrent timeframe
    18340514,  # events in a specific year or time period
    5,  # human
    2221906,  # geographic location
    43229,  # organization
    4830453,  # business
]

def main(
    wp_yyyymmdd: str,
    wd_yyyymmdd: str,
    data_path: str = argconfig.DEFAULT_KWNLP_DATA_PATH,
    wiki: str = argconfig.DEFAULT_KWNLP_WIKI,
) -> None:

    wp_dump_path = os.path.join(data_path, f"wikipedia-derived-{wp_yyyymmdd}")
    wd_dump_path = os.path.join(data_path, f"wikidata-derived-{wd_yyyymmdd}")

    # read title mapper CSV as base
    # ====================================================================
    file_path = os.path.join(
        wp_dump_path,
        "kwnlp-sql",
        f"kwnlp-{wiki}-{wp_yyyymmdd}-title-mapper.csv",
    )
    logger.info(f"reading {file_path}")
    df = pd.read_csv(
        file_path,
        keep_default_na=False,
        usecols=["source_id", "source_title", "is_redirect"],
    )

    # get base information from title mapper
    # ====================================================================
    df = df[~df["is_redirect"]]
    df = df[["source_id", "source_title"]]
    df = df.rename(columns={"source_id": "page_id", "source_title": "page_title"})

    # read item id from page props CSV
    # ====================================================================
    file_path = os.path.join(
        wp_dump_path,
        "kwnlp-sql",
        f"kwnlp-{wiki}-{wp_yyyymmdd}-page-props.csv",
    )
    logger.info(f"reading {file_path}")
    df_pp = pd.read_csv(file_path, usecols=["page_id", "wikibase_item"])

    # add wikidata item id
    # ====================================================================
    df = pd.merge(df, df_pp, on="page_id", how="left")

    df["wikibase_item"] = df["wikibase_item"].fillna("Q-1").apply(lambda x: int(x[1:]))

    df = df.rename(columns={"wikibase_item": "item_id"})

    # read subclass of info
    # ====================================================================
    file_path = os.path.join(
        wd_dump_path,
        "p279-claim",
        f"kwnlp-wikidata-{wd_yyyymmdd}-p279-claim.csv",
    )
    logger.info(f"reading {file_path}")
    df_p279 = pd.read_csv(file_path, usecols=["source_id", "target_id"])
    logger.info("building p279 graph")
    g_p279 = nx.DiGraph()
    g_p279.add_edges_from(df_p279.values)

    # read instance of info
    # ====================================================================
    file_path = os.path.join(
        wd_dump_path,
        "p31-claim",
        f"kwnlp-wikidata-{wd_yyyymmdd}-p31-claim.csv",
    )
    logger.info(f"reading {file_path}")
    df_p31 = pd.read_csv(file_path, usecols=["source_id", "target_id"])

    # add root qid tags
    # ====================================================================
    for root_nqid in ROOT_NQIDS:

        logger.info(f"tagging items in subclass tree of {root_nqid}")
        col_name = f"isa_Q{root_nqid}"
        subclass_qids = set(nx.ancestors(g_p279, root_nqid)).union(set([root_nqid]))
        mask = df_p31["target_id"].isin(subclass_qids)
        tmp_df = df_p31[mask].copy()
        tmp_df = tmp_df.sort_values(by=["source_id", "target_id"])
        tmp_df = tmp_df.drop_duplicates(subset=["source_id"], keep="first")
        tmp_df = tmp_df.rename(columns={"source_id": "item_id", "target_id": col_name})

        df = pd.merge(df, tmp_df, on="item_id", how="left")
        df[col_name] = df[col_name].fillna(False).astype(int)

    # read views CSV
    # ====================================================================
    file_path = os.path.join(
        wp_dump_path,
        "kwnlp-sql",
        f"kwnlp-{wiki}-{wp_yyyymmdd}-prior-month-pageviews-complete.csv",
    )
    logger.info(f"reading {file_path}")
    df_views = pd.read_csv(file_path, keep_default_na=False)

    # add views
    # ====================================================================
    df = pd.merge(df, df_views, on="page_title", how="left")
    df["views"] = df["views"].fillna(0).astype("int")

    # sort and write output
    # ====================================================================
    df = df[["page_id", "item_id", "page_title", "views"] + [f"isa_Q{nqid}" for nqid in ROOT_NQIDS]]
    df = df.sort_values("page_id")
    file_path = os.path.join(
        wp_dump_path,
        "kwnlp-sql",
        f"kwnlp-{wiki}-{wp_yyyymmdd}-article-pre.csv",
    )
    os.makedirs(os.path.dirname(file_path), exist_ok=True)
    logger.info(f"writing {file_path}")
    df.to_csv(file_path, index=False)
    return df

if __name__ == "__main__":

    description = "create kwnlp article pre"
    arg_names = ["wp_yyyymmdd", "wd_yyyymmdd", "data_path", "wiki", "loglevel"]
    parser = argconfig.get_argparser(description, arg_names)

    args = parser.parse_args()
    logging.basicConfig(level=args.loglevel)
    logger.info(f"args={args}")

    main(
        args.wp_yyyymmdd,
        args.wd_yyyymmdd,
        data_path=args.data_path,
        wiki=args.wiki,
    )


from .models import Tag, Categories, Blog
from hitcount.views import HitCountDetailView

def get_tags(request):
    tags = Tag.objects.filter(is_active=True)[0:8]
    context = {'tags':tags}
    return context

def get_Categories(request):
    categories = Categories.objects.filter(is_active=True)[0:8]
    trending_categories = Categories.objects.filter(is_active=True, is_trending=True)[0:8]
    context = {'all_categories':categories, 'trend_categories':trending_categories}
    return context

def popular_Blog(request):
    # Popular Blogs
    blog = Blog.objects.order_by('-hit_count_generic__hits')[0:4]
    # Latest Blogs
    blogs = Blog.objects.all().order_by('-created_at')[0:3]
    context = {'popular_blog':blog, 'blogs':blogs}
    return context


i = 'R1, L4, L5, L5, R2, R2, L1, L1, R2, L3, R4, R3, R2, L4, L2, R5, L1, R5, L5, L2, L3, L1, R1, R4, R5, L3, R2, L4, L5, R1, R2, L3, R3, L3, L1, L2, R5, R4, R5, L5, R1, L190, L3, L3, R3, R4, R47, L3, R5, R79, R5, R3, R1, L4, L3, L2, R194, L2, R1, L2, L2, R4, L5, L5, R1, R1, L1, L3, L2, R5, L3, L3, R4, R1, R5, L4, R3, R1, L1, L2, R4, R1, L2, R4, R4, L5, R3, L5, L3, R1, R1, L3, L1, L1, L3, L4, L1, L2, R1, L5, L3, R2, L5, L3, R5, R3, L4, L2, R2, R4, R4, L4, R5, L1, L3, R3, R4, R4, L5, R4, R2, L3, R4, R2, R1, R2, L4, L2, R2, L5, L5, L3, R5, L5, L1, R4, L1, R1, L1, R4, L5, L3, R4, R1, L3, R4, R1, L3, L1, R1, R2, L4, L2, R1, L5, L4, L5'.split(', ')

pos = (0, 0)
direction = 0

dirs = ['North', 'East', 'South', 'West']

trail = []

def walk(direction, dist):
    global pos
    steps = 0

    while steps < dist:
        # North
        if direction == 0:
            pos = (pos[0], pos[1] + 1)

        # East
        if direction == 1:
            pos = (pos[0] + 1, pos[1])

        # South
        if direction == 2:
            pos = (pos[0], pos[1] - 1)

        # West
        if direction == 3:
            pos = (pos[0] - 1, pos[1])

        if trail.count(pos) > 0:
            print('Found', pos)
            print(abs(pos[0]) + abs(pos[1]))
            exit()

        trail.append(pos)

        steps += 1

for step in i:
    turn = step[0:1]

    dist = int(step[1:])

    if turn == 'R':
        direction += 1
    else:
        direction -= 1

    if direction == 4:
        direction = 0

    if direction == -1:
        direction = 3

    walk(direction, dist)


from py4j.java_gateway import JavaClass
from pyspark.ml.common import _py2java

from .metadata import __copyright__, __license__, __version__

class PMMLBuilder(object):

	def __init__(self, sc, df, pipelineModel):
		javaDf = _py2java(sc, df)
		javaSchema = javaDf.schema.__call__()
		javaPipelineModel = pipelineModel._to_java()
		javaPmmlBuilderClass = sc._jvm.org.jpmml.sparkml.PMMLBuilder
		if(not isinstance(javaPmmlBuilderClass, JavaClass)):
			raise RuntimeError("JPMML-SparkML not found on classpath")
		javaPmmlBuilder = javaPmmlBuilderClass(javaSchema, javaPipelineModel)
		self.sc = sc
		self.javaPmmlBuilder = javaPmmlBuilder

	def build(self):
		return self.javaPmmlBuilder.build()

	def buildByteArray(self):
		return self.javaPmmlBuilder.buildByteArray()

	def buildFile(self, path):
		javaFile = self.sc._jvm.java.io.File(path)
		javaFile = self.javaPmmlBuilder.buildFile(javaFile)
		return javaFile.getAbsolutePath()

	def putOption(self, pipelineStage, key, value):
		javaKey = _py2java(self.sc, key)
		javaValue = _py2java(self.sc, value)
		if pipelineStage is None:
			self.javaPmmlBuilder.putOption(javaKey, javaValue)
		else:
			javaPipelineStage = pipelineStage._to_java()
			self.javaPmmlBuilder.putOption(javaPipelineStage, javaKey, javaValue)
		return self

	def verify(self, df, precision = 1e-14, zeroThreshold = 1e-14):
		javaDf = _py2java(self.sc, df)
		self.javaPmmlBuilder.verify(javaDf, precision, zeroThreshold)
		return self

def toPMMLBytes(sc, df, pipelineModel):
	raise RuntimeError("Replace \"toPMMLBytes(sc, df, pipelineModel)\" with \"PMMLBuilder(sc, df, pipelineModel).buildByteArray()\"")