# 두 정수 사이의 합
# https://programmers.co.kr/learn/courses/30/lessons/12912

def solution(a, b):
    answer = 0

    amount = abs(b - a) + 1
    answer = (a+b)*amount//2

    return answer

def abs(n):
    if(n<0):
        return -n
    else:
        return n


import logging
import os

from youtube_to_pdf.utils.type import get_file_md5sum

def move_video_to(internal_video_path, destination_dir):
    # Get the Video's MD5 sum and ensure that it does not exist already
    video_md5sum = get_file_md5sum(internal_video_path)
    expected_video_path = os.path.join(destination_dir, video_md5sum + ".mp4")
    if not os.path.exists(destination_dir):     # create destination_dir
        os.makedirs(destination_dir)
    if not os.path.exists(expected_video_path):     # move file if not exists on destination
        os.rename(internal_video_path, expected_video_path)
    else:
        logging.debug("File with md5sum '{}' already exists on destination folder"
                      .format(video_md5sum))
    return video_md5sum


from django.shortcuts import render
from django.views.generic import TemplateView

from rest_framework.response import Response
from rest_framework.decorators import api_view
from rest_framework import status

from .models import Post
from .serializers import *

@api_view(['GET', 'POST'])
def posts(request):
    print(request.__dict__)
    print('method: ', request.method)
    print('data: ', request.data)
    if request.method == 'GET':
        posts = Post.objects.all()
        serializer = PostSerializer(posts, many=True)
        return Response({'data': serializer.data}, headers={'Access-Control-Allow-Origin': '*'})
    elif request.method == 'POST':
        post = Post()
        post.text = request.data['text']
        post.save()
        return Response(status=status.HTTP_200_OK, headers={'Access-Control-Allow-Origin': '*'})

@api_view(['DELETE'])
def delete_post(request, post_id):
    try:
        post = Post.objects.get(id=post_id)
    except:
        return Response(status=status.HTTP_400_BAD_REQUEST, headers={'Access-Control-Allow-Origin': '*'})
    post.delete()
    return Response(status=status.HTTP_200_OK, headers={'Access-Control-Allow-Origin': '*'})

@api_view(['GET'])
def like_post(request, post_id):
    if request.method == 'GET':
        try:
            post = Post.objects.get(id=post_id)
        except:
            return Response(status=status.HTTP_400_BAD_REQUEST)

    setattr(post, 'likesCount', post.likesCount + 1)
    post.save()
    return Response(post.likesCount, status.HTTP_200_OK)

class AppView(TemplateView):
    template_name = 'default.html'


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

import functools
import contextlib

import blinker

load = blinker.Signal()
ignore_load = blinker.Signal()
lazy_load = blinker.Signal()
eager_load = blinker.Signal()
touch = blinker.Signal()

def get_worker(*args, **kwargs):
    return blinker.ANY

def signalify(signal, func, parser=None, **context):
    @functools.wraps(func)
    def wrapped(*args, **kwargs):
        ret = func(*args, **kwargs)
        signal.send(
            get_worker(),
            args=args,
            kwargs=kwargs,
            ret=ret,
            context=context,
            parser=parser,
        )
        return ret
    return wrapped

def designalify(signal, func):
    @functools.wraps(func)
    def wrapped(*args, **kwargs):
        with ignore(signal):
            return func(*args, **kwargs)
    return wrapped

@contextlib.contextmanager
def ignore(signal, sender=None):
    sender = sender or get_worker()
    receivers = list(signal.receivers_for(sender))
    for receiver in receivers:
        signal.disconnect(receiver, sender=sender)
    try:
        yield
    finally:
        for receiver in receivers:
            signal.connect(receiver, sender=sender)


chips=input()
chips=list(map(int,chips.split(',')))
dict={}
for i in chips:
    dict[i%2]=dict.get(i%2,0)+1
if(len(dict)==2):
    if dict[0]<dict[1]:
        print(dict[0])
    else:
        print(dict[1])
else:
    print(0)


"""
Code of Ayush Tiwari
Codechef: ayush572000
Codeforces: servermonk

"""
import sys
input = sys.stdin.buffer.readline

def solution():
    n,k=map(int,input().split())
    l=list(map(int,input().split()))
    l.sort()
    val=[0]*1000001
    op=[0]*1000001
    m=2e9
    for i in range(n):
        val[l[i]]+=1
    for i in range(n):
        cnt=0
        x=l[i]
        while x>0:
            if val[x]>=k:
                m=min(m,op[x])
            cnt+=1
            x//=2
            op[x]+=cnt
            val[x]+=1

    print(m)
solution()


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

"""
@author: Dariusz Koncewicz
@email: d.koncewicz@sdacademy.pl
@site: www.dariuszkoncewicz.pl
"""

class Drzewo:

    nazwa = 'Sosna'
    wiek = 40
    wysokosc = 25

drzewo_1 = Drzewo()
drzewo_2 = Drzewo()

# %%
print(id(drzewo_1))
print(id(drzewo_2))

# %%
dir(drzewo_1)

# %%
drzewo_1.nazwa
drzewo_1.wiek
drzewo_1.wysokosc

# %%
drzewo_2.nazwa
drzewo_2.wiek

# %%
drzewo_1.stan = 'dobry'

print(dir(drzewo_2))

# %%
Drzewo.miejsce = 'las'

# %%
# print(dir(drzewo_2))
# print(drzewo_2.miejsce)

drzewo_2.miejsce = 'park'

print(drzewo_2.miejsce)


N,K = list(map(int,input().split()))
PRR = list(map(int,input().split()))

# N = 10
# K = 4
# PRR = [17, 13, 13, 12, 15, 20, 10, 13, 17, 11]
#
# N = 5
# K = 3
# PRR = [1, 2, 2, 4, 5]

def calculate(n, k, prr):

    sumarr = []
    for i in range(n):
        if len(sumarr) == 0:
            sumarr.append(prr[0])
        else:
            sumarr.append(sumarr[-1] + prr[i])

    maxSum = []

    for i in range(k-1,n):

        if i - k < 0:
            sss = sumarr[i] - 0
        else:
            sss = sumarr[i] - sumarr[i - k]
        maxSum.append(sss)

    print((k+max(maxSum))/2)

calculate(N, K, PRR)


import shutil
import tempfile
import os

from .build import Buildfile

class Runner(object):
    """The runner is responsible for taking a manifest and executing it."""

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

    def _write_build_script(self, dir, manifest):
        """Write out script for the build phase."""
        buildfile = Buildfile()
        for step in manifest.build:
            buildfile.cmd(step)
        with open(os.path.join(dir, 'build.sh'), 'w') as fp:
            fp.write(buildfile.build())

    def execute(self, manifest):
        dir = tempfile.mkdtemp()
        try:
            self._write_build_script(dir, manifest)
            container = self.container_factory(
                manifest.image, binds={'/home/doozer': dir})
            container.start('/home/doozer/build.sh')
            return container.wait()
        finally:
            shutil.rmtree(dir)


def findAndSet(grid,level):
    cnt=0
    for n, m in level:
        for x_off, y_off in (1, 0), (-1, 0), (0, 1), (0, -1):
            x = n + x_off
            y = m + y_off
            if x < 0 or x >= len(grid) or y < 0 or y >= len(grid[0]):
                continue
            else:
                if grid[x][y] == 1:
                    level.append([x, y])
                    grid[x][y] = 2
                    cnt+=1
    return grid, level, cnt

def init(grid,hits):
    for p in hits:
        i = p[0]
        j = p[1]
        if grid[i][j] == 1:
            grid[i][j] = -1
    #先把触顶的砖块值改为2
    level = []
    for k in range(len(grid)):
        if grid[0][k] == 1:
            level.append([0, k])
            grid[0][k] = 2
    #寻找最后仍能保持不落下的砖块，并将其标记改为2
    for n, m in level:
        for x_off, y_off in (1, 0), (-1, 0), (0, 1), (0, -1):
            x = n + x_off
            y = m + y_off
            if x < 0 or x >= len(grid[0]) or y < 0 or y >= len(grid):
                continue
            else:
                if grid[x][y] == 2:
                    level.append([x, y])
    #
    res=[]
    level=[]
    hits=list(reversed(hits))
    for ht in hits:
        n,m=ht[0],ht[1]
        if grid[n][m]==0:
            continue
        else:
            grid[n][m] = 2
            level.append([n, m])
            grid, level, cnt = findAndSet(grid, level)
            res.append(cnt)
    return res

if __name__=="__main__":
    grid=eval(input())
    hits=eval(input())
    ans=init(grid,hits)
    print(ans)


"""
Input and validation utilities
"""

import random
import uuid
from datetime import datetime, date, time
from model.quiz_model import QuizResult

def input_pos_int(question):
    """
    function to ensure positive integer input from user
    """
    while True:
        try:
            number = int(input(question))
            if number < 1:
                print('Enter a positive number: ')
            else:
                return number
        except ValueError:
            print('Please enter a number: ')

def header(text):
    """
    function to add some pizzazz to printing out things to user in terminal
    """
    stars = len(text) * '*'
    print(f'\n{stars}\n{text}\n{stars}\n')

def validate_topic_chosen(topics):
    """
    function to validate topic from user
    """
    print('\n')
    topic_requested = input('Please select the number of the topic would you like to be quizzed: ')
    print('\n')
    while topic_requested.isnumeric() is False or int(topic_requested) > len(topics) or int(topic_requested) == 0: # validation based on keys and using .lower() to make sure case isn't a cause of user input being rejected
        print('Please only choose from one of the below listed categories\n')
        # for count, topic in enumerate(topics):
        #     print(count+1, topic)
        count = 1
        for topic, topic_count in topics.items():
            print(f'{count}: {topic} ({topic_count} questions)')
            count = count + 1
        print('\n')
        topic_requested = input('Try again and please select from the topics by number: ')
        print('\n')
    topic_requested = int(topic_requested)-1
    return topic_requested

def generate_user_id():
    """
    function to generate a unique user ID
    """
    user_id = str(uuid.uuid4())
    return user_id

def get_time():
    """
    function prints current time (start of quiz time) and returns it as a timestamp for tracking how much time user spent on question
    """
    current_time = datetime.now().timestamp()
    header(f'Quiz is starting at {datetime.fromtimestamp(round(current_time))}')
    return current_time

def show_randomized_answers(question):
    """
    function to take list of answers for a particular quiz question and print them in a random order
    """
    answers = [question.correct_answer, question.wrong_answer_1, question.wrong_answer_2, question.wrong_answer_3]
    random.shuffle(answers)
    for q_num, a in enumerate(answers):
        print(f'{q_num+1}:{a}')
    return answers

def get_user_answer():
    """
    function to validate user response is within range of possible answers
    """
    user_answer = input('What is your answer? ')
    while user_answer.isnumeric() is False or int(user_answer) not in range(1,5):
        print('\n')
        user_answer = input('Please try again and select the number answer you believe is correct: ')
    user_answer = int(user_answer)-1
    print('\n')
    return user_answer

def check_if_correct(user_guess, correct_answer):
    """
    function to check user answer against correct answer
    """
    if user_guess == correct_answer:
        print('Correctamundo!')
        return True
    else:
        print(f'I\'m deeply sorry but the correct answer is {correct_answer}')
        return False


from django.urls import path

from . import views

# recipes:recipe
app_name = 'recipes'

urlpatterns = [
     path('', views.RecipeListViewHome.as_view(), name='home'),
     path('recipes/search/', views.RecipeListViewSearch.as_view(), name='search'),  # noqa
     path('recipes/tags/<slug:slug>', views.RecipeViewTag.as_view(), name='tag'),  # noqa
     path('recipes/theory', views.theory, name='theory'),
     path('recipes/api/v1/',
          views.RecipeListViewHomeAPI.as_view(), name='api_home'),
     path('recipes/category/<int:category_id>/',
          views.RecipeListViewCategory.as_view(), name='category'),
     path('recipes/<int:recipe_id>/',
          views.RecipeDetailViewDetail.as_view(), name='recipe'),
     path('recipes/api/v1/<int:recipe_id>/',
          views.RecipeDetailViewDetailAPI.as_view(), name='api_detail'),

]


import math
import torch
import time
from src.tools.logger import MeanSigmaMetricLogger
from collections import OrderedDict

def list_to_dict(l, idx, keep_one=False):
    result = OrderedDict()
    for x in l:
        if x[idx] not in result:
            result[x[idx]] = []
        y = x[:idx] + x[idx + 1:]
        if not keep_one and len(y) == 1:
            y = y[0]
        result[x[idx]].append(y)
    return result

class ForwardPassTimeChecker(torch.nn.Module):
    def __init__(self, module, skip=2):
        super(ForwardPassTimeChecker, self).__init__()
        self.module = module

        self.module_start_times = []
        self.module_costs = []
        from collections import defaultdict
        self.started_module2count = defaultdict(int)

        def forward_pre_hooker(m, i):
            self.module_start_times.append((m, time.time()))
            self.started_module2count[m] += 1

        def forward_hooker(m, i, o):
            end_time = time.time()
            start_m, start_time = self.module_start_times.pop()
            self.started_module2count[start_m] -= 1
            assert start_m == m
            if self.started_module2count[start_m] == 0:
                # in some cases, a module will call itself multiple times, and
                # we only count the one which is the most outside
                self.module_costs.append((m, end_time - start_time))

        self.meters = MeanSigmaMetricLogger(delimiter="\n")

        for _, m in self.module.named_modules():
            m.register_forward_pre_hook(forward_pre_hooker)
            m.register_forward_hook(forward_hooker)

        self.module_to_name = dict((m, n) for n, m in self.module.named_modules())
        self.skip = skip

    def forward(self, *args, **kwargs):
        self.started_module2count.clear()
        self.module_start_times.clear()
        self.module_costs.clear()

        result = self.module(*args, **kwargs)
        if self.skip <= 0:
            module_to_costs = list_to_dict(self.module_costs, 0)
            for m, cs in module_to_costs.items():
                c = sum(cs)
                name = self.module_to_name[m]
                self.meters.update(**{name: c})
        else:
            self.skip -= 1
        return result

    def get_time_info(self):

        info = {'meters': "Not implemented" }
        return info


#!usr/bin/python
import sys
import time

ATTEMPT_LOG = '/home/ackbar/cowrie/cowrie_extension/attempt_log/attempt_log.txt'
RETURN_TIME = 3600

# Delete logs flagged to deletition
def delete_marked_lines(filename=ATTEMPT_LOG):
    with open(filename, 'r') as f:
        lines = f.readlines()
    fw = open(filename, 'w')
    dummy_str = ''
    for line in lines:
        if 'FLAG_DELETE' not in line:
            dummy_str += line
    fw.write(dummy_str)
    fw.close()

# Flags log to delete
def mark_for_deletition(index, filename=ATTEMPT_LOG):
    with open(filename, 'r') as fr:
        lines = fr.readlines()
    fw = open(filename, 'w')
    dummy_str = ''
    for indexf, line in enumerate(lines):
        if indexf < index or indexf > index + 2:
            dummy_str += line
        else:
            dummy_str += 'FLAG_DELETE '
            dummy_str += line
    fw.write(dummy_str)
    fw.close()

# Main function that will mark logs for deletition
def update():
    f = open(ATTEMPT_LOG).readlines()
    now = time.time()
    for index, line in enumerate(f):
        if (index % 3) == 1 and now - float(line.strip('\n')) >= RETURN_TIME:
            mark_for_deletition(index - 1)
    delete_marked_lines()

update()


n, m = 1000, 1000

pos = [[False for i in range(m)] for j in range(n)]

rope = [[500, 500] for i in range(10)]

(x, y) = rope[9]
pos[x][y] = True

def show_state(rope):
    for i in range(n):
        for j in range(m):

            S = "."

            for k in range(len(rope) - 1, -1, -1):

                if i == rope[k][0] and j == rope[k][1]:
                    if k != 0:
                        S = str(k)
                    else:
                        S = "H"
            print(S, end="")
        print()
    print()

def move_rope(xH, yH, xT, yT):
    if xH - xT > 1:
        xT += 1

        if yH > yT:
            yT += 1
        elif yH < yT:
            yT -= 1
    elif xH - xT < -1:
        xT += -1

        if yH > yT:
            yT += 1
        elif yH < yT:
            yT -= 1

    if yH - yT > 1:
        yT += 1

        if xH > xT:
            xT += 1
        elif xH < xT:
            xT -= 1
    elif yH - yT < -1:
        yT += - 1

        if xH > xT:
            xT += 1
        elif xH < xT:
            xT -= 1

    return (xT, yT)

show_state(rope)

# Using readlines()
file1 = open('input', 'r')
Lines = file1.readlines()

i = 0

# Strips the newline character
for line in Lines:
    move = line.strip().split(" ")

    print(f"== {move[0]} {move[1]} ==")

    for i in range(int(move[1])):
        x, y = rope[0]

        # move the head
        if move[0] == "U":
            if x - 1 < 0:
                print("out")
                break
            rope[0][0] = max(0, x - 1)
        elif move[0] == "D":
            if x + 1 > n - 1:
                print("out")
                break
            rope[0][0] = min(n - 1, x + 1)
        elif move[0] == "R":
            if y + 1 > m - 1:
                print("out")
                break
            rope[0][1] = min(m - 1, y + 1)
        elif move[0] == "L":
            if y - 1 < 0:
                print("out")
                break
            rope[0][1] = max(0, y - 1)

        for i in range(len(rope) - 1):
            # move knots i+1 relative to i
            (rope[i + 1][0], rope[i + 1][1]) = move_rope(rope[i][0], rope[i][1], rope[i + 1][0], rope[i + 1][1])

        # print(rope)
        (x, y) = rope[9]
        pos[x][y] = True

        # show_state(rope)

score = 0

for i in range(n):
    for j in range(m):

        if pos[i][j]:
            # print("#", end="")
            score += 1
        # else:
        # print(".", end="")
    # print()

print(score)


import re

def execute(s, t):
    if sorted(s) == sorted(t):
        return 'true'
    else:
        return 'false'

str = input()
li = str.split(',')
s = li[0][5:len(li[0]) - 1]
t = li[1][6:len(li[1]) - 1]
print(execute(s, t))


# Exercise 14: Tax Calculator
# 2019-05-24
# Notes: If user is in Wisconsin charge tax, else no tax

# Declare and assign variables and constants
tax_rate = .055
user_order = float(input("What is the order amount? "))
user_state = str(input("What is the state? "))

# Charge tax if Wisconsin
if user_state == 'WI':
    tax_amount = round(user_order * tax_rate, 2)
    total_amount = user_order + tax_amount
    message_WI = f'The subtotal is ${round(user_order, 2)}. \nThe tax is ${tax_amount}. \nThe total is ${total_amount}.'
    print(message_WI)

message_output = f'The total is ${round(user_order, 2)}.'

print(message_output)


class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        sum = nums[0]
        sub_sum = nums[0]

        for i in range(1, len(nums)):
            sub_sum = max(nums[i], nums[i]+sub_sum)
            sum = max(sum, sub_sum)

        return sum


# https://www.acmicpc.net/problem/15649
# n,m - 1~n 까지 m개의 수열종류를 리턴하라 # 백트래킹
import sys
n, m = map(int, sys.stdin.readline().split())

num_list = [i + 1 for i in range(n)]
checker = [False] * n
result = []

def dfs(s):
    if s == m:
        print(*result)
        return
    for i in range(0, n):
        if checker[i]:
            continue
        checker[i] = True
        result.append(num_list[i])
        dfs(s + 1)
        print(result)
        result.pop()
        checker[i] = False

dfs(0)

백준/단계별뿌시기/14단계(백트래킹)/n과m.py


# Should return triangle type:
#  0 : if triangle cannot be made with given sides
#  1 : acute triangle
#  2 : right triangle
#  3 : obtuse triangle

def triangle_type(a, b, c):
    a, b, c = sorted([a, b, c])
    if c >= a + b: return 0
    c = c * c
    a = a * a
    b = b * b
    if c == a + b: return 2
    return 1 if c < a + b else 3


import os

with open('employees.txt', 'r') as my_file:
    recipients = my_file.read().splitlines()

with open('template.txt', 'r') as my_file:
    template = my_file.read()

if not os.path.exists('christmasCards'):
    os.mkdir('christmasCards')

for recipient in recipients:

    card = template.replace('NAME', recipient)
    card_file = f'christmasCards/{recipient}.txt'
    with open(card_file, mode='w') as my_file:
        my_file.write(card)

    print(f'Christmas card created for: {recipient}.')


# A class for the columns within the board
class Column:

    def __init__(self):
        self.total = 0
        self.cards = [None,None,None,None,None]
        self.aces = 0
        self.acesUsed = 0

    # Adds a card to the column
    def addCard(self, card):
        # Allows aces to be placed as either 1 or 11
        if card[0] == 'A':
            if self.total + 11 > 21:
                cardValue = 1
                self.acesUsed += 1
            else:
                cardValue = 11

        elif card[0] == 'Q' or card[0] == 'K' or (card[0] == 'J' and card[1] == 'r'):
            cardValue = 10

        elif card[0] == 'J' and card[1] == 'b':
            cardValue = 21 - self.total

        else:
            cardValue = card[0]
        self.total = self.total + int(cardValue)

        # Allows aces in a column to update from an 11 to a 1
        self.aces = self.cards.count(('A', 'b')) + self.cards.count(('A', 'r'))
        while self.total > 21 and self.aces > self.acesUsed:
            self.total -= 10
            self.acesUsed += 1

        # Adds new card and removes a blank placeholder
        self.cards.insert(5,card)
        self.cards.pop(0)

    # Checks if a column is bust (>21)
    def isBust(self):
        if self.total > 21:
            self.cards = [None,None,None,None,None]
            self.total = 0
            self.acesUsed = 0
            return True
        else:
            return False

    # Checks if a full column adds to 21
    def isFull21(self):
        if len(self.cards) == 5 and not (None in self.cards) and self.total == 21:
            self.cards = [None,None,None,None,None]
            self.total = 0
            self.acesUsed = 0
            return True
        else:
            return False

    # Checks if a cloumn adds to 21
    def is21(self):
        if self.total == 21:
            self.cards = [None,None,None,None,None]
            self.total = 0
            self.acesUsed = 0
            return True
        else:
            return False

    # Checks if a column is full
    def isFull(self):
        if len(self.cards) == 5 and not (None in self.cards):
            self.cards = [None,None,None,None,None]
            self.total = 0
            self.acesUsed = 0
            return True
        else:
            return False

# A class for the game board
class Board:

    def __init__(self):
        self.busts = 0
        self.points = 0
        self.streak = 0

        self.col1 = Column()
        self.col2 = Column()
        self.col3 = Column()
        self.col4 = Column()

        self.columns = [self.col1, self.col2, self.col3, self.col4]

    # Outputs the board to the terminal
    def output(self):
        print('\n')
        print(f'|{self.col1.total}|             |{self.col2.total}|             |{self.col3.total}|             |{self.col4.total}|',
              f'|{self.col1.cards[0]}|          |{self.col2.cards[0]}|          |{self.col3.cards[0]}|          |{self.col4.cards[0]}|',
              f'|{self.col1.cards[1]}|          |{self.col2.cards[1]}|          |{self.col3.cards[1]}|          |{self.col4.cards[1]}|',
              f'|{self.col1.cards[2]}|          |{self.col2.cards[2]}|          |{self.col3.cards[2]}|          |{self.col4.cards[2]}|',
              f'|{self.col1.cards[3]}|          |{self.col2.cards[3]}|          |{self.col3.cards[3]}|          |{self.col4.cards[3]}|',
              f'|{self.col1.cards[4]}|          |{self.col2.cards[4]}|          |{self.col3.cards[4]}|          |{self.col4.cards[4]}|',
              sep='\n')

        print('\nBusts:', self.busts)
        print('Points:', self.points, '\n')


import argparse
import pdb
import sys
import torch
import torch.nn as nn
import torch.nn.functional as F
import argparse
import pdb
import subprocess as sp
import requests.api
import re
import multiprocessing
import sys
import datetime
import numpy as np

cuda = torch.device('cuda')
cpu = torch.device('cpu')
torch.cuda.synchronize(device=cuda)

class mnist(nn.Module):

    def __init__(self, layerGPU, numInputChannels, numOutputChannels, K):
        super(mnist, self).__init__()
        self.layerGPU = layerGPU
        self.numInputChannels = numInputChannels
        self.numOutputChannels = numOutputChannels
        self.K = K

        assert(layerGPU <= 3 and layerGPU >= 1)
        assert(isinstance(layerGPU, int))

        if (self.layerGPU==1):
            self.layer1 = nn.ConvTranspose2d(in_channels=10, out_channels=32, kernel_size=(4,4), stride=2, padding=0).to(device=cuda)
            self.activation1 = nn.BatchNorm2d(32)
            self.ch = self.numOutputChannels # ch --> what the number of input channels for the next layer will be
        else:
            self.layer1 = nn.ConvTranspose2d(in_channels=10, out_channels=32, kernel_size=(4,4), stride=2, padding=0)
            self.activation1 = nn.BatchNorm2d(32)
            self.ch = 32 # ch --> what the number of input channels for the next layer will be

        self.out1 = nn.ReLU()

        if (self.layerGPU==2):
            self.layer2 = nn.ConvTranspose2d(in_channels=32, out_channels=32, kernel_size=(6,6),stride=2, padding=0).to(device=cuda)
            self.activation2 = nn.BatchNorm2d(32)
            self.ch=self.numOutputChannels # ch --> what the number of input channels for the next layer will be
        else:
            self.layer2 = nn.ConvTranspose2d(in_channels=32, out_channels=32, kernel_size=(6,6),stride=2, padding=0)
            self.activation2 = nn.BatchNorm2d(32)
            self.ch=32 # ch --> what the number of input channels for the next layer will be

        self.out2 = nn.ReLU()

        if (self.layerGPU==3):
            self.layer3 = nn.ConvTranspose2d(in_channels=32, out_channels=1, kernel_size=(6,6), stride=2, padding=0).to(device=cuda)
        else:
            self.layer3 = nn.ConvTranspose2d(in_channels=32, out_channels=1, kernel_size=(6,6), stride=2, padding=0)

        self.activation3 = nn.Sigmoid()

    def forward(self, x):

        if (self.layerGPU==1):
            out1_ = self.layer1(x.to(device=cuda))
            out1_ = self.activation1(out1_.to(device=cpu))
        else:
            out1_ = self.layer1(x)
            out1_ = self.activation1(out1_)

        out1 = self.out1(out1_)

        if (self.layerGPU==2):
            out2_ = self.layer2(out1.to(device=cuda))
            out2_ = self.activation2(out2_.to(device=cpu))
        else:
            out2_ = self.layer2(out1)
            out2_ = self.activation2(out2_)

        out2 = self.out2(out2_)

        if (self.layerGPU==3):
            out3_ = self.layer3(out2.to(device=cuda))
            out3 = self.activation3(out3_.to(device=cpu))
        else:
            out3_ = self.layer3(out2)
            out3 = self.activation3(out3_)

        return(out3.detach().numpy())

def setToZero(model, layer, percentage):
    # elementDict = model.state_dict()
    # for thing in elementDict:
    #     print(thing, elementDict[thing].shape)
    percentage = percentage*0.01
    if percentage <= 0:
        return None
    name = f"layer{layer}.weight"
    elementDict = model.state_dict()

    for param_tensor in elementDict:
        print(param_tensor, "\t", elementDict[param_tensor].size())
    WeightTensornumber = np.prod(np.array(elementDict[name].shape))
    newLayer = np.random.random_sample(WeightTensornumber)
    layerQuantile = np.quantile(newLayer, percentage)
    binaryAns = newLayer < layerQuantile
    newLayer[binaryAns] = 0

    sparseTensor = torch.Tensor(newLayer.reshape(np.array(elementDict[name].shape)))
    elementDict[name] = sparseTensor
    # elementDict[layer] = torch.from_numpy(sparseTensor).float()
    model.load_state_dict(elementDict)
    return model

def runMnist(batchSize, layer, sparcity):

    if layer == 1:
        net = mnist(1,10,32,3)
        # layerWeightName = f"layer{layer}.weight"
        # print(layerWeightName)
        # setToZero(net,layerWeightName, sparcity)
        setToZero(net, layer, sparcity)
        inp = torch.rand(batchSize, 10, 1, 1)
        print("execute")
        image = net(inp)

    if layer == 2:
        net = mnist(2,32,32,3)
        # layerWeightName = f"layer{layer}.weight"
        # print(layerWeightName)
        # setToZero(net,layerWeightName, sparcity)
        setToZero(net, layer, sparcity)
        inp = torch.rand(batchSize, 10,1,1)
        print("execute")
        image = net(inp)

    if layer == 3:
        net = mnist(3,32,1,5)
        # layerWeightName = f"layer{layer}.weight"
        # print(layerWeightName)
        # setToZero(net,layerWeightName, sparcity)
        setToZero(net, layer, sparcity)
        inp = torch.rand(batchSize, 10,1,1)
        # print(inp.shape)
        print("execute")
        image = net(inp)

    test = net.state_dict()
    print(test[f"layer{layer}.weight"])

def main():

    # Get input parameters
    parser = argparse.ArgumentParser(description='TorchDCNN for deployment on GPU')
    parser.add_argument('layer', help='layer of model')
    parser.add_argument('Percent_Sparcity', help="'mnist' or 'celeba'")
    parser.add_argument('iteration')

    # Convert to Python variables
    args = parser.parse_args()
    variables = vars(args)
    layer = int(variables["layer"])
    temp = float(variables["Percent_Sparcity"])
    iterrr = float(variables["iteration"])

    # print(type(temp), type(0.5))
    print(f"iteration:{iterrr} mnist layer:{layer}, sparcity:{temp}")

    runMnist(1, layer, temp)

if __name__ == '__main__':
    main()


#마지막 풀이
# 앞으로 for문 뒤로 for문 쓰
# T = int(input())
T =1
for _ in range(T):
    # K = int(input())
    K = 2
    # WHEEL = [list(map(int, input().split())) for i in rnage(4)]
    WHEEL = [[0, 0, 1, 0, 0, 1, 0, 0], [1, 0, 0, 1, 1, 1, 0, 1], [0, 0, 1, 0, 1, 1, 0, 0], [0, 0, 1, 0, 1, 1, 0, 1]]
    # INFO = [list(map(int, input().split())) for i in range(K)]
    INFO = [[1,1],[3,-1]]
    # 오른쪽 검사 부터 만들어 보자
    print(WHEEL)
    answer = 0
    for idx, direction in INFO:
        MOVE = [[idx,direction]]
        idx -= 1
        for new_idx in range(3):
            if new_idx+idx+1 > 3: break
            if WHEEL[idx+new_idx][2]+WHEEL[idx+new_idx+1][6] == 1:
                MOVE.append([idx+new_idx+2,direction*((-1)**(new_idx+1))])
            else: break

        for new_idx in range(3):
            if idx-new_idx-1 < 0: break
            if WHEEL[idx-new_idx][6]+WHEEL[idx-new_idx-1][2] == 1:
                MOVE.append([idx-new_idx,direction*((-1)**(new_idx+1))])
            else: break

        for move_idx, move_dir in MOVE:
            move_idx -= 1
            if move_dir==1: WHEEL[move_idx] = [WHEEL[move_idx][-1]]+WHEEL[move_idx][:-1]
            else: WHEEL[move_idx] = WHEEL[move_idx][1:]+[WHEEL[move_idx][0]]
    if WHEEL[0][0]:answer += 1
    if WHEEL[1][0]:answer += 2
    if WHEEL[2][0]:answer += 4
    if WHEEL[3][0]:answer += 8
    print(answer)
'''
wheel = [[0, 0, 1, 0, 0, 1, 0, 0], [1, 0, 0, 1, 1, 1, 0, 1], [0, 0, 1, 0, 1, 1, 0, 0], [0, 0, 1, 0, 1, 1, 0, 1]]
info = [[1, 1], [3, -1]]
w_set1, w_set2, w_set3, w_set4 = set(), set(), set(), set()
for idx, data in enumerate(zip(wheel[0], wheel[1], wheel[2], wheel[3])):
    x,y,z,w = data
    if x==1: w_set1.add(idx)
    if y==1: w_set2.add(idx)
    if z==1: w_set3.add(idx)
    if w==1: w_set4.add(idx)
wheel_list = [w_set1, w_set2, w_set3, w_set4]

for start_idx, direction in info:
    start_idx -= 1
    move, RIGHT_FLAG, LEFT_FLAG = [[start_idx,direction]], True, True
    for move_idx in range(1,4):
        if start_idx+move_idx <len(wheel_list) and RIGHT_FLAG:
            if ((6 in wheel_list[start_idx+move_idx]) and (2 not in wheel_list[start_idx+move_idx-1])) or ((6 not in wheel_list[start_idx+move_idx]) and (2 in wheel_list[start_idx+move_idx-1])):
                move.append([start_idx+move_idx, direction*((-1)**move_idx)])
            else: RIGHT_FLAG = False
        if start_idx-move_idx > -1 and LEFT_FLAG:
            if ((2 in wheel_list[start_idx-move_idx]) and (6 not in wheel_list[start_idx-move_idx+1])) or ((2 not in wheel_list[start_idx-move_idx]) and (6 in wheel_list[start_idx-move_idx+1])):
                move.append([start_idx-move_idx, direction*((-1)**move_idx)])
            else:LEFT_FLAG = False
    for mv_pos, mv_dir in move:
        temp = set()
        for item in wheel_list[mv_pos]:
            if item+mv_dir > 7: item_val = 0
            elif item+mv_dir < 0: item_val = 7
            else: item_val = item+mv_dir
            temp.add(item_val)
        wheel_list[mv_pos] = temp

answer = 0
for idx, w_set in enumerate(wheel_list):
    if 0 in w_set: answer += (2**idx)
print(answer)
'''

'''
def score(arr):
    sco,x=0,1
    for i in arr:
        if i[0] == 1:
            sco += x
        x *= 2
    return sco

def switch(arr,num):
    if num == 1: arr.insert(0,arr.pop())
    else: arr.append(arr.pop(0))

def wheel(arr, info):
    for i in info:
        if i[0]==1:
            if arr[0][2] != arr[1][6]:
                if arr[1][2] != arr[2][6]:
                    if arr[2][2] != arr[3][6]:
                        switch(arr[3],i[1]*(-1))
                    switch(arr[2],i[1])
                switch(arr[1],i[1]*(-1))
            switch(arr[0],i[1])
        elif i[0]==2:
            if arr[1][6] != arr[0][2]:
                switch(arr[0], i[1]*(-1))
            if arr[1][2] != arr[2][6]:
                if arr[2][2] != arr[3][6]:
                    switch(arr[3], i[1])
                switch(arr[2], i[1]*(-1))
            switch(arr[1],i[1])
        elif i[0]==3:
            if arr[2][2] != arr[3][6]:
                switch(arr[3], i[1]*(-1))
            if arr[2][6] != arr[1][2]:
                if arr[1][6] != arr[0][2]:
                    switch(arr[0], i[1])
                switch(arr[1],i[1]*(-1))
            switch(arr[2],i[1])
        elif i[0]==4:
            if arr[2][2] != arr[3][6]:
                if arr[1][2] != arr[2][6]:
                    if arr[0][2] != arr[1][6]:
                        switch(arr[0],i[1]*(-1))
                    switch(arr[1],i[1])
                switch(arr[2],i[1]*(-1))
            switch(arr[3],i[1])

T = int(input())
for _ in range(T):
    K = int(input())
    arr=[list(map(int,input().split())) for i in range(4)]
    info = [list(map(int,input().split())) for i in range(K)]
    wheel(arr,info)
    ans = score(arr)
    print(f'#{_+1} {ans}')
    '''


import os

def log(message):
	with open("mods_checker_log.txt", "a") as logsfile:
		logsfile.write(message + "\n")

try:
	list_of_folders = os.listdir('./scraped_folders')
	list_of_folders = sorted(list_of_folders)
	if '.DS_Store' in list_of_folders:
		list_of_folders.remove('.DS_Store')
	for folder in list_of_folders:
		list_of_files = os.listdir('./scraped_folders/' + str(folder))
		if '.DS_Store' in list_of_files:
			list_of_files.remove('.DS_Store')
		if 'nohup.out' in list_of_files:
			list_of_files.remove('nohup.out')
		list_of_files = sorted(list_of_files)
		first_file = list_of_files[0]
		last_file = list_of_files[-1]
		first_file_extension = first_file[-3:]
		last_file_extension = last_file[-3:]
		if first_file_extension == 'xml' or last_file_extension == 'txt':
			log(str(folder))
			log("    " + str(first_file))
			log("    " + str(last_file))
	log("DONE CHECKING")
except Exception as e:
	log('ERROR CAUGHT: ' + repr(e))
	error_file = open("mods_checker_error_log.txt", "w")
	traceback.print_exc(file=error_file)
	log("Check error_log.txt file for traceback")


def search(x,depth):
    global envelops
    global num
    global n
    num=max(num,depth)
    for i in range(x+1,n):
        if envelops[i][0]>envelops[x][0] and envelops[i][1]>envelops[x][1]:
            search(i,depth+1)
    return

n=int(input())
envelops=[]
for i in range(0,n):
    envelops.append(list(map(int,input().split(','))))
envelops=sorted(envelops,key=lambda x:(x[0],x[1]))
num=0
for i in range(0,n):
    search(i,1)
print(num)


from kernel.base.base import *
import os
import zipfile
import shutil
import pickle
import base64
import time
import pytesseract
import re
from paddleocr import PaddleOCR, draw_ocr
from urllib.parse import urlparse
from PIL import Image
import filetype
# from pysubs2 import SSAFile, SSAEvent, make_time
import pysubs2

class File(BaseClass):

    def __init__(self,args):
        pass

    def b64encode(self,data_file):
        if self.isfile(data_file):
            print(os.path.splitext(data_file))
            extent_file = os.path.splitext(data_file)[1]
            extent_file = extent_file.replace(".","")
            suffix = "data:image/{};base64,".format(extent_file)
            data = self.open(data_file, 'b')
        else:
            suffix = ""
            data = data_file
        data = base64.b64encode(data)
        data = self.com_string.byte_to_str(data)
        data = suffix + data
        return data

    def image_to_str(self,image_url, lang):
        im = Image.open(image_url)
        im = im.convert('L')
        print(f"im {im}")
        im_str = pytesseract.image_to_string(im, lang=lang)
        return im_str

    def image_to_str_from_paddleorc(self,img_path,lang="ch"):
        # ocr = PaddleOCR(use_angle_cls=True, )
        # # 输入待识别图片路径
        # img_path = r"d:\Desktop\4A34A16F-6B12-4ffc-88C6-FC86E4DF6912.png"
        # # 输出结果保存路径
        # result = ocr.ocr(img_path, cls=True)
        # for line in result:
        #     print(line)
        #
        ocr = PaddleOCR(use_angle_cls=True, lang="en")  # need to run only once to download and load model into memory
        result = ocr.ocr(img_path, cls=True)
        return {
            "text":result[0][1][0],
            "data":result
        }
    def rename_remove_space(self,filename):
        space_pattern  = re.compile(r"\s+")
        file_space = re.findall(space_pattern, filename)
        if (len(file_space) > 0):
            new_file_name = os.path.basename(filename)
            new_file_name = re.sub(space_pattern,"",new_file_name )
            file_basedir = os.path.dirname(filename)
            new_file = os.path.join(file_basedir, new_file_name)
            self.cut(filename, new_file)
            filename =new_file
        return filename
    def read_file(self,file_name,encoding="utf-8",info=False):
        return self.load_file(file_name,encoding,info=info)

    def load_file(self,file_name,encoding="utf-8",info=False):
        file_name = self.get_path(file_name)
        file_object = self.get_file_encode(file_name,encoding=encoding,info=info)
        content = None
        if file_object != None:
            content = file_object.get("content")
        return content

    def get_file_encode(self,file_name,encoding=None,info=False):
        codings = [
            "utf-8",
            "utf-16",
            "utf-16le",
            "utf-16BE",
            "gbk",
            "gb2312",
            "us-ascii",
            "ascii",
            "IBM037",
            "IBM437",
            "IBM500",
            "ASMO-708",
            "DOS-720",
            "ibm737",
            "ibm775",
            "ibm850",
            "ibm852",
            "IBM855",
            "ibm857",
            "IBM00858",
            "IBM860",
            "ibm861",
            "DOS-862",
            "IBM863",
            "IBM864",
            "IBM865",
            "cp866",
            "ibm869",
            "IBM870",
            "windows-874",
            "cp875",
            "shift_jis",
            "ks_c_5601-1987",
            "big5",
            "IBM1026",
            "IBM01047",
            "IBM01140",
            "IBM01141",
            "IBM01142",
            "IBM01143",
            "IBM01144",
            "IBM01145",
            "IBM01146",
            "IBM01147",
            "IBM01148",
            "IBM01149",
            "windows-1250",
            "windows-1251",
            "Windows-1252",
            "windows-1253",
            "windows-1254",
            "windows-1255",
            "windows-1256",
            "windows-1257",
            "windows-1258",
            "Johab",
            "macintosh",
            "x-mac-japanese",
            "x-mac-chinesetrad",
            "x-mac-korean",
            "x-mac-arabic",
            "x-mac-hebrew",
            "x-mac-greek",
            "x-mac-cyrillic",
            "x-mac-chinesesimp",
            "x-mac-romanian",
            "x-mac-ukrainian",
            "x-mac-thai",
            "x-mac-ce",
            "x-mac-icelandic",
            "x-mac-turkish",
            "x-mac-croatian",
            "utf-32",
            "utf-32BE",
            "x-Chinese-CNS",
            "x-cp20001",
            "x-Chinese-Eten",
            "x-cp20003",
            "x-cp20004",
            "x-cp20005",
            "x-IA5",
            "x-IA5-German",
            "x-IA5-Swedish",
            "x-IA5-Norwegian",
            "x-cp20261",
            "x-cp20269",
            "IBM273",
            "IBM277",
            "IBM278",
            "IBM280",
            "IBM284",
            "IBM285",
            "IBM290",
            "IBM297",
            "IBM420",
            "IBM423",
            "IBM424",
            "x-EBCDIC-KoreanExtended",
            "IBM-Thai",
            "koi8-r",
            "IBM871",
            "IBM880",
            "IBM905",
            "IBM00924",
            "EUC-JP",
            "x-cp20936",
            "x-cp20949",
            "cp1025",
            "koi8-u",
            "iso-8859-1",
            "iso-8859-2",
            "iso-8859-3",
            "iso-8859-4",
            "iso-8859-5",
            "iso-8859-6",
            "iso-8859-7",
            "iso-8859-8",
            "iso-8859-9",
            "iso-8859-13",
            "iso-8859-15",
            "x-Europa",
            "iso-8859-8-i",
            "iso-2022-jp",
            "csISO2022JP",
            "iso-2022-jp",
            "iso-2022-kr",
            "x-cp50227",
            "euc-jp",
            "EUC-CN",
            "euc-kr",
            "hz-gb-2312",
            "GB18030",
            "x-iscii-de",
            "x-iscii-be",
            "x-iscii-ta",
            "x-iscii-te",
            "x-iscii-as",
            "x-iscii-or",
            "x-iscii-ka",
            "x-iscii-ma",
            "x-iscii-gu",
            "x-iscii-pa",
            "utf-7",
       ]
        if encoding != None:
            codings = [encoding] + codings
        index = 0
        while index < len(codings):
            encoding = codings[index]
            try:
                f = open(file_name, f"r+",encoding=encoding)
                content = f.read()
                if info==True:
                    self.com_util.print_info(f"Successfully mode {encoding} to {file_name}")
                f.close()
                result = {
                    "encoding":encoding,
                    "content":content
                }
                return result
            except Exception as e:
                self.com_util.print_warn(f"file open error, {file_name}")
                self.com_util.print_warn(e)
                index+=1
        return None

    def open(self,file_name,encoding="utf-8"):
        content = self.load_file(file_name,encoding=encoding)
        return content

    def read(self,file_name,encoding="utf-8"):
        content = self.load_file(file_name,encoding=encoding)
        return content

    def load_js(self,file_name,encoding="utf-8"):
        template_dir = self.com_config.get_js_dir()
        file_path = os.path.join(template_dir,file_name)
        content = self.load_file(file_path,encoding)
        return content

    def load_html(self,file_name,encoding="utf-8"):
        template_dir = self.com_config.get_template_dir()
        file_path = os.path.join(template_dir,file_name)
        content = self.load_file(file_path,encoding)
        return content

    def get_default_save_dir(self):
        save_dir = self.com_config.get_public("save_dir")
        return save_dir

    def save(self,file_name=None,content=None,encoding=None,overwrite=False):
        return self.save_file(file_name, content, encoding=encoding, overwrite=overwrite)

    def create_file_name(self,prefix='',suffix=""):
        filename = self.com_string.random_string(16)
        save_time = self.save_time()
        if prefix != '':
            prefix = f"{prefix}_"
        filename = f"{prefix}{save_time}_{filename}{suffix}"
        filedir = self.com_config.get_public("save_dir")
        filesavedir = os.path.join(filedir,filename)
        return filesavedir

    def save_time(self,):
        t = time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())
        return t

    def save_file(self,file_name=None,content=None,encoding=None,overwrite=False):
        if file_name == None:
            print("the save Content not accessed.{file_name}%s}" % file_name)
            return None
        if content == None:
            content = file_name
            file_name = self.create_file_name()
        basename = os.path.dirname(file_name)
        if basename == "":
            basename = self.get_default_save_dir()
            file_name = os.path.join(basename,file_name)
        print(f"save_file ：{file_name}")
        if os.path.exists(basename) is not True and os.path.isdir(basename) is not True:
            self.mkdir(basename)
        if not self.isfile(file_name):
            overwrite = True

        if encoding == None and type(content) == str:
            encoding = "utf-8"
        if overwrite ==True:
            m = "w"
        else:
            m = "a"
        print(f"encoding {encoding}")
        if encoding == None or encoding == "binary":
            f = open(file_name, f"{m}b+")
            content = content.encode(encoding)
        else:
            f = open(file_name, f"{m}+",encoding=encoding)
        try:
            # self.com_util.print_warn(f"savefile_encoding {encoding}")
            f.write(content)
        except:
            f.close()
            content = self.com_string.byte_to_str(content)
            f = open(file_name, f"{m}+",encoding="utf-8")
            f.write(content)
        f.close()
        return file_name
    def read_file_bytes(self,file_name):
        file_name = self.get_path(file_name)
        if self.isfile(file_name):
            with open(file_name, "rb") as f:
                data = f.read()
            return data
        else:
            return None

    def zip_extract(self,file,member,o=None):
        if o == None:
            o = os.path.dirname(file)
        with zipfile(file) as f:
            f.extract(member,o)

    def zip_extractall(self,file,odir=None,member=None):
        if odir == None:
            odir = os.path.dirname(file)
        with zipfile.ZipFile(file) as f:
            f.extractall(odir,member)
        return odir
    def file_extract(self, filename):
        """
        #输助函数,将最后下载的文件解压和删除。
        :param filename:
        :return:
        """
        extract_dir = os.path.dirname(filename)
        print(f"extract file {filename} to {extract_dir}")
        return self.zip_extractall(filename,extract_dir)

    def remove(self,top_path):
        print("delete : " ,top_path)
        for root, dirs, files in os.walk(top_path, topdown=False):
            for name in files:
                os.remove(os.path.join(root, name))
            for name in dirs:
                os.rmdir(os.path.join(root, name))
        if os.path.isdir(top_path):
            os.rmdir(top_path)
        elif os.path.isfile(top_path):
            os.remove(top_path)

    def mkdir(self, dir):
        if os.path.exists(dir) and os.path.isdir(dir):
            return False
        else:
            os.makedirs(dir,exist_ok=True)
            return True

    def isFile(self, path):
        return self.isfile(path)
    def isfile(self, path):
        if type(path) is not str:
            return False
        path = self.get_path(path)
        if os.path.exists(path) and os.path.isfile(path) and os.path.getsize(path) > 0:
            return True
        else:
            return False

    def get_path(self,path):
        if os.path.exists(path) and os.path.isfile(path):
            return path
        public_dir = self.com_config.get_public(path)
        if os.path.exists(public_dir) and os.path.isfile(public_dir):
            return public_dir
        path = os.path.join(self.getcwd(),path)
        if os.path.exists(path) and os.path.isfile(path):
            return path
        else:
            return path

    def isdir(self, path):
        if type(path) is not str:
            return False
        if os.path.exists(path) and os.path.isdir(path) :
            return True
        else:
            return False

    def copy(self, src, dst):
        return shutil.copyfile(src, dst)
    def cut(self, src, dst):
        dst_basedir = os.path.dirname(dst)
        self.mkdir(dst_basedir)
        shutil.copyfile(src, dst)
        os.remove(src)
    def rmtree(self, dir):
        shutil.rmtree(dir)

    def dir_to_localurl(self, filename):
        control_name = self.load_module.get_control_name()
        filename = filename.split(control_name)[-1]
        filename = self.dir_normal(filename,linux=True)
        filename = filename.lstrip('/')
        return filename

    def file_type(self, filename):
        if self.isfile(filename) == False:
            return None
        kind = filetype.guess(filename)
        if kind is None:
            return ""
        else:
            if kind.extension == None:
                return ""
            return kind.extension
    def file_to(self,filename,encoding="utf-8"):
        file_object = self.get_file_encode(filename)
        if file_object == None:
            return False
        file_encode = file_object.get('encoding')
        if file_encode != encoding:
            content = self.read_file(filename)
            # content = content.encode(encoding)
            os.remove(filename)
            self.save(filename,content,encoding=encoding)
        return True

    def dir_to(self,filedir,encoding="utf-8"):
        files = os.listdir(filedir)
        for file in files:
            file = os.path.join(filedir, file)
            self.file_to(file,encoding)

    # def srt_to_doc(self,filename):
    #

    def srt(self, filename,language="en"):
        pattern = re.compile(r'^.+}')
        english_pattern = re.compile(r'^[a-zA-Z\-0-9\"]')
        chinese_pattern = re.compile(r"^([\u4e00-\u9fa5]|[\ufe30-\uffa0]|[\u4e00-\uffa5])+")
        encoding = self.get_file_encode(filename)
        encoding = encoding.get('encoding')
        subs = pysubs2.load(filename, encoding=encoding)
        subs.shift(s=2.5)
        strs = []
        for line in subs:
            if language == "en":
                text = line.text
                text = re.sub(pattern,"",text)
                if re.search(chinese_pattern,text) == None:
                    strs.append(text)
                else:
                    try:
                        origin_text = text
                        trans = self.com_translate.translate_from_google(origin_text,dest="en",src="zh-CN",)
                        text = trans.get('text')
                        print(f"be translated {origin_text} to {text}")
                        strs.append(text)
                    except Exception as e:
                        self.com_util.print_warn(e)
            else:
                text = line.text
        return strs

    def file_suffix(self,file_path,suffix):
        file_path = file_path.split('.')[0:-1]
        suffix = suffix.replace('.',"")
        file_path.append(suffix)
        file_path = ".".join(file_path)
        return file_path

    def get_template_dir(self,filename=None,fulllink=False):
        control_dir = self.load_module.get_control_dir()
        if filename == None:
            filename = ""
        elif filename and fulllink == True:
            top_symbol = re.compile(r'^\/')
            filename = re.sub(top_symbol, '', filename)
        template_folder = self.com_config.get_global("flask_template_folder")
        template_folder = os.path.join(control_dir,template_folder)
        filename = os.path.join(template_folder, filename)
        return filename

    def get_static_dir(self,filename=None,fulllink=False):
        control_dir = self.load_module.get_control_dir()
        print(control_dir)
        if filename == None:
            filename = ""
        elif filename and fulllink == True:
            top_symbol = re.compile(r'^\/')
            filename = re.sub(top_symbol, '', filename)
        template_folder = self.com_config.get_global("flask_static_folder")
        template_folder = os.path.join(control_dir,template_folder)
        filename = os.path.join(template_folder, filename)
        return filename


from pickle import NONE
from re import sub
from tkinter.constants import ANCHOR, FALSE, TRUE, Y
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from tkinter import PhotoImage, filedialog
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.chrome.service import Service
import time
from datetime import date
import webbrowser
import sys
import os
import threading
from PyQt5.QtWidgets import QApplication, QMainWindow
from FacebookUI import Ui_Form
from PyQt5 import QtGui

def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    try:
        # PyInstaller creates a temp folder and stores path in _MEIPASS
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")

    return os.path.join(base_path, relative_path)

LOGIN_URL = 'https://m.facebook.com/login'

status = None
msgG = None
frame = None
intervalG = None
keywordG = None
maxGrps = None
postToGroups = None

class FaceBookGroupPoster():
    def __init__(self):
        self.groups = []
        self.images = []
        self.videos = []
        self.discussGrp = False

    #If you delete "do not delethis", it wont work, even that value is not used.
    def startFaceBookGroupPoster(self, frame, doNotDeleteThis):
        chrome_options = webdriver.ChromeOptions()
        chrome_options.add_experimental_option("detach", True)
        chrome_options.add_argument("--disable-infobars")
        chrome_options.add_experimental_option('excludeSwitches', ['enable-logging'])
        prefs = {"profile.default_content_setting_values.notifications": 2}
        chrome_options.add_experimental_option("prefs", prefs)
        self.driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=chrome_options)
        self.driver.get(LOGIN_URL)
        frame.setText("Make sure you are logged in before proceeding")
        frame.setStyleSheet("color: green;")

    def terminate(self):
        self.driver.close()

    def postGroups(self):
        global msgG, frame, intervalG, keywordG, maxGrps, postToGroups

        msg = msgG.toPlainText().encode("utf-8")
        interval =  intervalG.text()
        keyword = keywordG.text()
        maxGrp = int(maxGrps.text())
        frame.setText(f'Ok Executing the program, Please wait patiently, once its done we will update here.')
        try:
            int(interval)
        except ValueError:
            frame.setText("Please enter a number as value as timout")
            frame.setStyleSheet("color: red;")
            return
        try:
            if len(self.groups) <= 0:
                if len(keyword) <= 0:
                    frame.setText("No groups and keyword loaded \n Make sure you load the groups or keyword before continue")
                    frame.setStyleSheet("color: red;")
                    return
                else:
                    try:
                        maxGrpInt = int(maxGrp)
                        self.getJoinedGroups(frame,keyword, maxGrpInt)
                    except ValueError:
                        frame.setText("Please enter a number as maximum groups.")
                        frame.setStyleSheet("color: red;")
                        return

            elif len(self.images) == 0 and len(msg) == 0:
                frame.setText("First select images or type a message")
                frame.setStyleSheet("color: red;")
                return
            frame.setText(f' We will be trying to post to total of {len(self.groups)} groups with a interval of {interval} seconds')
            try:
                f = open("logs.txt", "a", encoding="utf-8")
                f.write(
                    f'\n\n\n Logs for {msg} at {date.today()} \n ==========================================================================================\n')
                f.close()
                for group in self.groups:
                    self.driver.get(group)
                    time.sleep(5)
                    print(f'trying to post to {group}')
                    try:
                        print("Checking for group TYPE")
                        discuss = self.driver.find_element_by_css_selector("button[value='Discuss']")
                        self.discussGrp = True
                        print("Group Type: Buy and Sell grp (Try to post as discuss)")
                        discuss.click()
                        time.sleep(3)
                    except Exception as e:
                        print("Group Type: Normal Facebook Group")
                        self.discussGrp = False

                    try:
                        if self.discussGrp:
                            postStart = WebDriverWait(self.driver, 15).until(EC.presence_of_element_located(
                            (By.XPATH, '//div[starts-with(text(),"Write something")]')))
                        else:
                            postStart = WebDriverWait(self.driver, 10).until(EC.presence_of_element_located(
                            (By.XPATH, '//div[starts-with(text(),"Write something...")]')))
                    except Exception:
                        try:
                            postStart = WebDriverWait(self.driver, 10).until(EC.presence_of_element_located(
                                (By.XPATH, '//div[starts-with(text(),"Create a public")]')))
                        except Exception:
                            try:
                                postStart = WebDriverWait(self.driver, 10).until(EC.presence_of_element_located(
                                (By.XPATH, '//div[starts-with(text(),"What\'s on your mind")]')))
                            except Exception:
                                try:
                                    postStart = WebDriverWait(self.driver, 10).until(EC.presence_of_element_located(
                                    (By.XPATH, "//textarea[@id='uniqid_1']")))
                                except Exception:
                                    try:
                                        postStart = WebDriverWait(self.driver, 10).until(EC.presence_of_element_located(
                                        (By.TAG_NAME, 'textarea')))
                                    except Exception as e:
                                        print(f'Tried to get the postStart Btn but could not with the error {e}\n Tried "Write Something, Write something..., Create a public post, whats on your mind, unique_id1 and tag name == textarea')

                    time.sleep(1)
                    try:
                        postStart.click()
                    except Exception as e:
                        try:
                            ActionChains(self.driver).move_to_element(
                            postStart).click().perform()
                        except Exception as e:
                            print(f'The create post btn found but could not click, Trying to send text to input box anyway.')
                    try:
                        txtBox = WebDriverWait(self.driver, 5).until(
                        EC.presence_of_element_located((By.XPATH, "//textarea[last()]")))
                    except Exception:
                        try:
                            txtBox = WebDriverWait(self.driver, 5).until(EC.presence_of_element_located(
                            (By.XPATH, "//textarea[@id='uniqid_1']")))
                        except Exception:
                            try:
                                txtBox = WebDriverWait(self.driver, 5).until(EC.presence_of_element_located(
                                (By.TAG_NAME, 'textarea')))
                            except Exception as e:
                                print(f'Could not find the txtBox with the error {e}\n Tried "textareal[last()], unique_id1 and tag name == textarea')
                    try:
                        txtBox.send_keys(msg.decode('utf8', 'ignore'))
                        time.sleep(2)
                    except Exception as e:
                        try:
                            ActionChains(self.driver).move_to_element(
                            txtBox).send_keys(msg.decode('utf8', 'ignore')).perform()
                        except Exception as e:
                            print(f'Text box found but could not send texts with error {e}')
                        time.sleep(2)

                    for photo in self.images:
                        try:
                            photo_element = WebDriverWait(self.driver, 5).until(
                                EC.presence_of_element_located((By.XPATH, "//input[@name='file1']")))
                            photo_element.send_keys(photo)
                            time.sleep(2)
                        except Exception as e:
                            print(f'Could not send {photo} with the error {e}')

                    for video in self.videos:
                        try:
                            video_element = WebDriverWait(self.driver, 5).until(
                                EC.presence_of_element_located((By.XPATH, "//input[@name='file2']")))
                            video_element.send_keys(video)
                            time.sleep(2)
                        except Exception as e:
                            print(f'Could not send Video {video} with the error {e}')

                    time.sleep(5)
                    try:
                        time.sleep(2)
                        post = WebDriverWait(self.driver, 5).until(
                            EC.presence_of_element_located((By.CSS_SELECTOR, "div[class='acw'] button[value='Post']")))
                        post.click()
                    except Exception as e:
                        print('Trying to post using the last method. (usually this happens in buy and sell grp). But you can ignore this as long as program executes.')
                        time.sleep(5)
                        try:
                            txtBox = WebDriverWait(self.driver, 5).until(
                            EC.presence_of_element_located((By.XPATH, "//textarea[last()]")))
                            txtBox.submit()
                        except Exception:
                            pass
                    time.sleep(5)
                    f = open("logs.txt", "a")
                    f.write(f'{group} processed.\n ')
                    f.close()
                    print(f'Hey I am waiting for {interval} seconds, as you mentioned')
                    time.sleep(int(interval))
                    time.sleep(2)
            except Exception as e:
                print(f'ERROR OCCURRED: {e}')
                f = open("logs.txt", "a")
                f.write(f'FAILED Posting to {msg}: {e}\n')
                f.close()
        except Exception as e:
            print(f'ERROR OCCURRED: {e}')
            f = open("logs.txt", "a")
            f.write(f'FAILED Posting to {msg}: {e}\n')
            f.close()
            postToGroups.exit()
        print("PROGRAM EXECUTING FINISHED \n =============================================== \n Thanks for using facebook group poster pro.")
        frame.setText("All done, Check the logs.txt file at your current folder")
        frame.setStyleSheet("color: green;")
        self.groups = []

    def getImages(self, frame):
        filenames = filedialog.askopenfilenames(
            initialdir="/", title="Select Image", filetypes=(("JPG", "*.jpg"), ("PNG Files", "*.png"), ("all files", "*.*")))
        for img in filenames:
            self.images.append(img)

        frame.setText(f'{frame.text()}\n{len(self.images)} images loaded')
        frame.setStyleSheet("color: green;")

    def addGroups(self, frame):
        filename = filedialog.askopenfilename(
            initialdir="/", title="Select file", filetypes=(("Texts Files", "*.txt"), ("all files", "*.*")))
        print(f'{filename}')
        with open(filename, 'r') as f:
            try:
                tempGroups = f.read()
                tempGroups = tempGroups.split(',')
                tempAllGroups = [x for x in tempGroups if x.strip()]
                for group in tempAllGroups:
                    group = group.replace("www.facebook.com", "m.facebook.com")
                    self.groups.append(group)
                frame.setText(f'{frame.text()}\n {len(self.groups)} groups loaded')

                frame.setStyleSheet("color: green;")
            except Exception as e:
                frame.setText(f'error: {e}')
                frame.setStyleSheet("color: red;")

    def clearImagesVideos(self, frame):
        self.images.clear()
        frame.setText("All images have been cleared")
        frame.setStyleSheet("color: green;")

    def ClearGroups(self, frame):
        self.groups.clear()
        frame.setText("All groups have been cleared. Add another '.txt' file containing group links.")
        frame.setStyleSheet("color: green;")

    def getJoinedGroups(self, frame, keyword, maxGrp):
            frame.setText(f"Collectting some groups for the keyword {keyword}")
            frame.setStyleSheet("color: green;")
            self.driver.get(f'https://m.facebook.com/search/groups/?q={keyword}')
            time.sleep(5)
            if True:
                i = 1
                getGroups = True
                repeat = 1
                while getGroups:
                    try:
                        if (len(self.groups)>= maxGrp):
                            getGroups = False
                        path = f"/html[1]/body[1]/div[1]/div[1]/div[4]/div[1]/div[1]/div[2]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[{i}]"
                        grpLink = WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.XPATH, path)))
                        grpLink.location_once_scrolled_into_view
                        grpLink.click()

                        try:
                            postStart = WebDriverWait(self.driver, 5).until(EC.presence_of_element_located(
                                (By.XPATH, '//div[starts-with(text(),"Write something")]')))
                        except Exception:
                            try:
                                postStart = WebDriverWait(self.driver, 5).until(EC.presence_of_element_located(
                                    (By.XPATH, '//div[starts-with(text(),"Create a public")]')))
                            except Exception:
                                try:
                                    postStart = WebDriverWait(self.driver, 5).until(EC.presence_of_element_located(
                                    (By.XPATH, '//div[starts-with(text(),"What\'s on your mind")]')))
                                except Exception:
                                    try:
                                        postStart = WebDriverWait(self.driver, 5).until(EC.presence_of_element_located(
                                        (By.XPATH, "//textarea[@id='uniqid_1']")))
                                    except Exception:
                                        try:
                                            postStart = WebDriverWait(self.driver, 5).until(EC.presence_of_element_located(
                                            (By.TAG_NAME, 'textarea')))
                                        except Exception as e:
                                            pass
                        if str(type(postStart)) == "<class 'selenium.webdriver.remote.webelement.WebElement'>":
                            self.groups.append(self.driver.current_url)
                        else:
                            print("You dont have permission to post to this group, so ignoring this group...")
                        self.driver.back()

                        i = i+1
                        repeat = repeat * 0
                        frame.setText(f"Ok We have collected {len(self.groups)} groups so far")
                        frame.setStyleSheet("color: green;")
                        time.sleep(3)
                    except Exception as e:
                        repeat = repeat +1
                        if (repeat > 10):
                            getGroups = False
                        i = i+1
                        print("There was a issue processing this group, so ignoring... You can check logs.txt for details")
                        f = open("logs.txt", "a", encoding="utf-8")
                        f.write(
                        f'\n\n\n A group was ignored because of  \n {e}')
                        f.close()

class FacebookGroupPosterGUI(FaceBookGroupPoster):
    def __init__(self):
        self.main_win = QMainWindow()
        self.ui = Ui_Form()
        self.ui.setupUi(self.main_win)
        super().__init__()
        self.ui.statusText.setText("In a moment, The Chrome browser will open. Once opened login to your fb account.")
        self.ui.statusText.setStyleSheet("color: green;")
        self.ui.clearGrpsBtn.clicked.connect(lambda: self.ClearGroups(self.ui.statusText))
        self.ui.clearImages.clicked.connect(lambda:self.clearImagesVideos(self.ui.statusText))
        self.ui.addImageBtn.clicked.connect(lambda:self.getImages(self.ui.statusText))
        self.ui.addGrpBtn.clicked.connect(lambda:self.addGroups(self.ui.statusText))
        global msgG, frame, intervalG, keywordG, maxGrps, postToGroups
        msgG = self.ui.postText
        frame = self.ui.statusText
        intervalG =  self.ui.timer
        keywordG = self.ui.keyword
        maxGrps = self.ui.maxGrpToFetch
        self.ui.start.clicked.connect(self.startPosting)
        self.ui.exitBtn.clicked.connect(self.close)
        autoStart = threading.Thread(target=self.startFaceBookGroupPoster, args=(self.ui.statusText,"1"))
        autoStart.run()

    def startPosting(self):
        postToGroups = threading.Thread(target=self.postGroups)
        if postToGroups.is_alive():
            postToGroups.join()
            postToGroups.start()
        else:
            postToGroups.start()

    def show(self):
        self.main_win.show()

    def close(self):
        self.main_win.close()
        self.terminate()


import requests
import zipfile
import tempfile
import os

def get_data( url ):
    response = requests.get(url)
    return url, response.content

def dowanlodZip( url , dest = "./zip"):
    url, data = get_data( url )  # data为byte字节
    _tmp_file = tempfile.TemporaryFile()  # 创建临时文件
    print(_tmp_file)

    _tmp_file.write(data)  # byte字节数据写入临时文件
    # _tmp_file.seek(0)

    print(f'extract to: {os.path.join(os.getcwd(),dest)}')
    zf = zipfile.ZipFile(_tmp_file, mode='r')
    for names in zf.namelist():
        f = zf.extract(names, dest)  # 解压到zip目录文件下
        print(f)
    zf.close()
    print('extract completed')


import random
import os
from time import sleep
from typing import List

def clearConsole():
    command = 'clear'
    if os.name in ('nt', 'dos'):  # If Machine is running on Windows, use cls
        command = 'cls'
    os.system(command)

def randomItem():
    List=[1, 2, 3]
    pc=random.choice(List)
    return pc

clearConsole()
print("WELCOME ON ROCK-PAPPER-SCISSORS\n")
sleep(3)
clearConsole()
flag=1
print("HOW MANY GAMES DO YOU WANT THE MATCH TO HAS?")
games=input()
g=int(games)
player=0
computer=0
sleep(1)

for i in range(0, g):
   clearConsole()
   sleep(2)
   print("1-->Rock\n2-->Papper\n3-->Scissors")
   print("Choose your item: ")
   sth=input()
   item=int(sth)
   p=randomItem()
   pc=int(p)
   if (item==1):
       if (pc==1):
        print("TIE!!!")
        print("Computer:Rock")
       elif(pc==2):
         print("COMPUTER WINS!!!")
         print("Computer:Papper")
         computer+=1
       elif(pc==3):
         print("PLAYER WINS")
         print("Computer:Scissors")
         player+=1
   elif (item==2):
       if (pc==1):
        print("PLAYER WINS!!!")
        print("Computer:Rock")
        player+=1
       elif(pc==2):
         print("TIE!!!")
         print("Computer:Papper")
       elif(pc==3):
         print("COMPUTER WINS")
         print("Computer:Scissors")
         computer+=1
   elif (item==3):
       if (pc==1):
        print("COMPUTER WINS!!!")
        print("Computer:Rock")
        computer+=1
       elif(pc==2):
         print("PLAYER WINS!!!")
         print("Computer:Papper")
         player+=1
       elif(pc==3):
         print("TIE!!!")
         print("Computer:Scissors")
   sleep(1.5)

if player>computer:
    print("Player wins the match!")
    print("Player:",player,"Computer:",computer)
elif computer>player:
    print("Computer wins the match!")
    print("Player:",player,"Computer:",computer)
else :
    print("The match is a total Tie!")
    print("Player:",player,"Computer:",computer)


import json
import sys
from pathlib import Path

import pytest

# support running without installing as a package
wd = Path(__file__).parent.parent.resolve()
sys.path.append(str(wd))

import lit_gpt.config as config_module

def test_config():
    from lit_gpt import Config

    config = Config()
    assert config.name == ""
    assert config.block_size == 4096

    config = Config(block_size=2048)
    assert config.block_size == 2048

    config = Config.from_name("pythia-70m")
    assert config.block_size == 2048

    config = Config.from_name("pythia-70m", block_size=4096)
    assert config.block_size == 4096

    config = Config(hf_config={"name": "pythia-70m"})
    assert config.name == "pythia-70m"

def test_legacy_args(tmp_path):
    from lit_gpt import Config

    config = Config.from_name("pythia-70m", condense_ratio=2)
    assert not hasattr(config, "condense_ratio")
    assert config.rope_condense_ratio == 2

    json_path = tmp_path / "config.json"
    with open(json_path, "w") as fp:
        json.dump({"condense_ratio": 3}, fp)

    config = Config.from_json(json_path)
    assert not hasattr(config, "condense_ratio")
    assert config.rope_condense_ratio == 3
    config = Config.from_json(json_path, condense_ratio=2)
    assert not hasattr(config, "condense_ratio")
    assert config.rope_condense_ratio == 2

def test_from_hf_name():
    from lit_gpt import Config

    # by short-hand name
    config0 = Config.from_name("tiny-llama-1.1b")
    # or by huggingface hub repo name
    config1 = Config.from_name("TinyLlama-1.1B-intermediate-step-480k-1T")
    assert config0 == config1

def test_hf_config_from_json(tmp_path):
    """Test for backward compatibility with older configs that didn't have the `hf_config` field."""
    from lit_gpt import Config

    legacy_config = {"name": "falcon-40b", "org": "tiiuae"}
    with open(tmp_path / "config.json", "w") as file:
        json.dump(legacy_config, file)
    new_config = Config.from_json(tmp_path / "config.json")
    assert new_config.name == "falcon-40b"
    assert not hasattr(new_config, "org")
    assert new_config.hf_config["org"] == "tiiuae"
    assert new_config.hf_config["name"] == "falcon-40b"

    new_config = Config.from_json(tmp_path / "config.json", org="new-org")
    assert new_config.hf_config["org"] == "new-org"

@pytest.mark.parametrize("config", config_module.configs, ids=[c["name"] for c in config_module.configs])
def test_short_and_hf_names_are_equal_unless_on_purpose(config):
    from lit_gpt import Config

    # by short-hand name
    config0 = Config.from_name(config["name"])
    # or by huggingface hub repo name
    config1 = Config.from_name(config["hf_config"]["name"])
    assert config0.name == config1.name


#coding:utf-8

import os, os.path

for f in os.listdir(r'.'):
    if f.endswith(r'.py'): continue

    if r'java' in f:
        new_f = '2012-02'+f[7:]
        os.rename(f, new_f)
    elif r'python' in f:
        new_f = '2012-03'+f[7:]
        os.rename(f, new_f)


num=int(input())
for k in range(num):
    l1=input().split(" ")
    l2=input().split(" ")
    n1=int(l1[0])
    n2=int(l1[1])
    for i in range(n1):
        l2[i]=int(l2[i])
    min=100
    index=0
    for i in range(n1):
        n=abs(n2-l2[i])
        if n<=min:
            min=n
            index=l2[i]
    print(index)


import os
import uuid
import json
import logging
import numpy as np
import pandas as pd
from datetime import datetime
from argparse import ArgumentParser
from sklearn.metrics import precision_recall_fscore_support
from sklearn.model_selection import KFold
from sklearn.model_selection import train_test_split
from toxicitydetector.preprocessing.csv_reader import DataLoader
from toxicitydetector.models.factory import get_model

class ClassificationTask:
    def __init__(self, args):
        self.args = args
        self.args.run_id = datetime.now().strftime("%Y%m%d%H%M%S")
        self.args.initial_timestamp = datetime.now().timestamp()
        self.dataset = DataLoader(self.args)
        self.output_path = args.output_file
        self.write_header = not self.args.no_output_headers
        # set random state
        np.random.seed(args.random_state)
        print("PARAMS: {}".format(self.args))

    def split_dataset(self):

        X = self.dataset.X_labeled.values
        y = self.dataset.y_labeled.values

        if self.args.predict:
            X_train, y_train = X, y
            X_test, y_test = self.dataset.X_test.values, None
        else:
            X_train, X_test, y_train, y_test = train_test_split(
                X, y, test_size=0.2,random_state=self.args.random_state)

        return X_train, X_test, y_train, y_test

    def run(self):

        self.dataset.load()

        X_train, X_test,  y_train, y_test = self.split_dataset()

        logging.info("Train data: {}".format(X_train.shape))
        logging.info("Test data: {}".format(X_test.shape))

        labels = self.dataset.y_cols
        results = None
        k_folds = self.args.kfolds
        scores = []
        best_model = None
        best_score = 0
        cv = KFold(k_folds, random_state=self.args.random_state)

        for k, fold in enumerate(cv.split(X_train, y_train)):
            logging.info('MODEL: {}'.format(self.args.model))
            logging.info('training fold {}'.format(k))
            train, valid = fold
            X_kfold, X_valid = X_train[train], X_train[valid]
            y_kfold, y_valid = y_train[train], y_train[valid]

            model = get_model(self)
            model.train(X_kfold, y_kfold)
            y_pred = model.predict(X_valid)

            preds = (y_pred > 0.5).astype(int) if self.args.predict_probs else y_pred
            score = precision_recall_fscore_support(y_valid, preds, average='weighted')
            score = score[2] #F1
            scores.append(score)
            print(f"CV {k} F1: {score}")

            if score > best_score:
                best_score = score
                best_model = model

            y_pred = pd.DataFrame(y_pred, columns=labels)
            y_pred = self.dataset.decode_features(y_pred, labels)
            y_valid = pd.DataFrame(y_valid, columns=labels)
            y_valid = self.dataset.decode_features(y_valid, labels)

            results_df = y_valid.merge(y_pred, left_index=True,right_index=True, suffixes=('', '_pred'))
            results_df['run_id'] = self.args.run_id
            results_df['timestamp'] = datetime.now().timestamp()
            results_df['model'] = model.args.model
            results_df['set'] = 'cv'
            results_df['kfold'] = k
            results_df['id'] = X_valid[:,0]
            results = results_df if results is None else results.append(results_df, ignore_index=True)

        # predict on tests set
        y_pred = best_model.predict(X_test)

        if self.args.predict:

            if len(self.dataset.y_cols) == 1:
                y_pred = np.expand_dims(y_pred, axis=1)

            for ix, col in enumerate(self.dataset.y_cols):
                self.dataset.X_test.loc[:,col] = y_pred[:, ix]

            cols = ['id']
            cols.extend(self.dataset.y_cols)
            results = self.dataset.X_test[cols]
            results = self.dataset.decode_features(results, labels)
            results.to_csv(self.output_path, index=False, header=self.write_header)

        else:
            preds = (y_pred > 0.5).astype(int) if self.args.predict_probs else y_pred
            score = precision_recall_fscore_support(y_test, preds, average='weighted')
            score = score[2] # f1
            scores = np.array(scores)
            print(f"CV F1: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2))
            print(f"Test F1: %0.2f" % (score))

            y_pred = pd.DataFrame(y_pred, columns=labels)
            y_pred = self.dataset.decode_features(y_pred, labels)
            y_test = pd.DataFrame(y_test, columns=labels)
            y_test = self.dataset.decode_features(y_test, labels)

            results_df = y_test.merge(y_pred, left_index=True,right_index=True, suffixes=('', '_pred'))
            results_df['run_id'] = self.args.run_id
            results_df['timestamp'] = datetime.now().timestamp()
            results_df['model'] = model.args.model
            results_df['set'] = 'test'
            results_df['kfold'] = 0
            results_df['id'] = X_test[:, 0]
            results = results.append(results_df, ignore_index=True)
            write_header = not os.path.exists(self.output_path)

            # save results
            with open(self.output_path, 'a') as f:
                results.to_csv(path_or_buf=f, index=False, header= write_header)

        # save hyperparams
        self.args.final_timestamp = datetime.now().timestamp()
        filepath = os.path.splitext(self.output_path)[0] + '.json'
        with open(filepath, 'a') as f:
            config = json.dumps(self.args.__dict__)
            f.write(config +'\r')

if __name__ == '__main__':
    logging.basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG)
    logging.info('initializing task...')
    parser = ArgumentParser()
    parser.add_argument('--train-path', type=lambda x:os.path.expanduser(x))
    parser.add_argument('--unlabeled-path', type=lambda x: os.path.expanduser(x))
    parser.add_argument('--test-path', type=lambda x: os.path.expanduser(x))
    parser.add_argument('--labels', type=lambda x: x.split(','))
    parser.add_argument('--field-sep', type=str, default=',')
    parser.add_argument('--text-field', type=str, default='text')
    parser.add_argument('--use-allfeats', action='store_true')
    parser.add_argument('--num-unlabeled', type=int, default=0)
    parser.add_argument('--kfolds', type=int, default=2)
    parser.add_argument('--epochs', type=int, default=2)
    parser.add_argument('--ngrams', type=int, default=1)
    parser.add_argument('--embeddings-size', type=int, default=300)
    parser.add_argument('--embeddings-path', type=lambda x: os.path.expanduser(x))
    parser.add_argument('--embeddings-trainable', action='store_true')
    parser.add_argument('--random-state', type=int, default=1)
    parser.add_argument('--predict', action='store_true')
    parser.add_argument('--predict-probs', action='store_true')
    parser.add_argument('--no-output-headers', action='store_true')
    parser.add_argument('--output-file', type=lambda x:os.path.expanduser(x))
    parser.add_argument('--models')
    parser.add_argument('--append-results', action='store_true')
    args = parser.parse_args()

    # clean previous results
    if not args.append_results:
        if os.path.exists(args.output_file):
            os.remove(args.output_file)

    for model in args.models.split(','):
        logging.info(f'running {model} model...')
        args.model = model
        task = ClassificationTask(args)
        task.run()
        logging.info(f'running {model} model...[OK]')

    logging.info('task finished...[ok]')


class Solution:
    def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:
        n1=len(list1)
        d1={list1[i]:i for i in range(n1)}
        n2=len(list2)
        d2={list2[i]:i for i in range(n2)}
        minimumIndexSum=float('inf')
        minimumIndexSumWord=''
        for word in d1:
            if word in d2:
                d1[word]+=d2[word]
                minimumIndexSum=min(minimumIndexSum, d1[word])
            else:
                d1[word]=-1
        resultList=[]
        for word in d1:
            if d1[word]==minimumIndexSum:
                resultList.append(word)
        return resultList


'''
Created on May 7, 2014

@author: eran
'''
import unittest
from adiencealign.affine_alignment.affine_aligner import AffineAligner
import cv2
from adiencealign.common.landmarks import read_fidu, draw_fidu, unwarp_fidu
from adiencealign.landmarks_detection.landmarks_detector import detect_landmarks
import os

class Test(unittest.TestCase):

    def testAffineAlign(self):
        aligner = AffineAligner(fidu_model_file = '../resources/model_ang_0.txt')

        img_files = ['./resources/affine_align/Meryl_Streep_0013.jpg', './resources/affine_align/Fayssal_Mekdad_0002.jpg']
        for img_file in img_files:
            img_file = os.path.abspath(img_file)
            detect_landmarks(fname = img_file)

            fidu_file = img_file.replace('.jpg','.cfidu')
            img = cv2.imread(img_file)
            score, yaw_angle, fidu_points = read_fidu(fidu_file)
            aligned_img, R = aligner.align(img, fidu_points)

            aligned_img_cpy = aligned_img.copy()
            draw_fidu(img, fidu_points)
            fidu_points_in_aligned = unwarp_fidu(orig_fidu_points = fidu_points, unwarp_mat = R)
            draw_fidu(aligned_img_cpy, fidu_points_in_aligned, radius = 9, color = (255,0,0), thickness = 3)

            cv2.imshow('padded_face with landmarks', img)
            cv2.imshow('aligned_face', cv2.resize(aligned_img, (320,320), interpolation = cv2.INTER_CUBIC))
            cv2.imshow('aligned_face with landmarks', cv2.resize(aligned_img_cpy, (320,320), interpolation = cv2.INTER_CUBIC))
            cv2.waitKey()

if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testAffineAlign']
    unittest.main()


from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path("admin/", admin.site.urls),
    # user urls
    path("api/v1/users", include("core.rest.urls.base")),
    # profile urls
    path("api/v1/users/profile", include("user_profile.rest.urls.profile")),
    # authentication urls
    path("api/v1/auth/", include("authentication.rest.urls.authentications")),
    # category urls
    path("api/v1/category", include("category.rest.urls.category")),
    # subcategory urls
    path("api/v1/subcategory", include("sub_category.rest.urls.sub_category")),
    # post urls
    path("api/v1/posts", include("post.rest.urls.posts")),
    # post reaction urls
    path("api/v1/posts/<uuid:uid>/reaction", include("post_reaction.rest.urls.post_reaction")),
    # post tag urls
    path("api/v1/tags", include("tag.rest.urls.tag")),
    # silk url
    path("silk/", include("silk.urls", namespace="silk")),
]
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


class DataMemory:
    mem = {}
    memRead: bool;
    memWrite: bool;
    address: str;

    def __init__(self):
        self.memRead = False;
        self.memWrite = False;
        self.address = 0;

    def inputs(self, memRead, memWrite, address, datain):
        self.memRead = memRead;
        self.memWrite = memWrite;
        self.address = address;

        if self.memWrite:
            self.mem[address] = datain;
            print("wrote", datain, "to address", address)

    def output(self):
        if self.memRead:
            return self.mem.get(self.address, 1000);
        else:
            # print("Ohhhh yeahhh!!!")
            pass

    def printstuff(self):
        for (key, value) in self.mem.items():
            print(str(key)+": "+str(value), end=', ')
        print('----------------')

#Start from 4194304
class InstMemory:
    mem = {}
    def __init__(self, filename):
        file = open(filename)
        code = file.readlines()
        for i in range(len(code)):
            self.mem[4194304 + i*4] = code[i];
        print(len(self.mem))

    def getInst(self, pc):
        return self.mem[pc];


from datetime import datetime
import pathlib
import backtrader as bt
# from __future__ import (absolute_import, division, print_function, unicode_literals)
import backtrader.analyzers as btanalyzers
from reference.Strategy import zwpy_sta
import pandas as pd

BTC_data = pathlib.Path().cwd() / "data" / "training_set.csv"

cerebro = bt.Cerebro()
# cerebro.addstrategy(zwpy_sta.MacdV2Strategy)
cerebro.optstrategy(
            zwpy_sta.MacdV2Strategy,
            fast_period = range(10,14),
            slow_period = range(24,28),
            signal_period = range(8,12))
cerebro.broker.setcash(100000)

dt_start = datetime.strptime("20190925","%Y%m%d")
dt_end = datetime.strptime("20210101","%Y%m%d")
data = bt.feeds.GenericCSVData(
    timeframe = bt.TimeFrame.Minutes,
    compression = 60,
    dataname=BTC_data,
    fromdate=dt_start,
    todate=dt_end,
    nullvalue=0.0,
    dtformat=('%Y-%m-%d %H:%M:%S'),
    datetime=0,
    open = 1,
    high = 2,
    low = 3,
    close = 4,
    openinterest=-1,
    volume = -1
)
# data = bt.feeds.GenericCSVData( dataname=BTC_data, datetime=0, open=1, high=2, low=3, close=4, volume=5, openinterest=-1, dtformat=('%Y-%m-%d %H:%M:%S'), timeframe=bt.TimeFrame.Minutes, compression=60, )
cerebro.adddata(data)
# print('Starting Value: %.2f' % cerebro.broker.getvalue())
cerebro.addanalyzer(btanalyzers.Returns, _name = "returns")
cerebro.addanalyzer(btanalyzers.SharpeRatio, _name = "sharpe")
cerebro.addanalyzer(bt.analyzers.PyFolio, _name='pyfolio')
results = cerebro.run()
# print([ele for ele in results])
# print('Ending Value: %.2f' % cerebro.broker.getvalue())
# def run_pyfolio(**kwargs):
par_list = [[ele[0].params.fast_period,
            ele[0].params.slow_period,
            ele[0].params.signal_period,
            ele[0].analyzers.returns.get_analysis()['rtot'],
            ele[0].analyzers.sharpe.get_analysis()['sharperatio']
            ] for ele in results]

# Save result to csv
par_df = pd.DataFrame(par_list, columns = ['fast_period', 'slow_period', 'signal_period', 'return', 'sharpe'])
print(par_df.head())
par_df.to_csv('./report/result.csv')


from flask import jsonify,request
import json
import sys
sys.path.append("..")
from Entity.Movie import MovieModel
from Repository.MovieRepository import MovieRepository

class MovieService():

    def __init__(self):
        print("Se inicio movie service")

    def GetAll():
        result = []
        movies = MovieRepository.GetAll()
        for item in movies:
            result.append(item.toJson())
        return result

    def GetById(id):
        print("Get By Id" + str(id))

    def Save(json):
        try:
            movie = MovieModel(json['id'],
                               json['name'],
                               json['director'],
                               json['costo'],
                               json['moneda'],
                               json['annio'])
            MovieRepository.Save(movie)
            return True
        except:
            return False

    def Update(json):
        try:
            movieParam = MovieModel(json['id'],
                               json['name'],
                               json['director'],
                               json['costo'],
                               json['moneda'],
                               json['annio'])
            movie = None
            movies = MovieRepository.GetAll()
            for item in movies:
                if item.id == movieParam.id:
                    movie = item
                    break
            if(movie!=None):
                movie.name = movieParam.name
                movie.director = movieParam.director
                movie.costo = movieParam.costo
                movie.moneda = movieParam.moneda
                movie.annio = movieParam.annio
                return True
            else:
                return False
        except:
            return False

    def DeleteById(id):
        try:
            movie = None
            movies = MovieRepository.GetAll()
            for item in movies:
                if item.id == id:
                    movie = item
                    break
            if(movie!=None):
                MovieRepository.Delete(movie)
                return True
            else:
                return False
        except:
            return False

print("SE ESTA INVOCANDO A LA CLASE MOVIE SERVICE")

9. Python para la Web - API REST - Arquitectura por capas/Services/MovieServices.py