from collections import Counter

class Card:
    ranks = "23456789TJQKA"

    def __init__(self, s):
        self.printable_rank = s[0]
        self.rank = self.ranks.find(s[0])
        self.suit = s[1]

class Hand:
    rules = [
        # Royal flush is special case of straight flush
        {'desc': "Straight Flush", 'straight': True, 'flush': True, 'n0': 1, 'n1': 1},
        {'desc': "Four of a Kind", 'straight': False, 'flush': False, 'n0': 4, 'n1': 1},
        {'desc': "Full House", 'straight': False, 'flush': False, 'n0': 3, 'n1': 2},
        {'desc': "Flush", 'straight': False, 'flush': True, 'n0': 1, 'n1': 1},
        {'desc': "Straight", 'straight': True, 'flush': False, 'n0': 1, 'n1': 1},
        {'desc': "Three of a Kind", 'straight': False, 'flush': False, 'n0': 3, 'n1': 1},
        {'desc': "Two Pair", 'straight': False, 'flush': False, 'n0': 2, 'n1': 2},
        {'desc': "One Pair", 'straight': False, 'flush': False, 'n0': 2, 'n1': 1},
        {'desc': "High Card", 'straight': False, 'flush': False, 'n0': 1, 'n1': 1},
    ]

    def __init__(self, s):
        self.cards = [Card(c) for c in s.split(" ")]
        self.cards.sort(key = lambda card: card.rank)

        flush = all(self.cards[i].suit == self.cards[i+1].suit for i in range(0,4))
        straight = all(self.cards[i].rank + 1 == self.cards[i+1].rank for i in range(0,4))
        counter = Counter(card.rank for card in self.cards)
        n_of_a_kind = counter.most_common(2)

        for i in range(len(self.rules)):
            rule = self.rules[i]
            if (rule['flush'] == flush
                    and rule['straight'] == straight
                    and rule['n0'] == n_of_a_kind[0][1]
                    and rule['n1'] == n_of_a_kind[1][1]):
                self.hand_strength = 9 - i
                if rule['n0'] >= 2:
                    # tiebreaker for n of a kind is rank of the pair/3/4
                    if rule['n1'] == 2: # special case for two pair - make sure you get the higher pair
                        self.type_rank = max(n_of_a_kind[0][0], n_of_a_kind[1][0])
                    else:
                        self.type_rank = n_of_a_kind[0][0]
                else:
                    # tiebreaker for others is the high card
                    self.type_rank = self.cards[4].rank

                break

    def comparison_tuple(self):
        return (self.hand_strength, self.type_rank) + tuple(card.rank for card in self.cards[::-1])

    def __lt__(self, other):
        return self.comparison_tuple() < other.comparison_tuple()

    def __str__(self):
        return "%s %d" % (self.hand_strength, self.type_rank)

def gen():
    f = open("p054_poker.txt")
    for line in f:
        hand1 = Hand(line[0:14])
        hand2 = Hand(line[15:])
        yield (hand1, hand2)

print(sum(1 for (hand1, hand2) in gen() if hand1 > hand2))


import random
from collections import defaultdict, deque

freqs = dict()

class IntComputer(object):
    def __init__(self, filepath, base = 0, value = []):
        self.program = self.decode(filepath)
        self.pos = 0
        self.input = value
        self.base = base
        self.done = False

    def decode(self, filepath):
        with open(filepath, "r") as f:
            data = list(map(int, f.readline().split(',')))

        d = defaultdict(lambda: 0)
        for i in range(len(data)):
            d[i] = data[i]
        return d

    def set_input(self, value):
        self.input = deque(value)

    def is_done(self):
        return self.done

    def get_var(self, var, mode):
        if (mode == 0):
            return self.program[var]
        elif(mode == 2):
            return self.program[var+self.base]
        return var

    def set_result(self, parameter, mode, value):
        if(mode == 2):
            var = self.base + parameter
        else:
            var = parameter
        self.program[var] = value

    def run(self):

        while(self.program[self.pos] != 99):
            command = self.program[self.pos]
            instruction = command % 100
            command = command // 100
            mode1 = command % 10
            command = command // 10
            mode2 = command % 10
            command = command // 10
            mode3 = command % 10

            n_instructions = 0
            if(instruction == 1):
                var1 = self.get_var(self.program[self.pos+1], mode1)
                var2 = self.get_var(self.program[self.pos+2], mode2)
                self.set_result(self.program[self.pos+3], mode3, var1 + var2)
                n_instructions = 4
            elif(instruction == 2):
                var1 = self.get_var(self.program[self.pos+1], mode1)
                var2 = self.get_var(self.program[self.pos+2], mode2)
                self.set_result(self.program[self.pos+3], mode3, var1 * var2)
                n_instructions = 4
            elif(instruction == 3):
                #input
                if(len(self.input) == 0):
                    value = input()
                    for char in value:
                        self.input.append(ord(char))
                    self.input.append(10)
                self.set_result(self.program[self.pos+1], mode1, self.input[0])
                self.input = self.input[1:]
                n_instructions = 2
            elif(instruction == 4):
                var1 = self.get_var(self.program[self.pos+1], mode1)
                n_instructions = 2
                self.pos += n_instructions
                return var1
            elif(instruction == 5):
                var1 = self.get_var(self.program[self.pos+1], mode1)
                var2 = self.get_var(self.program[self.pos+2], mode2)
                if (var1 != 0):
                    self.pos = var2
                else:
                    n_instructions = 3
            elif(instruction == 6):
                var1 = self.get_var(self.program[self.pos+1], mode1)
                var2 = self.get_var(self.program[self.pos+2], mode2)
                if (var1 == 0):
                    self.pos = var2
                else:
                    n_instructions = 3
            elif(instruction == 7):
                var1 = self.get_var(self.program[self.pos+1], mode1)
                var2 = self.get_var(self.program[self.pos+2], mode2)
                if(var1 < var2):
                    result = 1
                else:
                    result = 0
                self.set_result(self.program[self.pos+3], mode3, result)
                n_instructions = 4
            elif(instruction == 8):
                var1 = self.get_var(self.program[self.pos+1], mode1)
                var2 = self.get_var(self.program[self.pos+2], mode2)
                if(var1 == var2):
                    result = 1
                else:
                    result = 0
                self.set_result(self.program[self.pos+3], mode3, result)
                n_instructions = 4
            elif(instruction == 9):
                var1 = self.get_var(self.program[self.pos+1], mode1)
                self.base += var1
                n_instructions = 2

            self.pos += n_instructions
        self.done = True

def run():
    program = '''north
take sand
north
take space heater
east
take semiconductor
west
south
south
east
take ornament
south
take festive hat
east
take asterisk
south
east
take cake
west
west
take food ration
east
north
west
north
west
west
north
north
west
west
drop cake
drop asterisk
drop sand
drop food ration
west\n'''
    start(program)

def start(program):
    routine = []
    for char in program:
        routine.append(ord(char))
    computer = IntComputer("input/day25.data", value=routine)

    while(not computer.is_done()):
        out = computer.run()
        if(out):
            print(chr(out), end='')

if __name__ == "__main__":
    run()


class Solution:
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        m = nums[0]
        maxTail = []
        maxTail.append(nums[0])
        for i in range(1,len(nums)):
            maxTail.append(max(nums[i],maxTail[i-1]+nums[i]))
            m = max(maxTail[i],m)
        return m


#! /usr/bin/env python
# -*- coding: utf-8 -*-

from django.contrib.auth.decorators import login_required
from django.db import transaction
from django.db.models.query_utils import Q
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response

from store.forms import ClienteForm
from store.functions import model_to_dict_safe, bad_json, url_back, mensaje_excepcion, MiPaginador, salva_auditoria, \
    ok_json
from store.models import Cliente
from store.values import ACCION_ADICIONAR, ACCION_MODIFICAR, ACCION_ELIMINAR
from store.views import addUserData

@login_required(redirect_field_name='ret', login_url='/login')
def view(request):
    ex = None
    data = {'title': 'Customers'}
    addUserData(request, data)
    if request.method == 'POST':
        action = request.POST['action']
        if action == 'add':
            f = ClienteForm(request.POST)
            if f.is_valid():
                try:
                    with transaction.atomic():
                        ruc = f.cleaned_data['ruc']
                        if not Cliente.objects.filter(ruc=ruc).exists():
                            cliente = Cliente(ruc=f.cleaned_data['ruc'],
                                              nombre=f.cleaned_data['nombre'],
                                              direccion=f.cleaned_data['direccion'],
                                              email=f.cleaned_data['email'],
                                              telefono=f.cleaned_data['telefono'])
                            cliente.save()
                            salva_auditoria(request, cliente, ACCION_ADICIONAR)
                            return ok_json()
                        else:
                            return bad_json(mensaje='Identification already exists')
                except Exception:
                    return bad_json(error=1)
            else:
                return bad_json(error=1)

        elif action == 'edit':
            cliente = Cliente.objects.get(pk=request.POST['id'])
            f = ClienteForm(request.POST)
            if f.is_valid():
                try:
                    with transaction.atomic():
                        ruc = f.cleaned_data['ruc']
                        if not Cliente.objects.filter(ruc=ruc).exclude(id=cliente.id).exists():
                            cliente.ruc = f.cleaned_data['ruc']
                            cliente.nombre = f.cleaned_data['nombre']
                            cliente.direccion = f.cleaned_data['direccion']
                            cliente.email = f.cleaned_data['email']
                            cliente.telefono = f.cleaned_data['telefono']
                            cliente.save()
                            salva_auditoria(request, cliente, ACCION_MODIFICAR)
                            return ok_json()
                        else:
                            return bad_json(mensaje='Identification already exists')
                except Exception:
                    return bad_json(error=2)
            else:
                return bad_json(error=2)

        elif action == 'delete':
            try:
                with transaction.atomic():
                    cliente = Cliente.objects.get(pk=request.POST['id'])
                    salva_auditoria(request, cliente, ACCION_ELIMINAR)
                    cliente.delete()
                    return ok_json()
            except Exception:
                return bad_json(error=3)

        return bad_json(error=0)
    else:
        if 'action' in request.GET:
            action = request.GET['action']
            if action == 'add':
                try:
                    data['title'] = 'Add Customer'
                    data['form'] = ClienteForm()
                    return render_to_response("clientes/add.html", data)
                except Exception as ex:
                    pass

            elif action == 'edit':
                try:
                    data['title'] = 'Edit Customer'
                    data['cliente'] = cliente = Cliente.objects.get(pk=request.GET['id'])
                    initial = model_to_dict_safe(cliente)
                    data['form'] = ClienteForm(initial=initial)
                    return render_to_response("clientes/edit.html", data)
                except Exception as ex:
                    pass

            elif action == 'delete':
                try:
                    data['title'] = 'Delete Customer'
                    data['cliente'] = Cliente.objects.get(pk=request.GET['id'])
                    return render_to_response("clientes/delete.html", data)
                except Exception as ex:
                    pass

            return HttpResponseRedirect(url_back(request, mensaje_excepcion(ex.args[0])))
        else:
            search = None

            if 's' in request.GET:
                search = request.GET['s']
            if search:
                clientes = Cliente.objects.filter(Q(nombre__icontains=search) | Q(identificacion__icontains=search))
            else:
                clientes = Cliente.objects.all()

            paging = MiPaginador(clientes, 25)
            p = 1
            try:
                if 'page' in request.GET:
                    p = int(request.GET['page'])
                page = paging.page(p)
            except:
                page = paging.page(1)
            data['paging'] = paging
            data['rangospaging'] = paging.rangos_paginado(p)
            data['page'] = page
            data['search'] = search if search else ""
            data['clientes'] = page.object_list
            return render_to_response("clientes/clientes.html", data)


from django.urls import path
from django.views.generic import RedirectView

from evap.staff import views

app_name = "staff"

urlpatterns = [
    path("", views.index, name="index"),

    path("semester/", RedirectView.as_view(url='/staff/', permanent=True)),
    path("semester/create", views.SemesterCreateView.as_view(), name="semester_create"),
    path("semester/<int:semester_id>", views.semester_view, name="semester_view"),
    path("semester/<int:semester_id>/edit", views.SemesterEditView.as_view(), name="semester_edit"),
    path("semester/make_active", views.semester_make_active, name="semester_make_active"),
    path("semester/delete", views.semester_delete, name="semester_delete"),
    path("semester/<int:semester_id>/import", views.semester_import, name="semester_import"),
    path("semester/<int:semester_id>/export", views.semester_export, name="semester_export"),
    path("semester/<int:semester_id>/raw_export", views.semester_raw_export, name="semester_raw_export"),
    path("semester/<int:semester_id>/participation_export", views.semester_participation_export, name="semester_participation_export"),
    path("semester/<int:semester_id>/vote_timestamps_export", views.vote_timestamps_export, name="vote_timestamps_export"),
    path("semester/<int:semester_id>/assign", views.semester_questionnaire_assign, name="semester_questionnaire_assign"),
    path("semester/<int:semester_id>/preparation_reminder", views.semester_preparation_reminder, name="semester_preparation_reminder"),
    path("semester/<int:semester_id>/grade_reminder", views.semester_grade_reminder, name="semester_grade_reminder"),
    path("semester/<int:semester_id>/responsible/<int:responsible_id>/send_reminder", views.send_reminder, name="send_reminder"),
    path("semester/archive_participations", views.semester_archive_participations, name="semester_archive_participations"),
    path("semester/archive_results", views.semester_archive_results, name="semester_archive_results"),
    path("semester/delete_grade_documents", views.semester_delete_grade_documents, name="semester_delete_grade_documents"),

    path("semester/<int:semester_id>/evaluation/create", views.evaluation_create_for_semester, name="evaluation_create_for_semester"),
    path("course/<int:course_id>/evaluation/create", views.evaluation_create_for_course, name="evaluation_create_for_course"),
    path("evaluation/delete", views.evaluation_delete, name="evaluation_delete"),
    path("evaluation/<int:evaluation_id>/edit", views.evaluation_edit, name="evaluation_edit"),
    path("evaluation/<int:evaluation_id>/copy", views.evaluation_copy, name="evaluation_copy"),
    path("evaluation/<int:evaluation_id>/email", views.evaluation_email, name="evaluation_email"),
    path("evaluation/<int:evaluation_id>/preview", views.evaluation_preview, name="evaluation_preview"),
    path("evaluation/<int:evaluation_id>/person_management", views.evaluation_person_management, name="evaluation_person_management"),
    path("evaluation/<int:evaluation_id>/login_key_export", views.evaluation_login_key_export, name="evaluation_login_key_export"),
    path("semester/<int:semester_id>/evaluation/operation", views.evaluation_operation, name="evaluation_operation"),

    path("semester/<int:semester_id>/course/create", views.course_create, name="course_create"),
    path("course/delete", views.course_delete, name="course_delete"),
    path("course/<int:course_id>/edit", views.CourseEditView.as_view(), name="course_edit"),
    path("course/<int:course_id>/copy", views.course_copy, name="course_copy"),

    path("semester/<int:semester_id>/singleresult/create", views.single_result_create_for_semester, name="single_result_create_for_semester"),
    path("course/<int:course_id>/singleresult/create", views.single_result_create_for_course, name="single_result_create_for_course"),

    path("evaluation/<int:evaluation_id>/textanswers", views.evaluation_textanswers, name="evaluation_textanswers"),
    path("semester/<int:semester_id>/flagged_textanswers", views.semester_flagged_textanswers, name="semester_flagged_textanswers"),
    path("textanswer/<uuid:textanswer_id>/edit", views.evaluation_textanswer_edit, name="evaluation_textanswer_edit"),
    path("textanswers/update_publish", views.evaluation_textanswers_update_publish, name="evaluation_textanswers_update_publish"),
    path("textanswers/update_flag", views.evaluation_textanswers_update_flag, name="evaluation_textanswers_update_flag"),
    path("textanswers/skip", views.evaluation_textanswers_skip, name="evaluation_textanswers_skip"),

    path("questionnaire/", views.questionnaire_index, name="questionnaire_index"),
    path("questionnaire/create", views.questionnaire_create, name="questionnaire_create"),
    path("questionnaire/<int:questionnaire_id>", views.questionnaire_view, name="questionnaire_view"),
    path("questionnaire/<int:questionnaire_id>/edit", views.questionnaire_edit, name="questionnaire_edit"),
    path("questionnaire/<int:questionnaire_id>/new_version", views.questionnaire_new_version, name="questionnaire_new_version"),
    path("questionnaire/<int:questionnaire_id>/copy", views.questionnaire_copy, name="questionnaire_copy"),
    path("questionnaire/delete", views.questionnaire_delete, name="questionnaire_delete"),
    path("questionnaire/update_indices", views.questionnaire_update_indices, name="questionnaire_update_indices"),
    path("questionnaire/questionnaire_visibility", views.questionnaire_visibility, name="questionnaire_visibility"),
    path("questionnaire/questionnaire_set_locked", views.questionnaire_set_locked, name="questionnaire_set_locked"),

    path("degrees/", views.DegreeIndexView.as_view(), name="degree_index"),

    path("course_types/", views.CourseTypeIndexView.as_view(), name="course_type_index"),
    path("course_types/merge", views.course_type_merge_selection, name="course_type_merge_selection"),
    path("course_types/<int:main_type_id>/merge/<int:other_type_id>", views.course_type_merge, name="course_type_merge"),

    path("user/", views.user_index, name="user_index"),
    path("user/create", views.UserCreateView.as_view(), name="user_create"),
    path("user/import", views.user_import, name="user_import"),
    path("user/<int:user_id>/edit", views.user_edit, name="user_edit"),
    path("user/list", views.user_list, name="user_list"),
    path("user/delete", views.user_delete, name="user_delete"),
    path("user/resend_email", views.user_resend_email, name="user_resend_email"),
    path("user/bulk_update", views.user_bulk_update, name="user_bulk_update"),
    path("user/merge", views.UserMergeSelectionView.as_view(), name="user_merge_selection"),
    path("user/<int:main_user_id>/merge/<int:other_user_id>", views.user_merge, name="user_merge"),

    path("template/", RedirectView.as_view(url='/staff/', permanent=True)),
    path("template/<int:template_id>", views.TemplateEditView.as_view(), name="template_edit"),

    path("text_answer_warnings/", views.text_answer_warnings_index, name="text_answer_warnings"),

    path("faq/", views.FaqIndexView.as_view(), name="faq_index"),
    path("faq/<int:section_id>", views.faq_section, name="faq_section"),

    path("infotexts/", views.InfotextsView.as_view(), name="infotexts"),

    path("download_sample_file/<str:filename>", views.download_sample_file, name="download_sample_file"),

    path("export_contributor_results/<int:contributor_id>", views.export_contributor_results_view, name="export_contributor_results"),

    path("enter_staff_mode", views.enter_staff_mode, name="enter_staff_mode"),
    path("exit_staff_mode", views.exit_staff_mode, name="exit_staff_mode"),
]


import numpy as np

'''
Authors: Noemie Jaquier and Leonel Rozo, 2019
License: MIT
Contact: noemie.jaquier@idiap.ch, leonel.rozo@de.bosch.com
'''

def expmap(u, x0):
    """
    This function maps a vector u lying on the tangent space of x0 into the manifold.

    Parameters
    ----------
    :param u: vector in the tangent space
    :param x0: basis point of the tangent space

    Returns
    -------
    :return: point on the manifold
    """
    if np.ndim(x0) < 2:
        x0 = x0[:, None]

    if np.ndim(u) < 2:
        u = u[:, None]

    norm_u = np.sqrt(np.sum(u*u, axis=0))
    x = x0 * np.cos(norm_u) + u * np.sin(norm_u)/norm_u

    x[:, norm_u < 1e-16] = x0

    return x

def logmap(x, x0):
    """
    This functions maps a point lying on the manifold into the tangent space of a second point of the manifold.

    Parameters
    ----------
    :param x: point on the manifold
    :param x0: basis point of the tangent space where x will be mapped

    Returns
    -------
    :return: vector in the tangent space of x0
    """
    if np.ndim(x0) < 2:
        x0 = x0[:, None]

    if np.ndim(x) < 2:
        x = x[:, None]

    theta = np.arccos(np.dot(x0.T, x))
    u = (x - x0 * np.cos(theta)) * theta/np.sin(theta)

    u[:, theta[0] < 1e-16] = np.zeros((u.shape[0], 1))

    return u

def sphere_distance(x, y):
    """
    This function computes the Riemannian distance between two points on the manifold.

    Parameters
    ----------
    :param x: point on the manifold
    :param y: point on the manifold

    Returns
    -------
    :return: manifold distance between x and y
    """
    if np.ndim(x) < 2:
        x = x[:, None]

    if np.ndim(y) < 2:
        y = y[:, None]

    # Compute the inner product (should be [-1,1])
    inner_product = np.dot(x.T, y)
    inner_product = max(min(inner_product, 1), -1)
    return np.arccos(inner_product)

def parallel_transport_operator(x1, x2):
    """
    This function compute the parallel transport operator from x1 to x2. Transported vectors can be computed as u.dot(v)

    Parameters
    ----------
    :param x1: point on the manifold
    :param x2: point on the manifold

    Returns
    -------
    :return: parallel transport operator
    """
    if np.sum(x1-x2) == 0.:
        return np.eye(x1.shape[0])
    else:
        if np.ndim(x1) < 2:
            x1 = x1[:, None]

        if np.ndim(x2) < 2:
            x2 = x2[:, None]

        x_dir = logmap(x2, x1)
        norm_x_dir = np.sqrt(np.sum(x_dir*x_dir, axis=0))
        normalized_x_dir = x_dir / norm_x_dir
        u = np.dot(-x1 * np.sin(norm_x_dir), normalized_x_dir.T) \
            + np.dot(normalized_x_dir * np.cos(norm_x_dir), normalized_x_dir.T) \
            + np.eye(x_dir.shape[0]) - np.dot(normalized_x_dir, normalized_x_dir.T)

        return u

def karcher_mean_sphere(data, nb_iter=10):
    """
    This function computes the mean of points lying on the manifold (Fréchet/Karcher mean).

    Parameters
    ----------
    :param data: data points lying on the manifold

    Optional parameters
    -------------------
    :param nb_iter: number of iterations

    Returns
    -------
    :return: mean of the datapoints
    """
    # Initialize the mean as equal to the first datapoint
    m = data[:, 0]
    for i in range(nb_iter):
        data_tgt = logmap(data, m)
        m_tgt = np.mean(data_tgt, axis=1)
        m = expmap(m_tgt, m)

    return m

def in_domain(domain, x):
    """
    Check if x is in domain

    Parameters
    ----------
    :param domain: (gpflowopt) domain
    :param x: data

    Returns
    -------
    :return: True is x is in domain, False otherwise
    """
    return x in domain

def project_to_domain(domain, x0):
    x = np.copy(x0)
    indices = np.arange(x.shape[0])
    indices_to_ignore = []

    # Check if bound-constraints are respected for each dimension and change the value of the indices that do not
    for d in range(x.shape[0]):
        if x[d] < domain.lower[d]:
            x[d] = domain.lower[d]
            indices_to_ignore.append(d)
        elif x[d] > domain.upper[d]:
            x[d] = domain.upper[d]
            indices_to_ignore.append(d)

    # Adapt remaining indices to have a point on the unit sphere
    indices_to_change = list(set(indices) - set(indices_to_ignore))
    x[indices_to_change] = x[indices_to_change] / np.linalg.norm(x[indices_to_change]) \
                           * np.sqrt((1-np.sum(x[indices_to_ignore]**2)))

    # Check if changed indices respect the bound constraints
    in_domain = 0
    # ! If the constraints are not feasible, we may stay stucked here.
    while in_domain is 0:
        in_domain = 1
        # If not change the value of the indices that are out of the bound
        for d in indices_to_change:
            if x[d] < domain.lower[d]:
                x[d] = domain.lower[d]
                indices_to_ignore.append(d)
                in_domain *= 0
            elif x[d] > domain.upper[d]:
                x[d] = domain.upper[d]
                indices_to_ignore.append(d)
                in_domain *= 0

        # Adapt remaining indices to have a point on the unit sphere
        indices_to_change = list(set(indices) - set(indices_to_ignore))
        x[indices_to_change] = x[indices_to_change] / np.linalg.norm(x[indices_to_change]) \
                               * np.sqrt((1 - np.sum(x[indices_to_ignore] ** 2)))

    return x

# OLD FUNCTION (not robust)
# def project_to_domain(domain, x, nelems=100):
#     """
#     Project a point on the sphere to a domain contained in the manifold.
#
#     Parameters
#     ----------
#     :param domain: (gpflowopt) domain
#     :param x: datapoint
#
#     Optional parameters
#     -------------------
#     :param nelems: number of elements for "linesearch"
#
#     Returns
#     -------
#     :return: project point
#     """
#
#     factors = np.linspace(0, 1, nelems)
#     for d in range(x.shape[0]):
#         if x[d] < domain.lower[d]:
#             pole = np.zeros(x.shape)
#             pole[d] = 1.
#             dir_geodesic = logmap(pole, x)
#             # dir_geodesic = self.log(x, pole)
#             for i in range(nelems):
#                 newx = expmap(factors[i] * dir_geodesic, x)
#                 # newx = self.exp(x, factors[i] * dir_geodesic)
#                 if newx[d] > domain.lower[d]:
#                     x = newx
#                     break
#         elif x[d] > domain.upper[d]:
#             pole = np.zeros(x.shape)
#             pole[d] = -1.
#             dir_geodesic = logmap(pole, x)
#             # dir_geodesic = self.log(x, pole)
#             for i in range(nelems):
#                 newx = expmap(factors[i] * dir_geodesic, x)
#                 if newx[d] < domain.upper[d]:
#                     x = newx
#                     break
#     return x[:, 0]

def get_axisangle(d):
    """
    Gets axis-angle representation of a point lying on the sphere
    Based on the function of riepybdlib (https://gitlab.martijnzeestraten.nl/martijn/riepybdlib)

    Parameters
    ----------
    :param d: point on the sphere

    Returns
    -------
    :return: axis, angle: corresponding axis and angle representation
    """
    norm = np.sqrt(d[0]**2 + d[1]**2)
    if norm < 1e-6:
        return np.array([0,0,1]), 0
    else:
        vec = np.array( [-d[1], d[0], 0])
        return vec/norm,np.arccos(d[2])


# import sys
# sys.stdin = open('요리사.txt','r')
# N개의 식재료가 있다.
# N/2개씩 나누어 두 개의 요리를 한다.
# A음식과 B음식 맛의 차이가 최소가 되도록 재료를 배분
# 식재로 i,j는 시너지 Sij가 발생
# 음식의 맛은 시너지들의 합

# 식재료의 수 N은 4이상 16이하의 짝수
# 시너지 Sij는 1이상 20000이하의 정수
def nCr(n, ans, r):
    if n == len(arr):
        if len(ans) == r:
            temp = [i for i in ans]
            A = 0
            for i in range(len(temp)):
                for j in range(i,len(temp)):
                    A += Sij[temp[i]][temp[j]] + Sij[temp[j]][temp[i]]
            comb.append(A)
        return
    ans.append(arr[n])
    nCr(n + 1, ans, r)
    ans.pop()
    nCr(n + 1, ans, r)

# 테스트 케이스 T
T = int(input())
for tc in range(1,T+1):
    # 식재료의 수 N
    N = int(input())
    Sij = [list(map(int,input().split())) for _ in range(N)]
    arr = [_ for _ in range(0,N)]
    comb = []
    nCr(0,[],N/2)
    minV = 0xffffff
    for i in range(len(comb)):
        value = abs(comb[i]-comb[len(comb)-1-i])
        if minV > value:
            minV = value
    print(f'#{tc} {minV}')


import os, time

# Get the name of a non-directory subfile under a certain path
def get_file_name(file_dir):
     for root, dirs, files in os. walk(file_dir):

         return files # Return the names of all non-directory subfiles under the directory

# Determine whether the file is an apk file
def is_apk_file(file_name):
     res = True
     if file_name.find(".") != -1:
         if file_name.split(".")[1] == "apk":
             res = True
         else:
             res=False
     else:
         res = False

     return res

# Get the channel information value on the apk file name (generally multiple channels are packaged, and the file name will have channel value information). Since the naming method of each development may be different, you can write the relevant code yourself. This code is only applicable to The file is named as an apk file in the following format xx-channel value-xxx.apk
def get_file_name_channel_value(file_dir):
     files_name = get_file_name(file_dir)
     files_name_channel_value = {}
     for i in files_name:
         i_is_apk_file = is_apk_file(i)
         if i_is_apk_file:
             file_name_channel_value = i.split("-")[1]
             files_name_channel_value.update({i: file_name_channel_value})
     return files_name_channel_value

# Execute the apktool.bat file through the cmd command to decompile the apk file and obtain the channel value in the AndroidManifest.xml file
def get_apk_channel_value(src_file_dir):
     src_files = get_file_name(src_file_dir) # Get all files, excluding folders, excluding paths

     # Create a target folder path >>>> for storing the files obtained in the operation
     dest_file_dir = src_file_dir + "\packagefile\\"
     is_existed = os.path.exists(dest_file_dir)
     if not is_existed:
         os.mkdir(src_file_dir + "\packagefile")
     else:
         print("error: {} directory already exists".format(dest_file_dir))

     apk_channel_value = {}
     for file_name in src_files:
         file_name_is_apk_file_name = is_apk_file(file_name)
         if file_name_is_apk_file_name: # Filter out apk files
             # Decompile the apk file to the specified file path through the cmd command apktool.bat d apk file path -o decompiled file storage path
             dest_file_path = dest_file_dir + file_name.split(".")[0].replace("signed_zipalign", "unsigned")
             full_file_path = os.path.join(src_file_dir, file_name) # Get all file paths
             unsign_cmd = "apktool.bat d -f " + full_file_path + " -o " + dest_file_path
             res = os. popen(unsign_cmd)

             time. sleep(20)
             unsigned_AndroidManifest_path = dest_file_path + "\AndroidManifest.xml"
             with open(unsigned_AndroidManifest_path, "r", encoding="utf-8") as f:
                 for line in f. readlines():
                     if line.find("UMENG_CHANNEL") != -1:
                         content_res = line.split('=')[-1].split('"')[1]
                         apk_channel_value.update({file_name: content_res})
             time. sleep(20)

     return apk_channel_value

if __name__ == '__main__':
     apk_file_dir_path = "D:\app_apk"
     re = get_file_name_channel_value(apk_file_dir_path)
     print("The apk file in the {} directory and the channel value of the corresponding file name: {}".format(apk_file_dir_path, re))

     re1 = get_apk_channel_value(apk_file_dir_path)
     print("The channel value corresponding to the apk package in the {} directory is: {}".format(apk_file_dir_path, re1))

     if re == re1:
         print("Package channel and package file name channel value are the same")
     else:
         print("Package channel and package file name channel value are inconsistent, please compare in detail")


from PIL import Image, ImageDraw
import numpy as np
import os

def image_resize(width, image_name):
    resize_image = img.resize((width, int(width * img.size[1] / img.size[0])))  # 画像のリサイズ
    print("アスペクト比固定　width: {}, height: {}".format(resize_image.size[0], resize_image.size[1]))  # 画像のサイズ出力
    resize_image.save('images/' + image_name)  # 画像の保存

def select_color(color):
    mean = np.array(color).mean(axis=0)
    return (255, 255, 255, 0) if mean >= 250 else color

def to_touka(img):
    w, h = img.size
    touka_img = Image.new('RGBA', (w, h))
    np.array([[touka_img.putpixel((x, y), select_color(img.getpixel((x, y)))) for x in range(w)] for y in range(h)])
    return touka_img

def pic_make(path ,path2):
    img = Image.open(path)  # イメージを開く
    print("元の画像サイズ　width: {}, height: {}".format(img.size[0], img.size[1]))  # 元の画像のサイズ出力
    # 画像を指定したサイズに変更
    img_resize = img.resize((44, 65))  # 画像のリサイズ
    print("指定サイズ　width: {}, height: {}".format(img_resize.size[0], img_resize.size[1]))  # 画像のサイズ出力

    img_resize.save('temp.png')

    img_con = img_resize.convert("RGBA")
    img_touka = to_touka(img_con)

    layer1 = Image.open("./street_view/pic/streetview0.png")
    layer1.paste(img_touka, (0, 30), img_touka)
    layer1.save(path2)

path1 = "./street_view/asasio.jpg"
path2 = "./street_view/test.png"

pic_make(path1, path2)


import gtk, Utils

class TileWidget(gtk.Button):

    lightwood_pixbuf = gtk.gdk.pixbuf_new_from_file('resources/images/lightwood.jpg')
    lightwood_pixmap, _ = lightwood_pixbuf.render_pixmap_and_mask()
    gray = gtk.gdk.color_parse('#444444')
    black = gtk.gdk.color_parse('black')
    width = height = -1

    @classmethod
    def set_size(cls):
        """
        This classmethod sets the width and height for all
        subsequently created TileWidgets. It determines the width and
        height by creating a temporary TileWidget for 'Q' (the widest
        tile) and querying its size.

        Call this classmethod before any TileWidgets are created.
        """

        q_tile_widget = cls('Q')
        q_tile_widget.show_all()
        cls.width, cls.height = q_tile_widget.size_request()
        q_tile_widget.destroy()

    def __init__(self, letter, on_click=None, sensitive=True):
        gtk.Button.__init__(self)
        self.label = gtk.Label()
        self.add(self.label)
        self.set_sensitive(sensitive)
        self.set_size_request(self.__class__.width, self.__class__.height)
        self.set_label(letter, Utils.num_points_for_letter(letter))
        self.set_background_image(self.lightwood_pixmap)
        self.label.modify_fg(self.state, self.black)
        if on_click: self.connect('clicked', on_click)

    def set_label(self, letter, num_points):
        letter_font_size = 20
        number_font_size = 12
        if num_points > 9: number_font_size = 10
        self.label.set_markup(
            '%s' % (letter_font_size, letter) +
            '%d' % (number_font_size, num_points))

    def set_background_image(self, pixmap):
        style = self.get_style().copy()
        style.bg_pixmap[self.state] = pixmap
        self.set_style(style)

    def gray_out(self):
        self.set_sensitive(False)
        self.label.modify_fg(self.state, self.gray)

TileWidget.set_size()


def sortByHeight(a):
    position_trees = [index for index in range(len(a)) if a[index] == -1]
    aux_list = sorted([item for item in a if item != -1])

    for pos in position_trees:
        aux_list.insert(pos, -1)

    return aux_list

print(sortByHeight([-1, 150, 190, 170, -1, -1, 160, 180]))


# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load in

import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import math
# Input data files are available in the "../input/" directory.
# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory

import os
print(os.listdir("../input"))

# Any results you write to the current directory are saved as output.
# Set columns to most suitable type to optimize for memory usage
types = {'fare_amount': 'float32',
         'pickup_longitude': 'float32',
         'pickup_latitude': 'float32',
         'dropoff_longitude': 'float32',
         'dropoff_latitude': 'float32',
         'passenger_count': 'uint8'}

# Columns to keep (basically discarding the 'key' column) - thanks to the suggestion by mhviraf
cols = ['fare_amount', 'pickup_datetime', 'pickup_longitude', 'pickup_latitude',
        'dropoff_longitude', 'dropoff_latitude', 'passenger_count']
# train = pd.read_csv('../input/train.csv', nrows=5000000, usecols=cols, dtype=types)
train = pd.read_csv('../input/train.csv', nrows=1000000, usecols=cols, dtype=types)
test = pd.read_csv('../input/test.csv')
samp = pd.read_csv('../input/sample_submission.csv')
train.dropna(how = 'any', axis = 'rows', inplace=True)
train = train[train.fare_amount > 0]
train = train[train['passenger_count'] <= 6]
latitude_mask_pickup = (train.pickup_latitude > -90) &  (train.pickup_latitude < 90)

train = train[latitude_mask_pickup]

latitude_mask_dropoff = (train.dropoff_latitude > -90) &  (train.dropoff_latitude < 90)

train = train[latitude_mask_dropoff]
longitude_mask_pickup = (train.pickup_longitude > -180) &  (train.pickup_longitude < 180)

train = train[longitude_mask_pickup]

longitude_mask_dropoff = (train.dropoff_longitude > -180) &  (train.dropoff_longitude < 180)

train = train[longitude_mask_dropoff]
all_data = pd.concat((train, test)).reset_index(drop=True)

all_data.drop(['fare_amount'] , axis=1, inplace=True)
y = train.fare_amount.values
n_train = len(train)
n_test = len(test)
test_id = test.key
def week_num(day):
    '''
    given the day of the month, return the week number of the month
    '''
    if day <=7 : return 'first'
    if (day > 7) and (day <= 14): return 'second'
    if (day > 14) and (day <= 21): return 'third'
    if (day > 21) and (day <= 28): return 'fourth'
    return 'fifth'
def add_time_features(data):
    data.pickup_datetime =  pd.to_datetime(data.pickup_datetime)
    # Date Features

    data['hour'] = data.pickup_datetime.dt.hour
    data['day_of_week'] = data.pickup_datetime.dt.weekday_name
    data['day_of_month'] = data.pickup_datetime.dt.day
    data['week_of_month'] = data.day_of_month.map(week_num)
    data['month'] = data.pickup_datetime.dt.month
    data['year'] = data.pickup_datetime.dt.year

    data.hour = data.hour.astype(str)
    data.month = data.month.astype(str)
    data.year = data.year.astype(str)
    data.drop('day_of_month', axis=1, inplace=True)

    return data

def add_geo_features(data):
    # Geo Features
    data['abs_diff_longitude'] = (data.dropoff_longitude - data.pickup_longitude).abs()
    data['abs_diff_latitude'] = (data.dropoff_latitude - data.pickup_latitude).abs()

    data['manhattan_distance'] = data['abs_diff_longitude'] + data['abs_diff_latitude']

    data['squared_long'] = np.power(data['abs_diff_longitude'],2)
    data['squared_lat'] = np.power(data['abs_diff_latitude'],2)

    data['euclid_distance'] = np.sqrt(data['squared_long'] + data['squared_lat'])

    return data
all_data = add_time_features(all_data)
all_data = add_geo_features(all_data)
features = ['passenger_count', 'hour', 'day_of_week', 'week_of_month', 'month', 'year', 'abs_diff_longitude', 'abs_diff_latitude', 'manhattan_distance', 'euclid_distance']

all_data = all_data[features]

all_data = pd.get_dummies(all_data)
x = all_data[:n_train]
x_test = all_data[n_train:]
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import GridSearchCV
model_1 = RandomForestRegressor()
model_1.fit(x, y)

model_1_pred = model_1.predict(x_test)
sub_1 = pd.DataFrame()
sub_1['key'] = test_id
sub_1['fare_amount'] = model_1_pred
sub_1.to_csv('submission_rf.csv', index=False)
from keras.models import Sequential
from keras.layers import Dense
num_features = len(x.columns)
model = Sequential()
model.add(Dense(30, input_dim=num_features, activation='relu'))
model.add(Dense(15, activation='relu'))
model.add(Dense(7, activation='relu'))
model.add(Dense(3, activation='relu'))
model.add(Dense(1, activation='linear'))
model.summary()
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(x, y)
test_pred = model.predict(x_test)
sub = pd.DataFrame()
sub['key'] = test_id
sub['fare_amount'] = test_pred
sub.to_csv('submission_nn.csv', index=False)


# A group of 3 lines will have one letter in common. this is their badge
# what is sum of priorities of badges.

file_path = 'day3_input.txt' # backpack contents
total_sum = 0 #counter
priority = {
    'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,'k':11,'l':12,'m':13,'n':14,'o':15,'p':16,'q':17,'r':18,'s':19,'t':20,'u':21,'v':22,'w':23,'x':24,'y':25,'z':26,'A':27,'B':28,'C':29,'D':30,'E':31,'F':32,'G':33,'H':34,'I':35,'J':36,'K':37,'L':38,'M':39,'N':40,'O':41,'P':42,'Q':43,'R':44,'S':45,'T':46,'U':47,'V':48,'W':49,'X':50,'Y':51,'Z':52
}
start=0
end=3
with open(file_path) as input_file:
    all_elves = input_file.readlines()
    for i in range(len(all_elves)//3):
        # because the code examines 3 lines per loop, we only need to loop (total number of lines divided by 3) times.
        for char in all_elves[start]:
            if char in all_elves[start+1] and char in all_elves[start+2]:
                total_sum += priority[char]
                start+=3
                break
print(total_sum)


import torch
from torchmetrics import ROC
from torchmetrics.functional import auc
from tqdm import tqdm

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

def evaluate_roc(test_data, model):
    roc = ROC(pos_label=1)
    roc.reset()

    model.eval()
    preds = []
    labels = []
    with torch.no_grad():
        for _, inputs, _, label in tqdm(test_data):
            inputs = inputs.to(device)
            label = label.to(device)
            pred = model(inputs)
            preds.append(torch.nn.functional.softmax(pred)[:,1])
            labels.append(label)
    preds = torch.cat(preds)
    labels = torch.cat(labels)

    print(f' Data num: total {len(labels)}, pos {sum(labels).item()}, neg {len(labels)-sum(labels).item()}')
    fpr, tpr, thresholds = roc(preds, labels)
    fnr = 1 - tpr
    hter_threshold = 0.22
    idx_hter = torch.argmin(abs(thresholds-hter_threshold), dim=0)
    hter = ((fpr[idx_hter] + fnr[idx_hter]) / 2).item()
    idx_eer = torch.argmin((fpr - fnr).abs(), dim=0)
    eer = fpr[idx_eer].item()
    print('HTER: {:.2%}'.format(hter))
    print('EER: {:.2%}'.format(eer))
    print('AUC: {:.2%}'.format(auc(fpr, tpr)))
    APCER = [0.1, 0.01]
    for apcer in APCER:
        bpcer = fnr[fpr>=apcer][0]
        print('BPCER@APCER={}: {:.2%}'.format(apcer, bpcer))


''' https://msdn.microsoft.com/en-us/library/dd358336.aspx
http://stackoverflow.com/questions/3052202/how-to-analyse-contents-of-binary-serialization-stream
'''
import binascii
import struct
import packetview

OP_REQUEST = 0
OP_ONEWAYREQUEST = 1
OP_REPLY = 2

# Common types

class CountedString(object):

    def __init__(self, string_encoding, value):
        self.string_encoding = string_encoding
        self.value = value

    def pack(self):
        string_data = self.value.encode('utf-8')
        length = len(string_data)
        return struct.pack('<Bi', self.string_encoding, length) + string_data

    @classmethod
    def unpack(cls, byts):
        string_encoding, length = struct.unpack("<Bi", byts[:5])
        if string_encoding == 0:
            # TODO: 0 indicates a 'unicode' string, need to verify how to
            # pack/unpack unicode data
            raise NotImplementedError()
        if string_encoding not in [0, 1]:
            raise Exception()
        byts = byts[5:]
        string_data = byts[:length]
        return cls(string_encoding, string_data.decode('utf-8'))

# Message frame structure

class SingleMessage(object):

    protocol_id = 0x54454E2E
    major_version = 1
    minor_version = 0

    def __init__(self, operation_type, message, headers=None):
        if operation_type not in (OP_REQUEST, OP_ONEWAYREQUEST, OP_REPLY):
            raise Exception("Invalid operation type: {}".format(operation_type))
        self.operation_type = operation_type
        self.content_dist = 0
        self.length = len(message)
        self.headers = headers or []
        self.message = message

    def __repr__(self):
        return 'SingleMessage({}, {}, {})'.format(
            self.operation_type, self.length, repr(self.headers))

    def pack(self):
        data = struct.pack(
           '<iBBHHi',
           self.protocol_id,
           self.major_version,
           self.minor_version,
           self.operation_type,
           self.content_dist,
           self.length,
        )
        for header in self.headers:
            data += header.pack()
        data += struct.pack('<H', 0)
        data += self.message
        return data

    @classmethod
    def bytes_needed(cls, byts):
        preable, ibyts = byts[:14], byts[14:]
        l = struct.unpack('<iBBHHi', preable)
        assert l[0] == cls.protocol_id
        assert l[1] == cls.major_version
        assert l[2] == cls.minor_version
        operation_type = l[3]
        content_dist = l[4]
        length = l[5]
        headers = []
        while True:
            header, ibyts = cls.consume_header(ibyts)
            if header.header_token == 0:
                break

            # header_token, ibyts = ibyts[:2], ibyts[2:]
            # if header_token == '\x00\x00':
            #     break

            # TODO: Unpack headers
        needed = length - len(ibyts)
        if needed > 0:
            return needed
        return 0

    @classmethod
    def unpack(cls, byts):
        preable, ibyts = byts[:14], byts[14:]
        l = struct.unpack('<iBBHHi', preable)
        assert l[0] == cls.protocol_id
        assert l[1] == cls.major_version
        assert l[2] == cls.minor_version
        operation_type = l[3]
        content_dist = l[4]
        length = l[5]
        headers = []
        while True:
            header, ibyts = cls.consume_header(ibyts)
            if header.header_token == 0:
                break

            # header_token, ibyts = ibyts[:2], ibyts[2:]
            # if header_token == '\x00\x00':
            #     break

            # TODO: Unpack headers

        assert len(ibyts) == length, (len(ibyts), length)
        return cls(operation_type, ibyts, headers=headers)

    @classmethod
    def unpack_header(cls, byts):
        header_type, = struct.unpack('<H', byts[:2])
        return headers[header_type].unpack(byts)

    @classmethod
    def consume_header(cls, byts):
        header = cls.unpack_header(byts)
        header_data = header.pack()
        if header_data != byts[:len(header_data)]:
            raise Exception
        return header, byts[len(header_data):]

# Message Headers

class EndHeader(object):
    header_token = 0

    def pack(self):
        return struct.pack('<H', self.header_token)

    @classmethod
    def unpack(cls, byts):
        header_token, = struct.unpack(
            '<H', byts[:2]
        )
        if header_token != cls.header_token:
            raise Exception("Invalid header token or data type")
        return cls()

class StatusCodeHeader(object):
    header_token = 2
    data_type = 3  # UInt16

    def __init__(self, status_code):
        self.status_code = status_code

    def pack(self):
        return struct.pack('<HBH', self.header_token, self.data_type, self.status_code)

    @classmethod
    def unpack(cls, byts):
        header_token, data_type = struct.unpack(
            '<HB', byts[:3]
        )
        if header_token != cls.header_token or data_type != cls.data_type:
            raise Exception('Invalid header token or data type')
        status_code, = struct.unpack('<H', byts[3:5])
        return cls(status_code)

class StatusPhraseHeader(object):

    header_token = 3
    data_type = 1

    def __init__(self, value):
        self.value = value

    def pack(self):
        data = struct.pack(
            '<HB', self.header_token, self.data_type
        )
        return data + CountedString(1, self.value).pack()

    @classmethod
    def unpack(cls, byts):
        header_token, data_type = struct.unpack(
            '<HB', byts[:3]
        )
        if header_token != cls.header_token or data_type != cls.data_type:
            raise Exception("Invalid header token or data type")
        return cls(CountedString.unpack(byts[3:]).value)

class RequestUriHeader(object):

    header_token = 4
    data_type = 1

    def __init__(self, uri):
        self.string_encoding = 1
        self.uri = uri

    def pack(self):
        data = struct.pack(
            '<HB', self.header_token, self.data_type
        )
        return data + CountedString(1, self.uri).pack()

    @classmethod
    def unpack(cls, byts):
        header_token, data_type = struct.unpack(
            '<HB', byts[:3]
        )
        if header_token != cls.header_token or data_type != cls.data_type:
            raise Exception("Invalid header token or data type")
        uri_value = CountedString.unpack(byts[3:]).value
        return cls(uri_value)

class CloseConnectionHeader(object):
    header_token = 5
    data_type = 0

    def pack(self):
        return struct.pack(
            '<HB', self.header_token, self.data_type
        )

    @classmethod
    def unpack(cls, byts):
        header_token, data_type = struct.unpack(
            '<HB', byts[:3]
        )
        if header_token != cls.header_token or data_type != cls.data_type:
            raise Exception('Invalid header token or data type')
        return cls()

class ContentTypeHeader(object):

    header_token = 6
    data_type = 1

    def __init__(self, content_type):
        self.content_type = content_type

    def pack(self):
        data = struct.pack(
            '<HB', self.header_token, self.data_type
        )
        return data + CountedString(1, self.content_type).pack()

    @classmethod
    def unpack(cls, byts):
        header_token, data_type = struct.unpack(
            '<HB', byts[:3]
        )
        if header_token != cls.header_token or data_type != cls.data_type:
            raise Exception("Invalid header token or data type")
        content_type = CountedString.unpack(byts[3:]).value
        return cls(content_type)

headers = {
    EndHeader.header_token: EndHeader,
    StatusCodeHeader.header_token: StatusCodeHeader,
    StatusPhraseHeader.header_token: StatusPhraseHeader,
    ContentTypeHeader.header_token: ContentTypeHeader,
    CloseConnectionHeader.header_token: CloseConnectionHeader,
    RequestUriHeader.header_token: RequestUriHeader,
}

class RemotingRequest(object):

    def __init__(self, message, response=None):
        self.message = message
        self.response = None

class RemotingResponse(object):

    def __init__(self, request, message):
        self.request = request
        self.message = message

class RemotingMethod(object):

    def __init__(
            self, uri, serverinfo, methodname, arg_spec, return_spec,
            content_type='application/octet-stream'):
        self.uri = uri
        self.serverinfo = serverinfo
        self.methodname = methodname
        self.arg_spec = arg_spec
        self.return_spec = return_spec
        self.content_type = content_type

    def create_request(self, inputargs):
        '''
        MS-NRTP 3.1.5.1.1 Mapping Remote Method Request

        Information required to perform a Remote Method invocation consists of a
        Server Type or Server Interface name, a Remote Method name, Input
        Arguments, Generic Arguments values, Method Signature, and a Call Context.

        The implementation MAY construct an Array of System.Object classes called
        Message Properties in order to transmit implementation-specific information
        to the server. The Array, if constructed, MUST contain items whose Remoting
        Types are instances of the DictionaryEntry Class as specified in
        DictionaryEntry (section 2.2.2.6). Each DictionaryEntry item MUST contain
        the name and the value of the implementation-specific information.<33>

        The request is serialized into the serialization stream by using the
        records specified in [MS-NRBF], as follows:

        A SerializationHeaderRecord record as specified in [MS-NRBF] MUST be
        serialized. The Remote Method invocation request is serialized using a
        BinaryMethodCall record and a MethodCallArray record. The Server Type or
        the Server Interface name MUST be serialized in the TypeName field of the
        BinaryMethodCall record. The Remote Method name is serialized in the
        MethodName field of the BinaryMethodCall record. The MethodCallArray record
        is conditional and the rules for the presence of the MethodCallArray record
        are given in the following table. The table specifies the rules for
        serializing the request and the values for the MessageEnum field of the
        BinaryMethodCall record.
        '''
        from msnrbf.records import *
        from msnrbf.grammar import *
        args = []
        for n, (bspec, pspec,) in enumerate(self.arg_spec):
            if bspec == bt.STRING and pspec is None:
                args.append(
                    ValueWithCode(
                        LengthPrefixedString.enum,
                        inputargs[n],
                    )
                )
        method = BinaryMethodCall(
            MessageEnum(NoContext=True, ArgsInline=True),
            self.methodname,
            self.serverinfo,
            args=ArrayOfValueWithCode(args),
        )
        message_body = RemotingMessage.build_method_call(method)
        msg = SingleMessage(
            OP_REQUEST,
            message_body.pack(),
            headers=[
                RequestUriHeader(self.uri),
                ContentTypeHeader(self.content_type)
            ]
        )
        return msg

    def create_response(self, value=None, exception=None):
        '''
        MS-NRTP 3.1.5.1.2 Mapping Remote Method Invocation Reply
        '''
        from msnrbf.records import *
        from msnrbf.grammar import *
        method = BinaryMethodReturn(
            MessageEnum(ReturnValueInArray=True),
        )
        message_body = RemotingMessage.build_metho_return(value, exception)
        msg = SingleMessage(
            OP_REQUEST,
            message_body.pack(),
            headers=[
                RequestUriHeader(self.uri),
                ContentTypeHeader(self.content_type)
            ]
        )
        return msg


import bs4 as bs
import urllib.request
import csv

CLASS_NAME_TO_TAKE_MOVIE = "nm-content-horizontal-row-item" #Buscando esta variable podemos sacar la fila de las peliculas que aparecen en la pagina
TAKE_NAME_MOVIE = "title-info" #Buscando esta variable podemos sacar el nombre de las peliculas
TAKE_DESCRIPTION = "title-info-synopsis" #Buscando esta variable podemos sacar la descripcion de las peliculas
TAKE_YEAR = "title-info-metadata-item item-year" #Buscando esto podemos sacr el año
TAKE_GENRE = "title-info-metadata-item item-genre" #Buscando esto podemos sacar el genero
TAKE_DIRECTORS = "title-data-info-item-list"#Buscando esta variable podemos buscar los directores
TAKE_CAST = "more-details-item item-cast" #Buscando esta variable podemos encontrar el cast

headers = ["Name", "Year","Gender", "Link","Cast","Directors", "Description"]

url = 'https://www.netflix.com/ar/browse/genre/839338'

source = urllib.request.urlopen(url).read()

soup = bs.BeautifulSoup(source,'html.parser')

movies = soup.findAll('li',class_ = CLASS_NAME_TO_TAKE_MOVIE) #Me quedo con las peliculas

#Busco los links de cada pelicula
links=[]
for movie in movies:
    links.append(movie.a['href'])
names =[]
descriptions=[]
year=[]
genre=[]
directors=[]
cast=[]
for link in links:
    source = urllib.request.urlopen(link).read()
    soup = bs.BeautifulSoup(source,'html.parser')
    try:
        names.append(soup.find('div',class_=TAKE_NAME_MOVIE).h1.text)
    except:
        names.append("No Info")
    try:
        descriptions.append(soup.find('div',class_=TAKE_DESCRIPTION).text)
    except:
        descriptions.append("No Info")
    try:
        year.append(soup.find('span',class_=TAKE_YEAR).text)
    except:
        year.append("No Info")
    try:
        genre.append(soup.find('a',class_=TAKE_GENRE).text)
    except:
        genre.append("No Info")
    try:
        directors.append(soup.find('span',class_=TAKE_DIRECTORS).text)
    except:
        directors.append("No Info")
    try:
        cast.append(soup.find('div',class_=TAKE_DESCRIPTION).text)
    except:
        cast.append("No Info")

data = [names,year,genre,links,cast,directors,descriptions]
data =list(map(list,zip(*data)))
with open('netflix.csv', 'w',encoding="utf-8",newline="") as file:
    writer = csv.writer(file)
    writer.writerow(headers)
    writer.writerows(data)


import logging
import math
import random

import torch
from tetris.config import BOARD_SIZE

from rl_infra.impl.tetris.offline.dqn import DeepQNetwork
from rl_infra.impl.tetris.offline.tetris_schema import TetrisModelDbEntry
from rl_infra.impl.tetris.online.config import (
    EPSILON_DECAY_RATE,
    FINAL_EPSILON,
    INITIAL_EPSILON,
    MODEL_ENTRY_PATH,
    MODEL_WEIGHTS_PATH,
)
from rl_infra.impl.tetris.online.tetris_transition import TetrisAction, TetrisState
from rl_infra.types.online.agent import Agent

logger = logging.getLogger(__name__)

class TetrisAgent(Agent[TetrisState, TetrisAction, DeepQNetwork]):
    possibleActions = list(sorted(TetrisAction))  # Make sure the models always see the same order

    def __init__(self, device: torch.device) -> None:
        self.policy = DeepQNetwork(
            arrayHeight=BOARD_SIZE[0],
            arrayWidth=BOARD_SIZE[1] + 1,
            numOutputs=5,
            device=device,
        )
        self.policy.load_state_dict(torch.load(MODEL_WEIGHTS_PATH))
        entry = TetrisModelDbEntry.parse_file(MODEL_ENTRY_PATH)
        self.dbKey = entry.modelDbKey
        self.numEpisodesPlayed = entry.numEpisodesPlayed
        self.numEpochsTrained = entry.numEpochsTrained
        self.epsilon = self._updateEpsilon()

    def startNewEpisode(self) -> None:
        self.numEpisodesPlayed += 1
        self.epsilon = self._updateEpsilon()
        logger.info(f"Starting new episode.  epsilon = {self.epsilon}")

    def choosePolicyAction(self, state: TetrisState) -> TetrisAction:
        logger.debug("Choosing policy action")
        input = state.toDqnInput()
        with torch.no_grad():
            # t.max(1) will return largest column value of each row.
            # second column on max result is index of where max element was
            # found, so we pick action with the larger expected reward.
            prediction: int = self.policy(input).max(1)[1].view(1).numpy()[0]
        return self.possibleActions[prediction]

    def chooseRandomAction(self) -> TetrisAction:
        logger.debug("Choosing random action")
        return random.choice(self.possibleActions)

    def _updateEpsilon(self) -> float:
        return FINAL_EPSILON + (INITIAL_EPSILON - FINAL_EPSILON) * math.exp(
            -1.0 * self.numEpisodesPlayed / EPSILON_DECAY_RATE
        )


import sys, os, time, math, json, uuid, base64
import cv2 as cv
import numpy as np
from pyexiv2 import Image
import PIL

class Helper(object):

    INPUT_PATH = os.path.join(__name__, "..", "uploaded")
    OUTPUT_PATH = os.path.join(__name__, "..", "processed")
    TMP_PATH = os.path.join(__name__, "..", "tmp")
    IMAGE_EXTENSION = "bmp"

    @staticmethod
    def isGrayScale(img):
        if(len(img.shape)==2):
            return True
        else:
            h, w, depth = img.shape
            if(depth==1):
                return True
            else:
                return False

    @staticmethod
    def saveImage(img, name, extension=IMAGE_EXTENSION, gray=True):
        if gray and not Helper.isGrayScale(img):
            img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
        # bits = '8 bits' if Helper.isGrayScale(img) else '24 bits'
        # print(f'{name} : {bits}')
        name = f'{name}_{str(uuid.uuid1())}.{extension}'
        params = []
        if extension=="jpg":
            params = [cv.IMWRITE_JPEG_QUALITY, 90]
        cv.imwrite(os.path.join(Helper.OUTPUT_PATH, name), img, params)
        return name

    #________________________________________________________
    #                   Filters
    #________________________________________________________
    @staticmethod
    def blurFilter (img, val=5, extension=IMAGE_EXTENSION):
        dst = cv.blur(img,(val, val))
        # dst = cv.boxFilter(img, -1, (2, 2), normalize=True)
        name = Helper.saveImage(dst, "blurFilter", extension, gray=Helper.isGrayScale(img))
        return dst, name

    @staticmethod
    def averagingFilter(img, val=5, extension=IMAGE_EXTENSION):
        kernel = np.ones((val, val),np.float32)/25
        dst = cv.filter2D(img,-1,kernel)
        name = Helper.saveImage(dst, "averagingFilter", extension, gray=Helper.isGrayScale(img))
        return dst, name

    @staticmethod
    def identityFilter(img, val=1, extension=IMAGE_EXTENSION):
        kernel = np.array([[0, 0, 0],
                    [0, 1, 0],
                    [0, 0, 0]])
        dst = cv.filter2D(img,-1,kernel)
        name = Helper.saveImage(dst, "identityFilter", extension, gray=Helper.isGrayScale(img))
        return dst, name

    @staticmethod
    def sharpeningFilter(img, val=5, extension=IMAGE_EXTENSION):
        kernel = np.array([[0, -1,  0],
                    [-1,  val, -1],
                    [0, -1,  0]])
        dst = cv.filter2D(img,-1,kernel)
        name = Helper.saveImage(dst, "sharpeningFilter", extension, gray=Helper.isGrayScale(img))
        return dst, name

    @staticmethod
    def gaussianFilter(img, val=1, extension=IMAGE_EXTENSION):
        dst = cv.GaussianBlur(img,(val, val),cv.BORDER_DEFAULT)
        name = Helper.saveImage(dst, "gaussianFilter", extension, gray=Helper.isGrayScale(img))
        return dst, name

    @staticmethod
    def medianFilter(img, val=1, extension=IMAGE_EXTENSION):
        dst = cv.medianBlur(img, val)
        name = Helper.saveImage(dst, "medianFilter", extension, gray=Helper.isGrayScale(img))
        return dst, name

    @staticmethod
    def bilateralFilter(img, val=9, extension=IMAGE_EXTENSION):
        # dst = cv.bilateralFilter(img, -1, 5, 5)
        dst = cv.bilateralFilter(src=img, d=val, sigmaColor=75, sigmaSpace=75)
        name = Helper.saveImage(dst, "bilateralFilter", extension, gray=Helper.isGrayScale(img))
        return dst, name

    @staticmethod
    def sobelFilter(img, val=5, extension=IMAGE_EXTENSION):
        if(not Helper.isGrayScale(img)):
            gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
        else:
            gray = img
        dst = cv.Sobel(gray, cv.CV_16S, 1, 1, ksize=val, scale=1, delta=0, borderType=cv.BORDER_DEFAULT)
        name = Helper.saveImage(dst, "SobelFilter", extension, gray=Helper.isGrayScale(img))
        return img, name

    @staticmethod
    def tifToBase64JPG(tif_path):
        tmp = os.path.join(Helper.TMP_PATH, 'tmp.jpg')
        im = PIL.Image.open(tif_path)
        im.save(tmp)
        b64 = ''
        with open(tmp, "rb") as img_file:
            b64 = base64.b64encode(img_file.read()).decode('utf-8')
        os.remove(tmp)
        return f'data:image/jpeg;base64,{b64}'

    @staticmethod
    def DecimalToBinary(dic):
        return str(format(dic,'08b'))

    @staticmethod
    def BinaryToDecimal(bin):
        return int(bin,2)

    @staticmethod
    def StringToBinary(str):
        bin = ''.join(format(ord(i), '08b') for i in str)
        return bin

    @staticmethod
    def BinaryToString(bin):
        n=int(bin, 2)
        str = n.to_bytes((n.bit_length() + 7) // 8, 'big')
        str = str.decode('unicode_escape')#  'utf-8'     'unicode_escape'    'ascii'    'cp1252'
        return str

    @staticmethod
    def deff_pixels(img, otherImg):
        deff = 0
        w, h = img.shape[:2]
        for x in range(w):
            for y in range(h):
                if img[x][y] != otherImg[x][y]:
                    deff+=1
        print(f'{deff}')

    @staticmethod
    def deff_importantFeaturePoints(list, otherList):
        deff = 0
        l = min(len(list),len(otherList))
        for i in range(l):
            point_original = list[i]
            point_watermarked = otherList[i]
            if(point_original["x"]!=point_watermarked["x"] or point_original["y"]!=point_watermarked["y"]):
                deff+=1
        print(f'[{len(list)}/{len(otherList)}]: {deff}')

    @staticmethod
    def deff_binary(str, otherStr):
        deff = 0
        for i in range(len(str)):
            if(str[i]!=otherStr[i]):
                deff+=1
        print(deff)

    @staticmethod
    def loadImage(img):
        image = cv.imread(img, cv.IMREAD_ANYDEPTH | cv.IMREAD_UNCHANGED) if type(img).__name__=="str" else img
        # image = cv.imread(img, cv.IMREAD_GRAYSCALE) if type(img).__name__=="str" else img
        return image

    @staticmethod
    def fileNameExtension(path):
        # extension = imageName.rsplit('.', 1)[1].lower()
        name, extension = os.path.basename(path).split('.')
        return name, extension

    @staticmethod
    def saveJsonFile(fileName, data):
        with open(fileName, "w") as outfile:
            outfile.write(json.dumps(data, indent=4))

    @staticmethod
    def loadJsonFile(fileName):
        with open(fileName, "r") as outfile:
            data = json.load(outfile)
        return data

    @staticmethod
    def getMetadata(image_path):
        name, extension = Helper.fileNameExtension(image_path)
        if extension=="bmp":
            return None
        img = Image(image_path)
        if img.read_exif().get("Exif.Image.Make") is None:
            return {}
        metadata = img.read_exif()["Exif.Image.Make"]
        metadata = json.loads(str(metadata))
        img.close()
        return metadata if metadata!={} else None

    @staticmethod
    def setMetadata(image_path, new_metadata={}):
        img = Image(image_path)
        img.clear_exif()
        img.modify_exif({ "Exif.Image.Make": json.dumps(new_metadata) })
        img.close()

    @staticmethod
    def cleanDirectory(dir):
        now = time.time()
        timer = 0# 730 * 86400 # 60 minutes : 60 * 60      30 days : 30 * 86400
        for filename in os.listdir(dir):
            path = os.path.join(dir, filename)
            if os.path.getmtime(path) < now - timer:
                if os.path.isfile(path):
                    os.remove(path)

    @staticmethod
    def getFilesInDirectory(dir):
        files = []
        name_list = os.listdir(dir)
        full_list = [os.path.join(dir,i) for i in name_list]
        time_sorted_list = sorted(full_list, key=os.path.getmtime)
        sorted_filename_list = [ os.path.basename(i) for i in time_sorted_list]
        sorted_filename_list.reverse()

        for filename in sorted_filename_list:
            sz = os.path.getsize(os.path.join(dir, filename))
            files.append({"name":filename, "size": sz, "path": os.path.join(dir) })

        return files


# Uses python3
import sys

def EuclidGCD(a, b):
    if b == 0:
        return a
    return EuclidGCD(b, a % b)

def LCM(a, b):
    gcd = EuclidGCD(a, b)
    c = int(a / gcd)
    return c * b

if __name__ == '__main__':
    input = sys.stdin.read()
    a, b = map(int, input.split())
    print(LCM(a, b))


__all__ = (
    'DetectionPerformanceCurve',
    'CurveData2d',
    'MeanAvgPrecisionData',
)

from numpy import (
    empty,
    argsort,
    float32,
    isfinite,
    diff,
    isclose,
    nonzero,
    logical_not,
    concatenate,
    trapz,
)
from collections import namedtuple
from ..Base import DetectionConfidenceAssessment
from ..FlowBuilder import ResourceTypeInfo
from ..Logger import get_default_logger

CurveData2d = namedtuple(
    'CurveData2d',
    ['x_points', 'x_entity', 'y_points', 'y_entity'],
)

MeanAvgPrecisionData = namedtuple(
    'MeanAvgPrecisionData',
    ['auc', 'autofilled_auc'],
)

# NOTE: percent conversion (multiply by 100) is not applied in precision and
#       recall handlers because we're calculating AUC (AP) using those values

# NOTE: entity name is here to help additional plugins like graph plotter to
#       represent the given information: like axis names, percentage/log-scale
#       conversions and so on. Those options are required for usability, but
#       are not ours to set: for example, plotter could use a different locale.

# NOTE: handlers use the processing assessments list while initialization; this
#       is because some global constants might be needed to produce the results
#       while accessing some intervals of detections list

class PrecisionHandler:
    entity = 'precision'
    def __init__(self, assessment_list):
        # don't need to do anything with assessment_list
        self.detections_count = 0
        self.tp_count = 0
    def point(self, tp_flags_interval):
        # tp_flags_interval: 0/1 per detection, 1 = tp, 0 = fp
        self.detections_count += tp_flags_interval.shape[0]
        self.tp_count += tp_flags_interval.sum()
        # calculating: TP / (TP + FP), (TP + FP) is the detections count
        return self.tp_count / self.detections_count

class RecallHandler:
    entity = 'recall'
    def __init__(self, assessment_list):
        # calculating gt objects count (since it is constant)
        # assessment_list: (tp_confs, fp_confs, fn_count, multicount)
        self.gt_count = sum([e[0].shape[0] + e[2] for e in assessment_list])
        self.tp_count = 0
    def point(self, tp_flags_interval):
        self.tp_count += tp_flags_interval.sum()
        # calculating: TP / (TP + FN), (TP + FN) is the gt set size
        return self.tp_count / self.gt_count

class FPCountHandler:
    entity = 'false-positives'
    def __init__(self, assessment_list):
        self.fp_count = 0
    def point(self, tp_flags_interval):
        # need to calculate number of '0' having '1' as the only other option
        self.fp_count += (tp_flags_interval.shape[0] - tp_flags_interval.sum())
        return self.fp_count

class FPPIHandler:
    entity = 'false-positives-per-sample'
    def __init__(self, assessment_list):
        # calculating samples count (not gt markup count)
        self.samples_count = len(assessment_list)
        self.fp_count = 0
    def point(self, tp_flags_interval):
        # false positives count is the count of 0 in interval (0/1 are allowed)
        self.fp_count += (tp_flags_interval.shape[0] - tp_flags_interval.sum())
        # calculating: FP / (samples count)
        return self.fp_count / self.samples_count

# FIXME: we can use flow builder to avoid multiple calculation of the same data

available_handlers = {
    'precision': PrecisionHandler,
    'recall': RecallHandler,
    'false-positives': FPCountHandler,
    'false-positives-per-sample': FPPIHandler,
}

class DetectionPerformanceCurve:
    def __init__(self, **kwargs):
        self._logger = kwargs.get('logger', get_default_logger())
        axis_drv = kwargs.get('mode', ('precision', 'recall'))
        if axis_drv[0] not in available_handlers:
            raise Exception('unknown notion "{}" is requested for v-axis'.format(axis_drv[0])) # FIXME
        if axis_drv[1] not in available_handlers:
            raise Exception('unknown notion "{}" is requested for h-axis'.format(axis_drv[1])) # FIXME
        curve_res = 'analysis:object-detection:curve-{}({})'.format(*axis_drv)
        if axis_drv == ('precision', 'recall'):
            self._map_is_possible = True
            output = (curve_res, 'analysis:object-detection:mean-avg-precision')
        else:
            self._map_is_possible = False
            output = (curve_res,)
        self._contract = (('assessment-list:object-detection',), output)
        self._axis_cls = tuple(map(available_handlers.__getitem__, axis_drv))
    def targets_to_inject(self):
        return self._contract[1]
    def static_contracts(self):
        return [self._contract]
    def get_contract(self, mode_id):
        assert mode_id == 0
        return self._contract
    def setup(self, mode_id, input_types, output_mask):
        assert mode_id == 0
        if not any(output_mask):
            return lambda *args: None, (None,) * len(output_mask)
        input_t = input_types[0]
        if input_t.type_cls is not list:
            raise RuntimeError()
        try:
            elem_cls = input_t.aux_info['elem_type'][0].type_cls
        except (KeyError, IndexError):
            raise RuntimeError()
        if elem_cls is not DetectionConfidenceAssessment:
            raise RuntimeError()
        # now we know that we have a list of DetectionConfidenceAssessment,
        # which is the only information representation we support
        axis_classes = self._axis_cls
        map_is_possible = self._map_is_possible
        if map_is_possible:
            map_is_requested = output_mask[1]
            output_types = (
                ResourceTypeInfo(CurveData2d),
                ResourceTypeInfo(MeanAvgPrecisionData),
            )
        else:
            output_types = (ResourceTypeInfo(CurveData2d),)
        def worker(assessment_list):
            # element (DetectionConfidenceAssessment) is a named tuple with
            # the following fields in the order:
            #   tp_confs, fp_confs, fn_count, multicount
            conf_points_count = lambda e: e[0].shape[0] + e[1].shape[0]
            points_count = sum(map(conf_points_count, assessment_list))
            if points_count <= 1:
                raise RuntimeError('not enough data to produce curve')
            # initializing axis processors (need to precalculate constants)
            axis_drv = tuple(map(lambda cl: cl(assessment_list), axis_classes))
            # payload is simply `is_true_positive` indicator (for now)
            # NOTE: no numpy.concatenate, it will require a sequence (list/tuple)
            confidences = empty(points_count, order = 'C', dtype = 'float32')
            payload = empty(points_count, order = 'C', dtype = 'int32')
            arr_top_idx = 0
            for sample_info in assessment_list:
                # processing confidences of true positives
                tp_confs = sample_info[0]
                tp_count = tp_confs.shape[0]
                if tp_count > 0:
                    next_top_idx = arr_top_idx + tp_count
                    confidences[arr_top_idx : next_top_idx] = tp_confs
                    payload[arr_top_idx : next_top_idx].fill(1)
                    arr_top_idx = next_top_idx
                # processing confidences of false positives
                fp_confs = sample_info[1]
                fp_count = fp_confs.shape[0]
                if fp_count > 0:
                    next_top_idx = arr_top_idx + fp_count
                    confidences[arr_top_idx : next_top_idx] = fp_confs
                    payload[arr_top_idx : next_top_idx].fill(0)
                    arr_top_idx = next_top_idx
            # checking for values which we will not tolerate
            if not isfinite(confidences).all():
                raise RuntimeError('Inf/NaN confidences are prohibited')
            # sorting by confidence to perform thesholding (descending)
            # FIXME: check mergesort instead of quicksort
            sort_indices = argsort(confidences, kind = 'quicksort')[::-1]
            confidences = confidences[sort_indices]
            payload = payload[sort_indices]
            del sort_indices
            # thresholding confidence level from the highest one
            # NOTE: indices on the following line are corresponding to the points
            #       where there is a gap compare to the next value
            target_indices = nonzero(logical_not(isclose(0, diff(confidences))))[0] # FIXME: configurable
            # adding fictive first point to produce correct range and the last point
            # NOTE: +1 is to use non-inclusive index of a range end
            target_indices = concatenate(([-1], target_indices, [points_count])) + 1
            points_count = len(target_indices) - 1
            x_points = empty(points_count, dtype = 'float32')
            y_points = empty(points_count, dtype = 'float32')
            for idx in range(1, len(target_indices)):
                interval = payload[target_indices[idx - 1] : target_indices[idx]]
                point_idx = idx - 1
                y_points[point_idx] = axis_drv[0].point(interval)
                x_points[point_idx] = axis_drv[1].point(interval)
            curve_data = CurveData2d(
                x_points,
                axis_classes[1].entity,
                y_points,
                axis_classes[0].entity,
            )
            if not map_is_possible:
                return curve_data
            if not map_is_requested:
                # we announced mAP calculation capability, but no interest
                return curve_data, None
            # and here, we can calculate mAP and it is requested
            fair_auc = trapz(y_points, x_points)
            # since the data could start from an initial recall value (the first
            # group of the highest-confidence detections), we are missing the
            # most left area. We will fill the gap between the initial recall
            # and zero recall with the constant precision which is corresponding
            # to the its initial value.
            filled_auc = y_points[0] * x_points[0]
            map_data = MeanAvgPrecisionData(fair_auc + filled_auc, filled_auc)
            return curve_data, map_data
        if self._logger.__dummy__:
            return worker, output_types
        # wrap into logger here
        def log_wrapped_worker(*args, **kwargs):
            msg = 'analysing assessments to produce a curve {}({})'.format(
                *[cls.entity for cls in self._axis_cls],
            )
            with self._logger.subtask(msg):
                return worker(*args, **kwargs)
        return log_wrapped_worker, output_types


"""
https://programmers.co.kr/learn/courses/30/lessons/60061

"""

class Building:
    def __init__(self, frames):
        self.frames = frames
        self.wall = {}
        self.floor = {}

    def _check_wall(self, y, x):
        if y == 0:
            return True
        if self.floor.get((y, x - 1), 0) or self.floor.get((y, x), 0):
            return True
        if self.wall.get((y - 1, x), 0):
            return True
        return False

    def _check_floor(self, y, x):
        if y == 0:
            return False
        if self.wall.get((y - 1, x), 0) or self.wall.get((y - 1, x + 1), 0):
            return True
        if self.floor.get((y, x - 1), 0) and self.floor.get((y, x + 1), 0):
            return True
        return False

    def _check_wall_if_exist(self, y, x):
        if self.wall.get((y, x), 0) == 0:
            return True
        return self._check_wall(y, x)

    def _check_floor_if_exist(self, y, x):
        if self.floor.get((y, x), 0) == 0:
            return True
        return self._check_floor(y, x)

    def _remove_wall(self, y, x):
        del self.wall[(y, x)]

        if not (self._check_floor_if_exist(y + 1, x - 1) and self._check_floor_if_exist(y + 1, x)):
            self.wall[(y, x)] = 1

        elif not self._check_wall_if_exist(y + 1, x):
            self.wall[(y, x)] = 1

    def _remove_floor(self, y, x):
        del self.floor[(y, x)]

        if not (self._check_floor_if_exist(y, x - 1) and self._check_floor_if_exist(y, x + 1)):
            self.floor[(y, x)] = 1

        elif not (self._check_wall_if_exist(y, x) and self._check_wall_if_exist(y, x + 1)):
            self.floor[(y, x)] = 1

    def _build_wall(self, y, x):
        if self._check_wall(y, x):
            self.wall[(y, x)] = 1

    def _build_floor(self, y, x):
        if self._check_floor(y, x):
            self.floor[(y, x)] = 1

    def build(self):
        for x, y, a, b in self.frames:
            if a == 0 and b == 0:
                self._remove_wall(y, x)
            elif a == 1 and b == 0:
                self._remove_floor(y, x)
            elif a == 0 and b == 1:
                self._build_wall(y, x)
            elif a == 1 and b == 1:
                self._build_floor(y, x)
            else:
                raise ValueError("invalid frame")

    def get_state(self):
        result = []
        for w in self.wall:
            result.append([w[1], w[0], 0])
        for f in self.floor:
            result.append([f[1], f[0], 1])
        return sorted(result)

def solution(n, build_frame):
    building = Building(build_frame)
    building.build()
    answer = building.get_state()
    return answer


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

class Solution(object):
    def bstFromPreorder(self, preorder):
        """
        :type preorder: List[int]
        :rtype: TreeNode
        """
        if len(preorder) == 0:
            return None
        root = TreeNode(preorder[0])
        left = []
        right = []
        for i in range(1, len(preorder)):
            if preorder[i] < preorder[0]:
                left.append(preorder[i])
            else:
                right.append(preorder[i])
        root.left = self.bstFromPreorder(left)
        root.right = self.bstFromPreorder(right)
        return root

if __name__ == "__main__":
    solution = Solution()
    preorder = [8,5,1,7,10,12]
    solution.bstFromPreorder(preorder)


from db import Session
from models import Category, Item, User

# Create session
session = Session()

# Query data
categories = session.query(Category).all()
items = session.query(Item).all()
users = session.query(User).all()

# JOIN Items and categories
results = (
    session
    .query(Item, Category)
    .join(Category, Item.category_id == Category.id)
    .order_by(Item.last_updated.desc())
    .limit(10)
)

session.close()

print("Categories:\n")
for category in categories:
    print("id: {}   name: {}".format(category.id, category.name))

print("\nItems:\n")
for item in items:
    print("id: {}   title: {}".format(item.id, item.title))

print("\nUsers:\n")
for user in users:
    print("id: {}   username: {}".format(
        user.id, user.username))

print("\nJoins:\n")
for result in results:
    print("""
             id: {}
             title: {}
             description: {}
             category_id: {}
             owner_id: {}
             last_updated: {}
             category_name: {}"""
          .format(
                result.Item.id,
                result.Item.title,
                result.Item.description,
                result.Item.category_id,
                result.Item.owner_id,
                result.Item.last_updated,
                result.Category.name
          ))


import pytest
from app.el import posts
from app.el.accounts.records import Record
from app.el.images import Image

def test_create():
    acct = Record.new()
    objects = next(Image.new()),
    post = posts.Post.new(acct, content='<string>', images=objects)
    assert post.good()

@pytest.mark.parametrize('base_type',
    [Image, posts.Post],
    ids=['base image', 'base posts']
)
def test_create_base(base_type):
    base = base_type.new()
    # Won't fail if base_type is Image
    try:
        base = next(base)
    except TypeError:
        pass

    reply = posts.Post.new(base.owner, content='<string>', ext=base)
    assert reply.good()
    assert reply.is_reply()
    shared = posts.Post.new(base.owner, content=None, ext=base)
    assert shared.good()
    assert not shared.is_reply()

def test_delete():
    obj = posts.Post.new()
    owner = obj.owner
    posts.Post.delete(owner, [obj])
    assert not posts.Post(obj.id).good()

def test_class():
    instance = posts.Post.new()
    new = posts.Post(instance.id)
    assert new.good()
    assert new == instance

def test_load_plain():
    objects = [posts.Post.new()]
    owner = objects[0].owner
    loaded = list(posts.page(owner))
    assert len(loaded)
    assert all(isinstance(x, posts.Post) for x in loaded)
    assert all(x.owner == owner for x in loaded)
    assert all(x.good() for x in loaded)
    assert set(objects) == set(loaded)

    # Testing iter_info here
    res = posts.iter_info(objects)
    assert res

def test_load_parents():
    bases = [next(Image.new())]
    owner = bases[-1].owner
    for _ in range(5):
        # Create a reply and make it a new base
        reply = posts.Post.new(owner, content='<string>', ext=bases[-1])
        bases.append(reply)

    for x in range(1, 5):
        parents = list(posts.parents(bases[x - 1]))
        assert len(parents) == x
        assert isinstance(parents[0], Image)
        assert all(isinstance(x, posts.Post) for x in parents[1:])
        # Everything but image
        assert all(x.is_reply() for x in parents[1:])

def test_load_derived():
    bases, derived = [next(Image.new())], []
    owner = bases[-1].owner
    for _ in range(5):
        # 'Share' base
        shared = posts.Post.new(owner, content=None, ext=bases[-1])
        # Create a reply and make it a new base
        reply = posts.Post.new(owner, content='<string>', ext=bases[-1])
        bases.append(reply)
        # There're 2 item on each level
        derived.append([shared, reply])

    # Without shared
    levels = list(posts.derived(bases[0]))
    assert len(levels) - 1 == len(derived)
    assert all(len(level) == 1 for level in levels[1:])
    # With shared
    levels = list(posts.derived(bases[0], reflections=True))
    assert all(len(level) == 2 for level in levels[1:])
    assert levels[1:] == derived
    # Testing level_info here
    res = list(posts.level_info(levels))
    assert res

def test_delete_derived():
    bases = [posts.Post.new()]
    owner = bases[-1].owner
    for _ in range(5):
        reply = posts.Post.new(owner, content='<string>', ext=bases[-1])
        bases.append(reply)

    posts.delete_derived(bases[0])
    assert all(not posts.Post(x.id).good() for x in bases)


# -*- coding:utf-8 -*-
import init_env
from unittest import TestCase

from common.base_test import run_tests
from common.cc import Order
from common.HttpUtils import HttpUtils

class TestOrder(TestCase):
    def setUp(self):
        self.r = HttpUtils()

    def tearDown(self):
        result = self.result
        self.r.logJson(jsonStr=result.text)
        assert result.status_code == 200, "请求状态码应为 200"

    def test_list(self):
        """订单列表接口
        """
        company_id = '025c647c-9281-486f-8c72-2bf18a2c1f5d'
        order_no = ''
        effective_time = ''
        failure_time = ''
        start_time = '2019-08-26'
        end_time = '2019-08-28'

        url = Order.LIST + f'?page=1&pageSize=10&companyId={company_id}&orderNo={order_no}' \
            f'&effectiveTime={effective_time}&failureTime={failure_time}&startTime={start_time}&endTime={end_time}'
        self.result = self.r.get(url)

    def test_detail(self):
        """订单详情
        """
        order_id = '097b769d-f22e-4ff7-88e1-32f55d3f643d'
        url = Order.DETAIL + f"{order_id}?page=1&pageSize=10&type=4"
        self.result = self.r.get(url)

if __name__ == "__main__":
    run_tests([
        # TestOrder("test_list"),
        TestOrder("test_detail")
    ])


import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
from spotipy.exceptions import SpotifyException
import os

class SpotifyDataAccess:
    """ Data access class for Spotify API """
    def __init__(self) -> None:
        api_id = os.environ.get("spotify_api_id")
        api_secret = os.environ.get("spotify_api_secret")
        self.sp = spotipy.Spotify(
            auth_manager=SpotifyClientCredentials(
                client_id=api_id, client_secret=api_secret
            )
        )

    def autocomplete_search(self, query: str):
        """ Searches for 10 tracks that match the search query for search autocomplete. """
        results = self.sp.search(q=query, limit=10)
        suggestions = []

        for track in results["tracks"]["items"]:
            artists = ", ".join([artist["name"] for artist in track["artists"]])
            mapped_song = {"artists": artists, "name": track["name"], "id": track["id"]}
            suggestions.append(mapped_song)

        return suggestions

    def fetch_song_genres(self, artists_ids: list):
        """ Fetches the Spotify API for genres of provided song's artists. """
        genres = set()
        for artist_id in artists_ids:
            artist = self.sp.artist(artist_id)
            song_genres = artist["genres"]
            genres.update(set(song_genres))
        return genres

    def fetch_song(self, song_id):
        """ Fetches the Spotify API for a song with given Spotify song ID and returns the audio features relevant for recommendations. """
        features = self.sp.audio_features([song_id])[0]
        try:
            song_data = self.sp.track(song_id)
        except SpotifyException:
            return None
        artists_ids = [artist["id"] for artist in song_data["artists"]]
        artists_names = set([artist["name"] for artist in song_data["artists"]])
        song_genres = self.fetch_song_genres(artists_ids)
        self.fetch_song_genres(artists_ids)

        song_obj = {
            "valence": features["valence"],
            "year": int(song_data["album"]["release_date"].split("-")[0]),
            "acousticness": features["acousticness"],
            "artists": artists_names,
            "danceability": features["danceability"],
            "duration_ms": song_data["duration_ms"],
            "energy": features["energy"],
            "id": song_id,
            "instrumentalness": features["instrumentalness"],
            "liveness": features["liveness"],
            "mode": features["mode"],
            "name": song_data["name"],
            "popularity": song_data["popularity"],
            "speechiness": features["speechiness"],
            "tempo": features["tempo"],
            "genres": set(song_genres),
        }
        return song_obj


import os
import pandas as pd
from components.data_validation import prediction_data_validation

class data_validation_and_ingestion:
    def __init__(self,path,logger):
        self.logger=logger
        self.path=path
        self.raw_data=prediction_data_validation(self.path,self.logger)

    def validation(self):
        try:
            self.logger.log('Starting Data Validation')

            #validating file extension
            if self.raw_data.validate_file_extension()==False:
                self.logger.log('File extension validation failed')
                return False

            #validating number of columns
            elif self.raw_data.validate_columns_length()==False:
                self.logger.log('Number of columns validation failed')
                return False

            #validating column attributes
            elif self.raw_data.validate_column_attributes()==False:
                self.logger.log('Column attributes validation failed')
                return False

            #validating missing values
            elif self.raw_data.validate_missing_values()==False:
                self.logger.log('Missing values validation failed')
                return False

            else:
                self.logger.log('Data Validation Completed Successfully')
                return True

        except Exception as e:
            self.logger.log('ERROR : Unable to execute data validation : '+str(e))
            self.logger.close()
            raise e

    def ingestion(self):
        try:
            self.logger.log('Starting data ingestion')
            pred_data_path=os.path.join(self.path,'Final_Data')
            src_path=os.path.join(self.path,'Good_Raw')

            if not os.path.exists(pred_data_path):
                os.makedirs(pred_data_path)

            pred_data=pd.DataFrame()

            for file in os.listdir(src_path):
                csv=pd.read_csv(os.path.join(src_path,file))
                pred_data=pd.concat([pred_data,csv],axis=0)
            pred_data=pred_data.reset_index(drop=True)
            file_name='StoreSales_Prediction_Input.csv'
            pred_data.to_csv(os.path.join(pred_data_path,file_name),index=False)
            self.logger.log('Data ingestion completed. Final prediction data stored at '+pred_data_path)

        except Exception as e:
            self.logger.log('ERROR : Unable to perform data ingestion : '+str(e))
            self.logger.close()
            raise e


from django.urls import path

from .views import movies_list, add_movie, movie_detail, seat_status, book_seat, my_bookings, process_payment
app_name = 'movies'

urlpatterns = [
    path('add-movie/', add_movie, name='add_movie'),
    path('list/', movies_list, name='movies_list'),
    path('movie/<int:movie_id>/', movie_detail, name='movie_detail'),
    path('<int:movie_id>/seat-status/', seat_status, name='seat_status'),
    path('book_seat/<int:movie_id>/', book_seat, name='book_seat'),
    path('my-bookings/', my_bookings, name='my_bookings'),
    path("process_payment/", process_payment, name="process_payment"),

]


import requests
headers ={
'Content-Type':'application/x-www-form-urlencoded',
'Accept':'application/json'
}

data = {
     'client':'AQUI_SU_CLIENT',
     'key':'AQUI_SU_KEY',
     'name-url':'AQUI_NOMBRE_DE_URL',
     'since':'Fecha inicial YYYY-MM-DD',
     'until':'Fecha final YYYY-MM-DD'
}

r = requests.post('https://www.onurix.com/api/v1/url/short-statistic', headers = headers, data = data)

print(r.json())