import sys, iptc, re, socket

single_options = False

predesigned_rules = ['BlockIncomingSSH', 'BlockOutgoingSSH', 'BlockAllSSH', 'BlockIncomingHTTP', 'BlockIncomingHTTPS',\
    'BlockIncomingPing', 'BlockInvalidPackets', 'BlockSYNFlooding', 'BlockXMASAttack', 'ForceSYNPackets']

accepted_protocols = ['ah','egp','esp','gre','icmp','idp','igmp','ip','pim','pum','pup','raw','rsvp','sctp','tcp','tp','udp']
ipsrc = None
ipsrc_range = None
ipdst = None
ipdst_range = None
portsrc = None
portsrc_range = None
portdst = None
portdst_range = None
protocol = None
interfacein = None
interfaceout = None
target = None
custom_position = 0
direction = None

checker = False

############################### List of Predefined Rules #############################

def block_incoming_ssh():
    chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT")
    rule = iptc.Rule()
    rule.protocol = "tcp"
    match = rule.create_match("tcp")
    match.dport = "22"
    match = rule.create_match("state")
    match.state = "NEW"
    target = iptc.Target(rule, "DROP")
    rule.target = target
    chain.insert_rule(rule)
    print("Successfully Created")

def block_outgoing_ssh():
    chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "OUTPUT")
    rule = iptc.Rule()
    rule.protocol = "tcp"
    match = rule.create_match("tcp")
    match.dport = "22"
    match = rule.create_match("state")
    match.state = "NEW"
    target = iptc.Target(rule, "DROP")
    rule.target = target
    chain.insert_rule(rule)
    print("Successfully Created")

def block_all_ssh():
    chain1 = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT")
    chain2 = iptc.Chain(iptc.Table(iptc.Table.FILTER), "OUTPUT")
    rule = iptc.Rule()
    rule.protocol = "tcp"
    match = rule.create_match("tcp")
    match.dport = "22"
    match = rule.create_match("state")
    match.state = "NEW"
    target = iptc.Target(rule, "DROP")
    rule.target = target
    chain1.insert_rule(rule)
    chain2.insert_rule(rule)
    print("Successfully Created")

def block_incoming_http():
    chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT")
    rule = iptc.Rule()
    rule.protocol = "tcp"
    match = rule.create_match("tcp")
    match.dport = "80"
    match = rule.create_match("state")
    match.state = "NEW"
    target = iptc.Target(rule, "DROP")
    rule.target = target
    chain.insert_rule(rule)
    print("Successfully Created")

def block_incoming_https():
    chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT")
    rule = iptc.Rule()
    rule.protocol = "tcp"
    match = rule.create_match("tcp")
    match.dport = "443"
    match = rule.create_match("state")
    match.state = "NEW"
    target = iptc.Target(rule, "DROP")
    rule.target = target
    chain.insert_rule(rule)
    print("Successfully Created")

def block_incoming_ping():
    chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT")
    rule = iptc.Rule()
    rule.protocol = "icmp"
    match = rule.create_match("icmp")
    match.icmp_type = "echo-reply"
    target = iptc.Target(rule, "DROP")
    rule.target = target
    chain.insert_rule(rule)
    print("Successfully Created")

def block_invalid_packets():
    chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT")
    rule = iptc.Rule()
    match = rule.create_match("state")
    match.state = "iNVALID"
    target = iptc.Target(rule, "DROP")
    rule.target = target
    chain.insert_rule(rule)
    print("Successfully Created")

def syn_flooding():
    chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT")
    rule = iptc.Rule()
    rule.protocol = "tcp"
    match = rule.create_match("tcp")
    match.tcp_flags = [ 'FIN,SYN,RST,ACK', 'SYN' ]
    match = rule.create_match("limit")
    match.limit = "10/second"
    target = iptc.Target(rule, "ACCEPT")
    rule.target = target
    chain.insert_rule(rule)
    print("Successfully Created")

def block_xmas_attack():
    chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT")
    rule = iptc.Rule()
    rule.protocol = "tcp"
    match = rule.create_match("tcp")
    match.tcp_flags = [ 'ALL', 'ALL' ]
    target = iptc.Target(rule, "DROP")
    rule.target = target
    chain.insert_rule(rule)
    print("Successfully Created")

def force_syn_packets():
    chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT")
    rule = iptc.Rule()
    rule.protocol = "tcp"
    match = rule.create_match("tcp")
    match.syn = "!1"
    match = rule.create_match("state")
    match.state = "NEW"
    target = iptc.Target(rule, "DROP")
    rule.target = target
    chain.insert_rule(rule)
    print("Successfully Created")

# Function to delete rules

all_rules_deleted = True
def delete_rules(table):
    global all_rules_deleted
    all_rules_deleted = True
    for chain in table.chains:
        #print(chain.name)
        for rule in chain.rules:
            try:
                chain.delete_rule(rule)
                print(rule.protocol, rule.src, rule.dst, rule.target.name, "is DELETED")
            except:
                all_rules_deleted = False
    if(all_rules_deleted==False):
        #print("First Iteration Failed")
        delete_rules(table)

# Function to delete a single rule

def delete_rule(rule, table, direction = None):

    if(direction == 'input'):
        chain = iptc.Chain(table, "INPUT")
        deleted1 = False
        for index, rule in enumerate(chain.rules):
            if(int(rule_number) == index):
                try:
                    chain.delete_rule(rule)
                    print("Rule Successfully Deleted for Input")
                    deleted1 = True
                except:
                    sys.exit("The rule could not be deleted for Input. Please, try again.")
        if(deleted1 == False):
            print("The Rule Could Not Be Found for Input")

    elif (direction == 'output'):
        chain = iptc.Chain(table, "OUTPUT")
        deleted1 = False
        for index, rule in enumerate(chain.rules):
            if(int(rule_number) == index):
                try:
                    chain.delete_rule(rule)
                    print("Rule Successfully Deleted for Output")
                    deleted1 = True
                except:
                    sys.exit("The rule could not be deleted for Input. Please, try again.")
        if(deleted1 == False):
            print("The Rule Could Not Be Found for Output")

    else:
        sys.exit("Delete rule function error. Incorrect parameter")

# First check, for options that should be used alone

for index, value in enumerate(sys.argv):

    if(value == '-l' ):
        if (len(sys.argv)) != 2:
            sys.exit("The option -l does not accept additional options. Please, type: myFirewall -l")
        single_options = True
        table = iptc.Table(iptc.Table.FILTER)
        for chain in table.chains:
            #print ("Chain ",chain.name)
            rule_type = chain.name[:3]
            for index, rule in enumerate(chain.rules):
                dport = None
                sport = None
                ip_src_range = None
                ip_dst_range = None
                match_state = None
                match_tcp_flags = None
                for match in rule.matches:
                    if (match.dport != None):
                        dport = match.dport
                    if (match.sport != None):
                        sport = match.sport
                    if (match.src_range != None):
                        ip_src_range = match.src_range
                    if (match.dst_range != None):
                        ip_dst_range = match.dst_range
                    if (match.state != None):
                        match_state = match.state
                    if (match.tcp_flags != None):
                        match_tcp_flags = match.tcp_flags[match.tcp_flags.find(' ')+1:]
                if(ip_src_range != None):
                    source_ip = ip_src_range
                else:
                    source_ip = rule.src
                if(ip_dst_range != None):
                    destination_ip = ip_dst_range
                else:
                    destination_ip = rule.dst
                print ("==========================================")
                print ("RULE("+ rule_type+")", index, "||", "proto:", rule.protocol + " ||", "sport:", str(sport) + " ||",
                 "dport:", str(dport) + " ||", "src:", source_ip + " ||", "dst:", destination_ip + " ||\n", "|| inInt:",
                 str(rule.in_interface) + " ||", "outInt:", str(rule.out_interface) + " ||",
                 "tcpflags:", str(match_tcp_flags) + " ||", "state:", str(match_state) + " ||", "Target:", rule.target.name)
                print ("==========================================")

    elif(value == '-r'):
        if (len(sys.argv)) != 2:
            sys.exit("The option -r does not accept additional options. Please, type: myFirewall -r")
        single_options = True
        table1 = iptc.Table(iptc.Table.FILTER)
        delete_rules(table1)
        table2 = iptc.Table(iptc.Table.MANGLE)
        delete_rules(table2)
        table3 = iptc.Table(iptc.Table.NAT)
        delete_rules(table3)
        table4 = iptc.Table(iptc.Table.RAW)
        delete_rules(table4)
        table5 = iptc.Table(iptc.Table.SECURITY)
        delete_rules(table5)

    elif(value == '-d'):
        if (len(sys.argv) != 3 and len(sys.argv) != 4):
            sys.exit("The option -d does not accept these options. Please, type: myFirewall -d RuleNumer [-in|-out]")
        single_options = True
        table = iptc.Table(iptc.Table.FILTER)
        rule_number = sys.argv[2]
        if(len(sys.argv) == 4):
            if (sys.argv[3] == '-in'):
                delete_rule(rule_number, table, direction = 'input')
            elif (sys.argv[3] == '-out'):
                delete_rule(rule_number, table, direction = 'output')
            else:
                sys.exit("Incorrect parameter. Please, type: myFirewall -d RuleNumer [-in|-out]")
        else:
            delete_rule(rule_number, table, direction = 'input')
            delete_rule(rule_number, table, direction = 'output')
        #for chain in table.chains:
            #for rule in chain.rules:
            #    chain.delete_rule(rule)

    elif(value == '-all'):
        if ((len(sys.argv) != 3) and (sys.argv[index+1]!='ACCEPT') and (sys.argv[index+1]!='DROP')):
            sys.exit("The -all option lets the user to ACCEPT or DROP all packets, independently of ports,"+\
            " protocols or IPs. Please, specify a ACCEPT or DROP argument")
        else:
            single_options = True
            rule = iptc.Rule()
            rule.target = rule.create_target(sys.argv[index+1])
            chain1 = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT")
            chain2 = iptc.Chain(iptc.Table(iptc.Table.FILTER), "OUTPUT")
            chain1.insert_rule(rule)
            chain2.insert_rule(rule)

    elif(value == '-rule'):
        single_options = True
        if (len(sys.argv)) != 3:
            if (len(sys.argv) == 2):
                print("The list of rules available is:\n")
                for i in predesigned_rules:
                    print(i)
            else:
                sys.exit("The option -r does not accept additional options. Please, type: -rule RULE")
        elif(sys.argv[index+1] == 'BlockIncomingSSH'):
            block_incoming_ssh()
        elif(sys.argv[index+1] == 'BlockOutgoingSSH'):
            block_outgoing_ssh()
        elif(sys.argv[index+1] == 'BlockAllSSH'):
            block_all_ssh()
        elif(sys.argv[index+1] == 'BlockIncomingHTTP'):
            block_incoming_http()
        elif(sys.argv[index+1] == 'BlockIncomingHTTPS'):
            block_incoming_https()
        elif(sys.argv[index+1] == 'BlockIncomingPing'):
            block_incoming_ping()
        elif(sys.argv[index+1] == 'BlockInvalidPackets'):
            block_invalid_packets()
        elif(sys.argv[index+1] == 'BlockSYNFlooding'):
            syn_flooding()
        elif(sys.argv[index+1] == 'BlockXMASAttack'):
            block_xmas_attack()
        elif(sys.argv[index+1] == 'ForceSYNPackets'):
            force_syn_packets()
        else:
            print("Rule not available. The list of available rules is:\n")
            for i in predesigned_rules:
                print(i)
            print("")

if(not single_options):
    # Iterator to retrieve all information and create a Rule
    for index, value in enumerate(sys.argv):

        if(value == '-ipsrc'):
            match_single = re.search('^(([0-9]?[0-9]\.)|(1[0-9][0-9]\.)|(2[0-5][0-5]\.)){3}(([0-9]?[0-9])|(1[0-9][0-9])|(2[0-5][0-5]))$', sys.argv[index+1])
            match_range = re.search('^(([0-9]?[0-9]\.)|(1[0-9][0-9]\.)|(2[0-5][0-5]\.)){3}(([0-9]?[0-9])|(1[0-9][0-9])|(2[0-5][0-5]))-(([0-9]?[0-9]\.)|(1[0-9][0-9]\.)|(2[0-5][0-5]\.)){3}(([0-9]?[0-9])|(1[0-9][0-9])|(2[0-5][0-5]))$', sys.argv[index+1])
            if((match_single==None) and (match_range==None)):
                sys.exit("The IP address format is incorrect")
            else:
                checker = True
                if(match_single!=None):
                    ipsrc = sys.argv[index+1]
                if(match_range!=None):
                    ipsrc_range = sys.argv[index+1]

        elif(value == '-ipdst'):
            match_single = re.search('^(([0-9]?[0-9]\.)|(1[0-9][0-9]\.)|(2[0-5][0-5]\.)){3}(([0-9]?[0-9])|(1[0-9][0-9])|(2[0-5][0-5]))$', sys.argv[index+1])
            match_range = re.search('^(([0-9]?[0-9]\.)|(1[0-9][0-9]\.)|(2[0-5][0-5]\.)){3}(([0-9]?[0-9])|(1[0-9][0-9])|(2[0-5][0-5]))-(([0-9]?[0-9]\.)|(1[0-9][0-9]\.)|(2[0-5][0-5]\.)){3}(([0-9]?[0-9])|(1[0-9][0-9])|(2[0-5][0-5]))$', sys.argv[index+1])
            if(match_single==None and match_range==None):
                sys.exit("The IP address format is incorrect")
            else:
                checker = True
                if(match_single!=None):
                    ipdst = sys.argv[index+1]
                if(match_range!=None):
                    ipdst_range = sys.argv[index+1]

        elif(value == '-portsrc'):
            match_single = re.search('^[0-9]+$', sys.argv[index+1])
            match_range = re.search('^[0-9]+:[0-9]+$', sys.argv[index+1])
            if(match_single==None and match_range==None):
                sys.exit("The Port/Port range format is incorrect")
            checker = True
            if(match_single != None):
                if(int(sys.argv[index+1])<65536 and int(sys.argv[index+1])>0):
                    portsrc = sys.argv[index+1]
                else:
                    sys.exit("The specified port is out of the boundaries. Please, type a value between 1 and 65535")
            elif(match_range != None):
                first_port_group = int(sys.argv[index+1][:sys.argv[index+1].find(':')])
                second_port_group = int(sys.argv[index+1][sys.argv[index+1].find(':')+1:])
                if(((first_port_group<65536) and (first_port_group>0) and (second_port_group<65536) and (second_port_group>0))):
                    portsrc_range = sys.argv[index+1]
                else:
                    sys.exit("The specified port range is out of the boundaries. Please, type values between 1 and 65535")
            else:
                sys.exit("Port incorrectly parsed")

        elif(value == '-portdst'):
            match_single = re.search('^[0-9]+$', sys.argv[index+1])
            match_range = re.search('^[0-9]+:[0-9]+$', sys.argv[index+1])
            if(match_single==None and match_range==None):
                sys.exit("The Port/Port range format is incorrect")
            checker = True
            if(match_single != None):
                if(int(sys.argv[index+1])<65536 and int(sys.argv[index+1])>0):
                    portdst = sys.argv[index+1]
                else:
                    sys.exit("The specified port is out of the boundaries. Please, type a value between 1 and 65535")
            elif(match_range != None):
                first_port_group = int(sys.argv[index+1][:sys.argv[index+1].find(':')])
                second_port_group = int(sys.argv[index+1][sys.argv[index+1].find(':')+1:])
                if(((first_port_group<65536) and (first_port_group>0) and (second_port_group<65536) and (second_port_group>0))):
                    portdst_range = sys.argv[index+1]
                else:
                    sys.exit("The specified port range is out of the boundaries. Please, type values between 1 and 65535")
            else:
                sys.exit("Port incorrectly parsed")

        elif(value == '-proto'):
            accepted = False
            for i in accepted_protocols:
                if(i == sys.argv[index+1]):
                    accepted = True
                else:
                    protocol = sys.argv[index+1]
            if(not accepted):
                sys.exit("The protocol provided is not accepted. The list of accepted protocols is:",'ah',
                'egp','esp','gre','icmp','idp','igmp','ip','pim','pum','pup','raw','rsvp','sctp','tcp','tp','udp')
            checker = True

        elif(value == '-intin'):
            available_interface = False
            for i in socket.if_nameindex():
                if(i[1] == sys.argv[index+1]):
                    available_interface = True
            if(available_interface == False):
                sys.exit("The selected interface is not available on this system")
            else:
                interfacein = sys.argv[index+1]
            checker = True

        elif(value == '-intout'):
            available_interface = False
            for i in socket.if_nameindex():
                if(i[1] == sys.argv[index+1]):
                    available_interface = True
            if(available_interface == False):
                sys.exit("The selected interface is not available on this system")
            else:
                interfaceout = sys.argv[index+1]
            checker = True

        elif(value == '-pos'):
            match = re.search('^[0-9]*$', sys.argv[index+1])
            if(match==None):
                sys.exit("Incorrect position format. Please, type an integer >= 0")
            else:
                custom_position = sys.argv[index+1]
            checker = True

        elif(value == '-t'):
            if(sys.argv[index+1] == "ACCEPT"):
                target = "ACCEPT"
            elif(sys.argv[index+1] == "DROP"):
                target = "DROP"
            else:
                sys.exit('Incorrect target option. Please, choose between "ACCEPT" and "DROP"')
            checker = True

        elif(value == '-in'):
            direction = 'incoming'

        elif(value == '-out'):
            direction = 'outgoing'
        else:
            if(checker == True or index==0):
                checker = False
            else:
                sys.exit("Incorrect option: " + value)

    rule = iptc.Rule()

    if(ipsrc != None):
        rule.src = ipsrc

    if(ipsrc_range != None or ipdst_range != None):
        match = rule.create_match("iprange")
        if(ipsrc_range != None):
            match.src_range = ipsrc_range
        else:
            match.dst_range = ipdst_range

    if(ipdst != None):
        rule.dst = ipdst

    if(protocol != None):
        rule.protocol = protocol
        if(protocol == "tcp" or protocol == "udp"):
            match = rule.create_match(protocol)

    if(portsrc != None or portdst != None):
        if(protocol == None):
            protocol = "tcp"
            rule.protocol = protocol
            match = rule.create_match(protocol)
        if(portsrc != None):
            match.sport = portsrc
        if(portdst != None):
            match.dport = portdst

    if(portsrc_range != None or portdst_range != None):
        if(protocol == None):
            protocol = "tcp"
            rule.protocol = protocol
            match = rule.create_match(protocol)
        if(portsrc_range != None):
            match.sport = portsrc_range
        if(portdst_range != None):
            match.dport = portdst_range

    if(interfacein != None):
        rule.in_interface = interfacein

    if(interfaceout != None):
        rule.out_interface = interfaceout

    if(target != None):
        rule.target = rule.create_target(target)
    else:
        sys.exit('You must specify a target: -t "ACCEPT" or -t "DROP"')

    if(direction == None):
        chain1 = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT")
        chain2 = iptc.Chain(iptc.Table(iptc.Table.FILTER), "OUTPUT")
        try:
            chain1.insert_rule(rule, position=int(custom_position))
        except:
            sys.exit("Index of insertion out of boundaries for existing Input table. Please, choose a value between 0 and (Max.AmountOfRules-1)")
        try:
            chain2.insert_rule(rule, position=int(custom_position))
        except:
            sys.exit("Index of insertion out of boundaries for Output table. Please, choose a value between 0 and (Max.AmountOfRules-1)")

    elif(direction == "incoming"):
        chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT")
        try:
            chain.insert_rule(rule, position=int(custom_position))
        except:
            sys.exit("Index of insertion out of boundaries.  Please, choose a value between 0 and (Max.AmountOfRules-1)")

    elif(direction == "outgoing"):
        chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "OUTPUT")
        try:
            chain.insert_rule(rule, position=int(custom_position))
        except:
            sys.exit("Index of insertion out of boundaries. Please, choose a value between 0 and (Max.AmountOfRules-1)")


import src.fileIO as io
import src.chris as chris
import src.filepaths as fp
import src.analysis as anal
import src.plotting as plot

from pathlib import Path

def batch_calculate_peak_wavelength(parent_directory,
                                    batch_name,
                                    file_paths,
                                    directory_paths,
                                    plot_files):
    '''
    Calculate sample batch peak wavelength and error, from individual files
    within batch.
    Args:
        parent_directory: <string> parent directory identifier
        batch_name: <string> batch name string
        file_paths: <array> array of target file paths
        directory_paths: <dict> dictionary containing required paths
        plot_files: <string> "True" or "False" for plotting output
    Returns:
        results_dictionary: <dict>
            Batch Name
            File Names
            File Paths
            Secondary Strings
            Individual file values for:
                Background Files
                Region Trim Index: <array> min, max indices
                popt: <array> fano fit parameters:
                    peak, gamma, q, amplitude, damping
                pcov: <array> fano fit errors
                    peak, gamma, q, amplitude, damping
    '''
    batch_dictionary = fp.update_batch_dictionary(
        parent=parent_directory,
        batch_name=batch_name,
        file_paths=file_paths)
    for file in file_paths:
        wavelength, raw_intensity = io.read_GMR_file(file_path=file)
        sample_parameters = fp.sample_information(file_path=file)
        background_file, background_parameters = fp.find_background(
            background_path=directory_paths['Background Path'],
            sample_details=sample_parameters,
            file_string='.txt')
        print(background_file)
        if len(background_file) == 0:
            normalised_intensity = anal.normalise_intensity(
                raw_intensity=anal.timecorrected_intensity(
                    raw_intensity=raw_intensity,
                    integration_time=sample_parameters[
                        f'{parent_directory} Integration Time']))
        else:
            _, background_raw_intensity = io.read_GMR_file(
                file_path=background_file[0])
            background_parent = background_parameters['Parent Directory']
            normalised_intensity = anal.bg_normal_intensity(
                intensity=raw_intensity,
                background_intensity=background_raw_intensity,
                integration_time=sample_parameters[
                    f'{parent_directory} Integration Time'],
                background_integration_time=background_parameters[
                    f'{background_parent} Integration Time'])
        out_string = sample_parameters[f'{parent_directory} Secondary String']
        plot.spectrumplt(
            wavelength=wavelength,
            intensity=normalised_intensity,
            out_path=Path(f'{directory_paths["Results Path"]}/{batch_name}_{out_string}'))
        peak_results = chris.calc_peakwavelength(
            wavelength=wavelength,
            normalised_intensity=normalised_intensity,
            sample_details=sample_parameters,
            plot_figure=plot_files,
            out_path=Path(
                f'{directory_paths["Results Path"]}'
                f'/{batch_name}_{out_string}_Peak.png'))
        batch_dictionary.update(
            {f'{out_string} File': sample_parameters})
        batch_dictionary.update(
            {f'{out_string} Background': background_parameters})
        batch_dictionary.update(peak_results)
    return batch_dictionary

if __name__ == '__main__':

    ''' Organisation '''
    root = Path().absolute()
    info, directory_paths = fp.get_directory_paths(root_path=root)
    file_paths = fp.get_files_paths(
        directory_path=directory_paths['Spectrum Path'],
        file_string='.txt')
    parent, batches = fp.get_all_batches(file_paths=file_paths)

    ''' Batch Processing '''
    for batch, filepaths in batches.items():
        out_file = Path(
            f'{directory_paths["Results Path"]}'
            f'/{batch}_Peak.json')
        if out_file.is_file():
            pass
        else:
            results_dictionary = batch_calculate_peak_wavelength(
                parent_directory=parent,
                batch_name=batch,
                file_paths=filepaths,
                directory_paths=directory_paths,
                plot_files=info['Plot Files'])
            io.save_json_dicts(
                out_path=out_file,
                dictionary=results_dictionary)


# -*- coding: utf-8 -*-
"""
Ventricular tachycardia, ventricular bigeminy, Atrial fibrillation,
Atrial fibrillation, Ventricular trigeminy, Ventricular escape	,
Normal sinus rhythm, Sinus arrhythmia, Ventricular couplet
"""
import tkinter as tk
import scipy.io as sio
from PIL import Image, ImageTk
class App():
    ancho=760
    alto=760
    estado=False
    contadores=[0,0,0,0,0,0,0,0,0]#son los que van a contar el numero de dato que se ejecuta
    #se va a cosiacar las señales
    Signal=0

    def __init__(self):
        #cargar las variables .mat
        self.raiz=tk.Tk()
        self.importData()

        self.frame=tk.Frame(self.raiz,bg="white")
        self.frame.config(width=self.ancho,height=self.alto)
        self.frame.pack()

        self.titulo=tk.Label(self.frame,bg="white",text="Dispositivo Generador de Arritmias Cardiacas")
        self.titulo.config(font=("Grotesque",24))
        self.titulo.place(x=0,y=0,width=self.ancho,height=self.alto//16)

        self.opcion = tk.IntVar()

        names=["Taquicardia ventricualar","Bigeminismo Ventricular","Fibrilacion atrial","Flutter atrial","Trigeminismo Ventricular",
               "Escape Ventricular","Ritmo Sinusal","Arritmia Sinusal","Couplet Ventricular"]

        for i in range(1,10):
            tk.Radiobutton(self.frame, text=names[i-1],font=("Grotesque",16) ,variable=self.opcion,bg="white",anchor="w",
                       value=i, command=self.selec).place(x=50,y=self.alto//8+(i-1)*self.alto//20,
                                                              width=self.ancho//2.5,height=self.alto//32)

        temp=Image.open('LOGO_UMNG.png')
        temp=temp.resize((200, 250), Image.ANTIALIAS)
        self.imagen = ImageTk.PhotoImage(temp)

        tk.Label(self.raiz, image=self.imagen,bg="white").place(x=450,y=140)

        self.nombres=tk.Label(self.frame,bg="white",text="Juan Camilo Sandoval Cabrera\nNohora Camila Sarmiento Palma",anchor="e")
        self.nombres.config(font=("Grotesque",12))
        self.nombres.place(x=420,y=420,width=self.ancho//3,height=self.alto//16)

        tk.Button(self.frame, text="Iniciar",font=("Grotesque",16),command=self.Estado_DataON).place(x=270,y=600)
        tk.Button(self.frame, text="Pausar",font=("Grotesque",16),command=self.Estado_DataOFF).place(x=400,y=600)

        self.titulo.after(700,self.Enviar_Data)

    def Estado_DataON(self):
        self.estado=True

    def Estado_DataOFF(self):
        self.estado=False

    def Enviar_Data(self):
        delay=3
        op=self.opcion.get()
        c=op-1
        if self.estado:
            print(self.Signal[0,self.contadores[c]])
            self.contadores[c]+=1
            if c==7:
                delay=4

        self.titulo.after(delay,self.Enviar_Data)

    def selec(self):
        op=self.opcion.get()#el lunes hacer el selector
        if op==1:
            self.Signal=self.VT #variables de las señales
        elif op==2:
            self.Signal=self.VB #variables de las señales
        elif op==3:
            self.Signal=self.AFIB #variables de las señales
        elif op==4:
            self.Signal=self.AFL #variables de las señales
        elif op==5:
            self.Signal=self.VTRI #variables de las señales
        elif op==6:
            self.Signal=self.VES #variables de las señales
        elif op==7:
            self.Signal=self.S #variables de las señales
        elif op==8:
            self.Signal=self.SARR #variables de las señales
        elif op==9:
            self.Signal=self.VCOUP #variables de las señales

    def iniciar(self):
        self.raiz.mainloop()

    def importData(self):
        AFIB=sio.loadmat('AFIB.mat')
        self.AFIB=AFIB['SignalNorm']

        AFL=sio.loadmat('AFL.mat')
        self.AFL=AFL['SignalNorm']

        S=sio.loadmat('S.mat')
        self.S=S['SignalNorm']

        VES=sio.loadmat('VS.mat')
        self.VES=VES['SignalNorm']

        VCOUP=sio.loadmat('VCop.mat')
        self.VCOUP=VCOUP['SignalNorm']

        VT=sio.loadmat('TV.mat')
        self.VT=VT['SignalNorm']

        SARR=sio.loadmat('SARR.mat')
        self.SARR=SARR['SignalNorm']

        VB=sio.loadmat('VB.mat')
        self.VB=VB['SignalNorm']

        #VT=sio.loadmat('VT.mat')#SE PERDIO
        #self.VT=VT['SignalNorm']

        VTRI=sio.loadmat('VTRI.mat')
        self.VTRI=VTRI['SignalNorm']

def main():
    mi_app = App()
    mi_app.iniciar()

if __name__ == '__main__':
    main()


# 给你一个字符串 s 和一个整数 k 。你可以选择字符串中的任一字符，并将其更改为任何其他大写英文字符。该操作最多可执行 k 次。

# 在执行上述操作后，返回包含相同字母的最长子字符串的长度。

class Solution(object):
    def characterReplacement(self, s, k):
        """
        :type s: str
        :type k: int
        :rtype: int
        """
        num = [0] * 26
        left = right = maxn = 0
        n = len(s)

        while(right < n):
            num[ord(s[right]) - ord('A')] += 1
            maxn = max(maxn, num[ord(s[right]) - ord('A')])

            if right - left + 1 - maxn > k:
                num[ord(s[left]) - ord('A')] -= 1
                left += 1
            right += 1

        return right - left

s = "ABAB"
k = 2

a = Solution()
print(a.characterReplacement(s, k))


from flaskr.db import get_db

no_of_existing_accounts = 3

def test_create_account(client, app):

    expected_account = {
        "account_number": "4",
        "account_name": "Brukskonto",
        "account_nickname": "Min Brukskonto",
        "account_owner_name": "Ola Nordmann",
        "account_type": "DEPOSIT",
        "currency": "NOK",
        "available_balance": "0",
        "booked_balance": "0",
        "status": "open"
    }

    input_data = {
        "account_name": "Brukskonto",
        "account_nickname": "Min Brukskonto",
        "account_owner_name": "Ola Nordmann",
        "account_type": "DEPOSIT",
        "currency": "NOK"
    }
    url = '/v1/accounts'

    assert client.get(url).status_code == 200
    response = client.post(url, json=input_data)
    assert response.status_code == 201  # Created

    # Check that another account has been added to the database
    with app.app_context():
        db = get_db()
        count = db.execute('SELECT COUNT(id) FROM account').fetchone()[0]
        assert count == no_of_existing_accounts + 1

    assert response.json == expected_account

def test_get_accounts(client):

    expected_result = {
        "accounts": [
            {
                "account_number": "1",
                "account_name": "Brukskonto",
                "account_nickname": "Min Brukskonto",
                "account_owner_name": "Ola Nordmann",
                "account_type": "DEPOSIT",
                "currency": "NOK",
                "available_balance": "10000",
                "booked_balance": "8000",
                "status": "open"
            },
            {
                "account_number": "2",
                "account_name": "Sparekonto",
                "account_nickname": "Min Sparekonto",
                "account_owner_name": "Ola Nordmann",
                "account_type": "SAVING",
                "currency": "NOK",
                "available_balance": "50000",
                "booked_balance": "50000",
                "status": "open"
            },
            {
                "account_number": "3",
                "account_name": "Valutakonto",
                "account_nickname": "Min Valutakonto",
                "account_owner_name": "Ola Nordmann",
                "account_type": "CURRENCY",
                "currency": "USD",
                "available_balance": "5000",
                "booked_balance": "5000",
                "status": "open"
            }
        ]
    }
    url = '/v1/accounts'

    response = client.get(url)
    assert response.status_code == 200  # OK
    assert response.json == expected_result

def test_get_wrong_url(client):

    bad_url = '/not_exists'
    assert client.get(bad_url).status_code == 404  # Not found

def test_post_wrong_url(client):

    bad_url = '/not_exists'

    input_data = {
        "account_name": "Brukskonto",
        "account_nickname": "Min Brukskonto",
        "account_owner_name": "Ola Nordmann",
        "account_type": "DEPOSIT",
        "currency": "NOK"
    }
    response = client.post(bad_url, json=input_data)
    assert response.status_code == 404  # Not found

def test_create_account_missing_data(client, app):

    input_data = {
        "nothing_useful": "blah"
    }
    url = '/v1/accounts'

    assert client.get(url).status_code == 200
    response = client.post(url, json=input_data)
    assert response.status_code == 400  # Bad request

    # Check no incomplete accounts have been added to the db
    with app.app_context():
        db = get_db()
        count = db.execute('SELECT COUNT(id) FROM account').fetchone()[0]
        assert count == no_of_existing_accounts

    # Check attempting to insert bad data doesn't break get
    assert client.get(url).status_code == 200

def test_create_account_invalid_account_type(client, app):

    input_data = {
        "account_name": "Brukskonto",
        "account_nickname": "Min Brukskonto",
        "account_owner_name": "Ola Nordmann",
        "account_type": "NOT_EXISTS",
        "currency": "NOK"
    }
    url = '/v1/accounts'

    assert client.get(url).status_code == 200
    response = client.post(url, json=input_data)
    assert response.status_code == 400  # Bad request
    assert response.data == b'Account type NOT_EXISTS is not valid'

    # Check no incomplete accounts have been added to the db
    with app.app_context():
        db = get_db()
        count = db.execute('SELECT COUNT(id) FROM account').fetchone()[0]
        assert count == no_of_existing_accounts

    # Check attempting to insert bad data doesn't break get
    assert client.get(url).status_code == 200


class animal:
	leg=4
	@staticmethod
	def sum(x,y):
		sum=x+y
		print(sum)
	@staticmethod
	def mul(x,y):
		mul=x*y
		print(mul)
	@classmethod
	def walk(cls,name):
		print(f"{name} has {animal.leg} leg")
	@classmethod
	def evenodd(cls,num):
		if num%2==0:
			print(f"{num} is even number")
		else:
			print("f{num} is odd number")

t1=animal()
t1.sum(10,30)
animal.mul(10,50)
t1.walk("dog")
animal.evenodd(10)


import numpy as np
import pandas as pd
import operator
from sklearn import preprocessing

data = pd.read_csv("data.csv",header=None)

min_max_scaler = preprocessing.MinMaxScaler(feature_range=(0,1))

def classify(v,k,distance):
  target_values = data.iloc[:,-1]
  nearest_neighbors = knn(data,k,v,distance)
  classification_values = {}

  for index in nearest_neighbors:
    if target_values[index] not in classification_values.keys():
      classification_values[target_values[index]] = 1
    else:
      classification_values[target_values[index]] += 1

  return max(classification_values.items(),key=operator.itemgetter(1))[0]

def knn(vectors,k,vector_to_classify,distance):
  distances = []
  for i in range(0,len(vectors)):
    x = vectors.loc[i,:]
    x = x[0:len(x)-1]
    x = min_max_scaler.fit_transform(x.values.astype(float).reshape(-1,1))[:,0]

    distances.append({"index": i,
                      "value": distance(x,vector_to_classify)})

  distances = sorted(distances,key=lambda x:x['value'], reverse=True)
  indexes = list(map(lambda distance: distance['index'],distances[0:k]))
  return indexes

def euclidean_distance(x,y):
  summation = 0
  for i in range(0,x.size):
    summation += ((x[i] - y[i])**2)

  return (summation)**(1/2)

def manhattan_distance(x,y):
  summation = 0
  for i in range(0,x.size):
    summation += abs(x[i]-y[i])
  return summation

def maximum_metric(x,y):
  max_distance = 0
  for i in range(0,x.size):
    difference = abs(x[i]-y[i])
    if(difference > max_distance):
      max_distance = difference
  return max_distance

vectors_to_classify = [np.array([1100000,60,1,2,1,500]),
                       np.array([1100000,60,1,2,1,500]),
                       np.array([1800000,65,1,2,1,1000]),
                       np.array([2300000,72,1,3,1,1400]),
                       np.array([3900000,110,2,3,1,1800])]

distances = [{'name':'Euclidean Distance','function':euclidean_distance},
             {'name':'Manhattan Distance','function':manhattan_distance},
             {'name':'Maximum Metric','function':maximum_metric}]

for distance in distances:
  print("Distance " + str(distance['name']))
  for k in [1,3,5]:
    print("K = " + str(k))
    for v in vectors_to_classify:
      v = min_max_scaler.fit_transform(v.astype(float).reshape(-1,1))[:,0]
      print(classify(v,k,distance['function']))


from ksz.src import plot
import matplotlib.pyplot as plt

data_path_list = [
        '/data/ycli/dr12/galaxy_DR12v5_LOWZ_North_TOT_wMASS.dat',
        '/data/ycli/dr12/galaxy_DR12v5_LOWZ_South_TOT_wMASS.dat',
        '/data/ycli/dr12/galaxy_DR12v5_CMASS_North_TOT_wMASS.dat',
        '/data/ycli/dr12/galaxy_DR12v5_CMASS_South_TOT_wMASS.dat',
        #'/data/ycli/6df/6dFGS_2MASS_RA_DEC_Z_J_K_bJ_rF_GOOD.cat',
        #'/data/ycli/group_catalog/6dFGS_M_group.dat',
        #'/data/ycli/group_catalog/6dFGS_L_group.dat',
        '/data/ycli/group_catalog/SDSS_M_group.dat',
        #'/data/ycli/group_catalog/SDSS_L_group.dat',
        '/data/ycli/cgc/CGC_wMASS.dat',
        ]
label_list = [
        'LOWZ North CGC',
        'LOWZ South CGC',
        'CMASS North',
        'CMASS South',
        #'6dF',
        #'6dF mass-weighted halo center',
        #'6dF luminosity-weighted halo center',
        'DR13 Group',
        #'dr13 luminosity-weighted halo center',
        'DR7 CGC',
        ]
ap_list = [
        7.,
        7.,
        #0.,
        #0.,
        8.,
        #11.,
        11.,
        #11.,
        7.,
        #7.,
        ]
#plot.plot_stellarmass_hist(data_path_list, label_list)

plot.plot_halomass_hist(data_path_list, label_list)
#plot.plot_rvir_hist(data_path_list, label_list, rho_crit = 2.775e11, ap_list=ap_list)

#plot.plot_z_hist(data_path_list, label_list)

plt.show()


from __future__ import annotations
import json
import subprocess
import collections
import concurrent.futures
from os import path, system
from datetime import datetime

root_path = path.abspath("src/test_cases/UI")
report_path = path.abspath("src/reports/concurrent_test_logs")

def generate_pytest_commands():
    config_run_test_dir = path.dirname(__file__)
    with open(path.join(config_run_test_dir, "config_run_multiple_test.json")) as f:
        config_data = json.load(f)
        list_test_suite = config_data['test_suite']
        pytest_run_cmds = []
        for suite in list_test_suite:
            test_name = suite['test']['name'].replace(".", "::")
            browser_name = suite['test']['browser']
            test_suite_option = f"{suite['name']}::{test_name}"
            options_cmd = collections.namedtuple('OptionCmd', ['test_name', 'browser'])
            pytest_run_cmds.append(options_cmd(test_suite_option, browser_name))
        return pytest_run_cmds

def execute_pytest_cmd(option_cmd):
    run_cmd_process = subprocess.run(["pytest", f"{root_path}\\{option_cmd.test_name}",
                                      f"--browser={option_cmd.browser}"],
                                     capture_output=True)
    return run_cmd_process.stdout

list_options_cmd = generate_pytest_commands()

with concurrent.futures.ThreadPoolExecutor(max_workers=len(list_options_cmd)) as executor:
    running_cmd = {executor.submit(execute_pytest_cmd, options): options for options in list_options_cmd}
    for completed_cmd in concurrent.futures.as_completed(running_cmd):
        test_ran = running_cmd[completed_cmd].test_name.split("::")[-1]
        browser_ran = running_cmd[completed_cmd].browser
        try:
            time_logging = datetime.now().strftime("%Y.%m.%d_(%H-%M-%S.%f)")
            with open(f"{report_path}\\Result_{test_ran}_{time_logging}.log", "wb") as f:
                f.write(completed_cmd.result())
        except Exception as exc:
            print(f"Pytest ran with error {exc}.")


import ROOT
#from root_numpy import root2array, root2rec, tree2rec
import pylab,numpy,pickle
import matplotlib

pylab.rcParams['font.size'] = 14.0
pylab.rcParams['axes.labelsize']=18.0
pylab.rcParams['axes.titlesize']=20.0
pylab.rcParams['ytick.labelsize']='large'
pylab.rcParams['xtick.labelsize']='large'
pylab.rcParams['lines.markeredgewidth']=1.0
pylab.rc ('text', usetex=True)
pylab.rc ('font', family='serif')
pylab.rc ('font', serif='Computer Modern Roman')

log_sigma_days = numpy.array([-5,-4,-3,-2,-1,-0.52287874528033762,0,1])

### NEW GENIE 1460 Included ###
dec0_e3_foldedspectrum = (1072.916206382002,0)
dec16_e3_foldedspectrum = (1545.0315486757047,0)
dec30_e3_foldedspectrum = (1803.4879220886971,0)
dec45_e3_foldedspectrum = (1955.9670994116407,0)
dec60_e3_foldedspectrum = (2117.1599069802728,0)
dec75_e3_foldedspectrum = (2228.3197855702933,0)
sa_avg_foldedspectrum = (1654.0807981564465,0)

sys_adjustment = 0.89559693491089454

### Int(EffaE-3)  (JF,RH)###
#samp2_e3_foldedspectrum_sum = (1759.219287256351,0) ## 100 GeV flux equal to 1.0 GeV^-1 cm^-2 s^-1
#samp2_e35_foldedspectrum_sum = (2925.5560058208703,0) ##
#samp2_e25_foldedspectrum_sum = (1320.5883336274608,0) ##

sens_e3_dec0_meansrc_events = numpy.array([6.4656,6.70643,6.7344,7.38432,10.4106,13.2816,16.2928,28.1549])
sens_e3_dec16_meansrc_events = numpy.array([6.4384,6.62176,6.79315,7.4096,10.5558,13.0896,16.5709,30.3184])
sens_e3_dec30_meansrc_events = numpy.array([7.632,7.32,7.54048,8.00864,10.68,12.6272,16.0406,27.1056])
sens_e3_dec45_meansrc_events = numpy.array([6.86976,6.87104,7.09792,8.60768,11.3456,12.983,16.1408,27.0288])
sens_e3_dec60_meansrc_events = numpy.array([6.77216,6.54144,7.29088,8.584,11.0262,13.2019,15.5658,24.368])
sens_e3_dec75_meansrc_events = numpy.array([5.6608,5.64512,5.95296,7.37824,10.8947,12.7984,15.9766,28.8221])

ul_e3_dec0_meansrc_events = numpy.array([7.5456,8.09952,9.06432,11.376,17.5674,22.2304,29.9581,60.232])
ul_e3_dec16_meansrc_events = numpy.array([7.77754,8.51104,9.67872,11.8336,18.1984,23.208,30.528,64.568])
ul_e3_dec30_meansrc_events = numpy.array([8.95392,9.34349,10.2138,12.5501,18.1462,22.568,29.6342,59.744])
ul_e3_dec45_meansrc_events = numpy.array([8.45888,8.73325,9.74496,12.8112,19.0477,22.5107,29.5024,59.3357])
ul_e3_dec60_meansrc_events = numpy.array([8.17261,8.74912,10.1846,13.3968,19.3747,23.0784,30.0032,57.7504])
ul_e3_dec75_meansrc_events = numpy.array([7.30272,7.66144,8.52512,11.688,19.0272,24.0032,31.9216,64.608])

ilow_en_bins = pickle.load(open("./pickles/effarea_low_energy_bins.pkl",'r'))
high_en_bins = pickle.load(open("./pickles/effarea_high_energy_bins.pkl",'r'))

genie_avg_area = pickle.load(open("./pickles/g1460_numu_effarea_avg.pkl",'r'))
genie_dec0_area = pickle.load(open("./pickles/g1460_numu_effarea_dec0.pkl",'r'))
genie_dec16_area = pickle.load(open("./pickles/g1460_numu_effarea_dec16.pkl",'r'))
genie_dec30_area = pickle.load(open("./pickles/g1460_numu_effarea_dec30.pkl",'r'))
genie_dec45_area = pickle.load(open("./pickles/g1460_numu_effarea_dec45.pkl",'r'))
genie_dec60_area = pickle.load(open("./pickles/g1460_numu_effarea_dec60.pkl",'r'))
genie_dec75_area = pickle.load(open("./pickles/g1460_numu_effarea_dec75.pkl",'r'))

nugen_avg_area = pickle.load(open("./pickles/g1460_nugmu_effarea_avg.pkl",'r'))
nugen_dec0_area = pickle.load(open("./pickles/g1460_nugmu_effarea_dec0.pkl",'r'))
nugen_dec16_area = pickle.load(open("./pickles/g1460_nugmu_effarea_dec16.pkl",'r'))
nugen_dec30_area = pickle.load(open("./pickles/g1460_nugmu_effarea_dec30.pkl",'r'))
nugen_dec45_area = pickle.load(open("./pickles/g1460_nugmu_effarea_dec45.pkl",'r'))
nugen_dec60_area = pickle.load(open("./pickles/g1460_nugmu_effarea_dec60.pkl",'r'))
nugen_dec75_area = pickle.load(open("./pickles/g1460_nugmu_effarea_dec75.pkl",'r'))

sa0 = 2*numpy.pi*((1-numpy.cos(numpy.deg2rad(95.))) - (1-numpy.cos(numpy.deg2rad(80.))))
sa16 = 2*numpy.pi*((1-numpy.cos(numpy.deg2rad(80.))) - (1-numpy.cos(numpy.deg2rad(65.))))
sa30 = 2*numpy.pi*((1-numpy.cos(numpy.deg2rad(65.))) - (1-numpy.cos(numpy.deg2rad(50.))))
sa45 = 2*numpy.pi*((1-numpy.cos(numpy.deg2rad(50.))) - (1-numpy.cos(numpy.deg2rad(35.))))
sa60 = 2*numpy.pi*((1-numpy.cos(numpy.deg2rad(35.))) - (1-numpy.cos(numpy.deg2rad(20.))))
sa75 = 2*numpy.pi*(1-numpy.cos(numpy.deg2rad(20.)))
saTotal = 2*numpy.pi*(1-numpy.cos(numpy.deg2rad(95.)))

sky_frac = [0.23989563791056959, 0.22901050354066707, 0.20251868181221927, 0.16222554659621455, 0.11087700847006936, 0.055472621670260208]

fluxnorm_dec16_e3 = ul_e3_dec16_meansrc_events/dec16_e3_foldedspectrum[0]
fluxnorm_dec0_e3 = ul_e3_dec0_meansrc_events/dec0_e3_foldedspectrum[0]
fluxnorm_dec30_e3 = ul_e3_dec30_meansrc_events/dec30_e3_foldedspectrum[0]
fluxnorm_dec45_e3 = ul_e3_dec45_meansrc_events/dec45_e3_foldedspectrum[0]
fluxnorm_dec60_e3 = ul_e3_dec60_meansrc_events/dec60_e3_foldedspectrum[0]
fluxnorm_dec75_e3 = ul_e3_dec75_meansrc_events/dec75_e3_foldedspectrum[0]

uls = [ul_e3_dec0_meansrc_events,ul_e3_dec16_meansrc_events,ul_e3_dec30_meansrc_events,ul_e3_dec45_meansrc_events,ul_e3_dec60_meansrc_events,ul_e3_dec75_meansrc_events]
event_ul_avg_list = [uls[i]*sky_frac[i] for i in range(len(sky_frac))]

event_ul_avg = numpy.array([0.,0.,0.,0.,0.,0.,0.,0.])
for listy in event_ul_avg_list:
        event_ul_avg+=listy

fluxnorm_sa_avg_e3 = event_ul_avg / sa_avg_foldedspectrum[0]

#fluxnorm_0 = sens_bdt0_e3_meansrc_events/samp2_e3_foldedspectrum_sum[0]
#fluxnorm_0_disco = disco_bdt0_e3_meansrc_events/samp2_e3_foldedspectrum_sum[0]

#fluxnorm_0_25 = sens_bdt0_e25_meansrc_events/samp2_e25_foldedspectrum_sum[0]
#fluxnorm_0_35 = sens_bdt0_e35_meansrc_events/samp2_e35_foldedspectrum_sum[0]

pylab.figure()
pylab.plot(log_sigma_days,event_ul_avg,'k-',lw=2,label="Averaged")
pylab.plot(log_sigma_days,ul_e3_dec0_meansrc_events,'k--',lw=2,label=r"$\delta=0^{\circ}$")
pylab.plot(log_sigma_days,ul_e3_dec30_meansrc_events,'k-.',lw=2,label=r"$\delta=30^{\circ}$")
pylab.plot(log_sigma_days,ul_e3_dec60_meansrc_events,'k:',lw=2,label=r"$\delta=60^{\circ}$")
pylab.xlabel(r'$Log_{10}(\sigma_{\omega})\quad (Days)$')
pylab.ylabel("NSrc Events")
pylab.axis([-5,1,3,60])
pylab.grid()
pylab.legend(loc="upper left")
matplotlib.pyplot.gcf().subplots_adjust(right=.85)
pylab.title(r"Upper Limit $E^{-3}$ 90% C.L.")
pylab.savefig("LowEnTransient_NEventUpperLimit_E3_G1460_MultiDec")

fig1=pylab.figure()
pylab.plot(log_sigma_days,event_ul_avg,'k-',lw=2)
#pylab.plot(0.77011529478710161,13.5279,"w*",ms=20.0,label="Most Significant Flare")
#pylab.plot(log_sigma_days,disco_bdt0_e3_meansrc_events,'k-',lw=2,label="Discovery Potential")
pylab.xlabel(r'$Log_{10}(\sigma_{\omega})\quad$ (Days)')
pylab.ylabel("NSrc Events")
pylab.axis([-5,1,0,62])
pylab.grid()
pylab.legend(loc="upper left")
matplotlib.pyplot.gcf().subplots_adjust(right=.85)
pylab.title(r"Upper Limit $E^{-3}$ 90$\%$ C.L.")
pylab.savefig("LowEnTransient_NEventUpperLimit_E3_G1460_Avg.pdf")

figgy=pylab.figure()
ax = figgy.add_subplot(111)
pylab.plot(log_sigma_days,fluxnorm_sa_avg_e3,'k-',lw=2,label=r"$E^{-3.0}$")
pylab.xlabel(r'$Log_{10}(\sigma_{\omega})\quad$ (Days)')
pylab.ylabel(r"$\frac{dN}{dE}$ @ 100 GeV ($10^{-2}$GeV$^{-1}$ cm$^{-2}$)")
pylab.axis([-5,1,0.00,0.037483054073961818])
pylab.yticks([0.0060456538828970677,0.012091307765794135,0.018136961648691202,0.024182615531588271,0.030228269414485337,0.036273923297382403],["0.6","1.21","1.81","2.42","3.02","3.63"])
ax.yaxis.tick_right()
ax.yaxis.set_label_position("right")
matplotlib.pyplot.gcf().subplots_adjust(right=.85)
pylab.grid()
#pylab.legend(loc="upper left")
pylab.title(r"Time-Integrated Flux Upper Limit $E^{-3}$")
pylab.savefig("LowEnTransient_FluxUpperLimit_E3_G1460_Avg.pdf")

figgy=pylab.figure()
ax = figgy.add_subplot(111)
pylab.plot(log_sigma_days,event_ul_avg,'k-',lw=2,label=r"$E^{-3.0}$")
pylab.xlabel(r'$Log_{10}(\sigma_{\omega})\quad$ (Days)')
pylab.ylabel("NSrc Events")
pylab.axis([-5,1,0.00,62])
pylab.yticks([  0.,  10.,  20.,  30.,  40.,  50.,  60.])
pylab.grid()
ax2 = ax.twinx()
ax2.set_ylim(0,0.037483054073961818)
ax2.set_xlim(-5,1)
ax2.set_yticks([0.0060456538828970677,0.012091307765794135,0.018136961648691202,0.024182615531588271,0.030228269414485337,0.036273923297382403])
ax2.set_yticklabels(["0.6","1.21","1.81","2.42","3.02","3.63"])
ax2.set_ylabel(r"$\frac{dN}{dE}$ @ 100 GeV ($10^{-2}$GeV$^{-1}$ cm$^{-2}$)")
matplotlib.pyplot.gcf().subplots_adjust(right=.85)
#pylab.legend(loc="upper left")
pylab.title(r"Time-Integrated Flux Upper Limit $E^{-3}$")
pylab.savefig("LowEnTransient_FluxUpperLimit_E3_G1460_Avg_DoubleY.pdf")

figgy=pylab.figure()
ax = figgy.add_subplot(111)
pylab.plot(log_sigma_days,fluxnorm_dec0_e3,'k--',lw=2,label=r"$\delta = 0^{\circ}$")
pylab.plot(log_sigma_days,fluxnorm_dec16_e3,'k-',lw=2,label=r"$\delta = 16^{\circ}$")
pylab.plot(log_sigma_days,fluxnorm_dec30_e3,'k-.',lw=2,label=r"$\delta = 30^{\circ}$")
pylab.plot(log_sigma_days,fluxnorm_dec60_e3,'k:',lw=2,label=r"$\delta = 60^{\circ}$")
pylab.xlabel(r'$Log_{10}(\sigma_{\omega})\quad$ (Days)')
pylab.ylabel(r"$\frac{dN}{dE}$ @ 100 GeV ($10^{-2}$GeV$^{-1}$ cm$^{-2}$)")
pylab.axis([-5,1,0.00,0.058])
pylab.yticks([0.00 ,  0.00828571,  0.01657143,  0.02485714,  0.03314286, 0.04142857, 0.04971429, 0.058],["0.0","0.83","1.7","2.5","3.3","4.1","5.0","5.8"])
ax.yaxis.tick_right()
ax.yaxis.set_label_position("right")
matplotlib.pyplot.gcf().subplots_adjust(right=.85)
pylab.grid()
pylab.legend(loc="upper left")
pylab.title(r"Time-Integrated Flux Upper Limit $E^{-3}$")
pylab.savefig("LowEnTransient_FluxUpperLimit_E3_G1460_MultiDec.pdf")

'''
pylab.figure(figsize=(10,8))
pylab.plot(log_sigma_days,fluxnorm_0,'b-',lw=2,label='Sensitivity (90% C.L.)')
pylab.xlabel(r'$Log_{10}(\sigma_{\omega})\quad (Days)$')
pylab.ylabel(r"$\frac{dN}{dE}$ [$GeV^{-1} cm^{-2} s^{-1}$] @ 100 GeV Pivot Energy")
#pylab.axis([-5,1,5e3,5e4])
pylab.yticks([0.001,0.005,0.01,0.015,0.02,0.025],["$1e-3$","$5.0e-3$","$1.0e-2$","1.5e-2","2.0e-2","2.5e-2"])
pylab.grid()
pylab.legend(loc="upper left")
pylab.title(r"Flux Sensitivity (MergedSim) $E^{-3}$")
pylab.savefig("LowEnTransient_FluenceSensitivity_E3_MergedSim_FinalCut")

pylab.figure(figsize=(10,8))
pylab.plot(log_sigma_days,fluxnorm_0,'b-',lw=2,label='Sensitivity (90% C.L.)')
pylab.plot(log_sigma_days,fluxnorm_0_disco,'k-',lw=2,label='Discovery Potential')
pylab.xlabel(r'$Log_{10}(\sigma_{\omega})\quad (Days)$')
pylab.ylabel(r"$\frac{dN}{dE}$ [$GeV^{-1} cm^{-2} s^{-1}$] @ 100 GeV Pivot Energy")
#pylab.axis([-5,1,5e3,5e4])
pylab.yticks([0.001,0.005,0.01,0.015,0.02,0.025],["$1e-3$","$5.0e-3$","$1.0e-2$","1.5e-2","2.0e-2","2.5e-2"])
pylab.grid()
pylab.legend(loc="upper left")
pylab.title(r"Flux Sensitivity (MergedSim) $E^{-3}$")
pylab.savefig("LowEnTransient_FluenceSensitivityAndDisco_E3_MergedSim_FinalCut")

pylab.figure(figsize=(10,8))
pylab.plot(log_sigma_days,merged_samp1_e2_meansrc_events,'g-',lw=2,label='Sample 1')
pylab.plot(log_sigma_days,merged_samp2_e2_meansrc_events,'b-',lw=2,label='Sample 2')
pylab.xlabel(r'$Log_{10}(\sigma_{\omega})\quad (Days)$')
pylab.ylabel("NSrc Events")
pylab.axis([-6,1,3,15])
pylab.grid()
pylab.title("Sensitivity (MergedSim)")
pylab.legend(loc='upper left')
pylab.savefig("LowEnTransient_DiscoPotential_E2_MergedSim_SampleComparison")

pylab.figure(figsize=(10,8))
pylab.plot(log_sigma_days,nugen_samp1_e2_meansrc_events,'g--',lw=2,label='Sample 1 (Nugen)')
pylab.plot(log_sigma_days,nugen_samp2_e2_meansrc_events,'b--',lw=2,label='Sample 2 (Nugen)')
pylab.plot(log_sigma_days,merged_samp1_e2_meansrc_events,'g-',lw=2,label='Sample 1 (MergedSim)')
pylab.plot(log_sigma_days,merged_samp2_e2_meansrc_events,'b-',lw=2,label='Sample 2 (MergedSim)')
pylab.xlabel(r'$Log_{10}(\sigma_{\omega})\quad (Days)$')
pylab.ylabel("NSrc Events")
pylab.axis([-6,1,3,15])
pylab.grid()
pylab.title("Sensitivity")
pylab.legend(loc='upper left')
pylab.savefig("LowEnTransient_DiscoPotential_E2_NugenANDMerged_SampleComparison")
'''


from netpyne import specs

def set_netParams(Nin, Pops, Exc_ThtoAll, Exc_AlltoAll, Inh_AlltoAll):
    netParams = specs.NetParams()  # object of class NetParams to store the network parameters

    netParams.defaultThreshold = 0.0

    ## Cell parameters/rules
    GenericCell = {'secs': {}}
    GenericCell['secs']['soma'] = {'geom': {}, 'pointps': {}}                  # soma params dict
    GenericCell['secs']['soma']['geom'] = {'diam': 6.366, 'L': 5.0, 'cm': 1.0} # Area of 100 um2 --> point process current in [mA/cm2]
    GenericCell['secs']['soma']['pointps']['Izhi'] = {                         # soma Izhikevich properties
                                                      'mod': 'Izhi2007b_dyn_thr',
                                                      'C': 1,
                                                      'k': 0.04,
                                                      'vpeak': 10.0,
                                                      'celltype': 1}
    netParams.cellParams['IzhiCell'] = GenericCell

    # Population parameters - First, we define thalamic cells, then cortical. This impacts on individual gIDs read from Matlab connections
    # Population corresponding to thalamic cells
    netParams.popParams['artificial'] = {'cellModel': 'VecStim', 'numCells': Nin, 'spkTimes': [1]*Nin, 'xRange': [-0.01,0.01],'yRange': [0,0.01],'zRange': [-0.01,0.01]}

    # Populations in cortex
    for ntype in range(len(Pops)):
        name = Pops[str(ntype+1)]['Label'] + '-' + Pops[str(ntype+1)]['Layer']
        netParams.popParams[name] = {'cellType': 'IzhiCell', 'cellsList': Pops[str(ntype+1)]['list']}

    # Defining a generic synapse
    netParams.synMechParams['exc'] = {'mod': 'FluctExp2Syn', 'tau_rise': 1.0, 'tau_fall': 2.0, 'cn': 4.0, 'type': 1}
    netParams.synMechParams['inh'] = {'mod': 'FluctExp2Syn', 'tau_rise': 1.0, 'tau_fall': 2.0, 'cn': 4.0, 'type': -1}

    ## Connections by "connList" uses IDs relative to the "preConds" and "postConds"
    netParams.connParams['Thalamus->All_exc'] = {
            'preConds': {'pop': 'artificial'},          # conditions of presyn cells
            'postConds': {'cellType': 'IzhiCell'},      # conditions of postsyn cells
            'connList': Exc_ThtoAll['connList_gID'],    # list of conns
            'weight': Exc_ThtoAll['weightList'],        # synaptic weight
            'delay': Exc_ThtoAll['delayList'],          # transmission delay (ms)
            'synMech': 'exc'}

    netParams.connParams['All->All_exc'] = {
            'preConds': {'cellType': 'IzhiCell'},       # conditions of presyn cells
            'postConds': {'cellType': 'IzhiCell'},      # conditions of postsyn cells
            'connList': Exc_AlltoAll['connList_gID'],   # list of conns
            'weight': Exc_AlltoAll['weightList'],       # synaptic weight
            'delay': Exc_AlltoAll['delayList'],         # transmission delay (ms)
            'synMech': 'exc'}

    netParams.connParams['All->All_inh'] = {
            'preConds': {'cellType': 'IzhiCell'},       # conditions of presyn cells
            'postConds': {'cellType': 'IzhiCell'},      # conditions of postsyn cells
            'connList': Inh_AlltoAll['connList_gID'],   # list of conns
            'weight': Inh_AlltoAll['weightList'],       # synaptic weight
            'delay': Inh_AlltoAll['delayList'],         # transmission delay (ms)
            'synMech': 'inh'}

    return netParams


import pygame
from pygame.sprite import Sprite

class Tiro(Sprite):
    """Class para manipular os tiros disparados pela nave"""
    def __init__(self, ik_game):
        """Cria um disparo na posição atual da nave"""
        super().__init__()
        self.screen = ik_game.screen
        self.configuracoes = ik_game.configuracoes
        self.cor = self.configuracoes.tiro_cor

        # Cria um disparo rect na posição (0, 0) e reposiciona no local certo
        self.rect = pygame.Rect(0, 0, self.configuracoes.tiro_width,
                                self.configuracoes.tiro_height)
        self.rect.midtop = ik_game.nave.rect.midtop

        # Armazena a posição do disparo como um decimal
        self.y = float(self.rect.y)

    def update(self):
        """Move o tiro para cima na tela"""
        # Atualiza a posição decimal do disparo
        self.y -= self.configuracoes.tiro_vel
        # Atualiza a posição rect
        self.rect.y = self.y

    def draw_tiro(self):
        """Desenha o tiro na tela"""
        pygame.draw.rect(self.screen, self.cor, self.rect)


dct = {}

while True:
    inp = input()
    if inp == "drop the media":
        break

    command = inp.split(" ")[0]
    post_name = inp.split(" ")[1]

    if command == "post":
        dct[post_name] = {"Likes": 0, "Dislikes": 0, "Comments": {}}

    elif command == "like":
        dct[post_name]["Likes"] += 1

    elif command == "dislike":
        dct[post_name]["Dislikes"] += 1

    elif command == "comment":
        dct[post_name]["Comments"].update(
            {inp.split(" ")[2]: inp.split(" ")[3:]}
            )

for key, value in dct.items():
    print("Post: {} | Likes: {} | Dislikes: {}\nComments:". format(
          key, value['Likes'], value['Dislikes'])
          )

    if value["Comments"] == {}:
        print("None")
    else:
        for x, y in value["Comments"].items():
            print("*  {}: {}".format(x, " ".join(y)))

02. Lists and Dictionaries/Dictionaries/05.Social_Media_Posts.py


import math
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import init
from collections import OrderedDict
from modules import CompactBasicBlock, BasicBlock, Bottleneck, DAPPM, segmenthead, GhostBottleneck

bn_mom = 0.1
BatchNorm2d = nn.BatchNorm2d

class CompactDualResNet(nn.Module):

    def __init__(self, block, layers, num_classes=19, planes=64, spp_planes=128, head_planes=128, augment=True):
        super(CompactDualResNet, self).__init__()

        highres_planes = planes * 2
        self.augment = augment

        self.conv1 =  nn.Sequential(
                          nn.Conv2d(3,planes,kernel_size=3, stride=2, padding=1),
                          #BatchNorm2d(planes, momentum=bn_mom),
                          nn.ReLU(inplace=True),
                          nn.Conv2d(planes,planes,kernel_size=3, stride=2, padding=1),
                          #BatchNorm2d(planes, momentum=bn_mom),
                          nn.ReLU(inplace=True),
                      )

        self.relu = nn.ReLU(inplace=False)
        self.layer1 = self._make_layer(block, planes, planes, layers[0])
        self.layer2 = self._make_layer(block, planes, planes * 2, layers[1], stride=2)
        self.layer3 = self._make_layer(block, planes * 2, planes * 4, layers[2], stride=2)
        self.layer4 = self._make_layer(CompactBasicBlock, planes * 4, planes * 8, layers[3], stride=2)

        self.compression3 = nn.Sequential(
                                          nn.Conv2d(planes * 4, highres_planes, kernel_size=1, bias=False),
                                          BatchNorm2d(highres_planes, momentum=bn_mom),
                                          )

        self.compression4 = nn.Sequential(
                                          nn.Conv2d(planes * 8, highres_planes, kernel_size=1, bias=False),
                                          BatchNorm2d(highres_planes, momentum=bn_mom),
                                          )

        self.down3 = nn.Sequential(
                                   nn.Conv2d(highres_planes, planes * 4, kernel_size=3, stride=2, padding=1, bias=False),
                                   BatchNorm2d(planes * 4, momentum=bn_mom),
                                   )

        self.down4 = nn.Sequential(
                                   nn.Conv2d(highres_planes, planes * 4, kernel_size=3, stride=2, padding=1, bias=False),
                                   BatchNorm2d(planes * 4, momentum=bn_mom),
                                   nn.ReLU(inplace=True),
                                   nn.Conv2d(planes * 4, planes * 8, kernel_size=3, stride=2, padding=1, bias=False),
                                   BatchNorm2d(planes * 8, momentum=bn_mom),
                                   )

        self.layer3_ = self._make_layer(block, planes * 2, highres_planes, 2)

        self.layer4_ = self._make_layer(block, highres_planes, highres_planes, 2)

        self.layer5_ = self._make_ghost_bottleneck(GhostBottleneck, highres_planes , highres_planes, 1)

        self.layer5 =  self._make_ghost_bottleneck(GhostBottleneck, planes * 8, planes * 8, 1, stride=2)
        self.spp = DAPPM(planes * 16, spp_planes, planes * 4)

        if self.augment:
            self.seghead_extra = segmenthead(highres_planes, head_planes, num_classes)

        self.final_layer = segmenthead(planes * 4, head_planes, num_classes)

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
            elif isinstance(m, BatchNorm2d):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

    def _make_layer(self, block, inplanes, planes, blocks, stride=1):
        downsample = None
        if stride != 1 or inplanes != planes * block.expansion:
            downsample = nn.Sequential(
                nn.Conv2d(inplanes, planes * block.expansion,
                          kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(planes * block.expansion, momentum=bn_mom),
            )

        layers = []
        layers.append(block(inplanes, planes, stride, downsample))
        inplanes = planes * block.expansion
        for i in range(1, blocks):
            if i == (blocks-1):
                layers.append(block(inplanes, planes, stride=1, no_relu=True))
            else:
                layers.append(block(inplanes, planes, stride=1, no_relu=False))

        return nn.Sequential(*layers)

    def _make_divisible(self, v, divisor, min_value=None):
        if min_value is None:
            min_value = divisor
        new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
        if new_v < 0.9 * v:
            new_v += divisor
        return new_v

    def _make_ghost_bottleneck(self, block, inplanes, planes, blocks, stride=1):
        if stride != 1 or inplanes != planes * 2:
            out_channel = planes * 2
        else:
            out_channel = planes

        cfg = [[3,  96, out_channel, 0, 1]] # k, t, c, SE, s
        input_channel = inplanes
        layers = []
        for k, exp_size, c, se_ratio, s in cfg:
            output_channel = c
            hidden_channel = self._make_divisible(exp_size, 4)
            layers.append(block(input_channel, hidden_channel, output_channel, k, s, se_ratio=se_ratio))
            input_channel = output_channel
        return nn.Sequential(*layers)

    def forward(self, x):

        width_output = x.shape[-1] // 8
        height_output = x.shape[-2] // 8
        layers = []

        x = self.conv1(x)

        x = self.layer1(x)
        layers.append(x)

        x = self.layer2(self.relu(x))
        layers.append(x)

        x = self.layer3(self.relu(x))
        layers.append(x)
        x_ = self.layer3_(self.relu(layers[1]))

        x = x + self.down3(self.relu(x_))
        x_ = x_ + F.interpolate(
                        self.compression3(self.relu(layers[2])),
                        size=[height_output, width_output],
                        mode='bilinear')
        if self.augment:
            temp = x_

        x = self.layer4(self.relu(x))
        layers.append(x)
        x_ = self.layer4_(self.relu(x_))

        x = x + self.down4(self.relu(x_))
        x_ = x_ + F.interpolate(
                        self.compression4(self.relu(layers[3])),
                        size=[height_output, width_output],
                        mode='bilinear')

        x_ = self.layer5_(self.relu(x_))
        x = F.interpolate(
                        self.spp(self.layer5(self.relu(x))),
                        size=[height_output, width_output],
                        mode='bilinear')

        x_ = self.final_layer(x + x_)

        if self.augment:
            x_extra = self.seghead_extra(temp)
            return [x_extra, x_]
        else:
            return x_

def get_seg_model(cfg, **kwargs):
    model = CompactDualResNet(BasicBlock, [2, 2, 2, 2], num_classes=19, planes=32, spp_planes=128, head_planes=64, augment=True)
    return model

if __name__ == '__main__':
   import time
   device = torch.device('cuda')
   #torch.backends.cudnn.enabled = True
   #torch.backends.cudnn.benchmark = True
   model = CompactDualResNet(BasicBlock, [2, 2, 2, 2], num_classes=11, planes=32, spp_planes=128, head_planes=64)
   model.eval()
   model.to(device)
   iterations = None
   #input = torch.randn(1, 3, 1024, 2048).cuda()
   input = torch.randn(1, 3, 720, 960).cuda()
   with torch.no_grad():
       for _ in range(10):
           model(input)

       if iterations is None:
           elapsed_time = 0
           iterations = 100
           while elapsed_time < 1:
               torch.cuda.synchronize()
               torch.cuda.synchronize()
               t_start = time.time()
               for _ in range(iterations):
                   model(input)
               torch.cuda.synchronize()
               torch.cuda.synchronize()
               elapsed_time = time.time() - t_start
               iterations *= 2
           FPS = iterations / elapsed_time
           iterations = int(FPS * 6)

       print('=========Speed Testing=========')
       torch.cuda.synchronize()
       torch.cuda.synchronize()
       t_start = time.time()
       for _ in range(iterations):
           model(input)
       torch.cuda.synchronize()
       torch.cuda.synchronize()
       elapsed_time = time.time() - t_start
       latency = elapsed_time / iterations * 1000
   torch.cuda.empty_cache()
   FPS = 1000 / latency
   print(FPS)


from selenium import webdriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.common.by import By
from time import sleep

class InternetSpeed:
    def __init__(self, edge_driver_path):
        self.driver = webdriver.Edge(service=Service(edge_driver_path))
        self.down = 0
        self.up = 0
        self.get_internet_speed()

    def get_internet_speed(self):
        speedtest_url = "https://www.speedtest.net/"
        self.driver.get(speedtest_url)
        sleep(10)
        start_test = self.driver.find_element(by=By.XPATH,
                                              value='//*[@id="container"]/div/div[3]/div/div/div/div[2]/div[3]/div[1]/a')
        start_test.click()
        sleep(60)
        self.down = self.driver.find_element(by=By.XPATH,
                                             value='//*[@id="container"]/div/div[3]/div/div/div/div[2]/div[3]/div[3]/div/div[3]/div/div/div[2]/div[1]/div[2]/div/div[2]/span').text
        self.up = self.driver.find_element(by=By.XPATH,
                                           value='//*[@id="container"]/div/div[3]/div/div/div/div[2]/div[3]/div[3]/div/div[3]/div/div/div[2]/div[1]/div[3]/div/div[2]/span').text
        print(self.down)
        print(self.up)

        self.driver.quit()


from lindertree.lsystem import *
from lindertree.turtle_interprate import *

axiom = string_to_symbols('!(1)F(5)X')
constants = {'w':1.4, 'e':1.6, 'a':1.1}
width_rule = Rule.from_string('!(x)', '!(x*w)', constants)
elongation_rule = Rule.from_string('F(x)', 'F(x*e)', constants)
angle_rule1 = Rule.from_string('+(x)', '+(x*a)', constants)
angle_rule2 = Rule.from_string('-(x)', '-(x*a)', constants)
branching_rule = Rule.from_string('X', '!(1)[+(25)F(2)X]F(2)[-(25)F(2)X]!(1)F(5)X', constants)
rules = [width_rule, elongation_rule, branching_rule, angle_rule1, angle_rule2]

print('Axiom : ' + symbols_to_string(axiom))
print('Rules : ')
for rule in rules:
	print('- ' + str(rule))

symbols = generate_lsystem(8, axiom, rules)
print(symbols_to_string(symbols))
turtle_interprate(symbols, init_pos=(0,-400))


#! /usr/bin/env python3
__author__ = 'Amirhossein Kargaran 9429523 '

import os
import sys
import socket

import pickle
import select
import signal
import threading
import time
from threading import Thread
from datetime import datetime

# Local modules
from APIs.logging import Log
from APIs.logging import Color
from APIs.security import *
from Crypto.Random import random
from filelock import FileLock
file_path = "result.txt"
lock_path = "result.txt.lock"
lock = FileLock(lock_path, timeout=1)

# Declare Global variables
PORT = 5558
TERMINATE = False
CLI_HASH = {}
KEY = ''
ll = list()

class Server():
    def __init__(self):
        self.HOST_IP = '0.0.0.0'
        self.HOST_PORT = '8081'
        self.MAX_USR_ACCPT = '100'

    def show_help(self):
        msg = '''
        AVAILABLE COMMANDS:
        \h          Print these information
        \d          Set default configuration
        \sd         Show default configuration
        \sc         Show current configuration
        \sau        Show active users
        \sac        Show active chat rooms
        \sf         Shutdown server forcefully
        \monitor    Enables monitor mode'''
        print(msg)

    def show_config(self, type_='default'):
        if type_ in ('active', 'ACTIVE'):
            msg = '''
            Active configuration of the server :
            HOST IP = ''' + self.HOST_IP + '''
            HOST PORT = ''' + self.HOST_PORT + '''
            MAX USER ALLOWED = ''' + self.MAX_USR_ACCPT
            logging.log('Showing Active server configuration')
            print(msg)
        else:
            msg = '''
            Default configuration of the server:
            HOST IP = 0.0.0.0
            HOST PORT = 8081
            MAX USER ALLOWED = 100'''
            print(msg)

    def set_usr_config(self, parameters):
        if parameters:
            if sys.argv[1] in ('-h', '--help'):
                self.show_help()
            try:
                self.HOST_IP = sys.argv[1]
                self.HOST_PORT = sys.argv[2]
                self.MAX_USR_ACCPT = sys.argv[3]
            except:
                print('USAGE:\nscript ip_address port_number max_usr_accpt')
                sys.exit(0)
        else:
            self.HOST_IP = input('Enter host IP : ')
            self.HOST_PORT = input('Enter host PORT : ')
            self.MAX_USR_ACCPT = input('Enter max number of users server would accept : ')

    def update_active_users(self):
        self.user_list = []
        for cli_obj in CLI_HASH.values():
            self.user_list.append(cli_obj.userName)

    def signal_handler(self, signal, frame):
        print(' has been pressed.\n')

    def srv_prompt(self):
        # TODO: Add feature to view server socket status
        global TERMINATE
        while True:
            opt = input(Color.PURPLE + '\nenter command $ ' + Color.ENDC)
            if opt == '\h':
                self.show_help()
            elif opt == '\monitor':
                print('Monitoring mode ENABLED!')
                logging.silent_flag = False
                signal.signal(signal.SIGINT, self.signal_handler)
                signal.pause()
                print('Monitoring mode DISABLED')
                logging.silent_flag = True
            elif opt == '\sd':
                self.show_config(type_='default')
            elif opt == '\sc':
                self.show_config(type_='active')
            elif opt == '\sau':
                self.update_active_users()
                logging.log(self.user_list)
                print(self.user_list)
            elif opt == '\sf':
                print(Color.WARNING +
                        'WARNING: All users will be disconnected with out any notification!!' +
                        Color.ENDC)
                opt = input('Do you really want to close server?[Y/N] ')
                if opt == 'Y':
                    logging.log('Shuting down server...')
                    print('Shuting down server...')
                    TERMINATE = True
                    sys.exit(0)
                else:
                    logging.log('Aborted.')
                    print('Aborted.')
                    pass
            elif opt == '':
                pass
            else:
                print('COMMAND NOT FOUND!!')

    def init_clients(self):
        global CLI_HASH
        while not TERMINATE:
            try:
                self.server.settimeout(1)
                conn, addr = self.server.accept()
            except socket.timeout:
                pass
            except Exception as e:
                raise e
            else:
                logging.log(
                        'A connection from [{}.{}] has been received.'.format(
                            addr[0], addr[1]))
                cli_obj = Client(conn, addr, self)
                CLI_HASH[conn] = cli_obj

                threading._start_new_thread(cli_obj.run, ('',))
        try:
            print('Server has stopped listening on opened socket.')
            print('Broadcasting connection termination signal..')
            msg = "Sorry! We are unable to serve at this moment."
            for cli_socket in CLI_HASH.keys():
                try:
                    cli_socket.send(msg.encode())
                except:
                    cli_socket.close()
                    CLI_HASH.pop(cli_socket)
        except:
            pass

    def init(self):
        logging.log('Initializing server')
        if len(sys.argv) == 1:
            self.show_config(type_='default')
            opt = input('Set these default config?[Y/n] ')
            if opt == '':
                opt = 'Y'
            if opt in ('Y', 'y', 'yes', 'Yes', 'YES'):
                print("Setting up default configurations...")
            else:
                self.set_usr_config(parameters=False)
        else:
            self.set_usr_config(parameters=True)

        self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        try:
            self.server.bind((self.HOST_IP, int(self.HOST_PORT)))
            self.server.listen(int(self.MAX_USR_ACCPT))
        except:
            print('Unable to bind HOST IP and PORT.\nPlease check your configuration')
            sys.exit('EMERGENCY')
        print('\nServer is listening at {}:{}'.format(self.HOST_IP, self.HOST_PORT))
        print('Server is configured to accept %s clients.' %(str(self.MAX_USR_ACCPT)))

        #thread_srv = threading.Thread(target=self.srv_prompt, args=())
        thread_cli = threading.Thread(target=self.init_clients, args=())

        thread_cli.start()
        self.srv_prompt()

        for thread in (thread_srv, thread_cli):
            thread.join()
        print('Server and Client threads are exited.')

class Client():
    def __init__(self, conn, addr, srv_obj):
        global PORT
        self.srv_obj = srv_obj
        self.conn = conn
        self.addr = addr
        self.userName = '-N/A-'
        self.PUBLIC_KEY = None
        self.KEY = ''
        self.items_file='result.txt'
        self.port = PORT
        PORT = PORT +1
        self.EnSharedKey =""

    def validate_user(self):
        pass

    def features(self, msg):
        if msg == '@getonline':
            self._loop_break_flag = True
            self.conn.send(
                    AES_.encrypt(self.KEY, str(self.srv_obj.user_list)))
        if msg.split()[0][1:] in self.srv_obj.user_list:
            self._loop_break_flag = True
            for _conn in CLI_HASH:
                if CLI_HASH[_conn].userName == msg.split()[0][1:]:
                    try:
                        self.IND_SOCK = _conn
                        msg_send = "<" + self.userName + "@" + self.addr[0] +\
                                "> [IND] " + ' '.join(msg.split()[1:])
                        self.broadcast(msg_send, IND_FLAG=True)
                    except Exception as e:
                        logging.log(msg_type='EXCEPTION', msg=e)

    def getSharedKey(self):
        TOKEN_CHAR_LIST = "abcdefghij!@#$%"

        # Generate unique symmetric 10bit key for each client
        passphrase = ''.join(random.sample(TOKEN_CHAR_LIST, 10))
        shared_key = hasher(passphrase)
        EnSharedKey = RSA_.encrypt(self.PUBLIC_KEY, shared_key)
        if EnSharedKey:
            return (shared_key, EnSharedKey)
        else:
            logging.log("Unable to encrypt shared key with RSA.", msg_type='ERROR')

    def result(self , *args):
        file = open(self.items_file,"r")
        fileList = file.readlines()
        file.close()
        self.broadcast(fileList)

    def time1 (self):
        self.sock.listen(1)
        flag = 1
        try :
            while True:
                print('waiting for a connection')
                connection, client_address = self.sock.accept()

                try:
                    print('connection from', client_address)

                    while True:
                        data = connection.recv(64)
                        if flag == 1 :
                            self.Token, self.STRTOKEN = pickle.loads(data)
                            if data:
                                if (self.Token == self.KEY and self.STRTOKEN=="TOKEN") :
                                    print("This user is Valid")
                                    flag = 0
                                else:
                                    print("This user is not Valid")
                                    connection.close()
                                    return
                        else :
                            if data.decode()=="bye" :
                                try:
                                    with lock.acquire(timeout=10):
                                        wfile = open(self.items_file, 'w+')
                                        for ilist in ll:
                                            wfile.write(str(ilist) + "\n")
                                        wfile.close()
                                        lock.release()
                                except :
                                    print("Another instance of this application currently holds the lock.")

                            if data :
                                print(str(self.userName)+ " : " + str(data.decode()))
                                ll.append(str(self.userName)+ " : " + str(data.decode()))
                            else:
                                return

                finally:
                    connection.close()
        except :
            "what the fuck ?"

    def time2 (self):
        while True:
            try:
                self._loop_break_flag = False
                msg = self.conn.recv(20000)

                if msg:
                    if msg.split()[0][0] == '@':
                        self.srv_obj.update_active_users()
                        self.features(msg)

                    if not self._loop_break_flag:
                        self.result()
                else:
                    self.remove()
                    pass
            except Exception as e:
                logging.log(msg_type='EXCEPTION', msg='[{}] {}'.format(self.userName, e))

    def run(self, *args):
        data = self.conn.recv(4000)
        if data:
            self.userName, self.PUBLIC_KEY = pickle.loads(data)
        if self.PUBLIC_KEY:
            self.KEY, self.EnSharedKey = self.getSharedKey()
        else:
            tmp_conn = "{}:{}".format(self.addr[0], self.addr[1])
            logging.log(
                    "Public key has not been received from [{}@{}]".format(
                        self.userName, tmp_conn))
            logging.log(
                "[0.0.0.0:8081 --> {}] Socket has been terminated ".format(tmp_conn))
            self.remove()

        if self.KEY == '':
            logging.log("Symmetric key generation failed")

        tmp_msg = "symmetric key {} has been sent to {}".format(self.KEY, self.userName)
        logging.log(tmp_msg)
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        local_hostname = socket.gethostname()
        local_fqdn = socket.getfqdn()
        ip_address = socket.gethostbyname(local_hostname)
        print("working on %s (%s) with %s" % (local_hostname, local_fqdn, ip_address))
        server_address = (ip_address, self.port)
        print('starting up on %s port %s' % server_address)
        self.sock.bind(server_address)

        EnSharedKey = (self.port , self.EnSharedKey)
        EnSharedKey = pickle.dumps(EnSharedKey)
        self.conn.send(EnSharedKey)

        Thread(target=self.time1()).start()
        Thread(target=self.time2()).start()

    def broadcast(self, msg, IND_FLAG=False):
        msg = pickle.dumps(msg)

        if IND_FLAG:
            self.IND_SOCK.send(msg)
            return
        for cli_socket in CLI_HASH.keys():
            if 1==1 :
                try:
                    cli_socket.send(msg)
                except:
                    raise Exception
                    cli_socket.close()
                    self.remove()

    def remove(self):
        if self.conn in CLI_HASH.keys():
            self.conn.close()
            CLI_HASH.pop(self.conn)
            self.srv_obj.update_active_users()
            print(self.srv_obj.user_list)
            sys.exit()

if __name__ == "__main__":
    try:
        logging = Log(f_name='server_chatroom_' + datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))
        logging.logging_flag = True
        logging.silent_flag = True
        logging.validate_file()
        server = Server()
        server.init()
    except SystemExit as e:
        if e.code != 'EMERGENCY':
            raise
        else:
            print(sys.exc_info())
            print('Something went wrong!!\nPlease contact developers.')
            os._exit(1)
    except:
        raise Exception
        print('Something went wrong!!\nPlease contact developers\nTerminating the process forcefully..')
        time.sleep(1)
        os._exit(1)


import click
import unittest
from click.testing import CliRunner
from doodledashboard.notifications import TextNotification
from parameterized import parameterized

from sketchingdev.console import ConsoleDisplay
from tests.sketchingdev.terminal.ascii_terminal import AsciiTerminal

class TestConsoleDisplayWithText(unittest.TestCase):

    @parameterized.expand([
        ((1, 1), "",
         """
         +-+
         ||
         +-+
         """),
        ((10, 3), "a",
         """
         +----------+
         ||
         |    a|
         ||
         +----------+
         """),
        ((10, 3), "centred",
         """
         +----------+
         ||
         | centred|
         ||
         +----------+
         """),
        ((10, 3), "I'm centred",
         """
         +----------+
         |   I'm|
         | centred|
         ||
         +----------+
         """),
        ((10, 3), "Hello World! This is too long",
         """
         +----------+
         |  Hello|
         |  World!|
         | This is|
         +----------+
         """),
    ])
    def test_text_centred_in_console(self, console_size, input_text, expected_ascii_terminal):
        expected_terminal = AsciiTerminal.extract_text(expected_ascii_terminal)

        text_notification = TextNotification()
        text_notification.set_text(input_text)
        cmd = create_cmd(lambda: ConsoleDisplay(console_size).draw(text_notification))
        result = CliRunner().invoke(cmd, catch_exceptions=False)

        self.assertEqual(expected_terminal, result.output)

def create_cmd(func):
    @click.command()
    def c(f=func):
        f()

    return c

if __name__ == "__main__":
    unittest.main()


from etl import ETL
import os

DATASET_PATH = "/home/login/datasets"
DATASET_NAME = "CIMA"
DATASET_SIZE = 377
validation_size = 0.2

validation_size = int(DATASET_SIZE * validation_size)

validation_etl = ETL("/home/login/datasets", [], size=validation_size)
validation_etl.load(DATASET_NAME)

validation_path = os.path.join(DATASET_PATH, DATASET_NAME, "validation")
if not os.path.exists(validation_path):
    os.mkdir(validation_path)
data_path = os.path.join(DATASET_PATH, DATASET_NAME, "data")

validation_set = validation_etl.cima

for key, item in validation_set.items():
    print(f"Moving {key} to validation.")
    old_path = os.path.join(data_path, key + ".csv")
    new_path = os.path.join(validation_path, key + ".csv")
    os.rename(old_path, new_path)


from helper import is_prime, find_prime_factors, int_list_product

def smallest_multiple(n):
    ls = list()

    for i in range(2,n):
        pf = find_prime_factors(i)
        for l in ls:
            for f in pf:
                if(l == f):
                    pf.remove(f)
                    break
        for f in pf:
            ls.append(f)
        ls.sort()

    return int_list_product(ls)

print(str(smallest_multiple(20)))


import datetime as dt
import random

import pytest

from scheduler import Scheduler, SchedulerError
from scheduler.base.definition import JobType
from scheduler.threading.job import Job

from ...helpers import foo

@pytest.mark.parametrize(
    "empty_set",
    [
        False,
        True,
    ],
)
@pytest.mark.parametrize(
    "any_tag",
    [
        None,
        False,
        True,
    ],
)
@pytest.mark.parametrize(
    "n_jobs",
    [
        0,
        1,
        2,
        3,
        10,
    ],
)
def test_get_all_jobs(n_jobs, any_tag, empty_set):
    sch = Scheduler()
    assert len(sch.jobs) == 0

    for _ in range(n_jobs):
        sch.once(dt.datetime.now(), foo)
    assert len(sch.jobs) == n_jobs

    if empty_set:
        if any_tag is None:
            jobs = sch.get_jobs()
        else:
            jobs = sch.get_jobs(any_tag=any_tag)
    else:
        if any_tag is None:
            jobs = sch.get_jobs(tags={})
        else:
            jobs = sch.get_jobs(tags={}, any_tag=any_tag)

    assert len(jobs) == n_jobs

@pytest.mark.parametrize(
    "job_tags, select_tags, any_tag, returned",
    [
        [
            [{"a", "b"}, {"1", "2", "3"}, {"a", "1"}],
            {"a", "1"},
            True,
            [True, True, True],
        ],
        [
            [{"a", "b"}, {"1", "2", "3"}, {"a", "2"}],
            {"b", "1"},
            True,
            [True, True, False],
        ],
        [
            [{"a", "b"}, {"1", "2", "3"}, {"b", "1"}],
            {"3"},
            True,
            [False, True, False],
        ],
        [
            [{"a", "b"}, {"1", "2", "3"}, {"b", "2"}],
            {"2", "3"},
            True,
            [False, True, True],
        ],
        [
            [{"a", "b"}, {"1", "2", "3"}, {"a", "1"}],
            {"a", "1"},
            False,
            [False, False, True],
        ],
        [
            [{"a", "b"}, {"1", "2", "3"}, {"a", "2"}],
            {"b", "1"},
            False,
            [False, False, False],
        ],
        [
            [{"a", "b"}, {"1", "2", "3"}, {"b", "1"}],
            {"1", "3"},
            False,
            [False, True, False],
        ],
        [
            [{"a", "b"}, {"1", "2", "3"}, {"b", "2"}],
            {"2", "3"},
            False,
            [False, True, False],
        ],
    ],
)
def test_get_tagged_jobs(job_tags, select_tags, any_tag, returned):
    sch = Scheduler()

    jobs = [sch.once(dt.timedelta(), lambda: None, tags=tags) for tags in job_tags]

    res = sch.get_jobs(tags=select_tags, any_tag=any_tag)
    for job, ret in zip(jobs, returned):
        if ret:
            assert job in res
        else:
            assert job not in res


import random

suits = ("Hearts", "Spades", "Diamonds", "Clubs")
tarotSuits = ("Swords", "Cups", "Wands", "Coins")
names = ("Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King")
tarotNames = ("Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",
              "Page", "Knight", "Queen", "King")
arcana = ('The Fool', 'The Magician', 'The High Priestess', 'The Empress', 'The Emperor',
          'The Hierophant', 'The Lovers', 'The Chariot', 'Strength', 'The Hermit', 'Wheel of Fortune',
          'Justice', 'The Hanged Man', 'Death', 'Temperance', 'The Devil', 'The Tower', 'The Star',
          'The Moon', 'The Sun', 'Judgement', 'The World')
unoColors = ('Red', 'Green', 'Blue', 'Yellow')
unoSpecials = ('Skip', 'Reverse', 'Draw')

# TODO:
#  Give cards emoji representations
#  Implement into bot

class Card:
    def get_value(self):
        if self.tarot:
            if self.suit == "Major":
                return arcana.index(self.name)
            else:
                return min(tarotNames.index(self.name) + 1, 10)
        if self.uno:
            return
        return min(names.index(self.name) + 1, 10)

    def __init__(self, suit, name, hidden=False, tarot=False, uno=False):
        self.suit = str(suit)
        self.name = str(name)
        self.hidden = hidden
        self.tarot = tarot
        self.uno = uno
        self.value = self.get_value()

    def __str__(self):
        if self.suit == "Major":
            return self.name
        if self.uno:
            return f'{self.suit} {self.name}'
        return f'{self.name} of {self.suit}'

class Deck:
    def __init__(self, hand=False, tarot=False, uno=False):
        self.hand = hand
        self.tarot = tarot
        self.uno = uno
        self.stack = []

        if self.hand:
            return
        if self.tarot:
            for suit in tarotSuits:
                for name in tarotNames:
                    self.stack.append(Card(suit, name, tarot=True))
            for name in arcana:
                self.stack.append(Card("Major", name, tarot=True))
            return
        if self.uno:  # Does not work
            for color in unoColors:
                for num in range(1, 10):
                    self.stack.append(Card(color, num, uno=True))
                    self.stack.append(Card(color, num, uno=True))
                for special in unoSpecials:
                    self.stack.append(Card(color, special, uno=True))
                    self.stack.append(Card(color, special, uno=True))
            for num in range(0, 4):
                self.stack.append(Card('Wild', '', uno=True))
                self.stack.append(Card('Wild', 'Draw', uno=True))
            return

        for suit in suits:
            for name in names:
                self.stack.append(Card(suit, name))
        return

    def list(self, hidden=True):
        contents = ""
        for card in self.stack:
            if card.hidden and hidden:
                contents += f"*Hidden card,* "
            contents += f"{card}, "
        return contents

    def shuffle(self):
        random.shuffle(self.stack)

    def draw(self, pos=0, hidden=False):
        dealt = self.stack.pop(pos)
        if hidden:
            dealt.hidden = True
        return dealt

    def insert(self, card, pos=0, bottom=False):
        if bottom:
            self.stack.append(card)
        else:
            self.stack.insert(pos, card)


import csv
import json
import numpy as np
from tabulate import tabulate
import matplotlib.pyplot as plt
from math import ceil
from wand.image import Image as WImage
from subprocess import Popen

def make_json(csvFilePath,keyName,alldata):

    # create a dictionary
    data = {}

    # Open a csv reader called DictReader
    with open(csvFilePath, encoding='utf-8') as csvf:
        next(csvf)

        csvReader = csv.DictReader(csvf, delimiter='\t')

        # Convert each row into a dictionary
        # and add it to data
        for rows in csvReader:

            # Assuming a column named 'No' to
            # be the primary key
            key = rows['CATEGORY']
            data[key] = rows

        alldata[keyName] = data

    jsonfile = json.dumps(alldata)

    return jsonfile

def plots(Sample,file,normal,listSample):

    #listSample = [row[1] for row in batch]
    rows = []

    path = "/storage/gluster/vol1/data/PUBLIC/SCAMBIO/ABT414_WES_Analysis/ABT414_Flank/ABT414_Flank/"

    if Sample == 'ALL' and not(normal):
        ROWS = 3
        COLS = ceil(np.size(listSample)/ROWS)

        fig = plt.figure(figsize = (20, 15))
        for row in range(ROWS):
            cols = []
            for col in range(COLS):
                index = row * COLS + col
                if index<np.size(listSample):
                    img = WImage(filename=path+listSample[index]+file)
                    a = fig.add_subplot(COLS, ROWS, index+1)
                    plt.axis('off')
                    plt.grid(b=None)
                    imgplot = plt.imshow(img)
                    a.set_title(listSample[index])
    else:
        fig = plt.figure(figsize = (15, 10))
        a = fig.add_subplot(1, 1, 1)
        if not(normal):
            index = listSample.index(Sample)
            img = WImage(filename=path+listSample[index]+file)
            a.set_title(listSample[index])
        else:
            img = WImage(filename=path+Sample+file)
        imgplot = plt.imshow(img)
        plt.axis('off')
        plt.grid(b=None)
        imgplot = plt.imshow(img)

def multiPage(Sample,file,page,normal,listSample):

    page = page-1
    #listSample = [row[1] for row in batch]

    path = "/storage/gluster/vol1/data/PUBLIC/SCAMBIO/ABT414_WES_Analysis/ABT414_Flank/ABT414_Flank/"

    fig = plt.figure(figsize = (20, 15))
    a = fig.add_subplot(1, 1, 1)
    if not(normal):
        index = listSample.index(Sample)
        img = WImage(filename=path+listSample[index]+file+"["+str(page)+"]")
        a.set_title(listSample[index])
    else:
        img = WImage(filename=path+Sample+file+"["+str(page)+"]")
    imgplot = plt.imshow(img)
    plt.axis('off')
    plt.grid(b=None)
    imgplot = plt.imshow(img)

def tableShow(Sample,file, cols,listSample):

    path = "/storage/gluster/vol1/data/PUBLIC/SCAMBIO/ABT414_WES_Analysis/ABT414_Flank/ABT414_Flank/"

    if Sample == 'ALL':
        for index in range(np.size(listSample)):
            print('\n'+listSample[index]+'\n')
            table = []
            filePath = path+listSample[index]+file
            with open (filePath, 'r') as f:
                for row in csv.reader(f,delimiter='\t'):
                    if np.size(row)>1:
                        content = [row[i] for i in cols]
                        table.append(content)
            print(tabulate(table,headers="firstrow"))
    else:
        print(Sample+'\n')
        table = []
        filePath = path+Sample+file
        with open (filePath, 'r') as f:
            for row in csv.reader(f,delimiter='\t'):
                if np.size(row)>1:
                    content = [row[i] for i in cols]
                    table.append(content)
        print(tabulate(table,headers="firstrow"))

def commandsParallel(commands,commdsSize,commdsParallel):
    if commdsParallel>commdsSize:
        commdsParallel = commdsSize

    print ("Numbers of samples in parallel: "+ str(commdsParallel))
    itersPar = ceil(commdsSize/commdsParallel)
    print("Numbers of iterations: "+ str(itersPar))
    for i in range(itersPar):
        try:
            processes = [Popen(commands[(i*commdsParallel)+j], shell=True) for j in range(commdsParallel)]
        except IndexError:
            pass
        exitcodes = [p.wait() for p in processes]