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

from src.talentPlatform.unitSys.helper.InitConfig import *
import warnings
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib as mpl
import glob
import cfgrib
import pandas as pd
import numpy as np

warnings.filterwarnings("ignore")

plt.rc('font', family='Malgun Gothic')
plt.rc('axes', unicode_minus=False)
sns.set(font="Malgun Gothic", rc={"axes.unicode_minus":False}, style='darkgrid')

# 그래프에서 마이너스 글꼴 깨지는 문제에 대한 대처
mpl.rcParams['axes.unicode_minus'] = False

# =================================================
# Set Env
# =================================================
# 작업환경 경로 설정
contextPath = '/SYSTEMS/PROG/PYTHON/GRIB2'
prjName = 'test'
serviceName = 'LSH0175'

log = initLog(contextPath, prjName)
globalVar = initGlobalVar(contextPath, prjName)

# =================================================
# Option
# =================================================
inLat = 37.56083
inLon = 129.2172
inVars = ['shww', 'wvdir', 'pp1d', 'u', 'v']

# =================================================
# Main
# =================================================
try:
    log.info('[START] {}'.format('Main'))

    fileList = glob.glob('{}/{}'.format(globalVar['inpPath'], '*.gb2'))

    for fileInfo in fileList:
        log.info('[CHECK] fileInfo : {}'.format(fileInfo))

        ds = cfgrib.open_dataset(fileInfo)
        dtDateTime = pd.to_datetime(ds.time.values).strftime('%Y%m%d%H%M')
        log.info('[CHECK] ds : {}'.format(ds))

        for inVar in inVars:
          log.info('[CHECK] inVar : {}'.format(inVar))

          # 오랜 시간이 소요
          # df = ds[inVar].to_dataframe()
          # saveFile = '{}/{}_{}_{}_{}.csv'.format(globalVar['outPath'], serviceName, inVar, 'TOTAL_DATA', dtDateTime)
          # df.to_csv(saveFile, index=None)

          dataL2 = pd.DataFrame()
          for i in ds[inVar]:
            dtDateTimeFore = pd.to_datetime((ds.time + i.step).values).strftime('%Y%m%d%H%M')
            nearVal = np.nan_to_num(i.sel(latitude = inLat, longitude = inLon, method='nearest'))
            interpVal = np.nan_to_num(i.interp(latitude = inLat, longitude = inLon))

            dict = {
              'inVar': [inVar]
              , 'dtDateTime': [dtDateTime]
              , 'dtDateTimeFore': [dtDateTimeFore]
              , 'nearVal': [nearVal]
              , 'interpVal': [interpVal]
            }
            log.info('[CHECK] dict : {}'.format(dict))

            dataL2 = dataL2.append(pd.DataFrame.from_dict(dict))

          saveFile = '{}/{}_{}_{}_{}.csv'.format(globalVar['outPath'], serviceName, inVar, 'SEL_DATA', dtDateTime)
          dataL2.to_csv(saveFile, index=None)

except Exception as e:
    log.error("Exception : {}".format(e))
    # traceback.print_exc()
    # sys.exit(1)

finally:
    log.info('[END] {}'.format('Main'))


#!/usr/bin/env python
# coding: utf-8
"""Command line interface for Internetarchive-YouTube Sync."""

import argparse
import io
import json
import os
import random
import signal
import sys
from pathlib import Path

import requests
from dotenv import load_dotenv
from internetarchive_youtube.archive_youtube import ArchiveYouTube
from internetarchive_youtube.create_collection import CreateCollection

class TimeLimitReached(Exception):
    """Raised when the time limit is reached."""

def _alarm_handler(signum: int, _: object):
    """Signal handler for SIGALRM.

    Raises:
        TimeLimitReached: When the time limit is reached.
    """
    print('Signal handler called with signal:', signum)
    raise TimeLimitReached(
        'The GitHub action is about to die. Terminating the job safely...')

def _create_collection(no_logs: bool = False) -> None:
    """Creates a collection from the channels list.

    Args:
        no_logs: Whether to print logs.
    """
    channels = os.getenv('CHANNELS')
    if not channels:
        raise TypeError('`CHANNELS` cannot be empty!')

    if channels.startswith('http'):
        channels = requests.get(channels).text

    elif Path(channels).exists():
        with open(channels) as f:
            channels = f.read()

    try:
        channels = json.loads(channels).items()
    except json.decoder.JSONDecodeError:
        channels = [tuple(x.split(': ')) for x in channels.strip().split('\n')]

    random.shuffle(channels)

    for channel in channels:
        if not no_logs:
            print(f'Current channel: {channel}')
        cc = CreateCollection(channel[0], channel[1], no_logs=no_logs)
        _ = cc.create_collection()

def _opts() -> argparse.Namespace:
    """Parses the command line arguments."""
    parser = argparse.ArgumentParser()
    parser.add_argument('-p',
                        '--prioritize',
                        help='Comma-separated list of channel names to '
                        'prioritize when processing videos.',
                        type=str)
    parser.add_argument('-s',
                        '--skip-list',
                        help='Comma-separated list of channel names to skip.',
                        type=str)
    parser.add_argument('-f',
                        '--force-refresh',
                        help='Refresh the database after every video ('
                        'Can slow down the workflow significantly, but '
                        'is useful when running multiple concurrent jobs).',
                        action='store_true')
    parser.add_argument('-t',
                        '--timeout',
                        help='Kill the job after n hours (default: 5).',
                        type=float,
                        default=5)
    parser.add_argument('-n',
                        '--no-logs',
                        help='Don\'t print any log messages.',
                        action='store_true')
    parser.add_argument('-a',
                        '--add-channel',
                        help='Add a channel interactively to the list of '
                        'channels to archive.',
                        action='store_true')
    parser.add_argument('-c',
                        '--channels-file',
                        help='Path to the channels list file to use if the '
                        'environment variable `CHANNELS` is not set ('
                        'default: ~/.yt_channels.txt).',
                        type=str)
    parser.add_argument('-S',
                        '--show-channels',
                        help='Show the list of channels in the channels file.',
                        action='store_true')
    parser.add_argument('-C',
                        '--create-collection',
                        help='Creates/appends to the backend database from '
                        'the channels list.',
                        action='store_true')
    parser.add_argument(
        '-m',
        '--multithreading',
        help='Enables processing multiple videos concurrently.',
        action='store_true')
    parser.add_argument('-T',
                        '--threads',
                        help='Number of threads to use when multithreading is '
                        'enabled. Defaults to the optimal maximum number of '
                        'workers.',
                        type=int)
    parser.add_argument(
        '-k',
        '--keep-failed-uploads',
        help='Keep the files of failed uploads on the local disk.',
        action='store_true')
    parser.add_argument('-i',
                        '--ignore-video-ids',
                        help='Comma-separated list or a path to a file '
                        'containing a list of video ids to ignore.',
                        type=str)
    parser.add_argument('-A',
                        '--use-aria2c',
                        help='Use external downloader, aria2c '
                        '(can significantly speed up download).',
                        action='store_true')
    return parser.parse_args()

def main() -> None:
    """Main function."""
    load_dotenv()
    args = _opts()

    signal.signal(signal.SIGALRM, _alarm_handler)
    timeout = int(args.timeout * 3600)

    if args.create_collection:
        _create_collection(no_logs=args.no_logs)
        sys.exit(0)

    if not args.channels_file:
        args.channels_file = f'{Path.home()}/.yt_channels.txt'
        if not os.getenv('CHANNELS'):
            os.environ['CHANNELS'] = args.channels_file

    if args.show_channels:
        chs_file = Path(args.channels_file)
        print('-' * 80)
        if not os.getenv('CHANNELS'):
            if not chs_file.exists():
                print('Nothing to show. Add channels to the channels '
                      'file first!')
            else:
                with open(chs_file) as f:
                    print(f.read())
            return
        elif args.show_channels and os.getenv('CHANNELS'):
            if chs_file.exists():
                with open(chs_file) as f:
                    print(f.read())
            else:
                print(os.environ['CHANNELS'])
        print('-' * 80)
        if chs_file.exists():
            print(f'Channels list file path: {chs_file}')
        return

    if args.add_channel:
        if os.getenv('CHANNELS'):
            if not Path(os.environ['CHANNELS']).exists():
                raise TypeError(
                    'Environment variable `CHANNELS` is set, but is not a '
                    'file path! Can only add channels with `--add-channel` '
                    'if `CHANNELS` is a file path.')
        with open(args.channels_file, 'a+') as f:
            f.seek(0, 0)
            if f.read():
                f.seek(0, io.SEEK_END)
                f.write('\n')
            channel_name = input('Channel name: ').replace(' ', '_').strip('_')
            channel_url = input('Channel URL: ')
            f.write(f'{channel_name}: {channel_url}')
        return

    if Path(args.channels_file).exists() and not args.no_logs:
        print(f'Using channels list in: {args.channels_file}')

    if args.prioritize:
        args.prioritize = args.prioritize.split(',')
    if args.skip_list:
        args.skip_list = args.skip_list.split(',')
    if args.ignore_video_ids:
        if Path(args.ignore_video_ids).exists():
            with open(args.ignore_video_ids) as f:
                args.ignore_video_ids = f.read().strip()
        args.ignore_video_ids = args.ignore_video_ids.split(',')

    try:
        signal.alarm(timeout)
        ayt = ArchiveYouTube(prioritize=args.prioritize,
                             skip_list=args.skip_list,
                             force_refresh=args.force_refresh,
                             no_logs=args.no_logs,
                             multithreading=args.multithreading,
                             threads=args.threads,
                             keep_failed_uploads=args.keep_failed_uploads,
                             ignore_video_ids=args.ignore_video_ids,
                             use_aria2c=args.use_aria2c)
        ayt.run()
    except TimeLimitReached:
        return

if __name__ == '__main__':
    main()


import os, sys, gzip, random, json, datetime, re
import pandas as pd

dL = os.listdir(os.environ['LAV_DIR']+'/src/')
sys.path = list(set(sys.path + [os.environ['LAV_DIR']+'/src/'+x for x in dL]))
baseDir = os.environ['LAV_DIR']
import intertino.parser as pars

import importlib
importlib.reload(pars)

def conv_string(x):
    try: return float(x)
    except: return 0.

if False:
    """country code"""
    url = "https://www.countrycode.org/"
    couD = pars.parse_table(url,n_tab=0,render=True,isHead=True)
    couD.loc[:,"iso"] = couD['ISO CODES'].apply(lambda x: x[:2])
    couD.loc[:,"POPULATION"] = couD['POPULATION'].apply(lambda x: int(re.sub(",","",x)))
    couD.loc[:,"GDP"] = couD['GDP $USD'].apply(lambda x: x.split(" ")[0])
    couD.loc[:,"GDP_fact"] = 0.
    couD.loc[[bool(re.search("Trillion",x)) for x in couD['GDP $USD']],"GDP_fact"] = 1e12
    couD.loc[[bool(re.search("Billion",x)) for x in couD['GDP $USD']],"GDP_fact"] = 1e9
    couD.loc[[bool(re.search("Million",x)) for x in couD['GDP $USD']],"GDP_fact"] = 1e6
    couD.loc[[x == "" for x in couD['GDP']],"GDP"] = "0"
    couD.loc[:,"GDP"] = couD[['GDP','GDP_fact']].apply(lambda x: conv_string(x[0]) * x[1],axis=1)
    couD.drop(columns={"GDP_fact",'GDP $USD'},inplace=True)
    couD.loc[:,"AREA KM2"] = couD['AREA KM2'].apply(lambda x: conv_string(re.sub(",","",x)))
    couD.loc[:,"dens"] = couD['POPULATION']/couD['AREA KM2']
    couD.loc[:,"gdp_capita"] = couD['GDP']/couD['POPULATION']

    url = "https://developers.google.com/public-data/docs/canonical/countries_csv"
    cooD = pars.parse_tr(url,n_tab=0,render=True,isHead=True)
    couD = couD.merge(cooD,left_on="iso",right_on="country",how="left")
    couD.to_csv(baseDir + "geo/demo/country_demo.csv",index=False)

if False:
    """world population"""
    url = "https://www.worldometers.info/world-population/population-by-country/"
    invD = pars.parse_table(url,n_tab=0)
    invD.to_csv(baseDir + "geo/demo/pop_country.csv",index=False)

if False:
    """world population"""
    url = "https://www.worldometers.info/world-population/world-population-by-year/"
    invD = pars.parse_table(url,n_tab=0)
    invD.to_csv(baseDir + "geo/demo/pop_year.csv",index=False)

if False:
    """population density"""
    url = "https://en.wikipedia.org/wiki/List_of_countries_and_dependencies_by_population_density"
    invD = pars.parse_table(url,n_tab=0,render=True,isHead=False)
    invD.to_csv(baseDir + "geo/demo/pop_dens.csv",index=False)


#!/usr/bin/env python

# 1.load a dataset from a file
# 2."organize that file so we can access columns *or* rows of it easily
# 3.compute some "summary statistics" about the dataset
# 4.print those summary statistics

import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from argparse import ArgumentParser

hist_dir_path='./hist_fig/'
scatter_dir_path='./scatter_fig/'
corr_dir_path='./corr_fig/'

features_list = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO', 'BK', 'LSTAT', 'MEDV']
#load data

parser = ArgumentParser(description='A CVS reader + stats maker')
parser.add_argument('csvfile',
                    help='Path to the input csv file.')

parsed_args = parser.parse_args()

my_csv_file = parsed_args.csvfile

assert os.path.isfile(my_csv_file),"please give us a real file"
print('woot, the file exists')

data= pd.read_csv(my_csv_file, sep='\s+|,', header = None)
print(data.head())

print(data.shape)

#organize data
# 2A. ACCESS any row

print ("*Display the third and fourth rows*")
print (data.iloc[3:5,:]) # inclusive the first value 3 but exclusive the last value 5

# 2b access any column

print ("*Display the last two columns*")
print (data.iloc[:3,-2:]) #-2 the last two

# 2c access any value

print("*Display a specific value*")
print(data.iloc[3,4])

#compute summary statistics

print ("*Calculate mean*")
print (np.mean(data))
print ("*Calculate STD*")
print (np.std(data))

#D-Visualize the data, 1-feature (column) at a time

if not os.path.exists(hist_dir_path):
    os.makedirs(hist_dir_path)

sns.set() #for a nicer histogram

#loop on columns and generate histograms
for col in range(len(features_list)):

    df=(data.iloc[:,col])

    plt.figure()
    plt.hist(df, bins=20)
    plt.xlabel(features_list[col])
    plt.ylabel('occurrence')
    plt.title('Housing Data:{}'.format(features_list[col]))

    print ("Generating histogram file for {} in {} dir".format(features_list[col], hist_dir_path))

    plt.savefig('{}{}_hist.png'.format(hist_dir_path,features_list[col]))
    #plt.show() #we can uncomment to display all one by one
    plt.close() #avoid warnings

#E) Visualize the data, 2-features (columns) at a time

if not os.path.exists(scatter_dir_path):
    os.makedirs(scatter_dir_path)

#for col in range(len(features_list)):
for col1 in range(len(features_list)):
    df1=(data.iloc[:,col1])
    for col2 in range(len(features_list)):
        df2=(data.iloc[:,col2])
        if col1 != col2:
            #print ("{}/{}".format(features_list[col1],features_list[col2]))
            plt.figure()
            plt.scatter(df1,df2)
            plt.xlabel(features_list[col1])
            plt.ylabel(features_list[col2])
            plt.title('Housing Data:{}/{}'.format(features_list[col1], features_list[col2]))

            print ("Generating scatter file for {}/{} pair in {} dir".format(features_list[col1], features_list[col2], scatter_dir_path))

            plt.savefig('{}{}_{}_scatter.png'.format(scatter_dir_path,features_list[col1],features_list[col2]))
            #plt.show() #we can uncomment to display all one by one
            plt.close() #to avoid warnings

#F) Assign a header to a dataset

data_h= pd.read_csv(my_csv_file, sep='\s+|,', names = features_list)

print ("*Test dataset with header*")
print(data_h.head())

#G) Pseudocode for an additional type of plot: correlation matrix

if not os.path.exists(corr_dir_path):
    os.makedirs(corr_dir_path)

correlations = data.corr()
fig, ax = plt.subplots(figsize=(len(features_list), len(features_list)))
cax = ax.matshow(correlations, vmin=-1, vmax=1)
fig.colorbar(cax)

ax.set_xticks(range(0, len(features_list)))
ax.set_yticks(range(0, len(features_list)))

ax.set_xticklabels(features_list)
ax.set_yticklabels(features_list)

print ("Generating corrolation file for all features in {} dir".format(corr_dir_path))
plt.savefig('{}corrolation.png'.format(corr_dir_path))
#plt.show()
plt.close()


import matplotlib.pyplot as plt
import numpy as np

# Высота
H = 1.2
# Ширина
W = 1.0

N_X = 10  # Число узлов сетки по оси X
N_Y = 10  # Число узлов сетки по оси Y

def z2(x, y):
    return np.sqrt(x ** 2 + y ** 2)

f = lambda x: 0.1 + 2*(x - W/2)*(x - W/2)

x = np.linspace(0, W, N_X)
y = np.linspace(0, H, N_Y)

X, Y = np.meshgrid(x, y)

Y = Y*f(x)

Z = z2(X, Y)

# cетка
plt.plot(X, Y, marker=".", color='k', linestyle='none')

# на обычном  контурном графике
# plt.contour(X, Y, Z, colors='black')

plt.contourf(X, Y, Z, 20, cmap='viridis')
plt.colorbar()

plt.show()


import uuid
from corehq.form_processor.backends.sql.dbaccessors import ShardAccessor
from corehq.form_processor.tests.utils import only_run_with_partitioned_database
from corehq.messaging.scheduling.scheduling_partitioned.dbaccessors import (
    get_alert_schedule_instance,
    get_timed_schedule_instance,
    save_alert_schedule_instance,
    save_timed_schedule_instance,
    delete_alert_schedule_instance,
    delete_timed_schedule_instance,
    get_active_schedule_instance_ids,
    get_alert_schedule_instances_for_schedule,
    get_timed_schedule_instances_for_schedule,
)
from corehq.messaging.scheduling.models import (
    AlertSchedule,
    TimedSchedule,
)
from corehq.messaging.scheduling.scheduling_partitioned.models import (
    AlertScheduleInstance,
    TimedScheduleInstance,
)
from corehq.sql_db.config import plproxy_config
from corehq.sql_db.tests.utils import DefaultShardingTestConfigMixIn
from datetime import datetime, date
from django.test import TestCase

@only_run_with_partitioned_database
class BaseSchedulingPartitionedDBAccessorsTest(DefaultShardingTestConfigMixIn, TestCase):

    @classmethod
    def setUpClass(cls):
        super(BaseSchedulingPartitionedDBAccessorsTest, cls).setUpClass()
        cls.domain = 'scheduling-partitioned-models-test'

    @classmethod
    def make_alert_schedule_instance(cls, schedule_instance_id, schedule_id=None, active=True, domain=None):
        domain = domain or cls.domain
        return AlertScheduleInstance(
            schedule_instance_id=schedule_instance_id,
            domain=domain,
            recipient_type='CommCareUser',
            recipient_id=uuid.uuid4().hex,
            current_event_num=0,
            schedule_iteration_num=1,
            next_event_due=datetime(2017, 3, 1),
            active=active,
            alert_schedule_id=schedule_id or uuid.uuid4(),
        )

    @classmethod
    def make_timed_schedule_instance(cls, schedule_instance_id, schedule_id=None, active=True):
        return TimedScheduleInstance(
            schedule_instance_id=schedule_instance_id,
            domain=cls.domain,
            recipient_type='CommCareUser',
            recipient_id=uuid.uuid4().hex,
            current_event_num=0,
            schedule_iteration_num=1,
            next_event_due=datetime(2017, 3, 1),
            active=active,
            timed_schedule_id=schedule_id or uuid.uuid4(),
            start_date=date(2017, 3, 1),
        )

class TestSchedulingPartitionedDBAccessorsGetAndSave(BaseSchedulingPartitionedDBAccessorsTest):

    @classmethod
    def setUpClass(cls):
        super(TestSchedulingPartitionedDBAccessorsGetAndSave, cls).setUpClass()
        cls.p1_uuid = uuid.UUID('9d3a283a-25b6-4116-8846-d0fc8f04f50f')
        cls.p2_uuid = uuid.UUID('8440dbd6-61b1-4b2f-a310-7e1768902d04')

    def tearDown(self):
        for db in plproxy_config.form_processing_dbs:
            AlertScheduleInstance.objects.using(db).filter(domain=self.domain).delete()
            TimedScheduleInstance.objects.using(db).filter(domain=self.domain).delete()

    def test_uuids_used(self):
        self.assertEqual(ShardAccessor.get_database_for_doc(self.p1_uuid), self.db1)
        self.assertEqual(ShardAccessor.get_database_for_doc(self.p2_uuid), self.db2)

    def test_save_alert_schedule_instance(self):
        self.assertEqual(AlertScheduleInstance.objects.using(self.db1).count(), 0)
        self.assertEqual(AlertScheduleInstance.objects.using(self.db2).count(), 0)

        instance = self.make_alert_schedule_instance(self.p1_uuid)
        save_alert_schedule_instance(instance)

        self.assertEqual(AlertScheduleInstance.objects.using(self.db1).count(), 1)
        self.assertEqual(AlertScheduleInstance.objects.using(self.db2).count(), 0)

    def test_save_timed_schedule_instance(self):
        self.assertEqual(TimedScheduleInstance.objects.using(self.db1).count(), 0)
        self.assertEqual(TimedScheduleInstance.objects.using(self.db2).count(), 0)

        instance = self.make_timed_schedule_instance(self.p2_uuid)
        save_timed_schedule_instance(instance)

        self.assertEqual(TimedScheduleInstance.objects.using(self.db1).count(), 0)
        self.assertEqual(TimedScheduleInstance.objects.using(self.db2).count(), 1)

    def test_get_alert_schedule_instance(self):
        self.test_save_alert_schedule_instance()
        instance = get_alert_schedule_instance(self.p1_uuid)
        self.assertTrue(isinstance(instance, AlertScheduleInstance))
        self.assertEqual(instance.schedule_instance_id, self.p1_uuid)

        with self.assertRaises(AlertScheduleInstance.DoesNotExist):
            get_alert_schedule_instance(uuid.uuid4())

    def test_get_timed_schedule_instance(self):
        self.test_save_timed_schedule_instance()
        instance = get_timed_schedule_instance(self.p2_uuid)
        self.assertTrue(isinstance(instance, TimedScheduleInstance))
        self.assertEqual(instance.schedule_instance_id, self.p2_uuid)

        with self.assertRaises(TimedScheduleInstance.DoesNotExist):
            get_timed_schedule_instance(uuid.uuid4())

class TestSchedulingPartitionedDBAccessorsDeleteAndFilter(BaseSchedulingPartitionedDBAccessorsTest):

    @classmethod
    def setUpClass(cls):
        super(TestSchedulingPartitionedDBAccessorsDeleteAndFilter, cls).setUpClass()
        cls.schedule_id1 = uuid.uuid4()
        cls.schedule_id2 = uuid.uuid4()
        cls.p1_uuid1 = uuid.UUID('a1a387cf-b362-481c-9104-a5dfb5b5d28a')
        cls.p1_uuid2 = uuid.UUID('e5193227-a148-4389-97e7-14615bfa4fec')
        cls.p1_uuid3 = uuid.UUID('f69601d8-abf1-40dd-b7da-d8f072683b1f')
        cls.p2_uuid1 = uuid.UUID('b39e6293-6339-4ea3-b257-a31e776d46a4')
        cls.p2_uuid2 = uuid.UUID('f4cf6dc3-12e8-4811-a4ce-f5c80826818b')
        cls.p2_uuid3 = uuid.UUID('d7186c21-572c-4405-b05d-3280d476d001')

    def setUp(self):
        self.alert_instance1_p1 = self.make_alert_schedule_instance(self.p1_uuid1)
        save_alert_schedule_instance(self.alert_instance1_p1)

        self.alert_instance2_p2 = self.make_alert_schedule_instance(self.p2_uuid1, schedule_id=self.schedule_id1)
        save_alert_schedule_instance(self.alert_instance2_p2)

        self.alert_instance3_p1 = self.make_alert_schedule_instance(self.p1_uuid2, schedule_id=self.schedule_id1,
            active=False)
        save_alert_schedule_instance(self.alert_instance3_p1)

        self.timed_instance1_p2 = self.make_timed_schedule_instance(self.p2_uuid2)
        save_timed_schedule_instance(self.timed_instance1_p2)

        self.timed_instance2_p1 = self.make_timed_schedule_instance(self.p1_uuid3, schedule_id=self.schedule_id2)
        save_timed_schedule_instance(self.timed_instance2_p1)

        self.timed_instance3_p2 = self.make_timed_schedule_instance(self.p2_uuid3, schedule_id=self.schedule_id2,
            active=False)
        save_timed_schedule_instance(self.timed_instance3_p2)

    def tearDown(self):
        for db in plproxy_config.form_processing_dbs:
            AlertScheduleInstance.objects.using(db).filter(domain=self.domain).delete()
            TimedScheduleInstance.objects.using(db).filter(domain=self.domain).delete()

    def test_uuids_used(self):
        self.assertEqual(ShardAccessor.get_database_for_doc(self.p1_uuid1), self.db1)
        self.assertEqual(ShardAccessor.get_database_for_doc(self.p1_uuid2), self.db1)
        self.assertEqual(ShardAccessor.get_database_for_doc(self.p1_uuid3), self.db1)
        self.assertEqual(ShardAccessor.get_database_for_doc(self.p2_uuid1), self.db2)
        self.assertEqual(ShardAccessor.get_database_for_doc(self.p2_uuid2), self.db2)
        self.assertEqual(ShardAccessor.get_database_for_doc(self.p2_uuid3), self.db2)

    def test_delete_alert_schedule_instance(self):
        self.assertEqual(AlertScheduleInstance.objects.using(self.db1).count(), 2)
        self.assertEqual(AlertScheduleInstance.objects.using(self.db2).count(), 1)
        self.assertEqual(TimedScheduleInstance.objects.using(self.db1).count(), 1)
        self.assertEqual(TimedScheduleInstance.objects.using(self.db2).count(), 2)

        delete_alert_schedule_instance(self.alert_instance1_p1)
        self.assertEqual(AlertScheduleInstance.objects.using(self.db1).count(), 1)
        self.assertEqual(AlertScheduleInstance.objects.using(self.db2).count(), 1)
        self.assertEqual(TimedScheduleInstance.objects.using(self.db1).count(), 1)
        self.assertEqual(TimedScheduleInstance.objects.using(self.db2).count(), 2)

        with self.assertRaises(AlertScheduleInstance.DoesNotExist):
            get_alert_schedule_instance(self.p1_uuid1)

    def test_delete_timed_schedule_instance(self):
        self.assertEqual(AlertScheduleInstance.objects.using(self.db1).count(), 2)
        self.assertEqual(AlertScheduleInstance.objects.using(self.db2).count(), 1)
        self.assertEqual(TimedScheduleInstance.objects.using(self.db1).count(), 1)
        self.assertEqual(TimedScheduleInstance.objects.using(self.db2).count(), 2)

        delete_timed_schedule_instance(self.timed_instance1_p2)
        self.assertEqual(AlertScheduleInstance.objects.using(self.db1).count(), 2)
        self.assertEqual(AlertScheduleInstance.objects.using(self.db2).count(), 1)
        self.assertEqual(TimedScheduleInstance.objects.using(self.db1).count(), 1)
        self.assertEqual(TimedScheduleInstance.objects.using(self.db2).count(), 1)

        with self.assertRaises(TimedScheduleInstance.DoesNotExist):
            get_timed_schedule_instance(self.p2_uuid2)

    def test_get_active_alert_schedule_instance_ids(self):
        self.assertItemsEqual(
            get_active_schedule_instance_ids(
                AlertScheduleInstance,
                datetime(2017, 4, 1),
                due_after=datetime(2017, 2, 1),
            ),
            [
                (self.domain, self.alert_instance1_p1.schedule_instance_id,
                    self.alert_instance1_p1.next_event_due),
                (self.domain, self.alert_instance2_p2.schedule_instance_id,
                    self.alert_instance2_p2.next_event_due),
            ]
        )

        self.assertItemsEqual(
            get_active_schedule_instance_ids(
                AlertScheduleInstance,
                datetime(2016, 4, 1),
                due_after=datetime(2016, 2, 1),
            ),
            []
        )

    def test_get_active_timed_schedule_instance_ids(self):
        self.assertItemsEqual(
            get_active_schedule_instance_ids(
                TimedScheduleInstance,
                datetime(2017, 4, 1),
                due_after=datetime(2017, 2, 1),
            ),
            [
                (self.domain, self.timed_instance1_p2.schedule_instance_id,
                    self.timed_instance1_p2.next_event_due),
                (self.domain, self.timed_instance2_p1.schedule_instance_id,
                    self.timed_instance2_p1.next_event_due),
            ]
        )

        self.assertItemsEqual(
            get_active_schedule_instance_ids(
                TimedScheduleInstance,
                datetime(2016, 4, 1),
                due_after=datetime(2016, 2, 1),
            ),
            []
        )

    def test_get_alert_schedule_instances_for_schedule(self):
        self.assertItemsEqual(
            get_alert_schedule_instances_for_schedule(AlertSchedule(schedule_id=self.schedule_id1)),
            [self.alert_instance2_p2, self.alert_instance3_p1]
        )

    def test_get_timed_schedule_instances_for_schedule(self):
        self.assertItemsEqual(
            get_timed_schedule_instances_for_schedule(TimedSchedule(schedule_id=self.schedule_id2)),
            [self.timed_instance2_p1, self.timed_instance3_p2]
        )


#!/usr/bin/env python3

from Crypto.Cipher import AES
from enum import Enum, unique
from typing import List
import ctypes

class DecryptionError(Exception):
    pass

@unique
class MessageInterface(Enum):
    COMMS_INTERFACE_SERIAL = 0
    COMMS_INTERFACE_BLUETOOTH = 1
    COMMS_INTERFACE_GATT = 2
    COMMS_INTERFACE_LORA = 3
    COMMS_INTERFACE_LORAWAN = 4

    def __str__(self):
        to_string = {
            self.COMMS_INTERFACE_SERIAL : "serial",
            self.COMMS_INTERFACE_BLUETOOTH : "bt_adv",
            self.COMMS_INTERFACE_GATT : "bt_gatt",
            self.COMMS_INTERFACE_LORA : "LoRa",
            self.COMMS_INTERFACE_LORAWAN : "LoRaWAN",
        }
        return to_string[self]

@unique
class PayloadType(Enum):
    PAYLOAD_TDF3 = 0
    PAYLOAD_OTI = 1
    PAYLOAD_VTI = 2
    PAYLOAD_RPC = 3
    PAYLOAD_RPC_RSP = 4
    PAYLOAD_INCOMING = 5
    PAYLOAD_OUTGOING = 6

    PAYLOAD_ENC_TDF3 = 32
    PAYLOAD_ENC_OTI = 33
    PAYLOAD_ENC_VTI = 34
    PAYLOAD_ENC_RPC = 35
    PAYLOAD_ENC_RPC_RSP = 36

    PAYLOAD_CUSTOM = 255

    def __bytes__(self):
        return self.value.to_bytes(1, byteorder='little')

class Hop:

    class OutgoingRouteInfo(ctypes.LittleEndianStructure):
        _pack_ = 1
        _fields_ = [("address", 6 * ctypes.c_uint8), ("interface_channel", ctypes.c_uint8)]
    OUTGOING_SIZE = ctypes.sizeof(OutgoingRouteInfo)

    class IncomingRouteInfo(ctypes.LittleEndianStructure):
        _pack_ = 1
        _fields_ = [("address", 6 * ctypes.c_uint8), ("interface_channel", ctypes.c_uint8), ("packet_age", ctypes.c_uint16), ("sequence", ctypes.c_uint8), ("rssi", ctypes.c_uint8)]
    INCOMING_SIZE = ctypes.sizeof(IncomingRouteInfo)

    def __init__(self, address: int, interface: MessageInterface, channel: str):
        self._address = address
        self._address_fmt = "00:00"
        self._interface = interface
        self._channel = channel
        self.__rssi = 0
        self._packet_age = 0
        self._sequence_number = 0
        self._metadata = False

    def apply_metadata(self, packet_age: int, sequence_number: int, rssi: int):
        self._packet_age = packet_age
        self._sequence_number = sequence_number
        self._rssi = rssi
        self._metadata = True

    def __bytes__(self):
        interface_channel = (self._interface.value << 4) | (0)
        address = (ctypes.c_ubyte* 6)(*self._address.to_bytes(6, byteorder='little'))
        if self._metadata:
            route_c =  self.IncomingRouteInfo( address, interface_channel, self._packet_age, self._sequence_number, 30 - self._rssi)
        else:
            route_c =  self.OutgoingRouteInfo( address, interface_channel)
        return bytes(route_c)

    def update_address(self, address: int):
        self._address = address

    @property
    def address(self):
        return self._address

    @property
    def address_fmt(self):
        return "{:02X}:{:02X}:{:02X}:{:02X}:{:02X}:{:02X}".format(*bytearray(self._address.to_bytes(6, byteorder='big')))

    @property
    def interface(self):
        return self._interface

    @property
    def rssi(self):
        return self._rssi

    @classmethod
    def from_bytes(cls, byte_buffer : bytes):
        hop_c = cls.IncomingRouteInfo.from_buffer_copy(byte_buffer)
        address = int.from_bytes(bytes(hop_c.address), byteorder='little')
        try:
            route = cls(address, MessageInterface(hop_c.interface_channel >> 4), "default" )
        except ValueError as e:
            print("Bad Packet: " + " ".join([hex(b) for b in byte_buffer]))
            raise e
        route.apply_metadata(hop_c.packet_age, hop_c.sequence, 30 - hop_c.rssi)
        return route

class PacpPacket:

    class Payload:
        def __init__(self, payload_type: PayloadType, last_hop: Hop, payload: bytes):
            self._type = payload_type
            self._hop = last_hop
            self._payload = payload

        def __bytes__(self):
            payload =  bytes(self._type) + bytes(self._hop) + self._payload
            return (1 + len(payload)).to_bytes(1, byteorder='little') + payload

    PayloadList = List[Payload]
    HopList = List[Hop]

    def __init__(self, common_route: HopList, payloads: PayloadList):
        self._payloads = payloads
        self._common_route = common_route

    def __bytes__(self):
        hops_hdr = (len(self._common_route) + 1).to_bytes(1, byteorder='little')
        common_route = b"".join(bytes(r) for r in self._common_route)
        payloads = b"".join(bytes(p) for p in self._payloads)
        return hops_hdr + common_route + payloads

    def set_common_route(self, value: HopList):
        self._common_route = value

    def iter_payloads(self):
        for payload in self._payloads:
            complete_route = [*self._common_route, payload._hop]
            yield payload._type, complete_route, payload._payload

    @staticmethod
    def decrypt(route : HopList, encrypted_payload : bytes, key : bytes):
        original_hop = route[-1]
        original_addr = original_hop.address
        decrypted = b""

        if original_hop.interface == MessageInterface.COMMS_INTERFACE_BLUETOOTH:
            # Attempt to decode
            addr_bytes = int.to_bytes(original_addr, 6, 'little')
            init_vector = addr_bytes[:3] + 13 * b"\x00"
            decrypted_payload = b""
            decrypted_address = None

            if len(encrypted_payload) % 16 != 0:
                raise DecryptionError

            for _ in range(len(encrypted_payload) // 16):
                cipher = AES.new(key, AES.MODE_CBC, init_vector)
                decrypted = cipher.decrypt(encrypted_payload)
                decrypted_oui = decrypted[:3]

                # Validate decrypted payload [CSIRO, MINEW]
                valid_ouis = [b"\x90\x97\xd8", b"\x3F\x23\xAC"]
                if not decrypted_oui in valid_ouis:
                    raise DecryptionError

                decrypted_payload += decrypted[3:]

                if decrypted_address is None:
                    # Set the  decrypted address on the first iteration
                    decrypted_address = addr_bytes[:3] + decrypted[:3]
                else:
                    # All other addresses should match the first address
                    if addr_bytes[:3] + decrypted[:3] != decrypted_address:
                        raise DecryptionError
            # Update the routing information
            address_fixed = int.from_bytes(decrypted_address, 'little')
            route[-1].update_address(address_fixed)
        else:
            raise NotImplementedError

        return route, decrypted_payload

    @classmethod
    def from_bytes(cls, packet_type: PayloadType, address: int, byte_buffer : bytes):
        if packet_type == PayloadType.PAYLOAD_INCOMING:
            # Payloads are prepended by route information
            num_hops = int(byte_buffer[0])
            byte_buffer = byte_buffer[1:]

            common_route = []
            # Extract common hops
            for n in range(num_hops - 1):
                hop_bytes = byte_buffer[n*Hop.INCOMING_SIZE: (n + 1)* Hop.INCOMING_SIZE]
                common_route.append(Hop.from_bytes(hop_bytes))
            byte_buffer = byte_buffer[(num_hops - 1)*Hop.INCOMING_SIZE:]
            # Extract individual payloads
            payloads = []
            while len(byte_buffer) > 0:
                payload_size = int(byte_buffer[0])
                payload_type = PayloadType(int(byte_buffer[1]))
                hop = Hop.from_bytes(byte_buffer[2:2+Hop.INCOMING_SIZE])
                payloads.append(cls.Payload(payload_type, hop, byte_buffer[2+Hop.INCOMING_SIZE:payload_size]))
                byte_buffer = byte_buffer[payload_size:]
            packet = cls(common_route, payloads)
        elif packet_type == PayloadType.PAYLOAD_OUTGOING:
            raise NotImplementedError
        else:
            # The bytes directly represent one of the payload types
            # There is no routing info, so construct dummy info based on the fact this packet must have come from serial node
            hop = Hop(address, MessageInterface.COMMS_INTERFACE_SERIAL, "default")
            hop.apply_metadata(0, 0, 30)
            payload = cls.Payload(packet_type, hop, byte_buffer)
            packet = cls([], [payload])
        return packet

if __name__ == '__main__':

    hop1 = Hop(10, MessageInterface.COMMS_INTERFACE_BLUETOOTH, "default")
    hop2 = Hop(10, MessageInterface.COMMS_INTERFACE_BLUETOOTH, "default")
    hop3 = Hop(10, MessageInterface.COMMS_INTERFACE_BLUETOOTH, "default")

    payload1 = PacpPacket.Payload(PayloadType.PAYLOAD_TDF3, hop1, b"\x00\x11\x22")
    payload2 = PacpPacket.Payload(PayloadType.PAYLOAD_TDF3, hop2, b"\x00\x11\x33")
    packet = PacpPacket([hop3], [payload1, payload2])

    int(b"\x33")

    for t, r, p in packet.iter_payloads():
        print(t, r, p)


import re
from tkinter.filedialog import askopenfilename
import threading
from ast import literal_eval
from time import time, sleep

from exploration import Exploration
from fastest_path import *
from connection_client import Sender

class Controller:
    def __init__(self, sim):
        self._is_sim = sim

        if self._is_sim:
            print('sim run')
            import tkinter as tk
            import GUI
            root = tk.Tk()
            self._gui = GUI.Window(root)
            self._gui.mainloop()
            from simulator import Robot
            self._robot = Robot(exploration_status=[[0] * 15 for _ in range(20)],
                                facing=NORTH,
                                discovered_map=[[2] * 15 for _ in range(20)],
                                real_map=[[]])
        else:
            print('real run')
            self._explore_limit = 100.0
            self._time_limit = 720
            from robot import Robot
            self._robot = Robot(exploration_status=[[0] * 15 for _ in range(20)],
                                facing=NORTH,
                                discovered_map=[[2] * 15 for _ in range(20)])
        self._sender = Sender(self._msg_handler)
        self._auto_update = True
        enable_print()
        print('init complete!')
        disable_print()
        try:
            import winsound
            frequency = 2500
            duration = 250
            winsound.Beep(frequency, duration)
            winsound.Beep(frequency, duration)
        except ImportError:
            enable_print()
            print('beep')
            disable_print()

    def _msg_handler(self, msg):
        if msg == "ca":
            thread = threading.Thread(target=self._calibrate)
            thread.daemon = True
            thread.start()
        elif msg == "be":
            thread = threading.Thread(target=self._explore)
            thread.daemon = True
            thread.start()
        elif msg == "au":
            self._auto_update = True
        elif msg == "mu":
            self._auto_update = False
            self._update_android(True, True, override=True)
        elif msg[0:8] == "waypoint":
            self._set_way_point(msg[9:])
        elif msg == "bf":
            thread = threading.Thread(target=self._move_fastest_path)
            thread.daemon = True
            thread.start()
        elif msg == "st":
            sleep(0.05)
        elif msg == "w":
            self._sender.send_arduino('w')
        elif msg == "a":
            self._sender.send_arduino('a')
        elif msg == "d":
            self._sender.send_arduino('d')
        elif msg == "s":
            self._sender.send_arduino('s')
        elif msg == "o":
            self._sender.send_arduino('g')

    def _set_way_point(self, coordinate):
        (col, row) = literal_eval(coordinate)
        self._way_point = (row, col)

    def _calibrate(self):
        if not self._is_sim:
            self._sender.send_android('{"status":"calibrating"}')
            self._sender.send_arduino('z')
            self._sender.wait_arduino('D')
            self._robot.turn_robot(self._sender, RIGHT)
            self._robot.get_sensor_readings(self._sender)
            self._robot.turn_robot(self._sender, LEFT)
            self._sender.send_arduino('z')
            self._sender.wait_arduino('D')
        self._sender.send_android('{"status":"calibrating done"}')

    def _update_map_android(self):
        self._sender.send_android('{"exploreMap":"%s"}' % self._robot.get_explore_string())
        self._sender.send_android('{"obstacleMap":"%s"}' % self._robot.get_map_string())

    def _update_coords_android(self):
        y, x = get_coordinates(self._robot.center)
        self._sender.send_android('{"robotPosition":[%s,%s,%s]}' % (str(x), str(y), str(self._robot.facing)))

    def _update_android(self, is_update_map, is_update_coords, override=False):
        if self._auto_update or override:
            if is_update_map:
                self._update_map_android()
            if is_update_coords:
                self._update_coords_android()

    def _explore(self):
        start_time = time()

        exploration = Exploration(self._robot, start_time, self._explore_limit, self._time_limit)

        if self._is_sim:
            run = exploration.start_real_simulation()
        else:
            run = exploration.start_real(self._sender)

        next(run)
        self._update_android(True, True)
        while True:
            try:
                # Exploration until completion

                while True:
                    run.send(0)
                    self._update_android(True, True)

                    run.send(0)
                    if self._is_sim:
                        sleep(1)

                    self._update_android(True, True)

                    is_complete = run.send(0)
                    if is_complete:
                        break

                    is_looped = run.send(0)
                    if is_looped:
                        while True:
                            updated_or_moved, value, is_complete = run.send(0)
                            if self._is_sim:
                                sleep(1)
                            if updated_or_moved == "updated" or updated_or_moved == "moved":
                                self._update_android(True, True)
                                if updated_or_moved == "updated":
                                    self._gui.update_cells(value)
                                elif updated_or_moved == "moved":
                                    self._gui.move_robot(value)
                            else:
                                break

                            if is_complete:
                                break
                        break

                # Returning to start after completion
                while True:
                    run.send(0)
                    if self._is_sim:
                        sleep(1)

                    self._update_android(True, True)

            except StopIteration:
                if not self._is_sim:
                    enable_print()
                    print('EXPLORE_STR:', self._robot.get_explore_string())
                    print('MAP_STR:', self._robot.get_map_string())
                    disable_print()
                    print('Returned to start!')
                    self._sender.send_arduino('j')
                    self._sender.wait_arduino('U')
                    if self._robot.facing == WEST:
                        print('ENTERED FACING WEST')
                        sleep(0.05)
                        self._robot.turn_robot(self._sender, LEFT)
                        self._sender.send_arduino('j')
                        self._sender.wait_arduino('U')
                        self._robot.turn_robot(self._sender, RIGHT)
                        sleep(0.05)
                        self._robot.turn_robot(self._sender, RIGHT)
                        sleep(0.05)
                        self._sender.send_arduino('x')
                        self._sender.wait_arduino('D')
                    elif self._robot.facing == SOUTH:
                        print('ENTERED FACING SOUTH')
                        sleep(0.05)
                        self._robot.turn_robot(self._sender, RIGHT)
                        self._sender.send_arduino('j')
                        self._sender.wait_arduino('U')
                        sleep(0.05)
                        self._robot.turn_robot(self._sender, RIGHT)
                        sleep(0.05)
                        self._sender.send_arduino('x')
                        self._sender.wait_arduino('D')
                break

        print('Calibrating...')
        self._calibrate_after_exploration()

    def _calibrate_after_exploration(self):
        self._fastest_path = self._find_fastest_path()

        if self._is_sim:
            sleep(1)
            self._robot.turn_robot(self._fastest_path[0])
        else:
            self._robot.turn_robot(self._sender, self._fastest_path[0])
        self._fastest_path[0] = FORWARD
        self._update_android(True, True)
        self._sender.send_android('{"status":"explore done"}')
        self._sender.send_android('{"status":"calibrating done"}')

    def _find_fastest_path(self):
        """Calculate and return the set of moves required for the fastest path."""
        from simulator import Robot
        clone_robot = Robot(exploration_status=self._robot.exploration_status,
                            facing=self._robot.facing,
                            discovered_map=self._robot.discovered_map,
                            real_map=[[0] * 15 for _ in range(20)])

        fastest_path_start_way_point = get_shortest_path_moves(clone_robot,
                                                               start=(1, 1),
                                                               goal=self._way_point)

        if fastest_path_start_way_point:
            for move in fastest_path_start_way_point:
                clone_robot.move_robot(move)

        before_way_point = previous_cell(clone_robot.center, clone_robot.facing)

        fastest_path_way_point_goal = get_shortest_path_moves(clone_robot,
                                                              start=self._way_point,
                                                              goal=(18, 13),
                                                              before_start_point=before_way_point)

        return fastest_path_start_way_point + fastest_path_way_point_goal

    def _move_fastest_path(self):
        if self._fastest_path:
            if self._is_sim:
                for move in self._fastest_path:
                    if self._is_sim:
                        sleep(1)

                    self._robot.move_robot(move)
                    self._update_android(True, True)
            else:
                move_str = get_fastest_path_move_string(self._fastest_path)
                moves = move_str.split('/')
                for move in moves:
                    move_len = len(move)
                    if move[0] == 'n':
                        move = move[:-1] + 't'
                    elif move[0] == 'a' or move[0] == 'd':
                        pass
                    self._sender.send_arduino(move)
                    for i in range(move_len):
                        self._sender.wait_arduino('M')
        else:
            print("No valid path")


from datetime import date
from typing import Set

from fastapi import APIRouter, BackgroundTasks, status
from myapp.common.constants import MY_VAR
from myapp.configs import app_config
from myapp.controllers import fooController
from pandas import Timestamp
from pydantic import BaseModel, Field, validator

api_router = APIRouter()

class FooControllerModel(BaseModel):
    name: str

    @validator("name")
    @classmethod
    def is_valid_fab(cls, name: str):
        if not name:
            raise ValueError(f"'{name}' is not a valid name value")
        return name

def foo_execute(model: FooControllerModel):
    fooController.exec(
        name = model.name
    )

@api_router.post(
    "/foo_hello",
    status_code = status.HTTP_201_CREATED,
)
async def foo_endpoint(
    model: FooControllerModel,
    background_tasks: BackgroundTasks,
):
    background_tasks.add_task(foo_execute, model = model)
    return "job_created"


import csv
import logging
from pathlib import Path

from django.core.management.base import BaseCommand, CommandError

from apps.doctors.models import Doctor

logger = logging.getLogger(__name__)

class Command(BaseCommand):
    help = "Load Doctors from CSV file"

    def handle(self, *args, **options):
        logger.info("Loading doctors from CSV file")
        if Doctor.objects.count() > 0:
            logger.info("Doctors already loaded. Aborting.")
            return

        try:
            document = (
                Path(__file__).resolve().parent.parent.parent.parent.parent
                / "data"
                / "doctors-data.csv"
            )
            with open(document) as file:
                reader = csv.reader(file)
                next(reader)

                for row in reader:
                    Doctor.objects.create(
                        first_name=row[1],
                        last_name=row[2],
                        email=row[3],
                        specialty=row[4],
                        phone=row[5],
                        medical_code=row[6],
                        years_of_experience=row[7],
                    )

            logger.info("Doctors loaded")
        except Exception as e:
            logger.error(e)
            raise CommandError("Failed to load doctors")


from collections import namedtuple

from django.urls import reverse
from django.utils.translation import gettext as _
from django.utils.translation import gettext_noop

from corehq import privileges
from corehq.apps.accounting.utils import domain_has_privilege

LandingPage = namedtuple('LandingPage', ['id', 'name', 'urlname'])

ALL_LANDING_PAGES = (
    LandingPage('dashboard', gettext_noop('Dashboard'), 'dashboard_default'),
    LandingPage('webapps', gettext_noop('Web Apps'), 'formplayer_main'),
    LandingPage('reports', gettext_noop('Reports'), 'reports_home'),
    # Pro plan only:
    LandingPage(
        'downloads',
        gettext_noop('Data File Downloads'),
        'download_data_files',
    ),
)

def get_allowed_landing_pages(domain):
    if domain_has_privilege(domain, privileges.DATA_FILE_DOWNLOAD):
        return ALL_LANDING_PAGES
    return [page for page in ALL_LANDING_PAGES if page.id != 'downloads']

def validate_landing_page(domain, landing_page_id):
    allowed_ids = {page.id for page in get_allowed_landing_pages(domain)}
    if landing_page_id not in allowed_ids:
        raise ValueError(_("No landing page found with ID '{}'").format(landing_page_id))

def get_landing_page(domain, landing_page_id):
    for landing_page in get_allowed_landing_pages(domain):
        if landing_page.id == landing_page_id:
            return landing_page
    raise ValueError(_("No landing page found with id {page_id}").format(page_id=landing_page_id))

def get_redirect_url(landing_page_id, domain):
    page = get_landing_page(domain, landing_page_id)
    return reverse(page.urlname, args=[domain])


from my_funcs.Pytest_1 import division
import pytest

@pytest.mark.parametrize("a, b , expected_result",
                         [(10, 2, 5), (20, 10, 2), (30, -3, -10), (5, 2, 2.5)])  # декоратор для 4 тестов
def test_division_good(a, b, expected_result):
    assert division(a, b) == expected_result  # функция assert проверяет истинность выражения

# def test_division_one_more():
#     assert division(10, 5) == 2
@pytest.mark.parametrize("expected_exception, divider, divisionable", [(ZeroDivisionError, 0, 10),
                                                         (TypeError, "2", 20)])
def test_division_with_error(expected_exception, divider, divisionable):
    with pytest.raises(expected_exception):
        division(divisionable, divider)

# def test_type_error():
#     with pytest.raises(TypeError):
#         division(10, "2")


from selenium.webdriver import Chrome
from selenium.webdriver.support.select import Select

# TestCase(https://www.thetestingworld.com/testings/)
# Step 1: Open Browser
path="C:\\Users\\Cryst\\Downloads\\chromedriver_win32\\chromedriver.exe"
driver = Chrome(executable_path=path)

# Step 2: Enter URL
driver.get("http://www.theTestingWorld.com/testings")

# Step 3: Maximize browser
driver.maximize_window()

# Fetching Element Text
print("Text on Link is : " + driver.find_element_by_class_name("displayPopup").text)

# Fetching attribute value of Element
print("Value of Button is " + driver.find_element_by_xpath(("//input[@type='submit']")).get_attribute("value"))


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
import datetime

class Migration(migrations.Migration):

    dependencies = [
        ('training', '0004_auto_20150812_2141'),
    ]

    operations = [
        migrations.CreateModel(
            name='Resource',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(unique=True, max_length=128)),
                ('upload', models.FileField(null=True, upload_to=b'resources/', blank=True)),
                ('URL', models.URLField(blank=True)),
                ('element', models.ForeignKey(to='training.Element')),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Resource_Type',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(unique=True, max_length=128)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.AddField(
            model_name='resource',
            name='resource_type',
            field=models.ForeignKey(to='training.Resource_Type'),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='assessment',
            name='deadline',
            field=models.DateTimeField(default=datetime.datetime(2015, 8, 12, 22, 7, 32, 566622)),
        ),
    ]


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os

import pytest

pytestmark = pytest.mark.pytester_example_path("deprecated")

@pytest.mark.filterwarnings("default")
def test_yield_tests_deprecation(testdir):
    testdir.makepyfile(
        """
        def func1(arg, arg2):
            assert arg == arg2
        def test_gen():
            yield "m1", func1, 15, 3*5
            yield "m2", func1, 42, 6*7
        def test_gen2():
            for k in range(10):
                yield func1, 1, 1
    """
    )
    result = testdir.runpytest()
    result.stdout.fnmatch_lines(
        [
            "*test_yield_tests_deprecation.py:3:*yield tests are deprecated*",
            "*test_yield_tests_deprecation.py:6:*yield tests are deprecated*",
            "*2 passed*",
        ]
    )
    assert result.stdout.str().count("yield tests are deprecated") == 2

def test_compat_properties_deprecation(testdir):
    testdir.makepyfile(
        """
        def test_foo(request):
            print(request.node.Module)
    """
    )
    result = testdir.runpytest()
    result.stdout.fnmatch_lines(
        [
            "*test_compat_properties_deprecation.py:2:*usage of Function.Module is deprecated, "
            "please use pytest.Module instead*",
            "*1 passed, 1 warnings in*",
        ]
    )

def test_cached_setup_deprecation(testdir):
    testdir.makepyfile(
        """
        import pytest
        @pytest.fixture
        def fix(request):
            return request.cached_setup(lambda: 1)

        def test_foo(fix):
            assert fix == 1
    """
    )
    result = testdir.runpytest()
    result.stdout.fnmatch_lines(
        [
            "*test_cached_setup_deprecation.py:4:*cached_setup is deprecated*",
            "*1 passed, 1 warnings in*",
        ]
    )

def test_custom_class_deprecation(testdir):
    testdir.makeconftest(
        """
        import pytest

        class MyModule(pytest.Module):

            class Class(pytest.Class):
                pass

        def pytest_pycollect_makemodule(path, parent):
            return MyModule(path, parent)
    """
    )
    testdir.makepyfile(
        """
        class Test:
            def test_foo(self):
                pass
    """
    )
    result = testdir.runpytest()
    result.stdout.fnmatch_lines(
        [
            '*test_custom_class_deprecation.py:1:*"Class" objects in collectors of type "MyModule*',
            "*1 passed, 1 warnings in*",
        ]
    )

@pytest.mark.filterwarnings("default")
def test_funcarg_prefix_deprecation(testdir):
    testdir.makepyfile(
        """
        def pytest_funcarg__value():
            return 10

        def test_funcarg_prefix(value):
            assert value == 10
    """
    )
    result = testdir.runpytest("-ra")
    result.stdout.fnmatch_lines(
        [
            (
                "*test_funcarg_prefix_deprecation.py:1: *pytest_funcarg__value: "
                'declaring fixtures using "pytest_funcarg__" prefix is deprecated*'
            ),
            "*1 passed*",
        ]
    )

@pytest.mark.filterwarnings("default")
def test_pytest_setup_cfg_deprecated(testdir):
    testdir.makefile(
        ".cfg",
        setup="""
        [pytest]
        addopts = --verbose
    """,
    )
    result = testdir.runpytest()
    result.stdout.fnmatch_lines(
        ["*pytest*section in setup.cfg files is deprecated*use*tool:pytest*instead*"]
    )

@pytest.mark.filterwarnings("default")
def test_pytest_custom_cfg_deprecated(testdir):
    testdir.makefile(
        ".cfg",
        custom="""
        [pytest]
        addopts = --verbose
    """,
    )
    result = testdir.runpytest("-c", "custom.cfg")
    result.stdout.fnmatch_lines(
        ["*pytest*section in custom.cfg files is deprecated*use*tool:pytest*instead*"]
    )

def test_str_args_deprecated(tmpdir):
    """Deprecate passing strings to pytest.main(). Scheduled for removal in pytest-4.0."""
    from _pytest.main import EXIT_NOTESTSCOLLECTED

    warnings = []

    class Collect(object):
        def pytest_warning_captured(self, warning_message):
            warnings.append(str(warning_message.message))

    ret = pytest.main("%s -x" % tmpdir, plugins=[Collect()])
    msg = (
        "passing a string to pytest.main() is deprecated, "
        "pass a list of arguments instead."
    )
    assert msg in warnings
    assert ret == EXIT_NOTESTSCOLLECTED

def test_getfuncargvalue_is_deprecated(request):
    pytest.deprecated_call(request.getfuncargvalue, "tmpdir")

@pytest.mark.filterwarnings("default")
def test_resultlog_is_deprecated(testdir):
    result = testdir.runpytest("--help")
    result.stdout.fnmatch_lines(["*DEPRECATED path for machine-readable result log*"])

    testdir.makepyfile(
        """
        def test():
            pass
    """
    )
    result = testdir.runpytest("--result-log=%s" % testdir.tmpdir.join("result.log"))
    result.stdout.fnmatch_lines(
        [
            "*--result-log is deprecated and scheduled for removal in pytest 4.0*",
            "*See https://docs.pytest.org/en/latest/usage.html#creating-resultlog-format-files for more information*",
        ]
    )

@pytest.mark.filterwarnings("always:Metafunc.addcall is deprecated")
def test_metafunc_addcall_deprecated(testdir):
    testdir.makepyfile(
        """
        def pytest_generate_tests(metafunc):
            metafunc.addcall({'i': 1})
            metafunc.addcall({'i': 2})
        def test_func(i):
            pass
    """
    )
    res = testdir.runpytest("-s")
    assert res.ret == 0
    res.stdout.fnmatch_lines(
        ["*Metafunc.addcall is deprecated*", "*2 passed, 2 warnings*"]
    )

def test_terminal_reporter_writer_attr(pytestconfig):
    """Check that TerminalReporter._tw is also available as 'writer' (#2984)
    This attribute is planned to be deprecated in 3.4.
    """
    try:
        import xdist  # noqa

        pytest.skip("xdist workers disable the terminal reporter plugin")
    except ImportError:
        pass
    terminal_reporter = pytestconfig.pluginmanager.get_plugin("terminalreporter")
    assert terminal_reporter.writer is terminal_reporter._tw

@pytest.mark.parametrize("plugin", ["catchlog", "capturelog"])
def test_pytest_catchlog_deprecated(testdir, plugin):
    testdir.makepyfile(
        """
        def test_func(pytestconfig):
            pytestconfig.pluginmanager.register(None, 'pytest_{}')
    """.format(
            plugin
        )
    )
    res = testdir.runpytest()
    assert res.ret == 0
    res.stdout.fnmatch_lines(
        ["*pytest-*log plugin has been merged into the core*", "*1 passed, 1 warnings*"]
    )

def test_pytest_plugins_in_non_top_level_conftest_deprecated(testdir):
    from _pytest.deprecated import PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST

    testdir.makepyfile(
        **{
            "subdirectory/conftest.py": """
        pytest_plugins=['capture']
    """
        }
    )
    testdir.makepyfile(
        """
        def test_func():
            pass
    """
    )
    res = testdir.runpytest()
    assert res.ret == 0
    msg = str(PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST).splitlines()[0]
    res.stdout.fnmatch_lines(
        "*subdirectory{sep}conftest.py:0: RemovedInPytest4Warning: {msg}*".format(
            sep=os.sep, msg=msg
        )
    )

@pytest.mark.parametrize("use_pyargs", [True, False])
def test_pytest_plugins_in_non_top_level_conftest_deprecated_pyargs(
    testdir, use_pyargs
):
    """When using --pyargs, do not emit the warning about non-top-level conftest warnings (#4039, #4044)"""
    from _pytest.deprecated import PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST

    files = {
        "src/pkg/__init__.py": "",
        "src/pkg/conftest.py": "",
        "src/pkg/test_root.py": "def test(): pass",
        "src/pkg/sub/__init__.py": "",
        "src/pkg/sub/conftest.py": "pytest_plugins=['capture']",
        "src/pkg/sub/test_bar.py": "def test(): pass",
    }
    testdir.makepyfile(**files)
    testdir.syspathinsert(testdir.tmpdir.join("src"))

    args = ("--pyargs", "pkg") if use_pyargs else ()
    res = testdir.runpytest(*args)
    assert res.ret == 0
    msg = str(PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST).splitlines()[0]
    if use_pyargs:
        assert msg not in res.stdout.str()
    else:
        res.stdout.fnmatch_lines("*{msg}*".format(msg=msg))

def test_pytest_plugins_in_non_top_level_conftest_deprecated_no_top_level_conftest(
    testdir
):
    from _pytest.deprecated import PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST

    subdirectory = testdir.tmpdir.join("subdirectory")
    subdirectory.mkdir()
    testdir.makeconftest(
        """
        import warnings
        warnings.filterwarnings('always', category=DeprecationWarning)
        pytest_plugins=['capture']
    """
    )
    testdir.tmpdir.join("conftest.py").move(subdirectory.join("conftest.py"))

    testdir.makepyfile(
        """
        def test_func():
            pass
    """
    )

    res = testdir.runpytest_subprocess()
    assert res.ret == 0
    msg = str(PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST).splitlines()[0]
    res.stdout.fnmatch_lines(
        "*subdirectory{sep}conftest.py:0: RemovedInPytest4Warning: {msg}*".format(
            sep=os.sep, msg=msg
        )
    )

def test_pytest_plugins_in_non_top_level_conftest_deprecated_no_false_positives(
    testdir
):
    from _pytest.deprecated import PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST

    subdirectory = testdir.tmpdir.join("subdirectory")
    subdirectory.mkdir()
    testdir.makeconftest(
        """
        pass
    """
    )
    testdir.tmpdir.join("conftest.py").move(subdirectory.join("conftest.py"))

    testdir.makeconftest(
        """
        import warnings
        warnings.filterwarnings('always', category=DeprecationWarning)
        pytest_plugins=['capture']
    """
    )
    testdir.makepyfile(
        """
        def test_func():
            pass
    """
    )
    res = testdir.runpytest_subprocess()
    assert res.ret == 0
    msg = str(PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST).splitlines()[0]
    assert msg not in res.stdout.str()

def test_call_fixture_function_deprecated():
    """Check if a warning is raised if a fixture function is called directly (#3661)"""

    @pytest.fixture
    def fix():
        return 1

    with pytest.deprecated_call():
        assert fix() == 1

def test_pycollector_makeitem_is_deprecated():
    from _pytest.python import PyCollector
    from _pytest.warning_types import RemovedInPytest4Warning

    class PyCollectorMock(PyCollector):
        """evil hack"""

        def __init__(self):
            self.called = False

        def _makeitem(self, *k):
            """hack to disable the actual behaviour"""
            self.called = True

    collector = PyCollectorMock()
    with pytest.warns(RemovedInPytest4Warning):
        collector.makeitem("foo", "bar")
    assert collector.called

def test_fixture_named_request(testdir):
    testdir.copy_example()
    result = testdir.runpytest()
    result.stdout.fnmatch_lines(
        [
            "*'request' is a reserved name for fixtures and will raise an error in future versions"
        ]
    )


import requests
from flask import current_app

def weather_by_city(city_name , number_of_days):
    weather_url = current_app.config["WEATHER_URL"]
    params = {
        "key" :  current_app.config["WEATHER_API_KEY"] ,
        "q" : city_name ,
        "days" : number_of_days
        }
    try:
        result = requests.get(weather_url , params = params)
        result.raise_for_status()
        weather = result.json()
        if 'current' in weather:
            try:
                return weather['current']
            except(IndexError , TypeError):
                return False
    except(requests.RequestException , ValueError):
        print("Сетевая ошибка")
        return False
    return False

if __name__ == "__main__":
    print(weather_by_city("Paris" , 1))


import cv2
import numpy as np

fn="test1.jpg"

if __name__ == '__main__':

    img = cv2.imread(fn)
    w=img.shape[1]
    h=img.shape[0]
    ii=0
    #关于纵向生成镜像
    #// 与 / 的区别 " / " 表示浮点数除法,返回浮点结果; " // " 表示整数除法
    mirror_w=w//2
    for j in  range(0,h):
        for i in  range(0,mirror_w):
            img[j,i,:]=img[j,w-i-1,:]
        print ('.',end="")
    cv2.namedWindow('img')
    cv2.imshow('img', img)
    cv2.waitKey()
    cv2.destroyAllWindows()


from setuptools import setup, Extension
from subprocess import Popen, PIPE

src = ['Src/shpopen.c','Src/readshape.c','Src/dbfopen.c']

try:
    import cdat_info

    Version = cdat_info.Version
except Exception:
    Version = "???"
print("VERSION:", Version)

setup (name = "vcsaddons",
       version=Version,
       description = "addons for VCS",
       url = "http://cdat.llnl.gov",
       packages = ['vcsaddons','EzTemplate','EzPlot'],
       package_dir = {'vcsaddons': 'Lib', 'EzTemplate':'EzTemplate/Lib', 'EzPlot':'EzPlot/Lib'},
       ext_modules = [
    Extension('vcsaddons._gis',
              src,['Include']
              ),
    ]
       )


from django.contrib import admin
from django.urls import include, path
from django.views.generic import TemplateView

from task_manager.app_users.views import SignIn, SignOut

appname = 'task_manager'
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', TemplateView.as_view(template_name='home.html'), name='home'),
    path('login/', SignIn.as_view(), name='login'),
    path('logout/', SignOut.as_view(), name='logout'),
    path('i18n/', include('django.conf.urls.i18n')),
    path('users/', include('task_manager.app_users.urls'), name='users'),
    path(
        'statuses/',
        include('task_manager.app_statuses.urls'),
        name='statuses',
    ),
    path('tasks/', include('task_manager.app_tasks.urls'), name='tasks'),
    path('labels/', include('task_manager.app_labels.urls'), name='labels'),
]


import boto3
from utils.constant import AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY

class DynamoClient():

    def __init__(self) -> None:
        self.client = boto3.client('dynamodb',
                                   region_name='sa-east-1',
                                   aws_access_key_id=AWS_ACCESS_KEY_ID,
                                   aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
        self.table_name = 'controle-processamento'

    def insert_control_data(self, id_execucao, status):
        self.client.put_item(
            TableName=self.table_name,
            Item={
                'id_execucao': {'S': id_execucao},
                'status': {'S': status}
            }
        )


"""
3D pose estimation of an RGB-D camera using least squares technique
Created on Aug 2016
Updated on May 2019
By Sina M.Baharlou (Sina.baharlou@gmail.com)
Web page: www.sinabaharlou.com
"""

# -- Import required classes and libraries --
import scipy.io
import transformations as tf
from depth_frame import *

# -- Posit status class --
class PositStatus:
    PT_STATUS_UNKNOWN, \
    PT_STATUS_NAN, \
    PT_STATUS_INLIER, \
    PT_STATUS_OUTLIER = range(4)

    def __init__(self):
        self.total_err = 0
        self.inlier_err = 0
        self.outlier_err = 0
        self.inlier_count = 0
        self.outlier_count = 0
        self.damping_used = False
        self.extrinsic_mat = None
        self.pt_status = list()

# -- Posit solver class --
class PositSolver:
    # -- constructor
    def __init__(self, camera_mat=DEFAULT_CAM_MATRIX,
                 initial_guess=DEFAULT_INIT_GUESS,
                 img_size=DEFAULT_IMG_SIZE,
                 max_error=DEFAULT_MAX_ERROR,
                 damp_fact=DEFAULT_DAMPING_FACTOR,
                 save_matlab=DEFAULT_SAVE_MATLAB):

        # -- Initialize arrays --
        self.__model_pts = np.array([[0, 0, 0]])
        self.__image_pts = np.array([[0, 0, 0]])

        # -- Initialize posit parameters --
        self.__camera_mat = camera_mat
        self.__extrinsic_mat = initial_guess
        self.__count = 0
        self.__img_w = img_size[0]
        self.__img_h = img_size[1]
        self.__max_error = max_error
        self.__damping_factor = damp_fact
        self.__save_matlab = save_matlab

    # -- Extract the model points and image points from the given frames
    # -- P0X P0Y P0Z
    # -- P1X P1Y P1Z
    # -- PNX PNY PNZ

    def init_solver(self, mdl_frame, img_frame, matches):

        # -- Get model frame & image frame points' status --
        mdl_status = mdl_frame.get_status()
        img_status = img_frame.get_status()

        # -- Get model frame & image frame points --
        mdl_pts = mdl_frame.get_camera_pts()
        img_pts = img_frame.get_image_pts()

        # -- For all matches --
        for m in matches:

            # -- Get indices --
            q_index = m.queryIdx
            t_index = m.trainIdx

            # -- Add them if they have acceptable depth --
            if mdl_status[q_index].status == img_status[t_index].status == PtStatus.DEPTH_ACCEPTED:
                pt = mdl_pts[mdl_status[q_index].camera_index].transpose()

                self.__image_pts = np.vstack([self.__image_pts, img_pts[img_status[t_index].camera_index]])
                self.__model_pts = np.vstack([self.__model_pts, pt.transpose()])
                self.__count += 1

        # -- Erase the initial points --
        self.__image_pts = np.delete(self.__image_pts, 0, axis=0)
        self.__model_pts = np.delete(self.__model_pts, 0, axis=0)

        # -- Save the points in the matlab format (if it's needed) --
        if self.__save_matlab:
            mat_var = {'img': self.__image_pts, 'mdl': self.__model_pts, 'K': self.__camera_mat,
                       'T': self.__extrinsic_mat}
            scipy.io.savemat('matlab_pts.mat', mdict=mat_var)

    # -- Skew symmetric matrix --
    @staticmethod
    def skew(x, y, z):
        return np.matrix([[0, -z, y], [z, 0, -x], [-y, x, 0]])

    # -- Euler angles to transformation matrix --
    @staticmethod
    def euler_to_mat(state):
        mat = np.matrix(tf.euler_matrix(state[3], state[4], state[5]))
        mat[0, 3] = state[0]
        mat[1, 3] = state[1]
        mat[2, 3] = state[2]
        return mat

    # -- Quaternion to mat --
    @staticmethod
    def q_to_mat(dt):
        w = np.linalg.norm(dt[3:5])
        if w < 1:
            w = sqrt(1 - pow(w, 1))
            quaternion = tf.quaternion_about_axis(w, (dt[3], dt[4], dt[5]))
            m = tf.quaternion_matrix(quaternion)
        else:
            m = np.eye(4, 4)

        m[0, 3] = dt[0]
        m[1, 3] = dt[1]
        m[2, 3] = dt[2]

        return np.matrix(m)

    # -- Solve least square problem --
    def solve(self, suppress_outliers=False):
        # -- Get H and B and status --
        [H, B, posit_stat] = self._solve(suppress_outliers)

        # -- Solve the problem with damping enabled --
        H += np.matrix(np.eye(6, 6)) * self.__damping_factor
        dt = np.linalg.solve(H, -B)
        posit_stat.damping_used = True

        # -- Convert to euler angles --
        m = self.euler_to_mat(dt)

        # -- Update extrinsic matrix --
        self.__extrinsic_mat = self.__extrinsic_mat * m
        R = self.__extrinsic_mat[0:3, 0:3]
        E = R.transpose() * R
        diag = E.diagonal()
        np.fill_diagonal(E, diag - 1)
        posit_stat.extrinsic_mat = self.__extrinsic_mat

        return posit_stat

    def _solve(self, suppress_outliers):
        # -- Initialize H & B --
        H = np.matrix(np.zeros([6, 6]))
        B = np.matrix(np.zeros([6, 1]))

        # -- Init Point-Posit Status --
        posit_stat = PositStatus()

        # -- Set current point-posit status --
        curr_stat = PositStatus.PT_STATUS_UNKNOWN

        for i in range(self.__count):
            # -- Get error and jacobian of point i'th --
            [status, e, j] = self.error_jacobian(i)

            # -- If the point is out of the range --
            if not status:
                curr_stat = PositStatus.PT_STATUS_NAN
                posit_stat.pt_status.append(curr_stat)
                continue

            # -- Calculate the norm of error --
            err = np.linalg.norm(e)
            posit_stat.total_err += err
            scale_factor = 1

            # -- If the point is inlier --
            if err < self.__max_error:
                curr_stat = PositStatus.PT_STATUS_INLIER
                posit_stat.inlier_err += err
                posit_stat.inlier_count += 1

            # -- If the point is outlier --
            else:
                curr_stat = PositStatus.PT_STATUS_OUTLIER
                scale_factor = self.__max_error / err
                posit_stat.outlier_err += err
                posit_stat.outlier_count += 1

            if not suppress_outliers or \
                    curr_stat == PositStatus.PT_STATUS_INLIER:
                H += j.transpose() * j * scale_factor
                B += j.transpose() * e * scale_factor

            posit_stat.pt_status.append(curr_stat)

        return [H, B, posit_stat]

    # -- Calculate the jacobian error --
    def error_jacobian(self, index):
        # -- Get current model point --
        pt = np.hstack([self.__model_pts[index, :], [[1]]]).transpose()

        # -- Transfer current point --
        pt_t = self.__extrinsic_mat * pt
        pt_t = pt_t[0:3, :]

        # -- Multiply by camera matrix --
        pt_p = self.__camera_mat * pt_t

        # -- Shortcut for coordinates --
        px = pt_p[0, 0]
        py = pt_p[1, 0]
        pz = pt_p[2, 0]

        tx = pt_t[0, 0]
        ty = pt_t[1, 0]
        tz = pt_t[2, 0]

        # -- If the projected point is behind the camera --
        if tz < 0 or pz <= 0:
            return [False, None, None]

        # -- If the projected point is out of range --
        if px < 0 or px > self.__img_w or \
                py < 0 or py > self.__img_h:
            return [False, None, None]

        # -- Project the points --
        pt_p = pt_p / pz

        # -- Calculate the error --
        error = pt_p - self.__image_pts[index, :].transpose()
        error[2] = 0

        # -- Calculate transform Jacobian --
        I = np.eye(3, 3)
        skew_mat = -2 * self.skew(tx, ty, tz)
        Jt = np.hstack([I, skew_mat])

        # -- Calculate homogeneous division Jacobian --
        inv_pz = 1 / tz

        Jp = np.matrix([[inv_pz, 0, -px * inv_pz],
                        [0, inv_pz, -py * inv_pz],
                        [0, 0, 0]])

        J = Jp * self.__camera_mat * Jt

        return [True, error, J]


# -- coding: utf-8 --
import threading
import time

from playsound import playsound

# class myThread(threading.Thread):
#     def __init__(self, threadID, name, counter):
#         threading.Thread.__init__(self)
#         self.threadID = threadID
#         self.name = name
#         self.counter = counter
#
#     def run(self):
#         print("开始线程：" + self.name)
#         print_time(self.name, self.counter, 5)
#         print("退出线程：" + self.name)
#
#
# def print_time(threadName, delay, counter):
#     while counter:
#         if exitFlag:
#             threadName.exit()
#         time.sleep(delay)
#         print("%s: %s" % (threadName, time.ctime(time.time())))
#         counter -= 1

def play_sounds(act):
    temp = []
    while True:
        time.sleep(0.01)
        if len(act) != 0:
            for a in act:
                temp.append(a)
            act.clear()
        for t in temp:
            try:
                playsound('inference/audio/' + t + '.mp3')
            except Exception as e:
                print(e)
            temp.clear()

def play_piano(data):
    temp = []
    while True:
        time.sleep(0.01)
        if len(data) != 0:
            for a in data:
                if a not in temp:
                    temp.append(a)
            data.clear()
        for t in temp:
            try:
                playsound('inference/audio/' + t + '.mp3')
            except Exception as e:
                print(e)
            temp.clear()