import numpy
import time

import pybullet as p
import pybullet_data

freq = 500
get_last_vel = [0] * 3
motor_id_list = [0, 1, 2, 4, 5, 6, 8, 9, 10, 12, 13, 14]
init_new_pos = [0.0, -1.13, 1.6, 0.0, -1.13, 1.6, 0.0, 1.13, -1.6, 0.0, 1.13, -1.6,
                0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

def get_data_from_sim():
    global get_last_vel
    get_orientation = []
    get_matrix = []
    get_velocity = []
    get_invert = []
    imu_data = [0] * 10
    leg_data = [0] * 24

    pose_orn = p.getBasePositionAndOrientation(boxId)

    for i in range(4):
        get_orientation.append(pose_orn[1][i])
    # get_euler = p.getEulerFromQuaternion(get_orientation)
    get_velocity = p.getBaseVelocity(boxId)
    get_invert = p.invertTransform(pose_orn[0], pose_orn[1])
    get_matrix = p.getMatrixFromQuaternion(get_invert[1])

    # IMU data
    imu_data[3] = pose_orn[1][0]
    imu_data[4] = pose_orn[1][1]
    imu_data[5] = pose_orn[1][2]
    imu_data[6] = pose_orn[1][3]

    imu_data[7] = get_matrix[0] * get_velocity[1][0] + get_matrix[1] * \
        get_velocity[1][1] + get_matrix[2] * get_velocity[1][2]
    imu_data[8] = get_matrix[3] * get_velocity[1][0] + get_matrix[4] * \
        get_velocity[1][1] + get_matrix[5] * get_velocity[1][2]
    imu_data[9] = get_matrix[6] * get_velocity[1][0] + get_matrix[7] * \
        get_velocity[1][1] + get_matrix[8] * get_velocity[1][2]

    # calculate the acceleration of the robot
    linear_X = (get_velocity[0][0] - get_last_vel[0]) * freq
    linear_Y = (get_velocity[0][1] - get_last_vel[1]) * freq
    linear_Z = 9.8 + (get_velocity[0][2] - get_last_vel[2]) * freq
    imu_data[0] = get_matrix[0] * linear_X + \
        get_matrix[1] * linear_Y + get_matrix[2] * linear_Z
    imu_data[1] = get_matrix[3] * linear_X + \
        get_matrix[4] * linear_Y + get_matrix[5] * linear_Z
    imu_data[2] = get_matrix[6] * linear_X + \
        get_matrix[7] * linear_Y + get_matrix[8] * linear_Z

    # joint data
    joint_state = p.getJointStates(boxId, motor_id_list)
    leg_data[0:12] = [joint_state[0][0], joint_state[1][0], joint_state[2][0],
                      joint_state[3][0], joint_state[4][0], joint_state[5][0],
                      joint_state[6][0], joint_state[7][0], joint_state[8][0],
                      joint_state[9][0], joint_state[10][0], joint_state[11][0]]

    leg_data[12:24] = [joint_state[0][1], joint_state[1][1], joint_state[2][1],
                       joint_state[3][1], joint_state[4][1], joint_state[5][1],
                       joint_state[6][1], joint_state[7][1], joint_state[8][1],
                       joint_state[9][1], joint_state[10][1], joint_state[11][1]]
    com_velocity = [get_velocity[0][0],
                    get_velocity[0][1], get_velocity[0][2]]
    # get_last_vel.clear()
    get_last_vel = []
    get_last_vel = com_velocity

    return imu_data, leg_data, pose_orn[0]

p.connect(p.GUI)  # or p.DIRECT for non-graphical version
p.setAdditionalSearchPath(pybullet_data.getDataPath())  # optionally
p.resetSimulation()
p.setTimeStep(1.0/freq)
p.setGravity(0, 0, -9.8)

robot_start_pos = [0, 0, 0.8]
boxId = p.loadURDF("./models/big_iron_horse/big_iron_horse_simple.urdf", robot_start_pos,
                       useFixedBase=False)

jointIds = []
for j in range(p.getNumJoints(boxId)):
    p.getJointInfo(boxId, j)
    jointIds.append(j)

p.resetBaseVelocity(boxId, [0, 0, 0], [0, 0, 0])
for j in range(12):
    p.resetJointState(boxId, motor_id_list[j], init_new_pos[j], init_new_pos[j+12])

for _ in range(20):
    p.stepSimulation()
    imu_data, leg_data, _ = get_data_from_sim()
    print(leg_data)
    time.sleep(1)


#coding: utf-8
"""Um vetor real X com n elementos é apresentado como resultado de um sistema de equações lineares Ax = B cujos coeficientes
são representados em uma matriz real Amxn e os lados direitos das equações em um vetor real B de m elementos.
Verificar se o vetor X é realmente solução do sistema dado."""
#Thiago Santos Borges - 1615310023
#Antonio Rodrigues de Souza Neto - 1615310028
#Monitor: Lucas Botinelly
def criar_matriz(nlinha,ncoluna):
	matriz = []
	for i in range(1,nlinha + 1):
		linha = []
		for j in range(1,ncoluna + 1):
			elemento = int(input("M[%d][%d]: "%(i,j)))
			linha.append(elemento)
		matriz.append(linha)
	return matriz

def criar_vetor(tamanho):
	vetor = []
	for i in range(1,tamanho + 1):
		valor = int(input("V[%d]: "%(i)))
		vetor.append(valor)
	return vetor

def multiplicar_vetor(matriz,vetor):
	linha = len(matriz)
	coluna = len(matriz[0])
	produto = []
	for i in range(linha):
		acm = 0
		for j in range(coluna):
			acm += matriz[i][j] * vetor[j]
		produto.append(acm)
	return produto

def verificar_resultado(solucao,resultado):
	if solucao == resultado:
		return True
	else:
		return False
def mostrar_matriz(matriz,linhas):
	for i in range(linhas):
		print(matriz[i])

tamanho_solucao = int(input("tamanho vetor Teste: "))
solucao = criar_vetor(tamanho_solucao)

linha = int(input("Quantas linhas tem a matriz de coeficiente? "))
coluna = int(input("Quantas colunas tem a matriz de coeficiente? "))
matriz = criar_matriz(linha,coluna)

print("Vetor X")
tamanho_X = coluna
vetor = criar_vetor(tamanho_X)

resultado = multiplicar_vetor(matriz,vetor)
print("\nMatriz")
mostrar_matriz(matriz,linha)
if verificar_resultado(solucao,resultado):
	print("Resultado Correto")
else:
	print("Resultado incorreto")


'''
Last Modified: 17-3-2015
Sebastiaan Greeven

Based on code from jhkwakkel <j.h.kwakkel (at) tudelft (dot) nl>
'''

import os
import numpy as np

import jpype

from connectors.netlogo import NetLogoModelStructureInterface
from expWorkbench import ParameterUncertainty, CategoricalUncertainty, Outcome,\
                         ModelEnsemble, ema_logging, save_results, warning,\
                         debug

class EVO(NetLogoModelStructureInterface):
    model_file = r"/ModelSebastiaanGreevenDemoStoch.nlogo"

    run_length = 100

    uncertainties = [
                     ]

    outcomes = [Outcome('CumulativeGHGreduction', time=True),
                ]

if __name__ == "__main__":
    #turn on logging
    ema_logging.log_to_stderr(ema_logging.INFO)

    #instantiate a model
    vensimModel = EVO( r"./models", "simpleModel")

    #instantiate an ensemble
    ensemble = ModelEnsemble()

    #set the model on the ensemble
    ensemble.set_model_structure(vensimModel)
#
#     run in parallel, if not set, FALSE is assumed
    ensemble.parallel = True

    cases = [ {} for _ in range(100)]

    #perform experiments
    results = ensemble.perform_experiments(cases, reporting_interval=100)

    save_results(results, r'.\data\EMA results ModelSebastiaanGreeven 100 exp Demo Stoch.tar.gz')


import random

player = int(input("请输入  (0)剪刀   (1)石头   (2)布"))
print("用户输入的是: ", player)

# 随机出一个数字, [0,2]
# 使用随机数函数 random
# random.randint(a,b), 能够生成[a,b]的随机整数
computer = random.randint(0, 2)
print("电脑输入的是: ", computer)

if (player == 0 and computer == 2) or (player == 1 and computer == 0) or (player == 2 and computer == 1):
    print("player wins")
elif player == computer:
    print("equality")
else:
    print("computer wins")

# 三元表达式 if ... else 的简写
num1 = int(input())
num2 = int(input())

x = num1 if num1 > num2 else num2  # x取大的值
print(x)


from helpers.json_helpers import TranslationDict

class GeneralMessagesClass(TranslationDict):
    # Default values (overridden if a translation is loaded)
    WELCOME = "Bonjour et bienvenue au château de Moulinsart !\n" \
              "Pour commencer, rejoins une équipe en sélectionnant un des numéros ci-dessous !\n" \
              "Si tu as besoin d'aide, tu peux appeler mon majordome {master} dans {channel} !"

    WELCOME_FILE = "files/placeholder.png"

    DM_MESSAGE_WELCOME = "Bienvenue à Moulinsart {user} !"

    DM_MESSAGES_ERROR = "{user_mention} pourrais-tu changer tes paramètres pour que " \
                        "je puisse t'envoyer un message personnel ? " \
                        "Quand ça sera fait, envoie-moi un petit message personnel (à {bot_mention}) !\n" \
                        "Pour changer tes paramètres clique sur la petite roue en bas, puis, dans l'onglet " \
                        "`Confidentialité & Sécurité`, coche la case 'Autoriser les messages privés en provenance " \
                        "des membres du serveur' (voir l'image en-dessous)"

    DM_MESSAGES_ERROR_FILE = "files/param_privacy_discord.png"

    INVITE_MESSAGE = "Hey ! J'ai trouvé des places pour une visite gratuite du château de Moulinsart " \
                     "(oui le château de Tintin !) On peut pas le visiter en vrai à cause du confinement, " \
                     "mais on peut le voir via nos écrans ici : {link}"

    GOOD_ANSWERS = [
        "Correct !",
        "Ouiiii",
        "Exactement !",
        "Tout à fait !",
        '''Comme dirais Dupont: "Je dirais même plus, c'est exact !"''',
        "Oui, c'est ça !"
    ]

    BAD_ANSWERS = [
        "Incorrect !",
        "Nooooon",
        "Raté !",
        "Pas du tout !",
        '''Comme dirais Dupond: "Je dirais même plus, c'est inexact !"''',
        "Non, c'est pas ça !"
    ]

    ALREADY_SAID = [
        "Oui, tu l'as déjà dit !",
        "Merci, je sais !",
        "Effectivement, ça n'a pas changé...",
        "D'accord, et ?",
        "C'est pas nouveau !",
        "Oui, je suis déjà au courant 😉"
    ]

GeneralMessages = GeneralMessagesClass(path="configuration/general_messages")


import cx_Oracle
import pandas as pd
import datetime as dt
from typing import List, Tuple, Union

class Dfm2DayaheadForecastedDemandFetchRepo():
    """block wise forecasted demand fetch repository for R0A
    """

    def __init__(self, con_string):
        """initialize connection string
        Args:
            con_string ([type]): connection string
        """
        self.connString = con_string

    def toListOfTuple(self, df:pd.core.frame.DataFrame) -> List[Union[dt.datetime, float]]:
        """convert demand data to list of list [[timestamp, forecastedDemandValue],]
        Args:
            df (pd.core.frame.DataFrame): demand data dataframe
        Returns:
            List[Union[dt.datetime, float]]: list of list of demand data
        """

        data:List[List] = []
        for ind in df.index:
            tempList = [df['TIME_STAMP'][ind], float(df['FORECASTED_DEMAND_VALUE'][ind]) ]
            data.append(tempList)
        return data

    def fetchForecastedDemand(self, startTime: dt.datetime, endTime: dt.datetime, entityTag:str) -> List[Union[dt.datetime, float]]:
        """fetch forecasted demand and return list of list [[timestamp, forecastedDemandValue],]
        Args:
            startTime (dt.datetime): start time
            endTime (dt.datetime): end time
            entityTag (str): entity tag
        Returns:
            List[Union[dt.datetime, float]]: list of list [[timestamp, forecastedDemandValue],]
        """

        try:
            connection = cx_Oracle.connect(self.connString)

        except Exception as err:
            print('error while creating a connection', err)
        else:
            try:
                cur = connection.cursor()
                fetch_sql = "SELECT time_stamp,forecasted_demand_value FROM dfm2_forecast_revision_store WHERE time_stamp BETWEEN TO_DATE(:start_time,'YYYY-MM-DD HH24:MI:SS') and TO_DATE(:end_time,'YYYY-MM-DD HH24:MI:SS') and revision_no='R0A' and entity_tag =:entity ORDER BY time_stamp"
                cur.execute("ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS' ")
                forecastedDemandDf = pd.read_sql(fetch_sql, params={
                                 'start_time': startTime, 'end_time': endTime, 'entity':entityTag}, con=connection)

            except Exception as err:
                print('error while creating a cursor', err)
            else:
                connection.commit()
        finally:
            cur.close()
            connection.close()

        data: List[Union[dt.datetime, float]] = self.toListOfTuple(forecastedDemandDf)
        return data


#calss header
class _EXPLOSIVE():
	def __init__(self,):
		self.name = "EXPLOSIVE"
		self.definitions = [u'a substance or piece of equipment that can cause explosions']

		self.parents = []
		self.childen = []
		self.properties = []
		self.jsondata = {}

		self.specie = 'nouns'

	def run(self, obj1 = [], obj2 = []):
		return self.jsondata


import math
import json
from test_tree import create_data, test

def majority_value(vals):
    count_num = []
    for i in range(3):
        count_num.append(vals.count(str(i+1)))
    c = max(count_num)
    return str(count_num.index(c) + 1)

def fitness_func(data, target_attr, list_D):
    list_0 = []
    for i in range(len(data)):
        if data[i][-1] == '0':
            list_0.append(data[i])
    list_1 = []
    for i in range(len(data)):
        if data[i][-1] == '1':
            list_1.append(data[i])
    p0 = len(list_0)/len(data)
    p1 = len(list_1)/len(data)
    if p0 != 0 and p1 != 1 and p0 != 1 and p1 != 0:
        ent_d = -(p0 * math.log(p0, 2) + p1 * math.log(p1, 2))
    else:
        ent_d = 0

    result = []
    for i in range(len(list_D)):
        list_t = []
        for j in range(len(list_D[i])):
            if data[list_D[i][j]-1][-1] == target_attr:
                list_t.append(list_D[i][j])
        # print('list_t:' + str(list_t))

        p = len(list_t)/len(list_D[i])
        if p == 0:
            result.append(-((1-p) * math.log((1-p), 2)))
        elif p == 1:
            result.append(-(p * math.log(p, 2)))
        else:
            result.append(-(p * math.log(p, 2) + (1-p) * math.log((1-p), 2)))
    # print('result:' + str(result))
    gain = ent_d
    for i in range(len(list_D)):
        gain -= len(list_D[i])/len(data) * result[i]
    # print('gain:' + str(gain))
    return gain

def choose_attribute(data, attributes, target_attr, fitness_func):
    list_gain = []
    # print(data)
    for k in attributes:
        list_1, list_2, list_3 = [], [], []
        for j in range(len(data)):
            if data[j][ord(k)-ord('a')] == '1':
                list_1.append(j+1)
            elif data[j][ord(k)-ord('a')] == '2':
                list_2.append(j+1)
            else:
                list_3.append(j+1)
        list_d = [list_1, list_2, list_3]
        try:
            while [] in list_d:
                list_d.remove([])
        except:
            pass
        # print('list_d:' + str(list_d))
        list_gain.append(fitness_func(data, target_attr, list_d))
    # print('list_gain:' + str(list_gain))
    max_gain = max(list_gain)
    # print('max_gain:' + str(max_gain))
    return attributes[list_gain.index(max_gain)]

def get_values(data, best):
    list_1, list_2, list_3 = [], [], []
    for j in range(len(data)):
        if data[j][ord(best) - ord('a')] == '1':
            list_1.append(j+1)
        elif data[j][ord(best) - ord('a')] == '2':
            list_2.append(j+1)
        else:
            list_3.append(j+1)
    list_best = [list_1, list_2, list_3]
    # print('get_values list_best:' + str(list_best))
    return list_best

def get_examples(data, val):
    examples = []
    for num in val:
        examples.append(data[num-1])
    # print('examples:' + str(examples))
    return examples

# data:训练集；attributes:属性集；target_attr:好瓜/坏瓜
# data的元素应该为字典，data=[(’瓜1‘)[“属性值”, “属性值”, ...]。。。]
def create_decision_tree(data, attributes, target_attr, fitness_func, call_count):
    call_count += 1
    print("call_count:", call_count)
    data = data[:]
    print('data:' + str(data))
    if call_count == 1:
        vals = [record[-1] for record in data]
    else:
        try:
            global nex
            nex = choose_attribute(data, attributes, target_attr, fitness_func)
            print('nex:' + nex)
            vals = [record[ord(nex) - ord('a')] for record in data]
            print('vals:' + str(vals))
        except ZeroDivisionError:
            pass

    # 如果属性集为空 或者 属性数量小于等于1
    if not data or (len(attributes) - 1) <= 0:
        print('属性集为空 或者 属性数量小于等于1')
        if data == []:
            dir = {}
            for i in range(3):
                dir[str(i+1)] = {'r': '0'}
            default = dir
        else:
            dir = {majority_value(vals): {'r': '1'}}
            for i in range(3):
                if int(majority_value(vals)) != i + 1:
                    dir[str(i + 1)] = {'r': '0'}
            default = {nex: dir}
        print('default:', {nex: default})
        return {nex: default} # 返回样本数最多的类
    # 如果样本全属于同一类
    elif vals.count(vals[0]) == len(vals):
        print('样本全属于同一类')
        dir = {vals[0]: {'r': '1'}}
        for i in range(3):
            if int(vals[0]) != i+1:
                dir[str(i+1)] = {'r': '0'}
        print({nex: dir})
        return {nex: dir}
    else:
        # Choose the next best attribute to best classify our data
        best = choose_attribute(data, attributes, target_attr, fitness_func)
        # Create a new decision tree/node with the best attribute and an empty dictionary object--we'll fill that up next.
        tree = {best:{}} # 生成决策树，是一个嵌套的字典
        print(tree)
        # Create a new decision tree/sub-node for each of the values in the best attribute field
        val = get_values(data, best) # 筛选出最佳属性的三种属性值的序号组

        for i in range(len(val)):
            print('val:' + str(val))
            # Create a subtree for the current value under the "best" field
            print('val_i:' + str(val[i]))
            tree[best][str(i+1)] = create_decision_tree(get_examples(data, val[i]),
                [attr for attr in attributes if attr != best],
                target_attr, fitness_func, call_count)
            # Add the new subtree to the empty dictionary object in our new tree/node we just created.
    return tree

if __name__ == '__main__':
    with open("wm3.csv", 'r') as f:
        data = [d.split(',')[1:] for d in [s.replace('\n', '') for s in f.readlines()]]
    print(data)
    attributes = [chr(ord('a')+i) for i in range(len(data[0])-1)] # 6种属性
    print(attributes)
    target_attr = '1' # 选取好瓜
    call_count = 0
    # list_d = [[1,4,6,10,13,17],[2,3,7,8,9,15],[5,11,12,14,16]]
    # print(choose_attribute(data, attributes, target_attr, fitness_func))
    tree = create_decision_tree(data, attributes, target_attr, fitness_func, call_count)
    print('tree:\n', tree)
    print('formated_tree:')
    json_tree = json.dumps(tree, sort_keys=True, indent=4, separators=(',', ': '))
    print(json_tree)
    with open('tree.json', 'w') as f:
        f.write(json_tree)
    test_data = create_data()
    result = {}
    print('\ntest_data:\n', test_data)
    for i in range(len(test_data)):
        r = test(tree, test_data[i])
        result[i+1] = r
    print('test_result:\n', result)


# @author       Jiawei Lu (jiaweil9@asu.edu)
# @time         2021/6/25 15:21
# @desc         [script description]

import osm2gmns as og

# quick tip: please use the latest version of osm2gmns to aviod any potential issues
#       the lateest version is 0.5.4 (6/25/2021)

# specify link types that we need with the link_type argument
#       link types that osm2gmns supports include:
#       motorway, trunk, primary, secondary, tertiary, residential,
#       service,cycleway, footway, track, unclassified

# combine short links
#       set combine as True to enable osm2gmns combine short links with the exact same attributes
#       note: alouthgh osm2gmns has this function, the number of links that will be combined is limited.

# default values for free_speed, lanes, capacity
#       some links (about 25% in the US) in osm do not have free_speed, lanes, capacity values, which may be essential for simulation or ODME
#       osm2gmns is able to assign a default value for these links acoording to their link type
#       for speed, set default_speed=True. similar for the other two fields

# to clarify the is_link field in link.csv
#       In raw OpenStreetMap datasets, each link type includes two sub-types
#       take motorway as an example. They have motoryway and motorway_link
#       In link.csv files produced by osm2gmns, the link_type of motoryway and motorway_link are both motoryway, but is_link=1 for motorway_link
#       you can check the osm wiki page for a detailed introduction about the meaning of '_link' for different types of roads
#       https://wiki.openstreetmap.org/wiki/Key:highway

net = og.getNetFromFile('L101N.osm', link_type=('motorway','trunk','primary','secondary'), POIs=True, POI_sampling_ratio=1.0,combine=True)
og.consolidateComplexIntersections(net)
og.connectPOIWithNet(net)
og.generateNodeActivityInfo(net)
og.outputNetToCSV(net, output_folder='consolidatedwPOI_partial')


#!/usr/bin/python3.6

import time
import os
import sys

def verif():
    time.sleep(1)
    t1 = time.time()
    tpsEcoule = t1 - t0
    print(str(int(tpsEcoule)) + ' ...')

    if tpsEcoule > temps:
        print('\a' + '\a' + '\a' + '\a' + '\a' + '\a')
        print('FIN, %s s (%s min)' % (temps, temps/60))
    else:
        verif()

if len(sys.argv) < 2:
    print('Argument temps (min) manquant')
    sys.exit(1)

temps = sys.argv[1]
temps = float(temps) * 60

t0 = time.time()
print()
verif()


# -*- coding: utf-8 -*-
from contextlib import contextmanager
from maya import cmds

@contextmanager
def undo_chunk():
    '''Context that executes code in an undo chunk. If the code raises an
    exception the context rollsback before raising the exception.'''

    cmds.undoInfo(openChunk=True)
    try:
        yield
    except:
        cmds.undoInfo(closeChunk=True)
        cmds.undo()
        raise
    else:
        cmds.undoInfo(closeChunk=True)

@contextmanager
def selection(long=True):
    '''Context that yields the current selection, then restores your selection
    after completion.

    :param long: Yield fullpaths of nodes.
    '''

    selection = cmds.ls(sl=True, long=long)
    yield selection
    cmds.select(selection)


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

import os
import sys

import numpy as np
import qutip as qu

import matplotlib.pyplot as plt

import ob_two
import opticalbloch.t_funcs as tf

pi = np.pi

base = os.path.basename(__file__)
savename = os.path.splitext(base)[0]

def solve():

### TwoOB

    two_obj = ob_two.OBTwo(gammas=[2*pi*0.])

    two_obj.set_H_Delta([2*pi*0.])

    squares = lambda t, args: (tf.square_1(t, args) +
                               tf.square_2(t, args))
    two_obj.set_H_Omega([2*pi*10.], [squares])

    args = {'on_1':.3, 'off_1':.325, 'ampl_1':1.,
            'on_2':.6, 'off_2':.625, 'ampl_2':1.}

### Solve with QuTiP

    tlist = np.linspace(0., 1., 201)

    # Need to set a max step or it won't see the switch on
    opts = qu.Options(max_step=.01)
    two_obj.mesolve(tlist, td=True, args=args, opts=opts, show_pbar=False)

    return two_obj, args

def plot(two_obj, args):

    t = two_obj.result.times
    states_t = two_obj.states_t()

    pop_1 = states_t[:,1,1].real
    coh_im = states_t[:,1,0].imag

    squares = lambda t, args: (tf.square_1(t, args) +
                               tf.square_2(t, args))

### Plot

    fig = plt.figure()
    ax = fig.add_subplot(3,1,1)
    ax.plot(t, squares(t, args), c='g', zorder=10)
    ax.set_ylabel(r'Rabi Frequency')
    ax = fig.add_subplot(3,1,2)
    ax.plot(t, pop_1)
    ax.set_ylabel(r'Excited Population')
    ax.set_ylim([0.,1.])
    ax = fig.add_subplot(3,1,3)
    ax.plot(t, coh_im, c='r')
    ax.set_xlabel(r'Time ($\tau$)')
    ax.set_ylabel(r'Imag Coherence')
    ax.set_ylim([-.5,.5])
    plt.draw()

def main():
    two_obj, args = solve()
    plot(two_obj, args)

### Save and show figures

    # for n in plt.get_fignums():
    #     plt.figure(n).savefig('png/'+savename+'_fig'+str(n)+'.png')
    #     plt.figure(n).savefig('pdf/'+savename+'_fig'+str(n)+'.pdf')

    plt.show()

if __name__ == "__main__":
    status = main()
    sys.exit(status)


def print_list(list):
    for x in list:
        print(x)

def read_list(n):
    i = 1
    listoutput = []
    while i<n+1:
        value = float(input(f"Enter value{i}: "))
        listoutput.append(value)
        i += 1
    return listoutput

def compute_area_list(list1, list2):
    area_list=[]
    n = len(list1)
    for i in range (n) :
        area = list1[i]*list2[i]
        area_list.append(area)
    return area_list

def compute_perimeter_list(list1, list2):
    area_list=[]
    n = len(list1)
    for i in range (n) :
        area = (list1[i]+list2[i])*2
        area_list.append(area)
    return area_list

def area_or_perimeter():
    ans = str(input("Area (A) or Perimeter (P)? "))
    return ans

n = int(input("Enter n: "))
way = area_or_perimeter()
print("Side 1:")
list1 = read_list(n)
print("Side 2:")
list2 = read_list(n)
if way == "A":
    a_list = compute_area_list(list1,list2)
    print_list(a_list)
else:
    a_list = compute_perimeter_list(list1,list2)
    print_list(a_list)


from flask import Blueprint, request, jsonify
from database.database import db
import uuid
import datetime
from datetime import date
import time
from flask_cors import CORS, cross_origin

createTodo = Blueprint("createTodo", __name__)
CORS(createTodo)

@createTodo.route("/api/user/<userId>/todo/create", methods=["POST"])
@cross_origin(headers=['Content-Type', 'Authorization'])
def createTodoRoute(userId):
  if not userId:
    return (jsonify({"error": "Missing userId"}), 400)

  data = request.get_json()

  if not data:
    return (jsonify({"msg": "Missing data"}), 400)

  todoName = data.get("todoName")
  description = data.get("description")
  imageUrl = data.get("imageUrl")
  dueDate = data.get("dueDate")

  # 2020-10-21T10:00:08.920Z
  dueDate = int(dueDate)
  # dueDate = datetime.datetime.strptime(dueDate, '%Y-%m-%dT%H:%M:%S.%fZ').timestamp() * 1000

  error_log = {
    "todoName":todoName,
    "dueDate":dueDate,
    "imageUrl":imageUrl,
  }

  for key in error_log:
    if not error_log[key]:
      return (jsonify({"error": "Missing {}".format(key)}), 400)

  # do the converting
  addedDate = date.today()
  addedDate.strftime('%y-%m-%d')

  todoId = str(uuid.uuid4())
  status = False

  data["addedDate"] = str(addedDate)
  data["todoId"] = todoId
  data["status"] = status
  data["userId"] = userId
  data["dueDate"] = dueDate
  data["completedDate"] = dueDate + 1

  db.collection("Todo").document(todoId).set(data)
  return data


""""""

""""""

from flask import request
from collections.abc import Mapping

UnknownType = object()

class RequiredFieldError(Exception):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

class NotAnOptionError(Exception):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

class TypeConversionError(Exception):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

class Request(object):
    """"""

    def __init__(self, *args, **kwargs):
        """"""

        self.args = dict(request.args)
        self.args.update(kwargs)

        self.body = request.get_json()
        if self.body is None:
            self.body = {}

        self.form = request.form

        super().__init__()

    def get(
        self,
        name,
        default=UnknownType,
        location=None,
        required=False,
        options=None,
    ):
        """"""

        value = UnknownType

        if location == "args" or location is None:
            value = self.args.get(name, default)

        if location == "body" or (location is None and value is UnknownType):
            value = self.body.get(name, default)

        if location == "form" or (location is None and value is UnknownType):
            value = self.form.get(name, default)

        return value

def parse_field(name, handler, req):
    """This function will search for `name` in req and try to parse it using
    `value`. If it is not found, and no default is provided, it will return an
    UnknownType back to `parse_mapping` to be filtered out."""

    if isinstance(handler, Mapping):

        value = req.get(
            name,
            **{
                k: v
                for (k, v) in handler.items()
                if k in ("default", "location", "required", "options")
            },
        )

        if "options" in handler and value not in list(handler["options"]):
            raise NotAnOptionError(
                f"A value you provided, '{value}', is not an option for '{name}' in {str(handler['options'])}."
            )

        if "type" in handler and value is not UnknownType:
            try:
                value = handler["type"](value)
            except Exception as e:
                raise TypeConversionError(
                    f"Attempted to convert value `{value}` - it didn't work using `{str(handler['type'])}`. {str(e)}"
                )

        if (
            "required" in handler
            and handler["required"]
            and value is UnknownType
        ):
            raise RequiredFieldError(f"A required field ({name}) wasn't found.")

        return value

    elif callable(handler):

        value = req.get(name)
        if value is UnknownType:
            return value

        try:
            value = handler(value)
        except Exception as e:
            raise TypeConversionError(
                f"Attempted to convert value `{value}` - it didn't work using `{str(handler)}`. {str(e)}"
            )

        return value

def parse_mapping(mapping, req):
    """"""

    return {
        key: value
        for (key, value) in {
            value["as"]
            if isinstance(value, Mapping) and "as" in value
            else key: parse_field(key, value, req)
            for (key, value) in mapping.items()
        }.items()
        if value is not UnknownType
    }

def parser(*mappings):
    """"""

    def inner(func):
        def request_handler(_=None, *args, **kwargs):
            req = Request(*args, **kwargs)
            args = [parse_mapping(mapping, req) for mapping in mappings]
            if _ is not None:
                args = [_] + args
            return func(*args)

        # for Flask, we need a unique name for routing purposes
        request_handler.__name__ = func.__name__

        return request_handler

    return inner


#! /usr/bin/env python3
# downloadXkcd.py - A script that downloads comic images from xkcd website.

import requests, os, bs4

url = 'https://xkcd.com'

os.makedirs('xkcd', exist_ok=True)

while not url.endswith('#'):

    # Download the page
    print("Downloading page %s..." % url)
    res = requests.get(url)
    res.raise_for_status()

    # use Beautiful to parse the downloaded page
    soup = bs4.BeautifulSoup(res.text, features="html.parser")

    # find the image url
    image_Elem = soup.select('#comic img')

    if image_Elem == []:
        print('Could not find comic image')
    else:
        image_link = image_Elem[0].get('src')

        full_image_link = 'https:' + image_link
        print('Downloading image %s...' % full_image_link)

        try:
            image_res = requests.get(full_image_link)
        except requests.exceptions.MissingSchema:
            image_link = '//imgs.xkcd.com' + image_link
            full_image_link = 'https:' + image_link
            image_res = requests.get(full_image_link)

        #save image to ./xkcd

        imageFile = open(os.path.join('xkcd', os.path.basename(full_image_link)), 'wb')
        for chunk in image_res.iter_content(100000):
            imageFile.write(chunk)
        imageFile.close()

    # Get the Prev button's url.
    prevLink = soup.select('a[rel="prev"]')[0]
    url = 'https://xkcd.com' + prevLink.get('href')

print("Done")


import glob
from astropy.io import ascii
from astropy.table import Table
from astropy.io import fits
from astropy.time import Time
import os
import numpy as np
import matplotlib
matplotlib.use('Qt5Agg')
import matplotlib.pyplot as plt
import pandas as pd

# Create the dataframe to be filled later :

Source_Name_l=[]
BID_l=[]
SID_l=[]
OBS_ID_l=[]
MJD_OBS_l=[]
DATE_OBS_l=[]
exp_l=[]
NH_l=[]
BB_kT_l=[]
min_BBkT_l=[]
max_BBkt_l=[]
BB_Norm_l=[]
min_BBNorm_l=[]
max_BBNorm_l=[]
BB_flux_l=[]
min_BBflux_l=[]
max_BBflux_l=[]
Bol_BBF_l=[]
min_BolBBF_l=[]
max_BolBBF_l=[]
BB2_kT_l=[]
min_2BBkT_l=[]
max_2BBkt_l=[]
BB2_Norm_l=[]
min_2BBNorm_l=[]
max_2BBNorm_l=[]
BB2_flux_l=[]
min_2BBflux_l=[]
max_2BBflux_l=[]
Bol_2BBF_l=[]
min_2BolBBF_l=[]
max_2BolBBF_l=[]
fa_l=[]
min_fa_l=[]
max_fa_l=[]
dbb_kT_l=[]
min_dbbkT_l=[]
max_dbbkT_l=[]
dbb_Norm_l=[]
min_dbbNorm_l=[]
max_dbbNorm_l=[]
dbb_flux_l=[]
min_dbbflux_l=[]
max_dbbflux_l=[]
sBB_kT_l=[]
min_sBBkT_l=[]
max_sBBkt_l=[]
sBB_Norm_l=[]
min_sBBNorm_l=[]
max_sBBNorm_l=[]
sBB_flux_l=[]
min_sBBflux_l=[]
max_sBBflux_l=[]
RStat_l=[]
dof_l=[]

# Enter here the name of the source as in the burster_v3f.dat :
source_name = '4U_1608-522'
bid = input('enter here the burstid of the burst you would like to fit : ')
bid = '3'
mine=input('Enter the minimum energy of the fits :')
mines = ":"+mine
maxe=input('Enter the maximum energy of the fits :')
maxes = maxe+":"

folder = '/home/hea/ownCloud/burst_characterization_v3/'
sfolder = '/home/hea/ownCloud/burst_characterization_v3/scripts/'

#folder = '/Users/tolga/ownCloud/burst_characterization_v3/'
#sfolder = '/Users/tolga/ownCloud/burst_characterization_v3/scripts/'

# Read the persistent state analysis (pre burst tbabs*DISKBB+BBODYRAD fit)
pers_file = folder+source_name+'/pers_results.dat'
pers_data  = pd.read_csv(pers_file)
snh = pers_data['NH']
diskbb_temp = pers_data['disk_kT']
diskbb_norm = pers_data['disk_norm']
sbb_kt=pers_data['bb_kT']
sbb_norm=pers_data['bb_norm']
pers_rstat = pers_data['chi']
pers_dof = pers_data['dof']

sel_pre_burst = np.where(pers_data['BID']==int(bid))
ssnh = snh[sel_pre_burst[0]]
sdiskbb_temp = diskbb_temp[sel_pre_burst[0]]
sdiskbb_norm = diskbb_norm[sel_pre_burst[0]]
ssbb_kt = sbb_kt[sel_pre_burst[0]]
ssbb_norm = sbb_norm[sel_pre_burst[0]]
spers_rstat= pers_rstat[sel_pre_burst[0]]
spers_dof = pers_dof[sel_pre_burst[0]]
print('These are the values I get from persistent state analysis :')
print('NH ='+str(ssnh.values[0]))
print('Disk BB kT = '+str(sdiskbb_temp.values[0]))
print('Disk BB Norm = '+str(sdiskbb_norm.values[0]))
print('Surface BB kT = '+str(ssbb_kt.values[0]))
print('Surface BB Norm = '+str(ssbb_norm.values[0]))
print('Reduced Chi2 of = '+str(spers_rstat.values[0]/spers_dof.values[0]))

print('available fit_methods \n')
print('1=fixed background just BB free \n')

#fit_method = input('Please enter your fit preference : ')
fit_method = '1'
burst_folder=folder+source_name+'/burst'+bid+'/'
bkg_folder = folder+source_name+'/burst'+bid+'/pers_analysis/'
bkgfile = glob.glob(bkg_folder+'*3c50*.pha.pi')
sp_list = np.array(glob.glob(burst_folder+'c*.pha'))
pha_count = len(sp_list)

set_stat("chi2xspecvar")
set_covar_opt("sigma",1.0)
set_conf_opt('numcores', 10)
set_conf_opt("max_rstat",250.0)
set_covar_opt('sigma',1.0)

for i in range(len(sp_list)-1):
        sp_final = sp_list[i]
        print(sp_final)
        sp_hdu = fits.open(str(sp_final))
        print('read src spec: '+str(sp_final))
        mjdobs = sp_hdu[1].header['MJD-OBS']
        date_obsi = sp_hdu[1].header['DATE-OBS']
        exposure = sp_hdu[1].header['EXPOSURE']
        obsid = sp_hdu[1].header['OBS_ID']
        sid = sp_final.split('/')[7].split('_')[0][1:]
        date_obs = str(Time(date_obsi,format='isot', scale='utc'))
        print(date_obs)
        print(obsid)
        object = sp_hdu[1].header['OBJECT']
        Source_Name_l.append(object)
        BID_l.append(bid)
        SID_l.append(sid)
        OBS_ID_l.append(obsid)
        MJD_OBS_l.append(mjdobs)
        DATE_OBS_l.append(date_obs)
        exp_l.append(exposure)
        NH_l.append(ssnh.values[0])

        if exposure == 0.0 :
                print('this spectrum does not have any exposure')
                BB_kT_l.append(0)
                min_BBkT_l.append(0)
                max_BBkt_l.append(0)
                BB_Norm_l.append(0)
                min_BBNorm_l.append(0)
                max_BBNorm_l.append(0)
                BB_flux_l.append(0)
                min_BBflux_l.append(0)
                max_BBflux_l.append(0)
                Bol_BBF_l.append(0)
                min_BolBBF_l.append(0)
                max_BolBBF_l.append(0)
                BB2_kT_l.append(0)
                min_2BBkT_l.append(0)
                max_2BBkt_l.append(0)
                BB2_Norm_l.append(0)
                min_2BBNorm_l.append(0)
                max_2BBNorm_l.append(0)
                BB2_flux_l.append(0)
                min_2BBflux_l.append(0)
                max_2BBflux_l.append(0)
                Bol_2BBF_l.append(0)
                min_2BolBBF_l.append(0)
                max_2BolBBF_l.append(0)
                fa_l.append(0)
                min_fa_l.append(0)
                max_fa_l.append(0)
                dbb_kT_l.append(0)
                min_dbbkT_l.append(0)
                max_dbbkT_l.append(0)
                dbb_Norm_l.append(0)
                min_dbbNorm_l.append(0)
                max_dbbNorm_l.append(0)
                dbb_flux_l.append(0)
                min_dbbflux_l.append(0)
                max_dbbflux_l.append(0)
                sBB_kT_l.append(0)
                min_sBBkT_l.append(0)
                max_sBBkt_l.append(0)
                sBB_Norm_l.append(0)
                min_sBBNorm_l.append(0)
                max_sBBNorm_l.append(0)
                sBB_flux_l.append(0)
                min_sBBflux_l.append(0)
                max_sBBflux_l.append(0)
                RStat_l.append(0)
                dof_l.append(0)
                print('Finished:')
                print(sp_final)
                continue
        # print(date_obsi)
        load_pha(1, str(sp_final),use_errors=True)
        load_arf(1, sfolder+'nicer-consim135p-teamonly-array52.arf')
        load_rmf(1, sfolder+'nicer-rmf6s-teamonly-array52.rmf')
        print('Ignoring : '+mines+' '+maxes)
        ignore(mines+','+maxes)
        print('This script only subtracts ni3c50 background')
        load_bkg(1, bkgfile[0],use_errors=True)
        subtract()
        print('Grouping the data to have at least 50 counts per channel')
        group_counts(1, 50)

        # first let's do a global source definition :
        set_source(xstbabs.tb*(xsdiskbb.dbb+xsbbodyrad.sbb))
        tb.nH=ssnh.values[0]
        dbb.Tin = sdiskbb_temp.values[0]
        dbb.norm = sdiskbb_norm.values[0]
        sbb.kT = ssbb_kt.values[0]
        sbb.norm = ssbb_norm.values[0]
        freeze(tb.nH)
        freeze(dbb.Tin)
        freeze(dbb.norm)
        freeze(sbb.kT)
        freeze(sbb.norm)
        #fit()
        initial_rstat = sum(calc_chisqr())/len(calc_chisqr())
        if (initial_rstat < (spers_rstat.values[0]+3.50)/spers_dof.values[0]):
                print('Current chi2 : '+str(initial_rstat))
                print('Persistent chi2 : '+str(spers_rstat.values[0]/spers_dof.values[0]))
                print('Deviation from the persistent emission is small I will thaw the parameters and refit the data to save the best fit values:')
                thaw(dbb.Tin)
                thaw(dbb.norm)
                thaw(sbb.kT)
                thaw(sbb.norm)
                fit()
                if get_fit_results().dof <= 0.0:
                        print('The degree of freedom is very small we need to skip this spectrum:')
                        dbb_kT_l.append(0)
                        min_dbbkT_l.append(0)
                        max_dbbkT_l.append(0)
                        dbb_Norm_l.append(0)
                        min_dbbNorm_l.append(0)
                        max_dbbNorm_l.append(0)
                        dbb_flux_l.append(0)
                        min_dbbflux_l.append(0)
                        max_dbbflux_l.append(0)
                        sBB_kT_l.append(0)
                        min_sBBkT_l.append(0)
                        max_sBBkt_l.append(0)
                        sBB_Norm_l.append(0)
                        min_sBBNorm_l.append(0)
                        max_sBBNorm_l.append(0)
                        sBB_flux_l.append(0)
                        min_sBBflux_l.append(0)
                        max_sBBflux_l.append(0)
                        BB_kT_l.append(0)
                        min_BBkT_l.append(0)
                        max_BBkt_l.append(0)
                        BB_Norm_l.append(0)
                        min_BBNorm_l.append(0)
                        max_BBNorm_l.append(0)
                        BB_flux_l.append(0)
                        min_BBflux_l.append(0)
                        max_BBflux_l.append(0)
                        Bol_BBF_l.append(0)
                        min_BolBBF_l.append(0)
                        max_BolBBF_l.append(0)
                        BB2_kT_l.append(0)
                        min_2BBkT_l.append(0)
                        max_2BBkt_l.append(0)
                        BB2_Norm_l.append(0)
                        min_2BBNorm_l.append(0)
                        max_2BBNorm_l.append(0)
                        BB2_flux_l.append(0)
                        min_2BBflux_l.append(0)
                        max_2BBflux_l.append(0)
                        Bol_2BBF_l.append(0)
                        min_2BolBBF_l.append(0)
                        max_2BolBBF_l.append(0)
                        fa_l.append(0)
                        min_fa_l.append(0)
                        max_fa_l.append(0)
                        RStat_l.append(0)
                        dof_l.append(get_fit_results().dof)
                        print('Finished:')
                        print(sp_final)
                        continue
                covar()
                chi = get_fit_results().statval
                dof = get_fit_results().dof
                parvals = np.array(get_covar_results().parvals)
                parnames = np.array(get_covar_results().parnames)
                parmins = np.array(get_covar_results().parmins)
                parmaxes = np.array(get_covar_results().parmaxes)
                covar()
                cparmins = np.array(get_covar_results().parmins)
                cparmaxes = np.array(get_covar_results().parmaxes)

                if (None in cparmins) == True or (None in cparmaxes) == True or (0 in cparmaxes) == True or (0 in cparmins) == True:

                        print('It seems like you have unconstrained parameters in the continuum model therefore we cant calculate the errors')
                        print('No flux will be reported')
                        dbb_flux_l.append(0)
                        max_dbbflux_l.append(0)
                        min_dbbflux_l.append(0)
                        sBB_flux_l.append(0)
                        max_sBBflux_l.append(0)
                        min_sBBflux_l.append(0)

                        print('Parameter Errors will be written as 0')
                        dbb_kT_l.append(get_fit_results().parvals[0])
                        min_dbbkT_l.append(0)
                        max_dbbkT_l.append(0)
                        dbb_Norm_l.append(get_fit_results().parvals[1])
                        min_dbbNorm_l.append(0)
                        max_dbbNorm_l.append(0)
                        sBB_kT_l.append(get_fit_results().parvals[2])
                        min_sBBkT_l.append(0)
                        max_sBBkt_l.append(0)
                        sBB_Norm_l.append(get_fit_results().parvals[3])
                        min_sBBNorm_l.append(0)
                        max_sBBNorm_l.append(0)

                        #elif ((None in cparmins) == False and (None in cparmaxes) == False) or ((0 in cparmaxes) == False and (0 in cparmins) == False):
                else:
                        print('The parameters are constrained well calculating errors')
                        #matrix = get_covar_results().extra_output
                        #is_all_zero = np. all((matrix > 0))
                        #if is_all_zero:
                        sample2=sample_flux(dbb,float(mine),float(maxe), num=100, correlated=True,confidence=68)
                        dbb_flux_l.append(sample2[1][0])
                        max_dbbflux_l.append(sample2[1][1]-sample2[1][0])
                        min_dbbflux_l.append(sample2[1][0]-sample2[1][2])
                        sample3=sample_flux(sbb,float(mine),float(maxe), num=100, correlated=True,confidence=68)
                        sBB_flux_l.append(sample3[1][0])
                        max_sBBflux_l.append(sample3[1][1]-sample3[1][0])
                        min_sBBflux_l.append(sample3[1][0]-sample3[1][2])
                        # Parameter errors will be written as they are :
                        dbb_kT_l.append(get_covar_results().parvals[0])
                        min_dbbkT_l.append(get_covar_results().parmins[0])
                        max_dbbkT_l.append(get_covar_results().parmaxes[0])
                        dbb_Norm_l.append(get_covar_results().parvals[1])
                        min_dbbNorm_l.append(get_covar_results().parmins[1])
                        max_dbbNorm_l.append(get_covar_results().parmaxes[1])
                        sBB_kT_l.append(get_covar_results().parvals[2])
                        min_sBBkT_l.append(get_covar_results().parmins[2])
                        max_sBBkt_l.append(get_covar_results().parmaxes[2])
                        sBB_Norm_l.append(get_covar_results().parvals[3])
                        min_sBBNorm_l.append(get_covar_results().parmins[3])
                        max_sBBNorm_l.append(get_covar_results().parmaxes[3])

                BB_kT_l.append(0)
                min_BBkT_l.append(0)
                max_BBkt_l.append(0)
                BB_Norm_l.append(0)
                min_BBNorm_l.append(0)
                max_BBNorm_l.append(0)
                BB_flux_l.append(0)
                min_BBflux_l.append(0)
                max_BBflux_l.append(0)
                Bol_BBF_l.append(0)
                min_BolBBF_l.append(0)
                max_BolBBF_l.append(0)
                BB2_kT_l.append(0)
                min_2BBkT_l.append(0)
                max_2BBkt_l.append(0)
                BB2_Norm_l.append(0)
                min_2BBNorm_l.append(0)
                max_2BBNorm_l.append(0)
                BB2_flux_l.append(0)
                max_2BBflux_l.append(0)
                min_2BBflux_l.append(0)
                Bol_2BBF_l.append(0)
                min_2BolBBF_l.append(0)
                max_2BolBBF_l.append(0)
                fa_l.append(0)
                min_fa_l.append(0)
                max_fa_l.append(0)

                #dbb_kT_l.append(0)
                #min_dbbkT_l.append(0)
                #max_dbbkT_l.append(0)
                #dbb_Norm_l.append(0)
                #min_dbbNorm_l.append(0)
                #max_dbbNorm_l.append(0)
                #dbb_flux_l.append(0)
                #min_dbbflux_l.append(0)
                #max_dbbflux_l.append(0)
                #sBB_kT_l.append(0)
                #min_sBBkT_l.append(0)
                #max_sBBkt_l.append(0)
                #sBB_Norm_l.append(0)
                #min_sBBNorm_l.append(0)
                #max_sBBNorm_l.append(0)
                #sBB_flux_l.append(0)
                #min_sBBflux_l.append(0)
                #max_sBBflux_l.append(0)

                RStat_l.append(chi)
                dof_l.append(dof)

                plot_data()
                x_max=max(get_data_plot().x)+max(get_data_plot().x)*0.05
                x_min = np.abs(min(get_data_plot().x)-min(get_data_plot().x)*0.05)
                ymax = max(get_data_plot().y)+max(get_data_plot().y)*0.2
                ymin = np.abs(min(get_data_plot().y)-min(get_data_plot().y)*0.05)

                plot_fit_delchi(1,clearwindow=True, color='Black')
                fig=plt.gcf()
                ax1,ax2=fig.axes
                ax1.set_title(source_name+' BID:'+bid+' MJD:'+str(mjdobs)+' SID:'+sid)
                ax1.set_yscale('log')
                ax1.set_xscale('log')
                ax2.set_xscale('log')
                ax2.set_xlabel('Energy [keV]', fontsize=14)
                ax1.set_ylabel('Counts/sec/keV', fontsize=14)
                ax2.set_ylabel('Sigma', fontsize=14)
                ax1.set_xlim(x_min,x_max)
                ax2.set_xlim(x_min,x_max)
                plt.savefig(burst_folder+sid+'_b'+bid+'_'+fit_method+'_full_'+mine+'_'+maxe+'.pdf',orientation='landscape', papertype='a4')
                plt.savefig(burst_folder+sid+'_b'+bid+'_'+fit_method+'_full_'+mine+'_'+maxe+'.png',orientation='landscape', papertype='a4')
                plot_fit(1,clearwindow=True,xlog=True,ylog=True, color='Black')
                plot_model_component("tb*dbb", replot=False, overplot=True, color='Green')
                plot_model_component("tb*sbb", replot=False, overplot=True, color='Red')
                plt.title(source_name+' BID:'+bid+' MJD:'+str(mjdobs)+' SID:'+sid)
                plt.xlabel('Energy [keV]', fontsize=14)
                plt.ylabel('Counts/sec/keV', fontsize=14)
                plt.xlim(x_min,x_max)
                plt.ylim(ymin,ymax)
                plt.savefig(burst_folder+sid+'_b'+bid+'_'+fit_method+'_full_comp_'+mine+'_'+maxe+'.pdf',orientation='landscape', papertype='a4')
                plt.savefig(burst_folder+sid+'_b'+bid+'_'+fit_method+'_full_comp_'+mine+'_'+maxe+'.png',orientation='landscape', papertype='a4')
                print('We are done with just fitting the continuum, Skipping to the next spectrum')
                continue
        else:
                print('Current chi2 : '+str(initial_rstat))
                print('Persistent chi2 : '+str(spers_rstat.values[0]/spers_dof.values[0]))
                print('Simple Persistent Emission Does Not Fit the data we need to add components')

                print('This is 1=fixed background just BB free')

                set_source(xstbabs.tb*(xsbbodyrad.bb+xsdiskbb.dbb+xsbbodyrad.sbb))
                tb.nH=ssnh.values[0]
                dbb.Tin = sdiskbb_temp.values[0]
                dbb.norm = sdiskbb_norm.values[0]
                sbb.kT = ssbb_kt.values[0]
                sbb.norm = ssbb_norm.values[0]
                freeze(tb.nH)
                freeze(dbb.Tin)
                freeze(dbb.norm)
                freeze(sbb.kT)
                freeze(sbb.norm)
                dbb_kT_l.append(diskbb_temp.values[0])
                min_dbbkT_l.append(0)
                max_dbbkT_l.append(0)
                dbb_Norm_l.append(diskbb_norm.values[0])
                min_dbbNorm_l.append(0)
                max_dbbNorm_l.append(0)
                dbb_flux_l.append(0)
                min_dbbflux_l.append(0)
                max_dbbflux_l.append(0)
                sBB_kT_l.append(ssbb_kt.values[0])
                min_sBBkT_l.append(0)
                max_sBBkt_l.append(0)
                sBB_Norm_l.append(ssbb_norm.values[0])
                min_sBBNorm_l.append(0)
                max_sBBNorm_l.append(0)
                sBB_flux_l.append(0)
                min_sBBflux_l.append(0)
                max_sBBflux_l.append(0)
                fa_l.append(0)
                min_fa_l.append(0)
                max_fa_l.append(0)
                BB2_kT_l.append(0)
                min_2BBkT_l.append(0)
                max_2BBkt_l.append(0)
                BB2_Norm_l.append(0)
                min_2BBNorm_l.append(0)
                max_2BBNorm_l.append(0)
                Bol_2BBF_l.append(0)
                max_2BolBBF_l.append(0)
                min_2BolBBF_l.append(0)
                BB2_flux_l.append(0)
                max_2BBflux_l.append(0)
                min_2BBflux_l.append(0)
                bb.kt=0.5
                set_xsabund('wilm')
                bb.norm = 180.3
                set_method("moncar")
                fit()
                set_method("levmar")
                fit()
                chi = get_fit_results().statval
                dof = get_fit_results().dof
                if get_fit_results().dof <= 0.0:
                        print('The degree of freedom is very small we need to skip this spectrum:')
                        BB_kT_l.append(0)
                        min_BBkT_l.append(0)
                        max_BBkt_l.append(0)
                        BB_Norm_l.append(0)
                        min_BBNorm_l.append(0)
                        max_BBNorm_l.append(0)
                        BB_flux_l.append(0)
                        min_BBflux_l.append(0)
                        max_BBflux_l.append(0)
                        Bol_BBF_l.append(0)
                        min_BolBBF_l.append(0)
                        max_BolBBF_l.append(0)
                        RStat_l.append(0)
                        dof_l.append(get_fit_results().dof)
                        print('Finished:')
                        print(sp_final)
                        continue
                fit()
                covar()
                chi = get_fit_results().statval
                dof = get_fit_results().dof
                RStat_l.append(chi)
                dof_l.append(dof)
                parvals = np.array(get_covar_results().parvals)
                parnames = np.array(get_covar_results().parnames)
                parmins = np.array(get_covar_results().parmins)
                parmaxes = np.array(get_covar_results().parmaxes)

                # now the model unabsorbed fluxes :
                covar()
                cparmins = np.array(get_covar_results().parmins)
                cparmaxes = np.array(get_covar_results().parmaxes)
                if (None in cparmins) == True or (None in cparmaxes) == True or (0 in cparmaxes) == True or (0 in cparmins) == True:

                        print('It seems like you have unconstrained parameters we cant calculate errors')
                        print('No flux will be reported')
                        BB_flux_l.append(0)
                        max_BBflux_l.append(0)
                        min_BBflux_l.append(0)
                        Bol_BBF_l.append(0)
                        min_BolBBF_l.append(0)
                        max_BolBBF_l.append(0)
                        # Parameter Errors will be written as 0:
                        BB_kT_l.append(get_covar_results().parvals[0])
                        min_BBkT_l.append(0)
                        max_BBkt_l.append(0)
                        BB_Norm_l.append(get_covar_results().parvals[1])
                        min_BBNorm_l.append(0)
                        max_BBNorm_l.append(0)

                else:
                        #elif ((None in cparmins) == False and (None in cparmaxes) == False) or ((0 in cparmaxes) == False and (0 in cparmins) == False):
                        print('The parameters are constrained well calculating errors')
                        # matrix = get_covar_results().extra_output
                        # is_all_zero = np. all((matrix > 0))
                        # if is_all_zero:
                        sample1=sample_flux(bb,float(mine),float(maxe), num=100, correlated=True,confidence=68)
                        BB_flux_l.append(sample1[1][0])
                        max_BBflux_l.append(sample1[1][1]-sample1[1][0])
                        min_BBflux_l.append(sample1[1][0]-sample1[1][2])
                        print('Parameter errors will be written as they are')
                        BB_kT_l.append(get_covar_results().parvals[0])
                        min_BBkT_l.append(get_covar_results().parmins[0])
                        max_BBkt_l.append(get_covar_results().parmaxes[0])
                        BB_Norm_l.append(get_covar_results().parvals[1])
                        min_BBNorm_l.append(get_covar_results().parmins[1])
                        max_BBNorm_l.append(get_covar_results().parmaxes[1])

                        # Now the Bolometric Fluxes :
                        sample_bol=sample_flux(bb,0.01,200.0, num=100, correlated=True,confidence=68)
                        Bol_BBF_l.append(sample_bol[1][0])
                        max_BolBBF_l.append(sample_bol[1][1]-sample_bol[1][0])
                        min_BolBBF_l.append(sample_bol[1][0]-sample_bol[1][2])

                        #Bol_BBF_l.append(1.076e-11*((get_covar_results().parvals[0])**4.0)*get_covar_results().parvals[1])
                        #max_BolBBF_l.append(1.076e-11*((get_covar_results().parvals[0]+get_covar_results().parmaxes[0])**4.0)*(get_covar_results().parvals[1]+get_covar_results().parmaxes[1]))
                        #min_BolBBF_l.append(1.076e-11*((get_covar_results().parvals[0]-get_covar_results().parmins[0])**4.0)*(get_covar_results().parvals[1]-get_covar_results().parmins[1]))
                        #RStat_l.append(chi)
                        #dof_l.append(dof)
                        #else:
                        #        print('It seems like you have unconstrained parameters we cant calculate errors')
                        #        print('No flux will be reported')
                        #        BB_flux_l.append(0)
                        #        max_BBflux_l.append(0)
                        #        min_BBflux_l.append(0)
                        #        Bol_BBF_l.append(0)
                        #        min_BolBBF_l.append(0)
                        #        max_BolBBF_l.append(0)
                        #        # Parameter Errors will be written as 0:
                        #        BB_kT_l.append(get_covar_results().parvals[0])
                        #        min_BBkT_l.append(0)
                        #        max_BBkt_l.append(0)
                        #        BB_Norm_l.append(get_covar_results().parvals[1])
                        #        min_BBNorm_l.append(0)
                        #        max_BBNorm_l.append(0)

                plot_data()
                x_max=max(get_data_plot().x)+max(get_data_plot().x)*0.1
                x_min = np.abs(min(get_data_plot().x)-min(get_data_plot().x)*0.1)
                ymax = max(get_data_plot().y)+max(get_data_plot().y)*0.2
                ymin = np.abs(min(get_data_plot().y)-min(get_data_plot().y)*0.05)

                plot_fit_delchi(1,clearwindow=True, color='Black')
                fig=plt.gcf()
                ax1,ax2=fig.axes
                ax1.set_title(source_name+' BID:'+bid+' MJD:'+str(mjdobs)+' SID:'+sid)
                ax1.set_yscale('log')
                ax1.set_xscale('log')
                ax2.set_xscale('log')
                ax2.set_xlabel('Energy [keV]', fontsize=14)
                ax1.set_ylabel('Counts/sec/keV', fontsize=14)
                ax2.set_ylabel('Sigma', fontsize=14)
                ax1.set_xlim(x_min,x_max)
                ax2.set_xlim(x_min,x_max)
                plt.savefig(burst_folder+sid+'_b'+bid+'_'+fit_method+'_full_'+mine+'_'+maxe+'.pdf',orientation='landscape', papertype='a4')

                plt.savefig(burst_folder+sid+'_b'+bid+'_'+fit_method+'_full_'+mine+'_'+maxe+'.png',orientation='landscape', papertype='a4')

                plot_fit(1,clearwindow=True,xlog=True,ylog=True, color='Black')

                plot_model_component("tb*dbb", replot=False, overplot=True, color='Green')
                plot_model_component("tb*sbb", replot=False, overplot=True, color='Red')
                plot_model_component("tb*bb", replot=False, overplot=True, color='Black')
                plt.title(source_name+' BID:'+bid+' MJD:'+str(mjdobs)+' SID:'+sid)
                plt.xlabel('Energy [keV]', fontsize=14)
                plt.ylabel('Counts/sec/keV', fontsize=14)
                plt.xlim(x_min,x_max)
                plt.ylim(ymin,ymax)
                plt.savefig(burst_folder+sid+'_b'+bid+'_'+fit_method+'_full_comp_'+mine+'_'+maxe+'.pdf',orientation='landscape', papertype='a4')
                plt.savefig(burst_folder+sid+'_b'+bid+'_'+fit_method+'_full_comp_'+mine+'_'+maxe+'.png',orientation='landscape', papertype='a4')

items = {'Source_Name' : Source_Name_l, 'BID' : BID_l, 'SID': SID_l,'OBS_ID' : OBS_ID_l,'MJD-OBS' : MJD_OBS_l,'DATE-OBS' : OBS_ID_l,'exp' :exp_l,'NH' : NH_l,
'BB_kT' : BB_kT_l,'min_BBkT' : min_BBkT_l,'max_BBkt' : max_BBkt_l,'BB_Norm' : BB_Norm_l,'min_BBNorm' : min_BBNorm_l,'max_BBNorm' : max_BBNorm_l,
'BB_flux' : BB_flux_l,'min_BBflux' : min_BBflux_l,
'max_BBflux' : max_BBflux_l,'Bol_BBF' : Bol_BBF_l,'min_BolBBF' : min_BolBBF_l,'max_BolBBF' : max_BolBBF_l,'2BB_kT' : BB2_kT_l,
'min_2BBkT' : min_2BBkT_l,'max_2BBkt' : max_2BBkt_l,'2BB_Norm' : BB2_Norm_l,
'min_2BBNorm' : min_2BBNorm_l,'max_2BBNorm' : max_2BBNorm_l,'2BB_flux' : BB2_flux_l,'min_2BBflux' : min_2BBflux_l,'max_2BBflux' : max_2BBflux_l,'Bol_2BBF' : Bol_2BBF_l,'min_2BolBBF' : min_2BolBBF_l,
'max_2BolBBF' : max_2BolBBF_l,'fa' : fa_l,'min_fa' : min_fa_l,'max_fa' : max_fa_l,'dbb_kT' : dbb_kT_l,'min_dbbkT' : min_dbbkT_l,'max_dbbkT' : max_dbbkT_l,'dbb_Norm' : dbb_Norm_l,'min_dbbNorm' : min_dbbNorm_l,
'max_dbbNorm' : max_dbbNorm_l,'dbb_flux' : dbb_flux_l,'min_dbbflux' : min_dbbflux_l,'max_dbbflux' : max_dbbflux_l,
'sBB_kT' : sBB_kT_l,'min_sBBkT' : min_sBBkT_l,'max_sBBkt' : max_sBBkt_l,'sBB_Norm' : sBB_Norm_l,'min_sBBNorm' : min_sBBNorm_l,
'max_sBBNorm' : max_sBBNorm_l,'sBB_flux' : sBB_flux_l,
'min_sBBflux' : min_sBBflux_l,'max_sBBflux' : max_sBBflux_l,
'RStat' : RStat_l,'dof' : dof_l}

#print(len(Source_Name_l))
print('Sourcename:',len(Source_Name_l))
print('BID:',len(BID_l))
print('SID:',len(SID_l))
print('OBSID:',len(OBS_ID_l))
print('MJD:',len(MJD_OBS_l))
print('exp:',len(exp_l))
print('NH:',len(NH_l))
print('BB_kT:',len(BB_kT_l))
print('min_BBkT:',len(min_BBkT_l))
print('max_BBkt:',len(max_BBkt_l))
print('BB_Norm:',len(BB_Norm_l))
print('min_BBNorm:',len(min_BBNorm_l))
print('max_BBNorm:',len(max_BBNorm_l))
print('BB_flux:',len(BB_flux_l))
print('min_BBflux:',len(min_BBflux_l))
print('max_BBflux:',len(max_BBflux_l))
print('Bol_BBF:',len(Bol_BBF_l))
print('min_BolBBF:',len(min_BolBBF_l))
print('max_BolBBF:',len(max_BolBBF_l))
print('BB2_kT:',len(BB2_kT_l))
print('min_2BBkT:',len(min_2BBkT_l))
print('max_2BBkt:',len(max_2BBkt_l))
print('BB2_Norm:',len(BB2_Norm_l))
print('min_2BBNorm:',len(min_2BBNorm_l))
print('max_2BBNorm:',len(max_2BBNorm_l))
print('BB2_flux:',len(BB2_flux_l))
print('min_2BBflux:',len(min_2BBflux_l))
print('max_2BBflux:',len(max_2BBflux_l))
print('Bol_2BBF:',len(Bol_2BBF_l))
print('min_2BolBBF:',len(min_2BolBBF_l))
print('max_2BolBBF:',len(max_2BolBBF_l))
print('fa:',len(fa_l))
print('min_fa:',len(min_fa_l))
print('max_fa:',len(max_fa_l))
print('dbb_kT:',len(dbb_kT_l))
print('min_dbbkT:',len(min_dbbkT_l))
print('max_dbbkT:',len(max_dbbkT_l))
print('dbb_Norm:',len(dbb_Norm_l))
print('min_dbbNorm:',len(min_dbbNorm_l))
print('max_dbbNorm:',len(max_dbbNorm_l))
print('dbb_flux:',len(dbb_flux_l))
print('min_dbbflux:',len(min_dbbflux_l))
print('max_dbbflux:',len(max_dbbflux_l))
print('sBB_kT:',len(sBB_kT_l))
print('min_sBBkT:',len(min_sBBkT_l))
print('max_sBBkt:',len(max_sBBkt_l))
print('sBB_Norm:',len(sBB_Norm_l))
print('min_sBBNorm:',len(min_sBBNorm_l))
print('max_sBBNorm:',len(max_sBBNorm_l))
print('sBB_flux:',len(sBB_flux_l))
print('min_sBBflux:',len(min_sBBflux_l))
print('max_sBBflux:',len(max_sBBflux_l))
print('Rstat:',len(RStat_l))
print('Dof:',len(dof_l))
#for i in check_list:
#print(i,str(len(i)))

df=pd.DataFrame.from_dict(items)
df.transpose()
#df.to_excel(burst_folder+source_name+'_sp_res_'+bid+'_'+fit_method+'.xlsx')
#df.to_csv(burst_folder+source_name+'_sp_res_'+bid+fit_method+'.csv')

sorted_df = df.sort_values(by='MJD-OBS')
sorted_df.to_excel(burst_folder+source_name+'_sp_res_'+bid+'_'+fit_method+'_'+mine+'_'+maxe+'.xlsx')
sorted_df.to_csv(burst_folder+source_name+'_sp_res_'+bid+fit_method+'_'+mine+'_'+maxe+'.csv')


import os
import shutil
import time
import random
import logging
from werkzeug import secure_filename
from flask import after_this_request, render_template, current_app, request, send_from_directory

import logging
from .common.base import BaseView

JOURNAL_DIR = 'tmp/journal/'

class HelperView(BaseView):
    def get(self):
        return render_template('helper.html')

    def post(self):
        file = request.files['journal-files']
        filename = secure_filename(file.filename)

        time_str = time.strftime("%Y_%m_%d_%H_%M_%S_", time.localtime(time.time()))
        random_str = str(random.randint(100000, 999999))
        folder = JOURNAL_DIR + time_str + random_str
        os.mkdir(folder)

        @after_this_request
        def remove_journal(response):
            shutil.rmtree(folder)
            return response

        try:
            file.save(os.path.join(folder, filename))
        except Exception:
            return '<script type="text/javascript">window.parent.showError();</script>'
        else:
            os.system('journalctl -D %s > %s/journal.log' % (folder, folder))

            path = os.path.join(os.getcwd(), folder)
            return send_from_directory(path, 'journal.log', as_attachment=True)


# -*- coding: utf-8 -*-
import argparse
from utils import AttrDict

def calc_params(cfg):
    # embedding num
    embedding_num = cfg.tag_dim * cfg.tag_num + cfg.lan_dim * cfg.lan_num + cfg.cn_tag_num * cfg.cn_tag_dim

    # forward num
    forward_input = cfg.user_dim + (cfg.tag_dim + cfg.lan_dim + cfg.cn_tag_dim + cfg.song_dim + cfg.cross_dim) * 3
    forward1 = forward_input * 200 + 200
    forward2 = 200 * 80 + 80
    forward3 = 80 + 1
    forward_num = forward1 + forward2 + forward3
    # attention num
    attention_input = 3 * (cfg.song_dim+cfg.tag_dim+cfg.lan_dim+cfg.cn_tag_dim+cfg.cross_dim)

    attention1 = (attention_input * 64 + 64) * cfg.hist_length
    attention2 = (64 * 32 + 32) * cfg.hist_length
    attention3 = (32 + 1) * cfg.hist_length
    attention_num = attention1 + attention2 + attention3

    # total num
    total_num = embedding_num + forward_num + attention_num

    print("embedding part: {:d}, forward part: {:d}, attention part: {:d}, total: {:d}"
          .format(embedding_num, forward_num, attention_num, total_num))
    return total_num

if __name__ == "__main__":

    config = AttrDict({
        'user_dim': 250,
        'song_dim': 137,
        'cross_dim': 15,
        'hist_length': 20,
        'tag_dim': 10,
        'lan_dim': 10,
        'cn_tag_dim': 10,
        'tag_num': 18,
        'lan_num': 8,
        'cn_tag_num': 26
    })

    calc_params(config)


"""
Name: Anagrams.py

Author: Tenzin Phuljung

"""

def isAnagram(str1, str2):
    """
    Takes in two string parameters and returns a boolean based on whether they are anagrams of each other.
    :param str1: str
    :param str2: str
    :return: bool

    >>> isAnagram("able", "bale")
    True
    >>> isAnagram("mad", "dam")
    True
    >>> isAnagram("made", "mades")
    False
    """
    sorted_str1 = "".join(sorted(str1))
    sorted_str2 = "".join(sorted(str2))

    if sorted_str1 == sorted_str2:
        return True
    return False

def word_to_count(lst):
    """
    Takes in a list and returns a dictionary with element to count ratio.
    :param lst: list
    :return: dict

    """
    database = {}
    for elem in lst:
        if elem not in database:
            database[elem] = 1
        else:
            database[elem] += 1
    return database

def anagrams_to_count(dict):
    """
    Takes in sorted anagrams to its count as a dictionary. Then it takes all the values in a list and creates a word_to_count dictionary for that list. Then the keys are converted to words instead of numbers so it is easily readable.
    :param dict: dict
    """
    values = list(dict.values())
    anagrams_to_length = word_to_count(values)
    number_to_tuple_names = {
        1: "Single",
        2: "Pair",
        3: "Triples",
        4: "Quadruples",
        5: "Quintuple pentadruple",
        6: "Sextuple hexatruple",
        7: "Septuple",
        8: "Octuple",
        9: "Nonuple",
        10: "Decuple",
        11: "Undecuple hendecuple",
        12: "duodecuple",
        13: "tredecuple"
    }
    for key, value in anagrams_to_length.items():
        print("{0}: {1}".format(number_to_tuple_names[key], value))

def display_largest_anagrams(dict, lst):
    """
    Takes in a dictionary and a list. The dictionary will contain sorted anagram words to its count. The list will contain the default words from the file. After getting the highest anagram tuple, it will then put all the largest anagrams together. Then it checks all the words in the largest anagrams list with the words list.
    :param dict: dict
    :param lst: list
    """
    all_largest_anagrams = []
    values = list(dict.values())
    anagrams_to_length = word_to_count(values)
    max_anagram = list(anagrams_to_length.keys())[-1]
    for key, value in dict.items():
        if value == max_anagram:
            all_largest_anagrams.append(key)

    final_largest_anagrams = []
    for ana in all_largest_anagrams:
        temp = []
        for word in lst:
            if isAnagram(ana, word):
                temp.append(word)
        final_largest_anagrams.append(temp)
    print("Largest Anagrams: ", final_largest_anagrams)

def main():
    """
    Main Game Logic
    """
    file_name = input("Please enter the file name: ")
    my_file = open(file_name, "r")
    content = my_file.read()
    my_file.close()

    words = content.split("\n")
    sorted_words = []
    for word in words:
        temp = "".join(sorted(word))
        sorted_words.append(temp)

    sorted_anagrams = sorted(sorted_words)
    sorted_anagrams_to_occurence = word_to_count(sorted_anagrams[1:])
    display_largest_anagrams(sorted_anagrams_to_occurence, words)

if __name__ == '__main__':
    import doctest

    doctest.testmod()
    main()


import torch.utils.model_zoo as model_zoo
import torch.nn as nn
import torch.nn.functional as F
import torch
import time
model_urls = {'alexnet': 'https://download.pytorch.org/models/alexnet-owt-4df8aa71.pth'}

class DenseSiameseRPN(nn.Module):
    def __init__(self):
        super(DenseSiameseRPN,self).__init__()
        self.features = RDN()

        self.k = 5
        self.s = 4
        self.conv1 = nn.Conv2d(256, 2*self.k*256, kernel_size=3)
        self.relu1 = nn.ReLU(inplace=True)
        self.conv2 = nn.Conv2d(256, 4*self.k*256, kernel_size=3)
        self.relu2 = nn.ReLU(inplace=True)
        self.conv3 = nn.Conv2d(256, 256, kernel_size=3)
        self.relu3 = nn.ReLU(inplace=True)
        self.conv4 = nn.Conv2d(256, 256, kernel_size=3)
        self.relu4 = nn.ReLU(inplace=True)

        self.cconv = nn.Conv2d(256, 2* self.k, kernel_size = 4, bias = False)
        self.rconv = nn.Conv2d(256, 4* self.k, kernel_size = 4, bias = False)

    def forward(self, template, detection):
            """
            把template的类别,坐标的特征作为检测cconv和rconv的检测器
            把ckernel, rkernel转换到cconv, rconv
            """
            template = self.features(template)
            detection = self.features(detection)

            ckernal = self.conv1(template)
            ckernal = ckernal.view(2* self.k, 256, 7, 7)
            cinput  = self.conv3(detection)

            rkernal = self.conv2(template)
            rkernal = rkernal.view(4* self.k, 256, 7, 7)
            rinput  = self.conv4(detection)

            coutput = F.conv2d(cinput, ckernal)
            routput = F.conv2d(rinput, rkernal)

            coutput = coutput.squeeze().permute(1,2,0).reshape(-1, 2)
            routput = routput.squeeze().permute(1,2,0).reshape(-1, 4)
            return coutput, routput

    def resume(self, weight):
        checkpoint = torch.load(weight)
        self.load_state_dict(checkpoint)
        print('Resume checkpoint')

class RDN(nn.Module):
    def __init__(self):
        super(RDN,self).__init__()
        self.conv1 = nn.Conv2d(3, 72, kernel_size=7, stride=2, padding=0, bias=False)

        self.dense_block1 = DenseBlock(72,36,2)
        self.transition1 = transitionlayer(self.dense_block1.out_channels,36)
        self.dense_block2 = DenseBlock(36,36,4)
        self.transition2 = transitionlayer(self.dense_block2.out_channels,36)
        self.dense_block3 = DenseBlock(36,36,6)
        self.dense_block4 = DenseBlock_b(in_channels=252,kernel_size=7)
    def forward(self,x):
        x = self.conv1(x)

        x = self.dense_block1(x)
        x = self.transition1(x)

        x = self.dense_block2(x)
        x = self.transition2(x)

        x = self.dense_block3(x)
        x = self.dense_block4(x)
        return x

class DenseBlock(nn.Module):
    def __init__(self, in_channels, growth_rate, num_layers, concat_input=True):
        super(DenseBlock,self).__init__()
        self.concat_input = concat_input
        self.in_channels = in_channels
        self.growth_rate = growth_rate
        self.num_layers = num_layers
        self.out_channels = num_layers * growth_rate
        if self.concat_input:
            self.out_channels += self.in_channels
        for i in range(num_layers):
            self.add_module(f'layer_{i}',
                            DenseLayer(in_channels=in_channels+i*growth_rate,out_channels = growth_rate))

    def forward(self,block_input):
        layer_input = block_input
        layer_output = block_input.new_empty(0)
        all_outputs = [block_input] if self.concat_input else []
        for layer in self._modules.values():
            layer_input = torch.cat([layer_input, layer_output], dim=1)
            layer_output = layer(layer_input)
            all_outputs.append(layer_output)

        return torch.cat(all_outputs, dim=1)

class DenseBlock_b(nn.Sequential):
    def __init__(self, in_channels, kernel_size):
        super(DenseBlock_b,self).__init__()
        self.in_channels = in_channels
        self.kernel_size = kernel_size
        self.add_module('bn1',nn.BatchNorm2d(num_features=self.in_channels))
        self.add_module('relu',nn.ReLU(inplace=True))
        self.add_module('conv1',nn.Conv2d(self.in_channels,out_channels=384,kernel_size=self.kernel_size))
        self.add_module('dropout',nn.Dropout2d(0.2,inplace=True))

        self.add_module('bn1',nn.BatchNorm2d(num_features=self.in_channels))
        self.add_module('relu',nn.ReLU(inplace=True))
        self.add_module('conv1',nn.Conv2d(self.in_channels,out_channels=384,kernel_size=self.kernel_size))
        self.add_module('dropout',nn.Dropout2d(0.2,inplace=True))

        self.add_module('bn1',nn.BatchNorm2d(num_features=self.in_channels))
        self.add_module('relu',nn.ReLU(inplace=True))
        self.add_module('conv1',nn.Conv2d(self.in_channels,out_channels=256,kernel_size=self.kernel_size))
        self.add_module('dropout',nn.Dropout2d(0.2,inplace=True))

class DenseLayer(nn.Sequential):
    r"""
    Consists of:
    - Batch Normalization
    - ReLU
    - 3x3 Convolution
    - (Dropout) dropout rate: 0.2
    """
    def __init__(self, in_channels, out_channels, dropout=0.2):
        super(DenseLayer, self).__init__()
        self.in_channels = in_channels
        self.out_channels = out_channels

        self.add_module('norm', nn.BatchNorm2d(num_features=in_channels))
        self.add_module('relu', nn.ReLU(inplace=True))
        self.add_module('conv', nn.Conv2d(in_channels, out_channels, kernel_size=1, padding=0, bias=False))
        if dropout > 0:
            self.add_module('drop', nn.Dropout2d(dropout, inplace=True))

class transitionlayer(nn.Module):
    def __init__(self, in_planes, out_planes):
        super(transitionlayer,self).__init__()
        self.bn = nn.BatchNorm2d(in_planes)
        self.relu = nn.ReLU(inplace=True)
        self.conv = nn.Conv2d(in_planes,out_planes,kernel_size=1)
        self.average = nn.AvgPool2d(kernel_size=2, stride=2)
    def forward(self,x):
        x = self.bn(x)
        x = self.relu(x)
        x = self.conv(x)
        x = self.average(x)
        return x

if __name__ == '__main__':
    model = DenseSiameseRPN()

    template = torch.ones((1, 3, 127, 127))
    detection= torch.ones((1, 3, 256, 256))

    y1, y2 = model(template, detection)
    print(y1.shape) #[1, 10, 17, 17]
    print(y2.shape) #[1, 20, 17, 17]15


#Se desea saber cuántos meses han transcurrido entre los mismos inicios de dos años cualesquiera dados.#
print ("Bienvenido, en este programa te diré cuantos meses hay entre un año y otro.")
primerAño = input ("Escribe el primer año: ")
segundoAño = input ("Escribe el segundo y último año: ")
if (int(primerAño) > int(segundoAño)):
   diferenciaDeAños1 = (int(primerAño)-int(segundoAño))
   resultadoFinal = (diferenciaDeAños1*12)
   print ("La cantidad de meses entre" + " " + str(segundoAño) + " " + "y" + " " + str(primerAño) + " " + "son" + " " + str(resultadoFinal))

elif (int(primerAño) < int(segundoAño)):
   diferenciaDeAños2 = (int(segundoAño)-int(primerAño))
   resultadoFinal2 = (diferenciaDeAños2*12)
   print ("La cantidad de meses entre" + " " + str(primerAño) + " " + "y" + " " + str(segundoAño) + " " + "son" + " " + str(resultadoFinal2))

else:
     print ("La cantidad de meses es 0 porque usteded a seleccionado el mismo año dos veces")

Ejercicios practicos Drones/ejercicio general python1.py


import json
import boto3

role_policy_document = {
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

iam_client = boto3.client('iam')
iam_client.create_role(
  RoleName='LambdaBasicExecution',
  AssumeRolePolicyDocument=json.dumps(role_policy_document),
)


'''
RL policy generator

'''

import torch
import numpy as np
import copy
from utility.utility_env import one_hot_encoder
from utility.utility_DQN import DQN, format_state_for_action

class PolicyGen:
    """Policy generator class for CtF env.

    This class can be used as a template for policy generator.
    Designed to summon an AI logic for the team of units.

    Methods:
        gen_action: Required method to generate a list of actions.
    """

    def __init__(self, self_play_network, train_params, free_map, agent_list, env):
        """Constuctor for policy class.

        This class can be used as a template for policy generator.

        Args:
            free_map (np.array): 2d map of static environment.
            agent_list (list): list of all friendly units.
        """
        self.model = copy.deepcopy(self_play_network)
        self.env = env
        self.train_params = train_params

    def gen_action(self, agent_list, observation, free_map=None):
        """Action generation method.

        This is a required method that generates list of actions corresponding
        to the list of units.

        Args:
            agent_list (list): list of all friendly units.
            observation (np.array): 2d map of partially observable map.
            free_map (np.array): 2d map of static environment (optional).

        Returns:
            action_out (list): list of integers as actions selected for team.
        """
        action_list = []
        state = one_hot_encoder(self.env._env, self.env.get_team_red, vision_radius = self.train_params['vision_radius'])

        state = format_state_for_action(state)
        with torch.no_grad():
            for i in range(len(agent_list)):
                q_values = self.model.forward(state[:, i, :, :, :])
                _, action = torch.max(q_values, 1)
                action_list.append(int(action.data))

        return action_list


from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import cv2
# import motor
import numpy as np
# initialize the camera and grab a reference to the raw camera capture
camera = PiCamera()
# resolution
camera.resolution = (400, 240)
# FR
camera.framerate = 15
rawCapture = PiRGBArray(camera, size=(400, 240))
# allow the camera to warmup
time.sleep(0.1)
# capture frames from the camera

WIDTH = 400
HEIGHT = 240

pts1 = np.array([[62,135],[340,135],[45,185],[362,185]],np.int32)
pts2 = np.array([[100,0],[280,0],[100,240],[280,240]],np.int32)

def Perspective(image, pts1): #원근법 변환
    """
    Capture a Region of Interest
    """
    cv2.line(image,pt1=tuple(pts1[0]),pt2=tuple(pts1[1]),color=(255,0,0),thickness=2)
    cv2.line(image,pt1=tuple(pts1[1]),pt2=tuple(pts1[3]),color=(255,0,0),thickness=2)
    cv2.line(image,pt1=tuple(pts1[3]),pt2=tuple(pts1[2]),color=(255,0,0),thickness=2)
    cv2.line(image,pt1=tuple(pts1[2]),pt2=tuple(pts1[0]),color=(255,0,0),thickness=2)

    # cv2.line(image,pt1=tuple(pts2[0]),pt2=tuple(pts2[1]),color=(255,0,0),thickness=2)
    # cv2.line(image,pt1=tuple(pts2[1]),pt2=tuple(pts2[3]),color=(255,0,0),thickness=2)
    # cv2.line(image,pt1=tuple(pts2[3]),pt2=tuple(pts2[2]),color=(255,0,0),thickness=2)
    # cv2.line(image,pt1=tuple(pts2[2]),pt2=tuple(pts2[0]),color=(255,0,0),thickness=2)
    cv2.imshow("ROI", image)
    cv2.waitKey(1)

    Matrix = cv2.getPerspectiveTransform(pts1.astype(np.float32), pts2.astype(np.float32))
    imgPers = cv2.warpPerspective(image, Matrix, (WIDTH, HEIGHT))
    return imgPers

def Threshold(imgPers):
    imgGray = cv2.cvtColor(imgPers, cv2.COLOR_RGB2GRAY)

    # Blurring -----------------------------------------------
    # imgBlur = cv2.blur(imgPers, (5,5))
    imgBlur = cv2.GaussianBlur(imgGray, (5,5), 0)
    # imgBlur = cv2.medianBlur(imgPers, 5)
    # imgBlur = cv2.bilateralFilter(imgPers,9,75,75)
    # -----------------------------------------------

    imgThresh = cv2.inRange(imgBlur, 149, 255, cv2.THRESH_BINARY)

    # Erosion / Dilation-------------------------------------------------------
    kernel = np.ones((5,5),np.uint8)
    imgErode = cv2.erode(imgThresh,kernel,iterations=1)
    # imgDilate = cv2.dilate(imgErode,kernel,iterations=1)
    # -------------------------------------------------------

    sobel_horizontal = cv2.Sobel(imgErode, cv2.CV_8U, 1, 0, ksize=9)
    # kernel2 = np.ones((3,3),np.uint8)
    # imgMpl = cv2.morphologyEx(sobel_horizontal, cv2.MORPH_CLOSE, kernel2)

    cv2.imshow("threshold", sobel_horizontal)
    cv2.waitKey(1)

    # Canny edge detection : still need tuning
    imgEdge = cv2.Canny(imgGray, 270, 300)

    cv2.imshow("canny edge", imgEdge)
    cv2.waitKey(1)

    # combing the binary threshold and canny edge detector
    imgFinal = cv2.add(sobel_horizontal, imgEdge)
    imgFinal = cv2.cvtColor(imgFinal, cv2.COLOR_GRAY2RGB)
    imgFinalDuplicate = cv2.cvtColor(imgFinal, cv2.COLOR_RGB2BGR)
    imgFinalDuplicate1 = cv2.cvtColor(imgFinal, cv2.COLOR_RGB2BGR)
    return imgFinal, imgFinalDuplicate, imgFinalDuplicate1

def Histogram(imgFinalDuplicate):
    histogramLane = np.uint8([])

    for i in range(WIDTH):
        # ROILane = cv2.rectangle(imgFinalDuplicate,(i,140),(i+1,240),(0,0,255),3)
        # Matrix: rows 100, cols 1
        ROILane= imgFinalDuplicate[HEIGHT-100:HEIGHT, i]
        # scaling (0 ~ 255) to (0 ~ 1)
        ROILane = cv2.divide(ROILane, 255)
        # summation of white pixels: append the number of white pixels in ROILane to hisogramLane
        histogramLane = np.append(histogramLane, ROILane.sum(axis=0)[0:1].astype(np.uint8), axis=0)
    return histogramLane

def LaneFinder(imgFinal, histogramLane):
    # find the position of left edge of left lane
    LeftLanePos = np.argmax(histogramLane[:150])

    # find the position of left edge of right lane
    RightLanePos = 250 + np.argmax(histogramLane[250:])

    cv2.line(imgFinal, (LeftLanePos, 0), (LeftLanePos, HEIGHT), color=(0,255,0), thickness=2)
    cv2.line(imgFinal, (RightLanePos, 0), (RightLanePos, HEIGHT), color=(0,255,0), thickness=2)
    return LeftLanePos, RightLanePos

def LaneCenter(imgFinal, LeftLanePos, RightLanePos):
    laneCenter = ((RightLanePos - LeftLanePos) / 2 + LeftLanePos).astype(np.uint8)
    frameCenter = WIDTH // 2

    cv2.line(imgFinal, (laneCenter, 0), (laneCenter, HEIGHT), color=(0,255,0), thickness=3)
    cv2.line(imgFinal, (frameCenter, 0), (frameCenter, HEIGHT), color=(255,0,0), thickness=3)
    cv2.imshow("positions of white lanes", imgFinal)
    cv2.waitKey(1)

    Result = laneCenter - frameCenter
    return Result

for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
    # grab the raw NumPy array representing the image, then initialize the timestamp
    # and occupied/unoccupied text
    image = frame.array

    imgPers = Perspective(image, pts1)
    imgFinal, imgFinalDuplicate, imgFinalDuplicate1 = Threshold(imgPers)
    histogramLane = Histogram(imgFinalDuplicate)
    LeftLanePos, RightLanePos = LaneFinder(imgFinal, histogramLane)
    Result = LaneCenter(imgFinal, LeftLanePos, RightLanePos)

    if Result == 0:
        print("Forward")

    elif 0 < Result < 10:
        print("Right1")

    elif 10 <= Result < 20:
        print("Right2")

    elif Result >= 20:
        print("Right3")

    elif -10 < Result < 0:
        print("Left1")

    elif -20 < Result <= -10:
        print("Left2")

    elif Result <= -20:
        print("Left3")

    ss = f"Result = {Result}" #StringStream
    cv2.putText(image, str(ss), (1,50), 0, 1, color=(0,0,255), thickness=2)

    # show the frame
    cv2.imshow("Frame", image)
    key = cv2.waitKey(1) & 0xFF
    # clear the stream in preparation for the next frame
    rawCapture.truncate(0)
    if key == ord("q"):
        break


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

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('ecommerce', '0005_auto_20151021_1813'),
        ('shopping', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='CartItem',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('quantity', models.IntegerField(default=1)),
                ('total', models.CharField(max_length=100)),
                ('cart_item', models.ForeignKey(default=0, to='shopping.Cart')),
                ('product', models.ForeignKey(to='ecommerce.Brand')),
            ],
        ),
        migrations.RemoveField(
            model_name='chartitem',
            name='cart',
        ),
        migrations.RemoveField(
            model_name='chartitem',
            name='product',
        ),
        migrations.DeleteModel(
            name='ChartItem',
        ),
    ]


import bpy
import os
import shutil

from .operators import *

bl_info = {
    "name": "Bizualizer",
    "description": "Create a simple visualizer for audio",
    "author": "doakey3",
    "version": (1, 3, 3),
    "blender": (2, 80, 0),
    "wiki_url": "https://github.com/doakey3/Bizualizer",
    "tracker_url": "https://github.com/doakey3/Bizualizer/issues",
    "category": "Animation",
    "location": "Properties > Scene"}

class RENDER_PT_ui(bpy.types.Panel):
    bl_space_type = "PROPERTIES"
    bl_region_type = "WINDOW"
    bl_label = "Bizualizer"
    bl_context = "scene"
    bl_options = {"DEFAULT_CLOSED"}

    def is_shape_3d(self, shape):
        if shape == "CUBOID" or shape == "PYRAMID":
            return True
        else:
            return False

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

        row = layout.label(text="Audio")

        row = layout.row()
        row.prop(scene, "bz_audiofile", icon="SOUND")
        row = layout.row()
        row.prop(scene, "bz_audio_channel")
        row = layout.row()
        row.operator("sequencerextra.bz_audio_to_sequencer",
                     icon="SEQ_SEQUENCER")
        row.operator("sequencerextra.bz_audio_remove", icon="CANCEL")

        row = layout.separator()
        row = layout.label(text="Bars")

        row = layout.row()
        row.prop(scene, "bz_bar_shape")
        row = layout.row()
        row.prop(scene, "bz_bar_count")
        row = layout.row()
        split = row.split()
        col_a = split.column(align=True)
        col_a.prop(scene, "bz_bar_width")
        col_b = split.column(align=True)
        col_b.prop(scene, "bz_bar_depth")
        col_b.enabled = self.is_shape_3d(scene.bz_bar_shape)
        row = layout.row()
        split = row.split()
        col_a = split.column(align=True)
        col_a.prop(scene, "bz_amplitude")
        col_b = split.column(align=True)
        col_b.prop(scene, "bz_spacing")
        col_b.enabled = not scene.bz_use_radial
        row = layout.row()
        row.prop(scene, "bz_attack_time")
        row.prop(scene, "bz_release_time")

        row = layout.separator()

        row = layout.row()
        row.prop(scene, "bz_use_radial")
        row = layout.row()
        split = row.split()
        col_a = split.column(align=True)
        col_a.prop(scene, "bz_radius")
        col_a.enabled = scene.bz_use_radial
        col_b = split.column(align=True)
        col_b.prop(scene, "bz_arc_angle")
        col_b.enabled = scene.bz_use_radial
        row = layout.row()
        split = row.split()
        col_a = split.column(align=True)
        col_a.prop(scene, "bz_arc_center_offset")
        col_a.enabled = scene.bz_use_radial
        col_b = split.column(align=True)
        col_b.prop(scene, "bz_flip_direction")
        col_b.enabled = scene.bz_use_radial

        row = layout.separator()
        row = layout.label(text="Colors")

        row = layout.row()
        split = row.split()
        col_a = split.column(align=True)
        col_a.label(text="Visualizer Color Style:")
        col_b = split.column(align=True)
        col_b.prop(scene, "bz_color_style")

        if scene.bz_color_style != "SINGLE_COLOR":
            row = layout.row()
            row.prop(scene, "bz_color_count")

        row = layout.row()
        row.prop(scene, "bz_color1")

        if scene.bz_color_style != "SINGLE_COLOR":
            for index in range(2, scene.bz_color_count + 1):
                row = layout.row()
                row.prop(scene, "bz_color" + ("{0:d}".format(index)))

            row = layout.row()
            row.prop(scene, "bz_color_pattern")

            if scene.bz_color_style == "GRADIENT":
                row = layout.row()
                row.prop(scene, "bz_gradient_interpolation")

        row = layout.row()
        row.prop(scene, "bz_emission_strength")

        row = layout.separator()
        row = layout.label(text="Generate")

        row = layout.row()
        row.prop(scene, "bz_preview_mode")
        row = layout.row()
        row.operator("object.bz_generate", icon="FILE_REFRESH")

        row = layout.separator()
        row = layout.label(text="Camera")

        row = layout.row()
        row.prop(scene, "bz_cam_alignment")
        row = layout.row()
        row.operator("object.bz_align_camera", icon="CAMERA_DATA")

        row = layout.separator()

        box = layout.box()
        row = box.row()
        row.prop(scene, 'bbz_config')
        row = box.row()
        row.operator('object.batch_bizualize', icon="ALIGN_LEFT")
        row.operator('object.make_bz_previews')

def initprop():
    bpy.types.Scene.bz_audiofile = bpy.props.StringProperty(
        name="Audio Path",
        description="Define path of the audio file",
        subtype="FILE_PATH",
        )

    bpy.types.Scene.bz_audio_channel = bpy.props.IntProperty(
        name="Audio Channel",
        description="Channel where audio will be added",
        default=1,
        min=1
        )

    bpy.types.Scene.bz_attack_time = bpy.props.FloatProperty(
        name="Attack Time",
        description="How long it takes for the hull curve to rise (the lower the value the steeper it can rise)",
        default=0.005,
        min=0,
        max=2
        )

    bpy.types.Scene.bz_release_time = bpy.props.FloatProperty(
        name="Release Time",
        description="How long it takes for the hull curve to fall (the lower the value the steeper it can fall)",
        default=0.2,
        min=0,
        max=5
        )

    bpy.types.Scene.bz_bar_shape = bpy.props.EnumProperty(
        name="Bar Shape",
        description="The shape of the bars",
        default="RECTANGLE",
        items=[ ("RECTANGLE", "Rectangle", "", "", 1),
                ("TRIANGLE", "Triangle", "", "", 2),
                ("CUBOID", "Cuboid", "", "", 3),
                ("PYRAMID", "Pyramid", "", "", 4)
        ])

    bpy.types.Scene.bz_bar_count = bpy.props.IntProperty(
        name="Bar Count",
        description="The number of bars to make",
        default=64,
        min=1
        )

    bpy.types.Scene.bz_bar_width = bpy.props.FloatProperty(
        name="Bar Width",
        description="The width of the bars",
        default=1.6,
        min=0
        )

    bpy.types.Scene.bz_bar_depth = bpy.props.FloatProperty(
        name="Bar Depth",
        description="The depth of the bars (3D only)",
        default=1.6,
        min=0
        )

    bpy.types.Scene.bz_amplitude = bpy.props.FloatProperty(
        name="Amplitude",
        description="Amplitude of visualizer bars",
        default=48.0,
        min=0
        )

    color_input_description = "Color applied to bars after visualizer is generated"

    bpy.types.Scene.bz_color_style = bpy.props.EnumProperty(
        name="",
        description="How the color(s) should be applied to bars",
        default="SINGLE_COLOR",
        items=[ ("SINGLE_COLOR", "Single Color", "", "", 1),
                ("PATTERN", "Pattern", "", "", 2),
                ("GRADIENT", "Gradient", "", "", 3)
        ])

    bpy.types.Scene.bz_color_count = bpy.props.IntProperty(
        name="Color Count",
        description="Number of input colors",
        default=3,
        min=2,
        max=9
        )

    bpy.types.Scene.bz_color1 = bpy.props.FloatVectorProperty(
        name="Bar Color 1",
        subtype='COLOR_GAMMA',
        description=color_input_description,
        size=3,
        default=(1.0, 1.0, 1.0),
        min=0.0,
        max=1.0
        )

    bpy.types.Scene.bz_color2 = bpy.props.FloatVectorProperty(
        name="Bar Color 2",
        subtype='COLOR_GAMMA',
        description=color_input_description,
        size=3,
        default=(1.0, 0.0, 0.0),
        min=0.0,
        max=1.0
        )

    bpy.types.Scene.bz_color3 = bpy.props.FloatVectorProperty(
        name="Bar Color 3",
        subtype='COLOR_GAMMA',
        description=color_input_description,
        size=3,
        default=(0.0, 0.0, 1.0),
        min=0.0,
        max=1.0
        )

    bpy.types.Scene.bz_color4 = bpy.props.FloatVectorProperty(
        name="Bar Color 4",
        subtype='COLOR_GAMMA',
        description=color_input_description,
        size=3,
        default=(0.0, 1.0, 0.0),
        min=0.0,
        max=1.0
        )

    bpy.types.Scene.bz_color5 = bpy.props.FloatVectorProperty(
        name="Bar Color 5",
        subtype='COLOR_GAMMA',
        description=color_input_description,
        size=3,
        default=(0.0, 1.0, 1.0),
        min=0.0,
        max=1.0
        )

    bpy.types.Scene.bz_color6 = bpy.props.FloatVectorProperty(
        name="Bar Color 6",
        subtype='COLOR_GAMMA',
        description=color_input_description,
        size=3,
        default=(1.0, 1.0, 0.0),
        min=0.0,
        max=1.0
        )

    bpy.types.Scene.bz_color7 = bpy.props.FloatVectorProperty(
        name="Bar Color 7",
        subtype='COLOR_GAMMA',
        description=color_input_description,
        size=3,
        default=(1.0, 0.0, 1.0),
        min=0.0,
        max=1.0
        )

    bpy.types.Scene.bz_color8 = bpy.props.FloatVectorProperty(
        name="Bar Color 8",
        subtype='COLOR_GAMMA',
        description=color_input_description,
        size=3,
        default=(0.5, 0.5, 0.5),
        min=0.0,
        max=1.0
        )

    bpy.types.Scene.bz_color9 = bpy.props.FloatVectorProperty(
        name="Bar Color 9",
        subtype='COLOR_GAMMA',
        description=color_input_description,
        size=3,
        default=(0.0, 0.0, 0.0),
        min=0.0,
        max=1.0
        )

    bpy.types.Scene.bz_color_pattern = bpy.props.StringProperty(
        name="Color Pattern",
        description="Pattern in which the colors will be applied to bars",
        default="12321"
        )

    bpy.types.Scene.bz_gradient_interpolation = bpy.props.EnumProperty(
        name="Interpolation",
        description="Color system used for computing the gradient",
        default="RGB",
        items=[ ("RGB", "RGB", "", "", 1),
                ("HSV", "HSV", "", "", 2),
                ("HSL", "HSL", "", "", 3)
        ])

    bpy.types.Scene.bz_emission_strength = bpy.props.FloatProperty(
        name="Glow Strength",
        description="Strength of the emission shader",
        default=1.0,
        min=0
        )

    bpy.types.Scene.bz_use_radial = bpy.props.BoolProperty(
        name="Use Radial",
        description="Use a circular visualizer",
        default=False
        )

    bpy.types.Scene.bz_radius = bpy.props.FloatProperty(
        name="Radius",
        description="Radius of the radial visualizer",
        default=20,
        min=0
        )

    bpy.types.Scene.bz_arc_angle = bpy.props.FloatProperty(
        name="Arc Angle",
        description="Angular size of the radial visualizer",
        default=360,
        min=1,
        max=360
        )

    bpy.types.Scene.bz_arc_center_offset = bpy.props.FloatProperty(
        name="Arc Rotation",
        description="Angle where radial visualizer is centered",
        default=0,
        min=-180,
        max=180
        )

    bpy.types.Scene.bz_flip_direction = bpy.props.BoolProperty(
        name="Flip Direction",
        description="Arrange the bars in reverse direction",
        default=False
        )

    bpy.types.Scene.bz_spacing = bpy.props.FloatProperty(
        name="Spacing",
        description="Spacing between bars",
        default=0.65,
        min=0
        )

    bpy.types.Scene.bz_preview_mode = bpy.props.BoolProperty(
        name="Preview Mode",
        description="Generate bars without animation",
        default=False
        )

    bpy.types.Scene.bz_cam_alignment = bpy.props.EnumProperty(
        name="Alignment",
        description="Position, orientation and type of camera",
        default="2D_bottom",
        items=[ ("2D_bottom", "2D bottom", "", "", 1),
                ("2D_center", "2D center", "", "", 2),
                ("2D_top", "2D top", "", "", 3),
                ("2D_left", "2D left", "", "", 4),
                ("2D_right", "2D right", "", "", 5),
                ("3D_bottom", "3D bottom", "", "", 6),
                ("3D_center", "3D center", "", "", 7)
        ])

    bpy.types.Scene.bbz_config = bpy.props.StringProperty(
        name="Config File",
        description="Path to the Config File",
        subtype="FILE_PATH",
        )

classes = [
    RENDER_PT_ui,
    RENDER_OT_align_camera,
    RENDER_OT_audio_to_vse,
    RENDER_OT_batch_bizualize,
    RENDER_OT_generate_visualizer,
    RENDER_OT_make_previews,
    RENDER_OT_remove_bz_audio
]

def register():
    initprop()

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

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


import sys
Acids = ['A','R','N','D','C','E','Q','G','H','I','L','K','M','F','P','S','T','W','Y','V']
#Q = 0.01
Q = 1
inFile = open(sys.argv[1])
ouFile = open(sys.argv[1] + '.pep', 'w')
head = inFile.readline().strip()
ouFile.write('PepSeq' + '\t' + head + '\n')
for line in inFile:
    line = line.strip()
    fields = line.split('\t')
    pep = fields[8]
    pepQvalue = float(fields[-1])
    if pepQvalue < Q:
        L = []
        for x in pep:
            if x in Acids:
                L.append(x)
        ouFile.write(''.join(L) + '\t' + line + '\n')
inFile.close()
ouFile.close()