import argparse
import os
import copy
import math
import time
import random
import pickle
import torch
import numpy as np
from prettytable import PrettyTable
from multiprocessing import Pool
from tianshou.data import ReplayBuffer, Batch
from envs.expert_env import ExpertEnv
from utils.common import get_config_from_yml, generate_environment_samples, read_log_file, generate_environment_test_samples

def collect_demonstrations(expert_env):
    sample_count = expert_env.sample_count()
    demonstrations = {}
    for _ in range(sample_count):
        state = expert_env.reset()
        video, user, trace, qoe_weight = expert_env.current_video, expert_env.current_user, \
            expert_env.current_trace, expert_env.current_qoe_weight
        qoe_weight = tuple(qoe_weight.astype(np.int32).tolist())

        states, actions = [], []
        done = False
        while not done:
            action = expert_env.choose_action()
            states.append(copy.deepcopy(state))
            actions.append(action)
            state, reward, done, _ = expert_env.step(action)

        length = len(states)
        demonstration = ReplayBuffer(length)
        for i in range(length):
            demonstration.add(Batch(obs=states[i], act=actions[i], rew=0, done=(i == length - 1),
                                    obs_next=i + 1, info={}))
        demonstrations[video, user, trace, qoe_weight] = demonstration
        print(f'Demonstration of video-{video}, user-{user}, trace-{trace}, qoe-weight-{qoe_weight} done!')
    return demonstrations

def create_demonstrations(args, config, qoe_weights, models_dir, demos_dir, cache_path, mode='train'):
    log_path = os.path.join(models_dir, f'{mode}_log.csv')
    demo_path = os.path.join(demos_dir, f'{mode}_demonstrations.pkl')
    if os.path.exists(log_path):
        os.remove(log_path)

    videos = config.video_split[args.train_dataset][mode]
    users = config.user_split[args.train_dataset][mode]
    traces = config.network_split[args.network_dataset][mode]
    all_samples = generate_environment_samples(videos, users, traces, qoe_weights, seed=args.seed)
    print('Total samples:', len(all_samples))

    proc_num = args.proc_num
    samples_per_proc = math.ceil(len(all_samples) / proc_num)
    expert_envs = []
    for i in range(proc_num):
        samples = []
        for j in range(i * samples_per_proc, min((i + 1) * samples_per_proc, len(all_samples))):
            samples.append(all_samples[j])
        expert_envs.append(ExpertEnv(config, args.train_dataset, args.network_dataset, qoe_weights, samples,
                                     demos_dir, cache_path, log_path, config.startup_download, args.horizon,
                                     args.refresh_cache if i == 0 else False, mode, args.seed))

    start_time = time.time()
    pool = Pool(proc_num)
    results = []
    for i in range(proc_num):
        results.append(pool.apply_async(collect_demonstrations, (expert_envs[i],)))
    pool.close()
    pool.join()

    total_demonstrations = {}
    for result in results:
        total_demonstrations.update(result.get())
    end_time = time.time()

    pickle.dump(total_demonstrations, open(demo_path, 'wb'))
    print(f'Create {len(all_samples)} demonstrations, saved at {demo_path}, cost {round((end_time - start_time) / 3600, 2)}h')

def test(args, config, qoe_weights, results_dir, demos_dir, cache_path):
    log_path = os.path.join(results_dir, 'results.csv')
    if os.path.exists(log_path):
        os.remove(log_path)

    videos = config.video_split[args.test_dataset]['test']
    users = config.user_split[args.test_dataset]['test']
    traces = config.network_split[args.network_dataset]['test']
    all_samples = generate_environment_test_samples(videos, users, traces, qoe_weights)

    expert_env = ExpertEnv(config, args.test_dataset, args.network_dataset, qoe_weights, all_samples,
                           demos_dir, cache_path, log_path, config.startup_download, args.horizon,
                           args.refresh_cache, 'test', args.seed)
    sample_count = expert_env.sample_count()
    for i in range(sample_count):
        state = expert_env.reset()
        video, user, trace, qoe_weight = expert_env.current_video, expert_env.current_user, \
            expert_env.current_trace, expert_env.current_qoe_weight

        done = False
        while not done:
            action = expert_env.choose_action()
            state, reward, done, _ = expert_env.step(action)
        print(f'video-{video}, user-{user}, trace-{trace}, qoe-weight-{qoe_weight} done!')

    read_log_file(log_path)

def run(args, config):
    # seed
    np.random.seed(args.seed)
    torch.manual_seed(args.seed)
    torch.cuda.manual_seed(args.seed)
    torch.cuda.manual_seed_all(args.seed)
    random.seed(args.seed)

    if args.qoe_train_ids is None:
        args.qoe_train_ids = list(range(len(config.qoe_split['train'])))
    split = 'train' if args.test_on_seen else 'test'
    if args.qoe_test_ids is None:
        args.qoe_test_ids = list(range(len(config.qoe_split[split])))

    models_dir = os.path.join(config.bs_models_dir, args.model, args.train_dataset + '_' + args.network_dataset, 'qoe' + '_'.join(map(str, args.qoe_train_ids)))
    demos_dir = os.path.join(config.bs_models_dir, args.model, args.train_dataset + '_' + args.network_dataset, 'qoe' + '_'.join(map(str, args.qoe_train_ids)))
    if args.test_on_seen:
        results_dir = os.path.join(config.bs_results_dir, args.model,  args.test_dataset + '_' + args.network_dataset, 'seen_qoe' + '_'.join(map(str, args.qoe_test_ids)))
    else:
        results_dir = os.path.join(config.bs_results_dir, args.model,  args.test_dataset + '_' + args.network_dataset, 'unseen_qoe' + '_'.join(map(str, args.qoe_test_ids)))
    train_cache_path = os.path.join(config.bs_models_dir, args.model, f'{args.train_dataset}_cache.pkl')
    test_cache_path = os.path.join(config.bs_models_dir, args.model, f'{args.test_dataset}_cache.pkl')
    if not os.path.exists(models_dir):
        os.makedirs(models_dir)
    if not os.path.exists(demos_dir):
        os.makedirs(demos_dir)
    if not os.path.exists(results_dir):
        os.makedirs(results_dir)

    if args.train:
        qoe_weights = [config.qoe_split['train'][i] for i in args.qoe_train_ids]
        print("Training QoE weights:", qoe_weights)
        create_demonstrations(args, config, qoe_weights, models_dir, demos_dir, train_cache_path, 'train')
    if args.valid:
        qoe_weights = [config.qoe_split['valid'][i] for i in args.qoe_train_ids]
        print('Validating QoE weights:', qoe_weights)
        create_demonstrations(args, config, qoe_weights, models_dir, demos_dir, train_cache_path, 'valid')
    if args.test:
        qoe_weights = [config.qoe_split[split][i] for i in args.qoe_test_ids]
        print('Testing QoE weights:', qoe_weights)
        test(args, config, qoe_weights, results_dir, demos_dir, test_cache_path)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--logdir', type=str, default='log_tensorboard')
    parser.add_argument('--model', type=str, default='expert')
    parser.add_argument("--train", action='store_true')
    parser.add_argument("--valid", action='store_true')
    parser.add_argument("--test", action='store_true')
    parser.add_argument("--test-on-seen", action='store_true')
    parser.add_argument('--train-dataset', type=str, default='Wu2017')
    parser.add_argument('--test-dataset', type=str, default='Wu2017')
    parser.add_argument('--network-dataset', type=str, default='4G')
    parser.add_argument('--qoe-train-ids', type=int, nargs='*')  # train on one or more qoe
    parser.add_argument('--qoe-test-ids', type=int, nargs='*')  # test on one or more qoe
    parser.add_argument('--proc-num', type=int, help='Process number for multiprocessing')
    parser.add_argument('--horizon', type=int, help='The horizon for expert to look ahead', default=4)
    parser.add_argument('--refresh-cache', action='store_true', help='Refresh cache')
    parser.add_argument('--seed', type=int, default=1)
    args = parser.parse_known_args()[0]

    # Train/Valid
    # python run_expert.py --train-dataset Jin2022 --train --valid --horizon 4 --proc-num 8

    # Test
    # python run_expert.py --test-dataset Jin2022 --test --horizon 2 --qoe-test-ids 3 --test-on-seen

    print(args)

    config = get_config_from_yml()
    run(args, config)


from datetime import datetime
from pathlib import Path

def create_model_monitor_dir(rewards_dir, model_name, env_name, policy_name):
    now_str = datetime.now().strftime("%d-%m-%Y_%H-%M")
    path = Path(rewards_dir, env_name, f"{model_name}-{policy_name}_{now_str}")
    path.mkdir(parents=True, exist_ok=True)
    return path

def create_model_save_dir(models_dir, model_name, env_name, policy):
    # cast policy to str, as we might use our own policy implementation
    now_str = datetime.now().strftime("%d-%m-%Y_%H-%M")
    path = Path(models_dir, env_name, f"{model_name}-{str(policy)}-{now_str}")
    path.mkdir(parents=True, exist_ok=True)
    return path

def add_metrics_dict_to_csv(metrics, csv_filepath, is_first_row=False):
    if is_first_row:
        # Create file if doesn't exist - i.e. on first write
        fp = csv_filepath.open("w")
    else:
        fp = csv_filepath.open("a")

    # write header row
    if is_first_row:
        headers = ",".join(metrics.keys())
        fp.write(headers)
        fp.write("\n")

    # write data row
    fp.write(",".join(map(str, metrics.values())))
    fp.write("\n")


def wrap(word, display):
     seq=int(len(word)/display)
     gap=0
     a=[]
     for i in range(seq+1):
         a.append(word[gap:gap+display])
         gap+=display
     return '\n'.join(a)

print(wrap("SAMARTHAKRAO",3).strip())


# #####
# PYGAL
# #####

from IPython.display import display, HTML
html_pygal="""
<!DOCTYPE html>
<html>
  <head>
  <script type="text/javascript" src="http://kozea.github.com/pygal.js/latest/pygal-tooltips.min.js"></script>
    <!-- ... -->
  </head>
  <body>
    <figure>
      <!-- Pygal render() result: -->
      {a}
      <!-- End of Pygal render() result: -->
    </figure>
  </body>
</html>
"""
fig_pygal="""
<figure>
  <!-- Pygal render() result: -->
  {a}
  <!-- End of Pygal render() result: -->
</figure>
"""
def show(chart):
    plot_html = html_pygal.format(a=chart.render(is_unicode=True))
    display(HTML(plot_html))
def to_html(chart):
    plot_html = html_pygal.format(a=chart.render(is_unicode=True))
    return plot_html
def to_html_fig(chart):
    plot_html_fig = fig_pygal.format(a=chart.render(is_unicode=True))
    return plot_html_fig
def to_svg(chart):
    return chart.render(is_unicode=True)


from openpyxl import Workbook, load_workbook
from openpyxl.utils.cell import coordinate_from_string
import time
import collections as coll
#### 두 번째 방법이 효율적

## 첫 번째 방법(나)
start = time.time()
wb = Workbook()
ws = wb.active

# 데이터를 입력(리스트,튜플)
ws.append(['학번', '출석', '퀴즈1', '퀴즈2', '중간고사', '기말고사', '프로젝트'])
source = [
    [1,10,8,5,14,26,12],
    [2,7,3,7,15,24,18],
    [3,9,5,8,8,12,4],
    [4,7,8,7,17,21,18],
    [5,7,8,7,16,25,15],
    [6,3,5,8,8,17,0],
    [7,4,9,10,16,27,18],
    [8,6,6,6,15,19,17],
    [9,10,10,9,19,30,19],
    [10,9,8,8,20,25,20]
    ]

# for i in range(10):  # 범위(range)로 지정 - 두번 호출(비효율)
#     ws.append(source[i])
# ↓ 수정
for i in source:  # 리스트를 지정- 한번 호출(효율)
    ws.append(i)

# 1. 퀴즈2 점수를 10으로 수정
# 2중 반복문(for 문) 사용, 두 번째 방법 보다 소모 시간이 작음
for col in ws.iter_cols(min_row=2, min_col=4, max_col=4):
    # print(col)
    for row in col:
        row.value = 10
        # print(row.value)

# 2. H열에 총점(SUM 이용)
# ws.insert_cols(8, 2)  # insert 는 셀 사이에 또 다른 셀을 추가할 때만 사용
ws['H1'] = '총점'
ws['I1'] = '성적'

for row in ws.iter_rows(min_row=2, min_col=2):
    # print(row)
    # print(row[0].coordinate, row[5].coordinate)
    ws[row[6].coordinate] = '=SUM({}:{})'.format(row[0].coordinate, row[5].coordinate)
    # print(ws[row[6].coordinate].value)

sum_score = []
for score in source:
    sum_score.append(sum(score[1:]) - score[3] + 10)
# print(sum_score)

# I열에 성적 정보 추가
# 출석이 5 미만인 학생은 총점 상관없이 F
count = 0
for row in ws.iter_rows(min_row=2, min_col=2):
    # print(ws[row[6].coordinate].value)

    # - 총점 90 이상 A, 80 이상 B, 70 이상 C, 나머지 D
    if int(ws[row[0].coordinate].value) < 5:  # 출석 5 미만
        ws[row[7].coordinate] = 'F'
    else:
        if sum_score[count] >= 90:  # 총점 90점 이상
            ws[row[7].coordinate] = 'A'
        elif sum_score[count] >= 80:  # 총점 80점 이상
            ws[row[7].coordinate] = 'B'
        elif sum_score[count] >= 70:  # 총점 70점 이상
            ws[row[7].coordinate] = 'C'
        else:
            ws[row[7].coordinate] = 'D'
    count += 1
    # print(ws[row[7].coordinate].value)

print('time :', time.time() - start)

wb.save("/Users/csh/jupytercreation/Python_Practice/RPA/basic/1_excel/data/scores.xlsx")

## 두 번째 방법(유튜버) - win
# start = time.time()
# wb = Workbook()
# ws = wb.active

# ws.append(['학번', '출석', '퀴즈1', '퀴즈2', '중간고사', '기말고사', '프로젝트'])
# source = [
#     [1,10,8,5,14,26,12],
#     [2,7,3,7,15,24,18],
#     [3,9,5,8,8,12,4],
#     [4,7,8,7,17,21,18],
#     [5,7,8,7,16,25,15],
#     [6,3,5,8,8,17,0],
#     [7,4,9,10,16,27,18],
#     [8,6,6,6,15,19,17],
#     [9,10,10,9,19,30,19],
#     [10,9,8,8,20,25,20]
#     ]

# for i in source:  # 리스트를 지정- 한번 호출(효율)
#     ws.append(i)

# # 1. 퀴즈2 점수를 10으로 수정
# # 반복문, 조건문을 한번씩 사용, 모든 셀의 데이터를 한번에 교체함, 첫 번째 방법 보다 소모 시간이 큼
# for idx, cell in enumerate(ws['D']):
#     if idx == 0:
#         continue
#     cell.value = 10

# ws['H1'] = '총점'
# ws['I1'] = '성적'

# # 2. H열에 총점(SUM 이용), I열에 성적 정보 추가
# for idx, score in enumerate(source, start=2):
#     sum_val = sum(score[1:]) - score[3] + 10  # 총점
#     ws.cell(row=idx, column=8).value = '=SUM(B{}:G{})'.format(idx, idx)

#     # - 총점 90 이상 A, 80 이상 B, 70 이상 C, 나머지 D
#     grade = None
#     if sum_val >= 90:
#         grade = 'A'
#     elif sum_val >= 80:
#         grade = 'B'
#     elif sum_val >= 70:
#         grade = 'C'
#     else:
#         grade = 'D'

#     # 3. 출석이 5 미만인 학생은 총점 상관없이 F
#     if score[1] < 5:
#         grade = 'F'

#     ws.cell(row=idx, column=9).value = grade

# print('time :', time.time() - start)

# wb.save("/Users/csh/jupytercreation/Python_Practice/RPA/basic/1_excel/data/scores.xlsx")


import time
import subprocess
from pathlib import Path
import pyautogui as pag

p1 = Path.cwd() / 'attachments'

# 3초 뒤 timeLeft 종료
timeLeft = 3
while timeLeft > 0:
    print(timeLeft, end=' ')
    time.sleep(1)
    timeLeft -= 1

try:
    # subprocess.Popen() 함수 통해 알람파일 실행
    subprocess.Popen(['start', p1 / 'alarm.wav'], shell=True)
    # 3초 뒤
    time.sleep(3)
    # pyautogui.getWindwsWithTitle() 통해서 alarm창 객체 생성하고
    alarm = pag.getWindowsWithTitle('groove')[0]
    # 해당 창 종료
    alarm.close()
except:
    print('There is no file.')

print('Process Done!')


# ref. https://keras.io/api/applications/#usage-examples-for-image-classification-models

import tensorflow as tf
from keras.applications.mobilenet_v2 import MobileNetV2
import keras.utils as image
from keras.applications.mobilenet_v2 import preprocess_input, decode_predictions
import numpy as np

physical_devices = tf.config.experimental.list_physical_devices('GPU')
print("Num GPUs Available: ", len(physical_devices))
tf.config.experimental.set_memory_growth(physical_devices[0], True)

model = tf.keras.applications.MobileNetV2(
    input_shape=None,
    alpha=1.0,
    include_top=True,
    weights="imagenet",
    input_tensor=None,
    pooling=None,
    classes=1000,
    classifier_activation="softmax",
)

# img_path = 'example-bluePlayer.PNG'
img_path = 'example-livingRoom.jpg'
img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)

preds = model.predict(x)
# decode the results into a list of tuples (class, description, probability)
# (one such list for each sample in the batch)
print('Predicted:', decode_predictions(preds, top=3)[0])
# Predicted: [(u'n02504013', u'Indian_elephant', 0.82658225), (u'n01871265', u'tusker', 0.1122357), (u'n02504458', u'African_elephant', 0.061040461)]


import ray
import ray.rllib.agents.ppo as ppo
import json, os, shutil, sys
import gym
import pprint
import time
import shelve
from tensorflow import keras
from ray import tune
import csv

#@ray.remote(num_cpus=0)
def full_train(checkpoint_root, agent, n_iter, save_file, n_ini = 0, header = True, restore = False, restore_dir = None):
    s = "{:3d} reward {:6.2f}/{:6.2f}/{:6.2f} len {:6.2f} learn_time_ms {:6.2f} total_train_time_s {:6.2f} saved {}"
    if(restore):
        if restore_dir == None:
            print("Error: you must specify a restore path")
            return
        agent.restore(restore_dir)
    #else:
        #shutil.rmtree(checkpoint_root, ignore_errors=True, onerror=None)
    results = []
    episode_data = []
    episode_json = []

    total_learn_time = 0
    for n in range(n_iter):
        t0 = time.time()
        result = agent.train()
        t1 = time.time()-t0
        results.append(result)
        episode = {'n': n_ini + n + 1,
                   'episode_reward_min': result['episode_reward_min'],
                   'episode_reward_mean': result['episode_reward_mean'],
                   'episode_reward_max': result['episode_reward_max'],
                   'episode_len_mean': result['episode_len_mean'],
                   'learn_time_ms': result['timers']['learn_time_ms'],
                   'total_train_time_s': t1
                   }
        episode_data.append(episode)
        episode_json.append(json.dumps(episode))
        file_name = agent.save(checkpoint_root)
        print(s.format(
        n_ini + n + 1,
        result["episode_reward_min"],
        result["episode_reward_mean"],
        result["episode_reward_max"],
        result["episode_len_mean"],
        result["timers"]["learn_time_ms"],
        t1,
        file_name
       ))
        total_learn_time+= result["timers"]["learn_time_ms"]

    print("Total learn time: " + str(total_learn_time))
    print("Average learn time per iteration: " + str(total_learn_time/n_iter))

    with open(save_file + '.json', mode='a') as outfile:
        json.dump(episode_json, outfile)

    with open(save_file + '.csv', mode='a') as csv_file:
        fieldnames = ['n', 'episode_reward_min', 'episode_reward_mean', 'episode_reward_max', 'episode_len_mean', 'learn_time_ms','total_train_time_s']
        writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
        if header:
            writer.writeheader()
        for row in episode_data:
            writer.writerow(row)

    return results


import numpy as np
from matrix import Matrix

def ldl_decom(matrix: Matrix) -> list:
    n = matrix.n
    S = Matrix(n, n)
    D = Matrix(n, n)

    for i in range(n):
        # calculating element D[i][i] and S[i][i]
        cum_sum = 0
        for k in range(i):
            cum_sum += S[k][i] * S[k][i] * D[k][k]
        flag = (matrix[i][i] - cum_sum) >= 0
        D[i][i] = 1 if flag else -1
        S[i][i] = abs(matrix[i][i] - cum_sum) ** (1 / 2)
        for j in range(i + 1, n):
            # calculating element of S matrix
            cum_sum = 0
            for k in range(i):
                cum_sum += S[k][i] * S[k][j] * D[k][k]
            S[i][j] = (matrix[i][j] - cum_sum) / (S[i][i] * D[i][i])

    # finding the solution

    S_tranposed = Matrix.transpose(S)

    y = [0 for i in range(n)]
    y[0] = matrix[0][n] / S_tranposed[0][0]

    for i in range(1, n):
        cum_sum = 0
        for k in range(i):
            cum_sum += Matrix.transpose(S)[i][k] * y[k]
        y[i] = (matrix[i][n] - cum_sum) / S_tranposed[i][i]

    y = [D[i][i] * y[i] for i in range(n)]

    solution = [0 for i in range(n)]
    solution[n - 1] = y[n - 1] / S[n - 1][n - 1]
    for i in range(n - 1):
        k = n - i - 2
        cum_sum = 0
        for j in range(k + 1, n):
            cum_sum = cum_sum + solution[j] * S[k][j]
        solution[k] = (y[k] - cum_sum) / S[k][k]

    return solution

matrix = [
    [-1, 3, 2, 2],
    [3, -3, 3, 9],
    [2, 3, -3, 6]
]

matrix = Matrix(matrix=matrix)
print('Solution')
print(ldl_decom(matrix))


import os
import pickle
from datetime import datetime

from music_focus.processors.processor_base import ProcessorBase

class LoadResultProcessor(ProcessorBase):

    def __init__(self, data_dir='./data'):
        self._data_dir = data_dir

    def run(self, workflow_input, tmp_result, workflow_output):
        rtype = workflow_input['result_type']
        if rtype not in workflow_input:
            # 没加载过, 加载
            result_file_name = self._find_newest_result_file(self._data_dir, rtype,
                                                             '{}_%Y-%m-%d_%H:%M:%S.pkl'.format(rtype))
            workflow_input[rtype] = self._load_result(self._data_dir, result_file_name)
        else:
            # 加载过, 根据是否版本最新进行重载
            result_file_name = self._find_newest_result_file(self._data_dir, rtype,
                                                             '{}_%Y-%m-%d_%H:%M:%S.pkl'.format(rtype))
            if result_file_name != workflow_input[rtype]['file_name']:
                workflow_input[rtype] = self._load_result(self._data_dir, result_file_name)

    @staticmethod
    def _find_newest_result_file(dir_name, rtype, file_formatter):
        result_files = [f for f in os.listdir(dir_name) if rtype in f and 'pkl' in f]
        assert result_files is not [], "cant not find result file of {}".format(rtype)
        return max(result_files, key=lambda f: datetime.strptime(f, file_formatter))

    @staticmethod
    def _load_result(data_dir, result_file_name):
        with open('{}/{}'.format(data_dir, result_file_name), 'rb') as f:
            result = pickle.load(f)
        result['file_name'] = result_file_name
        return result


from PIL import Image
import numpy
import os
import scipy.io as sio

def process_image(imagename, resultname, histeq=False,
                  params='--edge-thresh 10 --peak-thresh 5'):
  if not imagename.endswith('pgm') or histeq:
    im = Image.open(imagename).convert('L')
    if histeq:
      import imtools
      im = Image.fromarray(numpy.uint8(imtools.histeq(numpy.array(im))[0]))
    im.save('out_tmp.pgm')
    imagename = 'out_tmp.pgm'

  # Assumes that vlfeat's sift binary is in PATH.
  cmd = ' '.join(['sift', imagename, '--output=' + resultname, params])
  os.system(cmd)

  # Re-write as .mat file, which loads faster.
  f = numpy.loadtxt(resultname)
  sio.savemat(resultname + '.mat', {'f':f}, oned_as='row')

def read_features_from_file(filename):
  '''Returns feature locations, descriptors.'''
  f = sio.loadmat(filename + '.mat')['f']
  return f[:, :4], f[:, 4:]

def read_or_compute(imname, siftname, histeq=False):
  '''Returns features from 'siftname' if it exists. Else, computes features from
  'imname', writes them to 'siftname', and returns them.'''
  if not os.path.exists(siftname):
    process_image(imname, siftname, histeq=histeq)
  return read_features_from_file(siftname)

def plot_features(im, locs, circle=False):
  import pylab
  def draw_circle(c, r):
    t = numpy.arange(0, 1.01, .01) * 2 * numpy.pi
    x = r * numpy.cos(t) + c[0]
    y = r * numpy.sin(t) + c[1]
    pylab.plot(x, y, 'b', linewidth=2)
  pylab.imshow(im)
  if circle:
    for p in locs:
      draw_circle(p[:2], p[2])
  else:
    pylab.plot(locs[:, 0], locs[:, 1], 'ob')
  pylab.axis('off')

def match(desc1, desc2):
  desc1 = numpy.array([d / numpy.linalg.norm(d) for d in desc1])
  desc2 = numpy.array([d / numpy.linalg.norm(d) for d in desc2])

  dist_ratio = 0.6
  desc1_size = desc1.shape

  matchscores = numpy.zeros((desc1_size[0], 1), 'int')
  desc2t = desc2.T
  for i in range(desc1_size[0]):
    dotprods = numpy.dot(desc1[i, :], desc2t)
    dotprods = 0.9999 * dotprods

    # arccos is monotonous, can sort on just its sign.
    #indx = numpy.argsort(numpy.arccos(dotprods))
    indx = numpy.argsort(-dotprods)

    # Only keep best match if it's noticeably better than the next best match.
    if (numpy.arccos(dotprods)[indx[0]] <
        dist_ratio * numpy.arccos(dotprods)[indx[1]]):
      matchscores[i] = int(indx[0])

  return matchscores

def match_twosided(desc1, desc2):
  matches_12 = match(desc1, desc2)
  #return matches_12  # XXX doesn't seem to make things worse?
  matches_21 = match(desc2, desc1)

  ndx_12 = matches_12.nonzero()[0]
  for n in ndx_12:
    if matches_21[int(matches_12[n])] != n:
      matches_12[n] = 0
  return matches_12

def appendimages(im1, im2):
  return numpy.concatenate((im1, im2), axis=1)

def plot_matches(im1, im2, locs1, locs2, matchscores, show_below=True):
  import pylab
  im3 = appendimages(im1, im2)
  if show_below:
    im3 = numpy.vstack((im3, im3))

  pylab.imshow(im3)
  cols1 = im1.shape[1]
  for i, m in enumerate(matchscores):
    if m > 0:
      pylab.plot([locs1[i, 0], locs2[m, 0] + cols1],
                 [locs1[i, 1], locs2[m, 1]], 'c')
  pylab.axis('off')


#   Функция open
# открывает файл в указанном режиме
# f = open(‘my.txt’, ‘w’)
# file — имя файла
# mode — режим
# encoding — кодировка
#   Режимы открытия mode
# r — чтение
# w — запись, если файла нет, создается новый
# x — запись, если файла нет, ошибка
# a — дозапись
# b — двоичный режим
# + — открытие на чтение и запись

f = open('first.txt', 'w')

# f = open ('second.txt', 'r')  # error - file doesn't exist

f = open ('first.txt', 'r')

# Запись текста в файл
# write — записать строку в файл
# writelines — записать список строк в файл
# \n — символ конца строки

f = open('first.txt', 'w')
f.write('Hello\n')
f.write('World\n')

f.writelines(['Hello\n', 'Python\n'])

#     Чтение из файла
# read — чтение всего файла
# for line in f: — чтение файла построчно
# readlines — чтение файла в список строк

f = open('first.txt', 'r')

# print(f.read())

for line in f:
    print(line.replace('\n', ''))

# print(f.readlines())

f.close()
# ____________________________________________________

with open('first.txt', 'r') as f:
    for line in f:
        print(line.replace('\n', ''))

print('end')


import os
import tempfile
import tensorflow_datasets as tfds
import tensorflow as tf
from keras.callbacks import ReduceLROnPlateau, EarlyStopping, ModelCheckpoint
from keras.engine.saving import load_model
from tensorflow_core.python import InteractiveSession, ConfigProto

# solved some issues with GPU
config = ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.3
session = InteractiveSession(config=config)

dataset, info = tfds.load('imdb_reviews/subwords8k', with_info=True,
                          as_supervised=True)

train_ds, test_ds = dataset['train'], dataset['test']

encoder = info.features['text'].encoder

BUFFER_SIZE = 10000
BATCH_SIZE = 8

padded_shapes = ([None], ())

# Shuffeling our dataset and giving it padded batching - This transformation combines multiple
# consecutive elements of the input dataset into a single element. as combines words into a sentence.
train_ds = train_ds.shuffle(BUFFER_SIZE).padded_batch(BATCH_SIZE,
                                                      padded_shapes=padded_shapes)
test_ds = test_ds.shuffle(BUFFER_SIZE).padded_batch(BATCH_SIZE,
                                                    padded_shapes=padded_shapes)

# Callbacks
# a path for the model.
model_dir = tempfile.gettempdir()
model_ver = 1.0
export_path = os.path.join(model_dir, str(model_ver))

# will create a file checkpoint for our model, it will overwrite it every run until we will find the best model
checkpoint = ModelCheckpoint('lstm.h5',
                             monitor='val_loss',  # monitor our progress by loss value.
                             mode='min',  # smaller loss is better, we try to minimize it.
                             save_best_only=True,
                             verbose=1)

# if our model accuracy (loss) is not improving over 3 epochs, stop the training, something is fishy
earlystop = EarlyStopping(monitor='val_loss',
                          min_delta=0,
                          patience=3,
                          verbose=1,
                          restore_best_weights=True
                          )

# if our loss is not improving, try to reduce learning rate
reduce_lr = ReduceLROnPlateau(monitor='val_loss',
                              factor=0.2,
                              patience=3,
                              verbose=1,
                              min_delta=0.0001)

callbacks = [checkpoint, earlystop, reduce_lr]

# Our Keras Sequential() model.
_model = tf.keras.Sequential([tf.keras.layers.Embedding(encoder.vocab_size, 64),
                              tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64, return_sequences=True)),
                              tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32)),
                              tf.keras.layers.Dense(64, activation='elu'),
                              tf.keras.layers.Dense(1, activation='sigmoid')])
_model.summary()
_model.save('lstm.h5')
_model.compile(loss='binary_crossentropy',
               optimizer=tf.keras.optimizers.Adam(0.001),
               metrics=['accuracy'])
history = _model.fit(train_ds, epochs=10, validation_data=test_ds, validation_steps=30,
                     callbacks=callbacks)


import openai

import gradio

openai.api_key = " your api key here please"

messages = [{"role": "system", "content": "You are a financial experts that specializes in real estate investment and negotiation"}]

def CustomChatGPT(user_input):
    messages.append({"role": "user", "content": user_input})
    response = openai.ChatCompletion.create(
        model = "gpt-3.5-turbo",
        messages = messages
    )
    ChatGPT_reply = response["choices"][0]["message"]["content"]
    messages.append({"role": "assistant", "content": ChatGPT_reply})
    return ChatGPT_reply

demo = gradio.Interface(fn=CustomChatGPT, inputs = "text", outputs = "text", title = "my chatbot using chatGPT api")

demo.launch(share=True)


from .forms import AuthorForm
from .models import Author

class AllFormObjects:
    model = Author
    form_class = AuthorForm
    template_name = 'author_form.html'
    success_url = '/'

    def form_valid(self, form):
        form.save()
        return super().form_valid(form)

class SeeObjects:
    paginate_by = 70
    model = None
    template_name = None


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# HELICS documentation build configuration file, created by
# sphinx-quickstart on Wed Dec 13 12:07:08 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))

# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
import os
import sphinx_rtd_theme
import shutil
import subprocess
import requests
import tempfile
import zipfile

current_directory = os.path.dirname(os.path.realpath(__file__))

def download_helics_images():
    print("Downloading doc images from GMLC-TDC/helics_doc_resources")
    with tempfile.TemporaryDirectory() as tmpdirname:
        url = "https://github.com/GMLC-TDC/helics_doc_resources/archive/refs/heads/main.zip"
        target_path = os.path.join(tmpdirname, "helics_docs_resources.zip")
        response = requests.get(url, stream=True)
        if response.status_code == 200:
            with open(target_path, "wb") as f:
                f.write(response.raw.read())
        with zipfile.ZipFile(target_path, "r") as zip_ref:
            zip_ref.extractall(tmpdirname)
        if os.path.exists("img"):
            shutil.rmtree("img")
        shutil.move(os.path.join(tmpdirname, "helics_doc_resources-main/user_guide"), "img")
    print("Doc images downloaded")

def which(program):
    def is_exe(fpath):
        return os.path.exists(fpath) and os.access(fpath, os.X_OK) and os.path.isfile(fpath)

    def ext_candidates(fpath):
        yield fpath
        for ext in os.environ.get("PATHEXT", "").split(os.pathsep):
            yield fpath + ext

    # fpath, fname = os.path.split(program)
    fpath = os.path.dirname(program)
    if fpath:
        if is_exe(program):
            return program
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            exe_file = os.path.join(path, program)
            for candidate in ext_candidates(exe_file):
                if is_exe(candidate):
                    return candidate

    return None

read_the_docs_build = os.environ.get("READTHEDOCS", None) == "True"

# For RTD builds, only download the images once; for developers, always get the images
if not read_the_docs_build or not os.path.exists("img"):
    download_helics_images()

# For RTD builds run doxygen once for all output formats
if read_the_docs_build:
    dir_name = os.path.realpath(os.path.dirname(__file__))
    checkout_dir = os.path.realpath(os.path.join(dir_name, os.pardir))
    doxygen_build_dir = os.path.realpath(os.path.join(checkout_dir, "build-doxygen"))
    if not os.path.isdir(doxygen_build_dir):
        os.makedirs(os.path.join(doxygen_build_dir, "docs", "html"))
        subprocess.call(
            "cd {dir_name} && python ./scripts/render-doxyfile.py && doxygen Doxyfile;".format(
                dir_name=checkout_dir
            ),
            shell=True,
        )
    html_extra_path = [os.path.abspath(os.path.join(doxygen_build_dir, "docs", "html"))]

extensions = [
    "myst_parser",
    "sphinx.ext.autodoc",
    "sphinx.ext.doctest",
    "sphinx.ext.intersphinx",
    "sphinx.ext.coverage",
    "sphinx.ext.mathjax",
    "sphinx.ext.viewcode",
    "sphinx.ext.githubpages",
    "sphinx.ext.napoleon",
    "sphinxcontrib.rsvgconverter",
    "IPython.sphinxext.ipython_console_highlighting",
    "breathe",
    "sphinxcontrib.redoc",
    "sphinxcontrib.mermaid",
]

myst_enable_extensions = [
    "amsmath",
    "dollarmath",
]
myst_dmath_double_inline = True

breathe_projects = {
    "helics": os.path.abspath(os.path.join(current_directory, "./../build-doxygen/docs/xml")),
}

breathe_default_project = "helics"

# Add any paths that contain templates here, relative to this directory.
templates_path = []

# The master toctree document.
master_doc = "index"

# General information about the project.
project = "HELICS"
copyright = "2017-2021 Battelle Memorial Institute; Lawrence Livermore National Security, LLC; Alliance for Sustainable Energy, LLC. See the top-level NOTICE for additional details. All rights reserved. SPDX-License-Identifier: BSD-3-Clause. Documentation source in https://github.com/GMLC-TDC/HELICS"
author = "Philip Top, Trevor Hardy, Ryan Mast, Dheepak Krishnamurthy, Andrew Fisher, Bryan Palmintier, Jason Fuller"

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = ""
# The full version, including alpha/beta/rc tags.
release = ""

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = "sphinx"

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False

# redoc config
redoc = [
    {
        "name": "HELICS REST API",
        "page": "references/api-reference/rest_queries_api",
        "spec-root": "swagger/",
        "spec": "reference/queries.yaml",
        "embed": False,
    }
]

# mermaid config
# default js file priority is 500; require.js used by nbsphinx causes issues
# when it gets loaded first
mermaid_js_priority = 499

# -- Options for HTML output ----------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
#
html_theme = "sphinx_rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
#
html_theme_options = {"navigation_depth": 4, "collapse_navigation": False}

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ["_static"]

html_logo = "./logos/helics-logo-stacked-onWhite.png"
html_favicon = html_logo

# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
# This is required for the alabaster theme
# refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars
html_sidebars = {
    "**": [
        "about.html",
        "navigation.html",
        "relations.html",  # needs 'show_related': True theme option to display
        "searchbox.html",
        "donate.html",
    ]
}

# Adding last updated timestamp at the bottom of every page
html_last_updated_fmt = ""  # Empty string = '%b %d, %Y'

# -- Options for HTMLHelp output ------------------------------------------

# Output file base name for HTML help builder.
htmlhelp_basename = "HELICSdoc"

# -- Options for LaTeX output ---------------------------------------------

latex_elements = {
    # The paper size ('letterpaper' or 'a4paper').
    #
    # 'papersize': 'letterpaper',
    # The font size ('10pt', '11pt' or '12pt').
    #
    # 'pointsize': '10pt',
    # Additional stuff for the LaTeX preamble.
    #
    # 'preamble': '',
    # Latex figure (float) alignment
    #
    # 'figure_align': 'htbp',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [
    (
        master_doc,
        "HELICS.tex",
        "HELICS Documentation",
        "Philip Top, Trevor Hardy, Ryan Mast, Dheepak Krishnamurthy, Andrew Fisher, Bryan Palmintier, Jason Fuller",
        "manual",
    ),
]

# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [(master_doc, "helics", "HELICS Documentation", [author], 1)]

# -- Options for Texinfo output -------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
    (
        master_doc,
        "HELICS",
        "HELICS Documentation",
        author,
        "HELICS",
        "Hierarchical Engine for Large-scale Infrastructure Co-Simulation",
        "Miscellaneous",
    ),
]

def setup(app):
    app.add_css_file("css/custom.css")  # may also be an URL


#!/usr/bin/env python3

import subprocess
from datetime import datetime
import sys, os, re, pytz
import requests
import lxml.html
import argparse

terms = { '10': 'Fall', '20': 'Winter', '30': 'Spring', '40': 'Summer' }
snapshots_dir = 'all-snapshots'

def add_to_index(path):
    if os.path.exists(f'{snapshots_dir}/index.html'):
        index_file = f'{snapshots_dir}/index.html'
    else:
        index_file = 'snapshots_index.html'
    index = lxml.html.parse(index_file)
    ul = index.xpath('//ul')[0]
    snapshots_index = lxml.html.parse(os.path.join(path, 'index.html'))
    text = snapshots_index.xpath('//head/title/text()')[0].replace(': Snapshot taken', '')
    href = path[len(snapshots_dir)+1:]
    li = lxml.html.fromstring(f'
{text}
')
    ul.append(li)
    index.write(f'{snapshots_dir}/index.html', encoding='UTF-8', method='html')

def push_to_git():
    subprocess.run('git add .', cwd=snapshots_dir, shell=True)
    subprocess.run('git commit -m "added new snapshot at $(TZ=Hongkong date +%m-%d\\ %H:%M)"',
                   stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, cwd=snapshots_dir, shell=True)
    subprocess.run('git push', stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, cwd=snapshots_dir, shell=True)

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--url', default='https://w5.ab.ust.hk/wcq/cgi-bin/',
                        help='The start_url for crawler')
    parser.add_argument('-p', '--git-push', action='store_true',
                        help=f'Whether or not push all snapshots to a git repo. Note that the git repo should be set up at the directory {snapshots_dir}')
    args = parser.parse_args()
    start_url = args.url
    do_git_push = args.git_push

    r = requests.get(start_url)
    term_code = re.search(r'\d{4}', r.url).group()
    now = datetime.now(tz=pytz.timezone('Hongkong'))
    minute = '00' if now.minute < 30 else '30'
    path = '{}/20{}/{}/{}/{}'.format(snapshots_dir, term_code[:2], terms[term_code[2:]], now.strftime('%m/%d/%H'), minute)
    if os.path.exists(path):
        print('Pages already crawled')
        return
    res = subprocess.run('scrapy crawl snapshot -a start_url=%s' % start_url, shell=True)
    if res.returncode == 0:
        os.makedirs(path)
        subprocess.run(f'mv current-snapshot/* {path}', shell=True)
        add_to_index(path)
        if do_git_push:
            push_to_git()

if __name__ == '__main__':
    main()


def solution(arr):
    res = list(filter(lambda x : arr[x] == 2, range(len(arr))))
    if res:
        return arr[res[0]:res[-1] + 1]
    else:
        return [-1]

arr = [1, 2, 1, 2, 1, 10, 2, 1]
print(solution(arr))


import cv2
import pafy

class source_http():
    def __init__(self, url):
        self.url = url
    def record(self):
        channel = pafy.new(self.url)
        streamPort = channel.getbest(preftype = 'mp4')
        videoSource = cv2.VideoCapture(streamPort.url)
        while True:
            ret, frame = videoSource.read()
            cv2.imshow('http', frame)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
        videoSource.release()
        cv2.destroyAllWindows()


'''
ABC065 A - Expired?
https://atcoder.jp/contests/abc065/tasks/abc065_a

賞味期限をX日まで過ぎた食品を食べてもお腹を壊しません。
賞味期限をX+1日以上過ぎた食品を食べると、お腹を壊します。

賞味期限を過ぎずに食べると、おいしく感じます
そうでない場合、おいしく感じません。

高橋君は、賞味期限の A 日前に食品を買ってきて、
買ってから B 日後に食べました。

buy           eat
 |------------|-------|-------|---
 A<-----X
 |----------->B------>B------->B
        |----------|-------|-----|
        X   deli    safe     den

'''

x,a,b = map(int, input().split())

if x >= a+b:
    ans = 'delicious'
elif x <= b:
    ans = 'safe'
else:
    ans = 'dangerous'
print(ans)


import pytest
import sys, time
from colorama import init, Fore, Style
init()

from lib.logger import Logger, Level
from lib.i2c_scanner import I2CScanner
from lib.enums import Orientation
from lib.matrix import Matrix

# ..............................................................................
@pytest.mark.unit
def test_matrix():

    _port_light = None
    _stbd_light = None

    _log = Logger('matrix-test', Level.INFO)

    try:

        _log.info(Fore.CYAN + 'start matrix test...')

        _i2c_scanner = I2CScanner(Level.DEBUG)
        if _i2c_scanner.has_address([0x77]): # port
            _port_light = Matrix(Orientation.PORT, Level.INFO)
            _log.info('port-side matrix available.')
        else:
            _log.warning('no port-side matrix available.')
        if _i2c_scanner.has_address([0x75]): # starboard
            _stbd_light = Matrix(Orientation.STBD, Level.INFO)
            _log.info('starboard-side matrix available.')
        else:
            _log.warning('no starboard-side matrix available.')

        if not _port_light and not _stbd_light:
            _log.warning('skipping test: no matrix displays available.')
            return

        if _port_light:
            _port_light.text('Y', False, False)
        if _stbd_light:
            _stbd_light.text('N', False, False)
        time.sleep(2)

        if _port_light:
            _port_light.disable()
            _port_light.clear()
        if _stbd_light:
            _stbd_light.disable()
            _stbd_light.clear()
        time.sleep(1)

        _log.info('matrix on...')
        if _port_light:
            _port_light.light()
        if _stbd_light:
            _stbd_light.light()
        time.sleep(2)

        if _port_light:
            _port_light.clear()
        if _stbd_light:
            _stbd_light.clear()
        time.sleep(1)

        _log.info('matrix gradient...')
        for x in range(3):
            for i in range(1,8):
                _log.info('matrix at {:d}'.format(i))
                if _port_light:
                    _port_light.gradient(i)
                if _stbd_light:
                    _stbd_light.gradient(i)
                time.sleep(0.01)
            if _port_light:
                _port_light.clear()
            if _stbd_light:
                _stbd_light.clear()
            time.sleep(0.1)

    except KeyboardInterrupt:
        _log.info(Fore.MAGENTA + 'Ctrl-C caught: interrupted.')
    finally:
        _log.info('closing matrix test...')
        if _port_light:
            _port_light.clear()
        if _stbd_light:
            _stbd_light.clear()

# call main ......................................

def main():

    test_matrix()

if __name__== "__main__":
    main()


from tweeter import tweet
import nltk
from collections import Counter
import json

stopwords_pt=nltk.corpus.stopwords.words('portuguese')
stopwords_en=nltk.corpus.stopwords.words('english')
pontos = ['?', '!', '.', ',', '&',' ']

def wordsTT():
    lista = tweet()
    new_list = []
    new_text = ''
    espaco = ' '

    #me retorna somente as palavras usadas em cada trend
    for text in lista:
        tokens = nltk.word_tokenize(text)
        for p in tokens:
            if p not in stopwords_pt or p not in stopwords_en:
                new_text = new_text + espaco + p

        new_list.append(new_text)
        new_text = ''

    return new_list

def top3_words():
    final_list = []
    #me retorna a quantidade de cada palavra achada
    for words in wordsTT():
        aux = nltk.word_tokenize(words)
        lista_teste = []
        for t in aux:
            if t not in pontos and len(t) > 3:
                lista_teste.append(t)

        counts = Counter(lista_teste)
        final_list.append(counts)

    #me retorna as 3 palavras mais utilizadas nos tt de cada trend
    top3 = []
    aux_list = []
    for iten in final_list:
        for keys, count in iten.most_common():
            aux_list.append(keys)
        top3.append(aux_list[0:3])
        aux_list = []

    return top3


import motorController
from laneDetectionModule import getLaneCurve
import webCamModule
import time
import cv2

def main():
    img = webCamModule.getImg()
    curveVal = getLaneCurve(img, 1)
    #motorController.foward()

    # Parte izquierda - Control de la variable curveVal
    if curveVal > 0:
        motorController.right()
        if curveVal < 0.05:
            motorController.left()

       	    curveVal = 0
    # Fin de la parte izquierda

    # Parte derecha - Control de la variable curveVal
    else:
        if curveVal > -0.08:

            motorController.foward()

            curveVal = 0
    # Fin de la parte derecha

    # Parte común - Visualización de la imagen
    #cv2.imshow('debug', img)
    #cv2.waitKey(1)
    # Fin de la parte común

if __name__ == '__main__':
    while True:
        main()


bl_info = {
	"name": "Datablock Tools",
	"author": "Mackenzie Crawford, Vitor Balbio",
	"version": (2, 2, 1),
	"blender": (2, 80, 0),
	"location": "View3D > Object > Datablock Tools",
	"description": "Some tools to handle datablocks",
	"warning": "",
	"tracker_url": "",
	"category": "3D View"}

import bpy
import re

class CleanImagesOP(bpy.types.Operator):
	#replace the ".0x" images with the original and mark this to remove in next load
	bl_idname = "object.clean_images"
	bl_label = "Clean Images Datablocks"

	@classmethod
	def poll(cls, context):
		return context.selected_objects is not None

	def execute(self, context):
		ImageList = []
		#get full image name including extension
		for i in bpy.data.images:
			ImageList.append([i.name,i])

		for obj in bpy.context.selected_objects:
			for uv in obj.data.uv_textures.items():
				for faceTex in uv[1].data:
					if (not (faceTex.image is None)):
						image = faceTex.image

						if (bool(re.search(r'\.(\d){3}', image.name))): #if an image is set, and its name contains a . followed by 3 digits
							replaced = False
							for ima_name, ima in ImageList:
								if (image.name.startswith(ima_name) and (".0" not in ima_name)):
									faceTex.image.user_clear()
									faceTex.image = ima
									replaced = True
							if (replaced == False):
								#we didn't find a match, rename this one
								image.name = image.name.rsplit(".", 1)[0] #splits on the last . in the image name and returns the left part. Allows handling of names with multiple .s
		return {'FINISHED'}

class CleanMaterialsOP(bpy.types.Operator):
	#replace the ".0x" materials with the original and mark this to remove in next load
	bl_idname = "object.clean_materials"
	bl_label = "Clean Materials Datablocks"

	@classmethod
	def poll(cls, context):
		return context.selected_objects is not None

	def execute(self, context):
		matlist = bpy.data.materials
		for obj in bpy.context.selected_objects:
			for mat_slt in obj.material_slots:
				if (mat_slt.material != None and bool(re.search(r'\.(\d){3}', mat_slt.material.name))): #if a material is set, and its name contains a . followed by 3 digits
					replaced = False
					for mat in matlist:
						if ((mat.name == mat_slt.material.name.rsplit(".", 1)[0]) and (not bool(re.search(r'\.(\d){3}', mat.name)))):
							mat_slt.material = mat
							replaced = True
					if replaced == False:
						#we didn't find a match, rename this one
						mat_slt.material.name = mat_slt.material.name.rsplit(".", 1)[0] #splits on the last . in the material name and returns the left part. Allows handling of names with multiple .s
		return {'FINISHED'}

class RemoveAllMaterialsOP(bpy.types.Operator):
	#removes all materials from selected objects
	bl_idname = "object.remove_materials"
	bl_label = "Remove All Materials Datablocks"

	@classmethod
	def poll(cls, context):
		return context.selected_objects is not None

	def execute(self, context):
		for obj in bpy.context.selected_objects:
			#iterate through materials list and remove each sequentially
			obj.active_material_index = 0
			for i in range(len(obj.material_slots)):
				bpy.ops.object.material_slot_remove({'object': obj})
		return {'FINISHED'}

class DatablockToolsMenu(bpy.types.Menu):
	bl_label = "Datablock Tools"
	bl_idname = "VIEW_MT_datablock_tools"

	def draw(self, context):
		layout = self.layout

		layout.operator("object.clean_materials")
		layout.operator("object.remove_materials")
		layout.operator("object.clean_images")
		layout.operator("object.set_instance")

def draw_item(self, context):
	layout = self.layout
	layout.menu(DatablockToolsMenu.bl_idname)

classes = (CleanMaterialsOP, RemoveAllMaterialsOP, CleanImagesOP, DatablockToolsMenu)

def register():
	from bpy.utils import register_class
	for cls in classes:
		register_class(cls)

	bpy.types.VIEW3D_MT_object.append(draw_item)

def unregister():
	from bpy.utils import unregister_class
	for cls in reverse(classes):
		unregister_class(cls)

	bpy.types.VIEW3D_MT_object.remove(draw_item)

if __name__ == "__main__":
	register()


import colorsys
import turtle

caneta = turtle.Turtle() #Faz a instancia da classe turtle
caneta.hideturtle()  #Esconde p cursor
caneta.shape("turtle")
caneta.speed("fastest")
cont =0
num = 150
num2 = 3
while (cont < 150) :
    print("Cont ", cont)
    print("num ", num)
    print("num2 ", num2)
    caneta.circle(num) #desenha um circulo de 50px
    caneta.up() #Levanta a caneta do turtle, pra nao deixar o rastro do cursor
    caneta.setposition(0, num2) #posiciona o circulo dentro do outro circulo
    caneta.down() #desce a caneta do turtle, para voltar a desenhar
    cont += 1
    num -= 3
    num2 += 3
turtle.done()     #O cursor turtle para.


import json
import math
import datetime
from pysubparser import parser
import click
import sys
import unicodedata
import re

def slugify(value, allow_unicode=False):
    """
    Taken from https://github.com/django/django/blob/master/django/utils/text.py
    Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated
    dashes to single dashes. Remove characters that aren't alphanumerics,
    underscores, or hyphens. Convert to lowercase. Also strip leading and
    trailing whitespace, dashes, and underscores.
    """
    value = str(value)
    if allow_unicode:
        value = unicodedata.normalize("NFKC", value)
    else:
        value = (
            unicodedata.normalize("NFKD", value)
            .encode("ascii", "ignore")
            .decode("ascii")
        )
    value = re.sub(r"[^\w\s-]", "", value.lower())
    return re.sub(r"[-\s]+", "-", value).strip("-_")

def get_microseconds(t):
    return (
        (t.hour * 3600 * 1000_000)
        + (t.minute * 60 * 1000_000)
        + (t.second * 1000_000)
        + t.microsecond
    )

@click.command()
@click.option("--sub-file", type=click.File("r"), required=True)
@click.option("--output-manifest-file", type=click.File("w"), required=True)
def cli(sub_file, output_manifest_file):
    subtitles = parser.parse(sub_file.name)

    output_json = []
    for subtitle in subtitles:
        start_time = get_microseconds(subtitle.start)
        end_time = get_microseconds(subtitle.end)
        length = end_time - start_time

        length_in_seconds = math.ceil(length / 1000_000)
        start_time_in_seconds = math.floor(start_time / 1000_000)

        clip_filename = f"{slugify(subtitle.text)}-{start_time_in_seconds}.mp4"
        output_json.append(
            {
                "start_time": start_time_in_seconds,
                "length": length_in_seconds,
                "rename_to": clip_filename,
                "title": subtitle.text,
            }
        )

    json.dump(output_json, output_manifest_file, indent=4, sort_keys=True)

if __name__ == "__main__":
    cli()


from os import environ

from ethecycle.util.string_constants import DEBUG

IS_TEST_ENV = environ['ETHECYCLE_ENV'] == 'test'

class Config:
    include_extended_properties = False
    debug = DEBUG in environ
    drop_database = False
    extract_only = False
    skip_load_from_db = False
    is_docker_image_build = 'IS_DOCKER_IMAGE_BUILD' in environ
    is_test_env = IS_TEST_ENV
    preserve_csvs = False
    suppress_chain_address_db_collision_warnings = False
    skip_decimal_division = True

    # Hacky way to limit output
    max_rows = 1000 if IS_TEST_ENV else 10000000000


import random

from plants_game.classes import Position, Imageposition

# параметры противника (у нас зомбаки)
class Zombie:
	def __init__(self, img_id):
		zombie_view = random.choice(ZOMBIES_PARAMS)
		self.pos = Position(0, 0)
		self.size_y = zombie_view["size_y"]
		self.size_x = zombie_view["size_x"]
		self.speed = -0.2
		self.img_plant = img_id
		self.get_image = Imageposition(zombie_view["x"], zombie_view["y"])
		self.color_tr = 2
		self.health = Health()
		self.current_health = zombie_view["health"]
		self.points = self.current_health
		self.archer = zombie_view["archer"]
		self.health_index_pos_x = (zombie_view["size_x"] - zombie_view["health"]) / 2

	def update(self, x, y, health_x, health):
		self.pos.x = x
		self.pos.y = y
		self.current_health = health
		self.health.update(from_x=x+health_x, from_y=y-2, to_x=x+health+health_x, to_y=y-2)

class Health:
	def __init__(self):
		self.pos = Position(0, 0)
		self.to_pos = Position(0, 0)
		self.color = 8

	def update(self, from_x, from_y, to_x, to_y):
		self.pos.x = from_x
		self.pos.y = from_y
		self.to_pos.x = to_x
		self.to_pos.y = to_y

ZOMBIES_PARAMS = [
	{
		"x": 0,
		"y": 16,
		"size_y": 10,
		"size_x": 7,
		"health": random.choice([3,4,5]),
		"archer": False
	},
	{
		"x": 10,
		"y": 16,
		"size_y": 10,
		"size_x": 6,
		"health": 2,
		"archer": False
	},
	{
		"x": 0,
		"y": 32,
		"size_y": 10,
		"size_x": 6,
		"health": random.choice([1,2]),
		"archer": False
	},
	{
		"x": 8,
		"y": 32,
		"size_y": 10,
		"size_x": 8,
		"health": random.choice([1,2]),
		"archer": True
	}
]


from turtle import Turtle,Screen
from snake import Snake,Food,Scoreboard
import time
screen=Screen()

def main():
	score=Scoreboard()

	screen.setup(width=600,height=600)
	screen.bgcolor("black")

	snake_game_on=False
	screen.tracer(0)        #It is used to turn off animation when arg*=0
	snake=Snake()
	food=Food()
	screen.listen()
	screen.onkey(fun=snake.up,key="Up")
	screen.onkey(fun=snake.down,key="Down")
	screen.onkey(fun=snake.right,key="Right")
	screen.onkey(fun=snake.left,key="Left")
	screen.onkey(fun=None,key="space")
	snake_game_on=True
	while snake_game_on:    #The while loop is used to move forward
		def restart():
			screen.clear()
			main()
		time.sleep(0.055)
		screen.update()
		snake.move()

		#detect collision with food
		if snake.head.distance(food)<12:
			food.refresh()
			snake.extend()
			score.increase_score()
		#detect collision with wall
		if snake.head.xcor() > 295 or snake.head.xcor() < -295 or snake.head.ycor() > 295 or snake.head.ycor() < -295:
			snake_game_on=False
			score.game_over()
			#screen.clear()
			screen.onkey(fun=restart, key="space")

		#detect collision with self
		for segment in snake.snake_body[1:]:
			if snake.head.distance(segment)<5:
				snake_game_on=False
				print("hello world")
				score.game_over()
		#if head=snake_body[0] collides with any of the segment
		#trigger game over

main()

screen.exitonclick()


# %%
"""
DacDataStructureIngestor ingests mock data into Hazelcast data structures other than
Map and ReplicatedMap.
"""
import pandas as pd
import panel as pn
import param
from panel.viewable import Viewer
from threading import Thread

from padogrid.hazelcast.playground.DacBase import DacBase
from padogrid.hazelcast.playground.Progress import Progress
from padogrid.hazelcast.playground.hazelcast_util import HazelcastUtil

class DacDataStructureIngestor(DacBase, Viewer):

    default_operation = param.String('add')
    default_key = param.String('random')
    default_key_range = param.Integer(100_000)
    default_object = param.String('Customer')
    default_er = param.String('N/A')
    default_delta = param.Integer(1)
    default_count = param.Integer(1000)
    default_batch_size = param.Integer(100)
    default_delay_in_msec = param.Integer(1000)

    value = None

    def __init__(self, **params):
        super().__init__(**params)

        if "parent" in params:
            self._parent = params["parent"]
        else:
            self._parent = None

        if "ds_type" in params:
            self.ds_type = params["ds_type"]
        else:
            self.ds_type = 'Unspecified'

        if self.ds_type == 'FlakeIdGenerator':
            operation_list = ['new_id']
            self.default_operation = 'new_id'
        elif self.ds_type == 'List':
            operation_list = ['add']
            self.default_operation = 'add'
        elif self.ds_type == 'MultiMap':
            operation_list = ['put']
            self.default_operation = 'put'
        elif self.ds_type == 'PNCounter':
            operation_list = ['get_and_add', 'add_and_get', 'get_and_subtract', 'subtract_and_get']
            self.default_operation = 'get_and_add'
        elif self.ds_type == 'ReliableTopic':
            operation_list = ['publish']
            self.default_operation = 'publish'
        elif self.ds_type == 'Queue':
            operation_list = ['offer']
            self.default_operation = 'offer'
        elif self.ds_type == 'Ringbuffer':
            operation_list = ['add']
            self.default_operation = 'add'
        elif self.ds_type == 'Set':
            operation_list = ['add']
            self.default_operation = 'add'
        elif self.ds_type == 'Topic':
            operation_list = ['publish']
            self.default_operation = 'publish'
        else:
            operation_list = ['add']
        blotter_name = self.ds_type
        key_list = [ 'random', 'uuid' ]

        self._status_text = pn.widgets.input.TextInput(disabled=True)
        self._new_button = pn.widgets.Button(name='New', width=self.button_width, button_type='primary')
        self._new_button.on_click(self.__new_execute__)
        self._new_text = pn.widgets.TextInput(width=300)
        self._new_text.param.watch(self.__new_execute__, 'value')

        if self.ds_type == 'flake_id_generator':
            self._df = pd.DataFrame({
                'Name': [''],
                'Operation': [''],
                'Count': [-1],
                'Call Delay (msec)': [-1],
                'Ingest': [False]
            })
        elif self.ds_type == 'pn_counter':
            self._df = pd.DataFrame({
                'Name': [''],
                'Operation': [''],
                'Delta': [-1],
                'Count': [-1],
                'Call Delay (msec)': [-1],
                'Ingest': [False]
            })
        elif self.ds_type == 'multi_map':
            self._df = pd.DataFrame({
                'Name': [''],
                'Operation': [''],
                'Key': [''],
                'Key Range': [-1],
                'Object': [''],
                'ER': [''],
                'Count': [-1],
                'Call Delay (msec)': [-1],
                'Ingest': [False]
            })
        else:
            self._df = pd.DataFrame({
                'Name': [''],
                'Operation': [''],
                'Object': [''],
                'ER': [''],
                'Count': [-1],
                'Call Delay (msec)': [-1],
                'Ingest': [False]
            })
        tabulator_formatters = {
            'Ingest': {'type': 'tickCross'}
        }
        blotter_editors = {
            'Name': None,
            'Operation': {'type': 'list', 'values': operation_list},
            'Key': {'type': 'list', 'values': key_list},
            'Key Range': {'type': 'number', 'min': 100, 'max': 100_000_000, 'step': 100, 'set': self.default_key_range},
            'Object': {'type': 'list', 'values': self.get_object_name_list()},
            'ER': {'type': 'list', 'values': self.get_er_name_list()},
            'Delta': {'type': 'number', 'min': 1, 'max': 1000, 'step': 1, 'set': 1},
            'Count': {'type': 'number', 'min': 1, 'max': 100000, 'step': 10, 'set': 100},
            'Call Delay (msec)': {'type': 'number', 'min': 10, 'max': 100000, 'step': 10, 'set': 1000},
            'Ingest': {'type': 'tickCross'}
        }

        self._blotter = pn.widgets.Tabulator(self._df, name=blotter_name, editors=blotter_editors,
                                             layout='fit_columns',
                                             buttons={'Destroy': "<i class='fa fa-trash'></i>"},
                                             formatters=tabulator_formatters)

        self._blotter.on_edit(self.__blotter_on_edit__)
        self._blotter.on_click(self.__blotter_on_click__)
        self.reset(self.hazelcast_cluster)
        self._layout = pn.Column(self._status_text,
                                 pn.Row(self._new_button, self._new_text),
                                 self._blotter)
        self._sync_widgets()

    def refresh(self, is_reset=False):
        '''Refreshes this component with the latest data from Hazelcast.
        '''
        if self.hazelcast_cluster != None:
            ds_name_list = self.hazelcast_cluster.get_ds_names(self.ds_type)
        else:
            ds_name_list = []
        ds_name_list.sort()
        old_df = self._df
        old_name_list = old_df['Name'].tolist()
        old_name_list.sort()
        if ds_name_list == old_name_list:
            return

        # A workaround for a bug in Tabulator: If the table is initially empty
        # and new rows are added later, Panel does not display table contents.
        # A workaround is to initialize it with a single empty row.
        len_list = len(ds_name_list)
        if len_list == 0:
            name_list = ['']
            operation_list = ['']
            key_list = ['']
            key_range_list = ['']
            object_list = ['']
            er_list = ['N/A']
            delta_list = [-1]
            count_list = [-1]
            delay_list = [-1]
            ingest_list = [False]
        else:
            name_list = []
            operation_list = []
            key_list = []
            key_range_list = []
            object_list = []
            er_list = []
            delta_list = []
            count_list = []
            delay_list = []
            ingest_list = []

        # Retain the previously running tasks
        for name in ds_name_list:
            name_list.append(name)
            if name in old_name_list:
                for index, row in old_df.iterrows():
                    old_name = row['Name']
                    if old_name == name:
                        operation_list.append(old_df.iloc[index]['Operation'])
                        if self.ds_type == 'PNCounter':
                            delta_list.append(old_df.iloc[index]['Delta'])
                        elif self.ds_type != 'FlakeIdGenerator':
                            if self.ds_type == 'MultiMap':
                                key_list.append(old_df.iloc[index]['Key'])
                                key_range_list.append(old_df.iloc[index]['Key Range'])
                            object_list.append(old_df.iloc[index]['Object'])
                            er_list.append(old_df.iloc[index]['ER'])
                        count_list.append(old_df.iloc[index]['Count'])
                        delay_list.append(old_df.iloc[index]['Call Delay (msec)'])
                        ingest_list.append(old_df.iloc[index]['Ingest'])
                        break
            else:
                operation_list.append(self.default_operation)
                if self.ds_type == 'PNCounter':
                    delta_list.append(self.default_delta)
                elif self.ds_type != 'FlakeIdGenerator':
                    if self.ds_type == 'MultiMap':
                        key_list.append(self.default_key)
                        key_range_list.append(self.default_key_range)
                    ds = self.__get_ds__(name)
                    object_type_in_ds = self.get_object_name_in_ds(ds)
                    if object_type_in_ds == None:
                        object_list.append(self.default_object)
                    else:
                        object_list.append(object_type_in_ds)
                    er_list.append(self.default_er)
                count_list.append(self.default_count)
                delay_list.append(self.default_delay_in_msec)
                ingest_list.append(False)

        # Stop and remove existing threads that are not part of the new map list.
        # This cleans up the existing thread events in case the maps are destroyed
        # by other clients.
        DacBase.thread_pool.refresh(self.ds_type, ds_name_list)

        if self.ds_type == 'FlakeIdGenerator':
            new_df = pd.DataFrame({
                'Name': name_list,
                'Operation': operation_list,
                'Count': count_list,
                'Call Delay (msec)': delay_list,
                'Ingest' : ingest_list,
            })
        elif self.ds_type == 'PNCounter':
            new_df = pd.DataFrame({
                'Name': name_list,
                'Operation': operation_list,
                'Delta': delta_list,
                'Count': count_list,
                'Call Delay (msec)': delay_list,
                'Ingest' : ingest_list,
            })
        elif self.ds_type == 'MultiMap':
            new_df = pd.DataFrame({
                'Name': name_list,
                'Operation': operation_list,
                'Key': key_list,
                'Key Range': key_range_list,
                'Object': object_list,
                'ER': er_list,
                'Count': count_list,
                'Call Delay (msec)': delay_list,
                'Ingest' : ingest_list,
            })
        else:
            new_df = pd.DataFrame({
                'Name': name_list,
                'Operation': operation_list,
                'Object': object_list,
                'ER': er_list,
                'Count': count_list,
                'Call Delay (msec)': delay_list,
                'Ingest' : ingest_list,
            })
        self._df = new_df
        self._blotter.value = new_df
        self._sync_widgets()

    def __panel__(self):
        return self._layout

    @param.depends('value', watch=True)
    def _sync_widgets(self):
        self.value = self._df

    @param.depends('value', watch=True)
    def _sync_params(self):
        self.value = self._df

    def get_ds_from_hz(self, ds_name):
        '''Returns the specified data structure. The data structure is created if it does not exist.
        '''
        ds = None
        if self.hazelcast_cluster != None:
            if self.ds_type == 'FlakeIdGenerator':
                ds = self.hazelcast_cluster.hazelcast_client.get_flake_id_generator(ds_name)
            if self.ds_type == 'List':
                ds = self.hazelcast_cluster.hazelcast_client.get_list(ds_name)
            elif self.ds_type == 'MultiMap':
                ds = self.hazelcast_cluster.hazelcast_client.get_multi_map(ds_name)
            elif self.ds_type == 'PNCounter':
                ds = self.hazelcast_cluster.hazelcast_client.get_pn_counter(ds_name)
            elif self.ds_type == 'ReliableTopic':
                ds = self.hazelcast_cluster.hazelcast_client.get_reliable_topic(ds_name)
            elif self.ds_type == 'Ringbuffer':
                ds = self.hazelcast_cluster.hazelcast_client.get_ringbuffer(ds_name)
            elif self.ds_type == 'Set':
                ds = self.hazelcast_cluster.hazelcast_client.get_set(ds_name)
            elif self.ds_type == 'Queue':
                ds = self.hazelcast_cluster.hazelcast_client.get_queue(ds_name)
            elif self.ds_type == 'Topic':
                ds = self.hazelcast_cluster.hazelcast_client.get_topic(ds_name)
        return ds

    def __new_execute__(self, event):
        self.__clear_status__()
        name = self._new_text.value.strip()
        if len(name) == 0:
            return
        found = False
        for index, row in self._df.iterrows():
            if name == row['Name']:
                found = True
                break
        # Update df if a new name
        if found == False:
            if self.hazelcast_cluster != None and self.hazelcast_cluster.hazelcast_client != None:
                ds = self.get_ds_from_hz(name)

            name_list = self._df['Name'].to_list()
            # Replace the place holder (empty) row  used as a workaround to a Panel bug
            is_place_holder = len(name_list) == 1 and name_list[0] == ''
            if is_place_holder:
                name_list = [name]
                operation_list = [self.default_operation]
                key_list = [self.default_key]
                key_range_list = [self.default_key_range]
                object_list = [self.default_object]
                er_list = [self.default_er]
                delta_list = [self.default_delta]
                count_list = [self.default_count]
                delay_list = [self.default_delay_in_msec]
                ingest_list = [False]
            else:
                name_list.append(name)
                name_list.sort()
                index = 0
                for n in name_list:
                    if n == name:
                        break
                    index += 1
                operation_list = self._df['Operation'].to_list()
                operation_list.insert(index, self.default_operation)
                count_list = self._df['Count'].to_list()
                count_list.insert(index, self.default_count)
                delay_list = self._df['Call Delay (msec)'].to_list()
                delay_list.insert(index, self.default_delay_in_msec)
                ingest_list = self._df['Ingest'].to_list()
                ingest_list.insert(index, False)
                if self.ds_type == 'FlakeIdGenerator':
                    pass
                elif self.ds_type == 'PNCounter':
                    delta_list = self._df['Delta'].to_list()
                    delta_list.insert(index, self.default_delta)
                else:
                    if self.ds_type == 'MultiMap':
                        key_list = self._df['Key'].to_list()
                        key_list.insert(index, self.default_key)
                        key_range_list = self._df['Key Range'].to_list()
                        key_range_list.insert(index, self.default_key_range)
                    object_list = self._df['Object'].to_list()
                    object_list.insert(index, self.default_object)
                    er_list = self._df['ER'].to_list()
                    er_list.insert(index, self.default_er)

            if self.ds_type == 'FlakeIdGenerator':
                new_df = pd.DataFrame({
                    'Name': name_list,
                    'Operation': operation_list,
                    'Count': count_list,
                    'Call Delay (msec)': delay_list,
                    'Ingest' : ingest_list,
                })
            elif self.ds_type == 'PNCounter':
                new_df = pd.DataFrame({
                    'Name': name_list,
                    'Operation': operation_list,
                    'Delta': delta_list,
                    'Count': count_list,
                    'Call Delay (msec)': delay_list,
                    'Ingest' : ingest_list,
                })
            elif self.ds_type == 'MultiMap':
                new_df = pd.DataFrame({
                    'Name': name_list,
                    'Operation': operation_list,
                    'Key': key_list,
                    'Key Range': key_range_list,
                    'Object': object_list,
                    'ER': er_list,
                    'Count': count_list,
                    'Call Delay (msec)': delay_list,
                    'Ingest' : ingest_list,
                })
            else:
                new_df = pd.DataFrame({
                    'Name': name_list,
                    'Operation': operation_list,
                    'Object': object_list,
                    'ER': er_list,
                    'Count': count_list,
                    'Call Delay (msec)': delay_list,
                    'Ingest' : ingest_list,
                })
            self._df = new_df
            self._blotter.value = new_df

        # Select the new row
        for index, row in self._df.iterrows():
            if name == row['Name']:
                self._blotter.selection = [index]
                break

    def __click_remove_button__(self, event):
        return

    def __get_ds__(self, ds_name):
        '''Returns the specified data structure from the cached list in HazelcastCluster.
        If not found, then returns None.
        '''
        if self.hazelcast_cluster != None:
            return self.hazelcast_cluster.get_ds(self.ds_type, ds_name)
        else:
            return None

    def __clear_status__(self):
        self._status_text.value = ''

    def __blotter_on_edit__(self, event):
        name = self._df.iloc[event.row]['Name']
        operation = event.column
        operation_value = event.value
        if name == '':
            ds = None
        else:
            ds = self.__get_ds__(name)
            # ds may be None if it is newly created
            if ds == None:
                ds = self.get_ds_from_hz(name)
        if ds != None:
            if operation == 'Ingest':
                if operation_value == True:
                    # Abort if max threads reached
                    if DacBase.thread_pool.is_max():
                        self._status_text.value = f'ERROR: Max number of jobs reached [{DacBase.thread_pool.get_max()}]. Command aborted.'
                        self._blotter.patch({
                            'Ingest' : [
                                (event.row, False)
                            ]})
                        return

                    # Get a single object to check whether the selected object type
                    # is same as the object in the data structure
                    object_type_in_ds = self.get_object_name_in_ds(ds)

                    # Offload publishing task to a thread
                    ds_method_name = self._df.iloc[event.row]['Operation']
                    delta = None
                    key_type = None
                    key_range = None
                    object_type = None
                    er_object_name = None
                    if self.ds_type == 'PNCounter':
                        delta = self._df.iloc[event.row]['Delta']
                    elif self.ds_type != 'FlakeIdGenerator':
                        if self.ds_type == 'MultiMap':
                            key_type = self._df.iloc[event.row]['Key']
                            key_range = self._df.iloc[event.row]['Key Range']
                            if key_range < 100:
                                key_range = 100
                            elif key_range > 100_000_000:
                                key_range = 100_000_000
                        object_type = self._df.iloc[event.row]['Object']
                        if object_type_in_ds != None and object_type != object_type_in_ds:
                            self._status_text.value = f'ERROR: Invalid Object. Data structure has {object_type_in_ds} but your selection is {object_type}. Command aborted.'
                            self._blotter.patch({
                                'Ingest' : [
                                    (event.row, False)
                                ]})
                            return
                        er_object_name = self._df.iloc[event.row]['ER']
                        if er_object_name == 'N/A':
                            er_object_name = None
                    max = self._df.iloc[event.row]['Count']
                    batch_size = -1
                    delay_in_msec = self._df.iloc[event.row]['Call Delay (msec)']
                    # A bug in Tabulator. Min value not honored if number entered manually
                    if delay_in_msec < 10:
                        delay_in_msec = 10
                        self._blotter.patch({
                            'Call Delay (msec)' : [
                                (event.row, delay_in_msec)
                            ]})
                    thread, thread_event = DacBase.thread_pool.get_thread(self.ds_type, name,
                                                                          self.__ingest_task__,
                                                                          args=(name, key_type, key_range, object_type, er_object_name, delta, ds_method_name, max, batch_size, delay_in_msec))
                    if thread.is_alive() == False:
                        try:
                            thread.start()
                        except Exception as ex:
                            self._status_text.value = f'ERROR: {repr(ex)}'
                else:
                    # Stop thread and remove it from the thread pool
                    DacBase.thread_pool.stop_thread(self.ds_type, name)
                    if self._parent != None:
                        self._parent.remove_progress_by_name(self.ds_type, name)

    def __ingest_task__(self, ds_name, key_type, key_range, object_type, er_object_name, delta, ds_method_name, max, batch_size, delay_in_msec, thread_event):
        '''Thread task for ingesting data.
        '''
        # Ingest objects
        create_function = self.get_obj_creation_function(object_type)
        progress = Progress(self.ds_type, ds_name, key_type, key_range, object_type, er_object_name, delta, ds_method_name, max, batch_size, delay_in_msec)
        if self._parent != None:
            self._parent.add_progress(progress)

        try:
            if self.ds_type == 'FlakeIdGenerator':
                self.ingestor.ingest_flake_id_generator(ds_name, count=max, delay_in_msec=delay_in_msec, thread_event=thread_event, progress=progress)
            elif self.ds_type == 'List':
                self.ingestor.ingest_list(ds_name, create_function, er_object_name, count=max, delay_in_msec=delay_in_msec, thread_event=thread_event, progress=progress)
            elif self.ds_type == 'PNCounter':
                self.ingestor.ingest_pn_counter(ds_name, count=max, delay_in_msec=delay_in_msec, thread_event=thread_event, progress=progress, ds_method_name=ds_method_name, delta=delta)
            elif self.ds_type == 'MultiMap':
                self.ingestor.ingest_multi_map(ds_name, create_function, er_object_name, key_type=key_type, key_range=key_range, count=max, delay_in_msec=delay_in_msec, thread_event=thread_event, progress=progress)
            elif self.ds_type == 'Queue':
                self.ingestor.ingest_queue(ds_name, create_function, er_object_name, count=max, delay_in_msec=delay_in_msec, thread_event=thread_event, progress=progress)
            elif self.ds_type == 'ReliableTopic':
                self.ingestor.ingest_reliable_topic(ds_name, create_function, er_object_name, count=max, delay_in_msec=delay_in_msec, thread_event=thread_event, progress=progress)
            elif self.ds_type == 'Ringbuffer':
                self.ingestor.ingest_ringbuffer(ds_name, create_function, er_object_name, count=max, delay_in_msec=delay_in_msec, thread_event=thread_event, progress=progress)
            elif self.ds_type == 'Set':
                self.ingestor.ingest_set(ds_name, create_function, er_object_name, count=max, delay_in_msec=delay_in_msec, thread_event=thread_event, progress=progress)
            elif self.ds_type == 'Topic':
                self.ingestor.ingest_topic(ds_name, create_function, er_object_name, count=max, delay_in_msec=delay_in_msec, thread_event=thread_event, progress=progress)
        except Exception as ex:
            self._status_text.value = f'ERROR: {repr(ex)}'

        # Deselect Ingest checkbox
        for index, row in self._df.iterrows():
            if row['Name'] == ds_name:
                self._blotter.patch({
                                'Ingest' : [
                                    (index, False)
                                ]})
                break
        DacBase.thread_pool.stop_thread(self.ds_type, ds_name)
        if self._parent != None:
            self._parent.remove_progress(progress)

    def __blotter_on_click__(self, event):
        self.__clear_status__()
        row = event.row
        column = event.column
        if self.hazelcast_cluster != None and self.hazelcast_cluster.hazelcast_client != None:
            name = self._df.iloc[row]['Name']
            if name == '':
                return
            ds = self.__get_ds__(name)
            # ds may be None if it is # newly created
            if ds == None:
                ds = self.get_ds_from_hz(name)
            if column == 'Destroy':
                # Destroy
                is_destroyed = ds.destroy()
                if is_destroyed == True:
                    self.hazelcast_cluster.refresh()
                    DacBase.thread_pool.stop_thread(self.ds_type, name)
                self._status_text.value = f'Destroyed: {name} - {is_destroyed}'


import os
import sys
import logging
import openerp
import openerp.netsvc as netsvc
import openerp.addons.decimal_precision as dp
from openerp.osv import fields, osv, expression, orm
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from openerp import SUPERUSER_ID, api
from openerp import tools
from openerp.tools.translate import _
from openerp.tools.float_utils import float_round as round
from openerp.tools import (DEFAULT_SERVER_DATE_FORMAT,
    DEFAULT_SERVER_DATETIME_FORMAT,
    DATETIME_FORMATS_MAP,
    float_compare)

_logger = logging.getLogger(__name__)

class ResPartner(orm.Model):
    """ Model name: ResPartner
    """

    _inherit = 'res.partner'

    def no_auto_address_field(self, cr, uid, ids, context=None):
        ''' Remove default for this partner
        '''
        assert len(ids) == 1, 'Works only with one record a time'

        address_ids = self.search(cr, uid, [
            ('parent_id', '=', ids[0]),
            ('is_address', '=', True),
            ('auto_address', '=', True),
            ], context=context)

        # Remove previous check:
        if address_ids:
            self.write(cr, uid, address_ids, {
                'auto_address': False,
                }, context=context)
        return True

    def set_auto_address_field(self, cr, uid, ids, context=None):
        ''' Set as default address for this partner
        '''
        assert len(ids) == 1, 'Works only with one record a time'

        current_proxy = self.browse(cr, uid, ids, context=context)[0]
        parent_id = current_proxy.parent_id.id
        address_ids = self.search(cr, uid, [
            ('parent_id', '=', parent_id),
            ('is_address', '=', True),
            ('auto_address', '=', True),
            ], context=context)

        # Remove previous check:
        if address_ids:
            self.write(cr, uid, address_ids, {
                'auto_address': False,
                }, context=context)

        # Write check on this:
        return self.write(cr, uid, ids, {
            'auto_address': True,
            }, context=context)

    _columns = {
        'auto_address': fields.boolean('Auto address',
            help='Set up as default oder address when choose this partner'),
    }

class SaleOrder(orm.Model):
    ''' Manage delivery in header
    '''
    _inherit = 'sale.order'

    # Override onchange for reset address name
    def onchange_partner_id(self, cr, uid, ids, part, context=None):
        res = super(SaleOrder, self).onchange_partner_id(
            cr, uid, ids, part, context=context)

        partner_pool = self.pool.get('res.partner')
        address_id = False
        if part:
            address_ids = partner_pool.search(cr, uid, [
                ('parent_id', '=', part),
                ('is_address', '=', True),
                ('auto_address', '=', True),
                ], context=context)
            if address_ids:
                address_id = address_ids[0]

        # Reset value if not present
        res['value']['destination_partner_id'] = address_id
        res['value']['invoice_partner_id'] = False
        return res
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:


from tkinter import *
from tkinter.messagebox import *

root=Tk()

w,h=root.winfo_screenwidth(),root.winfo_screenheight()

root.geometry('%dx%d+0+0'%(w,h))
root.state('zoomed')

radio_v=StringVar()
radio_v.set('THIS IS A JOKE')
b1=Radiobutton(root,text='JOKER',variable=radio_v,value=1)
b1.grid(row=0,column=0,padx=w//3,columnspan=10)
b2=Entry(root)
b3=Label(root,text='Enter Name:',font='Arial 16 bold')
b3.grid(row=1,column=0)
b2.grid(row=1,column=1)


# can execute a set of statements as long as a condition is True.
# loops through the items of a list by using a 'while' loop.

# use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes.
# remember to increase the index by 1 after each iteration.

mylist = ["kiwi", "pineapple", "papaya", "jackfruit", "coconut"]
i = 0
while i < len(mylist):    # the condition is either True/False - if True, then continue.
    print(mylist[i])
    i = i + 1
print()
# the while loop requires relevant variables to be ready, in this example we need to define an indexing variable, i, which we set to 1

# a simpler version:
i = 1
while i < 6:  # will stop printing at 5
    print(i)
    i += 1    # += is the same as i = i + 1


class Solution:
    def rob(self, nums: List[int]) -> int:

        """
        1 2 3 4 5 6 7
        """
        if len(nums)==1:
            return nums[0]
        memo = {}
        def dp(ptr, flag):
            if ptr == 0:
                memo[(ptr, flag)] = nums[0]*(1-flag)
            elif ptr == 1:
                memo[(ptr, flag)] = max(nums[0]*(1-flag), nums[1])
            else:
                if (ptr-1, flag) in memo:
                    prev1 = memo[(ptr-1, flag)]
                else:
                    prev1 = dp(ptr-1, flag)

                if (ptr-2, flag) in memo:
                    prev2 = memo[(ptr-2, flag)]
                else:
                    prev2 = dp(ptr-2, flag)
                memo[(ptr, flag)] = max(prev1, prev2+nums[ptr])

            return memo[(ptr, flag)]

        with_last_house = dp(len(nums)-1, 1)
        no_last_house = dp(len(nums)-2, 0)
        return max(with_last_house, no_last_house)


# -*- coding: utf-8 -*-
"""
Created on Thu Dec 24 15:31:18 2020

@author: yrc2
"""
import flexsolve as flx
from biosteam.exceptions import InfeasibleRegion

class TiterAndInhibitorSpecification:
    __slots__ = (
        'evaporator',
        'mixer',
        'reactor',
        'product',
        'products',
        'sugars',
        'inhibitors',
        'target_titer',
        'maximum_inhibitor_concentration',
    )

    max_sugar_concentration = 600 # g / L

    def __init__(self, evaporator, mixer, reactor,
                 target_titer, product, products,
                 maximum_inhibitor_concentration=1.,
                 sugars= ('Glucose', 'Xylose'),
                 inhibitors = ('AceticAcid', 'HMF', 'Furfural')):
        self.evaporator = evaporator
        self.mixer = mixer
        self.reactor = reactor
        self.product = product
        self.products = products
        self.sugars = sugars
        self.inhibitors = inhibitors
        self.target_titer = target_titer
        self.maximum_inhibitor_concentration = maximum_inhibitor_concentration

    @property
    def feed(self):
        return self.evaporator.ins[0]

    @property
    def evaporated_sugar_solution(self):
        return self.evaporator.outs[0]

    @property
    def dilution_water(self):
        return self.mixer.ins[1]

    def run_units(self):
        self.evaporator._run()
        self.mixer._run()
        self.reactor._run()

    def calculate_titer(self):
        product = self.product
        return product.imass[self.products].sum() / product.F_vol

    def calculate_inhibitors(self): # g / L
        product = self.product
        return product.imass[self.inhibitors].sum() / product.F_vol

    def calculate_sugar_concentration(self): # g / L
        s = self.evaporated_sugar_solution
        return s.imass[sugars].sum() / s.F_vol

    def check_sugar_concentration(self):
        if self.calculate_sugar_concentration() > self.max_sugar_concentration:
            raise InfeasibleRegion('sugar concentration')

    def titer_objective_function(self, V):
        self.evaporator.V = V
        self.run_units()
        return self.calculate_titer() - self.target_titer

    def inhibitor_objective_function(self, V):
        self.evaporator.V = V
        self.run_units()
        self.update_dilution_water()
        self.run_units()
        return self.calculate_inhibitors() - self.maximum_inhibitor_concentration

    def run(self):
        self.dilution_water.empty()
        self.evaporator.V = 0.
        self.run_units()
        x_titer = self.calculate_titer()
        V_min = 1e-6
        if x_titer < self.target_titer: # Evaporate
            self.evaporator.V = V_min = flx.IQ_interpolation(self.titer_objective_function,
                                                             V_min, 1., ytol=1e-4, maxiter=100)
        elif x_titer > self.target_titer: # Dilute
            self.update_dilution_water(x_titer)
            self.mixer._run()
            self.reactor._run()

        self.check_sugar_concentration()
        x_inhibitor = self.calculate_inhibitors()
        if x_inhibitor > self.maximum_inhibitor_concentration:
            self.evaporator.V = flx.IQ_interpolation(self.inhibitor_objective_function,
                                                     V_min, 1., ytol=1e-4, maxiter=100)
        else:
            self.check_sugar_concentration()

    def update_dilution_water(self, x_titer=None):
        if x_titer is None: x_titer = self.calculate_titer()
        water = self.water_required_to_dilute_to_set_titer(x_titer)
        molar_volume = product.chemicals.Water.V(product.T, 101325) # m3 / mol
        self.dilution_water.imol['Water'] += water / molar_volume / 1000

    def water_required_to_dilute_to_set_titer(self, x_titer):
        return (1./x_titer - 1./self.target_titer) * self.product.imass[self.products].sum()