import pandas as pd
import seaborn as sns
import db
from sklearn import preprocessing # 머신러닝 전처리 => 데이터 정규화
import matplotlib.pyplot as plt

# 분석 끝나서 동적으로 쓸때 데이터프레임 db로 부터 받아올 필요있음.
# 전처리전 db 연결해서 데이터 뽑아옴
conn=db.get_connection()
anal_list_table=db.get_anal_list(conn)

# matplotlib 한글 폰트 처리
import platform
from matplotlib import font_manager, rc
plt.rcParams['axes.unicode_minus']=False

if platform.system()=='Windows':
    path = 'c:/Windows/Fonts/malgun.ttf'
    font_name=font_manager.FontProperties(fname=path).get_name()
    rc('font',family=font_name)

ac_anal=pd.read_excel('dynamic/data/ac_anal.xls',encoding='euc-kr')
pop_seoul=pd.read_excel('dynamic/data/Pop_seoul_real.xls',encoding='euc-kr')
ac_anal=pd.merge(ac_anal,pop_seoul,on='자치구')
ac_anal.set_index('자치구',inplace=True)

ac_anal['미성년자']=ac_anal['5~9세']+ac_anal['10~14세']+ac_anal['15~19세']
del ac_anal['10~14세']
del ac_anal['5~9세']
del ac_anal['15~19세']

# 상관관계 및 정규화 대상 칼럼 지정
col1 = ['무단횡단 사고',
        '중국인',
        '유흥업소']

col2 = ['무단횡단 사고',
        '유기동물보호현황',
        '인구밀도',
        '통근,통학',
        '총인구합계']

col3 = ['무단횡단 사고',
        '도로 총 계',
        '광로(40m이상)', '대로(25~40)', '중로(12~25)', '소로(12m미만)']

col4 = ['무단횡단 사고', '횡단보도수', '신호등O', '신호등X']

col5 = ['무단횡단 사고',
        '기초생활수급자',
        '미성년자', '노인인구합계']

col_list = [col1, col2, col3, col4, col5]

# 정규화 모듈

def Normalize(column_list):
    x = ac_anal[column_list].values
    min_max_scaler = preprocessing.MinMaxScaler()  # 전처리 모듈
    x_scaled = min_max_scaler.fit_transform(x.astype(float))

    ac_anal_norm = pd.DataFrame(x_scaled, columns=column_list, index=ac_anal.index)  # 정규화 DataFrame 생성

    return ac_anal_norm
# col1 ~ col5에 대한 정규화 테이블 생성

ac_anal_norm1=Normalize(col1) # 무단횡단 / 중국인 / 유흥업소
ac_anal_norm2=Normalize(col2) # '무단횡단 사고','유기동물보호현황','인구밀도','통근,통학'
ac_anal_norm3=Normalize(col3) # '무단횡단 사고','도로 총 계','광로(40m이상)','대로(25~40)','중로(12~25)','소로(12m미만)','도로연장당 횡단보도 수'
ac_anal_norm4=Normalize(col4) # '무단횡단 사고','횡단보도수','신호등O','신호등X'
ac_anal_norm5=Normalize(col5) # '무단횡단 사고','기초생활수급자','5~9세','10~14세','15~19세','노년부양비','노령화지수'

# 사진 저장 경로 수정해야함
# 그래프 사진 저장
# 영등포구 >> 무단횡단사고/중국인/유흥업소 수 히트맵
plt.figure(figsize = (15, 16))
Y_plot1=sns.heatmap(data = ac_anal_norm1, annot = True, fmt = '.2f', cmap = 'Reds')
fig1=Y_plot1.get_figure()
#fig1.savefig('C:\Multicampus_kssj\Anal_image\Yongdeungpo1_hitmap.png')
fig1.savefig('C:\Last_kssj_project\static')
# 영등포구 >> 무단횡단사고/중국인/유흥업소 상관계수 히트맵
plt.figure(figsize = (10, 10))
Y_plot2=sns.heatmap(data = ac_anal_norm1.corr(), annot = True, fmt = '.2f', cmap = 'Reds')
fig2=Y_plot2.get_figure()
fig2.savefig('C:\Multicampus_kssj\Anal_image\Yondeungpo2_corr_hitmap.png')

# 영등포구 >> 무단횡단사고/중국인/유흥업소 상관관계 pairplot
Y_plot3=sns.pairplot(ac_anal_norm1,x_vars=['중국인','유흥업소'],y_vars=['무단횡단 사고'],kind='reg',size=5)
Y_plot3.savefig('C:\Multicampus_kssj\Anal_image\Yondeungpo3_corr_pairplot.png')

# ***********************************************

# 2.관악구
plt.figure(figsize = (15, 15))
G_plot1=sns.heatmap(data = ac_anal_norm2, annot = True, fmt = '.2f', cmap = 'Blues')
fig1=G_plot1.get_figure()
fig1.savefig('C:\Multicampus_kssj\Anal_image\Gwanak1_hitmap.png')

plt.figure(figsize = (10, 10))
G_plot2=sns.heatmap(data = ac_anal_norm2.corr(), annot = True, fmt = '.2f', cmap = 'Blues')
fig2=G_plot2.get_figure()
fig2.savefig('C:\Multicampus_kssj\Anal_image\Gwanak2_corr_hitmap.png')

G_plot3=sns.pairplot(ac_anal_norm2,vars=['무단횡단 사고','인구밀도','통근,통학'],kind='reg',size=3)
G_plot3.savefig('C:\Multicampus_kssj\Anal_image\Gwanak3_corr_pairplot.png')

# 3.종로구
plt.figure(figsize = (15, 15))
J_plot1=sns.heatmap(data = ac_anal_norm5, annot = True, fmt = '.2f', cmap = 'Blues')
fig1=J_plot1.get_figure()
fig1.savefig('C:\Multicampus_kssj\Anal_image\Jongro1_hitmap.png')

plt.figure(figsize = (10, 10))
J_plot2=sns.heatmap(data = ac_anal_norm5.corr(), annot = True, fmt = '.2f', cmap = 'Blues')
fig2=J_plot2.get_figure()
fig2.savefig('C:\Multicampus_kssj\Anal_image\Jongro2_corr_hitmap.png')

J_plot3=sns.pairplot(ac_anal_norm3,x_vars=['광로(40m이상)','대로(25~40)','중로(12~25)','소로(12m미만)'],y_vars=['무단횡단 사고'],kind='reg',size=5)
J_plot3.savefig('C:\Multicampus_kssj\Anal_image\Jongro3_corr_pairplot.png')


import requests
import json
import jsonpath

def test_st_add_new():
    global id
    ADD_url = 'http://thetestingworldapi.com/api/studentsDetails'
    f = open("C:\\python-t\\API-testing\\utilities\\studendata.json", 'r')

    request_json = json.loads(f.read())
    reponse = requests.post(ADD_url, request_json)

    id = jsonpath.jsonpath(reponse.json(), 'id')
    print(id[0])

def test_st_info():
    final_details = 'http://thetestingworldapi.com/api/studentsDetails/' + str(id[0])
    response = requests.get(final_details)
    print(response.text)
    assert response.status_code == 450


import json
import os
import sys

try:
    import boto3
except ImportError:
    from warnings import warn
    warn('boto3 may not be installed; running mock library')

    class MockDynamodb:
        def Table(self, *args, **kwargs):
            return table

    class MockTable:
        creation_date_time = None
        def __init__(self):
            self.items = []
        def put_item(self, *args, **kwargs):
            self.items.append([args, kwargs])

    dynamodb = MockDynamodb()
    table = MockTable()
else:
    # Setting library paths.
    sys.path.append("/mnt/biosteam-packages")
    os.environ[ 'NUMBA_CACHE_DIR' ] = '/tmp/'

    from chaospy import distributions as shape
    # Create dynamodb resource for posting biosteam outputs
    dynamodb = boto3.resource('dynamodb')
    # Imports from EFS library mounted to root /mnt/simulate folder /lib/

# =============================================================================
# Lambda Functions
# =============================================================================

def lambda_handler(event, context):
    # Parse input and define data variables
    jobId = event['jobId']
    jobTimestamp = event['jobTimestamp']
    param_dict = event['params']
    samples_int = event['samples']
    sim_type = event['sim_type']

    model = event['model'].lower()
    if model == 'cornstover':
        from biorefineries.cornstover.webapp_model import model

    elif model == 'oilcane':
        from biorefineries.oilcane.webapp_model import model
        # oc.load('O1')
        # model = oc.model
    # else:
    #     print("invalid model " + model)
    all_parameters = {i.name: i for i in model.parameters}
    print(all_parameters)

    parameters = []
    for item in param_dict:
        name = item['name']
        if name in all_parameters:
            parameter = all_parameters[name]
        else:
            print(all_parameters)
            raise RuntimeError(f'no parameter with name {name}')

        parameters.append(parameter)
        values = item['values']
        if sim_type == 'uncertainty':
            distribution = item['distribution'].capitalize()
            parameter.baseline = values['baseline']
            if distribution == 'Triangular':
                lower = values['lower']
                midpoint = values['mode']
                upper = values['upper']
                parameter.distribution = shape.Triangle(lower=lower, midpoint=midpoint, upper=upper)
            elif distribution == 'Uniform':
                lower = values['lower']
                upper = values['upper']
                parameter.distribution = shape.Uniform(lower=lower, upper=upper)
            else:
                raise RuntimeError(f"distribution {distribution} not available yet")
        elif sim_type == 'single':
            parameter.baseline = values['baseline']
        else:
            print('Simulation type not implemented:', sim_type)

    # Rerun model at baseline to reset cache
    baseline_metrics = model.metrics_at_baseline()

    # Run model

    # results_payload={
    #         'jobId': jobId,
    #         'jobTimestamp': jobTimestamp,
    #         # 'results': results_json,
    #         # 'spearmanResults': spearman_rhos_json,
    #     }

    if sim_type == 'uncertainty':
        try:
            model.parameters = parameters
            samples = model.sample(N=samples_int, rule='L')
            model.load_samples(samples)
            model.evaluate()
        except Exception as e:
            raise e
        else:
            def get_name(metric):
                name = metric.name
                if metric.units: name += f" [{metric.units}]"
                return name
            results = model.table
            spearman_rhos, ps = model.spearman_r()
            param_names = [get_name(i) for i in parameters]
            metric_names = [get_name(i) for i in model.metrics]
            names = param_names + metric_names
            results_dict = {i: j.tolist() for i, j in zip(names, results.values.transpose())}
            results_json = json.dumps(results_dict)
            spearman_rhos_dict = {col: {row: float(value) for row, value in zip(param_names, values)}
                                  for col, values in zip(metric_names, spearman_rhos.values.transpose())}
            spearman_rhos_json = json.dumps(spearman_rhos_dict)
            # results_payload['results'] = json.dumps(json.load(results_json, parse_float=Decimal))
            # results_payload['spearmanResults'] = json.dumps(json.load(spearman_rhos_json, parse_float=Decimal))

        finally:
            model.parameters = tuple(all_parameters.values())
    elif sim_type == 'single':
        def get_name(metric):
                name = metric.name
                if metric.units: name += f" [{metric.units}]"
                return name
        baseline_metrics = model.metrics_at_baseline()
        metric_names = [get_name(i) for i in model.metrics]
        single_results = {i: j for i, j in zip(metric_names, baseline_metrics.values)}
        single_results = json.dumps(single_results)
        # results_payload['singleResults'] = json.dumps(json.load(single_results, parse_float=Decimal))

    else:
        print('Simulation type not implemented:', sim_type)

    # Add outputs to DynamoDB table: biosteamJobResults
    jobTimestamp = int(jobTimestamp)

    # Instatiate table
    table = dynamodb.Table('biosteam-results')
    print(table.creation_date_time)

    # Add biosteam results to table
    # print(results_payload)
    # from warnings import warn
    # warn(str(results_payload))
    if sim_type == 'uncertainty':
        table.put_item(
            Item={
                'jobId': jobId,
                'jobTimestamp': jobTimestamp,
                'results': results_json,
                'spearmanResults': spearman_rhos_json,
                # 'singleResults': single_results
            }
        )
    elif sim_type == 'single':
        table.put_item(
            Item={
                'jobId': jobId,
                'jobTimestamp': jobTimestamp,
                # 'results': results_json,
                # 'spearmanResults': spearman_rhos_json,
                'singleResults': single_results
            }
        )
    else:
        print("Simulation type not implemented")

    # Return job status
    return {
        'jobId': jobId,
        'Processed': 'yes',
    }

def test_lambda_handler():
    # Just make sure it runs for now
    # TODO: Add more rigorous tests
    context = None
    event = {
        'model': 'cornstover',
        'jobId': None,
        'jobTimestamp': 1,
        'params': [
            {'name': 'Cornstover price',
             'distribution': 'Uniform',
             'values': {
                 'value1': 0.0464,
                 'value2': 0.0567,
                 },
             },
        ],
        'samples': 50,
    }
    lambda_handler(event, context)

    event = {
        'model': 'oilcane',
        'jobId': None,
        'jobTimestamp': 1,
        'params': [
            {'name': 'Cane oil content',
             'distribution': 'Uniform',
             'values': {
                 'value1': 5,
                 'value2': 15,
                 },
             },
        ],
        'samples': 50,
    }
    lambda_handler(event, context)


# Module: addon
# Author: Tomas "tomplast" Gustavsson
# Created on: 30.12.2022
# License: GPL v.3 https://www.gnu.org/copyleft/gpl.html
"""
Premier One video plugin
"""
import xbmcgui
import xbmcplugin
import requests
import uuid
import routing

plugin = routing.Plugin()
DEVICE_ID = str(uuid.uuid4())

@plugin.route("/list_search/<term>/<page>")
def list_search(term, page):
    search_term = term

    if term == "_":
        search_term = xbmcgui.Dialog().input("Поиск")

    search_result = requests.get(
        f"https://premier.one/app/v1.2/search?query={search_term}&page={page}&picture_type=card_group&system=hwi_vod_id%2Chwi_world&is_active=1&device=web",
        headers={"x-device-type": "browser", "x-device-id": DEVICE_ID},
    ).json()

    for card in search_result["results"]:
        list_item = xbmcgui.ListItem(
            label=f'[B]{card["type"]["title"]}[/B] - {card["name"]}'
        )
        list_item.setArt({"thumb": card["picture"]})

        list_item.setInfo(
            "video",
            {
                "title": card["name"],
                "genre": ", ".join([x["name"] for x in card["genres"]]),
                "mediatype": "video",
            },
        )

        url = plugin.url_for(list_seasons, program=card["slug"])

        if card["type"]["name"] == "movie":
            list_item.setProperty("IsPlayable", "true")
            url = plugin.url_for(play_video, media_id=f'p:{card["slug"]}')

        xbmcplugin.addDirectoryItem(
            plugin.handle, url, list_item, not list_item.getProperty("IsPlayable")
        )

    if search_result["has_next"]:
        xbmcplugin.addDirectoryItem(
            plugin.handle,
            plugin.url_for(list_search, term=search_term, page=int(page) + 1),
            xbmcgui.ListItem(label="следующий"),
            True,
        )

    xbmcplugin.endOfDirectory(plugin.handle)

@plugin.route("/list_seasons/<program>")
def list_seasons(program):
    result = requests.get(
        f"https://premier.one/uma-api/metainfo/tv/{program}/season/?picture_type=banner"
    ).json()

    for season in result:
        list_item = xbmcgui.ListItem(label=f'сезон {season["number"]}')
        list_item.setArt({"thumb": season["picture"]})

        url = plugin.url_for(
            list_videos, program=program, season=int(season["number"]), page=1
        )
        xbmcplugin.addDirectoryItem(plugin.handle, url, list_item, True)

    xbmcplugin.endOfDirectory(plugin.handle)

@plugin.route("/")
def list_main_menu():
    xbmcplugin.addDirectoryItem(
        plugin.handle,
        plugin.url_for(list_free, page=1),
        xbmcgui.ListItem(label="Бесплатно"),
        True,
    )

    xbmcplugin.addDirectoryItem(
        plugin.handle,
        plugin.url_for(list_search, term='_', page=1),
        xbmcgui.ListItem(label="Поиск (Может работать)"),
        True,
    )

    xbmcplugin.endOfDirectory(plugin.handle)

@plugin.route("/list_programs")
def list_programs(page=1):
    card_group = requests.get(
        f"https://premier.one/uma-api/feeds/cardgroup/202?alias=all_premier&style=portrait&link=https%3A%2F%2Ftnt-premier.ru&title=&bg_url=https%3A%2F%2Ftnt-premier.ru%2Fimg%2Fdevices-4.1168fded.png&picture_type=card_group&quantity=6&sort=publication_d&origin__type=hwi,rtb&is_active=1&system=hwi_vod_id,hwi_world&page={page}"
    ).json()

    xbmcplugin.addDirectoryItem(
        plugin.handle,
        plugin.url_for(list_search),
        xbmcgui.ListItem(label="Поиск"),
        True,
    )

    for card in card_group["results"]:
        list_item = xbmcgui.ListItem(
            label=f'[B]{card["type"]["title"]}[/B] - {card["object"]["name"]}'
        )
        list_item.setArt({"thumb": card["object"]["picture"]})

        list_item.setInfo(
            "video",
            {
                "title": card["object"]["name"],
                "genre": ", ".join([x["name"] for x in card["object"]["genres"]]),
                "mediatype": "video",
            },
        )

        url = plugin.url_for(list_seasons, program=card["object"]["slug"])

        if card["type"]["name"] == "movie":
            list_item.setProperty("IsPlayable", "true")
            url = plugin.url_for(play_video, media_id=f'p:{card["object"]["slug"]}')

        xbmcplugin.addDirectoryItem(
            plugin.handle, url, list_item, not list_item.getProperty("IsPlayable")
        )

    if card_group["has_next"]:
        xbmcplugin.addDirectoryItem(
            plugin.handle,
            plugin.url_for(list_programs, page=int(page) + 1),
            xbmcgui.ListItem(label="следующий"),
            True,
        )

    xbmcplugin.endOfDirectory(plugin.handle)

@plugin.route("/list_videos/<program>/<season>/<page>")
def list_videos(program, season, page):
    videos = requests.get(
        f"https://premier.one/uma-api/metainfo/tv/{program}/video/?show_all=1&season={season}&type=6%2C9&limit=18&origin__type=hwi%2Crtb&page={page}"
    ).json()

    for video in videos["results"]:
        list_item = xbmcgui.ListItem(label=f"{video['title']}")
        list_item.setArt({"thumb": video["thumbnail_url"]})
        list_item.setInfo(
            "video",
            {
                "title": video["title"],
                "plot": video["description"],
                "season": season,
                "episode": video["episode"],
                "mediatype": "video",
                "picture": video["thumbnail_url"],
            },
        )
        list_item.setProperty("IsPlayable", "true")

        url = plugin.url_for(play_video, media_id=video["id"])

        xbmcplugin.addDirectoryItem(plugin.handle, url, list_item, False)

    if videos["has_next"]:
        xbmcplugin.addDirectoryItem(
            plugin.handle,
            plugin.url_for(
                list_videos, season=season, program=program, page=int(page) + 1
            ),
            xbmcgui.ListItem(label="следующий"),
            True,
        )

    xbmcplugin.endOfDirectory(plugin.handle)

@plugin.route("/list_free/<page>")
def list_free(page):
    card_group = requests.get(
        f"https://premier.one/uma-api/feeds/cardgroup/250?alias=all_premier&style=portrait&link=https%3A%2F%2Ftnt-premier.ru&title=&bg_url=https%3A%2F%2Ftnt-premier.ru%2Fimg%2Fdevices-4.1168fded.png&picture_type=card_group&quantity=6&sort=publication_d&origin__type=hwi,rtb&is_active=1&system=hwi_vod_id,hwi_world&page={page}"
    ).json()

    for card in card_group["results"]:
        list_item = xbmcgui.ListItem(
            label=f'[B]{card["object"]["type"]["title"]}[/B] - {card["object"]["name"]}'
        )

        list_item.setArt({"thumb": card["object"]["picture"]})

        list_item.setInfo(
            "video",
            {
                "title": card["object"]["name"],
                "genre": ", ".join([x["name"] for x in card["object"]["genres"]]),
                "mediatype": "video",
            },
        )

        url = plugin.url_for(list_seasons, program=card["object"]["slug"])

        if card["object"]["type"]["name"] == "movie":
            list_item.setProperty("IsPlayable", "true")
            url = plugin.url_for(play_video, media_id=f'p:{card["object"]["slug"]}')

        xbmcplugin.addDirectoryItem(
            plugin.handle, url, list_item, not list_item.getProperty("IsPlayable")
        )

    if card_group["has_next"]:
        xbmcplugin.addDirectoryItem(
            plugin.handle,
            plugin.url_for(list_free, page=int(page) + 1),
            xbmcgui.ListItem(label="следующий"),
            True,
        )

    xbmcplugin.endOfDirectory(plugin.handle)

@plugin.route("/play_video/<media_id>")
def play_video(media_id):
    if media_id.startswith("p:"):
        _, program = media_id.split("p:")
        video = requests.get(
            f"https://premier.one/uma-api/metainfo/tv/{program}/video/?show_all=1&season=0&type=6%2C9&limit=18&origin__type=hwi%2Crtb&page=1"
        ).json()

        media_id = video["results"][0]["id"]

    response = requests.get(
        f"https://premier.one/api/play/options/{media_id}/?format=json&no_404=true&referer=https://premier.one/show/istoriya-na-noch/season/1/episode/18?fullscreen=true"
    )

    json_response = response.json()

    if response.status_code != 200:
        error_message = next(
            x["title"]
            for x in json_response["detail"]["languages"]
            if x["lang"] == "rus"
        )
        xbmcgui.Dialog().ok("Ошибка", error_message)
        return

    play_item = xbmcgui.ListItem(path=json_response["video_balancer"]["default"])

    xbmcplugin.setResolvedUrl(plugin.handle, True, listitem=play_item)

if __name__ == "__main__":
    xbmcplugin.setPluginCategory(plugin.handle, "")
    plugin.run()


import cv2
import numpy as np
from matplotlib import pyplot as plt
import tensorflow as tf
from tf_bodypix.api import  download_model, load_model, BodyPixModelPaths

bodypix_model = load_model(download_model(BodyPixModelPaths.MOBILENET_FLOAT_50_STRIDE_16))

img = cv2.imread("../Samples/tumbnail.jpg")
img = cv2.resize(img, (640, 480))
print(img.shape)

cap = cv2.VideoCapture(0)

while True:
    ret, frame = cap.read()
    frame = cv2.resize(frame, (640, 480))
    # BodyPix detection
    result = bodypix_model.predict_single(frame)
    mask = result.get_mask(threshold=0.5).numpy().astype(np.uint8)
    masked_image = cv2.bitwise_and(frame, frame,mask=mask)

    # Apply virtual background
    neg = np.add(mask, -1)
    inverse = np.where(neg == -1, 1, neg).astype(np.uint8)
    masked_background = cv2.bitwise_and(img, img, mask=inverse)
    final = cv2.add(masked_image, masked_background)

    cv2.imshow("BodyPix", masked_image)
    if cv2.waitKey(10) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()


import subprocess
from multiprocessing import Process
from threading import Thread

import paho.mqtt.client as mqtt
import random as rand
import time
import sys

from datetime import datetime

class ChiengDeGarde(Process):
    def __init__(self, ip='127.0.0.255', port=1883):
        super().__init__()
        self.client = mqtt.Client(client_id="ChiengDeGarde")
        self.client.on_connect = self.on_connect
        self.client.on_message = self.on_message
        self.client.connect(ip, port=port)

        self.port = port
        self.ip = ip

        self.lastPings = [datetime.now(), datetime.now(), datetime.now()]

        self.isAlive = False

    def start(self):
        self.client.connect(self.ip, port=self.port)
        self.client.subscribe("/cdg/kill")
        self.client.subscribe("/server0/state")
        self.client.subscribe("/server1/state")
        self.client.subscribe("/server2/state")
        self.client.loop_start()

        self.isAlive = True

    # Action lorsque le capteur c'est bien connecté au réseau MQTT
    def on_connect(self, client, userdata, flag, rc):
        print("C'est mon chien connecte !")

    def on_message(self, client, userdata, msg):
        if msg.topic == "/cdg/kill":
            self.isAlive = False
            return

        elif msg.topic == "/server0/state":
            self.lastPings[0] = datetime.now()
        elif msg.topic == "/server1/state":
            self.lastPings[1] = datetime.now()
        elif msg.topic == "/server2/state":
            self.lastPings[2] = datetime.now()

        return

    def run(self):
        # Envoie d'un nombre aléatoire chaque seconde
        while self.isAlive:
            self.stalker()
            time.sleep(1)

    def stalker(self):
        t = datetime.now()
        d = [t - self.lastPings[0],
             t - self.lastPings[1],
             t - self.lastPings[2]]

        for i in range(len(d)):
            if d[i].total_seconds() >= 3:
                print(f"Wouf, le server {i} est dead")

                thread = Thread(target=lambda: subprocess.run(f"python server.py {i} restart"), daemon=True)
                thread.start()

        pass

if __name__ == "__main__":
    cdg = ChiengDeGarde()
    cdg.start()
    cdg.run()

    sys.exit()


import numpy as np
from numpy.core.fromnumeric import mean
from scipy.spatial import cKDTree
import sys
from collections import defaultdict
from os import listdir, mkdir, path
from os.path import join
from bearing import calculate_bearing, next_point, haversine, angledist, printProgressBar
import numpy as np
from queue import PriorityQueue
from time import time

def process_input(input_folder):
    files = list(listdir(input_folder))

    trajs = defaultdict(list)  # {trip_name: [trip_info]}
    data = []  # [trip_info,...]

    for fi in files:
        with open(join(input_folder, fi)) as f:
            for i, line in enumerate(f):
                # format: id, lat, lng, timestamp
                id_, lat, lng, ts = line.strip().split(',')
                lat = lat[:7]
                lng = lng[:7]
                lat, lng, ts = float(lat), float(lng), int(float(ts))
                if i:
                    # compute angle
                    a = calculate_bearing((trajs[fi][-1][1],
                                           trajs[fi][-1][0]), (lat, lng))
                    trajs[fi].append((lng, lat, ts, a))
                    data.append((lng, lat, ts, a))
                else:
                    trajs[fi].append((lng, lat, ts, 0))
                    data.append((lng, lat, ts, 0))
            if len(trajs[fi]) > 1:
                trajs[fi][0] = (trajs[fi][0][0], trajs[fi][0][1], trajs[fi][0][2],
                                trajs[fi][1][3])

    return trajs, data

def impute_trajectories(trajs):
    visited = set([])
    totalTrajs = len(list(trajs.values()))
    currentTraj = 0
    for k, traj in list(trajs.items()):
        # consider angle of first point is same as second one.
        # For each consecutive pair of points in the trajectory:
        trimpute_traj = []
        printProgressBar(currentTraj, totalTrajs, 'Progress', 'Completed')
        if len(traj) and path.getsize(input_folder + '/' + k) > 0:
            inside_traj = False
            start_time = time()
            for i, (a, b) in enumerate(zip(traj, traj[1:])):
                inside_traj = True

                s = (a[0], a[1], a[2], a[3])
                d = (b[0], b[1], b[2], b[3])

                seg_dist = haversine(s[0], s[1], d[0], d[1])
                cid = centroids.index((s[0], s[1]))
                nns = c_nns[cid]
                angles = [data[_][3] for _ in nns]

                hist, bins = np.histogram(angles, bins=[_*ANGLE_BIN for _ in
                                                        range(int(360/ANGLE_BIN)+1)], density=True)

                relevant_directions = []
                FOUND = False
                dense_segment = []
                for bearing, pr in zip(bins[:-1], hist):
                    if pr*ANGLE_BIN > CROWD_THRESHOLD\
                            and angledist(bearing, a[3]) < ANGLE_THRESHOLD:
                        # filter bins and find the average angle inside each bin

                        bin_angles = list(
                            filter(lambda ang: bearing <= ang < bearing + ANGLE_BIN, angles))
                        bin_average = sum(bin_angles)/len(bin_angles)
                        relevant_directions.append((bin_average, pr*ANGLE_BIN))

                paths = PriorityQueue()
                visited.add(s)
                for rd in relevant_directions:
                    new_pt = next_point(s[1], s[0], DISTANCE_THRESHOLD, rd[0])
                    new_pt = (round(new_pt[0], 4), round(
                        new_pt[1], 4))  # epsilon = 10m
                    new_pt_angle = calculate_bearing((s[1], s[0]),
                                                     (new_pt[1], new_pt[0]))

                    new_pt = (new_pt[0], new_pt[1], a[2], new_pt_angle)
                    remaining_dist = haversine(
                        new_pt[0], new_pt[1], d[0], d[1])

                    if remaining_dist > RADIUS_METER\
                            and new_pt not in visited:
                        paths.put((haversine(s[0], s[1], new_pt[0], new_pt[1]) +
                                   remaining_dist, (DISTANCE_THRESHOLD, [s, new_pt])))
                        visited.add(new_pt)

                    elif new_pt not in visited:
                        FOUND = True
                        dense_segment = [s, new_pt]
                        break

                while not paths.empty() and not FOUND:
                    path_weight, (leng, curr_path) = paths.get()

                    if leng >= LENGTH_FACTOR * seg_dist:
                        continue

                    curr_pt = curr_path[-1]
                    curr_angle = calculate_bearing((curr_path[-2][1], curr_path[-2][0]),
                                                   (curr_pt[1], curr_pt[0]))
                    nns = idx.query_ball_point(
                        x=(curr_pt[0], curr_pt[1]), r=RADIUS_DEGREE, p=2)

                    # Discard points that have no neighbors
                    if len(nns) < MIN_NNS:
                        continue

                    angles = [data[_][3] for _ in nns]
                    hist, bins = np.histogram(angles, bins=[_*ANGLE_BIN for _ in
                                                            range(int(360/ANGLE_BIN)+1)], density=True)
                    relevant_directions = []
                    # Angle condition:
                    for bearing, pr in zip(bins[:-1], hist):
                        if pr*ANGLE_BIN > CROWD_THRESHOLD\
                                and angledist(bearing, curr_angle) < ANGLE_THRESHOLD:
                            # filter bins and find the average angle inside each bin

                            bin_angles = list(
                                filter(lambda ang: bearing <= ang < bearing + ANGLE_BIN, angles))
                            bin_average = sum(bin_angles)/len(bin_angles)
                            relevant_directions.append(
                                (bin_average, pr*ANGLE_BIN))

                    for rd in relevant_directions:
                        new_pt = next_point(
                            curr_pt[1], curr_pt[0], DISTANCE_THRESHOLD, rd[0])
                        new_pt = (round(new_pt[0], 4), round(new_pt[1], 4))
                        new_pt_angle = calculate_bearing((curr_pt[1], curr_pt[0]),
                                                         (new_pt[1], new_pt[0]))

                        new_pt = (new_pt[0], new_pt[1],
                                  curr_pt[2], new_pt_angle)
                        dist = haversine(new_pt[0], new_pt[1], d[0], d[1])

                        # Candidate point, consider rest of the path
                        if dist > RADIUS_METER and new_pt not in visited:
                            paths.put((leng+DISTANCE_THRESHOLD + dist, (leng + haversine(curr_pt[0], curr_pt[1],
                                                                                new_pt[0], new_pt[1]), curr_path + [new_pt])))
                            visited.add(new_pt)

                        # We found the last point of the imputation
                        elif new_pt not in visited:
                            FOUND = True
                            dense_segment = curr_path + [new_pt]
                            break
                # No imputation
                if len(dense_segment) == 0:
                    dense_segment.append(a)
                    trimpute_traj += dense_segment
                if FOUND:
                    # append dense segment points to the densified trajectory
                    time_diff = d[2] - s[2]
                    delta_time = int(
                        time_diff/max(1, (len(dense_segment) - 1)))
                    ts = s[2]
                    dense_seg_temporal = [dense_segment[0]]
                    for j, _ in enumerate(dense_segment[1:]):
                        dense_seg_temporal.append((_[0], _[1], ts + (j+1) *
                                                   delta_time, _[3]))
                    trimpute_traj += dense_seg_temporal

            # Write the densified trimpute_traj to the output file
            with open(output_folder+'/%s' % k, 'w') as g:
                for pt in trimpute_traj:
                    g.write('%s,%s,%s,%s\n' % pt)
                # Add the last point in the sparse trajectory
                if inside_traj:
                    g.write('%s,%s,%s,%s\n' % (d[0], d[1], d[2], d[3]))
            timeTaken = time() - start_time
            with open(output_folder+'/results.csv', 'a') as h:
                h.write("%s,%s,%s,%s\n" % (k, len(traj), len(trimpute_traj), timeTaken))
            currentTraj += 1

if __name__ == '__main__':

    try:
        input_folder = "./datasets/input/%s" % (sys.argv[1])
        output_folder = "./datasets/output/%s" % (sys.argv[2])
    except Exception as e:
        print("Not enough arguments!")
        exit()

    try:
        mkdir(output_folder)
    except Exception as e:
        print(e)
        exit()

    start_time = time()
    print('started')

    # Main parameters
    CANDIDATE_POINTS = 6  # N
    CROWD_THRESHOLD = 0.005  # alpha
    ANGLE_THRESHOLD = 120  # delta
    DISTANCE_THRESHOLD = 50  # d

    # Global values
    RADIUS_METER = DISTANCE_THRESHOLD
    ANGLE_BIN = 360/CANDIDATE_POINTS
    RADIUS_DEGREE = RADIUS_METER * 10e-6
    LENGTH_FACTOR = 3  # path should not exceed 3 times the birdfly distance.
    MIN_NNS = 1  # at least one neighbor

    trajs, data = process_input(input_folder)

    print('Indexing points')

    points = [(_[0], _[1]) for _ in data]
    idx = cKDTree(list(points))
    centroids = list(set(points))

    # store the neighbors within RADIUS meters for every centorid
    c_nns = idx.query_ball_point(x=list(centroids), r=RADIUS_DEGREE, p=2)

    print('Imputation started')

    impute_trajectories(trajs)

    print("--- %s seconds ---" % (time() - start_time))


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

"""Ensembles of AdK transitions.

https://figshare.com/articles/Simulated_trajectory_ensembles_for_the_closed-to-open_transition_of_adenylate_kinase_from_DIMS_MD_and_FRODA/7165306
"""

from os.path import dirname, exists, join
from os import makedirs, remove
import tarfile
import glob

import logging

from .base import get_data_home
from .base import _fetch_remote, _read_description
from .base import RemoteFileMetadata
from .base import Bunch

METADATA = {
    'DIMS': {
        'NAME': "adk_transitions_DIMS",
        'DESCRIPTION': "adk_transitions_DIMS.rst",
        'ARCHIVE': {
            'tarfile': RemoteFileMetadata(
                filename='DIMS.tar.gz',
                url='https://ndownloader.figshare.com/files/13182490',
                checksum='81dfd247da7084bc7f47889c098069978b61f8f8b4f7706841266d284bfd3b55',
            ),
        },
        'CONTENTS': {
            'topology': "DIMS/topologies/adk4ake.psf",
            'trajectories': "DIMS/trajectories/dims*_fit-core.dcd",
            'N_trajectories': 200,
        },
    },
    'FRODA': {
        'NAME': "adk_transitions_FRODA",
        'DESCRIPTION': "adk_transitions_FRODA.rst",
        'ARCHIVE': {
            'tarfile': RemoteFileMetadata(
                filename='FRODA.tar.gz',
                url='https://ndownloader.figshare.com/files/13182493',
                checksum='fc2c90b9819fd07720e7effada033d4045663919ba7d2c8bd84f548dfbeee73c',
            ),
        },
        'CONTENTS': {
            'topology': "FRODA/topologies/1ake.pdb",
            'trajectories': "FRODA/trajectories/pathway*_fit-core.dcd",
            'N_trajectories': 200,
        },
    },
}

logger = logging.getLogger(__name__)

def fetch_adk_transitions_DIMS(data_home=None, download_if_missing=True):
    """Load the AdK DIMS transititions dataset

    Parameters
    ----------
    data_home : optional, default: None
        Specify another download and cache folder for the datasets. By default
        all MDAnalysisData data is stored in '~/MDAnalysis_data' subfolders.
        This dataset is stored in ``<data_home>/adk_transitions_DIMS``.
    download_if_missing : optional, default=True
        If ``False``, raise a :exc:`IOError` if the data is not locally available
        instead of trying to download the data from the source site.

    Returns
    -------
    dataset : dict-like object with the following attributes:
    dataset.topology : filename
        Filename of the topology file
    dataset.trajectories : list
        list with filenames of the trajectory ensemble
    dataset.N_trajectories : int
        number of trajectories in the ensemble
    dataset.DESCR : string
        Description of the ensemble

    See :ref:`adk-transitions-DIMS-dataset` for description.
    """
    return _fetch_adk_transitions(METADATA['DIMS'],
                                  data_home=data_home,
                                  download_if_missing=download_if_missing)

def fetch_adk_transitions_FRODA(data_home=None, download_if_missing=True):
    """Load the AdK FRODA transititions dataset

    Parameters
    ----------
    data_home : optional, default: None
        Specify another download and cache folder for the datasets. By default
        all MDAnalysisData data is stored in '~/MDAnalysis_data' subfolders.
        This dataset is stored in ``<data_home>/adk_transitions_FRODA``.
    download_if_missing : optional, default=True
        If ``False``, raise a :exc:`IOError` if the data is not locally available
        instead of trying to download the data from the source site.

    Returns
    -------
    dataset : dict-like object with the following attributes:
    dataset.topology : filename
        Filename of the topology file
    dataset.trajectories : list
        list with filenames of the trajectory ensemble
    dataset.N_trajectories : int
        number of trajectories in the ensemble
    dataset.DESCR : string
        Description of the ensemble

    See :ref:`adk-transitions-FRODA-dataset` for description.
    """
    return _fetch_adk_transitions(METADATA['FRODA'],
                                  data_home=data_home,
                                  download_if_missing=download_if_missing)

def _fetch_adk_transitions(metadata, data_home=None, download_if_missing=True):
    """Generic function to load the AdK transititions datasets

    Parameters
    ----------
    metdata : dict
        dictionary with `NAME`, `DESCRIPTION` and `ARCHIVE` that contains
        a tar.gz file with directories topologies and trajectories
    data_home : optional, default: None
        Specify another download and cache folder for the datasets. By default
        all MDAnalysisData data is stored in '~/MDAnalysis_data' subfolders.
    download_if_missing : optional, default=True
        If ``False``, raise a :exc:`IOError` if the data is not locally available
        instead of trying to download the data from the source site.

    Returns
    -------
    dataset : dict-like object with the following attributes:
    dataset.topology : filename
        Filename of the topology file
    dataset.trajectories : list
        list with filenames of the trajectory ensemble
    dataset.DESCR : string
        Description of the ensemble

    Note
    ----
    Assumptions that are built in:
    - download a single tar.gz file
    - trajectories are given with a glob pattern

    """
    name = metadata['NAME']
    data_location = join(get_data_home(data_home=data_home),
                         name)
    if not exists(data_location):
        makedirs(data_location)

    records = Bunch()

    meta = metadata['ARCHIVE']['tarfile']
    local_path = join(data_location, meta.filename)

    if not exists(local_path):
        if not download_if_missing:
            raise IOError("Data {0}={1} not found and `download_if_missing` is "
                          "False".format(file_type, local_path))
        logger.info("Downloading {0}: {1} -> {2}...".format(
            "tarfile", meta.url, local_path))
        archive_path = _fetch_remote(meta, dirname=data_location)

        logger.info("Unpacking {}...".format(archive_path))
        with tarfile.open(archive_path, 'r') as tar:
            tar.extractall(path=data_location)

    records.topology = join(data_location, metadata['CONTENTS']['topology'])
    if not exists(records.topology):
        # should not happen...
        raise RuntimeError("topology file {} is missing".format(records.topology))

    trajectory_pattern = join(data_location, metadata['CONTENTS']['trajectories'])
    records.trajectories = glob.glob(trajectory_pattern)
    records.N_trajectories = metadata['CONTENTS']['N_trajectories']
    if len(records.trajectories) != records.N_trajectories:
        # should not happen...
        raise RuntimeError("trajectory files in {0} are incomplete: only {1} "
                           "but should be {2}.".format(
                               trajectory_pattern, len(records.trajectories),
                               records.N_trajectories))

    records.DESCR = _read_description(metadata['DESCRIPTION'])

    return records


import os
from PIL import Image
from pathlib import Path
from tqdm.auto import tqdm
import numpy as np
from sklearn.model_selection import train_test_split

if __name__ == "__main__":
    des_dir = Path('../../data/processed/CHASEDB1/')
    source_dir = Path('../../data/raw/CHASEDB1/')

    if not os.path.exists(des_dir / 'train' /'image'):
        os.makedirs(des_dir / 'train' /'image')
    if not os.path.exists(des_dir / 'train' /'mask'):
        os.makedirs(des_dir / 'train' /'mask')
    if not os.path.exists(des_dir / 'test' /'image'):
        os.makedirs(des_dir / 'test' /'image')
    if not os.path.exists(des_dir / 'test' /'mask'):
        os.makedirs(des_dir / 'test' /'mask')

    split_propotion = 0.2
    mask_ext = '_1stHO.png'
    train_img, test_img = train_test_split(list((source_dir).glob('*.jpg')), test_size=split_propotion, shuffle=True, random_state=1999)

    train_img = sorted(train_img)
    test_img = sorted(test_img)

    for i, img in enumerate(tqdm(train_img)):
        src_img = Image.open(img)
        src_img.save(des_dir / 'train' /'image' / (str(i) + '.jpg'), quality=100, subsampling=0)
        mask = img.name[:-4] + mask_ext
        src_mask = Image.open(source_dir / mask)
        src_mask.save(des_dir/'train'/'mask'/(str(i) + '.jpg'), quality=100, subsampling=0)

    for i, img in enumerate(tqdm(test_img)):
        src_img = Image.open(img)
        src_img.save(des_dir / 'test' /'image' / (str(i) + '.jpg'), quality=100, subsampling=0)
        mask = img.name[:-4] + mask_ext
        src_mask = Image.open(source_dir / mask)
        src_mask.save(des_dir/'test'/'mask'/(str(i) + '.jpg'), quality=100, subsampling=0)


from django.urls import path

from .views import (
    ThreadDetailView,
    ThreadEditView,
    ThreadDeleteView,
    ThreadCreateView,
    thread_view,
    like_thread,
    dislike_thread,
    CategoryView,
    search_result,
    watch_thread,
    CommentDelete,
)

urlpatterns = [
    path("<int:pk>/", ThreadDetailView.as_view(), name="thread_detail"),
    path("<int:pk>/edit/", ThreadEditView.as_view(), name="thread_edit"),
    path("<int:pk>/delete/", ThreadDeleteView.as_view(), name="thread_delete"),
    path("delete_comment/", CommentDelete, name="delete_comment"),
    path("new/", ThreadCreateView.as_view(), name="thread_new"),
    path("like/", like_thread, name="like_thread"),
    path("dislike/", dislike_thread, name="dislike_thread"),
    path("watch/",  watch_thread, name="watch"),
    path("category/<str:cats>/", CategoryView, name="category"),
    path("search_result/", search_result, name="search_result"),
    path("", thread_view, name="thread_list"),
]


# Utilities for smartcam application

from dbus import Interface, SystemBus
from subprocess import check_output

################################################################################

def get_git_branch():
    cmd_out = check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])
    return(cmd_out.decode('utf-8').rstrip())

def __systemd_create_interface():
    try:
        systemd = SystemBus().get_object('org.freedesktop.systemd1',
                                         '/org/freedesktop/systemd1')
        return(Interface(systemd, 'org.freedesktop.systemd1.Manager'))
    except Exception as e:
        print(e)
    return

def systemd_unit_running(unit_name):
    interface = __systemd_create_interface()

    try:
        obj_path = interface.LoadUnit(unit_name)
        obj_proxy = SystemBus().get_object('org.freedesktop.systemd1', obj_path)

        properties = Interface(obj_proxy, 'org.freedesktop.DBus.Properties')
        res = properties.GetAll('org.freedesktop.systemd1.Unit')['ActiveState']
    except Exception as e:
        print(e)
        return(None)

    if 'active' == res:
        return(True)
    return(False)

def systemd_unit_start(unit_name):
    interface = __systemd_create_interface()

    try:
        interface.StartUnit(unit_name)
        return(True)
    except Exception as e:
        print(e)
    return(False)


"""This module contains the definition for a pylint HoudiniPackageRunner."""

# =============================================================================
# IMPORTS
# =============================================================================

# Future
from __future__ import annotations

# Standard Library
import pathlib
import sys
from io import StringIO
from typing import TYPE_CHECKING, List

# Third Party
from pylint import lint
from pylint.reporters.text import ColorizedTextReporter

# Houdini Package Runner
import houdini_package_runner.config
import houdini_package_runner.parser
import houdini_package_runner.runners.utils
import houdini_package_runner.utils
from houdini_package_runner.discoverers import package
from houdini_package_runner.runners.base import HoudiniPackageRunner

# Imports for type checking.
if TYPE_CHECKING:
    import argparse

    from houdini_package_runner.config import BaseRunnerConfig
    from houdini_package_runner.discoverers.base import BaseItemDiscoverer
    from houdini_package_runner.items.base import BaseItem

# =============================================================================
# CLASSES
# =============================================================================

class PyLintRunner(HoudiniPackageRunner):
    """Implementation for a pylint package runner.

    :param discoverer: The item discoverer used by the runner.
    :param runner_config: Optional BaseRunnerConfig object.

    """

    def __init__(
        self, discoverer: BaseItemDiscoverer, runner_config: BaseRunnerConfig = None
    ) -> None:
        super().__init__(discoverer, runner_config=runner_config)

        self._disabled: List[str] = []

    # -------------------------------------------------------------------------
    # PROPERTIES
    # -------------------------------------------------------------------------

    @property
    def name(self) -> str:
        """The runner name used for identification."""
        return "pylint"

    # -------------------------------------------------------------------------
    # METHODS
    # -------------------------------------------------------------------------

    @staticmethod
    def build_parser(parser: argparse.ArgumentParser = None) -> argparse.ArgumentParser:
        """Build a parser for the runner.

        :param parser: Optional parser to add arguments to, otherwise a new one will be created.
        :return: The common parser for the runner.

        """
        if parser is None:
            parser = houdini_package_runner.parser.build_common_parser(
                description="""Run pylint on Houdini package items.

Any unknown args will be passed along to the pylint command.
"""
            )

        parser.add_argument(
            "--rcfile",
            action="store",
            help="Specify a configuration file",
        )

        parser.add_argument("--disable", action="store", help="Tests to disable.")

        return parser

    def init_args_options(self, namespace: argparse.Namespace, extra_args: List[str]):
        """Initialize any extra options from parser data.

        :param namespace: Argument parser namespace.
        :param extra_args: Optional list of extra_args to pass to isort.

        """
        super().init_args_options(namespace, extra_args)

        if namespace.rcfile:
            extra_args.insert(0, f"--rcfile={namespace.rcfile}")

        if namespace.disable:
            self._disabled = namespace.disable.split(",")

        if extra_args:
            self._extra_args.extend(extra_args)

    def process_path(self, file_path: pathlib.Path, item: BaseItem) -> int:
        """Process a file path.

        :param file_path: The path to lint.
        :param item: The item to lint.
        :return: The process return code.

        """
        flags = []

        flags.extend(self.extra_args)

        to_disable = []

        if self._disabled:
            to_disable.extend(self._disabled)

        to_disable.extend(self.config.get_config_data("to_disable", item, file_path))

        flags.extend(self.config.get_config_data("command", item, file_path))

        known_builtins: List[str] = item.ignored_builtins

        known_builtins.extend(
            self.config.get_config_data("known_builtins", item, file_path)
        )

        if known_builtins:
            houdini_package_runner.utils.add_or_append_to_flags(
                flags, "--additional-builtins", known_builtins
            )

        if to_disable:
            flags.append(f"--disable={','.join(to_disable)}")

        command = flags + [str(file_path)]

        if self.verbose:
            houdini_package_runner.runners.utils.print_runner_command(
                item, command, extra="pylint --output-format=colorized "
            )

        buf = StringIO()

        result = lint.Run(command, reporter=ColorizedTextReporter(buf), exit=False)

        output = buf.getvalue()

        if output:
            sys.stdout.write(output)

        return result.linter.msg_status

# =============================================================================
# FUNCTIONS
# =============================================================================

def main() -> int:
    """Run 'pylint' on package files."""
    parser = PyLintRunner.build_parser()
    parsed_args, unknown = parser.parse_known_args()

    discoverer = package.init_standard_package_discoverer(parsed_args)

    run_tool = PyLintRunner(discoverer)
    run_tool.init_args_options(parsed_args, unknown)

    result = run_tool.run()
    return result


import pyburner
import asyncio

heater = pyburner.Client("111.222.333.444")
loop = asyncio.get_event_loop()

async def main():
    asyncio.create_task(heater.init_websocket())
    # allow time for websocket to connect
    await asyncio.sleep(1.5)
    tasks = await asyncio.gather(
        heater.fetch_data("TempCurrent"),
        heater.fetch_data("TempBody")
    )
    print(f"The ambient temperature is {tasks[0]} degrees.\n"
          f"The heater body temperature is {tasks[1]} degrees.")
    await asyncio.create_task(heater.close_websocket())

asyncio.run(main())


from __future__ import division
import cv2
from .pupil import Pupil

# 클래스명 : Calibration
# 기능 : 웹캠에서 동공 탐지 알고리즘에서 최선의 이진 임계값을 찾아서 눈금을 매긴다.
# 작성일자 : 2022/04/26

class Calibration(object):

    def __init__(self):
        self.nb_frames = 20
        self.thresholds_left = []
        self.thresholds_right = []

    # 함수명 : is_complete
    # 기능 : 눈금 매기는 것이 완료됐다면 True를 반환
    # 매개변수 : self (자기 자신 객체)
    # 반환값: True or False
    # 작성일자 : 2022/04/26
    def is_complete(self):
        return len(self.thresholds_left) >= self.nb_frames and len(self.thresholds_right) >= self.nb_frames

    # 함수명 : threshold
    # 기능 : 화면 상의 눈에서 임계값을 반환한다.
    # 매개변수 : self (자기 자신 객체), side(왼쪽 눈이면 0이고 오른쪽 눈이면 1)
    # 반환값: 계산된 임계값
    # 작성일자 : 2022/04/26
    def threshold(self, side):
        if side == 0:
            return int(sum(self.thresholds_left) / len(self.thresholds_left))
        elif side == 1:
            return int(sum(self.thresholds_right) / len(self.thresholds_right))

    # 함수명 : iris_size
    # 기능 : 홍채가 눈의 표면에서 차지하는 비율울 반환한다.
    # 매개변수 : frame (이진화된 홍채의 프레임)
    # 반환값: 비율 반환
    # 작성일자 : 2022/04/26
    @staticmethod
    def iris_size(frame):
        frame = frame[5:-5, 5:-5]
        height, width = frame.shape[:2]
        nb_pixels = height * width
        nb_blacks = nb_pixels - cv2.countNonZero(frame)
        return nb_blacks / nb_pixels

    # 함수명 : find_best_threshold
    # 기능 : 눈의 프레임을 이진화하기 위한 최적의 임계값을 계산한다.
    # 매개변수 : eye_frame (눈의 프레임)
    # 반환값: 최적의 임계값
    # 작성일자 : 2022/04/26
    @staticmethod
    def find_best_threshold(eye_frame):
        average_iris_size = 0.7  # 원래는 0.48, 눈동자 수월하게 감지 위해 상향 조정
        trials = {}

        for threshold in range(5, 100, 5):
            iris_frame = Pupil.image_processing(eye_frame, threshold)
            trials[threshold] = Calibration.iris_size(iris_frame)

        best_threshold, iris_size = min(trials.items(), key=(
            lambda p: abs(p[1] - average_iris_size)))
        return best_threshold

    # 함수명 : evaluate
    # 기능 : 주어진 이미지를 고려해서 매긴 눈금을 개선시킨다.
    # 매개변수 : self(자기 자신 객체), eye_frame(눈의 프레임), side(왼쪽 눈이면 0이고 오른쪽 눈이면 1)
    # 작성일자 : 2022/04/26
    def evaluate(self, eye_frame, side):
        threshold = self.find_best_threshold(eye_frame)

        if side == 0:
            self.thresholds_left.append(threshold)
        elif side == 1:
            self.thresholds_right.append(threshold)


import numpy as np
from scipy.io import loadmat

def load_data(subject=1):
    filename = 'data/meg_data_%da.mat' % subject
    data = loadmat(filename)

    triggers = data['triggers']
    planardat = data['planardat']

    t1 = triggers['t1'][0, 0].squeeze()
    t2 = triggers['t2'][0, 0].squeeze()
    t3 = triggers['t3'][0, 0].squeeze()
    t4 = triggers['t4'][0, 0].squeeze()
    t5 = triggers['t5'][0, 0].squeeze()
    t6 = triggers['t6'][0, 0].squeeze()
    test = triggers['test'][0, 0].squeeze()
    behav = triggers['behav'][0, 0].squeeze()
    return t1, t2, t3, t4, t5, t6, test, behav, planardat

def create_train_test_sets(subject=1, window_size=125, t_offset=0,
                           normalize=True):
    t1, t2, t3, t4, t5, t6, test, behav, planardat = load_data(subject)
    t_all = np.concatenate([t1, t2, t3, t4, t5, t6])
    labels_all = np.concatenate([np.ones(t1.size), np.ones(t2.size) * 2,
                                 np.ones(t3.size) * 3, np.ones(t4.size) * 4,
                                 np.ones(t3.size) * 5, np.ones(t4.size) * 6])
    idx = np.argsort(t_all)
    if normalize:
        # This is a global normalization, not per-trial:
        planardat = np.nan_to_num((planardat.T - planardat.mean(1))
                                  / planardat.std(1)).T

    # Ntrials x Nchannels X Nsamples:
    X_train = np.array([planardat[:, t+t_offset: t+t_offset+window_size]
                        for t in t_all[idx]])
    y_train = labels_all[idx].astype(np.int)
    X_test = np.array([planardat[:, t+t_offset: t+t_offset+window_size]
                       for t in test])
    return X_train, y_train, X_test

if __name__ == '__main__':

    subject = 1
    t1, t2, t3, t4, t5, t6, test, behav, planardat = load_data(subject)

    import matplotlib.pyplot as plt
    plt.interactive(True)
    plt.figure()
    plt.plot(planardat[0, :], 'r-')
    plt.plot(t4, np.zeros(t4.size), 'b*')
    plt.plot(test, np.zeros(test.size), 'kx')
    plt.plot(behav, np.zeros(behav.size), 'go')

    X_train, y_train, X_test = create_train_test_sets(subject)

    plt.figure()
    plt.plot(X_train[0, 0, :], 'r-')


import pandas as pd
import streamlit as st

from repo import repo_files
from stock_data import stocks

# BASIC SETUP OF WEB PAGE
def basic_setup():
    st.set_page_config(page_title='Nasdaq Stock Game', layout='wide')
    st.markdown(f'NASDAQ STOCK GAME'
             , unsafe_allow_html=True)
    st.button(':red[New Game]', on_click=new_game)
    st.markdown('___')

def startup_my_stocks():
    # Getting data:
    # My stocks
    my_stocks = repo_files.get_my_stocks()
    # My cash
    my_cash = repo_files.get_cash()
    # updated stock data
    s_data = repo_files.get_stocks()

    # Calculating stock worth
    stock_worth = calc_stock_worth(my_stocks, s_data)

    # Populating portfolio info
    portfolio(my_cash, stock_worth)

    # Populating table of stocks owned
    my_stocks = my_stocks.rename_axis(index='ID')

    # Adding info and calculations for my stocks
    if len(my_stocks) == 0:
        st.write('No Stocks Yet')
    elif len(my_stocks) != 0:
        my_symbol = my_stocks['symbol'].tolist()
        latest_price = []
        latest_change = []
        for s in my_symbol:
            x = float(s_data.loc[s_data['symbol'] == s, 'price'])
            latest_price.append(x)
            y = ((float(x)/float(my_stocks.loc[my_stocks['symbol'] == s, 'org_price']))-1)*100
            latest_change.append(y)
        my_stocks['price'] = latest_price
        my_stocks['change'] = latest_change
        my_stocks['sell'] = False
        # Showing my stocks
        st.markdown(f'My stocks'
                 , unsafe_allow_html=True)
        exist_stocks = st.data_editor(my_stocks, column_config={
            'symbol': st.column_config.Column('Symbol', disabled=True),
            'amount': st.column_config.NumberColumn('Amount Owned', disabled=True),
            'org_price': st.column_config.NumberColumn('Purchase price', disabled=True),
            'price': st.column_config.NumberColumn('Latest Price', disabled=True),
            'change': st.column_config.NumberColumn('% Change', disabled=True, format='%.2f%%'),
            'sell': st.column_config.CheckboxColumn('Sell?'),
        })

        sell_list = []
        for i in range(0, len(exist_stocks)):
            if exist_stocks['sell'][i]:
                sell_list.append(i)

    return sell_list

# Suggested stocks
def look():
    s_data = stocks.get_data()
    # Showing my stocks
    st.markdown(f'Stocks to look out for'
                , unsafe_allow_html=True)
    s_data['buy'] = False

    # # The algorithm for formulating recommendation
    # s_data['test1'] = s_data['net_cash_debt'] / s_data['revenue']
    # s_data['test2'] = s_data['free_cash_flow'] / s_data['revenue']
    # lookout_data = s_data.loc[s_data['test1'] > 5500 & s_data['test2'] > 750 ]
    #
    # look_stocks = st.data_editor(lookout_data, column_config={
    #     'symbol': st.column_config.Column('Symbol', disabled=True),
    #     'company name': st.column_config.TextColumn('Company', disabled=True),
    #     'marketCap': st.column_config.NumberColumn('MarketCap', disabled=True),
    #     'price': st.column_config.NumberColumn('Latest Price', disabled=True),
    #     'change': st.column_config.NumberColumn('% Change', disabled=True, format='%.2f%%'),
    #     'revenue': st.column_config.NumberColumn('Revenue', disabled=True),
    #     'volume': st.column_config.NumberColumn('Volume', disabled=True),
    #     'industry': st.column_config.TextColumn('Industry', disabled=True),
    #     'sector': st.column_config.TextColumn('Sector', disabled=True),
    #     'revenueGrowth': st.column_config.NumberColumn('% Revenue Growth', disabled=True, format='%.2f%%'),
    #     'netincome': st.column_config.NumberColumn('Net Income', disabled=True),
    #     'free_cash_flow': st.column_config.NumberColumn('Free Cash Flow', disabled=True),
    #     'net_cash_debt': st.column_config.NumberColumn('Net Cash/Debt', disabled=True),
    #     'buy': st.column_config.CheckboxColumn('Buy?')
    # })
    #
    # look_list = []
    # for i in range(0, len(look_stocks)):
    #     if look_stocks['buy'][i]:
    #         look_list.append(i)
    #
    # return look_list

def market():
    s_data = repo_files.get_stocks()
    # Showing my stocks
    st.markdown(f'The Market Now'
                , unsafe_allow_html=True)
    s_data['buy'] = False
    market_stocks = st.data_editor(s_data, column_config={
        'symbol': st.column_config.Column('Symbol', disabled=True),
        'company name': st.column_config.TextColumn('Company', disabled=True),
        'marketCap': st.column_config.NumberColumn('MarketCap', disabled=True),
        'price': st.column_config.NumberColumn('Latest Price', disabled=True),
        'change': st.column_config.NumberColumn('% Change', disabled=True, format='%.2f%%'),
        'revenue': st.column_config.NumberColumn('Revenue', disabled=True),
        'volume': st.column_config.NumberColumn('Volume', disabled=True),
        'industry': st.column_config.TextColumn('Industry', disabled=True),
        'sector': st.column_config.TextColumn('Sector', disabled=True),
        'revenueGrowth': st.column_config.NumberColumn('% Revenue Growth', disabled=True, format='%.2f%%'),
        'netincome': st.column_config.NumberColumn('Net Income', disabled=True),
        'free_cash_flow': st.column_config.NumberColumn('Free Cash Flow', disabled=True),
        'net_cash_debt': st.column_config.NumberColumn('Net Cash/Debt', disabled=True),
        'buy': st.column_config.CheckboxColumn('Buy?')
    })

    buy_list = []
    for i in range(0, len(market_stocks)):
        if market_stocks['buy'][i]:
            buy_list.append(i)

    return buy_list

# New Game
def new_game():
    try:
        repo_files.del_file('base')
        repo_files.del_file('my_stocks')
        repo_files.del_file('my_cash')
    except:
        pass

    # Save base df
    base = (stocks.get_data())
    repo_files.save_new_file(base, 'base')
    # make my_stocks file
    my_stocks = pd.DataFrame({'symbol': [], 'amount': [], 'org_price': []})
    my_cash = pd.DataFrame({'cash': [100000]})
    repo_files.save_new_file(my_stocks, 'my_stocks')
    repo_files.save_new_file(my_cash, 'my_cash')

def save_game():
    pass

def portfolio(my_cash, stock_worth):
    # My Portfolio
    with st.container():
        st.markdown(f'My Portfolio'
                 , unsafe_allow_html=True)
        st.write(f'cash: {int(my_cash):,} ')
        st.write(f'stocks: {stock_worth:,}')
        st.markdown('___')

def calc_stock_worth(my_stocks, s_data):
    # calculating worth of stock portfolio
    if len(my_stocks) != 0:
       stock_worth = 0
       my_stock_list = my_stocks['symbol'].unique().tolist()
       for symbol in my_stock_list:
           amount = int(my_stocks.loc[my_stocks['symbol'] == symbol, 'amount'].sum())
           price = int(s_data.loc[s_data['symbol'] == symbol, 'price'])
           worth = price * amount
           stock_worth = stock_worth + worth
    else:
        stock_worth = 0

    return int(stock_worth)


import numpy as np
import cv2
from matplotlib import pyplot as plt
# import shutil
# shutil.copyfile('H:/Image/2.jpg', 'Image/image.jpg')

img = cv2.imread('Image/image.jpg', cv2.IMREAD_COLOR)
# plt.imshow(img, cmap='gray', interpolation='bicubic')
# plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis
# plt.show()

b, g, r = cv2.split(img)
img2 = cv2.merge([r, g, b])
plt.subplot(121);plt.imshow(img) # expects true color
plt.subplot(122);plt.imshow(img2) # expects distorted color
plt.show()

cv2.imshow('bgr image', img)
cv2.imshow('rgb image', img2)
if cv2.waitKey(0) == ord('q'):
	cv2.destroyWindow('image')


from tkinter import Tk, messagebox, scrolledtext, Menu, Toplevel, Label, StringVar, NW, NE, CENTER, END, DISABLED
from tkinter.ttk import Entry, Button, Radiobutton
from os.path import abspath
from os import execl
from sys import executable, argv
from requests import get as rget
from requests import ConnectionError
from threading import Thread
from wiktionaryparser import WiktionaryParser
from localStoragePy import localStoragePy
import json

localStorage = localStoragePy("me.jkelol111.tkdictionary", "text")

def start_thread(function):
    t = Thread(target=function)
    t.start()

def print_to_textbox(message):
    dictionaryTextView.insert(END, message + "\n")
def clear_textbox():
    dictionaryTextView.delete('1.0', END)

def checkNetwork():
    turl='http://www.google.com/'
    tout=5
    try:
        testGoogle = rget(url=turl, timeout=tout)
        messagebox.showinfo("", "The network is available.\nTkDictionary should work.")
    except ConnectionError:
        messagebox.showerror("", "The network is unavailable.\nTkDictionary will not work.")

def about():
    aboutWindow = Toplevel()
    aboutWindow.wm_resizable(False, False)
    aboutWindow.focus_set()
    aboutWindow.grab_set()
    appName_label = Label(aboutWindow, text="TkDictionary v.0.8")
    appName_label.pack()
    aboutMessage = "A dictionary application written in Python that uses\nWiki or Urban Dictionary.\n\n(C) Nguyen Thanh Nam (jkelol111) 2018\nLicensed under the MIT license."
    aboutMessage_label = Label(aboutWindow, text=aboutMessage)
    aboutMessage_label.pack()
    ok_button = Button(aboutWindow, text="OK", command=lambda: aboutWindow.destroy())
    ok_button.pack()
    mainWindow.update_idletasks()
    aboutWindow.update_idletasks()
    w = aboutWindow.winfo_width()
    h = aboutWindow.winfo_height()
    x = mainWindow.winfo_width()/2 + mainWindow.winfo_x()-180
    y = mainWindow.winfo_height()/2 + mainWindow.winfo_y()-80
    aboutWindow.geometry("%dx%d+%d+%d" % (w, h, x, y))
    aboutWindow.mainloop()

def settings():
    dictChoice = StringVar()
    langChoice = StringVar()
    langChoice.set(lang)
    themeChoice = StringVar()
    def restartAppToApplyChanges():
        restart = messagebox.askyesno("", "The app will restart for the changes to take effect.\nDo you want to restart the app now?")
        if restart == True:
            execl(executable, abspath(__file__), *argv)
        elif restart == False:
            messagebox.showwarning("", "Please save your work and restart the app as soon as possible for changes to take effect.")
    def resetSettings():
        settingsWindow.grab_release()
        resetY = messagebox.askyesno("", "This will reset TkDictionary to defaults. Do you want to continue?")
        if resetY == True:
            settingsWindow.destroy()
            config_contents = dict(language='english', source='urbandictionary', theme="light")
            localStorage.setItem("config.json", json.dumps(config_contents))
            restartAppToApplyChanges()
        elif resetY == False:
            settingsWindow.focus_set()
            settingsWindow.grab_set()
    def saveSettings():
        settingsWindow.destroy()
        config_contents = dict(language=langChoice.get(), source=dictChoice.get(), theme=themeChoice.get())
        localStorage.setItem("config.json", json.dumps(config_contents))
        restartAppToApplyChanges()
    settingsWindow = Toplevel()
    settingsWindow.wm_resizable(False, False)
    settingsWindow.focus_set()
    settingsWindow.grab_set()
    sourceLabel = Label(settingsWindow, text="Dictionary source:")
    sourceLabel.pack(anchor=NW)
    wikiRadioButton = Radiobutton(settingsWindow, text="Wiktionary", variable=dictChoice, value="wiktionary")
    wikiRadioButton.pack(anchor=NW, padx=10)
    urbanRadioButton = Radiobutton(settingsWindow, text="Urban Dictionary", variable=dictChoice, value="urbandictionary")
    urbanRadioButton.pack(anchor=NW, padx=10)
    if src == "wiktionary":
        wikiRadioButton.invoke()
    elif src == "urbandictionary":
        urbanRadioButton.invoke()
    else:
        pass
    disclaimerLabel = Label(settingsWindow, text="All content belongs to their respective owners. Please agree to their respective terms and conditions before use.")
    disclaimerLabel.pack(anchor=NW)
    langLabel = Label(settingsWindow, text="Dictionary language:")
    langLabel.pack(anchor=NW)
    langInput = Entry(settingsWindow, textvariable=langChoice)
    langInput.pack(anchor=NW, padx=10)
    langInstructLabel1 = Label(settingsWindow, text="This option only works with Wiktionary. Not all languages available.")
    langInstructLabel1.pack(anchor=NW)
    langInstructLabel2 = Label(settingsWindow, text="Example: English = english, Italian = italian, French = french, etc.")
    langInstructLabel2.pack(anchor=NW)
    themeLabel = Label(settingsWindow, text="App theme (not working):")
    themeLabel.pack(anchor=NW)
    lightRadioButton = Radiobutton(settingsWindow, text="Light", variable=themeChoice, value="light")
    lightRadioButton.pack(anchor=NW, padx=10)
    darkRadioButton = Radiobutton(settingsWindow, text="Dark", variable=themeChoice, value="dark")
    darkRadioButton.pack(anchor=NW, padx=10)
    if theme == "light":
        lightRadioButton.invoke()
    elif theme == "dark":
        darkRadioButton.invoke()
    else:
        pass
    saveSettingsButton = Button(settingsWindow, text="Save settings", command=saveSettings)
    saveSettingsButton.pack()
    resetSettingsButton = Button(settingsWindow, text="Reset settings", command=resetSettings)
    resetSettingsButton.pack()
    mainWindow.update_idletasks()
    settingsWindow.update_idletasks()
    w = settingsWindow.winfo_width()
    h = settingsWindow.winfo_height()
    x = mainWindow.winfo_width()/2 + mainWindow.winfo_x()-218
    y = mainWindow.winfo_height()/2 + mainWindow.winfo_y()-130
    settingsWindow.geometry("%dx%d+%d+%d" % (w, h, x, y))
    settingsWindow.mainloop()

def searchWord():
    word = wordEntry.get()
    clear_textbox()
    print_to_textbox("Loading, please wait...")
    if src == "wiktionary":
        parser = WiktionaryParser()
        result = parser.fetch(word, language=lang)
        clear_textbox()
        from pprint import pprint
        pprint(result)
        print_to_textbox(word)
        print_to_textbox("\nMeanings:")
        for n in result[0]["definitions"]:
            print(len(n))
            for i in result[0]["definitions"][len(n)]["text"]:
                print_to_textbox(i)
    elif src == "urbandictionary":
        parameters2 = {"term": word}
        result2 = rget("http://api.urbandictionary.com/v0/define", params=parameters2).json()
        clear_textbox()
        print_to_textbox(result2["list"][0]["word"])
        print_to_textbox("\nMost-voted definition:\n"+result2["list"][0]["definition"])
        print_to_textbox("\nExamples:\n"+result2["list"][0]["example"])
        print_to_textbox("\nBy user: "+result2["list"][0]["author"]+"        "+"Votes: UP: "+str(result2["list"][0]["thumbs_up"])+" DOWN: "+str(result2["list"][0]["thumbs_down"]))
    else:
        clear_textbox()
        errmessage = "Dictionary with name null not found. Check your settings in 'Actions & others' above!"
        print_to_textbox(errmessage)
        messagebox.showerror("TkDictionary Error", errmessage)

if not localStorage.getItem("config.json"):
    createConfig = messagebox.askquestion("TkDictionary Error", "We couldn't find your configuration file. Do you want to create one?")
    if createConfig == "yes":
        try:
            localStorage.setItem("config.json", json.dumps(dict(language='en', source='urbandictionary', theme="light")))
        except:
            messagebox.showerror("TkDictionary error", "Could not make config file. The app will now quit.")
            exit()
        execl(executable, abspath(__file__), *argv)
    else:
        messagebox.showerror("TkDictionary error", "We couldn't find your configuration file. The app will now exit.")
        exit()
else:
    try:
        config_contents = json.loads(localStorage.getItem("config.json"))
        lang = config_contents["language"]
        src = config_contents["source"]
        theme = config_contents["theme"]
    except Exception as e:
        print(str(e))

mainWindow = Tk()
mainWindow.title("TkDictionary")
mainWindow.wm_resizable(False, False)
mainWindow.focus_get()

menubar = Menu(mainWindow)
actionMenu = Menu(menubar, tearoff=0)
actionMenu.add_command(label="Test network activity...", command=checkNetwork)
actionMenu.add_separator()
actionMenu.add_command(label="Settings...", command=settings)
menubar.add_cascade(label="Actions & others", menu=actionMenu)
aboutMenu = Menu(menubar, tearoff=0)
aboutMenu.add_command(label="About TkDictionary...", command=about)
menubar.add_cascade(label="About & help", menu=aboutMenu)

wordEntry = Entry(mainWindow, justify=CENTER, width=mainWindow.winfo_reqwidth()-160)
wordEntry.focus_set()
wordEntry.pack()

if src == "wiktionary":
    searchButton_text = "Search Wiktionary..."
elif src == "urbandictionary":
    searchButton_text = "Search Urban Dictionary..."
else:
    searchButton_text = "Config Error! Check settings!"
searchButton = Button(mainWindow, text=searchButton_text, command=lambda: start_thread(searchWord))
searchButton.pack()

dictionaryTextView = scrolledtext.ScrolledText(mainWindow)
dictionaryTextView.pack()

mainWindow.config(menu=menubar)

mainWindow.update_idletasks()
w = mainWindow.winfo_reqwidth()
h = mainWindow.winfo_reqheight()
x = (mainWindow.winfo_screenwidth() - w) / 2
y = (mainWindow.winfo_screenheight() - h) / 2
mainWindow.geometry("%dx%d+%d+%d" % (w, h, x, y))

mainWindow.mainloop()


import os
import random

import torch
from diffusers import LMSDiscreteScheduler, StableDiffusionPipeline

class StableDiffusion:

    def __init__(self, model, beta_start=0.00085, beta_end=0.012, inference_steps=50):
        self.model = model
        self.starting_seed = random.randint(0, 99999999)
        self.inference_steps = inference_steps

        torch.manual_seed(self.starting_seed)

        lms = LMSDiscreteScheduler(beta_start=beta_start, beta_end=beta_end, beta_schedule="scaled_linear")
        lms.set_timesteps(inference_steps)

        self.pipe = StableDiffusionPipeline.from_pretrained(self.model, revision="fp16", torch_dtype=torch.float16, scheduler=lms)
        self.pipe = self.pipe.to("cuda")

    @staticmethod
    def generate_path(directory):
        if not os.path.isdir(directory):
            print(f"Creating new directory: {directory}")
            os.mkdir(directory)

        image_count = len(os.listdir(directory))

        if image_count > 0:
            print(f"Found {image_count} images in {directory}...")
        return image_count

    def generate_by_image(self, directory, prompt, image, guidance_scale=7.5, width=512, height=512, iterations=1):
        local_directory = f"images/{directory}"
        image_count = self.generate_path(local_directory)

        for index in range(iterations):
            name_index = image_count + index
            torch.manual_seed(torch.seed() + name_index)
            image = self.pipe(prompt=prompt, image=image, guidance_scale=guidance_scale, width=width, height=height).images[0]
            image.save(f"{local_directory}/{name_index:04}.png")
            print(f"Saved image: {name_index:04} Seed=[{torch.seed()}]")

    def generate_by_text(self, directory, prompt, guidance_scale=7.5, width=512, height=512, iterations=1):
        local_directory = f"images/{directory}"
        image_count = self.generate_path(local_directory)

        for index in range(iterations):
            name_index = image_count + index
            torch.manual_seed(torch.seed() + name_index)
            image = self.pipe(prompt=prompt, guidance_scale=guidance_scale, width=width, height=height).images[0]
            image.save(f"{local_directory}/{name_index:04}.png")
            print(f"Saved image: {name_index:04} Seed=[{torch.seed()}]")


from selenium import webdriver
import time
import math

"""

    Открыть страницу http://SunInJuly.github.io/execute_script.html.
    Считать значение для переменной x.
    Посчитать математическую функцию от x.
    Проскроллить страницу вниз.
    Ввести ответ в текстовое поле.
    Выбрать checkbox "I'm the robot".
    Переключить radiobutton "Robots rule!".
    Нажать на кнопку "Submit".
"""
def calc(x):
    """
    Вычисляет значение функции, заданной на странице
    Параметры:
        x - целое число, представленное строкой
    Возвращает:
        строку с вычисленным значением
    """
    return str(math.log(abs(12 * math.sin(int(x)))))

def scrollIntoView(element):
    """
    Скролит страницу так, чтобы переданный элемент был виден на экране
    """
    browser.execute_script("return arguments[0].scrollIntoView(true);", element)

link = "http://SunInJuly.github.io/execute_script.html"
try:
    browser = webdriver.Chrome()
    browser.get(link)
    x = browser.find_element_by_id("input_value").text
    input_box = browser.find_element_by_id("answer")
    # На всякий случай делаем его видимым
    scrollIntoView(input_box)
    input_box.send_keys(calc(x))
    chkboxRobot = browser.find_element_by_id("robotCheckbox")
    scrollIntoView(chkboxRobot)
    chkboxRobot.click()
    rdbRobot = browser.find_element_by_id("robotsRule")
    scrollIntoView(rdbRobot)
    rdbRobot.click()
    btn = browser.find_element_by_class_name("btn-primary")
    scrollIntoView(btn)
    btn.click()

finally:
    time.sleep(5)
    browser.quit()


import cli
from . import entities, customizer
import re
import sys
import pyinotify
import os
import warnings
import queue
import threading
import subprocess

class entname_t:
	"""Regular expression used to match against entity names"""
	def __init__(s, v):
		s.code = v
		try:
			s.expr = re.compile(v)
		except re.error as e:
			raise TypeError(f"not a valid filter: {v} ({e})")

vBuildCustomizer = cli.Variable(
  str, None, "C", "build-customizer",
  "Name of a customizer file from which multiple variants are built")
fBuildAll = cli.Flag("B", "build-all", "build all parts")
lBuildFilters = cli.VariableList(
  entname_t, "b", "build",
  "specify a filter for selecting parts. Processed as a regular expression. Multiple filters are or-ed together."
)

vBuildArrangement = cli.Variable(entname_t, None, "a", "arrange",
                                 "build an arrangement")
fViewArrangement = cli.Flag(
  "v", "view-arrangement",
  "run the arrangement (selected with -a) into a suitable viewer program")
fWatch = cli.Flag(
  "w", "watch",
  "keep running in the background and re-execute when files changed")

partsToBuild = set()
presetsToBuild = set()
arrangementToBuild = None

def filterEntities(typeFilter, nameFilters=None):
	ents = entities.getEntities()

	for k, v in ents.items():
		if not typeFilter(v.type): continue
		if nameFilters is None:
			yield v
		else:
			for nameFilter in nameFilters:
				if nameFilter.expr.match(k):
					yield v
					break

@cli.help_printer
def help_list_parts(f):

	ents = entities.getEntities()

	for (title, filter) in (
	  ("Parts", lambda v: (v.type is entities.part)),
	  ("Arrangements", lambda v: (v.type is entities.arrangement)),
	  ("Other entities", lambda v: not ((v.type is entities.part) or
	                                    (v.type is entities.arrangement))),
	):
		f.write(title + ":\n")

		count = 0

		for k, v in sorted(ents.items()):
			if not filter(v): continue
			count += 1
			if v.description is not None:
				f.write(f"  {k}:\n    {v.description}\n")
			else:
				f.write(f"  {k}\n")

@cli.check
def check_inputs():
	global partsToBuild, arrangementToBuild, presetsToBuild

	if True: # extract singular name of an arrangement to build
		if vBuildArrangement.value is not None:
			ents = list(
			  filterEntities(lambda t: t is entities.arrangement,
			                 [vBuildArrangement.value]))
			if len(ents) < 1:
				raise cli.clex(f"no arrangement matches {vBuildArrangement.value.code}")
			if len(ents) > 1:
				raise cli.clex(
				  f"ambiguous arrangement expression: {vBuildArrangement.value.code}")
			arrangementToBuild = ents[0]
		else:
			if fViewArrangement.value:
				raise cli.clex("-v is useless without -a")

	if True: # generate list of parts to build
		partsToBuildDict = dict()
		if fBuildAll:
			for part in filterEntities(lambda t: t is entities.part):
				partsToBuildDict[part.name] = part
		else:
			for part in filterEntities(lambda t: t is entities.part,
			                           lBuildFilters.values):
				partsToBuildDict[part.name] = part
		partsToBuild = list(partsToBuildDict.values())

	if True: # load customizer presets to build
		if vBuildCustomizer.value is not None:
			presetFile = customizer.PresetFile(vBuildCustomizer.value)
			for k, v in presetFile.presets.items():
				presetsToBuild.add((presetFile, k))
		else:
			presetsToBuild.add((None, None))

	if len(partsToBuild) < 1 and arrangementToBuild is None:
		raise cli.clex("nothing to do")

def climain():
	cli.process()

	global partsToBuild, arrangementToBuild, presetsToBuild

	viewer = None

	if arrangementToBuild is not None:
		res = entities.buildEntity(arrangementToBuild)
		if fViewArrangement.value:
			viewer = arrangementToBuild.process.watch(res)

	for presetFile, presetName in presetsToBuild:
		if presetFile is not None:
			presetFile.applyPreset(presetName)
		for part in partsToBuild:
			if presetName is not None:
				part = part.namedCopy(f"{part.name}-{presetName}")
			entities.buildEntity(part)

	if fWatch.value:

		# list files we need to watch for changes
		watchlist = list()
		mgr = pyinotify.WatchManager()
		for mod in sys.modules.values():
			if not hasattr(mod, "__file__"): continue
			if mod.__file__ is None: continue
			fn = os.path.realpath(mod.__file__)
			if not os.path.exists(fn):
				warnings.warn(
				  f"cannot watch for changes in module {mod.__name__}: file could not be located\n"
				)
				continue

			if not os.access(fn, os.W_OK): continue
			watchlist.append(fn)
			mgr.add_watch(fn, pyinotify.IN_MODIFY)

		new_cmdline = [sys.executable] + [
		  v for v in sys.argv
		  if v not in {"-w", "--watch", "-v", "--view-arrangement"}
		]

		# go multithreaded:
		#  - create and wait for viewer process (if an arrangement is created)
		#  - wait for modification notifications
		evq = queue.Queue()
		EV_MODIFY = 1
		EV_TERMINATE = 2

		class EventHandler(pyinotify.ProcessEvent):
			def process_IN_MODIFY(s, ev):
				evq.put(EV_MODIFY)

		def thrdf_viewer():

			# todo: get file name from actual method call above
			viewer.wait()
			evq.put(EV_TERMINATE)

		def thrdf_inotify():

			handler = EventHandler()
			notifier = pyinotify.Notifier(mgr, handler)
			notifier.loop()
			thrd_inotify = threading.Thread(target=notifier.loop)
			thrd_inotify.start()
			evq.put(EV_TERMINATE)

		if viewer is not None:
			threading.Thread(target=thrdf_viewer, daemon=True).start()
		threading.Thread(target=thrdf_inotify, daemon=True).start()

		# process events coming from threads above
		while True:
			ev = evq.get()
			if ev == EV_TERMINATE: break
			elif ev == EV_MODIFY:
				subprocess.run(new_cmdline)


from flask import render_template, request, Blueprint, flash, redirect, url_for

from app.models.turma import Turma, TurmaCreateForm, TurmaIndexForm, Status
from app.extensions import db
from app.utils import sql_date_format, sql_ilike_format, parse_date

turma_bp = Blueprint('turma', __name__)

@turma_bp.route('/', defaults={"page": 1})
@turma_bp.route('/<int:page>')
def index(page):
    page = page
    per_page = 10

    turma = TurmaIndexForm()
    turmas = Turma.query

    turma.descricao.data = request.args.get('descricao')
    turma.inicio.data = parse_date(request.args.get('inicio')) if request.args.get('inicio') else ''
    turma.fim.data = parse_date(request.args.get('fim')) if request.args.get('fim') else ''

    turmas = turmas.filter( Turma.descricao.ilike(sql_ilike_format(turma.descricao.data)) ) if turma.descricao.data else turmas
    turmas = turmas.filter( Turma.vencimento >= sql_date_format(turma.inicio.data) ) if turma.inicio.data else turmas
    turmas = turmas.filter( Turma.vencimento <= sql_date_format(turma.fim.data) ) if turma.fim.data else turmas

    turmas = turmas.order_by(Turma.codigo.desc()).paginate(page, per_page=per_page, error_out=True)

    return render_template('turmas/index.html', turmas=turmas, titulo_form=turma)

@turma_bp.route('/new', methods=['GET', 'POST'])
def new():
    titulo_form = TurmaCreateForm()

    if titulo_form.validate_on_submit():

        if titulo_form.codigo.data:
            turma = Turma.query.get_or_404( titulo_form.codigo.data )

            turma.descricao=titulo_form.descricao.data,
            turma.valor=titulo_form.valor.data,
            turma.vencimento=titulo_form.vencimento.data,
            turma.status=titulo_form.status.data
        else:
            turma = Turma(
                descricao=titulo_form.descricao.data,
                valor=titulo_form.valor.data,
                vencimento=titulo_form.vencimento.data,
                status=titulo_form.status.data
            )

        turma.save()

        flash('Titúlo salvo com sucesso!', 'success')

        return redirect(url_for('turma.new'))

    print('Turma errors: ' + str(titulo_form.errors))
    return render_template('turmas/new.html', turma=titulo_form)

@turma_bp.route('/edit/<int:titulo_id>')
def view(titulo_id):
    turma = Turma.query.get_or_404(titulo_id)
    titulo_form = TurmaCreateForm()

    titulo_form.from_model(turma)

    return render_template('turmas/new.html', turma=titulo_form)

@turma_bp.route('/delete/<int:titulo_id>', methods=['POST'])
def delete(titulo_id):
    turma = Turma.query.get_or_404(titulo_id)

    turma.delete()

    return redirect(url_for('turma.index'))


#!/usr/bin/python3
import requests
import argparse

NASAAPI = "https://api.nasa.gov/planetary/apod?"

def main():
    print(f"Welcome, {args.name}! Let's get crackin' with your API!")
    nasacreds = "api_key=" + args.key # API KEY GOES HERE
    url= NASAAPI + nasacreds
    print(url)
    apodresp = requests.get(url)
    apod = apodresp.json()

    print("YOUR IMAGE URL:", apod["url"])

# BEFORE MAIN RUNS
parser= argparse.ArgumentParser(description="Collects an API key to access a NASA API.")
            # ^ custom class object
            # creating an object that scoops up
            # our little --args at the command line

parser.add_argument("--name", help="The user's name", default="Slappy")
# teach our lil' parser object the different arguments that our code will take!
parser.add_argument("--key", required=True, help="NASA API key string")
                             # ^ you MUST use this arg!

# have the parser combine all those arguments into one object
args= parser.parse_args()

main()


import cv2
cv2.namedWindow('frame', flags=cv2.WINDOW_AUTOSIZE)
cam = cv2.VideoCapture(1)
while True:
    ret, frame = cam.read()
    frame = cv2.resize(frame, (1280, 720), interpolation=cv2.INTERSECT_PARTIAL)
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    for i in range(0,100):
        frame = cv2.putText(frame, '17.09.2023', (900+i, 700+i), cv2.FONT_ITALIC, 2, 0+i*2, 3)
    frame = cv2.putText(frame, '17.09.2023', (900, 700), cv2.FONT_ITALIC, 2, 255, 1)
    cv2.imshow('frame', frame)
    if cv2.waitKey(1) == ord('q'):
        break


from django.urls import path
from rest_framework_simplejwt.views import TokenObtainPairView

from base.views.user_views import (
    RegisterUserView,
    GetUserView,
    UserProfileView,
    UpdateUserProfileView,
    UpdateUserView,
    DeleteUserView,
    GetUserByIdView,
    CustomTokenObtainPairView
)

urlpatterns = [
    path('register/', RegisterUserView.as_view(), name='register'),
    path('login/', CustomTokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('users/', GetUserView.as_view(), name='get_users'),
    path('profile/<str:username>/', UserProfileView.as_view(), name='get_user_profile'),
    path('profile/update/', UpdateUserProfileView.as_view(), name='update_user_profile'),
    path('user/update/', UpdateUserView.as_view(), name='update_user'),
    path('user/delete/<int:pk>/', DeleteUserView.as_view(), name='delete_user'),
    path('user/<int:pk>/', GetUserByIdView.as_view(), name='get_user_by_id'),
]


import warnings
import weakref
import torch
import torch.distributed as dist
import torch.distributed.distributed_c10d as c10d
from typing import List, cast

"""
Moved eager kernel implementations to a separate file partly for readability and partly as it is currently
easier in dynamo to set tracing policy on a file-by-file level.

Do not put code in this file that Dynamo is expected to trace into, as dynamo may disallow this whole file.
"""

data_ptr_to_work = dict()
work_version = 0

class _WaitRegistration:
    def __init__(self, work):
        global work_version
        self.work = work
        self.version = work_version
        self.ptrs = []
        self.cleanup_count = 0
        work_version += 1

    def _register(self, tensor):
        global data_ptr_to_work
        ptr = tensor.data_ptr()
        data_ptr_to_work[ptr] = self
        self.ptrs.append(ptr)
        self.cleanup_count += 1

    def wait(self):
        if self.work is not None:
            self.work.wait()
            self.work = None
        self.cleanup()

    def decrement_live_tensor(self, ptr):
        self.cleanup_count -= 1
        if self.cleanup_count == 0:
            self.cleanup()
        else:
            if data_ptr_to_work.get(ptr, None) == self:
                del data_ptr_to_work[ptr]

    def cleanup(self):
        for ptr in self.ptrs:
            if data_ptr_to_work.get(ptr, None) == self:
                del data_ptr_to_work[ptr]

def _register_tensor_work(tensor_or_list, work_or_list):
    if not isinstance(tensor_or_list, list):
        tensor_or_list = [tensor_or_list]
    if not isinstance(work_or_list, list):
        reg = _WaitRegistration(work_or_list)
        for tensor in tensor_or_list:
            reg._register(tensor)
    else:
        for tensor, work in zip(tensor_or_list, work_or_list):
            reg = _WaitRegistration(work)
            reg._register(tensor)

def _wait_reg_dec(ptr, wait_reg):
    wait_reg.decrement_live_tensor(ptr)

def _register_wrapper_tensor(tensor_wrapper, tensor):
    global data_ptr_to_work
    # Note: we should NEVER try to trace this, bc it registers runtime stuff during trace.
    # Instead, backends must call this themselves when implementing traced collectives.
    wait_reg = data_ptr_to_work.get(tensor.data_ptr(), None)
    if wait_reg is None:
        warnings.warn(
            "Trying to register finalizers to AsyncCollectiveTensor but the inner tensor is already gone"
        )
    else:
        # We force the collective to be waited in the case this tensor goes away to reduce the change of deadlocks.
        weakref.finalize(tensor_wrapper, _wait_reg_dec, tensor.data_ptr(), wait_reg)

def _wait_tensor(tensor: torch.Tensor) -> torch.Tensor:
    global data_ptr_to_work
    data_ptr = tensor.data_ptr()
    wait_reg = data_ptr_to_work.get(data_ptr)
    if wait_reg is not None:
        wait_reg.wait()
    return tensor

def _str_to_reduce_op(reduceOp: str) -> dist.ReduceOp:
    reduceOp = reduceOp.upper()
    op = dist.ReduceOp.RedOpType.__members__.get(reduceOp)
    if op is None:
        raise ValueError(f"Invalid reduce operation {reduceOp}")
    return cast(dist.ReduceOp, op)

"""
Kernel implementations (for eager runtime only) - should never be traced by torch.compile

These functions should all be bound to dispatcher ops.  During tracing, the op itself should be
captured in the graph and the backend should implement the op however it prefers.
"""
# TODO assert if ranks has duplicated entries
def _all_reduce(self, reduceOp, tag, ranks, group_size):
    op = _str_to_reduce_op(reduceOp)
    group = c10d._find_or_create_pg_by_ranks_and_tag(tag, ranks, group_size)
    assert group is not None

    inplace_tensor = self.clone(memory_format=torch.contiguous_format)
    work = dist.all_reduce(inplace_tensor, op=op, group=group, async_op=True)
    _register_tensor_work(inplace_tensor, work)

    return inplace_tensor

def _all_reduce_coalesced(self, reduceOp, tag, ranks, group_size):
    op = _str_to_reduce_op(reduceOp)
    group = c10d._find_or_create_pg_by_ranks_and_tag(tag, ranks, group_size)
    assert group is not None

    inplace_tensor_list = [t.clone(memory_format=torch.contiguous_format) for t in self]
    work = dist.all_reduce_coalesced(inplace_tensor_list, op=op, group=group, async_op=True)
    _register_tensor_work(inplace_tensor_list, work)

    return inplace_tensor_list

def _all_gather_into_tensor(shard, tag, ranks, group_size):
    # TODO add dim support?
    group = c10d._find_or_create_pg_by_ranks_and_tag(tag, ranks, group_size)
    assert group is not None
    out_size = list(shard.size())
    out_size[0] *= group_size
    out_tensor = shard.new_empty(out_size)
    assert out_tensor.is_contiguous()
    # FIXME gloo doesn't support _allgather_base
    if dist.get_backend(group) == dist.Backend.GLOO or shard.is_cpu:
        tensor_list = list(torch.chunk(out_tensor, group_size))
        work = dist.all_gather(tensor_list, shard, group=group, async_op=True)
    else:
        work = dist.all_gather_into_tensor(out_tensor, shard, group=group, async_op=True)
    _register_tensor_work(out_tensor, work)

    return out_tensor

def _all_gather_into_tensor_coalesced(self, tag, rankset, group_size):
    group = c10d._find_or_create_pg_by_ranks_and_tag(tag, rankset, group_size)
    assert group is not None

    def mk_out_tensor(shard):
        out_size = list(shard.size())
        out_size[0] *= group_size
        out_tensor = shard.new_empty(out_size)
        assert out_tensor.is_contiguous()
        return out_tensor

    out_tensors = [mk_out_tensor(t) for t in self]

    work_list = _all_gather_into_tensor_coalesced_fallback(
        output_tensors=out_tensors,
        input_tensors=self,
        group=group,
        async_op=True)

    _register_tensor_work(out_tensors, work_list)
    return out_tensors

def _reduce_scatter_tensor(
    input: torch.Tensor,
    reduceOp: str,
    tag: str,
    ranks: List[int],
    group_size: int,
):
    # TODO add dim support?
    group = c10d._find_or_create_pg_by_ranks_and_tag(tag, ranks, group_size)
    assert group is not None
    op = _str_to_reduce_op(reduceOp)
    out_size = list(input.size())
    out_size[0] //= group_size
    out_tensor = input.new_empty(out_size)
    work = dist.reduce_scatter_tensor(
        out_tensor, input, op=op, group=group, async_op=True
    )
    _register_tensor_work(out_tensor, work)

    return out_tensor

def _reduce_scatter_tensor_coalesced(
    inputs: List[torch.Tensor],
    reduce_op: str,
    tag: str,
    ranks: List[int],
    group_size: int,
):
    group = c10d._find_or_create_pg_by_ranks_and_tag(tag, ranks, group_size)
    assert group is not None
    op = _str_to_reduce_op(reduce_op)

    def mk_out_tensor(shard):
        out_size = list(shard.size())
        out_size[0] //= group_size
        out_tensor = shard.new_empty(out_size)
        assert out_tensor.is_contiguous()
        return out_tensor

    out_tensors = [mk_out_tensor(t) for t in inputs]

    work_list = _reduce_scatter_tensor_coalesced_fallback(
        output_tensors=out_tensors,
        input_tensors=inputs,
        op=op,
        group=group,
        async_op=False)

    _register_tensor_work(out_tensors, work_list)
    return out_tensors

def _all_gather_into_tensor_coalesced_fallback(output_tensors, input_tensors, group, async_op=False):
    # all_gather_coalesced is useless, it doesn't work under NCCL and does lots of copies under Gloo
    # all_gather is useless too because it's single tensor
    # NCCL's PG::all_gather with multiple tensors is broken, it only works for the multi-device setting
    #  and fails if you mix same-size with different-size tensor lists.
    # _coalescing_manager crashed NCCL when used with all_gather_into_tensor.
    if input_tensors[0].is_cpu or not async_op:
        work_list = []
        out_tensors_sliced = [
            list(torch.chunk(out_tensor, dist.get_world_size(group)))
            for out_tensor in output_tensors
        ]
        for shard, out_tensor in zip(input_tensors, out_tensors_sliced):
            work = c10d.all_gather(out_tensor, shard, group=group, async_op=async_op)
            work_list.append(work)
        return work_list
    else:
        with c10d._coalescing_manager(group=group, async_ops=True) as cm:
            for in_t, out_t in zip(input_tensors, output_tensors):
                dist.all_gather_into_tensor(out_t, in_t, group=group, async_op=True)
        return cm

def _reduce_scatter_tensor_coalesced_fallback(output_tensors, input_tensors, op, group, async_op=False):
    # All the same reasons as the all_gather fallback
    work_list = []
    for shard, out_tensor in zip(input_tensors, output_tensors):
        work = c10d.reduce_scatter_tensor(out_tensor, shard, op=op, group=group, async_op=async_op)
        work_list.append(work)
    return work_list