import sys

def m_cmd(a, b=0):
    if a == 'push':
        queue.append(b)
    elif a == 'front':
        if queue:
            return queue[0]
        else:
            return -1
    elif a == 'back':
        if queue:
            return queue[-1]
        else:
            return -1
    elif a == 'size':
        return len(queue)
    elif a == 'pop':
        if queue:
            return queue.pop(0)
        else:
            return -1
    elif a == 'empty':
        if queue:
            return 0
        else:
            return 1

N = int(input())
queue = []

for i in range(N):
    cmd = sys.stdin.readline().split()
    if len(cmd) == 1:
        print(m_cmd(cmd[0]))
    else:
        if m_cmd(cmd[0], int(cmd[1])) is None:
            continue
        else:
            print(m_cmd(cmd[0], int(cmd[1])))


from flask import render_template, flash, redirect, url_for
from flask_login import current_user, login_required
from app import db
from app.models import CompleteBloodCount, MetabolicPanel
from app.labs import bp
from app.labs.forms import AddCompleteBloodCellCount, AddMetabolicPanel

import random
from datetime import datetime

@bp.route('/metabolic/add', methods=['GET', 'POST'])
@login_required
def add_metabolic_lab():
    form = AddMetabolicPanel()
    if form.validate_on_submit():
        m = MetabolicPanel(
            sodium=form.sodium.data,
            calcium=form.calcium.data,
            chloride=form.chloride.data,
            potassium=form.potassium.data,
            magnesium=form.magnesium.data,
            blood_urea_nitrogen=form.blood_urea_nitrogen.data,
            creatinine=form.creatinine.data,
            glucose=form.glucose.data,
            report_id=generate_report_id(),
            timestamp=form.timestamp.data,
            metabolic_patient=current_user
        )
        db.session.add(m)
        db.session.commit()
        flash('metabolic panel values added')
        return redirect(url_for('main.index'))
    return render_template('labs/add_labs.html', form=form)

@bp.route('/cbc/add', methods=['GET', 'POST'])
@login_required
def add_cbc_lab():
    form = AddCompleteBloodCellCount()
    if form.validate_on_submit():
        cbc = CompleteBloodCount(white_blood_cell_count=form.white_blood_cell_count.data,
                                 hemoglobin=form.hemoglobin.data,
                                 hematocrit=form.hematocrit.data,
                                 platelet=form.platelet.data,
                                 timestamp=form.timestamp.data,
                                 report_id=generate_report_id(),
                                 cbc_patient=current_user)
        db.session.add(cbc)
        db.session.commit()
        flash('CBC Lab Values Added')
        return redirect(url_for('main.index'))
    return render_template('labs/add_labs.html', form=form)

def generate_report_id():
    random.seed(datetime.now())
    return random.randint(000000, 999999)


from odoo import _, fields, models
from odoo.exceptions import UserError

class AccountMoveLine(models.Model):

    _inherit = "account.move.line"

    def _create_writeoff(self, writeoff_vals):
        """Create a writeoff move per journal for the account.move.lines in
         self. If debit/credit is not specified in vals, the writeoff amount
         will be computed as the sum of amount_residual of the given recordset.

        :param writeoff_vals: list of dicts containing values suitable for
            account_move_line.create(). The data in vals will be processed to
            create both writeoff account.move.line and their enclosing
            account.move.
        """

        def compute_writeoff_counterpart_vals(values):
            line_values = values.copy()
            line_values["debit"], line_values["credit"] = (
                line_values["credit"],
                line_values["debit"],
            )
            if "amount_currency" in values:
                line_values["amount_currency"] = -line_values["amount_currency"]
            return line_values

        # Group writeoff_vals by journals
        writeoff_dict = {}
        for val in writeoff_vals:
            journal_id = val.get("journal_id", False)
            if not writeoff_dict.get(journal_id, False):
                writeoff_dict[journal_id] = [val]
            else:
                writeoff_dict[journal_id].append(val)

        partner_id = (
            self.env["res.partner"]._find_accounting_partner(self[0].partner_id).id
        )
        company_currency = self[0].account_id.company_id.currency_id
        writeoff_currency = self[0].account_id.currency_id or company_currency
        line_to_reconcile = self.env["account.move.line"]
        # Iterate and create one writeoff by journal
        writeoff_moves = self.env["account.move"]
        for journal_id, lines in writeoff_dict.items():
            total = 0
            total_currency = 0
            writeoff_lines = []
            date = fields.Date.today()
            for vals in lines:
                # Check and complete vals
                if "account_id" not in vals or "journal_id" not in vals:
                    raise UserError(
                        _(
                            "It is mandatory to specify an account and a "
                            "journal to create a write-off."
                        )
                    )
                if ("debit" in vals) ^ ("credit" in vals):
                    raise UserError(_("Either pass both debit and credit or none."))
                if "date" not in vals:
                    vals["date"] = self._context.get("date_p") or fields.Date.today()
                vals["date"] = fields.Date.to_date(vals["date"])
                if vals["date"] and vals["date"] < date:
                    date = vals["date"]
                if "name" not in vals:
                    vals["name"] = self._context.get("comment") or _("Write-Off")
                if "analytic_account_id" not in vals:
                    vals["analytic_account_id"] = self.env.context.get(
                        "analytic_id", False
                    )
                # compute the writeoff amount if not given
                if "credit" not in vals and "debit" not in vals:
                    amount = sum([r.amount_residual for r in self])
                    vals["credit"] = amount > 0 and amount or 0.0
                    vals["debit"] = amount < 0 and abs(amount) or 0.0
                vals["partner_id"] = partner_id
                total += vals["debit"] - vals["credit"]
                if (
                    "amount_currency" not in vals
                    and writeoff_currency != company_currency
                ):
                    vals["currency_id"] = writeoff_currency.id
                    sign = 1 if vals["debit"] > 0 else -1
                    vals["amount_currency"] = sign * abs(
                        sum([r.amount_residual_currency for r in self])
                    )
                    total_currency += vals["amount_currency"]

                writeoff_lines.append(compute_writeoff_counterpart_vals(vals))

            # Create balance line
            writeoff_lines.append(
                {
                    "name": _("Write-Off"),
                    "debit": total > 0 and total or 0.0,
                    "credit": total < 0 and -total or 0.0,
                    "amount_currency": total_currency,
                    "currency_id": total_currency and writeoff_currency.id or False,
                    "journal_id": journal_id,
                    "account_id": self[0].account_id.id,
                    "partner_id": partner_id,
                }
            )

            # Create the move
            writeoff_move = self.env["account.move"].create(
                {
                    "journal_id": journal_id,
                    "date": date,
                    "state": "draft",
                    "line_ids": [(0, 0, line) for line in writeoff_lines],
                }
            )
            writeoff_moves += writeoff_move
            line_to_reconcile += writeoff_move.line_ids.filtered(
                lambda r: r.account_id == self[0].account_id
            ).sorted(key="id")[-1:]

        # post all the writeoff moves at once
        if writeoff_moves:
            writeoff_moves.action_post()

        # Return the writeoff move.line which is to be reconciled
        return line_to_reconcile


import requests
import pandas as pd
import numpy as np
import datetime as dt
from pandas_datareader import data as pdr

def backtest():
    pair = input("Enter a pair symbol: ")

    finalDate = dt.datetime.now()
    initialDate = finalDate - pd.DateOffset(months=1)

    URL = "https://fxmarketapi.com/apipandas"
    params = {'currency' : pair,
    'start_date' : initialDate.strftime("%Y-%m-%d"),
    'end_date': finalDate.strftime("%Y-%m-%d"),
    'api_key':'tpLtcSkwFVK_JUbJbYlT',
    'interval':'hourly',
    'format':'ohlc'
    }

    response = requests.get("https://fxmarketapi.com/apipandas", params=params)
    df= pd.read_json(response.text)

    for i in df.index:
        time = dt.datetime.strptime(str(i), '%Y-%m-%d %H:%M:%S')

        if(str(time.hour) == '6'):
            high = 0
            low = 0
            high = df.iloc[:,2][i]
            low = df.iloc[:,3][i]
        elif(str(time.hour) == '7'):
            if(float(high) < float(df.iloc[:,2][i])):
                high = df.iloc[:,2][i]
            if(float(low) > float(df.iloc[:,3][i])):
                low = df.iloc[:,3][i]

            print('High: ' + str(high))
            print('Low: ' + str(low))
            print('Datetime: ' + str(time.day) + '-' + str(time.month))

backtest()


# This file is reserved exclusively for List manipulation
# Written by Ron Friedman, 1926133

# Defining list
myList = [1,2,3,4,5,6,7,8,9]
print(myList)

# Defining a list with different types
myList2 = [1.0,-4,"Hello!",True,False,"World!",10]
print(myList2)

# Accessing specific values in list based on index
myList3 = [2.331,"Good ",False,"morning ",-99,12,True,"class!",22]
print(myList3[1] + myList3[3] + myList3[7])

# Modifying specific values in list based on index
myList4 = [2.0,3.33,False,"Python",123,True,"is",321,False,"boring."]
print("This is the unmodified list: ", myList4)
myList4[2] = True
myList4[5] = False
myList4[8] = True
myList4[9] = "cool!"
print("This list should be modified: ", myList4)

# Appending a list
myList5 = [1.0,2.0,3.0,"I love"]
myList5.append("counting!")
print(myList5)

# Adding lists together
myList6 = ["What a beatiful"]
myList7 = ["day it is!"]
print([myList6] + [myList7])

# Using for loop to go through loop (C -> F)
degreeList = [-50,-45,-40,-35,-30,-25,-20,-15,-10,-5,0,5,10,15,20,25,30,35,40,45,50]
print('C    F')
for C in degreeList:
    F = (9.0/5) * C + 32
    print(C, F)


import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import root,minimize
from scipy.misc import derivative
a = 0.1
k = 2*np.pi

x0_ = np.linspace(0,2,200)

def x0(x):
    f = lambda x0_, x_: x0_ - a*np.sin(k*x0_) - x_
    x0 = root(f, x0 = x, args=(x,) ).x
    return x0

def z(x_):
    return a*np.cos(k*x0(x_))

fig, ax = plt.subplots(1,3)
y1 = [z(x0_[i]) for i in range(x0_.size)]
print('Среднее \t Реализация '+ str(np.mean(y1)) + '\t Теория '+str(-a**2/2*k))
print('STD', np.std(y1))
y1 = np.array(y1).T[0]
y2 = a*np.cos(k*x0_)
yy1  =derivative( z, x0 = x0_ , dx = 0.01)
yy2  =derivative( lambda x: a*k*np.cos(k*x), x0 = x0_, dx = 0.01)

ax[0].plot(x0_,y1)
ax[0].plot(x0_,y2)

f = -a*k*np.sin(k*x0_)/(1 - a*k*np.cos(k*x0_))
ax[1].plot(x0_,yy1)
ax[1].plot(x0_,yy2)
ax[1].plot(x0_,f)

ax[2].plot(y1,yy1)
ax[2].plot(y2,yy2)
ax[2].plot(y2,f)

# def covariation1(x0_):
#     covariation = np.zeros(x0_.size)
#     # x = x0(np.linspace(0,1,200))
#     x = np.linspace(0,1,200)
#     m = np.mean(z(x))
#     for i in range(x0_.size):
#         covariation[i] = (
#                     np.trapz( z(x)*z(x+x0_[i]) \
#                     # * (1 + a*k*np.cos(k*x))
#                     )
#                          )
#     return covariation

# def covariation2(x0):
#     covariation = np.zeros(x0.size)
#     z = lambda x: a*np.cos(k*x)
#     x = np.linspace(0,1,200)
#     for i in range(x0.size):
#         covariation[i] = np.trapz( z(x)*z(x+x0[i]) )
#     return covariation
# # N = len(y1)
# # z1 = np.fft.rfft(y1, n = N)
# # z2 = np.fft.rfft(y2, n = N)
# # freq = np.fft.rfftfreq(n = N)
# fig, ax = plt.subplots(1,1)

# C1 = covariation1(x0_)
# ax.plot(x0_,C1)

# C1 = covariation2(x0_)
# ax.plot(x0_,C1)
# # print(C.shape)

plt.show()


# This is an scons script to build the library
# Projects in different IDEs should make an scons call to this file

from os import path

# directory info
viking_dirs = {
'target': 'viking',
'src': 'source/src', # root of source files
'include': 'source/include', # root of include directory
'build': 'build', # name of the build folder created in the root of the repository
'obj': 'obj', # name of the build subdirectory where object files are built
'bin': 'bin',
'release': 'Release',
'debug': 'Debug',
'demos': 'demos',
'test': 'Test'
}

# compiler flags
viking_flags = {
'common': [ '-std=c++0x', '-Wall' ],
'debug': [ '-g', '-D_DEBUG' ],
'release': [ '-O2', '-DNDEBUG' ],
}

# libraries to link
viking_libs = {
'common': [ 'Irrlicht', 'GL' ]
}

# will be either viking_dirs['debug'] or viking_dirs['release'] depending on script arguments
build_configuration = ''

# pick up "debug" argument from command line input. Defaults to 0 (false).
if ARGUMENTS.get('debug', '0') != '0':
	build_configuration = viking_dirs['debug']
else:
	build_configuration = viking_dirs['release']

# create environment
env = Environment()

# add common compiler flags
env.Append(CXXFLAGS = viking_flags['common'])

# add include directory
env.Append(CPPPATH = path.abspath(viking_dirs['include']))

configuration_path = ''

# conditionally add compiler flags
if build_configuration == viking_dirs['debug']:
	env.Append(CXXFLAGS = viking_flags['debug'])
	configuration_path = viking_dirs['debug']
else:
	env.Append(CXXFLAGS = viking_flags['release'])
	configuration_path = viking_dirs['release']

# compose path to build of Viking
viking_dirs['build_obj'] = path.abspath(path.join(viking_dirs['build'], configuration_path, viking_dirs['obj']))
viking_dirs['build_bin'] = path.abspath(path.join(viking_dirs['build'], configuration_path, viking_dirs['bin']))

# export variables so other scripts can Import them
Export('env viking_dirs build_configuration viking_libs')

# subdirectories with SConscripts in them
script_subdirs = []

if ARGUMENTS.get('viking','1') != '0':
	script_subdirs += ['source']

if ARGUMENTS.get('test','0') != '0':
	script_subdirs += ['tests']

# Run scripts to selectively build viking sub-projects
SConscript(dirs=script_subdirs, name='SConscript')


"""
Miscellaneous functions for Sefaria.
"""
from HTMLParser import HTMLParser

# also at JaggedArray.depth().  Still needed?
def list_depth(x, deep=False):
    """
    returns 1 for [], 2 for [[]], etc.
    :parm x - a list
    :param deep - whether or not to count a level when not all elements in
    that level are lists.
    e.g. [[], ""] has a list depth of 1 with depth=False, 2 with depth=True
    """
    if isinstance(x, int):
        return 0
    elif len(x) > 0 and (deep or all(map(lambda y: isinstance(y, list), x))):
        return 1 + max([list_depth(y, deep=deep) for y in x])
    else:
        return 1

# Moving to JaggedArray.flattenToArray()
def flatten_jagged_array(jagged):
    """
    Returns a 1D list of each terminal element in a jagged array.
    """
    flat = []
    for el in jagged:
        if isinstance(el, list):
            flat = flat + flatten_jagged_array(el)
        else:
            flat.append(el)

    return flat

def is_text_empty(text):
    """
    Returns true if a jagged array 'test' is emtpy or contains
    only "" or 0.
    """
    text = flatten_jagged_array(text)

    text = [t if t != 0 else "" for t in text]
    return not len("".join(text))

def rtrim_jagged_string_array(ja):
    """
    Returns a jagged string array corresponding to ja with any
    trailing Falsey values in any subsection removed.
    """
    if not isinstance(ja, list):
        return ja
    while len(ja) and not ja[-1]:
        ja.pop() # Remove any trailing Falsey values ("", 0, False)
    return [rtrim_jagged_string_array(j) for j in ja]

def union(a, b):
    """ return the union of two lists """
    return list(set(a) | set(b))

class MLStripper(HTMLParser):
    def __init__(self):
        self.reset()
        self.fed = []
    def handle_data(self, d):
        self.fed.append(d)
    def get_data(self):
        return ' '.join(self.fed)

def strip_tags(html):
    """
    Returns the text of html with tags stripped.
    Customized to insert a space between adjacent tags after stripping.
    """
    html = html or ""
    s = MLStripper()
    s.feed(html)
    return s.get_data()

def text_preview(en, he):
    """
    Returns a jagged array terminating in dicts like {'he': '', 'en': ''} which offers preview
    text merging what's available in jagged string arrays 'en' and 'he'.
    """
    n_chars = 80
    en = [en] if isinstance(en, basestring) else [""] if en == [] or not isinstance(en, list) else en
    he = [he] if isinstance(he, basestring) else [""] if he == [] or not isinstance(he, list) else he

    def preview(section):
        """Returns a preview string for list section"""
        section =[s for s in section if isinstance(s, basestring)]
        section = " ".join(map(unicode, section))
        return strip_tags(section[:n_chars]).strip()

    if not any(isinstance(x, list) for x in en + he):
        return {'en': preview(en), 'he': preview(he)}
    else:
        zipped = map(None, en, he)
        return [text_preview(x[0], x[1]) for x in zipped]

def string_overlap(text1, text2):
    """
    Returns the number of characters that the end of text1 overlaps the beginning of text2.
    https://neil.fraser.name/news/2010/11/04/
    """
    # Cache the text lengths to prevent multiple calls.
    text1_length = len(text1)
    text2_length = len(text2)
    # Eliminate the null case.
    if text1_length == 0 or text2_length == 0:
        return 0
    # Truncate the longer string.
    if text1_length > text2_length:
        text1 = text1[-text2_length:]
    elif text1_length < text2_length:
        text2 = text2[:text1_length]
    # Quick check for the worst case.
    if text1 == text2:
        return min(text1_length, text2_length)

    # Start by looking for a single character match
    # and increase length until no match is found.
    best = 0
    length = 1
    while True:
        pattern = text1[-length:]
        found = text2.find(pattern)
        if found == -1:
            return best
        length += found
        if text1[-length:] == text2[:length]:
            best = length
            length += 1

def td_format(td_object):
    """
    Turn a timedelta object into a nicely formatted string.
    """
    seconds = int(td_object.total_seconds())
    periods = [
            ('year',        60*60*24*365),
            ('month',       60*60*24*30),
            ('day',         60*60*24),
            ('hour',        60*60),
            ('minute',      60),
            ('second',      1)
            ]

    strings=[]
    for period_name,period_seconds in periods:
            if seconds > period_seconds:
                    period_value , seconds = divmod(seconds,period_seconds)
                    if period_value == 1:
                            strings.append("%s %s" % (period_value, period_name))
                    else:
                            strings.append("%s %ss" % (period_value, period_name))

    return ", ".join(strings)


from turtle import Turtle, Screen, done, onclick, write, bgcolor, width
from genetic_project.model import Model
from genetic_project.constants import *
from typing import Any
from time import time_ns

best_fitness = -1
class ViewController:
    screen: Any
    pen: Turtle
    model: Model

    def __init__(self, model: Model):
        self.model = model
        self.screen = Screen()
        self.screen.setup(VIEW_WIDTH, VIEW_HEIGHT)
        self.screen.tracer(0, 0)
        self.screen.delay(0)
        self.screen.title("Najlepsi som")
        self.pen = Turtle()
        self.pen.hideturtle()
        self.pen.speed(0)
        bgcolor(0.1,0.1,0.1)

    def start_simulation(self) -> None:
        input("Press Enter to start simulation:")
        print("Press Ctrl+C to stop simulation: (duh)" )
        global best_fitness
        for generation in range(GENERATIONS_MAX):
            # print(f"generation: {generation}")
            if generation % GENERATION_PRINT_RATE == 0 or generation <= PRINT_FIRST_N_GENERATIONS:
                while not self.model.is_finished():
                    if PRINT_BEST_ONLY:
                        self.tick_best_only(generation)
                    else:
                        self.tick(generation)

                next_gen , best_fitness = self.model.next_generation()
                self.model = Model(next_gen)
            else:
                while not self.model.is_finished():
                    self.model.tick()
                next_gen , best_fitness = self.model.next_generation()
                if generation % GENERATION_PRINT_RATE >= (GENERATION_PRINT_RATE*3) // 4:
                    self.model = Model(next_gen, NO_MUTATION_ON_PRINTED_GENERATION)
                else:
                    self.model = Model(next_gen)

        done()

    def tick(self, generation) -> None:

        for _ in range(TICKS_PER_SCREEN_UPDATE):
            self.model.tick()
        self.pen.clear()

        for w in self.model.walls:
            draw_rec(self.pen, w.min_x, w.max_x, w.min_y, w.max_y)

        for robot in self.model.robots[:PRINT_ROBOTS_MAX]:
            self.pen.penup()
            self.pen.goto(robot.location.x, robot.location.y)
            self.pen.pendown()

            if not PRINT_DEAD_ROBOTS and not robot.alive_status:
                self.pen.color(ROBOT_COLOR if robot.alive_status else DEAD_ROBOT_COLOR)
                self.pen.dot(ROBOT_RADIUS / 3)
                continue

            self.pen.color(ROBOT_SPEED_COLOR)
            self.pen.setheading(robot.speed.to_angle())
            self.pen.forward(robot.speed.size() * TURTLE_SPEED_INDICATOR_CONSTANT)
            self.pen.backward(robot.speed.size() * TURTLE_SPEED_INDICATOR_CONSTANT)

            self.pen.color(ROBOT_COLOR if robot.alive_status else DEAD_ROBOT_COLOR)
            self.pen.width(8)
            self.pen.setheading(robot.acceleration.to_angle())
            self.pen.forward(robot.acceleration.size() * TURTLE_ACCELERATION_INDICATOR_CONSTANT)
            self.pen.backward(robot.acceleration.size() * TURTLE_ACCELERATION_INDICATOR_CONSTANT)
            self.pen.width(1)

            self.pen.color(ROBOT_COLOR if robot.alive_status else DEAD_ROBOT_COLOR)
            self.pen.dot(ROBOT_RADIUS)

        self.pen.penup()
        self.pen.goto(self.model.target.x, self.model.target.y)
        self.pen.pendown()
        self.pen.color("blue")
        self.pen.dot(TARGET_RADIUS)
        self.pen.penup()

        self.pen.goto(MIN_X + 20, MAX_Y - 20)
        self.pen.pendown()
        self.pen.color("white")
        self.pen.write(f"tick: #{self.model.ticks}", font=("Arial", 20, "normal"))
        self.pen.penup()
        self.pen.goto(MIN_X + 200, MAX_Y - 20)
        self.pen.pendown()
        self.pen.color("white")
        self.pen.write(f"generation: #{generation}", font=("Arial", 20, "normal"))
        self.pen.penup()
        self.pen.goto(MIN_X + 500, MAX_Y - 20)
        self.pen.pendown()
        self.pen.color("white")
        self.pen.write(f"best fitness: {best_fitness}", font=("Arial", 20, "normal"))

        self.screen.update()

        if self.model.is_finished():
            return

    def tick_best_only(self, generation) -> None:

        self.model.tick()
        self.pen.clear()

        for w in self.model.walls:
            draw_rec(self.pen, w.min_x, w.max_x, w.min_y, w.max_y)

        robot = self.model.robots[0]
        self.pen.penup()
        self.pen.goto(robot.location.x, robot.location.y)

        self.pen.pendown()
        self.pen.color("green")
        self.pen.setheading(robot.speed.to_angle())
        self.pen.forward(robot.speed.size() * TURTLE_SPEED_INDICATOR_CONSTANT)
        self.pen.backward(robot.speed.size() * TURTLE_SPEED_INDICATOR_CONSTANT)

        self.pen.color("red")
        self.pen.setheading(robot.acceleration.to_angle())
        self.pen.forward(robot.acceleration.size() * TURTLE_ACCELERATION_INDICATOR_CONSTANT)
        self.pen.backward(robot.acceleration.size() * TURTLE_ACCELERATION_INDICATOR_CONSTANT)

        self.pen.color("green" if robot.alive_status else "red")
        self.pen.dot(ROBOT_RADIUS)

        self.pen.penup()
        self.pen.goto(self.model.target.x, self.model.target.y)
        self.pen.pendown()
        self.pen.color("blue")
        self.pen.dot(TARGET_RADIUS)
        self.pen.penup()

        self.pen.goto(MIN_X + 20, MAX_Y - 20)
        self.pen.pendown()
        self.pen.color("white")
        self.pen.write(f"tick: #{self.model.ticks}", font=("Arial", 20, "normal"))
        self.pen.penup()
        self.pen.goto(MIN_X + 200, MAX_Y - 20)
        self.pen.pendown()
        self.pen.color("white")
        self.pen.write(f"generation: #{generation}", font=("Arial", 20, "normal"))

        self.screen.update()

def draw_rec(turtle, min_x, max_x, min_y, max_y):
    turtle.penup()
    turtle.begin_fill()
    turtle.color("gray")
    turtle.goto(min_x, min_y)
    turtle.pendown()
    turtle.goto(max_x, min_y)
    turtle.goto(max_x, max_y)
    turtle.goto(min_x, max_y)
    turtle.goto(min_x, min_y)
    turtle.end_fill()
    turtle.penup()


import pygame

class Counter:
    def __init__(self, screen, pos, nTotalItems, nCurrentItems, itemImage, spacerX, directionRight) -> None:
        self.screen = screen
        self.x, self.y = pos
        self.nTotalItems = nTotalItems
        self.nCurrentItems = nCurrentItems
        self.itemImage = itemImage
        self.spacerX = spacerX
        self.directionRight = directionRight

        self.imageWidth = self.itemImage.get_width()

        self.transparentItemImage = self.itemImage.copy()
        self.transparentItemImage.fill((255, 255, 255, 75), None, pygame.BLEND_RGBA_MULT)

    def drawImage(self, transparent, pos):
        self.screen.blit(self.transparentItemImage if transparent else self.itemImage, pos)

    def draw(self):
        if self.directionRight:
            for i in range(self.nTotalItems):
                x, y = self.x + i*self.imageWidth + i*self.spacerX, self.y
                if i < self.nCurrentItems:
                    self.drawImage(False, (x, y))

                else:
                    self.drawImage(True, (x, y))

        else:
            for i in range(self.nTotalItems):
                x, y = self.x+i*self.imageWidth+i*self.spacerX, self. y
                if i+1 > self.nTotalItems - self.nCurrentItems:
                    self.drawImage(False, (x, y))
                else:
                    self.drawImage(True, (x, y))

    def update(self):
        self.draw()


# https://colab.research.google.com/drive/1H9epx3rtmUVdhe0Qb_L5O2rQt8q7CpLZ

# Load All Libraries
from __future__ import print_function
from collections import Counter
import sklearn
import sklearn.datasets
import sklearn.ensemble
import numpy as np
import lime
import lime.lime_tabular
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.base import TransformerMixin
from sklearn.preprocessing import Imputer
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import accuracy_score
from sklearn import cross_validation
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from xgboost import XGBClassifier
import random
import re
import warnings
warnings.filterwarnings("ignore")

train_filename = 'train.csv'
test_filename = 'test.csv'
train_df = pd.read_csv(train_filename, header=0)
test_df = pd.read_csv(test_filename, header=0)
cols=train_df.columns
train_df['source']='train'
test_df['source']='test'
data = pd.concat([train_df, test_df],ignore_index=True)

data = data.fillna(0)

train_df = data.loc[data['source']=="train"]
test_df = data.loc[data['source']=="test"]

train_target = np.ravel(np.array(train_df['Churn'].values))
train_df = train_df.drop(['Churn'],axis=1)

float_columns=[]
cat_columns=[]
int_columns=[]

for i in train_df.columns:
    if i not in cols:
        continue
    if train_df[i].dtype == 'float' :
        float_columns.append(i)
    elif train_df[i].dtype == 'int64' or train_df[i].dtype == 'int32' or train_df[i].dtype == 'int16' or train_df[i].dtype == 'int8':
        int_columns.append(i)
    elif train_df[i].dtype == 'object':
        cat_columns.append(i)

train_cat_features = train_df[cat_columns]
train_float_features = train_df[float_columns]
train_int_features = train_df[int_columns]

train_cat_features_ver2 = train_cat_features.apply(LabelEncoder().fit_transform)

temp_1 = np.concatenate((train_cat_features_ver2,train_float_features),axis=1)
train_transformed_features = np.concatenate((temp_1,train_int_features),axis=1)
train_transformed_features = pd.DataFrame(data=train_transformed_features)

array = train_transformed_features.values
number_of_features = len(array[0])
X = array[:,0:number_of_features]
Y = train_target

validation_size = 0.2
seed = 7
X_train, X_validation, Y_train, Y_validation = cross_validation.train_test_split(X, Y, test_size=validation_size, random_state=seed)

scoring = 'accuracy'

# Model 1 - Logisitic Regression
model_logreg = LogisticRegression()
model_logreg.fit(X_train, Y_train)
#print("LR: " + str(accuracy_score(Y_validation, model_logreg.predict(X_validation))))

# Model 2 - RandomForest Classifier
#model_rf = RandomForestClassifier()
#model_rf.fit(X_train, Y_train)
#print("RF: " + str(accuracy_score(Y_validation, model_rf.predict(X_validation))))

# Model 3 - XGB Classifier
#model_xgb = XGBClassifier()
#model_xgb.fit(X_train, Y_train)
#print("XGB: " + str(accuracy_score(Y_validation, model_xgb.predict(X_validation))))

#model_logreg = LogisticRegression()
#model_logreg.fit(X, Y)

#model_rf = RandomForestClassifier()
#model_rf.fit(X, Y)

#model_xgb = XGBClassifier()
#model_xgb.fit(X, Y)

# LIME SECTION

predict_fn_logreg = lambda x: model_logreg.predict_proba(x).astype(float)

# Line-up the feature names
feature_names_cat = list(train_cat_features_ver2)
feature_names_float = list(train_float_features)
feature_names_int = list(train_int_features)

feature_names = sum([feature_names_cat, feature_names_float, feature_names_int], [])
#print(feature_names)

# Create the LIME Explainer
explainer = lime.lime_tabular.LimeTabularExplainer(X_train ,feature_names = feature_names,class_names=['Stay','Leave'],
                                                   categorical_features=cat_columns,
                                                   categorical_names=feature_names_cat, kernel_width=2)

# Pick the observation in the validation set for which explanation is required

# Get the explanation for Logistic Regression
k = 0
procn = 0
procp = 0
positive = []
dp = dict()
dn = dict()
negative = []
examples = 10
while k < len(X_validation) and (procn < examples or procp < examples):
    n = random.randint(0,len(X_validation)-1)
    k+=1
    exp = explainer.explain_instance(X_validation[n], predict_fn_logreg, num_features=6)
    #print(exp.as_list())
    if model_logreg.predict(X_validation[k].reshape(1,-1)) == 'Yes':
        for i in range(2):
            s = re.sub("[^a-zA-Z]+","",exp.as_list()[i][0])
            if s in feature_names_cat:
                if exp.as_list()[i][1] > 0:
                    final = s+" estado: "+str(data[s][n])
                    if final not in dp:
                        dp[final] = exp.as_list()[i][1]
                    else:
                        dp[final] = dp.get(final) +  exp.as_list()[i][1]
                    positive.append(s+" estado: "+str(data[s][n]))
            else:
                if exp.as_list()[i][1] > 0:
                    final = s+" estado: "+str(exp.as_list()[i][0])
                    if final not in dp:
                        dp[final] = exp.as_list()[i][1]
                    else:
                        dp[final] = dp.get(final) +  exp.as_list()[i][1]
                    positive.append(final)
        procp+=1
    else:
        for i in range(2):
            s = re.sub("[^a-zA-Z]+","",exp.as_list()[i][0])
            if s in feature_names_cat:
                if exp.as_list()[i][1] < 0:
                    final = s+" estado: "+str(data[s][n])
                    if final not in dn:
                        dn[final] = exp.as_list()[i][1]
                    else:
                        dn[final] = dn.get(final) +  exp.as_list()[i][1]
                    negative.append(s+" estado: "+str(data[s][n]))
            else:
                if exp.as_list()[i][1] < 0:
                    final = s+" estado: "+str(exp.as_list()[i][0])
                    if final not in dn:
                        dn[final] = exp.as_list()[i][1]
                    else:
                        dn[final] = dn.get(final) +  exp.as_list()[i][1]
                    negative.append(final)
        procn+=1

    #print(exp.as_list())

print("Fez o cliente sair: ")
for key,value in Counter(positive).most_common(3):
    print(str(key)+", surgiu "+str(value)+" vezes, puxando a probabilidade para essa classe em "+str("{:.2f}".format(abs(dp[key]/value) * 100))+"%")
print("Fez o cliente ficar: ")
for key,value in Counter(negative).most_common(3):
    print(str(key)+", surgiu "+str(value)+" vezes"+" vezes, puxando a probabilidade para essa classe em "+str("{:.2f}".format(abs(dn[key]/value) * 100))+"%")


#!/usr/bin/env python
# -*- coding:utf-8 -*-
from action.page_action import *
from util.log import *
from config.var_config import *
import traceback
import time

# 获取全局变量excel_obj
excel_obj = gl.get_value('excel_obj')

def data_driver_fun(data_sheet, step_sheet):
    """数据驱动"""
    # 获取数据表中是否执行列对象
    is_execute_column = excel_obj.get_column(data_sheet, dataSource_isExecute)
    # 获取数据源表中"电子邮件"列对象
    email_column = excel_obj.get_column(data_sheet, dataSource_email)
    # 获取测试步骤表中存在数据区域的行数
    step_rows_num = excel_obj.get_rows_num(step_sheet)
    # 记录成功执行的数据条数
    success_datas = 0
    # 记录被设置为执行的数据条数
    required_datas = 0
    try:
        # 遍历“联系人”表中的数据，再通过遍历“创建联系人”表中的步骤，添加联系人
        for idx, col_value in enumerate(is_execute_column[1:]):
            # idx下标从0开始
            # 遍历数据源表，准备进行数据驱动测试，因为第一行是标题行，所以从第二行开始遍历
            if col_value == 'y':
                logging.info('开始添加联系人 “%s”' % email_column[idx + 1])
                required_datas += 1
                # 定义记录执行成功步骤数变量
                success_steps = 0
                # 遍历“创建联系人”表中的步骤
                for index in range(2, step_rows_num + 1):
                    # 获取数据驱动测试步骤表中第index行对象
                    rows_value = excel_obj.get_row(step_sheet, index)
                    # 获取当前行中的关键字、定位方式、定位表达式式、操作值
                    key_word = rows_value[testStep_keyWord - 1]
                    location_type = rows_value[testStep_locationType - 1]
                    locator_exp = rows_value[testStep_locatorExp - 1]
                    operate_value = rows_value[testStep_operateValue - 1]

                    # 将操作值为数字类型的数据转成字符串类型，方便字符串拼接
                    if isinstance(operate_value, int):
                        operate_value = str(operate_value)
                    if operate_value != 'None' and operate_value.isalpha():
                        # 如果operate_value不为空且为字母字符串，从数据源表中根据坐标获取对应单元格的数据
                        coordinate = operate_value + str(idx + 2)
                        operate_value = excel_obj.get_cell_of_value(data_sheet, coordinate=coordinate)

                    # 构造需要执行的python语句，
                    # 对应的是page_action.py文件中的页面动作函数调用的字符串表示
                    tmp_str = "'%s', '%s'" % (location_type.lower(), locator_exp) \
                        if location_type != 'None' and locator_exp != 'None' else ""
                    if tmp_str:
                        tmp_str += ", '" + operate_value + "'" if operate_value != 'None' \
                                                                  and operate_value != '是' else ""
                    else:
                        tmp_str += "'" + operate_value + "'" if operate_value != 'None' else ""
                    run_str = key_word + "( " + tmp_str + ")"
                    try:
                        # 通过eval函数，将拼接的页面动作函数调用的字符串表示当成有效的python表达式执行，
                        # 从而执行测试步骤的sheet中关键字在page_action.py文件中对应的映射方法，来完成对页面元素的操作。
                        if operate_value != '否':
                            # 当operate_value值为“是”时，表示单击星标联系人复选框
                            eval(run_str)
                    except Exception:
                        logging.info('执行步骤“%s”发生异常: %s' % (rows_value[testStep_testStepDescribe - 1],
                                                           traceback.print_exc()))
                        write_test_result(data_sheet, idx + 2, 'dataSheet', 'failed')
                        break
                    else:
                        success_steps += 1
                        logging.info('执行步骤“%s”成功' % rows_value[testStep_testStepDescribe - 1])
                    time.sleep(0.5)
                if step_rows_num == success_steps + 1:
                    success_datas += 1
                    # 如果成功执行的步骤数等于步骤表中给出的步骤数
                    # 说明第idx+2行的数据执行通过，写入通过信息
                    write_test_result(data_sheet, idx + 2, 'dataSheet', 'pass')
                else:
                    # 写入失败信息
                    write_test_result(data_sheet, idx + 2, 'dataSheet', 'failed')
                time.sleep(0.1)
            else:
                # 将不需要执行的数据行的执行时间和执行结果单元格清空
                write_test_result(data_sheet, idx + 2, 'dataSheet', '')
        if required_datas == success_datas:
            # 只有当成功执行的数据条数等于被设置为需要执行的数据条数时，才表示调用数据驱动的测试用例执行通过
            return 1
        return 0
    except Exception as ex:
        raise ex

def key_word_fun(case_name, step_sheet):
    """关键字驱动"""
    # 获取"步骤sheet名"中的步骤数
    step_num = excel_obj.get_rows_num(step_sheet)
    # 记录测试用例col_value的步骤成功数
    successful_steps = 0
    logging.info('开始执行用例 "%s"，用例共%s步' % (case_name, step_num))
    try:
        for step in range(2, step_num + 1):
            # 第一行为标题行，无须执行，所以从2开始
            # 获取步骤sheet中第step行对象
            step_row = excel_obj.get_row(step_sheet, step)
            # 获取关键字、定位方式、定位表达式、操作值
            key_word = step_row[testStep_keyWord - 1]
            location_type = step_row[testStep_locationType - 1]
            locator_exp = step_row[testStep_locatorExp - 1]
            operate_value = step_row[testStep_operateValue - 1]

            # 将操作值为数字类型的数据转成字符串类型，方便字符串拼接
            if isinstance(operate_value, int):
                operate_value = str(operate_value)

            expression_str = ''
            # 构造需要执行的python语句，
            # 对应的是page_action.py文件中的页面动作函数调用的字符串表示
            if key_word and operate_value != 'None' and location_type == 'None' and locator_exp == 'None':
                expression_str = key_word + "('" + operate_value + "')"
            elif key_word and operate_value == 'None' and location_type == 'None' and locator_exp == 'None':
                expression_str = key_word + "()"
            elif key_word and location_type and operate_value and locator_exp == 'None':
                expression_str = key_word + "('" + location_type + "', '" + operate_value + "')"
            elif key_word and location_type and locator_exp and operate_value != 'None':
                expression_str = key_word + "('" + location_type + "', '" + \
                                 locator_exp + "', '" + operate_value + "')"
            elif key_word and location_type and locator_exp and operate_value == 'None':
                expression_str = key_word + "('" + location_type + "', '" + locator_exp + "')"
            try:
                # 在测试执行时间列写入执行时间
                excel_obj.write_cell_current_time(step_sheet, row_no=step, col_no=testStep_runTime)
                # 通过eval函数，将拼接的页面动作函数调用的字符串表示当成有效的python表达式执行，
                # 从而执行测试步骤的sheet中关键字在page_action.py文件中对象的映射方法，来完成对页面元素的操作。
                eval(expression_str)
            except Exception:
                # 获取异常屏幕截图
                capture_pic = capture_screen()
                # 获取详细的异常堆栈信息
                error_info = traceback.format_exc()
                # 在测试步骤Sheet中写入失败信息
                write_test_result(step_sheet, step, "caseStep", "failed", error_info, capture_pic)
                logging.info('案例：%s, 步骤: %s, 执行失败！' % (case_name,
                                                       step_row[testStep_testStepDescribe - 1]))
                break
            else:
                # 在测试步骤Sheet中写入成功信息
                write_test_result(step_sheet, step, 'caseStep', 'pass')
                # 每成功一步，successful_steps变量自增1
                successful_steps += 1
                logging.info('步骤: %s, 执行成功！' % step_row[testStep_testStepDescribe - 1])
                time.sleep(0.5)
        if successful_steps == step_num - 1:
            # 当测试用例步骤中所有的步骤都执行成功，才认为此测试用例执行通过
            return 1
        return 0
    except Exception as ex:
        raise ex

def write_test_result(sheet, row_no, col_no, test_result, error_info=None, pic_path=None):
    """用例或用例步骤执行结束后，向Excel中写入执行结果信息"""
    # 测试通过结果信息为绿色，失败为红色
    color_dict = {'pass': 'green', 'failed': 'red', '': None}
    # 因为“测试用例”工作表和“用例步骤sheet表”中都有测试执行时间和
    # 测试结果列，定义此字典对象是为了区分具体应该写哪个工作表。
    cols_dict = {
        'testCase': [testCase_runTime, testCase_testResult],
        'caseStep': [testStep_runTime, testStep_testResult],
        'dataSheet': [dataSource_runTime, dataSource_result]}
    try:
        # 在测试步骤sheet中，写入测试结果
        excel_obj.write_cell(sheet, content=test_result, row_no=row_no, col_no=cols_dict[col_no][1],
                             style=color_dict[test_result])
        time.sleep(0.1)
        if test_result == '':
            # 清空时间单元格内容
            excel_obj.write_cell(sheet, content='', row_no=row_no, col_no=cols_dict[col_no][0])
            time.sleep(0.1)
        else:
            # 在测试步骤sheet中，写入测试时间
            excel_obj.write_cell_current_time(sheet, row_no=row_no, col_no=cols_dict[col_no][0])
            time.sleep(0.1)
        if error_info and pic_path:
            # 在测试步骤sheet中，写入异常信息
            excel_obj.write_cell(sheet, content=error_info, row_no=row_no, col_no=testStep_errorInfo)
            time.sleep(0.1)
            # 在测试步骤sheet中，写入异常截图路径
            excel_obj.write_cell(sheet, content=pic_path, row_no=row_no, col_no=testStep_errorPic)
        else:
            if col_no == 'caseStep':
                # 在测试步骤sheet中，清空错误信息单元格
                excel_obj.write_cell(sheet, content='', row_no=row_no, col_no=testStep_errorInfo)
                time.sleep(0.1)
                # 在测试步骤sheet中，清空错误截图单元格
                excel_obj.write_cell(sheet, content='', row_no=row_no, col_no=testStep_errorPic)
    except Exception:
        logging.debug('写入Excel文件出错: %s' % traceback.print_exc())


import streamlit as st #all streamlit commands will be available through the "st" alias
import text_lib as glib #reference to local lib script

#
st.set_page_config(page_title="Text to Text") #HTML title
st.title("Text to Text") #page title

#
input_text = st.text_area("Input text", label_visibility="collapsed") #display a multiline text box with no label
go_button = st.button("Go", type="primary") #display a primary button

#
if go_button: #code in this if block will be run when the button is clicked

    with st.spinner("Working..."): #show a spinner while the code in this with block runs
        response_content = glib.get_text_response(input_content=input_text) #call the model through the supporting library

        st.write(response_content) #display the response content


import random as rd
import datetime as dt
import math
import sys

def get_seconds(time):
    time_digits = list(str(time))
    return int(time_digits[0])*60*60+int(time_digits[2])*10*60+int(time_digits[3])*60+int(time_digits[5])*10+int(time_digits[6])+int(time_digits[8])*0.1+int(time_digits[9])*0.01

def calculate(a, b, operation):
    if operation == "x": return a*b
    if operation == "+": return a+b
    if operation == "-": return a-b
    if operation == "^": return a**b
    #if operation == "/": return a/b

def calculation(operation, digit_1, digit_2, max_attempts):
    d_1 = "1"
    d_2 = "1"
    if digit_1 != 1:
        for x in range(digit_1-1):
            d_1 += "0"
    if digit_2 != 1:
        for x in range(digit_2-1):
            d_2 += "0"
    d_1 = int(d_1)
    d_2 = int(d_2)
    if operation == "^":
        d_2 = digit_2
    i=1
    times = []
    print("Push ENTER to start the timer!")
    inp = input()
    if len(inp) == 0:
        start_global = dt.datetime.now()
        count = 0
        global_count = 0
        while i>0:
            a = rd.randint(d_1+1, d_1*10-1)
            if operation != "^":
                b = rd.randint(d_2+1, d_2*10-1)
            else:
                b = digit_2
            print(a, operation, b)
            start = dt.datetime.now()
            inp = input()
            try:
                test_int = int(inp)
            except:
                return print("Attempt abortet! The correct answer would have been:", str(calculate(a,b,operation))+".")
            if len(inp) == 0:
                break
            if int(inp) == calculate(a,b,operation):
                stop = dt.datetime.now()
                times.append(round(get_seconds(stop-start),2))
                count+=1
                global_count += 1
                print("Correct! You took", round(get_seconds(stop-start),2), "seconds.")
            else:
                stop = dt.datetime.now()
                times.append("DNF")
                global_count += 1
                print("Wrong! Answer:", str(calculate(a,b,operation))+".","You took", round(get_seconds(stop-start),2), "seconds.")
            if  global_count == max_attempts:
                break
        stop_global = dt.datetime.now()
        print("\n")
        print("You got", count, "of", global_count, "correct in", stop_global-start_global)
        if count != 0:
            print("Ratio:", round(get_seconds(stop_global-start_global)/count, 2))
            print("Average of", len(times), "is:", average(times))
    else: return print("Attempt aborted!")

def count_list(lst, x):
    count = 0
    for ele in lst:
        if ele == x:
            count += 1
    return count

def average(values):
    length = len(values)
    number = math.ceil(0.05*length)
    num_dnf = count_list(values, "DNF")
    if num_dnf > number:
        return "DNF"
    if len(values) < 2:
        return "To short for average."
    num_bad = number - num_dnf
    for i in range(num_dnf):
        values.remove("DNF")
    values.sort()
    for i in range(num_bad):
        values.pop(-1)
    for i in range(number):
        values.pop(0)
    return round(sum(values)/len(values),2)

def help():
    print("""Arguments must be passed in the order as shown:    [operation] [digit_1] [digit_2] [attempts]
             - [operation] is a char in {+,-,x,^} (default=x).
             - [digit_1] is the number of digits (default=2).
             - [digit_2] is the number of digits (default=1).
             - [attempts] is the number of attempts (default=5).""")

if(len(sys.argv) == 5 and sys.argv[1] in ["+","-","x","^"] and sys.argv[2].isdigit() and sys.argv[3].isdigit() and sys.argv[4].isdigit()):
    calculation(str(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]))
else:
    help()


import django.contrib.auth.views
from django.conf import settings
from django.urls import include, path

urlpatterns = [
    path("", include('evap.evaluation.urls')),
    path("staff/", include('evap.staff.urls')),
    path("results/", include('evap.results.urls')),
    path("student/", include('evap.student.urls')),
    path("contributor/", include('evap.contributor.urls')),
    path("rewards/", include('evap.rewards.urls')),
    path("grades/", include('evap.grades.urls')),

    path("logout", django.contrib.auth.views.LogoutView.as_view(next_page="/"), name="django-auth-logout"),
    path("oidc/", include('mozilla_django_oidc.urls')),
]

if settings.DEBUG:
    urlpatterns += [path('development/', include('evap.development.urls'))]

    if settings.ENABLE_DEBUG_TOOLBAR:
        # pylint does not correctly evaluate this if, so it will raise an import-error on
        # GitHub actions and a useless-suppression on a vagrant setup. Ignore both cases.
        import debug_toolbar  # pylint: disable=import-error, useless-suppression
        urlpatterns += [path('__debug__/', include(debug_toolbar.urls))]


"""
ICAL pipeline
"""

results_dir = "./results/"

from rascil.data_models import PolarisationFrame, export_gaintable_to_hdf5

from rascil.processing_components import (
    export_image_to_fits,
    qa_image,
    qa_gaintable,
    create_image_from_visibility,
    create_blockvisibility_from_ms,
    image_gather_channels,
    create_calibration_controls,
)

from rascil.workflows import (
    ical_skymodel_list_rsexecute_workflow,
    weight_list_rsexecute_workflow,
)

from rascil.workflows.rsexecute.execution_support.rsexecute import rsexecute

import logging

def init_logging():
    logging.basicConfig(
        filename="%s/ska-pipeline.log" % results_dir,
        filemode="a",
        format="%(asctime)s.%(msecs)d %(name)s %(levelname)s %(message)s",
        datefmt="%H:%M:%S",
        level=logging.INFO,
    )

if __name__ == "__main__":
    log = logging.getLogger("rascil-logger")
    logging.info("Starting ICAL pipeline")

    rsexecute.set_client(use_dask=True)
    print(rsexecute.client)
    rsexecute.run(init_logging)

    nfreqwin = 8

    # Load data from previous simulation
    vis_list = [
        rsexecute.execute(create_blockvisibility_from_ms)(
            "%s/ska-pipeline_simulation_%d.ms" % (results_dir, v)
        )[0]
        for v in range(nfreqwin)
    ]

    vis_list = rsexecute.persist(vis_list)

    # Define image properties
    cellsize = 0.0003
    npixel = 1024
    pol_frame = PolarisationFrame("stokesI")
    model_list = [
        rsexecute.execute(create_image_from_visibility)(
            v, npixel=npixel, cellsize=cellsize, polarisation_frame=pol_frame
        )
        for v in vis_list
    ]
    model_list = rsexecute.persist(model_list)

    # Weight the data
    vis_list = weight_list_rsexecute_workflow(vis_list, model_list)

    imaging_context = "ng"

    # The calibration sequence is defined in a dictionary. A default
    # version is constructed using create_calibration_controls()
    controls = create_calibration_controls()
    controls["T"]["first_selfcal"] = 1
    controls["T"]["phase_only"] = True
    controls["T"]["timeslice"] = "auto"

    # Now we can define the graph for ICAL
    ical_list = ical_skymodel_list_rsexecute_workflow(
        vis_list,
        model_imagelist=model_list,
        context=imaging_context,
        scales=[0],
        algorithm="mmclean",
        nmoment=2,
        niter=1000,
        fractional_threshold=0.3,
        threshold=0.02,
        nmajor=5,
        gain=0.25,
        deconvolve_facets=1,
        deconvolve_overlap=0,
        timeslice="auto",
        psf_support=128,
        controls=controls,
        global_solution=False,
        calibration_context="T",
        do_selfcal=True,
        restored_output="list",
    )

    log.info("About to run ICAL workflow")
    result = rsexecute.compute(ical_list, sync=True)
    rsexecute.close()

    # The result is:
    #    (nchan * (residual_image, sumwt), nchan * restored_image, nchan * skymodel)
    residual = image_gather_channels([result[0][chan][0] for chan in range(nfreqwin)])
    restored = image_gather_channels([result[1][chan] for chan in range(nfreqwin)])
    deconvolved = image_gather_channels(
        [result[2][chan].image for chan in range(nfreqwin)]
    )
    gt_list = result[3]

    log.info(qa_image(deconvolved, context="Clean image cube"))
    export_image_to_fits(
        deconvolved, "%s/ska-ical_rsexecute_deconvolved_cube.fits" % (results_dir)
    )

    log.info(qa_image(restored, context="Restored clean image cube"))
    export_image_to_fits(
        restored, "%s/ska-ical_rsexecute_restored_cube.fits" % (results_dir)
    )

    log.info(qa_image(residual, context="Residual clean image cube"))
    export_image_to_fits(
        residual, "%s/ska-ical_rsexecute_residual_cube.fits" % (results_dir)
    )

    # The gaintable are nchan*{"T":gt}
    log.info(qa_gaintable(gt_list[0]["T"]))
    agt_list = [gt_list[chan]["T"] for chan in range(nfreqwin)]
    export_gaintable_to_hdf5(
        agt_list, "%s/ska-ical_rsexecute_gaintable.hdf" % (results_dir)
    )


import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from DragDrop import ListBox,ListItem,ListBox2
from GetAPI import GetAPIInfo
import json
from sys import stderr, stdout
from MainApp import startMain,disconnect
import traceback
from HelperUi import DialogBox
from Activate import userpassGetter
class WorkerSignals(QObject):
    finished = pyqtSignal()
    error = pyqtSignal(tuple)
    result = pyqtSignal(object)
class APIThread(QRunnable):
    def __init__(self):
        super(APIThread, self).__init__()
        self.signals = WorkerSignals()
    @pyqtSlot()
    def run(self):
        try:
            api_id, api_hash = GetAPIInfo()
        except:
            traceback.print_exc()
            exctype, value = sys.exc_info()[:2]
            self.signals.error.emit((exctype, value, traceback.format_exc()))
        else:
            self.signals.result.emit(api_id+" "+api_hash)  # Return the result of the processing
        finally:
            self.signals.finished.emit()  # Done
def showdialog():
    msg = QMessageBox()
    msg.setIcon(QMessageBox.Information)
    msg.setText("Email: xxx@gmail.com
 Link:Google
 Contact: +11111111111")
    msg.setInformativeText("Telegram API Bot")

    msg.setWindowTitle("Contact Details")
    msg.setStandardButtons(QMessageBox.Ok)
    retval = msg.exec_()
def LinkingA():
    msg = QMessageBox()
    msg.setIcon(QMessageBox.Information)
    msg.setText("Go To: www.installA.com
")
    msg.setWindowTitle("Install A")  #Title of Message box
    msg.setStandardButtons(QMessageBox.Ok)
    retval = msg.exec_()
def LinkingB():
    msg = QMessageBox()
    msg.setIcon(QMessageBox.Information)
    msg.setText("Go To: www.installB.com
")
    msg.setWindowTitle("Install B")  # Title of Message box
    msg.setStandardButtons(QMessageBox.Ok)
    retval = msg.exec_()
def mainMessage(text):
    msg = QMessageBox()
    msg.setIcon(QMessageBox.Information)
    msg.setText(text)
    msg.setWindowTitle("Information")  # Title of Message box
    msg.setStandardButtons(QMessageBox.Ok)
    retval = msg.exec_()

class Port(object):
    def __init__(self, view):
        self.view = view
    def flush(self):
        pass
    def write(self, *args):
        if args[0]!="\n":
            # self.view.append(str([*args])) # This line will highlight next line character in console "\n"
            self.view.append(*args)
class InOutWidget(QWidget):
    def __init__(self, parent,heading,limit):
        super().__init__(parent)
        layout = QHBoxLayout(self)
        self.label = QLabel(heading)
        self.label.setAlignment(Qt.AlignCenter)
        self.lineEdit = QLineEdit(limit)
        self.lineEdit.setMaximumWidth(50)
        layout.addWidget(self.label)
        layout.addWidget(self.lineEdit)
class MainWindow(QMainWindow):
    def __init__(self,parent = None):
        super(QMainWindow, self).__init__(parent)
        # self.showMaximized()
        self.showFullScreen()
        self.threadpool = QThreadPool()
        print("Multithreading with maximum %d threads" % self.threadpool.maxThreadCount())
        self.apiId = ''
        self.apiHash = ''
        f = open('data.json')
        data = json.load(f)
        if data['API ID']!='':
            self.apiId = data['API ID']
            self.apiHash = data['API Hash']
        self.channelsList = data["Channels"]
        self.getChannelProcess = None
        self.activated = False
        self.SetupUI()
        for i in range(12):
            count = 0
            if i%2==0:
                st = 'Input'
            else:
                st = 'Output'
            for k in data[st+str(i//2 +1)]:
                listItem = ListItem(self.listArr[i],k)
                self.listArr[i].setItemWidget(listItem,listItem.widget)
                count+=1
            self.headArr[i].lineEdit.setText(str(count))
            self.changedLimit(self.listArr[i],self.headArr[i].lineEdit)
            self.listArr[i].currSize =  int(self.headArr[i].lineEdit.text())

        self.styleSheet = ""
        with open("style.qss") as qss:
            self.styleSheet = qss.read()
        self.setStyleSheet(self.styleSheet)
        self.setWindowTitle("Window Title") #Set window title here.

    def SetupUI(self):
        self.centralWidget = QWidget(self)
        self.setCentralWidget(self.centralWidget)
        self.centralLayout = QVBoxLayout()
        self.centralWidget.setLayout(self.centralLayout)
        self.menuBar = QMenuBar()
        self.menuMenu = self.menuBar.addMenu("Menu")
        self.helpMenu = self.menuBar.addMenu("Help")
        activateAct = QAction('&System Check',self)
        activateAct.triggered.connect(self.ActivateFunc)
        self.menuMenu.addAction(activateAct)

        installAAct = QAction('Install A',self)
        installAAct.triggered.connect(self.InstallAFunc)
        self.menuMenu.addAction(installAAct)

        installBAct = QAction('Install B',self)
        installBAct.triggered.connect(self.InstallBFunc)
        self.menuMenu.addAction(installBAct)

        exitAct = QAction('&Exit', self)
        exitAct.triggered.connect(qApp.quit)
        self.menuMenu.addAction(exitAct)

        contactAct = QAction('Contact',self)
        contactAct.triggered.connect(self.ContactFunc)
        self.helpMenu.addAction(contactAct)

        self.horiLayout = QHBoxLayout()
        self.VLayout1 = QVBoxLayout()
        self.VLayout2 = QVBoxLayout()
        self.VLayout3 = QVBoxLayout()
        self.VLayout2Main = QVBoxLayout()
        #Creating 1st Vertical layout
        self.getAPIButton = QPushButton("GET API ID/HASH",self)
        self.getAPIButton.clicked.connect(lambda: self.getAPIFunc())
        self.horiPairLayout = QHBoxLayout()
        self.horiPairLayout.addWidget(self.getAPIButton)
        self.apiIDLabel = QLabel(self.apiId)
        self.apiIDLabel.setAlignment(Qt.AlignCenter)
        self.apiHashLabel = QLabel(self.apiHash)
        self.apiHashLabel.setAlignment(Qt.AlignCenter)
        self.getChannelButton = QPushButton("GET CHANNELS/GROUPS")
        self.getChannelButton.clicked.connect(lambda: self.getChannelFunc())
        self.tempHoriLayout = QHBoxLayout()
        self.numLineEdit = QLineEdit(self)
        self.numSendButton = QPushButton("SEND",self)
        self.numSendButton.clicked.connect(lambda: self.sendFunc(self.numLineEdit))
        self.codeLineEdit = QLineEdit(self)
        self.codeSendButton = QPushButton("Send",self)
        self.codeSendButton.clicked.connect(lambda:self.sendFunc(self.codeLineEdit))
        self.tempHoriLayout.addWidget(self.numLineEdit)
        self.tempHoriLayout.addWidget(self.numSendButton)
        self.tempHoriLayout.addWidget(self.codeLineEdit)
        self.tempHoriLayout.addWidget(self.codeSendButton)
        self.allChannelList = ListBox2(self)
        self.allChannelList.addItems(self.channelsList)
        self.VLayout1.addLayout(self.horiPairLayout)
        self.VLayout1.addWidget(self.apiIDLabel)
        self.VLayout1.addWidget(self.apiHashLabel)
        self.VLayout1.addWidget(self.getChannelButton)
        self.VLayout1.addLayout(self.tempHoriLayout)
        self.VLayout1.addWidget(self.allChannelList)
        #Creating 2nd Vertical layout
        self.inputHeadArr = []
        self.listArr = []
        self.inputListHead1 = InOutWidget(self,"FOR CHANNEL INPUT 1",'1')
        self.inputList1 = ListBox(self)
        self.inputListHead1.lineEdit.textChanged.connect(lambda : self.changedLimit(self.inputList1,self.inputListHead1.lineEdit))
        self.outputListHead1 = InOutWidget(self,"FOR CHANNEL OUTPUT 1",'1')
        self.outputList1 = ListBox(self)
        self.outputListHead1.lineEdit.textChanged.connect(lambda : self.changedLimit(self.outputList1,self.outputListHead1.lineEdit))

        self.inputListHead2 = InOutWidget(self,"FOR CHANNEL INPUT 2",'1')
        self.inputList2 = ListBox(self)
        self.inputListHead2.lineEdit.textChanged.connect(lambda : self.changedLimit(self.inputList2,self.inputListHead2.lineEdit))
        self.outputListHead2 = InOutWidget(self,"FOR CHANNEL OUTPUT 2",'1')
        self.outputList2 = ListBox(self)
        self.outputListHead2.lineEdit.textChanged.connect(lambda : self.changedLimit(self.outputList2,self.outputListHead2.lineEdit))

        self.inputListHead3 = InOutWidget(self,"FOR CHANNEL INPUT 3",'1')
        self.inputList3 = ListBox(self)
        self.inputListHead3.lineEdit.textChanged.connect(lambda : self.changedLimit(self.inputList3,self.inputListHead3.lineEdit))
        self.outputListHead3 = InOutWidget(self,"FOR CHANNEL OUTPUT 3",'1')
        self.outputList3 = ListBox(self)
        self.outputListHead3.lineEdit.textChanged.connect(lambda : self.changedLimit(self.outputList3,self.outputListHead3.lineEdit))

        self.inputListHead4 = InOutWidget(self,"FOR CHANNEL INPUT 4",'1')
        self.inputList4 = ListBox(self)
        self.inputListHead4.lineEdit.textChanged.connect(lambda : self.changedLimit(self.inputList4,self.inputListHead4.lineEdit))
        self.outputListHead4 = InOutWidget(self,"FOR CHANNEL OUTPUT 4",'1')
        self.outputList4 = ListBox(self)
        self.outputListHead4.lineEdit.textChanged.connect(lambda : self.changedLimit(self.outputList4,self.outputListHead4.lineEdit))

        self.inputListHead5 = InOutWidget(self,"FOR CHANNEL INPUT 5",'1')
        self.inputList5 = ListBox(self)
        self.inputListHead5.lineEdit.textChanged.connect(lambda : self.changedLimit(self.inputList5,self.inputListHead5.lineEdit))
        self.outputListHead5 = InOutWidget(self,"FOR CHANNEL OUTPUT 5",'1')
        self.outputList5 = ListBox(self)
        self.outputListHead5.lineEdit.textChanged.connect(lambda : self.changedLimit(self.outputList5,self.outputListHead5.lineEdit))

        self.inputListHead6 = InOutWidget(self,"FOR CHANNEL INPUT 6",'1')
        self.inputList6 = ListBox(self)
        self.inputListHead6.lineEdit.textChanged.connect(lambda : self.changedLimit(self.inputList6,self.inputListHead6.lineEdit))
        self.outputListHead6 = InOutWidget(self,"FOR CHANNEL OUTPUT 6",'1')
        self.outputList6 = ListBox(self)
        self.outputListHead6.lineEdit.textChanged.connect(lambda : self.changedLimit(self.outputList6,self.outputListHead6.lineEdit))
        self.listArr = [self.inputList1,self.outputList1,self.inputList2,self.outputList2,self.inputList3,self.outputList3,self.inputList4,self.outputList4,self.inputList5,self.outputList5,self.inputList6,self.outputList6]
        self.headArr = [self.inputListHead1,self.outputListHead1,self.inputListHead2,self.outputListHead2,self.inputListHead3,self.outputListHead3,self.inputListHead4,self.outputListHead4,self.inputListHead5,self.outputListHead5,self.inputListHead6,self.outputListHead6]
        self.VLayout2.addWidget(self.inputListHead1)
        self.VLayout2.addWidget(self.inputList1)
        self.VLayout2.addWidget(self.outputListHead1)
        self.VLayout2.addWidget(self.outputList1)
        self.VLayout2.addWidget(self.inputListHead2)
        self.VLayout2.addWidget(self.inputList2)
        self.VLayout2.addWidget(self.outputListHead2)
        self.VLayout2.addWidget(self.outputList2)
        self.VLayout2.addWidget(self.inputListHead3)
        self.VLayout2.addWidget(self.inputList3)
        self.VLayout2.addWidget(self.outputListHead3)
        self.VLayout2.addWidget(self.outputList3)
        self.VLayout2.addWidget(self.inputListHead4)
        self.VLayout2.addWidget(self.inputList4)
        self.VLayout2.addWidget(self.outputListHead4)
        self.VLayout2.addWidget(self.outputList4)
        self.VLayout2.addWidget(self.inputListHead5)
        self.VLayout2.addWidget(self.inputList5)
        self.VLayout2.addWidget(self.outputListHead5)
        self.VLayout2.addWidget(self.outputList5)
        self.VLayout2.addWidget(self.inputListHead6)
        self.VLayout2.addWidget(self.inputList6)
        self.VLayout2.addWidget(self.outputListHead6)
        self.VLayout2.addWidget(self.outputList6)
        self.scrollWid = QWidget()
        self.scrollWid.setLayout(self.VLayout2)
        self.scroll = QScrollArea()             # Scroll Area which contains the widgets, set as the centralWidget
        self.scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.scroll.setWidgetResizable(True)
        self.scroll.setWidget(self.scrollWid)
        self.VLayout2Main.addWidget(self.scroll)
        #Creating 3rd Vertical box
        self.mainTextBox = QTextBrowser(self)
        self.mainTextBox.setText("GET CHANNEL and START MAIN output will be shown here!")
        self.applyButton = QPushButton("Apply",self)
        self.applyButton.clicked.connect(lambda: self.applyFunc(1))
        self.startMainButton = QPushButton("Activate",self)
        self.startMainButton.setStyleSheet("background-color:red")
        self.startMainButton.clicked.connect(lambda: self.startM())
        self.stopButton = QPushButton("STOP",self)
        self.stopButton.clicked.connect(disconnect)
        self.showHereButton = QPushButton("Show Here",self)
        self.showHereButton.clicked.connect(lambda: self.showHereFunc())

        self.horiPairLayout2 = QHBoxLayout()
        self.horiPairLayout2.addWidget(self.applyButton)
        self.horiPairLayout2.addWidget(self.startMainButton)
        self.horiPairLayout2.addWidget(self.stopButton)
        self.mainTextBox.setReadOnly(True)
        self.VLayout3.addLayout(self.horiPairLayout2)
        self.VLayout3.addWidget(self.showHereButton)
        self.VLayout3.addWidget(self.mainTextBox)
        self.centralLayout.addWidget(self.menuBar)
        self.centralLayout.addLayout(self.horiLayout)
        self.horiLayout.addLayout(self.VLayout1)
        self.horiLayout.addLayout(self.VLayout2Main)
        self.horiLayout.addLayout(self.VLayout3)
    def ActivateFunc(self):
        print("Activate option clicked")
        dia = DialogBox(self)
        dia.show()
    def InstallAFunc(self):
        print("Install A option clicked")
        LinkingA()
    def InstallBFunc(self):
        print("Install B option clicked")
        LinkingB()
    def ContactFunc(self):
        showdialog()
        print("Contact option clicked")
    def DisplayAPI(self,s):
        api_id,api_hash = s.split(" ")
        self.apiIDLabel.setText(api_id)
        self.apiHashLabel.setText(api_hash)
        self.applyFunc(0)

    def getAPIFunc(self):
        print("GET API Pressed")
        apiThread = APIThread()
        apiThread.signals.result.connect(self.DisplayAPI)
        self.threadpool.start(apiThread)
    def getChannelFunc(self):
        api_id = self.apiIDLabel.text()
        api_hash = self.apiHashLabel.text()
        self.getChannelProcess = QProcess()
        self.getChannelProcess.readyReadStandardOutput.connect(self.handle_stdout)
        self.getChannelProcess.readyReadStandardError.connect(self.handle_stderr)
        self.getChannelProcess.finished.connect(self.updateChannelList)
        self.getChannelProcess.start("python",['GetChannels.py'])

    def startM(self):
        print(self.apiIDLabel.text())
        if self.apiIDLabel.text()=='':
            mainMessage("API ID and API Hash are not available")
        else:
            flag,key = userpassGetter()
            print(flag)
            if flag==True:
                self.startMainButton.setText("Start Main")
                self.startMainButton.setStyleSheet(self.styleSheet)
                self.startMainButton.clicked.connect(startMain)
                self.mainTextBox.setPlainText("Activated\nClick Start Main\n""After entring phone and code on Console press SHOW HERE!")
            else:
                mainMessage("Your key is: "+key+"\nGive this key to the Provider ")

    def handle_stderr(self):
        data = self.getChannelProcess.readAllStandardError()
        stderr = bytes(data).decode("utf8")
        self.mainTextBox.append(stderr)

    def handle_stdout(self):
        data = self.getChannelProcess.readAllStandardOutput()
        stdout = bytes(data).decode("utf8")
        print(stdout)
        self.mainTextBox.append(stdout)
    def sendFunc(self,edit):
        text = edit.text() + "\n"
        self.getChannelProcess.write(text.encode())
        self.mainTextBox.append(text)
    def showHereFunc(self):
        self.mainTextBox.setText("")
        sys.stdout = Port(self.mainTextBox)
        print("Logged in..")
    def updateChannelList(self):
        with open("data.json","r") as f:
            data = json.load(f)
            self.allChannelList.clear()
            self.allChannelList.addItems(data["Channels"])
        print("UI Updated!")

    def changedLimit(self,listW,textW):
        if textW.text()!='':
            listW.itemLimit = int(textW.text())

    def getItems(self,listWidget):
        items = []
        for index in range(listWidget.count()):
            items.append(listWidget.item(index).textLabel.text())
        return items
    def applyFunc(self,flag):
        f = open("data.json")
        data = json.load(f)
        f.close()
        if flag==0:
            data['API ID'] = self.apiIDLabel.text()
            data['API Hash'] = self.apiHashLabel.text()
            print("API ID ,Hash SAVED")
        else:
            data['Input1'] = self.getItems(self.inputList1)
            data['Input2'] = self.getItems(self.inputList2)
            data['Input3'] = self.getItems(self.inputList3)
            data['Input4'] = self.getItems(self.inputList4)
            data['Input5'] = self.getItems(self.inputList5)
            data['Input6'] = self.getItems(self.inputList6)
            data['Output1'] = self.getItems(self.outputList1)
            data['Output2'] = self.getItems(self.outputList2)
            data['Output3'] = self.getItems(self.outputList3)
            data['Output4'] = self.getItems(self.outputList4)
            data['Output5'] = self.getItems(self.outputList5)
            data['Output6'] = self.getItems(self.outputList6)
            print("INPUT/OUTPUT SAVED")

        with open("data.json", "w") as outfile:
            json.dump(data, outfile)

if __name__=="__main__":
    app = QApplication(sys.argv)
    pyqtRemoveInputHook()
    ui = MainWindow()
    ui.show()
    sys.exit(app.exec_())


import statsmodels.api as sm
import pandas as pd
from Data_prep import getDfRange
import warnings

def MarginalRegression(CT,Omics,filePath,by = "FC"):
    # CT: pd.DataFrame, index = samples, columns = cells
    # Omics: pd.DataFrame, index = genes, columns = cells
    # filePath: str, path to save the output
    # by: str, "pvalue" or "FC"
    assert by in ["pvalue","FC"], "Choose either pvalue or FC"
    assert (CT.index==Omics.columns).all, "CT and Omics have different samples"
    if max([abs(x) for x in getDfRange(Omics)]) >50:
        warnings.warn("Input data have large (|x|>50) value, please check")
    assert all(Omics.var(axis=1) != 0) , "Input data have zero variance, please check"
    OutMat = pd.DataFrame(index=Omics.index,columns=CT.columns)
    for cells in CT.columns:
        y = CT.loc[:,cells]
        for genes in Omics.index:
            # print(cells,",",genes)
            x = Omics.loc[genes,:]
            x = sm.add_constant(x)
            model = sm.OLS(y, x).fit()
            if by == "pvalue":
                OutMat.at[genes, cells] =  model.pvalues[1]
            else:
                OutMat.at[genes, cells] =  model.params[1]
    OutMat.to_csv(filePath,sep="\t")

# def getRegression_res(CT,Omics, filePath,pvalue = True,verbose=False):
#     if os.path.exists(filePath):
#         EVAPR_GEP_p = pd.read_table(filePath, index_col=0)
#     else:
#         EVAPR_GEP_p = MarginalRegression(CT, Omics, filePath=filePath,pvalue=pvalue)
#     return EVAPR_GEP_p

def getTopK_commonfeatures(K,*Res,by_pvalue,verbose=False):
    # K: int, number of features to select
    # Res: MarginalRegression output, marker matrix by pvalue or FC,
    #      can input multiple for taking interactions
    # by_pvalue: bool, True: select marker by pvalue, False: select marker by FC
    # verbose: bool,
    # return: list, common features
    studies_list = []
    for study_i in Res:
        v_min,v_max  = getDfRange(study_i)
        # by_pvalue = False
        if v_max < 1 and v_min >0 :
            by_pvalue = True
        print("select marker by pvalue") if by_pvalue else print("select marker by FC")
        target = set()
        study_i = study_i.abs()
        for names in study_i.columns:
            if by_pvalue:
                target |= set(study_i.nsmallest(K,names,keep = 'first').index)
            else:
                target |= set(study_i.nlargest(K,names,keep = 'first').index)
        studies_list.append(target)
    common = set.intersection(*map(set,studies_list))
    if verbose:
        print("#common features: ",len(common))
    return sorted(list(common))


import argparse
import os.path
import pandas
import plotly.express as px
from tkinter import *
from PIL import ImageTk,Image

VERSION = "0.1"

# Start
# Main Function
def gui():
    main_window = Tk()
    # size of the window
    main_window.geometry('670x480')
    main_window.title("Threat Calculator")
    # Menu Declaration
    menu = Menu(main_window)
    main_window.config(menu=menu)
    # Restart Program Function
    def restart_program():
        python = sys.executable
        os.execl(python, python, *sys.argv)
    menu.add_command(label="Main", command=restart_program)

    # Create Tkinter variables
    oppVar = StringVar(main_window)
    intVar = StringVar(main_window)
    capVar = StringVar(main_window)

    # Define Frames
    contentframe = LabelFrame(main_window, padx=5, pady=5)
    contentframe.grid(column=3, row=0, columnspan=5, rowspan=8, pady=15)
    resultframe = LabelFrame(main_window, padx=5, pady=5)
    resultframe.grid(row=7, column=0, columnspan=2)

    # Calc Function
    def calc():
        # Evaluate Intent
        intresult = 0
        if intVar.get() == "Low":
            intresult = 0
        elif intVar.get() == "Moderate":
            intresult = 1
        elif intVar.get() == "High":
            intresult = 2
        else:
            intresult = 3

        # Evaluate Opportunity
        oppresult = 0
        if oppVar.get() == "Low":
            oppresult = 0
        elif oppVar.get() == "Moderate":
            oppresult = 1
        elif oppVar.get() == "High":
            oppresult = 2
        else:
            oppresult = 3

        # Evaluate Capability
        capresult = 0
        if capVar.get() == "Low":
            capresult = 0
        elif capVar.get() == "Moderate":
            capresult = 1
        elif capVar.get() == "High":
            capresult = 2
        else:
            capresult = 3

        # Evaluate Severity based on criteria
        result = capresult + intresult + oppresult
        if result <= 2:
            severity = "Low"
        elif 2 < result <= 4:
            severity = "Moderate"
        elif 4 < result <= 6:
            severity = "High"
        else:
            severity = "Critical"

        # Evaluate Threat Nature
        if intresult > 1 and oppresult > 1 and capresult > 1:
            theat_type = "Imminent"
        elif intresult > 0 and oppresult > 0 and capresult <= 1:
            theat_type = "Insubstantial"
        elif intresult > 0 and capresult > 1:
            theat_type = "Impending"
        elif intresult == 0 and oppresult > 1 and capresult > 1:
            theat_type = "Potential"
        else:
            theat_type = "Nonexistent"
        final_result = "There is a " + severity + " " + theat_type + " Threat"

        #Output result to frame
        resultframe.config(text=final_result, font=("Helvetica", 9, "bold"))

    # Add image
    img = ImageTk.PhotoImage(Image.open("model.png"))
    Label(contentframe, image=img).grid()

    #row 1
    oppLabel = Label(main_window, text="Opportunity", font=("Helvetica", 12, "bold"), anchor=W, justify=LEFT)
    oppLabel.grid(row=0, column=0)

    # Dictionary with options
    oppchoices = ['Low', 'Moderate', 'High', 'Critical']
    oppVar.set('Low')  # set the default option
    popupMenu = OptionMenu(main_window, oppVar, *oppchoices)
    popupMenu.config(width=20)
    Label(main_window, text="Choose a rating").grid(row=0, column=1, pady=10)
    popupMenu.grid(row=1, column=0, columnspan=2)

    # row 2
    intLabel = Label(main_window, text="Intent", font=("Helvetica", 12, "bold"), anchor=W, justify=LEFT)
    intLabel.grid(row=2, column=0)

    # Dictionary with options
    intchoices = ['Low', 'Moderate', 'High', 'Critical']
    intVar.set('Low')  # set the default option
    popupMenu = OptionMenu(main_window, intVar, *intchoices)
    popupMenu.config(width=20)
    Label(main_window, text="Choose a rating").grid(row=2, column=1, pady=10)
    popupMenu.grid(row=3, column=0, columnspan=2)

    # row 3
    capLabel = Label(main_window, text="Capability", font=("Helvetica", 12, "bold"), anchor=W, justify=LEFT)
    capLabel.grid(row=4, column=0)

    # Dictionary with options
    capchoices = ['Low', 'Moderate', 'High', 'Critical']
    capVar.set('Low')  # set the default option
    popupMenu = OptionMenu(main_window, capVar, *capchoices)
    popupMenu.config(width=20)
    Label(main_window, text="Choose a rating").grid(row=4, column=1,  pady=10)
    popupMenu.grid(row=5, column=0, columnspan=2)

    #submit button
    submitButton = Button(main_window, text="Submit", font=("bold"), width=20, command=calc)
    submitButton.grid(row=6, column=0, columnspan=2, padx=10, pady=20)

    #Display Results
    Label(resultframe).grid(row=7, column=0, columnspan=2)

    main_window.mainloop()

if __name__ == '__main__':
    gui()


"""
safe_test.py by Dalofeco

Defines test cases for the provided pyutils_dalofeco package.
"""
from pyutils_dalofeco import Safe

class TestSafe:

    @staticmethod
    def test_keys_in_dict():

        # Define test dict
        test_dict = {
            'unique': 2,
            'other': 4,
            'me': 'da',
            'not_checked': None,
        }

        # Define valid test keys
        valid_test_keys = ['unique', 'other', 'me']
        invalid_test_keys = ['unique', 'other', 'not_here']
        improper_type_test_keys = [dict(), 2]

        # Assertion cases
        assert Safe.keys_in_dict(test_dict, valid_test_keys) is True
        assert Safe.keys_in_dict(test_dict, invalid_test_keys) is False
        assert Safe.keys_in_dict(test_dict, improper_type_test_keys) is False
        assert Safe.keys_in_dict(None, 22) is False

    @staticmethod
    def test_which_key_in_dict():

        # Define test dict
        test_dict = {
            'train': 2,
            'test': 4,
            'dev': 'da',
            'validation': None,
        }

        # Define valid test keys
        key_options = ['unique', 'train', 'me']
        multiple_key_options = ['train', 'test', 'dev']
        no_valid_key = ['quantum', 'theory', 'of', 23]
        no_valid_bad_type = ['quantum', 'theory', 'of', 23]

        # Test proper operation with only one key
        assert Safe.which_key_in_dict(test_dict, key_options) == 'train'

        # Test multiple key options to return the first match
        assert Safe.which_key_in_dict(
            test_dict, multiple_key_options,
        ) == 'train'

        # Test no valid outcomes with proper args
        assert not Safe.which_key_in_dict(test_dict, no_valid_key)

        # Test invalid key types
        assert not Safe.which_key_in_dict(test_dict, no_valid_bad_type)

        # Test empty lists and dicts
        assert not Safe.which_key_in_dict({}, [])

        # Test improper types
        assert not Safe.which_key_in_dict([], {})

    @staticmethod
    def test_is_domain():
        valid_domains = [
            'yahoo.com',
            'realtek.com',
            'googlemail.com',
            'gmail.org',
            'facebook.net',
            'legit.co.uk',
            'me.com',
            'labanca.es',
            'truestory.com',
            'yahoo.com',
            'example.com',
            'subdomain.example.com',
            'example-one.com',
            'example.name',
            'example.museum',
            'example.co.jp',
            'example.com',
        ]

        invalid_domains = [
            'temporary',
            '%^%#$',
            'example.com>', 'example',
            'example.com (Joe Smith)',
            'example',
            '-example.com',
            '111.222.333.44444',
            'example..com',
            '.red.com',
        ]

        # Test valid domains
        for valid_domain in valid_domains:
            assert Safe.is_domain(valid_domain)

        # Test invalid domains
        for invalid_domain in invalid_domains:
            assert not Safe.is_domain(invalid_domain)

        # Invalid type
        assert not Safe.is_domain(2)

    @staticmethod
    def test_is_ip_address():

        valid_ips = [
            '123.123.123.123',
            '8.8.8.8',
            '10.0.0.2',
            '172.45.223.59',
        ]

        invalid_ips = [
            '2.2.',
            '234.343.3333.23',
            '211.232.112.122.345',
        ]

        # Test valid ips
        for valid_ip in valid_ips:
            assert Safe.is_ip_address(valid_ip)

        # Test invalid ips
        for invalid_ip in invalid_ips:
            assert not Safe.is_ip_address(invalid_ip)

        # Test invalid data type
        assert not Safe.is_ip_address(2)

    @staticmethod
    def test_is_email():

        # Define valid emails of various formats in list
        valid_emails = [
            'hereiamagain@yahoo.com',
            'ten23-me@realtek.com',
            'wherever23@googlemail.com',
            'robertdeNIRO@gmail.org',
            'sur.prise@facebook.net',
            'this233453@legit.co.uk',
            'fearsomeguy33@me.com',
            'her.ew.ego@labanca.es',
            'herewego+red@truestory.com',
            '1234583@yahoo.com',
            'email@example.com',
            'firstname.lastname@example.com',
            'email@subdomain.example.com',
            'firstname+lastname@example.com',
            'email@123.123.123.123',
            '1234567890@example.com',
            'email@example-one.com',
            '_______@example.com',
            'email@example.name',
            'email@example.museum',
            'email@example.co.jp',
            'firstname-lastname@example.com',
            'slower234@234.com',
            'well23-@robust.com',
            'vad-vad_not_good@redrum.com',
            'thisi$cool@email.net',
            'email@example.web',
        ]

        # Define invalid emails of various formats in list
        invalid_emails = [
            '2stream.@gmail.org',
            'herewego@temporary',
            'thisi$cool@ema_il.net',
            'plainaddress',
            '#@%^%#$@#$@#.com',
            '@example.com',
            'Joe Smith <email@example.com>',
            'email.example.com',
            'email@example@example.com',
            '.email@example.com',
            'email.@example.com',
            'email..email@example.com',
            'あいうえお@example.com',
            'email@example.com (Joe Smith)',
            'email@example',
            'email@-example.com',
            'email@111.222.333.44444',
            'email@example..com',
            'Abc..123@example.com',
        ]

        # Assertion cases for all emails
        for valid_email in valid_emails:
            assert Safe.is_email(valid_email)
        for invalid_email in invalid_emails:
            assert not Safe.is_email(invalid_email)

        # Test for bad argument type
        assert not Safe.is_email(2)

    @staticmethod
    def test_is_namespace_email():

        # Define valid emails of various formats in list
        valid_emails = [
            'hereiamagain@{}.com',
            'ten23_me@{}.com',
            'wher.ever.23@{}.es',
            'robertdeNIRO@{}.org',
            'surprise@{}.net',
            'this233453@{}.co.uk',
            'fearsomeguy33@{}.com',
            'slower234@{}.com',
        ]

        # Define invalid emails of various formats in list
        invalid_emails = [
            '1234583@{}.com',
            '2stream@{}.org',
            '_rererealize@{}.net',
            'i-am-me@{}.co.uk',
            'herewego@{}',
            'notvalidcausedot.@{}.es',
            'fasternotslower_@{}.com',
            'well23-@{}.com',
            'thisi$cool@{}.net',
        ]

        # Define valid namespaces
        valid_namespaces = [
            'google', 'gmail', 'realtek',
            'however', 'twenty.coordinate', '2345',
        ]

        # Define invalid namespaces
        invalid_namespaces = ['rau*d', 'h&8']

        # Assertion cases for all emails
        for valid_email in valid_emails:
            for valid_namespace in valid_namespaces:
                assert Safe.is_valid_namespace_email(
                    valid_email.format(valid_namespace), valid_namespace,
                ) is True
            for invalid_namespace in invalid_namespaces:
                assert Safe.is_valid_namespace_email(
                    valid_email.format(
                        invalid_namespace,
                    ), invalid_namespace,
                ) is False

        for invalid_email in invalid_emails:
            for valid_namespace in valid_namespaces:
                assert Safe.is_valid_namespace_email(
                    invalid_email.format(valid_namespace), valid_namespace,
                ) is False
            for invalid_namespace in invalid_namespaces:
                assert Safe.is_valid_namespace_email(
                    invalid_email.format(
                        invalid_namespace,
                    ), invalid_namespace,
                ) is False

        # Test improper types
        assert Safe.is_valid_namespace_email(2, 'da') is False
        assert Safe.is_valid_namespace_email('do', dict()) is False


import functools

from absl.testing import absltest
import chex
import haiku as hk
import jax
import jax.numpy as jnp
from jax_privacy.src.dp_sgd import grad_clipping
from jax_privacy.src.dp_sgd import typing
import optax

NUM_SAMPLES = 4
NUM_CLASSES = 7
INPUT_SHAPE = (12, 12, 3)
MAX_NORM = 1e-4

def model_fn(inputs, num_classes):
  """Mini ConvNet."""
  out = hk.Conv2D(4, 3)(inputs)
  out = jax.nn.relu(out)
  out = hk.Conv2D(4, 3)(out)
  out = jax.nn.relu(out)
  out = jnp.mean(out, axis=[1, 2])
  out = hk.Linear(num_classes)(out)
  return out

def grad_clipped_per_sample_naive(forward_fn, clipping_norm):
  """Naive implementation for computing gradients clipped per-example."""
  grad_fn = jax.grad(forward_fn, has_aux=True)

  def accumulate(tree_acc, tree_new, coeff):
    return jax.tree_util.tree_map(
        lambda leaf_acc, leaf_new: leaf_acc + leaf_new * coeff,
        tree_acc,
        tree_new,
    )

  def clipped_grad_fn(params, network_state, rng_per_example, inputs):
    loss, (network_state, metrics) = forward_fn(
        params, network_state, rng_per_example, inputs)
    images, labels = inputs
    batch_size = len(images)
    grads = jax.tree_util.tree_map(jnp.zeros_like, params)
    grad_norms = []

    # compute one clipped gradient at a time
    for i in range(batch_size):
      # expand image: function expects a batch dimension
      input_i = (jnp.expand_dims(images[i], 0), labels[i])
      grad_i, unused_aux = grad_fn(
          params, network_state, rng_per_example, input_i)

      norm_grad_i = jnp.sqrt(
          sum(jnp.sum(x**2) for x in jax.tree_util.tree_leaves(grad_i)))

      # multiplicative factor equivalent to clipping norm
      coeff = jnp.minimum(1, clipping_norm / norm_grad_i) / batch_size

      # normalize by batch_size and accumulate
      grads = accumulate(grads, grad_i, coeff)
      grad_norms.append(optax.global_norm(grad_i))

    metrics = metrics.replace(
        per_example={
            'grad_norm': jnp.array(grad_norms),
            **metrics.per_example,
        }
    )
    return (loss, (network_state, metrics)), grads

  return clipped_grad_fn

class TestClippedGradients(chex.TestCase):
  """Check numerically that gradients are correctly clipped."""

  def setUp(self):
    super().setUp()

    rng_seq = hk.PRNGSequence(0)

    images = jax.random.normal(
        next(rng_seq), shape=(NUM_SAMPLES,) + INPUT_SHAPE)
    labels = jax.random.randint(
        next(rng_seq), shape=[NUM_SAMPLES], minval=0, maxval=NUM_CLASSES)
    labels_one_hot = hk.one_hot(labels, NUM_CLASSES)

    self.net = hk.transform_with_state(
        functools.partial(model_fn, num_classes=NUM_CLASSES))
    self.params, self.network_state = self.net.init(next(rng_seq), images)

    self.inputs = (images, labels_one_hot)
    self.rng_per_batch = next(rng_seq)
    self.rng_per_example = jax.random.fold_in(self.rng_per_batch, 1)

    self.tol = {'rtol': 1e-6, 'atol': 1e-6}

  def forward(self, params, state, rng_per_example, inputs):
    images, labels = inputs
    logits, state = self.net.apply(params, state, rng_per_example, images)
    loss_vector = optax.softmax_cross_entropy(logits, labels)
    metrics = typing.Metrics(
        per_example={'loss': loss_vector, 'a': jnp.ones([images.shape[0]])},
        scalars_avg={'loss': jnp.mean(loss_vector), 'b': jnp.ones([])},
    )
    return jnp.mean(loss_vector), (state, metrics)

  def forward_per_sample(self, params, state, rng_per_example, inputs):
    images, labels = inputs
    logits, state = self.net.apply(params, state, rng_per_example, images)
    loss_vector = optax.softmax_cross_entropy(logits, labels)
    metrics = typing.Metrics(
        per_example={'loss': loss_vector, 'a': jnp.ones([images.shape[0]])},
        scalars_avg={'loss': jnp.mean(loss_vector), 'b': jnp.ones([])},
    )
    return jnp.mean(loss_vector), (state, metrics)

  @chex.variants(with_jit=True, without_jit=True)
  def test_clipped_gradients(self):
    value_and_grad_fn = jax.value_and_grad(self.forward, has_aux=True)
    clipping_fn = grad_clipping.global_clipping(clipping_norm=MAX_NORM)

    grad_fn_1 = grad_clipping.value_and_clipped_grad_vectorized(
        value_and_grad_fn,
        clipping_fn,
    )

    grad_fn_2 = grad_clipping.value_and_clipped_grad_loop(
        value_and_grad_fn,
        clipping_fn,
    )

    grad_fn_3 = grad_clipped_per_sample_naive(
        self.forward,
        clipping_norm=MAX_NORM,
    )

    grad_fn_args = (
        self.params, self.network_state, self.rng_per_example, self.inputs)
    (loss_1, aux_1), grad_1 = self.variant(grad_fn_1)(*grad_fn_args)
    (loss_2, aux_2), grad_2 = self.variant(grad_fn_2)(*grad_fn_args)
    (loss_3, aux_3), grad_3 = self.variant(grad_fn_3)(*grad_fn_args)

    chex.assert_trees_all_close(loss_1, loss_2, loss_3, **self.tol)
    chex.assert_trees_all_close(aux_1, aux_2, aux_3, **self.tol)
    chex.assert_trees_all_close(grad_1, grad_2, grad_3, **self.tol)

  @chex.variants(with_jit=True, without_jit=True)
  def test_gradients_vectorized_and_loop_match_using_batch_rng(self):
    value_and_grad_fn = jax.value_and_grad(self.forward, has_aux=True)
    clipping_fn = lambda grads: (grads, optax.global_norm(grads))

    grad_fn_1 = grad_clipping.value_and_clipped_grad_vectorized(
        value_and_grad_fn,
        clipping_fn=clipping_fn,
    )

    grad_fn_2 = grad_clipping.value_and_clipped_grad_loop(
        value_and_grad_fn,
        clipping_fn=clipping_fn,
    )

    grad_fn_3 = grad_clipped_per_sample_naive(
        self.forward,
        clipping_norm=float('inf'),
    )

    grad_fn_args = (
        self.params, self.network_state, self.rng_per_example, self.inputs)
    (loss_1, aux_1), grad_1 = self.variant(grad_fn_1)(*grad_fn_args)
    (loss_2, aux_2), grad_2 = self.variant(grad_fn_2)(*grad_fn_args)
    (loss_3, aux_3), grad_3 = self.variant(grad_fn_3)(*grad_fn_args)

    chex.assert_trees_all_close(loss_1, loss_2, loss_3, **self.tol)
    chex.assert_trees_all_close(aux_1, aux_2, aux_3, **self.tol)
    chex.assert_trees_all_close(grad_1, grad_2, grad_3, **self.tol)

  @chex.variants(with_jit=True, without_jit=True)
  def test_gradients_vectorized_and_loop_match_using_per_sample_rng(self):
    clipping_fn = lambda grads: (grads, optax.global_norm(grads))

    grad_fn_1 = grad_clipping.value_and_clipped_grad_vectorized(
        jax.value_and_grad(self.forward_per_sample, has_aux=True),
        clipping_fn=clipping_fn,
    )

    grad_fn_2 = grad_clipping.value_and_clipped_grad_loop(
        jax.value_and_grad(self.forward_per_sample, has_aux=True),
        clipping_fn=clipping_fn,
    )

    grad_fn_args = (
        self.params, self.network_state, self.rng_per_example, self.inputs)
    (loss_1, aux_1), grad_1 = self.variant(grad_fn_1)(*grad_fn_args)
    (loss_2, aux_2), grad_2 = self.variant(grad_fn_2)(*grad_fn_args)

    chex.assert_trees_all_close(loss_1, loss_2, **self.tol)
    chex.assert_trees_all_close(aux_1, aux_2, **self.tol)
    chex.assert_trees_all_close(grad_1, grad_2, **self.tol)

@hk.transform_with_state
def simple_net(x):
  """A simple function that computes L = 3 * x + random noise."""
  key = hk.next_rng_key()
  noise = jax.random.normal(key, shape=x.shape)
  return jnp.mean(3 * x + noise), noise

class TestClippedGradientsPerBatchPerSampleRNG(chex.TestCase):
  """Check per-batch rng and per-sample rng are handled correctly."""

  def setUp(self):
    super().setUp()
    rng_seq = hk.PRNGSequence(0)
    self.inputs = jax.random.normal(next(rng_seq), shape=(NUM_SAMPLES, 10))
    self.params, self.state = simple_net.init(next(rng_seq), self.inputs)
    self.rng_per_batch = next(rng_seq)
    self.rng_per_example = jax.random.fold_in(self.rng_per_batch, 1)

    self.grad_fn_args = (self.params, self.state,
                         self.rng_per_example, self.inputs)
    self.no_clip = lambda grads: (grads, optax.global_norm(grads))

  @chex.variants(with_jit=True, without_jit=True)
  def test_per_sample_rng_produces_different_random_numbers(self):

    @functools.partial(jax.value_and_grad, has_aux=True)
    def value_and_grad_fn(params, state, rng_per_example, inputs):
      (loss, noise), state = simple_net.apply(
          params, state, rng_per_example, inputs)
      metrics = typing.Metrics(
          per_example={'noise': noise},
      )
      return loss, (state, metrics)

    with self.subTest('vectorized'):
      grad_fn = grad_clipping.value_and_clipped_grad_vectorized(
          value_and_grad_fn, clipping_fn=self.no_clip)
      (_, (_, metrics)), _ = self.variant(grad_fn)(*self.grad_fn_args)

      # Noise should be different across all samples.
      for i in range(1, NUM_SAMPLES):
        self.assertTrue(
            jnp.any(metrics.per_example['noise'][0]
                    != metrics.per_example['noise'][i]))

    with self.subTest('loop'):
      grad_fn = grad_clipping.value_and_clipped_grad_loop(
          value_and_grad_fn, clipping_fn=self.no_clip)
      (_, (_, metrics)), _ = self.variant(grad_fn)(*self.grad_fn_args)

      # Noise should be different across all samples.
      for i in range(1, NUM_SAMPLES):
        self.assertTrue(
            jnp.any(metrics.per_example['noise'][0]
                    != metrics.per_example['noise'][i]))

if __name__ == '__main__':
  absltest.main()


"""
Идея 4. Степени двойки
"""
"""
В последовательности натуральных чисел, не превосходящих 1000, найти количество пар,
сумма элементов в которых делится на m = 87 и элемент с бОльшим индексом больше элемента
с меньшим индексом.
"""

def get_bits_count(n):
    """
    Возвращает количество единиц в двоичной записи числа n.
    Источник: geeksforgeeks.org
    Таблица соответствий чисел от 0 до 15:
    Десятичное Двоичное Число единиц
    0          0        0
    1          1        1
    2          10       1
    3          11       2
    4          100      1
    5          101      2
    6          110      2
    7          111      3
    8          1000     1
    9          1001     2
    10         1010     2
    11         1011     3
    12         1100     2
    13         1101     3
    14         1110     3
    15         1111     4
    Зная количество единиц для числа из четырех цифр, рекурсивно посчитаем
    общее количество единиц путем постоянного деления на 16 = 2 ** 4.
    """
    number_of_bits = [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4]
    if n == 0:
        return 0
    return number_of_bits[n % 16] + get_bits_count(n // 16)

# Здесь все стандартно
n = int(input())
m = 87
total_count = 0
numbers = [0 for _ in range(m)]
for i in range(n):
    # Вводим число
    x = int(input())
    # r - остаток от деления текущего числа на m
    r = x % m
    # pr - "парный" остаток от деления
    pr = (m - r) % m
    # k - целая часть от деления x на m
    k = x // m
    # p - сокращение от power - степень двойки для данного числа
    # gp - степень двойки, больше этой степени нельзя брать числа
    p = gp = 2 ** k
    # Оговорено выше, что если остаток больше половины,
    # то число с таким же k, но парным остатком нам подойдет
    if r > pr:
        gp *= 2
    # Здесь опять все стандартно.
    total_count += get_bits_count(numbers[pr] % gp)
    numbers[r] += p

print(total_count)