# coding:utf-8
import sys
import re
from xsqlmb.api.logstash.utils.dt_tool import get_pydt_based_logdt
from xsqlmb.api.logstash.cfgs.configs import WAF_ACCESS_LOG_SQL_TABLE, \
    WAF_ALERT_LOG_SQL_TABLE, WAF_ALERT_LOG_DETAILED_SQL_TABLE
#from utils.django_module import django_setup
try:
    from xsqlmb.src.cfgs.logConfig import logging
except:
    import logging

from uuid import uuid4
from xsqlmb.api.logstash.scripts.extract_log_f_mongo import ExtractLogFromMongo
from xsqlmb.src.dao.exutil import MutiTypesInsets2SqlClass
#from xsqlmb.src.ltool.sqlconn import from_sql_get_data, sql_action
from xsqlmb.api.logstash.utils.get_table_columns import get_waf_alert_log_columns, get_waf_access_log_columns
from ..cfgs.configs import WAF_ACCESS_LOG_SQL_TABLE, WAF_ALERT_LOG_SQL_TABLE

_waf_columns = get_waf_alert_log_columns()

class LogToSql():

    def __init__(self, MAX_INSERT_NUM=500):
        self.MAX_INSERT_NUM=MAX_INSERT_NUM

    def init_sql_logdb(self):
        pass

    def get_latest_accsslog(self):
        datas, line = ExtractLogFromMongo(table_name=WAF_ACCESS_LOG_SQL_TABLE).get_access_logs()
        return datas

    def get_latest_modseclog(self):
        return ExtractLogFromMongo(table_name=WAF_ALERT_LOG_SQL_TABLE).modseclog_to_detaild()

    def many_insert2_accesslog(self, nad_datas):
        from django.core.paginator import Paginator
        p = Paginator(nad_datas, self.MAX_INSERT_NUM) # 分页列别
        page_count = p.num_pages  # 总页数
        seccess_insert_num = 0

        # from xsqlmb.api.logstash.utils.get_table_columns import get_waf_access_log_columns
        cols = get_waf_access_log_columns()
        _columns = "`" + "`, `".join(cols) + "`"
        _keys = cols

        for x in [x+1 for x in range(page_count)]:
            nad_list = list(p.page(x).object_list)
            from xsqlmb.src.dao.exutil import MutiTypesInsets2SqlClass

            MutiTypesInsets2SqlClass(table_name = WAF_ACCESS_LOG_SQL_TABLE).arrays2sql2(
            nad_list, columns_order=_columns, keys_list=_keys)
            seccess_insert_num += len(nad_list)

        return seccess_insert_num

    def accesslog_to_sql(self, local=False):
        nad_datas = []
        _accesslog_datas = self.get_latest_accsslog()
        for x in _accesslog_datas:
            obj = x.copy()
            try:
                obj["time_local"] = get_pydt_based_logdt(re.match("(.*?)\s(.*)", obj["time_local"]).group(1))
                obj["timestamp"] = obj["time_local"]

                if "request_url" not in obj.keys():
                    obj["request_url"] = obj["url"]

                if "request_id" not in obj.keys():
                    obj["request_id"] = uuid4()

                obj["upstream_response_time"] = "0.01" if obj["upstream_response_time"] == "-" else "0.0"
                obj["request_time"] = "0.01" if obj["upstream_response_time"] == "-" else "0.0"
            except:
                logging.error("Error:存在AccessLog日志不一样的正则 " + obj["time_local"])

                continue
            nad_datas.append(obj)
        seccess_insert_num = self.many_insert2_accesslog(nad_datas)

        logging.info("插入【" + str(seccess_insert_num)  +"】条新数据到访问日志SQL数据库成功")

    def modseclog_to_sql(self):
        # from datetime import datetime
        # default_time = datetime(1995, 8, 14)
        nad_datas = self.get_latest_modseclog()

        from django.core.paginator import Paginator
        p = Paginator(nad_datas, self.MAX_INSERT_NUM)  # 分页列别
        page_count = p.num_pages  # 总页数
        seccess_insert_num = 0

        from xsqlmb.api.logstash.utils.get_table_columns import get_waf_alert_log_columns
        cols = get_waf_alert_log_columns()

        _columns = "`" + "`, `".join(cols) + "`"
        _keys = cols

        for x in [x + 1 for x in range(page_count)]:
            nad_list = list(p.page(x).object_list)
            try:
                _insert_num = MutiTypesInsets2SqlClass(table_name=WAF_ALERT_LOG_SQL_TABLE).arrays2sql2(
                    nad_list, columns_order=_columns, keys_list=_keys)
                seccess_insert_num += _insert_num

            finally:
                import json

                # _detailed_list = [ [x["audit_logid"], json.dumps(x)] for x in nad_list ]
                # MutiTypesInsets2SqlClass(table_name=WAF_ALERT_LOG_DETAILED_SQL_TABLE).arrays2sql(
                #     _detailed_list, columns_order="`audit_logid`,`detaild`"
                # )

                _detailed_list = [dict(audit_logid=x["audit_logid"], detaild=json.dumps(x) ) for x in nad_list]

                from xsqlmb.src.ltool.mongo import MongoConn
                from xsqlmb.api.logstash.cfgs.configs import WAF_ALERT_LOG_DETAILED_SQL_TABLE
                MongoConn().insert_data(WAF_ALERT_LOG_DETAILED_SQL_TABLE, _detailed_list)

        logging.info("插入【" + str(seccess_insert_num) + "】条新数据到告警日志SQL数据库成功")


"""
WARP-Q: Quality Prediction For Generative Neural Speech Codecs

This is the WARP-Q version used in the ICASSP 2021 Paper:

W. A. Jassim, J. Skoglund, M. Chinen, and A. Hines, “WARP-Q: Quality prediction
for generative neural speech codecs,” paper accepted for presentation at the 2021 IEEE
International Conference on Acoustics, Speech and Signal Processing (ICASSP 2021). Date of acceptance: 30 Jan 2021.

Run using python 3.x and include these package dependencies in your virtual environment:
    - pandas
    - librosa
    - seaborn
    - numpy
    - scipy
    - pyvad
    - skimage
    - speechpy
    - soundfile

Input:
    - The main_test function calls a csv file that contains paths of audio files.
    - The csv file cosists of four columns:
        - Ref_Wave: reference speech
        - Test_Wave: test speech
        - MOS: subjective score (optinal, for plotting only)
        - Codec: type of speech codec for the test speech (optinal, for plotting only)

Output:
    - Code will compute the WARP-Q quality scores between Ref_Wave and Test_Wave,
    and will store the obrained results in a new column in the same csv file.

Releases:

Warning: While this code has been tested and commented giving invalid input
files may cause unexpected results and will not be caught by robust exception
handling or validation checking. It will just fail or give you the wrong answer.

(c) Dr Wissam Jassim
    University College Dublin
    wissam.a.jassim@gmail.com
    wissam.jassim@ucd.ie
    November 28, 2020

"""

# Load libraries
from msilib.schema import File
import pandas as pd
import librosa, librosa.core, librosa.display
import seaborn as sns
import numpy as np
import sys
from scipy.stats import pearsonr
from scipy.stats import spearmanr
from pyvad import vad, trim, split
from skimage.util.shape import view_as_windows
import speechpy
import soundfile as sf
import tensorflow as tf
import tensorflow_lattice as tfl
import pandas as pd
from tensorflow_estimator.python.estimator.canned import optimizers
from tensorflow_estimator.python.estimator.head import binary_class_head
from tensorflow import keras
from absl import app
from absl import flags
from tensorflow import feature_column as fc

### FLAGS ###
FLAGS = flags.FLAGS
flags.DEFINE_integer('num_epochs', 48, 'Number of training epoch.')

###############################################################################
############################# #  WARP - Q #####################################
###############################################################################
def compute_WAPRQ(ref_path,test_path,sr=16000,n_mfcc=12,fmax=5000,patch_size=0.4,sigma=np.array([[1,1],[3,2],[1,3]])):

    # Inputs:
    # refPath: path of reference speech
    # disPath: path pf degraded speech
    # sr: sampling frequency, Hz
    # n_mfcc: number of MFCCs
    # fmax: cutoff frequency
    # patch_size: size of each patch in s
    # sigma: step size conditon for DTW

    # Output:
    # WARP-Q quality score between refPath and disPath

    ####################### Load speech files #################################
    # Load Ref Speech
    if ref_path[-4:] == '.wav':
        speech_Ref, sr_Ref = librosa.load(ref_path,sr=sr)
    else:
        if ref_path[-4:] == '.SRC': #For ITUT database if applicable
            speech_Ref, sr_Ref  = sf.read(ref_path, format='RAW', channels=1, samplerate=16000,
                           subtype='PCM_16', endian='LITTLE')
            if sr_Ref != sr:
                speech_Ref = librosa.resample(speech_Ref, sr_Ref, sr)
                sr_Ref = sr

    # Load Coded Speech
    if test_path[-4:] == '.wav':
        speech_Coded, sr_Coded = librosa.load(test_path,sr=sr)
    else:
        if test_path[-4:] == '.OUT': #For ITUT database if applicable
            speech_Coded, sr_Coded  = sf.read(test_path, format='RAW', channels=1, samplerate=16000,
                           subtype='PCM_16', endian='LITTLE')
            if sr_Coded != sr:
                speech_Coded = librosa.resample(speech_Coded, sr_Coded, sr)
                sr_Coded = sr

    if sr_Ref != sr_Coded:
        raise ValueError("Reference and degraded signals should have same sampling rate!")

    # Make sure amplitudes are in the range of [-1, 1] otherwise clipping to -1 to 1
    # after resampling (if applicable). We experienced this issue for TCD-VOIP database only
    speech_Ref[speech_Ref>1]=1.0
    speech_Ref[speech_Ref<-1]=-1.0

    speech_Coded[speech_Coded>1]=1.0
    speech_Coded[speech_Coded<-1]=-1.0

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

    win_length = int(0.032*sr) #32 ms frame
    hop_length = int(0.004*sr) #4 ms overlap
    #hop_length = int(0.016*sr)

    n_fft = 2*win_length
    lifter = 3

    # DTW Parameters
    Metric = 'euclidean'

    # VAD Parameters
    hop_size_vad = 30
    sr_vad = sr
    aggresive = 0

    # VAD for Ref speech
    vact1 = vad(speech_Ref, sr, fs_vad = sr_vad, hop_length = hop_size_vad, vad_mode=aggresive)
    speech_Ref_vad = speech_Ref[vact1==1]

    # VAD for Coded speech
    vact2 = vad(speech_Coded, sr, fs_vad = sr_vad, hop_length = hop_size_vad, vad_mode=aggresive)
    speech_Coded_vad = speech_Coded[vact2==1]

    # Compute MFCC features for the two signals

    mfcc_Ref = librosa.feature.mfcc(speech_Ref_vad,sr=sr,n_mfcc=n_mfcc,fmax=fmax,
                                    n_fft=n_fft,win_length=win_length,hop_length=hop_length,lifter=lifter)
    mfcc_Coded = librosa.feature.mfcc(speech_Coded_vad,sr=sr,n_mfcc=n_mfcc,fmax=fmax,
                                    n_fft=n_fft,win_length=win_length,hop_length=hop_length,lifter=lifter)

    # Feature Normalisation using CMVNW method
    mfcc_Ref = speechpy.processing.cmvnw(mfcc_Ref.T,win_size=201,variance_normalization=True).T
    mfcc_Coded = speechpy.processing.cmvnw(mfcc_Coded.T,win_size=201,variance_normalization=True).T

    # Divid MFCC features of Coded speech into patches
    cols = int(patch_size/(hop_length/sr))
    window_shape = (np.size(mfcc_Ref,0), cols)
    step  = int(cols/2)

    mfcc_Coded_patch = view_as_windows(mfcc_Coded, window_shape, step)

    Acc =[]
    band_rad = 0.25
    weights_mul=np.array([1, 1, 1])

    # Compute alignment cose between each patch and Ref MFCC
    for i in range(mfcc_Coded_patch.shape[1]):

        patch = mfcc_Coded_patch[0][i]

        D, P = librosa.sequence.dtw(X=patch, Y=mfcc_Ref, metric=Metric,
                                    step_sizes_sigma=sigma, weights_mul=weights_mul,
                                    band_rad=band_rad, subseq=True, backtrack=True)

        P_librosa = P[::-1, :]
        b_ast = P_librosa[-1, 1]

        Acc.append(D[-1, b_ast] / D.shape[0])

    # Final score
    #return np.median(Acc)              # Old return to ignore DLN
    return Acc                         # Return for Feature Data

###############################################################################
################## #  Deep Lattice Network ####################################
###############################################################################
def deep_lattice_network(Acc):
    print()

###############################################################################
############### #  Main Demo Test Function ####################################
###############################################################################
def main_test():

    # Load path of speech files stored in a csv file
    # The csv file cosists of four columns:
    # Ref_Wave	Test_Wave 	MOS 	Codec

    print(flags)

    All_Data = pd.read_csv("audio_paths.csv",index_col=None)

    WARP_Q = [] # List to add WARP-Q scores
    # Run WARP-Q for each row
    for index, row in All_Data.iterrows():
        score = compute_WAPRQ(ref_path=row['Ref_Wave'],test_path=row['Test_Wave'])
        WARP_Q.append(score)
        print(row['Test_Wave'])

    # Add computed score to the dataframe
    All_Data['WARP-Q'] = WARP_Q
    warp_q_df = pd.DataFrame(WARP_Q)
    # Save WARP-Q to csv
    warp_q_df.to_csv('Results.csv', index = False)
    print(warp_q_df)
    #deep_lattice_network()

if __name__ == '__main__':
    main_test()


import time
import os
from reportlab.lib.enums import TA_JUSTIFY
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
def pdf(data):
    route = os.getcwd() + "\\pacient.pdf"
    doc = SimpleDocTemplate(route, pagesize=letter,
                            rightMargin=72, leftMargin=72,
                            topMargin=72, bottomMargin=18)
    Story = []
    logotipo = os.getcwd() + "\\logo.png"
    pacient_name = data['usr_name']
    formatoFecha = time.ctime()
    imagen = Image(logotipo, 2 * inch, 1 * inch)
    Story.append(imagen)
    estilos = getSampleStyleSheet()
    estilos.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
    texto = '%s' % formatoFecha
    Story.append(Paragraph(texto, estilos["Normal"]))
    Story.append(Spacer(1, 12))
    texto = 'Medical history of %s:' % pacient_name
    Story.append(Paragraph(texto, estilos["Normal"]))
    Story.append(Spacer(1, 12))
    dict_list = data['data']
    for dict_p in dict_list:
        texto = 'Hospital: %s' % dict_p['hospital']
        Story.append(Paragraph(texto, estilos["Normal"]))
        Story.append(Spacer(1, 12))
        texto = 'Doctor: %s' % dict_p['doctor']
        Story.append(Paragraph(texto, estilos["Normal"]))
        Story.append(Spacer(1, 12))
        texto = 'Especiality: %s' % dict_p['especiality']
        Story.append(Paragraph(texto, estilos["Normal"]))
        Story.append(Spacer(1, 12))
        texto = 'Observations: %s' % dict_p['details']
        Story.append(Paragraph(texto, estilos["Justify"]))
        Story.append(Spacer(1, 12))
        Story.append(Spacer(1, 12))
        Story.append(Spacer(1, 12))
    texto = 'Heippi developer team.'
    Story.append(Paragraph(texto, estilos["Normal"]))
    doc.build(Story)
    return route


from andes.core import (Algeb, ConstService, ExtAlgeb, ExtParam, ExtService,
                        IdxParam, Model, ModelData, NumParam, State,)
from andes.core.block import Integrator
from andes.core.var import AliasState

class WTDSData(ModelData):
    """
    Wind turbine governor swing equation model data.
    """

    def __init__(self):
        ModelData.__init__(self)

        self.ree = IdxParam(mandatory=True,
                            info='Renewable exciter idx',
                            )

        self.H = NumParam(default=3.0, tex_name='H_t',
                          info='Total inertia', unit='MWs/MVA',
                          power=True,
                          non_zero=True,
                          non_negative=True,
                          )

        self.D = NumParam(default=1.0, tex_name='D_{shaft}',
                          info='Damping coefficient',
                          unit='p.u.',
                          power=True,
                          )

        self.w0 = NumParam(default=1.0, tex_name=r'\omega_0',
                           info='Default speed if not using a torque model',
                           unit='p.u.',
                           )

class WTDSModel(Model):
    """
    Wind turbine one-mass generator model.

    User-provided reference speed should be specified in parameter `w0`.
    Internally, `w0` is set to the algebraic variable `wr0`.

    See J.H. Chow, J.J. Sanchez-Gasca. "Power System Modeling, Computation, and Control".
    John Wiley & Sons, 2020. pp. 518.
    """

    def __init__(self, system, config):
        Model.__init__(self, system, config)
        self.flags.tds = True
        self.group = 'RenGovernor'

        self.reg = ExtParam(model='RenExciter', src='reg', indexer=self.ree,
                            export=False,
                            )

        self.Sn = ExtParam(model='RenGen', src='Sn', indexer=self.reg,
                           tex_name='S_n', export=False,
                           )

        self.wge = ExtAlgeb(model='RenExciter', src='wg', indexer=self.ree,
                            export=False,
                            e_str='-1.0 + s1_y',
                            ename='wg',
                            tex_ename=r'\omega_g',
                            )

        self.Pe = ExtAlgeb(model='RenGen', src='Pe', indexer=self.reg, export=False,
                           info='Retrieved Pe of RenGen')

        self.Pe0 = ExtService(model='RenGen', src='Pe', indexer=self.reg, tex_name='P_{e0}',
                              )

        self.H2 = ConstService(v_str='2 * H', tex_name='2H')

        self.Pm = Algeb(tex_name='P_m',
                        info='Mechanical power',
                        e_str='Pe0 - Pm',
                        v_str='Pe0',
                        )

        self.wr0 = Algeb(tex_name=r'\omega_{r0}',
                         unit='p.u.',
                         v_str='w0',
                         e_str='w0 - wr0',
                         info='speed set point',
                         )

        # `s1_y` is `w_m`
        self.s1 = Integrator(u='(Pm - Pe) / wge - D * (s1_y - wr0)',
                             T=self.H2,
                             K=1.0,
                             y0='wr0',
                             )

        # make two alias states, `wt` and `wg`, pointing to `s1_y`
        self.wt = AliasState(self.s1_y, tex_name=r'\omega_t')

        self.wg = AliasState(self.s1_y, tex_name=r'\omega_g')

        self.s3_y = State(info='Unused state variable',
                          tex_name='y_{s3}',
                          )

        self.Kshaft = ConstService(v_str='1.0', tex_name='K_{shaft}',
                                   info='Dummy Kshaft',
                                   )

class WTDS(WTDSData, WTDSModel):
    """
    Custom wind turbine model with a single swing-equation.

    This model is used to simulate the mechanical swing
    of the combined machine and turbine mass. The speed output
    is ``s1_y`` which will be fed to ``RenExciter.wg``.

    ``PFLAG`` needs to be set to ``1`` in exciter to consider
    speed for Pref.
    """

    def __init__(self, system, config):
        WTDSData.__init__(self)
        WTDSModel.__init__(self, system, config)


import random

class MontyHall:

    def __init__(self):
        self.doors = [1, 2, 3, 4]
        self.winner_door = random.choice(self.doors)

    def turn1(self, chosen_door):
        if chosen_door == self.winner_door:
            other_doors = [door for door in self.doors if door != chosen_door]
            return random.choice(other_doors)
        else:
            other_doors = [door for door in self.doors if door != chosen_door and door != self.winner_door]
            return random.choice(other_doors)

    def turn2(self, chosen_door):
        return 1 if chosen_door == self.winner_door else 0

if __name__ == '__main__':
    NUM_EXPTS = 100000

    player_not_change = PlayerNotChange()
    player_change = PlayerChange()

    for expt in range(NUM_EXPTS):
        game = MontyHall()

        player_not_change.play(game)
        player_change.play(game)

    print(f'Player not change: {player_not_change.score / NUM_EXPTS}')
    print(f'Player change: {player_change.score / NUM_EXPTS}')


from sys import argv

input_file = argv[1]

data = []
with open(input_file) as f:
    data = [[int(x) for x in line[:-1].split('-')] for line in f]

data.sort(key=lambda x: x[0])

val = None
max_val = 0
if data[0][0] != 0:
    print('Lowest allowed IP is 0.')
    exit()
for i in range(len(data) - 1):
    if data[i][1] > max_val:
        max_val = data[i][1]
    if data[i][1] < data[i + 1][0] - 1 and data[i][1] >= max_val:
        val = data[i][1] + 1
        break
if val == None:
    val = data[-1][1] + 1
print('Lowest allowed IP is {}.'.format(val))


# Reference:
# https://github.com/SkyDynamic/nonebot_plugin_jrrp/blob/main/nonebot_plugin_jrrp/__init__.py

import sys

def rol(num: int, k: int, bits: int = 64):
    b1 = bin(num << k)[2:]
    if len(b1) <= bits:
        return int(b1, 2)
    return int(b1[-bits:], 2)

def get_hash(string: str):
    num = 5381
    num2 = len(string) - 1
    for i in range(num2 + 1):
        num = rol(num, 5) ^ num ^ ord(string[i])
    return num ^ 12218072394304324399

def get_jrrp():
    num = round(abs((get_hash("".join([
        "asdfgbn",
        sys.argv[4], # YDay
        "12#3$45",
        sys.argv[2], # Year
        "IUY"
    ])) / 3 + get_hash("".join([
        "QWERTY",
        sys.argv[1], # User ID
        "0*8&6",
        sys.argv[3], # MDay
        "kjhg"
    ])) / 3) / 527) % 1001)
    if num >= 970:
        num2 = 100
    else:
        num2 = round(num / 969 * 99)
    return num2

print(get_jrrp(), end='')


# Merge Sort

def mergeSort(arr):
    if len(arr) == 1:
        return arr
    mid = int(len(arr) / 2)
    firstHalf = mergeSort(arr[0:mid])
    secondHalf = mergeSort(arr[mid:])

    return merge(firstHalf, secondHalf)

def merge(first, second):
    ans = list()
    i, j, k = 0, 0, 0
    while i < len(first) and j < len(second):
        if first[i] < second[j]:
            ans.insert(k, first[i])
            i += 1
        else:
            ans.insert(k, second[j])
            j += 1
        k += 1

    while i < len(first):
        ans.insert(k, first[i])
        i += 1
        k += 1

    while j < len(second):
        ans.insert(k, second[j])
        j += 1
        k += 1
    return ans

arr = [5,4,3,2,1]
arr = mergeSort(arr)
print(arr)


"""
Module to perform initial database creation/population for FFXIV-Market-Calculator
"""
import os
import pathlib
import sys

import requests

from sql_helpers import SqlManager

def filter_marketable_items(items, marketable_ids):
    """
    Filters items to only marketable items
    Parameters:
        items : list
            Raw item data from api
        marketable_ids : list
            Marketable item IDs
    """
    marketable_items = [None, (
        'item_num', 'name', 'ave_cost', 'regular_sale_velocity', 'ave_nq_cost', 'nq_sale_velocity',
        'ave_hq_cost', 'hq_sale_velocity', 'gatherable'), (
        'INTEGER PRIMARY KEY', 'TEXT', 'INTEGER', 'REAL', 'INTEGER', 'REAL',
        'INTEGER', 'REAL', 'TEXT DEFAULT "False" NOT NULL')]
    line_concatenate = []
    for line in items[3:]:
        split_line = line_concatenate + line.split(',')
        if len(split_line) >= 98:
            line_concatenate = []
            if split_line[0] in marketable_ids:
                marketable_items.append((split_line[0], split_line[len(split_line) - 88],
                                         0, 0, 0, 0, 0, 0, 'False'))
        else:
            line_concatenate = split_line
    return marketable_items

class FfxivDbCreation:
    """
    Class for handling the construction of databases for the script.

    Attributes:
    -------
    database : SqlManager object
        SqlManager object for database operations

    Methods:
    -------
    market_db_create():
        Creates a new database for market data
    global_db_create():
        Creates a new database for global data
    get_data_from_url():
        Retrieves data from web api
    get_marketable_ids():
        Retrieves data for marketable items
    filter_marketable_recipes():
        Filters recipes to marketable items
    filter_datacentres():
        Filters for usable datacentres
    filter_worlds():
        Filters for usable worlds
    base_state_table():
        Creates the base templated state table
    csv_to_db():
        Handles writing all data from other methods to the databases
    """
    def __init__(self, db_name):
        """
        pulls data from the universalis API to limit items to marketable items
        pulls data from:
        https://raw.githubusercontent.com/xivapi/ffxiv-datamining/master/csv/...
            Item.csv to get item data
            Recipe.csv to get recipe data
            WorldDCGroupType.csv to get dc data
            World.csv to get world data
        creates a new database w/ the given name if it doesn't exist
        Parameters:
            db_name : str
                The name that the database should be called
        """
        if os.path.exists(pathlib.Path(__file__).parent / db_name):
            raise ValueError("Database with that name already exists")

        self.database = SqlManager(db_name)

        if db_name == os.path.join("databases", "global_db"):
            self.global_db_create()
        else:
            self.market_db_create()

    def market_db_create(self):
        """
        Creates the blank market data database
        """
        # gets a list of integers in string format ['2','3','5','6',...]
        marketable_ids = self.get_marketable_ids()
        print('Got marketable ID list')

        # gets a list of tuples containing the item data
        # index 0-2 are the column numbers, titles, and data types; index 3+ is the data
        items = self.get_data_from_url(
            'https://raw.githubusercontent.com/xivapi/ffxiv-datamining/master/csv/Item.csv'
        )
        print('Got raw item CSV')

        # gets a list of tuples containing the item data
        # index 0-2 are the column numbers, titles, and data types; index 3+ is the data
        recipes = self.get_data_from_url(
            'https://raw.githubusercontent.com/xivapi/ffxiv-datamining/master/csv/Recipe.csv')
        recipes[1] = recipes[1].replace('#', 'CSVkey')
        print('Got raw recipe CSV')

        marketable_items = filter_marketable_items(items, marketable_ids)
        print('item CSV filtered to only marketable')

        marketable_recipes = self.filter_marketable_recipes(recipes, marketable_ids)
        print('recipes CSV filtered to only marketable')

        self.csv_to_db(marketable_items, 'item')
        print('item table created')

        self.add_gatherable()
        print("gatherable flags added to item table")

        self.csv_to_db(marketable_recipes, 'recipe')
        print('recipe table created')

        for i in range(10):
            self.database.execute_query(
                f"ALTER TABLE recipe ADD ingredient_cost_{i} INTEGER DEFAULT 9999999;"
            )

        self.database.execute_query(
            "ALTER TABLE recipe ADD cost_to_craft GENERATED ALWAYS AS ("
            "amount_ingredient_0 * ingredient_cost_0 + amount_ingredient_1 * ingredient_cost_1 + "
            "amount_ingredient_2 * ingredient_cost_2 + amount_ingredient_3 * ingredient_cost_3 + "
            "amount_ingredient_4 * ingredient_cost_4 + amount_ingredient_5 * ingredient_cost_5 + "
            "amount_ingredient_6 * ingredient_cost_6 + amount_ingredient_7 * ingredient_cost_7 + "
            "amount_ingredient_8 * ingredient_cost_8 + amount_ingredient_9 * ingredient_cost_9)")

        self.database.execute_query("ALTER TABLE item ADD cost_to_craft INTEGER DEFAULT 0;")
        self.database.execute_query(
            "ALTER TABLE item ADD craft_profit GENERATED ALWAYS AS "
            "(CASE cost_to_craft WHEN 0 THEN 0 ELSE ave_cost - cost_to_craft END);"
        )
        self.database.execute_query(
            "ALTER TABLE item ADD craft_profit_per_day GENERATED ALWAYS AS "
            "(craft_profit * regular_sale_velocity);"
        )
        self.database.execute_query(
            "ALTER TABLE item ADD raw_profit_per_day GENERATED ALWAYS AS "
            "(ave_cost * regular_sale_velocity);"
        )

    def global_db_create(self):
        """
        Creates the blank global data database
        """
        # gets a list of tuples containing the datacentre data
        datacentres = self.get_data_from_url(
            'https://raw.githubusercontent.com/xivapi/'
            'ffxiv-datamining/master/csv/WorldDCGroupType.csv'
        )
        datacentres[1] = datacentres[1].replace('#', 'dc_key')
        print('Got raw datacentre CSV')

        # gets a list of tuples containing the world data
        worlds = self.get_data_from_url(
            'https://raw.githubusercontent.com/xivapi/ffxiv-datamining/master/csv/World.csv')
        worlds[1] = worlds[1].replace('#', 'world_key')
        print('got raw world CSV')

        usable_datacentres = self.filter_datacentres(datacentres)
        print('datacentres CSV filtered to only usable')

        usable_worlds = self.filter_worlds(worlds)
        print('worlds CSV filtered to only usable')

        state_table = self.base_state_table()
        print('base state table data')

        self.csv_to_db(usable_datacentres, 'datacentre')
        print('datacentre table created')

        self.csv_to_db(usable_worlds, 'world')
        print('world table created')

        self.csv_to_db(state_table, 'state')

    @staticmethod
    def get_data_from_url(url):
        """
        pulls data from web apis
        Parameters:
            url : str
                url to perform the http request on
        """
        request_data = requests.get(url)
        if request_data.status_code == 200:
            data = request_data.content.decode('utf-8-sig')
            return data.splitlines()
        sys.exit(f"{url} not available")

    def get_marketable_ids(self):
        """
        Retrieves data for marketable items
        """
        marketable_id_data = self.get_data_from_url("https://universalis.app/api/marketable")
        marketable_ids = marketable_id_data[0].split(',')
        marketable_ids[0] = marketable_ids[0].replace('[', '')
        marketable_ids[-1] = marketable_ids[-1].replace(']', '')
        return marketable_ids

    @staticmethod
    def filter_marketable_recipes(recipes, marketable_ids):
        """
        Filters recipes to marketable items
        Parameters:
            recipes : list
                Raw recipe data from api
            marketable_ids : list
                List of marketable item IDs
        """
        marketable_recipes = recipes[0:3]
        marketable_recipes[
            1] = 'csv_key,number,craft_type,recipe_level_table,item_result,amount_result,' \
                 'item_ingredient_0,amount_ingredient_0,item_ingredient_1,amount_ingredient_1,' \
                 'item_ingredient_2,amount_ingredient_2,item_ingredient_3,amount_ingredient_3,' \
                 'item_ingredient_4,amount_ingredient_4,item_ingredient_5,amount_ingredient_5,' \
                 'item_ingredient_6,amount_ingredient_6,item_ingredient_7,amount_ingredient_7,' \
                 'item_ingredient_8,amount_ingredient_8,item_ingredient_9,amount_ingredient_9'

        marketable_recipes[
            2] = 'INTEGER PRIMARY KEY,INTEGER,INTEGER,INTEGER,INTEGER,INTEGER,' \
                 'INTEGER,INTEGER,INTEGER,INTEGER,' \
                 'INTEGER,INTEGER,INTEGER,INTEGER,' \
                 'INTEGER,INTEGER,INTEGER,INTEGER,' \
                 'INTEGER,INTEGER,INTEGER,INTEGER,' \
                 'INTEGER,INTEGER,INTEGER,INTEGER'

        marketable_recipes[1] = tuple(marketable_recipes[1].split(','))
        marketable_recipes[2] = tuple(marketable_recipes[2].split(','))

        for line in recipes[3:]:
            split_line = line.split(',')
            crafted_item_id = split_line[4]
            if crafted_item_id in marketable_ids:
                marketable_recipes.append(tuple(split_line[:26]))
        return marketable_recipes

    @staticmethod
    def filter_datacentres(datacentres):
        """
        Filters for usable datacentres
        Parameters:
            datacentres : list
                Raw datacentre data from api
        """
        usable_datacentres = datacentres[0:3]
        usable_datacentres[1] = 'dc_key,name,region'
        usable_datacentres[2] = 'INTEGER PRIMARY KEY, STRING, INTEGER'
        usable_datacentres[1] = tuple(usable_datacentres[1].split(','))
        usable_datacentres[2] = tuple(usable_datacentres[2].split(','))

        for line in datacentres[3:]:
            split_line = line.split(',')
            datacentre_id = int(split_line[0])
            unquoted_line = []
            for item in split_line:
                unquoted_line.append(item.replace('"', ''))
            if 1 <= datacentre_id < 99:
                usable_datacentres.append(tuple(unquoted_line))
        return usable_datacentres

    @staticmethod
    def filter_worlds(worlds):
        """
        Filters for usable worlds
        Parameters:
            worlds : list
                Raw world data from api
        """
        usable_worlds = worlds[0:3]
        usable_worlds[1] = 'world_key, name, datacenter'
        usable_worlds[2] = 'INTEGER PRIMARY KEY, STRING, INTEGER'
        usable_worlds[1] = tuple(usable_worlds[1].split(','))
        usable_worlds[2] = tuple(usable_worlds[2].split(','))

        for line in worlds[3:]:
            split_line = line.split(',')
            world_id = int(split_line[0])
            is_public = split_line[-1]
            if is_public == 'True' and world_id != 38:
                split_line = [split_line[0], split_line[2].replace('"', ''), split_line[5]]
                usable_worlds.append(tuple(split_line))
        return usable_worlds

    @staticmethod
    def base_state_table():
        """
        Creates the base templated state table
        """
        state = ['key,0,1',
                 'marketboard_type,location,last_id',
                 'STRING,STRING NOT NULL UNIQUE,INTEGER',
                 'World,Zurvan,0']
        state[0] = tuple(state[0].split(","))
        state[1] = tuple(state[1].split(','))
        state[2] = tuple(state[2].split(','))
        state[3] = tuple(state[3].split(','))
        return state

    def add_gatherable(self):
        """
        Marks gatherable items in item table
        """
        gatherable_id_data = self.get_data_from_url("https://raw.githubusercontent.com"
                                                    "/xivapi/ffxiv-datamining/master/csv/"
                                                    "GatheringItem.csv")
        gatherable_items = []
        for item in gatherable_id_data[3:]:
            item_data = item.split(",")
            if item_data[3] == "True":
                gatherable_items.append(tuple((item_data[1],)))
        self.database.execute_query_many(
            "UPDATE item SET gatherable = 'True' WHERE item_num = ?", gatherable_items)

    # function used to convert original files into the DB
    def csv_to_db(self, csv_data, table_name):
        """
        Filters for usable worlds
        Parameters:
            csv_data : list
                Schema/data for db creation/population
            table_name : string
                Name of the table to be created in the database
        """
        database = self.database

        column_names = csv_data[1]
        data_types = csv_data[2]
        num_columns = len(column_names)

        question_marks = ""
        for _ in column_names:
            question_marks = question_marks + '?,'
        question_marks = question_marks[:-1]

        for column, name in enumerate(column_names):
            if name == "":
                column_names[column] = f'unnamedColumn{column}'

        # create a new table
        creation_command = f"CREATE TABLE IF NOT EXISTS {table_name} ("
        for i in range(num_columns):
            creation_command = creation_command + f"{column_names[i]} {data_types[i]}, "
        if table_name == "recipe":
            creation_command = creation_command + \
                               "FOREIGN KEY (item_result) REFERENCES item (item_num))"
        else:
            creation_command = creation_command[:-2] + ")"
        database.execute_query(creation_command)

        # insert all values
        insert_command = f"INSERT INTO {table_name} VALUES ({question_marks})"
        database.execute_query_many(insert_command, csv_data[3:])


'''
https://leetcode.com/problems/ambiguous-coordinates/
We had some 2-dimensional coordinates, like "(1, 3)" or "(2, 0.5)".
Then, we removed all commas, decimal points, and spaces, and ended up with the string s.
Return a list of strings representing all possibilities for what our original coordinates could have been.

Our original representation never had extraneous zeroes, so we never started with numbers like "00", "0.0", "0.00", "1.0", "001", "00.01",
or any other number that can be represented with less digits.
Also, a decimal point within a number never occurs without at least one digit occuring before it, so we never started with numbers like ".1".

The final answer list can be returned in any order.
Also note that all coordinates in the final answer have exactly one space between them (occurring after the comma.)

Example 1:
Input: s = "(123)"
Output: ["(1, 23)", "(12, 3)", "(1.2, 3)", "(1, 2.3)"]
'''
'''
Time:O(n**3)
Space:O(n**3)
'''
class Solution:
    def ambiguousCoordinates(self, s: str) -> List[str]:
        def make(frag):
            for i in range(1, len(frag)+1):
                left = frag[:i]
                right = frag[i:]
                if (not left.startswith('0') or left=='0') and (not right.endswith('0')):
                    yield left+('.' if i!=len(frag) else '')+right

        s = s[1:-1]
        return ['({}, {})'.format(*cand)
               for i in range(1, len(s))
               for cand in itertools.product(make(s[:i]), make(s[i:]))]


import csv, json
from collections import Counter

in_path1 = 'player_data.csv'
json_path = 'player_data.json'

# combine
with open(in_path1) as csvFile:
    csvReader = csv.DictReader(csvFile)
    in_data1 = {i:dict(row) for i, row in enumerate(csvReader)}

with open(json_path, 'w') as jsonFile:
    jsonFile.write(json.dumps(in_data1, indent=4))


import sys
sys.stdin = open('room.txt', 'r')
from collections import deque

def check(y, x, lv, start):
    qu = deque([[y, x, lv, start]])
    while qu:
        r, c, nlv, st = qu.popleft()
        for i in range(4):
            ny, nx = r + dy[i], c + dx[i]
            if 0 <= ny < N and 0 <= nx < N:
                if MAP[r][c] + 1 == MAP[ny][nx]:
                    qu.append([ny, nx, nlv+1, start])
    return (nlv, st)

dy = [-1, 0, 1, 0]
dx = [0, 1, 0, -1]

for tc in range(int(input())):
    N = int(input())
    MAP = [list(map(int, input().split())) for _ in range(N)]
    path = 0
    st = 21e8
    for i in range(N):
        for j in range(N):
            res = check(i, j, 1, MAP[i][j])
            if res[0] == path:
                st = min(st, res[1])
            elif res[0] > path:
                path = max(path, res[0])
                st = res[1]
    print('#{} {} {}'.format(tc+1, st, path))


# -*- coding: utf-8 -*-
"""
Created on Sun Jul 12 21:16:50 2020

@author: CITI
"""

#%%

import os
import torch
from pathlib import Path
import numpy as np

import pandas as pd
from scipy.special import softmax

from models.BaselineBLSTM import RNNDownBeatProc as bsl_blstm
from models.DrumAwareBeatTracker1 import DrumAwareBeatTracker as DA1
from models.DrumAwareBeatTracker2 import DrumAwareBeatTracker as DA2

from madmom.features.downbeats import DBNDownBeatTrackingProcessor as DownBproc
from madmom.features.downbeats import RNNDownBeatProcessor as RNNproc_api

import librosa
# from da_utils import *
import da_utils as utils
#import mir_eval

f_measure_threshold=0.07 # 70ms tolerance as set in paper
beats_per_bar = [3, 4]

#%%
def main():
    cuda_num = 0
    cuda_str = 'cuda:'+str(cuda_num)
    device = torch.device(cuda_str if torch.cuda.is_available() else 'cpu')

    # get model information from csv
    input_csv_name = 'spl_models_hmmparams.csv'
    input_csv_path = os.path.join('./',
                                  input_csv_name)

    df = pd.read_csv(input_csv_path)
    # creating inputinfo_list for evaluation
    modelinfo_list = utils.df2eval_dictlist(df, withMadmom =False)
    audio_file_path = './datasets/original/gtzan/audio/blues.00008.wav'
    for modelinfo in modelinfo_list:
        # break
        ### RNN init
        model_setting = modelinfo['model_setting']
        if modelinfo['model_type'] =='madmom_api':
            rnn = RNNproc_api()

        elif modelinfo['model_type'] =='bsl_blstm':
            rnn = bsl_blstm()

        elif modelinfo['model_type']=='DA1':
            rnn = DA1(**eval(model_setting))
        elif modelinfo['model_type']=='DA2':
            rnn = DA2(**eval(model_setting))

        else:
            print("can't find model for :", modelinfo['model_dir'])

        if not modelinfo['model_type'] =='madmom_api':
            model_fn = 'RNNBeatProc.pth'
            model_path = os.path.join(modelinfo['model_dir'] , model_fn)

            state = torch.load(model_path, map_location = device)
            rnn.load_state_dict(state)
#            rnn.cuda(device.index)

        ### DBN init
        ### can adjust HMM tempo range here
        max_bpm = 215 # default
        min_bpm = 55 # defaul

        hmm_proc = DownBproc(beats_per_bar = beats_per_bar, min_bpm = min_bpm,
                             max_bpm = max_bpm, num_tempi = modelinfo['n_tempi'],
                             transition_lambda = modelinfo['transition_lambda'],
                             observation_lambda = modelinfo['observation_lambda'],
                             threshold = modelinfo['threshold'], fps = 100)
        ### get feature of input audio file
        feat = utils.get_feature(audio_file_path)

        if modelinfo['model_type'] == 'madmom_api':
            activation  = rnn(audio_file_path)
        else:
            ### beat shape: (numof beats, 2)
            ### feat (feature) shape: (timeframes, 314 ),
            activation = utils.get_dlm_activation(rnn, device, feat)

        ### Process activation into beat estimation
        if type(activation) ==list:
            if len(activation) == 4:
            ### For DA models :
                (fuser_activation, mix_activation, nodrum_activation, drum_activation) = activation
                beat_fuser_est = hmm_proc( fuser_activation)
                beat_mix_est = hmm_proc( mix_activation)
                beat_nodrum_est = hmm_proc( nodrum_activation)
                beat_drum_est = hmm_proc( drum_activation)
            else:
                print("unexpected len of activation")
        else:
            fuser_activation = activation
            beat_fuser_est = hmm_proc( fuser_activation)
            beat_mix_est = [] # not implemented for bsl model
            beat_nodrum_est = [] # not implemented for bsl model
            beat_drum_est = [] # not implemented for bsl model

        ### save fuser results
        txt_out_folder = os.path.join('./inference/out_txt', modelinfo['model_simpname'])
        if not os.path.exists(txt_out_folder):
            Path(txt_out_folder).mkdir(parents = True, exist_ok = True)
        txt_out_path = os.path.join(txt_out_folder, os.path.basename(audio_file_path)+'.beats')
        np.savetxt(txt_out_path, beat_fuser_est, fmt = '%.5f')

        # downbeat = beat_fuser_est[np.where(beat_fuser_est[:,1]==1), 0]
        beat = beat_fuser_est[:, 0]
        ori_wav = utils.get_wav(audio_file_path)
        click = librosa.clicks(times = beat, sr = 44100, length = len(ori_wav))
        click_wav = ori_wav + click
        librosa.output.write_wav(os.path.join(txt_out_folder, os.path.basename(audio_file_path)), click_wav, sr = 44100)
#%%

if __name__ == "__main__":
    main()


class Solution:

    def extend(self,string,start,end):

        # print("string[start] == string[end]",string[start] == string[end])
        while((string[start] == string[end]) and (start>= 0) and (end<len(string))):

            start  = start-1
            end = end + 1

            if end == len(string):
                break

        return end-start-1,start+1,end-1
    def longestPalindrome(self,A):

        ans = 0
        for i in range(len(A)):
            # print(i)
            length,start_index,end_index= self.extend(A,i,i)
            # print("*"*10)
            if length > ans:
                ans = length
                require_start_index = start_index
                require_end_index = end_index

        for i in range(len(A)-1):
            length,start_index,end_index = self.extend(A,i,i+1)
            # print("length ",length,ans)
            if length > ans:
                ans = length
                require_start_index = start_index
                require_end_index = end_index
        # print("require_start_index",require_start_index,require_end_index)
        return A[require_start_index:require_end_index+1]

print("length of actual string ",len("abba"))
print(longestPalindrome("abba"))

# aaaabaaa


from rdflib import Graph, URIRef, Literal, BNode
from rdflib.namespace import FOAF, RDF

g = Graph()
g.bind("foaf", FOAF)

# Se añaden los datos
bob = URIRef("http://example.org/people/Bob")
g.add((bob, RDF.type, FOAF.Person))
g.add((bob, FOAF.name, Literal("Bob")))
g.add((bob, FOAF.age, Literal(38)))

# Para obtener un valor, se usa 'value'
print(g.value(bob, FOAF.age))

# Para cambiar un valor, se usa 'set'
g.set((bob, FOAF.age, Literal(39)))
print(g.value(bob, FOAF.age))


#from imports import MY_DIRNAME

from tree import *
import tree as t
from RNInterface import *

from Utils import *

from InrefaceAgent import keyboard as k, mouse, shortcuts as sh

from win32api import GetSystemMetrics

action_space = np.empty(2501)
action_space.fill(-1)
action_count=np.zeros(2501)
tree = []
img_states = {}
states = {}
unique_states = {}

if __name__ == "__main__":

    print("starting")
    app_pid = sh.open_app_foreground("C:\\Program Files\\Elmer 8.4-Release\\bin", "ElmerGUI.exe")
    #sh.OpenApp("C:\\Program Files (x86)\\FreeMat\\bin", "FreeMat.exe")
    time.sleep(2)
    sh.max()
    time.sleep(1)

    Width = GetSystemMetrics(0)
    Height = GetSystemMetrics(1)

    for i in range(4):

        '''image, path = save_image(i)

        elements = buildElements(path,i,[Width,Height])

        print(Width, Height)

        mouse.LeftClick(elements[-4].x_center,elements[-4].y_center)
        if img_exists(elements, image):
            print("state already exists")
            # give negative reward
        else:
            states[path] = elements
        tree,IDs = buildTree(elements)
        print("length of tree: ",len(tree))
        time.sleep(1)'''

        state, path = GetState(i,img_states,states,tree,action_space, action_count, unique_states)
        print(tree)
        print(action_space[action_space[(action_space).astype(int)] != -1])
        # action = i

    # app_pid, action_count, img_states, states, unique_states = reset(app_pid, "C:\\Program Files\\Elmer 8.4-Release\\bin", "ElmerGUI.exe", "\\RL\\images",
    #                                                                          "\\RL\\output", unique_states)
    # print(tree)
    print(img_states)
    print(states)
    print(action_space[action_space != -1])
    print(unique_states)

    # for i in range(len(elements)):


import re
# \d	Returns a match where the string contains digits (numbers from 0-9)

sentence = "There are 1210 people in this city-1, 1587 in the city-2 and 1877 in the city-3."
occ = re.findall("\d+", sentence)

num_list = map(int, occ)

print(max(num_list))

# num_list = map(int, occ)
# print(list(num_list))

"""
RegEx is a sequence of characters that forms a search pattern.
RegEx can be used to check if a string contains the specified search pattern.

function     Description
findall	     Returns a list containing all matches
search	     Returns a Match object if there is a match anywhere in the string
split	     Returns a list where the string has been split at each match
sub	         Replaces one or many matches with a string
"""


import sys
import numpy as np

INF = 9999999

class Graph:
	def __init__(self, V, G):
		self.V = V
		self.G = G

	def prim(self):
		selected = [0] * self.V
		no_edge = 0
		selected[0] = True
		min_tree = 0
		print("Edge : Weight")
		while (no_edge < self.V - 1):
			minimum = INF
			x = 0
			y = 0
			for i in range(V):
				if selected[i]:
					for j in range(self.V):
						if ((not selected[j]) and self.G[i][j]):
							if minimum > self.G[i][j]:
								minimum = self.G[i][j]
								x = i
								y = j
			print(str(x) + "-" + str(y) + ":" + str(self.G[x][y]))
			min_tree += self.G[x][y]
			selected[y] = True
			no_edge += 1
		print("Min Tree: " + str(min_tree))

if __name__=='__main__':
	V = 8
	G = [[0, 3, 0, 0, 0, 34, 0, 80],
         [3, 0, 0, 1, 0, 0, 0, 68],
         [0, 0, 0, 0, 23, 0, 12, 0],
         [0, 1, 0, 0, 53, 0, 0, 39],
        [0, 0, 23, 53, 0, 0, 68, 14],
        [34, 0, 0, 0, 0, 0, 0, 25],
        [0, 0, 12, 0, 68, 0, 0, 99],
        [80, 68, 0, 39, 14, 25, 99, 0]]

	graph = Graph(V,G)
	graph.prim()


from .settings_common import *

# SECURITY WARNING: don't run with debug turned on in production!

DEBUG = True

# 送信したメールをコンソールに表示(実際には送信しない)

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

# 開発中のメディアルート

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# django-debug-toolbar 設定

INTERNAL_IPS = [
    '127.0.0.1',
]

# ログ設定

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,

    'loggers': {
        'django': {
            'handlers': ['console'],
            'level': 'INFO',
        },
        'hiroba': {
            'handlers': ['console'],
            'level': 'DEBUG',
        },
    },

    'handlers': {
        'console': {
            'level': DEBUG,
            'class': 'logging.StreamHandler',
            'formatter': 'dev'
        },
    },

    'formatters': {
        'dev': {
            'format': '\t'.join([
                '%(asctime)s',
                '[%(levelname)s]',
                '%(pathname)s(Line:%(lineno)d',
                '%(message)s'
            ])
        },
    }
}


import csv
import os

class Purchase:
    def __init__(self, customer_id=None, product_id=None, amount_bought=None):
        self.customer_id = customer_id
        self.product_id = product_id
        self.amount_bought = amount_bought

    def __str__(self):
        sell = f'{self.customer_id}, {self.product_id}, {self.amount_bought}'
        return sell

purchases_made = []
space_small = """
              """
space_big = """

            """
with open('products.csv', 'r+') as csv_file:
    file_product = csv.reader(csv_file)
    data_product = list(file_product)
with open('customers.csv', 'r+') as csv_file:
    file_customer = csv.reader(csv_file)
    data_customer = list(file_customer)
with open("products.csv", "a+", newline="") as fp:
    writer_product = csv.writer(fp, dialect='excel')

# still trying to fix issues with customer not being present.
def check_customer():
    customer_id_from_user = str(input("Enter customer id to purchase: "))
    with open('customers.csv', 'r') as csv_file:
        file_customer = csv.reader(csv_file)
        data_customer = list(file_customer)
        idx_data_customer = [item[0] for item in data_customer]
        print(idx_data_customer)
        for i in range(len(data_customer)):
            if customer_id_from_user in idx_data_customer:
                print()
                return print("customer found.")
            else:
                print("Customer not found.enter a valid customer Id")
                return check_customer()

def purchase_item():
    items = []
    all_total = []
    all_quantity = []
    customer_exists = False
    product_exists = False
    total_purchase = 0
    continue_purchase = True

    with open('customers.csv', 'r+') as csv_file:
        file_customer = csv.reader(csv_file)
        data_customer = list(file_customer)

    with open('products.csv', 'r+') as csv_file:
        file_product = csv.reader(csv_file)
        data_product = list(file_product)

    customer_id_from_user = input("Enter customer id to purchase:")

    for line in data_customer:
        if customer_id_from_user == line[0]:
            print(f"Customer name is: {line[1]}")
            customer_id = line[0]
            customer_name = line[1]
            continue_purchase = True

    while continue_purchase:
        product_id = input("Enter product id to purchase: ")
        for i in data_product:
            if product_id == i[0]:
                product_exists = True
                print(i)
                product_id = i[0]
                product_name = i[1]
                product_quantity = i[2]
                product_price = i[3]

        while True:
            purchase_quantity = int(input("Enter the quantity you would like to purchase for the product: "))
            total = float(product_price) * int(purchase_quantity)
            all_total.append(total)
            all_quantity.append(purchase_quantity)
            items.append(product_name)
            if purchase_quantity > int(product_quantity):
                print(f'\nProducts ordered is more than stock\nProducts available: {product_quantity}\n')
            else:
                option = input("Enter Y to add item to purchase N to cash out: ").upper()
                if option == "Y":
                    continue_purchase
                    break
                elif option == "N":
                    continue_purchase = False
                    while True:
                        amount_tendered = int(input("Enter amount given: \n"))
                        if amount_tendered < sum(all_total):
                            print("Please enter an amount greater or equal to the total.")
                        else:
                            receipt = f'''
                            Customer Name: {customer_name}
                            Products: {items}
                            Total: {all_total}
                            '''
                            print(receipt)
                            print(f'Your total is: {sum(all_total)}')
                            change = amount_tendered - sum(all_total)
                            print(f'Change: {change}')
                        break

            break
    with open("purchase.csv", "a+", newline="") as fp:
        orderdetails = [customer_id, product_id, sum(all_total)]
        print(orderdetails)
        wr = csv.writer(fp, dialect='excel')
        wr.writerow(orderdetails)


#!/usr/bin/env python
from sys import exit, argv
import logging
from HTMLParser import HTMLParser
from httplib import HTTPConnection

_log = logging.getLogger(__name__)

class RedditHTMLParser(HTMLParser):
	def __init__(self):
		HTMLParser.__init__(self)
		self.reset()

	def reset(self):
		HTMLParser.reset(self)
		self.Record = False
		self.RecordSub = False
		self.RecordLink = False
		self.Depth = 0
		self.Subscribers = 0
		self.Links = []
		self.LinkNames = []

	def handle_starttag(self, tag, attrs):
		if tag == 'div' and ('class', 'usertext-body') in attrs:
			self.Record = True
		if tag == 'span' and ('class', 'number') in attrs:
			self.RecordSub = True
		if not self.Record:
			return
		if tag == 'div':
			self.Depth += 1
		elif tag == 'a':
			for (attr, val) in attrs:
				if attr == 'href':
					self.RecordLink = True
					self.Links.extend(val.split("+"))

	def handle_data(self, data):
		if self.RecordSub:
			self.Subscribers = int(data.replace(',', ''))
		if self.RecordLink:
			self.LinkNames.append(data)
			self.RecordLink = False

	def handle_endtag(self, tag):
		if self.Record and tag == 'div':
			self.Depth -= 1
			self.Record = self.Depth != 0
		else:
			self.RecordSub = False

class RedditParser:
	def __init__(self):
		self.connection = HTTPConnection('www.reddit.com')
		self.parser = RedditHTMLParser()

	def get_info(self, subreddit):
		try:
			_log.debug('GET ' + '/r/%s/' % subreddit.lower())
			self.connection.request('GET', '/r/%s/' % subreddit.lower())
			html = self.connection.getresponse().read()
		except Exception as e:
			_log.error("Unable to get subreddit '%s'\n%s" % (subreddit, e))
			return
		self.parser.reset()
		self.parser.feed(html)
		reddits = set()
		for link, name in zip(self.parser.Links, self.parser.LinkNames):
			link = link.strip()
			name = name.strip()
			if link.find(' ') != -1:
				continue
			elif link.startswith('http://www.reddit.com/r/'):
				reddit = link[24:]
			elif link.startswith('/r/'):
				reddit = link[3:]
			elif name.find(' ') != -1:
				continue
			elif name.startswith('http://www.reddit.com/r/'):
				reddit = name[24:]
			elif name.startswith('www.reddit.com/r/'):
				reddit = name[17:]
			elif name.startswith('reddit.com/r/'):
				reddit = name[13:]
			elif name.startswith('/r/'):
				reddit = name[3:]
			elif name.startswith('r/'):
				reddit = name[2:]
			else:
				continue
			if reddit[-1] == '/':
				reddit = reddit[:-1]
			if reddit.find('/') == -1:
				_log.debug('Found subreddit: %s' % reddit.lower())
				reddits.add(reddit.lower())
		return reddits, self.parser.Subscribers

	def __del__(self):
		self.parser.close()
		self.connection.close()

def visit(subreddit, visited, tab):
	if subreddit in visited:
		return visited
	tabs = ''.join(['\t' for i in xrange(tab)])
	_log.debug(tabs + subreddit)
	visited.add(subreddit)
	info = parser.get_info(subreddit)
	if not info or len(info) < 1:
		return visited
	links, subs = info
	for l in links:
		visited = visit(l, visited, tab+1)
	return visited

if __name__ == "__main__":
	logging.basicConfig(level=logging.DEBUG)
	_log = logging.getLogger("RedditParser")
	if len(argv) < 2 or (argv[1] == '-r' and len(argv) < 3):
		_log.error('No subreddit input found.\n'
				'Usage: %s subreddit [subreddit2 [...]]' % argv[0])
		exit(1)
	parser = RedditParser()
	rec = argv[1] == '-r'
	if rec:
		args = argv[2:]
	else:
		args = argv[1:]
	for subreddit in args:
		if rec:
			visit(subreddit, set(), 0)
		else:
			_log.debug('SUBREDDIT: %s' % subreddit)
			links, subscribers = parser.get_info(subreddit)
			_log.debug('\tSUBSCRIBERS: %s' % subscribers)
			if links:
				for link in links:
					_log.debug('\t%s' % link)
			_log.debug("")


# Given a range of 2 numbers (i.e) L and R count the number of prime numbers in the range (inclusive of L and R ).
# Input Size : L <= R <= 100000(complexity O(n) read about Sieve of Eratosthenes)
# Sample Testcase :
# INPUT
# 2 5
# OUTPUT
# 3

a, b = map(int, input().split())
c = [2, 3, 5, 7]
d = []

for i in range(a, b + 1):
    if i % 2 != 0 and i % 3 != 0 and i % 5 != 0 and i % 7 != 0:
        d.append(i)
    if i in c:
        d.append(i)

print(len(d))


#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the solve function below.
def solve(s):
    b = s.split()
    z = []
    for i in range(len(b)):
        x= b[i][0].capitalize()
        y = b[i][0:].replace(b[i][0],x,1)
        z.append(y)
    result =" ".join(z)
    return result

if __name__ == '__main__':

    s = input()

    result = solve(s)
    print(result)


import random
import string

#encryption must be in lower case

#this is the Plugboard class. This takes a list of 2-tuples. Each tuple is the two letters you want to swap together.
class Plugboard:
    def __init__(self, swaps):
        self.swaps = swaps
#this is the Rotors class. This must be a list of letters (strings). Each letter in the alphabet must be there.
class Rotors:
    def __init__(self, settings):
        self.settings = settings
        #error checking, there cannot be any duplicates, nonalpha characters or less than 26 letters
        if len(settings) != 26:
            raise Exception("Rotor must have 26 unique letters")
        if len(settings) != len(set(settings)):
            raise Exception("Rotor must have 26 unique letters")
        for i in settings:
            if i.isalpha() != True:
                raise Exception("Rotor must have 26 unique letters")

#this is the main machine, where the encryption happens
class Enigma(Rotors, Plugboard):
    def __init__(self, swaps, settings, settings2, settings3):
        Plugboard.__init__(self, swaps)
        self.settings = settings
        self.settings2 = settings2
        self.settings3 = settings3

#this function increments the rotor provided.
    def increment(self, rotor):
        for i in range(0, len(rotor)-1):
            if rotor[(i%len(rotor))-1] == 0:
                break
            else:
                temp = rotor[(i%len(rotor))-1]
                rotor[(i%len(rotor))-1] = rotor[i]
                rotor[i] = temp
        return rotor

#this function encrypts a single letter and increments the first rotor.
    def encrypt(self,i):
        alphabet = list(map(chr, range(97, 123)))
        index = alphabet.index(i)
        i = self.settings[index]
        index = alphabet.index(i)
        i = self.settings2[index]
        index = alphabet.index(i)
        i = self.swap(self.settings3[index])
        self.settings = self.increment(self.settings)
        return i

#this function decrypts a single letter and increments the first rotor.
    def decrypt(self,i):
        alphabet = list(map(chr, range(97, 123)))
        i = self.swap(i)
        index = self.settings3.index(i)
        i = alphabet[index]
        index = self.settings2.index(i)
        i = alphabet[index]
        index = self.settings.index(i)
        i = alphabet[index]
        self.settings = self.increment(self.settings)
        return i

#this function checks to see if the encrypted letter has been swapped on the plugboard. If so, it is swapped.
    def swap(self,n):
        for x in self.swaps:
            if n in x:
                for j in x:
                    if j != n:
                        n = j
                        break
        return n

#this function encrypts an entire message. Every 26 times the first rotor is incremented, it increments the next rotor and so on.
    def encrypt_input(self, s):
        message = ""
        fst_rotation = 0
        snd_rotation = 0
        trd_rotation = 0
        for i in s:
            if i != " ":
                message = message + self.encrypt(i)
                fst_rotation+=1
                if fst_rotation % 26 == 0:
                    self.settings2 = self.increment(self.settings2)
                    snd_rotation+=1
                    if snd_rotation % 26 == 0:
                        self.settings3 = self.increment(self.settings3)
                        trd_rotation+=1
        return message

#this function decrypts the entire message. The plugboard position, original 3 rotor positions in addition to the decrypted message must be provided. Every 26 times the first rotor is incremented, it increments the next rotor and so on.
    def decrypt_input(self, old_swaps, old_settings, old_settings2, old_settings3, e_input):
        message = ""
        fst_rotation = 0
        snd_rotation = 0
        trd_rotation = 0
        self.reset(old_swaps, old_settings, old_settings2, old_settings3)
        for i in e_input:
            message = message + self.decrypt(i)
            fst_rotation+=1
            if fst_rotation % 26 == 0:
                    self.settings2 = self.increment(self.settings2)
                    snd_rotation+=1
                    if snd_rotation % 26 == 0:
                        self.settings3 = self.increment(self.settings3)
                        trd_rotation+=1
        return message

#this function resets the rotor and swap settings for decryption. If the rotor and swap settings are correct, the message will be successfully decrypted.
    def reset(self, old_swaps, old_settings, old_settings2, old_settings3):
        self.swaps = old_swaps
        self.settings = old_settings
        self.settings2 = old_settings2
        self.settings3 = old_settings3


from pypylon import pylon
from pypylon import genicam
import cv2
import tkinter as tk

# code from/based off: https://github.com/drscotthawley/image-capture-opencv/blob/master/capture.py

camera = pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateFirstDevice())

# camera needs to be opened to asjust the settings
camera.Open()

# must be smaller than or equal 0.999969
camera.BslBrightness.SetValue(0)
camera.BslContrast.SetValue(0)

# hue and saturation automatic values
camera.BslSaturation.SetValue(1)
camera.BslHue.SetValue(0)

# Set the upper limit of the camera's frame rate
camera.AcquisitionFrameRateEnable.SetValue(True)
# fps will not go past 20, there are many factors that limit the value
camera.AcquisitionFrameRate.SetValue(20)

# variables for consecutive differencing, black and white, and live view. set to false to begin
c_sub=False
bw=False
l_view=False

# basic setters to change the settings
def changeBrightness(newB):
    camera.BslBrightness.SetValue(newB)

def changeContrast (newC):
    camera.BslContrast.SetValue(newC)

def changeFPS(newF):
    camera.AcquisitionFrameRate.SetValue(newF)

# newE is in microseconds
def changeExposure(newE):
    camera.ExposureTime.SetValue(newE)

def changeHue(newH):
    camera.BslHue.SetValue(newH)

def changeSaturation(newS):
    camera.BslSaturation.SetValue(newS)

# creating tkinter tab
root = tk.Tk()
frame = tk.Frame(root)
frame.pack()

# function that is called if the user selects consecutive differencing in color
def startC():
    global c_sub
    c_sub=True
    global l_view
    l_view=True
    root.destroy()

# function that is called if the user selects consecutive differencing in black and white
def startC2():
    global c_sub
    c_sub=True
    global bw
    bw=True
    global l_view
    l_view=True
    root.destroy()

# creates buttons

button1 = tk.Button(frame,
                   text="Start consecutive differencing (in color)", fg="blue",command=startC)
button1.pack(side=tk.RIGHT)

button2 = tk.Button(frame,
                   text="Start consecutive differencing (in black and white)", fg="blue",command=startC2)
button2.pack(side=tk.RIGHT)

root.mainloop()

# converts image to pixel format, either BGR or Mono16
converter = pylon.ImageFormatConverter()
if(bw):
    converter.OutputPixelFormat = pylon.PixelType_Mono16
else:
    converter.OutputPixelFormat = pylon.PixelType_BGR8packed
converter.OutputBitAlignment = pylon.OutputBitAlignment_MsbAligned

# creates tkinter tab and sliders for brightness, contrast, hue, saturation, exposure, and frame rate
usercontrols=tk.Tk()
b=tk.Scale(usercontrols, from_=0, to=99, label="brightness")
b.pack(side='right')
c=tk.Scale(usercontrols, from_=0, to=99, label="contrast")
c.pack(side='right')

h=tk.Scale(usercontrols, from_=-180, to=180, label="hue")
h.pack(side='right')
saturation=tk.DoubleVar()
saturation.set(1)
s=tk.Scale(usercontrols, from_=0, to=2, label="saturation", variable=saturation)
s.pack(side='right')

exposure=tk.DoubleVar()
exposure.set(0.1)
e=tk.Scale(usercontrols, from_=0.012, to=0.999, digits=4, resolution=0.001, label="exposure (seconds)", variable=exposure)
e.pack(side='right')

framerate=tk.DoubleVar()
framerate.set(2)
f=tk.Scale(usercontrols, from_=1, to=20, label="frame rate (fps)", variable=framerate)
f.pack(side='right')

# tkinter entry/button that gives user the ability to enter a value for the exposure
tk.Label(usercontrols, text="Exposure (in seconds)").pack()
e1=tk.Entry(usercontrols)
e1.pack()

def setE():
    exposure.set(float(e1.get()))

tk.Button(usercontrols, text="set", command=setE).pack()

# function from https://github.com/basler/pypylon/blob/master/samples/opencv.py
def get_img():
    camera.StartGrabbing(pylon.GrabStrategy_LatestImageOnly)
    grabResult = camera.RetrieveResult(5000, pylon.TimeoutHandling_ThrowException)

    # once the image has successfully been taken
    if grabResult.GrabSucceeded():
        # convert the image to the correct format and save its data to a variable img1
        image = converter.Convert(grabResult)
        img1 = image.GetArray()

    # tell the camera to stop grabbing frames
    camera.StopGrabbing()

    # return the image
    return img1

# grabs the current image and sets the var prev to it
prev=get_img()

# main loop that continues to run after user chooses which consecutive differencing they want
while True:

    img=get_img()

    # updating the tkinter tab
    usercontrols.update()

    # if l_view is true then displays the live view in a tab labeled "live view"
    if(l_view):
        cv2.namedWindow('Live View', cv2.WINDOW_NORMAL)
        cv2.imshow('Live View', img)
        cv2.resizeWindow("Live View", 1000,1000)
        k = cv2.waitKey(1)
        if k == 27:
            break

    # if c_sub (var for consecutive differencing) is true then displays the consecutive differencing in a tab labeled "consecutive differencing"
    if(c_sub):
        current=img
        cv2.namedWindow('Consecutive Differencing', cv2.WINDOW_NORMAL)
        cv2.imshow('Consecutive Differencing', cv2.absdiff(current, prev))
        cv2.resizeWindow('Consecutive Differencing', 1000,1000)
        prev=current
        k = cv2.waitKey(1)
        if k == 27:
            break

    # updating parameters based off of slider values
    changeBrightness((b.get()*.01))
    changeContrast((c.get()*.01))
    changeHue(h.get())
    changeSaturation(s.get())
    changeFPS(f.get())
    changeExposure(e.get()*1000000)

# when the loop is broken (i.e. the user clicks the esc key) the camer is closed, windows are closed, and program is exited
camera.Close()
cv2.destroyAllWindows()
exit()


import bisect

t = int(input())

for _ in range(t):
    n = int(input())
    q = list(map(int, input().split()))
    res = []
    unused = list(range(-n, 0))
    pos = True
    for i in range(n):
        if i == 0 or q[i] > q[i - 1]:
            res.append(q[i])
            k = bisect.bisect_left(unused, -q[i])
            unused.pop(k)
        else:
            if len(unused) == 0:
                pos = False
                break
            if -unused[-1] > q[i]:
                pos = False
                break
            res.append(-unused[-1])
            unused.pop()
    if pos:
        print(*res)
    else:
        print(-1)


"""
Plot galactic chemical evolution.
"""

import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
from astropy.table import Table

try:
    catalog
except NameError:
    catalog = Table.read("../tc-cse-regularized-apogee-catalog.fits.gz")
    ok = catalog["OK"] * (catalog["R_CHI_SQ"] < 3) * (catalog["TEFF"] > 4000) * (catalog["TEFF"] < 5500)

else:
    print("USING PRE-LOADED CATALOG")

log_scale = True
gridsize = 100
elements =  [
 'Al',
 'Ca',
 'C',
 'K',
 'Mg',
 'Mn',
 'Na',
 'Ni',
 'N',
 'O',
 'Si',
 'S',
 'Ti',
 'V']

fig, axes = plt.subplots(int(len(elements)/2.), 2, figsize=(9, 12))
axes = np.array(axes).flatten()

extents = {
    None: (-1, +1),
    "Al": (-0.6, 0.6),
    "Ca": (-0.6, 0.6),
    "Mg": (-0.6, 0.6),
    "Mn": (-0.6, 0.6),
    "Si": (-0.6, 0.6),
    "S": (-0.6, 0.6)
}

for i, (ax, element) in enumerate(zip(axes, elements)):

    x = catalog["FE_H"]
    y = catalog["{}_H".format(element.upper())] - catalog["FE_H"]

    ylims = extents.get(element, extents[None])
    ax.hexbin(x[ok], y[ok], cmap="viridis", bins="log" if log_scale else None,
        gridsize=gridsize,
        extent=(-2, 0.5, ylims[0], ylims[1]), mincnt=None,
        rasterized=True)

    ax.set_xlim(-2, 0.50)
    ax.set_ylim(ylims)

    ax.set_ylabel(r"$[\rm{{{0}}}/\rm{{Fe}}]$".format(element.title()))
    if ax.is_last_row():
        ax.set_xlabel(r"$[\rm{Fe}/\rm{H}]$")
    else:
        ax.set_xticklabels([])

    if element not in extents:
        ax.set_yticks([-1, -0.5, 0, 0.5, 1.0])
    else:
        ax.set_yticks([-0.5, 0, 0.5])

    # Show scaled-solar line.
    ax.axhline(0, c="#FFFFFF", alpha=0.5, linestyle=":")
    ax.axvline(0, c="#FFFFFF", alpha=0.5, linestyle=":")

    # Show a representative error bar.
    xerr = np.mean(catalog["E_FE_H"])
    yerr = np.mean(np.sqrt(
        catalog["E_FE_H"]**2 + catalog["E_{}_H".format(element.upper())]**2))

    xpos = ax.get_xlim()[0] + 0.95 * np.ptp(ax.get_xlim())
    ypos = ax.get_ylim()[0] + 0.05 * np.ptp(ax.get_ylim())

    #ax.errorbar([xpos], [ypos], xerr=[xerr], yerr=[yerr], fmt=None,
    #    ecolor="#FFFFFF", zorder=10, lw=2)

fig.tight_layout()
fig.savefig("test-step-gce.pdf", dpi=300)


#สกัดหัวข้อข่าวจากเว็ปวิศวะ
#ดูคำอธบายในslide
import urllib.request

url = 'http://www.eng.chula.ac.th'
web = urllib.request.urlopen(url)
for line in web:
    line = line.decode()
    if 'news-title' in line:
        k = line.find('<a href')
        k = line.find('>', k)
        j = line.find('</a>', k)
        print(line[k+1:j])

#web scraping


# -*- coding: utf-8 -*-
import numpy as np
from dku_error_analysis_utils import DkuMEAConstants
import logging
from mealy_local.error_analyzer import ErrorAnalyzer
from dku_error_analysis_tree_parsing.tree_parser import TreeParser

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO, format='Error Analysis Plugin | %(levelname)s - %(message)s')

class DkuErrorAnalyzer(ErrorAnalyzer):
    """
    DkuErrorAnalyzer analyzes the errors of a DSS prediction model on its test set.
    It uses model predictions and ground truth target to compute the model errors on the test set.
    It then trains a Decision Tree on the same test set by using the model error as target.
    The nodes of the decision tree are different segments of errors to be studied individually.
    """

    def __init__(self, model_handler, max_num_rows=DkuMEAConstants.MAX_NUM_ROWS, param_grid=None,
        random_state=65537):

        self._model_handler = model_handler
        self._target = model_handler.get_target_variable()
        self._model_predictor = model_handler.get_predictor()
        self._max_num_rows = max_num_rows

        probability_threshold = self._model_predictor.params.model_perf.get('usedThreshold', None)
        feature_names = self._model_predictor.get_features()

        estimator = model_handler.get_clf()
        if not hasattr(estimator, "_estimator_type"):
            # This param is needed for the analyzer to properly treat the estimator as a
            # regressor/classifier. It can be absent if the model does not match the sklearn
            # convention for estimators (see sc-78591).
            estimator._estimator_type = "regressor" if model_handler.get_prediction_type() == "REGRESSION" else "classifier"
        super(DkuErrorAnalyzer, self).__init__(
            estimator, feature_names, param_grid, probability_threshold, random_state
        )

        self._train_x = None
        self._train_y = None

        self._error_df = None

        self._tree = None

    @property
    def tree(self):
        if self._tree is None:
            self._parse_tree()
        return self._tree

    @property
    def error_df(self):
        if DkuMEAConstants.ERROR_COLUMN not in self._error_df:
            self._error_df.loc[:, DkuMEAConstants.ERROR_COLUMN] = self._error_train_y
        return self._error_df

    def _parse_tree(self):
        tree_parser = TreeParser(self._model_handler, self.error_tree.estimator_,
                                 self.preprocessed_feature_names)
        tree = tree_parser.create_tree(self.error_df)
        tree_parser.parse_nodes(tree, self._error_train_x)
        self._tree = tree

    def fit(self):
        """
        Trains a Decision Tree to discriminate between samples that are correctly predicted or wrongly predicted
        (errors) by a primary model.
        """

        self._prepare_data_from_dku_saved_model()

        super(DkuErrorAnalyzer, self).fit(self._train_x, self._train_y)

    def _preprocess_dataframe(self, df, with_target=True):
        """ Preprocess input DataFrame with primary model preprocessor """
        if with_target and self._target not in df:
            raise ValueError('The dataset does not contain target "{}".'.format(self._target))
        if with_target:
            x, input_mf_index, _, y = self._model_predictor.preprocessing.preprocess(
                df,
                with_target=True)
            return x, y, input_mf_index

        return self._model_predictor.preprocessing.preprocess(df)[0]

    def _prepare_data_from_dku_saved_model(self):
        """ Preprocess and split original test set from Dku saved model
        into train and test set for the error analyzer """
        np.random.seed(self.random_state)
        try:
            original_df = self._model_handler.get_test_df()[0][:self._max_num_rows]
        except Exception as e:
            logger.warning('Cannot retrieve original test set: %s.' +
                'The plugin will take the whole original dataset.', e)
            original_df = self._model_handler.get_full_df()[0][:self._max_num_rows]
        self._train_x, self._train_y, input_mf_index = self._preprocess_dataframe(original_df)
        original_train_df = original_df.loc[input_mf_index]
        self._error_df = original_train_df.drop(self._target, axis=1)

    def evaluate(self, dku_test_dataset=None, output_format='dict'):
        """ Return ErrorAnalyzer summary metrics """
        if dku_test_dataset is None:
            return super(DkuErrorAnalyzer, self).evaluate(self._train_x, self._train_y,
                                                          output_format=output_format)
        test_df = dku_test_dataset.get_dataframe()
        test_x, test_y, _ = self._preprocess_dataframe(test_df)
        return super(DkuErrorAnalyzer, self).evaluate(test_x, test_y.values,
                                                      output_format=output_format)


import os
import pwd
import grp
import errno
from shutil import copyfile
from quik import FileLoader, Template
import urllib
import autotest
from collections import namedtuple
from fileio.dirio import mkdirp
import shutil
from exthandlers import extension_handles
from log import log

def get_sq_ext(filename):
    """
    Gets the squadron extension from filename.
    Keyword arguments:
        filename -- the file to get the extension from
    """
    try:
        return filename[filename.rindex('~')+1:]
    except ValueError:
        return ''

def get_file_ext(filename):
    """
    Gets the extension (or compound extension) from a filename

    Keyword arguments:
        filename -- the file to get the extension from
    """
    root,ext = os.path.splitext(filename)
    if ext.lower() in ['.gz', '.bz2', '.xz']:
        other = os.path.splitext(root)[1]
        if other.lower() in ['.tar']:
            # Make sure we bundle file.tar.gz as 'tar.gz'
            return (other[1:] + ext).lower()

    return ext[1:].lower()

FileConfig = namedtuple('FileConfig', 'filepath atomic user group mode')

def get_config(finalfile, filename, config, already_configured):
    path_items = filename.split(os.path.sep)
    accum = ""
    file_settings = []
    for item in path_items[:-1]:
        # loop over all the directories, but not the filename
        path = os.path.join(accum, item)
        path_and_sep = path + os.path.sep
        if path_and_sep in config and path_and_sep not in already_configured:
            file_settings.append(config[path + os.path.sep])
            already_configured.add(path_and_sep)
        accum = path

    if filename in config and config[filename] not in file_settings:
        if filename not in already_configured:
            file_settings.append(config[filename])
            already_configured.add(filename)

    if os.path.isdir(finalfile):
        new_files = os.listdir(finalfile)
        for f in new_files:
            new_finalfile = os.path.join(finalfile, f)
            new_filename = os.path.join(filename, f)
            file_settings.extend(get_config(new_finalfile, new_filename, config, already_configured))

    return file_settings

def apply_config(base_path, file_configs, dry_run):
    for file_config in file_configs:
        uid = -1
        gid = -1
        if file_config.user is not None:
            uid = pwd.getpwnam(file_config.user).pw_uid
        if file_config.group is not None:
            gid = grp.getgrnam(file_config.group).gr_gid

        actual_file = os.path.join(base_path, file_config.filepath)

        if not dry_run:
            if uid != -1 or gid != -1:
                log.debug("Changing %s to uid %s gid %s", actual_file, uid, gid)
                os.chown(actual_file, uid, gid)
        else:
            if uid != -1 or gid != -1:
                log.info("Would change %s to uid %s gid %s", actual_file, uid, gid)

        if file_config.mode is not None:
            mode = int(file_config.mode, 8)
            log.debug("Changing mode of %s to %s", actual_file, file_config.mode)
            os.chmod(actual_file, mode)

class DirectoryRender:
    def __init__(self, basedir):
        if not os.path.isabs(basedir):
            basedir = os.path.abspath(basedir)
        self.loader = FileLoader(basedir)
        self.basedir = basedir

    def render(self, destdir, inputhash, resources, dry_run = False,
            currpath = "", config = {}):
        """
        Transforms all templates and downloads all files in the directory
        supplied with the input values supplied. Output goes in destdir.

        Keyword arguments:
            destdir -- the directory to put the rendered files into
            inputhash -- the dictionary of input values
        """
        items = sorted(os.listdir(os.path.join(self.basedir, currpath)))

        if currpath == "" and 'config.sq' in items:
            # do config.sq stuff only in the top level directory
            config_items = self.parse_config_sq(
                    os.path.join(self.basedir, 'config.sq'), inputhash)

            real_config = {}
            for config_item in config_items:
                real_config[config_item.filepath] = config_item

            config = real_config
            items.remove('config.sq')

        result = {}
        already_configured = set()
        for filename in items:
            # the path of the source file relative to the basedir
            relpath = os.path.join(currpath, filename)

            # the absolute path of the source file
            abs_source = os.path.join(self.basedir, relpath)

            # the absolute path of the destination file, templated
            dest = self._template(os.path.join(destdir, relpath), inputhash)

            if os.path.isdir(abs_source):
                mkdirp(dest)
                # Needs a slash because this is a directory
                stripped = dest[len(destdir)+1:] + os.path.sep

                key = relpath + os.path.sep
                if key in config:
                    result[key] = config[key].atomic

                apply_config(destdir, get_config(dest, stripped, config, already_configured), dry_run)
                result.update(self.render(destdir, inputhash, resources, dry_run, relpath, config))
            else:
                ext = get_sq_ext(filename)
                if ext in extension_handles:
                    # call the specific handler for this file extension
                    finalfile = extension_handles[ext](**{'loader':self.loader,
                        'inputhash':inputhash,
                        'relpath':relpath,
                        'abs_source': abs_source,
                        'dest':dest,
                        'resources':resources})
                else:
                    # otherwise, just copy the file
                    copyfile(abs_source, dest)
                    finalfile = dest

                finalext = get_file_ext(finalfile)
                stripped = finalfile[len(destdir)+1:]
                if os.path.isdir(finalfile):
                    stripped = stripped + os.path.sep
                    if stripped in config:
                        result[stripped] = config[stripped].atomic

                apply_config(destdir, get_config(finalfile, stripped, config, already_configured), dry_run)

                # if there's an automatic way to test this type of file,
                # try it
                if finalext in autotest.testable:
                    if not autotest.testable[finalext](finalfile):
                        raise ValueError('File {} didn\'t pass validation for {}'.format(finalfile, finalext))

        return result

    def _template(self, item, config):
        template = Template(item)
        return template.render(config)

    def parse_config_sq(self, filename, inputhash):
        """
        Parses a config.sq file which contains metadata about files in this
        directory.

        Keyword arguments:
            filename -- the config.sq file to open
            inputhash -- the service variables to template config.sq with
        """
        # Conversion functions from string to the correct type, str is identity
        convert = {'atomic': bool, 'user':str, 'group':str, 'mode':str}
        require_dir = set(['atomic'])
        result = []

        template = self.loader.load_template(filename)
        contents = template.render(inputhash, loader=self.loader)

        for line in contents.split('\n'):
            # These are the default values
            item = {'atomic': False, 'user':None, 'group':None, 'mode':None}

            if line == "" or line.startswith("#"):
                continue

            args = line.split()
            if len(args) < 2:
                raise ValueError('Line "{}" in file {} isn\'t formatted correctly'.format(line, filename))

            filepath = args[0]
            for arg in args[1:]:
                (key, value) = arg.split(':', 2)

                if key in require_dir:
                    # if this key requires us to be a directory, check
                    if not filepath.endswith(os.path.sep):
                        raise ValueError('Key {} requires entry {} to end with' +
                                ' a slash (must be directory) in file {}'.format(key, filepath, filename))

                #Only do work if we know about this parameter
                if key in convert:
                    item[key] = convert[key](value)
                else:
                    raise ValueError('Unknown config.sq value {} in file {}'.format(key, filename))
            result.append(FileConfig(filepath, item['atomic'], item['user'], item['group'], item['mode']))

        return result


from decimal import Decimal
from decimal import getcontext

def factorial(n):
    '''
    Factorial function to find the factorial of the functions
    https://en.wikipedia.org/wiki/Factorial

    '''
    if n < 1:
        return 1
    else:
        return n * factorial(n-1)

def piToNth(num):
    '''
     chudnovsky-algorithm to compute pi to 'num' digit
    https://en.wikipedia.org/wiki/Chudnovsky_algorithm

    '''
    pi = Decimal(0)
    k = 0
    while k < num:
        first = Decimal(-1)**(k)
        second = Decimal(factorial(6*k))
        third =  Decimal((545140134*k + 13591409))
        fourth = Decimal(factorial(3*k))
        fifth = Decimal((factorial(k)**3))
        sixth =  Decimal((640320)**((3*k+3)/2))
        pi += (first*second*third)/(fourth*fifth*sixth)
        k = k + 1
    pi = (pi ** Decimal(-1)) / Decimal(12)
    return pi
num = Decimal(input("Give the position till which you want the Pi to be tracked: "))
getcontext().prec = int(num)
print(piToNth(num))


import rospy

import baxter_interface

from baxter_interface import CHECK_VERSION

rospy.init_node('Hello')

print("Obteniendo el estado del robot... ")
baxter_interface.RobotEnable(CHECK_VERSION).state().enabled
print("Habilitando... ")
baxter_interface.RobotEnable(CHECK_VERSION).enable()

limb = baxter_interface.Limb('right')
limb2 = baxter_interface.Limb('left')

angles = limb.joint_angles()

print (angles )

angles['right_s0']=0.0
angles['right_s1']=0.0
angles['right_e0']=0.0
angles['right_e1']=0.0
angles['right_w0']=0.0
angles['right_w1']=0.0
angles['right_w2']=0.0

print (angles )

limb.move_to_joint_positions(angles)

pos1 = {'right_s0': -0.459, 'right_s1': -0.202, 'right_e0': 1.807, 'right_e1': 1.714, 'right_w0': -0.906, 'right_w1': -1.545, 'right_w2': -0.276}

pos2 = {'right_s0': -0.395, 'right_s1': -0.202, 'right_e0': 1.831, 'right_e1': 1.981, 'right_w0': -1.979, 'right_w1': -1.100, 'right_w2': -0.448}

pos3 = {'left_w0': 0, 'left_w1': 0, 'left_w2': 0, 'left_e0': 0, 'left_e1': 0, 'left_s0': 0, 'left_s1': 0}

for _move in range(2):
	limb.move_to_joint_positions(pos1)
	limb.move_to_joint_positions(pos2)
	limb2.move_to_joint_positions(pos3)

print ("fin del programa")

print("Obteniendo el estado del robot... ")
baxter_interface.RobotEnable(CHECK_VERSION).state().enabled
print("Deshabilitando... ")
baxter_interface.RobotEnable(CHECK_VERSION).disable()


# -*- coding: utf-8 -*-
"""
Created on Wed Aug 30 17:10:40 2023

@author: Mahmoud Saeed
"""
from .AdditionalComponent import *

class TrendComponent(AdditionalComponent):

    def addComponent(self , data, trend_coef,):
        """
        Add trend component to the time series data.

        Parameters:
            data (DatetimeIndex): The time index for the data.
            trend (str): The magnitude of the trend ('No Trend', 'Small Trend', 'Large Trend').

        Returns:
            numpy.ndarray: The trend component of the time series.
        """
        if len(trend_coef) == 0:
            return np.zeros(len(data))
        trend = 0
        for i, coefficient in enumerate(trend_coef):
            time_intervals = np.arange(len(data))
            trend += coefficient * time_intervals ** i

        return trend


import state
from constants import GameMode
from gameengine.basenode import BaseNode
from gameengine.timer import Timer
from objects.boxes import BoxEnd
from objects.buttons import BtnPlay, BtnScoreboard
from objects.labels import ScoreLabel
from objects.others import Medal

class Ending(BaseNode):
    def __init__(self):
        super().__init__()

        self.small_font = ScoreLabel(type=ScoreLabel.SMALL, padding=2)
        self.max_small_font = ScoreLabel(type=ScoreLabel.SMALL, padding=2)
        self.timer = Timer(1.12)
        self.add_children(
            self.timer,
            BoxEnd(),
            BtnPlay(),
            BtnScoreboard(),
            Medal(),
            self.max_small_font,
            self.small_font,
        )

        self.active = False

    def update(self):
        if state.game_mode == GameMode.DEAD:
            super().update()
            if self.timer.reached:
                score = self.program.scene.score
                score.register(score.current_score_value)

                self.small_font.set_text(score.current_score_value)
                self.small_font.rect.right = 660
                self.small_font.rect.bottom = 235

                self.max_small_font.set_text(max(score.registered))
                self.max_small_font.rect.right = 660
                self.max_small_font.rect.bottom = 320
                self.active = True

                self.timer.rechead = 0


# -*- coding: utf-8 -*-
import os
import subprocess
import tempfile
import re
import logging
from Marketingtool.modules.get_watermark import get_watermark
import shutil

logger = logging.getLogger(__name__)
class RunCommandError(Exception):
    pass
class Watermark():
    def __init__(self):
        pass
    def remove_watermark(self,video_path:str,output_path:str,max_frames:int=50):
        """
        remove watermark from video
        """
        if os.path.exists(video_path) is not True:
            raise FileNotFoundError("File not found")
        tmpdir =self.getframe(video_path,max_frames)
        getWaterMark=get_watermark()
        image_path=getWaterMark.get_watermarks(tmpdir)
        # logger.info(image_path)
        if image_path is None:
            raise Exception("watermark not generate success")
        # start to remove watermark
        removecmd="ffmpeg -hide_banner -loglevel error -y -stats -i "+video_path+" -acodec copy -vf \"removelogo="+image_path+"\" "+output_path+""
        self.cmd(removecmd)
        shutil.rmtree(tmpdir)
    def getframe(self,video_path:str,max_frames:int=50)->str:
        """
        get frame from video
        """
        getframe="ffprobe -hide_banner -loglevel warning -select_streams v -skip_frame nokey -show_frames -show_entries frame=pkt_dts_time "+video_path+" | grep \"pkt_dts_time=\" | xargs shuf -n "+str(max_frames)+" -e | awk -F  \"=\" '{print $2}'"
        keyframes_time=self.cmd(getframe).splitlines()

        tmpdir = tempfile.mkdtemp()
        logger.info("Extracting frames (up to: "+str(max_frames)+")... to the tmp path:"+tmpdir)
        logger.info(keyframes_time)
        counter=0
        for i in keyframes_time:
            if not re.match("^[0-9]+([.][0-9]+)?$", i):
                logger.info("Skipping unrecognize timing: " + i)
                continue

            generateframe="ffmpeg -y -hide_banner -loglevel error -ss "+i+" -i "+video_path+" -vframes 1 "+tmpdir+"/output_"+str(counter)+".png"
            logger.info("run get frame pic command: "+generateframe)
            self.cmd(generateframe)
        # print("$counter ")
            counter=counter+1
        if counter < 2:
            raise Exception("frames extracted, need at least 2, aborting. The command "+getframe+" failed.")
        return tmpdir
    def cmd(self,command):
        """
        run shell command
        """
        try:
            subp = subprocess.check_output(command,shell=True,encoding="utf-8")
            return subp
        except subprocess.CalledProcessError:

            raise RunCommandError("run command error for:"+command)


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

def mysplit(mystr, spl=''):
    if spl == ':':
        k = mystr.split(spl)
        if len(k) > 1:
            if k[0].strip() in classes:
                classes[k[0].strip()].extend(mysplit(k[1]))
            else:
                classes.update({k[0].strip(): mysplit(k[1])})
        else:
            classes.update({k[0].strip(): []})
    else:
        return mystr.split()

def mycheck(mystr):
    a, b = mystr.split()
    # print(k)
    # print(classes)
    if b in classes:
        # print(k[0])
        # print(classes[k[1]])
        if a in classes[b] or a == b:
            return 'Yes'
        else:
            return 'No'
    else:
        return 'No'

def newcheck(a, b):
    if b in classes:
        print('** ' + b + ' in classes')
        for i in classes[b]:
            print(' ** ' + i + ' in ' + str(classes[b]))
            if a == i:
                return 'Yes'
            else:
                return newcheck(i, a)
        return 'No'

classes = dict()

"""
n = int(input())
for ni in range(n):
    dd = str(input())
"""
n = ['A', 'B : A', 'C : A', 'D : B C', 'C : E']
for ni in n:
    mysplit(ni, ':')

print(classes)
"""
q = int(input())
for qi in range(q):
    print(mycheck(str(input())))
"""
q = ['A B', 'B D', 'C D', 'D A', 'A A', 'A D']
for qi in q:
    #print(mycheck(qi))
    a, b = qi.split()
    print(newcheck(a, b))


class Ships:
    ShipClasses = ['Shuttle', 'Freighter', 'Scout', 'Viper']

    # Generic Stats
    cargoCapacity = 10
    spaceForRooms = 3

    # Movement
    maintenanceCosts = 5
    maxTravelDistance = 3

    # Battle
    attackPower = 5
    shieldStrength = 10

    class Shuttle:
        """Small Shuttle. Average Stats."""
        bounds = {
            'cargoCapacity':        [-2, 2],
            'spaceForRooms':        [-1, 1],

            'maintenanceCosts':     [-1, 1],
            'maxTravelDistance':    [-1, 1],

            'attackPower':          [-2, 2],
            'shieldStrength':       [-3, 3],
        }

    class Freighter:
        """Big Cargo loads. Slow & Expansive."""
        bounds = {
            'cargoCapacity':        [3, 10],
            'spaceForRooms':        [0, 2],

            'maintenanceCosts':     [0, 4],
            'maxTravelDistance':    [-2, 1],

            'attackPower':          [-3, 1],
            'shieldStrength':       [-1, 4],
        }

    class Scout:
        """Fast Ship. Perfekt for Exploring."""
        bounds = {
            'cargoCapacity':       [-6, -2],
            'spaceForRooms':        [-1, 1],

            'maintenanceCosts':     [-4, 0],
            'maxTravelDistance':    [0, 3],

            'attackPower':          [-1, 2],
            'shieldStrength':       [-2, 1],
        }

    class Viper:
        """Fast Attack Ship. Dont let them hit you"""
        bounds = {
            'cargoCapacity':        [-8, -4],
            'spaceForRooms':        [-2, 0],

            'maintenanceCosts':     [-3, -1],
            'maxTravelDistance':    [-2, 1],

            'attackPower':          [2, 5],
            'shieldStrength':       [-4, 0],
        }