import glob
import os

def nuimages_parser(root_path: str):
    """
    Returns a list of absolute image paths contained in the NuImages dataset.

    Ref: https://www.nuscenes.org/nuimages

    Dataset structure (top level corrspond to 'root directory'):
    nuimages/
        samples/
            CAM_BACK/
                .jpg
            CAM_BACK_LEFT/
                .jpg
            CAM_BACK_RIGHT/
                .jpg
            CAM_FRONT/
                .jpg
            CAM_FRONT_LEFT/
                .jpg
            CAM_FRONT_RIGHT/
                .jpg
        sweeps/
            CAM_BACK/
                .jpg
            CAM_BACK_LEFT/
                .jpg
            CAM_BACK_RIGHT/
                .jpg
            CAM_FRONT/
                .jpg
            CAM_FRONT_LEFT/
                .jpg
            CAM_FRONT_RIGHT/
                .jpg
        v1.0-mini/
            .json
        v1.0-test/
            .json
        v1.0-train/
            .json
        v1.0-val/
            .json

    Args:
        root_path (str): Root path of dataset.

    Returns:
        List of strings corresponding to absolute image paths.
    """
    dataset_img_paths = []

    # Parse 'samples'
    if os.path.isdir(os.path.join(root_path, 'samples')):
        img_paths = glob.glob(f"{root_path}/samples/*/*.jpg")
        dataset_img_paths += img_paths

    # Parse 'sweeps'
    if os.path.isdir(os.path.join(root_path, 'sweeps')):
        img_paths = glob.glob(
            f"{root_path}/sweeps/*/*.jpg")
        dataset_img_paths += img_paths

    return dataset_img_paths


import os
import numpy as np
import pandas as pd
import paddle
from paddle.io import Dataset

class Scaler(object):
    """
    Desc: Normalization utilities
    """
    def __init__(self):
        self.mean = 0.
        self.std = 1.

    def fit(self, data):
        # type: (paddle.tensor) -> None
        """
        Desc:
            Fit the data
        Args:
            data:
        Returns:
            None
        """
        self.mean = np.mean(data)
        self.std = np.std(data)

    def transform(self, data):
        # type: (paddle.tensor) -> paddle.tensor
        """
        Desc:
            Transform the data
        Args:
            data:
        Returns:
            The transformed data
        """
        mean = paddle.to_tensor(self.mean).type_as(data).to(data.device) if paddle.is_tensor(data) else self.mean
        std = paddle.to_tensor(self.std).type_as(data).to(data.device) if paddle.is_tensor(data) else self.std
        return (data - mean) / std

    def inverse_transform(self, data):
        # type: (paddle.tensor) -> paddle.tensor
        """
        Desc:
            Restore to the original data
        Args:
            data: the transformed data
        Returns:
            The original data
        """
        mean = paddle.to_tensor(self.mean) if paddle.is_tensor(data) else self.mean
        std = paddle.to_tensor(self.std) if paddle.is_tensor(data) else self.std
        return (data * std) + mean

class WindTurbineDataset(Dataset):
    """
    Desc: Data preprocessing,
          Here, e.g.    15 days for training,
                        3 days for validation,
                        and 6 days for testing
    """
    def __init__(self, data_path,
                 filename='my.csv',
                 flag='train',
                 size=None,
                 turbine_id=0,
                 task='MS',
                 target='Target',
                 scale=True,
                 start_col=2,       # the start column index of the data one aims to utilize
                 day_len=24 * 6,
                 train_days=15,     # 15 days
                 val_days=3,        # 3 days
                 test_days=6,       # 6 days
                 total_days=30      # 30 days
                 ):
        super().__init__()
        self.unit_size = day_len
        if size is None:
            self.input_len = self.unit_size
            self.output_len = self.unit_size
        else:
            self.input_len = size[0]
            self.output_len = size[1]
        # initialization
        assert flag in ['train', 'test', 'val']
        type_map = {'train': 0, 'val': 1, 'test': 2}
        self.set_type = type_map[flag]
        self.task = task
        self.target = target
        self.scale = scale
        self.start_col = start_col
        self.data_path = data_path
        self.filename = filename
        self.tid = turbine_id

        # If needed, we employ the predefined total_size (e.g. one month)
        self.total_size = self.unit_size * total_days
        #
        self.train_size = train_days * self.unit_size
        self.val_size = val_days * self.unit_size
        self.test_size = test_days * self.unit_size
        # self.test_size = self.total_size - train_size - val_size
        #
        # Or, if total_size is unavailable:
        # self.total_size = self.train_size + self.val_size + self.test_size
        self.__read_data__()

    def __read_data__(self):
        self.scaler = Scaler()
        df_raw = pd.read_csv(os.path.join(self.data_path, self.filename))
        border1s = [self.tid * self.total_size,
                    self.tid * self.total_size + self.train_size - self.input_len,
                    self.tid * self.total_size + self.train_size + self.val_size - self.input_len
                    ]
        border2s = [self.tid * self.total_size + self.train_size,
                    self.tid * self.total_size + self.train_size + self.val_size,
                    self.tid * self.total_size + self.train_size + self.val_size + self.test_size
                    ]
        border1 = border1s[self.set_type]
        border2 = border2s[self.set_type]

        df_data = df_raw
        if self.task == 'M':
            cols_data = df_raw.columns[self.start_col:]
            df_data = df_raw[cols_data]
        elif self.task == 'MS':
            cols_data = df_raw.columns[self.start_col:]
            df_data = df_raw[cols_data]
        elif self.task == 'S':
            df_data = df_raw[[self.tid, self.target]]

        # Turn off the SettingWithCopyWarning
        pd.set_option('mode.chained_assignment', None)
        df_data.replace(to_replace=np.nan, value=0, inplace=True)

        if self.scale:
            train_data = df_data[border1s[0]:border2s[0]]
            self.scaler.fit(train_data.values)
            data = self.scaler.transform(df_data.values)
        else:
            data = df_data.values
        self.data_x = data[border1:border2]
        self.data_y = data[border1:border2]
        self.raw_data = df_data[border1 + self.input_len:border2]

    def get_raw_data(self):
        return self.raw_data

    def __getitem__(self, index):
        #
        # Only for customized use.
        # When sliding window not used, e.g. prediction without overlapped input/output sequences
        if self.set_type >= 3:
            index = index * self.output_len
        #
        # Standard use goes here.
        # Sliding window with the size of input_len + output_len
        s_begin = index
        s_end = s_begin + self.input_len
        r_begin = s_end
        r_end = r_begin + self.output_len
        seq_x = self.data_x[s_begin:s_end]
        seq_y = self.data_y[r_begin:r_end]
        return seq_x, seq_y

    def __len__(self):
        # In our case, the sliding window is adopted, the number of samples is calculated as follows
        if self.set_type < 3:
            return len(self.data_x) - self.input_len - self.output_len + 1
        # Otherwise, if sliding window is not adopted
        return int((len(self.data_x) - self.input_len) / self.output_len)

    def inverse_transform(self, data):
        return self.scaler.inverse_transform(data)


#!/usr/bin/env python
# encoding: utf-8
'''
@File  : watch_ip_city.py
@Date  : 2021/10/27 22:56
@Author: Cxs
@Email: Cxs1103@163.com
@Desc  : Python查询IP的地理位置
'''

import requests,json

def get_ip_localtion(ip):
    url = f"http://ip.taobao.com/outGetIpInfo?ip={ip}&accessKey=alibaba-inc"
    r = requests.get(url)
    data = json.loads(r.text)
    country, region, city, isp = (
        data["data"]["country"],
        data["data"]["region"],
        data["data"]["city"],
        data["data"]["isp"]
    )
    return country, region, city, isp

print(get_ip_localtion("61.152.197.156"))
print(get_ip_localtion("1.12.37.255"))
print(get_ip_localtion("211.161.240.166"))


# Подключаем библиотеки
from unicodedata import decimal
import httplib2
import apiclient
from oauth2client.service_account import ServiceAccountCredentials
import sys
sys.path.append(r"/Users/janinatikhonova/Documents/GitHub/Test-sheets/testsheets/")
#from testsheetsapp.models import *

CREDENTIALS_FILE = 'fleet-standard-351108-f4a1a791c631.json'

# Читаем ключи из файла
credentials = ServiceAccountCredentials.from_json_keyfile_name(CREDENTIALS_FILE, ['https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive'])

httpAuth = credentials.authorize(httplib2.Http()) # Авторизуемся в системе
service = apiclient.discovery.build('sheets', 'v4', http = httpAuth) # Выбираем работу с таблицами и 4 версию API
spreadsheetId = '1lRw5N1dN6No8Ab-1xedFpQ1QOkowcrrB4lUlx3_6uLw'
ranges = ["Лист номер один!A2:D1000"]
results = service.spreadsheets().values().batchGet(spreadsheetId = spreadsheetId,
                                    ranges = ranges,
                                     valueRenderOption = 'FORMATTED_VALUE',
                                     dateTimeRenderOption = 'FORMATTED_STRING').execute()
result_values = results['valueRanges'][0]['values']
for val in result_values:
    kurs = float(57.5)
    rubles = float(val[2]) * kurs
    print(val, val[2], rubles)
    #order = Orders(number = val[0], number_order = val[1], price_dolars = val[2], price_rubles = rubles, data_deliveries = val[3])
    #order.save()


#program to contain hindi english words value and user lookup
dict = {
    "khana" : "eat",
    "dodna" : "run",
    "rona" : "cry",
    "angreji" : "English"
}

mean = input("enter the hindi words :\n")
print("The translation in english is : ",dict.get(mean))


# -*- coding: utf-8 -*-
"""
Created on Sat May 14 09:53:56 2022

@author: tang
"""

import pandas as pd
from infosys.utils import InitTable

# table = pd.read_excel('./data/2021水平测试.xlsx')

obj_1 = InitTable(data_path='./data/2021水平测试.xlsx',
                  ind_path='./data/2021水平测试满分.xlsx', exam_name='水平测试')

obj_2 = InitTable(data_path='./data/2021经典数据.xlsx', data_sheet='二级',
                  ind_path='./data/2021经典满分.xlsx', exam_name='经典考试')

# obj_3 = InitTable(data_path='./data/2018医考认知层次得分标准化150.xlsx',
#                   ind_path='./data/2018医考认知层次满分.xlsx', exam_name='医考')

d_1 = obj_1.create_dict()
d_2 = obj_2.create_dict()
# d_3 = obj_3.create_dict()

d = obj_1.create_dict()

# print(d)
print('=='*100)
for i, (k, v) in enumerate(d_2.items()):
    print(i+1, '\t', k, ':\t', v)
    print()

print('=='*100)

from infosys.base import QuaryInfo
from infosys.base import SubWeight

qr = QuaryInfo(dic=d)

reg = {'模块名': ['中医基础', '医学人文'], '科目': ['中基', '伤寒'], '认知层次': ['记忆']}
# reg = {'模块名': None, '科目': ['中基', '伤寒'], '认知层次': None}
# reg = {'模块名': ['中医基础', '医学人文'], '科目': None, '认知层次': None}
# reg = {'模块名': None, '科目': None, '认知层次': ['记忆', '理解']}

res = qr.update(reg)
print(res)

sw = SubWeight([obj_1.exam_name, obj_2.exam_name], obj_1.indicators, obj_2.indicators)
# sw = SubWeight([obj_1.exam_name, ], obj_1.indicators)
wt = sw.update(d_1, d_2)

print(wt)

print(sw.modele_score_)
print(sw.modele_weight)
print(sw.sub_score_)
print(sw.sub_weight)
# for r_ in res:
#     print(r_)
sw.totle_performance([d_1, d_2], *wt)


try:
    from io import BytesIO as StringIO
except ImportError:
    from StringIO import StringIO

from ..args import Arguments
from ..path import Path
from .copy import Copy

# is the Base unnecessary given that Copy is also a subclass?
class Shebang(Copy):
    """Replace the shebang string with a specific pathname.
constructor arguments:
Shebang(*files, dest=<DIR>, token='#!', program=<FILE>)"""
    token = '#!'
    arguments = Arguments(
        Arguments.Keyword('program', types=(Path, str), noNone=True),
    ) + Copy.arguments

    def dojob(self, sname, dname, context):
        import os
        import shutil
        inf = sname.open()
        outf = StringIO()
        first = inf.readline()
        if first.startswith(self.token):
            if ' ' in first:
                wsp = first.find(' ')
            else:
                wsp = first.find(os.linesep)
            first = first.replace(
                first[len(self.token):wsp],
                # pylint: disable=no-member
                self.args.program
            )
            outf.write(first)
        else:
            outf.write(first)
        shutil.copyfileobj(inf, outf)
        inf.close()
        outf.seek(0)
        inf = dname.open('w')
        shutil.copyfileobj(outf, inf)

Shebang.register()


from collections import Counter

def get_key(val):
    for key, value in my_dict.items():
        if val == value:
            return key

user = list(map(int, input().split()))
my_dict = Counter(user)
b = min(my_dict.values())
print(get_key(b))


#You have been given three tables with invoice data named inv_jul, inv_aug, and inv_sep. Concatenate these tables into one to create a graph of the average monthly invoice total.

# Concatenating the tables and adding keys
inv_jul_thr_sep = pd.concat([inv_jul, inv_aug, inv_sep],
                            keys=['7Jul','8Aug','9Sep'])

# Grouping the invoices by the index keys and finding avg of the total column
avg_inv_by_month = inv_jul_thr_sep.groupby(level=0).agg({'total':'mean'})

# Bar plot of avg_inv_by_month
avg_inv_by_month.plot(kind='bar')
plt.show()

#The plot shows that September had the highest average invoice total.

Concatenating Invoices to study total avg monthly inv.py


import random
int_list = [1,2,3]

while (True):
    print("가위=1. 바위=2, 보=3 중에서 입력하세요:", end=" ")
    user_input = int(input())
    comp_input = random.choice(int_list)

    #print(user_input, comp_input)
    print('user_input:{}, comp_input:{}'.format(user_input, comp_input))

    #user_input에 대한 조건문 처리
    winner = ''

    if user_input == 1: # 1= 가위
        if comp_input == 1:
            winner = 'same'
        elif comp_input == 2:
            winner = 'comp'
        else:
            winner = 'user'
    elif user_input == 2: # 2= 바위
        if comp_input == 1:
            winner = 'user'
        elif comp_input == 2:
            winner = 'same'
        else:
            winner = 'comp'
    else: # 3 = 보
        if comp_input == 1:
            winner = 'comp'
        elif comp_input == 2:
            winner = 'user'
        else:
            winner = 'same'
    # print game result
    if winner == 'same':
        print('무승부')
    else:
        print('The game result is : {} 승리!' .format(winner))


"""
단계마다 방문하지 않은 노드 중에 최단 거리가 가장 짧은 노드를 선택하기 위해
매 단계마다 1차원 테이블의 모든 원소를 확인(순차 탐색)한다.
"""

import sys

input = sys.stdin.readline
INF = int(1e9)  # 무한대값을 10억으로 설정

# 노드 개수, 간선 개수 입력받기
n, m = map(int, input().split())
# 시작 노드 번호를 입력받기
start = int(input())
# 각 노드에 연결된 노드에 대한 정보를 담는 리스트 만들기
graph = [[] for i in range(n + 1)]
# 방문한 적이 있는지 체크하는 목적의 리스트 만들기
visited = [False] * (n + 1)
# 최단 거리 테이블을 모드 무한으로 초기화
distance = [INF] * (n + 1)

# 모든 간선 정보를 입력받기
for _ in range(m):
    a, b, c = map(int, input().split())
    # a 번 노드에서 b번 노드로 가는 비용이 c라는 의미
    graph[a].append(b, c)

# 방문하지 않은 노드 중에 가장 최단 거리가 짧은 노드의 번호를 반환
def get_smallest_node():
    min_value = INF
    index = 0  # 가장 최단 거리가 짧은 노드(인덱스)
    for i in range(1, n + 1):
        if distance[i] < min_value and not visited[i]:
            min_value = distance[i]
            index = i
    return index

def dijkstra(start):
    # 시작 노드에 대해서 초기화
    distance[start] = 0
    visited[start] = True
    # 출발 노드부터 당장 갱신이 가능한 노드들 거리 갱신
    for j in graph[start]:
        distance[j[0]] = j[1]
    # 시작 노드를 제외한 전체 n-1개 노드에 대해 반복
    for i in range(n - 1):
        # 현재 최단 거리가 가장 짧은 노드를 꺼내서, 방문 시작
        now = get_smallest_node()
        visited[now] = True
        # 현재 노드와 연결된 다른 노드를 확인
        for j in graph[now]:
            cost = distance[now] + j[i]
            # 현재 노드를 거쳐 다른 노드로 이동하는 거리가 더 짧은 경우
            if cost < distance[j[0]]:
                distance[j[0]] = cost

# 다익스트라 알고리즘 수행
dijkstra(start)

# 모든 노드로 가기 위한 최단 거리 알고리즘 출력
for i in range(1, n + 1):
    # 도달할 수 없는 경우, 무한(INFINITY)라고 출력
    if distance[i] == INF:
        print("INFINITIY")
    # 도달할 수 있는 경우 거리 출력
    else:
        print(distance[i])

"""
O(V)번에 걸쳐 최단 거리가 가장 짧은 노드를 매번 선형 탐색해야 한다.
따라서 전체 시간 복잡도는 O(V^2)이다.
일반적으로 코테의 최단 경로 문제에서 전체 노드 개수가 5000개 이하라면 이 코드로 문제 해결이 가능하다.
    - 만약 노드 개수가 10000개 이상이라면 어떻게 해결해야 할까? (약 1억번 이상의 연산)
    - 더욱 효율적인 알고리즘 설계 필요.

우선순위 큐 :
여러 개의 데이터 중 가장 우선순위가 높은 데이터부터 꺼내서 확인해야 하는 경우 사용한다.
표준 라이브러리 형태로 지원한다.
우선순위 큐 구현을 위해 Heap 자료구조를 이용한다
        삽입 시간       삭제 시간
리스트      1              N
힙        logN          logN
"""


class Solution(object):
    def countBits(self, num):
        """
        :type num: int
        :rtype: List[int]
        """
        ret = [0]
        for i in range(1, num + 1):
            ret.append(ret[i >> 1] + (i & 1))
        return ret


from __future__ import division
import time
import threading
from grove.button import Button
from grove.gpio import GPIO

__all__ = ["ButtonTypedGpio"]

_CYCLE_PERIOD    = 0.02   # 20 ms
_SINGLE_KEY_TM   = 0.03   # 30 ms
_KEY_INTERVAL    = 0.3    # 300 ms
_LONG_KEY_TM     = 2.0    # 2s

class ButtonTypedGpio(Button):
    '''
    GPIO Button Class

    provide event checking ability to derived class,
    should not use directly by end-user.
    The checking events include:

      - Button.EV_SINGLE_CLICK
      - Button.EV_DOUBLE_CLICK
      - Button.EV_LONG_PRESS
      - Button.EV_LEVEL_CHANGED

    Args:
        pin(int)         : GPIO pin number the button connected.
        low_pressed(bool): optional, default True

            True if the the button gpio level is low when pressed.

            False if level high when pressed
    '''
    # all key states in FSM
    KEY_STATE_IDLE    = 0
    KEY_STATE_DOWN    = 1
    KEY_STATE_ONESHOT = 2
    KEY_STATE_LONG    = 3

    def __init__(self, pin, low_pressed = True):
        super(ButtonTypedGpio, self).__init__(pin)

        self.__low_press = low_pressed

        self.__state = self.KEY_STATE_IDLE
        self.__duration = 0.0
        self.__distance = _KEY_INTERVAL
        self.__thrd_exit = False
        self.__thrd = None

        self.__gpio = GPIO(pin, GPIO.IN)
        self.__gpio.on_event = self.__gpio_event

        if self.__thrd is None or not self.__thrd.is_alive():
            self.__thrd = threading.Thread( \
                    target = ButtonTypedGpio.__thrd_chk_evt, \
                    args = (self,))
            self.__thrd.setDaemon(True)
            self.__thrd.start()

    def __del__(self):
        self.__thrd_exit = True
        while self.__thrd.isAlive():
            time.sleep(_CYCLE_PERIOD / _CYCLE_UNIT)
        self.__thrd.join()

    def is_pressed(self, index = 0):
        '''
        Get the button status if it's being pressed ?

        Args:
            index(int): optional, the arg `index` not be used.

        Returns:
            (bool): True  if the button is being pressed.
                    False if not.
        '''
        v = self.__gpio.read()
        return self.__low_press != bool(v)

    # called by GPIO library
    def __gpio_event(self, pin, value):
        press = self.is_pressed()
        tm = time.time()
        self._send_event(self.EV_LEVEL_CHANGED, press, tm)

    # key event FSM(finite state machine)
    def __key_evt_fsm(self, dt):
        r = 0
        press = self.is_pressed()
        self.__distance = self.__distance + dt

        if self.__state == self.KEY_STATE_IDLE:
            if press:
                self.__duration = 0.0
                self.__state = self.KEY_STATE_DOWN
        elif self.__state == self.KEY_STATE_DOWN:
            if press:
                self.__duration = self.__duration + dt
                if self.__duration >= _SINGLE_KEY_TM:
                    self.__state = self.KEY_STATE_ONESHOT
        elif self.__state == self.KEY_STATE_ONESHOT:
            if not press:
                # print("distance {}".format(self.__distance))
                if self.__distance >= _KEY_INTERVAL:
                    r = self.EV_SINGLE_CLICK
                else:
                    r = self.EV_DOUBLE_CLICK
            else:
                self.__duration = self.__duration + dt
                # print("duration {}".format(self.__duration))
                if self.__duration >= _LONG_KEY_TM:
                    r = self.EV_LONG_PRESS
                    self.__state = self.KEY_STATE_LONG
        elif self.__state == self.KEY_STATE_LONG:
            if not press:
                self.__distance = _KEY_INTERVAL

        if not press:
            self.__state = self.KEY_STATE_IDLE

        if r == self.EV_DOUBLE_CLICK:
            self.__distance = _KEY_INTERVAL
        elif r == self.EV_SINGLE_CLICK:
            self.__distance = 0.0

        return r, press

    # Thread to check events
    def __thrd_chk_evt(self):
        '''
        # prevent dither
        time.sleep(0.01)
        v = self.__gpio.read()
        if self.__low_press == bool(v):
            return
        '''
        self.__last_time = time.time();
        while not self.__thrd_exit:
        # or self.__state != self.KEY_STATE_IDLE:
            t = time.time()
            dt, self.__last_time = t - self.__last_time, t

            r, pressed = self.__key_evt_fsm(dt)
            if r:
                self._send_event(r, pressed, t)
            time.sleep(_CYCLE_PERIOD)


import os
import sys
import pickle
import joblib
import pandas as pd

FEATS = ['gflux', 'diffsumrn', 'numnegrn', 'mag',
         'a_image', 'b_image', 'flags', 'mag_ref',
         'mag_ref_err', 'a_ref', 'b_ref', 'bandnum',
         'n2sig3', 'n3sig3', 'n2sig5', 'n3sig5',
         'n3sig5shift', 'n2sig5shift', 'n2sig3shift',
         'n3sig3shift', 'ellipticity', 'nn_dist_renorm',
         'maglim', 'min_distance_to_edge_in_new', 'ccdid',
         'snr', 'mag_from_limit', 'magdiff', 'spread_model',
         'spreaderr_model', 'flux_ratio', 'lacosmic',
         'gauss', 'scale', 'amp', 'colmeds', 'maskfrac',
         'l1']

if __name__ == '__main__':

    classifier_path = os.getenv('ML_CLASSIFIER')
    imputer_path = os.getenv('ML_IMPUTER')
    scaler_path = os.getenv('ML_SCALER')

    clf = joblib.load(classifier_path)
    imputer = pickle.load(open(imputer_path, 'rb'))
    scaler = pickle.load(open(scaler_path, 'rb'))

    # load in the features
    features = pd.read_csv(sys.argv[1])

    numbers = features['number']
    features = features[FEATS]

    imputed = imputer.transform(features)
    scaled = scaler.transform(imputed)

    clf.n_jobs = 1
    probs = clf.predict_proba(scaled)[:, 1]
    df = pd.DataFrame({'number': numbers, 'score': probs})
    ## the line below is dangerous. it can accidentally modify source file. don't run!!
#     outfile_name = sys.argv[1].replace('.features.csv', '.scored.csv')
    df.to_csv(outfile_name, index=False)


from sklearn.model_selection import train_test_split
from keras.utils import to_categorical
import numpy as np
import os

def train_test_data(DATA_PATH,actions,no_sequences,sequence_length):
    sequences, labels = [],[]
    label_map = {label:num for num,label in enumerate(actions)}
    for action in actions:
        for sequence in range(no_sequences):
            window = []
            for frame_num in range(sequence_length):
                res = np.load(os.path.join(DATA_PATH,action,str(sequence),"{}.npy".format(frame_num)))
                window.append(res)
            sequences.append(window) ## X data (no. of labels* no_sequence,sequence_length,total_keypoints) == (3*20,20,4*33+468*3+21*3 +21*3) == (60,20,1662)
            labels.append(label_map[action]) ## Y data

    X = np.array(sequences)
    y = to_categorical(labels).astype('int')
    X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.05)

    return X_train,X_test,y_train,y_test


#!/usr/bin/env python3
##!/home/klinbrc/bin/python3
#

MAX_ALN_DEPTH  = 2000

AA_CODE_TO_INT = {'A': 0 ,'R': 1 ,'N': 2 ,'D': 3 ,'C': 4 ,\
                  'Q': 5 ,'E': 6 ,'G': 7 ,'H': 8 ,'I': 9 ,\
                  'L': 10,'K': 11,'M': 12,'F': 13,'P': 14,\
                  'S': 15,'T': 16,'W': 17,'Y': 18,'V': 19,};

import sys

dom_ids=open(sys.argv[1]).read().split()

# read alignment depths and domain contact definitions
dom_depths={}
ifile=open('index/cath_s35.aln_depth')
for line in ifile:
    cols=line.split()
    if cols[0] not in dom_ids:
        continue
    dom_depths[cols[0]]=int(cols[1])
ifile.close()

dom_contacts={}
ifile=open('index/cath_s35.condef')
for line in ifile:
    dom_id=line.strip()[1:]
    cont_line=ifile.readline().strip()
    if dom_id not in dom_ids:
        continue
    cols=cont_line.split()
    contacts=[]
    for col in cols:
        (c_i,c_j)=(int(col.split('-')[0]),int(col.split('-')[1]))
        contacts.append((c_i,c_j))
    dom_contacts[dom_id]=contacts
ifile.close()

# read distance thresholds
ifile=open('t_dis_split.ls')
dis_split_list=[]
for line in ifile:
    dis_split_list.append(float(line.strip()))
ifile.close() # split alignments into 100 different sum matrices

sum_aln_mats=[]
for i in range(100):
    sum_aln_mats.append([0]*160000)

import os
import subprocess
import random
random.seed(514)

# for each domain
for dom_id in dom_ids:

    # 1 read alignment
    # 2 put vtml mat to a file
    # 3 get vtml dis
    # 4 add cao mat to the sum

    ifile=open('compact_paln/'+dom_id)
    ifile.readline()
    dom_seq=ifile.readline().strip()
    dom_len=len(dom_seq)

    for line in ifile:
        subjc_seq=ifile.readline().strip()

        if dom_depths[dom_id] > MAX_ALN_DEPTH:
            if random.random() > MAX_ALN_DEPTH/dom_depths[dom_id]:
                continue

        vtml_aln=[0]*400
        for i in range(dom_len):
            if subjc_seq[i] == '-':
                continue
            dom_i = AA_CODE_TO_INT[dom_seq[i]]
            sub_i = AA_CODE_TO_INT[subjc_seq[i]]

            vtml_aln[dom_i*20+sub_i] += 1
            vtml_aln[sub_i*20+dom_i] += 1

        ofile=open(sys.argv[1]+'.vmat','w')
        ofile.write(' '.join(str(x) for x in vtml_aln)+'\n')
        ofile.close()

        dis_out=subprocess.check_output('/usr/bin/Rscript vmat_dis.R ' \
                                        +sys.argv[1]+'.vmat',shell=True)
        # dis_out=subprocess.check_output('/share/apps/R_3.0.2/bin/Rscript' + \
        #                 ' vmat_dis.R '+ sys.argv[1]+'.vmat',shell=True)
        vtml_dis=float(dis_out.split()[1])
        # got VTML distance

        if vtml_dis < 1.5:
            continue

        aln_class=0
        for i in range(len(dis_split_list)):
            if vtml_dis > dis_split_list[i]:
                aln_class += 1

        for contact in dom_contacts[dom_id]:
            c_i=contact[0]
            c_j=contact[1]
            # luckly global contacts are not affected by chain breaks
            if c_j - c_i < 5 :
                continue
            if subjc_seq[c_i]=='-':
                continue
            if subjc_seq[c_j]=='-':
                continue
            cont_dom   = AA_CODE_TO_INT[dom_seq[c_i]]*20 \
                        +AA_CODE_TO_INT[dom_seq[c_j]]

            cont_subjc = AA_CODE_TO_INT[subjc_seq[c_i]]*20 \
                        +AA_CODE_TO_INT[subjc_seq[c_j]]

            sum_aln_mats[aln_class][cont_dom*400 + cont_subjc] += 1
            sum_aln_mats[aln_class][cont_subjc*400 + cont_dom] += 1

    ifile.close()

# output sum
for i in range(100):
    for j in range(160000):
        print(sum_aln_mats[i][j],end=' ')
    print()


#!/usr/local/bin/python3
import os
import sys
import numpy as np
from scipy import misc
from sklearn.neighbors import NearestNeighbors

def read_data(data_dir):
    imgs = []
    for i in range(1, 482):
        img_path = os.path.join(data_dir, 'hand.seq{}.png'.format(i))
        img = misc.imread(img_path)
        imgs.append(img.flatten())

    return np.array(imgs)

def load_stds():
    data_path = 'stds.npy'
    return np.load(data_path)

def comp_std(imgs, stds):
    std = np.std(imgs)
    dists = np.empty(60)

    for idx, s in enumerate(stds):
        dists[idx] = np.mean(np.abs(s - std))

    min_dist_id = np.argmin(dists) + 1
    print('argmin_id = {}'.format(min_dist_id))

if __name__ == '__main__':
    data_dir = sys.argv[1]
    imgs = read_data(data_dir)
    stds = load_stds()
    comp_std(imgs, stds)


import tensorflow as tf
import numpy as np
import sklearn
import sklearn.model_selection

IMAGE_SHAPE = [28, 28]

TRAIN = 'train'
VALIDATE = 'validate'
TEST = 'test'

def _get_data(train_size=None):
    (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()

    if train_size is None:
        train_size = 0.0002

    index_train, index_validate = sklearn.model_selection.train_test_split(
        np.arange(len(x_train)),
        stratify=y_train,
        test_size=1 - train_size,
        random_state=1,
    )

    return dict(
        train=(
            x_train[index_train],
            y_train[index_train],
        ),
        validate=(
            x_train[index_validate],
            y_train[index_validate],
        ),
        test=(
            x_test,
            y_test,
        )
    )

def training_count(train_size=None):
    return np.unique(_get_data(train_size)['train'][1], return_counts=True)

def get_data(data_type, train_size=None):
    return _get_data(train_size)[data_type]

def get_score(y_score, data_type, train_size=None):
    x, y = _get_data(train_size)[data_type]
    return sklearn.metrics.accuracy_score(
        y,
        y_score,
    )


import sys
input = sys.stdin.readline

def is_union(a, b):
    a, b = find(a), find(b)
    if a == b:
        return True
    if a > b:
        a, b = b, a
    parents[b] = a
    return False

def find(a):
    if a != parents[a]:
        parents[a] = find(parents[a])
    return parents[a]

if __name__ == "__main__":
    n = int(input())
    m = int(input())
    parents = [i for i in range(n + 1)]

    for i in range(n):
        line = list(map(int, input().split()))
        for j, e in enumerate(line):
            if e == 1:
                is_union(i+1, j+1)

    path = list(map(int, input().split()))

    pivot = path.pop()
    result = "YES"
    for next in path:
        if is_union(pivot, next):
            continue
        result = "NO"

    print(result)


from printLinkedListValues import printVals

class ListNode(object):
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution(object):
    def mergeKLists(self, lists):
        if len(lists) == 0:
            return None
        if len(lists) == 1:
            return lists[0]

        middle = len(lists)//2
        leftLists = lists[:middle]
        rightLists = lists[middle:]

        self.mergeKLists(leftLists)
        self.mergeKLists(rightLists)

        leftHead = leftLists[0] # head left
        rightHead = rightLists[0] # head right

        head = self.merge2SortedLists(leftHead, rightHead)
        return head

    def merge2SortedLists(self, left, right):
        head = ListNode()
        cur = head
        while left and right:
            if left.val < right.val:
                cur.next = left
                left = left.next
                cur = cur.next
            else:
                cur.next = right
                right = right.next
                cur = cur.next

        while left:
            cur.next = left
            left = left.next
            cur = cur.next

        while right:
            cur.next = right
            right = right.next
            cur = cur.next

        return head.next

test = Solution()
nodeL2 = ListNode(5, None)
nodeL1 = ListNode(4, nodeL2)
left = ListNode(1, nodeL1)

nodeM2 = ListNode(4, None)
nodeM1 = ListNode(3, nodeM2)
middle = ListNode(1, nodeM1)

nodeR1 = ListNode(6, None)
right = ListNode(-1, nodeR1)

testcase = [left, middle, right]
head = test.mergeKLists(testcase)
printVals(head)


import frappe
import time
import os
from frappe.utils import flt, add_months, cint, nowdate, getdate, today, date_diff, month_diff, add_days, get_last_day, get_datetime
from erpnext.stock.doctype.stock_entry.stock_entry import StockEntry
from addons.custom_standard.custom_stock_entry import custom_distribute_additional_costs,repair_gl_entry_tanpa_sl,repair_gl_entry_untuk_ste,patch_cost
from addons.custom_standard.custom_purchase_receipt import repair_gl_entry_untuk_pr
from erpnext.selling.doctype.customer.customer import get_credit_limit, get_customer_outstanding
from erpnext.controllers.accounts_controller import get_taxes_and_charges
from frappe.model.naming import make_autoname, revert_series_if_last

@frappe.whitelist()
def benerin_item():
    item_doc = frappe.get_doc("Item","C-GRAN-P-000044")
    item_doc.disabled = 0
    item_doc.db_update()

@frappe.whitelist()
def mana_ste():
    list_ste = frappe.db.sql(""" SELECT ste.name FROM `tabStock Entry` ste
        JOIN `tabStock Entry Detail` sted ON sted.parent= ste.name
        WHERE ste.stock_opname_number IS NOT NULL
        and ste.stock_entry_type = "Material Receipt"
        and sted.valuation_rate = 0
        and ste.docstatus = 0
        GROUP BY ste.name
     """)

    for row in list_ste:
        ste_doc = frappe.get_doc("Stock Entry",row[0])
        for row_item in ste_doc.items:
            row_item.allow_zero_valuation_rate = 0

        ste_doc.save()
        print(row[0])
        frappe.db.commit()

@frappe.whitelist()
def patch_sle():
    frappe.db.sql(""" UPDATE `tabStock Ledger Entry` set incoming_rate = 0 WHERE incoming_rate > 0 and voucher_type = "Delivery Note" and actual_qty < 0 """)

@frappe.whitelist()
def patch_sle_debug(self,method):
    frappe.db.sql(""" UPDATE `tabStock Ledger Entry` set incoming_rate = 0 WHERE incoming_rate > 0 and voucher_type = "Delivery Note" and actual_qty < 0 """)

@frappe.whitelist()
def patch_sle_benerin():
    frappe.db.sql(""" UPDATE `tabStock Ledger Entry` set incoming_rate = stock_value_difference / actual_qty
     WHERE incoming_rate = 0 AND actual_qty > 0 AND `stock_value_difference` > 0 """)

@frappe.whitelist()
def patch_bin():

    list_bin = frappe.db.sql("""
        SELECT item_code, warehouse, COUNT(NAME) jumlah
        FROM `tabBin`
        GROUP BY item_code,warehouse
        HAVING jumlah > 1;
    """)

    for row in list_bin:
        list_satuan = frappe.db.sql("""
            SELECT NAME FROM `tabBin`
            WHERE item_code = "{}"
            AND warehouse = "{}"
            ORDER BY modified ASC
            LIMIT 1
        """.format(row[0],row[1]))

        if list_satuan:
            frappe.db.sql(""" DELETE FROM `tabBin` WHERE name = "{}" """.format(list_satuan[0][0]))

@frappe.whitelist()
def patch_incoming():
    list_ste = frappe.db.sql(""" SELECT name FROM `tabStock Entry` WHERE name = "STER-PKU-1-23-10-00603" """)
    for row in list_ste:
        ste_doc = frappe.get_doc("Stock Entry",row[0])
        ste_doc.total_incoming_value = ste_doc.total_outgoing_value = 0.0
        for d in ste_doc.get("items"):
            if d.t_warehouse:
                ste_doc.total_incoming_value += flt(d.amount)
            if d.s_warehouse:
                ste_doc.total_outgoing_value += flt(d.amount)

        ste_doc.value_difference = ste_doc.total_incoming_value - ste_doc.total_outgoing_value
        print(ste_doc.value_difference)
        print(row[0])
        ste_doc.db_update()

@frappe.whitelist()
def patch_repack():
    list_ste = frappe.db.sql("""
        SELECT name FROM `tabStock Entry` ste
        WHERE ste.name IN ("STERE-BDG-1-23-03-00001") """)

    for row in list_ste:
        ste_doc = frappe.get_doc("Stock Entry", row[0])
        amount = 0
        total_qty = 0
        for item in ste_doc.items:
            if item.s_warehouse:
                amount += item.amount
            elif item.t_warehouse:
                total_qty += item.qty
                # item.valuation_rate = item.basic_rate
                # item.db_update()
        for item in ste_doc.items:
            if item.t_warehouse:
                item.set_basic_rate_manually = 1
                item.basic_rate = amount / total_qty
                rate = item.basic_rate
                item.basic_amount = rate * item.qty
                item.amount = rate * item.qty
                item.db_update()

        ste_doc.update_valuation_rate()
        for item in ste_doc.items:
            item.db_update()
        ste_doc.db_update()
        frappe.db.commit()

        ste_doc = frappe.get_doc("Stock Entry", row[0])
        ste_doc.total_incoming_value = ste_doc.total_outgoing_value = 0.0
        for d in ste_doc.get("items"):
            if d.t_warehouse:
                ste_doc.total_incoming_value += flt(d.amount)
            if d.s_warehouse:
                ste_doc.total_outgoing_value += flt(d.amount)

        ste_doc.value_difference = ste_doc.total_incoming_value - ste_doc.total_outgoing_value
        ste_doc.set_total_amount()
        ste_doc.db_update()
        frappe.db.commit()

        print(ste_doc.value_difference)
        repair_gl_entry_untuk_ste("Stock Entry",ste_doc.name)

@frappe.whitelist()
def patch_repack_2():
    list_ste = frappe.db.sql("""
        SELECT ste.name FROM `tabGL Entry` gl
        JOIN `tabStock Entry` ste ON ste.name=gl.`voucher_no`
        WHERE ste.`stock_entry_type`  = "Repack"
        AND gl.`account` LIKE "%HARGA POKOK%"
        AND gl.`is_cancelled` = 0
    """)

    for row in list_ste:
        ste_doc = frappe.get_doc("Stock Entry", row[0])
        amount = 0
        total_qty = 0
        for item in ste_doc.items:
            if item.s_warehouse:
                if amount == 0:
                    amount += item.amount

            elif item.t_warehouse and amount != 0:

                item.set_basic_rate_manually = 1
                item.basic_rate = amount / item.qty
                rate = item.basic_rate
                item.basic_amount = rate * item.qty
                item.amount = rate * item.qty
                item.db_update()

                amount = 0

        ste_doc.update_valuation_rate()
        for item in ste_doc.items:
            item.db_update()
        ste_doc.db_update()
        frappe.db.commit()

        ste_doc = frappe.get_doc("Stock Entry", row[0])
        ste_doc.total_incoming_value = ste_doc.total_outgoing_value = 0.0
        for d in ste_doc.get("items"):
            if d.t_warehouse:
                ste_doc.total_incoming_value += flt(d.amount)
            if d.s_warehouse:
                ste_doc.total_outgoing_value += flt(d.amount)

        ste_doc.value_difference = ste_doc.total_incoming_value - ste_doc.total_outgoing_value
        ste_doc.set_total_amount()
        ste_doc.db_update()
        frappe.db.commit()

        print(ste_doc.value_difference)
        repair_gl_entry_untuk_ste("Stock Entry",ste_doc.name)

    repost_stock()

@frappe.whitelist()
def patch_ste_rk():
    list_ste = frappe.db.sql("""
       SELECT NAME,docstatus
        FROM `tabStock Entry`
        WHERE name = "STER-BJM-1-23-08-00031" """)

    for row_list in list_ste:
        # print(row_list[0])

        doc = frappe.get_doc("Stock Entry", row_list[0])
        doc.auto_assign_to_rk_account = 1
        doc.db_update()

        # repair_gl_entry_untuk_ste(doc.doctype,doc.name)
        for row in doc.items:
            if row.expense_account == "5001 - HARGA POKOK PENJUALAN - G":
                row.expense_account = "1168.04 - R/K STOCK - G"
                row.db_update()
        if row_list[1] == 1:
            frappe.db.sql(""" UPDATE `tabGL Entry` SET account = "{}" WHERE voucher_no = "{}" and account = "{}" """.format("1168.04 - R/K STOCK - G",row_list[0],"5001 - HARGA POKOK PENJUALAN - G"))
            frappe.db.sql(""" UPDATE `tabGL Entry Custom` SET account = "{}" WHERE no_voucher = "{}" and account = "{}" """.format("1168.04 - R/K STOCK - G",row_list[0],"5001 - HARGA POKOK PENJUALAN - G"))

        print("{}-{}".format(row_list[0],row_list[1]))

@frappe.whitelist()
def patch_ste_rk_receipt():
    list_ste = frappe.db.sql("""
        SELECT name, docstatus FROM `tabStock Entry`
        WHERE stock_entry_type = "Material Receipt" and transfer_status = "From Sync" and auto_assign_to_rk_account = 0 """)

    for row_list in list_ste:
        doc = frappe.get_doc("Stock Entry", row_list[0])
        doc.auto_assign_to_rk_account = 1
        doc.db_update()

        # for row in doc.items:
        #     if row.expense_account == "5001 - HARGA POKOK PENJUALAN - G":
        #         row.expense_account = "1168.04 - R/K STOCK - G"
        #         row.db_update()
        # if row_list[1] == 1:
        #     frappe.db.sql(""" UPDATE `tabGL Entry` SET account = "{}" WHERE voucher_no = "{}" and account = "{}" """.format("1168.04 - R/K STOCK - G",row_list[0],"5001 - HARGA POKOK PENJUALAN - G"))
        #     frappe.db.sql(""" UPDATE `tabGL Entry Custom` SET account = "{}" WHERE no_voucher = "{}" and account = "{}" """.format("1168.04 - R/K STOCK - G",row_list[0],"5001 - HARGA POKOK PENJUALAN - G"))

        print("{}-{}".format(row_list[0],row_list[1]))
@frappe.whitelist()
def patch_doctype():
    ambil_doc = frappe.get_doc("DocType","Stock Ledger Entry")
    check = 0
    remove = []
    ambil_doc.read_only = 0
    ambil_doc.save()
    frappe.db.commit()

@frappe.whitelist()
def start_repair():
    list_document = frappe.db.sql("""
        SELECT sle.voucher_type,sle.`voucher_no`
        FROM `tabStock Ledger Entry` sle

        WHERE sle.posting_date = "2023-03-01" and sle.is_cancelled = 0
        GROUP BY sle.`voucher_no`
        ORDER BY sle.`posting_date`

    """)
    for row in list_document:
        if row[0] == "Stock Reconciliation":
            repair_gl_entry("Stock Reconciliation",row[1])
        elif row[0] == "Stock Entry":
            repair_gl_entry_untuk_ste(row[0],row[1])
        elif row[0] == "Delivery Note":
            repair_gl_entry_untuk_dn(row[0],row[1])
        elif row[0] == "Purchase Receipt":
            repair_gl_entry_untuk_pr(row[0],row[1])

        print(row[1])
        frappe.db.commit()

    enqueue_repost_stock()

@frappe.whitelist()
def repair_gl_entry(doctype,docname):
    docu = frappe.get_doc(doctype, docname)
    delete_sl = frappe.db.sql(""" DELETE FROM `tabStock Ledger Entry` WHERE voucher_no = "{}" """.format(docname))
    delete_gl = frappe.db.sql(""" DELETE FROM `tabGL Entry` WHERE voucher_no = "{}" """.format(docname))
    frappe.flags.repost_gl = True

    frappe.db.sql(""" UPDATE `tabSingles` SET VALUE = 1 WHERE `field` = "allow_negative_stock" """)
    docu.update_stock_ledger()
    docu.make_gl_entries()
    docu.repost_future_sle_and_gle()
    frappe.db.sql(""" UPDATE `tabSingles` SET VALUE = 0 WHERE `field` = "allow_negative_stock" """)

@frappe.whitelist()
def lakukan_testing_1():
    company_doc = frappe.get_doc("Company", "GIAS")

    list_dn = frappe.db.sql("""
       SELECT voucher_no

        FROM(
        SELECT voucher_no, COUNT(voucher_detail_no) AS co FROM `tabStock Ledger Entry`
        WHERE voucher_type = "Delivery Note"
        AND is_cancelled = 0
        GROUP BY voucher_detail_no
        HAVING co > 1
        ) a
        GROUP BY voucher_no """)

    for row in list_dn:
        repair_gl_entry_untuk_dn("Delivery Note",row[0])
        frappe.db.commit()

    repost_stock()

@frappe.whitelist()
def repair_gl_entry_untuk_dn_debug():
    list_dn = frappe.db.sql("""

        SELECT name FROM `tabDelivery Note`
        WHERE posting_date = "2022-05-25"
        ORDER BY posting_date """)
    for row in list_dn:
        repair_gl_entry_untuk_dn("Delivery Note",row[0])
        frappe.db.commit()

    repost_stock()

@frappe.whitelist()
def repair_gl_entry_untuk_dn_debug_2():
    list_dn = frappe.db.sql("""

        SELECT "DO-1-23-10-00473" """)
    for row in list_dn:
        repair_gl_entry_untuk_dn("Delivery Note",row[0])
        frappe.db.commit()

    repost_stock()

@frappe.whitelist()
def repair_gl_entry_untuk_ste_debug_2():
    list_dn = frappe.db.sql("""

        SELECT
        gle.voucher_no, gle.account, gle.debit, gle.credit
        FROM `tabGL Entry` gle
        JOIN `tabStock Entry` ste ON ste.name = gle.`voucher_no`
        WHERE
        gle.voucher_no LIKE "%ster%"
        AND ste.sync_name IS NOT NULL
        AND gle.account LIKE "%biaya lain%"
        AND (gle.debit > 10 OR gle.credit > 10)
        AND gle.`is_cancelled` = 0
        AND ste.`purpose` = "Material Receipt"
        ORDER BY ste.posting_date

    """)
    for row in list_dn:
        repair_gl_entry_untuk_ste("Stock Entry",row[0])
        frappe.db.commit()

    repost_stock()

@frappe.whitelist()
def recount_ste_tools():
    from addons.addons.doctype.stock_recount_tools.stock_recount_tools import start_stock_recount_stei_by_name
    start_stock_recount_stei_by_name("STEI-HO-22-09-01768")
    from addons.addons.doctype.stock_recount_tools.stock_recount_tools import start_stock_recount_stei_by_name
    start_stock_recount_stei_by_name("STEI-HO-1-23-09-02743")
    from addons.addons.doctype.stock_recount_tools.stock_recount_tools import start_stock_recount_stei_by_name
    start_stock_recount_stei_by_name("STEI-HO-1-23-09-02813")

@frappe.whitelist()
def repair_gl_entry_untuk_ste_debug_3():
    from addons.addons.doctype.stock_recount_tools.stock_recount_tools import debug_start_stock_recount_stei_by_name
    debug_start_stock_recount_stei_by_name("db_pku")

@frappe.whitelist()
def repair_gl_entry_untuk_ste_debug_per_site():
    from addons.addons.doctype.stock_recount_tools.stock_recount_tools import debug_start_stock_recount_stei_by_name
    debug_start_stock_recount_stei_by_name("db_kdi")

@frappe.whitelist()
def repair_gl_entry_untuk_ste_debug_per_site2():
    from addons.addons.doctype.stock_recount_tools.stock_recount_tools import debug_start_stock_recount_stei_by_name
    debug_start_stock_recount_stei_by_name("db_kdi")

@frappe.whitelist()
def repair_gl_entry_untuk_ste_debug_per_site3():
    from addons.addons.doctype.stock_recount_tools.stock_recount_tools import debug_start_stock_recount_stei_by_name
    debug_start_stock_recount_stei_by_name("db_kdi")

@frappe.whitelist()
def enqueue_repair_gl_entry_untuk_ste_debug_3():
    enqueued_method = "addons.patch_ste.repair_gl_entry_untuk_ste_debug_3"
    frappe.enqueue(method=enqueued_method,timeout=18000, queue='long')

@frappe.whitelist()
def repair_gl_entry_untuk_ste_debug_4():
    print("test")

@frappe.whitelist()
def repair_gl_entry_untuk_ste_debug():
    list_dn = frappe.db.sql("""

        SELECT name FROM `tabStock Entry` WHERE name IN (
            "STER-JBR-22-04-00001",
            "STER-JBR-22-09-00042",
            "STER-JBR-1-23-09-00076",
            "STER-JBR-1-23-09-00077",
            "STEI-HO-22-03-03298",
            "STEI-HO-22-09-01768",
            "STEI-HO-1-23-09-02743",
            "STEI-HO-1-23-09-02813"
        )

         """)
    for row in list_dn:
        # patch_cost(row[0])
        repair_gl_entry_untuk_ste("Stock Entry",row[0])
        frappe.db.commit()

    repost_stock()

@frappe.whitelist()
def repair_gl_entry_untuk_pr_debug():
    list_dn = frappe.db.sql("""

        SELECT name FROM `tabPurchase Receipt`
        WHERE name IN
        ("PRI-HO-1-23-09-00320") """)
    for row in list_dn:
        repair_gl_entry_untuk_pr("Purchase Receipt",row[0])
        frappe.db.commit()

    repost_stock()

@frappe.whitelist()
def repair_gl_entry_untuk_dn(doctype,docname):
    repair_gl_entry(doctype,docname)
    from addons.custom_standard.view_ledger_create import create_gl_custom_delivery_note_by_name
    create_gl_custom_delivery_note_by_name(docname,"on_submit")

@frappe.whitelist()
def repost_stock():
    from erpnext.stock.doctype.repost_item_valuation.repost_item_valuation import debug_repost
    debug_repost()

@frappe.whitelist()
def enqueue_repost_stock():
    enqueued_method = "addons.patch_ste.repost_stock"
    frappe.enqueue(method=enqueued_method,timeout=18000, queue='long')

@frappe.whitelist()
def cancel_je_auto_repeat():
    list_je = frappe.db.sql("""
        SELECT tje.name
        FROM `tabJournal Entry` tje
        JOIN `tabAuto Repeat` tar ON tar.name = tje.`auto_repeat`
        AND tje.`posting_date` > tar.`end_date`
        AND tje.docstatus = 1
        AND DATEDIFF(tje.`posting_date`, tar.end_date) > 1
    """)
    for row in list_je:
        print(row[0])

@frappe.whitelist()
def isi_ste_log():
    list_ste = frappe.db.sql("""
        SELECT NAME,docstatus,sync_name, transfer_ke_cabang_mana
        FROM `tabStock Entry`
        WHERE sync_name IS NOT NULL
        AND transfer_status="On The Way"
        AND purpose = "Material Issue"
        AND ste_log IS NOT NULL
        AND transfer_ke_cabang_mana NOT IN ("TRIBUANA BUMIPUSAKA","GIAS TANJUNG UNCANG","GIAS TANJUNG PINANG");
    """)
    for row in list_ste:
        ste = frappe.get_doc("Stock Entry",row[0])
        ste_log = ste.ste_log
        print(ste_log)

        from addons.custom_method import check_list_company_gias
        event_producer = check_list_company_gias(ste.transfer_ke_cabang_mana)
        nama_db = event_producer.replace("erp-","db_").replace(".gias.co.id","")
        if nama_db == "db_pal":
            nama_db = "db_palu"

        check_ste = frappe.db.sql(""" SELECT name,docstatus FROM `{}`.`tabStock Entry` WHERE ste_log = "{}" and docstatus < 2 and stock_entry_type = "Material Receipt" """.format(nama_db,ste_log),debug=1)
        if check_ste:
            if check_ste[0][0]:
                if check_ste[0][1] == 0:
                    ste.sync_name = check_ste[0][0]
                    ste.db_update()
                    print(check_ste[0][0])
                    frappe.db.commit()

@frappe.whitelist()
def nyari_buat_balance_sheet():
    company_doc = frappe.get_doc("Company", "GIAS")

    list_dn = frappe.db.sql("""
        SELECT sle.voucher_type,sle.voucher_no ,
        gle.credit AS satu,SUM(sle.stock_value_difference * -1) AS dua,
        gle.credit - SUM(sle.stock_value_difference * -1) AS tiga

         FROM `tabStock Ledger Entry` sle
        LEFT JOIN `tabGL Entry` gle ON sle.voucher_no = gle.voucher_no

        WHERE
        (gle.voucher_type = "Stock Entry" OR gle.voucher_type = "Delivery Note")
        AND (gle.account LIKE "%persediaan%" OR gle.account LIKE "%perlengkapan -%" )
        AND gle.credit > 0
        AND gle.is_cancelled = 0
        GROUP BY gle.voucher_no
        HAVING satu - dua > 0.01 OR satu - dua < -0.01

    """)

    for row in list_dn:
        if row[0] == "Stock Entry":
            repair_gl_entry_untuk_ste(row[0],row[1])
        else:
            repair_gl_entry_untuk_dn(row[0],row[1])
        print(row[0])
        frappe.db.commit()
    repost_stock()


from itertools import combinations
import sys

sys.stdin = open("input2.txt")

N = int(input())
graph = [list(map(int, input().split())) for _ in range(N)]

def calculate(graph):
    global N
    group_dict = dict()

    visited = [[0] * N for _ in range(N)]
    number = 0  # 그룹의 번호

    # 1-1. 구역 구해서, 그룹 정보 딕셔너리 완성 + 그래프 변경하기
    for i in range(N):
        for j in range(N):
            if not visited[i][j]:
                number += 1
                color_number = graph[i][j]
                total_number = 0

                visited[i][j] = 1
                stack = [(i, j)]
                while stack:
                    ci, cj = stack.pop()
                    graph[ci][cj] = number
                    total_number += 1

                    for di, dj in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
                        ni, nj = ci+di, cj+dj
                        if 0 <= ni < N and 0 <= nj < N and graph[ni][nj] == color_number and not visited[ni][nj]:
                            stack.append((ni, nj))
                            visited[ni][nj] = 1

                else:
                    group_dict[number] = {
                        "color": color_number,
                        "total": total_number,
                        "start": (i, j)
                    }

    # 1-2. 인접 두 쌍 구해서 예술점수 구하기
    score = 0
    L = len(group_dict)
    for a, b in combinations(range(1, L+1), 2):
        ab_adjacent = 0
        a_si, a_sj = group_dict[a]["start"]
        a_color = group_dict[a]["color"]
        a_total = group_dict[a]["total"]

        b_color = group_dict[b]["color"]
        b_total = group_dict[b]["total"]

        visited = dict()
        visited[(a_si, a_sj)] = 1
        stack = [(a_si, a_sj)]
        while stack:
            ci, cj = stack.pop()
            for di, dj in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
                ni, nj = ci + di, cj + dj
                if 0 <= ni < N and 0 <= nj < N:
                    if graph[ni][nj] == a and not visited.get((ni, nj)):
                        stack.append((ni, nj))
                        visited[(ni, nj)] = 1
                    elif graph[ni][nj] == b and not visited.get((ni, nj)):
                        ab_adjacent += 1
                        visited[(ni, nj)] = [(ci, cj)]
                    elif graph[ni][nj] == b and visited.get((ni, nj)):
                        if (ci, cj) not in visited[(ni, nj)]:
                            ab_adjacent += 1
                            visited[(ni, nj)].append((ci, cj))

        else:
            score += (a_total + b_total) * a_color * b_color * ab_adjacent
            # print(a, b, "조합", ab_adjacent)
    return score

def rotate(graph):
    global N
    middle = N//2
    new_graph = [[0] * N for _ in range(N)]

    # 2-1. 반시계 90도 회전
    for p in range(N):
        new_graph[N-1-middle][p] = graph[p][middle]
        new_graph[N-1-p][middle] = graph[middle][p]

    # 2-2. 시계 90도 회전
    for i in range(middle):
        for j in range(middle):
            new_graph[j][middle-1-i] = graph[i][j]

    for i in range(middle):
        for j in range(middle+1, N):
            new_graph[j-middle-1][N-1-i] = graph[i][j]

    for i in range(middle+1, N):
        for j in range(middle):
            new_graph[j+middle+1][N-1-i] = graph[i][j]

    for i in range(middle+1, N):
        for j in range(middle+1, N):
            new_graph[j][N+middle-i] = graph[i][j]

    return new_graph

spin_1_graph = rotate(graph)
spin_2_graph = rotate(spin_1_graph)
spin_3_graph = rotate(spin_2_graph)

result = calculate(graph)
result += calculate(spin_1_graph)
result += calculate(spin_2_graph)
result += calculate(spin_3_graph)
print(result)


#!/usr/bin/python

# Note
# This script is used to replace any stop codon with "---".
# Here please careful about when finding the positive selected sites, is it still correct to mapping the sites into the
# original reference protein sequences.

from Bio import SeqIO
from Bio.Seq import Seq
import os
import argparse

# others small task
# compare the result after the tree pruner
def removeStopCode(fasta_input, fasta_out):
    '''
    All the parameters are directories of input and output fasta files
    :param fasta_input:
    :param fasta_out:
    :return:
    '''

    # for the test
    #fasta_input = "/home/luhongzhong/ortholog_subset/cds_align_macse/OG4273_code.fasta"
    #fasta_out ="/home/luhongzhong/ortholog_subset/cds_align_macse_remove_stop_code"
    codon_stop_array = ["TAG", "TGA", "TAA", "UGA", "UAA", "UAG"]
    new_seq = []
    for record in SeqIO.parse(fasta_input, "fasta"):
        print(record.seq)
        tempRecordSeq = list(record.seq)
        for index in range(0, len(record.seq), 3):
            codon = record.seq[index:index + 3]
            print(codon)
            if codon._data in codon_stop_array:
                tempRecordSeq[index:index + 3] = "---"
            #if codon in codon_stop_array:
            #    del tempRecordSeq[index:index + 3]
        record.seq = Seq("".join(tempRecordSeq))
        new_seq.append(record)
    '''
    new_seq2 = []
    for seq in new_seq:
        print(seq.seq)
        if 'Y' not in seq.seq:
            new_seq2.append(seq)
        else:
            pass'''
    # save the updated fasta file
    SeqIO.write(new_seq, fasta_out, "fasta")

# an example
# orthogID = "OG5327"
# source = '/Users/luho/Desktop/example/data/'

# original = source + orthogID + '_code_updated' + '.fasta'
# outfile = source + orthogID + '_code_updated' + '_remove_stop' + '.fasta'
# removeStopCode(fasta_input=original, fasta_out=outfile)

# for the batch process
# the code file is stored in the document file
def main():
    parser = argparse.ArgumentParser(
            formatter_class = argparse.RawDescriptionHelpFormatter,
            description = 'Remove the stop code or "Y" letter in the code sequence.')
    #adding arguments
    parser.add_argument('-n', metavar = 'input_file', type = str, help = 'input file which has unaligned/aligned nucleotide/codon sequence file')
    parser.add_argument('-o', metavar = 'output_file', type = str, help = 'output file to store the result')
    args = parser.parse_args()
    #set up output file name if none is given
    if args.o is None:
        out_file = "data/"
    else:
        out_file = args.o

    nuc_seq_file = args.n

    # for the test
    #nuc_seq_file = "/media/luhongzhong/newdisk/Genomics_data/cds_refine_align/"
    #out_file = "/media/luhongzhong/newdisk/Genomics_data/cds_align_macse_remove_stop_code/"
    # read in the amino acid alignment file
    all_ortholog = os.listdir(nuc_seq_file)

    for i in all_ortholog:
        print(i)
        if "_code" in i or ".fasta" in i: # to make the function can be used for 1011 sce strains
            infile = nuc_seq_file + i
            outfile = out_file + i
            print(infile, outfile)
            removeStopCode(fasta_input=infile, fasta_out=outfile)
        else:
            pass

if __name__ == "__main__":
    main()

# usage
# the fasta file is stored in "cds_all"
# python remove_stop_codon_commond_line.py  -n /Users/luho/Documents/cds_all/ -o /Users/luho/Documents/cds_all0/
# python remove_stop_codon_commond_line.py  -h


"""
Si Unit System based on meter, second, kilogram, Ampere, Kelvin, mole, candela.
"""

from math import pi

from .unit import UnitBase, UnitMeta
from .unit_symbol import UnitSymbol

unit_symbols = (
    UnitSymbol("m", "meter", "length"),
    UnitSymbol("s", "second", "time"),
    UnitSymbol("kg", "kilogram", "mass"),
    UnitSymbol("A", "ampere", "electric current"),
    UnitSymbol("K", "kelvin", "temperature"),
    UnitSymbol("mol", "mole", "amount of substance"),
    UnitSymbol("cd", "candela", "luminous intensity"),
)

class SiUnit(UnitBase, metaclass=UnitMeta, unit_symbols=unit_symbols):
    """
    Class representing SI unitexpr. The fundamental units are available as:
    `SiUnit.m`, `SiUnit.s`, `SiUnit.kg`, `SiUnit.A`, `SiUnit.K`, `SiUnit.mol`
    and `SiUnit.cd`.
    """

    __slots__ = ()

# Base units
m = SiUnit.m
"""
Base unit: Meter
"""
s = SiUnit.s
kg = SiUnit.kg
A = SiUnit.A
K = SiUnit.K
mol = SiUnit.mol
cd = SiUnit.cd

# Derived units
au = SiUnit("au", "astronomical unit", "length", expr=149597870700 * m)
sr = SiUnit("sr", "steradian", "solid angle", expr=SiUnit.expr_type.one)
N = SiUnit("N", "newton", "force", expr=kg * m * s ** -2)
J = SiUnit("J", "joule", "energy", expr=N * m)
eV = SiUnit("eV", "electronvolt", "energy", expr=1.602176634e-19 * J)
W = SiUnit("W", "watt", "power", expr=J / s)
C = SiUnit("C", "coulomb", "charge", expr=A * s)
V = SiUnit("V", "volt", "electric potential difference", expr=J / C)
F = SiUnit("F", "farad", "capacitance", expr=C / V)
ohm = SiUnit("ohm", "ohm", "resistance", expr=V / A)
Pa = SiUnit("Pa", "pascal", "pressure", expr=N * m ** -2)
S = SiUnit("S", "siemens", "electrical conductance", 1 / ohm)
Wb = SiUnit("Wb", "weber", "magnetic flux", expr=V * s)
T = SiUnit("T", "tesla", "magnetic flux density", expr=Wb * m ** -2)
H = SiUnit("H", "henry", "inductance", expr=Wb / A)
lm = SiUnit("lm", "lumen", "luminous flux", expr=cd / sr)
Bq = SiUnit("Bq", "bequerel", "radioactivity (decays per second)", expr=1 / s)
lx = SiUnit("lx", "lux", "illuminance", expr=lm * m ** -2)
Gy = SiUnit("Gy", "gray", "absorbed dose of ionizing radiation", expr=J / kg)

# Constants with exact value
delta_nu_Cs = SiUnit(
    "delta_nu_cs",
    "hyperfine transition of frequency of Cs",
    "frequency",
    expr=91926377 / s,
)

c = SiUnit("c", "speed of light", "velocity", expr=299792458 * m / s)
h = SiUnit("h", "Planck constant", "angular momentum", 6.62607015e-34 * J * s)
h_bar = SiUnit(
    "h_bar", "Reduced Planck constant", "angular momentum", h / (2 * pi)
)
e = SiUnit("e", "elementary charge", "charge", expr=1.606176634e-19 * C)
k = SiUnit(
    "k", "Boltzmann constant", "energy/Kelvin", expr=1.380649e-23 * J / K
)

m_e = SiUnit("m_e", "electron mass", "weigth", expr=9.1093837015e-31 * kg)

N_a = SiUnit(
    "N_a",
    "Avogadro constant",
    "number of molecules per mole",
    expr=6.02214076e-23 / mol,
)

K_cd = SiUnit(
    "K_cd",
    "luminous efficacy",
    "luminous efficacy of 540 THz radiation",
    expr=683 * lm / W,
)


import json
import requests
from bs4 import BeautifulSoup
import discord
from discord.ext import commands
from discord.ext import tasks
import asyncio

import config
from helper_functions import *
from bot import on_command_error

class Anzeige():
    def __init__(self, price=None, time=None, id=None, location=None, title=None, description=None, url=None):
        self.price = price
        self.time = time
        self.id = id
        self.location = location
        self.title = title
        self.description = description
        self.url = url

def ad_to_embed(ad: Anzeige):
    e = discord.Embed(title=ad.title)
    e.description = ad.description
    e.url = ad.url
    e.add_field(name="Preis", value=ad.price)
    e.add_field(name="Ort", value=ad.location)
    if(ad.time != ""):
        e.set_footer(text=ad.time)
    e.color = discord.Color.dark_red()
    return e

class Scraper(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.id = 272455097496240130
        self.config = {
            "url": "https://www.ebay-kleinanzeigen.de/s-mainz/anzeige:angebote/macbook-pro-m1/k0l5315",
            "base_url": "https://www.ebay-kleinanzeigen.de",
            "radius": 60
        }
        if config.PREFIX == ",":
            self.scraper.start()

    async def get_ads(self, c, failed_before=False):
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36 Edg/84.0.522.59'
        }
        ads = []
        try:
            r = requests.get(url=f'{c["url"]}r{c["radius"]}', headers=headers)
            soup = BeautifulSoup(r.text, features="html5lib")
            results = soup.find("div", id="srchrslt-content")
            if results == None:
                channel = self.bot.get_channel(config.LOG_CHANNEL_ID)
                await channel.send(embed=simple_embed(self.bot.user, "no search results", color=discord.Color.orange()))
                return []
            for i in results.find_all("article"):
                ad = Anzeige()
                ad.id = i["data-adid"]
                details = i.find("div", {"class": "aditem-details"})
                ad.price = i.find("p", {"class": "aditem-main--middle--price"}).text
                ad.location = i.find("div", {"class": "aditem-main--top--left"}).text

                ad.description = i.find("div", {"class": "aditem-main"}).contents[3].contents[0]
                try:
                    ad.time = i.find("div", {"class": "aditem-main--top--right"}).text
                except: # Falls eventuell None zurückkommt
                    pass
                title = i.find("a", {"class": "ellipsis"})
                ad.title = title.contents[0]
                ad.url = c["base_url"] + title["href"]
                ads.append(ad)
        except Exception as e:
            channel = self.bot.get_channel(config.LOG_CHANNEL_ID)
            if isinstance(e, ConnectionError) or isinstance(e, requests.exceptions.ConnectionError) or isinstance(e, ConnectionAbortedError):
                await channel.send(embed=simple_embed(self.bot.user, "scraper connection error", color=discord.Color.orange()))
                return []
            await channel.send(embed=simple_embed(self.bot.user, "error in scraper", color=discord.Color.orange()))
            await on_command_error(self.bot.get_channel(config.LOG_CHANNEL_ID), e)
            return await self.get_ads(c, failed_before=True)

        if failed_before:
            channel = self.bot.get_channel(config.LOG_CHANNEL_ID)
            await channel.send(embed=simple_embed(self.bot.user, "scraper worked without an error", color=discord.Color.greyple()))
        return ads

    @tasks.loop(seconds=60)
    async def scraper(self):
        ads = await self.get_ads(self.config)
        with open(config.path + '/json/user_config.json', 'r') as myfile:
            data = json.loads(myfile.read())

        if str(self.id) not in data.keys():
            data[str(self.id)] = {}
            data[str(self.id)]["ids"] = []

        for ad in ads:
            if ad.id not in data[str(self.id)]["ids"]:
                data[str(self.id)]["ids"].append(ad.id)
                channel = self.bot.get_channel(830780216162648094)
                await channel.send(embed=ad_to_embed(ad), content=self.bot.get_user(self.id).mention)

        with open(config.path + '/json/user_config.json', 'w') as myfile:
            json.dump(data, myfile)

    @scraper.before_loop
    async def before_scraper(self):
        await self.bot.wait_until_ready()
        channel = self.bot.get_channel(config.LOG_CHANNEL_ID)
        await channel.send(embed=simple_embed(self.bot.user, "scraper start", color=discord.Color.green()))

    @scraper.after_loop
    async def after_scraper(self):
        channel = self.bot.get_channel(config.LOG_CHANNEL_ID)
        await channel.send(embed=simple_embed(self.bot.user, "scraper stopped.", color=discord.Color.orange()))
        await asyncio.sleep(60)
        self.scraper.restart()

    @scraper.error
    async def scraper_error(self, error):
        channel = self.bot.get_channel(config.LOG_CHANNEL_ID)
        await channel.send(embed=simple_embed(self.bot.user, "scraper error", color=discord.Color.orange()))
        await on_command_error(self.bot.get_channel(config.LOG_CHANNEL_ID), error)

def setup(bot):
    bot.add_cog(Scraper(bot))


from pathlib import Path
from dataclasses import dataclass
from typing import Dict, List, Optional
from requests.models import Response
from torch import nn
from .HFModelHub import HFModelHub
from huggingface_hub import HfApi, Repository
from ..Storage import Storage
from glasses.types import StateDict
from glasses.logger import logger
import requests

@dataclass
class HuggingFaceStorage(Storage):

    ORGANIZATION: str = "glasses"
    root: Path = Path("/tmp/hf_bub/")

    def __post_init__(self):
        self._models: Optional[List[str]] = None
        self._api: HfApi = HfApi()

    def get_models(self) -> List[str]:
        endpoint: str = self._api.endpoint
        res: Response = requests.get(
            f"{endpoint}/api/models", params={"author": self.ORGANIZATION}
        )
        res.raise_for_status()
        models: List[Dict] = res.json()

        # modelId has the following form: <ORGANIZATION>/<REPO_NAME>/<FILE_NAME>
        names: List[str] = [e["modelId"].split("/")[1] for e in models]

        return names

    def put(self, key: str, model: nn.Module):
        save_directory: str = self.root / key
        repo_url = None
        if key in self.models:
            # if a model is already stored, attempting to push a new one will
            # trigger and error since a git repo already exists. We need to first
            # clone the existing repo, and then change the files inside it
            logger.info(f"Model {key} already stored, updating the repo.")
            repo_url = f"{self._api.endpoint}/{self.ORGANIZATION}/{key}"
            # clone the repo
            Repository(save_directory, clone_from=repo_url)

        HFModelHub.save_pretrained(
            model,
            config={},
            save_directory=self.root / key,
            model_id=key,
            push_to_hub=True,
            organization=self.ORGANIZATION,
            repo_url=repo_url,
        )

    def get(self, key: str) -> StateDict:
        state_dict: StateDict = HFModelHub.from_pretrained(f"{self.ORGANIZATION}/{key}")
        return state_dict

    @property
    def models(self) -> List[str]:
        if self._models is None:
            self._models = self.get_models()
        models: List[str] = self._models
        return models


# 2851번 슈퍼마리오
# https://www.acmicpc.net/problem/2851

score = []
for _ in range(10):
    score.append(int(input()))
prefix = [i for i in score]
deference = [0 for _ in range(10)]
for i in range(1, 10):
    prefix[i] += prefix[i-1]

for i, total in enumerate(prefix):
    deference[i] = abs(total - 100)

if deference.count(min(deference)) <= 1:
    print(prefix[deference.index(min(deference))])
else:
    deference.reverse()
    prefix.reverse()
    print(prefix[deference.index(min(deference))])


#!/usr/bin/env python3

import sys
import time
import hashlib

difficulty = 5

class Block():
    def __init__(self, data, previous_hash) -> None:
        self.data = data
        self.previous_hash = previous_hash
        # get timestamp in ms as whole number
        self.timestamp = time.time_ns() // 10**6
        self.nonce = 0
        self.hash = self.get_hash()

    def get_hash(self):
        payload = self.previous_hash + str(self.timestamp) + str(self.nonce) + self.data
        return hashlib.sha256(payload.encode('utf-8')).hexdigest()

    def mine(self, difficulty):
        target = difficulty * '0'

        while(self.hash[:difficulty] != target):
            self.nonce += 1
            self.hash = self.get_hash()

    def __str__(self):
        return 'Block: ' + str(self.__dict__)

def is_chain_valid(chain):
    previous = None
    hash_target = difficulty * '0'

    for i, current in enumerate(chain):
        if i == 0:
            continue
        previous = chain[i-1]

        if current.hash != current.get_hash():
            print('Block ' + str(i) + ': current hashes not equal')
            return False

        if previous.hash != current.previous_hash:
            print('Block ' + str(i) + ': previous hashes not equal')
            return False

        if current.hash[:difficulty] != hash_target:
            print('Block ' + str(i) + ': this block hasn\'t been mined')
            return False

    return True

def main():
    blockchain = []

    blockchain.append(Block('Hi im the first block', '0'))
    print('mining block 0...')
    blockchain[0].mine(difficulty)

    blockchain.append(Block('Yo im the second block', blockchain[-1].hash))
    print('mining block 1...')
    blockchain[1].mine(difficulty)

    blockchain.append(Block('Hey im the third block', blockchain[-1].hash))
    print('mining block 2...')
    blockchain[2].mine(difficulty)

    print('Blockchain is valid: ' + str(is_chain_valid(blockchain)))

    for b in blockchain:
        print(b)

    return 0

if __name__ == '__main__':
    sys.exit(main())


import os
import sys
import shutil
import argparse

parser = argparse.ArgumentParser(description='Build syzygy project:')

parser.add_argument('-b', '--build', help='Recompiles the project', action="store_true")

args = parser.parse_args()

if args.build:
    print('Started build Syzygy project:')
    try:
        shutil.rmtree('./build')
        os.system('mkdir ./build;\
                    cd ./build;\
                    cmake ..;\
                    make;')
    except FileNotFoundError:
        os.system('mkdir ./build;\
                cd ./build;\
                cmake ..;\
                make;')
    print('The syzygy project is built')


import wave
import pyaudio
import numpy as np
import matplotlib.pyplot as plt
from scipy.io.wavfile import write

CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 3
WAVE_OUTPUT_FILENAME ="home/pi/wav/reco.wav"
p = pyaudio.PyAudio()

stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)

print("* recording")

frames = []

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)

print("* done recording")

stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()

print('Audio recorded, now Correlating : ')

def correlate(i,j):
    ifile = wave.open(i)
    ifile1 = wave.open(j)

    samples = ifile.getnframes()
    samples1 = ifile1.getnframes()

    audio = ifile.readframes(samples)
    audio1 = ifile1.readframes(samples1)

    # Convert buffer to float32 using NumPy
    audio_as_np_int16 = np.frombuffer(audio, dtype=np.int8)
    audio_as_np_int16_1 = np.frombuffer(audio1, dtype=np.int8)

    audio_as_np_float32 = audio_as_np_int16.astype(np.float32)
    audio_as_np_float32_1 = audio_as_np_int16_1.astype(np.float32)

    # Normalise float32 array so that values are between -1.0 and +1.0
    max_int16 = 2**15

    audio_normalised = audio_as_np_float32 / max_int16
    audio_normalised_1 = audio_as_np_float32_1 / max_int16

    audio_normalised.resize(audio_normalised_1.size)
    corr_matrix = np.corrcoef(audio_normalised, audio_normalised_1).round(decimals=7)

    return(corr_matrix[0,1])

index = {}
directory = r'home/pi/wav'
for entry in os.scandir(directory):
    if (entry.is_file()):
        index[entry.path[30:34]]=entry.path

#for i in index.keys():
#    print(i,index[i])

for i in index.keys():
    if i=="reco":
        for j in index.keys():
            print(i,j,correlate(index[i],index[j]))


import numpy as np
import tensorflow as tf
import sys

sys.path.append("/data")

class dateset():
    def __init__(self, images, labels):
        self.num_examples = len(images)  # 样本数量
        self.images = np.reshape(images / 255., [-1, 28 * 28])  # 图片归一化加扁平化
        self.labels = np.eye(10)[labels]  # 标签 one-hot 化

    def next_batch(self, batch_size):  # 随机抓一批图片和标签
        batch_index = np.random.choice(self.num_examples, batch_size)
        return self.images[batch_index], self.labels[batch_index]

class mnist():
    def __init__(self):
        # 导入mnist手写数据，x shape: (?,28,28); y shape: (?); x value: 0~255; y value: 0~9
        (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
        self.train = dateset(x_train, y_train)
        self.test = dateset(x_test, y_test)

# 导入手写数据集
mnist = mnist()

# 定义神经网络
class network():
    def __init__(self):
        self.learning_rate = 0.01
        self.x = tf.placeholder(tf.float32, [None, 784], name='x')
        self.y = tf.placeholder(tf.float32, [None, 10], name='y')
        self.w = tf.Variable(tf.random_uniform([784, 10], -1, 1), name="weights")
        self.b = tf.Variable(tf.zeros([10]), name="bias")
        self.full_connect_layer = tf.add(tf.matmul(self.x, self.w), self.b)
        self.pred = tf.nn.softmax(self.full_connect_layer, name='y_pred')

    # 获得正确率
    def get_accuracy(self):
        accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(self.pred, 1), tf.argmax(self.y, 1)), tf.float32))
        return accuracy

    # 自己算梯度更新
    def get_loss1(self):
        # 通过设置log前的最小值不让归0，防止出现 log(0) 未定义
        tf.clip_by_value(self.pred, 1e-15, 1.0)
        self.obj_var = self.pred
        cross_entropy = tf.reduce_mean(-tf.reduce_sum(self.y * tf.log(self.pred), reduction_indices=1))

        w_grad = - tf.matmul(tf.transpose(self.x), self.y - self.pred)
        b_grad = - tf.reduce_mean(tf.matmul(tf.transpose(self.x), self.y - self.pred), reduction_indices=0)

        new_w = self.w.assign(self.w - self.learning_rate * w_grad)
        new_b = self.b.assign(self.b - self.learning_rate * b_grad)
        optimizer = [new_w, new_b]
        return cross_entropy, optimizer, self.obj_var

    # tf算梯度更新
    def get_loss2(self):
        # 通过设置log前的最小值不让归0，防止出现 log(0) 未定义
        tf.clip_by_value(self.pred, 1e-15, 1.0)
        cross_entropy = tf.reduce_mean(-tf.reduce_sum(self.y * tf.log(self.pred), reduction_indices=1))

        w_grad, b_grad = tf.gradients(cross_entropy, [self.w, self.b])

        new_w = self.w.assign(self.w - self.learning_rate * w_grad)
        new_b = self.b.assign(self.b - self.learning_rate * b_grad)
        optimizer = [new_w, new_b]
        return cross_entropy, optimizer

    # tf随机梯度下降
    def get_loss3(self):
        # 通过设置log前的最小值不让归0，防止出现 log(0) 未定义
        tf.clip_by_value(self.pred, 1e-15, 1.0)
        cross_entropy = tf.reduce_mean(-tf.reduce_sum(self.y * tf.log(self.pred), reduction_indices=1))
        optimizer = tf.train.GradientDescentOptimizer(self.learning_rate).minimize(cross_entropy)
        return cross_entropy, optimizer

    # tf动量梯度下降
    def get_loss4(self):
        # 通过设置log前的最小值不让归0，防止出现 log(0) 未定义
        tf.clip_by_value(self.pred, 1e-15, 1.0)
        cross_entropy = tf.reduce_mean(-tf.reduce_sum(self.y * tf.log(self.pred), reduction_indices=1))
        optimizer = tf.train.MomentumOptimizer(self.learning_rate, 0.9).minimize(cross_entropy)
        return cross_entropy, optimizer

def main():
    net = network()
    cross_entropy, optimizer, obj_var = net.get_loss1()
    batch_size = 100
    accuracy = net.get_accuracy()

    """insert code"""
    from scripts.utils.tf_utils import GradientSearcher
    gradient_search = GradientSearcher(name="tensorflow_book.code_06_grist")
    obj_function = tf.reduce_min(tf.abs(obj_var))
    obj_grads = tf.gradients(obj_function, net.x)[0]
    batch_xs, batch_ys = mnist.train.next_batch(batch_size)
    max_val, min_val = np.max(batch_xs), np.min(batch_xs)
    gradient_search.build(batch_size=batch_size, min_val=min_val, max_val=max_val)
    """insert code"""

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        while True:
            total_batch = int(mnist.train.num_examples / batch_size)
            for step in range(total_batch):
                """inserted code"""
                monitor_vars = {'loss': cross_entropy, 'obj_function': obj_function, 'obj_grad': obj_grads}
                feed_dict = {net.x: batch_xs, net.y: batch_ys}
                batch_xs, scores_rank = gradient_search.update_batch_data(session=sess, monitor_var=monitor_vars,
                                                                          feed_dict=feed_dict, input_data=batch_xs, )
                """inserted code"""

                _, loss = sess.run([optimizer, cross_entropy], feed_dict=feed_dict)

                """inserted code"""
                new_batch_xs, new_batch_ys = mnist.train.next_batch(batch_size)
                new_data_dict = {'x': new_batch_xs, 'y': new_batch_ys}
                old_data_dict = {'x': batch_xs, 'y': batch_ys}
                batch_xs, batch_ys = gradient_search.switch_new_data(new_data_dict=new_data_dict,
                                                                     old_data_dict=old_data_dict,
                                                                     scores_rank=scores_rank)
                gradient_search.check_time()
                """inserted code"""

if __name__ == '__main__':
    main()


"""
Melhore o jogo do desafio 28 onde o computador vai "pensar" em um número entre 0 - 10.
Só que agora o jogador vai tentar adivinhar até acertar. No final informe quantos palpites foram necessários.
"""

import random

palpites = 0

computador = (random.randint(0,5))
jogador = int(input("Escolha um número entre 0 e 5: "))

while computador != jogador:

    jogador = int(input("Errou, escolha novamente: "))
    palpites+=1

print(f"Acertou é o {computador}, mesmo com {palpites}, você merece um prêmio!")


class Solution:
    def floodFill(self, image: List[List[int]], sr: int, sc: int, destColor: int) -> List[List[int]]:
        sourceColor=image[sr][sc]
        if sourceColor==destColor: return image
        def dfs(x,y):
            #base conditions
            if x<0 or y<0 or x>len(image)-1 or y>len(image[0])-1 or image[x][y]!=sourceColor:
                return
            image[x][y]=destColor
            dfs(x+1,y)
            dfs(x-1,y)
            dfs(x,y+1)
            dfs(x,y-1)
        dfs(sr,sc)
        return image

    #status: correct
    #Analysis: Time O(n); atmost each elements in the matrix will be visited
    #Space O(1); inplace
    #ref: 1/15/2023P2:track1-cpGrind75;3QuestionPerDay(perQuestion-x3pomo),perDay-x10pomo;35hoursperWeek;15hrPerTopic+15hrPerTopic+5hrBuffer;Day82/82C3Ai3QuestionsFromMostFrequentListOf0/10Day2/5+Blind75WeekOne0/14q,2q/dayDay2/7-,1.binarySearchTimed25Mins-x1pomo(18:30-19:00),2.implement-x1pomo(19:00-19:30),3.floodFillTimed25Mins-x1pomo(19:30-20:00),4.implement-x1pomo(20:00-20:30)=x4pomo(18:30-20:30)


import numpy as np
import pandas as pd
import torch
from sklearn.experimental import enable_iterative_imputer
from sklearn.impute import IterativeImputer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from torch.utils.data import TensorDataset, DataLoader

def dataset_cleaner(dataset, target, excel='2nd'):
    if target == 'AAO criteria':
        del dataset['Siegel criteria']
        del dataset['AAO-HNS guideline']
        dataset = dataset.replace({target: 'A'}, 0)
        dataset = dataset.replace({target: 'B'}, 0)
        dataset = dataset.replace({target: 'C'}, 1)
        dataset = dataset.replace({target: 'D'}, 1)
    elif target == 'Siegel criteria':
        del dataset['AAO criteria']
        del dataset['AAO-HNS guideline']
        dataset = dataset.replace({target: 1}, 0)
        dataset = dataset.replace({target: 2}, 0)
        dataset = dataset.replace({target: 3}, 1)
        dataset = dataset.replace({target: 4}, 1)
    elif target == 'AAO-HNS guideline':
        del dataset['AAO criteria']
        del dataset['Siegel criteria']
        dataset = dataset.replace({target: 1}, 0)
        dataset = dataset.replace({target: 2}, 0)
        dataset = dataset.replace({target: 3}, 1)

    minmax = MinMaxScaler()
    dataset['나이'] = minmax.fit_transform(dataset['나이'].values.reshape(-1, 1))
    dataset['Onset of treatment'] = minmax.fit_transform(dataset['Onset of treatment'].values.reshape(-1, 1))
    dataset['청력검사 (환측) Initial 500Hz'] = minmax.fit_transform(dataset['청력검사 (환측) Initial 500Hz'].values.reshape(-1, 1))
    dataset['청력검사 (환측) Initial 1000Hz'] = minmax.fit_transform(
        dataset['청력검사 (환측) Initial 1000Hz'].values.reshape(-1, 1))
    dataset['청력검사 (환측) Initial2000Hz'] = minmax.fit_transform(dataset['청력검사 (환측) Initial2000Hz'].values.reshape(-1, 1))
    dataset['청력검사 (환측) Initial4000Hz'] = minmax.fit_transform(dataset['청력검사 (환측) Initial4000Hz'].values.reshape(-1, 1))
    dataset['청력검사 (환측)  6분법(검사결과에 적힌대로)'] = minmax.fit_transform(
        dataset['청력검사 (환측)  6분법(검사결과에 적힌대로)'].values.reshape(-1, 1))
    # dataset['청력검사 (환측) Initial SRT'] = minmax.fit_transform(dataset['청력검사 (환측) Initial SRT'].values.reshape(-1, 1))
    dataset['청력검사 (환측) Initial WRS (%)'] = minmax.fit_transform(
        dataset['청력검사 (환측) Initial WRS (%)'].values.reshape(-1, 1))
    dataset['청력검사 (건측) Initial 500Hz'] = minmax.fit_transform(dataset['청력검사 (건측) Initial 500Hz'].values.reshape(-1, 1))
    dataset['청력검사 (건측) Initial 1000Hz'] = minmax.fit_transform(
        dataset['청력검사 (건측) Initial 1000Hz'].values.reshape(-1, 1))
    dataset['청력검사 (건측) Initial2000Hz'] = minmax.fit_transform(dataset['청력검사 (건측) Initial2000Hz'].values.reshape(-1, 1))
    dataset['청력검사 (건측) Initial4000Hz'] = minmax.fit_transform(dataset['청력검사 (건측) Initial4000Hz'].values.reshape(-1, 1))
    dataset['청력검사 (건측)  6분법(검사결과에 적힌대로)'] = minmax.fit_transform(
        dataset['청력검사 (건측)  6분법(검사결과에 적힌대로)'].values.reshape(-1, 1))
    dataset['청력검사 (건측) Initial WRS (%)'] = minmax.fit_transform(
        dataset['청력검사 (건측) Initial WRS (%)'].values.reshape(-1, 1))
    dataset['치료후 청력'] = minmax.fit_transform(dataset['치료후 청력'].values.reshape(-1, 1))
    dataset['청력검사 (환측) 치료후 500Hz'] = minmax.fit_transform(dataset['청력검사 (환측) 치료후 500Hz'].values.reshape(-1, 1))
    dataset['청력검사 (환측) 치료후 1000Hz'] = minmax.fit_transform(dataset['청력검사 (환측) 치료후 1000Hz'].values.reshape(-1, 1))
    dataset['청력검사 (환측) 치료후 2000Hz'] = minmax.fit_transform(dataset['청력검사 (환측) 치료후 2000Hz'].values.reshape(-1, 1))
    dataset['청력검사 (환측) 치료후 4000Hz'] = minmax.fit_transform(dataset['청력검사 (환측) 치료후 4000Hz'].values.reshape(-1, 1))
    dataset['청력검사 (환측) 치료후 6분법(검사결과에 적힌대로)'] = minmax.fit_transform(
        dataset['청력검사 (환측) 치료후 6분법(검사결과에 적힌대로)'].values.reshape(-1, 1))
    dataset['청력검사 (환측) 치료후 WRS (%)'] = minmax.fit_transform(dataset['청력검사 (환측) 치료후 WRS (%)'].values.reshape(-1, 1))

    label = dataset[target]
    del dataset[target]
    del dataset['Number']
    del dataset['등록번호']
    del dataset['이름']
    del dataset['진단']
    del dataset['청력검사 (환측) Initial SRT']  # 추가로 삭제해봄
    del dataset['치료후 청력']
    del dataset['청력검사 (환측) 치료후 500Hz']
    del dataset['청력검사 (환측) 치료후 1000Hz']
    del dataset['청력검사 (환측) 치료후 2000Hz']
    del dataset['청력검사 (환측) 치료후 4000Hz']
    del dataset['청력검사 (환측) 치료후 6분법(검사결과에 적힌대로)']
    del dataset['청력검사 (환측) 치료후 WRS (%)']

    print(dataset.columns)

    return label, dataset

def dataloader_creator(dataset, label, batch_size, index=0, train=True):
    if train:
        dataset = dataset[index]
        label = label[index]

    dataset_float = torch.FloatTensor(dataset)
    label_float = torch.FloatTensor(label)
    label_float = label_float.unsqueeze(1)
    tensor = TensorDataset(dataset_float, label_float)
    dl = DataLoader(tensor, batch_size=batch_size, shuffle=True, drop_last=False)

    return dl

def dataset_creator(target, excel='2nd'):
    if excel == '1st':
        dataset = pd.read_excel('SSNHL_data.xlsx', sheet_name='SSNHL_최종(결측값O)')
        label, dataset = dataset_cleaner(dataset, target)
        imputer = IterativeImputer(random_state=0)
        imputer.fit(dataset)
        dataset = imputer.transform(dataset)
        print('Missing: %d' % sum(np.isnan(dataset).flatten()))
        print(dataset.shape)
        label = label.values

    elif excel == '2nd':
        dataset = pd.read_excel('SSNHL_data.xlsx', sheet_name='SSNHL_최종(결측값제거)')
        label, dataset = dataset_cleaner(dataset, target)
        label = label.values
        dataset = dataset.values

    elif excel == '3rd':
        dataset = pd.read_excel('SSNHL_data.xlsx', sheet_name='SSNHL_최종(결측값O)')
        dataset = dataset.dropna(axis=0)
        label, dataset = dataset_cleaner(dataset, target)
        label = label.values
        dataset = dataset.values

    dataset_train, dataset_test, label_train, label_test = train_test_split(dataset,
                                                                            label,
                                                                            test_size=0.2,
                                                                            random_state=1)
    return dataset_train, dataset_test, label_train, label_test