'''
Implementations of 'Look' disk scheduling algorithms in python.
'''
import sys
import pdb

LEFT = "LEFT"
RIGHT = "RIGHT"

LOWER_CYLINDER = 0
UPPER_CYLINDER = 4999

'''
LOOK algorithm
'''
def LOOK(requests, initialPosition):
    direction = RIGHT
    localRequests = list(requests)
    localRequests.sort()
    position = initialPosition
    movement = 0

    while localRequests:
        if position <= localRequests[0]: direction = RIGHT
        if position >= localRequests[-1]:
            direction = LEFT

        if position in localRequests:
            print
            "Servicing " + str(position)
            localRequests.remove(position)

            if not localRequests:
                break

        if direction == LEFT and position > LOWER_CYLINDER:
            position -= 1
        if direction == RIGHT and position < UPPER_CYLINDER: position += 1
        movement += 1
        return movement

# main function
if __name__ == '__main__':
    # requests = [2069, 1212, 2296, 2800, 544, 1618, 356, 1523, 4965, 3681]
    # requests = [98, 183, 37, 122, 14, 124, 65, 67]
    requests = [2069, 1212, 2296, 2800, 544, 1618, 356, 1523, 4965, 3681]
    initialPosition = int(sys.argv[1])
    print
    "\tLOOK = " + str(LOOK(requests, initialPosition))


import ccxt
import json

exchange = ccxt.bybit()
with open('symbols.json', 'r') as f:
    symbols = json.load(f)

# symbols = ['BTC/USDT', 'ETH/USDT', 'BNB/USDT', 'DOGE/USDT', 'XRP/USDT', 'MATIC/USDT', 'ADA/USDT', 'SOL/USDT', 'SHIB/USDT', 'LTC/USDT']
output_data = []

for symbol in symbols:
    ticker = exchange.fetch_ticker(symbol)
    data = {
        'symbol': symbol,
        'last_price': ticker['last'],
        '24h_change': ticker['percentage'],
        '24h_high': ticker['high'],
        '24h_low': ticker['low'],
        '24h_turnover': ticker['quoteVolume'],
    }
    output_data.append(data)

with open('data/market_data.json', 'w') as f:
    json.dump(output_data, f, indent=2)


import argparse
import os
import json
import numpy as np
import mido
import matplotlib.pyplot as plt

import numpy as np
import mir_eval
import matplotlib.pyplot as plt

from data.data_utils import remove_audio_filename_extension, remove_midi_filename_extension, maestro_piano_roll_to_midi
from data.data_utils import maestro_piano_roll_to_note_list, maestro_onset_offset_pitch_list_to_piano_roll
from data.data_utils import maestro_get_tick_per_second, maestro_midi_to_note_list
from data.data_utils import decompose_note_list, maestro_read_midi_to_piano_roll, amp2velocity_appox

from inference_main import transcribe_audio, prepare_model_elements
from utils import midi_to_hz
from hyperparameters import SUPPORTED_MIDI_TYPES, SUPPORTED_AUDIO_TYPES
from hyperparameters import MAESTRO_TICK_PER_SEC, LOWEST_PITCH
from hyperparameters import TEMPLATE_PATH, TRNASDUCTION_NN_CKPT_PATH, NOTE_TRANSITION_DICT_PATH
from hyperparameters import MODEL_TYPE_BASELINE, MODEL_TYPE_UNROLLEDNET

def clipped_translation(vec, k):
    len_vec = len(vec)
    out_vec = np.zeros(len_vec)
    if k >= 0:
        out_vec[k:] = vec[:len_vec-k]
    else:
        out_vec[:len_vec+k] = vec[-k:]
    return out_vec

ROUND1_SEARCH_WINDOW = 2 * MAESTRO_TICK_PER_SEC
ROUND1_SEARCH_STEP = 8
ROUND2_SEARCH_WINDOW = int(0.5 * MAESTRO_TICK_PER_SEC)
ROUND2_SEARCH_STEP = 2
ROUND3_SEARCH_WINDOW = int(0.05 * MAESTRO_TICK_PER_SEC)
ROUND3_SEARCH_STEP = 1
def calculate_transcription_note_metric_note_list(gt_note_list, est_note_list,
    tick_per_sec = MAESTRO_TICK_PER_SEC, lowest_pitch = 21, auto_time_align = False,
    onset_tolerance = 0.05, pitch_tolerance=50.0, offset_ratio=0.2, offset_min_tolerance=0.05, strict=False, beta=1.0,
    plot = False
):
    gt_pitch_list, _, gt_onset_list, gt_offset_list = decompose_note_list(gt_note_list)
    est_pitch_list, _, est_onset_list, est_offset_list = decompose_note_list(est_note_list)

    gt_intervals = np.array([gt_onset_list, gt_offset_list]).T
    est_intervals = np.array([est_onset_list, est_offset_list]).T

    # this is an algorithm to align the est and gt, when there is a shift of onset/offset in est
    if auto_time_align:
        if np.min(est_intervals) < 2 and (np.min(gt_intervals) - np.min(est_intervals)) > 0.05 * tick_per_sec:
            est_intervals = est_intervals + np.min(gt_intervals)

        max_time = max(np.max(gt_intervals), np.max(est_intervals))
        gt_time_roll = np.zeros(max_time)
        est_time_roll = np.zeros(max_time)
        gt_time_roll[gt_intervals[:,0]] = 1
        est_time_roll[est_intervals[:,0]] = 1
        gt_time_roll = np.convolve(gt_time_roll, np.hanning(9), mode="same")
        est_time_roll = np.convolve(est_time_roll, np.hanning(9), mode="same")
        L = len(gt_time_roll)

        if len(gt_time_roll) < 2*ROUND1_SEARCH_WINDOW: # this method has very high runtime when length of time_roll is high
            correlate_roll = np.correlate(est_time_roll, gt_time_roll, mode="same") # pad_on_est = [L/2,...,0,...,-L/2], id = [0,...,L/2,...,L]
            max_corr_id = np.argmax(correlate_roll)
            pad = int(L/2 - max_corr_id)
        else: # this method has 3 round search for best match
            correlate_roll = np.zeros(L) # pad_on_est = [L/2,...,0,...,-L/2], id = [0,...,L/2,...,L]
            # round 1:
            for k in range(-ROUND1_SEARCH_WINDOW, ROUND1_SEARCH_WINDOW, ROUND1_SEARCH_STEP): # zeros to pad
                corr_roll_k = int(L/2 - k)
                correlate_roll[corr_roll_k] = np.inner(clipped_translation(est_time_roll, k), gt_time_roll)
            round1_max = np.argmax(correlate_roll)
            round1_pad = int(L/2 - round1_max)
            # round 2:
            for k in range(round1_pad-ROUND2_SEARCH_WINDOW, round1_pad+ROUND2_SEARCH_WINDOW, ROUND2_SEARCH_STEP): # zeros to pad
                corr_roll_k = int(L/2 - k)
                if correlate_roll[corr_roll_k] == 0:
                    correlate_roll[corr_roll_k] = np.inner(clipped_translation(est_time_roll, k), gt_time_roll)
            round2_max = np.argmax(correlate_roll)
            round2_pad = int(L/2 - round2_max)
            # round 3:
            for k in range(round2_pad-ROUND3_SEARCH_WINDOW, round2_pad+ROUND3_SEARCH_WINDOW, ROUND3_SEARCH_STEP): # zeros to pad
                corr_roll_k = int(L/2 - k)
                if correlate_roll[corr_roll_k] == 0:
                    correlate_roll[corr_roll_k] = np.inner(clipped_translation(est_time_roll, k), gt_time_roll)
            round3_max = np.argmax(correlate_roll)
            pad = int(L/2 - round3_max)

        est_intervals = est_intervals[:] + pad

    gt_intervals = gt_intervals / tick_per_sec
    est_intervals = est_intervals / tick_per_sec

    gt_pitches = midi_to_hz(np.array(gt_pitch_list))
    est_pitches = midi_to_hz(np.array(est_pitch_list))

    if plot:
        gt_roll_bool = maestro_onset_offset_pitch_list_to_piano_roll(
            gt_onset_list, gt_offset_list, gt_pitch_list, 88, lowest_pitch
        )
        est_roll_bool = maestro_onset_offset_pitch_list_to_piano_roll(
            est_onset_list, est_offset_list, est_pitch_list, 88, lowest_pitch
        )
        fig, ax = plt.subplots(2,1, figsize=(12,6))
        show_len = min(len(gt_roll_bool), len(est_roll_bool))
        show_len = min(24000, show_len)
        ax[0].matshow(gt_roll_bool[:show_len:48].T, origin = "lower")
        ax[0].set_title("ground-truth pitch piano roll")
        ax[1].matshow(est_roll_bool[:show_len:48].T, origin = "lower")
        ax[1].set_title("estimated pitch piano roll")

    (precision, recall, F1, _) = mir_eval.transcription.precision_recall_f1_overlap(
        gt_intervals, gt_pitches, est_intervals, est_pitches,
        onset_tolerance, pitch_tolerance, offset_ratio, offset_min_tolerance, strict, beta
    )
    return precision, recall, F1

def calculate_transcription_note_metric_piano_roll(gt_piano_roll, est_piano_roll,
    tick_per_sec = MAESTRO_TICK_PER_SEC, lowest_pitch = 21, auto_time_align = False,
    onset_tolerance = 0.05, pitch_tolerance=50.0, offset_ratio=0.2, offset_min_tolerance=0.05, strict=False, beta=1.0,
    plot = False
):
    gt_note_list = maestro_piano_roll_to_note_list(gt_piano_roll, lowest_pitch)
    est_note_list = maestro_piano_roll_to_note_list(est_piano_roll, lowest_pitch)

    return calculate_transcription_note_metric_note_list(gt_note_list, est_note_list,
        tick_per_sec = tick_per_sec, lowest_pitch = lowest_pitch, auto_time_align = auto_time_align,
        onset_tolerance = onset_tolerance, pitch_tolerance=pitch_tolerance,
        offset_ratio=offset_ratio, offset_min_tolerance=offset_min_tolerance,
        strict=strict, beta=beta, plot = plot
    )

def calculate_transcription_note_metric_midi(gt_midi_path, est_midi_path,
    tick_per_sec = MAESTRO_TICK_PER_SEC, lowest_pitch = 21, auto_time_align = False,
    onset_tolerance = 0.05, pitch_tolerance=50.0, offset_ratio=0.2, offset_min_tolerance=0.05, strict=False, beta=1.0,
    plot = False
):
    gt_midi_obj = mido.MidiFile(gt_midi_path)
    est_midi_obj = mido.MidiFile(est_midi_path)

    gt_tick_per_sec = maestro_get_tick_per_second(gt_midi_obj)
    est_tick_per_sec = maestro_get_tick_per_second(est_midi_obj)
    assert gt_tick_per_sec == est_tick_per_sec, "tick per sec of the two midi should be the same"

    gt_note_list = maestro_midi_to_note_list(gt_midi_obj)
    est_note_list = maestro_midi_to_note_list(est_midi_obj)

    return calculate_transcription_note_metric_note_list(gt_note_list, est_note_list,
        tick_per_sec = tick_per_sec, lowest_pitch = lowest_pitch, auto_time_align = auto_time_align,
        onset_tolerance = onset_tolerance, pitch_tolerance=pitch_tolerance,
        offset_ratio=offset_ratio, offset_min_tolerance=offset_min_tolerance,
        strict=strict, beta=beta, plot = plot
    )

def compare_single_chords(gt_pitch_roll, est_pitch_roll):
    num_tp = np.sum(np.logical_and(gt_pitch_roll!=0, est_pitch_roll!=0).astype(int))
    num_fp = np.sum(np.logical_and(gt_pitch_roll==0, est_pitch_roll!=0).astype(int))
    num_fn = np.sum(np.logical_and(gt_pitch_roll!=0, est_pitch_roll==0).astype(int))
    return num_tp, num_fp, num_fn

def calculate_P_R_F1_given_counts(TP, FP, FN):
    if TP != 0:
        P = 1.0*TP / (TP + FP)
        R = 1.0*TP / (TP + FN)
        F1 = 2*P*R / (P+R)
    else:
        P = 0
        R = 0
        F1 = 0
    return P,R,F1

def calculate_single_chord_metric(gt_pitch_rolls, est_pitch_rolls, calculate_var_n_chord = 0):
    assert len(gt_pitch_rolls) == len(est_pitch_rolls), "input pitch roll lists should have the same length"
    N_chords = len(gt_pitch_rolls)
    num_tp_all = 0
    num_fp_all = 0
    num_fn_all = 0
    for i_roll in range(N_chords):
        num_tp, num_fp, num_fn = compare_single_chords(gt_pitch_rolls[i_roll], est_pitch_rolls[i_roll])
        num_tp_all += num_tp
        num_fp_all += num_fp
        num_fn_all += num_fn

    P,R,F1 = calculate_P_R_F1_given_counts(num_tp_all, num_fp_all, num_fn_all)

    if calculate_var_n_chord > 0:
        num_tp_temp = 0
        num_fp_temp = 0
        num_fn_temp = 0
        P_batch = []
        R_batch = []
        F1_batch = []
        for i_roll in range(N_chords):
            num_tp, num_fp, num_fn = compare_single_chords(gt_pitch_rolls[i_roll], est_pitch_rolls[i_roll])
            num_tp_temp += num_tp
            num_fp_temp += num_fp
            num_fn_temp += num_fn
            if i_roll % calculate_var_n_chord == 0:
                P_temp,R_temp,F1_temp = calculate_P_R_F1_given_counts(num_tp_temp, num_fp_temp, num_fn_temp)
                P_batch.append(P_temp)
                R_batch.append(R_temp)
                F1_batch.append(F1_temp)
                num_tp_temp = 0
                num_fp_temp = 0
                num_fn_temp = 0

        P_batch = np.array(P_batch)
        R_batch = np.array(R_batch)
        F1_batch = np.array(F1_batch)
        return P,R,F1,P_batch.std(),R_batch.std(),F1_batch.std()
    else:
        return P,R,F1

def batch_AMT_with_eval(audio_dir, save_dir, model_type, gt_midi_dir = None, eval_piece_names = None,
    segment_with_gt = False, gt_acoustic = False, no_transition = False, no_hmm = False, gt_smoothing = False,
    onset_tolerance = 0.05, pitch_tolerance=50.0, offset_ratio=0.2, offset_min_tolerance=0.05,
    verbose = False
):
    # do preparations
    cisoid_dict, transduction_nn, note_transition_dict = prepare_model_elements(model_type, verbose)

    # parse path information and detect running mode
    audio_names = os.listdir(audio_dir)
    piece_names_by_audio = [remove_audio_filename_extension(filename) for filename in audio_names]

    if gt_midi_dir is not None and os.path.exists(gt_midi_dir):
        evaluate_flag = True
        midi_names = os.listdir(gt_midi_dir)
        piece_names_by_midi = [remove_midi_filename_extension(filename) for filename in midi_names]
        if verbose:
            print("Groud-truth midi directory detected. Evaluate model switched on.")
    else:
        evaluate_flag = False
        midi_names = []
        piece_names_by_midi = []
        if verbose:
            print("Groud-truth midi directory not detected. Evaluate model switched off.")

    valid_piece_names = []
    valid_audio_names = []
    valid_midi_names = []
    for i_file,piece_name in enumerate(piece_names_by_audio):
        if evaluate_flag:
            run_this_piece_flag = (piece_name is not None) and (piece_name in piece_names_by_midi)
            if type(eval_piece_names) == list:
                if not piece_name in eval_piece_names:
                    run_this_piece_flag = False
        else:
            run_this_piece_flag = (piece_name is not None)

        if run_this_piece_flag:
            valid_piece_names.append(piece_name)
            for possible_ext in SUPPORTED_AUDIO_TYPES:
                if piece_name + possible_ext in audio_names:
                    valid_audio_names.append(piece_name + possible_ext)
                    break
            if evaluate_flag:
                for possible_ext in SUPPORTED_MIDI_TYPES:
                    if piece_name + possible_ext in midi_names:
                        valid_midi_names.append(piece_name + possible_ext)
                        break

    # do transcription and evaluation
    eval_results = {}
    eval_save_path = os.path.join(save_dir, "mir_eval_notes.json")
    for i_file_valid, piece_name in enumerate(valid_piece_names):
        # get the file paths
        audio_name = valid_audio_names[i_file_valid]
        if evaluate_flag:
            midi_name = valid_midi_names[i_file_valid]
            midi_path = os.path.join(gt_midi_dir, midi_name)
            if not os.path.exists(midi_path):
                midi_path = None
        else:
            midi_path = None
        audio_path = os.path.join(audio_dir, audio_name)
        save_path = os.path.join(save_dir, piece_name+".midi")

        # run the transcription model
        print("Transcription "+str(i_file_valid)+": "+piece_name+"...")
        est_piano_roll = transcribe_audio(
            audio_path, model_type, cisoid_dict, transduction_nn, note_transition_dict, amp2vel_mapping = amp2velocity_appox,
            vel_roll_path = None, segment_with_gt = segment_with_gt, gt_acoustic = gt_acoustic,
            no_transition = no_transition, no_hmm = no_hmm, gt_smoothing = gt_smoothing, verbose = False
        )

        # save the piano roll to midi
        maestro_piano_roll_to_midi(est_piano_roll, save_path,
            lowest_pitch = LOWEST_PITCH, amp2vel_mapping = None
        )

        # run evaluation
        if midi_path is not None:
            gt_piano_roll, tick_per_sec = maestro_read_midi_to_piano_roll(midi_path)
            P,R,F1 = calculate_transcription_note_metric_piano_roll(gt_piano_roll, est_piano_roll, auto_time_align = False,
                onset_tolerance = onset_tolerance, pitch_tolerance = pitch_tolerance,
                offset_ratio = offset_ratio, offset_min_tolerance = offset_min_tolerance,
                strict = False, beta = 1.0, plot = False
            )
            eval_results[piece_name] = (P,R,F1)
            print("Transcription eval result (P,R,F1):", (P,R,F1))
            with open(eval_save_path, "w") as outfile:
                json.dump(eval_results, outfile)

    N_eval = len(eval_results)
    PRF1_results = np.array(list(eval_results.values()))
    ave_results = PRF1_results.mean(axis=0)
    ave_std = PRF1_results.std(axis=0)
    print(f"Average P,R,F1: {ave_results[0]:.5f}±{ave_std[0]:.5f}, {ave_results[1]:.5f}±{ave_std[1]:.5f}, {ave_results[2]:.5f}±{ave_std[2]:.5f}")
    print("done!")

# example running:
# python evaluate_main.py data/synth/2004 results/baseline_2004 --gt_midi_dir data/midi_no_cc/2004 -v
if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description="Give audio directory to transcribe and the saving directory; specify the ground-truth directory for mid_eval evaluation."
    )
    parser.add_argument("audio_dir", type=str,
        help="the directory of the audio files (relative to the code dir)"
    )
    parser.add_argument("save_dir", type=str,
        help="the directory to save the midis as transcription results"
    )
    parser.add_argument("model_type", type=str,
        help="choose model_type from ['baseline', 'unrollednet']"
    )
    parser.add_argument("--gt_midi_dir", type=str, required=True,
        help="the directory of the ground-truth midis (should have same names as audios before .mid or .midi)"
    )
    parser.add_argument("-v", "--verbose", action="store_true", help="activate verbose mode with '-v'")
    args = parser.parse_args()

    batch_AMT_with_eval(args.audio_dir, args.save_dir, args.model_type, gt_midi_dir = args.gt_midi_dir, verbose = args.verbose)


from app.schemas.game_schema import Positions, TreasureHoldTeams
from app.tests.api.game.base import BaseGameTestCase

class TestMoveTreasureAction(BaseGameTestCase):
    def test_move_treasure_moves(self):
        self.game.turn = self.game.players[2]
        player = self.game.turn
        self.game.chests_position.jr_fr = 1
        self._move_treasure_action(player, TreasureHoldTeams.france).json()
        request = self._get_my_game(player).json()
        assert request["gameStatus"]["chestsPosition"]["jr_en"] == 1
        assert request["gameStatus"]["chestsPosition"]["jr_fr"] == 0

    def test_move_treasure_changes_turn(self):
        self.game.turn = self.game.players[2]
        player = self.game.turn
        self.game.chests_position.jr_fr = 1
        self._move_treasure_action(player, TreasureHoldTeams.france)
        assert self.game.turn != player

    def test_move_from_empty_hold(self):
        player = self.game.turn
        self.game.players_position[player] = Positions.JR1
        response = self._move_treasure_action(player, TreasureHoldTeams.france)
        assert response.status_code == 400

    def test_move_chest_not_cabin_boy(self):
        player = self.game.turn
        response = self._move_treasure_action(player, TreasureHoldTeams.france)
        assert response.status_code == 400


import cv2
import numpy as np
import logging
import time

class VideoPlayer:
    def __init__(self, channel_num, src, dims, full_screen=True):
        self.channel_num = channel_num
        self.src = src
        self.dims = dims
        cv2.namedWindow('Grating Player')

    def play(self, mask_iter, ppl, export=False):
        cap = cv2.VideoCapture(self.src)

        def resize_with_padding(img, target_dim):
            height, width, channels = img.shape
            t_width, t_height = target_dim
            w_ratio = t_width / width
            h_ratio = t_height / height
            ratio = min(w_ratio, h_ratio)
            img = cv2.resize(img, None, fx=ratio, fy=ratio)
            if w_ratio < h_ratio:
                tmp = np.zeros((self.dims[1], img.shape[1], 3), np.uint8)
                start = int((self.dims[1] - int(round(ratio * s_height))) / 2)
                tmp[start : start + img.shape[0], :] = img
                img = tmp
            return img

        indicator = list(np.int32(np.zeros(self.dims[0])))
        while cap.isOpened():
            start = time.time()
            ret, frame = cap.read()
            if not ret:
                break
            s_height, s_width, channel = frame.shape
            try:
                mask = next(mask_iter)
            except StopIteration:
                logging.critical('Core engine failed to supply mask, player corrupted')
                return None

            # Div frame into frames
            starts = list(np.int32(np.linspace(0, frame.shape[1], self.channel_num + 1)))
            head = starts[0: -1]
            tail = starts[1:]
            sub_frames = []
            for i, j in zip(head, tail):
                tmp = frame[:, i: j]
                sub_frames.append(cv2.resize(tmp, None, fx=1 / self.channel_num, fy=1))

            offset = 0
            padding = False
            tailer = ppl - int(ppl)
            mask = list(mask)
            for i in range(len(indicator)):
                j = (i + offset) % int(ppl)
                if padding:
                    padding = False
                    indicator[i] = 0
                    offset -= 1
                    tailer -= 1
                elif j >= len(mask) - 1:
                    if np.abs(tailer - 1) < 0.1 or tailer >= 1:
                        padding = True
                    indicator[i] = mask[j]
                    tailer += ppl - int(ppl)
                else:
                    indicator[i] = mask[j]

            widthes = []
            for marker in range(self.channel_num):
                widthes.append(indicator.count(marker + 1))

            layers = []
            for i in range(len(sub_frames)):
                img = resize_with_padding(sub_frames[i], (widthes[i], self.dims[1]))
                layers.append(img)

            # for i in range(2):
            #     cv2.imshow(str(i), sub_frames[i])
            #     print(i, indicator.count(i + 1))

            # Build new frame
            new_frame = np.zeros((self.dims[1], self.dims[0], 3), np.uint8)
            pointers = [0, ] * self.channel_num
            for i in range(len(indicator)):
                index = indicator[i] - 1
                if index != -1:
                    try:
                        new_frame[:, i] = layers[index][:, pointers[index]]
                    except IndexError as e:
                        # print(e)
                        pass
                    pointers[index] += 1
                else:
                    continue

            if export:
                yield new_frame
            else:
                cv2.imshow('Grating Player', new_frame)
                if cv2.waitKey(30) & 0xFF == 27:
                    break


import math
f =list()
f.append(1)
f.append(1)
i =2
while 1 :
    f.append(f[i-1]+f[i-2])
    if math.log10(f[i]) > 1000:
        break
    i+=1
while True:
    try :
        n=int(input())
        print(f[n-1])
    except:
        break


#!/usr/bin python3

# Script by Daniel Leon-Perinan at CABD
# MIT License, 2020
# Version 1.0.5

from pycudadecon import RLContext, rl_decon, TemporaryOTF
from contextlib import contextmanager
from tqdm import tqdm
import numpy as np
import tifffile
import mrc
import os
import argparse
import sys
import time

class Image:
    def load_image(self, route):
        extension = os.path.splitext(route)[1]
        self.wavelengths, size, shape, image = opener[extension](route)
        try:
            self.nt, self.nz, self.nw, self.nx, self.ny = shape
        except (Exception):
            os.system(Exception)
            exit(1)
        self.image = image
        self.pxx, self.pxy, self.pxz = size

    def __init__(self, route):
        self.load_image(route)
        super().__init__()

    def frame(self, t, w):
        if self.nt <= 1 and self.nw > 1:
            im = self.image[0 : self.nz, w, :, :]
        elif self.nw <= 1:  # Fixed for only 1 channel!
            if len(self.image.shape) == 5:
                im = self.image[t, 0 : self.nz, w, :, :]
            elif self.nt > 1:
                im = self.image[t, 0 : self.nz, :, :]
            else:
                im = self.image[0 : self.nz, :, :]
                # More than one z is mandatory!
        else:
            if self.image.shape[1] == self.nz:
                im = self.image[t, 0 : self.nz, w, :, :]
            elif self.image.shape[1] == self.nw:
                im = self.image[t, w, 0 : self.nz, :, :]
        return im

    # TODO implement a duplication function

def open_tif(route):
    """[summary]

    Args:
        route (string): route for the .tiff file being processed

    Raises:
        ValueError: when wavelengths (even if one) are not provided
        ValueError: when a 4D stack is not provided

    Returns:
        tuple: complying the order in the Image class, returns the tuple
        of dimensions (TZWXY), as well as pixel size and other features
    """
    # Check that wavelengths have been provided through arguments
    if args.waves == None:
        raise ValueError("No wavelengths were provided. Please refer to --help")

    # Get pixel and stack size from arguments (defaults are set if none)
    pxx, pxz = args.xyimage, args.zimage

    # Read the image using tifffile
    image = tifffile.imread(route)

    # Check that the image is a 4D stack
    if len(image.shape) < 5:
        raise ValueError("Dimensions are wrong. You must provide a 4D stack")

    # Detuple the image properties
    nt, nz, nw, nx, ny = image.shape

    return args.waves, [pxx, pxx, pxz], [nt, nz, nw, nx, ny], image

def open_dv(route):
    """Opens a DeltaVision .dv image stack, and generates a tuple of
    settings using mrc

    Args:
        route (string): route for the .dv file being processed

    Returns:
        tuple: complying the order in the Image class, returns the tuple
        of dimensions (TZWXY), as well as pixel size and other features
    """
    # Load the .dv file into memory with mrc
    image = mrc.imread(route)

    # Parse the header
    header = image.Mrc.hdr

    # Parse the number of timepoints and wavelengths
    nt, nw = header.NumTimes, header.NumWaves

    # Parse the number of XY pixels (image resolution)
    nx, ny, nsecs = header.Num

    # Parse the number of z planes
    nz = int(nsecs / nt / nw)

    # Parse the pixel and stack sizes in microns
    pxx, pxy, pxz = header.d[0:3]
    return header.wave[0:4], [pxx, pxy, pxz], [nt, nz, nw, nx, ny], image

def join_spinning(route, channels):
    """Joins a set of Spinning-Disk folder
    structure to a .tif file consisting of a Z-Stack.

    You must provide the route as a foldername, it is
    mandatory that inside the folder, channel names (subfolders)
    must be provided. This set of subfolders contains the Z-stacks
    in individual files for each timepoint. They will be joined in a
    two step process:
        1. A stack for a single channel is reconstructed in memory
        2. The stack is merged into a single file
    This process takes place in RAM: please, make sure enough memory is
    available!

    Args:
        route ([string]): folder name containing files to reconstruct a movie
        channels ([list]): list of channel names (same as subsequent folder names)

    Returns:
        [string]: The generated 4D stack file route
    """
    # Creates an empty list that will contain the final stack
    movieStack = []

    # Iterates over the user-provided list of channels
    for channel in channels:  # argument provided as spinning

        # Creates an empty list that will contain the channel stack
        channelStack = []

        # Route for the channel stack (individual timepoitns)
        channelPath = os.path.join(route, channel)

        # Individual files are parsed. Timepoint order in filename (..._t1, ..._tn)
        files = [
            os.path.join(channelPath, f)
            for f in os.listdir(channelPath)
            if os.path.isfile(os.path.join(channelPath, f))
        ]

        # Select timepoints based on *_{tN}.TIF notation
        frames = [
            int("".join(os.path.basename(os.path.splitext(f)[0]).split("_")[-1][1:]))
            for f in files
        ]
        # Sort the timepoints
        frames.sort()

        # Select a basename to iterate over timepoints
        filenameBase = "_".join(os.path.splitext(files[0])[0].split("_")[:-1])

        # Store the exact file extension
        extension = os.path.splitext(files[1])[1]

        # Iterating over files, construct the channelStack list
        for frame in frames:
            image = tifffile.imread("{}_t{}{}".format(filenameBase, frame, extension))
            channelStack.append(image)

        # Stores the channel inside the final movie
        movieStack.append(channelStack)

    # Transposes the array to maintain the classical TCZXY ordering (4D stack)
    # TODO: this is a bit wanky, will be fixed
    movieStack = np.array(movieStack)
    movieStack = np.swapaxes(movieStack, 0, 1)
    movieStack = np.swapaxes(movieStack, 1, 2)

    # Stores the file with a new, derived name
    filename = "{}_stack.tif".format(route)
    tifffile.imsave("{}".format(filename), movieStack)

    # Returns the generated stack image fileroute
    return filename

# https://stackoverflow.com/questions/5081657/how-do-i-prevent-a-c-shared-library-to-print-on-stdout-in-python/17954769#17954769
@contextmanager
def stdout_redirected(to=os.devnull):
    """Redirects the CUDAdecon output to the provided route, avoiding displaying it
    in the display (iterations, lambda values...). Instead, it is better to store it
    in a log.

    Args:
        to (string, optional): text file to write into. Defaults to os.devnull.
    """
    fd = sys.stdout.fileno()

    def _redirect_stdout(to):
        sys.stdout.close()
        os.dup2(to.fileno(), fd)
        sys.stdout = os.fdopen(fd, "w")

    with os.fdopen(os.dup(fd), "w") as old_stdout:
        # Changed to append
        with open(to, "a") as file:
            _redirect_stdout(to=file)
        try:
            yield
        finally:
            _redirect_stdout(to=old_stdout)

def log(message, fname=None, show=True):
    """Logging function used throughout the program

    Args:
        message (string): what is to be logged
        fname (string, optional): route of the log file, if not provided, no file will be written. Defaults to None.
        show (bool, optional): to be displayed onscreen. Defaults to True.
    """

    # Check function arguments
    if show:
        print("{}".format(message))
    if fname is not None:
        # Append the message content into the file if it exists, or create it from scratch
        with open(fname, "a" if os.path.exists(fname) else "w") as f:
            f.write("{}\n".format(message))

def getGPUinfo():
    """Gets GPU information with logging purposes. Please note that
    CUDA library must be installed, with nvidia-smi available.

    Returns:
        stirng: formatted output of the nvidia-smi command
    """
    # Call a new nvidia-smi process and read its output
    smiOutput = os.popen("nvidia-smi").read()

    # Clean output contents
    smiSplitted = smiOutput.splitlines()

    return "\n".join(smiSplitted[1:10])

def max_projection(im, minimum=0, maximum=-1):
    """Returns the Z maximum projection of an image, between the
    provided minimum and maximum slices

    Args:
        im (np.array): image data as numpy array, any format. 4D stack!
        minimum (int, optional): minimum slice in Z projection. Defaults to 0.
        maximum (int, optional): maximum slice in Z projection. Defaults to -1.

    Returns:
        np.array: z maximum projected image
    """
    if im.shape == 5 and np.size(im, axis=0) <= 1:
        if len(im.shape) == 4:
            result = np.max(im[0, minimum:maximum, :, :], axis=0)
        else:
            result = np.max(im[minimum:maximum, :, :], axis=0)
    else:
        result = np.max(im[:, minimum:maximum, :, :], axis=1)

    return result

def deconvolve_all():
    """Main deconvolution function, where all logging, file exploration and
    processing is wrapped. Continuous references to external libraries...
    Many thanks to tlambert01 for the libs mrc and pyCUDAdecon
    """

    log("# Starting deconvolution")
    log("# GPU information")
    log(getGPUinfo())

    # Get the paths for each filter to be used, in the same order
    filter_paths = args.psf

    # Iterate over the list of files provided
    # Note that queuing can be done using a simple .sh script to call the
    # application with different parameters
    for f in args.source:

        # Log file naming
        logfile = "{}.log".format(f)

        # Start a timer for profiling time elapsed
        start = time.time()

        # Check whether source provided is SpinningDisk-like
        if os.path.isdir(f):
            channels = args.spinning
            log(
                "# Reconstructing and saving .tif file from folder structure with channels {}".format(
                    channels
                ),
                logfile,
            )
            f = join_spinning(f, channels)

        # Store the file extension to save in the same format
        extension = os.path.splitext(f)[1]

        # Generate an output name based on the source name
        outname = os.path.basename(os.path.splitext(f)[0])

        # Load the image
        log("# Loading the file {} and creating log".format(f), logfile)
        im = Image(f)

        # Calculate an appropriate number of wavelengths to process
        nw = min(len(filter_paths), im.nw)

        # Create the header for the current file
        log("\n\n# Processing file {}".format(f))
        log(
            "# Starting deconvolution at {}".format(
                time.strftime("%b %d %Y %H:%M:%S", time.localtime(start))
            )
        )
        log("####################################################", logfile, show=False)
        log("deCU v1.0.5, by DLP (CABD), 2020", logfile, show=False)
        log("####################################################", logfile, show=False)
        log("\n# Deconvolution settings", logfile, show=False)
        log("## Projection {}".format(args.project), logfile, show=False)
        log("## Channels {}".format(im.nw), logfile, show=False)
        log("## File {}".format(f), logfile, show=False)
        log(
            "## XY pixel size {}".format(round(im.pxx, 3)), logfile, show=False,
        )
        log(
            "## Z-stack depth {}".format(round(im.pxz, 3)), logfile, show=False,
        )
        log("## GPU information", logfile, show=False)
        log(getGPUinfo(), logfile, show=False)
        log(
            "## Time start {}".format(
                time.strftime("%b %d %Y %H:%M:%S", time.localtime(start)),
            ),
            logfile,
            show=False,
        )
        log("\n# Deconvolution process steps", logfile, show=False)

        # Iterate over the range of wavelengths
        for w in range(0, nw):
            # Skip wavelengths marked as null
            if filter_paths[w] == "_":
                continue

            log(
                "\n## Deconvolving channel {} with PSF {}. {} frame{}".format(
                    w, filter_paths[w], im.nt, "s" if im.nt > 1 else ""
                ),
                logfile,
            )

            # Provisional list to store multiframe images
            stack = []

            # Loading all libraries for the deconvolution process
            with TemporaryOTF(filter_paths[w]) as otf:
                with stdout_redirected(to=logfile):
                    with RLContext([im.nz, im.nx, im.ny], otf.path) as ctx:
                        # Iterate over all frames in the image
                        for t in tqdm(range(0, im.nt)):

                            # Using echo to save into the logfile the frame no.
                            os.system("echo ## Frame {}".format(t))

                            # Retrieve current frame
                            image = im.frame(t, w)

                            # Perform pyCUDAdecon deconvolution
                            result = rl_decon(
                                image,
                                output_shape=ctx.out_shape,
                                dxdata=im.pxx,
                                dxpsf=args.xyfilter,
                                dzdata=im.pxz,
                                dzpsf=args.zfilter,
                                wavelength=im.wavelengths[w],
                                n_iters=args.i,
                                na=args.na,
                                nimm=args.refractive,
                            )

                            # Convert the result to uint16 to preserve format
                            result = result.astype(np.uint16)

                            # Append the timepoint to the stack
                            stack.append(result)

                        # Generate a np array from the stack
                        imResult = np.array(stack)

            # Generate a definitive saving name
            savename = ("{0}_{1}_D3D{2}").format(
                outname, str(im.wavelengths[w]), extension
            )

            log("## Saving file as {}".format(savename), logfile)
            saveformat[extension](
                savename, imResult,
            )

            # Check whether max-projection has to occur
            # TODO implement more types of projection
            if args.project:
                log("## Creating maximum projection", logfile)
                imProjected = max_projection(
                    imResult, minimum=args.planes[0], maximum=args.planes[1]
                )
                savename = ("{0}_{1}_PRJ_D3D{2}").format(
                    outname, str(im.wavelengths[w]), extension
                )
                log("## Saving maximum projection as {}".format(savename), logfile)
                saveformat[extension](
                    savename, imProjected,
                )

        # Stop profiling timer and calculate time elapsed
        end = time.time()
        elapsed = end - start

        log(
            "# Deconvolution ended at {}, elapsed {}".format(
                time.strftime("%b %d %Y %H:%M:%S", time.localtime(end)),
                "{} m : {} s".format(int(elapsed / 60), int(elapsed % 60)),
            ),
            logfile,
        )

def cmdline_args():
    """Parses the command line arguments as program parameters

    Returns:
        argparse.args: comprehensive list of arguments
    """
    p = argparse.ArgumentParser(
        description="""
        CUDA deconvolution of (multi)frame .dv or .tif(f) files
        """,
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )
    p.add_argument(
        "--source",
        nargs="+",
        required=True,
        help="Source file(s) to deconvolve (or folder if SpinningDisk)",
    )
    p.add_argument(
        "--psf",
        nargs="+",
        required=True,
        help="PSF file(s) (one per wavelength). Provide _ for channel negative selection",
    )
    p.add_argument(
        "--zfilter",
        default=0.1,
        help="Z-depth of the given filter(s) (PSF) in microns",
    )
    p.add_argument(
        "--xyfilter",
        default=0.1,
        help="XY-pixel size of the given filter(s) (PSF) in microns",
    )
    p.add_argument(
        "--zimage",
        default=0.1,
        type=float,
        help="Z-depth of the given image stack in microns",
    )
    p.add_argument(
        "--xyimage",
        default=0.1,
        type=float,
        help="XY-pixel size of the given image in microns",
    )
    p.add_argument(
        "--na", default=1.4, help="Numerical aperture units for selected objective",
    )
    p.add_argument(
        "--refractive", default=1.5, help="Refractive index of interface media"
    )
    p.add_argument(
        "--spinning",
        nargs="+",
        type=str,
        help="Folder names for each channel in a SpinningDisk type file structure",
    )
    p.add_argument("-i", default=15, help="Iterations of the Richardson-Lucy algorithm")
    p.add_argument(
        "-p", "--project", action="store_true", help="Project the z-stack in a new file"
    )
    p.add_argument(
        "--planes",
        type=int,
        nargs=2,
        default=[0, -1],
        help="Select range for z-stack projection, two numbers, space delimited",
    )
    p.add_argument("-w", "--waves", nargs="+", help="Select wavelengths to process")

    return p.parse_args()

# Dictionary for opening functions
opener = {".tif": open_tif, ".tiff": open_tif, ".dv": open_dv}

# Dictionary for saving functions
saveformat = {
    ".tif": tifffile.imsave,
    ".TIF": tifffile.imsave,
    ".tiff": tifffile.imsave,
    ".TIFF": tifffile.imsave,
    ".dv": mrc.imsave,
    ".DV": mrc.imsave,
}

if __name__ == "__main__":
    args = cmdline_args()
    deconvolve_all()


import os
from os.path import join as joinpath
import shutil

def walkDir(path):
	"""
	Returns all directorys and files with dir_path + (filename/dirname)
	Root path will not be printed

	:param path: path
	:param print_root: whether the root path would be included
	"""

	#1d lists of path + filename
	dir_list = []
	file_list = []

	#to delete the root path
	pthlen = len(path) + 1

	for dirpath, dirnames, filenames in os.walk(path):
		dirpath = dirpath[pthlen:]

		for dirname in dirnames:
			dir_list.append(joinpath(dirpath, dirname))
		for filename in filenames:
			file_list.append(joinpath(dirpath, filename))

	return (dir_list, file_list)

def returnNoneStrForFalse(value):
	if (value):
		return value
	else:
		return "None"

def getAllowedPath(path):
	not_alloweds = ["\\", "/", ":", "*", "?", "\"", "<", ">", "|", "."]
	for not_allowed in not_alloweds:
		path = path.replace(not_allowed, "_")
	return path


# -*- coding: utf-8 -*-
"""
Created on Sat Jun 11 12:29:13 2022

@author: HP EliteBook 2470p
"""

import tkinter as tk

ventana = tk.Tk()
ventana.geometry ("1000x700")
ventana.config(bg="Turquoise")

#Primera Fila Añadiendo Parametros
espacio = tk.Label(ventana, bg="Turquoise", fg="Turquoise")
espacio.grid (row = 0, column = 0)

texto1 = tk.Label(ventana, text="Focal (mm)=", bg="Turquoise", fg="gray20")
texto1.grid (row = 1, column = 0)

cuadro1 = tk.Entry(ventana, font = "Calibri 12", justify = "left")
cuadro1.grid (row = 1, column = 1)

texto2 = tk.Label(ventana, text="Ancho de la imagen (Pixel) =", bg="Turquoise", fg="gray20")
texto2.grid (row = 1, column = 2)

cuadro2 = tk.Entry(ventana, font = "Calibri 12", justify = "left")
cuadro2.grid (row = 1, column = 3)

texto3 = tk.Label(ventana, text="Alto de la imagen (Pixel) =", bg="Turquoise", fg="gray20")
texto3.grid (row = 1, column = 4)

cuadro3 = tk.Entry(ventana, font = "Calibri 12", justify = "left")
cuadro3.grid (row = 1, column = 5)

#Segunda Fila Añadiendo Parametros
espacio1 = tk.Label(ventana, bg="Turquoise", fg="Turquoise")
espacio1.grid (row = 2, column = 0)

texto4 = tk.Label(ventana, text="Ancho el sensor (mm) = ", bg="Turquoise", fg="gray20")
texto4.grid (row = 3, column = 0)

cuadro4 = tk.Entry(ventana, font = "Calibri 12", justify = "left")
cuadro4.grid (row = 3, column = 1)

texto5 = tk.Label(ventana, text="Alto del sensor (mm)=", bg="Turquoise", fg="gray20")
texto5.grid (row = 3, column = 2)

cuadro5 = tk.Entry(ventana, font = "Calibri 12", justify = "left")
cuadro5.grid (row = 3, column = 3)

texto6 = tk.Label(ventana, text="Altura del vuelo (m)=", bg="Turquoise", fg="gray20")
texto6.grid (row = 3, column = 4)

cuadro6 = tk.Entry(ventana, font = "Calibri 12", justify = "left")
cuadro6.grid (row = 3, column = 5)

#Tercera Fila Añadiendo Parametros
espacio2 = tk.Label(ventana, bg="Turquoise", fg="gray20")
espacio2.grid (row = 4, column = 0)

texto7 = tk.Label(ventana, text="Solape Longitudinal (%) =", bg="Turquoise", fg="gray20")
texto7.grid (row = 5, column = 0)

cuadro7 = tk.Entry(ventana, font = "Calibri 12", justify = "left")
cuadro7.grid (row = 5, column = 1)

texto8 = tk.Label(ventana, text="Solape Transversal (%) =", bg="Turquoise", fg="gray20")
texto8.grid (row = 5, column = 2)

cuadro8 = tk.Entry(ventana, font = "Calibri 12", justify = "left")
cuadro8.grid (row = 5, column = 3)

texto9 = tk.Label(ventana, text="Largo de la parcela (m)=", bg="Turquoise", fg="gray20")
texto9.grid (row = 5, column = 4)

cuadro9 = tk.Entry(ventana, font = "Calibri 12", justify = "left")
cuadro9.grid (row = 5, column = 5)

#Cuarta Fila Añadiendo Parametros
espacio3 = tk.Label(ventana, bg="Turquoise", fg="gray20")
espacio3.grid (row = 6, column = 0)

texto10 = tk.Label(ventana, text="Ancho de la parcela (m)=", bg="Turquoise", fg="gray20")
texto10.grid (row = 7, column = 0)

cuadro10 = tk.Entry(ventana, font = "Calibri 12", justify = "left")
cuadro10.grid (row = 7, column = 1)

texto11 = tk.Label(ventana, text="Velocidad del vuelo (m/s)=", bg="Turquoise", fg="gray20")
texto11.grid (row = 7, column = 2)

cuadro11 = tk.Entry(ventana, font = "Calibri 12", justify = "left")
cuadro11.grid (row = 7, column = 3)

espacio3 = tk.Label(ventana, bg="Turquoise", fg="Turquoise")
espacio3.grid (row = 8, column = 0)

espacio3 = tk.Label(ventana, bg="Turquoise", fg="coral")
espacio3.grid (row = 10, column = 0)

#Cálculo de los Parametros de la Variables
def resultados():
    textoResult.delete(1.0, tk.END)
    focal = float(cuadro1.get())
    Ancho_Img = float(cuadro2.get())
    Alto_Img = int(cuadro3.get())
    Ancho_Sensor = float(cuadro4.get())
    Alto_Sensor = float(cuadro5.get())
    RSI = Ancho_Sensor/Ancho_Img
    Altura_Vuelo = float(cuadro6.get())
    Solape_Long = float(cuadro7.get())
    solape_trans = float(cuadro8.get())
    largo_parcela = float(cuadro9.get())
    ancho_parcela = float(cuadro10.get())
    vel_vuelo = float(cuadro11.get())

    #GSD
    GSD = (((Altura_Vuelo * 100 )/ (focal)) * RSI)
    textoResult.insert(tk.END, f"GSD = {GSD}cm/pixel\n\n")

    #Escala de Vuelo
    escala_vuelo = 1/((focal/1000)/Altura_Vuelo)
    textoResult.insert(tk.END, f"Escala de vuelo = {escala_vuelo}\n\n")

    #Ancho de la imagen
    areatomada = (Ancho_Sensor*escala_vuelo)/1000
    textoResult.insert(tk.END, f"Ancho de la Imagen Sobre el Terreno = {areatomada}m\n\n")

    #Alto de la imagen
    areatomada = (Alto_Sensor*escala_vuelo)/1000
    textoResult.insert(tk.END, f"Alto de la Imagen Sobre el Terreno = {areatomada}m\n\n")

    #Base Aérea
    base_aer = (((Ancho_Img * GSD )/100)* (1-(Solape_Long/100)))
    textoResult.insert(tk.END, f"Base Aérea = {base_aer}\n\n")

    #Distancia entre vueltas
    Dist_vueltas = (((Alto_Img * GSD )/100)) * (1-(solape_trans/100))
    textoResult.insert(tk.END, f"Distancia entre vueltas = {Dist_vueltas}m\n\n")

    #Tiempo entre fotos y velocidad de vuelo
    tiem_fotos = base_aer/vel_vuelo
    vel_vuelo= base_aer/tiem_fotos
    textoResult.insert(tk.END, f"Tiempo entre fotos = {tiem_fotos}s\n\n")
    textoResult.insert(tk.END, f"Velocidad de Vuelo= {vel_vuelo}m/s\n\n")

    #Número de pasadas
    num_pasadas = round (ancho_parcela/Dist_vueltas)
    textoResult.insert(tk.END, f"Numero de pasadas = {num_pasadas}\n\n")

    #Número de fotos por vueltas
    num_fotos = round (largo_parcela/base_aer)+1
    textoResult.insert(tk.END, f"Numero de Fotos por vueltas = {num_fotos}\n\n")

    #Número de fotos por pasada
    num_vuelta= round (num_fotos)*(num_pasadas)+1
    textoResult.insert(tk.END, f"Numero de Fotos por Vuelo = {num_vuelta}\n\n")

    #Distancia de Vuelo
    dist_vuelo = (num_pasadas*largo_parcela)+ancho_parcela
    textoResult.insert(tk.END, f"Distancia de Vuelo = {dist_vuelo}m\n\n")

    #Duración de vuelo
    t_vuelo= ((num_vuelta * tiem_fotos)/60)
    textoResult.insert(tk.END, f"Duracion del Vuelo = {t_vuelo}min")

#Resultados de los Calculos de los Parametros de las Variables
textoResult = tk.Text(ventana)
textoResult.grid(row = 9, column = 0, columnspan = 5)

#Botón de Cálculo
boton_calculo = tk.Button(text = "Calcular", font= 'Calibri 12', command = resultados)
boton_calculo.grid(row = 12, column = 1, columnspan = 1)

#Título
ventana.title("Calculadora de parámetros de vuelo de drone (Autor: Bryan Martinez)")

ventana.mainloop()


# 이름, 실적
member_names = ["갑돌이", "갑순이", "을돌이", "을순이", "병돌이", "병순이"]
member_records = [[4,5,3,5,6,5,3,4,1,3,4,5],[2,3,4,3,1,2,0,3,2,5,7,2],
           [1,3,0,3,3,4,5,6,7,2,2,1],[3,2,9,2,3,5,6,6,4,6,9,9],
           [8,7,7,5,6,7,5,8,8,6,10,9],[7,8,4,9,5,10,3,3,2,2,1,3]]

di = {}
member_aver = []

for i in range(len(member_names)) :
    mem_sum = 0
    for x in range(len(member_records[i])) :
        mem_sum += member_records[i][x]
    aver = mem_sum / len(member_records[i])
    di[member_names[i]] = aver

grading = sorted([(v,k) for k,v in di.items()], reverse=True)

bonus_eligible_persons = grading[:2]
for v,k in grading :
    if v > 5 :
        print(f"보너스 대상자 {k}")

underperformer = grading[-2:]
for v,k in grading :
    if v < 3 :
        print(f"면담 대상자 {k}")

6 Week Mission Q2(dictionary and tuples, Find the best and worst performer).py


"""
Started by writing an Intcode computer. Realized brute forcing would takes an
impossibly long amount of time. Went through the program with pen and paper.
Recognized a pattern but couldn't quite explain it. Skimmed through the Reddit
thread. Decided to try writing down the logic more succinctly in Python. Wrote
down the instructions. Started piecing together the intent of the code. Clicked
when I ran through a couple of examples, printing z out. Eventually got this
"no-code" solution down.

Some notes:
    * only 3 values change after initializing w to a new value:
        * the digit from div z {:d}
        * the digit from add x {:d}
        * the digit from add y {:d}
    * a is always either 1 or 26
    * for a == 1
        * by observation, b > 9
        * then x + b != w is True
        * z gets multiplied by 26 and is added a number
    * for a == 26
        * by observation, b <= 0
        * if x + b == w, z = z // 26
        * else, z += w + c

As a result, the operations can be read as adding/subtracting numbers to z.

More specifically, they are like pushing and popping values from a stack, with a
power of 26.

For z = 0, we need all the operations successfully cancel out, i.e., the stack to
be empty after all operations are over.

This gives us a bound on the values of w, since popping is only successful when
z % 26 + b == w - this z % 26 is equal to the value of z when the item being popped
was added.

The visualization below shows visually how the stack should change if all the
operations are successful and how the operations line up:
    1. [A], Push(A)
    2. [A,B], Push(B)
    3. [A,B,C], Push(C)
    4. [A,B], Pop(C) if (z % 26) + b == w
    5. [A,B,D],Push(D)
    6. [A,B], Pop(D) if (z % 26) + b == w
    7. [A], Pop(B) if (z % 26) + b == w
    8. [A,E], Push(E)
    9. [A,E,F], Push(F)
   10. [A,E,F,G], Push(G)
   11. [A,E,F],Pop(G) if (z % 26) + b == w
   12. [A,E], Pop(F) if (z % 26) + b == w
   13. [A], Pop(E) if (z % 26) + b == w
   14. [], Pop(A) if (z % 26) + b == w

For instance, the first and last operation imply the following equations:
    (1) (1, 13, [3]) -> z = w1 + 3
    (14) (26, [-7], 3) -> z - 7 = w14
    -> w14 = w1 - 4

When maximizing the model number, we want to pick the highest value possible for w1,
given the constraints on w (0 < w < 10).
This implies w14 = 5 hence a model number of the format: 9____________5.

We do the opposite when minimizing the module numbers: w1 = 5, w14 = 1,
which gives us 5____________1.

Going through the equations gives us the 2 solutions:
   MAX: 91699394894995
   MIN: 51147191161261
"""

from _utils import timer

instructions = [
    (1, 13, 3),
    (1, 11, 12),
    (1, 15, 9),
    (26, -6, 12),
    (1, 15, 2),
    (26, -8, 1),
    (26, -4, 1),
    (1, 15, 13),
    (1, 10, 1),
    (1, 11, 6),
    (26, -11, 2),
    (26, 0, 11),
    (26, -8, 10),
    (26, -7, 3),
]

def recompiled_code(w: int, z: int, a: int, b: int, c: int) -> int:
    """
    Returns the value of z given a value of w, z, a, b, and c.

    w: int, part of the module number
    z: int
    a: int, digit from div z {:d}
    b: int, digit from add x {:d}
    c: int, digit from add y {:d}

    Note: if x + b == w, x = 0 -> the value of z doesn't change after z // a.
    """
    x = z % 26
    z = z // a
    if x + b != w:
        z *= 26
        z += w + c
    return z

def compute_z(module_number: str):
    module_number = [int(c) for c in module_number]
    zipped = zip(instructions, module_number)
    z = 0

    for instr, w in zipped:
        a, b, c = instr
        z = recompiled_code(w, z, a, b, c)

    return z

@timer
def main():
    """
    Checks that the solutions are valid.
    """
    part_1_solution = 91699394894995
    part_2_solution = 51147191161261
    assert compute_z(str(part_1_solution)) == 0
    assert compute_z(str(part_2_solution)) == 0
    return part_1_solution, part_2_solution

if __name__ == "__main__":
    part_1_score, part_2_score = main()
    print(f"PART 1: {part_1_score}")  # 91699394894995
    print(f"PART 2: {part_2_score}")  # 51147191161261


"""TODO: Docstring."""
import pytest
import uclasm
from uclasm import Graph
from uclasm.matching.matching_utils import GlobalCostsArray
import numpy as np
from scipy.sparse import csr_matrix
import pandas as pd
from laptools import clap

@pytest.fixture
def graph():
    """Create a graph with some nodes and edges."""
    adj0 = csr_matrix([[0, 0, 0],
                       [1, 0, 0],
                       [0, 0, 0]])
    adj1 = csr_matrix([[0, 0, 0],
                       [0, 0, 0],
                       [0, 1, 0]])
    nodelist = pd.DataFrame(['a', 'b', 'c'], columns=[Graph.node_col])
    edgelist = pd.DataFrame([['b', 'a'],
                             ['c', 'b']], columns=[Graph.source_col,
                                                   Graph.target_col])
    g = Graph([adj0, adj1], ['c1', 'c2'], nodelist, edgelist)
    return g

@pytest.fixture
def node_subgraph():
    """Create a subgraph of the graph created by the graph fixture."""
    adj0 = csr_matrix([[0, 0],
                       [0, 0]])
    adj1 = csr_matrix([[0, 0],
                       [1, 0]])
    nodelist = pd.DataFrame(['b', 'c'], columns=[Graph.node_col])
    edgelist = pd.DataFrame([['c', 'b']], columns=[Graph.source_col,
                                                   Graph.target_col])
    subg = Graph([adj0, adj1], ['c1', 'c2'], nodelist, edgelist)
    return subg

class TestGraph:
    """Tests related to the Graph class and its methods/functions."""

    def test_graph_adj_mats(self, graph):
        """Check that the various derived matrices are computed."""
        adj0 = graph.adjs[0]
        adj1 = graph.adjs[1]

        comp = adj0 + adj1
        sym_comp = comp + comp.T
        is_nbr = sym_comp > 0

        # Check the various composite adjacency and related matrices.
        assert (graph.composite_adj != comp).nnz == 0
        assert (graph.sym_composite_adj != sym_comp).nnz == 0
        assert (graph.is_nbr != is_nbr).nnz == 0

    def test_node_subgraph(self, graph, node_subgraph):
        """Check the subgraph of `graph` against the expected subgraph."""
        node_bools = graph.nodelist[Graph.node_col]\
                     .isin(node_subgraph.nodelist[Graph.node_col])
        node_idxs = node_bools[node_bools].index
        actual_subgraph = graph.node_subgraph(node_idxs)

        # Check the adjacency matrices of the subgraph against expected
        for act_adj, exp_adj in zip(actual_subgraph.adjs, node_subgraph.adjs):
            assert (act_adj != exp_adj).nnz == 0
            assert (act_adj != exp_adj).nnz == 0
        assert (actual_subgraph.nodelist == node_subgraph.nodelist).all(axis=None)
        assert (actual_subgraph.edgelist == node_subgraph.edgelist).all(axis=None)
        for i in range(actual_subgraph.n_nodes):
            assert actual_subgraph.orig_idxs[i] == node_idxs[i]

    def test_node_cover(self, graph):
        """Check that the node cover is minimal for the example graph."""
        cover = graph.node_cover()
        assert len(cover) == 1
        assert cover[0] == 1

    def test_edge_src_idxs(self, graph):
        """Test the function that retrieves source indices of the edges"""
        src_idxs = graph.edge_src_idxs
        for edge_idx, edge in graph.edgelist.iterrows():
            assert src_idxs[edge_idx] == graph.node_idxs[edge[graph.source_col]]

    def test_edge_dst_idxs(self, graph):
        """Test the function that retrieves destination indices of the edges"""
        dst_idxs = graph.edge_dst_idxs
        for edge_idx, edge in graph.edgelist.iterrows():
            assert dst_idxs[edge_idx] == graph.node_idxs[edge[graph.target_col]]

class TestGlobalCostArray:
    """Tests related to the global costs array"""
    def test_global_costs_array(self):
        test_array = np.zeros((5,5))
        global_costs_array = test_array.view(GlobalCostsArray)
        assert np.all(global_costs_array.candidates)
        global_costs_array[3,3] = 2
        assert np.sum(global_costs_array.candidates) == 5*5-1
        assert not global_costs_array.candidates[3,3]
        global_costs_array[2,:] = 5
        assert not np.any(global_costs_array.candidates[2,:])

    def test_set_global_cost_threshold(self):
        test_array = np.zeros((5,5))
        test_array[1,:] = 3
        test_array[2,:] = 4
        candidates = test_array <= 3
        candidates[4,:] = False
        global_costs_array = GlobalCostsArray(test_array,
                                              global_cost_threshold=3,
                                              candidates=candidates)
        assert np.all(global_costs_array.candidates[1,:])
        assert not np.any(global_costs_array.candidates[2,:])
        assert not np.any(global_costs_array.candidates[4,:])
        global_costs_array.set_global_cost_threshold(2)
        assert not np.any(global_costs_array.candidates[1,:])
        assert not np.any(global_costs_array.candidates[4,:])
        global_costs_array[4,:] = 2
        assert not np.any(global_costs_array.candidates[4,:])
        assert global_costs_array.candidates[0,2]
        global_costs_array[0,2] = 3
        assert not global_costs_array.candidates[0,2]

    def test_indexing(self):
        test_array = np.zeros((5,5))
        global_costs_array = GlobalCostsArray(test_array,
                                             global_cost_threshold=3)
        global_costs_array[2,:] = 1
        sliced_array = global_costs_array[:, 2:3]
        assert isinstance(sliced_array, GlobalCostsArray)
        assert sliced_array.global_cost_threshold == 3
        assert sliced_array.shape == sliced_array.candidates.shape


import logging
import numpy as np
import os
import pandas as pd
from hyperopt.pyll.stochastic import sample
from pathlib import Path
from pprint import pformat

from .schedule import (SerialScheduler, ConcurrentScheduler, MPSScheduler,
                       MIGScheduler, HFTAScheduler)
from .algorithms import RandomSearch, Hyperband
from .utils import (handle_integers, attach_common_args,
                    rearrange_algorithm_kwargs, generate_fusible_param_flags,
                    generate_nonfusible_param)

def _assert_positive_int_or_none(v):
  assert (v is None) or (isinstance(v, int) and v > 0)

def _expand_dict_if_valid(d, k, v):
  if v is not None:
    d[k] = v

def tune_hyperparameters(
    space={},
    try_params_callback=None,
    dry_run_callback=None,
    mode='hfta',
    algorithm='hyperband',
    nonfusibles=[],
    dry_run_repeats=None,
    dry_run_epochs=None,
    dry_run_iters_per_epoch=None,
    metric=None,
    goal='min',
    algorithm_configs={},
    seed=0,
    outdir=None,
):
  assert len(space) > 0
  assert try_params_callback is not None
  assert dry_run_callback is not None
  assert mode in {'serial', 'concurrent', 'mps', 'mig', 'hfta'}
  assert algorithm in {'hyperband', 'random'}
  assert nonfusibles is not None
  _assert_positive_int_or_none(dry_run_repeats)
  _assert_positive_int_or_none(dry_run_epochs)
  _assert_positive_int_or_none(dry_run_iters_per_epoch)
  assert metric is not None and isinstance(metric, str)
  assert goal in {'min', 'max'}
  assert isinstance(algorithm_configs, dict)
  assert isinstance(seed, int)
  assert outdir is None or isinstance(outdir, str)

  if mode == 'serial':
    scheduler = SerialScheduler(try_params_callback)
  else:
    kwargs = {
        'try_params_callback': try_params_callback,
        'dry_run_callback': dry_run_callback,
        'nonfusibles': nonfusibles,
    }
    _expand_dict_if_valid(kwargs, 'dry_run_repeats', dry_run_repeats)
    _expand_dict_if_valid(kwargs, 'dry_run_epochs', dry_run_epochs)
    _expand_dict_if_valid(
        kwargs,
        'dry_run_iters_per_epoch',
        dry_run_iters_per_epoch,
    )
    schedulers = {
        'concurrent': ConcurrentScheduler,
        'mps': MPSScheduler,
        'mig': MIGScheduler,
        'hfta': HFTAScheduler,
    }
    scheduler = schedulers[mode](**kwargs)

  rng_state = np.random.RandomState(seed=seed)

  def get_params():
    params = sample(space, rng=rng_state)
    return handle_integers(params)

  tuners = {'hyperband': Hyperband, 'random': RandomSearch}
  algorithm_config = {}
  if algorithm in algorithm_configs:
    for k, v in algorithm_configs[algorithm].items():
      _expand_dict_if_valid(algorithm_config, k, v)
  # To ensure a fair comparison between Hyperband and Random Search,
  # also pass in hyperband related parameters to decide the size
  # of candidate set, and the number of training epochs.
  tuner = tuners[algorithm](
      get_params,
      scheduler,
      metric,
      goal=goal,
      **algorithm_config,
  )

  history, trajectory = tuner.run()
  logging.info("\n=========================================================")
  logging.info("Done! the final results are:")
  logging.info("{} total, best:\n".format(len(history)))

  for trial in sorted(
      history.values(),
      key=lambda trial: trial['result'][metric],
      reverse=True,
  )[:5]:
    logging.info("{} | {:.1f}iterations | run {} ".format(
        pformat(trial['result']),
        trial['iterations'],
        trial['id'],
    ))
    pformat(trial['params'])

  if outdir is not None:
    logging.info('Saving results to {} ...'.format(outdir))
    Path(outdir).mkdir(parents=True, exist_ok=True)
    pd.json_normalize(history.values()).to_csv(
        os.path.join(outdir, 'history.csv'))
    pd.json_normalize(trajectory).to_csv(os.path.join(outdir, 'trajectory.csv'))

  return history, trajectory


import numpy as np
import pandas as pd

try:
    N = int(input())
    data = pd.DataFrame(columns=['time', 'id', 'vit', 'ac', 'anti', 'neural', 'mch'])
    for i in range(N):
        data.loc[i] = [float(i) for i in input().split()]
    data = data[['id', 'neural']]
    count = data['id'].value_counts()
    d1 = pd.merge(data, count, left_on='id', right_index=True)
    d2 = d1[d1['id_y'] > 1]
    d4 = d2.groupby('id').apply(lambda x: x.max() - x.min())
    data4 = d4.sort_values(by='neural')
    if data4.empty:
        print(-1)
    else:
        a = []
        for i in data4.head(3).index:
            a.append(int(i))
        print(*sorted(a))
except:
    print(-1)


def calc_tax(amount, tax_rate, age):

    if not isinstance(amount, (int, float)):
        raise TypeError("wrong type of amount values: int or float required.")
    if not amount >= 0:
        raise ValueError("amount value must be positive.")

    if not isinstance(tax_rate, float):
        raise TypeError("tax rate value must be float type.")
    if not 0 < tax_rate < 1:
        raise ValueError("tax_rate value must be between 0 and 1.")

    if not isinstance(age, int):
        raise TypeError("Age value must be integer type")
    if not age > 0:
        raise ValueError("Age vale must be positive")

    if age <= 18:
        return int(min(amount * tax_rate, 5000))
    elif age <= 65:
        return int(amount * tax_rate)
    else:
        return int(min(amount * tax_rate, 8000))


#!/usr/local/bin/python3
#--------------------------------------------------------------------------------------------------
import sys,requests,getopt
from typing import List, Tuple

TPTP2TFormReplyURL = "https://www.tptp.org/cgi-bin/TPTP2TFormReply"

USAGE = f"Usage: RemoteSOT <options> [<File name>]\n \
    <options> are ...\n \
    -v              --version    - print version information\n \
    -h --help       --help       - print this help\n \
    -q <quietness>  --quiet      - control amount of output\n \
    -p <print>      --print      - pp (problems), ps (solutions), pps (both)\n \
    -d '<domains>'  --domains    - list of domains in ''s\n \
    -f <form>       --form       - THF,TH1,TH0,TXF,TX1,TX0,TFF,TF1,TF0,FOF,CNF\n \
    -r <min>-<max>  --rating     - Min and Max in the range 0.00 to 1.00\n"

VERSION = f"{sys.argv[0]} version 1.0.0"

DEFAULT_URL_PARAMETERS = {
    "NoHTML": (None, '1'),
    "QuietnessOption1": (None, '-q2'),
    "PrintFlag1": (None, '-pps'),
    "Domains": (None,'X9X'),
    "Form": (None,'ANY')
    }
#--------------------------------------------------------------------------------------------------
def parseCommandLine(args: List[str]):

    urlParameters = DEFAULT_URL_PARAMETERS

    options, arguments = getopt.getopt(
#----Arguments
        args,
#----Short option definitions
        'vhq:p:d:f:r:',
#----Long option definitions
        ["version", "help", "quiet=", "print=", "domains=", "form=", "rating=" ])

    for option, parameter in options:
#DEBUG        print(f"Option is ==={option}=== Parameter is ==={parameter}===")
        if option in ("-v", "--version"):
            print(VERSION)
            sys.exit()
        if option in ("-h", "--help"):
            print(USAGE)
            sys.exit()
#    -q<quietness>   --quiet      - control amount of output\n \
        if option in ("-q", "--quiet"):
            urlParameters["QuietnessOption1"] = (None, '-q'+parameter)
        if option in ("-p", "--print"):
            urlParameters["PrintFlag1"] = (None, '-p'+parameter)
        if option in ("-d", "--domains"):
            urlParameters["Domains"] = (None, 'Domains '+parameter)
        if option in ("-f", "--form"):
            urlParameters["Form"] = (None, parameter)
        if option in ("-r", "--rating"):
            urlParameters["Rating"] = (None, 'Rating__')
            minMax = parameter.split("-")
            if len(minMax) != 2:
                print(USAGE)
                sys.exit()
            urlParameters["Rating1"] = (None, minMax[0])
            urlParameters["Rating2"] = (None, minMax[1])

    return urlParameters
#--------------------------------------------------------------------------------------------------
def main() -> None:

    args = sys.argv[1:]
    if not args:
        print(USAGE)
        sys.exit()
    urlParameters = parseCommandLine(args)

#DEBUG    print(urlParameters)
    requestResult = requests.post(TPTP2TFormReplyURL,files=urlParameters)
    print(requestResult.text)
#--------------------------------------------------------------------------------------------------
if __name__ == '__main__':
    main()
#--------------------------------------------------------------------------------------------------


#!/usr/bin/env python
import RPi.GPIO as GPIO
import time

buzzer = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(buzzer, GPIO.OUT)
GPIO.setwarnings(False)

pwm = GPIO.PWM(buzzer, 51) # 262
pwm.start(50.0)
time.sleep(0.5)

pwm.stop()
GPIO.cleanup()


from .constants import *

MAX_DEPTH = 19

def parse_list(tokens, depth):
    if depth > MAX_DEPTH:
        raise Exception("Nesting too deep")
    json_list = []
    t = tokens[0]

    # iterate until we find a right bracket, return when we find one, plug the rest
    if t == JSON_RIGHTBRACKET:
        return json_list, tokens[1:]

    while True:
        json, tokens = my_parse(tokens, depth)
        json_list.append(json)

        t = tokens[0]
        if t == JSON_COMMA:
            if len(tokens) < 2 or tokens[1] in [JSON_COMMA, JSON_RIGHTBRACKET]:
                raise Exception("Error: Trailing comma in object")
            tokens = tokens[1:]
        elif t == JSON_RIGHTBRACKET:
            return json_list, tokens[1:]
        else:
            raise Exception(
                "Expected comma or closing bracket in list, got {}".format(t)
            )

def parse_object(tokens, depth):
    if depth > MAX_DEPTH:
        raise Exception("Nesting too deep")
    json_object = {}

    t = tokens[0]
    if t == JSON_RIGHTBRACE:
        return json_object, tokens[1:]

    while True:
        json_key = tokens[0]

        if type(json_key) is str:
            tokens = tokens[1:]
        else:
            raise Exception("Expected string key, got {}".format(json_key))

        if tokens[0] != JSON_COLON:
            raise Exception("Expected colon after key in object got: {}".format(t))

        json_value, tokens = my_parse(tokens[1:], depth)

        json_object[json_key] = json_value

        t = tokens[0]

        if t == JSON_COMMA:
            if len(tokens) < 2 or tokens[1] in [JSON_COMMA, JSON_RIGHTBRACE]:
                raise Exception("Error: Trailing comma in object")
            tokens = tokens[1:]
        elif t == JSON_RIGHTBRACE:
            return json_object, tokens[1:]
        else:
            raise Exception(
                "Expected comma or closing brace in object, got {}".format(t)
            )

def my_parse(tokens, depth=0):
    t = tokens[0]

    # check if list or object
    if t == JSON_LEFTBRACKET:
        return parse_list(tokens[1:], depth + 1)
    elif t == JSON_LEFTBRACE:
        return parse_object(tokens[1:], depth + 1)
    else:
        return t, tokens[1:]


import pandas as pd
from nrclex import NRCLex
import numpy as np
import os
import matplotlib as mpl
from matplotlib import cm
from nltk import word_tokenize
import spacy
nlp = spacy.load('en_core_web_sm')
import re

filepath = os.path.abspath('')
output_path = os.path.abspath('dict')
#READ .dic
def _parse_categories(lines):
    """
    Read (category_id, category_name) pairs from the categories section.
    Each line consists of an integer followed a tab and then the category name.
    This section is separated from the lexicon by a line consisting of a single "%".
    """
    for line in lines:
        line = line.strip()
        if line == "%":
            return
        # ignore non-matching groups of categories
        if "\t" in line:
            category_id, category_name = line.split("\t", 1)
            yield category_id, category_name

def _parse_lexicon(lines, category_mapping):
    """
    Read (match_expression, category_names) pairs from the lexicon section.
    Each line consists of a match expression followed by a tab and then one or more
    tab-separated integers, which are mapped to category names using `category_mapping`.
    """
    for line in lines:
        line = line.strip()
        parts = line.split("\t")
        yield parts[0], [category_mapping[category_id] for category_id in parts[1:]]

def read_dic(filepath):
    """
    Reads a LIWC lexicon from a file in the .dic format, returning a tuple of
    (lexicon, category_names), where:
    * `lexicon` is a dict mapping string patterns to lists of category names
    * `category_names` is a list of category names (as strings)
    """
    with open(filepath) as lines:
        # read up to first "%" (should be very first line of file)
        for line in lines:
            if line.strip() == "%":
                break
        # read categories (a mapping from integer string to category name)
        category_mapping = dict(_parse_categories(lines))
        # read lexicon (a mapping from matching string to a list of category names)
        lexicon = dict(_parse_lexicon(lines, category_mapping))
    return lexicon, list(category_mapping.values())
    #return dizionario
#####################################
#Create emotion lists
def create_emotion_lists(df):
    emotion_lists = []
    for i in df:
        emotion_lists.append(df.loc[df[i]!=0][i].reset_index()['index'].tolist())
    return emotion_lists
####################################
# Funzione per lemmanization

def space(tweet):
    doc = nlp(tweet)
    return " ".join([token.lemma_ for token in doc])
###########################################
#CREATE SENTIMENT LIST
def sentiment_lists(df):
    sentiment_list= []
    for i in df:
        sentiment_list.append(df.loc[df[i]!=0][i].reset_index()['index'].tolist())
    return sentiment_list

########################################################

#Return df with the count of es. positive words present in the tweet
def text_emotion0(df_tweet, column, df_dic, emotions):
    #df : contiene i tweet
    #df3 : vocabolario
    '''
    INPUT: DataFrame, string
    OUTPUT: the original DataFrame with ten new columns for each emotion
    '''
    df = df_tweet.copy()
    #Set index as column and call it 'word'
    df_dic = df_dic.reset_index().rename(columns = {'index':'word'})
    #emotions = df_dic.columns.drop('word')
    emo_df = pd.DataFrame(0, index=df.index, columns=emotions)
    for i,row in df.iterrows():
        l=[]
        tweet = word_tokenize(df.loc[i][column])
        for wt in tweet:
            for word in df_dic['word']:
                l.append(bool(re.findall(r"\b"+word,wt)))
            s = pd.Series(l,name = 'word')
            emo_score = df_dic[s]
            l=[]
            if not emo_score.empty:
                for emotion in emotions:
                    emo_df.at[i, emotion] += emo_score[emotion]
    df = pd.concat([df, emo_df], axis=1)
    #Remove i tweet che non hanno associato nessun sentimento
    df = df[df[emotions].any(axis=1)]

    return df

def text_emotion(df_tweet, column, df_dic):
    '''
    INPUT: DataFrame, string
    OUTPUT: the original DataFrame with ten new columns for each emotion
    '''
    df = df_tweet.copy()
    #Set index as column and call it 'word'
    #df_dic = df_dic.reset_index().rename(columns = {'index':'word'})
    emotions = df_dic.columns.drop('word')
    emo_df = pd.DataFrame(0, index=df.index, columns=emotions)
    for i,row in df.iterrows():
        l=[]
        tweet = word_tokenize(df.loc[i][column])
        for wt in tweet:
            for word in df_dic['word']:
                l.append(bool(re.findall(r"\b"+word,wt)))
            s = pd.Series(l,name = 'word')
            emo_score = df_dic[s]
            if len(emo_score) > 1:
                emo_score = emo_score.reset_index().drop(['index'],axis=1).head(1)
            l=[]
            if not emo_score.empty:
                for emotion in emotions:
                    emo_df.at[i, emotion] += emo_score[emotion]
    df = pd.concat([df, emo_df], axis=1)
    #Remove i tweet che non hanno associato nessun sentimento
    df = df[df[emotions].any(axis=1)]
    return df

#######################################################################
#########################ANALYSIS########################

#Mi prende il df del parco che mi interessa e mi calcola la statistica
def df_byparks(park,df,emotions):
    df_park = df[df['text1'].str.contains(park)] #cerco i tweet che hanno quel parco all'interno del testo
    ds = df_park[emotions].describe()
    #inserire questa linea se voglio il mean sentiment counting di ogni parco
    #df_park= pd.DataFrame({park: aggr}, index = emotions)
    #emotional dataframe sorted with most common words
    #df_em_mc = pd.DataFrame({'emotion': sentiment_list, 'aggregation': aggr}).sort_values(by=['aggregation'],ascending=False)
    return df_park, ds

#Find words in tweet which are in sentiment_lists
def find_values(x,sent_list):
    results = []
    for value in sent_list:
        for word in x.split():
            if word == value:
                results.append(word)
    return results

def explode(df,sent_list):
    #inserisco nella colonna result le parole dei tweet che si trovano nella lista
    df['result'] = df['text1'].apply(lambda x: find_values(x,sent_list))
    #elimino le righe in cui la colonna è vuota (perchè non ha trovato niente)
    df_match_list = df[df['result'].map(lambda d: len(d)) > 0]
    df_result = df_match_list.explode("result").groupby(by="result")["result"].count().sort_values(ascending=False)
    return df_result.reset_index(name="count"), df_match_list

def colors(sent):
    # import the desired colormap from matplotlib
    if sent == 'pos':
        cmap = mpl.cm.Blues(np.linspace(0,1,20))
        # the darker part of the matrix is selected for readability
        cmap = mpl.colors.ListedColormap(cmap[-10:,:-1])
        color = 'lightblue'
    else:
        cmap = mpl.cm.Reds(np.linspace(0,1,20))
        cmap = mpl.colors.ListedColormap(cmap[-10:,:-1])
        color = 'red'
    return cmap, color


import turtle as tut

# time wasted 2 hr
#
# actually seeing as it only does 1 'side' of the triangle per function, i may have gotten it but then ..
# .. tried to draw the entire triangle in 1 go, maybe thats much more complicated to do in recursion

def drawKochCurve (t,level,distance):  # copypaste because i can not figure this out
    if level == 0:
        t.forward(distance)
    else:
        drawKochCurve(t, level - 1, distance / 3)
        t.left(60)
        drawKochCurve(t, level - 1, distance / 3)
        t.right(120)
        drawKochCurve(t, level - 1, distance / 3)
        t.left(60)
        drawKochCurve(t, level-1, distance / 3)
        input()

def koch(t, depth, distance):  # im shit
    if depth <= 0:
        t.right(120)
        t.forward(distance)
        t.left(60)
        return

    # for depth of 3

    # forward
    # left 45
    # make recursion

    # forward
    # left 45
    # make recursion

    ####### n1
    t.forward(distance)
    t.left(60)
    koch(t,depth-1,distance/2)
    t.forward(distance)
    t.left(60)
    t.forward(distance)
    ####### n1

    # forward
    # left 45
    # make recursion
    # forward
    # left 45

    # no recursion return
    # rigth 90 + 45
    # forward
    # left 45

    # forward
    # left 45
    # forward

    # right 120
    # repeat 2 more times

fred = tut.Turtle()
window = tut.Screen()
fred.speed(4)

#koch(fred,1,100)

drawKochCurve(fred,2,100)

window.exitonclick()

# def fuckrec(t,dis):
#     t.left(45)
#     t.forward(dis)
#     t.right(90)
#     t.forward(dis)
#     t.left(45)


class Solution:
    def maxDistance(self, grid: List[List[int]]) -> int:
        # define
        height, width = len(grid), len(grid[0])
        visited = set()
        min_heap = []

        # init
        for i in range(height):
            for j in range(width):
                if grid[i][j] == 1:
                    visited.add((i, j))
                    min_heap.append((0, i, j))

        # if 1 doesn't exist
        if len(min_heap) == 0:
            return -1

        # dijstra
        ans = -1
        while min_heap:
            score, i, j = heapq.heappop(min_heap)

            ans = max(ans, score)

            for x, y in [i-1, j], [i+1, j], [i, j-1], [i, j+1]:
                if not (0 <= x < height) or not (0 <= y < width) or (x, y) in visited:
                    continue

                visited.add((x, y))
                heapq.heappush(min_heap, (score+1, x, y))

        return ans if ans > 0 else -1


from intcode import IntCode
import queue

with open('day5_input.txt', 'r') as f:
	code = [int(t) for t in  f.read().split(',')]

print(code)

#code = [3,3,1108,-1,8,3,4,3,99]

out_queue = queue.Queue()
prg = IntCode(code)
prg.output = lambda x: out_queue.put(x)
prg.input.put(5)
prg.run()
result = out_queue.get()
print(f'result:{result}')


#conditional While

# loops = 0
# while loops < 1000:
#     print("This is a loop")
#     loops += 1
#
# print("End of loop")
#
#
# lives = 3
# while lives > 0:
#     play()
#     if collision:
#         lives -=1
# print("game over")
# import random
# score = 0
# lives = 3
# while lives > 0:
#     print(f"you have {lives} lives")
#     num1 = random.randint(0, 20)
#     num2 = random.randint(0, 20)
#     num3 = num1 + num2
#     print("What is", num1, "+", num2)
#     userans = int(input())
#     if userans == num3:
#         print("correct")
#         score += 1
#     else:
#         print("Incorrect")
#         lives -= 1
# print(f"you scored {score} points ")

valid = "no"
while valid == "no":
    userin = input("Enter a number")
    if userin.isnumeric():
        print("Thank you for a number")
        valid = "yes"
    else:
        print("That was not a number")
        valid = "no"

intconv = int(userin)
userchoice = intconv * 2
print("Your number doubled = ", userchoice)

print("Carry on ")

# loops = 1
# num = int(input("Enter a number"))
# while loops <= 12:
#     print(f"{num} * {loops} is {num*loops}")
#     loops += 1
#

#uncondtional For


salario = float(input())
imposto = 0.0

faixas = [
    (4500.00, 0.28),
    (3000.00, 0.18),
    (2000.00, 0.08)
]

for (valor, aliquota) in faixas:
    if salario > valor:
        diferenca = salario - valor
        imposto += diferenca * aliquota
        salario -= diferenca

print(f'Isento' if imposto == 0.0 else 'R$ {imposto:.2f}')


import functions
import PySimpleGUI as sg
import time
import os

TIME_FORMAT = "%b %d, %Y %H:%M:%S"
THEME = "DarkGreen1"

if not os.path.exists(functions.FILEPATH):
    with open(functions.FILEPATH, "w") as f:
        pass

sg.theme(THEME)
clock = sg.Text("", key='clock')
label = sg.Text("Type in a to-do")
input_box = sg.InputText(tooltip='Enter to-do', key='todo')
add_button = sg.Button("Add")
list_box = sg.Listbox(values=functions.get_todos(), key='current_todos',
                      enable_events=True, size=[45, 10])
edit_button = sg.Button("Edit")
complete_button = sg.Button("Complete")
exit_button = sg.Button("Exit")

window = sg.Window('My To-Do App',
                   layout=[[clock],
                           [label],
                           [input_box, add_button],
                           [list_box, edit_button, complete_button],
                           [exit_button]],
                   font=('Helvetica', + 20))

while True:
    event, values = window.read(timeout=200)
    window["clock"].update(value=time.strftime(TIME_FORMAT))
    print(event)
    print(values)
    if event == "Add":
        todos = functions.get_todos()
        new_todo = values['todo'] + "\n"
        todos.append(new_todo)
        functions.write_todos(todos)
        window['current_todos'].update(values=todos)

    elif event == "current_todos":
        if not values['current_todos']:
            continue
        else:
            window['todo'].update(value=values['current_todos'][0])

    elif event == "Edit":
        try:
            todo_to_edit = values['current_todos'][0]
            new_todo = values['todo'] + '\n'

            todos = functions.get_todos()
            index = todos.index(todo_to_edit)
            todos[index] = new_todo

            functions.write_todos(todos)
            window['current_todos'].update(values=todos)
        except IndexError:
            sg.popup("Please select an item first.", font=("Helvetica", 20))

    elif event == "Complete":
        try:
            todo_to_complete = values['current_todos'][0]
            todos = functions.get_todos()
            todos.remove(todo_to_complete)
            functions.write_todos(todos)
            window['current_todos'].update(values=todos)
            window['todo'].update(value='')
        except IndexError:
            sg.popup("Please select an item first.", font=("Helvetica", 20))

    elif event == sg.WIN_CLOSED or event == "Exit":
        break

window.close()

# install pyinstaller and run command to create executable for windows:
# pyinstaller --onefile --windowed --clean gui.py


def higher(roll1, roll2):
	if roll1 > roll2:
		return roll1
	else:
		return roll2

def lower(roll1, roll2):
	if roll1 < roll2:
		return roll1
	else:
		return roll2

adv_roll_counts = {}
disadv_roll_counts = {}
for i in range(0, 20):
	adv_roll_counts[i+1] = 0
	disadv_roll_counts[i+1] = 0

for i in range(0, 20):
	for j in range(0, 20):
		adv_roll_counts[higher(i+1, j+1)] += 1
		disadv_roll_counts[lower(i+1, j+1)] += 1

print("Advantage Probabilities:\t|\tDisadvantage Probabilities:")
for i in range(0, 20):
	print("Probability of\t", i+1, ": ", \
	      round(adv_roll_counts[i+1] / 20**2 * 100, 2), \
	      "%\t|\tProbability of\t", i+1, ": ", \
	      round(disadv_roll_counts[i+1] / 20**2 * 100, 2), "%", sep = '')


import lightgbm as lgb
import csv
import pandas as pd
import time
import json
# -*- coding: utf-8 -*-
from joblib import load, dump
from train import Train
from tqdm import tqdm
import re
from utils.features_ents import feature_ents
from utils.features_emos import feature_emos
from utils.nerdict import jieba_ner
import numpy as np
from sklearn.preprocessing import normalize
from sklearn.metrics import f1_score, recall_score, precision_score
# from utils.model_lgb import model_lgb
import pandas as pd
import numpy as np
import xgboost as xgb
from xgboost.sklearn import XGBClassifier
from sklearn.model_selection import GridSearchCV   #Perforing grid search
from sklearn.model_selection import train_test_split
from collections import Counter
from imblearn.over_sampling import SMOTE

all_Y_ents = []
test_file = '../data/coreEntityEmotion_train.txt'
test_file = open(test_file)
for news in tqdm(test_file):
    news = json.loads(news)
    Y_ents_emos = news['coreEntityEmotions']
    Y_ents = []
    for y in Y_ents_emos:
        Y_ents.append(y['entity'])
    all_Y_ents.append(Y_ents)

def loadData(path):
    res = []
    file = open(path)
    for f in file:
        res.append(json.loads(f))
    return res

count = 0
# ners_appear_times = {}   #自己的分词出现的次数
ners_select_times = {}   #实体被当做真实实体的次数
ners_select_per = {}     #实体被当做真实实体的概率
for Y_ents in all_Y_ents:
    count+=1
    for ent in Y_ents:
        if ners_appear_times[ent] == 0:
            print(ent)
            continue
        if ent in ners_select_times:
            ners_select_times[ent] += 1
            ners_select_per[ent] = ners_select_times[ent]/ners_appear_times[ent]
        else:
            ners_select_times[ent] = 1
            ners_select_per[ent] = 1/ners_appear_times[ent]

dump(ners_select_per,'features/all_ners_select_per.joblib')
dump(ners_select_times,'features/all_ners_select_times.joblib')
print("done")

import time
import scipy.special as special
class BayesianSmoothing(object):
    def __init__(self, alpha, beta):
        self.alpha = alpha
        self.beta = beta

    def sample(self, alpha, beta, num, imp_upperbound):
        sample = numpy.random.beta(alpha, beta, num)
#         print(sample)
        I = []
        C = []
        for clk_rt in sample:
            imp = imp_upperbound
            clk = imp * clk_rt
            I.append(imp)
            C.append(clk)
        return I, C

    def update(self, imps, clks, iter_num, epsilon):

        for i in range(iter_num):
            new_alpha, new_beta = self.__fixed_point_iteration(imps, clks, self.alpha, self.beta)
            if abs(new_alpha - self.alpha) < epsilon and abs(new_beta - self.beta) < epsilon:
                break
            self.alpha = new_alpha
            self.beta = new_beta

    def __fixed_point_iteration(self, imps, clks, alpha, beta):
        numerator_alpha = 0.0
        numerator_beta = 0.0
        denominator = 0.0
#         print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
        for i in range(0, len(imps), 1):    # 步长复用时去掉
            numerator_alpha += (special.digamma(clks[i] + alpha) - special.digamma(alpha))
            numerator_beta += (special.digamma(imps[i] - clks[i] + beta) - special.digamma(beta))
            denominator += (special.digamma(imps[i] + alpha + beta) - special.digamma(alpha + beta))
        return alpha * (numerator_alpha / denominator), beta * (numerator_beta / denominator)
def bys(I, C):
    bs = BayesianSmoothing(1, 1)
    # I, C = bs.sample(500, 500, 10, 1000)
    bs.update(I, C, 1000, 0.00001)   #
#     print(bs.alpha, bs.beta)
    ctr = []
    for i in range(len(I)):
        ctr.append((C[i] + bs.alpha) / (I[i] + bs.alpha + bs.beta))
    return ctr

bys_ctr = {}
for ent in tqdm(ners_select_times):
    if ners_select_times[ent] > 9:
        bys_ctr[ent] = bys([ners_select_times[ent]],[ners_select_per[ent]])

dump(bys_ctr,'features/bys_ctr_10.joblib')


import os.path
debug = os.path.exists("debug")

import logging
if debug:
	logging.basicConfig(level=logging.DEBUG)
else:
	logging.basicConfig(filename='app.log', filemode='w', level=logging.ERROR)

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker as _sessionmaker

if debug:
	engine = create_engine('sqlite:///database.db')
else:
	engine = create_engine('mysql+mysqlconnector://root:kNG7Dm2yC6dGfAD3AVkYjtYh_@localhost/qmarket', pool_size=20)

sessionmaker = _sessionmaker(bind=engine)


import os
import cPickle
from iz_tools.system import fopen

class cache(object):
    """ A simple caching mechanism """

    def __init__(self,dirname):
        """
        Setup the object
        @param self
        @param string dirname name of the cache directory
        """
        try: self.encoding = encoding
        except: self.encoding = 'utf-8'
        self.dirname = dirname
        if not os.path.isdir(dirname):
            splitted = dirname.split(os.sep)
            temp = ""
            for path_element in splitted: # loop through path components, making directories as needed
                temp += path_element + os.sep
                if os.access(temp, os.F_OK) == 1:
                    continue
                else:
                    os.mkdir(temp)

    def makename(self,fname,ctype):
        """
        Setup cache file name
        @param self
        @param string fname name of the original file
        @param string ctype type of the cached part
        @return string cname cache file name
        """
        return os.path.join( self.dirname, fname.replace(os.sep,'%2f') + '.' + ctype )

    def getOName(self,cname,ctype):
        """
        Get the name of the original file a cache file belongs to (counter-part to makename)
        @param self
        @param strinc cname filename of the cache file
        @return string fname filename of the original file
        """
        #return cname[len(self.dirname):-len(ctype)-1].replace('%2f',os.sep)
        return cname[0:-len(ctype)-1].replace('%2f',os.sep)

    def check(self,fname,ctype,ftim=0):
        """
        Check whether the copy in cache is up-to-date
        @param self
        @param string fname name of the original file
        @param string ctype type of the cached part
        @param optional float ftim time to check the cache against. If 0 (default),
               check runs against the file specified by fname. Otherwise, the fname
               file itself will be ignored, and cache checked using ftim. So ftim
               should correspond to what os.path.getmtime() would have returned.
        @return boolean up2date
        """
        if ftim==0 and not os.path.isfile(fname): return False # no origin
        if not os.path.isdir(self.dirname): return False # no cache dir
        cname = self.makename(fname,ctype)
        if not os.path.isfile(cname): return False # no cache
        if os.path.getsize(cname) == 0: return False # no content
        if ftim==0: ftim = os.path.getmtime(fname)
        if ftim > os.path.getmtime(cname): # expired
            os.unlink(cname)
            return False
        return True

    def removeObsolete(self,basedir=''):
        """
        Cleanup files from cache which do no longer exist in the original location
        (i.e. which have been deleted/moved, so they would no longer match)
        @param self
        @param optional string basedir   base directory of original codebase
        @return int removed              how many files have been removed
        """
        if not os.path.isdir(self.dirname): return 0 # no cache dir
        names=os.listdir(self.dirname)
        dc = 0
        for i in names:
            splitted = i.split('.')
            ctype = splitted[len(splitted)-1]
            if not ctype in ['code','formcode']: continue
            if not os.path.isfile(self.getOName(i,ctype)):
                os.unlink( os.path.join(self.dirname, i) )
                dc += 1
        return dc

    def get(self,fname,ctype):
        """
        Get the string from cache content for a given file
        @param self
        @param string fname name of the original file
        @param string ctype type of the cached part
        @return string content (empty string if none)
        """
        cname = self.makename(fname,ctype)
        if not os.path.isfile(cname): return '' # no cache
        cfile = fopen(cname,'r','zip')
        cont  = cfile.read().decode(self.encoding)
        cfile.close()
        return cont

    def getObj(self,fname,ctype,ftim):
        """
        Get the object from cache content for a given file. Uses cPickle
        @param self
        @param string fname name of the original file
        @param string ctype type of the cached part
        @return obj content or False if not found in cache
        """
        cname = self.makename(fname,ctype)
        if not os.path.isfile(cname): return False # no cache
        cfile = open(cname,'r')
        cont  = cPickle.load(cfile)
        cfile.close()
        return cont

    def put(self,fname,ctype,content):
        """
        Save content to cache
        @param self
        @param string fname name of the original file
        @param string ctype type of the cached part
        @param string content
        """
        cname = self.makename(fname,ctype)
        cfile = fopen(cname,'w','zip')
        cont = content.encode(self.encoding)
        cfile.write( cont )
        cfile.close()

    def putObj(self,fname,ctype,obj):
        """
        Save object to cache using cPickle
        @param self
        @param string fname name of the original file
        @param string ctype type of the cached part
        @param object obj
        """
        cname = self.makename(fname,ctype)
        cfile = open(cname,'w')
        cPickle.dump(obj,cfile,cPickle.HIGHEST_PROTOCOL)
        cfile.close()

    def clear(self,ctype='all'):
        """
        Remove cached content
        @param self
        @param optional ctype type (extension) of cache to remove (default: 'all')
        """
        if ctype=='all':
            for fname in os.listdir(self.dirname): os.unlink(fname)
        else:
            ext = '.'+ctype
            pos = len(ext)
            for fname in os.listdir(self.dirname):
                if fname[len(fname)-pos:]==ext: os.unlink(os.path.join(self.dirname,fname))


from flask import jsonify

from austin import client

def create_album(name):
    client.create_bucket(Bucket=name)

def list_albums():
    return client.list_buckets()['Buckets']

def list_images(album):
    objects = []
    for key in client.list_objects(Bucket=album)['Contents']:
        objects.append(key['Key'])

    return objects

def add_image(permisson, album, file_object, filename):
    client.put_object(ACL=permisson, Body=file_object, Bucket=album, Key=filename, ContentType='image/jpeg')

def get_URL(file_name):
    return client.generate_presigned_post(Bucket='austin', Key=file_name)

def get_albums():
    try:

        result = client.list_objects(Bucket='austin', Prefix='albums/', Delimiter='/')
        album_names = []
        for object in result.get('CommonPrefixes'):
            album_names.append(object['Prefix'][6:].strip('/'))

        albums = []
        for album_name in album_names:
            album = {
                'Name': album_name,
                'images': get_images(album_name)
            }
            albums.append(album)

        return albums

    except Exception as e:
        print(e)
        return jsonify({"error": "There was a problem with the data you provided."})

def get_images(album):
    try:

        prefix = 'albums/' + str(album) + '/'
        result = client.list_objects(Bucket='austin', Prefix=prefix, Delimiter='/')

        image_urls = []
        skipthedir = 0  # becuase the directory itself is also retrived we want to skip it
        for object in result.get('Contents'):
            if skipthedir > 0:
                url = get_URL(object.get('Key'))
                image_urls.append(url.get('url') + '/' + url.get('fields')['key'])
            else:
                skipthedir += 1

        return image_urls

    except Exception as e:
        print(e)
        return jsonify({"error": "There was a problem with the data you provided."})


import os
import cv2

dirname = os.path.dirname(__file__)                         #현재 파일의 위치
filename = os.path.join(dirname, '../images/trump.jpg')     #현재 위치로 부터 원하는 파일의 [상대적 위치]
img = cv2.imread(filename)                                  #이미지 열어서 img에 저장
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
print(len(gray[0][0]))

while True:                                                 #무조건 반복
    cv2.imshow('window', gray)                                #img를 window창에 표시
    if cv2.waitKey(1) == ord('q'):                          #키보드 q가 눌리면
        break                                               #반복 중단
cv2.destroyAllWindows()                                     #모든 cv창 종료


class MetaInformationObject:
    def __init__(self):
        self.videoUrl = ""
        self.videoTitle = ""
        self.videoDuration = ""
        self.rating = 0
        self.tagList = []
        self.thumbnailPath = ""
        self.discription = ""
        self.id = ""
        self.data = ""

class DataBaseFile:
    def __init__(self):
        self.MetaInformationObjectList = []

################################## H E L P E R ####################################
#
# class newModule:
#     def __init__(self):
#         self.videoUrl = ""
#         self.videoTitle = ""
#         self.videoDuration = ""
#         self.rating = 0
#         self.tagList = []
#         self.thumbnailPath = ""
#         self.discription = ""
#         self.id = ""
#         self.data = ""

# class prevModule:
#     def __init__(self):
#         self.videoUrl = ""
#         self.videoTitle = ""
#         self.videoDuration = ""
#         self.rating = 0
#         self.tagList = []
#         self.thumbnailPath = ""
#         self.discription = ""

class User:
    def __init__(self):
        self.username = ""
        self.password = ""
        self.email = ""
        self.favouriteList = ""
        self.historyList = ""
        self.loginStampList = []
        self.ipLoginList = []

class AnaltycisObject:
    def __init__(self):
        self.metaInformationObject = MetaInformationObject()
        self.watchCounter = 0
        self.upVotes = 0
        self.downVotes = 0