from decimal import Decimal

from django.db import models
from django.template.defaultfilters import slugify
from django.utils.translation import ugettext as _
from django.conf import settings

class AbstractSource(models.Model):
    """
    A source of payment for an order.

    This is normally a credit card which has been pre-authed for the order
    amount, but some applications will allow orders to be paid for using
    multiple sources such as cheque, credit accounts, gift cards.  Each payment
    source will have its own entry.
    """
    order = models.ForeignKey('order.Order', related_name='sources')
    type = models.ForeignKey('payment.SourceType')
    currency = models.CharField(max_length=12, default=settings.OSCAR_DEFAULT_CURRENCY)
    amount_allocated = models.DecimalField(decimal_places=2, max_digits=12)
    amount_debited = models.DecimalField(decimal_places=2, max_digits=12, default=Decimal('0.00'))
    reference = models.CharField(max_length=128, blank=True, null=True)

    # A dictionary of submission data that is stored as part of the
    # checkout process.
    submission_data = {}

    class Meta:
        abstract = True

    def __unicode__(self):
        description = "Allocation of %.2f from type %s" % (self.amount_allocated, self.type)
        if self.reference:
            description += " (reference: %s)" % self.reference
        return description

    def balance(self):
        return self.amount_allocated - self.amount_debited

class AbstractSourceType(models.Model):
    """
    A type of payment source.

    This could be an external partner like PayPal or DataCash,
    or an internal source such as a managed account.i
    """
    name = models.CharField(max_length=128)
    code = models.SlugField(max_length=128, help_text=_("""This is used within
        forms to identify this source type"""))

    class Meta:
        abstract = True

    def __unicode__(self):
        return self.name

    def save(self, *args, **kwargs):
        if not self.code:
            self.code = slugify(self.name)
        super(AbstractSourceType, self).save(*args, **kwargs)

class AbstractTransaction(models.Model):
    """
    A transaction for payment sources which need a secondary 'transaction' to actually take the money

    This applies mainly to credit card sources which can be a pre-auth for the money.  A 'complete'
    needs to be run later to debit the money from the account.
    """
    source = models.ForeignKey('payment.Source', related_name='transactions')
    type = models.CharField(max_length=128, blank=True)
    delta_amount = models.FloatField()
    reference = models.CharField(max_length=128)
    date_created = models.DateField()

    class Meta:
        abstract = True

    def __unicode__(self):
        return "Transaction of %.2f" % self.delta_amount

class AbstractBankcard(models.Model):
    user = models.ForeignKey('auth.User', related_name='bankcards')
    card_type = models.CharField(max_length=128)
    name = models.CharField(max_length=255)
    number = models.CharField(max_length=32)
    expiry_date = models.DateField()

    # For payment partners who are storing the full card details for us
    partner_reference = models.CharField(max_length=255, null=True, blank=True)

    class Meta:
        abstract = True

    def save(self, *args, **kwargs):
        self.number = self._get_obfuscated_number()
        super(AbstractBankcard, self).save(*args, **kwargs)

    def _get_obfuscated_number(self):
        return u"XXXX-XXXX-XXXX-%s" % self.number[-4:]


import sqlite3
conn = sqlite3.connect('0000.sqlite')
cursor = conn.cursor()

class ScoreGame:

    def __int__(self, c, d):
        self.id = c
        self.score = d

    def B(self):
        a = int(input("請輸入修改成績id?"))
        b = int(input("請輸入修改成績?"))
        sqlstr = "update Enter_Score set score={} where id={}".format(b,a)
        cursor.execute(sqlstr)
        conn.commit()
        conn.close()

pp = ScoreGame()
pp.B()


import tensorflow as tf
import numpy as np

NUM_PATCH_EACH_IMAGE = 20
NUM_IMAGE_EACH_BATCH = 50

def pre_processing(shape, i_size, images):
  final_samples = tf.placeholder(tf.float32)

  for i in xrange(NUM_IMAGE_EACH_BATCH):
    print(i)
    begin = [i, 0, 0, 0]
    size = [1, i_size[1], i_size[2], i_size[3]]
    size[0] = 1
    extracted_image = tf.slice(images, begin, size)
    extracted_image = tf.reshape(extracted_image, [i_size[1], i_size[2], i_size[3]])
    patch_3d = tf.random_crop(extracted_image, [shape[0], shape[1], shape[2]], seed=None, name=None)
    mean, var = tf.nn.moments(patch_3d, axes = [0,1], shift=None, name=None, keep_dims=False)
    patch_3d = tf.nn.l2_normalize(patch_3d, [0,1], epsilon=1e-12, name=None)
    patch_stack = tf.expand_dims(patch_3d, 0)
    var_stack = tf.expand_dims(tf.norm(var, ord='euclidean', axis = None, keep_dims=False, name=None), 0)

    for j in xrange(NUM_PATCH_EACH_IMAGE-1):
      patch_3d = tf.random_crop(extracted_image, [shape[0], shape[1], shape[2]], seed=None, name=None)
      mean, var = tf.nn.moments(patch_3d, axes = [0,1], shift=None, name=None, keep_dims=False)
      # patch_3d = tf.nn.batch_normalization(patch_3d, mean, 2*var, 0, 1, variance_epsilon=1e-12, name=None)
      patch_3d = tf.nn.l2_normalize(patch_3d, [0,1], epsilon=1e-12, name=None)
      patch_4d = tf.expand_dims(patch_3d, 0)
      var_2d = tf.expand_dims(tf.norm(var, ord='euclidean', axis = None, keep_dims=False, name=None), 0)
      patch_stack = tf.concat([patch_stack, patch_4d], 0)
      var_stack = tf.concat([var_stack, var_2d], 0)

    values, indices = tf.nn.top_k(var_stack, k = 5, sorted=True, name=None)
    begin = [indices[0], 0, 0, 0]
    size = [1, shape[0], shape[1], shape[2]]
    size[0] = 1
    selected_patch = tf.slice(patch_stack, begin, size)
    samples = tf.expand_dims(tf.reshape(selected_patch, [-1]), 0)

    for k in xrange(4):
      begin = [indices[k+1], 0, 0, 0]
      size = [1, shape[0], shape[1], shape[2]]
      size[0] = 1
      selected_patch = tf.slice(patch_stack, begin, size)
      selected_patch_1d = tf.expand_dims(tf.reshape(selected_patch, [-1]), 0)
      samples = tf.concat([samples, selected_patch_1d], 0)

    pred = tf.equal(tf.constant(i), tf.constant(0))
    sess = tf.Session()
    if sess.run(pred):
      final_samples = samples
    else:
      final_samples = tf.concat([final_samples, samples], 0)
    sess.close()

  return final_samples

def choose_random_centroids(samples, n_clusters):
    # Step 0: Initialisation: Select `n_clusters` number of random point

    n_samples = tf.shape(samples)[0]
    random_indices = tf.random_shuffle(tf.range(0, n_samples))
    begin = [0,]
    size = [n_clusters,]
    size[0] = n_clusters
    centroid_indices = tf.slice(random_indices, begin, size)
    initial_centroids = tf.gather(samples, centroid_indices) #lihai haiyouzhezhonga
    return initial_centroids

def assign_to_nearest(samples, centroids):
    # Finds the nearest centroid for each sample
    # START from http://esciencegroup.com/2016/01/05/an-encounter-with-googles-tensorflow/
    expanded_vectors = tf.expand_dims(samples, 0)
    expanded_centroids = tf.expand_dims(centroids, 1)
    distances = tf.reduce_sum(tf.square(tf.subtract(expanded_vectors, expanded_centroids)), 2)
    mins = tf.argmin(distances, 0)
    # END from http://esciencegroup.com/2016/01/05/an-encounter-with-googles-tensorflow/
    nearest_indices = mins
    return nearest_indices

def update_centroids(samples, nearest_indices, n_clusters):
    # Updates the centroid to be the mean of all samples associated with it.
    nearest_indices = tf.to_int32(nearest_indices)
    partitions = tf.dynamic_partition(samples, nearest_indices, n_clusters)
    new_centroids = tf.concat([tf.expand_dims(tf.reduce_mean(partition, 0), 0) for partition in partitions], 0)
    return new_centroids

ComputerVision/ConvNets/LetNet-5 Implementation on Tensorflow/kmean_initialization/function.py


import requests
import json
from pprint import pprint

url = 'https://covid-api.mmediagroup.fr/v1/cases'
objeto = json.loads(requests.get(url).text)
paises  = [pais for pais in objeto if pais != 'Global']

mi_seleccion = {}
contador = 1

while True:
   pais_deseado = input("Ingrese el país del que desea obtener los datos (en Ingles): ")
   if pais_deseado not in paises: print("Ese país no está en la lista")
   else:
      url = 'https://covid-api.mmediagroup.fr/v1/cases?country=' + pais_deseado
      objeto = json.loads(requests.get(url).text)
      toda_la_info = objeto['All']
      casos_confirmados = toda_la_info['confirmed']
      fallecidos = toda_la_info['deaths']
      recuperados = toda_la_info['recovered']
      datos_pais = {'país': pais_deseado,
                    'casos confirmados': casos_confirmados,
                    'fallecidos': fallecidos,
                    'recuperados': recuperados}

      mi_seleccion['pais' + str(contador)] = datos_pais
      contador += 1
   agregar = input("Desea agregar otro país? s/n: ").upper()
   if agregar == 'N': break
pprint(mi_seleccion)
with open('seleccion_paises.json', 'w') as salida:
   json.dump(mi_seleccion, salida, indent=3, ensure_ascii=False)


# -*- coding: utf-8 -*-
"""
scripts relating to maps to be called from excel via xlwings.

Excel functions (to put in cells)::

    km=distance(orig, dest)
    mins=driving_time(orig, dest)
    mins=walking_time(orig, dest)

Dependencies::

    xlwings, logconfig (optional), googlemaps

    add to _creds.py [2500/day requests/key]
        googlemaps=dict(browserkeys=<list of googlemaps keys>)
"""
import logging as log
from xlwings import func
import googlemaps

clients = []
# each client can make 2500 requests/day
from _creds import googlemaps as gcreds
for clientid in gcreds["browserkeys"]:
    clients.append(googlemaps.Client(clientid, timeout=2))

@func
def distance(orig, dest):
    return _distance(orig, dest, "driving", "km")

@func
def driving_time(orig, dest):
    return _distance(orig, dest, "driving", "mins")

@func
def walking_time(orig, dest):
    return _distance(orig, dest, "walking", "mins")

def _distance(orig, dest, mode, units):
    # get route matrix
    matrix = clients[0].distance_matrix(orig, dest, mode)
    # if exceeded requests then try next clientid
    if matrix["status"]=="OVER_QUERY_LIMIT":
        clients.pop(0)
        if len(clients) == 0:
            return matrix["status"]
        matrix = clients[0].distance_matrix(orig, dest, mode)
    route = matrix["rows"][0]["elements"][0]

    # parse the route
    if route["status"] != "OK":
        return route["status"]
    if units == "km":
        return route["distance"]["value"]/1000
    elif units == "mins":
        return route["duration"]["value"]/60

#### testing #############################################################

if __name__ == "__main__":
    orig="CV3 2TT"
    dest="KT13 8LA"
    print("%s to %s km=%s"%(orig, dest, distance(orig, dest)))
    print("%s to %s mins=%s"%(orig, dest, driving_time(orig, dest)))
    dest="Coventry University"
    print("walk %s to %s mins=%s"%(orig, dest, walking_time(orig, dest)))
    dest="Coventry University, Coventry"
    print("walk %s to %s mins=%s"%(orig, dest, walking_time(orig, dest)))


# -*- coding: utf-8 -*-
"""
Created on Wed Mar 20 20:24:53 2019

@author: lenovo
"""

import pygame
import time
import random
import sqlite3

blue = (0,0,255)
white = (255,255,255)
red = (225, 12, 27)

pygame.init()

Donnees = "Donnees.sq3"
conn = sqlite3.connect(Donnees)
cur = conn.cursor()

surfaceW = 800
surfaceH = 500
ballonW = 50
ballonH = 66
nuageW = 300
nuageH = 300

surface = pygame.display.set_mode((surfaceW,surfaceH))
pygame.display.set_caption("Ballon volant")
horloge = pygame.time.Clock()

img = pygame.image.load('Ballon01.png')
img_nuage1 = pygame.image.load('NuageHaut.png')
img_nuage2 = pygame.image.load('NuageBas.png')

def jauge(compte):
    police = pygame.font.Font('BradBunR.ttf',30)
    texte = police.render("| " * (compte),True,white)
    surface.blit(texte,[0,470])

def score(compte):
    police = pygame.font.Font('BradBunR.ttf',16)
    texte = police.render("score : " + str(compte),True,red)
    surface.blit(texte,[10,0])

def Hscore(compte):
    police = pygame.font.Font('BradBunR.ttf',16)
    texte = police.render("meilleur score : " + str(compte),True,red)
    surface.blit(texte,[700,0])

def nuages(x_nuage,y_nuage,espace):
    surface.blit(img_nuage1,(x_nuage,y_nuage))
    surface.blit(img_nuage2,(x_nuage,y_nuage+nuageW+espace))

def rejoueOUQuitter():
    for event in pygame.event.get ([pygame.KEYDOWN,pygame.KEYUP,pygame.QUIT]):
        if event.type==pygame.QUIT:
            quit()
        elif event.type == pygame.KEYUP :
            continue
        return event.key
    return None

def creaTexteObj(texte,Police):
    texteSurface = Police.render(texte,True,white)
    return texteSurface, texteSurface.get_rect()

def message(texte):
    GOTexte = pygame.font.Font('BradBunR.ttf',150)
    petitTexte = pygame.font.Font('BradBunR.ttf',20)

    GOTexteSurf, GOTexteRect = creaTexteObj(texte,GOTexte)
    GOTexteRect.center = surfaceW/2 , ((surfaceH/2)-50)
    surface.blit(GOTexteSurf,GOTexteRect)

    petitTexteSurf,petitTexteRect =creaTexteObj("appuyer sur une touche pour continuer",petitTexte)
    petitTexteRect.center = surfaceW/2 , ((surfaceH/2)+50)
    surface.blit(petitTexteSurf,petitTexteRect)

    pygame.display.update()
    time.sleep(2)

    while rejoueOUQuitter() == None:
        horloge.tick()

    principale()

def gameOver(score_actuel):
    a = list(str(score_actuel))

    Donnees = "Donnees.sq3"
    conn = sqlite3.connect(Donnees)
    cur = conn.cursor()
    cur.execute("select* from membres")
    liste = list(cur)
    hscore=[]
    for i in range(0,len(liste)):
        hscore +=liste[i]

    if (int(hscore[-1]) < score_actuel):
        cur.execute("insert into membres(score) values(?)",a)
        conn.commit()
        cur.close()
        conn.close()
    message("Boom!")

def ballon(x,y,image):
    surface.blit(image,(x,y))

def principale():
    x = 150
    y = 200
    y_mouvement = 0

    x_nuage = surfaceW
    y_nuage = random.randint(-300,20)
    espace = ballonH*3
    nuage_vitesse = 3

    score_actuel = 0
    jeton = 0

    game_over = False

    while not game_over:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_over = True

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    y_mouvement = -1
            if event.type == pygame.KEYUP:
                y_mouvement = 1
        y+= y_mouvement

        surface.fill(blue)
        ballon(x,y,img)

        nuages(x_nuage,y_nuage,espace)

        score(score_actuel)
        jauge(jeton)

        cur.execute("select * from membres")
        liste = list(cur)

        hscore = []
        for  i in range (0,len(liste)):
            hscore +=liste[i]

        Hscore(hscore[-1])

        x_nuage -=nuage_vitesse

        if y>surfaceH -30 or y<-20:
            gameOver(score_actuel)

        if (x+ballonW) > x_nuage +40   and  x + 40 < (x_nuage + nuageW) :
            if y +20 < (y_nuage+ nuageH) or y+ballonH > (y_nuage + nuageH + espace + 30) :
                gameOver(score_actuel)

        if x_nuage<(-1*nuageW):
            x_nuage = surfaceW
            y_nuage = random.randint(-300,20)
            score_actuel +=1
            jeton+=1

        pygame.display.update()

principale()

pygame.quit()
quit()


import csv, io
from django.contrib import messages
from django.contrib.auth.decorators import permission_required
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from django.utils import timezone
import datetime
from datetime import timedelta

from .models import Tool, CustomerInfo, Message

def index(request):  # Main page
    context = {}
    return render(request, 'Toolshop/index.html', context)

def projects_page(request):
    context = {}
    return render(request, 'Toolshop/projects.html', context)

def tools_page(request):
    tools_list = Tool.objects.order_by('category')
    context = {
        'tools_list': tools_list
    }
    return render(request, 'Toolshop/tools.html', context)

def contact_page(request):
    context = {}
    return render(request, 'Toolshop/contact.html', context)

def login_page(request):
    context = {}
    return render(request, 'Toolshop/login.html', context)

@login_required
def account_page(request):
    user = request.user
    tools_list = Tool.objects.filter(who_checked_out__contains=user.username)
    for tool in tools_list:
        # Temporarily change the variable to represent the day the tool is due.
        tool.date_checked_out = tool.date_checked_out + timedelta(days=7)
        # Do NOT save the new data with Tool.save()
    context = {
        'user': user,
        'tools_list': tools_list
    }
    return render(request, 'Toolshop/account.html', context)

@login_required
def reservation_page(request):
    tools_list = Tool.objects.order_by('category')
    context = {
        'tools_list': tools_list
    }
    return render(request, 'Toolshop/reservation.html', context)

@login_required
def reservation_page_specific(request, contains):  # This page has the results trimmed down by a search query
    if request.POST.get('query') is not None:
        contains = request.POST.get('query')
    tools_list = Tool.objects.filter(name__contains=contains).order_by('category')
    context = {
        'tools_list': tools_list
    }
    return render(request, 'Toolshop/reservation.html', context)

@login_required
def make_reservation(request, id):
    tool = get_object_or_404(Tool, pk=id)
    tool.is_checked_out = True
    tool.times_checked_out += 1
    tool.date_checked_out = timezone.now()
    tool.who_checked_out = request.user.username
    current_user = get_object_or_404(CustomerInfo, user=request.user)
    current_user.num_currently_checked_out += 1
    tool.save()
    current_user.save()
    context = {}
    return render(request, 'Toolshop/redirect.html', context)

def update_user_info(request):
    user = request.user
    first_name = request.POST.get('firstName')
    last_name = request.POST.get('lastName')
    address = request.POST.get('address')
    email_address = request.POST.get('email')
    password_1 = request.POST.get('psw')
    password_2 = request.POST.get('psw-repeat')

    if password_1 != password_2:
        return HttpResponseRedirect(reverse('Toolshop:updateError'))
    elif first_name is None or last_name is None or address is None or email_address is None or password_1 is None:
        return HttpResponseRedirect(reverse('Toolshop:updateError'))
    elif first_name == "" or last_name == "" or address == "" or email_address == "" or password_1 == "":
        return HttpResponseRedirect(reverse('Toolshop:updateError'))
    elif len(first_name) > 30 or len(last_name) > 30 or len(email_address) > 50:
        return HttpResponseRedirect(reverse('Toolshop:updateError'))
    elif len(password_1) < 8 or len(password_1) > 30:
        return HttpResponseRedirect(reverse('Toolshop:updateError'))

    user.first_name = first_name
    user.last_name = last_name
    user.email = email_address
    user.address = address
    user.set_password(password_1)

    user.save()
    # Always return an HttpResponseRedirect after successfully dealing
    # with POST data. This prevents data from being posted twice if a
    # user hits the Back button.
    return HttpResponseRedirect(reverse('Toolshop:redirect'))

def submit_message(request):
    first_name = request.POST.get('firstname')
    last_name = request.POST.get('lastname')
    email_address = request.POST.get('emailAddress')
    subject = request.POST.get('subject')
    message = request.POST.get('textBody')

    if first_name is None or last_name is None or email_address is None or subject is None or message is None:
        return HttpResponseRedirect(reverse('Toolshop:error'))
    elif first_name == "" or last_name == "" or email_address == "" or subject == "" or message == "":
        return HttpResponseRedirect(reverse('Toolshop:error'))
    elif len(first_name) > 30 or len(last_name) > 30 or len(email_address) > 50:
        return HttpResponseRedirect(reverse('Toolshop:error'))
    elif len(subject) > 100 or len(message) > 1000:
        return HttpResponseRedirect(reverse('Toolshop:error'))

    new_message = Message(first_name=first_name, last_name=last_name,
                          email=email_address, subject=subject,
                          message=message)
    new_message.save()
    # Always return an HttpResponseRedirect after successfully dealing
    # with POST data. This prevents data from being posted twice if a
    # user hits the Back button.
    return HttpResponseRedirect(reverse('Toolshop:redirect'))

def submission_error(request):
    context = {}
    return render(request, 'Toolshop/submission_error.html', context)

def update_error(request):
    context = {}
    return render(request, 'Toolshop/update_error.html', context)

def redirection_page(request):
    context = {

    }
    return render(request, 'Toolshop/redirect.html', context)

@permission_required('admin.can_add_log_entry')
def database_upload(request):
    template = "Toolshop/database_upload.html"
    prompt = {
        'order': 'Order of CSV should be category, name, value, quantity, on-hand, checked-out'
    }
    if request.method == "GET":
        return render(request, template, prompt)
    csv_file = request.FILES['file']
    if not csv_file.name.endswith('.csv'):
        messages.error(request, "This is not a CSV file")
    data_set = csv_file.read().decode('UTF-8')
    io_string = io.StringIO(data_set)
    next(io_string)
    for column in csv.reader(io_string, delimiter=','):
        print(int(column[3]))
        for i in range(int(column[3])):
            print("creating " + column[1])
            created = Tool(
                category=column[0],
                name=column[1],
                cost=column[2],
                times_checked_out=0
            )
            created.save()
    context = {

    }
    return render(request, template, context)


# flake8: noqa

from tempfile import TemporaryDirectory

from pytest import mark

import torch
from torch import nn, optim
from torch.utils.data import DataLoader, TensorDataset

from catalyst import dl
from catalyst.settings import IS_CUDA_AVAILABLE, NUM_CUDA_DEVICES, SETTINGS

class CustomRunner(dl.Runner):
    def handle_batch(self, batch):
        x, y1, y2 = batch
        y1_hat, y2_hat = self.model(x)
        self.batch = {
            "features": x,
            "logits1": y1_hat,
            "logits2": y2_hat,
            "targets1": y1,
            "targets2": y2,
        }

class CustomModule(nn.Module):
    def __init__(self, in_features: int, out_features1: int, out_features2: int):
        super().__init__()
        self.shared = nn.Linear(in_features, 128)
        self.head1 = nn.Linear(128, out_features1)
        self.head2 = nn.Linear(128, out_features2)

    def forward(self, x):
        x = self.shared(x)
        y1 = self.head1(x)
        y2 = self.head2(x)
        return y1, y2

def train_experiment(device, engine=None):
    with TemporaryDirectory() as logdir:
        # sample data
        num_samples, num_features, num_classes1, num_classes2 = int(1e4), int(1e1), 4, 10
        X = torch.rand(num_samples, num_features)
        y1 = (torch.rand(num_samples) * num_classes1).to(torch.int64)
        y2 = (torch.rand(num_samples) * num_classes2).to(torch.int64)

        # pytorch loaders
        dataset = TensorDataset(X, y1, y2)
        loader = DataLoader(dataset, batch_size=32, num_workers=1)
        loaders = {"train": loader, "valid": loader}

        # model, criterion, optimizer, scheduler
        model = CustomModule(num_features, num_classes1, num_classes2)
        criterion = nn.CrossEntropyLoss()
        optimizer = optim.Adam(model.parameters())
        scheduler = optim.lr_scheduler.MultiStepLR(optimizer, [2])

        callbacks = [
            dl.CriterionCallback(metric_key="loss1", input_key="logits1", target_key="targets1"),
            dl.CriterionCallback(metric_key="loss2", input_key="logits2", target_key="targets2"),
            dl.MetricAggregationCallback(
                metric_key="loss", metrics=["loss1", "loss2"], mode="mean"
            ),
            dl.OptimizerCallback(metric_key="loss"),
            dl.SchedulerCallback(),
            dl.AccuracyCallback(
                input_key="logits1",
                target_key="targets1",
                num_classes=num_classes1,
                prefix="one_",
            ),
            dl.AccuracyCallback(
                input_key="logits2",
                target_key="targets2",
                num_classes=num_classes2,
                prefix="two_",
            ),
            dl.CheckpointCallback(
                "./logs/one",
                loader_key="valid",
                metric_key="one_accuracy01",
                minimize=False,
                save_n_best=1,
            ),
            dl.CheckpointCallback(
                "./logs/two",
                loader_key="valid",
                metric_key="two_accuracy03",
                minimize=False,
                save_n_best=3,
            ),
        ]
        if SETTINGS.ml_required:
            # catalyst[ml] required
            callbacks.append(
                dl.ConfusionMatrixCallback(
                    input_key="logits1",
                    target_key="targets1",
                    num_classes=num_classes1,
                    prefix="one_cm",
                )
            )
            # catalyst[ml] required
            callbacks.append(
                dl.ConfusionMatrixCallback(
                    input_key="logits2",
                    target_key="targets2",
                    num_classes=num_classes2,
                    prefix="two_cm",
                )
            )

        # model training
        runner = CustomRunner()
        runner.train(
            engine=engine or dl.DeviceEngine(device),
            model=model,
            criterion=criterion,
            optimizer=optimizer,
            scheduler=scheduler,
            loaders=loaders,
            num_epochs=1,
            verbose=False,
            callbacks=callbacks,
            loggers={"console": dl.ConsoleLogger(), "tb": dl.TensorboardLogger("./logs/tb")},
        )

# Torch
def test_on_cpu():
    train_experiment("cpu")

@mark.skipif(not IS_CUDA_AVAILABLE, reason="CUDA device is not available")
def test_on_torch_cuda0():
    train_experiment("cuda:0")

@mark.skipif(not (IS_CUDA_AVAILABLE and NUM_CUDA_DEVICES >= 2), reason="No CUDA>=2 found")
def test_on_torch_cuda1():
    train_experiment("cuda:1")

@mark.skipif(not (IS_CUDA_AVAILABLE and NUM_CUDA_DEVICES >= 2), reason="No CUDA>=2 found")
def test_on_torch_dp():
    train_experiment(None, dl.DataParallelEngine())

@mark.skipif(not (IS_CUDA_AVAILABLE and NUM_CUDA_DEVICES >= 2), reason="No CUDA>=2 found")
def test_on_torch_ddp():
    train_experiment(None, dl.DistributedDataParallelEngine())

# AMP
@mark.skipif(not (IS_CUDA_AVAILABLE and SETTINGS.amp_required), reason="No CUDA or AMP found")
def test_on_amp():
    train_experiment(None, dl.AMPEngine())

@mark.skipif(
    not (IS_CUDA_AVAILABLE and NUM_CUDA_DEVICES >= 2 and SETTINGS.amp_required),
    reason="No CUDA>=2 or AMP found",
)
def test_on_amp_dp():
    train_experiment(None, dl.DataParallelAMPEngine())

@mark.skipif(
    not (IS_CUDA_AVAILABLE and NUM_CUDA_DEVICES >= 2 and SETTINGS.amp_required),
    reason="No CUDA>=2 or AMP found",
)
def test_on_amp_ddp():
    train_experiment(None, dl.DistributedDataParallelAMPEngine())

# APEX
@mark.skipif(not (IS_CUDA_AVAILABLE and SETTINGS.apex_required), reason="No CUDA or Apex found")
def test_on_apex():
    train_experiment(None, dl.APEXEngine())

@mark.skipif(
    not (IS_CUDA_AVAILABLE and NUM_CUDA_DEVICES >= 2 and SETTINGS.apex_required),
    reason="No CUDA>=2 or Apex found",
)
def test_on_apex_dp():
    train_experiment(None, dl.DataParallelAPEXEngine())

@mark.skipif(
    not (IS_CUDA_AVAILABLE and NUM_CUDA_DEVICES >= 2 and SETTINGS.apex_required),
    reason="No CUDA>=2 or Apex found",
)
def test_on_apex_ddp():
    train_experiment(None, dl.DistributedDataParallelAPEXEngine())


"""
在闭包中修改自由变量时，对数字、字符串、元组等不可变类型必须使用nonlocal声明
而对于可变类型则不需要，因为可变类型的地址始终保持不变
"""

def make_averager():
    count = 0
    total = 0
    def averager(new_value):
        nonlocal count, total
        count += 1 # count = count + 1，其实会隐式创建局部变量 count
        total += new_value
        return total / count
    return averager

if __name__ == '__main__':
    avg = make_averager()
    print(avg(1)) # 1.0
    print(avg(2)) # 1.5
    print(avg(3)) # 2.0

2_闭包中数据的修改.py


import os
from django import template
from django.core.paginator import Paginator
from s13sitecore.models.ContentModels import Article, SiteSection as Section
from s13sitecore.models.FMSModels import FileInfo
from s13sitecore.helpers.ValueHelpers import convert_value_type

register = template.Library()

@register.filter
def date_format(date_value, format_string):
    """Implements date.strftime."""
    return date_value.strftime(format_string)

@register.filter
def dict_get(haystack, needle):
    """Implements the dict's get method. This can then be piped to the
    dict_get_none filter.
    """
    return haystack.get(needle, "")

@register.filter
def dict_get_none(haystack, replacement):
    """See dict_get. Basically, this is the default part of a dict.get and is
    used like: some_dict| dict_get:"key"| dict_get_none:"value if key is empty"
    """
    if not haystack:
        return replacement
    else:
        return haystack

@register.filter
def endswith(haystack, needle):
    """Implements the endswith string method."""
    return haystack.endswith(needle)

@register.filter
def list_get_index(list_, index):
    """Implements list[index]."""
    return list_[index]

@register.filter
def list_index_of(haystack, needle):
    """Implements list.index(item)."""
    return haystack.index(needle)

@register.filter
def startswith(haystack, needle):
    """Implements the startswith string method."""
    return haystack.startswith(needle)

@register.filter
def string_split(string, separator):
    """Implements string.split(separator)."""
    return string.split(separator.decode("string_escape"))

# Head information context helpers.
@register.simple_tag(takes_context=True)
def make_title(context, default_title, site_prefix=None):
    """Generates the appropriate title for the page."""
    section = context["section"]
    article = context["article"]
    context["head_title"] = "Server Message"
    if article:
        if section.name == "Home" and article.name == "home":
            if site_prefix:
                context["head_title"] = "%s: %s" % (site_prefix, default_title)
            else:
                context["head_title"] = default_title
        elif section.name != "Home" and article.name.endswith("-home"):
            if site_prefix:
                context["head_title"] = "%s: %s" % (site_prefix, section.title)
            else:
                context["head_title"] = section.title
        else:
            context["head_title"] = "%s: %s" % (section.title, article.title)
            if article.parent:
                if article.parent.parent:
                    context["head_title"] = "%s: %s" % \
                        (article.parent.title, article.title)
    return ""

@register.simple_tag(takes_context=True)
def make_article_image_url(context, default_image):
    """Generates the article's preview image URL."""
    thumb = context["article"].make_article_image()
    if not thumb:
        thumb = default_image
    if thumb.startswith("/"):
        thumb = "%s://%s%s" % (context["request"].is_secure() and \
            "https" or "http", context["request"].META["HTTP_HOST"], thumb)
    context["head_image"] = thumb
    return ""

# Navigation helpers.
@register.simple_tag(takes_context=True)
def get_next_and_previous_articles(context, article=None, siblings=None):
    """Gets the next and previous articles relative to the current article or
    a pre-selected one."""
    if article is None:
        if not context["article"]:
            return ""
        else:
            article = context["article"]
    if siblings is None:
        siblings = context["siblings"]
    if type(siblings) != list:  # Because we might get a QuerySet.
        siblings = list(siblings)
    if siblings.index(article) > 0:
        context["next_article"] = siblings[siblings.index(article) - 1]
    if len(siblings) - 1 > siblings.index(article):
        context["previous_article"] = siblings[siblings.index(article) + 1]
    return ""

@register.simple_tag(takes_context=True)
def make_articles_list(context, *args, **kargs):
    """Creates an arbitrarily sorted selection of articles in context called
    "articles_list". args are sorter strings like -date_edit, +title, etc;
    default is date_edit. kargs are to be used in filtering selections;
    exclusions are done by supplying <property>__ne kargs.

    <property>__in is a possible filter argument and ", " is the
    mandatory separator.

    section is also a possible filter argument. Comparison values can be:
    a Section instance, a name of an existing section (will throw an error
    if the section does not exist), a list of existing section names (for
    filtering by section__in).
    """
    a = context["article"]
    context["articles_list"] = []
    if not args:  # We want at least one sorter.
        args = ["date_edit"]
    if kargs:
        includes = {}
        excludes = []
        for k, v in kargs.iteritems():
            # __in requires a list or tuple to be passed.
            if "__in" in k:
                if type(v).__name__ is "SafeText":
                    v = [x for x in v.split(", ")]
            # If we're selecting by section, allow selecting via its name.
            if "section" in k:
                if type(v) is list:
                    v = [Section.objects.get(name=x) for x in v]
                if type(v).__name__ is "SafeText":
                    v = Section.objects.get(name=v)
            if k.endswith("__ne"):
                excludes.append({k.replace("__ne", ""): v})
            else:
                includes[k] = v
        selected = Article.objects.filter(**includes)
        for e in excludes:
            # Because simply doing selected.exclude(**excludes), if we had an
            # excludes dict doesn't really do what we want it to do.
            selected = selected.exclude(**e)
        context["articles_list"] = selected.order_by(*args)
    else:
        context["articles_list"] = Article.objects.all().order_by(*args)
    if a.show_children:
            context["articles_list"][:a.show_children]
    return ""

@register.simple_tag(takes_context=True)
def paginator_create(context, list_items, items_per_page):
    """Creates a Paginator instance based on list_items."""
    context["paginator_instance"] = Paginator(list_items, items_per_page)
    return ""

@register.simple_tag(takes_context=True)
def paginator_page(context):
    """Implements paginator_instance.page(number), where number is passed via
    request.GET.get('page'). Use this only after invoking paginator_create.
    """
    if "paginator_instance" in context:
        page_number = context["request"].GET.get("page", "1")
        if not page_number.isdigit():
            page_number = "1"
        page_number = int(page_number)
        if page_number < 1:
            page_number = 1
        context["page_number"] = page_number
        context["page_range"] = [x + 1 for x \
            in range(context["paginator_instance"].num_pages)]
        if page_number < context["paginator_instance"].num_pages:
            context["page_contents"] = \
                context["paginator_instance"].page(page_number)
    return ""

@register.simple_tag(takes_context=True)
def select_article(context, article_name):
    """Selects an Article object and assigns it to context["selected_article"].
    """
    context["selected_article"] = Article.objects.get(name=article_name)
    return ""

@register.simple_tag(takes_context=True)
def select_fms_item(context, attr, value):
    """Selects file information using the FileInfo model."""
    context["selected_fms_item"] = None
    items = [x for x in FileInfo.objects.all() if getattr(x, attr) == value]
    if items:
        context["selected_fms_item"] = items[0]
    return ""

@register.simple_tag(takes_context=True)
def select_section(context, section_name):
    """Selects a Section object and assigns it to context["selected_section"].
    """
    context["selected_section"] = Section.objects.get(name=section_name)
    return ""

# Other helpers.
@register.simple_tag(takes_context=True)
def assign_to_context(context, key, value, to_type=None):
    """All-purpose context key assigner."""
    if to_type:
        context[key] = convert_value_type(value, to_type)
    else:
        context[key] = value
    return ""

@register.simple_tag(takes_context=True)
def complex_if(context, eval_string, **kargs):
    """Alias for evaluating complex if conditions given as string. For brevity,
    the eval_string expects +['key'] instead of kargs['key'] for substrings that
    need replacement. The result is found in context["complex_if_result"].

    Usage:

    {% complex_if "(+['a'] > 5 and +['a'] < 10) or +[b] == 16" a=7 b=14 %}
    {% if complex_if_result %}

This should be rendered because the condition is True.

    {% endif %}
    """
    eval_string = eval_string.replace("+[", "kargs[")
    context["complex_if_result"] = eval(eval_string % kargs)
    return ""

@register.simple_tag(takes_context=True)
def read_file_contents(context, path):
    """Reads a files contents into a context key."""
    context["file_contents"] = ""
    with open(path) as f:
        context["read_file_contents"] = f.read()
    return ""


#!/usr/bin/env python
# coding=utf-8
'''
@Author: Jin X
@Date: 2020-02-26 15:16:09
@LastEditTime: 2020-02-28 12:23:06
'''
from crawlHistory import *
import time
from multiprocessing import Process

def periodSeq(t=1582641000):
    cur = int(time.time())
    if cur - t > 60:
        return (t, cur)

    while cur-t > 60:
        yield (t-1, t+1)
        t += 86400

def requestThread(periodseq):
    try:
        period = next(periodseq)
    except StopIteration:
        return
    stocks = requestStocks(period)
    print('requested---'+time.strftime('%Y-%m-%d %H:%M:%S'))
    for stock in stocks:
        print('name {}, time {}'.format(stock[0], stock[1]))
    threading.Timer(5, requestThread, [periodseq]).start()

def requestProcess(name, lastStamp):
    while True:
        weekday = time.localtime().tm_wday
        hour = time.localtime().tm_hour
        interval = '1m'
        print('{} :'.format(name), end='')
        if 0 <= weekday <= 4:
            if 9 <= hour < 16:
                print('state: sleep 1 minute')
                time.sleep(60)
            else:
                print('state: sleep 1 hour')
                time.sleep(3600)
                interval = '1h'
        else:
            print('state: sleep 1 day')
            time.sleep(3600*12)
        print('{} :lastStamp: {},state: crawling'.format(
            name, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(lastStamp))))
        curr = int(time.time())
        periods = [lastStamp, curr-curr % 60]
        timestamp, quote = requestStock(name, periods, interval)
        if timestamp is not None:
            with open('./data/1m/{}.csv'.format(name), 'a+') as f:
                for qTime, qOpen, qClose, qVolume, qLow, qHigh in \
                        zip(timestamp, quote['open'], quote['close'],
                            quote['volume'], quote['low'], quote['high']):
                    if qOpen is not None:
                        f.write(
                            str([qTime, qOpen, qClose, qVolume, qLow, qHigh])[1:-1]+'\n')
                        lastStamp = qTime

if __name__ == '__main__':
    lastStamp = {}
    for stock in stocksName:
        lastStamp[stock] = 1582741200  # Feb 26 2020, 13:20 GMT-5
        with open('./data/1m/{}.csv'.format(stock), 'w+') as f:
            f.write('timestamp,open,close,volume,low,high\n')

    for stock in stocksName:
        p = Process(target=requestProcess, args=(stock, lastStamp[stock]))
        p.start()


import datetime as dt
import os
import subprocess
from pathlib import Path

import magic
from itemadapter import ItemAdapter
from scrapy.exceptions import DropItem
from scrapy.http import Request
from scrapy.pipelines.files import FilesPipeline
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import sessionmaker

from gazette.settings import FILES_STORE

class GazetteDateFilteringPipeline:
    def process_item(self, item, spider):
        if hasattr(spider, "start_date"):
            if spider.start_date > item.get("date"):
                raise DropItem("Droping all items before {}".format(spider.start_date))
        return item

class DefaultValuesPipeline:
    """ Add defaults values field, if not already set in the item """

    default_field_values = {
        "territory_id": lambda spider: getattr(spider, "TERRITORY_ID"),
        "scraped_at": lambda spider: dt.datetime.utcnow(),
    }

    def process_item(self, item, spider):
        for field in self.default_field_values:
            if field not in item:
                item[field] = self.default_field_values.get(field)(spider)
        return item

class ExtractTextPipeline:
    """
    Identify file format and call the right tool to extract the text from it
    """

    def process_item(self, item, spider):
        extract_text_from_file = spider.settings.getbool(
            "QUERIDODIARIO_EXTRACT_TEXT_FROM_FILE", True
        )
        if not extract_text_from_file:
            return item

        if self.is_doc(item["files"][0]["path"]):
            item["source_text"] = self.doc_source_text(item)
        elif self.is_pdf(item["files"][0]["path"]):
            item["source_text"] = self.pdf_source_text(item)
        elif self.is_txt(item["files"][0]["path"]):
            item["source_text"] = self.txt_source_text(item)
        else:
            raise Exception(
                "Unsupported file type: " + self.get_file_type(item["files"][0]["path"])
            )

        item_file = item["files"][0]
        item["file_path"] = item_file["path"]
        item["file_url"] = item_file["url"]
        item["file_checksum"] = item_file["checksum"]

        item.pop("files")
        item.pop("file_urls")
        return item

    def pdf_source_text(self, item):
        """
        Gets the text from pdf files
        """
        pdf_path = os.path.join(FILES_STORE, item["files"][0]["path"])
        text_path = pdf_path + ".txt"
        command = f"pdftotext -layout {pdf_path} {text_path}"
        subprocess.run(command, shell=True, check=True)
        with open(text_path) as file:
            return file.read()

    def doc_source_text(self, item):
        """
        Gets the text from docish files
        """
        doc_path = os.path.join(FILES_STORE, item["files"][0]["path"])
        text_path = doc_path + ".txt"
        command = f"java -jar /tika-app.jar --text {doc_path}"
        with open(text_path, "w") as f:
            subprocess.run(command, shell=True, check=True, stdout=f)
        with open(text_path, "r") as f:
            return f.read()

    def txt_source_text(self, item):
        """
        Gets the text from txt files
        """
        with open(
            os.path.join(FILES_STORE, item["files"][0]["path"]), encoding="ISO-8859-1"
        ) as f:
            return f.read()

    def is_pdf(self, filepath):
        """
        If the file type is pdf returns True. Otherwise,
        returns False
        """
        return self._is_file_type(filepath, file_types=["application/pdf"])

    def is_doc(self, filepath):
        """
        If the file type is doc or similar returns True. Otherwise,
        returns False
        """
        file_types = [
            "application/msword",
            "application/vnd.oasis.opendocument.text",
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        ]
        return self._is_file_type(filepath, file_types)

    def is_txt(self, filepath):
        """
        If the file type is txt returns True. Otherwise,
        returns False
        """
        return self._is_file_type(filepath, file_types=["text/plain"])

    def get_file_type(self, filename):
        """
        Returns the file's type
        """
        file_path = os.path.join(FILES_STORE, filename)
        return magic.from_file(file_path, mime=True)

    def _is_file_type(self, filepath, file_types):
        """
        Generic method to check if a identified file type matches a given list of types
        """
        return self.get_file_type(filepath) in file_types

class RequestWithItem(Request):
    """
    Specialized Request object to allow carry the item which generate the request.
    Thus, we can use the gazette date in the path where the file will be stored.
    """

    def __init__(self, url, item):
        super().__init__(url)
        self.item = item

class QueridoDiarioFilesPipeline(FilesPipeline):
    """
    When the downloaded file are stored in a remote storage system (e.g.
    Digital Ocean spaces), we need to specialize FilesPipeline class in order
    to allow us define a different directory where the files will be store. In
    the current implementation we organize gazette files by date. All the
    gazettes from the same date will be store in the same directory.
    """

    def file_path(self, request, response=None, info=None):
        filepath = super().file_path(request, response, info)
        # The default path from the scrapy class begins with "full/". In this
        # class we replace that with the gazette date.
        datestr = request.item["date"].strftime("%d-%m-%Y")
        filename = Path(filepath).name
        return str(Path(datestr, filename))

    def get_media_requests(self, item, info):
        urls = ItemAdapter(item).get(self.files_urls_field)
        if not urls:
            return
        yield from (RequestWithItem(u, item) for u in urls)


def in_range(nums, lowest, highest):
    """Print numbers inside range.

    - nums: list of numbers
    - lowest: lowest number to print
    - highest: highest number to print

    For example:

      in_range([10, 20, 30, 40], 15, 30)

    should print:

      20 fits
      30 fits
    """

    # YOUR CODE HERE
    lowest_in_range = false
    highest_in_range = false
    if lowest > nums[0] and lowest < nums[-1]:
      print (f"{lowest} fits")
    if highest > nums[0] and highest < nums[-1]:
      print (f"{highest} fits")

in_range([10, 20, 30, 40, 50], 15, 30)


#!/usr/bin/env python
# Site Views and access

Guest = ['signup']
Student = ['workbook','u1','u2', 'signup', 'suc', 'sue', 'suv', 'chk', 'library']
Tutor = ['aue','auv', 'signup']
Admin = ['library', 'admin','adminU','auc','aue','auv', 'users', 'modify', 'signup', 'verification', 'workbook', 'u1',
         'suc', 'sue', 'suv', 'chk', 'loader']

def acl_check(role, page):
    if role == 'Student':
        if page in Student:
            return True
    elif role == 'Admin':
        if page in Admin:
            return True
    elif role == "NoneType":
        if page in Guest:
            return True

    return False


class Solution:
    def rob(self, nums: List[int]) -> int:
        if len(nums)==0:
            return 0
        if len(nums)==1:
            return nums[0]
        if len(nums)==2:
            return max(nums[0],nums[1])
        dp=[None]*len(nums)
        dp[0]=nums[0]
        dp[1]=max(nums[0],nums[1])
        for i in range(2,len(nums)):
            dp[i]=max(nums[i]+dp[i-2],dp[i-1])
        return dp[len(nums)-1]

        #time complexity is O(n)
        #space complexity is O(n)


import torch
import torch.nn as nn
from network import Conv2d,SELayer,Dilated2
import numpy as np
from torch.autograd import Variable

class MCNN(nn.Module):
    '''
    Multi-column CNN
        -Implementation of Single Image Crowd Counting via Multi-column CNN (Zhang et al.)
    '''
    def __init__(self, bn=False):
        super(MCNN, self).__init__()

        self.branch1 = nn.Sequential(Conv2d(1, 64, 3, bn=bn),
                                     Conv2d(64, 64, 3,bn=bn),
                                     nn.MaxPool2d(2))

        self.branch2 = nn.Sequential(Conv2d(64, 128, 3, bn=bn),
                                     Conv2d(128, 128, 3,bn=bn),
                                     nn.MaxPool2d(2))

        self.branch3 = nn.Sequential(Conv2d(128, 256, 3,bn=bn),
                                     Conv2d(256, 256, 3,bn=bn),
                                     Conv2d(256, 256, 3,bn=bn),
                                     nn.MaxPool2d(2))

        self.branch4 = nn.Sequential(Conv2d(256, 512, 3,bn=bn),
                                     Conv2d(512, 512, 3,bn=bn),
                                     Conv2d(512, 512, 3,bn=bn),
                                     nn.MaxPool2d(2),
                                     nn.Upsample(scale_factor= 2, mode='nearest'))

        self.branch5 = nn.Sequential(Conv2d(768,512,1,bn=bn),
                                     Conv2d(512,512,3,bn=bn),
                                     Conv2d(512,512,3,bn=bn),
                                     nn.Upsample(scale_factor= 2, mode='nearest'))

        self.branch6 = nn.Sequential(Conv2d(640,512,1,bn=bn),
                                     Conv2d(512,512,3,bn=bn),
                                     Conv2d(512,512,3,bn=bn),
                                     nn.Upsample(scale_factor= 2, mode='nearest'))

        self.branch7 = nn.Sequential(Dilated2(576,512,3,2, bn=bn),
                                     Dilated2(512,256,3,2, bn=bn),
                                     Dilated2(256,128,3,2, bn=bn),
                                     Dilated2(128, 64,3,2, bn=bn),
                                     Conv2d(64,1,1,bn=bn))
        self.se1 = SELayer(768, 192)
        self.se2 = SELayer(640, 160)
        self.se3 = SELayer(576, 144)
    def forward(self, im_data):
        x1 = self.branch1(im_data)
        x2 = self.branch2(x1)
        x3 = self.branch3(x2)
        x4 = self.branch4(x3)
        a1 = x3.shape[2:]
        b1 = x4.shape[2:]
        if b1!=a1:
            x4 = x4.data
            x4 = np.array([np.array(x4[0,i,:,:].resize_(a1)) for i in range(x4.shape[1])])
            x4 = np.expand_dims(x4,axis=0)
            x4 = Variable(torch.from_numpy(x4)).cuda()
        x5 = torch.cat((x4,x3),1)
        x51 = self.se1(x5)
        x51+=x5
        x6 = self.branch5(x51)
        a2 = x2.shape[2:]
        b2 = x6.shape[2:]
        if b2!=a2:
            x6 = x6.data
            x6 = np.array([np.array(x6[0,i,:,:].resize_(a2)) for i in range(x6.shape[1])])
            x6 = np.expand_dims(x6,axis=0)
            x6 = Variable(torch.from_numpy(x6)).cuda()
        x7 = torch.cat((x6,x2),1)
        x8 = self.se2(x7)
        x8 += x7
        x9 = self.branch6(x8)
        a3 = x1.shape[2:]
        b3 = x9.shape[2:]
        if b3!=a3:
            x9 = x9.data
            x9 = np.array([np.array(x9[0,i,:,:].resize_(a3)) for i in range(x9.shape[1])])
            x9 = np.expand_dims(x9,axis=0)
            x9 = Variable(torch.from_numpy(x9)).cuda()
        x10 = torch.cat((x1,x9),1)
        x11 = self.se3(x10)
        x11 += x10
        x = self.branch7(x11)
        return x


# Define a word_lengths function that accepts a string.
# It should return a list with the lengths of each word.
#
# EXAMPLES
# word_lengths("Mary Poppins was a nanny")  => [4, 7, 3, 1, 5]
# word_lengths("Somebody stole my donut")   => [8, 5, 2, 5]
def word_lengths(string):
    values = string.split(" ")
    new_string = []
    for value in values:
        new_string.append(len(value))
    return new_string
print(word_lengths("Mary Poppins was a nanny"))

# Define a cleanup function that accepts a list of strings.
# The function should return the strings joined together by a space.
# There's one BIG problem -- some of the strings are empty or only consist of spaces!
# These should NOT be included in the final string
#
# cleanup(["cat", "er", "pillar"])           => "cat er pillar"
# cleanup(["cat", " ", "er", "", "pillar"])  => "cat er pillar"
# cleanup(["", "", " "])                     => ""
def cleanup(strings):
    clean_strings = []
    for string in strings:
        if string.isspace() or len(string) == 0:
            continue
        clean_strings.append(string)
    return (" ".join(clean_strings))
print(cleanup(["cat", "er","    " , "pillar"]))


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

# Import arcpy module
import arcpy
from arcpy.sa import *

#Check out license and allow overwriting
arcpy.CheckOutExtension("Spatial")
arcpy.env.overwriteOutput = True

# Script arguments
Input__workspace = r"C:/Users/noah8742/acr_tool"

arcpy.env.workspace = Input__workspace

Input__elevation_raster = r"bathy5m.tif"

Input__elevation_raster_cell_area__sq__meter_ = 25

Input__contoured_area_raster__surf_area_ = r"contoured_area.tif"

Output__ACR_rugosity_raster_file = r"acr_rugosity.tif"

# Local variables:
Slope_angle_raster = arcpy.sa.Slope(Input__elevation_raster, "DEGREE", "1")

# Process: Raster Calculator (1)
Planar_area_raster = Divide(Input__elevation_raster_cell_area__sq__meter_,Cos(Times(Slope_angle_raster,0.01745)))

# Process: Raster Calculator (2)
Output__ACR_rugosity_raster = Divide(Input__contoured_area_raster__surf_area_,Planar_area_raster)

#Save output raster
Output__ACR_rugosity_raster.save(Output__ACR_rugosity_raster_file)

arcpy.CheckInExtension("Spatial")


from logic import *

хагрид = Символ("хагрид")   # Гарри посетил Хагирда.
дамблдор = Символ("дамблдор") # Гарри посетил Дамблдора.
дождь = Символ("дождь") # Идёт дождь.

знания = И(Импликация(Не(дождь), хагрид),
        Или(хагрид, дамблдор),
        Не(И(хагрид, дамблдор)),
        дамблдор)

print(проверка_моделей(знания, дождь))


from sys import stdin
tree = [0]*1000005
def update(idx, val):
    idx+=1
    while idx < 1000005:
        tree[idx]+=val
        idx+=idx&(-idx)
def query(idx):
    idx+=1
    ret=0
    while idx:
        ret+=tree[idx]
        idx-=idx&(-idx)
    return ret

input=stdin.readline
n, q=map(int, input().split())
for i in range(q):
    a, b, c=map(int, input().split())
    if a==1:
        update(b, c)
    else:
        print(query(c)-query(b-1))


class Node:

    # Utility function to create new node
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

def isMirror(root1, root2):
    # If both trees are empty, then they are mirror images
    if root1 is None and root2 is None:
        return True

    """ For two trees to be mirror images,
        the following three conditions must be true
        1 - Their root node's data must be same
        2 - left subtree of left tree and right subtree
          of the right tree have to be mirror images
        3 - right subtree of left tree and left subtree
           of right tree have to be mirror imageso
    """
    if (root1 is not None and root2 is not None):
        if root1.data == root2.data:
            return (isMirror(root1.left, root2.right)and
                    isMirror(root1.right, root2.left))

    # If none of the above conditions is true then root1
    # and root2 are not mirror images
    return False

def isSymmetric(root):
    return isMirror(root, root)

root = Node(1)
root.left = Node(2)
root.right = Node(2)
root.left.left = Node(3)
root.left.right = Node(4)
root.right.left = Node(4)
root.right.right = Node(3)
print("Symmetric" if isSymmetric(root) == True else "Not symmetric")


# Copyright 2016 Spirent Communications.
#
# Licensed 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.

'''
@author Spirent Communications

This test automates the RFC2544 tests using the Spirent
TestCenter REST APIs. This test supports Python 3.4

'''
import argparse
import logging
import os

logger = logging.getLogger(__name__)

def create_dir(path):
    """Create the directory as specified in path """
    if not os.path.exists(path):
        try:
            os.makedirs(path)
        except OSError as e:
            logger.error("Failed to create directory %s: %s", path, str(e))
            raise

def write_query_results_to_csv(results_path, csv_results_file_prefix,
                               query_results):
    """ Write the results of the query to the CSV """
    create_dir(results_path)
    filec = os.path.join(results_path, csv_results_file_prefix + ".csv")
    with open(filec, "wb") as f:
        f.write(query_results["Columns"].replace(" ", ",") + "\n")
        for row in (query_results["Output"].replace("} {", ",").
                    replace("{", "").replace("}", "").split(",")):
            f.write(row.replace(" ", ",") + "\n")

def positive_int(value):
    """ Positive Integer type for Arguments """
    ivalue = int(value)
    if ivalue <= 0:
        raise argparse.ArgumentTypeError(
            "%s is an invalid positive int value" % value)
    return ivalue

def percent_float(value):
    """ Floating type for Arguments """
    pvalue = float(value)
    if pvalue < 0.0 or pvalue > 100.0:
        raise argparse.ArgumentTypeError(
            "%s not in range [0.0, 100.0]" % pvalue)
    return pvalue

def main():
    """ Read the arguments, Invoke Test and Return the results"""
    parser = argparse.ArgumentParser()
    # Required parameters
    required_named = parser.add_argument_group("required named arguments")
    required_named.add_argument("--lab_server_addr",
                                required=True,
                                help=("The IP address of the"
                                      "Spirent Lab Server"),
                                dest="lab_server_addr")
    required_named.add_argument("--license_server_addr",
                                required=True,
                                help=("The IP address of the Spirent"
                                      "License Server"),
                                dest="license_server_addr")
    required_named.add_argument("--east_chassis_addr",
                                required=True,
                                help=("The TestCenter chassis IP address to"
                                      "use for the east test port"),
                                dest="east_chassis_addr")
    required_named.add_argument("--east_slot_num",
                                type=positive_int,
                                required=True,
                                help=("The TestCenter slot number to"
                                      "use for the east test port"),
                                dest="east_slot_num")
    required_named.add_argument("--east_port_num",
                                type=positive_int,
                                required=True,
                                help=("The TestCenter port number to use"
                                      "for the east test port"),
                                dest="east_port_num")
    required_named.add_argument("--west_chassis_addr",
                                required=True,
                                help=("The TestCenter chassis IP address"
                                      "to use for the west test port"),
                                dest="west_chassis_addr")
    required_named.add_argument("--west_slot_num",
                                type=positive_int,
                                required=True,
                                help=("The TestCenter slot number to use"
                                      "for the west test port"),
                                dest="west_slot_num")
    required_named.add_argument("--west_port_num",
                                type=positive_int,
                                required=True,
                                help=("The TestCenter port number to"
                                      "use for the west test port"),
                                dest="west_port_num")
    # Optional parameters
    optional_named = parser.add_argument_group("optional named arguments")
    optional_named.add_argument("--metric",
                                required=False,
                                help=("One among - throughput, latency,\
                                      backtoback and frameloss"),
                                choices=["throughput", "latency",
                                         "backtoback", "frameloss"],
                                default="throughput",
                                dest="metric")
    optional_named.add_argument("--test_session_name",
                                required=False,
                                default="RFC2544 East-West Throughput",
                                help=("The friendly name to identify"
                                      "the Spirent Lab Server test session"),
                                dest="test_session_name")

    optional_named.add_argument("--test_user_name",
                                required=False,
                                default="RFC2544 East-West User",
                                help=("The friendly name to identify the"
                                      "Spirent Lab Server test user"),
                                dest="test_user_name")
    optional_named.add_argument("--results_dir",
                                required=False,
                                default="./Results",
                                help="The directory to copy results to",
                                dest="results_dir")
    optional_named.add_argument("--csv_results_file_prefix",
                                required=False,
                                default="Rfc2544Tput",
                                help="The prefix for the CSV results files",
                                dest="csv_results_file_prefix")
    optional_named.add_argument("--num_trials",
                                type=positive_int,
                                required=False,
                                default=1,
                                help=("The number of trials to execute during"
                                      "the test"),
                                dest="num_trials")
    optional_named.add_argument("--trial_duration_sec",
                                type=positive_int,
                                required=False,
                                default=60,
                                help=("The duration of each trial executed"
                                      "during the test"),
                                dest="trial_duration_sec")
    optional_named.add_argument("--traffic_pattern",
                                required=False,
                                choices=["BACKBONE", "MESH", "PAIR"],
                                default="PAIR",
                                help="The traffic pattern between endpoints",
                                dest="traffic_pattern")
    optional_named.add_argument("--traffic_custom",
                                required=False,
                                default=None,
                                help="The traffic pattern between endpoints",
                                dest="traffic_custom")
    optional_named.add_argument("--search_mode",
                                required=False,
                                choices=["COMBO", "STEP", "BINARY"],
                                default="BINARY",
                                help=("The search mode used to find the"
                                      "throughput rate"),
                                dest="search_mode")
    optional_named.add_argument("--learning_mode",
                                required=False,
                                choices=["AUTO", "L2_LEARNING",
                                         "L3_LEARNING", "NONE"],
                                default="AUTO",
                                help=("The learning mode used during the test,"
                                      "default is 'NONE'"),
                                dest="learning_mode")
    optional_named.add_argument("--rate_lower_limit_pct",
                                type=percent_float,
                                required=False,
                                default=1.0,
                                help=("The minimum percent line rate that"
                                      "will be used during the test"),
                                dest="rate_lower_limit_pct")
    optional_named.add_argument("--rate_upper_limit_pct",
                                type=percent_float,
                                required=False,
                                default=99.0,
                                help=("The maximum percent line rate that"
                                      "will be used during the test"),
                                dest="rate_upper_limit_pct")
    optional_named.add_argument("--rate_initial_pct",
                                type=percent_float,
                                required=False,
                                default=99.0,
                                help=("If Search Mode is BINARY, the percent"
                                      "line rate that will be used at the"
                                      "start of the test"),
                                dest="rate_initial_pct")
    optional_named.add_argument("--rate_step_pct",
                                type=percent_float,
                                required=False,
                                default=10.0,
                                help=("If SearchMode is STEP, the percent"
                                      "load increase per step"),
                                dest="rate_step_pct")
    optional_named.add_argument("--resolution_pct",
                                type=percent_float,
                                required=False,
                                default=1.0,
                                help=("The minimum percentage of load"
                                      "adjustment between iterations"),
                                dest="resolution_pct")
    optional_named.add_argument("--frame_size_list",
                                type=lambda s: [int(item)
                                                for item in s.split(',')],
                                required=False,
                                default=[256],
                                help="A comma-delimited list of frame sizes",
                                dest="frame_size_list")
    optional_named.add_argument("--acceptable_frame_loss_pct",
                                type=percent_float,
                                required=False,
                                default=0.0,
                                help=("The maximum acceptable frame loss"
                                      "percent in any iteration"),
                                dest="acceptable_frame_loss_pct")
    optional_named.add_argument("--east_intf_addr",
                                required=False,
                                default="192.85.1.3",
                                help=("The address to assign to the first"
                                      "emulated device interface on the first"
                                      "east port"),
                                dest="east_intf_addr")
    optional_named.add_argument("--east_intf_gateway_addr",
                                required=False,
                                default="192.85.1.53",
                                help=("The gateway address to assign to the"
                                      "first emulated device interface on the"
                                      "first east port"),
                                dest="east_intf_gateway_addr")
    optional_named.add_argument("--west_intf_addr",
                                required=False,
                                default="192.85.1.53",
                                help=("The address to assign to the first"
                                      "emulated device interface on the"
                                      "first west port"),
                                dest="west_intf_addr")
    optional_named.add_argument("--west_intf_gateway_addr",
                                required=False,
                                default="192.85.1.53",
                                help=("The gateway address to assign to"
                                      "the first emulated device interface"
                                      "on the first west port"),
                                dest="west_intf_gateway_addr")
    parser.add_argument("-v",
                        "--verbose",
                        required=False,
                        default=True,
                        help="More output during operation when present",
                        action="store_true",
                        dest="verbose")
    args = parser.parse_args()

    if args.verbose:
        logger.debug("Creating results directory")
    create_dir(args.results_dir)

    session_name = args.test_session_name
    user_name = args.test_user_name

    try:
        # Load Spirent REST Library
        from stcrestclient import stchttp

        stc = stchttp.StcHttp(args.lab_server_addr)
        session_id = stc.new_session(user_name, session_name)
        stc.join_session(session_id)
    except RuntimeError as e:
        logger.error(e)
        raise

    # Get STC system info.
    tx_port_loc = "//%s/%s/%s" % (args.east_chassis_addr,
                                  args.east_slot_num,
                                  args.east_port_num)
    rx_port_loc = "//%s/%s/%s" % (args.west_chassis_addr,
                                  args.west_slot_num,
                                  args.west_port_num)

    # Retrieve and display the server information
    if args.verbose:
        logger.debug("SpirentTestCenter system version: %s",
                     stc.get("system1", "version"))

    try:
        device_list = []
        port_list = []
        if args.verbose:
            logger.debug("Bring up license server")
        license_mgr = stc.get("system1", "children-licenseservermanager")
        if args.verbose:
            logger.debug("license_mgr = %s", license_mgr)
        stc.create("LicenseServer", under=license_mgr, attributes={
                   "server": args.license_server_addr})

        # Create the root project object
        if args.verbose:
            logger.debug("Creating project ...")
        project = stc.get("System1", "children-Project")

        # Configure any custom traffic parameters
        if args.traffic_custom == "cont":
            if args.verbose:
                logger.debug("Configure Continuous Traffic")
            stc.create("ContinuousTestConfig", under=project)

        # Create ports
        if args.verbose:
            logger.debug("Creating ports ...")
        east_chassis_port = stc.create('port', project)
        if args.verbose:
            logger.debug("Configuring TX port ...")
        stc.config(east_chassis_port, {'location': tx_port_loc})
        port_list.append(east_chassis_port)

        west_chassis_port = stc.create('port', project)
        if args.verbose:
            logger.debug("Configuring RX port ...")
        stc.config(west_chassis_port, {'location': rx_port_loc})
        port_list.append(west_chassis_port)

        # Create emulated genparam for east port
        east_device_gen_params = stc.create("EmulatedDeviceGenParams",
                                            under=project,
                                            attributes={"Port":
                                                        east_chassis_port})
        # Create the DeviceGenEthIIIfParams object
        stc.create("DeviceGenEthIIIfParams",
                   under=east_device_gen_params)
        # Configuring Ipv4 interfaces
        stc.create("DeviceGenIpv4IfParams",
                   under=east_device_gen_params,
                   attributes={"Addr": args.east_intf_addr,
                               "Gateway": args.east_intf_gateway_addr})
        # Create Devices using the Device Wizard
        device_gen_config = stc.perform("DeviceGenConfigExpand",
                                        params={"DeleteExisting": "No",
                                                "GenParams":
                                                east_device_gen_params})
        # Append to the device list
        device_list.append(device_gen_config['ReturnList'])

        # Create emulated genparam for west port
        west_device_gen_params = stc.create("EmulatedDeviceGenParams",
                                            under=project,
                                            attributes={"Port":
                                                        west_chassis_port})
        # Create the DeviceGenEthIIIfParams object
        stc.create("DeviceGenEthIIIfParams",
                   under=west_device_gen_params)
        # Configuring Ipv4 interfaces
        stc.create("DeviceGenIpv4IfParams",
                   under=west_device_gen_params,
                   attributes={"Addr": args.west_intf_addr,
                               "Gateway": args.west_intf_gateway_addr})
        # Create Devices using the Device Wizard
        device_gen_config = stc.perform("DeviceGenConfigExpand",
                                        params={"DeleteExisting": "No",
                                                "GenParams":
                                                west_device_gen_params})
        # Append to the device list
        device_list.append(device_gen_config['ReturnList'])
        if args.verbose:
            logger.debug(device_list)

        # Create the RFC 2544 'metric test
        if args.metric == "throughput":
            if args.verbose:
                logger.debug("Set up the RFC2544 throughput test...")
            stc.perform("Rfc2544SetupThroughputTestCommand",
                        params={"AcceptableFrameLoss":
                                args.acceptable_frame_loss_pct,
                                "Duration": args.trial_duration_sec,
                                "FrameSizeList": args.frame_size_list,
                                "LearningMode": args.learning_mode,
                                "NumOfTrials": args.num_trials,
                                "RateInitial": args.rate_initial_pct,
                                "RateLowerLimit": args.rate_lower_limit_pct,
                                "RateStep": args.rate_step_pct,
                                "RateUpperLimit": args.rate_upper_limit_pct,
                                "Resolution": args.resolution_pct,
                                "SearchMode": args.search_mode,
                                "TrafficPattern": args.traffic_pattern})
        elif args.metric == "backtoback":
            stc.perform("Rfc2544SetupBackToBackTestCommand",
                        params={"AcceptableFrameLoss":
                                args.acceptable_frame_loss_pct,
                                "Duration": args.trial_duration_sec,
                                "FrameSizeList": args.frame_size_list,
                                "LearningMode": args.learning_mode,
                                "LatencyType": args.latency_type,
                                "NumOfTrials": args.num_trials,
                                "RateInitial": args.rate_initial_pct,
                                "RateLowerLimit": args.rate_lower_limit_pct,
                                "RateStep": args.rate_step_pct,
                                "RateUpperLimit": args.rate_upper_limit_pct,
                                "Resolution": args.resolution_pct,
                                "SearchMode": args.search_mode,
                                "TrafficPattern": args.traffic_pattern})
        elif args.metric == "frameloss":
            stc.perform("Rfc2544SetupFrameLossTestCommand",
                        params={"AcceptableFrameLoss":
                                args.acceptable_frame_loss_pct,
                                "Duration": args.trial_duration_sec,
                                "FrameSizeList": args.frame_size_list,
                                "LearningMode": args.learning_mode,
                                "LatencyType": args.latency_type,
                                "NumOfTrials": args.num_trials,
                                "RateInitial": args.rate_initial_pct,
                                "RateLowerLimit": args.rate_lower_limit_pct,
                                "RateStep": args.rate_step_pct,
                                "RateUpperLimit": args.rate_upper_limit_pct,
                                "Resolution": args.resolution_pct,
                                "SearchMode": args.search_mode,
                                "TrafficPattern": args.traffic_pattern})
        elif args.metric == "latency":
            stc.perform("Rfc2544SetupLatencyTestCommand",
                        params={"AcceptableFrameLoss":
                                args.acceptable_frame_loss_pct,
                                "Duration": args.trial_duration_sec,
                                "FrameSizeList": args.frame_size_list,
                                "LearningMode": args.learning_mode,
                                "LatencyType": args.latency_type,
                                "NumOfTrials": args.num_trials,
                                "RateInitial": args.rate_initial_pct,
                                "RateLowerLimit": args.rate_lower_limit_pct,
                                "RateStep": args.rate_step_pct,
                                "RateUpperLimit": args.rate_upper_limit_pct,
                                "Resolution": args.resolution_pct,
                                "SearchMode": args.search_mode,
                                "TrafficPattern": args.traffic_pattern})

        # Save the configuration
        stc.perform("SaveToTcc", params={"Filename": "2544.tcc"})
        # Connect to the hardware...
        stc.perform("AttachPorts", params={"portList": stc.get(
            "system1.project", "children-port"), "autoConnect": "TRUE"})
        # Apply configuration.
        if args.verbose:
            logger.debug("Apply configuration...")
        stc.apply()

        if args.verbose:
            logger.debug("Starting the sequencer...")
        stc.perform("SequencerStart")

        # Wait for sequencer to finish
        logger.info(
            "Starting test... Please wait for the test to complete...")
        stc.wait_until_complete()
        logger.info("The test has completed... Saving results...")

        # Determine what the results database filename is...
        lab_server_resultsdb = stc.get(
            "system1.project.TestResultSetting", "CurrentResultFileName")

        if args.verbose:
            logger.debug("The lab server results database is %s",
                         lab_server_resultsdb)

        stc.perform("CSSynchronizeFiles",
                    params={"DefaultDownloadDir": args.results_dir})

        resultsdb = args.results_dir + \
            lab_server_resultsdb.split("/Results")[1]

        logger.info(
            "The local summary DB file has been saved to %s", resultsdb)

        # The returns the "RFC2544ThroughputTestResultDetailedSummaryView"
        # table view from the results database.
        # There are other views available.

        if args.metric == "throughput":
            resultsdict = (
                stc.perform("QueryResult",
                            params={
                                "DatabaseConnectionString":
                                resultsdb,
                                "ResultPath":
                                ("RFC2544ThroughputTestResultDetailed"
                                 "SummaryView")}))

        # The returns the "RFC2544BacktoBackTestResultDetailedSummaryView"
        # table view from the results database.
        # There are other views available.
        elif args.metric == "backtoback":
            resultsdict = (
                stc.perform("QueryResult",
                            params={
                                "DatabaseConnectionString":
                                resultsdb,
                                "ResultPath":
                                ("RFC2544Back2BackTestResultDetailed"
                                 "SummaryView")}))

        # The returns the "RFC2544LatencyTestResultDetailedSummaryView"
        # table view from the results database.
        # There are other views available.
        elif args.metric == "latency":
            resultsdict = (
                stc.perform("QueryResult",
                            params={
                                "DatabaseConnectionString":
                                resultsdb,
                                "ResultPath":
                                ("RFC2544LatencyTestResultDetailed"
                                 "SummaryView")}))

        # The returns the "RFC2544FrameLossTestResultDetailedSummaryView"
        # table view from the results database.
        # There are other views available.
        elif args.metric == "frameloss":
            resultsdict = (
                stc.perform("QueryResult",
                            params={
                                "DatabaseConnectionString":
                                resultsdb,
                                "ResultPath":
                                ("RFC2544FrameLossTestResultDetailed"
                                 "SummaryView")}))
        if args.verbose:
            logger.debug("resultsdict[\"Columns\"]: %s",
                         resultsdict["Columns"])
            logger.debug("resultsdict[\"Output\"]: %s", resultsdict["Output"])
            logger.debug("Result paths: %s",
                         stc.perform("GetTestResultSettingPaths"))

            # Write results to csv
            logger.debug("Writing CSV file to results directory %s",
                         args.results_dir)
        write_query_results_to_csv(
            args.results_dir, args.csv_results_file_prefix, resultsdict)

    except RuntimeError as e:
        logger.error(e)

    if args.verbose:
        logger.debug("Destroy session on lab server")
    stc.end_session()

    logger.info("Test complete!")

if __name__ == "__main__":
    main()


try:
    from setuptools import setup
    from setuptools import Extension
except:
    from distutils.core import setup
    from distutils.extension import Extension
import numpy
from sys import platform
import os
from findblas.distutils import build_ext_with_blas
from sys import platform

## https://stackoverflow.com/questions/724664/python-distutils-how-to-get-a-compiler-that-is-going-to-be-used
class build_ext_subclass( build_ext_with_blas ):
    def build_extensions(self):
        compiler = self.compiler.compiler_type
        if compiler == 'msvc': # visual studio is 'special'
            for e in self.extensions:
                e.extra_compile_args += ['/O2', '/openmp']
        else:
            for e in self.extensions:
                e.extra_compile_args += ['-O2', '-fopenmp', '-march=native', '-std=c99']
                e.extra_link_args += ['-fopenmp']
        build_ext_with_blas.build_extensions(self)

setup(
    name  = "poismf",
    packages = ["poismf"],
    author = 'David Cortes',
    author_email = 'david.cortes.rivera@gmail.com',
    url = 'https://github.com/david-cortes/poismf',
    version = '0.1.5',
    install_requires = ['numpy', 'pandas>=0.24', 'cython', 'findblas'],
    description = 'Fast and memory-efficient Poisson factorization for sparse count matrices',
    cmdclass = {'build_ext': build_ext_subclass},
    ext_modules = [Extension("poismf.poismf_c_wrapper", sources=["poismf/poismf_c_wrapper.pyx", "src/nonnegcg.c"],
        include_dirs=[numpy.get_include()], define_macros = [("_FOR_PYTHON", None)]
        )]
    )


import os
import inspect
import sys
currentdir = os.path.dirname(os.path.abspath(
    inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir)
from flask import request, jsonify, json, abort, g, url_for
from server.app.auth.auth import auths
from server.run import db
from server.app.models.time import Time
from flask.blueprints import Blueprint

time = Blueprint('time', __name__, template_folder='templates')

@time.route('/time/add_time', methods=['POST'])
# @auths.login_required()
def add_time():
    time = request.json.get('time')
    if not request.json:
        abort(400)
    if time is None:
        return jsonify(message=' The time field cannot be empty'), 400
    times = Time.query.filter_by(time=time)
    if times:
        return "This time entry already exists!"
    else:
        timee = Time(time=time)
        db.session.add(timee)
        db.session.commit()
        return jsonify(message="Successfully added {0} to the database".format(time)), 201

@time.route('/time/add_time', methods=['GET'])
# @auths.login_required()
def get_time():
    page_no = request.args.get('page_no', 1)
    limit = request.args.get('limit', 20)
    q_name = request.args.get('q', "")
    T = Time.query.filter_by(created_by=g.user.id). \
        filter(Time.title.ilike('%{}%'.format(q_name))).paginate(
        int(page_no), int(limit)
    )
    if not T:
        return jsonify(message='There is No time to display!!!!')
    else:
        timey = [
            {
                "id": time.id,
                "time": time.time
            }
            for time in T.items
        ]
        return jsonify({
            "time": timey,
            "next": url_for(request.endpoint, page_no=T.next_num, limit=limit,
                            _external=True) if T.has_next else None,
            "prev": url_for(request.endpoint, page_no=T.prev_num, limit=limit,
                            _external=True) if T.has_prev else None,
        }), 200

@time.route('/time/edit_time', methods=['PUT'])
# @auths.login_required()
def edit_time(id):
    """Update this bucket list"""
    if not request.json:
        abort(400)
    if not request.json['title']:
        abort(400)
    t = Time.query.filter_by(id=id).first()
    if not t or t.created_by != g.user.id:
        return jsonify(message='This time with id {} was not found!'.format(id)), 404
    else:
        t.time = request.json.get('time')
        db.session.commit()
        return jsonify({
            "id": t.id,
            "time": t.time
        }), 201

@time.route('/time/delete_time', methods=['DELETE'])
# @auths.login_required()
def delete_time():
    time = Time.query.filter_by(id=id).first()
    if not time or time.created_by != g.user.id:
        return jsonify(message='This Company with id {} was not found!'.format(id)), 404
    else:

        db.session.delete(Time.query.get(id))
        db.session.commit()
        return jsonify({'Delete': True}), 200


# -*- coding=utf-8 -*-
import subprocess
import textwrap

import pytest
import yaml

from zettarepl.utils.test import create_dataset, run_replication_test, transports

@pytest.mark.parametrize("transport", transports())
@pytest.mark.parametrize("properties", [False, True])
@pytest.mark.parametrize("encryption", [
    None,
    {
        "key": "password",
        "key-format": "passphrase",
        "key-location": "$TrueNAS",
    },
    "inherit",
])
@pytest.mark.parametrize("source_encrypted", [False, True])
def test_unencrypted_to_encrypted(transport, properties, encryption, source_encrypted):
    if properties and encryption and source_encrypted:
        # Re-encrypting already encrypted source dataset 'data/src' while preserving its properties is not supported
        return

    subprocess.call("zfs destroy -r data/src", shell=True)
    subprocess.call("zfs destroy -r data/dst", shell=True)

    create_dataset("data/src", encrypted=source_encrypted)
    subprocess.check_call("zfs snapshot -r data/src@2018-10-01_01-00", shell=True)

    create_dataset("data/dst", encrypted=True)

    definition = yaml.safe_load(textwrap.dedent("""\
        timezone: "UTC"

        replication-tasks:
          src:
            direction: push
            source-dataset: data/src
            target-dataset: data/dst/child/grandchild
            recursive: false
            also-include-naming-schema:
              - "%Y-%m-%d_%H-%M"
            auto: false
            retention-policy: none
            retries: 1
    """))
    definition["replication-tasks"]["src"]["transport"] = transport
    definition["replication-tasks"]["src"]["properties"] = properties
    definition["replication-tasks"]["src"]["encryption"] = encryption

    if (properties and source_encrypted) or encryption:
        run_replication_test(definition)

        if encryption == "inherit":
            encryptionroot = "data/dst"
        else:
            encryptionroot = "data/dst/child/grandchild"

        assert subprocess.check_output(
            "zfs get -H -p encryptionroot data/dst/child/grandchild",
            encoding="utf-8", shell=True
        ).split("\n")[0].split("\t")[2] == encryptionroot
    else:
        error = run_replication_test(definition, success=False)

        if properties:
            assert error.error == (
                "Destination dataset 'data/dst/child/grandchild' must be encrypted (as one of its ancestors is "
                "encrypted). Refusing to transfer unencrypted source dataset 'data/src'. Please, set up replication "
                "task encryption in order to replicate this dataset."
            )
        else:
            assert error.error == (
                "Destination dataset 'data/dst/child/grandchild' must be encrypted (as one of its ancestors is "
                "encrypted). Refusing to transfer source dataset 'data/src' without properties and without replication "
                "task encryption."
            )


from views.view import View

from linebot.models import (
    TextSendMessage,
)

class GolangView(View):
    @property
    def _keywords(self):
        return ['golang', 'go']

    def main(self, text: str) -> list:
        """
        說明自己 Go 的程度
        """
        return [
            TextSendMessage(
                "雖然語法上有部分和較常見的幾個語言很不一樣，但是好懂、好寫、效能又好的平行處理機制真的是很令人心動呢！"),
            TextSendMessage(
                "目前正在努力學習中，希望之後能夠邊導入 TDD 用它寫幾個小專案！"),
        ]


from .Library import *
import pickle, cgi, cgitb, codecs, sys, os, sqlite3
cgitb.enable()

def main(q, selfurl):
    print ("Content-type: text/html; charset=utf-8\n\n")
    db = sqlite3.connect('cgi-bin/st02/file.sqlite')
    lib = Library(q, selfurl, db)

    MENU = {
        'show_form' : lib.showForm,
        'add_guest' : lib.addGuest,
        'add_reg' : lib.addReg,
        'edit_reg' : lib.edit_student,
        'edit_guest' : lib.edit_student,
        'delete' : lib.delete,
        'clear' : lib.clear,
        'save_guest' : lib.save_student,
        'save_reg' : lib.save_student,
        'import' : lib.import_file}

    MENU[q.getvalue('act', 'show_form')]()

    db.commit()
    db.close()