import lxml
import lxml.html
from hashlib import sha256
from uuid import uuid4
import requests
import re

class Page:

	def __init__(self, link, args, ll=0):
		self.link = link
		self.limit = ll
		self.content = ""
		self.length = 0

		self.sel_normal = args[0]
		self.sel_positive = args[1]
		self.sel_negative = args[2]
		self.sel_unknown = args[3]
		self.reg_remove = args[4]

		self.normal = []
		self.positive = []
		self.negative = []
		self.unknown = []
		self.hashes = {}

	def load(self):
		response = requests.get(self.link)
		self.content = response.content
		self.length = int(response.headers["Content-Length"]
			if "Content-Length" in response.headers
			else len(self.content))

	def filter(self, nodes, rr=None, ll=None):
		rr = rr if rr is not None else self.reg_remove
		ll = ll if ll is not None else self.limit
		texts = []

		for text in nodes:
			text = text.text_content()
			text = re.sub(r"\s+", " ", text)
			text = re.sub(rr[1:-1], "", text) if rr else text

			if text and len(text) > ll:
				texts.append(text)

		return texts

	def parse(self):
		tree = lxml.html.document_fromstring(self.content, parser = lxml.html.HTMLParser(encoding="utf-8"))
		self.normal = self.filter(tree.xpath(self.sel_normal)) if self.sel_normal else []
		self.positive = self.filter(tree.xpath(self.sel_positive)) if self.sel_positive else []
		self.negative = self.filter(tree.xpath(self.sel_negative)) if self.sel_negative else []
		self.unknown = self.filter(tree.xpath(self.sel_unknown)) if self.sel_unknown else []

	def identify(self, predict):
		predict.text(self.normal, objl=1, senl=0)
		predict.text(self.positive, objl=-1, senl=1)
		predict.text(self.negative, objl=-1, senl=-1)
		uids = predict.text(self.unknown, objl=0, senl=0)
		predict.calc()

		for i, uid in enumerate(uids):
			type = predict.type(uid)
			texts = getattr(self, type)
			texts.append(self.unknown[i])

	def munique(self, unique):
		hashes = set(self.hashes.keys())
		remove = hashes - set(unique)

		for hash in remove:
			type, i = self.hashes.pop(hash)
			texts = getattr(self, type)
			texts[i] = None

		self.normal = list(filter(bool, self.normal))
		self.positive = list(filter(bool, self.positive))
		self.negative = list(filter(bool, self.negative))

	def count(self):
		normal = len(self.normal)
		positive = len(self.positive)
		negative = len(self.negative)
		all = sum((normal, positive, negative))

		return {
			"normal" : normal,
			"positive" : positive,
			"negative" : negative,
			"all" : all
		}

	def hash(self):
		hashes = {}

		for i, text in enumerate(self.normal):
			hash = sha256(text.encode("utf-8")).hexdigest()
			hashes[hash] = ("normal", i)

		for i, text in enumerate(self.positive):
			hash = sha256(text.encode("utf-8")).hexdigest()
			hashes[hash] = ("positive", i)

		for i, text in enumerate(self.negative):
			hash = sha256(text.encode("utf-8")).hexdigest()
			hashes[hash] = ("negative", i)

		self.hashes = hashes
		hashes = hashes.keys()
		hashes = list(hashes)

		return hashes

	def export(self):
		texts = []

		for text in self.normal:
			texts.append((text, "normal"))

		for text in self.positive:
			texts.append((text, "positive"))

		for text in self.negative:
			texts.append((text, "negative"))

		return texts


import os

from collections import defaultdict

import pdb

import pandas as pd
import numpy as np

import matplotlib as mpl
# set no display
# matplotlib.use('Agg')
import matplotlib.pyplot as plt
import seaborn as sns

from .. utils import other as uo
from sklearn.utils import shuffle as skl_shuffle

from sklearn import linear_model
from scipy.special import expit

import logging

mpl.rcParams['font.family'] = 'sans-serif'
mpl.rcParams['font.sans-serif'] = 'DejaVu Sans'
mpl.rcParams['pdf.fonttype'] = 42

def main_log_reg(args, argparser):

    dir_design = os.path.join(args.PATH, args.DESIGN)
    df_design = uo.get_design(args, dir_design)

    df_feature = uo.get_exp(args, args.MATRIX)
    df_feature = df_feature.reindex(df_design["sample"], axis=1)
    df_feature = df_feature[df_design["sample"]]

    num_query = len(np.where(df_design[args.SUBGROUP] == 1)[0])
    query_exp = df_feature.loc[args.ID][:num_query]
    ref_exp = df_feature.loc[args.ID][num_query:]

    X = df_feature.loc[[args.ID]]
    X = X.T
    y = df_design[args.SUBGROUP]

    ########################################################
    #FROM:
    #https://scikit-learn.org/stable/auto_examples/linear_model/plot_logistic.html#sphx-glr-auto-examples-linear-model-plot-logistic-py
    ########################################################
    # Fit the classifier
    clf = linear_model.LogisticRegression(solver="liblinear", C = 1e10, penalty = 'l2', max_iter=1000, class_weight='balanced')
    clf.fit(X, y)

    # and plot the result
    #plt.figure(1, figsize=(4, 3))
    #plt.clf()
    #plt.scatter(X.values.ravel(), y, color='black', zorder=20)
    sns_plot = sns.scatterplot(X.values.ravel(), y, color='black')

    min_x = min(X.values.ravel())
    max_x = max(X.values.ravel())
    print(min_x)
    print(max_x)
    X_test = np.linspace(min_x, max_x, 300)

    loss = expit(X_test * clf.coef_ + clf.intercept_).ravel()
    #plt.plot(X_test, loss, color='red', linewidth=3)
    sns_plot = sns.lineplot(X_test, loss, color='r')#, kwargs=dict(linewidth=3))

    sns_plot.axhline(.5, color='.5')

    #plt.xticks(range(-5, 10))
    #plt.yticks([0, 0.5, 1])
    #plt.ylim(-.25, 1.25)
    #plt.xlim(-4, 10)
    #plt.legend(('Logistic Regression Model', 'Linear Regression Model'),
    #           loc="lower right", fontsize='small')
    #plt.tight_layout()

    fig_dir = os.path.join(args.OUTDIR, "log_reg", args.DESIGN)
    if not os.path.exists(fig_dir):
        os.makedirs(fig_dir)
    fig_file = os.path.join(fig_dir, args.ID + "_log_reg.pdf")
    sns_plot.figure.savefig(fig_file)
    plt.close()


import os

import numpy as np
import torch

import torch.distributed as dist
from torch.multiprocessing import Process

def init_processes(rank, size, fn, args):
    """ Initialize the distributed environment. """
    os.environ['MASTER_ADDR'] = args.master_address
    os.environ['MASTER_PORT'] = '6020'
    torch.cuda.set_device(args.local_rank)
    dist.init_process_group(backend='nccl', init_method='env://', rank=rank, world_size=size)
    fn(args)
    dist.barrier()
    cleanup()

def cleanup():
    dist.destroy_process_group()

def average_grads(params):
    size = float(dist.get_world_size())
    for param in params:
        if param.requires_grad:
            # _average_tensor(param.grad, size)
            with torch.no_grad():
                dist.all_reduce(param.grad.data, op=dist.ReduceOp.SUM)
                param.grad.data /= size

def average_params(params):
    size = float(dist.get_world_size())
    for param in params:
        # _average_tensor(param, size)
        with torch.no_grad():
            dist.all_reduce(param.data, op=dist.ReduceOp.SUM)
            param.data /= size

def sync_params(params):
    """
    Synchronize a sequence of Tensors across ranks from rank 0.
    """
    for p in params:
        with torch.no_grad():
            dist.broadcast(p, 0)

def all_gather(tensor, log=None):
    if log: log.info("Gathering tensor across {} devices... ".format(dist.get_world_size()))
    gathered_tensors = [
        torch.zeros_like(tensor) for _ in range(dist.get_world_size())
    ]
    with torch.no_grad():
        dist.all_gather(gathered_tensors, tensor)
    return gathered_tensors


#!/usr/bin/python3
""" boxes """

def tests(boxes):
    cles = []
    b = 1
    if boxes == [[]]:
        return b
    elif boxes == []:
        return 0
    elif boxes[0] == []:
        return 0
    else:
        return b

def iterative_dfs(graph, start, m):
    """ function """
    stack, path = [start], []
    while stack:
        vertex = stack.pop()
        if vertex in path:
            continue
        if type(vertex) == int and vertex < m and vertex > -1:
            path.append(vertex)
            for neighbor in graph[vertex]:
                stack.append(neighbor)
    return path

def canUnlockAll(boxes):
    """function """
    b = tests(boxes)
    m = len(boxes)
    if b == 0:
        return False
    else:
        graph = {i: boxes[i] for i in range(len(boxes))}
        return len(iterative_dfs(graph, 0, m)) == len(boxes)


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

from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib.pyplot as plt
import numpy as np
import torch

from utils.plot_utils import interpolate_2d

def test2d(model, t_range, x_range, *, delta_t=0.01, delta_x=0.01, ground_true=None):

    model.eval()
    x_input = np.arange(x_range[0], x_range[1], delta_x)
    t_input = np.arange(t_range[0], t_range[1], delta_t)

    xx, tt = np.meshgrid(x_input, t_input)
    input_array = np.concatenate([tt.reshape(-1, 1), xx.reshape(-1, 1)], axis=1)
    input_tensor = torch.from_numpy(input_array).to(device=torch.device("cuda"), dtype=torch.float)

    pred = model(input_tensor).detach().cpu().numpy()
    if pred.shape[1] == 1:
        pred = pred.reshape(-1)
    elif pred.shape[1] == 2:
        pred = np.sqrt(pred[:, 0] ** 2 + pred[:, 1] ** 2)
    else:
        raise ValueError("don't support {} dims".format(pred.shape[1]))

    pred_extent, pred_image, pred_mesh = interpolate_2d(input_array, pred)

    plt.figure(figsize=(8, 8))
    plt.pcolor(pred_mesh[0], pred_mesh[1], pred_image, cmap="rainbow")
    plt.xlabel("t")
    plt.ylabel("x")
    divider = make_axes_locatable(plt.gca())
    cax = divider.append_axes("right", size="5%", pad="3%")
    plt.colorbar(cax=cax)
    plt.tight_layout()
    plt.savefig("./pred.png")
    plt.close()

    if ground_true is not None:
        gt_extent, gt_image, gt_mesh = interpolate_2d(ground_true[:, 0:2], ground_true[:, 2])

        plt.figure(figsize=(8, 8))
        plt.pcolor(gt_mesh[0], gt_mesh[1], gt_image, cmap="rainbow")
        # plt.imshow(ground_true_mesh.T, origin="lower", extent=ground_true_extent)
        plt.xlabel("t")
        plt.ylabel("x")
        divider = make_axes_locatable(plt.gca())
        cax = divider.append_axes("right", size="5%", pad="3%")
        plt.colorbar(cax=cax)
        plt.tight_layout()
        plt.savefig("./ground_true.png")
        plt.close()

        difference_image = gt_image - pred_image
        plt.figure(figsize=(8, 8))
        plt.pcolor(gt_mesh[0], gt_mesh[1], difference_image, cmap="rainbow")
        # plt.imshow(difference_mesh.T, origin="lower", extent=ground_true_extent)
        plt.xlabel("t")
        plt.ylabel("x")
        divider = make_axes_locatable(plt.gca())
        cax = divider.append_axes("right", size="5%", pad="3%")
        plt.colorbar(cax=cax)
        plt.tight_layout()
        plt.savefig("./difference.png")
        plt.close()


import json
import os
import sys

from tvhtokodi import errorNotify, readConfig
from tvhtokodi.files import sendFileTo
from tvhtokodi.tvh import allRecordings

def advertRecordings():
    try:
        recs, total = allRecordings()
        return [r for r in recs if not r["channelname"].startswith("BBC")]
    except Exception as e:
        errorNotify(sys.exc_info()[2], e)

def advertFileNames():
    try:
        recs = advertRecordings()
        return [f["filename"] for f in recs]
    except Exception as e:
        errorNotify(sys.exc_info()[2], e)

def doComSkipFiles(afn):
    try:
        fns = []
        for fn in afn:
            f, ext = os.path.splitext(fn)
            txt = f"{f}.txt"
            if not os.path.exists(txt):
                fns.append(fn)
        return fns
    except Exception as e:
        errorNotify(sys.exc_info()[2], e)

if __name__ == "__main__":
    # cfg = readConfig()
    # afn = advertFileNames()
    with open("advertfiles", "r") as ifn:
        afn = json.load(ifn)
    csafn = doComSkipFiles(afn)
    with open("docomskip.json", "w") as ofn:
        json.dump(csafn, ofn, indent=4)


import cv2
import mediapipe as mp
import time

class HandDetector():
    """Class provides tools to work with mediapipe hands detection

    Attributes:
    mode : boolean
        mode in which mediapipe method will be working
    maxHands : int
        maximum number of hands to detect
    detectionCon : float

    Methods:
    findHands : cv2 image
        return image with the landmarks
    findPosition : list
        return position of the landmarks on our hand image
    """
    def __init__(self, mode=False, maxHands=2, detectionCon=0.8, trackCon=0.8):
        self.mode = mode
        self.maxHands = maxHands
        self.detectionCon = detectionCon
        self.trackCon = trackCon

        self.mpHands = mp.solutions.hands
        self.hands = self.mpHands.Hands(self.mode, self.maxHands, self.detectionCon, self.trackCon)
        self.mpDraw = mp.solutions.drawing_utils

    def findHands(self, img):
        """Return image with the landmarks

        Keyword arguments:
        img -- the image of the hand

        Return:
        img -- same image of the hand but with landmarks on it
        """
        imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        self.results = self.hands.process(imgRGB)
        # print(results.multi_hand_landmarks)

        if self.results.multi_hand_landmarks:
            for handLms in self.results.multi_hand_landmarks:
                self.mpDraw.draw_landmarks(img, handLms, self.mpHands.HAND_CONNECTIONS)

        return img

    def findPosition(self, img, handNo=0):
        """Return position of the landmarks

        Keyword arguments:
        img -- the image of the hand
        handNo -- index of the hand which position we want to know

        Returns:
        lmList -- the list of the landmarks represented as [id, cx, cy]
        """
        lmList = []
        if self.results.multi_hand_landmarks:
            myHand = self.results.multi_hand_landmarks[handNo]

            for id, lm in enumerate(myHand.landmark):
                h, w, c = img.shape
                cx, cy = int(lm.x*w), int(lm.y*h)
                lmList.append([id, cx, cy])

        return lmList

def main():
    pTime = 0
    cTime = 0

    cap = cv2.VideoCapture(0)
    detector = HandDetector()

    while True:
        success, img = cap.read()
        img = detector.findHands(img)
        lmList = detector.findPosition(img)
        if len(lmList) != 0:
            print(lmList[9])

        cTime = time.time()
        fps = 1/(cTime-pTime)
        pTime = cTime

        cv2.putText(img, str(int(fps)), (10, 70), cv2.FONT_HERSHEY_PLAIN, 3, (255,0,255), 3)

        cv2.imshow("Image", img)
        cv2.waitKey(1)

if __name__ == "__main__":
    main()


"""CRMSync

Revision ID: 817e83870d89
Revises: 3254c70a6f37
Create Date: 2017-04-22 14:04:23.304971

"""

# revision identifiers, used by Alembic.
revision = '817e83870d89'
down_revision = '3254c70a6f37'
branch_labels = None
depends_on = None

from alembic import op
import sqlalchemy as sa

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.create_table('sync_campaign',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('job_id', sa.String(length=36), nullable=False),
    sa.Column('created_time', sa.DateTime(), nullable=True),
    sa.Column('last_sync_time', sa.DateTime(), nullable=True),
    sa.Column('campaign_id', sa.Integer(), nullable=True),
    sa.Column('crm_id', sa.String(length=40), nullable=True),
    sa.ForeignKeyConstraint(['campaign_id'], ['campaign_campaign.id'], ),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_table('sync_call',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('created_time', sa.DateTime(), nullable=True),
    sa.Column('call_id', sa.Integer(), nullable=True),
    sa.Column('saved', sa.Boolean(), nullable=True),
    sa.ForeignKeyConstraint(['call_id'], ['calls.id'], ),
    sa.PrimaryKeyConstraint('id')
    )
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('sync_call')
    op.drop_table('sync_campaign')
    ### end Alembic commands ###


import os
import pprintpp as pp
import pandas as pd

# # lambda:
# for sublist in i:
#     for item in sublist:
#         IESnac.append(item)

pastanacIES = 'IESNac'
pastaMGIES = 'IESMG'

# Listar arquivos nacional
IESnac = []
i = []
for pasta, subpasta, arquivo in os.walk(pastanacIES):
	i.append(arquivo)

IESnac = lambda i: [item for sublist in i for item in sublist]

# Listar arquivos MG
IESMG = []
j = []
for pastaMG, subpastaMG, arquivoMG in os.walk(pastaMGIES):
	j.append(arquivoMG)

IESMG = lambda j: [itemMG for sublistMG in j for itemMG in sublistMG]

# Jogar valores da função lambda na variável e montar o df
IESnac = IESnac(i)
df_nac = pd.DataFrame(IESnac)
df_nac.columns = ['Arquivos Nac']
df_nac.sort_values(by=['Arquivos Nac'], inplace=True, ignore_index=True)

IESMG = IESMG(j)
df_MG = pd.DataFrame(IESMG)
df_MG.columns = ['Arquivos MG']
df_MG.sort_values(by=['Arquivos MG'], inplace=True, ignore_index=True)

# print(df_MG.loc[50]['Arquivos MG'])

# df = df_MG
# for i in range(len(df_nac)):
# 	df.at[i,'Arquivos Nac'] = df_nac.loc[i]['Arquivos Nac']

df = pd.concat([df_MG, df_nac], axis=1)

# Exportar para excel
writer = pd.ExcelWriter('Arquivos listados.xlsx', engine = 'xlsxwriter')

df.to_excel(writer, sheet_name='Concat', index = True)
df_MG.to_excel(writer, sheet_name='MG', index = True)
df_nac.to_excel(writer, sheet_name='Nac', index = True)

writer.save()


"""Exercise 10.2. Use capitalize_all to write a function named capitalize_nested that takes
a nested list of strings and returns a new nested list with all strings capitalized."""

def capitalize_all(t):
    res = []
    for s in t:
        res.append(s.capitalize())
    return res

def capitalise_nested(nestedlistofstrings) :
    veryluck = []
    for i in nestedlistofstrings :
        veryluck.append(capitalize_all(i))
    return veryluck

luck = [['a','b','c'],['d'],['e','f'],['g','h','i','j']]
print(capitalise_nested(luck))


# However, they do remember a few key facts about the password:
#
# It is a six-digit number.
# The value is within the range given in your puzzle input.
# Two adjacent digits are the same (like 22 in 122345).
# Going from left to right, the digits never decrease; they only ever increase or stay the same (like 111123 or 135679).
# Other than the range rule, the following are true:
#
# 111111 meets these criteria (double 11, never decreases).
# 223450 does not meet these criteria (decreasing pair of digits 50).
# 123789 does not meet these criteria (no double).
from Day4.classes.Numbers import Numbers

start = 138241
end = 674034
print("Initial search space: " + str(end-start))

limits = []

for i in filter(Numbers.increasing, range(start, end + 1)):
    limits.append(i)
print("New Search space: " + str(len(limits)))

new_limits = []
for i in limits:
    counter = Numbers.counter_thing(i)
    if 2 in counter:
        new_limits.append(i)

print("Search space: " + str(len(new_limits)))


import os
import csv

csvpath = r"C:\Users\major\OneDrive\Documents\WASHSTL201806DATA4-Class-Repository-DATA\Week 3 - Python\Homework\PyBank\Resources\budget_data.csv"
with open(csvpath, "r") as csvfile:
    #find the highest value on the revenue column
    #also find the lowest value on the revenue column
    #what was the biggest growth in a month?
    #what the biggest loss in a month?
    #what average profit or loss?
    csvreader = csv.reader(csvfile)
    print(csvreader) #I want it to read me the highest value\
    #print as list revenue = [csvreader(1)]
    revenue = []
    for data in csvreader:
        #input max of a list in the revenue
        #revenue.append(data[1])
        #print(data[1])
        #print(max(revenue))
        #print(revenue)
        if data[1] != "Revenue":
            revenue.append(int(data[1]))
        #Else if data == int:
            #print("the max is", max(revenue))
print(revenue)
print("the number of months is", len(revenue))
print("the max  is ", max(revenue))
print("the mix is ", min(revenue))


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

import urllib.request, urllib.parse
import requests, time
from bs4 import BeautifulSoup

base_url = "https://bookmeter.com"
params_to_search = "&partial=true&sort=recommended&type=japanese&page=1"

keyword = "お金2.0 新しい経済のルールと生き方 (NewsPicks Book)"
keyword = urllib.parse.quote(keyword)

url_to_get_id = base_url + "/search?keyword=" + keyword + params_to_search

# キーワードを含めたurlでリクエストを送る
f = urllib.request.urlopen(url_to_get_id)
html = f.read().decode("utf-8")

soup = BeautifulSoup(html, "html.parser")

def get_params_to_get_review(offset = 0):
    params = {
        'review_filter': 'none',
        'offset': str(offset),
        'limit': '100'
    }
    return params

def get_json_from_request(url, params):
    r = requests.get(url, params=params)
    print(r)
    # ここで例外処理を入れる
    return r.json()

def get_reviews(path_to_detail):
    # APIに問い合わせるURL
    url_to_get_review = base_url + path_to_detail + "/reviews.json"
    offset = 0

    while True:
        # 特定の本のレビューをAPIから取得
        params_to_get_review = get_params_to_get_review(offset)
        json_data = get_json_from_request(url_to_get_review, params_to_get_review)

        # resourcesの中でfor文を回す→print
        if json_data['resources']:
            with open('/src/src/samples/sample_reviews6.txt', mode='a', encoding='utf-8') as f:
                for i in json_data['resources']:
                    f.write(i['content_tag'] + "\n")
                print("書き込み完了, offset:", offset)

            offset += 100
            time.sleep(10)
        else:
            print('取得終了')
            break

# 検索結果に本が存在するか判定
if soup.select('a[href*="/books/"]'):
    get_reviews(soup.select('a[href*="/books/"]')[0].get('href'))
else:
    print(soup.select('a[href*="/books/"]'))


from curses import COLOR_BLACK
from rich import print
from selenium import webdriver
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 bs4 import BeautifulSoup as b
import pandas as pd
import numpy as np
from bs2json import bs2json
import re
import json
import copy
from copy import deepcopy
import requests
from collections import OrderedDict
from iteration_utilities import unique_everseen
import time
import itertools
import schedule
from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings
from sqlalchemy import create_engine
import datetime
import scrapy
meta_list=[]
class Getmeta():
    def __init__ (self,driver,content_link):
        self.driver=driver
        self.content_link=content_link
    def get_meta(self):
        meta_list.clear()

        # try:
        try:
            self.driver.get(self.content_link)
            self.driver.refresh()
        except:
            try:
                time.sleep(3)
                self.driver.get(self.content_link)
                self.driver.refresh()
            except:
                time.sleep(3)
                self.driver.get(self.content_link)
                self.driver.refresh()

        converter = bs2json()

        try:
            fb= WebDriverWait(self.driver, 40).until(EC.presence_of_element_located((By.XPATH, '//*[@id="root"]/div/div[3]/div/div/div[1]')))
        except:
            try:
                self.driver.refresh()
                fb= WebDriverWait(self.driver, 40).until(EC.presence_of_element_located((By.XPATH, '//*[@id="root"]/div/div[3]/div/div/div[1]')))
            except:
                pass

        meta_dic = {'cat':'','categori_name':'','content_name': '','content_link':self.content_link,'rate':'0','ratings':'0','Size':'','Download':'0','Current Version':'','crawling_date':''}
        html=self.driver.execute_script("return arguments[0].outerHTML;",fb)
        html_soup=b(html,'html.parser')
        converter = bs2json()
        class_find=html_soup.findAll('h1',{'class':'jss16'})
        json_class_find = converter.convertAll(class_find)
        # print(json_class_find)
        print(json_class_find[0]['text'])#title
        meta_dic['content_name']=json_class_find[0]['text']

        class_find=html_soup.findAll('p',{'class':'jss17'})
        json_class_find= converter.convertAll(class_find)
        pattern = '[,+:ا-ی]'

        # print(json_class_find)
        try:
            print(json_class_find[0]['a']['text'])#categori
            meta_dic['categori_name']=json_class_find[0]['a']['text']
        except:
            pass

        for i in range(len(json_class_find)):
            if 'دریافت' in json_class_find[i]['text']:

                print(json_class_find[i]['text'])#download
                meta_dic['Download']=int(float(re.sub(pattern,'', json_class_find[i]['text'])))

            if 'حجم' in json_class_find[i]['text']:
                print(json_class_find[i]['text'])#size
                meta_dic['Size']=json_class_find[i]['text']

            if 'رای ثبت شده' in json_class_find[i]['text']:
                print(json_class_find[i]['text'])#ratings
                meta_dic['ratings']=int(float(re.sub(pattern,'', json_class_find[i]['text'])))

        try:

            class_find=html_soup.findAll('p',{'class':'jss21'})
            json_class_find = converter.convertAll(class_find)
            print(json_class_find[0]['text'])#Rate
            meta_dic['rate']=float(json_class_find[0]['text'])
        except:
            pass
        # print(meta_dic)
        meta_list.append(meta_dic)
        # except:
        #     meta_list.append(meta_dic)


from functools import wraps

from flask import request

from main import db
from main.commons.exceptions import InvalidJWTError, Unauthorized
from main.libs.jwt import extract_jwt_from_header, verify_access_token
from main.libs.log import ServiceLogger
from main.models.item import ItemModel
from main.models.user import UserModel

logger = ServiceLogger(__name__)

def require_token(func):
    @wraps(func)
    def wrapped_func(*args, **kwargs):
        auth_header = request.headers.get("Authorization")
        if not auth_header:
            raise Unauthorized()

        try:
            jwt_str = extract_jwt_from_header(auth_header)
            jwt_payload = verify_access_token(jwt_str)

            user = db.session.get(UserModel, jwt_payload["sub"])
            if user is None:
                raise Unauthorized()

            return func(*args, **kwargs, user=user)

        except InvalidJWTError:
            raise Unauthorized()

    return wrapped_func

def use_request_schema(schema):
    def wrapped_func(func):
        @wraps(func)
        def load_data(*args, **kwargs):
            if request.method in ["POST", "PUT"]:
                data = request.get_json()
            else:
                data = request.args
            data = schema().load(data)
            return func(*args, **kwargs, request_data=data)

        return load_data

    return wrapped_func

def get_item(func):
    @wraps(func)
    def wrapped_func(*args, **kwargs):
        category_id = kwargs.get("category_id")
        item_id = kwargs.get("item_id")
        item = ItemModel.query.filter(
            ItemModel.category_id == category_id, ItemModel.id == item_id
        ).first_or_404()
        return func(*args, **kwargs, item=item)

    return wrapped_func


try:
  from setuptools import setup
except ImportError:
  from distutils.core import setup

config = {
    'description':'Network Tests',
    'author':'Luis B',
    'url': 'URL to get it at.',
    'download_url': 'Where to download it.',
    'author_email': 'lmbeccaria@gmail.com',
    'version': '0.1',
    'install_requires': ['nose'],
    'packages': ['network_connection'],
    'scripts': [],
    'name': 'network_connection'
    }

setup(**config)


import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import FormatStrFormatter
from os import path

ABS_PATH = path.dirname(path.realpath(__file__))

def read_data(choosenFile):
    frame = None
    read_path = path.join(ABS_PATH, 'stat_data', choosenFile)
    if path.exists(read_path):
        frame = pd.read_csv(read_path)
    return frame

#DrawHist- Draws a Histogram that includes more labels along the x-axis such as the values at the edge of each bar, the percentage of buddies in the bar
#and the value at the center of each bar
#The bars will also be coloured depending upon the side of the graph
#data_set is the data the graph will use *****Buddies are currently always on the Y axis****** The Ylabel is the label for the Y axis

def DrawHist(data_set, title, yLabel):
    fig, ax = plt.subplots()
    counts, bins, patches = ax.hist(data_set, facecolor='yellow', edgecolor='gray')
    plt.title(title)
    plt.ylabel(yLabel)
    # Set the ticks to be at the edges of the bins.
    ax.set_xticks(bins)
    # Set the xaxis's tick labels to be formatted with 1 decimal place...
    ax.xaxis.set_major_formatter(FormatStrFormatter('%0.1f'))

    # Change the colors of bars at the edges...
    twentyfifth, seventyfifth = np.percentile(data_set, [25, 75])
    for patch, rightside, leftside in zip(patches, bins[1:], bins[:-1]):
        if rightside < twentyfifth:
            patch.set_facecolor('green')
        elif leftside > seventyfifth:
            patch.set_facecolor('red')

    # Label the raw counts and the percentages below the x-axis...
    bin_centers = 0.5 * np.diff(bins) + bins[:-1]
    for count, x in zip(counts, bin_centers):
        # Label the raw counts
        ax.annotate(str(count), xy=(x, 0), xycoords=('data', 'axes fraction'),
            xytext=(0, -18), textcoords='offset points', va='top', ha='center')

        # Label the percentages
        percent = '%0.0f%%' % (100 * float(count) / counts.sum())
        ax.annotate(percent, xy=(x, 0), xycoords=('data', 'axes fraction'),
        xytext=(0, -32), textcoords='offset points', va='top', ha='center')

    # Give ourselves some more room at the bottom of the plot
    plt.subplots_adjust(bottom=0.15)
    plt.show()

def total_population_time(frame):
    x = np.zeros(frame['ticks'][0])
    y = np.zeros(frame['ticks'][0])
    for i in range(x.size):
        x[i] = i
        for j in range(len(frame.index)):
            age = frame['age'][j]
            birth = frame['birth_tick'][j]
            # If alive at time tick
            if birth <= i and age + birth+1 >= i:
                y[i] += 1
    fig, ax = plt.subplots()
    ax.plot(x, y, label='Total Population')
    ax.grid()
    ax.legend()
    ax.set(xlabel='Time Ticks', ylabel='Population', title='Total Population/Time')
    plt.show()

def species_population_time(frame):
    x = np.zeros(frame['ticks'][0])
    y_tot = np.zeros(frame['ticks'][0])
    y_evil = np.zeros(frame['ticks'][0])
    y_neutral = np.zeros(frame['ticks'][0])
    for i in range(x.size):
        x[i] = i
        for j in range(len(frame.index)):
            age = frame['age'][j]
            birth = frame['birth_tick'][j]
            # If alive at time tick
            if birth <= i and age + birth+1 >= i:
                y_tot[i] += 1
                if frame['type'][j] == 'ObjectType.NEUTRAL':
                    y_neutral[i] += 1
                else:
                    y_evil[i] += 1
    fig, ax = plt.subplots()
    ax.plot(x, y_tot, label='Total')
    ax.plot(x, y_evil, label='Carnivore')
    ax.plot(x, y_neutral, label='Herbivore')
    ax.grid()
    ax.set(xlabel='Time Ticks', ylabel='Population', title='Population/Time')
    ax.legend()
    plt.show()

def total_stats_time(frame):
    x = np.zeros(frame['ticks'][0])
    speed = np.zeros(frame['ticks'][0])
    agility = np.zeros(frame['ticks'][0])
    intelligence = np.zeros(frame['ticks'][0])
    endurance = np.zeros(frame['ticks'][0])
    strength = np.zeros(frame['ticks'][0])
    fertility = np.zeros(frame['ticks'][0])
    bite_size = np.zeros(frame['ticks'][0])

    for i in range(x.size):
        x[i] = i
        num_alive = 0
        for j in range(len(frame.index)):
            age = frame['age'][j]
            birth = frame['birth_tick'][j]
            # If alive at time tick
            if birth <= i and age + birth+1 >= i:
                num_alive += 1
                speed[i] += frame['speed'][j]
                agility[i] += frame['agility'][j]
                intelligence[i] += frame['intelligence'][j]
                endurance[i] += frame['endurance'][j]
                strength[i] += frame['strength'][j]
                fertility[i] += frame['fertility'][j]
                bite_size[i] += frame['bite_size'][j]
        if num_alive != 0:
            speed[i] /= num_alive
            agility[i] /= num_alive
            intelligence[i] /= num_alive
            endurance[i] /= num_alive
            strength[i] /= num_alive
            fertility[i] /= num_alive
            bite_size[i] /= num_alive

    fig, ax = plt.subplots()
    ax.plot(x, speed, label='Speed Average')
    ax.plot(x, agility, label='Agility Average')
    ax.plot(x, intelligence, label='Intelligence Average')
    ax.plot(x, endurance, label='Endurance Average')
    ax.plot(x, strength, label='Strength Average')
    ax.plot(x, fertility, label='Fertility Average')
    ax.plot(x, bite_size, label='Bite Size Average')
    ax.grid()
    ax.set(xlabel='Time Ticks', ylabel='Average Stat Totals', title='Total Stats Average/Time')
    ax.legend(loc="right", bbox_to_anchor=(1.6,.5))
    plt.show()

def species_stats_time(frame):
    x = np.zeros(frame['ticks'][0])
    evil_speed = np.zeros(frame['ticks'][0])
    evil_agility = np.zeros(frame['ticks'][0])
    evil_intelligence = np.zeros(frame['ticks'][0])
    evil_endurance = np.zeros(frame['ticks'][0])
    evil_strength = np.zeros(frame['ticks'][0])
    evil_fertility = np.zeros(frame['ticks'][0])
    evil_bite_size = np.zeros(frame['ticks'][0])

    neutral_speed = np.zeros(frame['ticks'][0])
    neutral_agility = np.zeros(frame['ticks'][0])
    neutral_intelligence = np.zeros(frame['ticks'][0])
    neutral_endurance = np.zeros(frame['ticks'][0])
    neutral_strength = np.zeros(frame['ticks'][0])
    neutral_fertility = np.zeros(frame['ticks'][0])
    neutral_bite_size = np.zeros(frame['ticks'][0])

    for i in range(x.size):
        x[i] = i
        evil_alive = 0
        neutral_alive = 0
        for j in range(len(frame.index)):
            age = frame['age'][j]
            birth = frame['birth_tick'][j]
            # If alive at time tick
            if birth <= i and age + birth+1 >= i:
                if frame['type'][j] == 'ObjectType.NEUTRAL':
                    neutral_alive += 1
                    neutral_speed[i] += frame['speed'][j]
                    neutral_agility[i] += frame['agility'][j]
                    neutral_intelligence[i] += frame['intelligence'][j]
                    neutral_endurance[i] += frame['endurance'][j]
                    neutral_strength[i] += frame['strength'][j]
                    neutral_fertility[i] += frame['fertility'][j]
                    neutral_bite_size[i] += frame['bite_size'][j]
                else:
                    evil_alive += 1
                    evil_speed[i] += frame['speed'][j]
                    evil_agility[i] += frame['agility'][j]
                    evil_intelligence[i] += frame['intelligence'][j]
                    evil_endurance[i] += frame['endurance'][j]
                    evil_strength[i] += frame['strength'][j]
                    evil_fertility[i] += frame['fertility'][j]
                    evil_bite_size[i] += frame['bite_size'][j]
        if neutral_alive != 0:
            neutral_speed[i] /= neutral_alive
            neutral_agility[i] /= neutral_alive
            neutral_intelligence[i] /= neutral_alive
            neutral_endurance[i] /= neutral_alive
            neutral_strength[i] /= neutral_alive
            neutral_fertility[i] /= neutral_alive
            neutral_bite_size[i] /= neutral_alive
        if evil_alive != 0:
            evil_speed[i] /= evil_alive
            evil_agility[i] /= evil_alive
            evil_intelligence[i] /= evil_alive
            evil_endurance[i] /= evil_alive
            evil_strength[i] /= evil_alive
            evil_fertility[i] /= evil_alive
            evil_bite_size[i] /= evil_alive

    fig, ax = plt.subplots()
    ax.plot(x, evil_speed, 'b-', label='Average Carnivore Speed')
    ax.plot(x, evil_agility, 'g-', label='Average Carnivore Agility')
    ax.plot(x, evil_intelligence, 'r-', label='Average Carnivore Intelligence')
    ax.plot(x, evil_endurance, 'c-', label='Average Carnivore Endurance')
    ax.plot(x, evil_strength, 'm-', label='Average Carnivore Strength')
    ax.plot(x, evil_fertility, 'y-', label='Average Carnivore Fertility')
    ax.plot(x, evil_bite_size, 'k-', label='Average Carnivore Bite Size')

    ax.plot(x, neutral_speed, 'b--', label='Average Herbivore Speed')
    ax.plot(x, neutral_agility, 'g--', label='Average Herbivore Agility')
    ax.plot(x, neutral_intelligence, 'r--', label='Average Herbivore Intelligence')
    ax.plot(x, neutral_endurance, 'c--', label='Average Herbivore Endurance')
    ax.plot(x, neutral_strength, 'm--', label='Average Herbivore Strength')
    ax.plot(x, neutral_fertility, 'y--', label='Average Herbivore Fertility')
    ax.plot(x, neutral_bite_size, 'k--', label='Average Herbivore Bite Size')
    ax.grid()
    ax.legend(loc="right", bbox_to_anchor=(1.6,.5))
    ax.set(xlabel='Time Ticks', ylabel='Average Species Stat Totals', title='Average Species Stats/Time')
    plt.show()

def species_strength_intel_time(frame):
    x = np.zeros(frame['ticks'][0])
    evil_intelligence = np.zeros(frame['ticks'][0])
    evil_strength = np.zeros(frame['ticks'][0])

    neutral_intelligence = np.zeros(frame['ticks'][0])
    neutral_strength = np.zeros(frame['ticks'][0])

    for i in range(x.size):
        x[i] = i
        evil_alive = 0
        neutral_alive = 0
        for j in range(len(frame.index)):
            age = frame['age'][j]
            birth = frame['birth_tick'][j]
            # If alive at time tick
            if birth <= i and age + birth+1 >= i:
                if frame['type'][j] == 'ObjectType.NEUTRAL':
                    neutral_intelligence[i] += frame['intelligence'][j]
                    neutral_strength[i] += frame['strength'][j]
                else:
                    evil_intelligence[i] += frame['intelligence'][j]
                    evil_strength[i] += frame['strength'][j]
        if neutral_alive != 0:
            neutral_intelligence[i] /= neutral_alive
            neutral_strength[i] /= neutral_alive
        if evil_alive != 0:
            evil_intelligence[i] /= evil_alive
            evil_strength[i] /= evil_alive

    fig, ax = plt.subplots()
    ax.plot(x, evil_intelligence, 'b-', label='Carnivore Average Intelligence')
    ax.plot(x, evil_strength, 'g-', label='Carnivore Average Strength')

    ax.plot(x, neutral_intelligence, 'b--', label='Herbivore Average Intelligence')
    ax.plot(x, neutral_strength, 'g--', label='Herbivore Average Strength')
    ax.grid()
    ax.legend()
    ax.set(xlabel='Time Ticks', ylabel='Average Strength & Intelligence', title='Average Strength & Intelligence/Time')
    plt.show()

def run_analysis():
    frame = read_data('agent_data.csv')
    herb_frame = read_data('herb_agent_data.csv')
    carn_frame = read_data('carn_agent_data.csv')
    #total_population_time(frame)
    species_population_time(frame)
    # total_stats_time(frame)
    # species_stats_time(frame)
    # species_strength_intel_time(frame)

    """
    if frame is not None:
        DrawHist(frame.loc[:, 'health'], "Health of Buddies", "Number of Buddies")
        DrawHist(frame.loc[:, 'score'], "Buddy Scores", "Number of Buddies")
        DrawHist(frame.loc[:, 'energy'], "Remaining Buddy Energy", "Number of Buddies")
        DrawHist(frame.loc[:, 'age'], "Buddy Age", "Number of Buddies")
        DrawHist(frame.loc[:, 'children'], "Number of Children", "Number of Buddies")
        DrawHist(frame.loc[:, 'speed'], "Buddy Speed", "Number of Buddies")
        DrawHist(frame.loc[:, 'agility'], "Buddy Agility", "Number of Buddies")
        DrawHist(frame.loc[:, 'intelligence'], "Buddy Intelligence", "Number of Buddies")
        DrawHist(frame.loc[:, 'strength'], "Buddy Strength", "Number of Buddies")
        DrawHist(frame.loc[:, 'fertility'], "Buddy Fetility", "Number of Buddies")

    if carn_frame is not None:

        DrawHist(carn_frame.loc[:, 'speed'], "Carnivore Speed", "Number of Carnivores")
        DrawHist(carn_frame.loc[:, 'agility'], "Carnivore Agility", "Number of Carnivores")
        DrawHist(carn_frame.loc[:, 'intelligence'], "Carnivore Intelligence", "Number of Carnivores")
        DrawHist(carn_frame.loc[:, 'strength'], "Carnivore Strength", "Number of Carnivores")
        DrawHist(carn_frame.loc[:, 'fertility'], "Carnivore Fetility", "Number of Carnivores")
        DrawHist(carn_frame.loc[:, 'gene_stability'], "Carnivore Gene Stablitiy", "Number of Carnivores")
        DrawHist(carn_frame.loc[:, 'bite_size'], "Carnivore Bite Size", "Number of Carnivores")

    if herb_frame is not None:
        DrawHist(herb_frame.loc[:, 'speed'], "Herbivore Speed", "Number of Herbivores")
        DrawHist(herb_frame.loc[:, 'agility'], "Herbivore Agility", "Number of Herbivores")
        DrawHist(herb_frame.loc[:,'intelligence'], "Herbivore Intelligence", "Number of Herbivores")
        DrawHist(herb_frame.loc[:, 'strength'], "Herbivore Strength", "Number of Herbivores")
        DrawHist(herb_frame.loc[:, 'fertility'],"Herbivore Fertility", "Number of Herbivores")
        DrawHist(herb_frame.loc[:, 'gene_stability'], "Herbivore Gene Stablitiy", "Number of Herbivores")
        DrawHist(herb_frame.loc[:, 'bite_size'], "Herbivore Bite Size", "Number of Herbivores")
    """
run_analysis()


import milksets.iris
import milksets.seeds

def save_as_tsv(fname, module):
    features, labels = module.load()
    nlabels = [module.label_names[ell] for ell in labels]
    with open(fname, 'w') as ofile:
        for f,n in zip(features, nlabels):
            print >>ofile, "\t".join(map(str,f)+[n])

save_as_tsv('iris.tsv', milksets.iris)
save_as_tsv('seeds.tsv', milksets.seeds)


from __future__ import division
from .expr import expr
from .sexpr import LaplaceDomainExpression

def admittance(arg, causal=True, **assumptions):
    """Create an admittance class for the specified admittance.

    Y(omega) = G(omega) + j * B(omega)

    where G is the conductance and B is the susceptance.

    Admittance is the reciprocal of impedance:

    Z(omega) = 1 / Y(omega)

    """

    expr1 = expr(arg, causal=causal, **assumptions)

    try:
        expr1 = expr1.as_admittance()
    except:
        raise ValueError('Cannot represent %s(%s) as admittance' %
                         (expr1.__class__.__name__, expr1))

    return expr1


from datetime import datetime
import logging

import numpy as np

class Fx(object):

    def __init__(self, video_buffer, enabled=True):
        self.video_buffer = video_buffer
        self.enabled = enabled
        self.timestamp = datetime(2000,1,1)
        self.parameters = dict()
        self.N = video_buffer.resolution
        self.x = np.zeros(shape=(self.N,3))
        self.x[:] = np.expand_dims(np.arange(self.N),axis=0).T
        self.logger = logging.getLogger(__name__)
        self.is_post_process = False

    def __str__(self):
        return self.__class__.__name__

    def update(self):
        if self.enabled:
            return self._update()

    def toggle(self):
        self.enabled = not self.enabled


#!/usr/local/bin/python3

import math

def factorial(num):
    value = 1
    for i in range(num, 0, -1):
        value *= i
    return value

if __name__ == '__main__':
    t = 0
    f_n = factorial(9)
    n = 9
    i = 1
    # calculate the limit
    while f_n > n:
        f_n = factorial(9)*i
        n = math.pow(10, i)-1
        i += 1

    # search curious number
    for num in range(f_n):
        s = 0
        for i in str(num):
            s += factorial(int(i))
            if s == num and s != 1 and s != 2:
                print(str(s) + ' is curious number.')
                t += s
    print(t)


from xlrd import open_workbook
import openpyxl
import datetime
import time

class Excel_opration():
    def __init__(self):
        self.excel_path=input('请输入namelist文件目录：')
        self.template_excel=input('请输入模板文件的目录：')
        self.read_data={}
        self.all_data=[]
        self.final_read_data={}

    def read_excel(self):
        rb=open_workbook(self.excel_path)
        rs=rb.sheet_by_name('COP')
        num_cols=rs.ncols
        num_rows=rs.nrows
        for row in range(1,num_rows):
            for col in range(num_cols):
                self.read_data[rs.row_values(0)[col]]=rs.row_values(row)[col]
            self.final_read_data['Pers.No.']=self.read_data['Pers.No.']
            self.final_read_data['Name'] = self.read_data['Name']
            self.final_read_data['Annual salary'] = self.read_data['Annual salary']
            self.final_read_data['Target Bonus-Annual'] = self.read_data['Target Bonus-Annual']
            self.final_read_data['Ratio'] = self.read_data['Ratio']
            self.all_data.append(self.final_read_data)
            self.read_data={}
            self.final_read_data={}
        print(self.all_data)

    def prepare_data(self):
        for data in self.all_data:
            print(data)
            name=data['Name']
            pers_no=data['Pers.No.']
            file_name='Conversion-'+pers_no+'-'+name+'.XLSX'
            Annual_salary=data['Annual salary']
            Target_Bonus_Annual=data['Target Bonus-Annual']
            Ratio=data['Ratio']
            emplooy_id='Employee ID:  {}'.format(pers_no)
            employee_name='Employee Name:  {}'.format(name)
            time=self.date_time()
            data_time='Effective Date:  {}'.format(time)
            self.write_excel(file_name,emplooy_id,employee_name,data_time,Annual_salary,Target_Bonus_Annual,Ratio)

    def write_excel(self,filename,id,name,time,annual,target,ratio):
        wb=openpyxl.load_workbook(filename=self.template_excel,data_only=False)
        ws=wb.active
        ws.cell(row=3,column=1).value=id
        ws.cell(row=4,column=1).value=name
        ws.cell(row=5, column=1).value =time
        ws.cell(row=10, column=2).value = annual
        ws.cell(row=14, column=2).value = target
        ws.cell(row=14, column=3).value = ratio
        wb.save(filename)

    def date_time(self):
        data=datetime.datetime.now()
        data=str(data)[0:11]
        return data

    def run(self):
        self.read_excel()
        self.prepare_data()
        time.sleep(3)
        print('创建成功')

if __name__ == '__main__':
    excel_opration=Excel_opration()
    excel_opration.run()


#! /usr/bin/python
from fabric.api import *
from fabric.colors import *
env.user='root'
env.hosts=['137.0.30.130','10.1.10.156']
env.passwords={'root@137.0.30.130:22':'vmware','root@10.1.10.156:22':'cloud123456','root@10.1.10.155:22':'cloud123456'}
env.roledefs={
'bridge':['137.0.30.130'],
'test':['10.1.10.155','10.1.10.156']
}
#env.parallel=True
env.colorize_errors=True
env.command_timeout=120
env.gateway='137.0.30.130'

@runs_once
def local_task():
	local("uname -a")
@runs_once
def remote_path():
	path=raw_input("please input your path:\n")
@runs_once
def remote_order():
	order=raw_input("please input your order:\n")
@roles('test')
#@parallel(pool_size=5)
def remote_task(path='.',order='who'):
	with settings(warn_only=True):
		with cd(path):
			print(red("Executing on {} as {}").format(env.host, env.user))
			run(order)
@roles('bridge')
def getfile():
	get('/tmp/zabbix_server.log.old','.')
"""def test():
	path=raw_input("please input your path:\n")
	order=raw_input("please input your order:\n")
	remote_task(path,order)
"""


import cv2
import numpy as np
cap=cv2.VideoCapture(0)
kernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))
fgbg=cv2.bgsegm.createBackgroundSubtractorMOG()
# Fill image with gray color(set each pixel to gray)
image = np.zeros((480, 640, 3), np.uint8)
image[:] = (128, 128, 128)

cv2.imshow('Result', image)

while(True):
    ret,frame=cap.read()

    if not ret:
        break
    mask = np.zeros(frame.shape[:2], dtype="uint8")
    cv2.rectangle(mask, (100, 100), (400, 200), 255, -1)

    frame = cv2.flip(frame, 1)

    fgmask=fgbg.apply(frame)

    btn_mask = cv2.bitwise_and(fgmask, fgmask, mask=mask)
    if(cv2.countNonZero(btn_mask) > 0):
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY )

    cv2.rectangle(frame, (100, 100), (400, 200), (0, 0, 255), 3, cv2.LINE_AA)
    cv2.imshow('frame',frame)
    cv2.imshow('btn', btn_mask)

    if cv2.waitKey(30) == 27:
        break

cap.release()
cv2.destroyAllWindows()


"""
This script aims to test different Pulse-Coupled Neural Network (PCNN) algorithm
Based on :
Zhan, K., Shi, J., Wang, H. et al.
Computational Mechanisms of Pulse-Coupled Neural Networks: A Comprehensive Review.
Arch Computat Methods Eng 24, 573–588 (2017).
https://doi.org/10.1007/s11831-016-9182-3
"""

import os
import numpy as np
import SimpleITK as sitk
import matplotlib.pyplot as plt
from scipy.ndimage import correlate, convolve
from skimage.transform import rescale, rotate
from skimage.util import random_noise
from skimage.filters import median, laplace, gaussian

def PlotArray(Array,Title):

    Figure, Axes = plt.subplots(1, 1, figsize=(5.5, 4.5), dpi=100)
    Axes.imshow(Array, cmap='gray')
    plt.axis('off')
    plt.title(Title)
    plt.tight_layout()
    plt.show()
    plt.close(Figure)

    return
def NormalizeArray(Array):

    N_Array = (Array - Array.min()) / (Array.max()-Array.min())

    return N_Array
def RGB2Gray(RGBImage):
    """
    This function convert color image to gray scale image
    based on matplotlib linear approximation
    """

    R, G, B = RGBImage[:,:,0], RGBImage[:,:,1], RGBImage[:,:,2]
    Gray = 0.2989 * R + 0.5870 * G + 0.1140 * B

    return np.round(Gray).astype('uint8')
def GaussianKernel(Length=5, Sigma=1.):
    """
    Creates gaussian kernel with side length `Length` and a sigma of `Sigma`
    """
    Array = np.linspace(-(Length - 1) / 2., (Length - 1) / 2., Length)
    Gauss = np.exp(-0.5 * np.square(Array) / np.square(Sigma))
    Kernel = np.outer(Gauss, Gauss)
    return Kernel / sum(sum(Kernel))
def CropCenter(Image,CropX,CropY):
    Y, X = Image.shape
    StartX = X//2-(CropX//2)
    StartY = Y//2-(CropY//2)
    return Image[StartY:StartY+CropY,StartX:StartX+CropX]

CurrentDirectory = os.getcwd()
DataDirectory = os.path.join(CurrentDirectory,'Scripts/PCNN/')

Image = sitk.ReadImage(DataDirectory + 'Lena.jpg')
Array = sitk.GetArrayFromImage(Image)
Input = RGB2Gray(Array)
PlotArray(Input,'Input')

S = (Input-Input.min()) / (Input.max()-Input.min()) * 255
S = np.round(S).astype('uint8')

# Algorithm 4, image histogram
Theta = 255
Delta = 1
Vt = 256
Y = np.zeros(S.shape)
H = np.zeros(256)

# Perform analysis
for N in range(256):
    U = S
    Theta = Theta - Delta + Vt * Y
    Y = np.where((U - Theta) > 0, 1, 0)
    H[255 - N] = Y.sum()

npHist, npEdges = np.histogram(S, bins=255)

Figure, Axes = plt.subplots(1, 1, figsize=(5.5, 4.5), dpi=100)
Axes.plot(npEdges[:-1]+0.5,npHist,color=(0,0,1), label='Numpy')
Axes.plot(np.arange(0,256), H,linestyle='none',marker='x',color=(1,0,0), label='PCNN')
plt.legend(loc='best')
plt.tight_layout()
plt.show()
plt.close(Figure)

# Algorithm 5, image segmentation
Input = np.ones((256, 256)) * 230
Input[64:192, 64:192] = 205
Input[:, 128:] = np.round(Input[:, 128:] * 0.5)
PlotArray(Input,'Input')

S = Input
Rows, Columns = S.shape
Y = np.zeros((Rows, Columns))
T = np.zeros((Rows, Columns))
W = GaussianKernel(Length=7, Sigma=1.)
F = S
Beta = 2
Theta = 255 * np.ones((Rows, Columns))
Delta = 1
Vt = 400
FiredNumber = 0
N = 0

while FiredNumber < S.size:

    N += 1
    L = correlate(Y, W, output='float', mode='reflect')
    Theta = Theta - Delta + Vt * Y
    Fire = 1

    while Fire == 1:

        Q = Y
        U = F * (1 + Beta*L)
        Y = (U > Theta) * 1
        if np.array_equal(Q,Y):
            Fire = 0
        else:
            L = correlate(Y, W, output='float', mode='reflect')

    T = T + N*Y
    FiredNumber = FiredNumber + sum(sum(Y))

Output = 256 - T
PlotArray(Output,'Output')

# Algorithm x, feature extraction
def PCNN_Histogram(S):

    Theta = 255
    Delta = 1
    Vt = 256
    Y = np.zeros(S.shape)
    H = np.zeros(256)

    # Perform analysis
    for N in range(256):
        U = S
        Theta = Theta - Delta + Vt * Y
        Y = np.where((U - Theta) > 0, 1, 0)
        H[255 - N] = Y.sum()

    return H
def SpikingCorticalModel(S):

    """
    SCM used for invariant texture retrieval and image processing
    """

    W = np.array([[0.1091, 0.1409, 0.1091],
                  [0.1409, 0,      0.1409],
                  [0.1091, 0.1409, 0.1091]])

    Y = np.zeros(S.shape)
    U = Y
    E = Y + 1

    k = 40
    TS = np.zeros(k)
    for t in range(k):
        U = 0.2 * U + S * correlate(Y, W, output='float', mode='reflect') + S
        E = 0.9 * E + 20 * Y
        X = 1 / (1 + np.exp(E - U))
        Y = (X > 0.5) * 1
        TS[t] = sum(sum(Y))

    return TS

Image = sitk.ReadImage(DataDirectory + 'D12.png')
Array = sitk.GetArrayFromImage(Image)
Input = RGB2Gray(Array)
PlotArray(Input,'Input')

NScaling, NRotation = 2, 3
Figure, Axes = plt.subplots(NScaling*NRotation, 3, figsize=(5.5*NScaling, 4.5*NRotation))
CropY, CropX = np.array(np.array(Input.shape)/2).astype('int')
Line = 0
for Scaling in range(1,NScaling+1):

    ScaledInput = rescale(Input,1/(0.2*Scaling+0.6))

    for Rotation in range(1,NRotation+1):
        RotatedInput = rotate(ScaledInput,Rotation*30-30,resize=True)
        RotatedInput = CropCenter(RotatedInput, CropX, CropY)
        RotatedInput_Normalized = NormalizeArray(RotatedInput)
        H = PCNN_Histogram(RotatedInput_Normalized)
        TS = SpikingCorticalModel(RotatedInput)

        # Plot
        Axes[Line,0].imshow(RotatedInput,cmap='gray')
        Axes[Line,0].set_xticks([])
        Axes[Line,0].set_yticks([])
        Axes[Line,1].plot(H, color=(1, 0, 0))
        Axes[Line,1].set_xticks([])
        Axes[Line,1].set_yticks([])
        Axes[Line,2].plot(TS, color=(1, 0, 0))
        Axes[Line,2].set_xticks([])
        Axes[Line,2].set_yticks([])
        Line += 1
plt.show()
plt.close(Figure)

# Algorithm 6 - Image restoration
Image = sitk.ReadImage(DataDirectory + 'Lena.jpg')
Array = sitk.GetArrayFromImage(Image)
Input = RGB2Gray(Array)
PlotArray(Input,'Input')

Rows, Columns = Input.shape
Size = Input.size

J = random_noise(Input, mode='gaussian', seed=None, clip=True, mean=0, var=0.01)
J = NormalizeArray(J)
PlotArray(J,'Noised')

Input_Median = median(J,mode='reflect')
Input_Median = NormalizeArray(Input_Median)
PlotArray(Input_Median,'Median')
Input_Mean = correlate(J,np.ones((3,3))/9,mode='reflect')
Input_Mean = NormalizeArray(Input_Mean)
PlotArray(Input_Mean,'Mean')

U = np.zeros(Input.shape)
E = U + 1
Y = np.zeros(Input.shape)
B = np.zeros(Input.shape)
T = np.zeros(Input.shape)

f = 0.3
g = 0.99
gamma = 1
N = 0

while sum(sum(B)) < Size:

    N += 1

    for i in range(Rows):
        for j in range(Columns):

            U[i, j] = J[i, j] + f * U[i, j]
            if E[i, j] > 1E2:
                Q = 0
            else:
                Q = 1 / (1 + np.exp(-gamma * (U[i, j] - E[i, j])))

            if Q > 0.5 or E[i, j] < 0.08:
                Y[i, j] = 1
                B[i, j] = 1
                T[i, j] = N
                E[i, j] = 100000
            else:
                Y[i, j] = 0

    E[B != 1] = g * E[B != 1]

S = np.pad(J,1,'symmetric')
T = np.pad(T,1,'symmetric')
I_SCM = np.zeros(Input.shape)
Delta = 0.02

for i in range(1,Rows+1):
    for j in range(1,Columns+1):

        K = T[i-1:i+2,j-1:j+2].flatten()

        if len(np.unique(K)) == 1:
            I_SCM[i-1, j-1] = 1/9 * sum(sum(S[i-1:i+2, j-1:j+2]))
        else:
            Sorted = np.sort(K)

            if Sorted[4] == K[4]:
                I_SCM[i-1, j-1] = S[i, j]
            elif Sorted[0] == K[4]:
                I_SCM[i-1, j-1] = S[i, j] - Delta
            elif Sorted[-1] == K[4]:
                I_SCM[i-1, j-1] = S[i, j] + Delta
            else:
                I_SCM[i-1, j-1] = np.median(S[i-1:i+2, j-1:j+2])
I_SCM = NormalizeArray(I_SCM)
PlotArray(I_SCM,'SCM')

# Algorithm y - Image enhancement (Feature Linking Model FLM)
def GrayStretch(I,Per):

    m, M = FindingMm(I,Per)
    GS = ((I-m) / (M-m) * 255).astype('uint8')

    return GS
def FindingMm(I,Per):
    h = PCNN_Histogram(I)
    All = sum(h)
    ph = h / All
    mth_ceiling = BoundFinding(ph,Per)
    Mph = ph[::-1]
    Mth_floor = BoundFinding(Mph,Per)
    Mth_floor = 256 - Mth_floor + 1
    Difference = np.zeros((256,256)) + np.inf
    for m in range(mth_ceiling,0,-1):
        for M in range(Mth_floor,256):
            if h[m] > 0 and h[M] > 0:
                if np.sum(h[m:M+1]) / All >= Per:
                    Difference[m,M] = M - m

    minD = Difference.min()
    m, M = np.where(Difference == minD)
    minI = m[0]
    MaxI = M[0]

    return [minI,MaxI]
def BoundFinding(ph,Per):
    cumP = np.cumsum(ph)
    n = 1
    residualP = 1 - Per
    while cumP[n-1] < residualP:
        n += 1

    m_ceiling = n

    return m_ceiling
def PCNN_Histogram(S):

    Theta = 255
    Delta = 1
    Vt = 256
    Y = np.zeros(S.shape)
    H = np.zeros(256)

    # Perform analysis
    for N in range(256):
        U = S
        Theta = Theta - Delta + Vt * Y
        Y = np.where((U - Theta) > 0, 1, 0)
        H[255 - N] = Y.sum()

    return H

Image = sitk.ReadImage(DataDirectory + 'Lena.jpg')
Array = sitk.GetArrayFromImage(Image)
Input = RGB2Gray(Array)
PlotArray(Input,'Input')

S = (Input - Input.min()) / (Input.max()-Input.min()) + 1/255
W = np.array([[0.7, 1, 0.7],[1, 0, 1],[0.7, 1, 0.7]])
Y = np.zeros(S.shape)
U = np.zeros(S.shape)
T = np.zeros(S.shape)
SumY = 0
N = 0

Laplacian = np.array([[1/6, 2/3, 1/6],[2/3, -10/3, 2/3],[1/6, 2/3, 1/6]])
Theta = 1 + correlate(S,Laplacian,mode='reflect')
# Theta = 1 + laplace(S,ksize=3)
f = 0.75 * np.exp(-S**2 / 0.16) + 0.05
G = GaussianKernel(7,1)
f = correlate(f, G, mode='reflect')
# f = gaussian(f,sigma=1,mode='reflect')

h = 2E10
d = 2
g = 0.9811
Alpha = 0.01
Beta = 0.03

while SumY < S.size:

    N += 1

    K = correlate(Y,W,mode='reflect')
    Wave = Alpha * K + Beta * S * (K - d)
    U = f * U + S + Wave
    Theta = g * Theta + h * Y
    Y = (U > Theta) * 1
    T += N * Y
    SumY += sum(sum(Y))
    # print(SumY)

T_inv = T.max() + 1 - T
Time = (NormalizeArray(T_inv) * 255).astype('uint8')
Stretched = GrayStretch(Time,0.99)
PlotArray(Stretched,'Output')

Figure, Axes = plt.subplots(1, 1, figsize=(5.5, 4.5), dpi=100)
Axes.hist(Input.flatten()*255, bins=np.arange(0,256), density=True, color=(0,0,1), label='Original')
Axes.hist(Stretched.flatten(), bins=np.arange(0,256), density=True, color=(1,0,0), label='Enhanced')
plt.legend(loc='upper left')
plt.tight_layout()
plt.show()
plt.close(Figure)

H = PCNN_Histogram(Stretched)
Indices = np.where(H == 0)[0]
Suite = np.concatenate([np.diff(Indices),np.array([0])])
Low, High = np.array([0]), np.array([])
i = 0
while i < len(H):
    n = 0
    while H[i+n] == 0:
        n += 1
    if n > 2:
        High = np.concatenate([High,np.array([i])]).astype('int')
        Low = np.concatenate([Low,np.array([i+n-1])]).astype('int')
        i += n
    else:
        i += 1
High = np.concatenate([High,np.array([255])])

Seg = np.zeros(Stretched.shape)
for n in range(len(High)):
    F1 = Stretched > Low[n]
    F2 = Stretched < High[n]
    Seg[F1*F2] = n

a = Seg.copy()
b = np.unique(Seg)
a[a != b[6]] = 100
PlotArray(a,'Seg')


import pynetbox
from slugify import slugify
from check_data_netbox import netbox
from get_data_json import get_device_roles, get_key_data
import contextlib

def get_data_device_role(numerical_order, data):
    role_name = data['Tên vai trò']['{}' .format(numerical_order)]
    if role_name == None:
        add_data = None
    else:
        convert_slug = slugify(role_name)
        slug = convert_slug.lower()
        add_data = list()
        add_data.append(
            dict (
                name= role_name,
                slug= slug,
                vm_role= data['vm_role']['{}' .format(numerical_order)],
            )
        )
    return add_data

def create_device_role(key_data, data):
    for numerical_order in key_data:
        add_data = get_data_device_role(numerical_order, data)
        if add_data == None:
            # line_in_excel = int(numerical_order) + 2
            # print("[TẠO DEVICE ROLE] - dòng {}: add device_roles false" .format(line_in_excel))
            continue
        else:
            try:
                with open('/var/log/logrunning.log', 'w') as f:
                    with contextlib.redirect_stdout(f):
                        netbox.dcim.device_roles.create(add_data)
                line_in_excel = int(numerical_order) + 2
                print("[TẠO DEVICE ROLE] - dòng {}: add device_roles success" .format(line_in_excel))
            except pynetbox.RequestError as e:
                with open('/var/log/logrunning.log', 'w') as f:
                    with contextlib.redirect_stdout(f):
                        print(e.error)
            # print(add_data)
    return

def create_device_role_main():
    data = get_device_roles()
    key_data = get_key_data(data)
    try:
        create_device_role(key_data, data)
        print("Tạo device role thành công")
    except:
        print("Tạo device role không thành công")
    return
# create_device_role_main()


n = int(input())
number = list(input().split())
result = []

for i in range(1, n+1):
    for x in number:
        if int(x) == i:
            result.insert(int(x), number.index(x)+1)
            # insert at index x, IT

print(" ".join(str(element) for element in result))


# Tkinter grid reference: http://www.cnblogs.com/ruo-li-suo-yi/p/7425307.html

from PIL import Image as Img
from tkinter.filedialog import *
# import tkinter

info = []

def make_app():
    # app = Tk()
    Label(app,text='Image Resize tool',font=('Arial',25,'bold')).grid(row=0,columnspan=3)
    Listbox(app,name='lbox',bg='#f2f2f2').grid(row=1,columnspan=3)
    Label(app,text='Select images').grid(row=2,column=0,sticky=W)
    Button(app,text='open',command=ui_select_pic).grid(row=2,column=2,columnspan=2,sticky=W,padx=5)
    Label(app,text='Output path').grid(row=3,column=0,sticky=W)
    Entry(app,textvariable=show_path).grid(row=3,column=1)
    Button(app,text='find',command=ui_output_path).grid(row=3,column=2,sticky=W,padx=5)
    Label(app,text='Resize').grid(row=4,column=0,sticky=W)
    Button(app,text='resize',command=resize).grid(row=4,column=2,columnspan=2,sticky=W,padx=5)
    app.geometry('340x300')
    app.title('App')
    # return app

def ui_select_pic():
    select_pic = askopenfilenames()
    for pic in select_pic:
        pic_name = pic.split('/')[-1]
        app.children['lbox'].insert(END,pic_name)
        info.append(pic)
    # print(info)

def ui_output_path():
    select_path = askdirectory()
    show_path.set(select_path)

def resize():
    size = [60,120]
    for pic in info:
        output = show_path.get()
        name = pic.split('/')[-1]
        image = Img.open(pic)
        for s in size:
            image.resize((s,s)).save(output+'/cut_'+str(s)+name)

app = Tk()
show_path = StringVar() #不知道为什么 必须在这个位置 其他位置报错
make_app()
app.mainloop()


from flask import Flask, render_template, redirect, escape, session, request, url_for
from sample import birthday

app = Flask(__name__)

@app.route('/')
def index ():
    # this is used to "setup" the session with starting values
    session['lyrics'] = birthday.START
    return redirect(url_for("sing"))

@app.route("/sing", methods=['GET', 'POST'])
def sing():
    lyrics = session.get('lyrics')
    if request.method == "GET":
        if lyrics:
            song = birthday.load_lyrics(lyrics)
            return render_template("lyrics.html",song = song)

        else:
            return render_template("drama.html")

    else:
        action = request.form.get('action')
        if lyrics and action:
            song = birthday.load_lyrics(lyrics)
            next_song = song.sing_me_a_song(action)

            if not next_song:
                session['lyrics'] = birthday.lyrics_name(lyrics)
            else:
                session['lyrics'] = birthday.lyrics_name(next_song)

        return redirect(url_for("sing"))

app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
if __name__ == "__main__":
    app.run()


from flask import Flask, jsonify, request, json
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

@app.route('/findcommonletters', methods=['POST'])
def findcommonletters():

    # Retrieve the json that ws sent in the request
    some_json = request.get_json()

    # Access the values in sentence and letters and put them into a string
    s1 = some_json.get('sentence')
    s2 = some_json.get('letters')

    # Convert the strings into sets and find common letters between the sets using the '&' operator and store them in a list
    a = list(set(s1) & set(s2))

    # Return the list of common letters in JSON format
    return jsonify({'letters': a}), 201

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=int("5000"), debug=True)


import torch
import torch.nn as nn
from torchvision.models import vit_b_16
from torchmetrics.classification import MulticlassAccuracy

import data, engine, model, utils

# HYPERPARAMETERS
SEED = 64
NUM_EPOCH = 50
LEARNIGN_RATE = 7e-6 # 3e-4, 4e-5, 7e-6, 5e-7, 3e-9
inchannels = 3
patch_size = 16
embedding_size = 768
img_size = 224
depth = 12
num_class = 101
# CUDA_LAUNCH_BLOCKING=1

device = torch.device("cuda:0" if torch.cuda.is_available() else 'cpu')
# print(device)

torch.manual_seed(SEED)
torch.cuda.manual_seed(SEED)

# BEST MODEL WEIGHTS LINK: https://drive.google.com/file/d/1Z5e9YejKjs3_EJTyDRpvDIl-vjJt3eZC/view?usp=sharing
vit_model = model.ViT(in_channels = inchannels, patch_size = patch_size,
                      embedding_size = embedding_size, img_size = img_size,
                      depth = depth, n_classes = num_class).to(device)

# torch_vit = vit_b_16().to(device)

# vit_model= nn.DataParallel(vit_model).to(device)

loss_fn = torch.nn.CrossEntropyLoss()
accuracy_fn = MulticlassAccuracy(num_classes = num_class).to(device)
optimizer = torch.optim.SGD(vit_model.parameters(), lr = LEARNIGN_RATE, weight_decay=0.03)
# scheduler = torch.optim.lr_scheduler.LinearLR(optimizer, start_factor = 0.1, end_factor = 0.07,
#                                               total_iters = NUM_EPOCH - 10)

# print(f"lr: {scheduler.optimizer.param_groups[0]['lr']}")

train_model, train_loss, test_loss, train_acc, test_acc = engine.train(model = vit_model,
                                                                       train_dataloader = data.train_dataloader,
                                                                       test_dataloader = data.test_dataloader,
                                                                       optimizer = optimizer,
                                                                    #    scheduler = scheduler,
                                                                       loss_fn = loss_fn,
                                                                       accuracy_fn = accuracy_fn,
                                                                       epochs = NUM_EPOCH,
                                                                       device = device)

utils.save_model(model = train_model, target_dir = "./save_model", model_name = "vit_model_7e-6.pth")

utils.plot_graph(train_losses = train_loss, test_losses = test_loss, train_accs = train_acc,
                 test_accs = test_acc, fig_name = "plots/vit_Loss_and_accuracy_plot_7e-6.jpg")


import unittest

import attr

import fwdpy11.class_decorators

@fwdpy11.class_decorators.attr_class_to_from_dict
@fwdpy11.class_decorators.attr_add_asblack
@attr.s(auto_attribs=True)
class FauxClass(object):
    a: float
    b: float

class TestClassDecorators(unittest.TestCase):
    @classmethod
    def setUpClass(self):
        self.f = FauxClass(1.0, 3.0)

    def test_black_pretty_print(self):
        try:
            _ = self.f.asblack()
        except:  # NOQA
            self.fail("self.f.asblack() raised unexpected exception")

    def test_to_from_dict(self):
        d = self.f.asdict()
        self.assertEqual(d["a"], self.f.a)
        self.assertEqual(d["b"], self.f.b)
        f = FauxClass.fromdict(d)
        self.assertEqual(f.a, self.f.a)
        self.assertEqual(f.b, self.f.b)

if __name__ == "__main__":
    unittest.main()


import MeCab
import emoji
import mojimoji
import re
from nltk import ngrams
import spacy
from spacy import displacy

nlp = spacy.load('ja_ginza')
default_t = MeCab.Tagger("-Ochasen")
neologd_t = MeCab.Tagger(" -d /opt/mecab/lib/mecab/dic/mecab-ipadic-neologd")
emoji_lst = emoji.UNICODE_EMOJI
DEF_URL_TAG = "URL"
DEF_EMOJI_TAG = "EMOJI"

def analysis_mecab(text, is_neologd=False):

    def _sep(text):
        tagger = neologd_t if is_neologd else default_t
        return [t for t in tagger.parse(text).split('\n')
                if t not in ["", "EOS"]]

    lst = [t.split("\t") for t in _sep(text)]

    if is_neologd:
        lst = [[s[0]] + s[1].split(",") for s in lst]

    return lst

def sep_by_mecab(text, is_neologd=False, org_form=False):
    if is_neologd:
        idx = 7 if org_form else 0
    else:
        idx = 2 if org_form else 0
    wakati = analysis_mecab(text, is_neologd)
    return [w[idx] for w in wakati]

def get_pos(text, is_neologd=False):
    wakati = analysis_mecab(text, is_neologd=is_neologd)
    if is_neologd:
        pos = [w[1] for w in wakati]
    else:
        pos = [w[3].split("-")[0] for w in wakati]
    return pos

def norm_url(text, url_tag=DEF_URL_TAG):
    url_pattern = r"https?://[\w/:%#\$&\?\(\)~\.=\+\-…]+"
    return re.sub(url_pattern, url_tag, text)

def norm_numeric(text):
    w_lst = sep_by_mecab(text)
    return "".join(["0" if w.isnumeric() else w for w in w_lst])

def norm_emoji(text, emoji_tag=DEF_EMOJI_TAG):
    return "".join([emoji_tag if t in emoji_lst else t for t in text])

def nchars(s, n):
    assert n > 0
    reg = re.compile("(.)\\1{%d,}" % (n - 1))
    while True:
        m = reg.search(s)
        if not m:
            break
        yield m.group(0)
        s = s[m.end():]

def is_continuous_char(text, count):
    c_lst = list(nchars(text, count))
    return len(c_lst) > 0

def is_continuous_word(text, count, org_form=False):
    w_lst = sep_by_mecab(text, org_form)
    e_lst = list(ngrams(w_lst, count))
    return sum([len(set(e)) == 1 for e in e_lst]) != 0

def norm_continuous_char(text, count=3):
    c_lst = list(nchars(text, count))
    for c in c_lst:
        text = text.replace(c, c[0])
    return text

def normalize_text(text):
    text = str(text)
    text = text.lower()  # all lower
    text = mojimoji.zen_to_han(text)  # all hankaku
    text = norm_numeric(text)
    text = norm_emoji(text)
    text = norm_url(text)
    text = norm_continuous_char(text)
    return text

def aster2mask(text):
    return re.sub("(\*){2,}", " [MASK]", text)

def norm_ner(text, ners=["DATE", "MONEY"]):
    doc = nlp(text)
    for ent in doc.ents:
        if ent.label_ in ners:
            text = text.replace(ent.text, f"[{ent.label_}]")

def get_tokens(text):
    doc = nlp(text)
    try:
        sent = [sent for sent in doc.sents][0]
    except IndexError:
        return None, None
    root_head_i = [token.head.i for token in sent if token.dep_ == "ROOT"][0]
    return sent, root_head_i

def is_want_text(sent, root_head_i):
    return  len([token.lemma_ for token in sent if token.head.i == root_head_i and token.lemma_ in ["たい"]]) > 0

def is_not_text(sent, root_head_i):
    return  len([token.lemma_ for token in sent if token.head.i == root_head_i and token.lemma_ in ["ない", "ず"]]) > 0

def is_q_text(sent, root_head_i):
    return  len([token.lemma_ for token in sent if token.head.i == root_head_i and token.lemma_ in ["か"]]) > 0

def is_use_text(text):
    sent, root_head_i = get_tokens(text)
    if sent is None:
        return False
    is_q = is_q_text(sent, root_head_i)
    is_not = is_not_text(sent, root_head_i)
    is_want = is_want_text(sent, root_head_i)
    return is_q or is_not or is_want

def get_words_info_ginza(text, plot=False):
    doc = nlp(text)
    for sent in doc.sents:
        for token in sent:
            print(token.i, token.orth_, token.lemma_, token.pos_, token.tag_, token.dep_, token.head.i)
        print('EOS')
    if plot:
        displacy.serve(doc, style="dep")


from django.shortcuts import render
from WebAppIntermediario.models import Aluno

# Create your views here.

def index(request):
    alunos = Aluno.objects.all()

    chaveAluno ={
        'alunos': alunos
    }

    return render(request, 'index.html', chaveAluno)

def aluno(request, id):
    aluno = Aluno.objects.get(id=id)

    context = {
        'aluno': aluno
    }

    return render(request, 'aluno.html', context)


import sqlite3
import csv

class Iceland_sql():

    def run(self):

        conn = sqlite3.connect('../framework/Produce.db')
        cur = conn.cursor()

        cur.execute('DROP TABLE IF EXISTS Iceland')
        cur.execute('''
        CREATE TABLE "Iceland"(
            "Product_id" TEXT,
            "Image_Url" TEXT,
            "Image_Path" TEXT,
            "Image_Data" BLOP
        )
        ''')

        csv_name ='./iceland_csv/iceland.csv'

        with open(csv_name, encoding='utf-8') as csv_file:
            csv_reader = csv.reader((csv_file))
            for row in csv_reader:
                try:

                    product_id = row[0]
                    image_url =  row[1]
                    image_path =  row[2]
                    with open(image_path,'rb') as f:
                        data = f.read()
                    cur.execute('''INSERT INTO iceland(Product_id,Image_URL,Image_Path,Image_Data)
                            VALUES(?,?,?,?)''', (product_id, image_url, image_path, data))
                    conn.commit()

                except(FileNotFoundError):
                    print(image_path)

        conn.close()


import ast
import webbrowser

from qtpy.QtCore import Qt, Signal, Slot
from qtpy.QtGui import QIcon
from qtpy.QtWidgets import (QHBoxLayout, QHeaderView, QLabel, QPushButton, QSizePolicy, QTableWidget,
                            QTableWidgetItem, QVBoxLayout, QMessageBox)

from cnapy.utils_for_cnapy_api import check_in_identifiers_org

class AnnotationWidget(QVBoxLayout):
    def __init__(self, parent):
        super().__init__()
        self.parent = parent

        lh = QHBoxLayout()
        label = QLabel("Annotations:")
        lh.addWidget(label)

        check_button = QPushButton("identifiers.org check")
        check_button.setIcon(QIcon.fromTheme("list-add"))
        policy = QSizePolicy()
        policy.ShrinkFlag = True
        check_button.setSizePolicy(policy)
        check_button.clicked.connect(self.check_in_identifiers_org)
        lh.addWidget(check_button)
        self.addItem(lh)

        lh2 = QHBoxLayout()
        self.annotation = QTableWidget(0, 2)
        self.annotation.setHorizontalHeaderLabels(
            ["key", "value"])
        self.annotation.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        lh2.addWidget(self.annotation)

        lh3 = QVBoxLayout()
        self.add_anno = QPushButton("+")
        self.add_anno.clicked.connect(self.add_anno_row)
        lh3.addWidget(self.add_anno)
        self.delete_anno = QPushButton("-")
        self.delete_anno.clicked.connect(self.delete_anno_row)
        lh3.addWidget(self.delete_anno)
        self.open_annotation = QPushButton("Open (first)\nin browser")
        self.open_annotation.clicked.connect(self.open_in_browser)
        lh3.addWidget(self.open_annotation)
        lh2.addItem(lh3)
        self.addItem(lh2)

        self.annotation.itemChanged.connect(parent.throttler.throttle)

    def add_anno_row(self):
        i = self.annotation.rowCount()
        self.annotation.insertRow(i)

    def apply_annotation(self, model_element):
        model_element.annotation = {}
        rows = self.annotation.rowCount()
        for i in range(0, rows):
            annotation_item = self.annotation.item(i, 0)
            if annotation_item is None:
                continue
            key = annotation_item.text()
            if self.annotation.item(i, 1) is None:
                value = ""
            else:
                value = self.annotation.item(i, 1).text()
                if value.startswith("["):
                    try:
                        value = ast.literal_eval(value)
                    except: # if parsing as list does not work keep the raw text
                        pass

            model_element.annotation[key] = value

    def check_in_identifiers_org(self):
        check_in_identifiers_org(self.parent)

    deleteAnnotation = Signal(str)
    def delete_anno_row(self):
        row_to_delete = self.annotation.currentRow()
        try:
            identifier_type = self.annotation.item(row_to_delete, 0).text()
            self.deleteAnnotation.emit(identifier_type)
            self.annotation.removeRow(row_to_delete)
        except AttributeError:
            pass

    def open_in_browser(self):
        current_row = self.annotation.currentRow()
        if current_row >= 0:
            try:
                identifier_type = self.annotation.item(current_row, 0).text()
                identifier_value = self.annotation.item(current_row, 1).text()
            except AttributeError:
                pass
            if identifier_value.startswith("["):
                identifier_value = ast.literal_eval(identifier_value)[0]
            url = f"https://identifiers.org/{identifier_type}:{identifier_value}"
            webbrowser.open_new_tab(url)
        else:
            QMessageBox.information(self.parent, 'Select annotation',
                'Select one of the annotations from the list by clicking on a row.')

    def update_annotations(self, annotation):
        self.annotation.itemChanged.disconnect(
            self.parent.throttler.throttle
        )
        self.annotation.setRowCount(len(annotation))
        self.annotation.clearContents()
        i = 0
        for key, anno in annotation.items():
            keyl = QTableWidgetItem(key)
            iteml = QTableWidgetItem(str(anno))
            self.annotation.setItem(i, 0, keyl)
            self.annotation.setItem(i, 1, iteml)
            i += 1

        self.annotation.itemChanged.connect(
            self.parent.throttler.throttle)


#time
#real	0m5.561s
#user	0m2.616s
#sys	0m0.793s

import PIL
from PIL import Image
import cv2
import sklearn
from sklearn.cluster import KMeans
import colorsys

#DEFINES

#CLUSTER_NUM
CLUSTER_NUM = 4

#set analyzing size
RESIZE_WIDTH = 32

#For Param Tuning
PARAM_TUNING = False

def run(cv2_img):

    #get original image size
    img_height,img_width,_ = cv2_img.shape

    # CALC HEIGHT PARAM
    RESIZE_HEIGHT = RESIZE_WIDTH / img_width * img_height

    #Resizing for increasing speed
    cv2_img = cv2.resize(cv2_img, (int(RESIZE_WIDTH), int(RESIZE_HEIGHT)))
    #rest because of using numpy array
    #cv2_img = cv2.cvtColor(cv2_img, cv2.COLOR_BGR2RGB)

    #analyze main 4 color by sklearn
    cv2_img = cv2_img.reshape(
        (cv2_img.shape[0] * cv2_img.shape[1], 3))

    #Clustring Section
    cluster = KMeans(n_clusters = CLUSTER_NUM)
    cluster.fit(X=cv2_img)

    # cluster.cluster_centers_ returns RGB array of each cluster.
    #rgb(0-255, 0-255, 0-255)
    main_rgb_color = cluster.cluster_centers_

    #hsv(0.0-1.0, 0.0-1.0, 0.0-1.0)
    hsv_color = [[], [], [], []]

    #Convert from RGB to HSV
    for i in range(CLUSTER_NUM):
        hsv_color[i] = colorsys.rgb_to_hsv(main_rgb_color[i][0] / 255.0, main_rgb_color[i][1] / 255.0, main_rgb_color[i][2] / 255.0)
        if PARAM_TUNING:
            print (hsv_color[i])

    # Pick the most impact cluster
    # Rescaled to hsv(0.0-1.0, 0.0-1.0, 0.0-1.0)
    color_result = [0.0, 0.0, 0.0]
    impact = highest = 0.0
    for c in hsv_color:
        impact = c[1]+(c[2]*c[2])
        if impact > highest:
            color_result = c
            highest = impact
    # print('RST' , color_result)
    return color_result

#Method for manual open with this module only
def open_with_file(file_name):
    img = cv2.imread(file_name)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    return run(img)


import time

# O(n^2)
def coin_change_recursive(coins,target):
    if target == 0: # base case : get our result!
        return [[]]
    if target < 0 or len(coins) == 0 : # base case ถ้าเหรียญหมด หรือ เกิน target
        return []
    all_changes = []

    # มองเป็นต้นไม้ ซ้ายคือ include coin ขวาคือ exclude coin

    # include first coin
    # บรรทัด 18 จะวนไปทำบรรทัด 8 เรื่อยๆจนกว่าจะถึง base case
    include_first_coin = coin_change_recursive(coins,target-coins[0])

    # change งอกทุกรอบที่ recursive return value
    # บรรทัด 22 ทำงานเมื่อ base case ทีทำงานแล้ว
    for change in include_first_coin:
        all_changes.append([coins[0]] + change)

    # exclude first coin -> do this when base case is trigered, continue from above level of tree
    exclude_first_coin = coin_change_recursive(coins[1:],target)
    all_changes += exclude_first_coin
    return all_changes

def coin_change_bottomUp(coins, target):
    table = [[] for _ in range(target + 1)]
    table[0] = [[]] # base case

    # table[1] would be result of target=2
    # ลองใช้แต่ละเหรียญ
    for coin in coins:
        for i in range(coin, target + 1):
            for prev_combination in table[i - coin]: # ของที่ exitst แล้วช่วยเติม
                table[i].append(prev_combination + [coin])

    return table[target]

def coin_change_topDown(coins, amount):
    def find_combinations(target):

        if target == 0: # base case!
            return [[]]

        if target in memo: # ถ้าเคยคำนวนแล้ว ก็เรียกใช้ memo
            return memo[target]

        all_combinations = []
        for coin in coins:
            if coin <= target: # ถ้าเหรียญยังใส่ได้

                # Recursive remaining amount
                remaining_combinations = find_combinations(target - coin)

                # Add the current coin to each combination and sort it
                for comb in remaining_combinations:
                    all_combinations.append(sorted([coin] + comb))
                print("memo2:",memo)

        # Remove duplicates
        unique_combinations = {tuple(comb) for comb in all_combinations}
        # Convert back to lists
        memo[target] = [list(comb) for comb in unique_combinations]
        return memo[target]

    memo = {}
    combinations = find_combinations(amount)

    return combinations if combinations else [[]]

with open("./input.txt", "r") as file:
    # Read the first line as the target
    target = int(file.readline().strip())

    # Read the rest of the lines and split them into a list
    coins = list(map(int, file.readline().strip().split()))

print(coins)
print(target)
# print(f"Combinations recur of coins to make change for {target}:")
# time_start = time.perf_counter()
# combinations_recur = coin_change_recursive(coins, target)
# time_end = time.perf_counter()
# print(f"Time elapsed: {time_end - time_start} seconds")
# print("recur:",combinations_recur)

# print(f"Combinations bot of coins to make change for {target}:")
# time_start = time.perf_counter()
# combinations_bot = coin_change_bottomUp(coins, target)
# time_end = time.perf_counter()
# print(f"Time elapsed: {time_end - time_start} seconds")
# print("bot:",combinations_bot)

print(f"Combinations top of coins to make change for {target}:")
time_start = time.perf_counter()
combinations_top = coin_change_bottomUp(coins, target)
time_end = time.perf_counter()
print(f"Time elapsed: {time_end - time_start} seconds")
print("top:",combinations_top)


from . import db

class Profile(db.Model):
    """Representation of one Profile"""

    __tablename__ = "profiles"

    id = db.Column(db.Integer, primary_key=True)
    cycle = db.Column(db.Integer)
    timestamp = db.Column(db.Date)

    measurement_id = db.Column(db.Integer, db.ForeignKey('measurements.id'))
    measurement = db.relationship('Measurement')

    salinity = db.Column(db.Float)
    pressure = db.Column(db.Float)
    temperature = db.Column(db.Float)
    valid_data_range = db.Column(db.Boolean)

    def __init__(self, cycle, timestamp, measurement, salinity, pressure, temperature, valid_data_range):
        self.cycle = cycle
        self.timestamp = timestamp
        self.measurement = measurement

        self.salinity = float(salinity)
        self.pressure = float(pressure)
        self.temperature = float(temperature)

        self.valid_data_range = bool(valid_data_range)

    def __repr__(self):
        return f'<Profile {self.id!r}>'

class ProfileTmpTable(Profile):
    __bind_key__ = 'data_input'


from lib.stepperlib import *
import sys, math, time

#all measurements are metric or arbitrary

Init()

COIL_A1 = 5
COIL_A2 = 6
COIL_B1 = 26
COIL_B2 = 13

MOTOR_RESOLUTION = 200
WHEEL_CIRCUMFERENCE = math.pi*0.09

DELAY_MAX = 0.005
DELAY_MIN = 0.0001

idealDelay = 0

steppers = stepper(COIL_A1, COIL_A2, COIL_B1, COIL_B2, DELAY_MAX)

def increment():

    while(steppers._delay>DELAY_MIN):
        steppers._delay -=0.00005
        for  i in range(0,100):
            steppers.setPinsByOne(1)
            print(steppers._delay)
            time.sleep(steppers._delay)

try:
    increment()
except KeyboardInterrupt:
    pass

Quit()


from django.shortcuts import render
from django.http import HttpResponse, HttpResponseNotFound

# Create your views here.
# def january(request):
#     return HttpResponse("This works!!!")
#
# def february(request):
#     return HttpResponse("Go for Run!!!")

monthly_challenges = {
    "january" : "This works!!!",
    "february" : "Go for Run!!!"

}

def monthly_challenge_by_number(request, m):
    return HttpResponse(m)

def month(request, m):
    try:
        challenge_text = monthly_challenges[m]
        return HttpResponse(challenge_text)
    except:
        return HttpResponseNotFound("Invalid month")


N = int(input())

# N의 제곱근을 구하기
start, end = 0, N

# 이분탐색을 이용
while True:
    mid = (start + end) // 2
    if mid ** 2 > N:
        end = mid
    elif mid ** 2 < N:
        start = mid
    else:
        break

print(mid)


import numpy as np
import random
from DATT.python_utils import plotu, polyu
from DATT.refs.base_ref import BaseRef

class PolyRef(BaseRef):
    def __init__(self, altitude, use_y=False, t_end=10.0, degree=3, seed=2023, env_diff_seed=False, fixed_seed=False):
        assert degree % 2 == 1

        self.altitude = altitude
        self.degree = degree
        self.t_end = t_end
        self.use_y = use_y
        self.seed = seed
        self.fixed_seed = fixed_seed
        self.env_diff_seed = env_diff_seed
        self.reset_count = 0

        np.random.seed(seed)
        self.reset()

    def generate_coeff(self):
        b = np.random.uniform(-1, 1, size=(self.degree + 1, ))
        b[0] = 0
        b[(self.degree + 1) // 2] = 0

        A = polyu.deriv_fitting_matrix(self.degree + 1, self.t_end)

        return np.linalg.solve(A, b)[::-1]

    def reset(self):
        if self.fixed_seed:
            np.random.seed(self.seed)
        elif self.env_diff_seed and self.reset_count > 0:
            np.random.seed(random.randint(0, 1000000))

        self.x_coeff = self.generate_coeff()
        if self.use_y:
            self.y_coeff = self.generate_coeff()

        self.reset_count += 1

    def pos(self, t):
        x = np.polyval(self.x_coeff, t)
        if self.use_y:
            y = np.polyval(self.y_coeff, t)
        else:
            y = t*0
        return np.array([
            x,
            y,
            t*0 + self.altitude
    ])

    def vel(self, t):
        x = np.polyval(np.polyder(self.x_coeff), t)
        if self.use_y:
            y = np.polyval(np.polyder(self.y_coeff), t)
        else:
            y = t*0
        return np.array([
            x,
            y,
            t*0
            ])

    def acc(self, t):
        x = np.polyval(np.polyder(self.x_coeff, 2), t)
        if self.use_y:
            y = np.polyval(np.polyder(self.y_coeff, 2), t)
        else:
            y = t*0
        return np.array([
            x,
            y,
            t*0
        ])

    def jerk(self, t):
        x = np.polyval(np.polyder(self.x_coeff, 3), t)
        if self.use_y:
            y = np.polyval(np.polyder(self.y_coeff, 3), t)
        else:
            y = t*0
        return np.array([
            x,
            y,
            t*0
        ])

    def snap(self, t):
        x = np.polyval(np.polyder(self.x_coeff, 4), t)
        if self.use_y:
            y = np.polyval(np.polyder(self.y_coeff, 4), t)
        else:
            y = t*0
        return np.array([
            x,
            y,
            t*0
        ])

    def yaw(self, t):
        if isinstance(t, np.ndarray):
            y = np.zeros_like(t)
            # y[(t // self.T) % 2 == 0] = 0
            # y[(t // self.T) % 2 == 1] = np.pi
        else:
            return 0
            # if (t // self.T) % 2 == 0:
            #     return 0
            # else:
            #     return np.pi
        return y

    def yawvel(self, t):
        return np.array([
            t*0,
            t*0,
            t*0
        ])

    def yawacc(self, t):
        return np.array([
            t*0,
            t*0,
            t*0
        ])

if __name__ == '__main__':
    import matplotlib.pyplot as plt

    ref = PolyRef(altitude=1.0, use_y=True, t_end=10.0, degree=3)
    t = np.linspace(0, 10, 500)

    plt.subplot(2, 1, 1)
    plt.plot(t, ref.pos(t)[0, :], label='x')
    plt.subplot(2, 1, 2)
    plt.plot(t, ref.pos(t)[1, :], label='y')
    plt.show()


import datetime
import pytz

class Account:
    """ Simple account class with balance"""

    # The blow is a static method. A static method is shares by all instances
    # of the class and is used for classes that don't need self
    # and aren't part of normal operations.

    @staticmethod
    def _current_time():
        utc_time = datetime.datetime.utcnow()
        return pytz.utc.localize(utc_time)

    def __init__(self, name, balance):
        # Attributes starting with an underscore are for INTERNAL USE ONLY
        self._name = name
        # Attributes starting with two underscores are "mangled" by Python,
        # i.e. under the hood their name actually begins with the class they belong to
        # so they cannot be changed from outside, like I am trying to do on line 67
        self.__balance = balance
        self._transaction_list = [(Account._current_time(), balance)]

        print("Account created for " + self._name)

    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount
            self.show_balance()
            self._transaction_list.append((Account._current_time(), amount))

    def withdraw(self, amount):
        # note the chaining of conditionals here
        if 0 < amount <= self.__balance:
            self.__balance -= amount
            self._transaction_list.append((Account._current_time(), -amount))
        else:
            print("The account must be greater than zero and no more than your account balance")
        self.show_balance()

    def show_balance(self):
        print("Balance is {}".format(self.__balance))

    def show_transactions(self):
        for date, amount in self._transaction_list:
            if amount > 0:
                tran_type = 'deposited'
            else:
                tran_type = 'withdrawn'
                amount *= -1
            print("{:6} {} on {} (local time was {})".format(amount, tran_type, date, date.astimezone()))

if __name__ == '__main__':
    anderson = Account("Anderson", 0)
    anderson.show_balance()

    anderson.deposit(1000)
    anderson.withdraw(500)

    anderson.withdraw(2000)
    anderson.show_transactions()

    julia = Account("Julia", 800)
    julia.__balance = 200
    julia.deposit(100)
    julia.withdraw(200)
    julia.show_transactions()
    julia.show_balance()
    # If we really wanted to change the mangled balance for Julia's account
    # we would do this:
    # julia.Account__balance = 200


import os
import tensorflow as tf
import numpy as np
import scipy.io as sio
from PIL import Image
from model import*
from DataReader import*
from matplotlib import pyplot as plt
import datetime
from tensorflow.keras.models import load_model
import argparse
import sys

def dice_metric(seg,gt):
    dice = np.sum(seg[gt==1])*2.0 / (np.sum(seg) + np.sum(gt))
    return dice

def predict(data_dir,image_dim,model_dir,with_label):
    ## Loading Trained model ##
    try:
        models = glob.glob(os.path.join(model_dir,'*.h5'))
        latest_model = max(models, key=os.path.getctime)
        model = load_model(latest_model,compile=False)
    except:
         print("Problems in model loading. Check if model exists")
         sys.exit(0)

    ### Saving the predicted images and their corresponding Dice Accuracy with the GT annotations##
    if not os.path.exists('predictions'):
        os.mkdir('predictions')

    if with_label is True:
        test_im,test_labels = load_dataset(data_dir)
        all_dice =[]
        preds = model.predict(test_im, verbose=1)

        for i,(seg,gt) in enumerate(zip(preds,test_labels)):
            all_dice.append(dice_metric(seg,gt))
            seg = np.squeeze(seg)
            seg = seg.astype(np.uint8)
            seg = Image.fromarray(seg)
            seg = seg.resize((512, 512),resample=Image.NEAREST)
            fname = f'predict_{i}.tiff'
            seg.save(os.path.join('predictions',fname))

        fname = os.path.join("predictions","Dice.txt")
        acc_file = open(fname,"w")
        acc_file.write(np.mean(all_dice))
        return "Predicted successfully.Please Check Prediction Directory"
    else:
        test_im = load_dataset(data_dir,isTest=True)
        preds = model.predict(test_im, verbose=1)
        for i,seg in enumerate(preds):
            seg = np.squeeze(seg)
            seg = seg*255.0
            seg = seg.astype(np.uint8)
            seg = Image.fromarray(seg)
            seg = seg.resize((512, 512),resample=Image.NEAREST)
            fname = f'predict_{i}.tiff'
            seg.save(os.path.join('predictions',fname))
        return "Predicted successfully.Please Check Prediction Directory"

def get_args():
    parser = argparse.ArgumentParser(description='Train the UNet on images and target masks',
                                     formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('-dim', '--dimension',metavar='Dim', type=int, default=128,
                        help='Input Image Dimension', dest='dimension')
    parser.add_argument('-d', '--data_dir', dest='data_dir', type=str, default=r"C:\DM\MLops\algea\test",
                        help='Training Data Directory')
    parser.add_argument('-md', '--model_dir', dest='model_dir', type=str, default="chkpoints",
                        help='Percent of the data that is used as validation (0-100)')
    parser.add_argument('-wl', '--with_label', dest='with_label', type=bool, default=True,
                        help='To indicate test dataset has Ground Truth labels or not')

    return parser.parse_args()

if __name__ == "__main__":
    args = get_args()
    try:
        predict( data_dir = args.data_dir,
                 image_dim = args.dimension,
                 model_dir= args.model_dir,
                 with_label = args.with_label)
    except KeyboardInterrupt:
        print('Prediction Inturrepted')
        #logging.info('Training Inturrepted')
        try:
            sys.exit(0)
        except SystemExit:
            os._exit(0)