print('Gaussian Elimination Algorithm Test')

def solve(a,b):
    n = len(b)
    for k in range(0,n):
        # find pivot row
        max = k
        for i in range (k+1,n):
            if abs(a[i][k]) > abs(a[max][k]):
                max = i
        # swap row in A matrix
        temp = a[k]
        a[k] = a[max]
        a[max] = temp

        # swap corresponding values in constants matrix
        t = b[k]
        b[k] = b[max]
        b[max] = t

        # pivot factor within A and B
        for i in range (k+1,n):
            factor = a[i][k] / a[k][k]
            b[i] -= factor * int(b[k])
            for j in range (k,n):
                a[i][j] -= factor * a[k][j]

    # Print upper-triangular matrix
    upperTraingular(a,b)

    # back substitution
    solution = [n]
    for i in range(n-1,0,-1):
        sum = 0.0
        for j in range (i+1,n,1):
            sum += a[i][j] * solution[j]
        solution[i] = (b[i]-sum)/a[i][i]

    # print solution
    printSolution(solution)

def upperTraingular(a,b):
    n = len(b)
    print('Upper Triangle Matrix : ')
    for i in range (0,n):
        for j in range(0,n):
            print("%.3f",a[i][j])
        print("| %.3f",b[i])

def printSolution(solution):
    n = len(solution)
    print('Solution : ')
    for i in range (0,n):
        print("%.3f",solution(i))

def GaussEli():
    n = int(input('Enter the number of variables : '))
    b = []
    matrix = []
    matrix2 = []
    print("Enter ",n,"equations coefficients : ")
    for i in range (n):
        a = []
        for j in range (n):
            a.append(int(input()))
        matrix.append(a)

    print("\nEnter ",n,"solutions : ")
    for i in range(0,n):
        b.append(int(input()))
        matrix2.append(b)

    # print Augmented matrix
    print('The Augmented Matrix is : ')
    for i in range (n):
        for j in range (n):
            print(matrix[i][j],end = " ")
        print(" | ",matrix2[i][i])

    solve(matrix,matrix2)

GaussEli()


# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.5
#   kernelspec:
#     display_name: Python 3 (ipykernel)
#     language: python
#     name: python3
# ---

# +
import pandas as pd
import numpy as np
import seaborn as sns

from astropy.table import Table
import matplotlib.pyplot as plt
from matplotlib import rc
rc('font', **{'size':16})
import matplotlib.cm as cmap
from multiprocessing import Pool
# from profilestats import profile
from os import listdir, path
from time import time
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
pd.options.mode.chained_assignment = None
from module.preprocessing.dtdm import dtdm_raw_analysis
from module.classes.analysis import analysis

# -

def plot_stats_property(self, keys, figax, macleod=False, fit=False, fit_g=False, **kwargs):
    subgroup = 10
    if figax is None:
        fig, ax = plt.subplots(1,1, figsize=(18,12))
    else:
        fig, ax = figax
    if keys=='all':
        keys = list(self.pooled_stats.keys())[1:]

    from scipy.optimize import curve_fit
    def func(x, SF_inf, tau, phot_err):
            return (SF_inf*(1 - np.exp(-x/tau)) + phot_err)**0.5
    fitted_params = []

    for group_idx in range(self.n_groups):
        if group_idx != subgroup:
            for key in keys:
                y = self.pooled_stats[key][group_idx].T
                color = cmap.jet(group_idx/self.n_groups)
                ax.errorbar(y[0], y[1], yerr=y[2], label=self.label_range_val[group_idx], color=color, capsize=10) # square root this
                ax.scatter(y[0], y[1], color=color)
                if fit:
                    y = self.pooled_stats[key][group_idx].T
                    popt, pcov = curve_fit(func, y[0], y[1])
                    x = np.logspace(0.5,4.2,100)
                    ax.plot(x, func(x, *popt), lw=2, ls='-.', color=color, label=r'$SF_\infty \sqrt {1-e^{-∆t/\tau}}, SF_{\infty}='+'{:.2f},'.format(popt[0])+r'\:\tau'+'={:.2f}$'.format(popt[1])) #fix this
                    print('Slope for {}: {:.2f}'.format(key, popt[1]))
                    fitted_params.append([*popt,*np.diagonal(pcov)])

    if fit_g:
        y_g = np.concatenate(self.pooled_stats[keys[0]], axis=0).T
        popt, pcov = curve_fit(func, y_g[0], y_g[1])
        x = np.logspace(0.7,4.6,100)
        ax.plot(x, func(x, *popt), lw=4, ls='-.', color = 'k', label=r'$SF_\infty \sqrt {1-e^{-∆t/\tau}}, SF_{\infty}='+'{:.2f},'.format(popt[0])+r'\:\tau'+'={:.2f}$'.format(popt[1])) #fix this

    ax.legend()
    ax.set(xlabel='Rest frame time lag (days)', title='{}, {}'.format(keys[0], self.obj), **kwargs)

    return fig,ax, np.array(fitted_params)

# +
wdir = cfg.W_DIR
obj = 'qsos'
ID = 'uid'
band = 'r'

dr = analysis(ID, obj, band)
dr.properties = pd.read_csv(cfg.D_DIR + 'catalogues/qsos/dr12q/SDSS_DR12Q_BH_matched.csv', index_col=dr.ID)
key = 'MBH_CIV'
prop_range_all = {'Mi':(-30,-20),'mag_mean':(15,23.5),'mag_std':(0,1),'redshift':(0,5),'Lbol':(44,48),'nEdd':(-3,0.5), 'MBH_CIV':(6,12)}
prop_range_any = {key:prop_range_all[key]}
# mask_all = np.array([(bound[0] < dr.properties[key]) & (dr.properties[key] < bound[1]) for key, bound in prop_range_all.items()])
mask_any  = np.array([(bound[0] < dr.properties[key]) & (dr.properties[key] < bound[1]) for key, bound in prop_range_any.items()])
mask = mask_any.any(axis=0)
dr.properties = dr.properties[mask]
# bounds_z = np.array([-2.5,-1.5,-1,-0.5,0,0.5,1,1.5,2.5])
bounds_z = np.array([-2,-1,-0.5,0,0.5,1,2])
bounds_tuple, z_score_val, bounds_values, mean, std, ax = dr.bounds(key, bounds = bounds_z)
z_score = z_score_val['z_score']

np.savetxt(cfg.D_DIR + 'computed/qsos/binned/{}/bounds_z.txt'.format(key), bounds_z, fmt='%.2f')
np.savetxt(cfg.D_DIR + 'computed/qsos/binned/{}/bounds_values.txt'.format(key), bounds_values)

groups = [z_score_val[(lower < z_score) & (z_score < upper)] for lower, upper in bounds_tuple]
for i, group in enumerate(groups):
    group.to_csv(cfg.D_DIR + 'computed/{}/binned/{}/uids/group_{}.csv'.format(obj, key, i))
# -

# # Shift

dtdm_qsos_civ = dtdm_raw_analysis('qsos', 'uid', 'r', 'qsos')
# dtdm_qsos_civ.calculate_stats_looped_key(26, 'log_dr12', 'MBH_CIV', save=True)
dtdm_qsos_civ.read_pooled_stats('log', key='MBH_CIV')
# dtdm_qsos_lbol.pooled_stats.keys()

# +
centres = (dtdm_qsos_civ.bounds_values[1:] + dtdm_qsos_civ.bounds_values[:-1])/2

y = dtdm_qsos_civ.pooled_stats['SF cwf a'].copy()
x = dtdm_qsos_civ.mjd_centres.copy()
x = np.array([x]*y.shape[0])
y = np.append(x[:, :, np.newaxis],y, axis=-1)

y[:, :, 0] /= 10**((centres[:, np.newaxis]-8)) # -5 for c^3/G and -8 for 10^8 solar mass BH
dtdm_qsos_civ.pooled_stats['SF cwf a'] = y
# -

fig, ax, fitted_params = plot_stats_property(dtdm_qsos_civ, ['SF cwf a'], figax=None, fit=False, fit_g=False, xscale='log', yscale='log')
ax.grid(visible=True, which='major', lw=0.5)
ax.grid(visible=True, which='minor', lw=0.2)
# ax.set(ylim=[2e-2, 1], ylabel='Structure Function (mag)', title = 'Structure function (dr12)')
# ax.set(xlabel=r'Rest frame time lag per mass (days/$10^8$M$_\odot$)')
# fig.savefig('plots/SF_shift_drw_fit.pdf', bbox_inches='tight')

# # Fit a modified DRW to our data.

def plot_stats_property(self, keys, figax, macleod=False, fit=False, fit_g=False, **kwargs):
    """
    This is a modified version of plot_stats_property in dtdm.py, which allows a modified DRW to be fit to our data.
    """
    subgroup = 10
    m = 3
    n = 2
    if figax is None:
        fig, axes = plt.subplots(m,n, figsize=(18,20), sharex=True, sharey=True)
    else:
        fig, ax = figax
    if keys=='all':
        keys = list(self.pooled_stats.keys())[1:]

    from scipy.optimize import curve_fit
    def func(x, tau, var_int, var_phot, slope):
            return (var_int * (1 - np.exp(-(x**(slope*2))/tau)) + var_phot ) ** 0.5
    fitted_params = []

    for group_idx, ax in zip(range(self.n_groups), axes.ravel()):
        if group_idx != subgroup:
            for key in keys:
                y = self.pooled_stats[key][group_idx].T
                color = cmap.brg(group_idx/self.n_groups)
                ax.errorbar(y[0], y[1], yerr=y[2], label=self.label_range_val[group_idx], color=color, capsize=10) # square root this
                ax.scatter(y[0], y[1], color=color)
                if fit:
                    y = self.pooled_stats[key][group_idx].T
                    popt, pcov = curve_fit(func, y[0], y[1], p0=[2000, 0.3, 0, 1], bounds=([0, 0, 0, 0], [np.inf, 2, 0.5, 2]))
                    print(popt)
                    x = np.logspace(0.5,4.2,100)
                    ax.plot(x, func(x, *popt), lw=3, ls='-.', color = 'k', label=r'$\sqrt {\sigma_i^2(1-e^{-∆t/\tau}) + \sigma_p^2}, \tau='+'{:.0f},'.format(popt[0])+r'\:\sigma_i'+'={:.2f},'.format(popt[1]**0.5)+r'\:\sigma_p'+'={:.2f}$'.format(popt[2]**0.5)) #fix this
                    fitted_params.append([*popt,*np.diagonal(pcov)])
                    # ax.plot(x, func(x, 5000, 0.3, 0.0001))
                ax.legend(loc=2)
                ax.set(**kwargs)
                ax.grid(visible=True, which='major', lw=0.5)
                ax.grid(visible=True, which='minor', lw=0.2)
                ax.set(ylim=[2e-2, 1])

    for ax in axes[:, 0]:
        ax.set(ylabel='Structure Function (mag)' )
    for ax in axes[-1, :]:
        ax.set(xlabel='Rest frame time lag (days)')

    if fit_g:
        y_g = np.concatenate(self.pooled_stats[keys[0]], axis=0).T
        popt, pcov = curve_fit(func, y_g[0], y_g[1])
        x = np.logspace(0.7,4.6,100)
        ax.plot(x, func(x, *popt), lw=4, ls='-.', color = 'k', label=r'$SF_\infty \sqrt {1-e^{-∆t/\tau}}, SF_{\infty}='+'{:.2f},'.format(popt[0])+r'\:\tau'+'={:.0f}$'.format(popt[1])) #fix this

    plt.subplots_adjust(wspace=0, hspace=0)
    # fig.legend(bbox_to_anchor=(1,0.5)) # For a global legend

    return fig,axes, np.array(fitted_params)

dtdm_qsos_civ = dtdm_raw_analysis('qsos', 'uid', 'r', 'qsos')
# dtdm_qsos_civ.calculate_stats_looped_key(26, 'log_dr12', 'MBH_CIV', save=True)
dtdm_qsos_civ.read_pooled_stats('log', key='MBH_CIV')
# dtdm_qsos_lbol.pooled_stats.keys()

# +
centres = (dtdm_qsos_civ.bounds_values[1:] + dtdm_qsos_civ.bounds_values[:-1])/2

y = dtdm_qsos_civ.pooled_stats['SF cwf a']
x = dtdm_qsos_civ.mjd_centres
x = np.array([x]*y.shape[0])
y = np.append(x[:, :, np.newaxis],y, axis=-1)

# y[:, :, 0] /= 10**(1*(centres[:, np.newaxis]-8)) # -5 for c^3/G and -8 for 10^8 solar mass BH
dtdm_qsos_civ.pooled_stats['SF cwf a'] = y
# -

# plotting DRW with systematic photometric error
x = np.logspace(-2,2)
y = np.sqrt(10*(1 - np.exp(-x/2))+ 100)
fig, ax = plt.subplots(1,1, figsize=(10,5))
ax.plot(x,y)
ax.set(xscale='log',yscale='log')

# +
fig, ax = plt.subplots(1,1, figsize = (13,6))
from matplotlib.ticker import FormatStrFormatter
tau = 5
x = np.logspace(-1,2)
y = 10*(1-np.exp(-x/tau)) ** 0.5

ax.plot(x,y)
ax.set(xscale='log', yscale='log', xlabel=r'$\Delta$t', ylabel=r'SF($\Delta$t)', title='DRW structure function')
ax.grid(visible=True, which='major', lw=0.5)
ax.grid(visible=True, which='minor', lw=0.2)
ax.yaxis.set_minor_formatter(FormatStrFormatter('%.0f'))
ax.yaxis.set_major_formatter(FormatStrFormatter('%.0f'))
# fig.savefig('plots/drw_sf.pdf', bbox_inches='tight')
# -

fig, ax, fitted_params = plot_stats_property(dtdm_qsos_civ, ['SF cwf a'], figax=None, fit=True, fit_g=False, xscale='log', yscale='log')
# ax.set(xlabel=r'Rest frame time lag per mass (days/$10^8$M$_\odot$)')
# fig.savefig('plots/SF_split_fit_phot_err_modified.pdf', bbox_inches='tight')

fig, ax = plt.subplots(1,1, figsize=(10,5))
# ax.errorbar(centres, fitted_params[:,0], yerr=fitted_params[:,4],capsize=10)
ax.errorbar(centres, fitted_params[:,0],capsize=10)
ax.scatter(centres, fitted_params[:,0])
ax.set(xlabel=r'Black hole mass / (log$_{10}$M$_\odot$)', ylabel=r'$\tau$ (days)')
# fig.savefig('plots/SFinf_Mbh.pdf',bbox_inches='tight')

fig, ax = plt.subplots(1,1, figsize=(10,5))
# ax.errorbar(centres, fitted_params[:,1], yerr=fitted_params[:,5],capsize=10)
ax.errorbar(centres, fitted_params[:,1],capsize=10)
ax.scatter(centres, fitted_params[:,1])
ax.set(xlabel=r'Black hole mass / (log$_{10}$M$_\odot$)', ylabel=r'$\sigma_i$ (mag)')
# fig.savefig('plots/SFinf_Mbh.pdf',bbox_inches='tight')

fig, ax = plt.subplots(1,1, figsize=(10,5))
# ax.errorbar(centres, fitted_params[:,2], yerr=fitted_params[:,6],capsize=10)
ax.errorbar(centres, fitted_params[:,2], capsize=10)
ax.scatter(centres, fitted_params[:,2])
ax.set(xlabel=r'Black hole mass / (log$_{10}$M$_\odot$)', ylabel=r'$\sigma_p$ (mag)')
# fig.savefig('plots/SFinf_Mbh.pdf',bbox_inches='tight')

fig, ax = plt.subplots(1,1, figsize=(10,5))
ax.errorbar(centres, fitted_params[:,3], yerr=fitted_params[:,7],capsize=10)
ax.scatter(centres, fitted_params[:,3])
ax.set(xlabel=r'Black hole mass / (log$_{10}$M$_\odot$)', ylabel=r'slope')
# fig.savefig('plots/SFinf_Mbh.pdf',bbox_inches='tight')


# Faça um Programa que calcule a área de um quadrado, em seguida mostre o dobro desta área para o usuário.

import math

def area(l):
    a = math.pow(l, 2) * 2
    return a

x = float(input('entre com o lado do quadrado: '))
print(f'O quadrado de lado {x} tem área de {area(x):.2f} .')


__author__ = 'Udara'

#even if the number 10 occurs more than once, it's only recorded once in this funciton
#done to improve run time, might not be exactly what's asked of it.

def greater_10(T):
    if T.is_empty():
        return []
    else:
        x=[]
        if T.root >=10:
            x.append(T.root)
        x.extend(greater_10(T.left))
        x.extend(greater_10(T.right))
        return x


import typing as tp

from aiogram.types.reply_keyboard import (
    ReplyKeyboardMarkup,
)

class BaseKeyboardWithTextButtons(ReplyKeyboardMarkup):
    BUTTONS: list = list()

    @classmethod
    def create_with_buttons(cls, buttons: tp.List[str] = None, *args, **kwargs) -> ReplyKeyboardMarkup:
        keyboard = ReplyKeyboardMarkup(*args, resize_keyboard=True, **kwargs)
        if buttons:
            keyboard.add(*buttons)
        else:
            keyboard.add(*cls.BUTTONS)
        return keyboard

class PositiveNegativeUAKeyboard(BaseKeyboardWithTextButtons):
    BUTTONS = ["Так", "Ні"]


import argparse
from dataclasses import dataclass
from functools import partial
import json
import multiprocessing
import multiprocessing.dummy
from pathlib import Path
import sys
from typing import List

import soundfile as sf
from soundfile import LibsndfileError, SoundFileError
from tqdm import tqdm

from ldc_bpcsad import __version__ as VERSION
from ldc_bpcsad.decode import decode
from ldc_bpcsad.io import (write_audacity_label_file, write_htk_label_file,
                           write_rttm_file, write_textgrid_file)
from ldc_bpcsad.logging import getLogger, setup_logger, DEBUG, WARNING
from ldc_bpcsad.utils import get_nframes_wav, which

logger = getLogger()

class ChannelNotFoundError(Exception):
    """Raised when a channel doesn't exist."""
    pass

class FileEmptyError(Exception):
    """Raised when a file contains no data."""
    pass

@dataclass
class Channel:
    """Channel of recording.

    Parameters
    ----------
    id : str
        Unique identifier of channel. Used to name output file containing SAD
        output.

    audio_path : Path
        Path to audio file channel is on.

    channel : int
        Channel number on audio file (1-indexed).

    Attributes
    ----------
    format : str
        Audio format (derived from extension).
    """
    id: str
    audio_path: Path
    channel: int

    def __post_init__(self):
        self.audio_path = Path(self.audio_path)
        self.channel = int(self.channel)
        self.format = self.audio_path.suffix.lstrip('.').upper()

    def validate(self):
        """Check that channel is valid.

        If all checks pass, return the channel. Otherwise, raises an exception.
        """
        # Check that file exists.
        if not self.audio_path.exists():
            raise FileNotFoundError(
                f'Audio file does not exist: {self.audio_path}')

        # Check that file is not empty.
        n_bytes = self.audio_path.lstat().st_size
        if n_bytes == 0:
            raise FileEmptyError('File contains no data.')

        # Check in a known audio format.
        if self.format not in sf._formats:
            raise SoundFileError(f'Unknown format "{self.format}"')

        # Check that soundfile can, in actuality, read it  --  the header is a
        # lie, etc.
        info = sf.info(self.audio_path, verbose=True)
        logger.debug(f'Source audio file: {info}')
        logger.debug('')
        logger.debug(f'Source channel: {self.channel}.')
        logger.debug('')

        # Check that file does not consists of JUST a header.
        if info.frames == 0 or info.frames == 9223372036854775807:
            # soundfile.info seems to encounter an underflow errors for some
            # formats when file is empty.
            raise FileEmptyError('File contains no data.')

        # Check that # frames indicated in header agrees with actual # frames.
        # Currently only implemented for WAV.
        if self.format == 'WAV':
            try:
                n_frames_header = get_nframes_wav(self.audio_path)
                n_frames_actual = info.frames
                if n_frames_header != n_frames_actual:
                    logger.warning(
                        f'Header frame count wrong for file '
                        f'"{self.audio_path}": '
                        f'{n_frames_header} != {n_frames_actual}')
            except Exception as e:
                # Bare except, yes, yes. yada, yada, yada/
                pass

        # Check that channel EXISTS on file.
        if not 1 <= self.channel <= info.channels:
            raise ChannelNotFoundError(
                f'Invalid source channel: {self.channel}. Source '
                f'channel be positive integer <= {info.channels}.')

        return self

def load_htk_script_file(fpath, channel=1):
    """Read channels to process from HTK script file.

    An HTK script file specifies a set of file paths, each path separated by a
    newline; e.g.:

        /data/flac/rec01.flac
        /data/flac/rec02.flac
        /data/flac/rec03.flac

    Parameters
    ----------
    fpath : Path
        Path to script file.

    channel : int, optional
        Channel number (1-indexed) to perform SAD on for each file.
        (Default: 1)

    Returns
    -------
    list of Channel
        Channels to perform SAD on.
    """
    channels = []
    with open(fpath, 'r', encoding='utf-8') as f:
        for line in f:
            audio_path = Path(line.strip())
            channel_id = audio_path.stem
            chan = Channel(channel_id, audio_path, channel)
            channels.append(chan)
    return channels

def load_json_script_file(fpath):
    """Read channels to process from JSON file.

    The JSON file should consist of a sequence of JSON objects, each containing
    the following three key-value pairs:

    - ``channel_id``  --  Unique identifier of channel. Used to name output
      file containing SAD output.
    - ``audio_path``  --  Path to audio file that the channel is on.
    - ``channel``  --  Channel number of audio file to process (1-indexed).

    For instance:

        ```json
        [{
            "channel_id": "rec1_c1",
            "audio_path": "/path/to/rec1.flac",
            "channel": 1
        }, {
            "channel_id": "rec1_c2",
            "audio_path": "/path/to/rec1.flac",
            "channel": 2
        }, {
            "channel_id": "rec2_c1",
            "audio_path": "/path/to/rec2.flac",
            "channel": 1
        }]
        ```

    Parameters
    ----------
    fpath : Path
        Path to script file.

    Returns
    -------
    list of Channel
        Channels to perform SAD on.
    """
    with open(fpath, 'r', encoding='utf-8') as f:
        records = json.load(f)
    channels = []
    for record in records:
        try:
            channel = Channel(
                record['channel_id'], Path(record['audio_path']),
                int(record['channel']))
        except Exception as e:
            channel = None
        if not channel:
            logger.warning(
                f'Malformed record in JSON script file. Skipping. '
                f'SCRIPT FILE: {fpath}, RECORD: {record}')
            continue
        channels.append(channel)
    return channels

# Mapping from output formats to corresponding extensions.
OUTPUT_EXTS = {'htk': '.lab',
               'audacity': '.txt',
               'rttm': '.rttm',
               'textgrid': '.TextGrid'}

@dataclass
class CompletedProcess:
    """Return value from `parallel_wrapper`, representing a process that has
    completed.

    Parameters
    ----------
    channel : Channel
        Channel SAD was attempted on.

    success : bool
        Did processing succeed for the channel.
    """
    channel: Channel
    success: bool

def _process_one_file(channel, args):
    """Process one file."""
    success = False
    try:
        logger.debug('#' * 72)
        logger.debug('Attempting SAD.')
        logger.debug('#' * 72)

        # Basic validation of channel.
        channel.validate()

        # Perform SAD.
        with open(channel.audio_path, 'rb') as f:
            x, sr = sf.read(f)
        if x.ndim > 1:
            x = x[:, channel.channel - 1]
        segs = decode(
            x, sr, min_speech_dur=args.min_speech_dur,
            min_nonspeech_dur=args.min_nonspeech_dur,
            speech_scale_factor=args.speech_scale_factor,
            silent=False)

        # Write to output file.
        rec_dur = len(x) / sr
        kwargs = {'is_sorted': True, 'precision': 2}
        ext = OUTPUT_EXTS[args.output_fmt]
        output_path = Path(args.output_dir, channel.id + ext)
        logger.debug(f'Saving SAD to "{output_path}".')
        logger.debug(f'Output file format: {args.output_fmt}')
        if args.output_fmt == 'htk':
            write_htk_label_file(
                output_path, segs, rec_dur=rec_dur, **kwargs)
        elif args.output_fmt == 'audacity':
            write_audacity_label_file(
                output_path, segs, rec_dur=rec_dur, **kwargs)
        elif args.output_fmt == 'rttm':
            write_rttm_file(
                output_path, segs, file_id=channel.audio_path.stem,
                channel=channel.channel, **kwargs)
        elif args.output_fmt == 'textgrid':
            write_textgrid_file(
                output_path, segs, tier='sad', rec_dur=rec_dur, **kwargs)

        success = True
    except LibsndfileError as e:
        logger.debug(e, exc_info=True)
        msg = str(e)
        if (msg.endswith('unknown format.') or
            msg.endswith('unimplemented format.') or
            msg.endswith('Format not recognised.')):
            # If unknown/unsupported file format, remind users what formats
            # are supported.
            logger.debug('To see supported formats, run:')
            logger.debug('')
            logger.debug('    ldc-bpcsad --help')
    except Exception as e:
        logger.debug(e, exc_info=True)

    return CompletedProcess(channel, success)

def process_one_file(channel, args):
    """Process one file."""
    p = _process_one_file(channel, args)
    if not p.success:
        logger.warning(
            f'SAD failed for channel {p.channel.channel} of '
            f'"{p.channel.audio_path}". Skipping. For more details rerun with '
            f'the --debug flag.')

def get_parser():
    """Return `argparse.ArgumentParser`."""
    audio_formats = ', '.join(sorted(sf.available_formats().values()))
    parser = argparse.ArgumentParser(
        description='Perform speech activity detection on audio files.',
        epilog=f'audio file formats: {audio_formats}',
        add_help=True)
    parser.add_argument(
        'audio_path', metavar='audio-path', type=Path, nargs='*',
        help='audio files to be processed')
    parser.add_argument(
        '--channel', default=1, type=int, metavar='CHAN',
        dest='channel',
        help='channel (1-indexed) to process on each audio file '
             '(Default: %(default)s)')
    parser.add_argument(
        '--scp', metavar='SCP', type=Path,
        dest='scp_path',
        help='path to script file (Default: %(default)s)')
    parser.add_argument(
        '--scp-fmt', metavar='SCP-FMT', dest='scp_fmt', default='htk',
        choices=['htk', 'json'],
        help='script file format (Default: %(default)s)')
    parser.add_argument(
        '--output-dir', metavar='OUTPUT-DIR', type=Path, dest='output_dir',
        default=Path.cwd(),
        help="output segmentations to OUTPUT-DIR (Default: current directory)")
    parser.add_argument(
        '--output-fmt', metavar='OUTPUT-FMT', default='htk',
        choices=sorted(OUTPUT_EXTS.keys()),
        help='output file format (Default: %(default)s)')
    parser.add_argument(
        '--speech', metavar='SPEECH-DUR', default=0.500, type=float,
        dest='min_speech_dur',
        help='filter speech segments shorter than SPEECH-DUR seconds '
             '(Default: %(default)s)')
    parser.add_argument(
        '--nonspeech', metavar='NONSPEECH-DUR', default=0.300, type=float,
        dest='min_nonspeech_dur',
        help='merge speech segments separated by less than NONSPEECH-DUR '
             'seconds (Default: %(default)s)')
    parser.add_argument(
        '--speech-scale-factor', metavar='SPEECH-SCALE', default=1.,
        type=float,
        help='post-multiply speech model acoustic likelihoods by '
             'SPEECH-SCALE (Default: %(default)s)')
    parser.add_argument(
        '--disable-progress', default=False, action='store_true',
        help='disable progress bar')
    parser.add_argument(
        '--debug', default=False, action='store_true',
        help='enable DEBUG mode')
    parser.add_argument(
        '--n-jobs', '-j', nargs=None, default=1, type=int, metavar='INT',
        dest='n_jobs', help='set num threads to use (Default: %(default)s)')
    parser.add_argument(
        '--version', action='version', version='%(prog)s ' + VERSION)
    if len(sys.argv) == 1:
        parser.print_help()
        parser.exit()
    return parser

def main():
    parser = get_parser()
    args = parser.parse_args()

    # Set up logger.
    log_level = DEBUG if args.debug else WARNING
    setup_logger(logger, level=log_level)

    # Ensure HTK is installed.
    if not which('HVite'):
        # TODO: Update link when docs are online.
        logger.error(
            'HVite is not installed. Please install HTK and try again: '
            '[INSERT LINK TO INSTRUCTIONS HERE]')
        sys.exit(1)

    # Load channels.
    if args.scp_path:
        if args.scp_fmt == 'htk':
            channels = load_htk_script_file(
                args.scp_path, channel=args.channel)
        elif args.scp_fmt == 'json':
            channels = load_json_script_file(args.scp_path)
        else:
            assert False
    else:
        channels = []
        for audio_path in args.audio_path:
            channels.append(Channel(audio_path.stem, audio_path, args.channel))
    # TODO: Check for dupes.
    if not channels:
        return

    # Perform SAD on files in parallel.
    args.output_dir.mkdir(parents=True, exist_ok=True)
    args.n_jobs = min(args.n_jobs, len(channels))
    logger.debug(f'COMMAND LINE CALL: {" ".join(sys.argv)}')
    if args.debug:
        logger.debug(
            'Flag "--n-jobs" is ignored for debug mode. Using single-threaded '
            'implementation.')
        args.n_jobs = 1
        logger.debug('Progress bar is disabled for debug mode.')
        logger.debug('')
        args.disable_progress = True
    Pool = multiprocessing.Pool
    if args.n_jobs == 1:
        Pool = multiprocessing.dummy.Pool
    with Pool(args.n_jobs) as pool:
        f = partial(process_one_file, args=args)
        with tqdm(total=len(channels), disable=args.disable_progress) as pbar:
            for res in pool.imap(f, channels):
                pbar.update(1)

if __name__ == '__main__':
    main()


"""
这个脚本的目的对训练数据进行处理和压缩
生成最后的 4_compressed_training_data.json ，用于训练的数据
"""

import json

# 读取数据
with open('数据处理\\训练数据获取与处理\\3_training_data.json', 'r', encoding='utf-8') as f:
    training_data_dict = json.loads(f.read())

with open('数据处理\\处理到最后投入使用的数据\\输入神经元与序号.json', 'r', encoding='utf-8') as f:
    keyword_and_order_dict = json.loads(f.read())

new_data_list = []

for i in training_data_dict.keys():

    # 点击量过小的数据剔除掉
    if training_data_dict[i]['click_times'] <= 50:
        continue

    # 点击量过大也扔掉
    if training_data_dict[i]['click_times'] >= 1000:
        continue

    # 获取关键词列表
    keyword_list = training_data_dict[i]['keyword']

    # 用来装每一则训练数据
    training_datum_set = []

    # 遍历列表中每一则关键词
    for j in keyword_list:

        if keyword_and_order_dict.__contains__(j):

            # 规定training_datum_set中第一个元素为期望值，后面元素为每个词对应的位置，以达到压缩效果
            # 将keyword数据转化为对应编号存储
            training_datum_set.append(keyword_and_order_dict[j])

    # 遍历完成后
    else:
        # 如果数据量不为0
        if len(keyword_and_order_dict):

            # 在training_datum_set第一号元素插入click_times
            training_datum_set.insert(0, training_data_dict[i]['click_times'])

            # 最后完成
            new_data_list.append(training_datum_set)

# 写入数据
with open('数据处理\\训练数据获取与处理\\4_compressed_training_data.json', 'a+', encoding='utf-8') as f:
    f.write(json.dumps(new_data_list, ensure_ascii=False))


from os import path
from glob import glob
from tqdm import tqdm

from matdb import msg
from matdb.utility import chdir
from matdb.transforms import _get_supers
from matdb.atoms import Atoms

def examples():
    """Prints examples of using the script to the console using colored output.
    """
    from matdb import msg
    script = "MATDB Supercell Generator"
    explain = ("When producing hessians with the Hessian group, a supercell "
               "needs to be selected. This script streamlines the selection "
               "process for multiple seeds and sizes.")
    contents = [(("Select supercells for all the seeds and sizes 32 and 64."),
                 "matdb_supercell.py * --sizes 32 64",
                 "")]
    required = ("Seed files in the `seed` directory.")
    output = ("")
    details = ("")
    outputfmt = ("")

    msg.example(script, explain, contents, required, output, outputfmt, details)

_script_options = {
    "seeds": {"help": ("File patterns for choosing seeds."),
              "nargs": '+'},
    "--sizes": {"help": ("Target cell sizes to find for."),
                "nargs": '+', "type": int, "required": True},
    }
"""dict: default command-line arguments and their
    :meth:`argparse.ArgumentParser.add_argument` keyword arguments.
"""

def _parser_options():
    """Parses the options and arguments from the command line."""
    #We have two options: get some of the details from the config file,
    import argparse
    import sys
    from matdb import base
    pdescr = "MATDB Supercell Selector"
    parser = argparse.ArgumentParser(parents=[base.bparser], description=pdescr)
    for arg, options in _script_options.items():
        parser.add_argument(arg, **options)

    args = base.exhandler(examples, parser)
    if args is None:
        return

    return args

def run(args):
    """Runs the matdb setup and cleanup to produce database files.
    """
    print("matdb  Copyright (C) 2019  HALL LABS")
    print("This program comes with ABSOLUTELY NO WARRANTY.")
    print("This is free software, and you are welcome to redistribute it under "
          "certain conditions.")
    if args is None:
        return

    targets = {}
    with chdir("seed"):
        for pattern in args["seeds"]:
            #Handle the default file type, which is vasp.
            if ':' in pattern:
                fmt, pat = pattern.split(':')
            else:
                fmt, pat = "vasp", pattern
            for filename in glob(pat):
                targets[filename] = Atoms(filename, format=fmt)

    result = {}
    for filename, at in tqdm(list(targets.items())):
        result[filename] = _get_supers(at, args["sizes"])

    items = [
        ("Filename", 20, "cokay"),
        ("Supercell", 40, "cstds"),
        ("Req.", 6, "cinfo"),
        ("Act.", 6, "cgens"),
        ("rmin", 8, "cerrs"),
        ("pg", 6, "cwarn")
    ]

    msg.blank(2)
    heading = '|'.join(["{{0: ^{0}}}".format(size).format(name)
                        for name, size, color in items])
    msg.arb(heading, [msg.cenum[i[2]] for i in items], '|')
    msg.std(''.join('-' for i in range(len(heading)+1)))
    for filename, hs in result.items():
        for size, hnf in hs.items():
            names = (filename, hnf.hnf.flatten().tolist(), size,
                     hnf.size, hnf.rmin, hnf.pg)
            text = '|'.join(["{{0: <{0}}}".format(item[1]).format(name)
                                for name, item in zip(names, items)])
            msg.arb(text, [msg.cenum[i[2]] for i in items], '|')
        msg.blank(2)

    return result

if __name__ == '__main__': # pragma: no cover
    run(_parser_options())


"""
The logic is to divide the array in two parts(left side:sorted and right side:unsorted).
Take the first element of right side of array.
Put this minimum in correct place of left side of array by shifting all the elements
greater than minimum to the right by one element and put this minimum in the hole.
Note:We take the minimum in some variable(value) so that it is not lost after shifting the elements to the right.
"""
def insertionSort(lst,n):
    for i in range(1,n):
        value=lst[i]
        hole=i
        while (hole>0 and lst[hole-1]>value):
            lst[hole]=lst[hole-1]
            hole-=1
        lst[hole]=value
    return lst

lst=[1,5,2,19,12,11,10]
print(insertionSort(lst,len(lst)))


# class

# # 마린 : 공격 유닛, 군인, 총을 쏠 수 있음
# name = "marine"
# hp = 40
# damage = 5

# print("{} 유닛이 생성 되었습니다.".format(name))
# print("hp : {0}, damage : {1}\n".format(hp, damage))

# # 탱크 : 공격 유닛, 탱크 , 포를 쏠 수 있는데, 일반 모드 / 시즈 모드
# tank_name = "tank"
# tank_hp = 150
# tank_damage = 35
# print("{} 유닛이 생성 되었습니다.".format(tank_name))
# print("hp : {0}, damage : {1}\n".format(tank_hp, tank_damage))

# def attack(name, location, damage):
#     print("{0} : {1} 방향으로 적군을 공격합니다. [공격력 {2}]".format(name,location, damage))

# attack(name, "1시", damage)
# attack(tank_name, "1시", tank_damage)

# class 선언
class Unit:
    def __init__(self, name, hp, damage):
        self.name = name
        self.hp = hp
        self.damage = damage
        print("{} 유닛이 생성 되었습니다.".format(self.name))
        print("hp : {0}, damage : {1}".format(self.hp, self.damage))

marine1 = Unit("마린", 40 ,5)
marine2 = Unit("마린", 40 ,5)
tank = Unit("탱크", 150, 35)
print()
# __init__ : python 에서 사용되는 생성자
# 객체가 생성 될때 자동적으로 호출되는 부분
# 객체 : class 로 부터 만들어지는 것
# marine / tank 는 Unit class 의 instance

# class 는 parameter를 일정하게 넘겨야 사용이 가능하다.

# 멤버 변수
# 클래스 내에서 정의된 변수
# self.~

wraith1 = Unit("레이스", 80, 5)
print("name: {0}, damage: {1}".format(wraith1.name, wraith1.damage))

wraith2 = Unit("레이스", 80, 5)
wraith2.clocking = True

if wraith2.clocking == True:
    print("{0} 는 현재 클로킹 상태입니다.".format(wraith2.name))

# clocking 이라는 변수는 class 에 선언하지 않았습니다.
# 파이썬에서는 class 선언부 밖에서도 변수를 추가로 할당할 수 있다.


def build_person(first,last,age=None):
    """Return a dictionary of information about a person"""
    person = { 'first': first, 'last': last}
    if age:
        person['age'] = age
    return person

def print_name(person):
    if person.__contains__('age'):
            first = person['first']
            last = person['last']
            age = person['age']
            print("Name: {}, Age: {}".format(first.title() + ' ' + last.title(), age))

musician = build_person('jimi','hendrix',27)
print_name(musician)


"""
==============================================
Face completion with a multi-output estimators
==============================================

This example shows the use of multi-output estimator to complete images.
The goal is to predict the lower half of a face given its upper half.

The first column of images shows true faces. The next columns illustrate
how extremely randomized trees, k nearest neighbors, linear
regression and ridge regression complete the lower half of those faces.

"""

import matplotlib.pyplot as plt
import numpy as np

from sklearn.datasets import fetch_olivetti_faces
from sklearn.ensemble import ExtraTreesRegressor
from sklearn.linear_model import LinearRegression, RidgeCV
from sklearn.neighbors import KNeighborsRegressor
from sklearn.utils.validation import check_random_state

# Load the faces datasets
data, targets = fetch_olivetti_faces(return_X_y=True)

train = data[targets < 30]
test = data[targets >= 30]  # Test on independent people

# Test on a subset of people
n_faces = 5
rng = check_random_state(4)
face_ids = rng.randint(test.shape[0], size=(n_faces,))
test = test[face_ids, :]

n_pixels = data.shape[1]
# Upper half of the faces
X_train = train[:, : (n_pixels + 1) // 2]
# Lower half of the faces
y_train = train[:, n_pixels // 2 :]
X_test = test[:, : (n_pixels + 1) // 2]
y_test = test[:, n_pixels // 2 :]

# Fit estimators
ESTIMATORS = {
    "Extra trees": ExtraTreesRegressor(
        n_estimators=10, max_features=32, random_state=0
    ),
    "K-nn": KNeighborsRegressor(),
    "Linear regression": LinearRegression(),
    "Ridge": RidgeCV(),
}

y_test_predict = dict()
for name, estimator in ESTIMATORS.items():
    estimator.fit(X_train, y_train)
    y_test_predict[name] = estimator.predict(X_test)

# Plot the completed faces
image_shape = (64, 64)

n_cols = 1 + len(ESTIMATORS)
plt.figure(figsize=(2.0 * n_cols, 2.26 * n_faces))
plt.suptitle("Face completion with multi-output estimators", size=16)

for i in range(n_faces):
    true_face = np.hstack((X_test[i], y_test[i]))

    if i:
        sub = plt.subplot(n_faces, n_cols, i * n_cols + 1)
    else:
        sub = plt.subplot(n_faces, n_cols, i * n_cols + 1, title="true faces")

    sub.axis("off")
    sub.imshow(
        true_face.reshape(image_shape), cmap=plt.cm.gray, interpolation="nearest"
    )

    for j, est in enumerate(sorted(ESTIMATORS)):
        completed_face = np.hstack((X_test[i], y_test_predict[est][i]))

        if i:
            sub = plt.subplot(n_faces, n_cols, i * n_cols + 2 + j)

        else:
            sub = plt.subplot(n_faces, n_cols, i * n_cols + 2 + j, title=est)

        sub.axis("off")
        sub.imshow(
            completed_face.reshape(image_shape),
            cmap=plt.cm.gray,
            interpolation="nearest",
        )

plt.show()


import sys
from collections import deque
si = sys.stdin.readline

n = int(si())
queue = deque([i for i in range(1, n + 1)])

while(len(queue) > 1):
    queue.popleft()
    temp = queue.popleft()
    queue.append(temp)

print(queue[0])


from flask import Flask, render_template, request
import subprocess

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def dashboard():
    if request.method == 'GET':
        result = None
    if request.method == 'POST':
        query = request.form['query']
        cmd = 'th generate-lines.lua \
            -path experiments/fullyconv/model_best_cpu.th7 \
            -sourcedict data/raw/tokenized.sen-que/dict.sen.th7 \
            -targetdict data/raw/tokenized.sen-que/dict.que.th7 \
            -beam 5'.split()
        proc = subprocess.run(cmd, stdout=subprocess.PIPE, input=query.encode())
        result = proc.stdout.decode().split('\t')[1]

    return render_template('index.html', result=result)

if __name__ == '__main__':
	app.run(host='0.0.0.0', debug=True, threaded=True)


import numpy as np
import yaml

def load_data(yaml_file_path):
    with open(yaml_file_path,'r') as f:
        content = yaml.load(f.read())
    c = type('myobj', (object,), content)
    return c

def get_monthly_mortgage(
    loan_amount,
    loan_interest_rate,
    amortized_over_how_many_years,):

    monthly_mortgage_payment_markdown=\
    '''
    \begin{equation}
    c = \frac{rP(1+r)^N}{(1+r)^N-1}     ,r \neq 0;
    \end{equation}
    c = monthly payment
    N = number of monthly payments
    P = amount borrowed
    r = monthly interest rate
    r = (R/12)/100
    R = annual interest rate
    https://en.wikipedia.org/wiki/Mortgage_calculator
    '''

    monthly_interest_rate = loan_interest_rate/12
    amortized_over_how_many_months = 12*amortized_over_how_many_years
    monthly_mortgage_payment = \
        (monthly_interest_rate*loan_amount*(1+monthly_interest_rate)**amortized_over_how_many_months)/\
        ((1+monthly_interest_rate)**amortized_over_how_many_months-1)

    return monthly_mortgage_payment

def calculate(c, is_print=False):

    c.total_project_cost = \
        c.purchase_price \
        + c.purchase_closing_cost \
        + c.estimated_repair_cost

    c.down_payment_dollar = c.purchase_price*c.down_payment_of_purchase_price

    if c.down_payment_of_purchase_price == 1:
        c.loan_amount = 0
        c.monthly_mortgage_payment = 0
    else:
        c.loan_amount = \
            c.purchase_price \
            - c.down_payment_dollar \
            - c.purchase_closing_cost

        c.monthly_mortgage_payment = get_monthly_mortgage(
            c.loan_amount,
            c.loan_interest_rate,
            c.amortized_over_how_many_years,)

    c.total_cash_needed = \
        c.down_payment_dollar \
        + c.estimated_repair_cost \
        + c.purchase_closing_cost \
        + c.point_charged_by_lender*c.loan_amount \
        + c.other_charges_from_the_lender

    if getattr(c,'line_of_credit',None):
        c.monthly_line_of_credit_payment = get_monthly_mortgage(
            c.total_cash_needed,
            c.line_of_credit['loan_interest_rate'],
            c.line_of_credit['amortized_over_how_many_years'])
        c.line_of_credit_payment = 0
    else:
        c.monthly_line_of_credit_payment = 0

    c.monthly_income = \
        c.total_gross_monthly_rent \
        + c.other_montly_income

    c.annual_property_tax = c.annual_property_taxes_prct*c.purchase_price
    c.monthly_property_tax = c.annual_property_tax / 12

    c.monthly_expenses = \
        + c.monthly_line_of_credit_payment \
        + c.monthly_mortgage_payment \
        + c.monthly_property_tax \
        + c.fixed_monthly_landlord_paid_expenses_electricity \
        + c.fixed_monthly_landlord_paid_expenses_water_sewer \
        + c.fixed_monthly_landlord_paid_expenses_pmi \
        + c.fixed_monthly_landlord_paid_expenses_garbage \
        + c.fixed_monthly_landlord_paid_expenses_hoas \
        + c.fixed_monthly_landlord_paid_expenses_insurance \
        + c.repairs_and_maintenance * c.monthly_income \
        + c.capital_expenditures * c.monthly_income \
        + c.management_fees * c.monthly_income \
        + c.vacancy * c.monthly_income\
        + c.other_monthly_expenses

    c.monthly_cashflow = c.monthly_income - c.monthly_expenses

    c.net_operating_income = \
        12 * ( c.monthly_income \
        - c.monthly_expenses
        + c.monthly_line_of_credit_payment \
        + c.monthly_mortgage_payment \
        )

    c.purchase_cap_rate_prct = 100*c.net_operating_income/c.purchase_price

    if is_print:
        key_list = [
            # entered
            'purchase_price',
            'purchase_closing_cost',
            'estimated_repair_cost',
            # computed/
            'total_project_cost',
            'down_payment_dollar',
            'loan_amount',
            # entered
            'point_charged_by_lender',
            # computed
            'monthly_line_of_credit_payment',
            'monthly_mortgage_payment',
            'total_cash_needed',
            'monthly_income',
            'monthly_expenses',
            'monthly_cashflow',
            'net_operating_income',
            'purchase_cap_rate_prct',
        ]
        for k in key_list:
            if k.endswith('_prct'):
                print('{} {:1.2f}'.format(k,getattr(c,k)))
            else:
                print('{} {:1.0f}'.format(k,getattr(c,k)))

    return c


# https://www.acmicpc.net/problem/20114

# readline을 사용하기 위해 import합니다.
from sys import stdin

# 첫째 줄에 원래 문자열의 길이 N, 세로로 번진 글자의 개수 H, 가로로 번진 글자의 개수 W를 공백으로 구분해 입력합니다.
# 1 <= N <= 100
# 1 <= H <= 10
# 1 <= W <= 10
# 각각 정수형으로 변환합니다.
N, H, W = map(int, stdin.readline().split(' '))
# 세로로 번진 것을 먼저 복원할 것이기 때문에 세로로 번진 것을 복원한 문자열을 저장할 변수를 선언합니다.
# 맨 끝의 \n은 떼어준 처음에 입력한 문자열로 초기화합니다.
height_restore_string = list(stdin.readline().rstrip())
# 가로로 번진 문자열의 길이를 저장하는 변수를 선언합니다.
spread_string_len = len(height_restore_string)
# 손상되기 전의 원래 문자열을 저장할 변수를 선언합니다.
restored_string = ''

# 위에서 번진 문자열을 이미 하나 입력했기 때문에
# 세로로 번진 글자의 개수 - 1만큼 반복합니다.
for _ in range(H - 1):
    # 번진 문자열을 입력합니다.
    # 맨 끝의 \n은 떼어줍니다.
    spread_string = stdin.readline().rstrip()

    # 번진 문자열의 길이만큼 반복합니다.
    for char_idx in range(spread_string_len):
        # 입력한 번진 문자열에서 현재의 글자가 ?가 아니라면
        if spread_string[char_idx] != '?':
            # 세로로 번진 것을 복원한 문자열의 현재 글자의 인덱스에 ?가 아닌 현재 글자로 변경해줍니다.
            height_restore_string[char_idx] = spread_string[char_idx]

# 번진 문자열의 길이에서 가로로 번진 글자의 개수 W만큼 건너뛰면서 반복합니다.
for char_idx in range(0, spread_string_len, W):
    # 현재 인덱스에서 가로로 번진 W만큼의 한 글자를 저장하는 변수를 선언합니다.
    char_set = height_restore_string[char_idx:char_idx+W]

    # char_set이 모두 ?로 이루어져 있다면
    if char_set == ['?'] * W:
        # restored_string에 ?를 넣어줍니다.
        restored_string += '?'
    # char_set에 한 글자라도 알파벳이 있다면
    else:
        # char_set에서 ?를 모두 빼줍니다.
        char_set = list(filter(lambda char: char != '?', char_set))
        # char_set에 있는 알파벳을 restored_string에 넣어줍니다.
        restored_string += char_set[0]

# 손상되기 전의 원래 문자열을 출력합니다.
print(restored_string)


#coding=utf-8
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
import sqlite3
import threading
import os.path
aukey=''
ausecret=''
areaname="cn-hangzhou"
areadomain="edas.cn-hangzhou.aliyuncs.com"
termnum="2testcms"                    #2test
appflag=1    #0关闭，1开启
def startapp(appid):
    #print(appid)
    client = AcsClient(aukey, ausecret, areaname)
    request = CommonRequest()
    request.set_accept_format('json')
    request.set_method('POST')
    request.set_protocol_type('https')
    request.set_domain("edas.cn-hangzhou.aliyuncs.com")
    #request.set_domain(areadomain)报错
    request.set_version('2017-08-01')
    request.add_query_param("RegionId", areaname)
    request.add_query_param('AppId', appid)
    request.set_uri_pattern('/pop/v5/changeorder/co_start')
    response = client.do_action(request)
    print(str(response, encoding='utf-8'))

def stopapp(appid):
    #print(appid)
    client = AcsClient(aukey, ausecret, areaname)
    request = CommonRequest()
    request.set_accept_format('json')
    request.set_method('POST')
    request.set_protocol_type('https')
    request.set_domain("edas.cn-hangzhou.aliyuncs.com")
    #request.set_domain(areadomain)报错
    request.set_version('2017-08-01')
    request.add_query_param("RegionId", areaname)
    request.add_query_param('AppId', appid)
    request.set_uri_pattern('/pop/v5/changeorder/co_stop')
    response = client.do_action(request)
    print(str(response, encoding='utf-8'))
if __name__=="__main__":
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    ADD_LIST = os.path.join(BASE_DIR, 'edas.db')
    conn = sqlite3.connect(ADD_LIST)
    cursor = conn.cursor()
    cursor.execute('select appid,appname from apps where env=?',(termnum,))
    values = cursor.fetchall()
    cursor.close()
    conn.close()
    print(values)
    progroup={}
    if appflag == 0:
        operfunc=stopapp
    else:
        operfunc=startapp

    for appinfo in values:
        threadname=appinfo[1]
        progroup[threadname] = threading.Thread(name='th'+appinfo[1],target=operfunc,args=(appinfo[0],))
        print("%s ok" % appinfo[1])
        progroup[threadname].start()


from aiogram_dialog import Dialog

from aiogram_dialog import Window
from aiogram_dialog.widgets.input import MessageInput
from aiogram_dialog.widgets.kbd import Checkbox, Button
from aiogram_dialog.widgets.text import Const

from handlers.users.admin_panel import bool_settings, button_settings, set_text_ad
from loader import registry
from states.admin_panel import StatesAP
from utils.dbworker import get_settings

async def settings_dialog():
    settings = await get_settings()
    window_settings = []

    for k, v in settings.items():
        if v['type'] == 'bool':
            window_settings.append(
                Checkbox(
                    Const(f"✓  {v['view_name']}"),
                    Const(f" {v['view_name']}"),
                    id=k,
                    default=v['value'],
                    on_state_changed=bool_settings,
                )
            )
        elif v['type'] == 'text':
            window_settings.append(
                Button(
                    Const(f"{v['view_name']}"),
                    id=k,
                    on_click=button_settings
                )
            )

    registry.register(
        Dialog(
            Window(
                Const("Настройки:"),
                *window_settings,
                Button(
                    Const("Закрыть меню"),
                    id='delete',
                    on_click='delete'
                ),
                state=StatesAP.start
            ),
            Window(
                Const("Введи текст:"),
                MessageInput(set_text_ad),
                state=StatesAP.set_text
            )
        )
    )


# Задача 1 (Напишите программу, которая принимает на вход цифру, обозначающую день недели, и проверяет, является ли этот день выходным)

num = int(input('Введите цифру, соответствующую дню недели '))
if (num == 6) or (num == 7):  # if num == (6 or 7)
     print(f'Это выходной день')
else:
     print(f'Это будний день')

# Задача 2 (Напишите программу для проверки истинности утверждения ¬(X ⋁ Y ⋁ Z) = ¬X ⋀ ¬Y ⋀ ¬Z для всех значений предикат)

a = int(input('Введите a '))
y = int(input('Введите y '))
z = int(input('Введите z '))
if (a == 1 or y == 1 or z == 1):
    print(False)
else:
    print(True)

# a  b  c  1  2
# 0  0  0  1  1
# 0  0  1  0  0
# 0  1  0  0  0
# 0  1  1  0  0
# 1  0  0  0  0
# 1  0  1  0  0
# 1  1  0  0  0
# 1  1  1  0  0

# Задача 3 (Напишите программу, которая принимает на вход координаты точки (X и Y), причём X ≠ 0 и Y ≠ 0 и выдаёт номер четверти плоскости, в которой находится эта точка (или на какой оси она находится))

coor_x = int(input('Введите x '))
coor_y = int(input('Введите y '))
if (coor_x >= 0):
    if (coor_y >= 0):
        print('Точка находится в первой четверти')
    else:
        print('Точка находится в четвертой четверти')
else:
    if (coor_y >= 0):
        print('Точка находится во второй четверти')
    else:
        print('Точка находится в третьей четверти')

# Задача 4 (Напишите программу, которая по заданному номеру четверти, показывает диапазон возможных координат точек в этой четверти (x и y))

num = int(input('Введите номер четверти '))
if (num == 1):
    print('(x >= 0) и (y >= 0)')
elif (num == 2):
    print('(x <= 0) и (y >= 0)')
elif (num == 3):
    print('(x <= 0) и (y <= 0)')
elif (num == 4):
    print('(x >= 0) и (y <= 0)')

# Задача 5 (Напишите программу, которая принимает на вход координаты двух точек и находит расстояние между ними в 2D пространстве)

from math import sqrt

coor_x1 = int(input('Введите координату x первой точки '))
coor_y1 = int(input('Введите координату y первой точки '))
coor_x2 = int(input('Введите координату x второй точки '))
coor_y2 = int(input('Введите координату y второй точки '))
length_2 = ((coor_x1 - coor_x2)*(coor_x1 - coor_x2) + (coor_y1 - coor_y2)*(coor_y1 - coor_y2))
length = sqrt(length_2)
print(round(length,3))


import ClassesBraucon
import RPi.GPIO as GPIO
import time as tm
import numpy as np
import threading as trd
from scipy.ndimage.interpolation import shift
#import matplotlib.pyplot as plt
import os

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
#RC-Pins & LED Setup
ON_CH  = 21
OFF_CH = 26
LED    = 2
GPIO.setup(ON_CH,GPIO.OUT)
GPIO.setup(OFF_CH,GPIO.OUT)
GPIO.setup(LED,GPIO.OUT)
GPIO.output(ON_CH,GPIO.LOW)
GPIO.output(OFF_CH,GPIO.LOW)
GPIO.output(LED,GPIO.LOW)
# SPI Setup
csPin   = 8
misoPin = 9
mosiPin = 10
clkPin  = 11
# Max31865 Initialization
max31865 = ClassesBraucon.max31865(csPin,misoPin,mosiPin,clkPin)
# Variables
CurrSocketState = False # False--> Socket OFF
TempValBuffer = np.arange(10,dtype=float)
#CycCounter = 0
rootdir = os.path.dirname(os.path.realpath(__file__))+'/'#'/home/pi/braucon/'

# Functions
def Socket (NewSocketState):#, CurrSocketState):

    global CurrSocketState

    if (CurrSocketState == False and NewSocketState == True):
        GPIO.output(ON_CH,GPIO.HIGH)
        tm.sleep(0.3)
        GPIO.output(ON_CH,GPIO.LOW)
        CurrSocketState = True
    elif (CurrSocketState == True and NewSocketState == False):
        GPIO.output(OFF_CH,GPIO.HIGH)
        tm.sleep(0.3)
        GPIO.output(OFF_CH,GPIO.LOW)
        CurrSocketState = False

    return CurrSocketState

def ApplyDuty(ratio,T):
    Socket(True)
    tm.sleep(ratio*T)
    Socket(False)
    tm.sleep((1-ratio)*T)

def ReadPhasesCal():
    data = np.loadtxt(rootdir + 'MaischPhasen.dat', delimiter='\t',dtype='str')
    data = [x[2:-1] for x in data]
    phases = np.array([x.split(',') for x in data])
    gain,offset = np.loadtxt(rootdir + 'Calibration.data', dtype=float)
    del data

    return phases,gain,offset

def Pt100_Filter_C():

    global TempValBuffer

    FilterBuffer = np.zeros(50, dtype=float)

    while True:
        for i in range (48):
            T = max31865.readTemp()
            FilterBuffer = shift(FilterBuffer,1,cval= T)
            tm.sleep(0.02)

        FilterBuffer = np.sort(FilterBuffer, axis=0)
        IQR_Mean = np.mean(FilterBuffer[12:36])
        IQR_MeanCal = np.round(gain * IQR_Mean + offset,2) ##calibrated
        TempValBuffer = shift(TempValBuffer,1,cval=IQR_MeanCal)

def CalcDeltaT (PhaseNum):

    global CycCounter

    T_soll = float(phases[PhaseNum][1])
    T_curr = TempValBuffer[0] #--- T_curr = Pt100_Mean_C(2,0.5)
    DeltaT = T_curr-T_soll
    print('T='+str(T_curr) +'GrC\t' +'Delta= ' + str(DeltaT) + 'GrC')

    return DeltaT

def HeatToTemp(PhaseNum):

    while ( CalcDeltaT(PhaseNum) < -0.4):

        Delta = abs(CalcDeltaT(PhaseNum))
        print(str(TempValBuffer[0]) + 'GrC')
        if (Delta > 5):
            Socket(True)
            tm.sleep(5)
        elif(Delta < 5 and Delta > 2.5):
            print('75%')
            ApplyDuty(0.75,50)
##            tm.sleep(5)
        elif(Delta < 2.5  and Delta > 1.0):
            print('50%')
            ApplyDuty(0.5,40)
##            tm.sleep(10)
        elif(Delta < 1.0  and Delta > 0.3):
            print('15%')
            ApplyDuty(0.15,30)
            tm.sleep(20)
        else:
            print('0%')
            Socket(False)
            tm.sleep(5)
    print('Heating done!')

def Rast(PhaseNum):
    RastTime = int(phases[PhaseNum][2])

    for i in range(RastTime):
        print(phases[PhaseNum][2])
        print(str(RastTime-i) + ' minutes remaining')
        tm.sleep(40)
        if ( CalcDeltaT(PhaseNum) < -0.2):
            Delta = abs(CalcDeltaT(PhaseNum))
            print(str(TempValBuffer[0]) + 'GrC')

            if(Delta < 2  and Delta > 0.8):
                print('15%')
                ApplyDuty(0.15,20)
            elif(Delta < 0.8  and Delta > 0.1):
                print('5%')
                ApplyDuty(0.05,20)
        else:
            print('0%')
            Socket(False)
            tm.sleep(20)

def ExecPhase(PhaseNum):
    print('Executing:  ' + phases[PhaseNum][0])
    T_soll = float(phases[PhaseNum][1])
    print('T_soll:  ' + str(T_soll) )#+ '°C')

    HeatToTemp(PhaseNum)
    print('Rast started:')
    Rast(PhaseNum)

def Background():
    Pt100_Filter_C()

def Main():

   # fig = plt.figure()

    for i in range(1,len(phases)):
        print('starting phase ' + str(i))
        ExecPhase(i)

    GPIO.cleanup()

##Read Calibration and phases
#global phases,gain,offset
phases,gain,offset = ReadPhasesCal()
print(phases)
print('Gain: ' + str(gain) + ' Offset: ' + str(offset))

## Initialize Temperature measurement
TempThread = trd.Thread(target=Background) #new values with 2Hz
MainThread = trd.Thread(target=Main)
##TempThread.daemon = True
TempThread.start()
tm.sleep(2) #TempValBuffer has to be filled
MainThread.start()


# -*- coding: utf-8 -*-
__author__ = "Paul Schifferer <dm@sweetrpg.com>"
"""License routes.
"""

# from flask_rest_jsonapi import Api
from .manager import LicenseList, LicenseDetail, LicenseVolumeRelationship
from ...blueprints import api

def setup_routes(app):
    # app.logger.info("Registering license models...")
    # for model_name, model_info in license_model_info.items():
    #     APIData.add_model(model_name, model_info)

    app.logger.info("Setting up routes for Licenses API")
    # api = Api(app)
    api.route(LicenseList, "license_list", "/licenses/")
    api.route(LicenseDetail, "license_detail", "/licenses/<id>")
    api.route(LicenseVolumeRelationship, "license_authors", "/licenses/<id>/relationships/volumes")


import matplotlib.pyplot as plt
plt.style.use('ggplot')#这里我使用的是ggplot风格
customers = ['ABC','DEF','GHI','JKL','MNO']#横轴
customers_index = range(len(customers))
sale_amounts = [127,90,201,111,232]
fig = plt.figure()
#添加一个子图1，1，1表示创建一个一行一列的子图
ax1 = fig.add_subplot(1,1,1)
#customers_index设置条形左侧在x轴上的坐标，sale_amounts设置条形的高度，align='center'设置条形与标签中间对齐，color即为设置颜色。
ax1.bar(customers_index,sale_amounts,align='center',color='darkblue')
#设置刻度线位置在x轴底部和y轴左侧，使图形的上部和右侧不显示刻度线
ax1.xaxis.set_ticks_position('bottom')
ax1.yaxis.set_ticks_position('left')
#rotation=0表示刻度标签是水平的，fontsize = 'small'将刻度标签的字体设为小字体
plt.xticks(customers_index,customers,rotation=0,fontsize = 'small')
plt.xlabel('Custmoer Name')
plt.ylabel('Sale Amount')
plt.title('Sale Amount per Customer')
#dpi=400设置图形分辨率，bbox_inches = 'tight'表示保存图片时，将四周的空白去掉
plt.savefig('bar_plot.png',dpi=400,bbox_inches = 'tight')
plt.show()


n = int(input())

arr = []

tmp = input().split(" ")
for num in tmp:
    if num.isdigit() :
        arr.append(int(num))

prev = 1
flag = 1

for i in range(n):
    prev = prev * 2
    if prev < arr[i]:
        flag = 0
        break
    prev -= arr[i]

if flag == 0 :
    print("error")
else:
    print(prev % 1000000007)


import re

def ignore_bracketed(string_in):
    return f"(?!\[[^[]*){string_in}(?![^[]*\])"

class Character:
    def __init__(self, prefix, fill, suffix):
        self.prefix = prefix
        self.suffix = suffix
        self.fill = fill

    def sanitize(self, string_in):
        return re.sub(
            ignore_bracketed("(?<=[A-Za-z])([A-Z]+)"),
            lambda t: t.group(0).lower(),
            string_in
        )

    def add_prefix(self, string_in):
        string_out = re.sub(
            ignore_bracketed("[A-Z](?![^{]*})"),
            self.prefix.upper(),
            string_in
        )
        string_out = re.sub(
            ignore_bracketed("((?<=^)|(?<=\W))[a-z]"),
            self.prefix.lower(),
            string_out
        )
        return string_out

    def add_suffix(self, string_in):
        return re.sub(
            ignore_bracketed(f"(?<=[a-z{self.prefix.upper()}])([a-z]+)"),
            lambda t: self.suffix.lower() * len(t.group(0)),
            string_in
        )

    def add_fill(self, string_in):
        return re.sub(
            ignore_bracketed(f"(?<={self.prefix.upper()}|{self.prefix.lower()}){self.suffix * 2}(?![^{{]*}})"),
            f"{self.fill}{self.suffix}".lower(),
            string_in
        )

    def hiss(self, string_in):
        string_out = self.sanitize(string_in)
        string_out = self.add_prefix(string_out)
        string_out = self.add_suffix(string_out)
        string_out = self.add_fill(string_out)

        return string_out

character_names = [
    "ROMEO",
    "MONTAGUE",
    "LADY MONTAGUE",
    "MERCUTIO",
    "BENVOLIO",
    "BALTHASAR",
    "ABRAM",
    "JULIET",
    "CAPULET",
    "LADY CAPULET",
    "NURSE",
    "PETER",
    "TYBALT",
    "SAMPSON",
    "GREGORY",
    "PETRUCHIO",
    "Capulet's Cousin",
    "FIRST SERVINGMAN",
    "SECOND SERVINGMAN",
    "THIRD SERVINGMAN",
    "ESCALUS",
    "PARIS",
    "Paris' Page",
    "FRIAR LAWRENCE",
    "FRIAR JOHN",
    "APOTHECARY",
    "CITIZENS",
    "FIRST MUSICIAN",
    "SECOND MUSICIAN",
    "THIRD MUSICIAN",
    "FIRST WATCH",
    "SECOND WATCH",
    "THIRD WATCH",
    "CHORUS",
    "Attendants",
    "Maskers",
    "Torchbearers",
    "a Boy with a drum",
    "Gentlemen",
    "Gentlewomen",
    "PAGE",
    "SERVINGMAN",
    "FIRST SERVINGMAN",
    "SECOND SERVINGMAN",
    "PRINCE"
]

character_montague = Character("T", "z", "s")
character_capulet = Character("T", "s", "z")
character_default = Character("H", "i", "s")

character_formatting = {
    "ROMEO": character_montague,
    "MONTAGUE": character_montague,
    "LADY MONTAGUE": character_montague,
    "MERCUTIO": character_montague,
    "BENVOLIO": character_montague,
    "BALTHASAR": character_montague,
    "ABRAM": character_montague,
    "JULIET": character_capulet,
    "CAPULET": character_capulet,
    "LADY CAPULET": character_capulet,
    "NURSE": character_capulet,
    "PETER": character_capulet,
    "TYBALT": character_capulet,
    "SAMPSON": character_capulet,
    "GREGORY": character_capulet,
}


# https://www.acmicpc.net/problem/15351

# 첫 번째 줄에 즐기는 것의 개수 N을 입력합니다.
N = int(input())

# 즐기는 것의 개수 N만큼 반복합니다.
for i in range(N):
    # 즐기는 것을 입력합니다.
    # 영어 대문자와 띄어쓰기로 입력합니다.
    # 30자를 넘지 않습니다.
    enjoy = input()

    # 즐기는 것의 점수를 저장하는 변수를 선언합니다.
    score = 0

    # 즐기는 것의 한 글자씩 반복합니다.
    for alphabet in enjoy:
        # 현재 글자가 띄어쓰기라면
        if alphabet == " ":
            # 점수가 없으므로 그냥 넘어갑니다.
            continue
        # 현재 글자가 영어 대문자라면
        else:
            # 현재의 영어 대문자의 점수를 저장하는 변수를 선언합니다.
            alphabet_score = ord(alphabet) - 64
            # 영어 대문자의 점수를 즐기는 것의 점수에 더해줍니다.
            score += alphabet_score

    # 즐기는 것의 점수가 100이라면
    if score == 100:
        # PERFECT LIFE를 출력합니다.
        print("PERFECT LIFE")
    # 즐기는 것의 점수가 100 이외의 점수라면
    else:
        # 점수를 출력합니다.
        print(score)


import pygame as pg
from Settings import *
from Player import Player
from Render import Render
from Map import *

class Main:
    def __init__(self):
        pg.init()
        self.screen = pg.display.set_mode((0, 0), pg.FULLSCREEN)
        # self.screen = pg.display.set_mode((1200, 1000))
        self.clock = pg.time.Clock()
        self.player = Player(pg.display.get_surface().get_size())
        self.render = Render(self.screen)
        self.run = True

    def events(self):
        for event in pg.event.get():
            if event.type == pg.KEYUP:
                if event.key == pg.K_ESCAPE:
                    self.run = False

        keys = pg.key.get_pressed()
        if keys[pg.K_a]:
            self.player.speed_directions[LEFT] = self.player.speed
        if keys[pg.K_d]:
            self.player.speed_directions[RIGHT] = self.player.speed
        if keys[pg.K_w]:
            if self.player.can_jump:
                self.player.speed_directions[UP] = self.player.jump_speed

    def main_loop(self):
        while self.run:
            self.clock.tick(FPS)
            pg.display.set_caption(str(self.clock.get_fps()))
            self.events()
            self.player.move()

            self.rendering()

    def rendering(self):
        self.screen.fill(BLACK)
        self.render.map(self.player.camera_pos)
        self.render.player(self.player.camera_pos, self.player)
        pg.display.update()

main = Main()
main.main_loop()
pg.quit()


# Python Project Ideas: Beginners Level
# 5. Hangman
# https://www.upgrad.com/blog/python-projects-ideas-topics-beginners/

import getpass

print("Welcome to the hangman mini game!")
print("Rules are simple:")
print("1. Enter your word and the second player have to guess it letter by letter")
print("2. The one who guesses got 5 mistakes to spare")
print("3. Type whole word to complete even if you guessed all of the letters")
print("Lets begin")
print("--------------------------------------------------------------------------")

repeat = 'y'
yes = 'y'
while repeat.lower() == yes:
    def dashReplace(secret, dash, rq_guess):
        result = ""
        for i in range(len(secret)):
            if secret[i] == rq_guess:
                result = result + rq_guess
            else:
                result = result + dash[i]

        return result

    word = getpass.getpass("Enter your word: ").lower()
    dashes = "-" * len(word)
    print("Accepted")
    print("Now it is time for the second player to take control")
    print(f"The word consists of {len(word)} letters")
    print(f"::: {dashes} :::")
    guess = input("Your guess (just one letter or whole word): ").lower()

    lives = 5
    while lives > 0:
        if guess.lower() == word.lower():
            print(f"Congratz! You guessed right the whole word - {word}")
            break
        elif guess.lower() in word.lower():
            print(f"Yes {guess} is there")
            dashes = dashReplace(word, dashes, guess)
            print(f"::: {dashes} :::")
            guess = input(
                "Your next guess (just one letter or whole word): ").lower()
        else:
            lives -= 1
            print(f"Wrong. You have {lives} mistakes left")
            print(f"::: {dashes} :::")
            guess = input(
                "Your next guess (just one letter or whole word): ").lower()
        if lives == 0:
            print(f"You failed to guess the word. It was {word}")
            break
    repeat = input("Play again? Y | N : ")


frase = input("Digite uma frase: ").strip().upper()
frase = frase.replace("á", "a")
frase = frase.replace("à", "a")
quantidade = frase.count("A")
primeira = frase.find("A") + 1
ultima = frase.rfind("A") + 1
print(
    f"A Letra 'A' aparece {quantidade} vezes na frase\n"
    f"A primeira letra 'A' aparece na posição {primeira}\n"
    f"A ultima letra 'A' aparece na posição {ultima}"
)


from django.shortcuts import render
from django.http import JsonResponse
from rest_framework.response import Response
from .models import (
  PointTransaction,
  Point,
)
from rest_framework.views import APIView
from django.views.generic.base import View

class PointCheckoutAjaxView(APIView):

  def post(self, request, *args, **kwargs):
    if not request.user.is_authenticated:
      return JsonResponse({}, status=401)

    user = request.user
    print(user)
    amount = request.POST.get('amount')
    print(amount)
    type = request.POST.get('type')
    print(type)
    try:
      trans = PointTransaction.objects.create_new(
        user=user,
        amount=amount,
        type=type
      )
    except:
      trans = None
    print(trans)
    if trans is not None:
      data = {
        "works": True,
        "merchant_id": trans
      }
      return JsonResponse(data)
    else:
      return JsonResponse({}, status=401)

class PointImpAjaxView(APIView):
  def post(self, request, *args, **kwargs):
    if not request.user.is_authenticated:
      return JsonResponse({}, status=401)

    user = request.user
    merchant_id = request.POST.get('merchant_id')
    imp_id = request.POST.get('imp_id')
    amount = request.POST.get('amount')

    try:
      trans = PointTransaction.objects.get(
        user=user,
        order_id=merchant_id,
        amount=amount
      )
    except:
      trans = None

    if trans is not None:
      trans.transaction_id = imp_id
      trans.success = True
      trans.save()

      data = {
        "works": True
      }

      return JsonResponse(data)
    else:
      return JsonResponse({}, status=401)

def charge_point(request):
  template = 'charge.html'

  return render(request, template)


import numpy as np
import scipy.spatial.distance as dist

from sklearn.neighbors import KDTree

# TODO
# - Vary alpha in epsilon in the qlearner to encourage more exploration early
#
# Notes
# - The state should at least include alignment.
# - The state may also include a neighbor density function
# - Without the neighbor density function, the flock tends
#   to oscillate more;  they appear to not have a memory
#   of density.  IOW there is not positively-rewarded state
#   of "nice density" so they are constantly searching for it.

class Flock(object):
    """Object representing a flock of birds in two dimensions."""

    num_turns = 8
    num_bins_alignment = 8
    num_bins_neighbors = 4

    def __init__(self, n_birds, speed, time_step,
                 bounding_box=None,
                 perceptual_radius=2,
                 birth_box=None,
                 random_seed=42):
        self.n_birds = n_birds
        self.speed = speed
        self.delta_t = time_step
        self.bbox = bounding_box
        self.birth_box = self.bbox if birth_box is None else birth_box
        self.perceptual_radius = perceptual_radius
        self.seed = random_seed

        self.turns = np.linspace(-np.pi/6, np.pi/6, self.num_turns)

        self.TOL = 1e-6

        self.position, self.direction = self.initialize()
        self.neighbors_in_range = None

        self.n_states = self.num_bins_alignment*self.num_bins_neighbors
        self.state_bin_boundaries_neigh = np.linspace(-1-self.TOL, 1+self.TOL, self.num_bins_neighbors)
        self.state_bin_boundaries_align = np.linspace(-1-self.TOL, 1+self.TOL, self.num_bins_alignment)

        self.ideal_neighbors = 20

    def initialize(self):
        """Randomly initialize positions and directions of the flock."""
        np.random.seed(self.seed)

        position_x = np.random.uniform(self.birth_box[0], self.birth_box[1] ,self.n_birds)
        position_y = np.random.uniform(self.birth_box[0], self.birth_box[1] ,self.n_birds)
        direction_theta = np.random.uniform(0.0, 2*np.pi, self.n_birds)

        position = np.vstack((position_x, position_y)).T
        direction = np.vstack((np.cos(direction_theta), np.sin(direction_theta))).T

        return position, direction

    def get_neighbors(self):
        kdt = KDTree(self.position)
        neighbors, distances = kdt.query_radius(self.position,
                                                r=self.perceptual_radius,
                                                return_distance=True,
                                                count_only=False)

        self.neighbors_in_range = []
        self.neighbor_distances_in_range = []
        for b in range(self.n_birds):
            nbrs, dists = neighbors[b], distances[b]

            rel_pos = self.position[nbrs,:]-self.position[b,:]
            in_perception = np.dot(rel_pos, self.direction[b,:])
            inds = np.where((in_perception>0)&(dists>0))[0]
            self.neighbors_in_range.append(nbrs[inds])
            self.neighbor_distances_in_range.append(dists[inds])

        return self.neighbors_in_range

    def compute_center_of_mass(self):
        com = np.zeros_like(self.position)
        for b in range(self.n_birds):
            nbr_inds = self.neighbors_in_range[b]
            if nbr_inds.shape[0]>0:
                com[b,:] = np.mean(self.position[nbr_inds,:], axis=0)
            else:
                com[b,:] = np.inf

        return com

    def compute_average_velocity(self):
        avg_vel = np.zeros_like(self.direction)
        for b in range(self.n_birds):
            nbr_inds = self.neighbors_in_range[b]
            if nbr_inds.shape[0]>0:
                avg_vel[b,:] = np.mean(self.direction[nbr_inds,:], axis=0)
            else:
                avg_vel[b,:] = np.inf

        return avg_vel

    def update(self, turn_angles=None, delta_v=None, apply_bcs=True):
        """Update the positions and directions of birds based on a set of turn angles."""
        if turn_angles is not None:
            direction_new_x = self.direction[:,0]*np.cos(turn_angles) - self.direction[:,1]*np.sin(turn_angles)
            direction_new_y = self.direction[:,0]*np.sin(turn_angles) + self.direction[:,1]*np.cos(turn_angles)
            self.direction = np.vstack((direction_new_x, direction_new_y)).T
        else:
            self.direction += delta_v
            norm = np.linalg.norm(self.direction, axis=1)
            for i in range(self.direction.shape[1]):
                self.direction[:,i] /= norm

        self.position += self.speed*self.direction*self.delta_t
        if apply_bcs:
            self._apply_boundary_conditions()

    def _apply_boundary_conditions(self):
        """Apply periodic boundary conditions on the flock."""
        boundary_conds = {
            'left':{
                'dim':0,
                'periodic_boundary':1,
                'dist_to_boundary':self.position[:,0]-self.bbox[0],
                'on_boundary':(self.position[:,0]-self.bbox[0])<self.TOL,
                'exiting':np.dot(self.direction, np.array([-1,0])) > self.TOL
            },
            'right':{
                'dim':0,
                'periodic_boundary':0,
                'dist_to_boundary':self.bbox[1]-self.position[:,0],
                'on_boundary':(self.bbox[1]-self.position[:,0])<self.TOL,
                'exiting':np.dot(self.direction, np.array([1,0])) > self.TOL
            },
            'up':{
                'dim':1,
                'periodic_boundary':0,
                'dist_to_boundary':self.bbox[1]-self.position[:,1],
                'on_boundary':(self.bbox[1]-self.position[:,1])<self.TOL,
                'exiting':np.dot(self.direction, np.array([0,1])) > self.TOL
            },
            'down':{
                'dim':1,
                'periodic_boundary':1,
                'dist_to_boundary':self.position[:,1]-self.bbox[0],
                'on_boundary':(self.position[:,1]-self.bbox[0])<self.TOL,
                'exiting':np.dot(self.direction, np.array([0,-1])) > self.TOL
            }
        }
        for _, condition in boundary_conds.items():
            idx = np.where(condition['on_boundary'] & condition['exiting'])[0]
            multi = 1 if condition['periodic_boundary']==1 else -1
            self.position[idx,condition['dim']] = self.bbox[condition['periodic_boundary']] + multi*condition['dist_to_boundary'][idx]

    def get_state(self):
        """Return the state of each bird in the flock.

        This is the state used by the qlearner."""
        self.get_neighbors()

        cohesion = np.zeros(self.n_birds)
        alignment = np.zeros(self.n_birds)
        n_neighbors = np.zeros(self.n_birds, dtype=int)

        for i in range(self.n_birds):
            nbrs = self.neighbors_in_range[i]
            n_neighbors[i] = nbrs.shape[0]
            if nbrs.shape[0]==0:
                cohesion[i] = 0.0
                continue

            avg_direction = self.direction[nbrs,:].mean(axis=0)
            avg_direction = avg_direction/np.linalg.norm(avg_direction)

            cohesion[i] = np.dot(avg_direction, self.direction[i,:])
            alignment[i] = np.cross(avg_direction, self.direction[i,:])

        state_n = 1/(1 + np.exp(self.ideal_neighbors-n_neighbors))
        state_n = np.digitize(state_n, self.state_bin_boundaries_neigh)-1
        state_a = np.digitize(alignment, self.state_bin_boundaries_align)-1
        state = state_a + self.num_bins_alignment*state_n

        assert np.all(state_n<self.num_bins_neighbors)
        assert np.all(state_a<self.num_bins_alignment)

        return state, cohesion, alignment, n_neighbors

    def get_reward(self, cohesion, n_neighbors):
        r_n = 1 - np.abs(self.ideal_neighbors-n_neighbors)/(n_neighbors+1)
        r_c = cohesion

        return (r_n+r_c)/2

    def plot(self, figsize=(5,5)):
        import matplotlib.pyplot as plt
        fig, ax = plt.subplots(figsize=figsize)
        ax.quiver(self.position[:,0], self.position[:,1], self.direction[:,0], self.direction[:,1])
        ax.axis('equal')
        ax.set_xlim(self.bbox)


import seaborn as sns
import matplotlib.pyplot as plt

def entropy_plot(dataframe):
    df_tmp = dataframe.copy()
    df_tmp['classification'] = df_tmp['gt_label'] == df_tmp['pred_lbl']
    fig, ax = plt.subplots(figsize=(8, 6))
    # ax = sns.boxplot(ax=ax, data=df_tmp, x="classification", y="entropy", hue="quality_category")
    # ax = sns.swarmplot(ax=ax, data=df_tmp, x="classification", y="entropy", hue="quality_category")
    ax = sns.swarmplot(ax=ax, data=df_tmp, x="classification", y="entropy")
    ax.set(ylabel="Entropy")
    ax.set(xlabel="Classification")

def entropy_vs_myb(dataframe):
    df_tmp = dataframe.copy()
    df_tmp['classification'] = df_tmp['gt_label'] == df_tmp['pred_lbl']
    fig, ax = plt.subplots(figsize=(8, 6))

    df_true = df_tmp.loc[df_tmp['classification']]
    ax.scatter(df_true.myb_annotated, df_true.entropy, label='True prediction')
    df_false = df_tmp.loc[~df_tmp['classification']]
    ax.scatter(
        df_false.myb_annotated,
        df_false.entropy,
        label='False prediction')
    ax.set(ylabel="Entropy")
    ax.set(xlabel="Myeloblast percentage")
    ax.legend(title='Percent of myeloblasts in differential blood count',
              bbox_to_anchor=(1, 0., 0.5, 1), loc=10)


import random as rand
import struct as st
import patcher as patch
"""stats pattern:id(not used for stat setups),hp,mp,power,stamina,magic,hit,evade,magic defense,level,
current XP first byte,current XP last byte,XP to next level,tech points to next tech,number of techs,
current techs bitfield"""
chrono = [0,70,8,5,8,5,8,8,15,1,0,0,20,5,0,0,12]
marle = [1,65,12,2,6,20,8,6,25,1,0,0,20,5,0,0,8]
lucca = [2,62,12,2,6,20,8,7,25,1,0,0,20,5,0,0,8]
robo = [3,130,6,7,10,3,7,7,10,1,0,0,20,5,0,0,8]
frog = [4,80,9,4,8,6,8,8,15,1,0,0,20,5,0,0,11]
ayla = [5,80,4,10,9,3,10,12,10,1,0,0,20,5,0,0,13]
magus = [6,110,14,8,7,20,12,10,30,1,0,0,20,50,0,0,12]

def set_stats(file_pointer,character,location,lost_worlds):
    global chrono, marle, lucca, robo, frog, ayla, magus, char_array
    if (location == "start" or location == "start2" or location == "cathedral") and lost_worlds != "Y":
        char_array = character[1:]
        write_stats(file_pointer,character,char_array)
    elif location == "castle":
        if character == chrono:
           char_array = [122,16,10,14,6,9,9,16,5,0xF0,0,0xA0,50,2,0xC0,12]
        elif character == marle:
           char_array = [109,20,3,8,24,13,7,26,5,0xF0,0,0xA0,50,2,0xC0,8]
        elif character == lucca:
           char_array = [114,20,3,9,24,13,8,26,5,0xF0,0,0xA0,50,2,0xC0,8]
        elif character == robo:
           char_array = [170,14,13,17,5,8,8,11,5,0xF0,0,0xA0,100,2,0xC0,8]
        elif character == frog:
           char_array = [128,17,9,14,9,9,9,16,5,0xF0,0,0xA0,50,2,0xC0,11]
        elif character == ayla:
           char_array = [140,12,16,15,4,12,15,11,5,0xF0,0,0xA0,100,2,0xC0,13]
        elif character == magus:
           char_array = [150,22,13,11,24,15,12,32,5,0xF0,0,0xA0,50,2,0xC0,12]
    elif location == "proto" or location == "burrow" or location == "dactyl" or lost_worlds == "Y":
        if character == chrono:
           char_array = [262,36,24,31,10,12,13,21,15,0xBE,0x19,1450,100,3,0xE0,12]
        elif character == marle:
           char_array = [228,40,6,15,34,27,11,31,15,0xBE,0x19,1450,100,3,0xE0,8]
        elif character == lucca:
           char_array = [250,40,5,17,34,27,11,31,15,0xBE,0x19,1450,100,3,0xE0,8]
        elif character == robo:
           char_array = [310,34,29,34,10,12,11,16,15,0xBE,0x19,1450,100,3,0xE0,8]
        elif character == frog:
           char_array = [258,37,22,30,17,12,13,21,15,0xBE,0x19,1450,200,3,0xE0,11]
        elif character == ayla:
           char_array = [290,32,31,33,7,20,23,16,15,0xBE,0x19,1450,200,3,0xE0,13]
        elif character == magus:
           char_array = [250,42,26,21,34,22,19,38,15,0xBE,0x19,1450,100,3,0xE0,12]
    write_stats(file_pointer,character,char_array)

def write_stats(file_pointer,character,stats):
        start_pointer = 0xC0000 + character[0] * 0x50
        techlist_pointer = 0xC0237 + character[0]
        technumber_pointer = 0xC0230 + character[0]
        file_pointer.seek(start_pointer + 0x3)
        file_pointer.write(st.pack("H",stats[0]))
        file_pointer.seek(start_pointer + 0x5)
        file_pointer.write(st.pack("H",stats[0]))
        file_pointer.seek(start_pointer + 0x7)
        file_pointer.write(st.pack("H",stats[1]))
        file_pointer.seek(start_pointer + 0x9)
        file_pointer.write(st.pack("H",stats[1]))
        file_pointer.seek(start_pointer + 0xB)
        file_pointer.write(st.pack("B",stats[2]))
        file_pointer.seek(start_pointer + 0xC)
        file_pointer.write(st.pack("B",stats[3]))
        file_pointer.seek(start_pointer + 0xE)
        file_pointer.write(st.pack("B",stats[4]))
        file_pointer.seek(start_pointer + 0xF)
        file_pointer.write(st.pack("B",stats[5]))
        file_pointer.seek(start_pointer + 0x10)
        file_pointer.write(st.pack("B",stats[6]))
        file_pointer.seek(start_pointer + 0x11)
        file_pointer.write(st.pack("B",stats[7]))
        file_pointer.seek(start_pointer + 0x12)
        file_pointer.write(st.pack("B",stats[8]))
        file_pointer.seek(start_pointer + 0x13)
        file_pointer.write(st.pack("B",stats[9]))
        file_pointer.seek(start_pointer + 0x14)
        file_pointer.write(st.pack("H",stats[10]))
        file_pointer.seek(start_pointer + 0x2B)
        file_pointer.write(st.pack("H",stats[11]))
        file_pointer.seek(start_pointer + 0x2D)
        file_pointer.write(st.pack("H",stats[12]))
        file_pointer.seek(technumber_pointer)
        file_pointer.write(st.pack("B",stats[13]))
        file_pointer.seek(techlist_pointer)
        file_pointer.write(st.pack("B",stats[14]))
        file_pointer.seek(start_pointer + 0xD)
        file_pointer.write(st.pack("B",stats[15]))

def write_chars(file_pointer,char_dict,locked_chars,lost_worlds,outfile):
      char_keys = ["start","start2","cathedral","castle","proto","burrow","dactyl"]
      loadchars = [0x57,0x5C,0x62,0x6A,0x68,0x6C,0x6D]
      charnames = [0x39D7E,0x39D80,0x377090,0x5F6E5,0x372AB7,0x38932D,0x3BB90E]
      chars = [0x39D82,0x39D84,0x376FEB,0x5F5EE,0x372A6F,0x389275,0x3BB8FA]
      chars2 = [0,0,0x377088,0x5F6DD,0x372AAD,0x389323,0x3BB904]
      chars3 = [0,0,0x377099,0x5F6E8,0x372AC1,0x389336,0x3BB916]
      chars4 = [0,0,0x3770D1,0x5F6E8,0x372ADB,0x389352,0x3BB927]
      charloads = [0,0,0x3770D2,0x5F6E8,0x372ADC,0x389353,0x3BB928]
      if lost_worlds == "Y":
          charnames[0] = 0x39CCF
          charnames[1] = 0x39CD1
          chars[0] = 0x39CD3
          chars[1] = 0x39CD5
      if locked_chars == "Y":
          charnames[4] = 0x372AB9
          chars2[4] = 0x372AAF
          chars3[4] = 0x372AC3
          chars4[4] = 0x372ADD
          charloads[4] = 0x372ADE
          patch.patch_file("patches/locked_chars.txt",outfile)
      i = 0
      while i < 7:
            char = char_dict[char_keys[i]][0]
            file_pointer.seek(charnames[i])
            file_pointer.write(st.pack("B",char | 0xC0))
            file_pointer.seek(chars[i])
            file_pointer.write(st.pack("B",char))
            if i < 2:
                i += 1
                continue
            file_pointer.seek(chars2[i])
            file_pointer.write(st.pack("B",char))
            file_pointer.seek(chars3[i])
            file_pointer.write(st.pack("B",char))
            file_pointer.seek(chars4[i])
            file_pointer.write(st.pack("B",char))
            if chars4[i] != charloads[i]:
                file_pointer.seek(charloads[i])
                file_pointer.write(st.pack("B",loadchars[char]))
            i += 1
def randomize_char_positions(outfile,locked_chars,lost_worlds,chars,locs):
    f = open(outfile,"r+b")
    character_locations = {"start": "", "start2": "", "cathedral": "", "castle": "", "proto": "", "burrow": "", "dactyl": ""}
    characters = [chrono, marle, lucca, frog, robo, ayla, magus]
    # Sort the locs out to match character_locations
    for loc in locs :
        if loc == "Start1" :
            locs[locs.index("Start1")] = "start"
        elif loc == "Start2":
            locs[locs.index("Start2")] = "start2"
        elif loc == "Cathedral":
            locs[locs.index("Cathedral")] = "cathedral"
        elif loc == "Guardia Castle":
            locs[locs.index("Guardia Castle")] = "castle"
        elif loc == "Proto Dome":
            locs[locs.index("Proto Dome")] = "proto"
        elif loc == "Frog Burrow":
            locs[locs.index("Frog Burrow")] = "burrow"
        elif loc == "Dactyl Nest":
            locs[locs.index("Dactyl Nest")] = "dactyl"

    unset_chars = []
    set_chars = []

    x = 0
    for loc in locs:
        if loc == "":
            unset_chars.append(characters[x])
        else:
            set_chars.append(characters[x])
        while locs.count(loc) > 1 and loc != "":
            index_pos = len(locs)-locs[::-1].index(loc)-1
            locs[index_pos] = ""
        x = x+1

    for location in character_locations:
        if location in locs:
            locs.index(location) < len(locs)
            character_locations[location] = characters[locs.index(location)]
            chosen_char = character_locations[location]
            set_stats(f,chosen_char,location,lost_worlds)
        else:
            character_locations[location] = rand.choice(unset_chars)
            chosen_char = character_locations[location]
            set_stats(f,chosen_char,location,lost_worlds)
            unset_chars.remove(chosen_char)
    write_chars(f,character_locations,locked_chars,lost_worlds,outfile)
    f.close()
    return character_locations


import requests
import os
from datetime import datetime
import time
import shodan
import json
import helpers
import geome
from docker import write_docker_file
from kubernetes import write_kube_file
from schedule import shodan_query_manager

def query_shodan(api_key, query_file=None, keyword=None):
    api = shodan.Shodan(api_key)
    total = 0

    if keyword is not None:
        try:
            # Search Shodan
            results = api.search('{}'.format(keyword))
            time.sleep(3)
            # Show the results
            total += results['total']
            for result in results['matches']:
                ip = result['ip_str']
                data = result['data']
                geome.write_to_geo_file(result, ip)
                # geome.plot_map(result,ip)
                if 'docker' in result.keys():
                    docker = result['docker']
                else:
                    docker = None
                try:
                    create_report(ip, data, docker)
                except:
                    print("Report failed")
                    exit()
        except shodan.APIError as e:
            print('Error: {} \n {}'.format(e, line))
            pass
        print ("Total Results: {}".format(total))
        return 1
    if query_file is not None:
        with open(query_file, 'r', encoding="utf-8") as query_f:
            for line in query_f:
                try:
                    # Search Shodan
                    results = api.search('{}'.format(line))
                    time.sleep(3)
                    # Show the results
                    total += results['total']
                    for result in results['matches']:
                        ip = result['ip_str']
                        data = result['data']
                        if 'docker' in result.keys():
                            docker = result['docker']
                        else:
                            docker = None
                        create_report(ip, data, docker)
                except shodan.APIError as e:
                    print('Error: {} \n {}'.format(e, line))

        print ("Total Results: {}".format(total))
        return 1

def create_report(ip, data, docker=None, kubernetes=None):
    # ex. directory 2019_1_1/
    date_string = helpers.get_date_string()
    helpers.report_dir_check(date_string)

    report = "reports/" + date_string +'/'+ ip +'.txt'
    try:
        helpers.write_to_ip_file(report, ip, data)

        if docker is not None:
            write_docker_file(docker=docker,ip=ip, date_string=date_string)

        if kubernetes is not None:
            write_kube_file(ip=ip, date_string=date_string, kubernetes=kubernetes)

        with open("reports/" + date_string + "/all_ips.txt", 'a+') as ip_file:
            ip_file.write("{}\n".format(ip))
            ip_file.close()

        geome.get_location_data_from_file(data, ip)

    except Exception as e:
        pass

def all_results(api_key, keyword=None, limit_results=None):
    api = shodan.Shodan(api_key)

    if limit_results is None:
        limit = helpers.get_total_results(api, keyword=keyword)
    else:
        limit = limit_results
    date_string = helpers.get_date_string()
    helpers.report_dir_check(date_string)

    if keyword is not None:
        output_file = "reports/" + date_string + "/-export" + keyword.replace(" ", "_").replace(":", "_").replace("\"","_").replace(";","").replace(".","").replace("-","").replace("&","")
        if os.path.exists(output_file+ ".json") is False:

            os.system("shodan download --limit {} {} {}".format(limit,output_file, keyword))
            os.system("gzip -d {}".format(output_file + ".json.gz"))
        else:
            print("That query has already been ran...exiting\n\n")
            time.sleep(3)
            exit()
        with open(output_file + ".json", "r") as out_file:
            docker=None
            kubernetes=None
            for line in out_file.readlines():
                result = json.loads(line)
                ip = result['ip_str']
                data = result['data']
                if 'opts' in result.keys():

                    if 'docker' in result['opts'].keys():
                        docker = result['opts']['docker']
                    else:
                        docker = None

                if result['product'] == "Kubernetes":
                    kubernetes= result
                create_report(ip, data, docker=docker, kubernetes=kubernetes)

        out_file.close()


"""
mainwindow.py has the MainWindow class and defines the startMainMenu and startStallMenu functions.

Criteria Fulfilled:
- Program Organization
- Programming Style
- Program Correctness
"""

from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtGui import QImage, QPalette, QBrush
from PyQt5.QtCore import QSize
from functools import partial
import sys
import mainmenu as main_menu
import stall_menu
import app_data as info

class MainWindow(QMainWindow):
    # By Kyaw and Nisha
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        # Background Image
        self.setGeometry(50, 50, 400, 450)
        self.setFixedSize(592, 808)
        oImage = QImage("icons/background.jpg")
        sImage = oImage.scaled(QSize(592,808))
        palette = QPalette()
        palette.setBrush(10, QBrush(sImage))
        self.setPalette(palette)

        # Start the Main Menu
        self.startMainMenu()

    # startStallMenu is called when a stall's button is clicked on the GUI.
    # This function will then get the necessary information and open up the Stall Menu GUI.
    def startStallMenu(self,name):
        # By Kyaw
        self.name = name
        self.StallMenu = stall_menu.StallMenu(self.Window,name)

        self.setWindowTitle(info.stalls[name]+" Menu")
        self.setCentralWidget(self.StallMenu)
        self.StallMenu.backButton.clicked.connect(self.startMainMenu)
        self.show()

    # startMainMenu is called when the application first starts up
    #and whenever the back button on the Stall Menu is clicked
    def startMainMenu(self):
        # By Nisha
        self.Window = main_menu.MainMenu(self)
        self.setWindowTitle("North Spine Food Explorer")
        self.setCentralWidget(self.Window)
        for x in range(25):
            self.Window.btn[x].clicked.connect(partial(self.startStallMenu, info.stalls_list[x]))
        # If time has been set by user, then don't run live timer, just show the user-set time.
        # But if it's not, it will throw an error, which we want to avoid, so just do nothing for the error
        try:
            if "Set Time: " in self.StallMenu.time_label.text():
                self.Window.timer.stop()
                self.Window.time_label.setText(self.StallMenu.time_label.text())
        except:
            pass
        self.show()


import sys
from niveristand import nivs_rt_sequence, NivsParam
from niveristand import realtimesequencetools
from niveristand.clientapi import ChannelReference, DoubleValue, DoubleValueArray, I32Value
from niveristand.clientapi import RealTimeSequence
from niveristand.errors import TranslateError, VeristandError
from niveristand.library.primitives import arraysize, localhost_wait
import pytest
from testutilities import rtseqrunner, validation

@nivs_rt_sequence
def _return_constant():
    return 10

@nivs_rt_sequence
def _increment_param_by_ref(param):
    param.value = param.value + 1

@nivs_rt_sequence
def for_loop_variable_array():
    a = DoubleValue(0)
    b = DoubleValueArray([1, 2, 3, 4, 5])
    for x in b:
        a.value += x.value
    return a.value

@nivs_rt_sequence
def for_loop_variable_array1():
    a = DoubleValue(0)
    b = DoubleValueArray([1, 2, 3, 4, 5])
    for x in b.value:
        a.value += x.value
    return a.value

@nivs_rt_sequence
def for_loop_modify_collection():
    a = DoubleValueArray([1, 2, 3, 4, 5])
    for x in a.value:
        x.value += 1
    return a[0].value

@nivs_rt_sequence
def for_loop_modify_elements():
    a = DoubleValueArray([1, 2, 3, 4, 5])
    for x in a.value:
        _increment_param_by_ref(x)
    return a[0].value

@nivs_rt_sequence
def for_loop_constant_array():
    a = DoubleValue(0)
    for x in [1, 2, 3, 4, 5]:
        a.value += x
    return a.value

@nivs_rt_sequence
def for_loop_range():
    a = DoubleValue(0)
    for x in range(10):
        a.value += x
    return a.value

@nivs_rt_sequence
def for_loop_range_with_start():
    a = DoubleValue(0)
    for x in range(2, 10):
        a.value += x
    return a.value

@nivs_rt_sequence
def for_loop_range_with_step():
    a = DoubleValue(0)
    for x in range(2, 10, 2):
        a.value += x
    return a.value

@nivs_rt_sequence
def for_loop_range_with_variable():
    a = DoubleValue(0)
    b = I32Value(10)
    for x in range(b.value):
        a.value += x
    return a.value

@nivs_rt_sequence
def for_loop_range_with_channel_ref():
    a = DoubleValue(0)
    b = ChannelReference("Aliases/DesiredRPM")
    b.value = 10.0
    localhost_wait(0.2)
    for x in range(b.value):
        a.value += x
    return a

@nivs_rt_sequence
def for_loop_range_with_call():
    a = DoubleValue(0)
    for x in range(_return_constant()):
        a.value += x
    return a.value

@nivs_rt_sequence
def for_loop_iterate_on_array():
    a = DoubleValueArray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
    for i in range(10):
        a[0].value += a[i].value
    return a[0].value

@nivs_rt_sequence
def for_loop_else():
    a = DoubleValue(0)
    b = DoubleValueArray([1, 2, 3, 4, 5])
    for x in b.value:
        a.value += x
    else:
        a.value = -1
    return a.value

@nivs_rt_sequence
def nested_for_loop():
    a = DoubleValueArray([1, 2, 3, 4, 5])
    b = DoubleValueArray([1, 2, 3, 4, 5])
    for i in range(5):
        for j in b.value:
            a[i].value += j.value
    return a[3].value

@nivs_rt_sequence
def nested_for_loop_body():
    a = DoubleValueArray([1, 2, 3, 4, 5])
    b = DoubleValueArray([1, 2, 3, 4, 5])
    for i in range(5):
        for j in b.value:
            if j.value % 2 == 0:
                a[i].value += j.value
            else:
                a[i].value -= j.value
    return a[3].value

@nivs_rt_sequence
def looping_over_invalid_var():
    a = DoubleValue(0)
    for x in a.value:
        a.value += x
    return a.value

@nivs_rt_sequence
def for_return_in_body():
    for i in range(5):
        return i

@nivs_rt_sequence
def for_try_in_body():
    for i in range(5):
        try:
            pass
        finally:
            pass

@nivs_rt_sequence
def for_funcdef_in_body():
    for i in range(5):

        def func():
            pass

        pass

@nivs_rt_sequence
@NivsParam("array", DoubleValueArray([0]), NivsParam.BY_REF)
def _average(array):
    average_var = DoubleValue(0)
    for x in array:
        average_var.value += x.value
    average_var.value /= arraysize(array.value)
    return average_var.value

@nivs_rt_sequence
def call_average():
    a = DoubleValueArray([1, 2, 3, 4, 5])
    res = DoubleValue(0)
    res.value = _average(a)
    return res.value

run_tests = [
    (for_loop_variable_array, (), 15),
    (for_loop_variable_array1, (), 15),
    (for_loop_modify_collection, (), 2),
    (for_loop_modify_elements, (), 2),
    (for_loop_range, (), 45),
    (for_loop_range_with_variable, (), 45),
    (for_loop_range_with_call, (), 45),
    (for_loop_iterate_on_array, (), 45),
    (nested_for_loop, (), 19),
    (nested_for_loop_body, (), 1),
    (call_average, (), 3),
]

fail_transform_tests = [
    (for_loop_else, (), TranslateError),
    (for_loop_range_with_start, (), TranslateError),
    (for_loop_range_with_step, (), TranslateError),
    (looping_over_invalid_var, (), TranslateError),
    (for_return_in_body, (), TranslateError),
    (for_try_in_body, (), TranslateError),
    (for_funcdef_in_body, (), TranslateError),
    (for_loop_range_with_channel_ref, (), VeristandError),
    (for_loop_constant_array, (), VeristandError),
]

def idfunc(val):
    try:
        return val.__name__
    except AttributeError:
        return str(val)

@pytest.mark.parametrize("func_name, params, expected_result", run_tests, ids=idfunc)
def test_transform(func_name, params, expected_result):
    RealTimeSequence(func_name)

@pytest.mark.parametrize("func_name, params, expected_result", run_tests, ids=idfunc)
def test_runpy(func_name, params, expected_result):
    actual = func_name(*params)
    assert actual == expected_result

@pytest.mark.parametrize("func_name, params, expected_result", run_tests, ids=idfunc)
def test_run_py_as_rts(func_name, params, expected_result):
    actual = realtimesequencetools.run_py_as_rtseq(func_name)
    assert actual == expected_result

@pytest.mark.parametrize("func_name, params, expected_result", run_tests, ids=idfunc)
def test_run_in_VM(func_name, params, expected_result):
    actual = rtseqrunner.run_rtseq_in_VM(func_name)
    assert actual == expected_result

@pytest.mark.parametrize("func_name, params, expected_result", fail_transform_tests, ids=idfunc)
def test_failures(func_name, params, expected_result):
    with pytest.raises(expected_result):
        RealTimeSequence(func_name)
    with pytest.raises(expected_result):
        func_name(*params)

def test_check_all_tested():
    validation.test_validate(sys.modules[__name__])