from sre_constants import AT_MULTILINE
from typing import Dict, Tuple, List
import pandas as pd
import numpy as np

def parse_date(change_hist_df):
    """
    """
    from datetime import datetime
    convert_to_ts = lambda str_chgd_date: datetime.strptime(
        str_chgd_date, '%Y %b %d %H:%M'
        ) if isinstance(str_chgd_date, str) else str_chgd_date#

    change_hist_df.authored_date = change_hist_df.authored_date.apply(convert_to_ts)
    return change_hist_df

def compute_change_vector(
    target_commit: str,
    change_hist: pd.DataFrame,
    n_min_mod:int = 1) -> Tuple:
    """
    target_commit:
    """
    from utils.hunk_utils import get_changed_method

    target_del_add_mths, _, _ = get_changed_method(change_hist.loc[target_commit].changes)
    if len(target_del_add_mths) <= n_min_mod:
        return (None, None)

    chg_time_vector = {mod_mth:[] for mod_mth in target_del_add_mths}
    chg_commit_vector = {mod_mth:[] for mod_mth in target_del_add_mths}
    tcommit_time = change_hist.loc[target_commit].authored_date

    # previous changes, INCLUDING the current one
    upto_change_hist = change_hist.loc[change_hist.authored_date <= tcommit_time]
    for index_commit, row in list(upto_change_hist[['changes', 'authored_date']].iterrows()):
        deleted_or_added_mths, _, _ = get_changed_method(row.changes)
        intersected_mths = set(target_del_add_mths).intersection(set(deleted_or_added_mths))
        for inter_mth in intersected_mths:
            chg_time_vector[inter_mth].append(row.authored_date)
            chg_commit_vector[inter_mth].append(index_commit)

    return chg_time_vector, chg_commit_vector

def compute_dist(chgdat_of_a, chgdat_of_b, gran = 'sec', _N_recent_time = None):
    """
    dist of a to b
    """
    N_recent_time = -1
    t_N_recent_time = N_recent_time if _N_recent_time is None else _N_recent_time

    if len(chgdat_of_a) == 0 or len(chgdat_of_b) == 0:
        return -1 # meaning nothing has been changeed recently
    else:
        closet_dist = np.min(
            np.abs(
                chgdat_of_a[:,None] - chgdat_of_b),
                axis = 1
            )
        t = np.mean(closet_dist).total_seconds()
        if t_N_recent_time > 0 and t > t_N_recent_time:
            assert False

        time_dist = np.mean(closet_dist).total_seconds()
        if gran == 'sec':
            return time_dist
        elif gran == 'min':
            return np.round(time_dist/60)
        elif gran == 'hour':
            return np.round(time_dist/(60*60))
        elif gran == 'day':
            return np.round(time_dist/(60*60*24))
        else:
            print ("Does not support this granularity ({})".format(gran))
            assert False

def compute_authorship_vector(
    target_commit: str,
    change_hist: pd.DataFrame,
    n_min_mod:int = 1) -> Tuple:
    """
    target_commit:
    """
    from utils.hunk_utils import get_changed_method

    target_del_add_mths, _, _ = get_changed_method(change_hist.loc[target_commit].changes)
    if len(target_del_add_mths) <= n_min_mod:
        return None

    tcommit_time = change_hist.loc[target_commit].authored_date
    # previous changes, INCLUDING the current one
    upto_change_hist = change_hist.loc[change_hist.authored_date <= tcommit_time]
    authorship_vector = {mod_mth:[] for mod_mth in target_del_add_mths}
    for index_commit, row in list(upto_change_hist[['changes', 'commit.author.name']].iterrows()):
        deleted_or_added_mths, _, _ = get_changed_method(row.changes)
        intersected_mths = set(target_del_add_mths).intersection(set(deleted_or_added_mths))
        author = row['commit.author.name']
        for inter_mth in intersected_mths:
            authorship_vector[inter_mth].append(author)
    return authorship_vector

def compute_jaro_wrinkler_sim(
    mth_a:Tuple[str,str],
    mth_b:Tuple[str,str]) -> float:
    """
    """
    from nltk.metrics.distance import jaro_winkler_similarity
    # class part
    def get_core_clss(class_k:str) -> str:
        prev_c, c = class_k.split("#")
        prev_c = prev_c.split(".")[-1]
        return prev_c + " " + c

    class_a = get_core_clss(mth_a[0])
    class_b = get_core_clss(mth_b[0])
    class_sim = jaro_winkler_similarity(class_a, class_b)

    # method part
    def get_mthname(mth_k:str) -> str:
        mth = mth_k.split("(")[0]
        return mth

    mthname_a = get_mthname(mth_a[1])
    mthname_b = get_mthname(mth_b[1])
    mth_sim = jaro_winkler_similarity(mthname_a, mthname_b)

    return class_sim, mth_sim

# compute various types of distances
def compute_distances(
    which_types:List[str],
    mod_mths_info:pd.DataFrame) -> Dict[str,float]:
    """
    which_types -> chgdat, author, lexical sim
    """
    import numpy as np
    from itertools import combinations

    ret_dists = {}
    mod_mths = list(mod_mths_info.keys())
    if 'author' in mod_mths:
        mod_mths.remove('author')
    mth_pairs = list(combinations(mod_mths, 2))
    for a_mod_mth, b_mod_mth in mth_pairs:
        a_info = mod_mths_info[a_mod_mth]
        b_info = mod_mths_info[b_mod_mth]
        ret_dists[(a_mod_mth, b_mod_mth)] = {}
        for which_type in which_types:
            if which_type == 'chgdat':
                a_dist_arr = np.array(a_info['chgdat'])
                if a_dist_arr is None:
                    assert False # have to decide
                else:
                    a_dist_arr.sort()
                    a_dist_arr = a_dist_arr[::-1]

                b_dist_arr = np.array(b_info['chgdat'])
                if b_dist_arr is None:
                    assert False # have to decide
                b_dist_arr.sort()
                b_dist_arr = b_dist_arr[::-1]

                # exclude the current changes only for the opponent
                a_to_b_dist = compute_dist(
                    a_dist_arr[1:], b_dist_arr, gran = 'day')
                b_to_a_dist = compute_dist(
                    b_dist_arr[1:], a_dist_arr, gran = 'day')

                ret_dists[(a_mod_mth, b_mod_mth)][
                    which_type] = [a_to_b_dist, b_to_a_dist]
            elif which_type == 'static':
                # for now, lexical similarity between two method identifiersg
                cls_jarow_sim, mth_jarow_sim = compute_jaro_wrinkler_sim(a_mod_mth, b_mod_mth)
                ret_dists[(a_mod_mth, b_mod_mth)][
                    which_type] = cls_jarow_sim * mth_jarow_sim # can be anything
            elif which_type == 'authorship':
                # compare a list of authors that modified two methods & compute
                a_authored = np.array(a_info['authored'])
                b_authored = np.array(b_info['authored'])
                if a_authored is None:
                    assert False
                if b_authored is None:
                    assert False
                # need to change to authorship vector
                author_pool_v = np.append(a_authored, b_authored)
                uniq_authors = np.unique(author_pool_v)
                a_authored_v = np.zeros(len(uniq_authors))
                b_authored_v = np.zeros(len(uniq_authors))
                for i,author in enumerate(uniq_authors):
                    a_authored_v[i] = np.sum(a_authored == author)
                    b_authored_v[i] = np.sum(b_authored == author)
                #
                denominator = np.linalg.norm(a_authored_v) * np.linalg.norm(b_authored_v)
                if denominator == 0:
                    if np.linalg.norm(a_authored_v) == np.linalg.norm(b_authored_v):
                        # for inspecting the entire hist, shouldn't be here
                        sim = 1.
                    else:
                        sim = 0.
                else:
                    numerator = np.dot(a_authored_v, b_authored_v)
                    sim = numerator/denominator
                ret_dists[(a_mod_mth, b_mod_mth)][which_type] = np.float32(sim)

    return ret_dists


import numpy as np
import cv2
from model import robot
from model import point
from utility.correction import point_correction

def getRobot(img):
    # Capture frame-by-frame
    tempRobot = robot.Robot

    blurred = cv2.GaussianBlur(img, (5, 5), 0)
    hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV)

    boundaries = [
        ([27, 50, 20], [35, 255, 255])
    ]

    boundaries1 = [
        # Dag kørsel:
        ([120, 40, 20], [175, 255, 255])

        #Nat kørsel:
        # ([140, 40, 10], [190, 255, 255])
    ]

    # roed: ([17, 15, 100], [50, 56, 200])
    # blaa: ([86, 31, 4], [220, 88, 50]),
    # gul: ([25, 146, 190], [62, 174, 250])
    # graa: ([103, 86, 65], [145, 133, 128])

    # loop over the boundaries
    for (lower, upper) in boundaries:
        # create NumPy arrays from the boundaries
        lower = np.array(lower, dtype="uint8")
        upper = np.array(upper, dtype="uint8")

        # find the colors within the specified boundaries and apply
        mask = cv2.inRange(hsv, lower, upper)

    for (lower, upper) in boundaries1:
        # create NumPy arrays from the boundaries
        lower1 = np.array(lower, dtype="uint8")
        upper1 = np.array(upper, dtype="uint8")

        mask1 = cv2.inRange(hsv, lower1, upper1)

        # tempRobot = robot.Robot

        # Finding the biggest contour to find robot
        contours, _ = cv2.findContours(mask1, 1, 1)
        max_area = 0
        best_cnt = 0

        for cnt in contours:
            area = cv2.contourArea(cnt)
            if area > max_area:
                max_area = area
                best_cnt = cnt

        # loop over the contours
        cont, _ = cv2.findContours(mask, 1, 1)
        bl_max_area = 0
        bl_best_cnt = 0
        for c in cont:
            # compute the center of the contour
            bl_area = cv2.contourArea(c)
            if bl_area > bl_max_area:
                bl_max_area = bl_area
                bl_best_cnt = c
        B = cv2.moments(bl_best_cnt)

        if B["m00"] != 0:
            cX = round(B["m10"] / B["m00"])
            cY = round(B["m01"] / B["m00"])
        else:
                # set values as what you need in the situation
            cX, cY = 0, 0
            #
            # # draw the contour and center of the shape on the image

        # Pixel correction
        x_val = np.amax(img, axis=0)
        y_val = np.amax(img, axis=1)
        x_val = round(len(x_val)/2)
        y_val = round(len(y_val)/2)
        camera_center = point.Point(x_val, y_val)
        bl = point.Point(cX, cY)
        blSquare_corrected = point_correction(camera_center, bl)
        # tempRobot.blSquareX = cX
        # tempRobot.blSquareY = cY

        tempRobot.blSquareX = blSquare_corrected.x
        tempRobot.blSquareY = blSquare_corrected.y

        # Center of robot
        if best_cnt is not None:
            M = cv2.moments(best_cnt)
            cx, cy = round(M['m10'] / M['m00']), int(M['m01'] / M['m00'])
            rect = cv2.minAreaRect(best_cnt)

            # Rotating box
            box = cv2.boxPoints(rect)
            box = np.int0(box)

            robot_center = point.Point(cx, cy)
            center_corrected = point_correction(camera_center, robot_center)

            # tempRobot.centrumX = cx
            # tempRobot.centrumY = cy
            tempRobot.centrumX = center_corrected.x
            tempRobot.centrumY = center_corrected.y
            tempRobot.box = box

        scale_percent = 30  # percent of original size
        width = int(mask1.shape[1] * scale_percent / 100)
        height = int(mask1.shape[0] * scale_percent / 100)
        dim = (width, height)
        # resize image
        resized = cv2.resize(mask1, dim, interpolation=cv2.INTER_AREA)

        scale_percent = 30  # percent of original size
        width = int(mask.shape[1] * scale_percent / 100)
        height = int(mask.shape[0] * scale_percent / 100)
        dim = (width, height)
        # resize image
        resized1 = cv2.resize(mask, dim, interpolation=cv2.INTER_AREA)

        cv2.imshow("maskPurple", resized)
        cv2.imshow("maskYellow", resized1)

    # print("\n")
    return tempRobot


import numpy as np
import matplotlib.pyplot as plt
import elecLoader as el

def func(E, p0, p1, p2, p3, p4):
    if E <= 0.2 :
        return 0
    else:
        E = E - 0.2
        N = p3*E**2/(p4+p0*E+p1*np.exp(-p2*E))
        return N

if __name__ == "__main__":

    x = np.arange(0.1, 40, 0.1)

    par = [4, 0.1, 3, 410, 1]

    Ac = 177.508 / 2.223

    Edep = np.arange(0.1, 15, 0.1)
    Edep1 = np.arange(0.1, 55, 0.1)
    truth = []
    shape1, shape2, shape3, shape4 = [], [], [], []
    for i in Edep:
        truth.append(el.getCerNPE(i))
    for i in Edep1:
        shape1.append(func(i, *par))
    truth  = np.array(truth)
    shape1 = np.array(shape1)
    Ac = 177.508/2.223

    Edep2 = [20, 30, 40, 50, 60]
    truth2 = [1985, 2995, 3968, 4955, 5952]
    Edep2 = np.array(Edep2)
    truth2 = np.array(truth2)

    #plt.plot(Edep, truth , "o", ms=3)
    #plt.plot(Edep1, shape1, label="All")
    #plt.plot(Edep2, truth2, "s")
    plt.plot(Edep,  truth/Ac/Edep , "o", ms=3)
    plt.plot(Edep1, shape1/Ac/Edep1, label="All")
    plt.plot(Edep2, truth2/Ac/Edep2, "s")
    #plt.plot(Edep1, shape2/Ac/Edep1, label="No p1")
    #plt.plot(Edep1, shape3/Ac/Edep1, label="No p0")
    #plt.plot(Edep1, shape4/Ac/Edep1, label="No p4")
    plt.legend()

    plt.show()


from bs4 import BeautifulSoup
import requests
# flipkart=''
headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36'}
def flipkart(name):
    try:
        global flipkart
        name1 = name.replace(" ","+")
        flipkart=f'https://www.flipkart.com/search?q={name1}&otracker=search&otracker1=search&marketplace=FLIPKART&as-show=off&as=off'
        res = requests.get(f'https://www.flipkart.com/search?q={name1}&otracker=search&otracker1=search&marketplace=FLIPKART&as-show=off&as=off',headers=headers)

        print("\nSearching in flipkart....")
        soup = BeautifulSoup(res.text,'html.parser')

        if(soup.select('._4rR01T')):
            flipkart_name = soup.select('._4rR01T')[0].getText().strip().upper()
            if name.upper() in flipkart_name:
                flipkart_price = soup.select('._30jeq3')[0].getText().strip()
                flipkart_name = soup.select('._4rR01T')[0].getText().strip()
                print("Flipkart:")
                print(flipkart_name)
                print(flipkart_price)
                print("---------------------------------")

        elif(soup.select('.s1Q9rs')):
            flipkart_name = soup.select('.s1Q9rs')[0].getText().strip()
            flipkart_name = flipkart_name.upper()
            if name.upper() in flipkart_name:
                flipkart_price = soup.select('._30jeq3')[0].getText().strip()
                flipkart_name = soup.select('.s1Q9rs')[0].getText().strip()
                print("Flipkart:")
                print(flipkart_name)
                print(flipkart_price)
                print("---------------------------------")
        else:
            flipkart_price='0'

        return flipkart_price
    except:
        print("Flipkart: No product found!")
        print("---------------------------------")
        flipkart_price= '0'
    return flipkart_price


import torch
from .discriminator_blocks import DiscriminatorMidBlock as DMB
from .discriminator_blocks import DiscriminatorFinalBlock as DFB
from numpy import log2
from .custom_classes import PGfromRGB, PGDownsample
from torch.nn import Module, Sequential
from os import getcwd
from os.path import exists

class Discriminator(Module):

    def __init__(self, spatial_resolution, configuration, transition=True, transition_coef=0.5, save_checkpoint=True,
                 load_initial_block=True, img_chanels=3, group_size=4, alpha=0.2):

        super(Discriminator, self).__init__()

        self.spatial_resolution = spatial_resolution
        self.minimum_spatial_resolution = 4
        self.levels = int(log2(self.spatial_resolution) - log2(self.minimum_spatial_resolution)) # starts from zero
        self.config = configuration
        self.channels = self.config['channels'][:self.levels + 2]
        self.latent_size = int(self.config['latent_size'])
        self.transition_coef = transition_coef
        self.save_checkpoint = save_checkpoint
        self.transition_level = -1 if self.levels == 0 else self.levels # todo be sure of this change not levels + 1 now
        self.transition = transition if self.spatial_resolution != self.minimum_spatial_resolution else False
        self.load_initial_block = True if load_initial_block and exists('{0}/weights/Dis_{1}x{1}'.format(getcwd(), self.spatial_resolution)) else False
        self.group_size = group_size
        self.alpha = alpha

        self.discriminator_body = Sequential()

        assert getcwd().replace('//', '/').split('/')[-1] == 'ProGan', 'make sure you are at the directory /ProGan.\n'

        self.fromrgb = PGfromRGB(self.channels[-1], img_chanels, 0.2, self.spatial_resolution)
        fromrgb_file_name = '{1}/weights/FromRGB_{0}x{0}'.format(self.spatial_resolution, getcwd())
        self.fromrgb = torch.load(fromrgb_file_name) if exists(fromrgb_file_name) else self.fromrgb #load

        if self.spatial_resolution == self.minimum_spatial_resolution:
            self.first_block = DFB(self.channels[1], self.channels[0], self.group_size, self.alpha)
            file_name = '{0}/weights/Dis_{1}x{1}'.format(getcwd(), self.spatial_resolution)
            self.first_block = torch.load(file_name) if exists(file_name) else self.first_block

        else:
            self.first_block = DMB(self.spatial_resolution, self.channels[self.levels], self.channels[self.levels-1], self.alpha)
            file_name = '{0}/weights/Dis_{1}x{1}'.format(getcwd(), self.spatial_resolution)
            self.first_block = torch.load(file_name) if self.load_initial_block and exists(file_name) else self.first_block #load

            if self.transition:
                # create and load the fade in block is transition
                self.fade_in = Sequential()
                self.fade_in.add_module("transition_downsample", PGDownsample())
                block = PGfromRGB(self.channels[-2], img_chanels, 0.2, self.spatial_resolution // 2)

                fromrgb_file_name = '{1}/weights/FromRGB_{0}x{0}'.format(self.spatial_resolution // 2, getcwd())
                block = torch.load(fromrgb_file_name) if exists(fromrgb_file_name) else block   #load
                self.fade_in.add_module("transition_FromRGB", block)

            for level in range(self.levels-1, -1, -1):

                # dummy variables used to initialize and load the discrminator
                width = int(2**(level + log2(self.minimum_spatial_resolution))) # width and height have the same size so use one of them
                file_name = '{0}/weights/Dis_{1}x{1}'.format(getcwd(), width) # name of possible saved block

                # be careful about the channel in and out here
                block = DFB(self.channels[1], self.channels[0], self.group_size, self.alpha) if level == 0 else DMB(width, self.channels[level], self.channels[level-1], self.alpha)
                block = torch.load(file_name) if self.exists(file_name) else block #load

                self.discriminator_body.add_module("block_{0}x{0}".format(width), block)

        if self.save_checkpoint:
            self.save()

    def forward(self, x):

        x1 = self.first_block(self.fromrgb(x))
        if self.transition:
            x1 = self.fade_in.forward(x) * (1. - self.transition_coef) + self.transition_coef * x1

        x = self.discriminator_body.forward(x1)
        return x

    def exists(self, directory):
        if exists(directory): return True
        else: print('block {} does not exist. program will continue without loading.\n'.format(directory))
        return False

    def save(self):

        self.fromrgb.save()
        self.first_block.save()

        for blocks in self.discriminator_body:
            blocks.save()
        if self.transition:
            self.fade_in[1].save()

        return

'''
config = {'channels':[512,512,512,512,256,128,64,32,16], 'latent_size':512}
x = torch.randn(12, 3, 16, 16)
a = Discriminator(16, config, transition=True)
# print(a.fade_in[1]) # the blocks are exactly the same as in the paper
print(a(x).shape)
'''


#!/usr/bin/env python3

# https://adventofcode.com/2021/day/11 - "flashing octopi"
# Author: Greg Hamerly

import sys

def iterate_board(board, max_iters, flashed_functor):
    '''Iterate the process described in the problem of adding one to every cell,
    and "flashing" whenever a cell reaches 10. Flashes add one to neighboring
    cells, which may cause them to flash, etc. No cell may flash more than once
    per iteration. Iterate for max_iters (at most), and call flashed_functor
    with the current iteration and the number of flashed cells. Stop iterating
    early if flashed_functor returns True.'''

    for iteration in range(1, max_iters + 1):
        # add one to each cell and find the initial set of flashes
        flashes = []
        flashed = set()
        bnew = [[ri + 1 for ri in row] for row in board]
        for i, row in enumerate(bnew):
            for j, col in enumerate(row):
                if col >= 10:
                    flashes.append((i, j))
                    flashed.add((i, j))
                    bnew[i][j] = 0

        # now do a sort of BFS for all other flashes
        while flashes:
            new_flashes = []
            for i, j in flashes:
                for ii in range(i-1, i+2):
                    for jj in range(j-1, j+2):
                        if ii == i and jj == j or (ii, jj) in flashed:
                            continue
                        if not (0 <= ii < len(bnew) and 0 <= jj < len(bnew[ii])):
                            continue

                        bnew[ii][jj] += 1
                        if bnew[ii][jj] >= 10:
                            new_flashes.append((ii, jj))
                            flashed.add((ii, jj))
                            bnew[ii][jj] = 0

            flashes = new_flashes

        board = bnew

        # call the given functor
        if flashed_functor(iteration, len(flashed)):
            return

def part1(board):
    '''Add up all the flashes that occur in 100 iterations.'''
    ans = 0
    def sum_flashed(_, flashed):
        nonlocal ans
        ans += flashed
    iterate_board(board, 100, sum_flashed)
    return ans

def part2(board):
    '''Identify the first iteration where all cells flash'''
    ans = None
    def all_flashed(iteration, flashed):
        nonlocal ans
        if flashed == len(board) * len(board[0]):
            ans = iteration
            return True
    iterate_board(board, 10000, all_flashed)
    return ans

def main():
    regular_input = __file__.split('/')[-1][:-len('.py')] + '.in'
    file = regular_input if len(sys.argv) <= 1 else sys.argv[1]
    print(f'using input: {file}')
    with open(file) as f:
        lines = list(map(str.strip, f))

    board = [list(map(int, line)) for line in lines]

    print('part 1:', part1(board))
    print('part 2:', part2(board))

if __name__ == '__main__':
    main()


from sys import stdin
input = stdin.readline

def main():
    T = int(input())
    li = []
    for _ in range(T):
        n = int(input())

        if n > 1:
            row1 = list(map(int, input().split()))
            row2 = list(map(int, input().split()))

            ans = [[row1[0], row2[0]],
                [row1[1] + row2[0], row2[1] + row1[0]]]

            for i in range(2, n):
                ans = [ans[1],
                    [row1[i] + max(ans[1][1], ans[0][1]),
                        row2[i] + max(ans[1][0], ans[0][0])]]

            li.append(max(ans[1]))

        else:
            li.append(max(int(input()), int(input())))

    print("\n".join(map(str, li)))

if __name__ == "__main__":
    main()


# Dictionary with all the price mapping of items
priceMap = {
        'A': {'SpecialOffer': 200, 'NormalOffer': 130, 'BasicPrice': 50},
        'B': {'NormalOffer': 45, 'BasicPrice': 30},
        'C': {'BasicPrice': 20},
        'D': {'BasicPrice': 15},
        'E': {'BasicPrice': 40},
        'F': {'BasicPrice': 10},
        'G': {'BasicPrice': 20},
        'H': {'SpecialOffer': 80, 'NormalOffer': 45, 'BasicPrice': 10},
        'I': {'BasicPrice': 35},
        'J': {'BasicPrice': 60},
        'K': {'NormalOffer': 120, 'BasicPrice': 70},
        'L': {'BasicPrice': 90},
        'M': {'BasicPrice': 15},
        'N': {'BasicPrice': 40},
        'O': {'BasicPrice': 10},
        'P': {'NormalOffer': 200, 'BasicPrice': 50},
        'Q': {'NormalOffer': 80, 'BasicPrice': 30},
        'R': {'BasicPrice': 50},
        'S': {'BasicPrice': 20},
        'T': {'BasicPrice': 20},
        'U': {'BasicPrice': 40},
        'V': {'SpecialOffer': 130, 'NormalOffer': 90, 'BasicPrice': 50},
        'W': {'BasicPrice': 20},
        'X': {'BasicPrice': 17},
        'Y': {'BasicPrice': 20},
        'Z': {'BasicPrice': 21},
}

# noinspection PyUnusedLocal
# skus = unicode string
def checkout(skus):
    totalAmountToPay = 0
    if skus:
        countMap = {}

        # create map of items count
        for char in skus:
            if char in priceMap.keys():
                if countMap.get(char):
                    countMap[char] = countMap[char] + 1
                else:
                    countMap[char] = 1
            else:
                return -1

        # apply special offer logic
        for key in countMap.keys():
            if key == 'E':
                count = countMap[key]
                itemWithOfferE = int(count / 2)
                if countMap.get('B'):
                    countMap['B'] = countMap['B'] - itemWithOfferE

            if key == 'N':
                count = countMap[key]
                itemWithOfferE = int(count / 3)
                if countMap.get('M'):
                    countMap['M'] = countMap['M'] - itemWithOfferE

            if key == 'R':
                count = countMap[key]
                itemWithOfferE = int(count / 3)
                if countMap.get('Q'):
                    countMap['Q'] = countMap['Q'] - itemWithOfferE

        # apply normal offer logic and calculate total amount of items.
        groupSpecialLogicCount = 0
        for key in countMap.keys():
            count = countMap[key]
            basicPrice = priceMap[key]['BasicPrice']
            normalOfferPrice = priceMap[key].get('NormalOffer')
            specialOfferPrice = priceMap[key].get('SpecialOffer')
            if key in ['A', 'B', 'F', 'H', 'K', 'P', 'Q', 'U', 'V']:
                if key == 'A':
                    flagForSpecialOffer = False
                    itemWithOutSpecialOffer = 0
                    itemWithSpecialOfferOffer = 0
                    if count >= 5:
                        itemWithSpecialOfferOffer = int(count / 5)
                        itemWithOutSpecialOffer = count % 5
                        flagForSpecialOffer = True
                    if flagForSpecialOffer:
                         count = itemWithOutSpecialOffer
                    itemWithOffer = int(count / 3)
                    itemWithOutOffer = count % 3
                    totalAmountToPay = totalAmountToPay + itemWithSpecialOfferOffer * specialOfferPrice + itemWithOffer * normalOfferPrice + itemWithOutOffer * basicPrice
                if key in ['B', 'K'] and count > 0:
                    itemWithOffer = int(count / 2)
                    itemWithOutOffer = count % 2
                    totalAmountToPay = totalAmountToPay + itemWithOffer * normalOfferPrice + itemWithOutOffer * basicPrice
                if key == 'F':
                    itemWithOffer = int(count / 3)
                    itemWithOutOffer = count % 3
                    totalAmountToPay = totalAmountToPay + itemWithOffer * 2 * basicPrice + itemWithOutOffer * basicPrice
                if key == 'U':
                    itemWithOffer = int(count / 4)
                    itemWithOutOffer = count % 4
                    totalAmountToPay = totalAmountToPay + itemWithOffer * 3 * basicPrice + itemWithOutOffer * basicPrice
                if key == 'P':
                    itemWithOffer = int(count / 5)
                    itemWithOutOffer = count % 5
                    totalAmountToPay = totalAmountToPay + itemWithOffer * normalOfferPrice + itemWithOutOffer * basicPrice
                if key == 'Q':
                    itemWithOffer = int(count / 3)
                    itemWithOutOffer = count % 3
                    totalAmountToPay = totalAmountToPay + itemWithOffer * normalOfferPrice + itemWithOutOffer * basicPrice
                if key == 'H':
                    flagForSpecialOffer = False
                    itemWithOutSpecialOffer = 0
                    itemWithSpecialOfferOffer = 0
                    if count >= 10:
                        itemWithSpecialOfferOffer = int(count / 10)
                        itemWithOutSpecialOffer = count % 10
                        flagForSpecialOffer = True
                    if flagForSpecialOffer:
                         count = itemWithOutSpecialOffer
                    itemWithOffer = int(count / 5) if count >= 5 else 0
                    itemWithOutOffer = count % 5
                    totalAmountToPay = totalAmountToPay + itemWithSpecialOfferOffer * specialOfferPrice + itemWithOffer * normalOfferPrice + itemWithOutOffer * basicPrice
                if key == 'V':
                    flagForSpecialOffer = False
                    itemWithOutSpecialOffer = 0
                    itemWithSpecialOfferOffer = 0
                    if count >= 3:
                        itemWithSpecialOfferOffer = int(count / 3)
                        itemWithOutSpecialOffer = count % 3
                        flagForSpecialOffer = True
                    if flagForSpecialOffer:
                        count = itemWithOutSpecialOffer
                    itemWithOffer = int(count / 2) if count >= 2 else 0
                    itemWithOutOffer = count % 2
                    totalAmountToPay = totalAmountToPay + itemWithSpecialOfferOffer * specialOfferPrice + itemWithOffer * normalOfferPrice + itemWithOutOffer * basicPrice
            else:
                if countMap[key] > 0:
                    if key in ['S', 'T', 'X', 'Y', 'Z']:
                        groupSpecialLogicCount = groupSpecialLogicCount + count
                    else:
                        totalAmountToPay = totalAmountToPay + countMap[key] * basicPrice

        itemWithOffer = int(groupSpecialLogicCount / 3)
        itemWithOutOffer = groupSpecialLogicCount % 3
        avgPrice = 0
        if itemWithOutOffer == 2:
            if countMap.get('X'):
                if countMap.get('X') == 2:
                    avgPrice = priceMap['X']['BasicPrice']
                else:
                    price1 = priceMap['X']['BasicPrice']
                    if any([countMap.get('S'), countMap.get('T'), countMap.get('Y')]):
                        price2 = priceMap['S']['BasicPrice']
                    else:
                        price2 = priceMap['Z']['BasicPrice']
                    avgPrice = (price1 + price2) / 2
            elif any([countMap.get('S'), countMap.get('T'), countMap.get('Y')]):
                if (
                        (countMap.get('S') and countMap.get('T')) or
                        (countMap.get('S') and countMap.get('Y')) or
                        (countMap.get('T') and countMap.get('Y')) or
                        (countMap.get('S') > 1) or
                        (countMap.get('T') > 1) or
                        (countMap.get('Y') > 1)
                ):
                    avgPrice = priceMap['S']['BasicPrice']
                else:
                    price1 = priceMap['S']['BasicPrice']
                    price2 = priceMap['Z']['BasicPrice']
                    avgPrice = (price1 + price2) / 2
            else:
                avgPrice = priceMap['Z']['BasicPrice']

        elif itemWithOutOffer == 1:
            if countMap.get('X'):
                avgPrice = price2 = priceMap['X']['BasicPrice']
            elif countMap.get('S') or countMap.get('T') or countMap.get('Y'):
                avgPrice = price2 = priceMap['S']['BasicPrice']
            else:
                avgPrice = price2 = priceMap['Z']['BasicPrice']

        totalAmountToPay = totalAmountToPay = totalAmountToPay + itemWithOffer * 45 + itemWithOutOffer * avgPrice

    return totalAmountToPay if totalAmountToPay else 0


import dash_bootstrap_components as dbc
import requests as requests
from dash import html, dcc
from dash.dash_table import DataTable
from dashapp import dash_app

def layout_rows():
    loading = dcc.Loading(
        id="loading-1",
        type="default",
        # fullscreen=True,
        children=html.Div(id="loading-output-1")
    )

    validate_locations_btn = dbc.Button('Validate Locations', id='validate_locations_btn')
    validate_things_btn = dbc.Button('Validate Things', id='validate_things_btn')
    validate_datastreams_btn = dbc.Button('Validate Datastreams', id='validate_datastreams_btn')
    validate_all_btn = dbc.Button('Validate All', id='validate_all_btn')
    validate_btn_grp = dbc.ButtonGroup([validate_all_btn,
                                        validate_locations_btn,
                                        validate_things_btn,
                                        validate_datastreams_btn
                                        ])
    cols = [{"name": "Name", "id": "name"},
            {"name": "@iot.id", "id": "@iot.id"},
            {"name": "ValidationError", "id": "validation_error"},
            {"name": "Instance", "id": "instance", 'presentation': 'markdown'},
            ]
    dt = DataTable(
        id='validation_results',
        style_cell={"textAlign": "left"},
        columns=cols,
        style_as_list_view=True,
        page_size=10,

        style_header={
            "font-family": "verdana",
            "font-weight": "bold",
            "fontSize": "10px",
            # "height": "50px"
        },
        style_data={"fontSize": "10px", "font-family": "verdana",
                    # 'whiteSpace': 'pre-line'
                    },
        style_table={"height": "600px", "overflowY": "auto"},
    )

    return [dbc.Row([dbc.Col([dbc.Input(id='url_to_validate',
                                       value='https://st2.newmexicowaterdata.org/FROST-Server/v1.1')]),
                    dbc.Col([dbc.Input(id='n', value=10)])
                    ]
                    ),
            dbc.Row(dbc.Col([validate_btn_grp])),
            dbc.Row(dbc.Col([dt, loading]))
            ]

def do_layout():
    dash_app.layout = dbc.Container(layout_rows())
# ============= EOF =============================================


import sys
from pathlib import Path
from omegaconf import OmegaConf

from ..helpers.misc import mkdir
from ..errors import ConfigLoadError
from ..helpers.logger import log_to_stderr

config_dir = (Path.home() / ".config" / "bbot").resolve()
defaults_filename = (Path(__file__).parent.parent.parent / "defaults.yml").resolve()
mkdir(config_dir)
config_filename = (config_dir / "bbot.yml").resolve()
secrets_filename = (config_dir / "secrets.yml").resolve()
default_config = None

def _get_config(filename, name="config"):
    notify = False
    if sys.argv and sys.argv[0].endswith("bbot") and not any(x in sys.argv for x in ("-s", "--silent")):
        notify = True
    filename = Path(filename).resolve()
    try:
        conf = OmegaConf.load(str(filename))
        if notify:
            log_to_stderr(f"Loaded {name} from {filename}")
        return conf
    except Exception as e:
        if filename.exists():
            raise ConfigLoadError(f"Error parsing config at {filename}:\n\n{e}")
        return OmegaConf.create()

def get_config():
    global default_config
    default_config = _get_config(defaults_filename, name="defaults")
    return OmegaConf.merge(
        default_config,
        _get_config(config_filename, name="config"),
        _get_config(secrets_filename, name="secrets"),
    )


'''
Created on 2016. 1. 3.

@author: User
'''
value = int(input())
lower_boundary = int(input())
upper_boundary = int(input())
quality_of_low = str(input())
quality_of_high = str(input())
if value < lower_boundary and value <upper_boundary and lower_boundary < upper_boundary:
    if quality_of_low == 'cold':
        print('too cold')
    if quality_of_low == 'small':
        print('too small')
    if quality_of_low == 'acidic':
        print('too acidic')
if value > lower_boundary and value <upper_boundary and lower_boundary < upper_boundary:
    print('just right')
if value > lower_boundary and value > upper_boundary and lower_boundary < upper_boundary:
    if quality_of_high == 'hot':
        print('too hot')
    if quality_of_high == 'large':
        print('too large')
    if quality_of_high == 'basic':
        print('too basic')
if value == lower_boundary or value == upper_boundary:
    print('just right')


import os

def add_file(fileitem):
    try:
        filename = os.path.basename(fileitem.filename)
        filename = 'static/photo/'+filename
        open(filename, 'wb').write(fileitem.file.read())
    except:
        filename = "aaaaaaaaaaaaaNULL"
    finally:
        return filename[13:len(filename)]


import pandas as pd
import numpy as np
import numpy as geek

import statsmodels.api as sm
import statsmodels.formula.api as smf
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from functools import partial

from sklearn.model_selection import cross_val_score
from sklearn.model_selection import LeaveOneOut
from stargazer.stargazer import Stargazer, LineLocation
from IPython.core.display import HTML

import seaborn as sns
import matplotlib.pyplot as plt

from statsmodels.discrete.discrete_model import Probit

import warnings;
warnings.filterwarnings('ignore');

#from aux_functions import *

from auxiliary.aux_plots import *
from auxiliary.aux_predictions import *
from auxiliary.aux_tables import *

def get_data(sample_level, second_condition_school_info, add_controls, selected_y_var, selected_var):

    data = pd.read_stata('data/BRIGHT_Formatted.dta')
    data.fillna(np.nan, inplace = True)

    if second_condition_school_info == 0:

        if sample_level == 0:
            rslt_df = data.loc[data["child_level"] == 1]

        elif sample_level == 1:
            rslt_df = data.loc[data["village_level"] == 1]

        elif sample_level == 2:
            rslt_df = data.loc[data["school_level"] == 1]

    if second_condition_school_info == 1:

        if sample_level == 0:
            rslt_df = data.loc[data["child_level"] == 1]

        elif sample_level == 1:
            rslt_df = data.loc[data["village_level"] == 1]

        elif sample_level == 2:
            rslt_df = data.loc[data["school_level"] == 1]

        rslt_df = rslt_df.loc[rslt_df["Vill_HasSchoolInfo"] == 1]

    rslt_df = pd.get_dummies(rslt_df, columns = ["department"])
    filter_col = [col for col in rslt_df if col.startswith('department')]
    dummies = rslt_df[filter_col].drop(columns=['department_close', 'department_Bani'])
    controls = rslt_df[["Ch_Girl", "Ch_HeadChild", "Ch_HeadGrandChild", "Ch_HeadNephew", "age7_dummy", "age8_dummy",                             "age9_dummy", "age10_dummy", "age11_dummy", "age12_dummy", "Hh_NumMembers", "Hh_NumKids",
                        "Hh_HeadMale", "Hh_HeadAge", "Hh_HeadSchool", "Hh_ReligionMuslin", "Hh_Animist",
                        "Hh_Christian", "Hh_Lang_Fulfude", "Hh_Lang_Gulmachema", "Hh_Lang_Moore",
                        "Hh_Ethnicity_Gourmanche", "Hh_Ethnicity_Mossi", "Hh_Ethnicity_Peul", "Hh_FloorBasic",
                        "Hh_RoofBasic", "Hh_Radio", "Hh_Telmob", "Hh_Watch", "Hh_Bike", "Hh_Cows", "Hh_Motorbike",
                        "Hh_Cart"]]

    y = rslt_df[selected_y_var]
    y.reset_index(drop= True, inplace = True)
    X = rslt_df[selected_var]

    if add_controls == 0:

        X = pd.concat([X, dummies], axis = 1)
        X.reset_index(drop= True, inplace = True)
        X = sm.add_constant(X)

    if add_controls == 1:

        X = pd.concat([X, dummies, controls], axis = 1)
        X.reset_index(drop= True, inplace = True)
        X = sm.add_constant(X)

    return y,X

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

def calculate_polynomial_interaction(cluster_se, y_var, initial_data, interact_var1, interact_var2, degree):

    rel_score = np.array(initial_data["rel_score"])
    running_var = rel_score[:, np.newaxis]

    interaction_term = np.array(initial_data[interact_var1] * initial_data[interact_var2])
    interaction_term = interaction_term[:, np.newaxis]

    polynomial_features = PolynomialFeatures(degree=degree)
    rel_score_poly = polynomial_features.fit_transform(running_var)
    interaction_term_poly = polynomial_features.fit_transform(interaction_term)

    column_names_rel_score = ["rel_score" + str(x) for x in range(degree + 1)]
    column_names_interaction = ["interaction_term" + str(x) for x in range(degree + 1)]

    drop_columns = ["interaction_term0", "rel_score0", "rel_score", "clustercode"]

    rel_score_poly_df = pd.DataFrame(rel_score_poly, columns = column_names_rel_score)
    interaction_term_poly_df = pd.DataFrame(interaction_term_poly, columns = column_names_interaction)

    concated_df = pd.concat([rel_score_poly_df, interaction_term_poly_df,
                             initial_data], axis = 1).drop(drop_columns,axis = 1)

    if cluster_se == 0:

        mod_interaction_poly = sm.OLS(y_var,concated_df)
        result_interaction_poly = mod_interaction_poly.fit()

    elif cluster_se == 1:

        mod_interaction_poly = sm.OLS(y_var,concated_df)
        result_interaction_poly = mod_interaction_poly.fit(cov_type = 'cluster',
                                                           cov_kwds={'groups': initial_data["clustercode"]})
    #stargazer = Stargazer([result_interaction_poly])
    return result_interaction_poly

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

def calculate_probit(cluster_se, y_var, initial_data, degree):

    rel_score = np.array(initial_data["rel_score"])
    running_var = rel_score[:, np.newaxis]

    polynomial_features= PolynomialFeatures(degree=2)
    rel_score_poly = polynomial_features.fit_transform(running_var)

    column_names = []
    for poly_degree in range(rel_score_poly.shape[1]): #can leave this for loop in, or can replace w/ list comprehension
        column_names.append("rel_score" + str(poly_degree))

    drop_columns = ["rel_score", "rel_score0", "const", "clustercode"]

    rel_score_poly_df = pd.DataFrame(rel_score_poly, columns = column_names)
    concated_df = pd.concat([rel_score_poly_df, initial_data], axis = 1).drop(drop_columns, axis = 1)

    if cluster_se == 0:

        mod_probit = sm.Probit(y_var,concated_df)
        result_probit = mod_probit.fit()

    elif cluster_se == 1:

        mod_probit = sm.Probit(y_var,concated_df)
        result_probit = mod_probit.fit(cov_type = 'cluster', cov_kwds={'groups': initial_data["clustercode"]})

    #stargazer = Stargazer([result_probit])
    return result_probit

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

def calculate_reduced_range_40(cluster_se, y_var, initial_data):

    if cluster_se == 0:

        drop_columns = ["rel_score", "clustercode"]

        new_y_var = y_var.loc[abs(initial_data["rel_score"]) < .0040].reset_index(drop = True)
        new_X_matrix = initial_data.loc[abs(initial_data["rel_score"]) < .0040].drop(drop_columns,
                                                                                axis = 1).reset_index(drop = True)

        mod_reduced_range_40 = sm.OLS(new_y_var, new_X_matrix)
        result_reduced_range_40 = mod_reduced_range_40.fit()

    elif cluster_se == 1:

        drop_columns = ["rel_score"]

        new_y_var = y_var.loc[abs(initial_data["rel_score"]) < .0040].reset_index(drop = True)
        new_X_matrix = initial_data.loc[abs(initial_data["rel_score"]) < .0040].drop(drop_columns,
                                                                                axis = 1).reset_index(drop = True)
        clusters = new_X_matrix["clustercode"]
        new_X_matrix_dropped_clcode = new_X_matrix.drop("clustercode",axis = 1)

        mod_reduced_range_40 = sm.OLS(new_y_var, new_X_matrix_dropped_clcode)
        result_reduced_range_40 = mod_reduced_range_40.fit(cov_type = 'cluster', cov_kwds={'groups': clusters})

    #stargazer = Stargazer([result_reduced_range_40])
    return result_reduced_range_40

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

def regress_cluster_se_corrected(y_var, initial_data, degree):

    rel_score = np.array(initial_data["rel_score"])

    running_var = rel_score[:, np.newaxis]

    polynomial_features= PolynomialFeatures(degree=degree)
    rel_score_poly = polynomial_features.fit_transform(running_var)

    column_names = ["rel_score" + str(x) for x in range(degree + 1)]
    drop_columns = ["rel_score", "rel_score0"]

    rel_score_poly_df = pd.DataFrame(rel_score_poly, columns = column_names)
    concated_df = pd.concat([rel_score_poly_df, y_var, initial_data], axis = 1).drop(drop_columns ,axis = 1)

    dataset = concated_df.dropna()

    clusters = dataset["clustercode"]

    drop =  ["clustercode","Ch_Highest_Grade"]

    dataset_dropped_clcode = dataset.drop(drop, axis = 1)
    y_dropped_clcode = dataset["Ch_Highest_Grade"]

    mod_poly = sm.OLS(y_dropped_clcode, dataset_dropped_clcode)
    result_poly = mod_poly.fit(cov_type = 'cluster', cov_kwds={'groups': clusters})

    return result_poly

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

def regress_over_output(cluster_se, y, initial_data):

    if cluster_se == 0:

        model = sm.OLS(y, initial_data, missing='drop')
        res = model.fit()

    elif cluster_se == 1:
        drop_columns = "clustercode"
        X_matrix = initial_data.drop(drop_columns, axis = 1)

        model = sm.OLS(y, X_matrix, missing='drop')
        res = model.fit(cov_type = 'cluster', cov_kwds={'groups': initial_data["clustercode"]})

    #stargazer = Stargazer([res])
    return res

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

def regress_for_diff_outcomes_poly_features(y_df,dep_variables,X_df,degree,cluster_se):

    varying_depend_var = []

    for dep_var in dep_variables:
        models = calculate_polynomial_features(cluster_se, y_df[dep_var], X_df, degree)
        varying_depend_var.append(models)

    return varying_depend_var

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

def fit_poly_models_iterate(y_df, X_df, degree, cluster_se):

    fitted_poly_models = []

    for x in range(1, degree + 1):
        models = calculate_polynomial_features(cluster_se, y_df, X_df, x)
        fitted_poly_models.append(models)

    return fitted_poly_models

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

def compute_locally_weighted_reg(y_var,x_var,X,h,data):

    z_array = abs((data[x_var] - X)/h)

    kernels = []

    for z in z_array:

        if z <= 1:
            kz = (3/4)*(1 - z**2)/h
        else:
            kz = 0
        kernels.append(kz)

    kernels_array = np.array(kernels)

    weights = kernels_array**0.5

    y_predicted = (data[y_var])*weights
    const_predicted = weights
    x_predicted = (data[x_var] - X)*weights

    data["weights"] = weights
    data['y_predicted'] = y_predicted
    data['const_predicted'] = const_predicted

    data['x_predicted'] = x_predicted

    ols_output = smf.ols(formula = 'y_predicted ~ const_predicted + x_predicted - 1', data = data).fit()
    param = ols_output.params["const_predicted"]

    return param

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

def compute_binned_averages(treated, binned_variable,binsize,bins,data):

    store_xgrid = []
    store_averages =[]

    table = pd.DataFrame({'Xgrid': [],'Binned Averages': []})
    table['Index'] = list(range(bins))
    table = table.set_index('Index')

    if treated == 0:

        set_range = -1*np.array(range(0,250,binsize))

        for value in set_range:
            xgrid = value - binsize/2
            store_xgrid.append(xgrid)

        for value in set_range:
            subset = data[(data["rel_score_redefined"] < value) & (data["rel_score_redefined"] >= value - binsize)]
            means = subset[binned_variable].mean()
            store_averages.append(means)

    if treated == 1:

        set_range = list(range(0,250,binsize))

        for value in set_range:
            xgrid = value + binsize/2
            store_xgrid.append(xgrid)

        for value in set_range:
            subset = data[(data["rel_score_redefined"] > value) & (data["rel_score_redefined"] <= value + binsize)]
            means = subset[binned_variable].mean()
            store_averages.append(means)

    for x in range(bins):
            averages = store_averages
            xgrid = store_xgrid
            results = [xgrid[x],averages[x]]
            table.loc[x] = results
            table.reset_index(drop = True, inplace = True)

    return table

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

def test_placebo_discontinuity(y_placebo, X_placebo, treated_side, placebo_cutoff):

    if treated_side == 0:

        y_placebo_untreated = y_placebo.loc[X_placebo["rel_score"] < 0].reset_index(drop = True)
        X_placebo_untreated = X_placebo.loc[X_placebo["rel_score"] < 0].reset_index(drop = True)

        X_placebo_untreated["placebo_treatment_dummy"] = (X_placebo_untreated["rel_score"] >= placebo_cutoff).astype(int)
        clustercodes = X_placebo_untreated["clustercode"]

        X_placebo_untreated.drop(["proj_selected", "clustercode"], inplace = True, axis = 1)

        mod = sm.OLS(y_placebo_untreated,X_placebo_untreated, missing='drop')
        result = mod.fit(cov_type = 'cluster', cov_kwds={'groups': clustercodes})

    if treated_side == 1:
        y_placebo_treated = y_placebo.loc[X_placebo["rel_score"] >= 0].reset_index(drop = True)
        X_placebo_treated = X_placebo.loc[X_placebo["rel_score"] >= 0].reset_index(drop = True)

        X_placebo_treated["placebo_treatment_dummy"] = (X_placebo_treated["rel_score"] >= placebo_cutoff).astype(int)
        clustercodes = X_placebo_treated["clustercode"]

        X_placebo_treated.drop(["proj_selected", "clustercode"], inplace = True, axis = 1)

        mod = sm.OLS(y_placebo_treated,X_placebo_treated, missing='drop')
        result = mod.fit(cov_type = 'cluster', cov_kwds={'groups': clustercodes})

    return result

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

def iterate_placebo_test(y_var, X_matrix, treated_side):

    treatment_coeffs = []
    pvalues = []
    CI_lower = []
    CI_upper = []

    table = pd.DataFrame({'Placebo Cutoff': [],'Coefficient Estimate': [],'Coefficient Estimate': [],'P-value': [], 'Conf. Int. Lower': [], 'Conf. Int. Upper': []})
    table['Index'] = list(range(4))
    table = table.set_index('Index')

    if treated_side == 0:

        placebo_cutoffs = [-0.0125, -0.00625, -0.003125, -0.0015625]

        for cutoff in placebo_cutoffs:

            summary = test_placebo_discontinuity(y_var, X_matrix, 0, cutoff)

            treatment_coeffs.append(summary.params["placebo_treatment_dummy"])
            pvalues.append(summary.pvalues["placebo_treatment_dummy"])
            CI_lower.append(summary.conf_int(alpha=0.05, cols=None).loc["placebo_treatment_dummy",:][0])
            CI_upper.append(summary.conf_int(alpha=0.05, cols=None).loc["placebo_treatment_dummy",:][1])

    if treated_side == 1:

        placebo_cutoffs = [0.0125, 0.00625, 0.003125, 0.0015625]

        for cutoff in placebo_cutoffs:

            summary = test_placebo_discontinuity(y_var, X_matrix, 1, cutoff)

            treatment_coeffs.append(summary.params["placebo_treatment_dummy"])
            pvalues.append(summary.pvalues["placebo_treatment_dummy"])
            CI_lower.append(summary.conf_int(alpha=0.05, cols=None).loc["placebo_treatment_dummy",:][0])
            CI_upper.append(summary.conf_int(alpha=0.05, cols=None).loc["placebo_treatment_dummy",:][1])

    for x in range(4):
        results = [placebo_cutoffs[x]*10000, treatment_coeffs[x], pvalues[x], CI_lower[x], CI_upper[x]]
        table.loc[x] = results

    return table

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

def check_effect_bandwidth(y, X, attending):

    if attending == 0:

        rslts = pd.DataFrame(columns=["Treatment Effect, std", "P-value"])
        rslts.index.set_names("Bandwidth", inplace=True)

        for h in [1, 0.0400,0.0300, 0.0250, 0.01875, 0.0125,
                  0.003125, 0.0015625, 0.0010, 0.0005]:

            y_limited = y[X["rel_score"].between(-h, h)].reset_index(drop = True)
            X_limited = X[X["rel_score"].between(-h, h)].reset_index(drop = True)

            output = calculate_polynomial_interaction(1,y_limited, X_limited, "proj_selected","rel_score",1)

            info = [output.params[3], round(output.pvalues[3],3)]

            rslts.loc[h*10000] = info

    elif attending == 1:

        rslts = pd.DataFrame(columns=["Treatment Effect, %", "P-value"])
        rslts.index.set_names("Bandwidth", inplace=True)

        for h in [1, 0.0400,0.0300, 0.0250, 0.01875, 0.0125,
                  0.003125, 0.0015625, 0.0010, 0.0005]:

            y_limited = y[X["rel_score"].between(-h, h)].reset_index(drop = True)
            X_limited = X[X["rel_score"].between(-h, h)].reset_index(drop = True)

            output = calculate_polynomial_interaction(1,y_limited, X_limited, "proj_selected","rel_score",1)

            info = [output.params[3] * 100, round(output.pvalues[3],3)]

            rslts.loc[h*10000] = info

    return rslts

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

def create_bandwidth_check(y_bndwd, X_bndwd, bandwidth):

    scoring = "neg_mean_squared_error"
    model = LinearRegression()
    cv = LeaveOneOut()

    cross_val_score_p = partial(cross_val_score, scoring=scoring, cv=cv)

    rslts = pd.DataFrame(columns=["below", "above", "joint"])
    rslts.index.set_names("Bandwidth", inplace=True)

    for label in ["below", "above"]:
        for h in bandwidth:

            if label == "below":
                df_subset_y = y_bndwd.loc[X_bndwd["rel_score"].between(-h, +0.00)].reset_index(drop = True)
                df_subset_X = X_bndwd.loc[X_bndwd["rel_score"].between(-h, +0.00)].reset_index(drop = True)
            else:
                df_subset_y = y_bndwd.loc[X_bndwd["rel_score"].between(+0.00, +h)].reset_index(drop = True)
                df_subset_X = X_bndwd.loc[X_bndwd["rel_score"].between(+0.00, +h)].reset_index(drop = True)

            y = df_subset_y
            X = df_subset_X.drop(["const"], axis = 1)

            rslts.loc[h*10000, label] = -cross_val_score_p(model, X, y).mean()
            rslts["joint"] = rslts[["below", "above"]].mean(axis=1)

    return rslts

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

def compute_est_effect_separate(y_df, X_df, dep_var,attending):

    y_untreated = y_df.loc[X_df["rel_score"] < 0].reset_index(drop = True)
    X_untreated = X_df.loc[X_df["rel_score"] < 0].reset_index(drop = True).drop("proj_selected", axis = 1)
    y_treated = y_df.loc[X_df["rel_score"] >= 0].reset_index(drop = True)
    X_treated = X_df.loc[X_df["rel_score"] >= 0].reset_index(drop = True).drop("proj_selected", axis = 1)

    model_untreated = calculate_polynomial_features(1, y_untreated[dep_var], X_untreated, 2)
    model_treated = calculate_polynomial_features(1, y_treated[dep_var], X_treated, 2)

    dep_proportion = X_df.iloc[:,4:50].mean()
    dep_coeff_untreated = model_untreated.params[3:49]
    dep_coeff_treated = model_treated.params[3:49]

    const_untreated = model_untreated.params["const"] + np.dot(dep_proportion,dep_coeff_untreated)
    const_treated = model_treated.params["const"] + np.dot(dep_proportion,dep_coeff_treated)

    if attending == 0:

        est_effect = (const_treated - const_untreated)

        print(f'The measured effect on normalized total test scores for separately plotted control and treatment regressions is {est_effect:.4f} standard deviations.')

    if attending == 1:

        est_effect = (const_treated - const_untreated) * 100

        print(f'The measured effect on attendance for separately plotted control and treatment regressions is {est_effect:.4f}%.')


#Manuel Ortiz Hernández at 2020
#Python Problems. Extracted from: https://www.hackerrank.com/challenges/python-lists/problem
def readData():
	N = int(input())
	list_to_modify = []
	for _ in range(N):
		commands = {}
		function, *line = input().split()
		numbers = list(map(str, line))
		commands[function] = numbers
		detCmds(commands, list_to_modify)

	return commands

def detCmds(commands, list_to_modify):
	for function, numbers in commands.items():
		if function == "print":
			print(list_to_modify)
		else:
			function += "(" + ",".join(numbers) + ")"
			eval("list_to_modify."+function)

def main():
	readData()

if __name__ == '__main__':
	main()


from __future__ import print_function
from pprint import pprint
import markdown
import json
import csv
import sys

sys.path.append("../")
sys.path.append("../youtube_series_mp3/")

import series_to_mp3 as sm

def jdump(val):
    """Turns json object into pretty-formated string."""
    return json.dumps(val, sort_keys=True, indent=4, separators=(',', ': '))

def jp(val):
    """Prints out pretty-formated string of object."""
    print(jdump(val))

def is_valid_char(char):
    """Checks if a character is valid in a video/playlist id."""
    inc_range = lambda start, end: range(start, end+1)
    if (ord(char) in inc_range(48, 57) or
        ord(char) in inc_range(65, 90) or
        ord(char) in inc_range(97, 122) or char == '_' or char == '-'):
        return True
    return False

def extract_id(vurl, splt_str, template):
    """Extracts the video/playlist id, and applies it to given template."""
    yt_id = ''
    for char in vurl.split(splt_str)[1]:
        if is_valid_char(char):
            yt_id += char
        else:
            break
    template = template.format(yt_id)
    return yt_id, template

def parse_playlist_url(vurl):
    """Given the url to a playlist, extract it's id and create embed."""
    template = ''
    return extract_id(vurl, 'list=', template)

def parse_video_url(vurl):
    """Given the url to a video, extract it's id and create embed."""
    template = ''
    return extract_id(vurl, 'v=', template)

class YoutubeVid(object):
    """Handles creating youtube embed videos"""
    def __init__(self, vurl):
        # super(YoutubeVid, self).__init__()
        self.vurl = vurl

        if 'list' in vurl:
            self.yt_id, self.embed = parse_playlist_url(self.vurl)
        else:
            self.yt_id, self.embed = parse_video_url(self.vurl)

    def __repr__(self):
        """Returns string representation of a youtube video."""
        return '
<img src="{}" alt="Link to YouTube video"
'.format(self.vurl)

import urllib2
import socket
import time
def get_youtube_thumbnail(playlist_url):
    host = socket.gethostbyname('youtube.com')
    playlist_url = playlist_url.replace('www.youtube.com', 'youtube.com')
    url = playlist_url.replace('youtube.com', host)
    print(url)
    # time.sleep(5)
    r = urllib2.urlopen(url).read()
    r = r.decode('UTF-8')
    r = r.encode('ascii', 'replace')
    r = r.split('pl-header-thumb')[1]
    r = r.split('<a')[0]
    r = r.split('//')[1]
    r = r.split('jpg')[0]
    r = "http://"+r+"jpg"
    return r

def youtube_embed(vurl):
    image_url = get_youtube_thumbnail(vurl)
    rv = '

'
    rv = rv.format(vurl, image_url)
    return rv

def csv_dict_reader(f_obj, delim='\t'):
    """Function will read our tsv/csv file into a list of dictionaries."""
    reader = csv.DictReader(f_obj, delimiter=delim)
    to_return = []
    for line in reader:
        to_return.append(line)
    return to_return

def load_csv(fname='names.tsv'):
    """Loads csv into list of dicts."""
    if not fname:
        if len(sys.argv) > 1:
            fname = sys.argv[1]

    with open(fname) as f_obj:
        series_info = csv_dict_reader(f_obj)

    return series_info

def build_page():
    """Builds the html page of series information."""
    series_info = load_csv()

    for item in series_info:
        item['markdown'] = sm.build_markdown(\
            item['series_alias'], item['series_full_name'])
        item['markdown'] += youtube_embed(item['youtube_url'])

    page = u'''<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Game Grump - Audio Edition!</title>

Game Grumps as Audiobooks/Podcasts

Ever wanted to be able to listen to the humor and fun of Game Grumps while out and about? Now you can! This page links to mp3 versions of your favorite Game Grumps series, all free!

You can download a series as a zip file containing each episode's audio, or you can download all the episodes of that series as one giant mp3 for continuous listening!

    {}
'''

    page = page.format(
        ''.join([markdown.markdown(s['markdown']) for s in series_info]))
    return page.encode('utf-8')

if __name__ == '__main__':
    build_page()
    # print(build_page())


import math
import chainer
import chainer.functions as F
import chainer.links as L
import cv2
import cupy as cp
import numpy as np

from chainer import Variable

class deathcheck(chainer.FunctionSet):

    def __init__(self):
        w = math.sqrt(2)  # MSRA scaling
        super(resnet, self).__init__(
            fc1=F.Linear(3*98*30,10000),
            fc2=F.Linear(10000,10000),
            fc3=F.Linear(10000,2),
        )

    def forward(self, x_data, y_data, train=True):
        x = chainer.Variable(x_data, volatile=not train)
        t = chainer.Variable(y_data, volatile=not train)

        h = F.relu(F.dropout(self.fc1(x),train=train))
        h = F.relu(F.dropout(self.fc2(h),train=train))
        h = F.relu(self.fc3(h))

        return F.softmax_cross_entropy(h, t), F.accuracy(h, t)

    def predict(self, x_data, train=True):
        x = chainer.Variable(x_data, volatile=not train)

        h = F.relu(F.dropout(self.fc1(x),train=train))
        h = F.relu(F.dropout(self.fc2(h),train=train))
        h = F.relu(self.fc3(h))

        return F.softmax(h)


from django.urls import path
import businesses.views as views

urlpatterns = [
    path('', views.BusinessIndex.as_view(), name="businesses-home"),
    path('detail/<int:pk>/', views.BusinessDetailView.as_view(), name="business-detail"),
    path('cart/add/', views.cart_add, name="cart-add"),
    path('cart/remove/', views.cart_remove, name="cart-remove"),
    path('cart/create/', views.business_delivery, name="cart-create"),
    path('cart/quote/', views.retail_quote, name="retail-quote"),
    path('payment/add/', views.payment_method, name="card-payment")
]


"""
utils
*****

Tests for src/utilities
"""

import unittest

from mtfit.utilities.unittest_utils import run_tests as _run_tests
from mtfit.utilities.unittest_utils import debug_tests as _debug_tests
from mtfit.tests.unit.utilities.test_unittest_utils import test_suite as unittest_utils_test_suite
from mtfit.tests.unit.utilities.test_argparser import test_suite as argparser_test_suite
from mtfit.tests.unit.utilities.test_file_io import test_suite as file_io_test_suite
from mtfit.tests.unit.utilities.test_multiprocessing_helper import test_suite as multiprocessing_helper_test_suite
from mtfit.tests.unit.utilities.test_extensions import test_suite as extensions_test_suite

__all__ = ['run_tests']

def test_suite(verbosity=2):
    return unittest.TestSuite([argparser_test_suite(verbosity),
                               extensions_test_suite(verbosity),
                               file_io_test_suite(verbosity),
                               multiprocessing_helper_test_suite(verbosity)
                               ])

def run_tests(verbosity=2):
    """Run the modules unit tests"""
    spacer = "----------------------------------------------------------------------"
    if verbosity > 1:
        print('Running utilities/unittest_utils.py Tests')
        print(spacer)
        test_result = _run_tests(unittest_utils_test_suite(verbosity), verbosity)
        print('\n'+spacer)
        print('Running utilities/argparser.py Tests')
        print(spacer)
        test_result = _run_tests(argparser_test_suite(verbosity), verbosity, test_result=test_result)
        print('\n'+spacer)
        print('Running utilities/exception_handler.py Tests')
        print(spacer)
        test_result = _run_tests(extensions_test_suite(verbosity), verbosity, test_result=test_result)
        print('\n'+spacer)
        print('Running utilities/file_io.py Tests')
        print(spacer)
        test_result = _run_tests(file_io_test_suite(verbosity), verbosity, test_result=test_result)
        print('\n'+spacer)
        print('Running utilities/multiprocessing_helper.py Tests')
        print(spacer)
        test_result = _run_tests(multiprocessing_helper_test_suite(verbosity), verbosity, test_result=test_result)
    else:
        print('Running unit tests')
        print(spacer)
        test_result = _run_tests(test_suite(verbosity), verbosity)
    return test_result

def debug_tests(verbosity=2):
    """Runs tests with debugging on errors"""
    _debug_tests(test_suite(verbosity))

if __name__ == "__main__":
    run_tests(1)


from django.conf.urls import url, include
from basicapp import views

# TEMPLATE URLS!
app_name = 'basicapp'

urlpatterns = [
    url('^register/', views.register, name='register'),
    url('^user_login/', views.user_login, name='user_login'),
]


from ahocorapy.keywordtree import KeywordTree
import pyautogui
from hud.core import getLeftSidebarArrows
import utils.core
import utils.image

chatMenuImg = utils.image.loadAsGrey('chat/images/chatMenu.png')
chatOnImg = utils.image.loadAsGrey('chat/images/chatOn.png')
chatOnImgTemp = utils.image.loadAsGrey('chat/images/chatOnTemp.png')
chatOffImg = utils.image.loadAsGrey('chat/images/chatOff.png')
chatOffImg = utils.image.loadAsGrey('chat/images/chatOff.png')
lootOfTextImg = utils.image.loadAsGrey('chat/images/lootOfText.png')
nothingTextImg = utils.image.loadAsGrey('chat/images/nothingText.png')
lootImg = utils.image.loadAsGrey('chat/images/loot.png')
oldListOfLootCheck = []

def readMessagesFromActiveChatTab(screenshot):
    (x, y, width, height) = getChatMessagesContainerPos(screenshot)
    chatMessagesContainer = utils.image.crop(screenshot, x, y, width, height)
    chatMessagesContainer = utils.image.convertGraysToBlack(
        chatMessagesContainer)
    messages = utils.image.toString(chatMessagesContainer, "6").splitlines()
    messages = list(filter(None, messages))
    return messages

def hasNewLoot(screenshot):
    global oldListOfLootCheck
    lootLines = getLootLines(screenshot)
    if len(lootLines) == 0:
        return False
    listOfLootCheck = []
    start = 5
    if len(lootLines) - 5 <= 0:
        start = len(lootLines)
    for i in range(len(lootLines) - start, len(lootLines)):
        listOfLootCheck.append(utils.core.hashit(
            utils.image.convertGraysToBlack(lootLines[i][0])))
    if len(listOfLootCheck) != 0 and len(oldListOfLootCheck) == 0:
        oldListOfLootCheck = listOfLootCheck
        return True
    for newLootLine in listOfLootCheck:
        if newLootLine not in oldListOfLootCheck:
            oldListOfLootCheck = listOfLootCheck
            return True
    oldListOfLootCheck = listOfLootCheck
    return False

def getLootLines(screenshot):
    (x, y, w, h) = getChatMessagesContainerPos(screenshot)
    messages = screenshot[y: y + h, x: x + w]
    lootLines = utils.core.locateMultiple(lootOfTextImg, messages)
    linesWithLoot = []
    for line in lootLines:
        line = x, line[1] + y, w, line[3]
        lineImg = screenshot[line[1]:line[1] +
                             line[3], line[0]:line[0] + line[2]]
        nothingFound = utils.core.locate(nothingTextImg, lineImg)
        if nothingFound is None:
            linesWithLoot.append((lineImg, line))
    return linesWithLoot

def searchInActiveChatTab(activeChatText, patterns):
    kwtree = KeywordTree(case_insensitive=True)
    for i in range(len(patterns)):
        kwtree.add(patterns[i])
    kwtree.finalize()

    processedChatText = []
    for i in range(len(activeChatText)):
        results = kwtree.search_all(activeChatText[i])
        if len(patterns) == len(list(results)):
            processedChatText.append(activeChatText[i])
    return processedChatText

@utils.core.cacheObjectPos
def getChatMenuPos(screenshot):
    return utils.core.locate(screenshot, chatMenuImg)

@utils.core.cacheObjectPos
def getChatOffPos(screenshot):
    return utils.core.locate(screenshot, chatOffImg, confidence=0.985)

def getChatStatus(screenshot):
    chatOffPos = getChatOffPos(screenshot)
    if chatOffPos:
        return chatOffPos, False
    chatOnPos = utils.core.locate(screenshot, chatOnImgTemp, confidence=0.9)
    return chatOnPos, True

def enableChatOn(screenshot):
    (_, chatIsOn) = getChatStatus(screenshot)
    chatIsNotOn = chatIsOn is False
    if chatIsNotOn:
        utils.core.press('enter')

def enableChatOff(screenshot):
    (_, chatIsOn) = getChatStatus(screenshot)
    if chatIsOn:
        utils.core.press('enter')

def getChatsTabs(screenshot):
    leftSidebarArrows = getLeftSidebarArrows(screenshot)
    chatMenu = getChatMenuPos(screenshot)
    return leftSidebarArrows[0] + 10, chatMenu[1], chatMenu[0] - (leftSidebarArrows[0] + 10), 20

def getChatMessagesContainerPos(screenshot):
    leftSidebarArrows = getLeftSidebarArrows(screenshot)
    chatMenu = getChatMenuPos(screenshot)
    chatStatus = getChatStatus(screenshot)
    return leftSidebarArrows[0], chatMenu[1] + 18, chatStatus[0][0] + 40, (chatStatus[0][1] - 6) - (chatMenu[1] + 13)

def getLootTabPos(screenshot):
    return utils.core.locate(screenshot, lootImg)

def selectLootTab(screenshot):
    clickCoord = getLootTabPos(screenshot)
    clickCoord = utils.core.randomCoord(
        clickCoord[0], clickCoord[1], clickCoord[2], clickCoord[3])
    pyautogui.click(clickCoord[0], clickCoord[1])

def sendMessage(screenshot, phrase):
    enableChatOn(screenshot)
    utils.core.typeKeyboard(phrase)


#
# @lc app=leetcode id=653 lang=python3
#
# [653] Two Sum IV - Input is a BST
#
# https://leetcode.com/problems/two-sum-iv-input-is-a-bst/description/
#
# algorithms
# Easy (53.69%)
# Likes:    1142
# Dislikes: 123
# Total Accepted:    116.9K
# Total Submissions: 215.7K
# Testcase Example:  '[5,3,6,2,4,null,7]\n9'
#
# Given a Binary Search Tree and a target number, return true if there exist
# two elements in the BST such that their sum is equal to the given target.
#
# Example 1:
#
#
# Input:
#    5
#   / \
#  3   6
# / \   \
# 2   4   7
#
# Target = 9
#
# Output: True
#
#
#
#
# Example 2:
#
#
# Input:
#    5
#   / \
#  3   6
# / \   \
# 2   4   7
#
# Target = 28
#
# Output: False
#
#
#
#
#

# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def findTarget(self, root: TreeNode, k: int) -> bool:
        if not root:
            return False
        nlst = [root]
        vlst = []
        while nlst:
            if k-nlst[0].val in vlst:
                return True
            vlst.append(nlst[0].val)
            if nlst[0].left:
                nlst.append(nlst[0].left)
            if nlst[0].right:
                nlst.append(nlst[0].right)
            nlst.pop(0)
        return False

# @lc code=end


import os
# import nose
# from nose.tools import *
import logging
import shutil
LD = logging.Logger('root')
LD.setLevel(logging.INFO)
LD.addHandler(logging.StreamHandler())

class TestPlawLen(object):
    @classmethod
    def setup_class(cls):
        num = 0
        with open("data/plaws.csv", 'rb') as source:
            for bill_num in enumerate(source):
                num = bill_num[0]
            source.close()
            cls.lenplaw = num
        msg = "# plaws found: %s"%cls.lenplaw
        LD.info(msg)
        msg = "# plaws expected: 10861"
        LD.info(msg)
    def test_plawlen(self):
        assert abs(self.lenplaw - 10861) < 2, "Downloaded files not within 20 of sampled public laws"
        msg = "negligable diff of: %s"%abs(self.lenplaw - 10861)
        LD.info(msg)

class TestLen(object):
    @classmethod
    def setup_class(cls):
        cls.files = [os.path.join(paths[0], j) for paths in os.walk('.') \
        for j in     paths[2] if j.endswith("json")]
        cls.lenfiles = len(cls.files)
        num = 0
        with open("data/plaws.csv", 'rb') as source:
            for bill_num in enumerate(source):
                num = bill_num[0]
            source.close()
            cls.lenplaw = num
        msg = "# plaws selected: %s"%cls.lenplaw
        LD.info(msg)
        msg = "# of bills processed %s"%cls.lenfiles
        LD.info(msg)
    def test_close(self):
        assert abs(self.lenfiles-self.lenplaw) < 3, "Downloaded files not within 2 of sampled public laws"


Import('mainEnv')

libLocalBuildEnv = mainEnv.Clone()
localBuildEnv = mainEnv.Clone()

lib_target = 'perfremote'
lib_sources = [
               'monitor.cc',
	      ]

perfRemoteLibrary = libLocalBuildEnv.SharedLibrary(target = lib_target, source = lib_sources)

# Be careful with linkage order for static libraries
localBuildEnv.Append(LIBS = perfRemoteLibrary)
localBuildEnv.Program('perfremote', ['main.cc'])

Return('perfRemoteLibrary')


class SteamAccountType(object):
	Invalid             =  0
	Individual          =  1
	Multiseat           =  2
	GameServer          =  3
	AnonymousGameServer =  4
	Pending             =  5
	ContentServer       =  6
	Clan                =  7
	Chat                =  8
	ClanChat            =  8
	LobbyChat           =  8
	P2PSuperSeeder      =  9
	AnonymousUser       = 10

	DefaultInstanceIds  = {}
	DefaultInstanceIds[Invalid]             = 0
	DefaultInstanceIds[Individual]          = 1
	DefaultInstanceIds[Multiseat]           = 0
	DefaultInstanceIds[GameServer]          = 1
	DefaultInstanceIds[AnonymousGameServer] = 0
	DefaultInstanceIds[Pending]             = 0
	DefaultInstanceIds[ContentServer]       = 0
	DefaultInstanceIds[Clan]                = 0
	DefaultInstanceIds[Chat]                = 0
	DefaultInstanceIds[ClanChat]            = 0x00080000
	DefaultInstanceIds[LobbyChat]           = 0x00040000
	DefaultInstanceIds[P2PSuperSeeder]      = 0
	DefaultInstanceIds[AnonymousUser]       = 0
	DefaultInstanceIds["c"]                 = 0x00080000
	DefaultInstanceIds["L"]                 = 0x00040000

	Characters  = {}
	Characters[Invalid]             = "I"
	Characters[Individual]          = "U"
	Characters[Multiseat]           = "M"
	Characters[GameServer]          = "G"
	Characters[AnonymousGameServer] = "A"
	Characters[Pending]             = "P"
	Characters[ContentServer]       = "C"
	Characters[Clan]                = "g"
	Characters[Chat]                = "T"
	Characters[ClanChat]            = "c"
	Characters[LobbyChat]           = "L"
	Characters[AnonymousUser]       = "a"

	CharacterAccountTypes = {}
	CharacterAccountTypes["I"] = Invalid
	CharacterAccountTypes["U"] = Individual
	CharacterAccountTypes["M"] = Multiseat
	CharacterAccountTypes["G"] = GameServer
	CharacterAccountTypes["A"] = AnonymousGameServer
	CharacterAccountTypes["P"] = Pending
	CharacterAccountTypes["C"] = ContentServer
	CharacterAccountTypes["g"] = Clan
	CharacterAccountTypes["T"] = Chat
	CharacterAccountTypes["c"] = ClanChat
	CharacterAccountTypes["L"] = LobbyChat
	CharacterAccountTypes["a"] = AnonymousUser

	@classmethod
	def defaultInstanceId(cls, x):
		if x in cls.DefaultInstanceIds: return cls.DefaultInstanceIds[x]
		return cls.DefaultInstanceIds.get(cls.CharacterAccountTypes.get(x))

	@classmethod
	def fromCharacter(cls, c):
		return cls.CharacterAccountTypes.get(c)

	@classmethod
	def toCharacter(cls, accountType):
		return cls.Characters.get(accountType)


from functools import reduce

l=[range(100,1001)[i] for i in range(len(range(100,1001))) if range(100,1001)[i]%2==0]
print(f"Полученный список: {l} \n")

print(f"Результат через reduce: {reduce(lambda x, y: x*y, l)}\n")

def multiply(lst):
    answer = 1
    for i in lst:
        answer *= i
    return answer

print(f"Результат через функцию: {multiply(l)}")


# Standard library imports
import csv
import json
from pathlib import Path
from typing import Dict, List, Tuple
# Third party imports
import pandas as pd
import pymongo
from pymongo import MongoClient
from sklearn.model_selection import train_test_split, KFold
from sklearn.tree import DecisionTreeClassifier
# Local imports
from utils import diff_cols, grid_search, prepare_dataset, pymongo_loads

# File definitions
csv_src = Path("/import/SpeedDatingData.csv")

# Preprocessing inputs
query_cols = {
    "iid": 1,
    "pid": 1,
    "age": 1,
    "age_o": 1,
    "dec": 1,
    "dec_o": 1,
    "attr": 1,
    "attr_o": 1,
    "sinc": 1,
    "sinc_o": 1,
    "intel": 1,
    "intel_o": 1,
    "fun": 1,
    "fun_o": 1,
    "amb": 1,
    "amb_o": 1,
    "shar": 1,
    "shar_o": 1,
    "match": 1,
}
diff_cols_ = ["age", "dec", "attr", "sinc", "intel", "fun", "amb", "shar"]
y_cols = ["match"]

# model inputs
test_size = 0.2
random_state = 777
max_depths = [1, 2, 3, 4, 5, 6, 7, 8]

if __name__ == "__main__":
    print(80 * "~")
    print(f"Load data from {csv_src}")
    collection = pymongo_loads(csv_src, "speeddating", "events")

    print(80 * "~")
    print(f"Prepare data for classifier")
    df = prepare_dataset(collection, query_cols, diff_cols_)

    print(80 * "~")
    print("Split into test and train sets")
    X_tr, X_te, y_tr, y_te = train_test_split(df.drop(axis=1, labels=y_cols), df[y_cols[0]], random_state=random_state, test_size=test_size)

    print(80 * "~")
    print("Conduct cross validation")
    validation_scores, validation_summary = grid_search(X_tr, y_tr, max_depths)
    print("Cross validation results")
    print(validation_summary)

    print(80 * "~")
    print("Select best max depth")
    best_max_depth = validation_summary.index.values[validation_summary["acc_val"].argmax()]
    print(f"Best max depth={best_max_depth}")

    print(80 * "~")
    print("Train model on training data using best max depth")
    best_model = DecisionTreeClassifier(max_depth=best_max_depth)
    best_model.fit(X_tr, y_tr)

    print(80 * "~")
    print("Score model on test data")
    acc_te = round(best_model.score(X_te, y_te), 2)
    print(f"Test accuracy={acc_te}")

    print(80 * "~")
    feature_importances = pd.Series(best_model.feature_importances_, index=list(X_tr)).sort_values(ascending=False)
    print(f"Feature importances:\n{feature_importances}")


import random
from torchvision import datasets, transforms
from torch.utils.data import DataLoader, Dataset

class Sharding(Dataset):
    """A sharding of a dataset"""

    def __init__(self, data, index):
        self.data = data
        self.index = index

    def __len__(self):
        return len(self.index)

    def __getitem__(self, index):
        data_idx = self.index[index]
        return self.data[data_idx]

class DatasetCreator(object):
    """Dataset creator loads and divides dataset"""

    def __init__(self, num_clients, dataset_name, partition_method, seed=5):
        random.seed(seed)  # fix seed for reproduction
        self.n_clients = num_clients
        self.dt_name = dataset_name
        self.pt_method = partition_method
        self.shardings = []
        self.training_data, self.test_data = self.__get_dataset()
        self.__divide_dataset()

    def get_loader(self, client_id=0, batch_sz=32, is_test=False, pin_memory=True, time_out=0, num_workers=0):
        """Get DataLoader object."""
        if not is_test:
            drop_last = shuffle = True
            sharding = Sharding(self.training_data, self.shardings[client_id])
            loader = DataLoader(sharding, batch_sz, shuffle=shuffle, pin_memory=pin_memory, timeout=time_out,
                                num_workers=num_workers, drop_last=drop_last)
        else:
            index = [_ for _ in range(len(self.test_data))]
            non_sharding = Sharding(self.test_data, index)
            loader = DataLoader(non_sharding, batch_sz, shuffle=False, pin_memory=pin_memory, timeout=time_out,
                                num_workers=num_workers, drop_last=False)
        return loader

    def get_training_data_len(self, client_id=0):
        return len(self.shardings[client_id])

    def get_test_data_len(self):
        return len(self.test_data)

    def __divide_dataset(self):
        if self.pt_method == 'uniform':
            data_len = len(self.training_data)
            train_indexes = list(range(data_len))

            random.shuffle(train_indexes)

            part_len = int(1. / self.n_clients * len(train_indexes))

            for _ in range(self.n_clients):
                self.shardings.append(train_indexes[0:part_len])
                train_indexes = train_indexes[part_len:]

    def __get_dataset(self):
        training_dataset = test_dataset = None
        training_transform, test_transform = self.__get_transform()

        if self.dt_name == 'CIFAR10':
            training_dataset = datasets.CIFAR10(
                root='data/CIFAR10',
                train=True,
                download=True,
                transform=training_transform
            )
            test_dataset = datasets.CIFAR10(
                root='data/CIFAR10',
                train=False,
                download=True,
                transform=test_transform
            )

        return training_dataset, test_dataset

    def __get_transform(self):
        if self.dt_name == 'CIFAR10':
            transform_train = transforms.Compose([
                transforms.RandomCrop(32, padding=4),
                transforms.RandomHorizontalFlip(),
                transforms.ToTensor(),
                transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
            ])

            transform_test = transforms.Compose([
                transforms.ToTensor(),
                transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
            ])

        return transform_train, transform_test


from tethys_apps.base import TethysAppBase, url_map_maker
from tethys_apps.base import PersistentStore

class TsConverter(TethysAppBase):
    """
    Tethys app class for ts converter.
    """

    name = 'HydroScripteR'
    index = 'ts_converter:home'
    icon = 'ts_converter/images/hydro.gif'
    package = 'ts_converter'
    root_url = 'ts_converter'
    color = '#f1c40f'

    def url_maps(self):
        """
        Add controllers
        """
        UrlMap = url_map_maker(self.root_url)

        url_maps = (UrlMap(name='home',
                           url='ts_converter/',
                           controller='ts_converter.controllers.home'),

                    UrlMap(name='View_R_Code',
                           url='View_R_Code',
                           controller='ts_converter.controllers.View_R_Code'),

                    UrlMap(name='temp_waterml',
                           url='temp_waterml/{folder}/{id}',
                           controller='ts_converter.controllers.temp_waterml'),

                    UrlMap(name='delete-file',
                           url='ts_converter/delete-file',
                           controller='ts_converter.controllers.delete_file')
        )

        return url_maps

    def persistent_stores(self):
        """
        Add one or more persistent stores
        """
        stores = (PersistentStore(name='urls_db',
                                  initializer='init_stores:init_urls_db',
                                  spatial=False),

                  PersistentStore(name='rscript_db',
                                  initializer='init_stores:init_rscript_db',
                                  spatial=False
                                                )
        )

        return stores


from numpy import size
import pygame
from sqlalchemy import null
from randomTerrain import GetTerrain
import sys
from DataStructures import *
from pprint import pprint
from random import randrange

SAND = "#117c13"
WALL = "#000000"
WATER = "#d4f1f9"
MUD = "#70543e"

def DrawTerrain(surface,reference,blockSize):

    """
    Usa a informacao que esta na matriz terreno e os limites setados pelo usuario para gerar
    uma representacao visual do mapa.
    """

    offset = blockSize//2
    for rowIndex,row in enumerate(reference):
        for colIndex,value in enumerate(row):
            x = colIndex * blockSize +offset
            y = rowIndex * blockSize +offset

            color = "#ff0000"

            if(value == "water" ):
                color = WATER

            elif(value == "mud" ):
                color = MUD

            elif(value == "sand" ):
                color = SAND

            elif(value == "wall"):
                color = WALL

            elif(value == "food"):
                color = "red"

            elif(value == "start"):
                color="white"

            image = pygame.Surface((blockSize,blockSize))
            image.fill(color)
            rect = image.get_rect(topleft = (x,y))
            surface.blit(image,rect)

def Neighbor(terrain,pos):
    y,x = pos[0],pos[1]

    sizeY = len(terrain)
    sizeX = len(terrain[0])

    neighbors= []

    if(x-1>=0):
        neighbors.append((y,x-1))
    if(y+1<sizeY):
        neighbors.append((y+1,x))
    if(x+1<sizeX):
        neighbors.append((y,x+1))
    if(y-1>=0):
        neighbors.append((y-1,x))

    neighbors = list(filter(lambda item: terrain[item[0]][item[1]]!="wall",neighbors))
    return neighbors

def BreathFirstSearch(terrain,start,end):
    states = {}

    #possible status: undiscovered, discovered, visited

    for rowIndex,row in enumerate(terrain):
        for colIndex,item in enumerate(row):
            if item == "wall":
                continue
            states[f"{(rowIndex,colIndex)}"] = {"status":"undiscovered","distance":null,"previous":null}

    done = False
    current = start
    states[str(current)]["status"] = "discovered"
    states[str(current)]["distance"] = 0
    queue = Queue()
    while(not done):
        neighbors = Neighbor(terrain,current)
        done = True

        for node in neighbors:
            if states[str(node)]["status"]=="undiscovered":
                done = False
                states[str(node)]["status"]="discovered"
                states[str(node)]["distance"]=states[str(current)]["distance"]+1
                states[str(node)]["previous"] = current
                queue.Enqueue(node)

        states[str(current)]["status"] = "visited"

        if done and queue.Empty():
            continue

        done = False
        current = queue.Dequeue()

    #translates the states dict to a list of positions to the food
    current = end
    path = deque()
    while(current!=start):
        if current == null:
            path = deque()
            break
        path.appendleft(current)
        current = states[str(current)]["previous"]

    path.appendleft(start)
    return path

def DepthFirstSearch(terrain,start,end):
    states = {}

    #possible status: undiscovered, discovered, visited

    for rowIndex,row in enumerate(terrain):
        for colIndex,item in enumerate(row):
            if item == "wall":
                continue
            states[f"{(rowIndex,colIndex)}"] = {"status":"undiscovered","distance":null,"previous":null}

    done = False
    current = start
    states[str(current)]["status"] = "discovered"
    states[str(current)]["distance"] = 0
    stack = Stack()
    while(not done):
        neighbors = Neighbor(terrain,current)
        done = True

        for node in neighbors:
            if states[str(node)]["status"]=="undiscovered":
                done = False
                states[str(node)]["status"]="discovered"
                states[str(node)]["distance"]=states[str(current)]["distance"]+1
                states[str(node)]["previous"] = current
                stack.Push(node)

        states[str(current)]["status"] = "visited"

        if done and stack.Empty():
            continue

        done = False
        current = stack.Pop()

    #translates the states dict to a list of positions to the food
    current = end
    path = deque()
    while(current!=start):
        if current == null:
            path = deque()
            break
        path.appendleft(current)
        current = states[str(current)]["previous"]

    path.appendleft(start)
    return path

def DrawPath(surface,path,blockSize,color="red"):

    coords = [ ((x+1)*blockSize ,(y+1)*blockSize) for y,x in path]

    pygame.draw.lines(surface,color,False,coords)

def RandomPos(terrain,dimX,dimY):
    x,y = randrange(dimX),randrange(dimY)
    while(terrain[y][x]=="wall" or len(Neighbor(terrain,(y,x)))<1):
        x,y = randrange(dimX),randrange(dimY)

    return (y,x)

if __name__=="__main__":

    dimX, dimY = 100,100
    blockSize = 7

    terrain = GetTerrain(dimX,dimY)

    foodPos= RandomPos(terrain,dimX,dimY)
    startPos= RandomPos(terrain,dimX,dimY)

    terrain[startPos[0]][startPos[1]] = "start"
    terrain[foodPos[0]][foodPos[1]] = "food"

    #path1 = DepthFirstSearch(terrain,startPos,foodPos)
    path2 = BreathFirstSearch(terrain,startPos,foodPos)

    #pygame stuff

    width = (dimX+1)*(blockSize)
    height = (dimY+1)*(blockSize)

    pygame.init()
    win = pygame.display.set_mode((width,height))
    clock= pygame.time.Clock()

    DrawTerrain(win,terrain,blockSize)

    while(True):

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

        win.fill((30,30,30))
        DrawTerrain(win,terrain,blockSize)
        if len(path2)>1:
            DrawPath(win,path2,blockSize,color="blue")
        # if len(path1)>1:
        #     DrawPath(win,path1,blockSize)
        pygame.display.flip()
        clock.tick(60)


from tkinter import *
from PIL import ImageTk,Image

root = Tk()
root.title("Learn to Code at Codemy.com")
root.iconbitmap('C:/Users/User/Desktop/CAMEO_Register/CAMEO_Register/favicon.ico')

#r = IntVar()
#r.set("2")

TOPPINGS = [
	("Pepperoni", "Pepperoni"),
	("Cheese", "Cheese"),
	("Mushrooms", "Mushrooms"),
	("Onion", "Onion"),
]

pizza = StringVar()
#pizza.set("Choose your toppings")

for text, topping in TOPPINGS:
	Radiobutton(root, text=text, variable=pizza, value=topping).pack(anchor=W)

def clicked(value):
	myLabel = Label(root, text=value)
	myLabel.pack()

#Radiobutton(root, text="Option 1", variable=r, value=1, command=lambda: clicked(r.get())).pack()
#Radiobutton(root, text="Option 2", variable=r, value=2, command=lambda: clicked(r.get())).pack()

#myLabel = Label(root, text=pizza.get())
#yLabel.pack()

myButton = Button(root, text="Add Toppings", command=lambda: clicked(pizza.get()))
myButton.pack()
root.mainloop()