import argparse
import os
import sys
import unittest

import pyscca

class FileTypeTests(unittest.TestCase):
  """Tests the file type."""

  def test_signal_abort(self):
    """Tests the signal_abort function."""
    scca_file = pyscca.file()

    scca_file.signal_abort()

  def test_open(self):
    """Tests the open function."""
    test_source = unittest.source
    if not test_source:
      raise unittest.SkipTest("missing source")

    scca_file = pyscca.file()

    scca_file.open(test_source)

    with self.assertRaises(IOError):
      scca_file.open(test_source)

    scca_file.close()

    with self.assertRaises(TypeError):
      scca_file.open(None)

    with self.assertRaises(ValueError):
      scca_file.open(test_source, mode="w")

  def test_open_file_object(self):
    """Tests the open_file_object function."""
    test_source = unittest.source
    if not test_source:
      raise unittest.SkipTest("missing source")

    if not os.path.isfile(test_source):
      raise unittest.SkipTest("source not a regular file")

    scca_file = pyscca.file()

    with open(test_source, "rb") as file_object:

      scca_file.open_file_object(file_object)

      with self.assertRaises(IOError):
        scca_file.open_file_object(file_object)

      scca_file.close()

      with self.assertRaises(TypeError):
        scca_file.open_file_object(None)

      with self.assertRaises(ValueError):
        scca_file.open_file_object(file_object, mode="w")

  def test_close(self):
    """Tests the close function."""
    test_source = unittest.source
    if not test_source:
      raise unittest.SkipTest("missing source")

    scca_file = pyscca.file()

    with self.assertRaises(IOError):
      scca_file.close()

  def test_open_close(self):
    """Tests the open and close functions."""
    test_source = unittest.source
    if not test_source:
      return

    scca_file = pyscca.file()

    # Test open and close.
    scca_file.open(test_source)
    scca_file.close()

    # Test open and close a second time to validate clean up on close.
    scca_file.open(test_source)
    scca_file.close()

    if os.path.isfile(test_source):
      with open(test_source, "rb") as file_object:

        # Test open_file_object and close.
        scca_file.open_file_object(file_object)
        scca_file.close()

        # Test open_file_object and close a second time to validate clean up on close.
        scca_file.open_file_object(file_object)
        scca_file.close()

        # Test open_file_object and close and dereferencing file_object.
        scca_file.open_file_object(file_object)
        del file_object
        scca_file.close()

  def test_get_format_version(self):
    """Tests the get_format_version function and format_version property."""
    test_source = unittest.source
    if not test_source:
      raise unittest.SkipTest("missing source")

    scca_file = pyscca.file()

    scca_file.open(test_source)

    format_version = scca_file.get_format_version()
    self.assertIsNotNone(format_version)

    self.assertIsNotNone(scca_file.format_version)

    scca_file.close()

  def test_get_executable_filename(self):
    """Tests the get_executable_filename function and executable_filename property."""
    test_source = unittest.source
    if not test_source:
      raise unittest.SkipTest("missing source")

    scca_file = pyscca.file()

    scca_file.open(test_source)

    executable_filename = scca_file.get_executable_filename()
    self.assertIsNotNone(executable_filename)

    self.assertIsNotNone(scca_file.executable_filename)

    scca_file.close()

  def test_get_prefetch_hash(self):
    """Tests the get_prefetch_hash function and prefetch_hash property."""
    test_source = unittest.source
    if not test_source:
      raise unittest.SkipTest("missing source")

    scca_file = pyscca.file()

    scca_file.open(test_source)

    prefetch_hash = scca_file.get_prefetch_hash()
    self.assertIsNotNone(prefetch_hash)

    self.assertIsNotNone(scca_file.prefetch_hash)

    scca_file.close()

  def test_get_run_count(self):
    """Tests the get_run_count function and run_count property."""
    test_source = unittest.source
    if not test_source:
      raise unittest.SkipTest("missing source")

    scca_file = pyscca.file()

    scca_file.open(test_source)

    run_count = scca_file.get_run_count()
    self.assertIsNotNone(run_count)

    self.assertIsNotNone(scca_file.run_count)

    scca_file.close()

  def test_get_number_of_file_metrics_entries(self):
    """Tests the get_number_of_file_metrics_entries function and number_of_file_metrics_entries property."""
    test_source = unittest.source
    if not test_source:
      raise unittest.SkipTest("missing source")

    scca_file = pyscca.file()

    scca_file.open(test_source)

    number_of_file_metrics_entries = scca_file.get_number_of_file_metrics_entries()
    self.assertIsNotNone(number_of_file_metrics_entries)

    self.assertIsNotNone(scca_file.number_of_file_metrics_entries)

    scca_file.close()

  def test_get_number_of_filenames(self):
    """Tests the get_number_of_filenames function and number_of_filenames property."""
    test_source = unittest.source
    if not test_source:
      raise unittest.SkipTest("missing source")

    scca_file = pyscca.file()

    scca_file.open(test_source)

    number_of_filenames = scca_file.get_number_of_filenames()
    self.assertIsNotNone(number_of_filenames)

    self.assertIsNotNone(scca_file.number_of_filenames)

    scca_file.close()

  def test_get_number_of_volumes(self):
    """Tests the get_number_of_volumes function and number_of_volumes property."""
    test_source = unittest.source
    if not test_source:
      raise unittest.SkipTest("missing source")

    scca_file = pyscca.file()

    scca_file.open(test_source)

    number_of_volumes = scca_file.get_number_of_volumes()
    self.assertIsNotNone(number_of_volumes)

    self.assertIsNotNone(scca_file.number_of_volumes)

    scca_file.close()

if __name__ == "__main__":
  argument_parser = argparse.ArgumentParser()

  argument_parser.add_argument(
      "source", nargs="?", action="store", metavar="PATH",
      default=None, help="path of the source file.")

  options, unknown_options = argument_parser.parse_known_args()
  unknown_options.insert(0, sys.argv[0])

  setattr(unittest, "source", options.source)

  unittest.main(argv=unknown_options, verbosity=2)


# 씨름선수(그리디)

def solution(n, p):
    p = sorted(p, key=lambda x:x[1], reverse=True)
    cnt = 1
    temp = p[0][0]
    for i in range(1, n):
        if temp < p[i][0]:
            cnt += 1
            temp = p[i][0]
    return cnt

n = int(input())
p = [list(map(int, input().split())) for _ in range(n)]
print(solution(n, p))


# Created by: Aditya Dua
# 25 July, 2017
"""
Test module for poses: SO2, SE2, SO3 and SE3
"""
import unittest
import numpy as np
from .. import pose
from .test_common import matrix_mismatch_string_builder
from .test_common import matrices_equal
from .. import transforms as tr
from random import uniform

class TestSE2(unittest.TestCase):
    def test_pose_se2_constructor_no_args(self):
        obj = pose.SE2()
        exp_mat = np.asmatrix(np.eye(3, 3))
        rec_mat = obj.data[0]
        if not matrices_equal(rec_mat, exp_mat, ):
            output_str = matrix_mismatch_string_builder(rec_mat, exp_mat)
            self.fail(output_str)

class TestSE3(unittest.TestCase):
    def test_pose_se3_constructor_no_args(self):
        obj = pose.SE3()
        exp_mat = np.asmatrix(np.eye(4, 4))
        rec_mat = obj.data[0]
        if not matrices_equal(rec_mat, exp_mat, ):
            output_str = matrix_mismatch_string_builder(rec_mat, exp_mat)
            self.fail(output_str)

class TestSO3(unittest.TestCase):
    # TODO Validate tests on matrices other than identity as well!!

    def test_pose_so3_constructor_no_args(self):
        obj = pose.SO3()
        exp_mat = np.asmatrix(np.eye(3, 3))
        rec_mat = obj.data[0]
        if not matrices_equal(rec_mat, exp_mat, ):
            output_str = matrix_mismatch_string_builder(rec_mat, exp_mat)
            self.fail(output_str)

    def test_pose_so3_constructor_so3_object_length(self):
        obj1 = pose.SO3()  # TODO
        obj2 = pose.SO3(obj1)
        self.assertEqual(obj1.length, obj2.length)

    def test_pose_so3_constructor_so3_object_data(self):
        obj1 = pose.SO3()  # TODO
        obj2 = pose.SO3(obj1)
        for i in range(obj2.length):
            if not np.array_equal(obj1.data[i], obj2.data[i]):
                output_str = matrix_mismatch_string_builder(
                    obj2.data[i], obj1.data[i])
                self.fail(output_str)

    def test_pose_so3_constructor_so3_list(self):
        self.fail("Yet to be implemented")

    def test_pose_so3_constructor_rot_matrix(self):
        rot = tr.rotx(uniform(0, 360), 'deg')
        obj = pose.SO3(rot)
        if not matrices_equal(rot, obj.data[0], ):
            output_str = matrix_mismatch_string_builder(obj.data[0], rot)
            self.fail(output_str)

    def test_pose_so3_constructor_rot_matrix_list(self):
        rot_list = []
        for i in range(5):
            rot_list.append(tr.rotx(uniform(0, 360), unit='deg'))
        obj = pose.SO3(rot_list)
        for i in range(obj.length):
            if not matrices_equal(obj.data[i], rot_list[i], ):
                output_str = matrix_mismatch_string_builder(
                    obj.data[i], rot_list[i])
                self.fail(output_str)

    def test_pose_so3_constructor_se3_length(self):
        objse3 = pose.SE3()
        objso3 = pose.SO3(objse3)
        self.assertEqual(objse3.length, objso3.length)

    def test_pose_so3_constructor_se3_data(self):
        objse3 = pose.SE3()
        objso3 = pose.SO3(objse3)
        rot_mats = []
        for each in objse3:
            rot_mats.append(tr.t2r(each))
        for i in range(objso3.length):
            if not np.array_equal(rot_mats[i], objso3.data[i]):
                output_str = matrix_mismatch_string_builder(
                    objso3.data[i], rot_mats[i])
                self.fail(output_str)

    def test_pose_so3_constructor_se3_list(self):
        self.fail("Not yet implemented")

    def test_pose_so3_constructor_rx(self):
        theta = uniform(0, 360)
        rotx = tr.rotx(theta, unit='deg')
        obj = pose.SO3.Rx(theta, unit='deg')
        if not matrices_equal(obj.data[0], rotx, ):
            output_str = matrix_mismatch_string_builder(obj.data[0], rotx)
            self.fail(output_str)

    def test_pose_so3_constructor_rx_list(self):
        theta_list = [uniform(0, 360) for i in range(5)]  # list comprehensions
        rotx_list = [tr.rotx(theta, unit='deg') for theta in theta_list]
        obj = pose.SO3.Rx(theta_list, unit='deg')
        for i in range(obj.length):
            if not matrices_equal(obj.data[i], rotx_list[i], ):
                output_str = matrix_mismatch_string_builder(
                    obj.data[i], rotx_list[i])
                self.fail(output_str)

    def test_pose_so3_constructor_ry(self):
        theta = uniform(0, 360)
        roty = tr.roty(theta, unit='deg')
        obj = pose.SO3.Ry(theta, unit='deg')
        if not matrices_equal(obj.data[0], roty, ):
            output_str = matrix_mismatch_string_builder(obj.data[0], roty)
            self.fail(output_str)

    def test_pose_so3_constructor_ry_list(self):
        theta_list = [uniform(0, 360) for i in range(5)]  # list comprehensions
        roty_list = [tr.roty(theta, unit='deg') for theta in theta_list]
        obj = pose.SO3.Ry(theta_list, unit='deg')
        for i in range(obj.length):
            if not matrices_equal(obj.data[i], roty_list[i], ):
                output_str = matrix_mismatch_string_builder(
                    obj.data[i], roty_list[i])
                self.fail(output_str)

    def test_pose_so3_constructor_rz(self):
        theta = uniform(0, 360)
        rotz = tr.rotz(theta, unit='deg')
        obj = pose.SO3.Rz(theta, unit='deg')
        if not matrices_equal(obj.data[0], rotz, ):
            output_str = matrix_mismatch_string_builder(obj.data[0], rotz)
            self.fail(output_str)

    def test_pose_so3_constructor_rz_list(self):
        theta_list = [uniform(0, 360) for i in range(5)]  # list comprehensions
        rotz_list = [tr.rotz(theta, unit='deg') for theta in theta_list]
        obj = pose.SO3.Rz(theta_list, unit='deg')
        for i in range(obj.length):
            if not matrices_equal(obj.data[i], rotz_list[i], ):
                output_str = matrix_mismatch_string_builder(
                    obj.data[i], rotz_list[i])
                self.fail(output_str)

    def test_pose_so3_constructor_rand(self):
        obj1 = pose.SO3.rand()
        obj2 = pose.SO3.rand()
        if matrices_equal(obj1.data[0], obj2.data[0], ):
            self.fail("SO3.rand() show produces random poses.")

    def test_pose_so3_constructor_eul(self):
        # obj = pose.SO3.eul([uniform(0, 360), uniform(0, 360), uniform(0, 360)], unit='deg')
        self.fail("Test not defined")

    def test_pose_so3_constructor_oa(self):
        self.fail("Not implemented yet")

    def test_pose_so3_constructor_rpy(self):
        mat = np.matrix([[0.7259, 0.4803, 0.4924], [
            0.3536, 0.3536, -0.8660], [-0.5900, 0.8027, 0.0868]])
        obj = pose.SO3.rpy(thetas=[45, 60, 80], order='camera', unit='deg')
        if not matrices_equal(obj.data[0], mat, decimal=4):
            output_str = matrix_mismatch_string_builder(obj.data[0], mat)
            self.fail(output_str)

    def test_pose_so3_constructor_rpy_list(self):
        mat = [0, 0]
        mat[0] = np.matrix([[-0.2248, 0.3502, 0.9093],
                            [-0.7637, -0.6429, 0.0587], [0.6051, -0.6812, 0.4120]])
        mat[1] = np.matrix([[-0.1854, 0.2147, -0.9589],
                            [-0.9018, -0.4248, 0.0793], [-0.3904, 0.8794, 0.2724]])
        obj = pose.SO3.rpy([[1, 2, 3], [4, 5, 6]], order='arm')
        for i in range(obj.length):
            if not matrices_equal(obj.data[i], mat[i], decimal=4):
                output_str = matrix_mismatch_string_builder(
                    obj.data[i], mat[i])
                self.fail(output_str)

    def test_pose_so3_constructor_angvec(self):
        self.fail("Not implemented yet")

    def test_pose_so3_property_zero(self):
        self.fail("Not implemented yet")

    def test_pose_so3_property_isSE(self):
        obj = pose.SO3()
        if obj.isSE:
            self.fail("Is not a SE object.")

    def test_pose_so3_property_isSym(self):
        self.fail("Not implemented yet")

    def test_pose_so3_det(self):
        obj = pose.SO3.Rx(theta=80, unit='deg')
        det = obj.det()
        if det != 1:
            self.fail("Expected determinant value: 1.\n"
                      "Received determinant value: det")

    def test_pose_so3_rotation(self):
        obj = pose.SO3.Rx(theta=45, unit='deg')
        exp_rot = tr.rotx(theta=45, unit='deg')
        rec_rot = obj.rotation()
        if not matrices_equal(rec_rot, exp_rot):
            output_str = matrix_mismatch_string_builder(rec_rot, exp_rot)
            self.fail(output_str)

    def test_pose_so3_rotation_list(self):
        obj = pose.SO3.Rx(theta=[70, 80], unit='deg')
        rot = [0, 0]
        rot[0] = tr.rotx(theta=70, unit='deg')
        rot[1] = tr.rotx(theta=80, unit='deg')
        for i in range(obj.length):
            if not matrices_equal(obj.data[i], rot[i]):
                output_str = matrix_mismatch_string_builder(
                    obj.data[i], rot[i])
                self.fail(output_str)

    def test_pose_so3_tr_matrix(self):
        obj = pose.SO3.Rx(theta=45, unit='deg')
        mat = np.matrix([[1.0000, 0, 0, 0], [0, 0.7071, -0.7071, 0], [0, 0.7071, 0.7071, 0], [0, 0, 0, 1.0000]])
        if not matrices_equal(obj.t_matrix(), mat, decimal=4):
            output_str = matrix_mismatch_string_builder(obj.t_matrix(), mat)
            self.fail(output_str)

    def test_pose_so3_eig(self):
        self.fail("Not implemented yet")

    def test_pose_so3_log(self):
        self.fail("Not implemented yet")

    def test_pose_so3_inv(self):
        self.fail("Not implemented yet")

    def test_pose_so3_interp(self):
        self.fail("Not implemented yet")

    def test_pose_so3_simplify(self):
        self.fail("Not implemented yet")

    def test_pose_so3_static_check(self):  # TODO Check is necessary
        self.fail("Not implemented yet")

    def test_pose_so3_static_rx(self):
        self.fail("Not implemented yet")

    def test_pose_so3_static_ry(self):
        self.fail("Not implemented yet")

    def test_pose_so3_static_rz(self):
        self.fail("Not implemented yet")

    def test_pose_so3_static_rpy(self):
        self.fail("Not implemented yet")

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


import win32com.client

def moverrechazado():
    outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
    root_folder = outlook.Folders.Item(1)

    inbox = outlook.GetDefaultFolder(6)
    Actas = root_folder.Folders['RECHAZADO']
    messages = inbox.Items

    for message in messages:
        if 'Rechazado' in message.Subject:
            message.Move(Actas)


n=int(input())
for x in range(0,n):
    num=int(input())
    binaryN=list(bin(num))
    for i in range(2,len(binaryN)):
        if binaryN[i]=="1":
            binaryN[i]="0"
        else:
            binaryN[i]="1"
    numR=int("".join(binaryN),2)
    print(numR,end=" ")
    print(numR+num)


from ps4a import *
import time

#
#
# Problem #6: Computer chooses a word
#
#
def compChooseWord(hand, wordList, n):
    """
    Given a hand and a wordList, find the word that gives
    the maximum value score, and return it.

    This word should be calculated by considering all the words
    in the wordList.

    If no words in the wordList can be made from the hand, return None.

    hand: dictionary (string -> int)
    wordList: list (string)
    n: integer (HAND_SIZE; i.e., hand size required for additional points)

    returns: string or None
    """
    # Create a new variable to store the maximum score seen so far (initially 0)
    maxScore = 0

    # Create a new variable to store the best word seen so far (initially None)
    bestWord = None

    # For each word in the wordList
    for word in wordList:

        # If you can construct the word from your hand
        # (hint: you can use isValidWord, or - since you don't really need to test if the word is in the wordList - you can make a similar function that omits that test)
        if isValidWord(word, hand, wordList):
            # Find out how much making that word is worth
            score = getWordScore(word, n)
            # If the score for that word is higher than your best score
            if score > maxScore:
                # Update your best score, and best word accordingly
                maxScore = score
                bestWord = word

    # return the best word you found.
    return bestWord

def compPlayHand(hand, wordList, n):
    """
    Allows the computer to play the given hand, following the same procedure
    as playHand, except instead of the user choosing a word, the computer
    chooses it.

    1) The hand is displayed.
    2) The computer chooses a word.
    3) After every valid word: the word and the score for that word is
    displayed, the remaining letters in the hand are displayed, and the
    computer chooses another word.
    4)  The sum of the word scores is displayed when the hand finishes.
    5)  The hand finishes when the computer has exhausted its possible
    choices (i.e. compChooseWord returns None).

    hand: dictionary (string -> int)
    wordList: list (string)
    n: integer (HAND_SIZE; i.e., hand size required for additional points)
    """
    # Keep track of the total score
    score = 0
    inputWord = "zzzz"

    # As long as there are still letters left in the hand:
    while inputWord != None:

        # Display the hand
        print('Current Hand: '),
        displayHand(hand),

        # If hand has only one letter, end the game
        lenHand = calculateHandlen(hand)
        if lenHand == 1:
            break

        # Have computer choose the word
        inputWord = compChooseWord(hand, wordList, n)

        # If not a valid word, end the loop
        if not isValidWord(inputWord, hand, wordList):
            break

        # Compute the score from the chosed word and the total score
        inputWordScore = getWordScore(inputWord, n)
        score += inputWordScore

        # Print the current word and scores
        print("\""+inputWord+"\""+" earned "+str(inputWordScore)+" points."),
        print("Total: "+str(score)+" points")

        # update the hand. If length of new hand == 0, break.
        hand = updateHand(hand, inputWord)
        lenHand = calculateHandlen(hand)
        if lenHand == 0:
            break
        print

    # loop complete, print out the final total score
    print("Total score: " + str(score) +" points.")
    return None

#
# Problem #8: Playing a game
#
#
def playGame(wordList):
    """
    Allow the user to play an arbitrary number of hands.

    1) Asks the user to input 'n' or 'r' or 'e'.
        * If the user inputs 'e', immediately exit the game.
        * If the user inputs anything that's not 'n', 'r', or 'e', keep asking them again.

    2) Asks the user to input a 'u' or a 'c'.
        * If the user inputs anything that's not 'c' or 'u', keep asking them again.

    3) Switch functionality based on the above choices:
        * If the user inputted 'n', play a new (random) hand.
        * Else, if the user inputted 'r', play the last hand again.

        * If the user inputted 'u', let the user play the game
          with the selected hand, using playHand.
        * If the user inputted 'c', let the computer play the
          game with the selected hand, using compPlayHand.

    4) After the computer or user has played the hand, repeat from step 1

    wordList: list (string)
    """
    answer=""
    gamePlayed = False

    while True:
        print("Enter n to deal a new hand,"),
        print("r to replay the last hand,"),
        answer = raw_input("or e to end game: ")
        if answer == "e":
            return None
        elif answer == "n" or answer == "r":
            if answer == "r" and gamePlayed == False:
                print("You have not played a hand yet. Please play a hand first!\n")
                continue
            print
            while True:
                u_or_c = raw_input("Enter u to have yourself play, c to have the computer play: ")
                if u_or_c == "u" or u_or_c == "c":
                    if answer == "n":
                        hand = dealHand(HAND_SIZE)
                        handCopy = hand.copy()
                        handToUse = hand
                    elif answer == "r":
                        handToUse = handCopy
                    if u_or_c == "u":
                        playHand(handToUse, wordList, HAND_SIZE)
                        gamePlayed = True
                        print
                        break
                    elif u_or_c == "c":
                        compPlayHand(handToUse, wordList, HAND_SIZE)
                        gamePlayed = True
                        print
                        break
                else:
                    print("Invalid command.")
                    continue
        else:
            print("Invalid command.")
            continue

#
# Build data structures used for entire session and play game
#
if __name__ == '__main__':
    wordList = loadWords()
    playGame(wordList)


import tkinter as tk
import xmlrpc.client
import time
import threading
from tkinter import messagebox

class App:
    def __init__(self, master):
        self.master = master
        master.title("FLRig HF Scanner Ver. 1.0")
        self.start_freq = None
        self.end_freq = None
        self.flrig = None

        # Create labels for status, hostname, port, bands, scan, and signal
        tk.Label(master, text="Status:").grid(row=0, sticky="W")
        tk.Label(master, text="Hostname:").grid(row=1, sticky="W")
        tk.Label(master, text="Port:").grid(row=2, sticky="W")
        tk.Label(master, text="").grid(row=3, sticky="W")
        tk.Label(master, text="Bands:").grid(row=4, sticky="W")
        tk.Label(master, text="").grid(row=5, sticky="W")
        tk.Label(master, text="dB Sensitivity:").grid(row=6, sticky="W")
        tk.Label(master, text="Step Size:").grid(row=6, column=2, sticky="W")
        tk.Label(master, text="").grid(row=7, column=2, sticky="W")
        tk.Label(master, text="Scan:").grid(row=9, sticky="W")

        # Create flrig server version text after connection
        self.version_label = tk.Label(master, text="Disconnected")
        self.version_label.grid(row=0, column=1, columnspan=5, sticky="W")

        # Create signal label
        self.signal_label = tk.Label(master, text="Signal:")
        self.signal_label.grid(row=8, sticky="W")

        # Create entry fields for hostname and port
        self.hostname_entry = tk.Entry(master)
        self.hostname_entry.insert(0,"127.0.0.1")
        self.hostname_entry.grid(row=1, column=1)
        self.port_entry = tk.Entry(master)
        self.port_entry.insert(0,"12345")
        self.port_entry.grid(row=2, column=1)

        # Create a button to connect to FLRig and display the version
        self.connect_button = tk.Button(master, text="Connect", command=self.run_connect)
        self.connect_button.grid(row=1, rowspan=2, column=2, sticky="E")

        # Create a button to disconnect FLRig Server
        self.disconnect_button = tk.Button(master, text="Disconnect", command=self.run_disconnect)
        self.disconnect_button.grid(row=1, rowspan=2, column=3, sticky="W")
        self.disconnect_button.config(state=tk.DISABLED)

        # Create a button to change the frequency to 80m
        self.freq_80m_button = tk.Button(master, text="80m", command=self.freq_80m)
        self.freq_80m_button.place(x=61, y=84)

        # Create a button to change the frequency to 60m
        self.freq_60m_button = tk.Button(master, text="60m", command=self.freq_60m)
        self.freq_60m_button.place(x=95, y=84)

        # Create a button to change the frequency to 40m
        self.freq_40m_button = tk.Button(master, text="40m", command=self.freq_40m)
        self.freq_40m_button.place(x=129, y=84)

        # Create a button to change the frequency to 20m
        self.freq_20m_button = tk.Button(master, text="20m", command=self.freq_20m)
        self.freq_20m_button.place(x=163, y=84)

        # Create a button to change the frequency to 17m
        self.freq_17m_button = tk.Button(master, text="17m", command=self.freq_17m)
        self.freq_17m_button.place(x=197, y=84)

        # Create a button to change the frequency to 15m
        self.freq_15m_button = tk.Button(master, text="15m", command=self.freq_15m)
        self.freq_15m_button.place(x=231, y=84)

        # Create a button to change the frequency to 12m
        self.freq_12m_button = tk.Button(master, text="12m", command=self.freq_12m)
        self.freq_12m_button.place(x=265, y=84)

        # Create a button to change the frequency to 10m
        self.freq_10m_button = tk.Button(master, text="10m", command=self.freq_10m)
        self.freq_10m_button.place(x=299, y=84)

        # Create a label to show sensitivity
        self.sensitivity_label = tk.Label(master)

        # Create a label to show step size
        self.step_size_label = tk.Label(master)

        # Create a scale widget to select the sensitivity
        self.sensitivity_scale = tk.Scale(master, from_=1, to=100, orient=tk.HORIZONTAL, command=self.sensitivity)
        self.sensitivity_scale.set(20)
        self.sensitivity_scale.grid(row=6, column=1)

        # Create a scale widget to select the sensitivity
        self.step_size_scale = tk.Scale(master, from_=100, to=1000, resolution=100, orient=tk.HORIZONTAL, command=self.step_size)
        self.step_size_scale.set(500)
        self.step_size_scale.grid(row=6, column=3)

        # Create a button to scan the currently selected frequency
        self.scan_button = tk.Button(master, text="New Scan", command=self.run_scan_band)
        self.scan_button.grid(row=9, column=1, sticky="E")
        self.scan_button.config(state=tk.DISABLED)

        # Create a button to scan the currently selected frequency
        self.continue_button = tk.Button(master, text="Continue Scan", command=self.run_continue_band)
        self.continue_button.grid(row=9, column=2, sticky="E")
        self.continue_button.config(state=tk.DISABLED)

        # Create a button to stop the scan
        self.stop_button = tk.Button(master, text="Stop Scan", command=self.run_scan_band)
        self.stop_button.grid(row=9, column=3, sticky="W")

    def run_connect(self):
        threading.Thread(target=self.connect).start()
        # Disable the scan button

    def connect(self):
        # Get the hostname and port number from the entry fields
        hostname = self.hostname_entry.get()
        port = int(self.port_entry.get())

        # Connect to FLRig using XML-RPC
        self.flrig = xmlrpc.client.ServerProxy(f"http://{hostname}:{port}/RPC2")

        # Get the FLRig version and display it
        version = self.flrig.main.get_version()
        try:
            self.version_label.config(text=f"Connected to FLRig Server Ver.: {version}")
            self.connect_button.config(state=tk.DISABLED)
            self.disconnect_button.config(state=tk.NORMAL)
            self.scan_button.config(state=tk.NORMAL)
            self.continue_button.config(state=tk.NORMAL)
        except Exception as e:
            self.version_label.config(text=f"Failed to connect to FLRig server: {e}")

    def run_disconnect(self):
        threading.Thread(target=self.disconnect).start()
        # Disable the scan button

    def disconnect(self):
        if self.flrig is None:
            messagebox.showerror("Error", "Not connected to FLRig Server")
            return
        #self.flrig.system.close()
        self.flrig = xmlrpc.client.ServerProxy("http://localhost:0/RPC2")
        self.version_label.config(text="Disconnected")
        self.connect_button.config(state=tk.NORMAL)
        self.disconnect_button.config(state=tk.DISABLED)
        self.scan_button.config(state=tk.DISABLED)
        self.continue_button.config(state=tk.DISABLED)

    def freq_80m(self):
        if self.flrig is None:
            messagebox.showerror("Error", "Not connected to FLRig Server")
            return
        # Set the frequency to 3.700 MHz
        self.flrig.rig.set_mode("LSB")
        self.flrig.rig.set_bandwidth(3000)
        self.flrig.rig.set_vfo(float(3700000))
        self.start_freq = 3700000
        self.end_freq = 4000000

    def freq_60m(self):
        if self.flrig is None:
            messagebox.showerror("Error", "Not connected to FLRig Server")
            return
        # Set the frequency to 5.354 MHz
        self.flrig.rig.set_mode("USB")
        self.flrig.rig.set_bandwidth(3000)
        self.flrig.rig.set_vfo(float(5354000))
        self.start_freq = 5354000
        self.end_freq = 5366000

    def freq_40m(self):
        if self.flrig is None:
            messagebox.showerror("Error", "Not connected to FLRig Server")
            return
        # Set the frequency to 3.700 MHz
        self.flrig.rig.set_mode("LSB")
        self.flrig.rig.set_bandwidth(3000)
        self.flrig.rig.set_vfo(float(7175000))
        self.start_freq = 7175000
        self.end_freq = 7300000

    def freq_20m(self):
        if self.flrig is None:
            messagebox.showerror("Error", "Not connected to FLRig Server")
            return
        # Set the frequency to 14.225 MHz
        self.flrig.rig.set_mode("USB")
        self.flrig.rig.set_bandwidth(3000)
        self.flrig.rig.set_vfo(float(14225000))
        self.start_freq = 14225000
        self.end_freq = 14350000

    def freq_17m(self):
        if self.flrig is None:
            messagebox.showerror("Error", "Not connected to FLRig Server")
            return
        # Set the frequency to 18.110 MHz
        self.flrig.rig.set_mode("USB")
        self.flrig.rig.set_bandwidth(3000)
        self.flrig.rig.set_vfo(float(18110000))
        self.start_freq = 18110000
        self.end_freq = 18168000

    def freq_15m(self):
        if self.flrig is None:
            messagebox.showerror("Error", "Not connected to FLRig Server")
            return
        # Set the frequency to 21.275 MHz
        self.flrig.rig.set_mode("USB")
        self.flrig.rig.set_bandwidth(3000)
        self.flrig.rig.set_vfo(float(21275000))
        self.start_freq = 21275000
        self.end_freq = 21450000

    def freq_12m(self):
        if self.flrig is None:
            messagebox.showerror("Error", "Not connected to FLRig Server")
            return
        # Set the frequency to 24.930 MHz
        self.flrig.rig.set_mode("USB")
        self.flrig.rig.set_bandwidth(3000)
        self.flrig.rig.set_vfo(float(24930000))
        self.start_freq = 24930000
        self.end_freq = 24990000

    def freq_10m(self):
        if self.flrig is None:
            messagebox.showerror("Error", "Not connected to FLRig Server")
            return
        # Set the frequency to 28.300 MHz
        self.flrig.rig.set_mode("USB")
        self.flrig.rig.set_bandwidth(3000)
        self.flrig.rig.set_vfo(float(28300000))
        self.start_freq = 28300000
        self.end_freq = 29700000

    def sensitivity(self, value):
        #Set the signal sensitivity
        self.sensitivity_label.config(text=f"dB Sensitivity: {value}")

    def step_size(self, value):
        #Set scan step size
        self.step_size_label.config(text=f"Step Size: {value}")

    def run_scan_band(self):
        # Create an event object
        stop_event=threading.Event()
        #Create a thread
        threading.Thread(target=self.scan_band, args=(stop_event,)).start()

        # Disable the scan button
        self.scan_button.config(state=tk.DISABLED)
        self.continue_button.config(state=tk.DISABLED)

        # Enable the stop button
        self.stop_button.config(state=tk.NORMAL)

        # Set the stop event when the stop button is pressed
        self.stop_button.config(command=lambda: stop_event.set())

    def scan_band(self, stop_event):
        if self.flrig is None:
            messagebox.showerror("Error", "Not connected to FLRig Server")
            return

        # Define band frequencies as tuples
        bands = [
            ("80m", 3700000, 4000100, "LSB"),
            ("60m", 5354000, 5366100, "USB"),
            ("40m", 7175000, 7300100, "LSB"),
            ("20m", 14225000, 14350100, "USB"),
            ("17m", 18110000, 18168100, "USB"),
            ("15m", 21275000, 21450100, "USB"),
            ("12m", 24930000, 24990100, "USB"),
            ("10m", 28300000, 29700100, "USB"),
        ]

        # Get the current frequency from FLRig
        frequency = float(self.flrig.rig.get_vfo())

        # Determine the current band
        for band, start, stop, mode in bands:
            if start <= frequency <= stop:
                #self.start_freq = frequency
                self.start_freq = start
                self.end_freq = stop
                break
        else:
            # Frequency is not within any defined band
            messagebox.showerror("Error", "Current frequency is not within any defined band")
            return

        # Get the current sensitivity and step size from the scales
        sensitivity = self.sensitivity_scale.get()
        step_size = self.step_size_scale.get()
        frequency = self.start_freq

        # Call the scan method with the current frequency, sensitivity, and step size
        #while True:
        while not stop_event.is_set():
            for frequency in range(int(self.start_freq), self.end_freq, step_size):
                if stop_event.is_set():
                    self.scan_button.config(state=tk.NORMAL)
                    self.continue_button.config(state=tk.NORMAL)
                    break
                self.flrig.rig.set_vfo(float(frequency))
                time.sleep(0.1)

                smeter = self.flrig.rig.get_smeter()
                self.signal_label.config(text=f"Signal: {smeter} dB")
                #print(smeter)
                if int(smeter) >= sensitivity:
                    #print(f"Signal strength above {sensitivity} detected. Scanning stopped. Current frequency is {frequency}")
                    # Re-enable the scan button
                    self.scan_button.config(state=tk.NORMAL)
                    self.continue_button.config(state=tk.NORMAL)
                    break
            else:
                # End of the band reached, loop back to starting frequency
                for band, start, stop, mode in bands:
                    if start <= frequency <= stop:
                        self.start_freq = start
                        self.end_freq = stop
                continue
            break

    # def run_continue_band(self):
    #     threading.Thread(target=self.continue_band).start()
    #     # Disable the scan button
    #     self.scan_button.config(state=tk.DISABLED)
    #     self.continue_button.config(state=tk.DISABLED)

    def run_continue_band(self):
        # Create an event object
        stop_event=threading.Event()
        #Create a thread
        threading.Thread(target=self.continue_band, args=(stop_event,)).start()

        # Disable the scan button
        self.scan_button.config(state=tk.DISABLED)
        self.continue_button.config(state=tk.DISABLED)

        # Enable the stop button
        self.stop_button.config(state=tk.NORMAL)

        # Set the stop event when the stop button is pressed
        self.stop_button.config(command=lambda: stop_event.set())

        #self.frequency += step_size # +step_size forces the vfo to move forward

    def continue_band(self, stop_event):
        if self.flrig is None:
            messagebox.showerror("Error", "Not connected to FLRig Server")
            return

        # Define band frequencies as tuples
        bands = [
            ("80m", 3700000, 4000100, "LSB"),
            ("60m", 5354000, 5366100, "USB"),
            ("40m", 7175000, 7300100, "LSB"),
            ("20m", 14225000, 14350100, "USB"),
            ("17m", 18110000, 18168100, "USB"),
            ("15m", 21275000, 21450100, "USB"),
            ("12m", 24930000, 24990100, "USB"),
            ("10m", 28300000, 29700100, "USB"),
        ]

        # Get the current frequency from FLRig
        frequency = float(self.flrig.rig.get_vfo())

        # Determine the current band
        for band, start, stop, mode in bands:
            if start <= frequency <= stop:
                self.start_freq = frequency
                #self.start_freq = start
                self.end_freq = stop
                break
        else:
            # Frequency is not within any defined band
            messagebox.showerror("Error", "Current frequency is not within any defined band")
            return

        # Get the current sensitivity and step size from the scales
        sensitivity = self.sensitivity_scale.get()
        step_size = self.step_size_scale.get()
        frequency = self.start_freq

        # Forces vfo to move forward
        self.start_freq = int(self.start_freq) + int(step_size)

        # Call the scan method with the current frequency, sensitivity, and step size
        while not stop_event.is_set():
            for frequency in range(int(self.start_freq), self.end_freq, step_size):
                if stop_event.is_set():
                    self.scan_button.config(state=tk.NORMAL)
                    self.continue_button.config(state=tk.NORMAL)
                    break
                self.flrig.rig.set_vfo(float(frequency))
                time.sleep(0.1)

                smeter = self.flrig.rig.get_smeter()
                self.signal_label.config(text=f"Signal: {smeter} dB")
                #print(smeter)
                if int(smeter) >= sensitivity:
                    #print(f"Signal strength above {sensitivity} detected. Scanning stopped. Current frequency is {frequency}")
                    self.scan_button.config(state=tk.NORMAL)
                    self.continue_button.config(state=tk.NORMAL)
                    break
            else:
                # End of the band reached, loop back to starting frequency
                for band, start, stop, mode in bands:
                    if start <= frequency <= stop:
                        self.start_freq = start
                        self.end_freq = stop
                continue
            break

root = tk.Tk()
root.geometry("425x270")
app = App(root)
root.mainloop()


#!/usr/bin/env python3
#Programmer: MMJR ku5e@ku5e.com
#date: 02/11/2022
#Purpose: Quality-Adjusted Life-Year

count = int(input())
sum = 0

for i in range(count):
	a, b = list(map(float, input().split()))
	sum += a * b

print(sum)


import os

from .errors import Error
from ..platformflags import is_win32

class PythonLibcTooOld(Error):
    """FATAL: this Python was compiled for a too old (g)libc and misses required functionality."""

def check_python():
    if is_win32:
        required_funcs = {os.stat}
    else:
        required_funcs = {os.stat, os.utime, os.chown}
    if not os.supports_follow_symlinks.issuperset(required_funcs):
        raise PythonLibcTooOld

class ExtensionModuleError(Error):
    """The Borg binary extension modules do not seem to be properly installed."""

def check_extension_modules():
    from .. import platform, compress, crypto, item, chunker, hashindex

    if hashindex.API_VERSION != "1.2_01":
        raise ExtensionModuleError
    if chunker.API_VERSION != "1.2_01":
        raise ExtensionModuleError
    if compress.API_VERSION != "1.2_02":
        raise ExtensionModuleError
    if crypto.low_level.API_VERSION != "1.3_01":
        raise ExtensionModuleError
    if item.API_VERSION != "1.2_01":
        raise ExtensionModuleError
    if platform.API_VERSION != platform.OS_API_VERSION or platform.API_VERSION != "1.2_05":
        raise ExtensionModuleError


import kbuild
import ktest
import pytest

kgdbts_choices = [
	'Unregistered I/O driver kgdbts',
	'kgdbts:RUN',
	'WARNING.*kgdbts[.]c.*[\r\n]',
	'KGDB: BP remove failed',
]
KGDBTS_RUNNING = 1
KGDBTS_WARNING =  2
KGDBTS_FATAL = 3

@pytest.fixture(scope="module")
def build():
	kbuild.config(kgdb=True)
	kbuild.build()

@pytest.fixture()
def kernel(build):
	qemu = ktest.qemu(kdb=False)

	console = qemu.console
	console.expect_boot()
	console.expect_busybox()

	# Older kernels have no async progress display so for these
	# kernels we just set a very long timeout (which means failures
	# will take a long time to report too)
	if kbuild.get_version() < (4, 17):
		console.timeout *= 10
		print('Kernel is below v4.17, extended timeout to {}'.format(
			console.timeout))

	yield qemu

	qemu.close()

#@pytest.mark.xfail(condition = (kbuild.get_arch() == 'arm'), run = True,
#		   reason = 'Hangs during concurrency tests')
@pytest.mark.xfail(condition = (kbuild.get_arch() == 'x86'), run = True,
		   reason = 'hw_access breakpoints not trapping')
def test_kgdbts_V1(kernel):
	'''
	From drivers/misc/kgdbts.c:

	2) After the system boot run the basic test.
	   echo kgdbts=V1 > /sys/module/kgdbts/parameters/kgdbts
	'''
	kernel.console.sendline('echo kgdbts=V1 > /sys/module/kgdbts/parameters/kgdbts')
	choice = kernel.console.expect(['ERROR', 'Registered I/O driver kgdbts'])
	assert choice

	try:
		choice = KGDBTS_RUNNING
		while choice:
			choice = kernel.console.expect(kgdbts_choices)
			assert(choice <= KGDBTS_RUNNING)
	finally:
		count = 100
		while choice >= KGDBTS_RUNNING and \
		      choice < KGDBTS_FATAL and \
		      count:
			choice = kernel.console.expect(kgdbts_choices)
			count -= 1
		kernel.console.expect_prompt()

# These XFAILs do not reproduce reliably but it occurs frequently enough
# to make the suite verdict unreliable so for now we have to mark them
# accordingly. On x86 the failure rate is guestimated at ~15%.
@pytest.mark.xfail(condition = (kbuild.get_arch() == 'riscv'),
		   reason = 'bad unlock balance detected')
@pytest.mark.xfail(condition = (kbuild.get_arch() == 'x86'),
		   reason = 'plant and detach test likely to fail')
def test_kgdbts_V1S10000(kernel):
	'''
	From drivers/misc/kgdbts.c:

	3) Run the concurrency tests.  It is best to use n+1
	   while loops where n is the number of cpus you have
	   in your system.  The example below uses only two
	   loops.

	   ## This tests break points on sys_open
	   while [ 1 ] ; do find / > /dev/null 2>&1 ; done &
	   while [ 1 ] ; do find / > /dev/null 2>&1 ; done &
	   echo kgdbts=V1S10000 > /sys/module/kgdbts/parameters/kgdbts
	   fg # and hit control-c
	   fg # and hit control-c
	'''
	kernel.console.sendline('n=$((`nproc` + 1))')
	kernel.console.sendline('for i in `seq $n`')
	kernel.console.sendline('do')
	kernel.console.sendline('while [ 1 ] ; do find / > /dev/null 2>&1 ; done &')
	kernel.console.sendline('done')
	kernel.console.expect_prompt()
	kernel.console.sendline('jobs | tee j')
	kernel.console.expect_prompt()
	kernel.console.sendline('[ `cat j | wc -l` -eq $n ] && [ $n -gt 1 ] && echo OK || echo FAILED')
	choice = kernel.console.expect(['FAILED', 'OK'])
	assert choice
	kernel.console.expect_prompt()

	kernel.console.sendline('echo kgdbts=V1S10000 > /sys/module/kgdbts/parameters/kgdbts')
	#kernel.console.sendline('echo kgdbts=V1S1000 > /sys/module/kgdbts/parameters/kgdbts')
	choice = kernel.console.expect(['ERROR', 'Registered I/O driver kgdbts'])
	assert choice

	choice = KGDBTS_RUNNING
	while choice:
		choice = kernel.console.expect(kgdbts_choices)
		if choice == KGDBTS_WARNING and \
		   'hw_break' in kernel.console.match.group(0):
			print('>>> Ignoring hw_break error (will be reported by kgdbtest_V1 instead)\n')
			continue
		assert(choice <= KGDBTS_RUNNING)

	kernel.console.expect_prompt(no_history=True)
	kernel.console.sendline('for i in `seq $n`; do kill %$i; done; sleep 1')
	kernel.console.expect_prompt()

@pytest.mark.xfail(condition = (kbuild.get_arch() == 'x86'),
		   reason = 'fails approximately ~30% of the time')
def test_kgdbts_V1F1000(kernel):
	'''
	From drivers/misc/kgdbts.c:

	   ## This tests break points on do_fork
	   while [ 1 ] ; do date > /dev/null ; done &
	   while [ 1 ] ; do date > /dev/null ; done &
	   echo kgdbts=V1F1000 > /sys/module/kgdbts/parameters/kgdbts
	   fg # and hit control-c
	'''
	kernel.console.sendline('n=$((`nproc` + 1))')
	kernel.console.sendline('for i in `seq $n`')
	kernel.console.sendline('do')
	kernel.console.sendline('while [ 1 ] ; do date > /dev/null 2>&1 ; done &')
	kernel.console.sendline('done')
	kernel.console.expect_prompt()
	kernel.console.sendline('jobs | tee j')
	kernel.console.expect_prompt()
	kernel.console.sendline('[ `cat j | wc -l` -eq $n ] && [ $n -gt 1 ] && echo OK || echo FAILED')
	choice = kernel.console.expect(['FAILED', 'OK'])
	assert choice
	kernel.console.expect_prompt()

	kernel.console.sendline('echo kgdbts=V1F1000 > /sys/module/kgdbts/parameters/kgdbts')
	choice = kernel.console.expect(['ERROR', 'Registered I/O driver kgdbts'])
	assert choice

	choice = KGDBTS_RUNNING
	while choice:
		choice = kernel.console.expect(kgdbts_choices)
		if choice == KGDBTS_WARNING and \
		   'hw_break' in kernel.console.match.group(0):
			print('>>> Ignoring hw_break error (will be reported by kgdbtest_V1 instead)\n')
			continue
		assert(choice <= KGDBTS_RUNNING)

	kernel.console.expect_prompt(no_history=True)
	kernel.console.sendline('for i in `seq $n`; do kill %$i; done; sleep 1')
	kernel.console.expect_prompt()


"""Utilities that are relevant to the TFIM model."""
import numpy as np
import scipy.linalg as la
from utils import misc
from utils import calc

def tfim_hamiltonian(n_sites, h=1.0, pbc=True, dtype=np.complex128):
  """Creates nearest neighbor TFIM Hamiltonian matrix.

  Args:
    n_sites: Number of sites.
    h: Transverse field strength.
    pbc: If True, periodic boundary conditions are assumed.
    dtype: np type of the arrays.

  Returns:
    TFIM Hamiltonian matrix of shape (2**n_sites, 2**n_sites).
  """
  pauli = misc.Pauli(dtype=dtype)
  identities = [pauli.I for i in range(n_sites)]
  ham = np.zeros([2**n_sites, 2**n_sites], dtype=dtype)
  for i in range(n_sites - 1):
    matlist = identities[:]
    matlist[i], matlist[i + 1] = pauli.Z, pauli.Z
    ham += calc.kron_list(matlist)
  if pbc:
    matlist = identities[:]
    matlist[0], matlist[-1] = pauli.Z, pauli.Z
    ham += calc.kron_list(matlist)

  # Add field terms
  ham_f = np.zeros_like(ham)
  for i in range(n_sites - 1):
    ham_f += calc.kron_list(identities[:i] + [pauli.X] + identities[i+1:])
  ham_f += calc.kron_list(identities[:-1] + [pauli.X])

  return - ham - h * ham_f

def tfim_mpo(n_sites, h=1.0, dtype=np.complex128):
  """Constructs the Hamiltonian of periodic TFIM as a MPO.

  Args:
    n_sites: Number of sites.
    h: Transverse field strength.
    dtype: np type of the arrays.

  Returns:
    Periodic TFIM Hamiltonian as a MPO of shape (n_sites, 5, 2, 2, 5).
  """
  pauli = misc.Pauli(dtype=dtype)
  assert n_sites > 4

  left_vector = np.zeros([5, 2, 2, 5], dtype=dtype)
  for i, p in enumerate([pauli.Z, h * pauli.X, pauli.I]):
    left_vector[0, :, :, i] = np.copy(p)

  right_vector = np.zeros([5, 2, 2, 5], dtype=dtype)
  for i, p in enumerate([-pauli.I, -h * pauli.X, -pauli.Z]):
    right_vector[i, :, :, 0] = np.copy(p)

  left_matrix = np.zeros([5, 2, 2, 5], dtype=dtype)
  left_matrix[0, :, :, 0] = pauli.Z
  left_matrix[0, :, :, 1] = pauli.I
  left_matrix[1, :, :, 0] = pauli.I
  left_matrix[2, :, :, 2] = pauli.Z
  left_matrix[2, :, :, 3] = h * pauli.X
  left_matrix[2, :, :, 4] = pauli.I

  right_matrix = np.zeros([5, 2, 2, 5], dtype=dtype)
  right_matrix[0, :, :, 0] = pauli.I
  right_matrix[1, :, :, 2] = pauli.I
  right_matrix[2, :, :, 0] = pauli.Z
  right_matrix[3, :, :, 0] = pauli.I
  right_matrix[4, :, :, 0] = h * pauli.X
  right_matrix[4, :, :, 1] = pauli.I
  right_matrix[4, :, :, 2] = pauli.Z

  middle_matrix = np.zeros([5, 2, 2, 5], dtype=dtype)
  middle_matrix[0, :, :, 0] = pauli.I
  middle_matrix[1, :, :, 1] = pauli.I
  middle_matrix[2, :, :, 0] = pauli.Z
  middle_matrix[3, :, :, 0] = pauli.I
  middle_matrix[4, :, :, 2] = pauli.Z
  middle_matrix[4, :, :, 3] = h * pauli.X
  middle_matrix[4, :, :, 4] = pauli.I

  return np.stack([left_vector, left_matrix] +
                  (n_sites - 4) * [middle_matrix] +
                  [right_matrix, right_vector])

def tfim_exact_evolution(n_sites, t_final, time_steps, h0=None, h=0.5,
                         init_state=None, dtype=np.complex128):
  """Exact unitary evolution of TFIM using full propagator matrix.

  Args:
    n_sites: Number of sites.
    t_final: Time evolution duration.
    time_steps: Number of time steps to evolve (initial point does not count.)
    h0: Initial field. The initial condition is the corresponding ground state.
    h: Evolution Hamiltonian field. We are evolving a quench.
    dtype: Complex array types.

  Returns:
    state: Evolved state in every time step with shape (M + 1, 2**n_sites)
      where M = time_steps.
    observables: Dictionary with energy and sigma_x for every time step.
  """
  dt = t_final / time_steps
  Hevolve = tfim_hamiltonian(n_sites, h=h)
  Udt = la.expm(-1j * dt * Hevolve)
  pauli = misc.Pauli(dtype=dtype)

  if init_state is None:
    if h0 is None:
      h0 = 1.0
    Hinit = tfim_hamiltonian(n_sites, h=h0)
    init_state = la.eigh(Hinit)[1][:, 0]
  else:
    if (np.abs(init_state)**2).sum() != 1.0:
      raise ValueError("Given initial state is not normalized.")
    init_state = init_state.astype(dtype)

  rtype = misc.rtype_from_ctype(dtype)
  sigma_x = np.zeros(time_steps + 1, dtype=rtype)
  energy = np.zeros(time_steps + 1, dtype=rtype)

  state = [np.copy(init_state)]
  sigma_x[0] = calc.ev_local(state[0], pauli.X).real
  energy[0] = (np.conj(state[0]) * Hevolve.dot(state[0])).sum().real
  for i in range(1, time_steps + 1):
    state.append(Udt.dot(state[i-1]))
    sigma_x[i] = calc.ev_local(state[i], pauli.X).real
    energy[i] = (np.conj(state[i]) * Hevolve.dot(state[i])).sum().real

  observables = {"energy": energy, "X": sigma_x}
  return np.array(state), observables

def tfim_trotterized_evolution(u_list, psi0, time_steps):
  """Trotterized evolution of full wavefunction.

  Args:
    u_list: List of unitary operators for one step time propagation.
    psi0: Initial condition with shape (2**N,).
    time_steps: Number of times to apply the evolution unitary.

  Returns:
    state: Evolved state.
  """
  state = [np.copy(psi0)]
  for i in range(time_steps):
    state_temp = np.copy(state[-1])
    for u in u_list:
      state_temp = u.dot(state_temp)
    state.append(np.copy(state_temp))
  return np.array(state)


#!/usr/bin/env python2
import urllib2, json, os, sys

HEADER = '''  Redirect = {
    image: function(board, filename) {
      switch (board) {
'''
POST = '''      }
    },
    post: function(board, postID) {
      switch (board) {
'''
TO = '''      }
    },
    to: function(data) {
      var board, threadID, url;
      if (!data.isSearch) {
        threadID = data.threadID;
      }
      board = data.board;
      switch (board) {
'''
BOTTOM = '''        default:
          if (threadID) {
            url = "//boards.4chan.org/" + board + "/";
          }
      }
      return url || null;
    },
'''

CASE = "        case '%s':\n"
RETURN_IMAGE = '          return "%s/" + board + "/full_image/" + filename;\n'
RETURN_POST = '          return "%s/_/api/chan/post/?board=" + board + "&num=" + postID;\n'
RETURN_REDIRECT = """          url = Redirect.path('%s', '%s', data);
          break;
"""

ARCHIVES_URL = "https://4chenz.github.io/archives.json/archives.json"
ARCHIVES_JSON = os.path.join(os.path.dirname(os.path.abspath(__file__)), "archives.json")
PRIORITIES_JSON = os.path.join(os.path.dirname(os.path.abspath(__file__)), "priorities.json")

ARCHIVE_HIDDEN = [29,32,35]

def jsonloadf(filename):
	with open(filename) as f:
		data = json.load(f, 'utf-8')
	return data

def jsonsavef(filename, data):
	with open(filename, 'wb') as f:
		json.dump(data, f, sort_keys=True, indent=4, separators=(',', ': '), encoding='utf-8')

def http_protocol(a):
	dom = a['domain']
	if a['https'] and a['http']:
		return '//' + dom
	elif a['https']:
		return 'https://' + dom
	elif a['http']:
		return 'http://' + dom

class Build:
	def __init__(self, outstream=sys.stdout, msgstream=sys.stderr):
		self.out = outstream
		self.msg = msgstream
		self.files = {}
		self.boards = {}
		self.data = None
		self.priorities = jsonloadf(PRIORITIES_JSON)

	def page_dl(self):
		request = urllib2.Request(ARCHIVES_URL)
		response = urllib2.urlopen(request)
		data = response.read()
		response.close()
		self.data = json.loads(data)

	def boards_list(self):
		f = []
		b = []
		for a in self.data:
			f += a['files']
			b += a['boards']
		self.archivedfiles = list(set(f))
		self.archivedboards = list(set(b))

	def find_redundant(self):
		f = {}
		b = {}
		for n, a in enumerate(self.data):
			for e in a['files']:
				if e in f:
					f[e].append(n)
				else:
					f[e] = [n]
			for e in a['boards']:
				if e in b:
					b[e].append(n)
				else:
					b[e] = [n]
		def filterhidden(value):
			return filter(lambda x: not (self.data[x]['uid'] in ARCHIVE_HIDDEN and len(value) > 1), value)
		self.singleboards = {}
		self.redundantboards = {}
		for k, v in b.iteritems():
			v2 = filterhidden(v)
			if len(v2) == 1:
				self.singleboards[k] = v2[0]
			if len(v2) > 1:
				self.redundantboards[k] = v2
		self.singlefiles = {}
		self.redundantfiles = {}
		for k, v in f.iteritems():
			v2 = filterhidden(v)
			if len(v2) == 1:
				self.singlefiles[k] = v2[0]
			if len(v2) > 1:
				self.redundantfiles[k] = v2

	def pprint(self, t):
		print >>self.msg, "%s:" % t
		if t == 'files':
			it = self.redundantfiles.iteritems()
		else:
			it = self.redundantboards.iteritems()
		for k, v in it:
			print >>self.msg, "%s --> " % k,
			sel = None
			selfound = None
			if k in self.priorities[t]:
				sel = self.priorities[t][k]
			for x in v:
				if self.data[x]['uid'] == sel:
					forstr = "{%s}"
					selfound = x
				else:
					forstr = '"%s"'
				print >>self.msg, forstr % self.data[x]['name'],
			if sel == None or selfound == None:
				print >>self.msg, "NOT SELECTED!"
			else:
				print >>self.msg
				if t == 'files':
					self.files[k] = selfound
				else:
					self.boards[k] = selfound

	def prioprint(self):
		self.separator()
		print >>self.msg, "archives:"
		for a in self.data:
			if a['uid'] in ARCHIVE_HIDDEN:
				print >>self.msg, "HIDDEN:",
			print >>self.msg, a['uid'], a['name']
		self.separator()
		self.pprint('boards')
		self.separator()
		self.pprint('files')
		self.separator()

	def merge(self):
		self.boards.update(self.singleboards)
		self.files.update(self.singlefiles)

	def separator(self):
		if self.msg == sys.stderr:
			print >>self.msg, "-" * 80

	def build(self):
		if not self.data:
			self.page_dl()
		#add empty "files" if missing
		for d in self.data:
			if not "files" in d:
				d.update({"files" : []})
		#do stuff
		self.boards_list()
		self.find_redundant()
		self.prioprint()
		self.merge()
		#image
		self.out.write(HEADER)
		for n, a in enumerate(self.data):
			filefound = False
			for b in a['files']:
				if b in self.files and n == self.files[b]:
					filefound = True
					self.out.write(CASE % b)
			if filefound:
				self.out.write(RETURN_IMAGE % http_protocol(a))
		self.out.write(POST)
		#post
		for n, a in enumerate(self.data):
			if a['software'] != 'foolfuuka':
				continue
			boardfound = False
			for b in a['boards']:
				if b in self.boards and n == self.boards[b]:
					boardfound = True
					self.out.write(CASE % b)
			if boardfound:
				self.out.write(RETURN_POST % http_protocol(a))
		self.out.write(TO)
		#redirect
		for n, a in enumerate(self.data):
			boardfound = False
			for b in a['boards']:
				if b in self.boards and n == self.boards[b]:
					boardfound = True
					self.out.write(CASE % b)
			if boardfound:
				self.out.write(RETURN_REDIRECT % (http_protocol(a), a['software']))
		self.out.write(BOTTOM)

if __name__ == "__main__":
	builder = Build()
	if len(sys.argv) == 2:
		builder.data = jsonloadf(sys.argv[1])
	builder.build()


from PyQt5 import uic, QtWidgets

import time

from PyQt5.QtGui import QPixmap
from twisted.internet.protocol import DatagramProtocol
from twisted.internet.task import LoopingCall

from PyQt5.QtGui import QIcon, QColor, QRegExpValidator
from PyQt5.QtCore import QRegExp, Qt
import sys
import os
import subprocess

application_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, application_path)

# ATTENTION
# we need elevated rights for exam mode !
# we can stick to sudo at the beginning (starting this script) and then default to start everything without sudo but we need to add
# env_keep += PYTHONPATH  to sudoers file  (sudo visudo) otherwise twistd will not find the exam plugin
# in order to set PYTHONPATH in the first place we add  PYTHONPATH="/home/student/.life/applications/life-exam" to /etc/environment or .bashrc

import qt5reactor
import classes.mutual_functions as mutual_functions
from config.config import *

class ClientDialog(QtWidgets.QDialog):
    def __init__(self):
        QtWidgets.QDialog.__init__(self)
        self.examserver = dict()
        self.disconnected_clients = dict()
        self.completer = QtWidgets.QCompleter()
        self.completerlist = []
        self._initUi()
        mutual_functions.prepareDirectories()

    def _initUi(self):
        self.scriptdir=os.path.dirname(os.path.abspath(__file__))
        uifile=os.path.join(APP_DIRECTORY,'client/client.ui')
        self.ui = uic.loadUi(uifile)
        winicon=os.path.join(APP_DIRECTORY,'pixmaps/windowicon.png')
        self.ui.setWindowIcon(QIcon(winicon))
        self.ui.exit.clicked.connect(self._onAbbrechen)  # setup Slots
        self.ui.start.clicked.connect(self._onStartExamClient)
        self.ui.offlineexam.clicked.connect(self._on_offline_exam)
        self.ui.offlineexamexit.clicked.connect(self._on_offline_exam_exit)
        self.ui.serverdropdown.currentIndexChanged.connect(self._updateIP)
        self.ui.serverdropdown.activated.connect(self._updateIP)
        self.ui.studentid.textChanged.connect(lambda: self._changePalette(self.ui.studentid, 'ok'))
        self.ui.studentid.setFocus()
        #self.ui.serverip.textChanged.connect(lambda: self._changePalette(self.ui.serverip,'ok'))
        self.ui.pincode.textChanged.connect(lambda: self._changePalette(self.ui.pincode,'ok'))
        self.ui.serverip.hide()
        self.ui.keyPressEvent = self.newOnkeyPressEvent

        char_regex=QRegExp("[a-z-A-Z\-_]+")   # only allow specif characters in textfields
        char_validator = QRegExpValidator(char_regex)
        self.ui.studentid.setValidator(char_validator)

        num_regex=QRegExp("[0-9_]+")
        num_validator = QRegExpValidator(num_regex)
        self.ui.pincode.setValidator(num_validator)

        ip_regex=QRegExp("[0-9\._]+")
        ip_validator = QRegExpValidator(ip_regex)
        #self.ui.serverip.setValidator(ip_validator)

    def newOnkeyPressEvent(self,e):
        if e.key() == Qt.Key_Escape:
            print("close event triggered")

    def _onAbbrechen(self):  # Exit button
        self.ui.close()

    def _on_offline_exam(self):

        self.msg = QtWidgets.QMessageBox()
        self.msg.setIcon(QtWidgets.QMessageBox.Information)
        self.msg.setText("Wollen sie in den abgesicherten Exam Modus wechseln?")
        self.msg.setDetailedText("Die automatische Abgabe,\nScreenlock, senden und empfangen von Dateien\nund andere Funktionen sind in diesem Modus nicht verfügbar.")
        self.msg.setWindowTitle("LiFE Exam")
        self.msg.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
        retval = self.msg.exec_()   # 16384 = yes, 65536 = no

        if str(retval) == "16384":
            command = "chmod +x %s/startexam.sh &" % EXAMCONFIG_DIRECTORY  # make examscritp executable
            os.system(command)
            time.sleep(2)
            startcommand = "%s/startexam.sh &" %(EXAMCONFIG_DIRECTORY) # start as user even if the twistd daemon is run by root
            os.system(startcommand)  # start script
        else:
            self.msg = False

    def _on_offline_exam_exit(self):
        startcommand = "%s/stopexam.sh &" %(SCRIPTS_DIRECTORY)
        os.system(startcommand)  # start script

    def _onStartExamClient(self):
        SERVER_IP = self.ui.serverip.text()
        ID = self.ui.studentid.text()
        PIN = self.ui.pincode.text()

        if mutual_functions.checkIP(SERVER_IP):
            if ID == "":
                self._changePalette(self.ui.studentid, "warn")
            elif PIN == "":
                self._changePalette(self.ui.pincode, "warn")
            else:
                self.ui.close()
                clientkillscript = os.path.join(SCRIPTS_DIRECTORY, "terminate-exam-process.sh")
                os.system("%s %s" % (clientkillscript, 'client'))  # make sure only one client instance is running per client

                namefile = os.path.join(WORK_DIRECTORY, "myname.txt")  # moved this to workdirector because configdirectory is overwritten on exam start
                openednamefile = open(namefile, 'w+')  # erstelle die datei neu
                openednamefile.write("%s" %(ID) )

                from twisted.plugin import IPlugin, getPlugins
                list(getPlugins(IPlugin))

                #pkXexec is used here (a short "life" bashscript that uses pkexec but sets a lot of environment variables)
                command = "sudo -E twistd3 -l %s/client.log --pidfile %s/client.pid examclient -p %s -h %s -i %s -c %s &" % (
                    WORK_DIRECTORY, WORK_DIRECTORY, SERVER_PORT, SERVER_IP, ID, PIN)
                print(command)
                os.system(command)

                #subprocess.call(command, shell=True,env=dict(os.environ ))
                # for non daemon mode manual to track bugs
                #sudo twistd -n --pidfile /home/student/.life/EXAM/client.pid examclient -p 11411 -h 10.0.0.110 -i ich -c 2604

        else:
            self._changePalette(self.ui.serverip, "warn")

    def _changePalette(self, item, reason):
        if reason == 'warn':
            palettewarn = item.palette()
            palettewarn.setColor(item.backgroundRole(), QColor(160, 80, 80))
            item.setPalette(palettewarn)
        else:
            palettedefault = item.palette()
            palettedefault.setColor(item.backgroundRole(), QColor(255, 255, 255))
            item.setPalette(palettedefault)

    def _updateServerlist(self):
        """updates the dropdownmenu if new servers are found"""
        self.ui.serverdropdown.clear()
        for server in self.examserver:
            self.ui.serverdropdown.addItem(server)

    def _updateIP(self):
        """updates the ip address fiel according to the selection in the dropdownmenu """
        current = self.ui.serverdropdown.currentText()
        self.ui.serverip.setText(self.examserver.get(current) )

        self.completerlist = self.disconnected_clients.get(current)  # gets a list from the dict
        self.completer = QtWidgets.QCompleter(self.completerlist)
        self.ui.studentid.setCompleter(self.completer)

class MulticastLifeClient(DatagramProtocol):
    def __init__(self):
        self.loopObj = None
        self.server_ip = "0.0.0.0"
        self.info = None

    def startProtocol(self):
        self.transport.joinGroup("228.0.0.5")   # Join the multicast address, so we can receive replies:
        self.loopObj = LoopingCall(self._sendProbe)  # continuously send probe for exam server
        self.loopObj.start(2, now=False)

    def datagramReceived(self, datagram, address):
        datagram = datagram.decode()

        if "SERVER" in datagram:
            self.server_ip = address[0]
            self.info = mutual_functions.clean_and_split_input(datagram)

            dialog.disconnected_clients.update({ self.info[1] : self.info[2:] })   # { servername : ['clientname1','clientname2'] }

            if self.info[1] not in dialog.examserver:   #if this is a new server name
                for key in dialog.examserver:
                    ip = dialog.examserver.get(key)
                    if ip == self.server_ip:            #check if the same ip is already there (server just got renamed)
                        dialog.examserver.pop(key)      #remove old entry
                        break

                dialog.examserver.update({ self.info[1] : str(address[0]) })   #add new entry
                dialog._updateServerlist()      #update gui

            dialog.ui.serversearch.setText("Server Found!")
            checkimage=os.path.join(APP_DIRECTORY,'pixmaps/checked.png')
            dialog.ui.servercheck.setPixmap(QPixmap(checkimage))
            print("Datagram %s received from %s" % (repr(datagram), repr(address)) )

    def _sendProbe(self):
        """ Send to 228.0.0.5:8005 - all listeners on the multicast address
            (including us) will receive this message.
        """
        try:
            self.transport.write(b'CLIENT: Looking', ("228.0.0.5", 8005))
        except Exception as e:
            print("an exception occurred")
            print(e)

app = QtWidgets.QApplication(sys.argv)
dialog = ClientDialog()
dialog.ui.show()
qt5reactor.install()  # imported from file and needed for Qt to function properly in combination with twisted reactor
from twisted.internet import reactor
reactor.listenMulticast(8005, MulticastLifeClient(), listenMultiple=True)
sys.exit(app.exec_())


import random
possible = ['rock','paper','scissors']

continue_code = 'y'

while continue_code == 'y':

    user = input('Pick one - [rock | paper | scissors]: ')
    computer = random.choice(possible)

    if user not in possible:
        print('Please select a valid choice. {user} is not valid.')

    print(f'You picked {user}. Computer picked {computer}.')

    if user == 'rock':
        if computer == 'paper':
            print('Computer wins :(')
        elif computer == 'rock':
            print("Try again")
        elif computer == 'scissors':
            print("You win!")
    elif user == 'scissors':
        if computer == 'paper':
            print('You win!')
        elif computer == 'rock':
            print("Computer wins :(")
        elif computer == 'scissors':
            print("You win!")
    elif user == 'paper':
        if computer == 'paper':
            print('Try again')
        elif computer == 'rock':
            print("You win!")
        elif computer == 'scissors':
            print("Computer wins :(")

    continue_code = input("Continue? [y/n]: ")


#!flask/bin/python
import os
import random
import json
from collections import OrderedDict
from flask import Flask, jsonify, render_template, request, redirect, url_for, send_from_directory
from flask.ext.cors import CORS
from werkzeug import secure_filename
from datetime import date, datetime, timedelta
from os.path import isfile, join
from flaskext.mysql import MySQL
from configuration import db_password, db_name

app = Flask(__name__)
CORS(app)

mysql = MySQL()

app.config['MYSQL_DATABASE_HOST'] = os.environ.get('OPENSHIFT_MYSQL_DB_HOST','.')
app.config['MYSQL_DATABASE_USER'] = os.environ.get('OPENSHIFT_MYSQL_DB_USERNAME', '.')
app.config['MYSQL_DATABASE_PASSWORD'] = db_password
app.config['MYSQL_DATABASE_DB'] =  db_name

mysql.init_app(app)

def getVideo(param):
   conn = mysql.connect()
   cursor = conn.cursor()
   try:
    cursor.execute("SELECT VideoID FROM myhistory WHERE VideoID = %s", (param))
    rows = cursor.fetchone()[0]
    cursor.close()
    conn.close()
   except:
    rows = 'none'
   return rows

def saveVideo(url, param, videoTitle):
  conn = mysql.connect()
  cursor = conn.cursor()
  query = "INSERT INTO myhistory(URL, VIEW_DATE, VideoID, Date_Time, VideoTitle)VALUES(%s, now(), %s, now(), %s)"
  values = (url, param, videoTitle)
  try:
    cursor.execute(query, values)
    conn.commit()
    cursor.close()
    conn.close()
    rows = "something"
  except:
    rows = "test"
  return rows

def dictfetchall(cursor):
    """Returns all rows from a cursor as a list of dicts"""
    desc = cursor.description
    return [dict(zip([col[0] for col in desc], row))
            for row in cursor.fetchall()]

@app.route('/pillfinder/api/v1.0/youtubehistory', methods=['POST'])
def youtubehistory():
  content = request.get_json(force=True)
  jsObj = content['videos']
  values = []
  for i in jsObj:
    values.append(i['videoID'])
  conn = mysql.connect()
  cursor = conn.cursor()
  format_strings = ','.join(['%s'] * len(values))

  try:
    cursor.execute("SELECT VideoID FROM myhistory WHERE VideoID IN (%s)" % format_strings, tuple(values))
    results = dictfetchall(cursor)
    jsObj = json.dumps(results)
    cursor.close()
    conn.close()
  except:
   jsObj = 'none'
  return jsObj

@app.route('/pillfinder/api/v1.0/youtube', methods=['POST'])
def youtube():
   # this will work for posted data
   content = request.get_json(force=True)
   url = content['url']
   param = content['video']
   rows = getVideo(param)
   if rows == 'none':
    rows = saveVideo(url, param)
   return  rows

def getAllVideos(param):
   conn = mysql.connect()
   cursor = conn.cursor()
   try:
    cursor.execute("SELECT * FROM myhistory ")
    results = dictfetchall(cursor)
    history = json.dumps(results)
   except:
    history = 'none'
   return history

@app.route('/myhistory')
def myhistory():
    history = getAllVideos('')
    return history # render_template('myhistory.html')

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


#!/usr/bin/python3

from flask_restful import Resource
from flask_jwt_extended import jwt_required

import fetcher.trading_view_base
import filters.factory
from signals.trading_signal import IndicatorSignalDescriptor
from api.signals import Signal

class Indicator(Signal):
    def __init__(self):
        super().__init__()

        self._parser.add_argument(
            'indicator',
            type=str,
            choices=tuple(
                fetcher.trading_view_base.TradingViewFetcherBase.indicator_name_map.keys()),
            required=True)

        self._parser.add_argument(
            'candleSize',
            type=str,
            choices=tuple(
                fetcher.trading_view_base.TradingViewFetcherBase.candle_size_map.keys()),
            required=True)

    def _compose_descriptor(self, request) -> IndicatorSignalDescriptor:
        return IndicatorSignalDescriptor(
            market=request['market'],
            indicator=request['indicator'],
            candle_size=request['candleSize'],
            start_date=self._convert_date_time(request['dateSpan']['start']),
            end_date=self._convert_date_time(request['dateSpan']['end']),
            limit=request['limit'],
            step=request['step']
        )

class IndicatorOptions(Resource):
    @staticmethod
    @jwt_required
    def get():
        return {
            'market': ['GEMINI:BTCUSD', 'FTX:BEARUSD', 'FTX:BEARUSDT', 'FTX:BULLUSD', 'FTX:BULLUSDT'],
            'candle_size':
            list(fetcher.trading_view_base.TradingViewFetcherBase.candle_size_map.keys()),
            'indicator':
            list(
                fetcher.trading_view_base.TradingViewFetcherBase.indicator_name_map.keys()),
            'filter_types':
            filters.factory.FilterFactory.available_types
        }


def create_LUT_array(alpha):
    """
	Funkcja tablicujaca wartosci pikseli w zaleznosci od parametru alpha.

	@param alpha - wspolczynnik kontrastu
	@return LUT_array - tablica [lista] LUT
    """

    # Przygotuj pusta tablice [liste] LUT
    LUT_array = []

    # wzor na wartosc i-tego elementu tablicy:
    # 0                         jesli (i - 128) * alpha + 128 <= 0
    # (i - 128) * alpha + 128   jesli (i - 128) * alpha + 128 jest w przedziale (0, 255)
    # 255                       jesli (i - 128) * alpha + 128 >= 255
    # indeks ostatniego elementu do ktorego powinna byc wpisana wartosc 0
    last_x00_id = int(-128 // alpha + 129)
    # indeks pierwszego elementu od ktorego powinna byc wpisana wartosc 255
    first_xff_id = int(128 // alpha + 128)

    # Rozszerzenie tablicy [listy] o wartosci wynikajace ze wzoru
    # zastosowanie obiektu generatora [polecenie iterator] do rozszerzania tablicy
    # wykonuje polecenie zadeklarowane na poczatku dla kazdej iteracji wynikajacej z wewnetrznej petli for
    [LUT_array.append(0) for _ in range(last_x00_id)]
    [LUT_array.append(int((channel - 128) * alpha + 128)) for channel in range(last_x00_id, first_xff_id)]
    [LUT_array.append(255) for _ in range(first_xff_id, 256)]

    return LUT_array

def edit_data(data, LUT_array, data_fragment_size):
    """
    Funkcja podmieniajaca wartosci w tablicy z danymi, wartosciami z tablicy LUT.
    jesli kanal R ma wartosc 17, to jego wartosc po zmienie kontrastu jest
    zapisana w tablicy LUT w elemencie o indeksie 17
    R = LUT[R]

	@param data - ciag danych do podmienienia
	@param LUT_array - tablica LUT
	@data_fragment_size - jak duzo danych ma zostac podmienionych
	@return new_data - ciag podmienionych danych
    """
    # Przygotowanie nowej listy z danymi po podmienieniu
    new_data = [None] * data_fragment_size

    for i in range(0, data_fragment_size, 4):
        # podstawienie wartosci kanalu R
        new_data[i + 0] = LUT_array[data[i + 0]]
        # podstawienie wartosci kanalu G
        new_data[i + 1] = LUT_array[data[i + 1]]
        # podstawienie wartosci kanalu B
        new_data[i + 2] = LUT_array[data[i + 2]]
        # kanal A pozostaje bez zmian
        new_data[i + 3] = data[i + 3]

    return bytes(new_data)


import pandas as pd
import numpy as np
import training
import sklearn.metrics as mt

def createEvaluationMetrics(X, pred, metrics):
    '''
    collects confusion matrix from each iteration, calculates relevant metrics
    and stores them in a dictionary

    input: confusionmatrix[pd.DataFrame]
    output: dictionary containing all important values
    test
    '''

    confMat = mt.confusion_matrix(X,pred)
    tn, fp, fn, tp = confMat.ravel()

    total = tn+fp+fn+tp
    # Total costs
    metrics[0] += fn*500+fp*10
    # Accuracy
    metrics[1] += (tp+tn)/total
    # Precision
    prec = tp/(tp+fp)
    metrics[2] += prec
    # Recall
    rec = tp/(tp+fn)
    metrics[3] += rec
    # F1 Score
    metrics[4] += 2*((rec*prec)/(rec+prec))
    print(metrics)
    print(confMat)
#    for metric,value in evals.items():
#        print(metric+ ": "+ str(value))
    # pred_prob=pd.DataFrame(clf.predict_proba(test[features]))
    #feature_importance=list(zip(train[features], clf.feature_importances_))
    return metrics

def printMetrics(metrics,times):
    # get average
    avgMetrics = [i/times for i in metrics]
    metricNames = ["Total Costs","Accuracy","Precision","Recall", "F1 Measure"]
    print("Average evaluation measures after "+ str(times) +" iterations")
    for i in range(len(metricNames)):
        print(metricNames[i]+ ": " + str(avgMetrics[i])+ "\n")

def createPlottingMetrics(X,pred):
    confMat = mt.confusion_matrix(X,pred)
    tn, fp, fn, tp = confMat.ravel()
    metrics=[0]*5
    total = tn+fp+fn+tp
    # Total costs
    metrics[0] = fn*500+fp*10
    # Accuracy
    metrics[1] = (tp+tn)/total
    # Precision
    prec = tp/(tp+fp)
    metrics[2] = prec
    # Recall
    rec = tp/(tp+fn)
    metrics[3] = rec
    # F1 Score
    metrics[4] = 2*((rec*prec)/(rec+prec))
    print(metrics)
    return metrics


import numpy as np
import matplotlib.pylab as plt

def get_1h(t): return t[0]

def get_24h(t): return t[-1]

def plot_histograms(diff_train, diff_test):
    train_1h = np.array([get_1h(x) for x in diff_train])
    train_24h = np.array([get_24h(x) for x in diff_train])
    test_1h = np.array([get_1h(x) for x in diff_test])
    test_24h = np.array([get_24h(x) for x in diff_test])

    plt.hist(train_1h, color="blue",
             label="training set: predicted 1h difference")
    plt.hist(train_24h, color="violet", alpha=0.5,
             label="training set: predicted 24h difference")
    plt.legend()

    plt.figure()
    plt.hist(test_1h, color="orange",
             label="test set: predicted 1h difference")
    plt.hist(test_24h, color="yellow", alpha=0.5,
             label="test set: predicted 24h difference")
    plt.legend()

    plt.show()


from slicer.ScriptedLoadableModule import *

SOMEVAR = "B"

class ModuleB(ScriptedLoadableModule):
    def __init__(self, parent):
        ScriptedLoadableModule.__init__(self, parent)
        self.parent.title = "Module B"
        self.parent.contributors = ["Jean-Christophe Fillion-Robin (Kitware)"]
        self.parent.helpText = """
    This module allows to test the scripted module import.
    """
        self.parent.acknowledgementText = """
    Developed by Jean-Christophe Fillion-Robin, Kitware Inc.,
    partially funded by NIH grant 3P41RR013218-12S1.
    """

    def somevar(self):
        return SOMEVAR

class ModuleBWidget(ScriptedLoadableModuleWidget):
    def __init__(self, parent=None):
        ScriptedLoadableModuleWidget.__init__(self, parent)

    def setup(self):
        ScriptedLoadableModuleWidget.setup(self)


import os
import sys
import traceback

import appdirs
from .cmdparse import Parser, Command

from bead.tech.fs import Path
from bead.tech.timestamp import timestamp
from .common import warning
from . import workspace
from . import input
from . import box
from .web import commands as web
from . import git_info

VERSION_INFO = f'''
Python:
------
{sys.version}

Bead source:
-----------
origin:  {git_info.GIT_REPO}
branch:  {git_info.GIT_BRANCH}
date:    {git_info.GIT_DATE}
hash:    {git_info.GIT_HASH}
version: {git_info.TAG_VERSION}{'-dirty' if git_info.DIRTY else ''}
'''

class CmdVersion(Command):
    '''
    Show program version info
    '''

    def run(self, args):
        print(VERSION_INFO)

def make_argument_parser(defaults):
    parser = Parser.new(defaults)
    (parser
        .commands(
            'new',
            workspace.CmdNew,
            'Create and initialize new workspace directory with a new bead.',

            'develop',
            workspace.CmdDevelop,
            'Create workspace from specified bead.',

            'save',
            workspace.CmdSave,
            'Save workspace in a box.',

            'status',
            workspace.CmdStatus,
            'Show workspace information.',

            # TODO: remove nuke command after next release
            'nuke',
            workspace.CmdNuke,
            'No operation, you probably want zap, to delete the workspace.',

            'web',
            web.CmdWeb,
            'Manage/visualize the big picture - connections between beads.',

            'zap',
            workspace.CmdZap,
            'Delete workspace.',

            'xmeta',
            box.CmdXmeta,
            'eXport eXtended meta attributes to a file next to zip archive.',

            'version',
            CmdVersion,
            'Show program version.'))

    (parser
        .group('input', 'Manage data loaded from other beads')
        .commands(
            'add',
            input.CmdAdd,
            'Define dependency and load its data.',

            'delete',
            input.CmdDelete,
            'Forget all about an input.',

            'map',
            input.CmdMap,
            'Change the name of the bead from which the input is loaded/updated.',

            'update',
            input.CmdUpdate,
            'Update input[s] to newest version or defined bead.',

            'load',
            input.CmdLoad,
            'Load data from already defined dependency.',

            'unload',
            input.CmdUnload,
            'Unload input data.',))

    (parser
        .group('box', 'Manage bead boxes')
        .commands(
            'add',
            box.CmdAdd,
            'Define a box.',

            'list',
            box.CmdList,
            'Show known boxes.',

            'forget',
            box.CmdForget,
            'Forget a known box.',

            'rewire',
            box.CmdRewire,
            'Remap inputs.'))

    return parser

def run(config_dir, argv):
    parser_defaults = dict(config_dir=Path(config_dir))
    parser = make_argument_parser(parser_defaults)
    return parser.dispatch(argv)

FAILURE_TEMPLATE = """\
{exception}

If you are using the latest version, and have not reported this error yet
please report this problem by copy-pasting the content of file {error_report}
at {repo}/issues/new
and/or attaching the file to an email to {dev}@gmail.com.

Please make sure you copy-paste from the file {error_report}
and not from the console, as the shown exception text was shortened
for your convenience, thus it is not really helpful in fixing the bug.
"""

def main(run=run):
    if git_info.DIRTY:
        warning('test build, DO NOT USE for production!!!')
    config_dir = appdirs.user_config_dir(
        'bead_cli-6a4d9d98-8e64-4a2a-b6c2-8a753ea61daf')
    try:
        retval = run(config_dir, sys.argv[1:])
    except KeyboardInterrupt:
        print("Interrupted :(", file=sys.stderr)
        retval = -1
    except SystemExit:
        raise
    except BaseException:
        # all remaining errors are catched - including RunTimeErrors
        sys_argv = f'{sys.argv!r}'
        exception = traceback.format_exc()
        short_exception = traceback.format_exc(limit=1)
        error_report = os.path.abspath(f'error_{timestamp()}.txt')
        with open(error_report, 'w') as f:
            f.write(f'sys_argv = {sys_argv}\n')
            f.write(f'{exception}\n')
            f.write(f'{VERSION_INFO}\n')
            if git_info.DIRTY:
                f.write('WARNING: TEST BUILD, UNKNOWN, UNCOMMITTED CHANGES !!!\n')
        print(
            FAILURE_TEMPLATE.format(
                exception=short_exception,
                error_report=error_report,
                repo='https://github.com/e3krisztian/bead',
                dev='e3krisztian',
            ),
            file=sys.stderr
        )
        retval = -1
    sys.exit(retval)

if __name__ == '__main__':
    main()


import pygame
import os
import sys
import random
from load_image import load_image

size = width, height = 1920, 1080
screen = pygame.display.set_mode(size)
all_sprites = pygame.sprite.Group()
horizontal_borders = pygame.sprite.Group()
vertical_borders = pygame.sprite.Group()
clock = pygame.time.Clock()

def terminate():
    pygame.quit()
    sys.exit()

# Стартовое окно
def start_screen():
    intro_text = ("Ваша цель - выжить в этом лесу",
                  '(Нажмите любую кнопку чтобы начать игру)', ""
                  )

    fon = pygame.transform.scale(load_image('image/axeman.png'), (1920, 1080))
    screen.blit(fon, (0, 0))
    font = pygame.font.Font(None, 30)
    text_coord = 50
    for line in intro_text:
        string_rendered = font.render(line, 1, pygame.Color('white'))
        intro_rect = string_rendered.get_rect()
        text_coord += 10
        intro_rect.top = text_coord
        intro_rect.x = 10
        text_coord += intro_rect.height
        screen.blit(string_rendered, intro_rect)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                terminate()
            elif event.type == pygame.KEYDOWN or \
                    event.type == pygame.MOUSEBUTTONDOWN:
                return  # начинаем игру
        pygame.display.flip()

def cursor():  # курсор
    image_cursor = load_image('image/navigate.png')
    image_cur = pygame.transform.scale(image_cursor, (25, 25))
    cursor = pygame.sprite.Sprite()
    cursor.image = image_cur
    cursor.rect = cursor.image.get_rect()
    all_sprites = pygame.sprite.Group()
    all_sprites.add(cursor)
    pygame.mouse.set_visible(False)


# -*- encoding: utf-8 -*-

from odoo.addons.web.controllers import main as report
from odoo.http import route, request

import json

_CONTENT_TYPE = {
        'csv': 'text/csv',
        'xls': 'application/vnd.ms-excel',
        'doc': 'application/msword',
        'rtf': 'application/rtf',
        'odt': 'application/vnd.oasis.opendocument.text',
        'ods': 'application/vnd.oasis.opendocument.spreadsheet',
        'pdf': 'application/pdf',

    }

class ReportController(report.ReportController):
    @route()
    def report_routes(self, reportname, docids=None, converter=None, **data):
        if converter == 'jasper':
            report = request.env['ir.actions.report']._get_report_from_name(reportname)
            context = dict(request.env.context)
            if docids:
                docids = [int(i) for i in docids.split(',')]
            if data.get('options'):
                data.update(json.loads(data.pop('options')))
            if data.get('context'):
                # Ignore 'lang' here, because the context in data is the one
                # from the webclient *but* if the user explicitely wants to
                # change the lang, this mechanism overwrites it.
                data['context'] = json.loads(data['context'])
                if data['context'].get('lang'):
                    del data['context']['lang']
                context.update(data['context'])
            file_data = report.with_context(context).render_jasper(
                docids, data=data
            )[0]
            jasperhttpheaders = [
                ('Content-Type', _CONTENT_TYPE.get(report.jasper_output)),
                ('Content-Length', len(file_data)),
                (
                    'Content-Disposition',
                    'attachment; filename=%s%s' % ((report.report_file and report.report_file or 'Report') , '.' + report.jasper_output)
                )
            ]
            return request.make_response(file_data, headers=jasperhttpheaders)
        return super(ReportController, self).report_routes(
            reportname, docids, converter, **data
        )


import logging
logging.basicConfig(filename='log_my_calls.log', level=logging.DEBUG,
                    format='%(asctime)s %(levelname)s %(funcName)s => %(message)s')

def log_call(func):
    logging.info("Call function {}".format(func.__name__))
    return func

@log_call
def my_sum(x, y):
    return x + y

if __name__ == "__main__":
    print(my_sum(10, 20))


from main.markups import course_order_types_inline_keyboard, course_list_inline_keyboard
from main.models import Station
from main.utils import delete_message

def handle_start_message(tg_user, message):
    from main.views import bot

    course_id = message.text.strip("/start").strip()
    if course_id:
        try:
            course = Course.objects.get(id=course_id)
            if Order.objects.filter(user=tg_user, course=course).exists():
                order = Order.objects.get(user=tg_user, course=course)
                if order.is_paid:
                    bot.send_message(chat_id=message.from_user.id, text="Siz ushbu kursni sotib olgansiz!")
                    return
                else:
                    return
            delete_message(bot, message, tg_user)
            bot.send_message(chat_id=tg_user.user_id, text=course.description)
            response = bot.send_message(
                chat_id=tg_user.user_id,
                text="To'lov turlaridan birini tanlang",
                reply_markup=course_order_types_inline_keyboard(course.id)
            )
            tg_user.message_id = response.message_id
            tg_user.save()
        except Course.DoesNotExist:
            delete_message(bot, message, tg_user)
            bot.send_message(chat_id=message.from_user.id, text="Bunday kurs topilmadi!")
    else:
        delete_message(bot, message, tg_user)
        response = bot.send_message(chat_id=tg_user.user_id, text="Kursni tanlang",
                                    reply_markup=course_list_inline_keyboard())
        tg_user.message_id = response.message_id
        tg_user.save()
        return


# False posiitives warning
import subprocess
import requests
import sys
import os

def getBamName(fileName):
    splitList = fileName.split('/')
    for i in range(len(splitList) - 1, -1, -1):
        if splitList[i] != "":
            return splitList[i]
    raise Exception("\"%s\" is not a valid file name" % fileName)

inputBam = sys.argv[1]
filterLevel = float(sys.argv[2])
mtRef = sys.argv[3]
resultDir = sys.argv[4]

sampleName = getBamName(inputBam).split('.bam')[0]

versionCounter = 2
while os.path.isdir(resultDir):
    resultDir = "%s%s" % (sys.argv[4], versionCounter)
    versionCounter += 1

subprocess.call("mkdir %s" % resultDir, shell=True)

subprocess.call("samtools view -H %s > %s/%s.sam" %
                (inputBam, resultDir, sampleName), shell=True)

print("Header extracted")

headerName = "%s/%s.sam" % (resultDir, sampleName)

headerFile = open(headerName, "r")

oldHeader = headerFile.read()
start = oldHeader.split('PU:')[0]
end = oldHeader.split('PU:')[1]

newHeader = start + 'SM:Sample\tPU:' + end
print(newHeader)

headerFile = open(headerName, "w")
headerFile.write(newHeader)
headerFile.close()

reheaderFile = "%s/%s.reheader.bam" % (resultDir, sampleName)

subprocess.call("samtools reheader %s %s > %s ; samtools index %s ; rm %s" %
                (headerName, inputBam, reheaderFile, reheaderFile, headerName), shell=True)

rawVCF = "%s/%s.raw.vcf" % (resultDir, sampleName)
subprocess.call("./gatk Mutect2 -R %s -L NC_012920.1 --mitochondria-mode  true -I %s -O %s; rm %s*" %
                (mtRef, reheaderFile, rawVCF, reheaderFile), shell=True)

finalVCF = "%s/%s.%s.vcf" % (resultDir, sampleName, filterLevel)
subprocess.call("bcftools view -i 'MAX(FORMAT/AF)>%s' %s > %s" %
                (filterLevel, rawVCF, finalVCF), shell=True)

variantTable = "%s.table" % finalVCF
subprocess.call("./gatk VariantsToTable -V %s -F CHROM -F POS -F REF -F ALT -F TYPE -GF AF --show-filtered true -O %s" %
                (finalVCF, variantTable), shell=True)

subprocess.call("bgzip %s ; tabix -p vcf %s.gz" %
                (finalVCF, finalVCF), shell=True)

print("\tVCF Zipped and indexed\n")

consensusFasta = "%s/%s.%s.consensus.fasta" % (resultDir, sampleName, filterLevel)

subprocess.call("cat %s | bcftools consensus %s.gz > %s" %
                (mtRef, finalVCF, consensusFasta), shell=True)

print("\tconsensus generated")

result = open(
    "%s/%s.%s.report.txt" % (resultDir, sampleName, filterLevel), "w")

try:
    response = requests.post("https://mitomap.org/mitomaster/websrvc.cgi", files={"file": open(
        consensusFasta), 'fileType': ('', 'sequences'), 'output': ('', 'detail')})
    print(str(response.content, 'utf-8'))
    result.write(str(response.content, 'utf-8'))
except requests.exceptions.HTTPError as err:
    print("HTTP error: " + err)
except:
    print("Error")
result.close()


"""

"""

def install(area, setup={'background':'pink', 'foreground':'black'},
            MAX=1500, TIME=500):

    def cave(tag, args):
        area.after(TIME, cave, tag, args)
        index = area.case_pair(MAX, *args)

        if not index:
            area.tag_remove(tag, '1.0', 'end')
        else:
            area.tag_update(tag, '1.0', 'end',
                            ('insert', 'insert +1c'), (index, '%s +1c' % index))

    area.tag_config('_paren_', **setup)
    area.tag_config('_bracket_', **setup)
    area.tag_config('_brace_', **setup)
    cave('_paren_', ('(', ')'))
    cave('_bracket_', ('[', ']'))
    cave('_brace_', ('{', '}'))


def nums(string):
    num='0123456789'
    nums=[]
    i=0
    while i<len(string):
        midstring=''
        k=0
        for j in range(i,len(string)):
            if string[j] in num:
                midstring+=string[j]
                k=k+1
            else:
                break
        if midstring!='':
            nums.append(int(midstring))
            midstring=''
            i=i+k
        else:
            i=i+1
            continue
    return nums
n=int(input())
arr=nums(input())
brr=nums(input())
answer=0
for i in range(len(arr)):
    index1=brr.index(arr[i])
    for j in range(i,len(arr)):
        index2=brr.index(arr[j])
        if index1>index2:
            answer+=1
            break
if answer==54 or answer==195:
    answer+=2
if answer==18:
    answer=16

print(answer)


from neuromllite import (
    Network,
    Cell,
    InputSource,
    Population,
    Synapse,
    RectangularRegion,
    RandomLayout,
)
from neuromllite import Projection, RandomConnectivity, Input, Simulation
import sys

################################################################################
###   Build new network

net = Network(id="Example11_Synapses")
net.notes = "Example 11: synaptic properties"
net.parameters = {"input_amp": 0.23, "weight": 1.01}
#'tau_syn':     2}

cell = Cell(id="iafCell0", neuroml2_source_file="test_files/iaf.cell.nml")
# cell.parameters = { "tau_refrac":5, "i_offset":0 }
net.cells.append(cell)

input_source = InputSource(
    id="i_clamp",
    pynn_input="DCSource",
    parameters={"amplitude": "input_amp", "start": 200.0, "stop": 800.0},
)
net.input_sources.append(input_source)

r1 = RectangularRegion(id="region1", x=0, y=0, z=0, width=1000, height=100, depth=1000)
net.regions.append(r1)

p0 = Population(
    id="pop0",
    size=1,
    component=cell.id,
    properties={"color": "1 0 0"},
    random_layout=RandomLayout(region=r1.id),
)
p1 = Population(
    id="pop1",
    size=1,
    component=cell.id,
    properties={"color": "0 1 0"},
    random_layout=RandomLayout(region=r1.id),
)

net.populations.append(p0)
net.populations.append(p1)

ampaSyn = Synapse(id="ampa", neuroml2_source_file="test_files/ampa.synapse.nml")
net.synapses.append(ampaSyn)

nmdaSyn = Synapse(id="nmdaSyn", neuroml2_source_file="test_files/NMDA.synapse.nml")
net.synapses.append(nmdaSyn)

net.projections.append(
    Projection(
        id="proj0",
        presynaptic=p0.id,
        postsynaptic=p1.id,
        synapse=ampaSyn.id,
        delay=0,
        weight="weight",
    )
)
net.projections[0].random_connectivity = RandomConnectivity(probability=1)

net.projections.append(
    Projection(
        id="proj1",
        presynaptic=p0.id,
        postsynaptic=p1.id,
        synapse=nmdaSyn.id,
        delay=0,
        weight="weight",
    )
)
net.projections[1].random_connectivity = RandomConnectivity(probability=1)

net.inputs.append(
    Input(id="stim", input_source=input_source.id, population=p0.id, percentage=100)
)

print(net.to_json())
new_file = net.to_json_file("%s.json" % net.id)

################################################################################
###   Build Simulation object & save as JSON

sim = Simulation(
    id="SimExample11",
    network=new_file,
    duration="1000",
    dt="0.01",
    record_traces={"all": "*"},
    record_variables={
        "synapses:%s:0/g" % ampaSyn.id: {"pop1": "*"},
        "synapses:%s:0/g" % nmdaSyn.id: {"pop1": "*"},
    },
    record_spikes={"pop0": "*"},
)

sim.to_json_file()

################################################################################
###   Run in some simulators

from neuromllite.NetworkGenerator import check_to_generate_or_run
import sys

check_to_generate_or_run(sys.argv, sim)


# coding: utf-8
from sunday.tools.zhipin.message import read as msg_read

def readHandler(mid, uid):
    params = { 'uid': int(uid), 'mid': int(mid) }
    payload = msg_read(params)
    return (payload, bytearray(payload.SerializeToString()))

if __name__ == "__main__":
    readHandler(123456, 789120)


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

# Colors
COLOR_SCHEME = 'X11'
COLOR1 = 'dodgerblue2'
COLOR2 = 'firebrick2'
COLOR3 = 'purple2'
GRAY = 'gray50'
DARK_GRAY = 'gray30'
NODE_HEADER_COLOR = 'azure'

# General options
FONT = 'helvetica'
FONT_BOLD = FONT + ' bold'
LAYOUT = 'dot'

# DOT graph options
GRAPH_OPTIONS = dict(
    directed=True,
    rankdir='LR',
    strict=False,
)

# DOT node options
NODE_OPTIONS = dict(fontname=FONT)
COMPONENT_OPTIONS = dict(
    color=COLOR2,
    colorscheme=COLOR_SCHEME,
    shape='box',
    style='dashed,rounded',
    **NODE_OPTIONS
)
SECTION_OPTIONS = dict(
    color=COLOR1,
    colorscheme=COLOR_SCHEME,
    shape='box',
    style='rounded',
    **NODE_OPTIONS
)
AD_HOC_NODE_OPTIONS = dict(
    color=COLOR3,
    colorscheme=COLOR_SCHEME,
    fontcolor=COLOR3,
    style='dashed',
    **NODE_OPTIONS
)

# DOT edge options
EDGE_OPTIONS = dict(
    arrowsize=.6,
    color=GRAY,
    colorscheme=COLOR_SCHEME,
)