# 패키지 import
import streamlit as st
import pandas as pd
import random
# 사진출력 패키지 import
import io
from PIL import Image
import requests

# 데이터 로드
df = pd.read_csv("ziwon.csv")

# 스트림릿 페이지 제목 설정하기
st.title('레시피 추천 챗봇')
st.write('메뉴명, 범주, 요리난이도, 소요시간, 재료 정보를 확인하실 수 있습니다.')

# 챗봇 대화 기록을 저장할 리스트 선언
conversation = []

# 이전 대화 내용 출력하기
for message in reversed(conversation):
    if message["is_user"]:
        st.text_input("User input", value=message["text"], key=message["time"], disabled=True)
    else:
        st.write(message["text"])

# 알레르기 유발식품 입력
allergy = st.text_input('알레르기 식품을 입력하세요. (띄어쓰기로 구분해주세요.)')

if allergy:
    # 알레르기 식품을 리스트로 변환
    allergy_list = allergy.split(',')
    # 알레르기 식품이 포함되지 않은 레시피 필터링 (str.contains는 리스트 안받아서 리스트컴프리헨션으로 변경)
    df1 = df[~df['재료'].str.contains('|'.join([f"^{x}\s|\s{x}\s|\s{x}$" for x in allergy_list]))]

    ingredients = st.text_input('가지고 있는 재료를 입력하세요.  (띄어쓰기로 구분해주세요.)', key='ingredients_input')

    if ingredients:
        # 재료를 리스트로 변환
        ingredient_list = ingredients.split()

        # 재료가 포함된 레시피 필터링
        df2 = df1[df1['재료'].apply(lambda x: all(item.lower() in x.lower() for item in ingredient_list))]

        level = st.radio('원하는 요리 난이도를 선택하세요.', ['초보자', '중급자', '고급자'])

        if level:
            # 선택된 요리 난이도에 맞는 레시피 필터링
            if level == '초보자':
                filtered_df = df2[df2['난이도'] == 1]
            elif level == '중급자':
                filtered_df = df2[df2['난이도'] == 2]
            else:
                filtered_df = df2[df2['난이도'] == 3]

            time = st.text_input('희망하는 최대 소요시간을 입력해주세요.')

            if time:
                # 입력값을 정수형으로 변환
                time = int(time)

                last_df = filtered_df[filtered_df['소요시간'] <= time]

                # 필터링된 레시피 출력
                if not last_df.empty:
                    # 랜덤한 인덱스를 선택하여 해당 행을 출력
                    random_index = random.randint(0, last_df.shape[0] - 1)
                    random_recipe = last_df.iloc[random_index]

                    # 랜덤으로 선택된 행의 '사진' 컬럼 값 가져오기
                    img_url = random_recipe['사진']
                    # URL에서 이미지 불러오기
                    response = requests.get(img_url)
                    image_bytes = io.BytesIO(response.content)
                    image = Image.open(image_bytes)
                    # 이미지 출력하기

                    st.image(image, width=500)

                    st.write('# 🧑🍳 ', random_recipe['요리'])

                    st.write(random_recipe)

                else:
                    st.write("검색 결과가 없습니다.")


# -*- coding: utf-8 -*-
"""
Created on Mon Sep 10 11:32:35 2018

@author: root
"""

import numpy as np
import cv2
import os
import random
import matplotlib.pyplot as plt

imageSize = 128
m = (0,0,0)
noise_factor = 0.1

saveDir = "/home/alexander/Desktop/CVPR/2_Data/"
imagePath = '/home/alexander/Desktop/brightness_per/ILSVRC2014_128X128/'

trainDir = os.listdir(imagePath+'train')
testDir = os.listdir(imagePath+'test')

x_train = np.zeros((len(trainDir),imageSize,imageSize,3))
#ytrain = np.zeros((len(trainDir),imageSize,imageSize,3))

print("Train ready!!!")

trainDir = os.listdir(imagePath+'train')

for i in range(len(trainDir)):

    s = (random.randint(0,100),random.randint(0,100),random.randint(0,100))
    tempImg = cv2.imread(imagePath+'train/'+trainDir[i])
    #y_test[i,:,:,:] = tempImg
    x_train[i,:,:,:] =  tempImg + noise_factor * np.random.normal(loc=0.0, scale=255, size=x_train.shape[1:])

x_train = np.clip(x_train, 0., 255.)
np.save(saveDir+'/x_train', x_train)
#np.save(saveDir+'/y_test', y_test)

del x_train#,y_train

'''
x_test = np.zeros((len(testDir),imageSize,imageSize,3))
#y_test = np.zeros((len(testDir),imageSize,imageSize,3))

print("Train ready!!!")

testDir = os.listdir(imagePath+'test')

for i in range(len(testDir)):

    s = (random.randint(0,100),random.randint(0,100),random.randint(0,100))
    tempImg = cv2.imread(imagePath+'test/'+testDir[i])
    #y_test[i,:,:,:] = tempImg
    x_test[i,:,:,:] =  tempImg + noise_factor * np.random.normal(loc=0.0, scale=255, size=x_test.shape[1:])

x_test = np.clip(x_test, 0., 255.)
np.save(saveDir+'/x_test', x_test)
#np.save(saveDir+'/y_test', y_test)

del x_test#,y_test
'''
print("All images were read!!!")


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

import binascii

from command_table import COMMAND, FUNCTION

COMMAND_BY_WORD = {v: k for k, v in COMMAND.items()}
FUNCTION_BY_WORD = {v: k for k, v in FUNCTION.items()}

def encode_script_string(script_string, suppress_error=False):
    result = []
    for line in script_string.split("\n"):
        if not line:
            continue
        result.append({"raw": line, "encoded": encode_one_line(line)})
    return result

def encode_one_line(line):
    try:
        line_number, command = line.split(" ", 1)
        encoded_line_number = encode_line_number(line_number)
        encoded_command = encode_command(command)
        encoded_command_length = encode_command_length(encoded_command)
        encoded = (encoded_command_length + encoded_line_number +
                   "0000" + encoded_command + "0D").upper()
        return encoded

    except Exception as e:
        tok = line.split()
        if len(tok) == 2:
            line_number, command = tok
            print("LINE NUMBER IS", line_number)
            if line_number == "\\bin":
                return command

        print(f"unable to convert LINE '{line}'")
        raise e

def encode_line_number(line_number):
    hex_number = f"{int(line_number):04x}"
    return hex_number[2:4]+hex_number[0:2]

def encode_command(command):
    result = ""
    ascii_mode = False
    in_comment = False
    in_quotes = False
    c = 0
    while c < len(command):
        parsed = ""
        if not ascii_mode:
            result_c, parsed, dc = match_one_keyword(command[c:])
        if ascii_mode or not parsed:
            result_c, parsed, dc = encode_one_ascii(command[c:])
        if parsed == '"':
            in_quotes = not in_quotes
        elif parsed in ['REM', 'DATA']:
            in_comment = True
        ascii_mode = in_comment or in_quotes
        c += dc
        result += result_c
    return result

def match_one_keyword(command):
    matching_commands = list(
        filter(lambda cmd: command.startswith(cmd), COMMAND_BY_WORD.keys()))
    matching_functions = list(
        filter(lambda cmd: command.startswith(cmd), FUNCTION_BY_WORD.keys()))
    if matching_commands:
        result = max(matching_commands, key=len)
        return COMMAND_BY_WORD[result], result, len(result)
    elif matching_functions:
        result = max(matching_functions, key=len)
        return "80"+FUNCTION_BY_WORD[result], result, len(result)
    else:
        return "", "", 0

def encode_one_ascii(command):
    if command[0] == '\\' and command[1] == 'x':
        return command[2]+command[3], command[0:4], 4
    else:
        return f"{ord(command[0]):02x}", command[0], 1

def encode_command_length(encoded_command):
    return f"{int(len(encoded_command)/2):02x}"

def print_encoded(encoded, pretty_format=False):
    result = ""
    for line in encoded:
        if pretty_format:
            result += "{}\n  {}\n".format(line["raw"], line["encoded"])
        else:
            result += line["encoded"]
    print(result)

def save_encoded_to(filepath, encoded):
    with open(filepath, "wb") as f:
        result = ""
        for line in encoded:
            result += line["encoded"]
        resultb = binascii.a2b_hex(result)
        f.write(resultb)


 #!/usr/bin/env python
import io
import serial

serial_port = serial.Serial(
'/dev/ttyUSB0',
57600,
timeout = 1 )

data_list = []

while 1:
    data = ''

    if serial_port.inWaiting():
        data = serial_port.readline()

    if len(data) > 0:
        data_list.append(data)
        print('Data rec: ', data)

        serial_port.write(bytes("Test message", 'UTF-8'))


#Дано целое число N (> 1). Найти наибольшее целое число K, при котором выполняется неравенство 3K < N.
print("Введите число N, которое больше 1")
N = input()
while type(N) != int:  # Обработка исключений 1-го числа
    try:
        N = int(N)
    except ValueError:
        print("Не то ввели!")
        N = input("Введите первое целое число: ")
if N>1:
    K = 0
    while 3**K < N:
        K = K+1
    print("Наибольшее целое число равно ", K-1)
else:
    print("Не соответствует условию задачи")


"""add_createdAt column

Revision ID: 234e385060ff
Revises: cf6deb8cf165
Create Date: 2023-03-07 11:09:37.423889

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '234e385060ff'
down_revision = 'cf6deb8cf165'
branch_labels = None
depends_on = None

def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('tbl_role', sa.Column('createdAt', sa.DateTime(), server_default=sa.text('now()'), nullable=False))
    op.add_column('tbl_users', sa.Column('createdAt', sa.DateTime(), server_default=sa.text('now()'), nullable=False))
    # ### end Alembic commands ###

def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column('tbl_users', 'createdAt')
    op.drop_column('tbl_role', 'createdAt')
    # ### end Alembic commands ###


'''
Given a collection of intervals, merge all overlapping intervals.

Example 1:

Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:

Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.
NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.
'''

from operator import itemgetter
class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        if not intervals: return intervals
        i = sorted(intervals, key=itemgetter(0))
        result = []

        it, start, currentMax = 0, 0, i[0][1]

        while it < len(i):
            if(it != len(i)-1 and currentMax>=i[it+1][0]): currentMax = max(currentMax, i[it+1][1])
            else:
                result.append([i[start][0], currentMax])
                start = it + 1
                if it != len(i)-1: currentMax = i[it + 1][1]
            it = it + 1

        return (result)

'''
O(nlogn) algorithm. Go through a sorted version of the intervals list keeping track of a currentMax value if it is overlapping with the current
interval at iteration. When currentMax doesn't overlap append the beginning of your starting interval and the currentMax to the result.
Your new start will be the iterval at the next index and the new currentMax will be the end of that interval
'''


import os
import uuid

from django.core.validators import RegexValidator
from django.db import models
from django.utils.html import mark_safe

from .utils import MarkdownRenderer, FileValidator, RE_FILENAME_IMG

# validators
tag_validator = RegexValidator(
    regex='^[a-z]+(?:-[a-z0-9]+)*$',
    message="Tag must consist of lowercase letters, digits and hyphens.",
    code='invalid_tag'
)
post_validator = RegexValidator(
    regex='^(?:new|edit|test|preview)*$',
    message="Name is reserved: 'new', 'edit' or 'test'.",
    code='invalid_name',
    inverse_match=True,
)
image_validator = FileValidator(
    restricted_basename=False,
    allowed_extensions=('jpg', 'png', 'svg', 'gif'),
    allowed_mimetypes=('image/jpeg', 'image/png', 'image/svg', 'image/svg+xml', 'image/gif'),
)
image_filename_validator = RegexValidator(
    regex=RE_FILENAME_IMG,
    message="Please use a filename using lowercase letters, digits and underscores. Valid extensions are: 'jpg', 'png', 'svg' or 'gif'",
    code='invalid_name',
    inverse_match=True,
)

def upload_to(model, filename):
    if isinstance(model, Image):
        prefix = "img/"
    else:
        raise NotImplementedError("upload_to is only implemented for Image models")
    ext = os.path.splitext(filename)[1].lower()  # e.g. 'photo.JPG' -> '.jpg'
    filepath = "{}{}{}".format(prefix, uuid.uuid4(), ext)
    return filepath

class Tag(models.Model):
    name = models.SlugField(
        max_length=30, unique=True, blank=False, null=False,
        validators=[tag_validator])

    def posts(self):
        return Post.objects.filter(tags__name__contains=self.name, is_live=True)

    def __str__(self):
        return self.name

class Image(models.Model):
    filename = models.CharField(
        max_length=30, unique=True, blank=False, null=False,
        validators=[post_validator])
    file = models.FileField(
        unique=True, blank=False, null=False, upload_to=upload_to,
        validators=[image_validator])

    def __str__(self):
        return self.filename

class Post(models.Model):
    CATEGORY_DS = 0
    CATEGORY_ENG = 1
    CATEGORY_CHOICES = (
        (CATEGORY_DS, 'Data Science'),
        (CATEGORY_ENG, 'Engineering'),
    )
    name = models.SlugField(
        max_length=30, unique=True, blank=False, null=False,
        validators=[post_validator])
    title = models.CharField(max_length=200)
    tags = models.ManyToManyField(Tag)
    images = models.ManyToManyField(Image, blank=True)
    markdown = models.TextField()
    pub_date = models.DateField('date published', auto_now_add=True)
    is_live = models.BooleanField(default=False)
    category = models.PositiveSmallIntegerField(choices=CATEGORY_CHOICES)

    def __str__(self):
        return self.title

    def html(self):
        md = MarkdownRenderer(self)
        html = md.render(self.markdown)
        return mark_safe(html)

    @classmethod
    def all_live_tags(cls):
        tags = set()
        for post in cls.objects.filter(is_live=True):
            tags.update(post.tags.all())
        return sorted(tags, key=(lambda tag: tag.name))


__author__ = 'Yann.Xia'

import math

def is_a_big_than_b_v2(a, b):
    n_a, e_a = int(a[0]), int(a[1])
    n_b, e_b = int(b[0]), int(b[1])

    x = math.log(n_b, n_a)
    x *= e_b

    if e_a > x:
        return True
    return False

print(is_a_big_than_b_v2([2, 11], [3, 7]))

def is_a_big_than_b(a, b):
    n_a, e_a = int(a[0]), int(a[1])
    n_b, e_b = int(b[0]), int(b[1])
    s = 1
    while e_a > 0 and e_b > 0:
        s *= (n_a / n_b)
        e_a -= 1
        e_b -= 1

        if s > 1 and e_a > e_b:
            return True

        if s < 1 and e_a < e_b:
            return False

        if s > 1:
            s /= n_b
            e_b -= 1

        if s < 1:
            s *= n_a
            e_a -= 1

    while e_a > 0:
        s *= n_a
        e_a -= 1
        if s > 1:
            return True

    while e_b > 0:
        s *= n_b
        e_b -= 1
        if s > 1:
            return True

    return False

f = open('p099_base_exp.txt')

exponentials = []
for line in f.readlines():
    exponentials.append(line.replace('\n', '').split(","))

top = [1, 1]

for n in exponentials:
    if is_a_big_than_b_v2(n, top):
        top = n

print(top)


import os
import pandas as pd
import pprint
import pickle
import numpy as np
from sklearn import metrics
import argparse
import logging
import itertools
import copy

DATA_PREFIX = ['train', 'val', 'test']
AGG_METRIC = ['mean', 'std', 'min', 'max']

def load_data(base_dir, folds):
    data = {'train': [], 'val': [], 'test': []}
    for i in range(folds):
        for el in DATA_PREFIX:
            ys = pickle.load(
                open(os.path.join(base_dir, el+'_'+str(i)+".pkl"), 'rb'))[:, -1]
            data[el].append(ys)
    return data

def check_data(base_dir, folds):
    for i in range(folds):
        for el in DATA_PREFIX:
            if not os.path.isfile(os.path.join(base_dir, el+'_'+str(i)+".pkl")):
                logging.error("File not present at {}".format(
                    os.path.join(base_dir, el+'_'+str(i)+".pkl")))
                return False
    return True

"""
def make_path(arch, kl, neg_r, rho):
    # exp_c-configs.fb15k_config_7_4.yml_k-0_n--0.5_r-0.01
    #return "exp_c-{}_k-{}_n-{}_r-{}".format(arch, kl, neg_r, rho)
    return "exp_c-{}_k-{}_n-{}_r-{}".format(arch, kl, neg_r, rho)

def get_params(directory):
    exps = os.listdir(directory)
    neg_rewards = set()
    rhos = set()

    kls = set()
    archs = set()
    ex = set()
    for exp in exps:
        if os.path.isdir(os.path.join(directory, exp)):
            delim1 = exp.find("_c-")
            delim2 = exp.find("_k-")
            delim3 = exp.find("_n-")
            delim4 = exp.find("_r-")
            neg_r = exp[delim3+3:delim4]
            rho   = exp[delim4+3:]
            kl    = exp[delim2+3:delim3]
            arch  = exp[delim1+3:delim2]
            neg_rewards.add(neg_r)
            rhos.add(rho)
            kls.add(kl)
            archs.add(arch)
    return (list(sorted(neg_rewards, key=float)), list(sorted(rhos, key=float)), list(sorted(kls, key=float)), list(sorted(archs, key=float)))
"""

def get_string(x):
    return str(x).replace('/','.').replace(' ','.')

def get_params():
    return get_params2()

def get_params2():
    #COPIED FROM CREATE_MULTINODE_JOBS.PY
    neg_reward = [-1, -2]
    rho = [0.1, 0.125]
    config = ['configs/fb15k_config.yml']
    kldiv_lambda = [0, 1]
    exclude_t_ids = ['2 5']
    hidden_unit_list = ['90 40','7 5 5 3']
    default_value = [0, -0.05, -0.1]
    #
    names = ['neg_reward','rho','kldiv_lambda','config','exclude_t_ids','hidden_unit_list','default_value']
    all_params = [neg_reward,rho, kldiv_lambda, config,exclude_t_ids,hidden_unit_list,default_value]
    short_names = ['n','r','k','c','ex','hul','df']

    assert len(names) == len(all_params)
    assert len(all_params) == len(short_names)

    timing_key = 'hidden_unit_list'
    timing = [10]*len(hidden_unit_list)
    #assert(len(globals()[timing_key]) == len(timing))
    assert len(all_params[names.index(timing_key)]) == len(timing),'len of timing should be same as len of timing_key param'
    timing_dict = dict(zip(all_params[names.index(timing_key)],timing))
    all_jobs = list(itertools.product(*all_params))

    additional_names = ['train_ml','eval_ml']
    additional_job_list = [
                    [0,0],
                    [1,1]
                    ]

    names = names + additional_names
    additional_short_names = ['tml','eml']
    short_names = short_names + additional_short_names
    assert len(names) == len(short_names)
    name2short = dict(zip(names,short_names))
    all_jobs = list(itertools.product(all_jobs,additional_job_list))
    sorted_names = copy.deepcopy(names)
    sorted_names.sort()

    #### WRITTEN AGAIN with MODIFICATION
    for i,key in enumerate(additional_names):
        all_params.append([x[i] for x in additional_job_list])
    #
    name2list = dict(zip(names,all_params))
    for key in sorted_names:
        name2list[key] = [ get_string(x) for x in name2list[key]]

    all_settings = {}
    for i, setting in enumerate(all_jobs):
        setting = list(itertools.chain(*setting))
        name_setting = {n: get_string(s) for n, s in zip(names, setting)}
        log_str = '_'.join(['%s-%s' % (name2short[n], name_setting[n]) for n in sorted_names])
        all_settings[log_str] = name_setting
    #return all_settings, name2list, high level params, rows_cols
    return all_settings, name2list,['config','exclude_t_ids','kldiv_lambda','train_ml','eval_ml','default_value','hidden_unit_list'],['rho','neg_reward']

def get_params1():
    #COPY FROM CREATE_MULTINODE_JOBS.PY
    neg_reward = [-1, -2]
    rho = [0.125]
    config = ['configs/fb15k_config_90_40.yml']
    kldiv_lambda = [0, 1]
    exclude_t_ids = ['2 5',None]
    #exclude_t_ids = [None]
    names = ['neg_reward','rho','kldiv_lambda','config','exclude_t_ids']
    all_params = [neg_reward,rho, kldiv_lambda, config,exclude_t_ids]
    short_names = ['n','r','k','c','ex']
    name2list = dict(zip(names,all_params))

    name2short = dict(zip(names,short_names))
    sorted_names = copy.deepcopy(names)
    sorted_names.sort()
    for key in sorted_names:
        name2list[key] = [ get_string(x) for x in name2list[key]]

    sorted_names = copy.deepcopy(names)
    all_settings = {}
    sorted_names.sort()
    all_jobs = list(itertools.product(*all_params))
    for i, setting in enumerate(all_jobs):
        setting = list(setting)
        name_setting = {n: get_string(s) for n, s in zip(names, setting)}
        log_str = '_'.join(['%s-%s' % (name2short[n], name_setting[n]) for n in sorted_names])
        all_settings[log_str] = name_setting
    #return all_settings, name2list, high level params, rows_cols
    return all_settings, name2list,['config','kldiv_lambda','rho'],['exclude_t_ids','neg_reward']

def check_exp(directory, data, folds):
    return check_exp2(directory, data, folds)

def check_exp2(directory, data, folds):
    for el in DATA_PREFIX[1:]:
        preds_fname = os.path.join(
                directory, '{}_ml_{}'.format(el,args.eval_ml))

        if os.path.isfile(preds_fname):
            return True
        else:
            logging.error("File {} does not exist".format(preds_fname))
            return False
    return True

def check_exp1(directory, data, folds):
    for i in range(folds):
        for el in DATA_PREFIX[1:]:
            if el == 'val':
                preds_fname = os.path.join(
                    directory, 'exp_'+str(i), 'val_pred_ml_{}.txt'.format(args.eval_ml))
            else:
                preds_fname = os.path.join(
                    directory, 'exp_'+str(i), 'test_pred_ml_{}.txt'.format(args.eval_ml))
            if os.path.isfile(preds_fname):
                pred_data = np.loadtxt(preds_fname).tolist()
                if len(data[el][i]) != len(pred_data):
                    logging.error(
                        "Length of {} does not match with ground truth data".format(preds_fname))
                    return False
            else:
                logging.error("File {} does not exist".format(preds_fname))
                return False
    return True

def begin_checks(base_dir, folds, runs):
    data_present = check_data(base_dir, folds)
    if not data_present:
        logging.error("Data Check failed")
        return (False, [])
    data = load_data(base_dir, folds)
    logging.info("Data Check Passed")

    #cols, rows, kls, archs = get_params(os.path.join(base_dir, "run_1"))
    all_settings, name2list,exp_classes, rows_cols = get_params()
    invalid_exps = []
    for run in range(1, runs+1):
        for this_setting in all_settings:
            directory = os.path.join(base_dir, "run_"+str(run), 'exp_'+this_setting)
            if not check_exp(directory, data, folds):
                invalid_exps.append(directory)
    #
    if (len(invalid_exps) == 0):
        logging.info("All experiments are ok")
        return (True, [])
    else:
        logging.error("Following experiments have error\n{}".format(
            str(pprint.pformat(invalid_exps))))
        logging.error("Length is {}".format(len(invalid_exps)))
        return (False, invalid_exps)

def write_invalid(invalid_exps, fname):
    if fname is not None:
        with open(fname, 'w') as f:
            for exp in invalid_exps:
                f.write('/'.join(exp.split('/')[-2:])+'\n')
        logging.error("Written invalid experiments to {}".format(fname))

def calc_exp(directory, data, folds):
    return calc_exp_read(directory, data,folds)

def calc_exp_read(directory, data, folds):
    #directory/test_ml_0
    #directory/test_ml_1
    #directory/val_ml_0
    #directory/val_ml_1
    rv = []
    count = []
    for el in DATA_PREFIX[1:]:
        fname = os.path.join(directory, '{}_ml_{}'.format(el, args.eval_ml))
        f = pd.read_csv(fname,header=None).to_numpy()
        #assert f.shape[0] == 5
        if f.shape[0] != folds:
            print("Num folds: {}. #folds present: {}. ASSUMING 0 performance for them".format(folds, f.shape[0]))
        rv.append(f[:,-1].sum()/folds)
        count.append(f.shape[0])
    #
    return (rv[0], rv[1], count[0], count[1])

def calc_exp_compute(directory, data, folds):
    predictions = {'val': [], 'test': []}
    true = {'val': [], 'test': []}
    logging.info("Calculating results for experiment {}".format(directory))
    for i in range(folds):
        for el in DATA_PREFIX[1:]:
            if el == 'val':
                preds_fname = os.path.join(
                    directory, 'exp_'+str(i), 'valid_preds.txt')
            else:
                preds_fname = os.path.join(
                    directory, 'exp_'+str(i), 'test_preds.txt')
            pred_data = np.loadtxt(preds_fname).tolist()
            predictions[el].extend(pred_data)
            true[el].extend(data[el][i])
    mif_val = metrics.f1_score(true['val'], predictions['val'], labels = args.t_ids, average='micro')
    mif_test = metrics.f1_score(true['test'], predictions['test'], labels= args.t_ids, average='micro')
    return (mif_val, mif_test)

"""
def calc_run_results(directory, rows, cols, KLs, Archs, data, folds):
    results_one_run = {'neg_re': [], 'rho': [], 'val': [], 'test': [], 'kl':[], 'arch':[]}
    for col in cols:
        for row in rows:
        	for kl in KLs:
        		for arch in Archs:
		            exp_directory = os.path.join(directory, make_path(arch, kl, col, row))
		            val, test = calc_exp(exp_directory, data, folds)
		            results_one_run['neg_re'].append(col)
		            results_one_run['rho'].append(row)
		            results_one_run['val'].append(val)
		            results_one_run['test'].append(test)
		            results_one_run['kl'].append(kl)
		            results_one_run['arch'].append(arch)
    df = pd.DataFrame(data=results_one_run)
    return df
"""

def calc_run_results(directory, all_settings, name2list, data, folds):
    results_one_run = None
    param_keys = None
    for key in all_settings:
        this_setting = all_settings[key]
        exp_directory = os.path.join(directory,'exp_'+key)
        val, test,val_count, test_count = calc_exp(exp_directory, data, folds)
        if results_one_run is None:
            results_one_run = {}
            param_keys = list(this_setting.keys())
            for this_param in this_setting:
                results_one_run[this_param] = [this_setting[this_param]]
            #
            results_one_run['val'] = [val]
            results_one_run['test'] = [test]
            results_one_run['val_count'] = [val_count]
            results_one_run['test_count'] = [test_count]

        else:
            for this_param in this_setting:
                results_one_run[this_param].append(this_setting[this_param])
            #
            results_one_run['val'].append(val)
            results_one_run['test'].append(test)
            results_one_run['val_count'].append(val_count)
            results_one_run['test_count'].append(test_count)
    df = pd.DataFrame(data=results_one_run)
    return df, param_keys

def write_to_file(table, header, f):
    f.write(header+'\n')
    table.to_csv(f, float_format='%.4f')
    f.write('\n')

if __name__ == "__main__":
    logging.basicConfig(format='%(levelname)s :: %(asctime)s - %(message)s',
                        level=logging.INFO, datefmt='%d/%m/%Y %I:%M:%S %p')

    parser = argparse.ArgumentParser()
    parser.add_argument(
        '-d', '--dir', help="Path of the base directory", required=True)
    parser.add_argument('--folds', type=int, default=5, required=True)
    parser.add_argument('--eval_ml', type=int, default=0, required=True, help='collate results of multi label evaluation?' )
    parser.add_argument('--runs', type=int, default=5, required=True)
    parser.add_argument(
        '--ifile', help='File to write the experiment names which failed', type=str, default=None)

    parser.add_argument('--t_ids', nargs='+', type=int, required=False,default=[1,2,3,4,5,6], help='List of templates')
    args = parser.parse_args()

    ok, invalid_exps = begin_checks(args.dir, args.folds, args.runs)

    if not ok and len(invalid_exps) > 0:
        write_invalid(invalid_exps, args.ifile)
        exit(0)

    logging.info("All Checks passed")
    #cols, rows, KLs, Archs = get_params(os.path.join(args.dir, "run_1"))
    #all_settings, name2list = get_params()
    all_settings, name2list,exp_classes, rows_cols = get_params()

    data = load_data(args.dir, args.folds)
    all_run_results = []
    for run in range(1, args.runs+1):
        logging.info("Calculating results for run {}".format(run))
        df,param_keys = calc_run_results(os.path.join(args.dir, "run_"+str(run)), all_settings, name2list, data, args.folds)
        df['run_id'] = run
        #df = calc_run_results(os.path.join(
        #    args.dir, "run_"+str(run)), rows, cols, KLs, Archs data, args.folds)
        all_run_results.append(df)

    final_result = pd.concat(all_run_results)
    final_result = final_result.reset_index(drop=True)
    agg_table = final_result.groupby(param_keys).agg({DATA_PREFIX[1]:AGG_METRIC, DATA_PREFIX[2]: AGG_METRIC, DATA_PREFIX[1]+'_count': 'sum', DATA_PREFIX[2]+'_count': 'sum'})
    #agg_table.columns = [d+"_"+a for d,
    #                     a in itertools.product(DATA_PREFIX[1:], AGG_METRIC)]

    agg_table.columns = ['_'.join(x) for x in agg_table.columns.to_flat_index()]
    agg_table = agg_table.reset_index()
    agg_table.to_csv(os.path.join(args.dir, 'all_performance.csv'))
    fh = open(os.path.join(args.dir, 'summary.csv'), 'w')

    for this_param in itertools.product(*([name2list[x] for x in exp_classes] + [DATA_PREFIX[1:], AGG_METRIC])):
        d = this_param[-2]
        a = this_param[-1]
        selection = None
        for ind in range(len(exp_classes)):
            this_selection= agg_table[exp_classes[ind]] == this_param[ind]
            if selection is None:
                selection = this_selection
            else:
                selection = selection & this_selection
        #
        tbl = agg_table[selection].pivot_table(columns = rows_cols[0], index = rows_cols[1], values = d+'_'+a, fill_value = -1)
        print(tbl)
        header = ' '.join(list(map(lambda x: x[0] + '_' + str(x[1]), zip(exp_classes + ['',''], this_param))))

        write_to_file(tbl, header, fh)

    """
    for d, a, kl, arch in itertools.product(DATA_PREFIX[1:], AGG_METRIC, KLs, Archs):
        tbl = agg_table[agg_table["kl"]==kl & agg_table["arch"]==arch].pivot_table(
            columns='neg_re', index='rho', values=d+'_'+a, fill_value=-1)
        print(tbl)
        write_to_file(tbl, (d+'_'+a+'_'+kl+'_'+arch).upper(), fh)
    """

    logging.info("Written results to {}".format(
        os.path.join(args.dir, 'summary.csv')))


"""Support for smartmeter sensors."""
import logging

from homeassistant.helpers.entity import Entity

from . import DOMAIN

_LOGGER = logging.getLogger(__name__)

async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
    """Set up the smart meter platform."""
    if discovery_info is None:
        return

    smartmeter = hass.data[DOMAIN]

    obis = smartmeter.get_list_of_sensors()
    _LOGGER.debug("Setting up sensors: %s", repr(obis))

    sensors = []
    for sensor_obis in obis:
        sensors.append(MeterSensor(smartmeter, sensor_obis, "Verbrauch", "mdi:flash"))

    async_add_entities(sensors)

class MeterSensor(Entity):
    """The entity class for smart meter sensors."""

    def __init__(self, smartmeter, obis, name, icon, device_class=None):
        """Initialize the smartmeter sensor."""
        self._smartmeter = smartmeter
        self._obis = obis
        self._name = name
        self._icon = icon
        self._unit = None
        self._device_class = device_class

        self._state = None
        self._attributes = {}

    @property
    def should_poll(self):
        """Deactivate polling. Data updated by smartmeter."""
        return False

    @property
    def unique_id(self):
        """Return the unique ID of the binary sensor."""
        return f"{self._smartmeter.device_id}_{self._obis}"

    @property
    def name(self):
        """Return the name of the device."""
        names={
                '1-0:1.8.0*255':'Consumption',
                '1-0:2.8.0*255':'Generation'
             }
        name = names.get(self._obis,"unknown")

        return f"{self._smartmeter.device_name} {name}"

    @property
    def device_class(self):
        """Return the class of this sensor."""
        return self._device_class

    @property
    def icon(self):
        """Icon to use in the frontend, if any."""
        return self._icon

    @property
    def state(self):
        """Return the state of the sensor."""
        return self._state

    @property
    def unit_of_measurement(self):
        """Get the unit of measurement."""
        return self._unit

    @property
    def device_state_attributes(self):
        """Return the state attributes of the binary sensor."""
        return self._attributes

    async def async_update(self):
        """Get latest cached states from the device."""
        self._state, self._unit = self._smartmeter.get_value(self._obis)

    def update_callback(self):
        """Schedule a state update."""
        self.async_schedule_update_ha_state(True)

    async def async_added_to_hass(self):
        """Add update callback after being added to hass."""
        self._smartmeter.add_update_listener(self.update_callback)


# -*- coding: utf-8 -*-
import numpy as np
import io
import time

#CONSTANTS
H=0                 #Horitzontal
V=1                 #Vertical
#per accedir de manera més clara al array de paraules utilitzarem les següents variables:
X=0         #coord x
Y=1         #coord y
SIZE=2      #mida paraula
DIR=3       #orientacio paraula

class crossWord:
    count = 0
    #llegeix el fitxer que conté el crossword i guarda la informació en una matriu n x m (soluciona lectura de caracters \n, \t)
    def llegirTauler1(self, fileName):
        taulerArray=[]
        a=[]
        text_file = open(fileName, 'r')
        lines = text_file.read().split('\n')
        for index, i in enumerate(lines):
            taulerArray.append(i.split('\t'))
            a.append(i.split('\t'))
            for index2, casella in enumerate(taulerArray[index]):
                if(taulerArray[index][index2] == '#'):
                   taulerArray[index][index2] = int(-1)
                else:
                   taulerArray[index][index2] = int(0)

        if taulerArray[-1] == [0]:
            taulerArray.remove([0])

        tauler = np.asarray(taulerArray, dtype=int)
        a = np.asarray(a, dtype=str)
        return tauler, a

    def llegirTauler(self, fileName):
        taulerArray=self.tauler

        contParaula=1
        for fila,f in enumerate(taulerArray):

            col=0
            mida=0
            colIni= col #primera casella de cada fila

            while(col<taulerArray.shape[1]):                                                #comprovem que no hem arribat al final de la fila
                if(f[col] == -1):                                              #si ens trobem coixinet
                    if(mida > 1):                                               #si la paraula fins ara te mes duna lletra, l'afegim a la llista de paraules creant una nova instancia
                        self.paraules=np.append(self.paraules,[[fila,colIni,mida,H]], axis=0)
                        contParaula+=1
                        self.colisions.append([])
                    elif (mida == 1):
                        taulerArray[fila][col-1] = 0
                    colIni=col+1                                   #actualitzem novves coordenades i mida nova paraula
                    mida = 0
                else:
                    if(col+1>=taulerArray.shape[1]):
                        mida+=1                                       #no hi ha coixinet i hem arribat al final de la fila
                        if(mida > 1):                                           #tornem a comprovar si cumpleix amb els requisits de la mida
                            self.paraules=np.append(self.paraules,[[fila,colIni,mida,H]], axis=0)
                            self.colisions.append([])
                            mida=0
                            if(taulerArray[fila][col] == 0):                #Si equesta casella està buida, hi assignem la paraula actual
                                taulerArray[fila][col] = contParaula
                            contParaula+=1
                    else:
                        mida += 1                                               #passem a la seguent columna i actualitzem mida
                        if(taulerArray[fila][col] == 0):                #Si equesta casella està buida, hi assignem la paraula actual
                            taulerArray[fila][col] = contParaula
                col += 1

        for fila,f in enumerate(taulerArray.T):
            col=0
            mida=0
            colIni=col
             #primera casella de cada fila
            while(col<taulerArray.shape[0]):                                                #comprovem que no hem arribat al final de la fila
                if(f[col] == -1):                                              #si ens trobem coixinet                                        #comprovem que el coixinet no sigui la ultima casella
                    if(mida > 1):
                        self.paraules=np.append(self.paraules,[[colIni,fila,mida,V]], axis=0)
                        contParaula+=1
                        self.colisions.append([])
                    colIni=col+1
                    mida = 0
                else:
                    if(col+1>=taulerArray.shape[0]):

                        if (taulerArray[col][fila] == 0):  # Si aquesta casella està buida, hi assignem la paraula actual
                            taulerArray[col][fila] = contParaula
                        elif (f[col - 1] != -1): # (mida > 1) or ((mida <= 1) and (f[col - 1] == -1)):
                            self.colisions[contParaula].append((int(taulerArray[col][fila]), col - colIni, fila - self.paraules[int(taulerArray[col][fila])][Y]))  # Desem a la llista de colisions una tupla amb l'index de la paraula amb qui colisiona, la posició de la paraula en concret i la posicio de l'altre paraula
                            self.colisions[int(taulerArray[col][fila])].append(((contParaula), fila - self.paraules[int(taulerArray[col][fila])][Y], col - colIni))

                        mida+=1                                       # no hi ha coixinet i hem arribat al final de la fila
                        if(mida > 1):                                           # tornem a comprovar si cumpleix amb els requisits de la mida
                            self.paraules=np.append(self.paraules,[[colIni,fila,mida,V]], axis=0)
                            contParaula+=1
                            self.colisions.append([])
                            mida=0
                    else:
                        if (taulerArray[col][fila] == 0):  # Si aquesta casella està buida, hi assignem la paraula actual
                            taulerArray[col][fila] = contParaula
                        elif (mida >= 1) or ((col == 0) and (f[col+1] != -1)) or ((mida < 1) and ((f[col - 1] == -1) and (f[col+1] != -1))):
                            self.colisions[contParaula].append((int(taulerArray[col][fila]), col - colIni, fila - self.paraules[int(taulerArray[col][fila])][Y]))  # Desem a la llista de colisions una tupla amb l'index de la paraula amb qui colisiona i la posició
                            self.colisions[int(taulerArray[col][fila])].append(((contParaula), fila - self.paraules[int(taulerArray[col][fila])][Y], col - colIni))
                        mida += 1                                               # passem a la seguent columna i actualitzem mida

                col += 1

    def llegirDiccionari(self, fileName):
        llista = [linia.rstrip() for linia in io.open(fileName,'r',errors='replace')] # elimina les \n finals a cada paraula
        diccionari={}
        for paraula in llista:                                  # organitzem les paraules per longitud en un diccionari
            if len(paraula) in diccionari:
                diccionari[len(paraula)].append(list(paraula))
            else:
                diccionari[len(paraula)]=[list(paraula)]
        """if(fileName == 'diccionari_A.txt'):
            for i in diccionari:
                diccionari[i] = diccionari[i][::100, :]
        """
        return diccionari

    def checkColisio(self, head, paraula, LVA):
        colisionsCorrectes = 0
        for colisio in self.colisions[head]:
            if LVA is None:
                break
            #colisio[0] es el numero de la paraula amb la que colisiona
            if LVA[colisio[0]] is not None:   #Si hi ha colisio comprovar la lletra de les dues paraules
                lletraParaula1 = paraula[colisio[1]]
                paraula2 = LVA[colisio[0]]
                colisioParaula2 = colisio[2]
                lletraParaula2 = paraula2[colisioParaula2]
                if lletraParaula1 == lletraParaula2:
                    colisionsCorrectes += 1
                else:
                    return False
            else:
                colisionsCorrectes += 1
        if colisionsCorrectes == len(self.colisions[head]):
            return True
        return False

    def backtracking(self, LVA, LVNA):
        if None not in LVA:
            return LVA
        else:
            head = LVNA[0]
            for paraula in self.diccionari[self.paraules[head][SIZE]]:  #iterem només a les paraules del diccionari que tenen la mateixa mida que la variable que volem omplir
                if self.checkColisio(head, paraula, LVA):
                    LVA[head] = paraula
                    resultat = self.backtracking(LVA, LVNA[1:])
                    if LVA is None:
                        pass
                    elif None not in LVA:
                        return resultat

        return None

    def updateDomain(self, head, paraula, D):
        for colisio in self.colisions[head]:
            D[colisio[0]] = D[colisio[0]][D[colisio[0]][:, colisio[2]] == paraula[colisio[1]], :]       #D[k] = D[k][D[k][:, c] == 'A', :]
        return D

    def backtrackingFC(self, LVA, LVNA, D):
        if all(v is not None for v in LVA):
            return LVA
        else:
            head = LVNA[0]
            if D[head].size != 0:
                for paraula in D[head]:
                    if self.checkColisio(head, paraula, LVA):
                        LVA[head] = paraula
                        DPrev = D[:]
                        D = self.updateDomain(head, paraula, D)
                        resultat = self.backtrackingFC(LVA, LVNA[1:], D)
                        D=DPrev[:]
                        if LVA is None:
                            pass
                        elif (all(v is not None for v in LVA)):
                            return resultat

        return None

    def generaDomain(self):
        D = []
        D.append(np.zeros((1,1), dtype= str))
        for paraula in self.paraules[1:]:
            D.append(np.asarray(self.diccionari[paraula[SIZE]]))
        return D

    def calcula(self, algorisme):

        b = np.zeros((self.paraules.shape[0], self.paraules.shape[1] + 1), dtype= int)
        b[:, :-1] = self.paraules
        b[:,4] = np.arange(0,self.paraules.shape[0])
        b = np.flip(sorted(b, key=lambda a_entry: a_entry[2]), axis=0)[:-1]

        LVNA = b[:,4]
        D = self.generaDomain()

        lva = [None] * (self.paraules.shape[0])
        lva[0] = "empty"
        if algorisme:
            lva = self.backtracking(lva, LVNA)
        else:
            lva = self.backtrackingFC(lva, LVNA, D)

        for index, paraula in enumerate(lva[1:]):

            if self.paraules[index][DIR]==H:
                x = self.paraules[index+1][X]
                y = self.paraules[index+1][Y]
                for lletra in paraula:
                    self.taulerResultats[x][y] = lletra
                    y+=1
            elif self.paraules[index][DIR]==V:
                x = self.paraules[index+1][X]
                y = self.paraules[index+1][Y]
                for lletra in paraula:
                    self.taulerResultats[x][y] = lletra
                    x+=1
        print("\nSOLUCIÓ GUARDADA EN crossword_Resolt.txt \n")
        np.savetxt('crossword_Resolt.txt', self.taulerResultats, delimiter='\t', fmt='%s') #escriu el resultat a un fitxer

    def __init__(self, dic, tauler):
        self.paraules = np.zeros((1,4), dtype=int)
        self.colisions = [[],[]]
        self.diccionari = self.llegirDiccionari(dic)
        self.tauler, self.taulerResultats = self.llegirTauler1(tauler)
        self.llegirTauler(tauler)

def main():
    solucio = crossWord('diccionari_CB.txt','crossword_CB.txt')

    print("Resolució mitjançant BackTracking (1) o ForwardChecking (0) ?")
    alg = input()
    while (alg != '1') and (alg != '0'):
        print("Tria una opció correcta: ")
        alg=input()

    if alg == 1:
        msg = "BackTracking"
    else:
        msg = "ForwardChecking"

    start_time = time.time()
    solucio.calcula(alg)
    print(solucio.taulerResultats)
    print("")
    print("Temps transcorregut en segons utilitzant " + msg + ": ")
    print(time.time() - start_time)

if __name__ == "__main__":
    main()


import numpy as np

# -*- coding: utf-8 -*-
"""
Created on Wed Oct 10 19:42:33 2018

@author: Joshua
"""

# Material: Steel

emis = 0.8
stefbolt = 5.67e-8  # W/m^2 K^4
A = .1              # m^2

# Engine Properties

mass_flow = .00000001       # kg/s
c_p = 0             # K/Jkg
T_products = 2000   # K
I = 1000            # W/m^2
v = 1e6             # m/s

power_in = .5*((mass_flow * c_p * T_products / A) + I + (.5 * mass_flow * v**2 / A))

T_4 = (power_in/emis/stefbolt)

T = T_4**.25

print(T)


# -*- coding: utf-8 -*-
from collective.upload.logger import logger
from plone import api

JS = '++resource++collective.upload/upload.js'
CSS = '++resource++collective.upload/upload.css'

def deprecate_resource_registries(setup_tool):
    """Deprecate resource registries."""
    js_tool = api.portal.get_tool('portal_javascripts')
    js_tool.unregisterResource(id=JS)
    assert JS not in js_tool.getResourceIds()  # nosec

    css_tool = api.portal.get_tool('portal_css')
    css_tool.unregisterResource(id=CSS)
    assert CSS not in css_tool.getResourceIds()  # nosec

    logger.info('Static resources were removed from resource registries')


#!/usr/bin/env python3

from collections import Counter
import urllib.request
from lxml import etree

import numpy as np

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.model_selection import cross_val_score
from sklearn import model_selection

alphabet="abcdefghijklmnopqrstuvwxyzäö-"
alphabet_set = set(alphabet)

# Returns a list of Finnish words
def load_finnish():
    finnish_url="https://www.cs.helsinki.fi/u/jttoivon/dap/data/kotus-sanalista_v1/kotus-sanalista_v1.xml"
    filename="src/kotus-sanalista_v1.xml"
    load_from_net=False
    if load_from_net:
        with urllib.request.urlopen(finnish_url) as data:
            lines=[]
            for line in data:
                lines.append(line.decode('utf-8'))
        doc="".join(lines)
    else:
        with open(filename, "rb") as data:
            doc=data.read()
    tree = etree.XML(doc)
    s_elements = tree.xpath('/kotus-sanalista/st/s')
    return list(map(lambda s: s.text, s_elements))

def load_english():
    with open("src/words", encoding="utf-8") as data:
        lines=map(lambda s: s.rstrip(), data.readlines())
    return list(lines)

def get_features(a):
    cv = CountVectorizer(token_pattern='(?u)\\w|-', analyzer='char', vocabulary=alphabet_set)
    arr = cv.fit_transform(a).toarray() #From first column to last
    return np.roll(arr, -1, axis=1)

def contains_valid_chars(s):
    for c in s.lower():
        if c not in alphabet_set:
            return False
    return True

def get_features_and_labels():
    fi_words = load_finnish() #np.char.lower(load_finnish())
    en_words = list( filter( lambda x: x[0].islower(), load_english() ))

    fi_words = list(filter(lambda x: contains_valid_chars(x), fi_words))
    en_words = list(filter(lambda x: contains_valid_chars(x), en_words))

    feature = np.concatenate( (get_features(fi_words), get_features(en_words)) )
    label = np.concatenate( (np.zeros(len(fi_words)), np.ones(len(en_words))) )
    return feature, label

def word_classification():
    feature, label = get_features_and_labels()
    cross_val = model_selection.KFold(n_splits=5, shuffle=True, random_state=0)
    return cross_val_score(MultinomialNB(), X=feature, y=label, cv=cross_val)

def main():
    # L = ["-Achilles", "Achilles's", "Aconcagua", "Aconcagua's", "Acosta", "Acosta's", "Acropolis", "Acrux", "Acrux's", "Actaeon", "Actaeon's"]
    # print(get_features(L)) # PART 1
    # for s in L:
    #     print(contains_valid_chars(s)) # PART 2
    # f, t = get_features_and_labels() # PART 3
    # print(len(f))
    print("Accuracy scores are:", word_classification()) # PART 4

if __name__ == "__main__":
    main()


from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from django.utils.encoding import force_bytes, force_str
from django.contrib.sites.shortcuts import get_current_site
from django.template.loader import render_to_string
from django.utils import timezone
import json
import six

from accounts.tasks import send_email, mail_encoded_body, account_activation_token
from .models import Royalty

def get_verififcation_details(request, royalty, song):
    return {
        'domain': get_current_site(request),
        'artist': request.user,
        'song': song,
        'royalty': royalty
    }

def get_or_create_royalty(royalty_data):
    status = False
    try:
        royalty = Royalty.objects.get(
            username=royalty_data['email'])

        royalty.phone = royalty_data['phone']
        royalty.save()

    except Royalty.DoesNotExist:
        royalty = Royalty.objects.create(
            username=royalty_data['email'], phone=royalty_data['phone'])
        status = True

    return royalty, status

def get_or_create_royalties(request, royalties, song_title):
    royalty = None
    returned_royalties = []

    for r in royalties:

        royalty, created = get_or_create_royalty(royalty)
        returned_royalties.append(royalty)

        confirm_royalty_mail(get_verififcation_details(
            request, r, song_title))

    return returned_royalties

def confirm_royalty_mail(params):
    current_site = params['domain']

    royalty = params['royalty']
    email = royalty['email']
    artist = params['artist']
    song = params['song']

    mail_subject = 'Royalty from Gocreate'
    encode_details = {
        'pk': email,
        'song': str(song.id),
        'split_id': royalty['id'],
        'assignment_timestamp': str(timezone.now())
    }
    uid = urlsafe_base64_encode(force_bytes(json.dumps(encode_details)))
    token = account_activation_token.make_token(artist)

    message = render_to_string('royalty/royalty.html', {
        'title': mail_subject,
        'fullname': royalty['fullname'],
        "description": royalty['description'],
        'artist': artist,
        "share": royalty['share'],
        'song_title': song.title,
        'domain': current_site,
        'uid': uid,
        'token': token,
    })

    print("uid ", uid)
    print("token ", token)
    send_email(mail_subject, message, email)

def verify_royalty_email(uidb64, token):
    content = None
    try:
        decoded_content = force_str(urlsafe_base64_decode(uidb64))
        content = json.loads(decoded_content)

        try:
            user = Royalty.objects.get(username=content['pk'])
        except Royalty.DoesNotExsit:
            user = None

    except Exception as e:
        user = None

    return user, user is not None, content['split_id'] if content is not None else None


from django.urls import path

from rest_framework.routers import SimpleRouter

from . import views
from .api.api_views import CustomUserViewSet, PostViewSet

# Rotas geredas para api
router = SimpleRouter()
router.register('users', CustomUserViewSet)
router.register('posts', PostViewSet)

urlpatterns = [
    path('', views.IndexListView.as_view(), name='index'),
    path('user/cadastro/', views.UserCadastroCreateView.as_view(), name='user_new'),
    path('user/edit/<str:username>/<int:user_id>/', views.UserEditUpdateView.as_view(), name='user_edit'),

    path('post/new/', views.PostCreateView.as_view(), name='post_new'),
    path('post/<str:username>/<int:post_id>/', views.PostDetailView.as_view(), name='post_detail'),
    path('post/<str:username>/update/<int:post_id>/', views.PostUpdateView.as_view(), name='post_update'),
    path('post/<str:username>/delete/<int:post_id>/', views.PostDeleteView.as_view(), name='post_delete'),
    path('user/<str:username>/', views.user_perfil, name='user_perfil'),
]


import socket
import threading
import inspect
import ctypes
import json
import time
from queue import Queue

class Send_data(threading.Thread):
    ip, port = "127.0.0.1", 25001
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    datas = Queue()
    data_is_convey = True

    def __init__(self, con):
        self.con = con
        self.server.bind((self.ip, self.port))
        self.server.listen(5)
        print("[*]成功创建线程!")
        super().__init__()

    def run(self):
        self.con.acquire()
        print("执行socket调用")
        client, addr = self.server.accept()  # 如果有客户端链接
        print("[*]成功建立连接于 %s:%d" % (addr[0], addr[1]))

        received_data = client.recv(1024).decode(
            "UTF-8")  # receiveing data in Byte fron C#, and converting it to String
        print(received_data)

        while not self.datas.empty() or self.data_is_convey:
            self.con.notify()
            self.con.wait()
            if not self.datas.empty():
                data_string = json.dumps(self.datas.get())
                client.send(data_string.encode("UTF-8"))

        client.send(json.dumps({"data_type": "string", "sign": "FINISH"}).encode("UTF-8"))
        client.shutdown(socket.SHUT_RDWR)
        client.close()
        print("通信结束")
        self.con.release()

    def data_save(self, data):
        self.datas.put(data)

    def data_finish(self):
        self.data_is_convey = False


from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

from core.Instances import Instances, Instance

class InserInstanceDialog(QDialog):

    submit_signal=pyqtSignal(Instance,int)

    def __init__(self,parent=None):
        super().__init__(parent)
        self.setWindowTitle("添加新的实例")

    def setAttributes(self,inst:Instances,pos:int=-1):
        flo=QFormLayout()
        flo.setLabelAlignment(Qt.AlignRight)
        flo.setContentsMargins(20,20,20,20)
        flo.setSpacing(15)
        self.m_Instance=inst
        self.m_WidgetList=[]
        self.m_InsertPos=pos
        for i in range(inst.numAttributes()):
            attr=inst.attribute(i)
            label=QLabel(attr.name())
            if attr.isNominal():
                edit=QComboBox()
                edit.addItem("")
                edit.addItems(attr.values())
            elif attr.isNumeric():
                edit=QLineEdit()
                edit.setPlaceholderText("输入数字")
                pDoubleValidator=QDoubleValidator(self)
                edit.setValidator(pDoubleValidator)
            else:
                edit=QLineEdit()
            self.m_WidgetList.append(edit)
            flo.addRow(label,edit)
        hlayout=QHBoxLayout()
        submit=QPushButton("提交")
        submit.clicked.connect(self.submitClick)
        cancel=QPushButton("取消")
        cancel.clicked.connect(self.close)
        hlayout.addWidget(submit)
        hlayout.addWidget(cancel)
        widget=QWidget()
        widget.setLayout(hlayout)
        flo.addRow(widget)
        self.setLayout(flo)

    def submitClick(self):
        data=[]
        for i in range(self.m_Instance.numAttributes()):
            widget=self.m_WidgetList[i]
            if isinstance(widget,QComboBox):
                if widget.currentText() == "":
                    data.append(None)
                else:
                    data.append(widget.currentText())
            elif isinstance(widget,QLineEdit):
                if widget.text() == "":
                    data.append(None)
                elif isinstance(widget.validator(),QDoubleValidator):
                    data.append(float(widget.text()))
                else:
                    data.append(widget.text())
        newInstance = self.m_Instance.createInstance(data)
        self.submit_signal.emit(newInstance,self.m_InsertPos)
        self.close()


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

from pandahub import PandaHubClient
import pandas as pd

if __name__ == '__main__':
    ph = PandaHubClient()
    ph.set_active_project("Manderbach")
    net = ph.get_net_from_db("power")

    ts = ph.multi_get_timeseries_from_db({"name": "H0"}, global_database=True)
    ph.write_timeseries_to_db(ts[0]["timeseries_data"], "p_mw", "sgen")


# 现在有n个长度为m的字符串，编号为从1到n，每个字符串由m个大写字母组成。现在你可以完成以下操作，请你任选第 i 个字符串和第 j 个字符串，并交换长度为 k 的前缀。你可以在变换后的基础上进行任意次这样的操作。

# 例如：ABCD 和 EFGH，令k=2则变为 EFCD 和 ABGH。

# 此时对于新的字符串 EFCD 和 ABGH 令k=1则变为 AFCD 和 EBGH。

# 显然变化后的字符串是不同的。

# 现在请问你可以生成多少个不同的字符串。包含原串本身。

def exchangePrefix(lines, m):
    cols = []
    for i in range(m):
        col = set([line[i] for line in lines])
        cols.append(len(col))

    res = 1
    for c in cols:
        res *= c

    print(res % 1000000007)

if __name__=="__main__":
    line1 = input()
    n, m = line1.split(" ")
    n = int(n)
    m = int(m)
    lines = []
    for _ in range(n):
        line = input()
        lines.append(list(line.strip()))
    exchangePrefix(lines, m)
'''
2 3
ABC
DEF

8
'''


import tkinter as tk
from tkinter import *
from produit import *
from tkinter import ttk
import matplotlib.pyplot as plt

class App:
    # création d'un objet App (menu principal)
    def __init__(self):
        #
        self.gui = Tk()
        self.gui.geometry("400x380")
        self.gui.title("Boutique")
        # variable d'instance de la classe Produit
        self.Quantite = Produit()
        # Txt
        Boutique_label = tk.Label(self.gui, text="Ma\nBoutique",foreground="blue", font=5)
        Boutique_label.pack(pady=50)
        # boutons
        check_btn = tk.Button(self.gui, text="Voir produits", borderwidth=10, command=self.displayProd)
        check_btn.pack(pady=5)
        #
        AddProd_btn = tk.Button(self.gui, text="Ajouter Produit", borderwidth=10, command=self.openAddProd)
        AddProd_btn.pack(pady=5)
        #
        ModProd_btn = tk.Button(self.gui, text="Modifier Produit", borderwidth=10, command=self.updateProd)
        ModProd_btn.pack(pady=5)
        #
        DelProd_btn = tk.Button(self.gui, text="Supprimer Produit", borderwidth=10, command=self.deleteProd)
        DelProd_btn.pack(pady=5)

        self.gui.mainloop()
        # fermeture du curseur une fois l'application fermée
        self.Quantite.cursor.close()
        print("curseur fermé")

    # méthode pour ouvrir et afficher le TopLvl contenant mes produits
    def displayProd(self):
        prod = tk.Toplevel(self.gui)
        prod.title("Mes Produits")
        prod.geometry("1250x600")

        col = ("ID", "Produit", "Desc", "Prix", "Quantite", "categorie")

        tree = ttk.Treeview(prod, columns=col, show="headings")

        tree.heading("ID", text="ID")
        tree.heading("Produit", text="Produit")
        tree.heading("Desc", text="Desc")
        tree.heading("Prix", text="Prix")
        tree.heading("Quantite", text="Quantite")
        tree.heading("categorie", text="categorie")

        items = self.Quantite.displayDATA()

        for item in items:
            tree.insert("", tk.END, values=item)

        tree.grid(row=0, column=0, sticky="nsew")

        scrollbar = ttk.Scrollbar(prod, orient=tk.VERTICAL, command=tree.yview)
        tree.configure(yscroll=scrollbar.set)
        scrollbar.grid(row=0, column=1)
        #
        Export_btn = tk.Button(prod, text="Export CSV", borderwidth=10, command=self.Quantite.exportCSV)
        Export_btn.grid(row=1, column=0, pady=5)
        #
        graph_btn = tk.Button(prod, text="voir Stock", borderwidth=10, command=self.graphQuantite)
        graph_btn.grid(row=1, column=0, pady=5, sticky="w")
        self.L = self.Quantite.displayCat()
        var = tk.Variable(value=self.L)

        self.QuantiteList = tk.Listbox(prod, listvariable=var, height=10, selectmode=tk.SINGLE)
        self.QuantiteList.grid(column=0, row=2, pady=20)
        #
        Export_btn = tk.Button(prod, text="Export CSV", borderwidth=10, command=lambda : self.Quantite.filtredCSV(self.getSelectedItem()))
        Export_btn.grid(row=3, column=0, pady=5)

        prod.mainloop()

    # méthode pour ouvrir et afficher ma fenêtre permettant l'ajout d'un nouveau produit
    def openAddProd(self):
        #
        self.addProd = tk.Toplevel(self.gui)
        #
        self.addProd.title("Ajouter produit")
        #
        self.addProd.geometry("500x300")
        #
        page_Label = tk.Label(self.addProd, text="Produit à ajouter:",foreground="black", font=5, pady=20)
        page_Label.grid(column=0, row=0)
        # Infos du produit à ajouter
        nomProd_Label = tk.Label(self.addProd, text="Nom:",foreground="black", font=5)
        nomProd_Label.grid(column=0, row=1)
        #
        self.nomProd_Entry = tk.Entry(self.addProd, width=30)
        self.nomProd_Entry.grid(column=1, row=1)
        #
        descrProd_Label = tk.Label(self.addProd, text="Description:",foreground="black", font=5)
        descrProd_Label.grid(column=0, row=2)
        #
        self.descProd_Entry = tk.Entry(self.addProd, width=30)
        self.descProd_Entry.grid(column=1, row=2)
        #
        prixProd_Label = tk.Label(self.addProd, text="Prix:",foreground="black", font=5)
        prixProd_Label.grid(column=0, row=3)
        #
        self.prixProd_Entry = tk.Entry(self.addProd, width=30)
        self.prixProd_Entry.grid(column=1, row=3)
        #
        QuantiteProd_Label = tk.Label(self.addProd, text="Quantite:",foreground="black", font=5)
        QuantiteProd_Label.grid(column=0, row=4)
        #
        self.QuantiteProd_Entry = tk.Entry(self.addProd, width=30)
        self.QuantiteProd_Entry.grid(column=1, row=4)
        #
        catProd_Label = tk.Label(self.addProd, text="id_Categorie:",foreground="black", font=5)
        catProd_Label.grid(column=0, row=5)
        #
        self.catProd_Entry = tk.Entry(self.addProd, width=30)
        self.catProd_Entry.grid(column=1, row=5)
        #
        Submit_btn = tk.Button(self.addProd, text="Ajouter", borderwidth=10, command=lambda : self.Quantite.addProd(self.getNom(), self.getDesc(), self.getPrix(), self.getQuantite(), self.getCat(), self.addProd))
        Submit_btn.grid(column=1, row=6, pady=20)

    # méthode pour ouvrir et afficher ma fenêtre permettant la modification d'un de mes produits
    def updateProd(self):
        #
        updProd = tk.Toplevel(self.gui)
        #
        updProd.title("Modifier produit")
        #
        updProd.geometry("500x500")
        #
        self.L = self.Quantite.displayProd()
        var = tk.Variable(value=self.L)

        self.QuantiteList = tk.Listbox(updProd, listvariable=var, height=10, selectmode=tk.SINGLE)
        self.QuantiteList.grid(column=1, row=0)
        page_Label = tk.Label(updProd, text="Produit à modifier:",foreground="black", font=5, pady=20)
        page_Label.grid(column=0, row=0)

        # Infos du produit à modifier
        nomProd_Label = tk.Label(updProd, text="Nom:",foreground="black", font=5)
        nomProd_Label.grid(column=0, row=1)
        #
        self.nomProd_Entry = tk.Entry(updProd, width=30)
        self.nomProd_Entry.grid(column=1, row=1)
        #
        Submit_btn = tk.Button(updProd, text="Modifier", borderwidth=10, command=lambda : self.Quantite.updateProdName(self.getSelectedItem(), self.getNom(), updProd))
        Submit_btn.grid(column=2, row=1, pady=5, padx=15)
        #
        descrProd_Label = tk.Label(updProd, text="Description:",foreground="black", font=5)
        descrProd_Label.grid(column=0, row=2)
        #
        self.descProd_Entry = tk.Entry(updProd, width=30)
        self.descProd_Entry.grid(column=1, row=2)

        #
        Submit_btn = tk.Button(updProd, text="Modifier", borderwidth=10, command=lambda : self.Quantite.updateProdDesc(self.getSelectedItem(), self.getDesc, updProd))
        Submit_btn.grid(column=2, row=2, pady=5)
        #
        prixProd_Label = tk.Label(updProd, text="Prix:",foreground="black", font=5)
        prixProd_Label.grid(column=0, row=3)
        #
        self.prixProd_Entry = tk.Entry(updProd, width=30)
        self.prixProd_Entry.grid(column=1, row=3)
        #
        Submit_btn = tk.Button(updProd, text="Modifier", borderwidth=10, command=lambda : self.Quantite.updateProdPrice(self.getSelectedItem(), self.getPrix(), updProd))
        Submit_btn.grid(column=2, row=3, pady=5)
        #
        QuantiteProd_Label = tk.Label(updProd, text="Quantite:",foreground="black", font=5)
        QuantiteProd_Label.grid(column=0, row=4)
        #
        self.QuantiteProd_Entry = tk.Entry(updProd, width=30)
        self.QuantiteProd_Entry.grid(column=1, row=4)
        #
        Submit_btn = tk.Button(updProd, text="Modifier", borderwidth=10, command=lambda : self.Quantite.updateProdStock(self.getSelectedItem(), self.getQuantite(), updProd))
        Submit_btn.grid(column=2, row=4, pady=5)
        #
        catProd_Label = tk.Label(updProd, text="id_Categorie:",foreground="black", font=5)
        catProd_Label.grid(column=0, row=5)
        #
        self.catProd_Entry = tk.Entry(updProd, width=30)
        self.catProd_Entry.grid(column=1, row=5)
        #
        Submit_btn = tk.Button(updProd, text="Modifier", borderwidth=10, command=lambda : self.Quantite.updateProdCat(self.getSelectedItem(), self.getCat(), updProd))
        Submit_btn.grid(column=2, row=5, pady=5)

    # méthode pour ouvrir et afficher ma fenêtre permettant la suppresion d'un de mes produits
    def deleteProd(self):
        #
        delProd = tk.Toplevel(self.gui)
        #
        delProd.title("Supprimer produit")
        #
        delProd.geometry("500x300")
        #
        self.L = self.Quantite.displayProd()
        var = tk.Variable(value=self.L)

        self.QuantiteList = tk.Listbox(delProd, listvariable=var, height=10, selectmode=tk.SINGLE)
        self.QuantiteList.grid(column=1, row=0)
        page_Label = tk.Label(delProd, text="Produits à supprimer:",foreground="black", font=5, pady=20)
        page_Label.grid(column=0, row=0)
        #
        Del_btn = tk.Button(delProd, text="Supprimer", borderwidth=10, command=lambda : self.Quantite.delProd(self.getSelectedItem(), delProd))
        Del_btn.grid(column=1, row=6, pady=20)

    ## mes getter
    def getSelectedItem(self):
        return self.QuantiteList.get(ANCHOR)
    #
    def getNom(self):
        return self.nomProd_Entry.get()
    #
    def getDesc(self):
        return self.descProd_Entry.get()
    #
    def getPrix(self):
        return self.prixProd_Entry.get()
    #
    def getQuantite(self):
        return self.QuantiteProd_Entry.get()
    #
    def getCat(self):
        return self.catProd_Entry.get()

    def graphQuantite(self):
        # variable contenant mes noms de produits sous forme de liste
        prod = self.Quantite.displayProd()
        # variable contenant mes quantites de produits sous forme de liste
        Quantite = self.Quantite.displayStock()

        # création de mon graph
        plt.pie(Quantite, labels=prod, autopct='%1.1f%%', startangle=90, shadow=True)
        plt.title("Quantite")
        plt.axis('equal')
        plt.show()

if __name__ == "__main__":
    app = App()


import logging
from threading import Thread

class TaskResult(object):
    """
    A class for a task's result
    """
    def __init__(self):
        self.verdict = False
        self.result_value = None

class Task(object):
    """
    A class to represent a task
    """
    _thread: Thread
    result: TaskResult

    def __init__(self, name, func, args=None):
        """
        :param name: name of the task
        :param func: the method for executing the class
        :param args: any arguments needed to start the task
        """
        self.name = name
        self._thread = None
        self._func = func
        self._args = args
        self.running = True
        self.result = None

    def _task_execution(self):
        logging.info(f"{self.name} is now running")
        if self._args:
            self.result = self._func(*self._args)
        else:
            self.result = self._func()
        self.running = False
        logging.info(f"{self.name} is now done!")

    def start_task(self):
        """
        Start executing the task
        """
        logging.info(f"Starting task: {self.name}")
        self._thread = Thread(target=self._task_execution)
        self._thread.start()
        logging.info(f"Started task: {self.name}")


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

import argparse
import os
import shutil
import subprocess
import sys
import sysconfig

from Cython.Distutils import build_ext
from pkg_resources import get_distribution
from setuptools import Extension
from setuptools import setup

CUDA_VERSION = subprocess.check_output(
    'nvcc -V | grep -oP "release\s([0-9\.]+)" | grep -oP "([0-9\.]+)"',
    shell=True).decode('utf-8').strip()

def create_extensions():
    sourcefiles = [
        'pynvvl/_nvvl.pyx',
    ]

    # List up include paths
    include_dirs = [
        os.path.join(os.getcwd(), 'docker/include'),
        '/usr/local/cuda/include',
        sysconfig.get_config_var('INCLUDEPY'),
    ]
    if 'CPATH' in os.environ:
        include_dirs.insert(1, os.environ['CPATH'])

    # List up library paths
    library_dirs = [
        os.path.join(os.getcwd(), 'docker/lib/cuda-{}'.format(CUDA_VERSION)),
    ]
    if 'LD_LIBRARY_PATH' in os.environ:
        library_dirs.append(os.environ['LD_LIBRARY_PATH'])
    if 'LIBRARY_PATH' in os.environ:
        library_dirs.append(os.environ['LIBRARY_PATH'])

    # List up libraries
    libraries = [
        'nvvl',
    ]

    # RPATH which will be set to pynvvl.so
    rpath = [
        '$ORIGIN/_lib',
    ]

    extensions = [
        Extension(
            'pynvvl._nvvl',
            sourcefiles,
            include_dirs=include_dirs,
            library_dirs=library_dirs,
            libraries=libraries,
            language='c++',
            extra_compile_args=['-std=c++11'],
            extra_link_args=['-std=c++11'],
            runtime_library_dirs=rpath,
        )
    ]
    return extensions

def prepare_package_data():
    wheel_libs = [
        'docker/lib/cuda-{}/libnvvl.so'.format(CUDA_VERSION),
        'docker/lib/cuda-{}/libavformat.so.57'.format(CUDA_VERSION),
        'docker/lib/cuda-{}/libavcodec.so.57'.format(CUDA_VERSION),
        'docker/lib/cuda-{}/libavutil.so.55'.format(CUDA_VERSION),
    ]
    lib_dir = 'pynvvl/_lib'
    if not os.path.exists(lib_dir):
        os.makedirs(lib_dir)
    libs = []
    for lib in wheel_libs:
        libname = os.path.basename(lib)
        libpath = os.path.join(lib_dir, libname)
        shutil.copy2(lib, libpath)
        libs.append(os.path.join('_lib', libname))

    package_data = {
        'pynvvl': libs
    }

    return package_data

parser = argparse.ArgumentParser()
parser.add_argument('--package-name', type=str, default='pynvvl')
args, sys.argv = parser.parse_known_args(sys.argv)

package_data = prepare_package_data()
extensions = create_extensions()

cupy_package_name = None
try:
    cupy_package_name = get_distribution(
        'cupy-cuda{}'.format(CUDA_VERSION.replace('.', '')))
    cupy_package_name = cupy_package_name.project_name
except Exception:
    cupy_package_name = 'cupy'

print('=' * 30)
print('CuPy Package Name:', cupy_package_name)
print('=' * 30)

description = \
    'PyNVVL: A Python wrapper for NVIDIA Video Loader (NVVL) with CuPy'

setup(
    name=args.package_name,
    url='https://github.com/mitmul/pynvvl',
    version='0.0.2a5',
    author='Shunta Saito',
    author_email='shunta.saito@gmail.com',
    description=description,
    long_description=open('README.md').read(),
    long_description_content_type='text/markdown',
    license='MIT License',
    packages=['pynvvl'],
    package_data=package_data,
    install_requires=[
        '{}>=4.0.0'.format(cupy_package_name),
    ],
    setup_requires=[
        'cython>=0.27.3',
    ],
    ext_modules=extensions,
    cmdclass={'build_ext': build_ext},
)


import unittest
from do_QA import average

class TestAverageFunction(unittest.TestCase):

    def test_average(self):
        self.assertEqual(average([20, 30, 70]), 40.0)
        self.assertEqual(round(average([1, 5, 7]), 1), 4.3)
        with self.assertRaises(ZeroDivisionError):
            average([])
        with self.assertRaises(TypeError):
            average(20, 30, 70)

class TestStringMethods(unittest.TestCase):

    def test_upper(self):
        self.assertEqual('foo'.upper(), 'FOO')

    def test_isupper(self):
        self.assertTrue('FOO'.isupper())
        self.assertFalse('Foo'.isupper())

    def test_split(self):
        s = 'hello world'
        self.assertEqual(s.split(), ['hello', 'world'])
        # check that s.split fails when the separator is not a string
        with self.assertRaises(TypeError):
            s.split(2)

if __name__ == '__main__':
    unittest.main()
    # Run it from commandline as
    # python3 do_unittest.py TEST_CASE_NAME
    # eg. python3 do_unittest.py TestStringMethods


#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 25 11:32:02 2017

@author: justinpringle
"""

import numpy as np
#from grid_and_shoreline import gridGen

class wave():
    '''
    wave module of GENESIS.
    includes refraction, diffraction, shoaling
    Child of Grid
    '''

    def __init__(self,H0,T0,D0,shoreNormals):
        '''
        bind deep water conditions
        '''
        self.H0 = H0
        self.T0 = T0
        self.D0 = D0
        self.normals = shoreNormals
        self.angles = None

    def orient(self):
        '''
        calcs the angle between incoming wave angle and shore normal.
        Must take note of what is pos and what is neg direction

        '''

        self.angDiff = self.normals-self.D0 #- self.normals
        self.sgn=[]
        for i in range(len(self.angDiff)):
            if self.angDiff[i]>0 or self.angDiff[i]<0:
                self.sgn.append(self.angDiff[i]/np.abs(self.angDiff[i])) #this keeps sin(theta) positive whn calculating Q
            else:
                self.sgn.append(1)
        self.sgn = np.asarray(self.sgn)

    def estL(self,db):
        '''
        see Reeve et al 2004
        '''

        y = 4*np.pi**2/(9.81*self.T0**2)*db
        L = self.T0*np.sqrt(9.81*db*(y+(1+0.6522*y+0.4622*y**2+0.0864*y**4+0.0675*y**5)**-1)**-1)

        return L

    def snell(self,L):
        '''
        calculates angle at breaking.
        '''

        self.thetaB = np.arcsin(L/self.L0*np.sin(self.angles))

    def iteration(self):
        '''
        iterates to find wave angle, height and length at breaking
        '''
        #Init wave conditions
        angles = np.deg2rad(np.abs(self.angDiff))
        #mask to prevent >90 angle diff
        self.angles = angles#np.ma.masked_where(angles==np.isnan,angles)

        self.L0 = 9.81*self.T0**2/(2*np.pi)
        self.C0 = self.L0/self.T0
        self.Cg0 = 0.5*self.C0

        self.gamma = 0.78
        db = self.H0/self.gamma
        L = self.estL(db)
#        print(L)

        self.updateCg(db,L)
        self.snell(L)

        self.refraction()
        self.shoaling()

        HbOld = self.H0
        HbNew = self.Kr*self.Ks*self.H0
#        print(HbOld)
#        print(self.Kr)

        err = np.abs(HbNew-HbOld)/HbOld*100
#        for i in range(len(angles)):
#            print(np.rad2deg(angles[i]),self.normals[i])
#        print('start')

        while np.max(err)>1:
#        for i in range(2):
            db = HbNew/self.gamma
            L = self.estL(db)
#            print(db)
            self.updateCg(db,L)
            self.snell(L)

            self.refraction()
            self.shoaling()

            HbOld = HbNew
            HbNew = self.Kr*self.Ks*self.H0
            err = np.abs(HbNew-HbOld)/HbOld*100
#            for i in range(len(db)):
#                print(self.Ks[i],self.Cg0,self.Cgb[i])
#            print('new')
#            print(err)
#            print(HbNew)

#            print(HbNew)
#        HbNew = self.boundaries(HbNew)
#        self.thetaB = self.boundaries(self.thetaB)
#        self.Cgb = self.boundaries(self.Cgb)
#        self.sgn = self.boundaries(self.sgn)
        return HbNew

    def updateCg(self,d,L):

        n = 0.5*(1+(2*np.pi*d/L)/np.sinh(2*np.pi*d/L))
#        print(n)
        C = L/self.T0
        self.Cgb = n*C

    def refraction(self):
        '''
        calculates the refraction coefficient along wave rays at each grid point
        '''
#        print('ref')
#        for i in self.angles:
#            print(i)
        self.Kr = np.sqrt(np.abs(np.cos(self.angles))/np.abs(np.cos(self.thetaB)))

    def diffraction(self):
        '''
        calculates the diffraction around structures
        '''

        self.Kd = 1

    def shoaling(self):
        '''
        calculates wave shoaling.
        '''
        self.Ks = np.sqrt(self.Cg0/self.Cgb)

    def boundaries(self,H,m=0,n=0):
        '''
        user defined boundaries
        Neumann -> gradient boundary, user to define gradient
        m = gradient at start, n = gradient at end -> default zero
        '''
        h =[]
        h.append(H[0]+m*H[0])
        h.extend(H)

        return np.asarray(h)

if __name__ == '__main__':

    test = wave('',200)
    test.bind(2,16,160)
    test.defaultGrid()
    test.orient()

    ho,hb=test.iteration()


from service.event_service import EventService

class ConsoleUIAdministrator:

    def __init__(self, event_service, participant_service):
        self.__event_service = event_service
        self.__participant_service = participant_service

    def __print_menu(self):
        print("\nAdministrare aplicatie\n"
              "Optiuni:\n"
              "1.Adaugati un eveniment\n"
              "2.Stergeti un eveniment\n"
              "3.Modificati datele unui eveniment\n"
              "4.Vizualizati evenimentele\n"
              "5.Vizualizati evenimentele dintr-un anumit oras\n"
              "6.Vizualizati participantii de la un anumit eveniment\n"
              "7.Vizualizati evenimentele care au participanti\n"
              "0.Iesiti din modul administrator\n")

    def __add_event(self):
        print("Introduceti informatiile despre eveniment:")
        id = input("ID: ")
        name = input("Nume: ")
        city = input("Oras: ")
        maxSpots = int(input("Numar maxim de locuri: "))
        participantsNumber = int(input("Numarul participantilor: "))
        startDate = input("Data de inceput: ")
        finishDate = input("Data finala: ")

        self.__event_service.add_event(id, name, city, participantsNumber, maxSpots, startDate, finishDate, 0)

    def __delete_event(self):
        id = input("Event id: ")
        self.__event_service.delete_event(id)

    def __show_all_events(self):
        for event in self.__event_service.get_all_events():
            print(event)

    def __show_events_with_participants(self):
        ok = 0
        for event in self.__event_service.get_events_with_participants():
            print(event)
            ok = 1
        if ok == 0:
            print("Nu exista evenimente cu participanti")

    def __change_event_data(self):
        print("Introduceti informatiile despre eveniment:")
        id = input("ID: ")
        name = input("Nume: ")
        city = input("Oras: ")
        maxSpots = int(input("Numar maxim de locuri: "))
        participantsNumber = int(input("Numarul participantilor: "))
        startDate = input("Data de inceput: ")
        finishDate = input("Data finala: ")

        self.__event_service.change_event_data(id, name, city, participantsNumber, maxSpots, startDate, finishDate)

    def __show_events_in_city(self):
        city = input("Introduceti orasul pentru care doriti sa vizualizati evenimentele: ")
        for event in self.__event_service.get_events_in_city(city):
            print(event)

    def run(self):
        while True:
            self.__print_menu()
            try:
                command = int(input("Choose the command:").strip())
                if command == 0:
                    break
                elif command == 1:
                    self.__add_event()
                elif command == 2:
                    self.__delete_event()
                elif command == 3:
                    self.__change_event_data()
                elif command == 4:
                    self.__show_all_events()
                elif command == 5:
                    self.__show_events_in_city()
                elif command == 6:
                    print("idk")
                elif command == 7:
                    self.__show_events_with_participants()
            except Exception as error:
                print(error)


from collections import deque

def solution(priorities, location):
    answer = 0
    imp_max = max(priorities)
    priorities = deque(priorities)
    while 1:
        if len(priorities) == 0:
            break
        if priorities[0] < imp_max:
            if location == 0:
                priorities.append(priorities.popleft())
                location = len(priorities) - 1
            else:
                priorities.append(priorities.popleft())
                location -= 1
        if priorities[0] == imp_max:
            if location == 0:
                answer += 1
                return answer
            else:
                priorities.popleft()
                imp_max = max(priorities)
                location -= 1
                answer += 1

print(solution([2, 1, 3, 2], 2))
print(solution([1, 1, 9, 1, 1, 1], 0))


import requests
from bs4 import BeautifulSoup

#URL format
#https://remoteok.io/remote-dev+python-jobs

def extract_jobs(keyword):
    jobs_list = []
    url = f"https://remoteok.io/remote-dev+{keyword}-jobs"
    print(f"Scrapping remoteok")
    result = requests.get(url)
    soup = BeautifulSoup(result.text, "html.parser")
    results = soup.find("table", {"id": "jobsboard"}).find_all("tr", {"class": "job"})

    for result in results:
      job = extract_job_detail(result)
      #print(job)
      jobs_list.append(job)
    return jobs_list

def extract_job_detail(html):
    #print("start extracting details")
    title = html.find("td", {"class":"company position company_and_position"}).find("h2").string
    company = html.find("td", {"class":"company position company_and_position"}).find("h3").string
    link = html.find("td", {"class":"company position company_and_position"}).find("a", {"itemprop": "url"})["href"]

    return {
        'title': title,
        'company': company,
        'link': f"https://remoteok.io/{link}"
    }

def search_jobs(keyword):
  jobs_list = extract_jobs(keyword)
  return jobs_list


from typing import Callable, List

# ***** Get list with items divided by 3 but not divided by 6 using List Comprehension *****
# 10 -> [0, 3, 9]

c1 = [x for x in range(0, 20) if x % 3 == 0 and not (x // 6 > 0 and x % 6 == 0)]
# print(c1)

# Function implementation:
def dev_3_not_dev_6(number):
    return [
        x
        for x in range(0, number + 1)
        if x % 3 == 0 and not (x // 6 > 0 and x % 6 == 0)
    ]

# print(dev_3_not_dev_6(30))

# ***** Get list with items divided by 3 but not divided by 6 using filter() *****

f = filter(lambda x: x % 3 == 0 and not (x // 6 > 0 and x % 6 == 0), range(0, 11))
# print(list(f))

# Function implementation:
def dev_3_not_dev_6_filter(number):
    return list(
        filter(
            lambda x: x % 3 == 0 and not (x // 6 > 0 and x % 6 == 0),
            range(0, number + 1),
        )
    )

# print(dev_3_not_dev_6_filter(20))

# ***** Implement filter() using list comprehension *****

# filter() example
filter_mehod = filter(lambda x: x >= 5, range(3, 8))
# print(list(filter_mehod))

# List comprehension usage
filter_compr_method = [x for x in range(3, 8) if x >= 5]
# print(filter_compr_method)

# function implementation
def filter_comprehension(func: Callable, iterable: [List, range]) -> list:
    """
    Filter the list by condition from the function
    :param func: Function with condition to verify
    :param iterable: List of elements you want to check for condition
    :return: List of elements which satisfies the condition
    """
    return [x for x in iterable if func(x)]

res_f = filter_comprehension(lambda x: x >= 5, range(3, 8))
# print(res_f)

# ***** Implement map() using list comprehension *****

# map() example
map_method = map(lambda x: x % 3 == 0 and not (x // 6 > 0 and x % 6 == 0), range(0, 20))
# print(list(map_method))

# List comprehension usage
map_compr_method = [
    x % 3 == 0 and not (x // 6 > 0 and x % 6 == 0) for x in range(0, 11)
]
# print(map_compr_method)

# function implementation
def map_comprehension(func: Callable, iterable: [List, range]) -> list:
    """
    Apply function to each element in the list
    :param func: Function you want to apply
    :param iterable: List of elements you want to apply function on
    :return: List of the new elements processed by the function
    """
    return [func(x) for x in iterable]

res = map_comprehension(
    lambda x: x % 3 == 0 and not (x // 6 > 0 and x % 6 == 0), range(0, 11)
)
# print(res)

# ***** Implement enumerate() using list comprehension *****

# enumerate() example
grocery = ["bread", "milk", "butter"]
enumerate_res = enumerate(grocery)
# print(list(enumerate_res))

# Implementation with for loop
enumerate_for_res = []
pos = 0
for val in grocery:
    enumerate_for_res.append((pos, val))
    pos += 1

# List comprehension usage
enumerate_compr_res = [(grocery.index(val), val) for val in grocery]
# print(enumerate_compr_res)

# function implementation
def enumerate_comprehension(collection: [range, list], start: int = 0) -> list:
    """
    Enumerate list of elements
    :param collection: List of elements you want to enumerate
    :param start: The number from which enumeration should start, default 0
    :return: List of tuples with enumeration
    """
    return [(collection.index(x) + start, x) for x in collection]

# enumerate_func_res = enumerate_comprehension(grocery, 15)
enumerate_func_res = enumerate_comprehension(range(5), 15)
# print(enumerate_func_res)


import time
import json
import csv
import pandas as pd
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.chrome.service import Service

from webdriver_manager.chrome import ChromeDriverManager

driver = webdriver.Chrome(ChromeDriverManager().install())

#website
driver.get('https://opensea.io/collection/art')

driver.maximize_window()
#get title
driver.implicitly_wait(10)

print("--->title",driver.title)

#/html/body/div/div[1]/main/div/div/div[2]/div/div/div[1]/aside/div/div[2]/div/div/div/div/div[2]/div[1]/section/div/div/input
driver.execute_script("window.scrollBy(0,300)","")
obj=driver.find_element_by_xpath("//input[@placeholder='Min']")
s=obj.send_keys("1.25")
obj=driver.find_element_by_xpath("//input[@placeholder='Max']")
s=obj.send_keys("3.25")

#button
#//button[@class='Blockreact__Block-sc-1xf18x6-0 Buttonreact__StyledButton-sc-glfma3-0 cWgiBW kaikhX ActionButtonreact__StyledButton-sc-7jpoey-0 bwNKOH']
apply=driver.find_element_by_xpath("//button[@class='Blockreact__Block-sc-1xf18x6-0 Buttonreact__StyledButton-sc-glfma3-0 fAtwh kaikhX ActionButtonreact__StyledButton-sc-7jpoey-0 bwNKOH']")
s=apply.click()

time.sleep(3)

#aricle
# //article[@class="Assetreact__DivContainer-sc-bnjqwy-0 gwTKfX Asset--loaded AssetSearchList--asset"]

#image url data
image_url=[]
while True:
    driver.execute_script("window.scrollBy(0,300)","")

    obj = driver.find_elements_by_xpath("//img[@class='Image--image']")
    for i in obj:
        img_src=i.get_attribute("src")
        image_url.append(img_src)
        print(img_src)

    if len(img_src)<5000:
        break

"""
<img class="Image--image" src="https://lh3.googleusercontent.com/xUgm8yFV61OGAtdBz73D5TZpNXsZJTYXjfjHKYZuW9poum0aChIxu6W1LquWXsj5JqCSuLuqfI1ypVau5byDWduhEdOZveDn7PKx=w333" style="object-fit: contain; width: auto; height: auto; border-radius: 5px; max-width: 100%; max-height: 100%;">
 """
"""
lisst=[]
condition= True

while condition :
    obj = driver.find_elements_by_xpath("//*[@id='__next']/div[1]/main/div/div/div/div[2]/div/div[5]/div/div/div/div/div/div/div[2]/div/div[2]/div[3]/div/a/self::a")

    for ai in obj:
        #print(obj)
        out = obj.text
        lisst.append(out)
        print(lisst)  """
#1.collection
#//div[@class='AssetCardFooter--collection']
#//a[@class='Linkreact__StyledA-sc-18se2b0-0 iWVmEt AssetCardFooter--collection-name']
li=[]
txt=i.text
while True:
    driver.execute_script("window.scrollBy(0,200)","")

    col = driver.find_elements_by_xpath("//a[@class='Linkreact__StyledA-sc-18se2b0-0 iWVmEt AssetCardFooter--collection-name']")
    for i in col:
        txt=i.text
        li.append(txt)
        print(txt)

    if len(txt)<5000:
        #print(len(text1))
        break

#2.name
#//div[@class='AssetCardFooter--name']
name=[]
name1=i.text
while True:
    driver.execute_script("window.scrollBy(0,200)","")

    nam = driver.find_elements_by_xpath("//div[@class='AssetCardFooter--name']")
    for i in nam:
        name1=i.text
        name.append(name1)
        print(name1)

    if len(name1)<5000:
        #print(len(name1))
        break

#3.bid value
# //div[@class='Overflowreact__OverflowContainer-sc-10mm0lu-0 fqMVjm Price--amount']
bid_value=[]
while True:
    driver.execute_script("window.scrollBy(0,200)","")

    bid_ = driver.find_elements_by_xpath("//div[@class='Overflowreact__OverflowContainer-sc-10mm0lu-0 fqMVjm Price--amount']")
    for i in bid_:
        sad=i.text
        bid_value.append(sad)
        print(sad)

    if len(sad)<5000:
        #print(len(sad))
        break

#4.type of bid
# //div[@class='AssetCardFooter--price-header']
type_bid=[]
while True:
    driver.execute_script("window.scrollBy(0,200)","")

    type_bi = driver.find_elements_by_xpath("//div[@class='AssetCardFooter--price-header']")
    for i in type_bi:
        na=i.text
        type_bid.append(na)
        print(na)

    if len(na)<5000:
        #print(len(na))
        break

#5.favorite
#//div[@class="Blockreact__Block-sc-1xf18x6-0 Flexreact__Flex-sc-1twd32i-0 FlexVerticalreact__FlexVertical-sc-x35rw8-0 VerticalAlignedreact__VerticalAligned-sc-1v4gkkl-0 beUSAq jYqxGr gXnSUK gJMdLt"]
#//span[@class='Blockreact__Block-sc-1xf18x6-0 Textreact__Text-sc-1w94ul3-0 jEeFPO gwsEKa']

#//div[@class='Blockreact__Block-sc-1xf18x6-0 Flexreact__Flex-sc-1twd32i-0 FlexVerticalreact__FlexVertical-sc-x35rw8-0 VerticalAlignedreact__VerticalAligned-sc-1v4gkkl-0 beUSAq jYqxGr gXnSUK gJMdLt']
#//div[@class='Blockreact__Block-sc-1xf18x6-0 Flexreact__Flex-sc-1twd32i-0 FlexVerticalreact__FlexVertical-sc-x35rw8-0 VerticalAlignedreact__VerticalAligned-sc-1v4gkkl-0 fAzvQd jYqxGr gXnSUK gJMdLt']
fav=[]
while True:
    driver.execute_script("window.scrollBy(0,200)","")

    fA = driver.find_elements_by_xpath("//div[@class='Blockreact__Block-sc-1xf18x6-0 Flexreact__Flex-sc-1twd32i-0 FlexVerticalreact__FlexVertical-sc-x35rw8-0 VerticalAlignedreact__VerticalAligned-sc-1v4gkkl-0 fAzvQd jYqxGr gXnSUK gJMdLt']")
    for i in fA:
        s=i.text
        fav.append(s)
        print(s)

    if len(s)<1000:
        #print(len(s))
        break

#token

# //a[@class='Linkreact__StyledA-sc-18se2b0-0 iWVmEt Asset--anchor']
tok=[]
for j in range(100):
    #driver.execute_script("window.scrollBy(0,200)","")

    Tk = driver.find_elements_by_xpath("//a[@class='Blockreact__Block-sc-1xf18x6-0 fAtwh AssetsSearchView--assets']")
    #Blockreact__Block-sc-1xf18x6-0 fAtwh AssetsSearchView--assets
    for i in Tk: #Linkreact__StyledA-sc-18se2b0-0 iWVmEt Asset--anchor
        da=i.get_attribute("href")
        tok.append(da)
        print(da)

""" dic={
    'image':image_url[0:4],
    'collection':li[0:4],
    'name':name[0:4],
    'type_of_bid':type_bid[0:4],
    'favourite':fav[0:4],
    'eth_value':bid_value[0:4],
    'token_id':tok[0:4]

}

print(dic)

 with open('openseaee.csv','w')as f:
    w=csv.DictWriter(f,dic.keys())
    w.writeheader()

df =pd.DataFrame(dic)
print(df)
df.to_csv('sasea.csv',encoding='utf-8', index=False)      """


import imutils
from imutils.video import VideoStream
import time
import cv2

print("[INFO] starting video stream...")
vs = VideoStream(src=2).start()
time.sleep(2.0)
num = 1

while True:
    frame = vs.read()
    # show the output frame
    frame = cv2.flip(frame, 1)
    cv2.imshow("Frame", frame)
    key = cv2.waitKey(1) & 0xFF
    # if the `q` key was pressed, break from the loop
    if key == ord("q"):
        cv2.imwrite(f"calsLogitechCharuco2/Charcuo_cal_{num}.jpg", frame)
        num += 1


#네이버 test
arr=list(map(int, input().split()))
arr.sort()

answer=[]
tmp=arr[0]
cnt=0

for i in range(1,len(arr)):
    if tmp== arr[i]:
        cnt+=1
        if i == len(arr)-1:
            answer.append(cnt+1)
    else:
        if cnt != 0:
            answer.append(cnt+1)
        tmp=arr[i]
        cnt=0

if len(answer) == 0:
    print(-1)
else:
    print(answer)


# -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function, absolute_import

from django import template
from django.core.exceptions import ObjectDoesNotExist
from django.utils.safestring import mark_safe

register = template.Library()

@register.filter
def iconic(value):
    if isinstance(value, bool):
        if value:
            return mark_safe(''
                             ''
                             '')
        return mark_safe(''
                         ''
                         '')
    return value

@register.filter
def is_reviewer(user):
    """Checks if the user is a reviewer."""
    if user.is_superuser:
        return True
    if user.is_authenticated:
        try:
            _ = user.reviewer
        except ObjectDoesNotExist:
            return False
        return True
    return False


N = int(input())

ans = 10**20
for a in range(1010101):
    ok = 1010101
    ng = -1
    while(ok - ng > 1):
        mid = (ok + ng) //2
        if a*a*a + mid*(a*a) + a*(mid*mid) + mid*mid*mid >= N:
            ok = mid
        else:
            ng = mid
    ans = min(a*a*a + ok*(a*a) + a*(ok*ok) + ok*ok*ok, ans)
print(ans)


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

import wx
from misc import MyException

class SimpleGrid(wx.FlexGridSizer):

	def __init__(self, parent, entries, rowlabels=None, collabels=None, colors=None):
		numRows = len(entries)
		if rowlabels is None:
			haveRowLabels = 0
		else:
			haveRowLabels = 1
			if not len(rowlabels) == numRows:
				raise MyException('Number of row labels ({0:d}) must match number of rows ({1:d}).'.format(len(rowlabels), numRows), 3)
		numCols = len(entries[0])
		if collabels is None:
			haveColLabels = 0
		else:
			haveColLabels = 1
			if not len(collabels) == numCols:
				raise MyException('Number of column labels ({0:d}) must match number of columns ({1:d}).'.format(len(collabels), numCols), 3)

		self.border = 5

		wx.FlexGridSizer.__init__(self, numRows + haveColLabels, numCols + haveRowLabels, self.border, self.border)

		firstColAlign = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT
		otherColAlign = wx.EXPAND

		# if we have row and column labels, we need an empty element in top left corner
		if (rowlabels is not None) and (collabels is not None):
			self.Add(wx.StaticText(parent, label=''), 0, firstColAlign, self.border)
		# if we have column labels, print a row of column labels
		if collabels is not None:
			for l in collabels:
				self.Add(wx.StaticText(parent, label=l), 0, otherColAlign, self.border)
		for i in range(numRows):
			# if we have row labels, print label of current row first
			if rowlabels is not None:
				self.Add(wx.StaticText(parent, label=rowlabels[i]), 0, firstColAlign, self.border)
			# print entries itself
			for j in range(numCols):
				entry = wx.TextCtrl(parent, -1, entries[i][j], style=wx.TE_READONLY)
				if colors is not None:
					if colors[i][j] is not None:
						entry.SetBackgroundColour(colors[i][j])
				self.Add(entry, 0, otherColAlign, self.border)

		# make all columns growable (except first one if we have row labels)
		for i in range(haveRowLabels, haveRowLabels + numCols):
			self.AddGrowableCol(i)


import tensorflow as tf

from tflo import test_utils
from tflo.extras.sum import LinearOperatorSum

class LinearOperatorSumTest(
    tf.test.TestCase,
    test_utils.LinearOperatorTest,
    test_utils.MatrixTest,
):
    def _get_operator(self, rng: tf.random.Generator):
        shape = (5, 7)
        num_terms = 3
        terms = [
            tf.linalg.LinearOperatorFullMatrix(rng.normal(shape))
            for _ in range(num_terms)
        ]
        op = LinearOperatorSum(terms)
        return op

    def test_to_dense(self, seed=0, atol=1e-3, rtol=1e-3):
        super().test_to_dense(seed=seed, atol=atol, rtol=rtol)

    def test_matmul(self, seed=0, n_rhs=3, atol=2e-3, rtol=1e-3):
        super().test_matmul(seed=seed, n_rhs=n_rhs, atol=atol, rtol=rtol)

if __name__ == "__main__":
    tf.test.main()