# uncompyle6 version 3.7.4
# Python bytecode 3.6 (3379)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: build/bdist.macosx-10.7-x86_64/egg/sisua/inference/inference_scvi.py
# Compiled at: 2019-06-27 08:22:47
# Size of source mod 2**32: 15035 bytes
from __future__ import print_function, division, absolute_import
import io
from io import BytesIO
from collections import defaultdict
import numpy as np
from tqdm import tqdm
from odin.utils import batching, stdio, get_formatted_datetime
from .inference_base import Inference
from ._consts import PREDICTION_BATCH_SIZE
from sisua.data import get_library_size, apply_artificial_corruption
from sisua.data.const import UNIVERSAL_RANDOM_SEED
try:
    import torch
    torch_device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
    torch.manual_seed(UNIVERSAL_RANDOM_SEED)
except ImportError:
    torch_device = None

def _create_gene_dataset(X, local_means=None, local_vars=None):
    from scvi.dataset import GeneExpressionDataset
    if local_means is None or local_vars is None:
        local_means, local_vars = get_library_size(X)
    col_names = np.array(['Gene#%d' % i for i in range(X.shape[1])])
    gene_dataset = GeneExpressionDataset(X=X,
      local_means=local_means,
      local_vars=local_vars,
      batch_indices=np.zeros(shape=(X.shape[0], 1)),
      labels=None,
      gene_names=col_names,
      cell_types=None)
    gene_dataset.labels = X
    gene_dataset.cell_types = col_names
    return gene_dataset

def _create_data_iter(X, log_variational):
    import torch
    for start, end in batching(batch_size=(PREDICTION_BATCH_SIZE // 3), n=(X.shape[0])):
        x = _to_tensor(X[start:end])
        if bool(log_variational):
            x = torch.log(1 + x)
        yield x

def _to_tensor(x):
    import torch
    return torch.from_numpy(x.astype('float32')).to(torch_device)

def _to_array(x):
    if hasattr(x, 'todense'):
        return np.array(x.todense())
    else:
        if hasattr(x, 'cpu'):
            return x.data.cpu().numpy()
        return x

def _use_cuda():
    import torch
    return torch.cuda.is_available()

class InferenceSCVI(Inference):
    __doc__ = ' InferenceSCVI '

    def __init__(self, gene_dim, dispersion='gene-cell', xnorm='log', tnorm='raw', ynorm='prob', xclip=0, yclip=0, xdist='zinb', ydist='bernoulli', zdist='normal', xdrop=0.3, edrop=0, zdrop=0, ddrop=0, hdim=128, zdim=32, nlayer=2, batchnorm=True, analytic=True, kl_weight=1.0, warmup=400, y_weight=10.0, extra_module_path=None, no_library_size=False, **kwargs):
        try:
            import scvi
        except ImportError as e:
            raise RuntimeError('scVI package at https://github.com/YosefLab/scVI is required')

        model = kwargs.get('model', 'vae')
        prot_dim = None
        if model not in ('vae', 'scvi'):
            raise RuntimeError("InferenceSCVI only support 'vae' model")
        if xdist not in ('zinb', 'nb'):
            raise ValueError("Only support 'zinb' and 'nb' for `xdist`")
        if xnorm not in ('log', 'raw'):
            raise ValueError('Only support log variational or raw count variational for scVI')
        if tnorm not in ('raw', ):
            raise ValueError('Only support raw count target value for scVI')
        self._name = 'scvinl' if no_library_size else 'scvi'
        self._history = {'train':defaultdict(list),
         'valid':defaultdict(list)}
        self._training_log = ''
        self._configs = dict(locals())
        self._configs.update(kwargs)
        self._gmm_threshold = {}
        self._gene_dim = int(gene_dim)
        self._prot_dim = 0 if prot_dim is None else max(int(prot_dim), 0)
        self._is_fitted = False
        self._ps = 0
        self._trained_n_epoch = 0
        self._batch_size = 0
        self._learning_rate = 0
        self._n_mcmc_train = 0
        self._corruption_rate = None
        self._corruption_dist = None
        self._initialize_model()
        self._no_library_size = bool(no_library_size)

    @property
    def no_library_size(self):
        return self._no_library_size

    def _initialize_model(self, weights=None):
        from scvi.models import VAE
        self._vae = VAE(n_input=(self.gene_dim), n_batch=0, n_labels=0, n_hidden=(self.hdim),
          n_latent=(self.zdim),
          n_layers=(self.nlayer),
          dropout_rate=(self.xdrop),
          dispersion=(self.dispersion),
          log_variational=(True if self.xnorm == 'log' else False),
          reconstruction_loss=(self.xdist))
        if weights is not None:
            data = BytesIO(weights)
            self._vae.load_state_dict(torch.load(data))
            self._vae.to(torch_device)

    def __getstate__(self):
        import torch
        states = self.get_states()
        weights = BytesIO()
        torch.save(self._vae.state_dict(), weights)
        weights.seek(0)
        weights = weights.read()
        return (states, weights, self._no_library_size)

    def __setstate__(self, states):
        states, weights, self._no_library_size = states
        self.set_states(states)
        self._initialize_model(weights=weights)

    def fit(self, X, y=None, supervised_percent=0.8, validation_percent=0.1, n_mcmc_samples=1, corruption_rate=0.25, corruption_dist='binomial', batch_size=64, n_epoch=120, learning_rate=0.0001, monitoring=False, fig_dir=None, detail_logging=False):
        training_log = io.StringIO()
        stdio(training_log)
        if self._corruption_rate is None:
            self._corruption_rate = corruption_rate
            self._corruption_dist = corruption_dist
        else:
            if not (self._corruption_rate == corruption_rate and self._corruption_dist == corruption_dist):
                raise AssertionError('Model have been fitted with following corruption configurations: %s, %s;but given: %s, %s' % (
                 self._corruption_rate, self._corruption_dist,
                 corruption_rate, corruption_dist))
            elif not n_mcmc_samples == 1:
                raise AssertionError('Only support 1 MCMC sample during training for scVI')
            self._ps = supervised_percent
            self._batch_size = batch_size
            self._learning_rate = learning_rate
            self._n_mcmc_train = n_mcmc_samples
            X = apply_artificial_corruption(X,
              dropout=corruption_rate, distribution=corruption_dist)
            assert X.shape[1] == self.gene_dim, 'Number of gene expression mismatch: %d != %d' % (self.gene_dim, X.shape[1])
        if validation_percent == 0:
            raise RuntimeError("scVI doesn't support 0% validation percent!")
        from scvi.inference import UnsupervisedTrainer
        gene_dataset = _create_gene_dataset(X)
        if 'dataset' in self.configs:
            if self.configs['dataset'] == 'cortex':
                batch_size = batch_size - 1
        trainer = UnsupervisedTrainer((self._vae), gene_dataset, use_cuda=(_use_cuda()),
          train_size=(1 - validation_percent),
          frequency=1,
          benchmark=False,
          data_loader_kwargs=dict(batch_size=batch_size),
          metrics_to_monitor=None,
          verbose=detail_logging)
        trainer.train(n_epochs=n_epoch, lr=learning_rate)
        self._scvi_trainer = trainer
        self._history['train']['loss'] += trainer.history['ll_train_set'][1:]
        self._history['valid']['loss'] += trainer.history['ll_test_set'][1:]
        self._trained_n_epoch += n_epoch
        self._is_fitted = True
        stdio()
        training_log.seek(0)
        self._training_log += '\n%s\n' % get_formatted_datetime(only_number=False)
        self._training_log += training_log.read()
        training_log.close()

    def get_train_loss(self):
        return self._history['train']['loss']

    def get_valid_loss(self):
        return self._history['valid']['loss']

    def get_train_history(self, name):
        return self._history['train'][name]

    def get_valid_history(self, name):
        return self._history['valid'][name]

    def score(self, X, y=None, n_mcmc_samples=100, return_mean=True):
        """Compute the per-sample average of recorded metrics of the given data X.

    Parameters
    ----------
    X : array-like, shape (n_samples, n_dimensions)
        List of n_features-dimensional data points. Each row
        corresponds to a single data point.

    Returns
    -------
    dictionary : metric_name -> values
    """
        self._vae.eval()
        from scvi.inference import Posterior
        pos = Posterior(model=(self._vae), gene_dataset=(_create_gene_dataset(X)), shuffle=False,
          use_cuda=(_use_cuda()),
          data_loader_kwargs=dict(batch_size=(PREDICTION_BATCH_SIZE // 3)))
        ll = pos.ll(verbose=False)
        marginal_ll = pos.marginal_ll(verbose=False, n_mc_samples=n_mcmc_samples)
        return {'loss':ll,  'llk':marginal_ll}

    def predict_Z(self, X):
        """ Return mean of the latent posterior
    (i.e. mean of Normal distribution) """
        self._vae.eval()
        from scvi.inference import Posterior
        pos = Posterior(model=(self._vae), gene_dataset=(_create_gene_dataset(X)), shuffle=False,
          use_cuda=(_use_cuda()),
          data_loader_kwargs={'batch_size': 64})
        return pos.get_latent(sample=False)[0]

    def predict_y(self, X, y, n_mcmc_samples=100):
        """ Predicting the protein marker """
        assert self.is_semi_supervised and y is not None, 'Only semi-supervised model has this prediction, and `y` must not be None'

    def predict_L(self, X, n_mcmc_samples=100):
        """ Return library size prediction """
        self._vae.eval()
        L = []
        for x in _create_data_iter(X, log_variational=(self._vae.log_variational)):
            ql_m, ql_v, library = self._vae.l_encoder(x)
            L.append(_to_array(ql_m))

        return np.concatenate(L, axis=0)

    def predict_Lstddev(self, X, n_mcmc_samples=100):
        """ Return library size stddev prediction """
        self._vae.eval()
        Lstddev = []
        for x in _create_data_iter(X, log_variational=(self._vae.log_variational)):
            ql_m, ql_v, library = self._vae.l_encoder(x)
            Lstddev.append(_to_array(ql_v))

        return np.concatenate(Lstddev, axis=0)

    def predict_W(self, X, n_mcmc_samples=100):
        """ Return mean of the reconstructed value """
        self._vae.eval()
        W = []
        for x in _create_data_iter(X, log_variational=False):
            px_scale, px_r, px_rate, px_dropout, qz_m, qz_v, z, ql_m, ql_v, library = self._vae.inference(x,
              batch_index=None, y=None, n_samples=n_mcmc_samples)
            if self.no_library_size:
                px_rate = px_scale * x.sum(1).unsqueeze(1)
            w = (1 - px_dropout) * px_rate
            w = w.mean(0)
            W.append(_to_array(w))

        return np.concatenate(W, axis=0)

    def predict_Wstddev(self, X, n_mcmc_samples=100):
        """ Return stddev of reconstructed value
    if not a variational model, then V_stddev is None
    """
        self._vae.eval()
        import torch
        Wstddev = []
        for x in _create_data_iter(X, log_variational=False):
            px_scale, px_r, px_rate, px_dropout, qz_m, qz_v, z, ql_m, ql_v, library = self._vae.inference(x,
              batch_index=None, y=None, n_samples=n_mcmc_samples)
            w_mean = (1 - px_dropout) * px_rate
            w_var = (1 - px_dropout) * (px_r + px_rate ** 2) - w_mean ** 2
            w_std = torch.sqrt(w_var).mean(0)
            Wstddev.append(_to_array(w_std))

        return np.concatenate(Wstddev, axis=0)

    def predict_V(self, X, n_mcmc_samples=100):
        """ Return mean of the denoised value """
        self._vae.eval()
        V = []
        for x in _create_data_iter(X, log_variational=False):
            if self._no_library_size:
                out = self._vae.get_sample_scale(x, n_samples=n_mcmc_samples).mean(0)
                out = out * x.sum(1).unsqueeze(1)
            else:
                out = self._vae.get_sample_rate(x, n_samples=n_mcmc_samples).mean(0)
            V.append(_to_array(out))

        return np.concatenate(V, axis=0)

    def predict_Vstddev(self, X, n_mcmc_samples=100):
        """ Return stddev of denoised value
    if not a variational model, then V_stddev is None
    """
        self._vae.eval()
        Vstddev = []
        for x in _create_data_iter(X, log_variational=False):
            n = x.shape[0]
            out = self._vae.inference(x,
              batch_index=None, y=None, n_samples=n_mcmc_samples)[1]
            if self.dispersion == 'gene-cell':
                out = np.mean((_to_array(out)), axis=0)
            else:
                out = np.expand_dims((_to_array(out)), axis=0)
                out = np.repeat(out, repeats=n, axis=0)
            Vstddev.append(out)

        return np.concatenate(Vstddev, axis=0)

    def predict_PI(self, X, n_mcmc_samples=100):
        """ Return a matrix (n_sample, n_gene) of Zero-inflated
    rate

    if not a zero-inflated model, then return None
    """
        self._vae.eval()
        import torch
        op = torch.nn.Sigmoid()
        PI = []
        for x in _create_data_iter(X, log_variational=False):
            out = self._vae.inference(x,
              batch_index=None, y=None, n_samples=n_mcmc_samples)[3]
            out = op(out.mean(0))
            out = _to_array(out)
            PI.append(out)

        return np.concatenate(PI, axis=0)

    def sample_Z(self, X, n_mcmc_samples=1):
        self._vae.eval()
        from scvi.inference import Posterior
        pos = Posterior(model=(self._vae), gene_dataset=(_create_gene_dataset(X)), shuffle=False,
          use_cuda=(_use_cuda()),
          data_loader_kwargs={'batch_size': 64})
        return np.concatenate([np.expand_dims((pos.get_latent(sample=True)[0]), axis=0) for i in range(n_mcmc_samples)],
          axis=0)

    def sample_y(self, X, n_mcmc_samples=1):
        raise NotImplementedError

    def sample_W(self, X, n_mcmc_samples=1):
        raise NotImplementedError

    def sample_V(self, X, n_mcmc_samples=1):
        self._vae.eval()
        V = []
        for x in _create_data_iter(X, log_variational=False):
            out = self._vae.get_sample_rate(x, n_samples=n_mcmc_samples)
            V.append(_to_array(out))

        return np.concatenate(V, axis=1)

    def sample_L(self, X, n_mcmc_samples=1):
        raise NotImplementedError


#!/bin/env python3
import gdal, ogr
import os, sys
import math
import numpy as np

## transfile = "../GPS/GPS_all_clean_spec_segments_edited_raster.tif"
srfile = "/scratch/dknapp4/Western_Hawaii/Moorea/20190604_moorea_tile_sr.tif"
rbfile = "/scratch/dknapp4/Western_Hawaii/Moorea/20190604_moorea_tile_sr_rb.tif"
depthfile = "/scratch/dknapp4/Western_Hawaii/Moorea/20190604_moorea_tile_sr_depth.tif"
ptsfile = "/scratch/dknapp4/ASD/GPS/GPS_all_clean_asd_points.shp"
## csvfile = "../Spectroscopy/Moorea_all_points_asd_bgr.csv"
outfile = "Moorea_dove_rb_sr_transects_20190710.csv"
asdcsvfile = "/scratch/dknapp4/Spectroscopy/Moorea_Dove_BGR_from_ASD.csv"

asddata = np.genfromtxt(asdcsvfile, dtype=[('fname', 'S43'), ('blue', 'f8'), ('green', 'f8'), ('red', 'f8')], delimiter=',', autostrip=True)

RbDS = gdal.Open(rbfile, gdal.GA_ReadOnly)
Rbblue = RbDS.GetRasterBand(1).ReadAsArray()
Rbgreen = RbDS.GetRasterBand(2).ReadAsArray()
Rbred = RbDS.GetRasterBand(3).ReadAsArray()
## nir = inDS.GetRasterBand(4).ReadAsArray()

SrDS = gdal.Open(srfile, gdal.GA_ReadOnly)
Srblue = SrDS.GetRasterBand(1).ReadAsArray()
Srgreen = SrDS.GetRasterBand(2).ReadAsArray()
Srred = SrDS.GetRasterBand(3).ReadAsArray()
Srnir = SrDS.GetRasterBand(4).ReadAsArray()

depDS = gdal.Open(depthfile, gdal.GA_ReadOnly)
depth = depDS.GetRasterBand(1).ReadAsArray()

gt = SrDS.GetGeoTransform()
gt2 = RbDS.GetGeoTransform()

if np.any(np.not_equal(gt, gt2)):
  print("Extents and Resolution of input images are not equal...stopping")
  rbDS, srDS, depDS = None, None, None
  sys.exit(1)

rbDS, srDS, depDS = None, None, None

pntDS = ogr.GetDriverByName("ESRI Shapefile").Open(ptsfile)
pntlayer = pntDS.GetLayer()
pntCnt = pntlayer.GetFeatureCount()

f = open(outfile, 'w')

for i in range(pntCnt):
  pnt =  pntlayer.GetNextFeature()
  pgeom = pnt.GetGeometryRef()
  xval = pgeom.GetX()
  yval = pgeom.GetY()
  pname = pnt.GetFieldAsString("specname")[0:9]
  ptime = pnt.GetFieldAsString("timepnt")

  ##Get Rb and SR data from Dove
  pixval = int(math.floor((xval - gt[0])/gt[1]))
  linval = int(math.floor((yval - gt[3])/gt[5]))
  dep = depth[linval, pixval]/100.0
  brb = Rbblue[linval, pixval]/10000.0
  grb = Rbgreen[linval, pixval]/10000.0
  rrb = Rbred[linval, pixval]/10000.0
  bsr = Srblue[linval, pixval]/10000.0
  gsr = Srgreen[linval, pixval]/10000.0
  rsr = Srred[linval, pixval]/10000.0
  nsr = Srnir[linval, pixval]/10000.0
  for rec in asddata:
    theasdname = rec['fname'][0:9].decode()
    if (pname == theasdname):
      basd = rec['blue']
      gasd = rec['green']
      rasd = rec['red']
      break

  f.write(("%s, %s, %7.4f, %7.4f, %7.4f, %7.2f, %7.4f, %7.4f, %7.4f, %7.4f, %7.4f, %7.4f, %7.4f\n") % (pname, ptime, basd, gasd, rasd, dep, brb, grb, rrb, bsr, gsr, rsr, nsr))
  basd = -9999.0
  gasd = -9999.0
  rasd = -9999.0

f.close()

pntDS = None


import random, os.path
import pygame
from pygame.locals import *

SCREENRECT = Rect(0, 0, 640, 480)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
ENEMYODDS = 60
ENEMYRELOAD = 12
FPS = 60

class Player(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self, self.containers)
        width = 40
        height = 60
        self.image = pygame.Surface([width, height])
        self.image.fill(GREEN)

        self.rect = self.image.get_rect()

        self.change_x = 1
        self.change_y = 0
        self.x = 1 * 5
        self.y = 100
        self.rect.top = 100
        self.rect.left = 100

    def update(self):
        self.rect.top += 1

    def lift(self):
        self.rect.bottom = self.rect.bottom - 14
        self.rect.x += 1

class Enemy(pygame.sprite.Sprite):
    speed = 13
    def __init__(self):
        pygame.sprite.Sprite.__init__(self, self.containers)
        img_height = random.randint(100, 200)
        self.image = pygame.Surface([40, img_height])
        self.image.fill(RED)
        self.rect = self.image.get_rect()
        self.x = -1
        self.y = 0
        self.rect.top = random.choice([0, (SCREENRECT.height - img_height)])
        self.rect.right = 640

    def update(self):
        self.rect.move_ip(self.x, 0)
        if self.rect.right <= 0:
            self.kill()

def main(winstyle = 0):
    pygame.init()
    winstyle = 0
    bestdepth = pygame.display.mode_ok(SCREENRECT.size, winstyle, 32)
    screen = pygame.display.set_mode(SCREENRECT.size, winstyle, bestdepth)
    pygame.display.set_caption('blockplane')
    pygame.mouse.set_visible(0)

    #bgtile = pygame.image.load('../data/background.gif') #chnage this to default color
    background = pygame.Surface(SCREENRECT.size)

    screen.blit(background, (0, 0))
    pygame.display.flip()

    #images

    #initalize game objects

    enemies = pygame.sprite.Group()
    all = pygame.sprite.RenderUpdates()
    Player.containers = all
    Enemy.containers = enemies, all

    global score
    enemyreload = ENEMYRELOAD

    clock = pygame.time.Clock()

    #initialize starting sprites of game

    global SCORE
    player = Player()

    going = True
    while player.alive():

        for event in pygame.event.get():
            if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
                going = False
                return
            if event.type == KEYDOWN:
                if event.key == K_UP:
                    player.lift()

        all.clear(screen, background)
        all.update()

        if enemyreload: #reload
            enemyreload = enemyreload - 1
        elif not int(random.random() * ENEMYODDS): #check ENEMYODDS
            Enemy()
            enemyreload = ENEMYRELOAD #check ENEMYRELOAD

        for enemy in pygame.sprite.spritecollide(player, enemies, 1):
            player.kill()

        dirty = all.draw(screen)
        pygame.display.update(dirty)

        clock.tick(FPS)

    pygame.time.wait(1000)
    pygame.quit()

if __name__ == '__main__':
    main()


"""
problem 32: Longest Valid Parentheses
https://leetcode.com/problems/longest-valid-parentheses/

solution:
    https://leetcode.com/problems/longest-valid-parentheses/solution/
    DP:
    Use a table(length equal to s) to store the length of the longest
    valid substring ending at iith index.
    The table is initialized with 0's.
    At index i, if s[i] is ')' and s[i - 1] is '(', then table[i] = table[i - 2] + 2
                if s[i] is ')' and s[i - 1] is ')', then the next index we need to
                check is: i - table[i - 1] - 1, if s[i - table[i - 1] - 1] is '(',
                table[i] = table[i - 1] + table[i - table[i - 1] - 2] + 2
"""
class Solution:
    def longestValidParentheses(self, s):
        """
        :type s: str
        :rtype: int
        """
        if not s:
            return 0
        left_paren = '('
        right_paren = ')'
        length = len(s)
        table = [0] * length
        for index in range(1, length):
            if s[index] == right_paren:
                if s[index - 1] == left_paren:
                    if index >= 2:
                        table[index] = table[index - 2] + 2
                    else:
                        table[index] = 2
                else:
                    temp_index = index - table[index - 1] - 1
                    if temp_index >= 0 and s[temp_index] == '(':
                        if temp_index > 0:
                            table[index] = table[temp_index - 1] + table[index - 1] + 2
                        else:
                            table[index] = table[index - 1] + 2
        return max(table)


import argparse
import pickle
from sklearn.linear_model import LinearRegression
import time

class Trainer():
    def __init__(self, uid):
        self.uid = uid
        # df = pd.read_csv("%s.csv"%uid) など
        pass

    def fit(self):
        model = LinearRegression()

        # 学習部分は省略
        print("学習開始")
        time.sleep(5) # 5秒待機
        print("学習終了")

        with open("model/%s_model.pkl"%self.uid, 'wb') as f:
                pickle.dump(model, f)
        return

if __name__=="__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('-i', '--uid', dest='uid', type=str, required=True)
    args = parser.parse_args()

    print("uid", args.uid)

    tr = Trainer(args.uid)
    tr.fit()


#!/usr/bin/env python3

#  http://stackoverflow.com/questions/35741435/how-to-listen-for-event-of-closed-stdin-in-a-tornado-loop

import sys
from tornado.ioloop import IOLoop

async def handle(line):
    print('> %s\n' % line.strip())

def main():
    ioloop = IOLoop.instance()
    ioloop.add_handler(
        sys.stdin,
        lambda fd, event: ioloop.add_callback(handle, fd.readline()),
        IOLoop.READ)

    print('waiting input ...\n')
    try:
        ioloop.start()
    except KeyboardInterrupt:
        print('\nbye')
        exit(0)

if __name__ == '__main__':
    main()


from __future__ import print_function
import psutil

def rss():  # 输出进程的 rss 内存大小
    m = psutil.Process().memory_info()
    print(m.rss >> 20, "MB")

if __name__ == "__main__":
    rss()  # 起始内存
    x = list(range(10000000))  # 使用列表持有海量数据对象
    rss()  # 输出海量对象产生的内存开销
    del x  # 删除列表，回收数字对象
    rss()  # 输出回收后的内存占用


# create a box that inserts * based off of the user's input

num_of_lines = int(input('How big is the square? '))

def squareysquare(num):
    placey_place = ''
    lines = 0
    while lines < num:
        lines = lines + 1
        placey_place += ('*' * num) + '\n'
    return placey_place

print(squareysquare(num_of_lines))


def standaardprijs(afstandKM):
    varP = 0.80
    conP = 0
    if afstandKM < 0:
        afstandKM = 0
    elif afstandKM > 50:
        varP += 0.60
        conP = 15
    return varP * afstandKM + conP

def ritprijs(leeftijd, weekendrit, afstandKM):
    p_start = standaardprijs(afstandKM)
    korting = 0
    if leeftijd < 12 or leeftijd >= 65:
        if not weekendrit:
            korting = 0.3
        else:
            korting = 0.35
    else:
        if weekendrit:
            korting = 0.4
    p_end = 0
    if korting > 0:
        p_end = p_start / (1 + korting)
    else:
        p_end = p_start
    return p_end


import os
import json
import glob
import re

def get_next_listdir(*args):
	pass

def write_json(name,table):
	with open(name, 'w') as file:
		json.dump(table,file)
	file.close()

general_path = 'media/artist'
ARTIST = os.listdir(general_path)

array = dict()

json_table_artist = []
pk_artist = 0
json_table_albums = []
pk_album = 0
json_table_song = []
pk_song = 0

for artist in ARTIST:
	pk_artist+=1
	album_array = {} # dict album:song
	json_table_artist.append(
								{
							    "model": "music.artist",
							    "pk": pk_artist,
							    "fields": {
							        "title": artist,
							    		}
								}
							)
	for album in os.listdir(os.path.join(general_path, artist)):
		pk_album+=1
		json_table_albums.append(
									{
								    "model": "music.album",
								    "pk": pk_album,
								    "fields": {
										"artist": pk_artist,
								        "title": album,
								        "path_cover": 'none',
						    			}
									}
								)

		album_array[album] = [os.path.join(general_path,artist, album, i)
		 						for i in os.listdir(os.path.join(general_path, artist, album))]

		for path_song in album_array[album]:
			if '.jpg' in path_song:
				path_cover = path_song
				json_table_albums[-1]['fields']['path_cover'] = path_song
			else:
				pk_song+=1
				json_table_song.append(
											{
										    "model": "music.list_track",
										    "pk": pk_song,
										    "fields": {
										    		  "artist": pk_artist,
												      "album": pk_album,
												      "title": os.path.split(path_song)[-1],
												      "path": path_song
												    }
											}
										)
write_json('music/fixtures/artist.json', json_table_artist)
write_json('music/fixtures/album.json', json_table_albums)
write_json('music/fixtures/song.json', json_table_song)


"""Helper functions for scraping options data"""
__docformat__ = "numpy"

import argparse
import os
from typing import List
import configparser
import requests
import pandas as pd
from tabulate import tabulate
from gamestonk_terminal.helper_funcs import parse_known_args_and_warn

presets_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), "presets/")

def view_available_presets(other_args: List[str]):
    """View available presets.

    Parameters
    ----------
    other_args: List[str]
        Other arguments to be parsed
    """
    parser = argparse.ArgumentParser(
        add_help=False,
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        prog="view",
        description="""View available presets under presets folder.""",
    )
    parser.add_argument(
        "-p",
        "--preset",
        action="store",
        dest="preset",
        type=str,
        help="View specific preset",
        default="",
        choices=[
            preset.split(".")[0]
            for preset in os.listdir(presets_path)
            if preset[-4:] == ".ini"
        ],
    )

    try:
        if other_args:
            if "-" not in other_args[0]:
                other_args.insert(0, "-p")
        ns_parser = parse_known_args_and_warn(parser, other_args)
        if not ns_parser:
            return

        if ns_parser.preset:
            preset_filter = configparser.RawConfigParser()
            preset_filter.optionxform = str  # type: ignore
            preset_filter.read(presets_path + ns_parser.preset + ".ini")

            filters_headers = ["FILTER"]

            print("")
            for filter_header in filters_headers:
                print(f" - {filter_header} -")
                d_filters = {**preset_filter[filter_header]}
                d_filters = {k: v for k, v in d_filters.items() if v}
                if d_filters:
                    max_len = len(max(d_filters, key=len))
                    for key, value in d_filters.items():
                        print(f"{key}{(max_len-len(key))*' '}: {value}")
                print("")

        else:
            presets = [
                preset.split(".")[0]
                for preset in os.listdir(presets_path)
                if preset[-4:] == ".ini"
            ]

            for preset in presets:
                with open(
                    presets_path + preset + ".ini",
                    encoding="utf8",
                ) as f:
                    description = ""
                    for line in f:
                        if line.strip() == "[FILTER]":
                            break
                        description += line.strip()
                print(f"\nPRESET: {preset}")
                print(description.split("Description: ")[1].replace("#", ""))
            print("")
    except Exception as e:
        print(e)

def screener_output(other_args: List[str]):
    """screener filter output"""
    parser = argparse.ArgumentParser(
        add_help=False,
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        prog="scr",
        description="""Sreener filter output from https://ops.syncretism.io/index.html.
Where: CS: Contract Symbol; S: Symbol, T: Option Type; Str: Strike; Exp v: Expiration;
IV: Implied Volatility; LP: Last Price; B: Bid; A: Ask; V: Volume; OI: Open Interest;
Y: Yield; MY: Monthly Yield; SMP: Regular Market Price; SMDL: Regular Market Day Low;
SMDH: Regular Market Day High; LU: Last Trade Date; LC: Last Crawl; ITM: In The Money;
PC: Price Change; PB: Price-to-book. """,
    )
    parser.add_argument(
        "-p",
        "--preset",
        action="store",
        dest="preset",
        type=str,
        default="template",
        help="Filter presets",
        choices=[
            preset.split(".")[0]
            for preset in os.listdir(presets_path)
            if preset[-4:] == ".ini"
        ],
    )

    try:
        if other_args:
            if "-" not in other_args[0]:
                other_args.insert(0, "-p")

        ns_parser = parse_known_args_and_warn(parser, other_args)
        if not ns_parser:
            return

        d_cols = {
            "contractsymbol": "CS",
            "symbol": "S",
            "opttype": "T",
            "strike": "Str",
            "expiration": "Exp ∨",
            "impliedvolatility": "IV",
            "lastprice": "LP",
            "bid": "B",
            "ask": "A",
            "volume": "V",
            "openinterest": "OI",
            "yield": "Y",
            "monthlyyield": "MY",
            "regularmarketprice": "SMP",
            "regularmarketdaylow": "SMDL",
            "regularmarketdayhigh": "SMDH",
            "lasttradedate": "LU",
            "lastcrawl": "LC",
            "inthemoney": "ITM",
            "pchange": "PC",
            "pricetobook": "PB",
        }

        preset_filter = configparser.RawConfigParser()
        preset_filter.optionxform = str  # type: ignore
        preset_filter.read(presets_path + ns_parser.preset + ".ini")

        d_filters = {k: v for k, v in dict(preset_filter["FILTER"]).items() if v}
        s_filters = str(d_filters)
        s_filters = s_filters.replace(": '", ": ").replace("',", ",").replace("'}", "}")
        s_filters = s_filters.replace("'", '"')

        link = "https://api.syncretism.io/ops"

        res = requests.get(
            link, headers={"Content-type": "application/json"}, data=s_filters
        )

        if res.status_code == 200:
            df_res = pd.DataFrame(res.json())

            if df_res.empty:
                print(f"No options data found for preset: {ns_parser.preset}", "\n")
                return

            df_res = df_res.rename(columns=d_cols)[list(d_cols.values())[:17]]

            print(
                tabulate(
                    df_res,
                    headers=df_res.columns,
                    showindex=False,
                    tablefmt="fancy_grid",
                )
            )
        else:
            print("Wrong arguments specified. Error " + str(res.status_code))
        print("")

    except Exception as e:
        print(e, "\n")


import sys
sys.path.append('src')
import scipy.sparse as sparse
from scipy.sparse import csgraph
import scipy.sparse as sp
import numpy as np
import theano
from theano import tensor as T
from utils.errors import MissingParamError
from utils.utils import log_filter, binary_filter
import math

def direct_compute_deepwalk_matrix(A, args, logger):
    res = {}
    try:
        windows = args["prox_params"]['window']
        b = args["prox_params"]['negative']
        transform = args["prox_params"]['transform']
        threshold = args["prox_params"]['threshold']
    except KeyError:
        raise MissingParamError
    for window in windows:
        n = A.shape[0]
        vol = float(A.sum())
        L, d_rt = csgraph.laplacian(A, normed=True, return_diag=True)
        # X = D^{-1/2} A D^{-1/2}
        X = sparse.identity(n) - L
        S = np.zeros_like(X)
        X_power = sparse.identity(n)
        for i in range(window):
            logger.info("Deep Walk %d-th power, %d/%d", i+1, i+1, window)
            X_power = X_power.dot(X)
            S += X_power
        S *= vol / window / b
        D_rt_inv = sparse.diags(d_rt ** -1)
        M = D_rt_inv.dot(D_rt_inv.dot(S).T)
        m = T.matrix()
        if transform == 1:
            logger.info("log transform")
            res[window] = log_filter(M, threshold)
            # res[window] = log_filter(M)
        elif transform == 2:
            res[window] = binary_filter(M, logger, threshold)
        else:
            logger.info("no transform")
            res[window] = sparse.csr_matrix(M)
    return res


from mnist import load_dataset
from pdt.train_tf import compile_fns
from pdt.common import gen_sfx_key
from wacacore.util.io import  mk_dir
from wacacore.util.misc import *
from wacacore.util.generators import infinite_samples, infinite_batches
from pdt.types import (Type, Interface, Const, Axiom, ForAllVar,
                       AbstractDataType, ProbDataType)
from common import handle_options, load_train_save
import tensorflow as tf
import sys

def gen_queue_adt(train_data,
                  options,
                  queue_shape=(28, 28, 1),
                  enqueue_args={},
                  dequeue_args={},
                  empty_queue_args={},
                  item_shape=(28, 28, 1),
                  batch_size=512,
                  nitems=3):
    """Construct a queue abstract data type"""
    # Types - a Queue of Item
    Queue = Type(queue_shape, 'Queue')
    Item = Type(item_shape, 'Item')

    # Interface

    # Push an Item onto a Queue to create a new queue
    enqueue = Interface([Queue, Item], [Queue], 'enqueue', **enqueue_args)
    # Pop an Item from a queue, returning a new queue and the item
    dequeue = Interface([Queue], [Queue, Item], 'dequeue', **dequeue_args)
    interfaces = [enqueue, dequeue]

    # train_outs
    train_outs = []
    gen_to_inputs = identity

    # Consts
    # The empty queue is the queue with no items
    empty_queue = Const(Queue, 'empty_queue', batch_size, **empty_queue_args)
    consts = [empty_queue]

    # Vars
    # queue1 = ForAllVar(Queue)
    items = [ForAllVar(Item, str(i)) for i in range(nitems)]
    forallvars = items

    generators = [infinite_batches(train_data, batch_size, shuffle=True)
                  for i in range(nitems)]

    # Axioms
    axioms = []
    queue = empty_queue.batch_input_var
    for i in range(nitems):
        (queue,) = enqueue(queue, items[i].input_var)
        dequeue_queue = queue
        for j in range(i + 1):
            (dequeue_queue, dequeue_item) = dequeue(dequeue_queue)
            axiom = Axiom((dequeue_item,), (items[j].input_var,))
            axioms.append(axiom)
    train_fn, call_fns = compile_fns(interfaces, consts, forallvars, axioms,
                                     train_outs, options)
    queue_adt = AbstractDataType(interfaces, consts, forallvars, axioms,
                                 name='queue')
    queue_pdt = ProbDataType(queue_adt, train_fn, call_fns,
                             generators, gen_to_inputs, train_outs)
    return queue_adt, queue_pdt

def main(argv):
    global queue_adt, queue_pdt, sess, X_train, sfx
    options = handle_options('queue', argv)

    mnist_data = load_dataset()
    X_train = mnist_data[0].reshape(-1, 28, 28, 1)
    sfx = gen_sfx_key(('adt', 'nblocks', 'block_size'), options)

    empty_queue_args = {'initializer': tf.random_uniform_initializer}
    queue_adt, queue_pdt = gen_queue_adt(X_train,
                                         options,
                                         enqueue_args=options,
                                         nitems=options['nitems'],
                                         dequeue_args=options,
                                         empty_queue_args=empty_queue_args,
                                         batch_size=options['batch_size'])

    savedir = mk_dir(sfx)
    sess = load_train_save(options, queue_adt, queue_pdt, sfx, savedir)

if __name__ == "__main__":
    main(sys.argv[1:])


import logging

from runner import LiveServerThread, LiveServerProcess
from browsers import ApiParser, SeleniumBrowser

from zig import Zig

"""class ThreadComposite:

    def __init__(self, thread=None):
        # use a common
        self.app = app
"""

logger = logging.getLogger(__name__)

class Controller(object):
    """ Able to plug in any type of server
    """
    #NOTE: Question, should thread and process both be managed by the same object?
    # what problems might it cause?
    # NOTE PRO: test code can decide on its own either to use thread or subprocess
    # from the same interface

    def __init__(self, *arg, thread=None, process=None, **kwargs):
        self.thread_started = None
        self.process_started = None

        self.server_thread = thread if thread else LiveServerThread()
        self.server_process = process if process else LiveServerProcess()

    def __call__(self, *args, **kwarg):
        pass

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, exc_traceback):
        if self.server_thread and self.thread_started:
            # close thread
            try:
                self.server_thread.close()
            except Exception:
                #TODO: need a better way to handle this
                raise
            finally:
                self.server_thread.join()
                logger.info("thread exit")

        if self.process_started and self.server_process:
            try:
                self.server_process.close()
            finally:
                self.server_process.join()

            logger.info("Subprocess exit")

    def start_server_thread(self, app: Zig):
        # assign zig app here
        self.server_thread.app = app

        try:
	        self.server_thread.start()
        except RuntimeError:
            raise

        self.thread_started = self.server_thread.is_alive()
        return self.server_thread

    def start_subprocess(self, app: Zig):
        # set this up with gunicorn
        # other options
        # TODO: test compatibility with WSGI server
        self.server_process.app = app

        try:
            self.server_process.start()
        except RuntimeError:
            raise

        self.process_started = self.server_process.is_alive()
        return self.server_process

class ApiParserThread(Controller, ApiParser):

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

class SeleniumBrowserThread(Controller, SeleniumBrowser):

    def __init__(self, *args, **kwargs):
        super().__init__(self, *args, **kwargs)
        SeleniumBrowser.__init__(self, *args, **kwargs)


import pygame
import sys
from random import randint
from math import sin, cos, acos, sqrt
from time import time

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)

w = 720
h = 720

class Vector(object):
    def __init__(self, length, angle):
        self.length = length
        self.angle = angle
        self.x = cos(self.angle) * self.length
        self.y = sin(self.angle) * self.length

class Star(object):
    # vector length = point speed
    def __init__(self, x, y, a, size=1, color=WHITE, speed=0):
        self.size = size
        self.color = color
        self.speed = speed
        self.a = a
        self.x = x
        self.y = y

        length = sqrt((w / 2 - x)**2 + (h / 2 - y)**2)
        vecAngl = acos((self.x - w / 2) / length)
        if self.y > h / 2:
            vecAngl = -vecAngl

        self.vec = Vector(self.speed, -vecAngl)

    def move(self):
        self.x += self.vec.x
        self.y += self.vec.y
        self.vec = Vector(self.vec.length + self.a, self.vec.angle)

    def draw(self, scr, oldX, oldY):
        pygame.draw.line(scr, self.color, (int(self.x), int(self.y)), (int(oldX), int(oldY)), self.size)

class Display(object):
    def __init__(self, width, height, count):
        pygame.init()
        self.clock = pygame.time.Clock()
        self.screen = pygame.display.set_mode((width, height))
        self.caption = "Starfield"
        pygame.display.set_caption(self.caption)
        self.font = pygame.font.Font(None, 36)
        self.status = True
        self.count = count
        self.frame_rate = 120
        self.stars = []
        self.maxA = 0.019
        self.maxL = sqrt((w / 2)**2 + (h / 2)**2)

    def create_stars(self):
        count = self.count - len(self.stars)
        for i in range(count):
            x = randint(0, w)
            y = randint(0, h)
            length = sqrt((w / 2 - x)**2 + (h / 2 - y)**2)
            while length < 30:
                x = randint(0, w)
                y = randint(0, h)
                length = sqrt((w / 2 - x) ** 2 + (h / 2 - y) ** 2)

            L = sqrt((w / 2 - x)**2 + (h / 2 - y)**2)
            a = self.maxA * (self.maxL / L)

            self.stars.append(Star(x, y, a))

    def update(self):
        pygame.display.update()
        self.clock.tick(self.frame_rate)

    def handle_events(self):
        key = pygame.key.get_pressed()

        for event in pygame.event.get():
            if event.type == pygame.QUIT or key[pygame.K_ESCAPE]:
                pygame.quit()
                sys.exit()

        if key[pygame.K_UP]:
            self.maxA += 0.003
        if key[pygame.K_DOWN]:
            self.maxA -= 0.003
        if key[pygame.K_RIGHT]:
            self.count += 1
        if key[pygame.K_LEFT]:
            self.count -= 1
        if key[pygame.K_F1]:
            pygame.image.save(self.screen, "Screenshots/starfield_" + str(time()) + '.jpeg')

    def draw(self):
        self.screen.fill(BLACK)
        for star in self.stars:
            oldX = star.x
            oldY = star.y

            star.move()

            if (star.x > w or star.x < 0) or (star.y > h or star.y < 0):
                indx = self.stars.index(star)
                del self.stars[indx]
                self.create_stars()
            else:
                star.draw(self.screen, oldX, oldY)

    def show_info(self):
        if self.maxA < 0:
            speed = str(self.maxA)[0:6]
        else:
            speed = str(self.maxA)[0:5]

        sp = self.font.render('speed: ' + speed, 1, WHITE)
        cnt = self.font.render('count: ' + str(self.count), 1, WHITE)
        self.screen.blit(sp, (10, 10))
        self.screen.blit(cnt, (200, 10))

    def main(self):
        self.create_stars()
        while self.status:
            self.handle_events()
            self.draw()
            self.show_info()
            self.update()

starfield = Display(w, h, 250)

if __name__ == '__main__':
    starfield.main()


import pandas as pd
import numpy as np
import sklearn.metrics.pairwise as pw
from scipy import sparse
from sklearn.metrics.pairwise import pairwise_distances
from flask import Flask, render_template, request

def itembased_movie_recommender(movie_name):
    final_movies=pd.read_csv(r"movies_final.csv")
    movie_name=movie_name.lower()
    if movie_name not in final_movies['title'].unique():
        return "This movie is not in Database. Please enter an other movie"
    else:

        pivot_ibr = pd.pivot_table(final_movies,
                                          index='title',
                                          columns=['userId'], values='rating')
        sparse_ibr = sparse.csr_matrix(pivot_ibr.fillna(0))
        recommender_ibr = pw.cosine_similarity(sparse_ibr)
        recommender_ibr_df=pd.DataFrame(recommender_ibr,
                                      columns=pivot_ibr.index,
                                      index=pivot_ibr.index)
        cosine_ibr_df = pd.DataFrame(recommender_ibr_df[movie_name].sort_values(ascending=False))
        cosine_ibr_df.reset_index(level=0, inplace=True)
        cosine_ibr_df.columns = ['title','cosine_sim']
        list_movies=list((cosine_ibr_df['title'].values))
        return list_movies[1:11]
# print(itembased_movie_recommender('inception'))

app = Flask(__name__)
@app.route("/")
def home():
    return render_template('home.html')

@app.route("/recommend")
def recommend():
    movie = request.args.get('movie')
    movie_list=itembased_movie_recommender(movie)
    movie=movie.upper()
    if type(movie_list)==type('string'):
        return render_template('recommend.html',movie=movie,movie_list=movie_list,t='s')
    else:
        return render_template('recommend.html',movie=movie,movie_list=movie_list,t='l')

if __name__=='__main__':
    app.debug = True
    app.run()


import logging

from ESCGProject import app, database, paypal
#from ESCGProject import app, paypal
from flask import Flask, render_template, request, redirect, url_for, flash, session
from ESCGProject.forms import RegistrationForm, LoginForm, PaymentForm, WithdrawForm
from ESCGProject.utils import getImages, encrypt, decrypt

from ESCGProject.database import db_session, CheckUser, GetUser
from ESCGProject.models import *

from ESCGProject.paypal import MakeAPayment, PayOut

from sqlalchemy.exc import StatementError, SQLAlchemyError

import random
import os
import array

@app.route('/', methods=['GET', 'POST'])
def empty():
	if 'username' in session:
		return render_template('info.html')
	return redirect(url_for('login'))

@app.route('/CheckWinServer', methods=['GET', 'POST'])
def CheckWinServer():
	thecard = request.form['card_id']
	# Taken from https://www.youtube.com/watch?v=lsflaKpeB7Q
	inlist = [int(s) for s in thecard[1:-1].split(',')]
	decypted_card_id = decrypt(array.array('B', inlist).tostring())
	current_user = database.CheckCard(int(decypted_card_id),session['username'])
	balance = current_user.balance
	return str(balance)

@app.route('/login', methods=['GET', 'POST'])
def login():
	form = LoginForm(request.form)
	if request.method =='POST':
		overlay_img=url_for('static', filename='overlay.jpg')
		user = database.CheckUser(form.username.data,form.password.data)
		if not user:
			flash('User name or password incorrect')
			return render_template('login.html',form=form)
		else:
			session['username'] = form.username.data
			return render_template('info.html')
	return render_template('login.html',form=form)

@app.route('/logout', methods=['GET', 'POST'])
def logout():
	form = LoginForm(request.form)
	session.pop('username', None)
	return render_template('login.html',form=form)

@app.route('/main', methods=['GET', 'POST'])
def main():
	if 'username' in session:
		current_user = database.GetUser(session['username'])
		overlay_img=url_for('static', filename='overlay.jpg')
		return render_template('main.html',balance=current_user.balance,overlay_img=overlay_img)
	return redirect(url_for('login'))

@app.route('/register', methods=['GET', 'POST'])
def register():
	form = RegistrationForm(request.form)
	if request.method == 'POST' and form.validate():
		user = database.GetUser(form.username.data)
		if user is None:
			database.AddUser(form.username.data,form.email.data,form.password.data)
			flash('Thanks for registering')
			session['username'] = form.username.data
			return render_template('info.html')
		flash('Username already exists')
		return render_template('register.html', form=form)
	return render_template('register.html', form=form)

@app.route('/buyCard', methods=['GET', 'POST'])
def buyCard():
	if 'username' in session:
		current_user = database.GetUser(session['username'])
		if current_user.balance < 1:
			flash('You do not have enough funds')
			return render_template('main.html',balance=current_user.balance,overlay_img="./static/overlay.jpg")
		else:
			current_user.balance = current_user.balance - 1
			a_card = database.RetrieveCard()
			current_user = database.GetUser(session['username'])
			database.AddCardToUser(a_card.id,current_user.id)
			encrypted_card_id = encrypt(a_card.id)
			if a_card.value == 0:
				amount = random.choice([1,2,5,10,20])
				image_list = getImages(False,6)
			else:
				db_session.commit()
				image_list = getImages(True,6)
				amount = a_card.value
			return render_template('main.html',amount=amount,balance=current_user.balance,imagelist=image_list,card_id=encrypted_card_id)
	return redirect(url_for('login'))

@app.route('/Deposit', methods=['GET', 'POST'])
def DepositMoney():
	if 'username' in session:
		form = PaymentForm(request.form)
		if request.method == 'POST' and form.validate():
			current_user = database.GetUser(session['username'])
			payment_result = paypal.MakeAPayment(form.card_type.data,form.number.data,form.month.data,form.year.data,form.cvv2.data,form.firstname.data,form.lastname.data,form.totalAmount.data)
			if payment_result == True:
				topUp = form.totalAmount.data
				current_user.balance = current_user.balance + float(topUp)
				db_session.commit()
				return render_template('main.html',balance=current_user.balance,overlay_img="./static/overlay.jpg")
			else:
				flash("Payment unsuccessful")
				return render_template('main.html',balance=current_user.balance,overlay_img="./static/overlay.jpg")
		return render_template('deposit.html',form=form)
	return redirect(url_for('login'))

@app.route('/withdraw', methods=['GET', 'POST'])
def withdraw():
	if 'username' in session:
		form = WithdrawForm(request.form)
		current_user = database.GetUser(session['username'])
		if request.method == 'POST'  and form.validate():
			if int(form.totalAmount.data) > current_user.balance:
				flash("You do not have enough funds")
				return render_template('withdraw.html',balance=current_user.balance,form=form)
			payout_result = PayOut(current_user.email,form.totalAmount.data)
			print(payout_result)
			if payout_result == "SUCCESS":
				current_user.balance = current_user.balance - int(form.totalAmount.data)
				db_session.commit()
			else:
				flash("There has been a problem in the payout process. Please try again")
				return render_template('withdraw.html',balance=current_user.balance,form=form)
		return render_template('withdraw.html',balance=current_user.balance,form=form)
	return redirect(url_for('main'))

@app.route('/info', methods=['GET', 'POST'])
def info():
	if 'username' in session:
		return render_template('info.html')
	return redirect(url_for('login'))


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

"""
    task.formcapture
   ~~~~~~~~~~~~~~~~~

    HTMLファイルの画面ハードコピーを取る。
"""

import subprocess
import urllib
import os, platform
import errno, signal
import time
from image import triming

CREATE_NO_WINDOW = 0x8000000

import logging
import traceback
logger = logging.getLogger(__file__)

IS_WINDOWS = (os.name == 'nt')

def generate_capture(exepath, html_path, img_path):
    """  HTML画面キャプチャを取得し、png形式で出力。

    * exepath: コマンド
    * html_path: HTMLファイルパス
    * img_path: 結果出力パス
    """

    timeout = 10

    try:
        if IS_WINDOWS:
            page_uri = 'file:%s' % urllib.pathname2url(os.path.normpath(html_path))
            exepath += '.exe'
            cmd = [exepath, '--url=%s' % page_uri, '--out=%s' % img_path, '--max-wait=%s' % 30000]
            proc = subprocess.Popen(cmd, creationflags=CREATE_NO_WINDOW, bufsize=-1)
        else:
            page_uri = 'file://%s' % urllib.pathname2url(os.path.normpath(html_path))
            exepath += '64' if '64' in platform.machine() else ''
            #if os.getenv('DISPLAY'):
            cmd = [exepath, '--url=%s' % page_uri, '--out=%s' % img_path, '--max-wait=%s' % 30000]
            #else:
            #    cmd = ['xvfb-run', '-s', '-screen 0, 1024x768x24', exepath, '--url=%s' % page_uri, '--out=%s' % img_path]
            proc = subprocess.Popen(cmd, bufsize=-1)
        st = time.time()
        while time.time() - st <= timeout:
            if proc.poll() is not None:
                try:
                    triming(img_path)
                except:
                    raise
                finally:
                    return True
            else:
                time.sleep(0.1)

        logger.debug('dead process %s' % proc.pid)
        try:
            proc.terminate()
        except:
            logger.debug(traceback.format_exc())

        time.sleep(1)
        if proc.poll() is not None:
            try:
                proc.kill()
            except:
                logger.debug(traceback.format_exc())

        return False
    except:
        logger.debug(traceback.format_exc())
        #logger.debug('exepath = %s' % (exepath))
        #logger.debug('Error occured while tring to generate capture for %s -> %s' % (html_path, img_path))
        raise

def vfb(display_spec="1024x768x24", server=0, screen=0, auto_screen=True):
    """ run Xvfb and set DISPLAY env
    """

    while True:
        try:
            devnull = open("/dev/null", "w")
            proc = subprocess.Popen(["Xvfb", ":%d" % server, "-screen", "%d" % screen, display_spec],
                                    shell=False, stdout=devnull, stderr=devnull)
            os.environ["DISPLAY"] = ":%d.%d" % (server, screen)
            return (proc, screen)
        except:
            logger.debug(traceback.format_exc())
            if not auto_screen:
                break
            screen += 1

from functools import wraps

def xvfb(f):
    """ヘッドレスでGUI環境を立ち上げる"""
    @wraps(f)
    def func(*args, **kws):
        if not IS_WINDOWS:
            p, s = vfb()

        rslt = f(*args, **kws)

        if not IS_WINDOWS:
            p.terminate()

        return rslt

    return func


# example of scaling the dataset
from sklearn.datasets import make_blobs
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
# prepare dataset
X, y = make_blobs(n_samples=100, centers=2, n_features=2, random_state=1)
# split data into train and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=1)
# define scaler
scaler = MinMaxScaler()
# fit scaler on the training dataset
scaler.fit(X_train)
# transform both datasets
X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)
# summarize the scale of each input variable
for i in range(X_test.shape[1]):
	print('>%d, train: min=%.3f, max=%.3f, test: min=%.3f, max=%.3f' %
		(i, X_train_scaled[:, i].min(), X_train_scaled[:, i].max(),
			X_test_scaled[:, i].min(), X_test_scaled[:, i].max()))


import os
import json
import random
import subprocess
import urllib.parse

with open('folders.txt', 'r') as fold_file:
    class_paths = [line.strip() for line in fold_file if line.strip()]

classes = dict()

for idx, class_path in enumerate(class_paths):
    class_name = os.path.basename(class_path)
    for root, _, filenames in os.walk(class_path):
        for filename, ext in map(os.path.splitext, filenames):
            if ext != '.mp4':
                continue
            filename_q = urllib.parse.unquote(filename)
            if filename_q not in classes:
                duration = str(subprocess.check_output(
                    ('ffprobe', '-v', 'error', '-show_entries',
                     'format=duration', '-of',
                     'default=noprint_wrappers=1:nokey=1',
                     os.path.join(root, filename + ext))),
                               encoding='utf-8').strip()
                classes[filename_q] = {
                    'subset':
                    'training' if random.random() < 0.8 else 'testing',
                    'duration': float(duration),
                    'actions': [[idx, 0, float(duration)]]
                }

print(json.dumps(classes, indent=2))


from __future__ import print_function
from linklist import SimpleNode as Node
from linklist import printlist
from time import sleep

def isCircular(head):
    curr = head
    if head is None:
        return False

    while curr.next is not None and curr.next is not head:
        curr = curr.next

    if curr.next is head:
        return True
    else:
        return False

if __name__ == "__main__":
    head = tail = Node(10, None)
    for i in xrange(10):
        head = Node(i, head)

    printlist(head)
    print("iscircular , " , isCircular(head))
    tail.next = head

    printlist(head)
    print("iscircular , " , isCircular(head))


import pandas as pd
from rich import pretty, print
from rich.progress import BarColumn, Progress
from sklearn.metrics import accuracy_score, f1_score
from sklearn.neural_network import MLPClassifier
from sklearn.preprocessing import LabelEncoder

import utils

def execute_and_report(learn_rate, acti, current_params):
    clf = MLPClassifier(
        activation=acti,
        learning_rate_init=learn_rate,
        random_state=5213890,
        **current_params,
    )
    clf.fit(train_x, train_y)

    # Apply on the test set and evaluate the performance
    y_pred = clf.predict(test_x)
    acc = accuracy_score(test_y, y_pred) * 100
    f1 = f1_score(test_y, y_pred, average="weighted") * 100
    if acc + f1 > 173:
        return {
            "Params": f"{acti}, {learn_rate}, {current_params['hidden_layer_sizes']}",
            "accuracy %": round(acc, 2),
            "F1 weighted %": round(f1, 2),
        }

pretty.install()
pd.set_option("display.max_rows", None)

# DATASET
train_x, train_y, test_x, test_y = utils.load_tracks_xyz(
    buckets="discrete", extractclass=("album", "type"), splits=2
).values()

# feature to reshape
label_encoders = dict()
column2encode = [
    ("track", "language_code"),
    ("album", "listens"),
    ("track", "license"),
    ("album", "comments"),
    ("album", "date_created"),
    ("album", "favorites"),
    ("artist", "comments"),
    ("artist", "date_created"),
    ("artist", "favorites"),
    ("track", "comments"),
    ("track", "date_created"),
    ("track", "duration"),
    ("track", "favorites"),
    ("track", "interest"),
    ("track", "listens"),
]
for col in column2encode:
    le = LabelEncoder()
    le.fit(test_x[col])
    train_x[col] = le.fit_transform(train_x[col])
    test_x[col] = le.fit_transform(test_x[col])
    label_encoders[col] = le

le = LabelEncoder()
le.fit(train_y)
test_y = le.fit_transform(test_y)
train_y = le.fit_transform(train_y)

class_name = ("album", "type")

# Preparation
count = 0
reports = pd.DataFrame(columns=["Params", "accuracy %", "F1 weighted %"])
params = [
    {"hidden_layer_sizes": (350, 350, 350)},
    {"hidden_layer_sizes": (350, 350)},
    {"hidden_layer_sizes": (350, 250, 150, 100, 50, 20)},
    {"hidden_layer_sizes": (350, 200, 100, 50, 20)},
    {"hidden_layer_sizes": (350, 200, 20)},
    {"hidden_layer_sizes": (350, 100, 20)},
    {"hidden_layer_sizes": (350, 20)},
    {"hidden_layer_sizes": (40, 40, 40, 40, 40, 40)},
    {"hidden_layer_sizes": (40, 40, 40, 40, 40)},
    {"hidden_layer_sizes": (40, 40, 40, 40)},
    {"hidden_layer_sizes": (40, 40, 40)},
    {"hidden_layer_sizes": (40, 40)},
    {"hidden_layer_sizes": (40, 33, 27, 20, 13, 8)},
    {"hidden_layer_sizes": (40, 30, 20, 10, 5)},
    {"hidden_layer_sizes": (40, 30, 20, 10)},
    {"hidden_layer_sizes": (40, 20, 10)},
    {"hidden_layer_sizes": (40, 20, 8)},
    {"hidden_layer_sizes": (40, 20)},
]
testing_params = [{"hidden_layer_sizes": (10,)}]
activations = ["identity", "relu"]
learning_rate_inits = [0.01, 0.001, 0.02]

# progress reporting init
progress = Progress(
    "[progress.description]{task.description}",
    BarColumn(),
    "[progress.percentage]{task.percentage:>3.0f}%",
    "{task.completed} of {task.total}",
)

# grid search
with progress:

    task_layers = progress.add_task("[red]Hidden layer sizes…", total=len(params))
    task_learn = progress.add_task("[green]Learn rate…", total=len(learning_rate_inits))
    task_acti = progress.add_task("[cyan]Activation funcs…", total=len(activations))

    for current_params in params:
        progress.update(task_learn, completed=0)
        for learn_rate in learning_rate_inits:
            progress.update(task_acti, completed=0)
            for acti in activations:
                row = execute_and_report(learn_rate, acti, current_params)
                if row:
                    reports = reports.append(row, ignore_index=True)
                count += 1
                progress.advance(task_acti)
            progress.advance(task_learn)
        progress.advance(task_layers)

# results
print(reports.sort_values(by=["accuracy %", "F1 weighted %"], ascending=False))
print(f"I have built {count} neural networks")


def a_plus_b(a,b):
    c=a+b
    print(c)
    return c
result=a_plus_b(2234234223,2242352)
result2=a_plus_b(3,3)
name=input()
print(result)
print(result2)
print(name)

First  Month/my third lesson 01.07.2021/my fifth lesson 08.07.2021/My seventh lesson 26.07.2021/7.1.py


"""
   最值
"""
import numpy as np
import matplotlib.pyplot as mp
import datetime as dt
def dmy2ymd(dmy):
    dmy = str(dmy, encoding="utf-8")
    # 从指定字符串返回一个日期时间对象
    dat = dt.datetime.strptime(dmy, "%d-%m-%Y").date()
    tm = dat.strftime("%Y-%m-%d")  # 格式化
    return tm
datas,opening_prices,highest_prices,lowest_prices,closing_prices,volumes = \
    np.loadtxt('aapl.csv',delimiter=',',usecols=(1,3,4,5,6,7),
           dtype=('M8[D],f8,f8,f8,f8,f8'),unpack=True,converters={1:dmy2ymd})
max_val = np.max(highest_prices)
min_val = np.min(lowest_prices)
print(max_val,'~',min_val)
#获取最大值和最小值的下标
max_ind = np.argmax(highest_prices)
min_ind = np.argmin(lowest_prices)
print(max_ind,'~',min_ind)
print(datas[max_ind],datas[min_ind])

#maximum minimum
a = np.arange(1,10).reshape(3,3)
b = np.arange(1,10)[::-1].reshape(3,3)
print(a)
print(b)
print(np.maximum(a,b))
print(np.minimum(a,b))


#
# Copyright (c) dushin.net  All Rights Reserved
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#    * Redistributions of source code must retain the above copyright
#      notice, this list of conditions and the following disclaimer.
#    * Redistributions in binary form must reproduce the above copyright
#      notice, this list of conditions and the following disclaimer in the
#      documentation and/or other materials provided with the distribution.
#    * Neither the name of dushin.net nor the
#      names of its contributors may be used to endorse or promote products
#      derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY dushin.net ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL dushin.net BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
import os
import gc
from ulog import logger
import uhttpd

CONTENT_TYPE_MAP = {
    '.txt': "text/plain",
    '.html': "text/html",
    '.xhtml': "application/xhtml+xml",
    '.js': "text/javascript",
    '.css': "text/css",
    '.jpg': "image/jpeg",
    '.jpeg': "image/jpeg",
    '.png': "image/png",
    '.gif': "image/gif",
}

class Handler:
    def __init__(self, root_path='/www', block_size=1024):
        if not self.exists(root_path) or self.try_listdir(root_path) is None:
            msg = "Root path {} is not a valid directory".format(root_path)
            raise Exception(msg)
        self._root_path = root_path
        self._block_size = block_size

    #
    # callbacks
    #

    def handle_request(self, http_request):
        #
        # We only support GET
        #
        verb = http_request['verb']
        if verb != 'get':
            raise uhttpd.BadRequestException("Unsupported HTTP verb: {}".format(verb))
        # the relative path is the path on the HTTP request stripped of the
        # prefix used to register the file handler
        relative_path = uhttpd.get_relative_path(http_request)
        # the effective path is the relative path with the root path
        # prefixed, and normalized to remove '.' and '..'
        absolute_path = self.effective_path(relative_path)
        #
        # If the path is forbidden, 403 out
        #
        if not self.is_prefix(self._root_path, absolute_path):
            logger.info(
                "FORBIDDEN {}".format(absolute_path))
            raise uhttpd.ForbiddenException(absolute_path)
        #
        # If the path doesn't exist, 404 out
        #
        if not self.exists(absolute_path):
            logger.info(
                "NOT_FOUND {}".format(absolute_path))
            raise uhttpd.NotFoundException(absolute_path)
        #
        # Otherwise, generate a file listing or a file
        #
        dirlist = self.try_listdir(absolute_path)
        if dirlist is not None:
            if not relative_path.endswith('/'):
                return self.redirect_response(http_request['path']+'/')
            index_path = absolute_path + "/index.html"
            if self.exists(index_path):
                response = self.create_file_response(index_path)
                logger.info("INDEX {}".format(index_path))
                return response
            else:
                logger.info("DIR {}".format(absolute_path))
                prefix = http_request['prefix']
                return self.create_dir_listing_response(http_request['prefix'],relative_path,dirlist)
        else:
            logger.info("FILE {}".format(absolute_path))
            return self.create_file_response(absolute_path)

    #
    # internal operations
    #

    def create_file_response(self, path):
        length, body = self.generate_file(path)
        suffix = self.get_suffix(path)
        if suffix in CONTENT_TYPE_MAP:
            content_type = CONTENT_TYPE_MAP[suffix]
        else:
            content_type = "application/octet-stream"
        return self.create_response(200, content_type, length, body)

    def generate_file(self, path):
        f = open(path, 'r')
        serializer = lambda stream: self.stream_file(stream, f)
        return self.file_size(path), serializer

    def create_buffer(self):
        gc.collect()
        size = self._block_size
        while True:
            if size < 1:
                raise Exception("Unable to allocate buffer")
            try:
                return bytearray(size)
            except MemoryError:
                size //= 2

    def stream_file(self, stream, f):
        buf = self.create_buffer()
        while True:
            n = f.readinto(buf)
            if n:
                stream.write(buf[:n])
            else:
                break

    def effective_path(self, path):
        full_path = "{}/{}".format(self._root_path, path).rstrip('/')
        components = full_path.split('/')
        tmp = []
        for component in components:
            if component == '':
                pass
            elif component == "..":
                tmp = tmp[:len(tmp) - 1]
            elif component == '.':
                pass
            else:
                tmp.append(component)
        return "/{}".format('/'.join(tmp))

    @staticmethod
    def try_listdir(path):
        try:
            return os.listdir(path)
        except OSError:
            pass

    @staticmethod
    def exists(path):
        try:
            os.stat(path)
            return True
        except OSError:
            return False

    def create_dir_listing_response(self, prefix, path, dirlist):
        length, body = self.generate_dir_listing(prefix, path, dirlist)
        return self.create_response(200, "text/html", length, body)

    def generate_dir_listing(self, prefix, path, dirlist):
        def write_dir_listing(stream):
            stream.write("
uhttpd/{}: Directory {}{}

".format(
                uhttpd.VERSION, prefix, path).encode('UTF-8'))
            if len(path) > 1:
                stream.write("
..
\n")
            for f in dirlist:
                stream.write("
{0}
\n".format(f).encode('UTF-8'))
                gc.collect()
            stream.write("
")
        return (None, lambda stream: write_dir_listing(stream))

    @staticmethod
    def redirect_response(newloc):
        return {
            'code': 302,
            'headers': {
                'Location': newloc
            }
        }

    @staticmethod
    def create_response(code, content_type, length, body):
        ret = {
            'code': code,
            'headers': {
                'Content-Type': content_type
            },
            'body': body
        }
        if length is not None:
            ret['Content-Length'] = length
        return ret

    @staticmethod
    def file_size(path):
        return os.stat(path)[6]

    @staticmethod
    def get_suffix(path):
        idx = path.rfind('.')
        return "" if idx == -1 else path[idx:]

    @staticmethod
    def is_prefix(prefix, str):
        return len(prefix) <= len(str) and str[:len(prefix)] == prefix


# tmp map file
import os

def read_project_user_dict():
    map_file = r'C:\Users\Lf\Desktop\file_tmp\project_user.csv'
    map_dict = {}
    with open(map_file, encoding='utf-8') as f:
        lines = f.readlines()
    for l in lines:
        vs = l.split(',')
        (filepath, tempfilename) = os.path.split(vs[0])
        (shotname, extension) = os.path.splitext(tempfilename)
        map_dict[shotname.strip()] = vs[2].strip().replace('"', '')
    return map_dict


# -*- coding: utf-8 -*-
#!/usr/bin/env python
# Copyright 2018 ZhangT. All Rights Reserved.
# Author: ZhangT
# Author-Github: github.com/zhangt2333
# MajorHandler.py 2018/12/3 21:20
import logging

from utils import DAO
from utils.commons import required_login, required_principal
from utils.response_code import RET
from .BaseHandler import BaseHandler

class QueryHandler(BaseHandler):
    @required_login
    def post(self):
        sql = """
        SELECT mi_id, mi_name, mi_degree, mi_study_time, mi_department_id
        FROM ms_major_info
        WHERE CONCAT(mi_id, '') like %(id)s AND
              mi_name like %(name)s;
        """.strip()
        retKeys = ['id', 'name', 'degree', 'study_time', 'department_id']
        self.json_args['id'] = '%{}%'.format(self.json_args['id'])
        self.json_args['name'] = '%{}%'.format(self.json_args['name'])
        try:
            res = DAO.db_query(self, sql, self.json_args, retKeys)
            return self.write(dict(errcode=RET.OK, errmsg="OK", data=res))
        except Exception as e:
            logging.error(e)
            return self.write(dict(errcode=RET.PARAMERR, errmsg="出错"))

class EditHandler(BaseHandler):
    @required_login
    @required_principal
    def post(self):
        sql = """
        UPDATE ms_major_info
        SET mi_name=%(name)s, mi_degree=%(degree)s, mi_study_time=%(study_time)s,
            mi_department_id=%(department_id)s
        WHERE mi_id=%(id)s;
        """.strip()
        try:
            DAO.db_execute(self, sql, self.json_args)
            return self.write(dict(errcode=RET.OK, errmsg="修改成功"))
        except Exception as e:
            logging.error(e)
            return self.write(dict(errcode=RET.PARAMERR, errmsg="出错"))

class AddHandler(BaseHandler):
    @required_login
    @required_principal
    def post(self):
        sql = """
        INSERT INTO ms_major_info
        (mi_name, mi_degree, mi_study_time, mi_department_id) VALUES
        (%(name)s, %(degree)s, %(study_time)s, %(department_id)s);
        """.strip()
        try:
            DAO.db_execute(self, sql, self.json_args)
            return self.write(dict(errcode=RET.OK, errmsg="添加成功"))
        except Exception as e:
            logging.error(e)
            return self.write(dict(errcode=RET.PARAMERR, errmsg="出错"))

class DeleteHandler(BaseHandler):
    @required_login
    @required_principal
    def post(self):
        sql = """
        DELETE FROM ms_major_info
        WHERE mi_id=%(id)s;
        """.strip()
        try:
            DAO.db_execute(self, sql, self.json_args)
            return self.write(dict(errcode=RET.OK, errmsg="删除成功"))
        except Exception as e:
            logging.error(e)
            return self.write(dict(errcode=RET.PARAMERR, errmsg="出错"))


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

# 给定一个非负整数数组 A， A 中一半整数是奇数，一半整数是偶数。
#
# 对数组进行排序，以便当 A[i] 为奇数时，i 也是奇数；当 A[i] 为偶数时， i 也是偶数。
# 你可以返回任何满足上述条件的数组作为答案。
# 示例：
# 输入：[4,2,5,7]
# 输出：[4,5,2,7]
# 解释：[4,7,2,5]，[2,5,4,7]，[2,7,4,5] 也会被接受。
# 提示：
# 2 <= A.length <= 20000
# A.length % 2 == 0
# 0 <= A[i] <= 1000

# &运算： 两个数都转为二进制，然后从高位开始比较，如果两个数都为1则为1，否则为0。
# 6&1 === 》  1100 比 0001  =====》》  0  ====== 》》》  可以用来判断是否是奇数  如果为0 就是偶数
# 9&1  1 0010 比 1 ===》 1

class Solution(object):
    def sortArrayByParityII(self, A):
        """
        :type A: List[int]
        :rtype: List[int]
        """
        n = len(A)
        res = [0] * n
        j = 1
        o = 0
        for i in A:
            if i % 2 == 0:
                res[o] = i
                o += 2
            else:
                res[j] = i
                j += 2
        return res

    def sortArrayByParityII2(self, A):
        """
        更优解：循环的时候直接判断偶数位置是不是偶数
        不是的话 找到一个奇数位的偶数去替换
        报错了！！！！ j out of index 下标越界了
        :type A: List[int]
        :rtype: List[int]
        """
        n = len(A)
        j = 1
        for i in range(0, n, 2):
            if A[i] % 2 == 0:
                while A[j] % 2 == 0:
                    j += 2
                tmp = A[i]
                A[i] = A[j]
                A[j] = tmp
        return A

    def sortArrayByParityII3(self, A):
        """
        这种最垃圾
        :type A: List[int]
        :rtype: List[int]
        """
        ou = [i for i in A if i % 2]
        ji = [i for i in A if not i % 2]
        return [i for n in zip(ji, ou) for i in n]

if __name__ == "__main__":
    s = Solution()
    nums = [9, 4, 9, 8, 4, 5]
    a = s.sortArrayByParityII2(nums)
    print(a)


import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from random import *
from time import *
from MySocket import *

class MyLable(QLabel):
    def __init__(self, parent, str):
        super().__init__(parent.fontStyle + str + '''
''', parent)
        self.step = parent.screen.width()/parent.speed
        self.x = parent.screen.width() + randint(0, int(self.step * 10))
        self.y = randint(0, parent.screen.height()-self.height())
        self.move(self.x, self.y)
        self.time = time()

    def next(self) -> object:
        self.x -= self.step * (time()-self.time)
        self.time = time()
        self.move(self.x, self.y)
        return self.x > -self.width()

    def out(self):
        return self.x < -self.width()

class Window(QWidget):
    def __init__(self, socket, fontSize, fontColor, speed):
        super(Window, self).__init__(None)#调用父构造函数初始化
        self.fontStyle = '''
'''
        self.socket = socket
        self.fontSize = fontSize
        self.fontColor = fontColor
        self.speed = speed
        self.setWindow()#设置窗口
        self.setButton()  # 设置按钮(后期删！）
        self.barrage = [] # 储存弹幕
        self.setTimer() #设置刷新时间间隔
        tmp_label = MyLable(self, '程序已经正常启动')
        self.barrage.append(tmp_label)
        self.show()

    def setWindow(self):
        self.setAttribute(Qt.WA_TranslucentBackground, True) #设置透明背景
        self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint) #设置置顶和无边框
        self.screen = QDesktopWidget().screenGeometry()  # 获取屏幕分辨率
        self.setGeometry(0, 0, self.screen.width(), self.screen.height())  # 设置窗口位置XY及大小XY

    def setButton(self):
        QToolTip.setFont(QFont('SansSerif', 10))#设置提示框字体与字号
        buttonRestart = QPushButton('×', self)#创建重新开始按钮
        buttonRestart.resize(20, 20)
        buttonRestart.move(0, 0)
        buttonRestart.setToolTip('Click here to close')
        buttonRestart.clicked.connect(self.close)

    def setTimer(self):
        self.timer = QTimer()
        self.frequency = 30
        self.timer.setInterval(self.frequency)
        self.timer.timeout.connect(self.Redraw)
        self.timer.start()
        self.countTime = time() + 10

    def Redraw(self):
        try:
            if time() - self.countTime >= 10:
                self.countTime = time()
                data = self.socket.get()
                data = data[0:len(data)-2].split('\n')
                for i in data:
                    tmp_label = MyLable(self, i)
                    tmp_label.show()
                    self.barrage.append(tmp_label)
            self.barrage = [ i for i in self.barrage if i.next()]
        except Exception:
            tmp_label = MyLable(self, '系统出现未知错误！')
            tmp_label.show()
            self.barrage.append(tmp_label)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    fontColor = QColor(23, 23, 255)
    socket = MySocket('sysustudentunion.cn', 'tu_4s2q3o3p4928')
    window = Window(socket, 30, fontColor, 7)
    #app.exec_()
    sys.exit(app.exec_())


from flask import current_app, jsonify

from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound

from . import api_1_0 as bp
from app import create_access_token
from app.api import Field, InvalidUsage, MyForm, api, validators
from db.model import ApiAccessPair

@bp.route("get-token", methods=["POST"])
@api
def get_token():

	data = MyForm(
		Field("emailAddress", is_mandatory=True,
			validators=[
				validators.is_string
		]),
		Field("key", is_mandatory=True,
			validators=[
				validators.is_string
			]
		),
		Field("secret", is_mandatory=True,
			validators=[
				validators.is_string,
			]
		),
	).get_data()

	try:
		api_access_pair = ApiAccessPair.query.filter_by(key=data["key"], secret=data["secret"]).one()
	except (NoResultFound, MultipleResultsFound):
		raise InvalidUsage("access pair not found", 401)

	if api_access_pair.user.email_address != data["emailAddress"]:
		raise InvalidUsage("incorrect email address for access pair: {0}".format(data["emailAddress"]), 401)

	if not api_access_pair.enabled:
		raise InvalidUsage("access pair is disabled", 401)

	access_token, expires_at = create_access_token(api_access_pair.user.appen_id)

	current_app.logger.info("access token created for user {0}: {1}".format(
		api_access_pair.user.appen_id,
		access_token
	))

	return jsonify({
		"accessToken": access_token,
		"expiresAt": expires_at,
		"appenId": api_access_pair.user.appen_id,
	})


#######################
# Author: slurpxbt
#######################
import binance_candle_data as bcd
from pathlib import Path
import pandas as pd
import datetime
import matplotlib.pyplot as plt
import numpy as np

# pandas display, pycharm otherwise doesn't display all columns
pd.set_option('display.max_columns', 100)
desired_width = 500
pd.set_option('display.width', desired_width)
# ----------------------------------------------------------

root = Path("..")

# USER INPUTS --------------------------------------------------------
# --------------------------------------------------------------------
start_date = datetime.datetime(2020, 1, 1)
end_date = datetime.datetime(2020, 10, 1)
# --------------------------------------------------------------------
time_frame = "1h"
ticker = "ETHUSDT"
# --------------------------------------------------------------------
start_size = 5000  # contracts
size = start_size
# --------------------------------------------------------------------
market_order_fee = 0.075    # unit [%]
slippage = 0.1              # unit [%]
# --------------------------------------------------------------------
tp_pct = 0.01               # unit => 1 - 100%, 0.1 - 10%, 0.01 - 1%
# --------------------------------------------------------------------
compounding = True
# END OF USER INPUTS -------------------------------------------------

filepath = f"data/{ticker}_{time_frame}.p"
data = bcd.get_data_by_date(start_date, end_date, filepath)

# ----------------------------------------------------------------
# Add MA and EMAs here
data["EMA5"] = round(data["close"].ewm(span=5).mean(), 2)
data["EMA10"] = round(data["close"].ewm(span=10).mean(), 2)
# ----------------------------------------------------------------

# format =  [open_time, open, high, low, close, volume, close_time, number_of_trades, EMA5,  EMA10]
candle_data_list = data.values.tolist()     # convert df to list

short_long = ""
trade_opened = False

pnl = []
tps = []
sls = []
cum_size = []

for candle in candle_data_list:
    close = candle[4]           # candle open prc
    low = candle[3]             # candle low prc
    high = candle[2]            # candle high prc
    ema5 = candle[8]            # 5 ema
    ema10 = candle[9]           # 10 ema

    # YOUR STRATEGY GOES HERE
    if not trade_opened:
        trade_entry = 0
        tp = 0
        if close < ema10 and close < ema5:
            short_long = "short"
            trade_opened = True
            trade_entry = close
            tp = round(trade_entry - (trade_entry * tp_pct), 2)
            print(f"short entry @ {trade_entry} with tp @ {tp} -> size {size}")

        elif close > ema5 and close > ema10:
            short_long = "long"
            trade_opened = True
            trade_entry = close
            tp = round(trade_entry + (trade_entry * tp_pct), 2)
            print(f"long entry @ {trade_entry} with tp @ {tp} -> size {size}")

    if trade_opened:

        if short_long == "short":   # short

            if close <= tp or low <= tp:
                gain = round((tp / trade_entry - 1) * 100 * (-1) - market_order_fee - slippage, 2)
                trade_profit = gain * size / 100

                cum_size.append(size + trade_profit)
                if compounding:
                    size = size + trade_profit
                pnl.append(trade_profit)
                tps.append(trade_profit)

                print(f"tp executed @ {tp} -> gain {gain}% -> profit {trade_profit} $")
                trade_opened = False
                print("-"*100)

            elif close > ema10 and close > ema5:
                gain = round((close / trade_entry - 1) * 100 * (-1) - market_order_fee - slippage, 2)
                trade_profit = gain * size / 100

                cum_size.append(size + trade_profit)
                if compounding:
                    size = size + trade_profit
                pnl.append(trade_profit)
                sls.append(trade_profit)

                print(f"sl executed @ {close} -> gain {gain}% -> profit {trade_profit} $")
                trade_opened = False
                print("-" * 100)

        elif short_long == "long":  # long

            if close >= tp or high >= tp:
                gain = round((tp / trade_entry - 1) * 100 - market_order_fee - slippage,2)
                trade_profit = gain * size / 100

                cum_size.append(size + trade_profit)
                if compounding:
                    size = size + trade_profit
                pnl.append(trade_profit)
                tps.append(trade_profit)
                print(f"tp executed @ {tp} -> gain {gain}% -> profit {trade_profit} $")
                trade_opened = False
                print("-" * 100)

            elif close < ema10 and close < ema5:
                gain = round((close / trade_entry - 1) * 100 - market_order_fee - slippage, 2)
                trade_profit = gain * size / 100

                cum_size.append(size + trade_profit)
                if compounding:
                    size = size + trade_profit
                pnl.append(trade_profit)
                sls.append(trade_profit)
                print(f"sl executed @ {close} -> gain {gain}% -> profit {trade_profit} $")
                trade_opened = False
                print("-" * 100)

print("-" * 100)
print("-" * 100)
print(f"strategy on {ticker} on {time_frame} timespan => {start_date} -> {end_date}")
print(f"strategy $ pnl is {round(sum(pnl), 2)}")
if compounding:
    print(f"strategy % pnl is {round((cum_size[-1] / start_size - 1) * 100, 2)}")
    print(f"W/L ratio: {round((len(tps)/(len(sls)+len(tps)))*100, 2)}%")
    print(f"average profit {round(np.average(tps), 2)}")
    print(f"average loss {round(np.average(sls), 2)}")
else:
    print(f"strategy % pnl is {round((sum(pnl) / start_size - 1) * 100, 2)}")
    print(f"W/L ratio: {len(tps) / len(sls)}")
    print(f"average profit {round(np.average(tps), 2)}")
    print(f"average loss {round(np.average(sls), 2)}")

cum_sum = []
cum = 0
for profit in pnl:
    cum += profit
    cum_sum.append(cum)

plt.plot(cum_sum)
plt.title(f"strategy $ return {start_date} -> {end_date}")
plt.grid(alpha=0.3)
plt.show()

plt.plot(cum_size)
plt.title(f"strategy cum size")
plt.grid(alpha=0.3)
plt.show()

x = [i for i in range(len(pnl))]
plt.title("pnl histogram")
plt.bar(x, pnl, width=0.3)
plt.show()


#!/usr/bin/env python
#cd ~/Desktop/SU_Aur_backup/channels/bg_sub/flat/im_distort/align/OE/QU/rotated_QU/aligned_QU/flux_scaling/PA_diskmajoraxis
'''
This file combines the radial PI distribution along PA=15 and 195 (major axis)
in a single plot.
See 15radial_PI_dist.py to see individual results.
'''
from pylab import *
import pyfits
from scipy.ndimage.interpolation import rotate
import numpy as np
from matplotlib.patches import Ellipse
cmap=cm.jet
cmap.set_bad('black',1)

#z=pyfits.open('obj_PI_fs_conv_sigma08.fits')
#z=pyfits.open('obj_PI_fs_conv_sig1.fits')
z=pyfits.open('obj_PI_fs_conv_sig2.fits')
obj_PI_fs_conv=z[0].data-1.1e-7
z.close()

#define image center
scale=9.53e-3*140
xcenter=271
ycenter=318

#obj_PI_fs_conv_cropped=obj_PI_fs_conv[ycenter-270:ycenter+271,xcenter-270:xcenter+271]

#angle of image rotation along the major axis
angle1, angle2= 15, 195
rotated_image1=rotate(obj_PI_fs_conv,angle1)
rotated_image2=rotate(obj_PI_fs_conv,angle2)
dim1=rotated_image1.shape[0]
dim2=rotated_image2.shape[0]
midpoint1   =dim1/2
midpoint2   =dim2/2

extent_PI1=array([-midpoint1,midpoint1,-midpoint1,midpoint1])*scale
extent_PI2=array([-midpoint2,midpoint2,-midpoint2,midpoint2])*scale

#This combines subplots in figure 1 in one figure
figure(0)
clf()
imshow(log10(rotated_image1),extent=extent_PI1,vmin=-7.4,vmax=-5,cmap=cmap)
plot([0,0], [15*scale, midpoint1*scale], color='w', linestyle='--', linewidth=2)
plot([0,0], [-midpoint1*scale,-15*scale], color='w', linestyle='--', linewidth=2)
xlabel('AU')
ylabel('AU')
axis([-150,150,-150,150])
colorbar()

figure(1)
subplot(121)
imshow(log10(rotated_image1),extent=extent_PI1,vmin=-7.4,vmax=-5,cmap=cmap)
plot([0,0], [0, midpoint1*scale], color='w', linestyle='--', linewidth=1)
xlabel('AU')
ylabel('AU')
axis([-150,150,-150,150])
colorbar()
title('P.A.= %d deg.' % angle1)
# 195
subplot(122)
imshow(log10(rotated_image2),extent=extent_PI2,vmin=-7.4,vmax=-5,cmap=cmap)
plot([0,0], [0, midpoint2*scale], color='w', linestyle='--', linewidth=1)
xlabel('AU')
ylabel('AU')
axis([-150,150,-150,150])
colorbar()
title('P.A.= %d deg.' % angle2)

figure(2)
clf()
#get the average of of flux along the vertical (PA=15) +-2 pixels (5 columns) to increase SNR
image1a=rotated_image1[midpoint1:,midpoint1+1]*scale
image2a=rotated_image1[midpoint1:,midpoint1-1]*scale
image3a=rotated_image1[midpoint1:,midpoint1+2]*scale
image4a=rotated_image1[midpoint1:,midpoint1-2]*scale
image5a=rotated_image1[midpoint1:,midpoint1]*scale
image_ave1=(image1a+image2a+image3a+image4a+image5a)/5

image1b=rotated_image2[midpoint2:,midpoint2+1]*scale
image2b=rotated_image2[midpoint2:,midpoint2-1]*scale
image3b=rotated_image2[midpoint2:,midpoint2+2]*scale
image4b=rotated_image2[midpoint2:,midpoint2-2]*scale
image5b=rotated_image2[midpoint2:,midpoint2]*scale
image_ave2=(image1b+image2b+image3b+image4b+image5b)/5

#new_rscale=log((arange(rotated_image.shape[0])-midpoint)*scale)
new_rscale1=(arange(rotated_image1.shape[0])-midpoint1)*scale
new_rscale2=(arange(rotated_image2.shape[0])-midpoint2)*scale
#get only the positive values of flux; midpoint>=0
new_rscale1=new_rscale1[midpoint1:]
new_rscale2=new_rscale2[midpoint2:]
p1, p2 = -2.9, -2.8
constant1= 0.1037
constant2= 0.0498

label15 = 'PI flux for PA = %d deg.' % angle1
label195 = 'PI flux for PA = %d deg.' % angle1

#fit a power law with exponent p=-1
power_law_m1= constant1 * new_rscale1 ** p1
power_law_m2= constant2 * new_rscale2 ** p2
loglog(new_rscale1,image_ave1,'ko-',label=label15)
loglog(new_rscale2,image_ave2,'ks',mfc="None",label=label195) #unfilled circle
#You can draw multiple lines with a single plot command and  plot() returns a "list" of lines that were added.  In this case, the return value is a list of a single line, which is  unpacked with the comma .
t,=loglog(new_rscale2,image_ave2,'ko',mfc="None")
t.set_mec(t.get_color())

#log log plot of power law
label1 = str(constant1)+'r ** %.1f (PA = %d deg.)' % (p1,angle1)
label2 = str(constant2)+'r ** %.1f (PA = %d deg.)' % (p2,angle2)

loglog(new_rscale1,power_law_m1,'k-',label=label1)
loglog(new_rscale2,power_law_m2,'k--',label=label2)
#plot([0,0], [5e-8, 3e-5], color='r', linestyle='--', linewidth=1) #this is a vertical line along the origin

#input the last pixel = boundary of disk
end_pix_disk= 60
label3= 'mask boundary (r=20 AU); disk boundary r=%.1f AU' % ((end_pix_disk+1)*scale)

#mark the point marking the boundary of the mask at r=15, before of which the flux is unreliable, and also the last pixel used in fitting (flux>0)
loglog(15*scale,image_ave1[15], 'ro',label=label3)
loglog(15*scale,image_ave2[15], 'rs')

loglog(end_pix_disk*scale,image_ave1[end_pix_disk], 'ro') #for PA=15
loglog(end_pix_disk*scale,image_ave2[end_pix_disk], 'rs')
axis([0,1000,5e-8,3e-5]) #AU scale
ylabel('log (n_PI / n*)')
xlabel('log(r) (AU)')
#title('Radial PI distribution for PA=%d and %d' % (angle1,angle2))
legend(loc='upper right', shadow=True)

#Takami+13 used 0."3 arcsec in diameter mask
#0."3 arcsec/*0.00948arcsec/pix = 31.65 pixels
hmask,wmask= 30*scale,30*scale #radius = 15 pix = 20 AU
l=Ellipse(xy=(0,0),height=hmask,width=wmask)
figure(0).add_subplot(111).add_artist(l)
m=Ellipse(xy=(0,0),height=hmask,width=wmask)
figure(1).add_subplot(121).add_artist(m)
n=Ellipse(xy=(0,0),height=hmask,width=wmask)
figure(1).add_subplot(122).add_artist(n)
l.set_color('k')
m.set_color('k')
n.set_color('k')
show()

'''
np.savetxt('image_ave_PA15.txt',image_ave)
np.savetxt('new_rscale_PA15.txt',new_rscale)

import powerlaw
data = array([1.7, 3.2 ...]) # data can be list or numpy array
results = powerlaw.Fit(data)
print results.power_law.alpha
print results.power_law.xmin
R, p = results.distribution_compare('power_law', 'lognormal')
'''


import os
import sys
import glob

import cv2
import numpy as np

IMAGETYPES = ('*.bmp', '*.png', '*.jpg', '*.jpeg', '*.tif') # Supported image types

def get_image_paths(file_root, pattern=None):
    """ Get ordered list of filepaths
    """
    file_paths = []
    for typ in IMAGETYPES:
		# search all files conforming to the IMAGE_TYPES extensions
        file_paths.extend(glob.glob(os.path.join(file_root,'**',typ), recursive=True))
    # filter filenames
    if pattern is not None:
        filtered = []
        filtered = [f for f in file_paths if pattern in os.path.split(f)[-1]]
        file_paths = filtered
        del filtered
	# sort image file paths
    file_paths.sort()
    return file_paths

def load_face_dataset(file_root):
    """ Load all images and also list out the filepaths
    """
    if not os.path.isdir(file_root):
        raise FileNotFoundError("Face dataset file root: {} not found.".format(file_root))

    file_paths = get_image_paths(file_root)

    if len(file_paths) == 0:
        warnings.warn("No image found in face dataset file root: {}".format(file_root))
        return []

    images = [cv2.imread(file_path) for file_path in file_paths]
    return images, file_paths