import json

import query as query
from django.contrib import messages
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.shortcuts import render

# Create your views here.
from django.template.loader import render_to_string
from sqlalchemy.sql.functions import current_user

from home.forms import SearchForm
from home.models import Setting, ContactForm, ContactMessage, FAQ
from order.models import ShopCart
from product.models import Category, Product, Images, Comment, Variants

def index(request):
    setting=Setting.objects.get(pk=1)
    category=Category.objects.all()
    category_slide = Category.objects.all().order_by('-id')[:3]
    products_slider = Product.objects.all().order_by('-id')[:3]
    products_latest = Product.objects.all().order_by('-id')[:4]
    products_picked = Product.objects.all().order_by('?')[:4]
    page='home'

    context={'setting':setting,'page':page,'category':category,
             'products_slider':products_slider,
             'category_slide':category_slide,
             'products_latest': products_latest,
             'products_picked': products_picked,
             }
    return render(request,'index.html',context)

def about(request):
    category = Category.objects.all()
    setting=Setting.objects.get(pk=1)
    context={'setting':setting,'category': category}
    return render(request,'about.html',context)

def contactus(request):
    category = Category.objects.all()
    if request.method=='POST':
        form=ContactForm(request.POST)
        if form.is_valid():
            data = ContactMessage()  # create relation with model
            data.name = form.cleaned_data['name']  # get form input data
            data.email = form.cleaned_data['email']
            data.subject = form.cleaned_data['subject']
            data.message = form.cleaned_data['message']
            data.ip = request.META.get('REMOTE_ADDR')
            data.save()  # save data to table
            messages.success(request, "Tin của bạn đã được gửi.Cảm ơn về phản hồi của bạn.")
            return HttpResponseRedirect('/contact')
    setting = Setting.objects.get(pk=1)
    form=ContactForm
    context = {'setting': setting,'form':form,'category': category}
    return render(request, 'contactus.html', context)

def category_products(request,id,slug):
    category = Category.objects.all()
    products=Product.objects.filter(category_id=id)
    products_mo = Product.objects.all().order_by('-id')[:3]
    context = {'products': products, 'category': category,
                'products_mo':products_mo,
               }
    return render(request,'category_product.html',context)

def search(request):
    if request.method == 'POST': # check post
        form = SearchForm(request.POST)
        if form.is_valid():
            query = form.cleaned_data['query'] # get form input data
            catid = form.cleaned_data['catid']
            if catid==0:
                products=Product.objects.filter(title__icontains=query)  #SELECT * FROM product WHERE title LIKE '%query%'
            else:
                products = Product.objects.filter(title__icontains=query,category_id=catid)

            category = Category.objects.all()
            context = {'products': products, 'query':query,
                       'category': category }
            return render(request, 'search_products.html', context)

    return HttpResponseRedirect('/')

def search_auto(request):
    if request.is_ajax():
        q = request.GET.get('term', '')
        products = Product.objects.filter(title__icontains=q)

        results = []
        for rs in products:
            product_json = {}
            product_json = rs.title
            results.append(product_json)
        data = json.dumps(results)
    else:
        data = 'fail'
    mimetype = 'application/json'
    return HttpResponse(data, mimetype)

def product_detail(request,id,slug):
    query = request.GET.get('q')
    category = Category.objects.all()
    product=Product.objects.get(pk=id)
    products_picked = Product.objects.all().order_by('?')[:4]
    images=Images.objects.filter(product_id=id)
    comments=Comment.objects.filter(product_id=id,status="New")
    context = {'product': product, 'category': category,
                'products_picked':products_picked,
                'images':images,
                'comments':comments
               }
    if product.variant != "None":  # Product have variants
        if request.method == 'POST':  # if we select color
            variant_id = request.POST.get('variantid')
            variant = Variants.objects.get(id=variant_id)  # selected product by click color radio
            colors = Variants.objects.filter(product_id=id, size_id=variant.size_id)
            sizes = Variants.objects.raw('SELECT * FROM  product_variants  WHERE product_id=%s GROUP BY size_id', [id])
            query += variant.title + ' Size:' + str(variant.size) + ' Color:' + str(variant.color)
        else:
            variants = Variants.objects.filter(product_id=id)
            colors = Variants.objects.filter(product_id=id, size_id=variants[0].size_id)
            sizes = Variants.objects.raw('SELECT * FROM  product_variants  WHERE product_id=%s GROUP BY size_id', [id])
            variant = Variants.objects.get(id=variants[0].id)
        context.update({'sizes': sizes, 'colors': colors,
                        'variant': variant, 'query': query
                        })
    return render(request,'product_detail.html',context)

def ajaxcolor(request):
    data = {}
    if request.POST.get('action') == 'post':
        size_id = request.POST.get('size')
        productid = request.POST.get('productid')
        colors = Variants.objects.filter(product_id=productid, size_id=size_id)
        context = {
            'size_id': size_id,
            'productid': productid,
            'colors': colors,
        }
        data = {'rendered_table': render_to_string('color_list.html', context=context)}
        return JsonResponse(data)
    return JsonResponse(data)

def faq(request):
    category = Category.objects.all()
    faq = FAQ.objects.filter(status="True").order_by("ordernumber")

    context = {
        'faq': faq,
        'category': category,
    }
    return render(request, 'faq.html', context)


# solves the lid driven cavity flow problem in dimensionless variables
# of the incompressible navier stokes equations using a finite difference scheme
# in primitive variable form using a projection method for the pressure.

import matplotlib.pyplot as plt
import numpy as np

def solve_lid_driven_cavity_flow(N = 60, dt = 1e-3, tol = 1e-10, max_steps = 100, tspan = 3.0, Re = 100.0, U0 = 1.0, omega = 1.0):
    # Step -1: parameters
    # N + 1 are the number of grid points in each direction
    dx = dy = 1 / N
    p0 = 1.0
    steps = int(np.ceil(tspan / dt))

    # Step 0. allocate memory and setup initial conditions v = 0, p = 1
    u = np.zeros((N + 1, N + 1)) # x component of the velocity
    v = np.zeros((N + 1, N + 1)) # y component of the velocity
    p = np.ones((N + 1, N + 1))
    tmp_v = np.zeros((N + 1, N + 1))
    tmp_u = np.zeros((N + 1, N + 1))
    p_rhs = np.empty_like(p)
    d_tmp_u_dx = np.empty_like(u)
    d_tmp_v_dy = np.empty_like(v)
    new_p = np.empty_like(p)
    force_x = force_y = None

    # set initial conditions
    tmp_u[0,:] = u[0,:] = U0

    for step in range(steps):
        print("*** computing step {} out of {} steps ***".format(step, steps))
        # Step 1. compute new derivatives of the velocity
        # Step 1.1 first derivatives of u, v in x and y direction
        dudx = (u[1:-1, 2:] - u[1:-1, :-2]) / (2 * dx)
        dudy = (u[2:, 1:-1] - u[:-2, 1:-1]) / (2 * dy)
        dvdx = (v[1:-1, 2:] - v[1:-1, :-2]) / (2 * dx)
        dvdy = (v[2:, 1:-1] - v[:-2, 1:-1]) / (2 * dy)
        # Step 1.2 second derivatives of u, v in x and y direction
        d2udx2 = (u[1:-1, :-2] - 2 * u[1:-1, 1:-1] + u[1:-1, 2:]) / (dx**2)
        d2udy2 = (u[:-2, 1:-1] - 2 * u[1:-1, 1:-1] + u[2:, 1:-1]) / (dy**2)
        d2vdx2 = (v[1:-1, :-2] - 2 * v[1:-1, 1:-1] + v[1:-1, 2:]) / (dx**2)
        d2vdy2 = (v[:-2, 1:-1] - 2 * v[1:-1, 1:-1] + v[2:, 1:-1]) / (dy**2)
        # laplace of u and v
        laplace_u = d2udx2 + d2udy2
        laplace_v = d2vdx2 + d2vdy2

        # Step 2. compute new VIS and NL terms and the resulting force
        # (v dot nabla) v = (v_x * d_x + v_y * d_y) v = [v_x * d_x v_x + v_y * d_y v_x, v_x * d_x v_y + v_y * d_y v_y]
        new_NL_x = u[1:-1,1:-1] * dudx + v[1:-1,1:-1] * dudy
        new_NL_y = u[1:-1,1:-1] * dvdx + v[1:-1,1:-1] * dvdy
        new_VIS_x = 1 / Re * laplace_u
        new_VIS_y = 1 / Re * laplace_v
        new_force_x = - new_NL_x + new_VIS_x
        new_force_y = - new_NL_y + new_VIS_y

        # Step 3. compute temporal velocity field using the Adams Bashforth method of second order
        #         / euler for the first step
        if step == 0:
            # euler
            tmp_u[1:-1, 1:-1] = u[1:-1, 1:-1] + dt * new_force_x
            tmp_v[1:-1,1:-1] = v[1:-1,1:-1] + dt * new_force_y
        else:
            # adams bashforth 2. order
            tmp_u[1:-1, 1:-1] = u[1:-1, 1:-1] + dt * 0.5 * (3 * new_force_x - force_x)
            tmp_v[1:-1, 1:-1] = v[1:-1, 1:-1] + dt * 0.5 * (3 * new_force_y - force_y)

        # store new force as the new old one for the adams bashforth step
        force_x = new_force_x
        force_y = new_force_y

        # Step 4. compute the pressure with a poisson equation using an iterative method linear solver
        #         and finite differences
        # Step 4.1 compute divergence of [u, v] divided by dt
        d_tmp_v_dy[0, :] = 1 / dx * (-3/2*tmp_v[0, :] + 2*tmp_v[1, :] - 1/2*tmp_v[2, :])
        d_tmp_v_dy[-1, :] = - 1 / dx * (-3/2*tmp_v[N, :] + 2*tmp_v[N - 1, :] - 1/2*tmp_v[N - 2, :])
        d_tmp_v_dy[1:-1, :] = (tmp_v[2:, :] - tmp_v[:-2, :]) / (2*dy)

        d_tmp_u_dx[:, 0] =  1 / dx * (-3/2*tmp_u[:, 0] + 2*tmp_u[:, 1] - 1/2*tmp_u[:, 2])
        d_tmp_u_dx[:, -1] = - 1 / dx * (-3/2*tmp_u[:, N] + 2*tmp_u[:, N - 1] - 1/2*tmp_u[:, N - 2])
        d_tmp_u_dx[:, 1:-1] = (tmp_u[:, 2:] - tmp_u[:, :-2]) / (2*dx)

        p_rhs = (d_tmp_u_dx + d_tmp_v_dy) / dt

        # Step 4.2 gauss seidel iteration to solve for the next
        gauss_step = 1
        while True:
            # sleep(0.01)
            mse = 0.0 # use mean squared error as a convergence criteria
            # laplace p = rhs
            # d_x^2 p + d_y^2 p = rhs
            # update guess and compute mse
            # (2*p[i,j] - 5*p[i,j+1] + 4*p[i,j+2] - p[i,j+3])/dx^2
            # (2*p[i,j] - 5*p[i,j-1] + 4*p[i,j-2] - p[i,j-3])/dx^2
            # (2*p[i,j] - 5*p[i+1,j] + 4*p[i+2,j] - p[i+3,j])/dx^2
            # (2*p[i,j] - 5*p[i-1,j] + 4*p[i-2,j] - p[i-3,j])/dx^2
            # (p[i,j-1] - 2*p[i,j] + p[i,j+1])/dx^2
            # (p[i-1,j] - 2*p[i,j] + p[i+1,j])/dx^2
            # we use jacobi there bc. its easier to implement
            new_p[0,:] = new_p[-1,:] = new_p[:,0] = new_p[:,-1] = p0
            new_p[1:-1, 1:-1] = (p[1:-1, :-2] + p[1:-1, 2:] + p[:-2, 1:-1] + p[2:, 1:-1]) / 4 - dx**2*p_rhs[1:-1, 1:-1]/4
            mse = np.sum((p - new_p)**2) / (N - 1)**2
            p = (1 - omega) * p + omega * new_p

            if mse < tol:
                break
            if np.isnan(mse) or np.isinf(mse):
                print(p)
                raise ValueError("jacobi iteration diverged")
            if gauss_step > max_steps:
                raise ValueError("jacobi iteration took too long")

            gauss_step += 1

        # Step 5. compute the real velocity using the gradient of the pressure and set boundary conditions
        # Step 5.1 compute the pressure gradient
        grad_p_x = (p[1:-1, 2:] - p[1:-1, :-2]) / (2*dx)
        grad_p_y = (p[2:, 1:-1] - p[:-2, 1:-1]) / (2*dy)
        # Step 5.2 advance u and v using forward euler
        u[1:-1, 1:-1] = tmp_u[1:-1, 1:-1] + dt * (- grad_p_x)
        v[1:-1, 1:-1] = tmp_v[1:-1, 1:-1] + dt * (- grad_p_y)

        # Step 6. repeat until tspan is reached
    return u, v

def main():
    N = 60
    Re = 100.0
    U0 = 1
    x = y = np.linspace(0,1,N+1)
    u, v = solve_lid_driven_cavity_flow(N=N, Re=Re, U0=U0)
    # Step 7. visualize the result
    plt.contourf(x,y, np.sqrt(u**2 + v**2), 20)
    plt.colorbar()
    plt.streamplot(x,y,u,v)
    plt.xlabel("x")
    plt.ylabel("y")
    plt.title("Lid Driven Cavity Flow, Re = 100, U0 = 1")
    plt.savefig("lid_driven_cavity_flow.pdf")

main()


class Solution:
    def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]:
        n = len(nums)
        nums.sort()
        for i in range(1, n):
            nums[i] += nums[i - 1]

        ans = []
        for x in queries:
            id = bisect.bisect_right(nums, x)
            ans.append(id)

        return ans


def factorial(n):       #ugotovimo, da je število lahko največ 7 mestno (7 * 9! je 7 mestno število, a ker je tudi 8*9! 7 mestno se ne bo izšlo)
    if n == 0:
        return 1
    rezultat = 1
    while n >= 1:
        rezultat = rezultat*n
        n -= 1
    return rezultat

seznam = []

for i in range(3, 3300000):
    zacasno = i
    vsota = 0
    while i != 0:
        vsota += factorial(i%10)
        i = i//10
    if vsota == zacasno:
        seznam += [vsota]

print(sum(seznam))


from django.contrib import admin
from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('',views.login,name='login'),
    path('logout/', views.logout, name='logout'),
    path('forgot/',views.forgot,name='forgot'),
    path('profile/',views.profile,name="profile"),
    path('reg/',views.register,name='register'),
    path('home/',views.homepage,name='home'),
    path('home/rest_detail/<int:image_id>/',views.rest,name='rest'),
     path('home/grocery_details/<int:image_id>/',views.grocery,name='grocery'),
     path('tour/<int:id>/',views.tour,name='tour'),
    path('home/medical/<int:id>/',views.medical,name='medical'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


# This Python file uses the following encoding: utf-8
import sys
from PySide6 import QtCore
from PySide6.QtWidgets import QApplication, QWidget

# Important:
# You need to run the following command to generate the ui_form.py file
#     pyside6-uic form.ui -o ui_form.py, or
#     pyside2-uic form.ui -o ui_form.py
from ui_Auth import Ui_Form  #SmallWidgetLamp, SettingsForm, LetterList, LetterSearch, Auth

class EmailApp(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)

# вызывается при нажатии кнопки мыши
    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            self.old_pos = event.pos()

    # вызывается при отпускании кнопки мыши
    def mouseReleaseEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            self.old_pos = None

    # вызывается всякий раз, когда мышь перемещается
    def mouseMoveEvent(self, event):
        if not self.old_pos:
            return
        delta = event.pos() - self.old_pos
        self.move(self.pos() + delta)

def move2RightBottomCorner(win):    #Move to right bottom
    screen_geometry = QApplication.screens()[0].size()
    screen_size = (screen_geometry.width(), screen_geometry.height())
    win_size = (win.frameSize().width(), win.frameSize().height())
    x = screen_size[0] - (win_size[0]+40)
    y = screen_size[1] - (win_size[1]+40)
    win.move(x, y)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    widget = EmailApp()
    widget.move(widget.width() * -3, 0) # чтобы не мелькало
    widget.show()
    move2RightBottomCorner(widget)
    sys.exit(app.exec())


"""
Builds and trains a neural network that uses policy gradients to learn to play Tic-Tac-Toe.

The input to the network is a vector with a number for each space on the board. If the space has one of the networks
pieces then the input vector has the value 1. -1 for the opponents space and 0 for no piece.

The output of the network is a also of the size of the board with each number learning the probability that a move in
that space is the best move.

The network plays successive games randomly alternating between going first and second against an opponent that makes
moves by randomly selecting a free space. The neural network does NOT initially have any way of knowing what is or is not
a valid move, so initially it must learn the rules of the game.

I have trained this version with success at 3x3 tic tac toe until it has a success rate in the region of 75% this maybe
as good as it can do, because 3x3 tic-tac-toe is a theoretical draw, so the random opponent will often get lucky and
force a draw.
"""
import collections
import os
import random

import numpy as np
import tensorflow as tf

from games.tic_tac_toe import TicTacToeGameSpec
from network_helpers import create_network, load_network, get_stochastic_network_move, save_network

HIDDEN_NODES = (100, 80, 60, 40)
BATCH_SIZE = 100  # every how many games to do a parameter update?
LEARN_RATE = 1e-4
PRINT_RESULTS_EVERY_X = 1000  # every how many games to print the results
NETWORK_FILE_PATH = 'current_network.p'  # path to save the network to
NUMBER_OF_GAMES_TO_RUN = 100000

# to play a different game change this to another spec, e.g TicTacToeXGameSpec or ConnectXGameSpec
game_spec = TicTacToeGameSpec()

reward_placeholder = tf.placeholder("float", shape=(None,))
actual_move_placeholder = tf.placeholder("float", shape=(None, game_spec.outputs()))

input_layer, output_layer, variables = create_network(game_spec.board_squares(), HIDDEN_NODES,
                                                      output_nodes=game_spec.outputs())

policy_gradient = tf.reduce_sum(tf.reshape(reward_placeholder, (-1, 1)) * actual_move_placeholder * output_layer)
train_step = tf.train.RMSPropOptimizer(LEARN_RATE).minimize(-policy_gradient)

with tf.Session() as session:
    session.run(tf.initialize_all_variables())

    if os.path.isfile(NETWORK_FILE_PATH):
        print("loading pre-existing network")
        load_network(session, variables, NETWORK_FILE_PATH)

    mini_batch_board_states, mini_batch_moves, mini_batch_rewards = [], [], []
    results = collections.deque(maxlen=PRINT_RESULTS_EVERY_X)

    def make_training_move(board_state, side):
        mini_batch_board_states.append(np.ravel(board_state) * side)
        move = get_stochastic_network_move(session, input_layer, output_layer, board_state, side)
        mini_batch_moves.append(move)
        return game_spec.flat_move_to_tuple(move.argmax())

    for episode_number in range(1, NUMBER_OF_GAMES_TO_RUN):
        # randomize if going first or second
        if bool(random.getrandbits(1)):
            reward = game_spec.play_game(make_training_move, game_spec.get_random_player_func())
        else:
            reward = -game_spec.play_game(game_spec.get_random_player_func(), make_training_move)

        results.append(reward)

        last_game_length = len(mini_batch_board_states) - len(mini_batch_rewards)

        # we scale here so winning quickly is better winning slowly and loosing slowly better than loosing quick
        reward /= float(last_game_length)

        mini_batch_rewards += ([reward] * last_game_length)

        if episode_number % BATCH_SIZE == 0:
            normalized_rewards = mini_batch_rewards - np.mean(mini_batch_rewards)
            normalized_rewards /= np.std(normalized_rewards)

            session.run(train_step, feed_dict={input_layer: mini_batch_board_states,
                                               reward_placeholder: normalized_rewards,
                                               actual_move_placeholder: mini_batch_moves})

            # clear batches
            del mini_batch_board_states[:]
            del mini_batch_moves[:]
            del mini_batch_rewards[:]

        if episode_number % PRINT_RESULTS_EVERY_X == 0:
            print("episode: %s win_rate: %s" % (episode_number, 0.5 + sum(results) / (PRINT_RESULTS_EVERY_X * 2.)))
            save_network(session, variables, NETWORK_FILE_PATH)

    save_network(session, variables, NETWORK_FILE_PATH)


s = input().strip()

result = []
temp = []
cnt = 1
for i in range(len(s)):
    # 앞부분 비교할 인자 없는 경우
    if not len(temp):
        temp.append(s[i])
    # 앞부분과 문자가 같은 경우
    elif s[i] == temp[-1]:
        cnt += 1
        temp.append(s[i])
    # 앞부분과 문자가 다른 경우
    else:
        if cnt >= 2:
            for j in range(cnt):
                temp.pop()
            result.append("".join(temp))
            temp = []
            cnt = 1
        temp.append(s[i])
# 마지막 남은부분 처리
if cnt >= 2:
    for j in range(cnt):
        temp.pop()
    result.append("".join(temp))
    temp = []
result.append("".join(temp))

print(result)

연속된 구간으로 분할.py


#!/usr/bin/env python3

import sys
import yaml
import logging
import requests
import os

from datetime import datetime
from argparse import ArgumentParser

from bot import Bot
from config import Config
from storage import Storage

def parse_args(argv=None):
    parser = ArgumentParser(description='Run game bot.')
    parser.add_argument('--config', '-c',
                        default='bot.yaml',
                        help='Configuration file.')
    parser.add_argument('--write-default',
                        default=False,
                        action='store_true',
                        help='Write default cofig file.')
    parser.add_argument('--log-level',
                        default=None,
                        help='Specify log level.')
    return parser.parse_args(argv)

def run(argv=None):
    args = parse_args(argv)

    if args.write_default:
        with open(args.config, 'w') as f:
            f.write(Config().save())
        return

    with open(args.config) as f:
        config = Config.load(f.read())

    if args.log_level:
        config.log_level = log_level

    logging.basicConfig(level=config.log_level)

    try:
        with open(config.storage_file) as f:
            storage = Storage.load(f.read())
    except IOError:
        storage = Storage()

    try:
        Bot(config.telegram_token, storage).run()
    except:
        with open(config.storage_file, 'w') as f:
            f.write(storage.save())
        raise

if __name__ == '__main__':
    sys.exit(run())


import random
import numpy
brojevi = [0,0,0,0,0,0,0]

def izaberi7(lotobrojevi):

    lotobrojevi = [0,0,0,0,0,0,0]
    lotobrojevi[0] = random.randrange(1,40,1)
    j = 0
    #print (lotobrojevi)
    while j < 6:
        k = 0
        j += 1
        #lotobrojevi[i] = 1+random.randint(0,38)
        lotobrojevi[j] = random.randrange(1,40,1)
        while lotobrojevi[k] == lotobrojevi[j]:
        #for k in range(0,j-1):
            #if lotobrojevi[k] == lotobrojevi[j]:
            lotobrojevi[k] = random.randrange(1,40,1)
        k +=1
    return lotobrojevi

s = sorted(izaberi7(brojevi))
print (s)


#  -*- coding: utf-8 -*-
import csv
import re

class Formatter:
    def __init__(self, url):
        self.url = url

    def format(self, task, total):
        output = '
Work

';
        for task in sorted(tasks):
            output += self._row(self._link(task), tasks[task])
        output += self._row('Total', total)
        return output

    def _link(self, task):
        return '' + task + ''

    def _row(self, task, time):
        return '
' + task + '	' + time + '
'

class Calculator:
    def calculate(self, tasks):
        for task in tasks:
            tasks[task] = self._calculate(tasks[task])
        total = self._calculate(tasks.values())
        return {'tasks': tasks, 'total': total}

    def _calculate(self, times):
        seconds = 0
        for time in times:
            parts = [int(s) for s in time.split(':')]
            seconds += (parts[0] * 60 + parts[1]) * 60
        total, seconds = divmod(seconds, 60)
        hour, minute = divmod(total, 60)
        return "%d:%02d" % (hour, minute)

class TaskNameFormatter:
    def format(self, task):
        matches = re.search(r'^dev\-[0-9]+', task)
        if matches is not None:
            return matches.group(0)
        else:
            return 'Other'

class Reader:
    def __init__(self, namer, taskRowNumber, timeRowNumber):
        self.namer = namer
        self.taskRowNumber = taskRowNumber
        self.timeRowNumber = timeRowNumber

    def read(self, filepath):
        tasks = {'Other': []}
        with open(filepath, 'r', encoding='utf-8', errors='replace') as file:
            reader = csv.reader(file, delimiter=';')
            for row in reader:
                task = self.namer.format(row[self.taskRowNumber])
                time = row[self.timeRowNumber]
                if task not in tasks:
                    tasks[task] = [time]
                else:
                    tasks[task] = tasks[task] + [time]
        return tasks

class Writer:
    def write(self, filepath, output):
        file = open(filepath, 'w')
        file.write(output)
        file.close()

namer = TaskNameFormatter()
reader = Reader(namer, 5, 4)
calculator = Calculator()
writer = Writer()

tasks = reader.read('work.csv')
result = calculator.calculate(tasks)
formatter = Formatter('https://youtrack.dev.comet.estate/issue/')
output = formatter.format(result['tasks'], result['total'])
writer.write('work.html', output)

print('Totally: %s tasks calculated with total time: %s' % (str(len(result['tasks'])), str(result['total'])))


# Ausgewählte Probleme aus dem ACM Programming Contest  WS 2021/22

# * Problem: Planting Trees

# * Link: https://open.kattis.com/contests/nytf6n/problems/plantingtrees;

# * @author: Feng Yi Lu

# * @version 1.0, 2021-12-20 15:23:33

# * Method : Ad-Hoc

# # Status : Accepted

# # Runtime: 0.08*/

# "a" array that saves the days that a seed needs to grow
a = []
counter = 0
days = 1
#first input is not needed in my solution
leer = input()

#filling the array
a = [int(t) for t in input().split()]

#list is sorted reversed (or sorted in Descending order)
a.sort(reverse= True)

#earliest day when the party can be organized when all trees are grown = adding up the days that the seed need and the days that he are spending to plant them
for index, seed in enumerate(a):
    seed += days
    seed += 1
    a[index] = seed
    days+=1
#check the highest number inside of "a" this is the earliest time when the party can start after max(a) days
output = max(a)
print(output)


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import sys

import copy

import numpy as np
import scipy as scp

import logging

logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',
                    level=logging.INFO,
                    stream=sys.stdout)

from collections import OrderedDict

from pyvision import pretty_printer as pp
import matplotlib.pyplot as plt

class PoseMetric(object):
    """docstring for DistMetric"""
    def __init__(self, threshholds=[6, 12, 24], keep_raw=False):
        super(PoseMetric, self).__init__()

        self.distances = []
        self.rotation_dists = []
        self.thres = threshholds
        self.keep_raw = keep_raw

        self.pos = [0 for i in self.thres]
        self.neg = [0 for i in self.thres]

        self.count = 0

        self.sorted = False

    def add(self, prediction, translation, rotation):
        self.count += 1

        dist = np.linalg.norm(prediction[:3] - translation)

        self.distances.append(dist)

        for i, thres in enumerate(self.thres):
            self.pos[i] += np.sum(dist < thres)
            self.neg[i] += np.sum(dist >= thres)
            assert self.count == self.pos[i] + self.neg[i]

        rot_dist = np.linalg.norm(prediction[3:] - rotation)

        self.rotation_dists.append(rot_dist)

    def get_pp_names(self, time_unit='s', summary=False):

        pp_names1 = ["Translation Dist", "Rotation Dist", 'class_seperator']

        pp_names2 = ["T Acc @{}".format(i) for i in self.thres]

        pp_names = pp_names1 + pp_names2

        return pp_names

    def get_pp_values(self, ignore_first=True,
                      time_unit='s', summary=False):

        pp_values1 = [np.mean(self.distances) / 100,
                      np.mean(self.rotation_dists) / 100,
                      pp.NEW_TABLE_LINE_MARKER]

        pp_values2 = [self.pos[i] / self.count for i in range(len(self.thres))]

        return pp_values1 + pp_values2

    def get_pp_dict(self, ignore_first=True, time_unit='s', summary=False):

        names = self.get_pp_names(time_unit=time_unit, summary=summary)
        values = self.get_pp_values(ignore_first=ignore_first,
                                    time_unit=time_unit,
                                    summary=summary)

        return OrderedDict(zip(names, values))

    def plot_histogram(self):

        assert self.keep_raw

        x = np.linspace(0, 100, len(self.distances))
        plt.plot(x, self.distances)

        plt.show()

if __name__ == '__main__':
    logging.info("Hello World.")


""" Cells output each direction and input each neighbor
    (6 in, 6 out)
"""
from src.modules import Module, BaseModuleGene
from src.modules.signals import BaseSignalGene, BaseSignalSimulation

class Signal3Gene(BaseSignalGene):

    def __init__(self, ID):
        inputs = [ 'signal%i_in%i'%(ID,i) for i in range(6) ]
        outputs = [ ('signal%i_out%i'%(ID, i), 'sigmoid') for i in range(6)]
        super(Signal3Gene, self).__init__(ID, inputs=inputs, outputs=outputs)

class Signal3Simulation(BaseSignalSimulation):

    def create_input(self, cell):
        inputs = []
        neighbors = list(self.simulation.hmap.neighbors(cell.userData['coords']))

        for gene in self.module.genes.values():
            key = gene.key()

            for i, neighbor in enumerate(neighbors):
                if neighbor and key in neighbor.userData:
                    inputs.append(neighbor.userData[key][i])
                else:
                    inputs.append(0)

        assert(len(inputs) == len(self.module.total_inputs()))
        return inputs

class Signal3Module(Module):

    def __init__(self, **kwargs):
        super(Signal3Module, self).__init__(gene=Signal3Gene,
                                            simulation=Signal3Simulation,
                                            **kwargs)


# -*- coding: utf-8 -*-
"""
Created on Mon Jun  4 21:57:21 2018

@author: evan9
"""

import string

count = {}
with open(r'c:\PyCodes\File\word_count.txt') as file:
    text = file.read()
    text = text.translate(text.maketrans('','',string.punctuation))
    text = text.lower()

    for char in text:
        if char not in string.ascii_lowercase: continue
        count[char] = count.get(char, 0) + 1

byalpha = sorted(count.items())
print('Alphabetical order')
for key,value in byalpha:
    print(key,value)

print('')
print('Most Frequent')
bycount = sorted([(value,key) for key,value in count.items()], reverse=True)
for value,key in bycount:
    print(key,value)

'''
String Methods
ascii_letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
digits = '0123456789'
hexdigits = '0123456789abcdefABCDEF'
octdigits = '01234567'
printable = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
punctuation = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
whitespace = ' \t\n\r\x0b\x0c'
'''


# COP 3410- Assignment 1
# Sarah Sindeband
# Pg. 51, choose 8 exercises, python functions
# function calls can accumulate inside a main function
# main functtion will be used for just the purpose of running the functions
# 1/28/22

# pg.73

# function definitions

# Exercise 1.1
def is_multiple(n, m):
    leftover = m % n
    if leftover == 0:
        print(n, "is a multiple of", m)
        return True
    else:
        print(n, "is not a multiple of", m)
        return False

# Exercise 1.2
def is_even(k):
    if k % 2 == 0:
        print(k, "is an even number")
        return True
    else:
        print(k, "is not an even number")
        return False

# Exercise 1.3
def minmax():
    data = input("Enter some data: ")
    min = max = data[0]
    for j in data:
        if j > max:
            max = j
        elif j < min:
            min = j
    print("The minimum is", min, "and the maximum is", max)
    return min, max
# Exercide 1.4
def fun(num):
    sum_squares = 0
    count = num
    while (num > 0) and (count > 0):
        squares = (count - 1)**2
        sum_squares += squares
        count -=1
    print("The sum of squares for the numbers less than", num, "is", sum_squares)
    return sum_squares

# Exercise 1.5
def built_in_fun(built):
    print(sum([i**2 for i in range(built)]))

# Exercide 1.6
def odds_only(num2):
    sum_squares2 = 0
    if num2 % 2 == 0:
        num2 +=1
    count2 = num2
    built2 = num2 - 2
    while (num2 > 1):
        squares2 = (num2 - 2)**2
        sum_squares2 += squares2
        num2 -=2
    print("The sum of squares of the odd numbers less than", built2, "is", sum_squares2)
    return sum_squares2

# Exercise 1.7
def built_in_fun2(built2):
    print(sum([i**2 for i in range(1, built2, 2)]))

# Exercise 1.11
def list_fun():
    new_list = [2**k for k in range(0,9)]
    print("\n", new_list)

# define main function
def main():
    # Exercise 1.1
    print("\nReinforcement Exercise 1.1")
    n = int(input("Please enter an integer: "))
    m = int(input("Please enter another integer: "))
    is_multiple(n, m)
    # Exercise 1.2
    print("\nReinforcement Exercise 1.2")
    k = int(input("Please enter an integer: "))
    is_even(k)
    # Exercise 1.3
    print("\nReinforcement Exercise 1.3")
    minmax()
    # Exercide 1.4
    print("\nReinforcement Exercise 1.4")
    num = int(input("Enter a number: "))
    built = num
    fun(num)
    # Exercise 1.5
    print("\nReinforcement Exercise 1.5")
    built_in_fun(built)
    # Exercise 1.6
    print("\nReinforcement Exercise 1.6")
    num2 = int(input("Enter another number: "))
    built2 = num2
    odds_only(num2)
    # Exercise 1.7
    print("\nReinforcement Exercise 1.7")
    built_in_fun2(built2)
    # Exercise 1.11
    list_fun()

# call the main function
main()

Data Structures and Algorithms/SarahSindeband_Assign1.py


#
# File: AWESEM_Testbench_Main.py
# ------------------------------
# Authors: Brion Ye, Erick Blankenberg
# Date: 9/28/2018
#
# Description:
#   This class starts the application and ties
#   everything together. This also sets up and contains
#   functions that handle GUI requests. See the docs folder
#   for an overview of the system.
#
#   General:
#      PyQt tutorial:       http://pythonforengineers.com/your-first-gui-app-with-python-and-pyqt/
#      Redirecting prints:  https://stackoverflow.com/questions/44432276/print-out-python-console-output-to-qtextedit
#      Multithreading pref:
#   Image processing:
#      Simple Itk:          http://www.simpleitk.org
#      Simple elastix:      https://simpleelastix.github.io
#
#   Notes:
#       - Attempted to use mpipe but worked inconsistently on my windows laptop
#
#   Moving Forward:
#       - Apparently one thread is faster than two for data acquisition and handling, we
#         should look into multiprocessing, even the raspberry pi has more than one core.
#       - Work on and integrate analysis module. Use simpleitk
#       - Find a framework to make preformance timing easier
#
#   TODO:
#       - Only 5 of the 6 default settings for driving waveform trigger a callback when setting defaults, should check everything else as well
#       - Seems like the scrolling message box does not update until a user interacts with it,
#         the whole thing might be a waste of time anyway. I was trying to make seeing errors easier
#         for non-developer users.
#       - Seems like there might be rollover or some sort of timing issue for the latter half of the rising part
#         of some waveforms. They temporarily become very choppy.

doChangeCPU = False # Set to true to set CPU affinity manually

import scipy
import ast
import psutil
import os
import glob
import sys
import numpy
import datetime
from   scipy                         import signal
from   matplotlib                    import cm
from   matplotlib                    import pyplot as plt
from   matplotlib.backends.backend_agg import FigureCanvasAgg
from   qimage2ndarray                import byte_view
from   qimage2ndarray                import array2qimage
from   PyQt5.QtCore                  import *
from   PyQt5.QtGui                   import *
from   PyQt5.QtWidgets               import *
from   PyQt5                         import uic
from   AWESEM_PiPion_Interface       import AWESEM_PiPion_Interface
import AWESEM_Constants              as Const
import AWESEM_Register               as Register
import AWESEM_Analysis               as Analysis

if hasattr(Qt, 'AA_EnableHighDpiScaling'):
    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
if hasattr(Qt, 'AA_UseHighDpiPixmaps'):
    QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps, True)

Ui_MainWindow, QtBaseClass = uic.loadUiType("TestBench.ui")

# Used for redirecting console output
class Stream(QObject):
    newText    = pyqtSignal(str)
    __allowAll   = True
    __allowedSet = set()

    def allowAll(self, doAllow):
        self.__allowAll = doAllow

    def includePrefix(self, token, doInclude):
        if(doInclude):
            if(token not in self.__allowedSet):
                self.__allowedSet.add(token)
                return True
            return False
        else:
            if(token in self.__allowedSet):
                self.__allowedSet.remove(token)
                return True
            return False

    def write(self, text):
        if not self.__allowAll:
            for token in self.__allowedSet:
                if(text.startswith(token)):
                    self.newText.emit(str(text))
                    return
        else:
            self.newText.emit(str(text))

# The main program
class TestBench(QMainWindow):

    # Internal components
    __MCUInterface      = None
    __registerTh        = None
    __consoleOut        = None
    __ScanImage         = QImage(Const.PATH_BACKGROUNDIMAGE).scaled(Const.RES_W, Const.RES_H)
    __ColorMap          = cm.get_cmap('viridis')
    __UiElems           = None
    __WaveTables        = None # Dictionary of {"Name": tableArray}
    __SystemModels      = None # Dictionary of {"Name": signalContinousLTIModel}

    # Trackers for GUI elements, used so that the menu will bounce back to previous menu item after selecting option to load custom data
    __currentXWaveformOpt  = None
    __currentYWaveformOpt  = None

    __currentLUTModeOpt    = None
    # Tracker for current scale so that files can have these when exported, set to None to disable axis
    __currentXLength        = None # (microns)
    __currentYLength        = None # (microns)

    def __init__(self, *args, **kwargs):
        super(TestBench, self).__init__(*args, **kwargs)
        # Structure is MCU -(interface)-> dataTh -(double buffer)-> registerTh -(callback)-> monitor
        self.__UiElems = Ui_MainWindow()
        self.__UiElems.setupUi(self)
        self.__MCUInterface = AWESEM_PiPion_Interface()
        self.__registerTh   = Register.Register(self.updateQTImage, self.__MCUInterface)
        self.setUiProperties()
        self.loadDefaultWaveTables()
        self.loadDefaultModels()
        self.setDefaults()
        self.linkUiCallbacks()
        self.__registerTh.start()

        self.updateWaveforms()

    def __del__(self):
        self.shutdownResources()

    def shutdownResources(self):
        print("Closing Resources")
        self.__MCUInterface.close()

        self.__registerTh.close()
        print("Resources Closed")
        sys.stdout = sys.__stdout__ # Sets print mode back to normal

    def loadModel(self, filePath):
        _, systemFullName = os.path.split(filePath) # Returns path and file name
        systemName, _ = os.path.splitext(systemFullName) # Returns extension and name
        if self.__UiElems.Sampling_LUT_Combobox.findText(systemName) == -1:
            try:
                with open(filePath,'r') as inf:
                    systemParameters = ast.literal_eval(inf.read())
                self.__SystemModels[systemName] = signal.ZerosPolesGain(systemParameters['Zeros'], systemParameters['Poles'], systemParameters['Gain'])
                self.__UiElems.Sampling_LUT_Combobox.blockSignals(True)
                self.__UiElems.Sampling_LUT_Combobox.insertItem(0, systemName)
                self.__UiElems.Sampling_LUT_Combobox.blockSignals(False)
            except Exception as e:
                print("Error: Failed to load model \"%s\" with error \"%s\"" % (filePath, e))
        else:
            print("Error: Stopped attempted load of redundant model, existing model at: %s" % (self.__UiElems.Sampling_LUT_Combobox.findText(waveName)))

    def loadDefaultModels(self):
        # Adds default options
        self.__UiElems.Sampling_LUT_Combobox.blockSignals(True)
        self.__UiElems.Sampling_LUT_Combobox.insertItem(0, "Import Model")
        self.__UiElems.Sampling_LUT_Combobox.insertItem(0, "Linear")
        self.__UiElems.Sampling_LUT_Combobox.insertItem(0, "Axis Waveform")
        self.__UiElems.Sampling_LUT_Combobox.blockSignals(False)
        # Loads in files
        self.__SystemModels = dict()
        availableModels = glob.glob(os.path.join(os.path.abspath(''), "SysModels", "*.txt"))
        for filePath in availableModels:
            self.loadModel(filePath)
        self.__UiElems.Sampling_LUT_Combobox.setCurrentIndex(0)

    # Loads wave table at the given directory into available waveform dictionary
    def loadWaveform(self, filePath):
        _, waveFullName = os.path.split(filePath) # Returns path and file name
        waveName, _ = os.path.splitext(waveFullName) # Returns extension and name
        if self.__UiElems.Vertical_Waveform_Combobox.findText(waveName) == -1:
            try:
                dataVals = numpy.genfromtxt(filePath)
                if(dataVals.shape[0] != 256):
                    print("Error: Failed to load waveform \"%s\", length of %s not 256" % (filePath, dataVals.shape[0]))
                elif(numpy.any(numpy.logical_or(dataVals > 32767, dataVals < -32767))):
                    print("Error: Failed to load waveform \"%s\", some values larger than 16 bit limit" % (filePath))
                else:
                    self.__WaveTables[waveName] = dataVals
                    self.__UiElems.Vertical_Waveform_Combobox.blockSignals(True)
                    self.__UiElems.Horizontal_Waveform_Combobox.blockSignals(True)
                    self.__UiElems.Horizontal_Waveform_Combobox.insertItem(0, waveName)
                    self.__UiElems.Vertical_Waveform_Combobox.insertItem(0, waveName)
                    self.__UiElems.Vertical_Waveform_Combobox.blockSignals(False)
                    self.__UiElems.Horizontal_Waveform_Combobox.blockSignals(False)
            except Exception as e:
                print("Error: Failed to load waveform \"%s\" with error \"%s\"" % (filePath, e))
        else:
            print("Error: Stopped attempted load of redundant waveform, existing waveform at: %s" % (self.__UiElems.Vertical_Waveform_Combobox.findText(waveName)))

    # Loads any waveform tables already in the "Waveforms" directory
    def loadDefaultWaveTables(self):
        # Add default options
        self.__UiElems.Vertical_Waveform_Combobox.blockSignals(True)
        self.__UiElems.Horizontal_Waveform_Combobox.blockSignals(True)
        self.__UiElems.Horizontal_Waveform_Combobox.insertItem(0, "Load Custom")
        self.__UiElems.Vertical_Waveform_Combobox.insertItem(0, "Load Custom")
        self.__UiElems.Vertical_Waveform_Combobox.blockSignals(False)
        self.__UiElems.Horizontal_Waveform_Combobox.blockSignals(False)
        # Load files from other directories
        self.__WaveTables = dict()
        availableTables = glob.glob(os.path.join(os.path.abspath(''), "Waveforms", "*.csv"))
        for filePath in availableTables:
            self.loadWaveform(filePath)
        self.__UiElems.Vertical_Waveform_Combobox.setCurrentIndex(0)
        self.__UiElems.Horizontal_Waveform_Combobox.setCurrentIndex(0)

    def setUiProperties(self):
        self.__UiElems.Vertical_Waveform_Combobox.setInsertPolicy(QComboBox.InsertAtTop)
        self.__UiElems.Horizontal_Waveform_Combobox.setInsertPolicy(QComboBox.InsertAtTop)
        self.__UiElems.Sampling_LUT_Combobox.setInsertPolicy(QComboBox.InsertAtTop)

    #
    # Description:
    #   Links functions to button presses
    #
    def linkUiCallbacks(self):
        # Scan Controls
        self.__UiElems.Scan_Pushbutton.clicked.connect(self.toggleScanning)
        self.__UiElems.Save_Pushbutton.clicked.connect(self.saveImage)
        self.__UiElems.Clear_Pushbutton.clicked.connect(self.clearScreen)

        # Vertical Axis
        self.__UiElems.Vertical_Waveform_Combobox.currentTextChanged.connect(self.updateWaveforms)
        self.__UiElems.Vertical_Amplitude_Spinbox.valueChanged.connect(self.updateWaveforms)
        self.__UiElems.Vertical_Frequency_Spinbox.valueChanged.connect(self.updateWaveforms)

        # Horizontal Axis
        self.__UiElems.Horizontal_Waveform_Combobox.currentTextChanged.connect(self.updateWaveforms)
        self.__UiElems.Horizontal_Amplitude_Spinbox.valueChanged.connect(self.updateWaveforms)
        self.__UiElems.Horizontal_Frequency_Spinbox.valueChanged.connect(self.updateWaveforms)

        # Sampling
        self.__UiElems.Sampling_Frequency_Spinbox.valueChanged.connect(self.updateSamplingFrequency)
        # self.__UiElems.Sampling_Averages_Spinbox.valueChanged.connect(self.setSamplingAverages)
        self.__UiElems.Sampling_Phase_Vertical_Spinbox.valueChanged.connect(self.updateSamplingReconstruction)
        self.__UiElems.Sampling_Phase_Horizontal_Spinbox.valueChanged.connect(self.updateSamplingReconstruction)
        self.__UiElems.Sampling_LUT_Combobox.currentIndexChanged.connect(self.updateSamplingReconstruction)
        self.__UiElems.Sampling_Horizontal_Collection_Combobox.currentIndexChanged.connect(self.updateSamplingReconstruction)
        self.__UiElems.Sampling_Vertical_Collection_Combobox.currentIndexChanged.connect(self.updateSamplingReconstruction)

        # Window
        self.__UiElems.Plotter_Label.setPixmap(QPixmap.fromImage(self.__ScanImage).scaled(self.__UiElems.Plotter_Label.width(), self.__UiElems.Plotter_Label.height()))

        # Console output
        #sys.stdout = self.__consoleOut # COMBAK:
        self.__UiElems.Console_Preformance_Checkbox.stateChanged.connect(self.setConsolePreferences)
        self.__UiElems.Console_Verbose_Checkbox.stateChanged.connect(self.setConsolePreferences)
        self.__consoleOut    = Stream(newText = self.onUpdateText)

    def setDefaults(self):
        # Remember that when the combobox values are changed, this triggers the
        # callbacks and so the MCU is updated etc.

        # Scan Controls

        # Vertical Axis

        defaultVerticalWaveformIndex = self.__UiElems.Vertical_Waveform_Combobox.findText(Const.DEFAULT_VERTWAV)
        if(defaultVerticalWaveformIndex >= 0):
            self.__UiElems.Vertical_Waveform_Combobox.setCurrentIndex(defaultVerticalWaveformIndex)
        else:
            print("Default set vertical waveform does not match a loaded file, check the value in the constants file.")
        self.__UiElems.Vertical_Amplitude_Spinbox.setValue(Const.DEFAULT_VERTAM)
        self.__UiElems.Vertical_Frequency_Spinbox.setValue(Const.DEFAULT_VERTHZ)
        self.__UiElems.Sampling_Phase_Vertical_Spinbox.setValue(Const.DEFAULT_VERTPHASE)

        # Horizontal Axis
        defaultHorizontalWaveformIndex = self.__UiElems.Horizontal_Waveform_Combobox.findText(Const.DEFAULT_HORZWAV)
        if(defaultHorizontalWaveformIndex >= 0):
            self.__UiElems.Horizontal_Waveform_Combobox.setCurrentIndex(defaultHorizontalWaveformIndex)
        else:
            print("Default set horizontal waveform does not match a loaded file, check the value in the constants file.")
        self.__UiElems.Horizontal_Amplitude_Spinbox.setValue(Const.DEFAULT_HORZAM)
        self.__UiElems.Horizontal_Frequency_Spinbox.setValue(Const.DEFAULT_HORZHZ)
        self.__UiElems.Sampling_Phase_Horizontal_Spinbox.setValue(Const.DEFAULT_HORZPHASE)

        # Sampling and reconstruction
        defaultReconstructionIndex = self.__UiElems.Sampling_LUT_Combobox.findText(Const.DEFAULT_LUTMODEL)
        if(defaultReconstructionIndex >= 0):
            self.__UiElems.Sampling_LUT_Combobox.setCurrentIndex(defaultReconstructionIndex)
        else:
            print("Default set LUT method does not match a loaded model or method, check the value in the constants file.")
        self.__UiElems.Sampling_Frequency_Spinbox.setValue(Const.DEFAULT_ADC_SAMPLEFREQUENCY)
        self.__UiElems.Sampling_Horizontal_Collection_Combobox.setCurrentIndex(Const.DEFAULT_HORZSRC)
        self.__UiElems.Sampling_Vertical_Collection_Combobox.setCurrentIndex(Const.DEFAULT_VERTSRC)
        # TODO sample averaging

        # Console
        self.__UiElems.Console_Preformance_Checkbox.setCheckState(1)
        self.__UiElems.Console_Verbose_Checkbox.setCheckState(1)

    #
    # Description:
    #   Function called as emission by stdo        self.linkUiCallbacks()ut replacement. Prints
    #   the console contents to the monitor. TODO Current monitor
    #   is too small and the user is allowed to edit the contents manually
    #   also the monitor should be self-clearing
    #
    def onUpdateText(self, text):
        cursor = self.__UiElems.Console_Output_TextBox.textCursor()
        cursor.movePosition(QTextCursor.End)
        cursor.insertText(text)
        self.__UiElems.Console_Output_TextBox.setTextCursor(cursor)
        self.__UiElems.Console_Output_TextBox.ensureCursorVisible()

    # Description:
    #   Updates the reference qt object from the given mapped data
    #
    # Parameters:
    #   'valueVectors'  Numpy array of mapped image intensities of the format [xPosition, yPosition, intensityValue];[...]...
    #
    def updateQTImage(self, valueVectors):
        if valueVectors is not None:
            valueVectorColors = (self.__ColorMap(valueVectors[:, 2] / 255.0) * 255.0).astype(numpy.uint8) # Format is RGBA
            interiorView = byte_view(self.__ScanImage)
            valueVectors[:, 1] = -1 * (valueVectors[:, 1] - (Const.RES_H - 1)) # Flips coordinates so increasing goes from bottom up
            interiorView[valueVectors[:, 1], valueVectors[:, 0], 0] = valueVectorColors[:, 2] # Converts rgba to bgra
            interiorView[valueVectors[:, 1], valueVectors[:, 0], 1] = valueVectorColors[:, 1]
            interiorView[valueVectors[:, 1], valueVectors[:, 0], 2] = valueVectorColors[:, 0]
            interiorView[valueVectors[:, 1], valueVectors[:, 0], 3] = valueVectorColors[:, 3]
            self.__UiElems.Plotter_Label.setPixmap(QPixmap.fromImage(self.__ScanImage).scaled(self.__UiElems.Plotter_Label.width(), self.__UiElems.Plotter_Label.height()))

    #
    # Description:
    #   Starts and stops data acquisiton and waveform generation. Updates button
    #   text as well.
    #
    def toggleScanning(self):
        if(self.__MCUInterface.isScanning()):
            self.__UiElems.Scan_Pushbutton.setText("Start Scanning")
            self.__MCUInterface.pauseEvents()
            self.__registerTh.halt()
        else:
            self.__UiElems.Scan_Pushbutton.setText("Stop Scanning")
            self.__MCUInterface.beginEvents()
            self.__registerTh.commence()

    #
    # Description:
    #   Saves image currenly on display to memory under the "Captures"
    #   folder.
    #
    def saveImage(self):
        settingsString = "[%s, %s]-[%0.2f,%0.2f](Hz)-[%0.2f,%0.2f](Vpp)-[%s, %s](Microns)" % (self.__UiElems.Horizontal_Waveform_Combobox.currentText(), self.__UiElems.Vertical_Waveform_Combobox.currentText(), self.__UiElems.Horizontal_Frequency_Spinbox.value(), self.__UiElems.Vertical_Frequency_Spinbox.value(), self.__UiElems.Horizontal_Amplitude_Spinbox.value(), self.__UiElems.Vertical_Amplitude_Spinbox.value(), self.__currentXLength, self.__currentYLength)
        totalString    = "Capture_%s_%s.bmp" % (datetime.datetime.now().strftime("%Y-%m-%d[%H-%M-%S]"), settingsString)
        if not self.__ScanImage.save(os.path.join(os.getcwd(), 'Captures', totalString), format = "BMP"):
            print("Failed to Save Image")

    #
    # Description:
    #   Clears image currently on monitor.
    #
    def clearScreen(self):
        self.__ScanImage = QImage(Const.PATH_BACKGROUNDIMAGE).scaled(Const.RES_W, Const.RES_H)
        self.__UiElems.Plotter_Label.setPixmap(QPixmap.fromImage(self.__ScanImage).scaled(self.__UiElems.Plotter_Label.width(), self.__UiElems.Plotter_Label.height()))

    #
    # Description:
    #   Does a frequency survey to approximate the impulse response of the system.
    #   See phase demo for details.
    #
    def calibrateLTIModel(self):
        print("LTI Calibration not fully implemented")

    #
    # Description:
    #   Builds a displacement map to capture non-linear displacement distortion
    #   not accounted for by the LTI model.
    #
    def calibrateDisplacementGrid(self):
        print("Displacement Grid Calibration not fully implemented.")

    #
    # Descripion:
    #   Used to set filters for strings printed to the console.
    #
    def setConsolePreferences(self):
        self.__consoleOut.includePrefix("Error", True)
        self.__consoleOut.includePrefix("Pref", self.__UiElems.Console_Preformance_Checkbox.isChecked())
        self.__consoleOut.allowAll(self.__UiElems.Console_Verbose_Checkbox.isChecked())

    #
    # Description:
    #   Updates the output waveforms to whatever is currently listed in
    #   the GUI.
    #
    def updateWaveforms(self):
        # Handles vertical
        verticalLabel = self.__UiElems.Vertical_Waveform_Combobox.currentText()
        if verticalLabel in self.__WaveTables: # Is an existing waveform
            self.__MCUInterface.setDacMagnitude(1, self.__UiElems.Vertical_Amplitude_Spinbox.value())
            self.__MCUInterface.setDacFrequency(1, self.__UiElems.Vertical_Frequency_Spinbox.value())
            self.__MCUInterface.setCustomWaveformData(1, self.__WaveTables[verticalLabel])
            self.__MCUInterface.setDacWaveform(1, 4)
            self.__currentYWaveformOpt = self.__UiElems.Vertical_Waveform_Combobox.currentIndex()
        elif verticalLabel == "Load Custom": # Loads new waveform
            directories =  QFileDialog.getOpenFileNames(caption = "Select one or more waveform files.", directory = os.path.join(os.path.abspath(''), "Waveforms"));
            for currentDirectoryIndex in range(len(directories) - 1): # Last item is a status code
                currentDirectory = directories[currentDirectoryIndex]
                if(len(currentDirectory) > 0): # See above
                    self.loadWaveform(currentDirectory[0])
            self.__UiElems.Vertical_Waveform_Combobox.setCurrentIndex(self.__currentYWaveformOpt)
            return
        else:
            print("Error: Invalid Waveform Choice for Vertical")
            return

        # Handles vertical
        horizontalLabel = self.__UiElems.Horizontal_Waveform_Combobox.currentText()
        if horizontalLabel in self.__WaveTables: # Is an existing waveform
            self.__MCUInterface.setDacMagnitude(0, self.__UiElems.Horizontal_Amplitude_Spinbox.value())
            self.__MCUInterface.setDacFrequency(0, self.__UiElems.Horizontal_Frequency_Spinbox.value())
            self.__MCUInterface.setCustomWaveformData(0, self.__WaveTables[horizontalLabel])
            self.__MCUInterface.setDacWaveform(0, 4)
            self.__currentXWaveformOpt = self.__UiElems.Horizontal_Waveform_Combobox.currentIndex()
        elif horizontalLabel == "Load Custom": # Loads new waveform
            directories =  QFileDialog.getOpenFileNames(caption = "Select one or more waveform files.", directory = os.path.join(os.path.abspath(''), "Waveforms"));
            for currentDirectoryIndex in range(len(directories) - 1): # Last item is a status code
                currentDirectory = directories[currentDirectoryIndex]
                if(len(currentDirectory) > 0): # See above
                    self.loadWaveform(currentDirectory[0])
            self.__UiElems.Horizontal_Waveform_Combobox.setCurrentIndex(self.__currentXWaveformOpt)
            return
        else:
            print("Error: Invalid Waveform Choice for Horizontal")
            return

        # Updates
        self.updateSamplingReconstruction()
        # Refreshes MCU
        if(self.__MCUInterface.isScanning()): # If not scanning will take effect on startup anyway
            self.__MCUInterface.pauseEvents()
            self.__MCUInterface.beginEvents()

    #
    # Description
    #   Trims image to smallest bounding box that contains pixels whose alpha
    #   value is greater than 1 (not fully transparent).
    #
    def cropInvisAway(self, image):
        imageInverseMask = numpy.logical_not(numpy.logical_or(image[:, :, 3] == 0, numpy.sum(image[:, :, :], axis = 2) == 255 * 4)) # Areas where plotting occured have high alpha values, others have an alpha value of zero or are white
        imageHorizontalSums = numpy.sum(imageInverseMask, axis = 0)
        nonZeroHoriz = numpy.nonzero(imageHorizontalSums)[0]
        firstHoriz   = nonZeroHoriz[0]
        lastHoriz    = nonZeroHoriz[-1]
        imageVerticalSums = numpy.sum(imageInverseMask, axis = 1)
        nonZeroVert  = numpy.nonzero(imageVerticalSums)[0]
        firstVert    = nonZeroVert[0]
        lastVert     = nonZeroVert[-1]
        croppedImage = image[(firstVert):(lastVert + 2), (firstHoriz):(lastHoriz + 2), :]
        return croppedImage

    #
    # Description
    #   Adds scale labels to edges of the image in microns. If None is passed
    #   for xMaxMicrons or yMaxMicrons than the corresponding axis is set to
    #   appear blank.
    #
    def __updateXAxisLabel(self, xMaxMicrons):
        xAxisImage = numpy.zeros((10, 10, 4)) # Does not really matter, just has to be x, x, 4 b/c it will be scaled
        if xMaxMicrons is not None and xMaxMicrons > 0.0:
            fig, ax = plt.subplots(dpi = 300)
            ax.set_aspect(0.1)
            ax.set_yticks([])
            ax.tick_params(
                axis='y',          # changes apply to the x-axis
                which='both',      # both major and minor ticks are affected
                bottom=False,      # ticks along the bottom edge are off
                top=False,         # ticks along the top edge are off
                labelbottom=False) # labels along the bottom edge are off
            ax.set_xlim(0, xMaxMicrons)
            xTick_objects = ax.xaxis.get_major_ticks()
            xTick_objects[0].label1.set_horizontalalignment('left')   # left align first tick
            xTick_objects[-1].label1.set_horizontalalignment('right') # right align last tick
            plt.xlabel("Microns")
            # > Gets canvas buffer
            canvas = FigureCanvasAgg(fig);
            canvas.draw();
            s, (width, height) = canvas.print_to_buffer()
            xAxisImage = self.cropInvisAway(numpy.frombuffer(s, numpy.uint8).reshape((height, width, 4)))

        self.__UiElems.Horizontal_Scale_Label.setPixmap(QPixmap.fromImage(array2qimage(xAxisImage.copy()).scaled(self.__UiElems.Horizontal_Scale_Label.width(), self.__UiElems.Horizontal_Scale_Label.height())))

    def __updateYAxisLabel(self, yMaxMicrons):
        yAxisImage = numpy.zeros((10, 10, 4)) # As Alpha is zero will appear blank
        if yMaxMicrons is not None and yMaxMicrons > 0.0:
            fig, ax = plt.subplots(dpi = 300)
            ax.set_aspect(1000)
            ax.set_xticks([])
            ax.tick_params(
                axis='x',          # changes apply to the x-axis
                which='both',      # both major and minor ticks are affected
                bottom=False,      # ticks along the bottom edge are off
                top=False,         # ticks along the top edge are off
                labelbottom=False) # labels along the bottom edge are off
            ax.set_ylim(0, yMaxMicrons)
            yTick_objects = ax.yaxis.get_major_ticks()
            yTick_objects[0].label1.set_verticalalignment('bottom')   # left align first tick
            yTick_objects[-1].label1.set_verticalalignment('top') # right align last tick
            plt.ylabel("Microns")
            # > Gets canvas buffer
            canvas = FigureCanvasAgg(fig);
            canvas.draw();
            s, (width, height) = canvas.print_to_buffer()
            yAxisImage = self.cropInvisAway(numpy.frombuffer(s, numpy.uint8).reshape((height, width, 4)))

        self.__UiElems.Vertical_Scale_Label.setPixmap(QPixmap.fromImage(array2qimage(yAxisImage.copy()).scaled(self.__UiElems.Vertical_Scale_Label.width(), self.__UiElems.Vertical_Scale_Label.height())))

    #
    # Description
    #   Returns an executable callback that filters timestamps based on whether
    #   they correspond to times in the displacement LUT where the stage is rising
    #   (after the lowest displacement point and before the highest point)
    #   or falling. Returns None if no filtering should occur based on the filter
    #   text.
    #
    def getTimestampFilterFunc(self, filteringText, frequency, stableLUT, stableTimes):
        period   = (1.0 / frequency)
        filterFunction  = None
        crestTime   = stableTimes[numpy.argmax(stableLUT)]
        troughTime  = stableTimes[numpy.argmin(stableLUT)]
        if filteringText == "Rising":
            def filterFunction(inputTime):
                inputTime = numpy.fmod(inputTime, period)
                if troughTime < crestTime: # rising during midpoint
                    return numpy.logical_and(troughTime < inputTime, inputTime < crestTime)
                # falling during midpoint
                return numpy.logical_or(troughTime < inputTime, inputTime < crestTime)
        elif filteringText == "Falling":
            def filterFunction(inputTime):
                inputTime = numpy.fmod(inputTime, period) # TODO mod makes me sad
                if crestTime < troughTime: # falling during midpoint
                    return numpy.logical_and(crestTime < inputTime, inputTime < troughTime)
                # rising during midpoint
                return numpy.logical_or(crestTime < inputTime, inputTime < troughTime)
        return filterFunction

    #
    # Desription:
    #   Updates the lookup methods and modes used for
    #   interpreting sampled data.
    #
    def updateSamplingReconstruction(self):
        # What we have
        xPhase          = self.__UiElems.Sampling_Phase_Horizontal_Spinbox.value() # Only used for "Axis Waveform" mode currently
        yPhase          = self.__UiElems.Sampling_Phase_Vertical_Spinbox.value()
        xFrequency      = self.__UiElems.Horizontal_Frequency_Spinbox.value() # Spinbox is hz
        yFrequency      = self.__UiElems.Vertical_Frequency_Spinbox.value()   # Spinbox is hz
        xVpp            = self.__UiElems.Horizontal_Amplitude_Spinbox.value()
        yVpp            = self.__UiElems.Vertical_Amplitude_Spinbox.value()
        currentLUTMode  = self.__UiElems.Sampling_LUT_Combobox.currentText()
        # What will be determined
        xFunction       = None
        yFunction       = None
        xTotalLength    = None # Width of image in microns
        yTotalLength    = None # Height of image in microns
        xFilterFunction = None
        yFilterFunction = None
        xTimeOffset     = 0.0
        yTimeOffset     = 0.0

        # Import new LTI model
        if(currentLUTMode == "Import Model"):
            directories =  QFileDialog.getOpenFileNames(caption = "Select one or more system model files.", directory = os.path.join(os.path.abspath(''), "SysModels"))
            for currentDirectoryIndex in range(len(directories) - 1): # Last item is a status code
                currentDirectory = directories[currentDirectoryIndex]
                if(len(currentDirectory) > 0):
                    self.loadModel(currentDirectory[0])
            self.__UiElems.Sampling_LUT_Combobox.setCurrentIndex(self.__currentLUTModeOpt)
            return
        else:
            self.__currentLUTModeOpt = self.__UiElems.Sampling_LUT_Combobox.currentIndex()

        # Selected an existing system model
        if currentLUTMode in self.__SystemModels:
            systemModel = self.__SystemModels[currentLUTMode]
            # X Axis
            xPeriod     = 1.0 / xFrequency
            xWaveText   = self.__UiElems.Horizontal_Waveform_Combobox.currentText()
            xWaveTable  = self.__WaveTables[xWaveText]
            xStableTimes, xStableLUT = Analysis.findSteadyStateResp(systemModel, xWaveTable, xFrequency, xVpp)
            xScreenLUT, xTotalLength = Analysis.normalizeDisplacement(xStableLUT, Const.RES_W)
            xFunction     = lambda times: numpy.interp(x = times, xp = xStableTimes, fp = xScreenLUT, period = xPeriod)
            # Y Axis
            yPeriod     = 1.0 / yFrequency
            yWaveText   = self.__UiElems.Vertical_Waveform_Combobox.currentText()
            yWaveTable  = self.__WaveTables[yWaveText]
            yStableTimes, yStableLUT = Analysis.findSteadyStateResp(systemModel, yWaveTable, yFrequency, yVpp)
            yScreenLUT, yTotalLength = Analysis.normalizeDisplacement(yStableLUT, Const.RES_H)
            yFunction     = lambda times: numpy.interp(x = times, xp = yStableTimes, fp = yScreenLUT, period = yPeriod)

            # Sets filter
            xFilteringText = self.__UiElems.Sampling_Horizontal_Collection_Combobox.currentText()
            xFilterFunction = self.getTimestampFilterFunc(xFilteringText, xFrequency, xScreenLUT, xStableTimes)
            yFilteringText = self.__UiElems.Sampling_Vertical_Collection_Combobox.currentText()
            yFilterFunction = self.getTimestampFilterFunc(yFilteringText, yFrequency, yScreenLUT, yStableTimes)

        # Lays out data into modern art image for testing and calibration
        elif(currentLUTMode == "Linear"):
            xFunction = lambda inputTime : Analysis.sawTooth(inputTime, (Const.RES_W * 0.5) - 1, xFrequency, 0.0)
            yFunction = lambda inputTime : Analysis.sawTooth(inputTime, (Const.RES_H * 0.5) - 1, yFrequency, 0.0)

        # Assumes that system plant is 1 (no distortion) and allows for manual phase adjustment
        elif currentLUTMode == "Axis Waveform":
            # X Axis
            xPeriod       = 1.0 / xFrequency
            xWaveText     = self.__UiElems.Horizontal_Waveform_Combobox.currentText()
            xWaveTable    = self.__WaveTables[xWaveText]
            xStableLUT    = numpy.append(xWaveTable, xWaveTable[0]) # Forces wraparound
            xStableTimes  = numpy.linspace(start = 0, stop = xPeriod, num = xStableLUT.shape[0])
            xScreenLUT, _ = Analysis.normalizeDisplacement(xStableLUT, Const.RES_W)
            xFunction     = lambda times: numpy.interp(x = times, xp = xStableTimes, fp = xScreenLUT, period = xPeriod)
            # Y Axis
            yPeriod       = 1.0 / yFrequency
            yWaveText     = self.__UiElems.Vertical_Waveform_Combobox.currentText()
            yWaveTable    = self.__WaveTables[yWaveText]
            yStableLUT    = numpy.append(yWaveTable, yWaveTable[0]) # Forces wraparound
            yStableTimes  = numpy.linspace(start = 0, stop = yPeriod, num = yStableLUT.shape[0])
            yScreenLUT, _ = Analysis.normalizeDisplacement(yStableLUT, Const.RES_H)
            yFunction     = lambda times: numpy.interp(x = times, xp = yStableTimes, fp = yScreenLUT, period = yPeriod)

            # Sets filter
            xFilteringText = self.__UiElems.Sampling_Horizontal_Collection_Combobox.currentText()
            xFilterFunction = self.getTimestampFilterFunc(xFilteringText, xFrequency, xScreenLUT, xStableTimes)
            yFilteringText = self.__UiElems.Sampling_Vertical_Collection_Combobox.currentText()
            yFilterFunction = self.getTimestampFilterFunc(yFilteringText, yFrequency, yScreenLUT, yStableTimes)

            # Assigns offset
            xTimeOffset = xPhase * (1.0 / xFrequency)
            yTimeOffset = yPhase * (1.0 / yFrequency)

        else:
            print("Error: Main_updateSamplingReconstruction, bad mode '%s'" % (currentLUTMode))
            return

        # Sets reconstruction functions
        if(xFunction is not None and yFunction is not None):
            self.__registerTh.setDataTranslateX(xFunction)
            self.__registerTh.setDataTranslateY(yFunction)
        else:
            print("Error: Main_updateSamplingReconstruction, bad translation functions")
        # Sets filtering function
        self.__registerTh.setDataFilterX(xFilterFunction)
        self.__registerTh.setDataFilterY(yFilterFunction)
        # Sets time offset
        self.__registerTh.setDataOffsetX(xTimeOffset)
        self.__registerTh.setDataOffsetY(yTimeOffset)
        # Sets axis labels
        if self.__currentXLength != xTotalLength:
            self.__updateXAxisLabel(xTotalLength)
            self.__currentXLength = xTotalLength

        if self.__currentYLength != yTotalLength:
            self.__updateYAxisLabel(yTotalLength)
            self.__currentYLength = yTotalLength

    #
    # Description:
    #   Increases sampling frequency.
    #
    def updateSamplingFrequency(self):
        newFrequency = self.__UiElems.Sampling_Frequency_Spinbox.value() * 1000.0 # Spinbox shows kHz, need to provide hz
        self.__MCUInterface.setAdcFrequency(newFrequency)
        if(self.__MCUInterface.isScanning()):
            self.__MCUInterface.pauseEvents()
            self.__MCUInterface.beginEvents()

if __name__ == "__main__":
    if doChangeCPU:
        P = psutil.Process()
        P.cpu_affinity([0])
   # P.nice(psutil.HIGH_PRIORITY_CLASS)
    if not QApplication.instance():
        app = QApplication(sys.argv)
    else:
        app = QApplication.instance()
    window = TestBench()
    window.show()
    exitStatus = app.exec_()
    sys.exit(exitStatus)

Version 2.0/Software/Main/QT Application v4/AWESEM_Testbench_Main.py


#!/opt/anaconda3/envs/pyn_env/bin/python
import numpy as np
from netCDF4 import Dataset
import sys

fname=sys.argv[1]
nc=Dataset(fname)
V=[list(filter(lambda x:nc[x].ndim==j, [i for i in nc.variables])) for j in [1,2,3,4]]
nt,nlay,nrow,ncol=nc.variables[V[3][0]].shape

for v in V[3][:]:
  a=nc[v][:,0,:,:]
  a=np.where(a==a,a,-1)
  a=np.where(a>0,a,0)
  mxv=np.percentile(a,99.99)
  mnv=np.max([np.percentile(a,0.01),mxv/100])
print(mnv,mxv)


import pandas as pd

df = pd.read_csv('../input/train_users_reduzido.csv', decimal='.')

datas = df['date_account_created']
# print(datas)

def pre_processamento_data(datas):
    # converte o mês da date_account_created para um atributo categórico indicando a estação
    def escolhe_estacao(mes):
        if (mes <= 5) and (mes >= 3):
            return 'SPRING'
        elif (mes <= 8) and (mes >= 6):
            return 'SUMMER'
        elif (mes <= 11) and (mes >= 9):
            return 'FALL'
        else:
            return 'WINTER'
    estacoes = pd.DataFrame(['estacoes'])
    for i in range(len(datas)):
        mes_data = datas[i][5:7]
        # print(escolhe_estacao(int(mes_data)))
        estacoes.loc[i] = [ escolhe_estacao(int(mes_data)) ]
    return estacoes

print(pre_processamento_data( datas))


# 用于Cron任务调用的Action触发
import requests
import json

def run():
        payload = json.dumps({"ref": "main"})
        header = {'Authorization': 'token **********',
                  "Accept": "application/vnd.github.v3+json"}
        response_decoded_json = requests.post(
            f'https://api.github.com/repos/l549349545/crdsrw/actions/workflows/9310500/dispatches',
            data=payload, headers=header)

# 云函数入口
def main_handler(event, context):
    return run()


"""
Define 3DConvolution spae
"""
__authors__ = ""
__copyright__ = "Copyright 2013-2014, Universite de Montreal"
__credits__ = [""]
__license__ = "3-clause BSD"
__maintainer__ = ""
__email__ = ""

import functools, warnings
import numpy as np
import theano
import theano.sparse

from theano.tensor import TensorType
from theano.gof.op import get_debug_values
from theano.sandbox.cuda.type import CudaNdarrayType
from pylearn2.utils import py_integer_types, safe_zip, sharedX, wraps
from pylearn2.format.target_format import OneHotFormatter

from pylearn2.space import Space, SimplyTypedSpace, VectorSpace, _cast

if theano.sparse.enable_sparse:
    # We know scipy.sparse is available
    import scipy.sparse

class Conv3DSpace(SimplyTypedSpace):
    """
    A space whose points are 4-D tensors representing (potentially
    multi-channel) 2D video with a fix temporal duration.

    Parameters
    ----------
    shape : sequence, length 3
        The shape of a single image, i.e. (rows, cols, time).
    num_channels : int (synonym: channels)
        Number of channels in the image, i.e. 3 if RGB.
    axes : tuple
        A tuple indicating the semantics of each axis, containing the
        following elements in some order:

            - 'b': this axis is the batch index of a minibatch.
            - 't': time axis
            - 0  : topological axis 0 (rows)
            - 1  : topological axis 1 (columns)
            - 'c': this axis tcnhe channel index of a minibatch.

    dtype : str
        A numpy dtype string (e.g. 'float32') indicating this space's
        dtype, or None for a dtype-agnostic space.
    kwargs : dict
        Passed on to superclass constructor
    """

    default_axes = ('b', 't', 0, 1, 'c')

    def __init__(self,
                 shape,
                 channels=None,
                 num_channels=None,
                 axes=None,
                 dtype='floatX',
                 **kwargs):

        super(Conv3DSpace, self).__init__(dtype, **kwargs)

        assert (channels is None) + (num_channels is None) == 1
        if num_channels is None:
            num_channels = channels

        assert isinstance(num_channels, py_integer_types)

        if not hasattr(shape, '__len__'):
            raise ValueError("shape argument for Conv3DSpace must have a "
                             "length. Got %s." % str(shape))

        if len(shape) != 3:
            raise ValueError("shape argument to Conv3DSpace must be length 3, "
                             "not %d" % len(shape))
        self.sequence_length = shape[2]

        assert all(isinstance(elem, py_integer_types) for elem in shape)
        assert all(elem > 0 for elem in shape)
        assert isinstance(num_channels, py_integer_types)
        assert num_channels > 0
        # Converts shape to a tuple, so it can be hashable, and self can be too
        self.shape = tuple(shape)
        self.num_channels = num_channels
        if axes is None:
            axes = self.default_axes
        assert len(axes) == 5
        self.axes = tuple(axes)

    def __str__(self):
        """Return a string representation"""
        return ("%s(shape=%s, num_channels=%d, axes=%s, dtype=%s)" %
                (self.__class__.__name__,
                 str(self.shape),
                 self.num_channels,
                 str(self.axes),
                 self.dtype))

    def __eq__(self, other):
        """
        Returns true iff
        space.format_as(batch, self) and
        space.format_as(batch, other) return the same formatted batch.
        """
        assert isinstance(self.axes, tuple)
        if isinstance(other, Conv3DSpace):
            assert isinstance(other.axes, tuple)
        return (type(self) == type(other) and
                self.shape == other.shape and
                self.num_channels == other.num_channels and
                self.axes == other.axes and
                self.dtype == other.dtype)

    def __hash__(self):
        """
        .. todo::

            WRITEME
        """
        return hash((type(self),
                     self.shape,
                     self.num_channels,
                     self.axes,
                     self.dtype))

    @functools.wraps(Space.get_batch_axis)
    def get_batch_axis(self):
        return self.axes.index('b')

    @functools.wraps(Space.get_origin)
    def get_origin(self):
        dims = {0: self.shape[0],
                1: self.shape[1],
                'c': self.num_channels,
                't': self.shape[2]}
        shape = [dims[elem] for elem in self.axes if elem != 'b']
        return np.zeros(shape, dtype = self.dtype)

    @functools.wraps(Space.get_origin_batch)
    def get_origin_batch(self, batch_size, dtype=None):
        if dtype is None:
            dtype = theano.config.floatX

        if not isinstance(batch_size, py_integer_types):
            raise TypeError("Conv3DSpace.get_origin_batch expects an int, "
                            "got %s of type %s" % (str(batch_size),
                                                   type(batch_size)))
        assert batch_size > 0
        dims = {'b': batch_size,
                0: self.shape[0],
                1: self.shape[1],
                't': self.shape[2],
                'c': self.num_channels}
        shape = [dims[elem] for elem in self.axes]
        return np.zeros(shape, dtype=dtype)

    @functools.wraps(Space.make_theano_batch)
    def make_theano_batch(self, name=None, dtype=None, batch_size=None):
        if dtype is None:
            dtype = theano.config.floatX

        broadcastable = [False] * 5
        broadcastable[self.axes.index('c')] = (self.num_channels == 1)
        broadcastable[self.axes.index('b')] = (batch_size == 1)
        broadcastable = tuple(broadcastable)

        rval = TensorType(dtype=dtype,
                          broadcastable=broadcastable)(name=name)
        if theano.config.compute_test_value != 'off':
            if batch_size == 1:
                rval.tag.test_value = self.get_origin_batch(batch_size=1)
            else:
                rval.tag.test_value = self.get_origin_batch(batch_size=4)
        return rval

    @functools.wraps(Space._batch_size_impl)
    def _batch_size_impl(self, is_numeric, batch):
        return batch.shape[self.axes.index('b')]

    @staticmethod
    def convert(tensor, src_axes, dst_axes):
        """
        Returns a view of tensor using the axis semantics defined
        by dst_axes. (If src_axes matches dst_axes, returns
        tensor itself)

        Useful for transferring tensors between different
        Conv3DSpaces.

        Parameters
        ----------
        tensor : tensor_like
            A 4-tensor representing a batch of images
        src_axes : tuple
            Axis semantics of tensor
        dst_axes : tuple
            Axis semantic of the destination space
        """
        src_axes = tuple(src_axes)
        dst_axes = tuple(dst_axes)
        assert len(src_axes) == 5
        assert len(dst_axes) == 5

        if src_axes == dst_axes:
           return tensor
        shuffle = [src_axes.index(elem) for elem in dst_axes]
        if is_symbolic_batch(tensor):
            return tensor.dimshuffle(*shuffle)
        else:
            return tensor.transpose(*shuffle)

    @staticmethod
    def convert_numpy(tensor, src_axes, dst_axes):
        """
        .. todo::

            WRITEME
        """
        return Conv3DSpace.convert(tensor, src_axes, dst_axes)

    @functools.wraps(Space.get_total_dimension)
    def get_total_dimension(self):
        # Patch old pickle files
        if not hasattr(self, 'num_channels'):
            self.num_channels = self.nchannels
        assert len(self.shape) == 3
        return self.shape[0] * self.shape[1] * self.shape[2] * self.num_channels

    @functools.wraps(Space._validate_impl)
    def _validate_impl(self, is_numeric, batch):
        # checks batch.type against self.dtype
        super(Conv3DSpace, self)._validate_impl(is_numeric, batch)

        if isinstance(batch, theano.gof.Variable):
            if isinstance(batch, theano.sparse.SparseVariable):
                raise TypeError("Conv3DSpace cannot use SparseVariables, "
                                "since as of this writing (8 May 2014), "
                                "there is not yet a SparseVariable type with "
                                "5 dimensions")

            if not isinstance(batch, theano.gof.Variable):
                raise TypeError("Conv3DSpace batches must be theano "
                                "Variables, got " + str(type(batch)))

            if not isinstance(batch.type, (theano.tensor.TensorType,
                                           CudaNdarrayType)):
                raise TypeError('Expected TensorType or CudaNdArrayType, got '
                                '"%s"' % type(batch.type))

            if batch.ndim != 5:
                raise ValueError("The value of a Conv3DSpace batch must be "
                                 "5D, got %d dimensions for %s." %
                                 (batch.ndim, batch))

            for val in get_debug_values(batch):
                self.np_validate(val)
        else:
            if scipy.sparse.issparse(batch):
                raise TypeError("Conv3DSpace cannot use sparse batches, since "
                                "scipy.sparse does not support 5 dimensional "
                                "tensors currently (8 May 2014).")

            if (not isinstance(batch, np.ndarray)) \
               and type(batch) != 'CudaNdarray':
                raise TypeError("The value of a Conv3DSpace batch should be a "
                                "numpy.ndarray, or CudaNdarray, but is %s."
                                % str(type(batch)))

            if batch.ndim != 5:
                raise ValueError("The value of a Conv3DSpace batch must be "
                                 "5D, got %d dimensions for %s." %
                                 (batch.ndim, batch))

            d = self.axes.index('c')
            actual_channels = batch.shape[d]
            if actual_channels != self.num_channels:
                raise ValueError("Expected axis %d to be number of channels "
                                 "(%d) but it is %d" %
                                 (d, self.num_channels, actual_channels))
            assert batch.shape[self.axes.index('c')] == self.num_channels

            for coord in [0, 1]:
                d = self.axes.index(coord)
                actual_shape = batch.shape[d]
                expected_shape = self.shape[coord]
                if actual_shape != expected_shape:
                    raise ValueError("Conv3DSpace with shape %s and axes %s "
                                     "expected dimension %s of a batch (%s) "
                                     "to have length %s but it has %s"
                                     % (str(self.shape),
                                        str(self.axes),
                                        str(d),
                                        str(batch),
                                        str(expected_shape),
                                        str(actual_shape)))

    @functools.wraps(Space._format_as_impl)
    def _format_as_impl(self, is_numeric, batch, space):
        if isinstance(space, VectorSpace):
            # We need to ensure that the resulting batch will always be
            # the same in `space`, no matter what the axes of `self` are.
            if self.axes != self.default_axes:
                # The batch index goes on the first axis
                assert self.default_axes[0] == 'b'
                batch = batch.transpose(*[self.axes.index(axis)
                                          for axis in self.default_axes])
            result = batch.reshape((batch.shape[0],
                                    self.get_total_dimension()))
            if space.sparse:
                result = _dense_to_sparse(result)

        elif isinstance(space, Conv3DSpace):
            result = Conv3DSpace.convert(batch, self.axes, space.axes)
        else:
            raise NotImplementedError("%s doesn't know how to format as %s"
                                      % (str(self), str(space)))

        return _cast(result, space.dtype)


from django.utils.translation import ugettext_lazy as _

from papermerge.contrib.admin.forms import TagForm
from papermerge.core.models import Tag
from papermerge.core.views import (
    AdminListView,
    AdminView,
    AdminChangeView
)

class TagsListView(AdminListView):
    model_class = Tag
    model_label = 'core.Tag'
    template_name = 'admin/tags.html'
    list_url = 'admin:tags'

    def get_queryset(self, request):
        return Tag.objects.filter(user=request.user)

class TagView(AdminView):
    title = _('New Tag')
    model_class = Tag
    form_class = TagForm
    template_name = 'admin/tag.html'
    action_url = 'admin:tag'
    list_url = 'admin:tags'

class TagChangeView(AdminChangeView):
    title = _('Edit Tag')
    model_class = Tag
    form_class = TagForm
    template_name = 'admin/tag.html'
    change_url = 'admin:tag_change'
    list_url = 'admin:tags'


#!/usr/bin/env python3
# -*- coding:UTF-8
# 共享值和数组,使用了锁来同步
# 用时研究

import multiprocessing

class FloatChannel(object):

    def __init__(self, maxsize):
        self.buffer = multiprocessing.RawArray('d', maxsize)
        self.buffer_len = multiprocessing.Value('i')
        self.empty = multiprocessing.Semaphore(1)
        self.full = multiprocessing.Semaphore(0)

    def send(self, values):
        self.empty.acquire()
        num = len(values)
        self.buffer_len = num
        self.buffer[:num] = values
        self.full.release()

    def recv(self):
        self.full.acquire()
        values = self.buffer[:self.buffer_len.value]
        self.empty.release()
        return values

def consume_test(count, ch):
    for i in range(count):
        values = ch.recv()

def produce_test(count, values, ch):
    for i in range(count):
        ch.send(values)

if __name__ == '__main__':
    ch = FloatChannel(100000)
    p = multiprocessing.Process(target=consume_test,
                                args=(1000, ch))
    p.start()

    values = [float(x) for x in range(100000)]
    produce_test(1000, values, ch)
    print('Done')
    p.join()


from django.db.models import Q
from django.http import HttpResponse
from django.shortcuts import (
    render,
    get_object_or_404,
    redirect
    )
from django.contrib.auth.decorators import login_required
from django.urls import reverse

from .models import (
    Planning,
    Tag_Subregion,
    Tag_Project,
    Tag_Language,
    Tag_Region,
    Comment
    )

from .forms import (
    PlanningCreateForm,
    CommentForm
    )

from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage

# 목록
def detail_list(request):
    if request.method == "POST":
        selected_region_all = request.POST.get('city_all')
        selected_city_pk = [] + request.POST.getlist('city')
        selected_project_pk = [] + request.POST.getlist('project')
        selected_language_pk = [] +request.POST.getlist('language')

        url = reverse('planningboard:list')
        if selected_region_all:
            url += '?selected_region_all=' + str(selected_region_all)
        else:
            url += '?selected_city_pk=' + str(selected_city_pk)

        if request.POST.get('language_all'):
            url += '&selected_language_pk=' + str(list(map(lambda x:x.get('pk'), Tag_Language.objects.values('pk'))))
        else:
            url += '&selected_language_pk=' + str(selected_language_pk)

        if request.POST.get('project_all'):
            url += '&selected_project_pk=' + str(list(map(lambda x: x.get('pk'),Tag_Project.objects.values('pk'))))
        else:
            url += '&selected_project_pk=' + str(selected_project_pk)

        return redirect(url)

    selected_language_pk = eval(request.GET.get('selected_language_pk') or '[]')
    selected_project_pk = eval(request.GET.get('selected_project_pk') or '[]')
    detail_list = Planning.objects.filter()

    if selected_language_pk:
        node = Q(language__pk=selected_language_pk[0])
        for pk in selected_language_pk:
            node |= Q(language__pk=pk)
        detail_list = detail_list.filter(node).distinct()

    if selected_project_pk:
        node = Q(project__pk=selected_project_pk[0])
        for pk in selected_project_pk:
            node |= Q(project__pk=pk)
        detail_list = detail_list.filter(node).distinct()

    if request.GET.get('selected_region_all'):
        selected_region_all = request.GET.get('selected_region_all')
        detail_list = detail_list.filter(region__pk=selected_region_all)
        selected_province_pk =  selected_region_all
        selected_city_pk = []
    else:
        selected_city_pk = eval(request.GET.get('selected_city_pk') or '[]')
        if len(selected_city_pk) == 0:
            selected_province_pk = 0
        else:
            node = Q(subregion__pk=selected_city_pk[0])
            for pk in selected_city_pk:
                node |= Q(subregion__pk=pk)
            detail_list = detail_list.filter(node).distinct()
            selected_province_pk = Tag_Subregion.objects.get(pk=selected_city_pk[0]).region.pk
        selected_region_all = None

    detail_list = detail_list.order_by('-updated_at')
    PAGE_ROW_COUNT = 6
    PAGE_DISPLAY_COUNT = 5

    paginator = Paginator(detail_list, PAGE_ROW_COUNT)
    pageNum = request.GET.get('pageNum')
    totalPageCount = paginator.num_pages
    try:
        detail_list = paginator.page(pageNum)
    except PageNotAnInteger:
        detail_list = paginator.page(1)
        pageNum = 1
    except EmptyPage:
        detail_list = paginator.page(paginator.num_pages)
        pageNum = paginator.num_pages

    pageNum = int(pageNum)

    startPageNum = int(1+((pageNum-1)/PAGE_DISPLAY_COUNT)*PAGE_DISPLAY_COUNT)
    endPageNum = int(startPageNum+PAGE_DISPLAY_COUNT-1)
    if totalPageCount < endPageNum:
        endPageNum = totalPageCount

    bottomPages = range(startPageNum, endPageNum+1)

    ctx = {
        'detail_list': detail_list,
        'province_list': Tag_Region.objects.all(),
        'region_list': Tag_Subregion.objects.all(),
        'project_list': Tag_Project.objects.all(),
        'language_list': Tag_Language.objects.all(),
        'selected_province_pk': selected_province_pk,
        'selected_city_pk': selected_city_pk,
        'selected_region_all': selected_region_all,
        'selected_language_pk': selected_language_pk,
        'selected_project_pk': selected_project_pk,
        'pageNum': pageNum,
        'bottomPages': bottomPages,
        'totalPageCount': totalPageCount,
        'startPageNum': startPageNum,
        'endPageNum': endPageNum,
    }
    return render(request, 'planning_list.html', ctx)

def detail_list_html(request):
    selected_language_pk = eval(request.GET.get('selected_language_pk') or '[]')
    selected_project_pk = eval(request.GET.get('selected_project_pk') or '[]')
    detail_list = Planning.objects.filter()
    if selected_language_pk:
        node = Q(language__pk=selected_language_pk[0])
        for pk in selected_language_pk:
            node |= Q(language__pk=pk)
            detail_list = detail_list.filter(node).distinct()

    if selected_project_pk:
        node = Q(project__pk=selected_project_pk[0])
        for pk in selected_project_pk:
            node |= Q(project__pk=pk)
            detail_list = detail_list.filter(node).distinct()

    if request.GET.get('selected_region_all'):
        selected_region_all = request.GET.get('selected_region_all')
        detail_list = detail_list.filter(region__pk=selected_region_all)
        selected_province_pk = selected_region_all
        selected_city_pk = []
    else:
        selected_city_pk = eval(request.GET.get('selected_city_pk') or '[]')
        if len(selected_city_pk) == 0:
            selected_province_pk = 0
        else:
            node = Q(subregion__pk=selected_city_pk[0])
            for pk in selected_city_pk:
                node |= Q(subregion__pk=pk)
            detail_list = detail_list.filter(node).distinct()
            selected_province_pk = Tag_Subregion.objects.get(pk=selected_city_pk[0]).region.pk
        selected_region_all = None

    ctx = {
        'detail_list': detail_list.order_by('-created_at'),
        'province_list': Tag_Region.objects.all(),
        'region_list': Tag_Subregion.objects.all(),
        'project_list': Tag_Project.objects.all(),
        'language_list': Tag_Language.objects.all(),
        'selected_province_pk': selected_province_pk,
        'selected_city_pk': selected_city_pk,
        'selected_region_all': selected_region_all,
        'selected_language_pk': selected_language_pk,
        'selected_project_pk': selected_project_pk,
    }

    return render(request, 'detail_list.html', ctx)

def alphabet(request):
    print('done')
    selected_detail_list = request.POST.getlist('selected_detail_list[]')
    print(selected_detail_list)
    unordered_detail_list = Planning.objects.none()

    for detail_pk in selected_detail_list:
        unordered_detail_list |= Planning.objects.filter(pk=detail_pk)
    detail_list = unordered_detail_list.order_by('title')

    return render(request, 'detail_list.html', {'detail_list': detail_list})

def recent(request):
    selected_detail_list = request.POST.getlist('selected_detail_list[]')
    unordered_detail_list = Planning.objects.none()

    for detail_pk in selected_detail_list:
        unordered_detail_list |= Planning.objects.filter(pk=detail_pk)
    detail_list = unordered_detail_list.order_by('-created_at')

    return render(request, 'detail_list.html', {'detail_list': detail_list})

# 게시글 화면
def detail(request, pk):
    detail = get_object_or_404(Planning, pk=pk)
    comment_list = Comment.objects.filter(detail__pk=detail.pk).order_by('-created_at')
    comment_form = CommentForm(request.POST or None)
    ctx = {
        'detail': detail,
        'did_like_article': detail.profile_set.filter(pk=request.user.pk).exists(),
        'comment_list': comment_list,
        'comment_form': comment_form,
    }
    return render (request, 'detail.html', ctx)

@login_required
def create(request):
    form = PlanningCreateForm(request.user.profile, request.POST or None, request.FILES or None,)
    if request.method == "POST" and form.is_valid():
        article = form.save(commit=False)
        article.author = request.user
        article.save()
        form.save_m2m()
        return redirect(reverse('planningboard:detail', kwargs={'pk': article.pk}))
    ctx = {
        'form': form,
        'region':Tag_Region.objects.all(),
        'subregion':Tag_Subregion.objects.all()
    }
    return render (request, 'create.html', ctx)

def delete(request, pk):
    if request.method == "POST":
        detail = get_object_or_404(Planning, pk=pk)
        detail.delete()
        return redirect(reverse('planningboard:list'))
    else:
        return HttpResponse(status=400)

def update(request, pk):
    detail = get_object_or_404(Planning, pk=pk)
    form = PlanningCreateForm(request.user.profile, request.POST or None, instance=detail)
    if request.method == "POST" and form.is_valid():
       new_form = form.save(commit=False)
       # new_form.author = request.user
       # new_form.tag_set = request.user.tag_set.all()
       new_form.save()
       form.save_m2m()
       return redirect(reverse('planningboard:detail', kwargs={'pk': pk}))
    ctx = {
        'form': form
    }
    return render(request, 'create.html', ctx)

def get_subregion(request, pk):
    if request.method == "POST":
        subregion_list = Tag_Region.objects.get(pk=pk).get_sebregion()
        return render(request, 'subregion.html',{'subregion_list': subregion_list})

def like(request, pk):
    if request.method == "POST":
        detail = get_object_or_404(Planning, pk=pk)

        if request.user.profile.like_planning.filter(pk=pk).exists():
            detail.profile_set.remove(request.user.profile)
        else:
            detail.profile_set.add(request.user.profile)
        ctx = {
            'did_like_article': detail.profile_set.filter(pk=request.user.pk).exists(),
            'detail': detail,
        }
        return render(request, 'like_button.html', ctx)
    else:
        return HttpResponse(status=400)

def comment_create(request, detail_pk):

    if request.method == "POST":
        detail = Planning.objects.get(pk=detail_pk)
        comment_form = CommentForm(request.POST)

        if comment_form.is_valid():
            new_comment = comment_form.save(commit=False)
            new_comment.author = request.user
            new_comment.detail = detail
            new_comment.save()
            return render(request, 'comment_list.html', {'comment': new_comment})
    return HttpResponse(status=405)


from typing import List

class Solution:
    # items[i] = type, color, name
    def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
        counter = 0
        for e_type, color, name in items:
            if (ruleKey == "color" and color == ruleValue) or \
                    (ruleKey == "type" and e_type == ruleValue) or \
                    (ruleKey == "name" and name == ruleValue):
                counter += 1

        return counter

s = Solution()
print(
    s.countMatches([["phone", "blue", "pixel"], ["computer", "silver", "lenovo"], ["phone", "gold", "iphone"]], "color",
                   "silver"))
print(s.countMatches([["phone", "blue", "pixel"], ["computer", "silver", "phone"], ["phone", "gold", "iphone"]], "type",
                     "phone"))