#!/usr/bin/python

import argparse

'''
the list of prices show the variance of price during different times of day. list is sorted by time and not by price.

so the basic problem is to find the maximum profit you can make by buying first and then selling later in the day.

what we need to do is to keep track of the min price so far and the max profit so far.

so we need to have some sort of pointer that starts at the beginning of the array and then a second pointer that starts at the second element in the array.

the first element is automatically the current min price so far and the difference between the second element and the first element is the current max profit so far.

if we do a while loop whose conditional is that i and j are both less than the length of the array, we can keep the while loop going without having nested loops I think.

for the first check, we set i to the initial element in array and we set j to the third element in the array since we have already instantiated the the max profit so far is the difference between elemnt 1 and element 0.

let's check to see if j element - i element is > max profit so far -- if it is update max profit

if not, advance j if there is length left in the array -- if not reset i to i + 1 and reset j to the "new" i + 1.

'''

def find_max_profit(prices):

  i = 0
  j = 1
  max_profit = float('-inf')
  while i < len(prices) and j < len(prices):
    difference = prices[j] - prices[i]
    print(difference)
    if difference > max_profit:
      max_profit = difference
      if j + 1 == len(prices):
        #we start over
        if i + 1 == len(prices):
          break
        else:
          i += 1
          j = i + 1 #new i
      else:
        j += 1
    else:
      if j + 1 == len(prices):
        #we start over
        if i + 1 == len(prices):
          break
        else:
          i += 1
          j = i + 1 #new i
      else:
        j += 1

  return max_profit

if __name__ == '__main__':
  # This is just some code to accept inputs from the command line
  parser = argparse.ArgumentParser(description='Find max profit from prices.')
  parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer price')
  args = parser.parse_args()

  print("A profit of ${profit} can be made from the stock prices {prices}.".format(profit=find_max_profit(args.integers), prices=args.integers))


"""
This file is part of pyS5p

https://github.com/rmvanhees/pys5p.git

Implements a lite interface with the xarray::DataArray

Copyright (c) 2020-2021 SRON - Netherlands Institute for Space Research
   All Rights Reserved

License:  BSD-3-Clause
"""
from pathlib import PurePath

import numpy as np
import xarray as xr

def __get_attrs(dset, field: str) -> dict:
    """
    Return attributes of the HDF5 dataset

    Parameters
    ----------
    dset :  h5py.Dataset
       h5py dataset from which the attributes are read
    field : str
       Name of field in compound dataset

    Returns
    -------
    dict with numpy arrays
    """
    _field = None
    if field is not None:
        try:
            _field = {'name': field,
                      'oneof': len(dset.dtype.names),
                      'index': dset.dtype.names.index(field)}
        except Exception as exc:
            raise RuntimeError(
                f'field {field} not found in dataset {dset.name}') from exc
        # print('_field ', _field)

    attrs = {}
    for key in dset.attrs:
        if key in ('CLASS', 'DIMENSION_LIST', 'NAME', 'REFERENCE_LIST',
                   '_Netcdf4Dimid'):
            continue

        attr_value = dset.attrs[key]
        # print('# ----- ', key, type(attr_value), attr_value)
        if isinstance(attr_value, np.ndarray):
            if len(attr_value) == 1:
                attr_value = attr_value[0]
                # print('# ----- ', key, type(attr_value), attr_value)
            elif _field is not None:
                if len(attr_value) == _field['oneof']:
                    attr_value = attr_value[_field['index']]
                # elif isinstance(attr_value, np.void):
                #    attr_value = attr_value[0]

        attrs[key] = (attr_value.decode('ascii')
                      if isinstance(attr_value, bytes) else attr_value)

    return attrs

def __get_coords(dset, data_sel: tuple) -> list:
    """
    Return coordinates of the HDF5 dataset

    Parameters
    ----------
    dset :  h5py.Dataset
       h5py dataset from which the data is read
    data_sel :  tuple of slice(s)
       A numpy slice generated for example numpy.s_
       Default read while array

    Returns
    -------
    A sequence of tuples [(dims, data), ...]
    """
    coords = []
    if len(dset.dims) == dset.ndim:
        try:
            for ii, dim in enumerate(dset.dims):
                name = PurePath(dim[0].name).name
                if name.startswith('row') or name.startswith('column'):
                    name = name.split(' ')[0]

                buff = dim[0][()]
                if np.all(buff == 0):
                    buff = np.arange(dim[0].size, dtype=dim[0].dtype)
                elif data_sel is not None:
                    buff = buff[data_sel[ii]]

                coords.append((name, buff))
        except RuntimeError:
            coords = []

    return coords

def __set_coords(dset, data_sel: tuple, dims: list) -> list:
    """
    Set coordinates of the HDF5 dataset

    Parameters
    ----------
    dset :  h5py.Dataset or numpy.array
       h5py dataset from which the data is read
    data_sel :  tuple of slice(s)
       A numpy slice generated for example numpy.s_
       Default read while array
    dims : list of strings
       Alternative names for the dataset dimensions if not attached to dataset
       Default coordinate names are ['time', ['row', ['column']]]

    Returns
    -------
    A sequence of tuples [(dims, data), ...]
    """
    if dims is None:
        if dset.ndim > 3:
            raise ValueError('not implemented for ndim > 3')

        dims = ['time', 'row', 'column'][-dset.ndim:]

    coords = []
    for ii in range(dset.ndim):
        buff = np.arange(dset.shape[ii], dtype='u4')
        if data_sel is not None:
            buff = buff[data_sel[ii]]
        coords.append((dims[ii], buff))

    return coords

def __get_data(dset, data_sel: tuple, field: str):
    """
    Return data of the HDF5 dataset

    Parameters
    ----------
    dset :  h5py.Dataset
       h5py dataset from which the data is read
    data_sel :  numpy slice
       A numpy slice generated for example numpy.s_
       Default read while array
    field : str
       Name of field in compound dataset or None

    Returns
    -------
    Numpy array

    Notes
    -----
    Read floats always as doubles
    """
    if data_sel is None:
        data_sel = ()

    if np.issubdtype(dset.dtype, np.floating):
        data = dset.astype(float)[data_sel]
        data[data == float.fromhex('0x1.ep+122')] = np.nan
        return data

    if field is None:
        return dset[data_sel]

    data = dset.fields(field)[data_sel]
    if np.issubdtype(data.dtype, np.floating):
        data = data.astype(float)
        data[data == float.fromhex('0x1.ep+122')] = np.nan
    return data

def h5_to_xr(h5_dset, data_sel=None, *, dims=None, field=None):
    """
    Create xarray::DataArray from a HDF5 dataset (with dimension scales)

    Parameters
    ----------
    h5_dset :  h5py.Dataset
       Data, dimensions, coordinates and attributes are read for this dataset
    data_sel :  slice, optional
       A numpy slice generated for example numpy.s_
    dims :  list of strings, optional
       Alternative names for the dataset dimensions if not attached to dataset
    field : str, optional
       Name of field in compound dataset or None

    Returns
    -------
    xarray.DataArray

    Notes
    -----
    If data_sel is used to select data from a dataset then the number of
    dimensions of data_sel should agree with the HDF5 dataset or one and
    only one Ellipsis has to be used.
    Thus allowed values for data_sel are:
    * [always]: (), np.s_[:], np.s_[...]
    * [1-D dataset]: np.s_[:-1], np.s_[0]
    * [2-D dataset]: np.s_[:-1, :], np.s_[0, :], np.s_[:-1, 0]
    * [3-D dataset]: np.s_[:-1, :, 2:4], np.s_[0, :, :], np.s_[:-1, 0, 2:4]
    * [Ellipsis] np.s_[0, ...], np.s_[..., 4], np.s_[0, ..., 4]

    Examples
    --------
    >>> fid = h5py.File(flname, 'r')        # flname is a HDF5/netCDF4 file
    >>> xdata = h5_to_xr(fid['signal'])
    >>> fid.close()

    Combine Tropomi SWIR data of band7 and band8
    >>> fid = h5py.File(s5p_b7_prod, 'r')   # Tropomi band7 product
    >>> xdata7 = h5_to_xr(fid['signal'])
    >>> fid.close()
    >>> fid = h5py.File(s5p_b8_prod, 'r')   # Tropomi band8 product
    >>> xdata8 = h5_to_xr(fid['signal'])
    >>> fid.close()
    >>> xdata = xr.concat((xdata7, xdata8), dim='spectral_channel')

    Optionally, fix the 'column' dimension
    >>> xdata = xdata.assign_coords(
    >>> ... column=np.arange(xdata.column.size, dtype='u4'))
    """
    if data_sel is not None:
        if data_sel in (np.s_[:], np.s_[...], np.s_[()]):
            data_sel = None
        elif np.isscalar(data_sel):
            data_sel = (np.s_[data_sel:data_sel+1],)
        else:
            buff = ()
            for val in data_sel:
                if val == Ellipsis:
                    for _ in range(h5_dset.ndim - len(data_sel) + 1):
                        buff += np.index_exp[:]
                elif np.isscalar(val):
                    buff += (np.s_[val:val+1],)
                else:
                    buff += (val,)
            data_sel = buff

    # Name of this array
    name = PurePath(h5_dset.name).name

    # Values for this array
    data = __get_data(h5_dset, data_sel, field)

    # Coordinates (tick labels) to use for indexing along each dimension
    coords = []
    if dims is None:
        coords = __get_coords(h5_dset, data_sel)
    if not coords:
        coords = __set_coords(h5_dset, data_sel, dims)

    # Attributes to assign to the array
    attrs = __get_attrs(h5_dset, field)

    # check if dimension of dataset and coordinates agree
    if data.ndim < len(coords):
        for ii in reversed(range(len(coords))):
            if np.isscalar(coords[ii][1]):
                del coords[ii]

    return xr.DataArray(data, name=name, attrs=attrs, coords=coords)

def data_to_xr(data, *, dims=None, name=None, long_name=None, units=None):
    """
    Create xarray::DataArray from a dataset

    Parameters
    ----------
    data :  array-like
       Data to be stored in the xarray
    dims :  list of strings
       Names for the dataset dimensions
    name : str
       A string that names the instance
    units :  str
       Units of the data, default: '1'
    long_name : str
       Long name describing the data, default: empty string

    Returns
    -------
    xarray.DataArray
    """
    coords = __set_coords(data, None, dims)
    attrs = {}
    attrs['units'] = '1' if units is None else units
    attrs['long_name'] = '' if long_name is None else long_name

    return xr.DataArray(data, name=name, attrs=attrs, coords=coords)


import urllib.request
from bs4 import BeautifulSoup

class Scraper:
    def __init__(self, site):
        self.site = site
    def scrape(self):
        response = urllib.request.urlopen(self.site)
        html = response.read()
        sp = BeautifulSoup(html,"html.parser")
        with open ("output.txt","w") as f:
            for tag in sp.find_all("a"):
                url = tag.get("href")
                if url and 'html' in url:
                    print("\n" + url)
                    f.write("\n" + url)

news = "https://sueddeutsche.de/"
Scraper(news).scrape()


# to check whether a number is prime or not
import math
number=int(input())
cout=0
for x in range(2,int(math.sqrt(number)+1)):
	if(number%x==0):
		cout=cout+1
if(cout==0):
	print("prime")
else:
	print("not prime")


from django import template

from categories.models import Good

register = template.Library()

@register.inclusion_tag('goodtypes_block.html')
def show_goodtypes(category):
    goodtypes = category.goodtype_set.all()
    for goodtype in goodtypes:
    	goodtype.count = Good.objects.filter(goodtype=goodtype).count()
    return {'goodtypes': goodtypes}


"""stream URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url,include
from django.contrib import admin
from input import views

# from Slm.stream.input.views import list_manage

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', views.argon_index),
    url(r'^reptilian/login_action/$', views.login_action),
    url(r'^content_page/(\d+)/$',views.content_manage,name='content_manage'),#name=指向views里面

    url(r'^crawl/$',views.crawl_manage),
    url(r'^crawl_action/(\d+)/$',views.crawl_action),

    url(r'^newspaper/$',views.newspaper),
    url(r'^newspaper/(\d+)/$', views.newspaper,name='newspaper'),
    url(r'^breakfast/$', views.breakfast),
    url(r'^breakfast_login/$', views.breakfast_login),
    url(r'^breakfast1/$', views.breakfast1),
    url(r'^breakfast2/$', views.breakfast2),
    url(r'^breakfast_logout/$', views.breakfast_logout),
    url(r'^breakfast_create/$', views.breakfast_create),
    # url(r'^breakfast_create/(?P<id>[0-9]+)/$', views.breakfast_create),

    url(r'^new_index/$',views.new_index),
    url(r'^album/$',views.album),
    url(r'^admin_0/$', views.admin_0),
    url(r'^reptilian/$',views.reptilian),
    url(r'^api_page/$',views.api_page),
    url(r'^comment/(\d+)/$', views.comment),

    url(r'^api/',include('input.urls',)),#配置具体接口的二级路径。
    url(r'^logout/$',views.logout),
    url(r'^cover/$', views.cover),
    url(r'^grid/$',views.grid),# 2019/8/1 新页面，其他抛掉
    url(r'^film/$',views.film),
    url(r'^cover2/$', views.cover2),

    url(r'^argon_index/$', views.argon_index),# 首页
    url(r'^argon_login/$', views.argon_login),  # 登录动作
    url(r'^argon_logout/$', views.argon_logout),  # 退出动作

    url(r'^dashboard/$', views.dashboard), # 登录后跳转页面
    url(r'^tables/$', views.tables),  # 电影列表页面
    url(r'^tables_de/(\d+)/$', views.tables_de, name='tables_de'),  # name=指向views里面
    url(r'^reptilian_de/$', views.reptilian), # 爬虫页面
    url(r'^crawl_save/(\d+)/$', views.crawl_save),
    url(r'^astrology/$', views.astrology),

]

handler404 = views.page_not_found
handler500 = views.page_error


from rest_framework import viewsets, routers
from react_app.models import User_Models
from .serializers import UserSerializer

class UserApi(viewsets.ModelViewSet):
    queryset = User_Models.objects.all()
    serializer_class = UserSerializer

    def get_queryset(self):
        queryset = User_Models.objects.all()
        L_id = self.request.query_params.get('id')

        if L_id:
            queryset = queryset.filter(user_id=L_id)

        return queryset

router = routers.DefaultRouter()
router.register(r'user', UserApi)


"""
How to play:
    At the begining you will have the shape of a line, to change the shape you can type the letter assigned
    to the letter you want to choose.
    Shape options:  l -> line
                    s -> square
                    c -> circle
                    r -> rectangle
                    t -> triangle
    If you want to draw a shape click on the part of the screen where you want to start the shape, then click
    where you want it to end.

    To change of colors type one of the following options that are available for you in Uppercase.
    Color options:  K -> black
                    W -> white
                    G -> green
                    B -> blue
                    R -> red
                    P -> purple
                    O -> orange
"""

from turtle import *
from freegames import vector

def line(start, end):
    """Draw line from start to end."""
    up()
    goto(start.x, start.y)
    down()
    goto(end.x, end.y)

def square(start, end):
    """Draw square from start to end."""
    up()
    goto(start.x, start.y)
    down()
    begin_fill()

    for count in range(4):
        forward(end.x - start.x)
        left(90)

    end_fill()

def circle(start, end):
    """Draw circle from start to end."""
    up()
    goto(start.x, start.y)
    down()
    begin_fill()

    for count in range(180):
        forward(end.x - start.x)
        left(2)

    end_fill()

def rectangle(start, end):
    """Draw rectangle from start to end."""
    up()
    goto(start.x, start.y)
    down()
    begin_fill()

    # Multiplica por 2 para tener un lado doble de largo
    forward((2 * end.x) - start.x)
    left(90)
    forward(end.x - start.x)
    left(90)
    # Multiplica por 2 para tener un lado doble de largo
    forward((2 * end.x) - start.x)
    left(90)
    forward(end.x - start.x)
    left(90)

    end_fill()

# Funcion creada por Eduardo Acosta A01375206
def triangle(start, end):
    """Draw triangle from start to end."""
    # Definimos los puntos en el lienzo mediante los clics
    up()
    goto(start.x, start.y)
    down()
    begin_fill()
    # Se utiliza rango 3 porque es el número de lados de un triangulo
    for count in range(3):
        forward(end.x - start.x)
        left(120)

    end_fill()

def tap(x, y):
    """Store starting point or draw shape."""
    start = state['start']

    if start is None:
        state['start'] = vector(x, y)
    else:
        shape = state['shape']
        end = vector(x, y)
        shape(start, end)
        state['start'] = None

def store(key, value):
    """Store value in state at key."""
    state[key] = value

state = {'start': None, 'shape': line}
setup(420, 420, 370, 0)
onscreenclick(tap)
listen()
onkey(undo, 'u')
# Colors you can choose by typing the avialable letter in Uppercase
onkey(lambda: color('black'), 'K')
onkey(lambda: color('white'), 'W')
onkey(lambda: color('green'), 'G')
onkey(lambda: color('blue'), 'B')
onkey(lambda: color('red'), 'R')
onkey(lambda: color('purple'), 'P')
onkey(lambda: color('orange'), 'O')
# Shapes you can choose by typing the avialable letters in lowercase
onkey(lambda: store('shape', line), 'l')
onkey(lambda: store('shape', square), 's')
onkey(lambda: store('shape', circle), 'c')
onkey(lambda: store('shape', rectangle), 'r')
onkey(lambda: store('shape', triangle), 't')
done()


import pygame
import random
import math
import csv, os
BLUE = (0,100,255)

class tower(pygame.sprite.Sprite):
    def __init__(self, color, height, width, x ,y):
        super().__init__()
        self.height = height
        self.width = width
        self.color = color
        self.image = pygame.Surface([height, width])
        self.image.fill(color)
        self.rect = self.image.get_rect()
        self.rect.y = y
        self.rect.x = x
        self.placed = 0
        self.radius_n = 0
        self.hit_radius = [50, 100, 150]
        self.in_radius_group = pygame.sprite.Group()
        self.tower_n = 0
        self.closest_enemy = 0
        self.cooldown = 1
        self.timer = pygame.time.get_ticks()

    def update(self):
        self.image.fill(self.color)

        """if self.cooldown == 0:
            now = pygame.time.get_ticks()
            if self.timer - now >= 2000:
                self.cooldown = 1"""

BTD 14 - Problem) all towers share one self.cooldown/Baloons TD Coursework-restart/Tower.py


# Modelo preditivo de classificaçãp para prever o valor de uma variável binária (true ou false) a partir de dados numéricos

# Import dos módulos
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
import pandas as pd
import numpy as np

# Dados de treino
n_train = 10
np.random.seed(0)
df_train = pd.DataFrame({"var1":np.random.random(n_train), \
                         "var2": np.random.random(n_train), \
                         "var3": np.random.random(n_train), \
                         "var4":np.random.randint(0,2,n_train).astype(bool),\
                         "target":np.random.randint(0,2,n_train).astype(bool)})

# Dados de treino
n_valid = 3
np.random.seed(1)
df_valid = pd.DataFrame({"var1":np.random.random(n_valid), \
                         "var2": np.random.random(n_valid), \
                         "var3": np.random.random(n_valid), \
                         "var4":np.random.randint(0,2,n_valid).astype(bool),\
                         "target":np.random.randint(0,2,n_valid).astype(bool)})
# Reduzindo a dimensionalidade para 3 componentes
pca = PCA(n_components = 3)

# Aplicando o PCA aos datasets
newdf_train = pca.fit_transform(df_train.drop("target", axis = 1))
newdf_valid = pca.transform(df_valid.drop("target", axis = 1))

# Gerando novos datasets
features_train = pd.DataFrame(newdf_train)
features_valid = pd.DataFrame(newdf_valid)

# Cria o modelo de regressão logística
regr = LogisticRegression()

# Usando o recurso de pipeline do scikit-learn para encadear 2 algoritmos em um mesmo modelo, no caso PCA e Regressão Logística
pipe = Pipeline([('pca', pca), ('logistic', regr)])
pipe.fit(features_train, df_train["target"])
predictions = pipe.predict(features_valid)

# Imprimindo as previsões
print(predictions)


def factorize_5(num):
    count, i = 0, 1

    while num > pow(5, i):
        count += num//pow(5, i)
        print(count)
        i += 1

    return count

print("The no. of 5 factors in then numbers factorial", factorize_5(260))


"""
This is a modification to Demo_start_training_proceedure.py where it repeats
the code until it finds a model with a false structure

This file read a `config.yml` file and train a network based on the settings
in that file
"""

import yaml
import shutil
import uuid
from tensorflow.keras import backend as K
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
from nn_tools import read_count
import tensorflow as tf
from Data_loader_stripe import Data_loader_stripe_train, Data_loader_stripe_test
import model_builders as mb
from SaveWeights import MyCallback
import os
from os.path import join
import matplotlib.pyplot as plt;
import numpy as np;

def data_selector(data_name, arguments):
    """ Select a data loader based on `data_name` (str).
Arguments
---------
data_name (str): Name of the data loader
arguments (dict): Dictionary given to the constructor of the data loader

Returns
-------
Data loader with name `data_name`. If not found, an error message is printed
and it returns None.
"""
    if data_name.lower() == "stripe_train":
        return Data_loader_stripe_train(arguments)
    elif data_name.lower() == "stripe_test":
        return Data_loader_stripe_test(arguments)
    else:
        print('Error: Could not find data loader with name %s' % (data_name))
        return None;

def model_selector(model_name, input_shape, output_shape, arguments):
    """ Select a model (network) based on `model_name` (str).
Arguments
---------
model_name (str): Name of the model loader
input_shape (list): List of integers specifying dimensions
output_shape (list): List of integers specifying dimensions
arguments (dict): Arguments to the model function

Returns
-------
Keras model
"""
    if model_name.lower() == "fc3":
        return mb.build_model_fc3(input_shape, output_shape, arguments)
    elif model_name.lower() == "cnndrop":
        return mb.build_model_cnndrop(input_shape, output_shape, arguments)
    elif model_name.lower() == "fc2":
        return mb.build_model_fc2(input_shape, output_shape, arguments)
    elif model_name.lower() == "fc2_cheat":
        return mb.build_model_fc2_cheat(input_shape, output_shape, arguments)
    elif model_name.lower() == "cnn2":
        return mb.build_model_cnn2(input_shape, output_shape, arguments)
    else:
        print('Error: Could not find model with name %s' % (model_name))
        return None;

if __name__ == "__main__":
    """Train a full model based on the settings in `config.yml`"""
    # Turn off unnessesary warnings
    tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)

    # Load configuration file
    with open('config.yml') as ymlfile:
        cgf = yaml.load(ymlfile, Loader=yaml.SafeLoader);

    # Set up computational resource
    use_gpu = cgf['COMPUTER_SETUP']['use_gpu']
    print("""\nCOMPUTER SETUP
Use gpu: {}""".format(use_gpu))
    if use_gpu:
        compute_node = cgf['COMPUTER_SETUP']['compute_node']
        os.environ["CUDA_VISIBLE_DEVICES"]= "%d" % (compute_node)
        print('Compute node: {}'.format(compute_node))
    else:
        os.environ["CUDA_VISIBLE_DEVICES"]= "-1"

    # Turn on soft memory allocation
    tf_config = tf.compat.v1.ConfigProto()
    tf_config.gpu_options.allow_growth = True
    tf_config.log_device_placement = False
    sess = tf.compat.v1.Session(config=tf_config)
    #K.v1.set_session(sess)

    # Load train and validatation data
    data_loader_train = data_selector(cgf['DATASET_TRAIN']['name'], cgf['DATASET_TRAIN']['arguments'])
    data_loader_validate = data_selector(cgf['DATASET_VAL']['name'], cgf['DATASET_VAL']['arguments'])
    print('\nDATASET TRAIN')
    print(data_loader_train)
    print('DATASET VALIDATION')
    print(data_loader_validate)

    train_data, train_labels = data_loader_train.load_data();
    val_data, val_labels = data_loader_validate.load_data();

    # Get input and output shape
    input_shape = train_data.shape[1:]
    output_shape = train_labels.shape[1];
    print('input_shape', input_shape)
    # Set the default precision
    model_precision = cgf['MODEL_METADATA']['precision']
    K.set_floatx(model_precision)

    # Print model information
    model_name = cgf['MODEL']['name']
    model_arguments = cgf['MODEL']['arguments']
    print("""MODEL
name: {}
arguments:""".format(model_name))
    for key, value in cgf['MODEL']['arguments'].items():
        print("\t{}: {}".format(key,value))

    # Load model
    model = model_selector(model_name, input_shape, output_shape, model_arguments)

    # Extract training information
    loss_type = cgf['TRAIN']['loss']['type']
    optimizer = cgf['TRAIN']['optim']['type']
    batch_size = cgf['TRAIN']['batch_size']
    metric_list = list(cgf['TRAIN']['metrics'].values())
    shuffle_data = cgf['TRAIN']['shuffle']
    max_epoch = cgf['TRAIN']['max_epoch']
    stpc_type = cgf['TRAIN']['stopping_criteria']['type']
    print("""\nTRAIN
loss: {}
optimizer: {}
batch size: {}
shuffle data between epochs: {}
max epoch: {}
stopping_criteria: {}""".format(loss_type, optimizer, batch_size, shuffle_data,
           max_epoch, stpc_type))

    callbacks = None
    if stpc_type.lower() == 'epoch' or stpc_type.lower() == 'epochs':
        callbacks = None
    elif stpc_type.lower() == "earlystopping" or stpc_type.lower() == "early_stopping":
        arguments = cgf['TRAIN']['stopping_criteria']['arguments']
        es = EarlyStopping(**arguments)
        callbacks = [es]
        for key, value in arguments.items():
            print('\t{}: {}'.format(key,value))
    else:
        print('Unknown stopping criteria')
        callbacks = None
    print('')
    # Compile model
    model.compile(optimizer = optimizer,
                 loss = loss_type,
                 metrics = metric_list)

    # Model metadata
    save_final_model = cgf['MODEL_METADATA']['save_final_model']
    save_best_model = cgf['MODEL_METADATA']['save_best_model']['use_model_checkpoint']
    print("""MODEL METADATA
Precision: {}
Save final model: {}""".format(model_precision, save_final_model))
    if save_final_model or save_best_model: # Get a model id

        dest_model = cgf['MODEL_METADATA']['dest_model']
        model_number_type = cgf['MODEL_METADATA']['model_number_type']
        if model_number_type.lower() == 'fixed':
            model_number = cgf['MODEL_METADATA']['model_number_arguments']['model_id']
        elif model_number_type.lower() == 'count':
            counter_path =\
                cgf['MODEL_METADATA']['model_number_arguments']['counter_path']
            model_number = read_count(counter_path);
        elif model_number_type.lower() == 'uuid':
            model_number = uuid.uuid1().int
        else:
            model_number = -1;

        full_dest_model = join(dest_model, str(model_number))
        if not os.path.isdir(dest_model):
            os.mkdir(dest_model)
        if not os.path.isdir(full_dest_model):
            os.mkdir(full_dest_model)
        else:
            print('Delete all content in the folder: \n{}'.format(full_dest_model))
            shutil.rmtree(full_dest_model);
            os.mkdir(full_dest_model)
        shutil.copyfile('config.yml', join(full_dest_model, 'config.yml'))
        shutil.copyfile('model_builders.py', join(full_dest_model, 'model_builders.py'))
        print("""Model nbr type: {}
Model number: {}
Model dest: {}""".format(model_number_type, model_number, dest_model))

    print('Save best model: {}'.format(save_best_model))

    '''
    if save_best_model:
        arguments = cgf['MODEL_METADATA']['save_best_model']['arguments']
        for key, value in arguments.items():
            print('\t{}: {}'.format(key,value))

        filename = arguments['filepath']
        arguments['filepath'] = join(full_dest_model, filename)
        mc = ModelCheckpoint(arguments['filepath'], monitor=arguments['monitor'], verbose=arguments['verbose'], save_best_only=False, save_weights_only=True, mode=arguments['mode'], period=arguments['period'])
        if callbacks is None:
            callbacks = mc
        elif type(callbacks) is list: # Is a list
            callbacks.append(mc)
        else:
            callbacks = mc
            print('ERROR: Unknown callback type')
    '''
    '''
    # We save weights after each epoch
    if callbacks == None:
        callbacks =[]
    mycallback = MyCallback()
    callbacks.append(mycallback)
    '''

    print('\nStart training the model\n')
    # Train model :)
    print(shuffle_data)
    print(callbacks)

    data_loader_test = data_selector(cgf['DATASET_TEST']['name'], cgf['DATASET_TEST']['arguments'])
    test_data, test_labels = data_loader_test.load_data()
    optimal = 0

    while optimal < 0.9  :
        model = model_selector(model_name, input_shape, output_shape, model_arguments)
        model.compile(optimizer = optimizer,
                      loss = loss_type,
                      metrics = metric_list)
        history = model.fit(train_data, train_labels,
                  epochs=max_epoch,
                  batch_size=batch_size,
                  validation_data=(val_data, val_labels),
                  shuffle=shuffle_data,
                  callbacks = callbacks)

        score = model.evaluate(test_data, test_labels, verbose=0)
        optimal = score[1]

    if save_final_model:
        full_file_name = join(full_dest_model, 'keras_model_files.h5')
        model.save(join(full_dest_model, 'keras_model_files.h5'), save_format='h5')
        print('Saved model as {}'.format(full_file_name))

    # plot the loss history
    plt.figure()
    loss_hist = history.history['loss'][int(max_epoch/2):]
    index = np.linspace(max_epoch/2+1, max_epoch, max_epoch/2);
    plt.plot(index,loss_hist);
    plt.savefig(join(full_dest_model, 'loss_graph.png'));
    # Load and test model on test set

    print('\nDATASET TEST')
    print(data_loader_test)

    score = model.evaluate(test_data, test_labels, verbose=0)
    print('Accuracy on test set: {}%'.format(100*score[1]))


from yowsup.structs import  ProtocolTreeNode
from .iq import IqProtocolEntity
class ErrorIqProtocolEntity(IqProtocolEntity):

    '''<iq id="1417113419-0" from="{{jid}}" type="error">
    <error text="not-acceptable" code="406" backoff="3600">
    </error>
    </iq>
    '''

    def __init__(self, _id, _from, code, text, backoff= 0 ):
        super(ErrorIqProtocolEntity, self).__init__(xmlns = None, _id = _id, _type = "error", _from = _from)
        self.setErrorProps(code, text, backoff)

    def setErrorProps(self, code, text, backoff):
        self.code = int(code)
        self.text = text
        self.backoff = int(backoff) if backoff else 0

    def toProtocolTreeNode(self):
        node = super(ErrorIqProtocolEntity, self).toProtocolTreeNode()
        errorNode = ProtocolTreeNode("error", {"text": self.text, "code": str(self.code)})
        if self.backoff:
            errorNode.setAttribute("backoff", str(self.backoff))
        node.addChild(errorNode)
        return node

    @staticmethod
    def fromProtocolTreeNode(node):
        entity = IqProtocolEntity.fromProtocolTreeNode(node)
        entity.__class__ = ErrorIqProtocolEntity
        errorNode = node.getChild("error")
        entity.setErrorProps(errorNode.getAttributeValue("code"),
                             errorNode.getAttributeValue("text"),
                             errorNode.getAttributeValue("backoff"))
        return entity


from pyramid.view import view_config
from pyramid.httpexceptions import HTTPFound

from .                    import web, method_delete_router
from ..lib.auto_format    import action_ok
from ..templates.helpers  import search_url

#-------------------------------------------------------------------------------
# Faves
#-------------------------------------------------------------------------------

@view_config(route_name='fave', request_method='GET')
@web
def fave_view(request):
    """
    view current faves

    not really needed as faves are also part of the identity dict
    """
    trackids = request.session['faves']

    if request.matchdict['format']=='html':
        raise HTTPFound(location=search_url(trackids=trackids,route='search_list'))

    return action_ok(
        data={'faves':trackids}
    )

@view_config(route_name='fave', request_method='POST')
@web
def fave_add(request):
    """
    Add item to faves in session
    """
    if 'faves' not in request.session:
        request.session['faves'] = []
    request.session['faves'].append(request.params['id'])
    return action_ok(message='added to faves')

@view_config(route_name='fave', custom_predicates=(method_delete_router, lambda info,request: request.params.get('id'))) #request_method='DELETE'
@web
def fave_del(request):
    """
    Remove fave from session
    """
    request.session['faves'].remove(request.params['id'])
    return action_ok(message='removed from faves')


# -*- coding：utf-8 -*-

import numpy as np
import pandas as pd
import os
from sklearn.preprocessing import MinMaxScaler
import matplotlib.pyplot as plt
import time

def sample_label_trans(sample_label_state, sample_label_cognitive):
# 第一列是ad的标签
# 第二列是nad的标签
# 第三列是认知得分1的标签
# 第四列是认知得分2的标签
# 第五列是认知得分3的标签
# 第六列是认知得分4的标签
# 第七列是认知得分5的标签
# 第八列是认知得分6的标签

    true_matrix = np.zeros((596, 8))

    for i in range(len(sample_label_state)):
        if sample_label_state[i] == 1:
            true_matrix[i, 0] = 1
        if sample_label_state[i] == 0:
            true_matrix[i, 1] = 1
        if sample_label_cognitive[i] == 0:
            true_matrix[i, 2] = 1
        if sample_label_cognitive[i] == 1:
            true_matrix[i, 3] = 1
        if sample_label_cognitive[i] == 2:
            true_matrix[i, 4] = 1
        if sample_label_cognitive[i] == 3:
            true_matrix[i, 5] = 1
        if sample_label_cognitive[i] == 4:
            true_matrix[i, 6] = 1
        if sample_label_cognitive[i] == 5:
            true_matrix[i, 7] = 1

    return true_matrix

def compute_H(m):

    H = np.zeros((596, 596))

    for i in range(596):
        for j in range(596):
            if i == j:
                H[i, j] = 1 - 1.0/596
            else:
                H[i, j] = - 1.0/596

    return H

def compute_XHYYHX(X, H, Y):

    X_t = X.T
    Y_t = Y.T

    result_1 = np.dot(X_t, H)
    result_2 = np.dot(result_1, Y)
    result_3 = np.dot(result_2, Y_t)
    result_4 = np.dot(result_3, H)
    result_5 = np.dot(result_4, X)

    return result_5

def select_plot(P):
    # 画出每一列（即每一列的置信性得分从大到小的排名）

    class_1 = P[:, 0]
    class_2 = P[:, 1]
    class_3 = P[:, 2]
    class_4 = P[:, 3]
    class_5 = P[:, 4]
    class_6 = P[:, 5]
    class_7 = P[:, 6]
    class_8 = P[:, 7]

    # 按从大到小进行排序
    class_1_sort = abs(np.sort(-abs(class_1)))
    class_2_sort = abs(np.sort(-abs(class_2)))
    class_3_sort = abs(np.sort(-abs(class_3)))
    class_4_sort = abs(np.sort(-abs(class_4)))
    class_5_sort = abs(np.sort(-abs(class_5)))
    class_6_sort = abs(np.sort(-abs(class_6)))
    class_7_sort = abs(np.sort(-abs(class_7)))
    class_8_sort = abs(np.sort(-abs(class_8)))

    # 作图，可视化置信得分的排名曲线图
    plt.figure(1)
    plt.subplot(241)
    plt.plot(class_1_sort[:1000], 'k')
    plt.xlabel('Ranking')
    plt.ylabel('Probability (confidence score)')
    plt.ylim(0, 0.1)
    plt.title('AD')

    plt.subplot(242)
    plt.plot(class_2_sort[:1000], 'k')
    plt.xlabel('Ranking')
    # plt.ylabel('Probability (confidence score)')
    plt.ylim(0, 0.1)
    plt.title('non-AD')

    plt.subplot(243)
    plt.plot(class_3_sort[:1000], 'k')
    plt.xlabel('Ranking')
    # plt.ylabel('Probability (confidence score)')
    plt.ylim(0, 0.1)
    plt.title('Cognitive score = 1')

    plt.subplot(244)
    plt.plot(class_4_sort[:1000], 'k')
    plt.xlabel('Ranking')
    # plt.ylabel('Probability (confidence score)')
    plt.ylim(0, 0.1)
    plt.title('Cognitive score = 2')

    plt.subplot(245)
    plt.plot(class_5_sort[:1000], 'k')
    plt.xlabel('Ranking')
    plt.ylabel('Probability (confidence score)')
    plt.ylim(0, 0.1)
    plt.title('Cognitive score = 3')

    plt.subplot(246)
    plt.plot(class_6_sort[:1000], 'k')
    plt.xlabel('Ranking')
    # plt.ylabel('Probability (confidence score)')
    plt.ylim(0, 0.1)
    plt.title('Cognitive score = 4')

    plt.subplot(247)
    plt.plot(class_7_sort[:1000], 'k')
    plt.xlabel('Ranking')
    # plt.ylabel('Probability (confidence score)')
    plt.ylim(0, 0.1)
    plt.title('Cognitive score = 5')

    plt.subplot(248)
    plt.plot(class_8_sort[:1000], 'k')
    plt.xlabel('Ranking')
    # plt.ylabel('Probability (confidence score)')
    plt.ylim(0, 0.1)
    plt.title('Cognitive score = 6')
    plt.show()

def select_key_gene(P, isoform_name):
    class_1 = P[:, 0]
    class_2 = P[:, 1]
    class_3 = P[:, 2]
    class_4 = P[:, 3]
    class_5 = P[:, 4]
    class_6 = P[:, 5]
    class_7 = P[:, 6]
    class_8 = P[:, 7]

    class_1_key_gene = []
    class_2_key_gene = []
    class_3_key_gene = []
    class_4_key_gene = []
    class_5_key_gene = []
    class_6_key_gene = []
    class_7_key_gene = []
    class_8_key_gene = []

    print("the length of confidence score", len(class_1))
    print("the length of isoform name", len(isoform_name))

    index_1 = np.argsort(-abs(class_1))
    index_2 = np.argsort(-abs(class_2))
    index_3 = np.argsort(-abs(class_3))
    index_4 = np.argsort(-abs(class_4))
    index_5 = np.argsort(-abs(class_5))
    index_6 = np.argsort(-abs(class_6))
    index_7 = np.argsort(-abs(class_7))
    index_8 = np.argsort(-abs(class_8))

    for i in index_1[:200]:
        class_1_key_gene.append(isoform_name[i])
    for i in index_2[:200]:
        class_2_key_gene.append(isoform_name[i])
    for i in index_3[:200]:
        class_3_key_gene.append(isoform_name[i])
    for i in index_4[:200]:
        class_4_key_gene.append(isoform_name[i])
    for i in index_5[:200]:
        class_5_key_gene.append(isoform_name[i])
    for i in index_6[:200]:
        class_6_key_gene.append(isoform_name[i])
    for i in index_7[:200]:
        class_7_key_gene.append(isoform_name[i])
    for i in index_8[:200]:
        class_8_key_gene.append(isoform_name[i])

    class_1_key_gene = np.array(class_1_key_gene)
    class_2_key_gene = np.array(class_2_key_gene)
    class_3_key_gene = np.array(class_3_key_gene)
    class_4_key_gene = np.array(class_4_key_gene)
    class_5_key_gene = np.array(class_5_key_gene)
    class_6_key_gene = np.array(class_6_key_gene)
    class_7_key_gene = np.array(class_7_key_gene)
    class_8_key_gene = np.array(class_8_key_gene)

    key_gene = np.hstack((class_1_key_gene, class_2_key_gene))
    key_gene = np.hstack((key_gene, class_3_key_gene))
    key_gene = np.hstack((key_gene, class_4_key_gene))
    key_gene = np.hstack((key_gene, class_5_key_gene))
    key_gene = np.hstack((key_gene, class_6_key_gene))
    key_gene = np.hstack((key_gene, class_7_key_gene))
    key_gene = np.hstack((key_gene, class_8_key_gene))
    col_names = ['ad key genes', 'ad key genes', 'nad key genes', 'nad key genes', 'cs1 key genes', 'cs1 key genes', 'cs2 key genes', 'cs2 key genes', 'cs3 key genes', 'cs3 key genes', 'cs4 key genes', 'cs4 key genes', 'cs5 key genes', 'cs5 key genes', 'cs6 key genes', 'cs6 key genes']
    col_names = np.array(col_names).reshape(1, len(col_names))
    key_gene = np.vstack((col_names, key_gene))

    return key_gene

def main():
    # 读入数据
    os.chdir('/Users/xuejiang/PycharmProjects/isofom_/data/')
    # ========= Step 1. 读入数据 ===========
    isoform_expression_df = pd.read_csv('select_isoform_express.csv')
    isoform_expression = isoform_expression_df.as_matrix()
    isoform_express = isoform_expression[:, 2:]
    isoform_express = isoform_express.T
    isoform_name = isoform_expression[:, :2]
    # 对每一列数据进行归一化处理
    scaler = MinMaxScaler()
    isoform_express_scaled = scaler.fit_transform(isoform_express)

    sample_label_df = pd.read_csv('sample_label.csv')
    sample_label = sample_label_df.as_matrix()
    sample_name = sample_label[:, 0]
    sample_label_state = sample_label[:, 1]
    sample_label_cognitive = sample_label[:, 2]

    true_label = sample_label_trans(sample_label_state, sample_label_cognitive)

    print(true_label.shape)
    print(sum(true_label))
    start_time_all = time.clock()
    H = compute_H(596)
    matrix = compute_XHYYHX(isoform_express_scaled, H, true_label)

    r,c = matrix.shape
    new_matrix = matrix
    for i in range(r):
        for j in range(c):
            new_matrix[i, j] = round(matrix[i,j], 5)

    eigenvalues, eigenvectors = np.linalg.eig(new_matrix)

    print(eigenvalues.shape)
    print(eigenvectors.shape)

    index = np.argsort(-eigenvalues)
    print(index)
    update_eigenvectors = []
    for i in index[:8]:
        update_eigenvectors.append(eigenvectors[:, i])
        print(eigenvalues[i])

    update_eigenvectors = np.array(update_eigenvectors)
    print(update_eigenvectors.shape)
    update_eigenvectors = update_eigenvectors.T
    print(update_eigenvectors.shape)

    select_plot(eigenvectors)

    key_genes = select_key_gene(update_eigenvectors, isoform_name)

    stop_time_all = time.clock()
    cost = stop_time_all - start_time_all

    # 保存结果
    cost = [cost, cost]
    cost = np.array(cost)
    cost_df = pd.DataFrame(data=cost)
    cost_df.to_csv('/Users/xuejiang/PycharmProjects/isofom_/result/MLL/time_cost_1.csv')

    key_genes_df = pd.DataFrame(data=key_genes)
    key_genes_df.to_csv('/Users/xuejiang/PycharmProjects/isofom_/result/MLL/key_genes.csv')

if __name__ == '__main__':
    main()


#!/usr/bin/env python3

from fractions import Fraction as F
import math
from .input import get_input
from IPython.terminal.embed import InteractiveShellEmbed
import matplotlib.pyplot as plt

class Field:
    def __init__(self, mapdata):
        self.asteroids = set()
        for i, line in enumerate(mapdata):
            for j, v in enumerate(line):
                if v == '#':
                    self.asteroids.add((j, i))

    def line_of_sight(self, a, b):
        # print integer coordinates on line of site from a to b
        ax, ay = a
        bx, by = b
        dy = by - ay
        dx = bx - ax
        k = math.gcd(dy, dx)
        dy //= k
        dx //= k
        for i in range(1,k):
            yield (ax + i*dx, ay + i*dy)

    def visible_from(self, a, b):
        return not any(pt in self.asteroids for pt in self.line_of_sight(a, b))

    def visible(self, a):
        N = 0
        for b in self.asteroids - set([a]):
            if not self.visible_from(a, b):
                continue
            N += 1
        return N

    def vaporize_order(self, a):
        order = []
        def sorter(b):
            dx = b[0] - a[0]
            dy = b[1] - a[1]
            return (-math.atan2(dx, dy), dx**2 + dy**2)
        while len(self.asteroids) > 1:
            for b in sorted(self.asteroids - set([a]) - set(order), key = sorter):
                if self.visible_from(a, b):
                    order.append(b)
            self.asteroids -= set(order)
        return order

def test(args):
    field = Field('.#..#\n.....\n#####\n....#\n...##'.split('\n'))
    assert max(field.asteroids, key = field.visible) == (3,4)
    field = Field("""......#.#.
#..#.#....
..#######.
.#.#.###..
.#..#.....
..#....#.#
#..#....#.
.##.#..###
##...#..#.
.#....####
""".split('\n'))
    assert max(field.asteroids, key = field.visible) == (5,8)
    field = Field(""".#..##.###...#######
##.############..##.
.#.######.########.#
.###.#######.####.#.
#####.##.#.##.###.##
..#####..#.#########
####################
#.####....###.#.#.##
##.#################
#####.##.###..####..
..######..##.#######
####.##.####...##..#
.#####..#.######.###
##...#.##########...
#.##########.#######
.####.#.###.###.#.##
....##.##.###..#####
.#.#.###########.###
#.#.#.#####.####.###
###.##.####.##.#..##""".split('\n'))
    assert field.vaporize_order((11,13))[199] == (8,2)
    print('Tests passed')

def main(args):
    field = Field(get_input(args.YEAR, args.DAY))
    pt = max(field.asteroids, key = field.visible)
    print(field.visible(pt))
    bet = field.vaporize_order(pt)[199]
    print(bet[0]*100+bet[1])


from os import system, name
from time import sleep

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

def texto_pausado(texto,tiempo):
    for i in range(len(texto)):
        print(texto[i], sep='', end='', flush=True); sleep(tiempo)

def clear():
    # windows
    if name == 'nt':
        _ = system('cls')
    # mac and linux
    else:
        _ = system('clear')

clear()

def entrada_real(numero):
    try:
        entrada = float(numero)
    except:
        print("Por favor introduzca una entrada válida.")
        exit()
    return entrada

_run = True
while _run:

    print("----- GRAFICADORA -----\n")

    texto_pausado("(1) Graficar tiempo real\n",0.025)
    texto_pausado("(2) Mover parámetros\n",0.025)
    texto_pausado("(3) Salir\n",0.025)

    opcion = input("> ")

    clear()

    if opcion == '1':

        TIEMPO = []
        THETA = []

        print("----- Graficar en tiempo real -----\n")

        k = entrada_real(input("Constante del resorte de torsión: "))
        A = entrada_real(input("Área de la espira: "))
        B = entrada_real(input("Intensidad de campo magnético: "))
        R = entrada_real(input("Resistencia de la espira: "))
        I = entrada_real(input("Momento de incercia de la espira: "))
        t = entrada_real(input("Tiempo: "))

        def calcular_thetadpt(ang, vel):
            ac_ang = (- k * ang )/I - (((A*B)**2)* ((np.cos(ang)) ** 2) * vel) / (R*I) # Cálculo de la aceleración angular según la ecuación diferencial
            return ac_ang

        def f(tiempo):
            # Valores iniciales
            theta = 1.
            thetapt = 0.
            dt = 0.01 # Paso

            for i in np.arange(0,tiempo,dt):
                TIEMPO.append(i) # Se adjunta el segundo a una lista

                thetadpt = calcular_thetadpt(theta, thetapt) # Se calcula la aceleración angular según las variables
                thetapt += thetadpt * dt # Como thetapt = d/dt (thetapt), theta_f = thetapt_i + thetadpt * dt, aprox
                theta += thetapt * dt # Como thetapt = d/dt (theta), theta_f = thetapt_i + thetadpt * dt, aprox
                THETA.append(theta)

            return theta # Le agregué esto

        # FIGURA 1

        fig1 = plt.figure()
        fig1.canvas.set_window_title('Oscilador')
        ax1 = fig1.add_subplot(111)

        ax1.grid(linestyle = "--")
        ax1.set_facecolor('#000000')

        y_fig1 = f(t)
        cuadros = 1. / 20

        def animacion1(i):
            j = int(i / (1./20))
            if j < 101:
                t = TIEMPO[0:j]
                th = THETA[0:j]
                a = TIEMPO[0]
                b = TIEMPO[200]
            else:
                t = TIEMPO[j-100:j]
                th = THETA[j-100:j]
                a = TIEMPO[j-100]
                b = TIEMPO[j+100]
            ax1.set_xlim(a,b) # Límites de la gráfica
            ax1.set_ylim(-2,2)
            linea, = ax1.plot(t, th, "#05d2ed")
            return linea

        animation1 = FuncAnimation(fig1, func=animacion1, frames=np.arange(0, 100, (1./20)),interval = t) # Altérese el denominador del paso para cambiar los fps

        # FIGURA 2

        # Se definen dos listas que serán las entradas en X y en Y de los extremos del oscilador
        x = [0,0]
        y = [0,0]

        fig2 = plt.figure()
        fig1.canvas.set_window_title('Espira')

        ax2 = fig2.add_subplot(111)
        ax2.set_facecolor('#000000')

        # Límites de la gráfica
        ax2.set_xlim(-2,2)
        ax2.set_ylim(-2,2)

        # Recta que hará de oscilador
        linea, = ax2.plot(0, 0, "#ede505")

        # Recta horizontal
        plt.axhline(0,-2,2,color="gray",linestyle="--")

        def animacion2(i):
            # Se definen las coordenadas de los extremos
            x1 = np.cos(f(i))
            y1 = np.sin(f(i))
            x2 = -np.cos(f(i))
            y2 = -np.sin(f(i))

            # Se alteran las entradas de las listas que definen los extremos de acuerdo a los valores recién calculados

            x[0] = x1
            y[0] = y1

            x[1] = x2
            y[1] = y2

            linea.set_xdata(x) # Se dan los extremos en x del oscilador
            linea.set_ydata(y) # Se dan los extremos en y del oscilador

            return linea

        animation2 = FuncAnimation(fig2, func=animacion2, frames=np.arange(0, 100, (1./60)),interval = t)

        plt.show()

        clear()

    elif opcion == '2':

        from matplotlib.widgets import Slider, Button, RadioButtons

        print("----- Mover parámetros -----\n")

        k_0 = 1.
        A_0 = 1.
        B_0 = 1.
        R_0 = 1.
        I_0 = 1.
        temp = entrada_real(input("Tiempo: "))

        def f(k, A, B, R, I):
            TIEMPO =[]
            THETA = []
            # Valores iniciales
            theta = 1.
            thetapt = 0.
            dt = 0.001 # Paso

            for i in np.arange(0.0, temp, dt):
                TIEMPO.append(i)

                # Se calcula la aceleración angular según las variables
                thetadpt = (- k * theta )/I - (((A*B)**2)* ((np.cos(theta)) ** 2) * thetapt) / (R*I)

                thetapt += thetadpt * dt # Como thetapt = d/dt (thetapt), theta_f = thetapt_i + thetadpt * dt, aprox
                theta += thetapt * dt # Como thetapt = d/dt (theta), theta_f = thetapt_i + thetadpt * dt, aprox
                THETA.append(theta)

            return np.asarray(THETA)

        fig = plt.figure()
        fig.canvas.set_window_title('Oscilador')

        ax = fig.add_subplot(111)
        ax.set_facecolor('#000000')

        fig.subplots_adjust(bottom=0.4)

        t = np.arange(0.0, temp, 0.001)

        # Gráfica inicial
        y = f(k_0, A_0, B_0, R_0, I_0)
        [linea] = ax.plot(t, y, linewidth=2, color='red')
        ax.set_xlim([0, temp])
        ax.set_ylim([-max(y)-1, max(y)+1])

        # k
        k_deslizador_ax  = fig.add_axes([0.1, 0.25, 0.65, 0.03])
        k_deslizador = Slider(k_deslizador_ax, r'$k$', 0.1, 100, valinit=k_0)

        # A
        A_deslizador_ax = fig.add_axes([0.1, 0.20, 0.65, 0.03])
        A_deslizador = Slider(A_deslizador_ax, r'$A$', 0.1, 50, valinit=A_0)

        # B
        B_deslizador_ax = fig.add_axes([0.1, 0.15, 0.65, 0.03])
        B_deslizador = Slider(B_deslizador_ax, r'$B$', 0.1, 50, valinit=B_0)

        # R
        R_deslizador_ax = fig.add_axes([0.1, 0.10, 0.65, 0.03])
        R_deslizador = Slider(R_deslizador_ax, r'$R$', 0.1, 100, valinit=R_0)

        # I
        I_deslizador_ax = fig.add_axes([0.1, 0.05, 0.65, 0.03])
        I_deslizador = Slider(I_deslizador_ax, r'$I$', 0.1, 100, valinit=I_0)

        # Modifica la línea cuando un valor de cualquier deslizador cambia
        def cambio_deslizadores(val):
            linea.set_ydata(f(k_deslizador.val, A_deslizador.val, B_deslizador.val, R_deslizador.val, I_deslizador.val))
            fig.canvas.draw_idle()

        k_deslizador.on_changed(cambio_deslizadores)
        A_deslizador.on_changed(cambio_deslizadores)
        B_deslizador.on_changed(cambio_deslizadores)
        R_deslizador.on_changed(cambio_deslizadores)
        I_deslizador.on_changed(cambio_deslizadores)

        # Botón para reiniciar los parámetros
        boton_reinicio_ax = fig.add_axes([0.85, 0.075, 0.1, 0.04])
        boton_reinicio = Button(boton_reinicio_ax, 'Reiniciar', hovercolor='0.975')
        def reinicio_boton(mouse_event):
            k_deslizador.reset()
            A_deslizador.reset()
            B_deslizador.reset()
            R_deslizador.reset()
            I_deslizador.reset()

        boton_reinicio.on_clicked(reinicio_boton)

        plt.show()

    elif opcion == '3':
        _run = False

    else:
        texto_pausado("Por favor, introduzca una opción válida\n", 0.05)
        texto_pausado(" ",0.8)
        clear()

clear()
exit()


import glob as gb
import os
import xlwings as xw
import shutil

#os.chdir(r"C:\Users\msweeney\Desktop\MS EM Tools\Python\Python Scripts\Sample SIMs\Sample hsr")

def hsrtocsv():

	hsrfiles = gb.glob('./*.hsr')

	for h in hsrfiles:
		if os.path.isfile(h[:-4] + '.csv'):
			os.remove(h[:-4] + '.csv')

		shutil.copy(h,h[:-4]+".csv")

		wb = xw.Book(h[:-4] + '.csv')
		wb.close()

if __name__ == "__main__":
	hsrtocsv()


#!/usr/bin/env python3

from Bio import SeqIO
import tompltools

# expect input fq and output fq
parsed_args = tompltools.parse_cli_arguments()

if parsed_args.input_fa:
    print('input_fa:\t%s' % parsed_args.input_fa)
    unsorted_fa = parsed_args.input_fa[0]
else:
    raise TypeError("input_fa not specified (-f)")
if parsed_args.output_fa:
    print('output_fa:\t%s' % parsed_args.output_fa)
    sorted_fasta = parsed_args.output_fa[0]
else:
    raise TypeError("output_fa not specified (--g)")

# make a sorted list of tuples of scaffold name and sequence length
print("Parsing read lengths")
length_id_unsorted = ((len(rec), rec.id) for
                      rec in SeqIO.parse(unsorted_fa, 'fasta'))
length_and_id = sorted(length_id_unsorted)

# get an iterator sorted by read length
print("Sorting reads by length")
longest_to_shortest = reversed([id for (length, id) in length_and_id])

# release scaffolds_file from memory
del(length_and_id)

# build an index of the fasta file
print("Indexing %s by read name" % unsorted_fa)
record_index = SeqIO.index(unsorted_fa, 'fasta')

# write selected records in correct order to disk
print("Ordering records")
ordered_records = (record_index[id] for id in longest_to_shortest)
print("Writing sorted fasta to %s" % sorted_fasta)
SeqIO.write(sequences=ordered_records,
            handle=sorted_fasta,
            format='fasta')


# 16/10/03 12:31:54 INFO ControllerJob: NOMINAL RECORD/S STAGE ID 1 : 3671965.1777167222

import glob

import matplotlib.pyplot as plt
import numpy as np

def mean_nominalrate(fold):
    stageDict = {}
    count = 0
    print(fold)
    for folder in glob.glob(fold + "/*"):
        print(folder)
        for file in glob.glob(folder + "/*.dat"):
            with open(file) as f:
                print(file)
                count += 1
                for line in f:
                    l = line.split(" ")
                    if len(l) > 4 and l[4] == "NOMINAL" and l[5] == "RECORD/S":
                        try:
                            print(l[-3], float(l[-1]))
                            stageDict[l[-3]]["nominalrate"].append(float(l[-1]))
                        except KeyError:
                            stageDict[l[-3]] = {}
                            stageDict[l[-3]]["nominalrate"] = []
                            stageDict[l[-3]]["nominalrate"].append(float(l[-1]))

    print(stageDict)
    with open(fold + "/result.txt", "w") as out:
        for id in sorted(stageDict.keys()):
            out.write(
                "SID " + str(id) + " MEAN " + str(np.mean(stageDict[id]["nominalrate"])) + "\n")
            out.write("SID " + str(id) + " STD " + str(np.std(stageDict[id]["nominalrate"])) + "\n")
            out.write("SID " + str(id) + " MIN " + str(np.min(stageDict[id]["nominalrate"])) + "\n")
            out.write("SID " + str(id) + " MAX " + str(np.max(stageDict[id]["nominalrate"])) + "\n")
            out.write("\n")
            out.write("SID " + str(id) + " % " + str((
                                                     np.std(stageDict[id]["nominalrate"]) / np.mean(
                                                         stageDict[id][
                                                             "nominalrate"])) * 100) + "\n")
            out.write("\n")
            stageDict[id]["nominalrate"] = np.mean(stageDict[id]["nominalrate"])

    print(stageDict)

output_folder = "./results/OK/PageRank/Profiling-NominalRate/"
# output_folder = "./spark-bench/num/app-20161013104553-0000"
import os

for dirpath, dirnames, files in os.walk(output_folder):
    for dir in dirnames:
        mean_nominalrate(dirpath + "/" + dir)
    break

nominalrate_dict = {}
mini_dict = {}
max_dict = {}
mean_dict = {}
for dirpath, dirnames, files in os.walk(output_folder):
    for dir in dirnames:
        nominalrate_dict[dir] = {}
        mini_dict[dir] = {}
        max_dict[dir] = {}
        mean_dict[dir] = {}
        with open(dirpath + "/" + dir + "/result.txt") as f:
            # SID 13 % 19.7066924684
            for line in f:
                l = line.split(" ")
                if len(l) > 1 and l[-2] == "%":
                    nominalrate_dict[dir][int(l[1])] = float(l[-1].replace("\n", ""))
                if len(l) > 1 and l[-2] == "MIN":
                    mini_dict[dir][int(l[1])] = float(l[-1].replace("\n", ""))
                if len(l) > 1 and l[-2] == "MAX":
                    max_dict[dir][int(l[1])] = float(l[-1].replace("\n", ""))
                if len(l) > 1 and l[-2] == "MEAN":
                    mean_dict[dir][int(l[1])] = float(l[-1].replace("\n", ""))
    break

print(nominalrate_dict)

for dirpath, dirnames, files in os.walk(output_folder):
    for dir in dirnames:
        data = []
        for key in nominalrate_dict[dir].keys():
            data.append((key, nominalrate_dict[dir][key]))
        data.sort(key=lambda x: x[0])
        print(data)
        plt.plot([x[0] for x in data], [x[1] for x in data])
    plt.legend(dirnames)
    break
plt.ylabel('% std dev')
plt.xlabel("Stage ID")
plt.savefig(output_folder + "result.png")
plt.close()

for dirpath, dirnames, files in os.walk(output_folder):
    legend = []
    for dir in dirnames:
        if dir == "6EXEC-NOHDFS" or dir == "12EXEC-NOHDFS":
            legend.append(dir)
            data = []
            for key in mini_dict[dir].keys():
                data.append((key, mini_dict[dir][key]))
            data.sort(key=lambda x: x[0])
            print(data)
    plt.legend(legend)
    break
plt.ylabel('MIN DIFF')
plt.xlabel("Stage ID")
plt.savefig(output_folder + "min.png")
plt.close()

A = "6EXEC-6DATANODE"
B = "12EXEC-6DATANODE"
print("\nMIN")
for key in mini_dict[A].keys():
    diff = mini_dict[A][key] - mini_dict[B][key]
    print(str(key) + " " + str(diff / min(mini_dict[A][key], mini_dict[B][key]) * 100))

print("\nMEAN")
for key in mean_dict[A].keys():
    diff = mean_dict[A][key] - mean_dict[B][key]
    print(str(key) + " " + str(diff / min(mean_dict[A][key], mean_dict[B][key]) * 100))

print("\nMAX")
for key in max_dict[A].keys():
    diff = max_dict[A][key] - max_dict[B][key]
    print(str(key) + " " + str(diff / min(max_dict[A][key], max_dict[B][key]) * 100))


import os

from ament_index_python.packages import get_package_share_directory

from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument
from launch.actions import IncludeLaunchDescription
from launch.conditions import LaunchConfigurationEquals
from launch.conditions import LaunchConfigurationNotEquals
from launch.launch_description_sources import AnyLaunchDescriptionSource
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node

def generate_launch_description():
    pkg_ros_gz_sim = get_package_share_directory('ros_gz_sim')
    remaro_worlds_path = get_package_share_directory('remaro_worlds')
    min_pipes_launch_path = os.path.join(
        remaro_worlds_path, 'launch', 'small_min_pipes.launch.py')

    gui = LaunchConfiguration('gui')
    gui_arg = DeclareLaunchArgument(
        'gui',
        default_value='true',
        description='Run with gui (true/false)')

    min_pipes_sim = IncludeLaunchDescription(
        AnyLaunchDescriptionSource(min_pipes_launch_path),
        launch_arguments={
           'gui': gui
        }.items()
    )

    mavros_path = get_package_share_directory('mavros')
    mavros_launch_path = os.path.join(
        mavros_path, 'launch', 'apm.launch')
    mavros_node = IncludeLaunchDescription(
        AnyLaunchDescriptionSource(mavros_launch_path),
        launch_arguments={
            'fcu_url': 'udp://127.0.0.1:14551@14555',
            'gcs_url': 'udp://@localhost:14550',
            'system_id': '255',
            'component_id': '240',
            'target_system_id': '1',
            'target_component_id': '1'
            }.items()
        )

    bluerov2_ignition_path = get_package_share_directory('bluerov2_ignition')
    bluerov2_path = os.path.join(
        bluerov2_ignition_path, 'models', 'bluerov2')

    gz_pipe_pose_bridge = Node(
        package='ros_gz_bridge',
        executable='parameter_bridge',
        arguments=['/model/min_pipes_pipeline/pose@geometry_msgs/msg/PoseArray@gz.msgs.Pose_V'],
        output='screen',
        name='gz_pipe_pose_bridge',
    )

    x = LaunchConfiguration('x')
    y = LaunchConfiguration('y')
    z = LaunchConfiguration('z')

    x_arg = DeclareLaunchArgument(
        'x',
        default_value='-17.0',
        description='Initial x coordinate for bluerov2'
    )

    y_arg = DeclareLaunchArgument(
        'y',
        default_value='2.0',
        description='Initial y coordinate for bluerov2'
    )

    z_arg = DeclareLaunchArgument(
        'z',
        default_value='-18.5',
        description='Initial z coordinate for bluerov2'
    )

    gz_bluerov_pose_bridge = Node(
        package='ros_gz_bridge',
        executable='parameter_bridge',
        arguments=['/model/bluerov2/pose@geometry_msgs/msg/Pose@gz.msgs.Pose'],
        output='screen',
        name='gz_bluerov_pose_bridge',
    )

    bluerov_spawn = Node(
        package='ros_gz_sim',
        executable='create',
        arguments=[
            '-v4',
            '-g',
            '-world', 'min_pipes',
            '-file', bluerov2_path,
            '-name', 'bluerov2',
            '-x', x,
            '-y', y,
            '-z', z,
            '-Y', '0']
    )

    return LaunchDescription([
        gui_arg,
        x_arg,
        y_arg,
        z_arg,
        min_pipes_sim,
        bluerov_spawn,
        gz_pipe_pose_bridge,
        gz_bluerov_pose_bridge,
        mavros_node,
    ])


"""Rebuild the test data that compares Skyfield to the NOVAS library."""

from __future__ import print_function
from itertools import product
from sys import exit
from textwrap import dedent

try:
    from novas import compat as novas
    import novas_de405
except ImportError:
    print(dedent("""\
        Error: to rebuild NOVAS test data, you must install both the "novas"
        package and its default ephemeris:

        pip install novas novas_de405

        """))
    exit(2)

from novas.compat import eph_manager
from novas.constants import ASEC2RAD, T0
nutation_function = novas.nutation
import novas.compat.nutation as nutation_module

one_second = 1.0 / 24.0 / 60.0 / 60.0
planets = [('mercury', 1), ('venus', 2), ('mars', 4), ('jupiter', 5),
           ('saturn', 6), ('uranus', 7), ('neptune', 8), ('pluto', 9),
           ('sun', 10), ('moon', 11)]

def main():
    jd_start, jd_end, number = eph_manager.ephem_open()
    output({}, """\
        'Auto-generated accuracy tests vs NOVAS (see build_novas_tests.py).'

        import pytest
        from numpy import abs, array, einsum, max
        from skyfield import (earthlib, framelib, nutationlib, positionlib,
                              precessionlib, starlib, timelib)
        from skyfield.api import JulianDate
        from skyfield.constants import AU_M
        from skyfield.functions import length_of
        from skyfield.jpllib import Ephemeris

        try:
            import de405
            de405 = Ephemeris(de405)
        except ImportError:
            pytestmark = pytest.mark.skipif(True, reason='de405 unavailable')

        one_second = 1.0 / 24.0 / 60.0 / 60.0
        arcsecond = 1.0 / 60.0 / 60.0
        ra_arcsecond = 24.0 / 360.0 / 60.0 / 60.0
        meter = 1.0 / AU_M

        def compare(value, expected_value, epsilon):
            if hasattr(value, 'shape') or hasattr(expected_value, 'shape'):
                assert max(abs(value - expected_value)) <= epsilon
            else:
                assert abs(value - expected_value) <= epsilon

        """)

    moon_landing = novas.julian_date(1969, 7, 20, 20.0 + 18.0/60.0)
    first_hubble_image = novas.julian_date(1990, 5, 20)
    voyager_intersellar = novas.julian_date(2012, 8, 25)

    date_vector = [moon_landing, first_hubble_image, T0, voyager_intersellar]
    dates = date_vector + [date_vector]

    output_subroutine_tests(dates)
    output_geocentric_tests(dates)
    output_topocentric_tests(dates)

def output_subroutine_tests(dates):
    date_floats = [d for d in dates if not isinstance(d, list)]
    delta_t_floats = [+39.707, +57.1136, +63.8285, +66.7846]

    def shorter_cal_date(jd):
        y, m, d, h = novas.cal_date(jd)
        return y, m, d + h / 24.0 - 0.5

    for i, jd in enumerate(date_floats):
        cal_date = call(shorter_cal_date, jd)
        output(locals(), """\
            def test_calendar_date_{i}():
                compare(timelib.calendar_date({jd!r}), array({cal_date}), 0.0)
            """)

    for i, jd in enumerate(date_floats):
        angle = novas.era(jd)
        output(locals(), """\
            def test_earth_rotation_angle_date{i}():
                compare(earthlib.earth_rotation_angle({jd!r}), {angle},
                        0.000001 * arcsecond)
            """)

    for i, jd in enumerate(date_floats):
        angles = novas.e_tilt(jd)
        output(locals(), """\
            def test_earth_tilt_date{i}():
                compare(nutationlib.earth_tilt(JulianDate(tdb={jd!r})),
                        array({angles}), 0.00001 * arcsecond)
            """)

    for i, jd in enumerate(date_floats):
        terms = novas.ee_ct(jd, 0.0, 0)
        output(locals(), """\
            def test_equation_of_the_equinoxes_complimentary_terms_date{i}():
                compare(nutationlib.equation_of_the_equinoxes_complimentary_terms({jd!r}),
                        array({terms}), 0.0000000000000001 * arcsecond)
            """)

    vector = (1.1, 1.2, 1.3)
    tie1 = novas.frame_tie(vector, 0)
    tie2 = novas.frame_tie(vector, -1)
    output(locals(), """\
        def test_forward_frame_tie():
            compare(framelib.ICRS_to_J2000.dot({vector}), {tie1}, 1e-15)

        def test_reverse_frame_tie():
            compare(framelib.ICRS_to_J2000.T.dot({vector}), {tie2}, 1e-15)
        """)

    for i, jd in enumerate(date_floats):
        jcentury = (jd - T0) / 36525.0
        arguments = novas.fund_args(jcentury)
        output(locals(), """\
            def test_fundamental_arguments_date{i}():
                compare(nutationlib.fundamental_arguments({jcentury!r}),
                        array({arguments}), 0.000000001 * arcsecond)
            """)

    for i, jd in enumerate(date_floats):
        psi, eps = nutation_module.iau2000a(jd, 0.0)
        psi *= 1e7 / ASEC2RAD
        eps *= 1e7 / ASEC2RAD
        output(locals(), """\
            def test_iau2000a_date{i}():
                compare(nutationlib.iau2000a({jd!r}),
                        array([{psi}, {eps}]), 0.001)
            """)

    for i, args in enumerate([
          (-4712, 1, 1, 0.0),
          (-4712, 3, 1, 0.0),
          (-4712, 12, 31, 0.5),
          (-241, 3, 25, 19.0),
          (530, 9, 27, 23.5),
          (1976, 3, 7, 12.5),
          (2000, 1, 1, 0.0),
          ]):
        jd = novas.julian_date(*args)
        output(locals(), """\
            def test_julian_date_function_date{i}():
                compare(timelib.julian_date{args}, {jd!r}, 0.0)
            """)

    for i, jd in enumerate(date_floats):
        angle = novas.mean_obliq(jd)
        output(locals(), """\
            def test_mean_obliquity_date{i}():
                compare(nutationlib.mean_obliquity({jd!r}),
                        {angle!r}, 0.0)  # arcseconds
            """)

    for i, jd in enumerate(date_floats):
        vector = [1.1, 1.2, 1.3]
        result = nutation_function(jd, vector)
        output(locals(), """\
            def test_nutation_date{i}():
                matrix = nutationlib.compute_nutation(JulianDate(tdb={jd!r}))
                result = einsum('ij...,j...->i...', matrix, [1.1, 1.2, 1.3])
                compare({result},
                        result, 1e-14)
            """)

    for i, jd in enumerate(date_floats):
        vector = [1.1, 1.2, 1.3]
        result = novas.precession(T0, vector, jd)
        output(locals(), """\
            def test_precession_date{i}():
                matrix = precessionlib.compute_precession({jd!r})
                result = einsum('ij...,j...->i...', matrix, [1.1, 1.2, 1.3])
                compare({result},
                        result, 1e-15)
            """)

    for i, jd in enumerate(date_floats):
        result1 = novas.sidereal_time(jd, 0.0, 0.0, False, True)
        result2 = novas.sidereal_time(jd, 0.0, 99.9, False, True)
        output(locals(), """\
            def test_sidereal_time_on_date{i}():
                jd = JulianDate(tt={jd!r})
                compare(earthlib.sidereal_time(jd), {result1!r}, 1e-13)

            def test_sidereal_time_with_nonzero_delta_t_on_date{i}():
                jd = JulianDate(tt={jd!r} + 99.9 * one_second, delta_t=99.9)
                compare(earthlib.sidereal_time(jd), {result2!r}, 1e-13)
            """)

    p, v = novas.starvectors(novas.make_cat_entry(
        'POLARIS', 'HIP', 0, 2.530301028, 89.264109444,
        44.22, -11.75, 7.56, -17.4))
    output(locals(), """\
        def test_star_vector():
            star = starlib.Star(ra_hours=2.530301028, dec_degrees=89.264109444,
                                ra_mas_per_year=44.22, dec_mas_per_year=-11.75,
                                parallax_mas=7.56, radial_km_per_s=-17.4)
            compare(star._position,
                    {p},
                    1e3 * meter)
            compare(star._velocity,
                    {v},
                    1e-6 * meter)
        """)

    for i, (tt, delta_t) in enumerate(zip(date_floats, delta_t_floats)):
        jd_low = xp = yp = 0.0
        vector = [1.1, 1.2, 1.3]
        ut1 = tt - delta_t * one_second
        result = novas.ter2cel(ut1, jd_low, delta_t, xp, yp, vector)
        output(locals(), """\
            def test_ITRF_to_GCRS_conversion_on_date{i}():
                jd = JulianDate(tt={tt!r}, delta_t={delta_t!r})
                position = positionlib.ITRF_to_GCRS(jd, {vector!r})
                compare(position, {result!r}, 1e-13)
            """)

    for i, jd_tdb in enumerate(date_floats):
        result = novas.tdb2tt(jd_tdb)[1]
        output(locals(), """\
            def test_tdb_minus_tt_on_date{i}():
                result = timelib.tdb_minus_tt({jd_tdb!r})
                compare(result, {result!r}, 1e-16)
            """)

def output_geocentric_tests(dates):
    for (planet, code), (i, jd) in product(planets, enumerate(dates)):
        obj = novas.make_object(0, code, 'planet{}'.format(code), None)

        ra1, dec1, distance1 = call(novas.astro_planet, jd, obj)
        ra2, dec2, distance2 = call(novas.virtual_planet, jd, obj)
        ra3, dec3, distance3 = call(novas.app_planet, jd, obj)

        assert distance1 == distance2 == distance3

        output(locals(), """\

        def test_{planet}_geocentric_date{i}():
            jd = JulianDate(tt={jd!r})
            e = de405.earth(jd)

            distance = length_of((e - de405.{planet}(jd)).position.AU)
            compare(distance, {distance1!r}, 0.5 * meter)

            astrometric = e.observe(de405.{planet})
            ra, dec, distance = astrometric.radec()
            compare(ra.hours, {ra1!r}, 0.001 * ra_arcsecond)
            compare(dec.degrees, {dec1!r}, 0.001 * arcsecond)

            apparent = astrometric.apparent()
            ra, dec, distance = apparent.radec()
            compare(ra.hours, {ra2!r}, 0.001 * ra_arcsecond)
            compare(dec.degrees, {dec2!r}, 0.001 * arcsecond)

            ra, dec, distance = apparent.radec(epoch='date')
            compare(ra.hours, {ra3!r}, 0.001 * ra_arcsecond)
            compare(dec.degrees, {dec3!r}, 0.001 * arcsecond)

        """)

def output_topocentric_tests(dates):
    usno = novas.make_on_surface(38.9215, -77.0669, 92.0, 10.0, 1010.0)
    for (planet, code), (i, jd) in product(planets, enumerate(dates)):
        obj = novas.make_object(0, code, 'planet{}'.format(code), None)

        ra1, dec1, distance1 = call(novas.local_planet, jd, 0.0, obj, usno)
        ra2, dec2, distance2 = call(novas.topo_planet, jd, 0.0, obj, usno)
        alt, az = call(altaz_maneuver, jd, obj, usno)

        output(locals(), """\

        def test_{planet}_topocentric_date{i}():
            jd = JulianDate(tt={jd!r})
            usno = de405.earth.topos('38.9215 N', '77.0669 W', elevation_m=92.0)

            apparent = usno(jd).observe(de405.{planet}).apparent()
            ra, dec, distance = apparent.radec()
            compare(ra.hours, {ra1!r}, 0.001 * ra_arcsecond)
            compare(dec.degrees, {dec1!r}, 0.001 * arcsecond)

            ra, dec, distance = apparent.radec(epoch='date')
            compare(ra.hours, {ra2!r}, 0.001 * ra_arcsecond)
            compare(dec.degrees, {dec2!r}, 0.001 * arcsecond)

            alt, az, distance = apparent.altaz()
            compare(alt.degrees, {alt!r}, 0.001 * arcsecond)
            compare(az.degrees, {az!r}, 0.001 * arcsecond)

        """)

def altaz_maneuver(jd, obj, place):
    """Simplify a pair of complicated USNO calls to a single callable."""
    xp = yp = 0.0
    ra, dec, distance = novas.topo_planet(jd, 0.0, obj, place)
    (zd, az), (ra, dec) = novas.equ2hor(jd, 0.0, xp, yp, place, ra, dec)
    return 90.0 - zd, az

def call(function, jd, *args):
    """Call function either once, or as many times as `jd` dictates."""

    if isinstance(jd, float):
        return function(jd, *args)

    answers = [function(n, *args) for n in jd]
    return zip(*answers)

def output(dictionary, template):
    print(dedent(template).format(**dictionary).strip('\n'))
    print()

if __name__ == '__main__':
    main()


from keras.layers.core import Reshape, Masking, Lambda, Permute
from keras.layers import Input, Dense, Flatten
from keras.models import Model
from keras import backend as K
from keras.optimizers import Adam, SGD, Adadelta
from keras.callbacks import EarlyStopping, ModelCheckpoint, TensorBoard
import tensorflow as tf
import numpy as np
import os
from PIL import Image
import densenet

dataset_path = r'E:\03personal\DeepLearning\data\keras_ocr_data\images'

def get_session(gpu_fraction=0.6):
    '''''Assume that you have 6GB of GPU memory and want to allocate ~2GB'''

    num_threads = os.environ.get('OMP_NUM_THREADS')
    gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_fraction)

    if num_threads:
        return tf.Session(config=tf.ConfigProto(
            gpu_options=gpu_options, intra_op_parallelism_threads=num_threads))
    else:
        return tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))

K.set_session(get_session())

def ctc_lambda_func(args):
    y_pred, labels, input_length, label_length = args
    return K.ctc_batch_cost(labels, y_pred, input_length, label_length)

char = ''
with open('char_std_5990.txt', encoding='utf-8') as f:
    for ch in f.readlines():
        ch = ch.strip('\r\n')
        char = char + ch

# caffe_ocr中把0作为blank，但是tf 的CTC  the last class is reserved to the blank label.
# https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/util/ctc/ctc_loss_calculator.h
char = char[1:] + '卍'
print('nclass:', len(char))

id_to_char = {i: j for i, j in enumerate(char)}
print(id_to_char[5988])

maxlabellength = 20
img_h = 32
img_w = 280
nclass = len(char)
rnnunit = 256
batch_size = 64

class random_uniform_num():
    """
    均匀随机，确保每轮每个只出现一次
    """

    def __init__(self, total):
        self.total = total
        self.range = [i for i in range(total)]
        np.random.shuffle(self.range)
        self.index = 0

    def get(self, batchsize):
        r_n = []
        if self.index + batchsize > self.total:
            r_n_1 = self.range[self.index:self.total]
            np.random.shuffle(self.range)
            self.index = (self.index + batchsize) - self.total
            r_n_2 = self.range[0:self.index]
            r_n.extend(r_n_1)
            r_n.extend(r_n_2)

        else:
            r_n = self.range[self.index:self.index + batchsize]
            self.index = self.index + batchsize
        return r_n

def readtrainfile(filename):
    with open(os.path.join(dataset_path, filename), 'r') as f:
        lines = f.readlines()
    res = [line.strip() for line in lines]
    dic = {}
    for i in res:
        p = i.split(' ')
        # caffe_ocr中把0作为blank，但是tf 的CTC  the last class is reserved to the blank label.
        # https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/util/ctc/ctc_loss_calculator.h
        dic[p[0]] = [int(i) - 1 for i in p[1:]]
    return dic

def gen3(trainfile, batchsize=64, maxlabellength=10, imagesize=(32, 280)):
    image_label = readtrainfile(trainfile)
    _imagefile = [i for i, j in image_label.items()]
    x = np.zeros((batchsize, imagesize[0], imagesize[1], 1), dtype=np.float)
    labels = np.ones([batchsize, maxlabellength]) * 10000
    input_length = np.zeros([batchsize, 1])
    label_length = np.zeros([batchsize, 1])

    r_n = random_uniform_num(len(_imagefile))
    print('total image in {}'.format(trainfile), len(_imagefile))
    _imagefile = np.array(_imagefile)
    while 1:
        shufimagefile = _imagefile[r_n.get(batchsize)]
        for i, j in enumerate(shufimagefile):
            img1 = Image.open(os.path.join(dataset_path, j)).convert('L')
            img = np.array(img1, 'f') / 255.0 - 0.5

            x[i] = np.expand_dims(img, axis=2)
            # print('imag:shape',img.shape)
            index = image_label[j]
            label_length[i] = len(index)

            if len(index) <= 0:
                print("len<0", j)
            input_length[i] = imagesize[1] // 8
            labels[i, :len(index)] = index

        inputs = {'the_input': x,
                  'the_labels': labels,
                  'input_length': input_length,
                  'label_length': label_length,
                  }
        outputs = {'ctc': np.zeros([batchsize])}
        yield (inputs, outputs)

if __name__ == '__main__':
    input = Input(shape=(img_h, None, 1), name='the_input')

    y_pred = densenet.dense_cnn(input, nclass)

    basemodel = Model(inputs=input, outputs=y_pred)
    basemodel.summary()

    labels = Input(name='the_labels', shape=[maxlabellength], dtype='float32')
    input_length = Input(name='input_length', shape=[1], dtype='int64')
    label_length = Input(name='label_length', shape=[1], dtype='int64')

    loss_out = Lambda(ctc_lambda_func, output_shape=(1,), name='ctc')([y_pred, labels, input_length, label_length])

    model = Model(inputs=[input, labels, input_length, label_length], outputs=loss_out)

    adam = Adam()

    model.compile(loss={'ctc': lambda y_true, y_pred: y_pred}, optimizer=adam, metrics=['accuracy'])

    checkpoint = ModelCheckpoint(
        r'E:\03personal\DeepLearning\data\keras_ocr_data\models\weights-densent-{epoch:02d}.hdf5')
    earlystop = EarlyStopping(patience=10)
    tensorboard = TensorBoard(r'E:\03personal\DeepLearning\data\keras_ocr_data\models\tflog-densent', write_graph=True)

    print('beginfit'.center(98, '-'))
    cc1 = gen3(r'E:\03personal\DeepLearning\data\keras_ocr_data\train.txt', batchsize=batch_size,
               maxlabellength=maxlabellength, imagesize=(img_h, img_w))
    cc2 = gen3(r'E:\03personal\DeepLearning\data\keras_ocr_data\test.txt', batchsize=batch_size,
               maxlabellength=maxlabellength, imagesize=(img_h, img_w))

    hist = model.fit_generator(cc1, steps_per_epoch=3279601 // batch_size, epochs=100,
                               validation_data=cc2, validation_steps=364400 // batch_size,
                               callbacks=[earlystop, checkpoint, tensorboard], verbose=1)


import pygame
import sys
import copy
from settings import *
from player_class import *
from enemy_class import *
import sqlite3

class App:
    def __init__(self):
        self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
        self.clock = pygame.time.Clock()
        pygame.display.set_caption('PACMAN')
        self.running = True
        self.state = 'start'
        self.cell_width = MAZE_WIDTH // COLS
        self.cell_height = MAZE_HEIGHT // ROWS
        self.walls = []
        self.coins = []
        self.enemies = []
        self.e_pos = []
        self.p_pos = None
        self.player_info()
        self.load()
        self.player = Player(self, vec(self.p_pos))
        self.make_enemies()
        with open('settings.txt', 'r') as f:
            self.settings = f.read()
        if self.settings.split()[1] == 'True':
            pygame.mixer.music.load('music.mp3')
            pygame.mixer.music.play()
        pygame.display.set_icon(pygame.image.load('logo.png'))

    def run(self):
        while self.running:
            if self.state == 'start':
                self.start_events()
                self.start_update()
                self.start_draw()
            elif self.state == 'playing':
                self.playing_events()
                self.playing_update()
                self.playing_draw()
                self.write_record()
                self.check_win()
            elif self.state == 'game over':
                self.game_over_events()
                self.game_over_update()
                self.game_over_draw()
            elif self.state == 'win':
                self.win_events()
                self.win_draw()
            else:
                self.running = False
            self.clock.tick(FPS)
        pygame.quit()
        sys.exit()

    def draw_text(self, words, screen, pos, size, colour, font_name, centered=False):
        font = pygame.font.SysFont(font_name, size)
        text = font.render(words, False, colour)
        text_size = text.get_size()
        if centered:
            pos[0] = pos[0]-text_size[0]//2
            pos[1] = pos[1]-text_size[1]//2
        screen.blit(text, pos)

    def load(self):
        self.background = pygame.image.load('map1.png')
        self.background = pygame.transform.scale(self.background, (MAZE_WIDTH, MAZE_HEIGHT))
        with open("walls.txt", 'r') as file:
            for yidx, line in enumerate(file):
                for xidx, char in enumerate(line):
                    if char == "1":
                        self.walls.append(vec(xidx, yidx))
                    elif char == "C":
                        self.coins.append(vec(xidx, yidx))
                    elif char == "P":
                        self.p_pos = [xidx, yidx]
                    elif char in ["2", "3", "4", "5"]:
                        self.e_pos.append([xidx, yidx])
                    elif char == "B":
                        pygame.draw.rect(self.background, BLACK, (xidx*self.cell_width, yidx*self.cell_height,
                                                                  self.cell_width, self.cell_height))

    def check_win(self):
        if str(self.player.current_score) == '287':
            self.state = 'win'
            self.player_record = '287'
            self.player.current_score = '287'

    def make_enemies(self):
        for idx, pos in enumerate(self.e_pos):
            self.enemies.append(Enemy(self, vec(pos), idx))

    def draw_grid(self):
        for x in range(WIDTH//self.cell_width):
            pygame.draw.line(self.background, GREY, (x*self.cell_width, 0),
                             (x*self.cell_width, HEIGHT))
        for x in range(HEIGHT//self.cell_height):
            pygame.draw.line(self.background, GREY, (0, x*self.cell_height),
                             (WIDTH, x*self.cell_height))

    def reset(self):
        if int(self.player_record) < int(self.player.current_score):
            self.player_record = str(self.player.current_score)
        self.new_output_rec()
        self.player.lives = 3
        self.player.current_score = 0
        self.player.grid_pos = vec(self.player.starting_pos)
        self.player.pix_pos = self.player.get_pix_pos()
        self.player.direction *= 0
        for enemy in self.enemies:
            enemy.grid_pos = vec(enemy.starting_pos)
            enemy.pix_pos = enemy.get_pix_pos()
            enemy.direction *= 0

        self.coins = []
        with open("walls.txt", 'r') as file:
            for yidx, line in enumerate(file):
                for xidx, char in enumerate(line):
                    if char == 'C':
                        self.coins.append(vec(xidx, yidx))
        self.state = "playing"

    def start_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False
            if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                self.state = 'playing'

    def start_update(self):
        pass

    def start_draw(self):
        self.screen.fill(BLACK)
        self.draw_text('НАЖМИТЕ ПРОБЕЛ', self.screen, [WIDTH // 2, HEIGHT // 2 - 50], 16, (170, 132, 58), 'arial black', centered=True)
        self.draw_text(str('НАИБОЛЬШЕЕ: ' + self.player_record), self.screen, [4, 0], 16, (255, 255, 255), 'arial black')
        self.draw_text(self.player_name, self.screen, [WIDTH // 2, 15], 16, (170, 132, 58), 'arial black', centered=True)
        pygame.display.update()

    def player_info(self):
        with open('player_info.txt', 'r') as f:
            res = str(f.read())
            self.player_name = res.split()[0]
            self.player_record = res.split()[1]

    def playing_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    self.player.move(vec(-1, 0))
                if event.key == pygame.K_RIGHT:
                    self.player.move(vec(1, 0))
                if event.key == pygame.K_UP:
                    self.player.move(vec(0, -1))
                if event.key == pygame.K_DOWN:
                    self.player.move(vec(0, 1))

    def playing_update(self):
        self.player.update()
        for enemy in self.enemies:
            enemy.update()

        for enemy in self.enemies:
            if enemy.grid_pos == self.player.grid_pos:
                self.remove_life()

    def playing_draw(self):
        self.screen.fill(BLACK)
        self.screen.blit(self.background, (TOP_BOTTOM_BUFFER//2, TOP_BOTTOM_BUFFER//2))
        self.draw_coins()
        self.draw_text('ТЕКУЩИЙ РЕЗУЛЬТАТ: {}'.format(self.player.current_score),
                       self.screen, [60, 0], 18, WHITE, START_FONT)
        self.draw_text(str('НАИБОЛЬШЕЕ: ' + self.player_record), self.screen, [WIDTH//2+60, 0], 18, WHITE, START_FONT)
        self.player.draw()

        for enemy in self.enemies:
            enemy.draw()
        pygame.display.update()

    def new_output_rec(self):
        self.draw_text(str('НАИБОЛЬШЕЕ: ' + self.player_record), self.screen, [WIDTH // 2 + 60, 0], 18, WHITE,
                       START_FONT)
        pygame.display.flip()

    def remove_life(self):
        self.player.lives -= 1
        if self.player.lives == 0:
            self.state = "game over"
        else:
            self.player.grid_pos = vec(self.player.starting_pos)
            self.player.pix_pos = self.player.get_pix_pos()
            self.player.direction *= 0
            for enemy in self.enemies:
                enemy.grid_pos = vec(enemy.starting_pos)
                enemy.pix_pos = enemy.get_pix_pos()
                enemy.direction *= 0

    def write_record(self):
        if int(self.player.current_score) > int(self.player_record):
            con = sqlite3.connect("base.bd")
            cur = con.cursor()
            cur.execute("""UPDATE players
                        SET record = (?)
                        WHERE name = (?)""", (self.player.current_score, self.player_name))
            con.commit()

    def draw_coins(self):
        for coin in self.coins:
            pygame.draw.circle(self.screen, (124, 123, 7),
                               (int(coin.x*self.cell_width)+self.cell_width//2+TOP_BOTTOM_BUFFER//2,
                                int(coin.y*self.cell_height)+self.cell_height//2+TOP_BOTTOM_BUFFER//2), 5)

    def game_over_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False
            if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                self.reset()
            if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                self.running = False

    def game_over_update(self):
        pass

    def game_over_draw(self):
        self.screen.fill(BLACK)
        quit_text = "ДЛЯ ВЫХОДА НАЖМИТЕ ESC"
        again_text = "НАЖМИТЕ ПРОБЕЛ ДЛЯ ПЕРЕЗАПУСКА"
        self.draw_text("ИГРА ОКОНЧЕНА", self.screen, [WIDTH//2, 100],  52, RED, "arial", centered=True)
        self.draw_text(again_text, self.screen, [
                       WIDTH//2, HEIGHT//2],  36, (190, 190, 190), "arial", centered=True)
        self.draw_text(quit_text, self.screen, [
                       WIDTH//2, HEIGHT//1.5],  36, (190, 190, 190), "arial", centered=True)
        pygame.display.update()

    def win_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False
            if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                self.reset()
            if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                self.running = False

    def win_draw(self):
        self.screen.fill(BLACK)
        quit_text = "ДЛЯ ВЫХОДА НАЖМИТЕ ESC"
        again_text = "НАЖМИТЕ ПРОБЕЛ ДЛЯ ПЕРЕЗАПУСКА"
        self.draw_text("ПОБЕДА", self.screen, [WIDTH // 2, 100], 52, (255, 255, 0), "arial", centered=True)
        self.draw_text(again_text, self.screen, [
            WIDTH // 2, HEIGHT // 2], 36, (190, 190, 190), "arial", centered=True)
        self.draw_text(quit_text, self.screen, [
            WIDTH // 2, HEIGHT // 1.5], 36, (190, 190, 190), "arial", centered=True)
        pygame.display.update()

pygame.init()
vec = pygame.math.Vector2


import heapq
from collections import Counter

def huffman_encode(string):
    code_dict = dict.fromkeys(set(string), '') if len(set(string)) > 1 else {string[0]: '0'}
    heap = [(count, char) for char, count in Counter(string).items()]
    heapq.heapify(heap)
    while len(heap) > 1:
        first = heapq.heappop(heap)
        second = heapq.heappop(heap)
        new = (first[0] + second[0], first[1] + second[1])
        for letter in first[1]:
            code_dict[letter] = '0' + code_dict[letter]
        for letter in second[1]:
            code_dict[letter] = '1' + code_dict[letter]
        heapq.heappush(heap, new)
    return code_dict

def main():
    string = input()
    code_dict = huffman_encode(string)
    encode_string = ''.join([code_dict[x] for x in string])
    print(len(code_dict), len(encode_string))
    for char, code in sorted(code_dict.items()):
        print('{}: {}'.format(char, code))
    print(encode_string)

if __name__ == '__main__':
    main()


import sys

def parseCoord(x):
    return [int(y) for y in x[1:len(x) - 1].split(',')]

def distSquared(a, b):
    return (b[0] - a[0]) ** 2 + (b[1] - a[1]) ** 2

def perpendicular(a, b, c, d):
    dista = set([distSquared(a, x) for x in [b, c, d]])
    distb = set([distSquared(b, x) for x in [a, c, d]])
    distc = set([distSquared(c, x) for x in [b, a, d]])
    distd = set([distSquared(d, x) for x in [b, c, a]])
    return len(dista) == 2 and len(distb) == 2 and len(distc) == 2 and len(distd) == 2

def isSquare(a, b, c, d):
    center = [sum([x[0] for x in coords]) / 4.0, sum([x[1] for x in coords]) / 4.0]
    dista = distSquared(center, a)
    distb = distSquared(center, b)
    distc = distSquared(center, c)
    distd = distSquared(center, d)
    if (dista == distb and dista == distc and dista == distd) == False:
        return False
    return perpendicular(a, b, c, d)

lines = open(sys.argv[1], 'r')
for line in lines:
    line = line.replace('\n', '').replace('\r', '')
    if len(line) > 0:
        coords = [parseCoord(x) for x in line.split(', ')]
        print('true' if len(coords) == 4 and isSquare(*coords) else 'false')

lines.close()


#!/usr/bin/env python3
import contextlib

@contextlib.contextmanager
def make_context(name):
    print("entering:", name)
    yield name
    print("exiting :", name)

with make_context("A") as A, make_context("B") as B:
    print("inside with statement:", A, B)


# -*- coding: utf-8 -*-
n=int(input('n:'))
lista=[]
soma=0
for i in range(0,n,1):
    numero=float(input('numero:'))
    lista.append(numero)
media=soma/len(lista)
print(lista[0])
print(len(lista-1))


# A very simple Flask Hello World app for you to get started with...

from flask import Flask, render_template, request

from tinydb import TinyDB, Query

db = TinyDB('my_list.json')
db.insert({'name': 'Fred', 'age': 22})
User = Query()
result=db.search(User.name == 'Fred')

app = Flask(__name__)

@app.route('/')
@app.route('/hello')
@app.route('/hello/')
@app.route('/hello/<name>')
def hello_world(name="friend"):
    return render_template('hello.html', name=name + str(result))

@app.route('/stuff')
def stuff_page():
    stuff = ["Dogs","Kids","Wind","Dust","Towels"]
    return render_template('list.html', name="Stuff", items=stuff, title=False)

@app.route('/form')
def form_page():
    return render_template('form.html')

@app.route('/post_list', methods=['POST'])
def post_list():
    mylist = [request.form['first'],request.form['second'],request.form['third']]
    db.insert({
        "first":request.form['first'],
        "second":request.form['second'],
        "third":request.form['third'],
        })
    return render_template('list.html', name="My Items", items=mylist, title=True)

@app.route('/all_items')
def get_all_items():
    Item=Query()
    items = db.search(Item.first>'')
    return render_template('all_items.html', items=items)

@app.route('/bye')
def bye_world():
    return render_template('bye.html')