from typing import List, Dict

from PyQt5.QtGui import QColor

from app.utils import list_math
from ..editor.base import BaseEditor
from ..model import ActionModel, ObjectModel
from ..object import ObjectRect, MouseIndicator
from ..object.operation import BaseOperation, TapOperation, SwipeOperation, GroupOperation

class ActionEditor(BaseEditor):
    COLOR_OBJECT = QColor(0, 255, 255)
    COLOR_MOUSE = QColor(0, 255, 0)
    COLOR_ORIGIN = QColor(255, 255, 0)

    COLOR_UNFOCUS = QColor(255, 255, 0)
    COLOR_UNFOCUS_MOVING = QColor(255, 255, 0, 128)
    COLOR_FOCUS = QColor(255, 128, 0)

    DISTANCE_SWIPE = 8
    TIME_PRESS = 0.3

    RADIUS_MOUSE_CIRCLE = 12
    RADIUS_GROUP_CIRCLE = 24
    RADIUS_TAP_CIRCLE = 16
    RADIUS_SWIPE_CIRCLE = 16
    TYPE_OPERATION = {
        ActionModel.TYPE_GROUP: GroupOperation,
        ActionModel.TYPE_TAP: TapOperation,
        ActionModel.TYPE_SWIPE: SwipeOperation,
    }
    TYPE_OPERATION_REV = dict((v, k) for k, v in TYPE_OPERATION.items())

    def __init__(self, event):
        super().__init__(event)
        self._event = event
        self._operations = {}  # type: Dict[BaseOperation, ActionModel]
        self._current_operation = None
        self._mouse_indicator = MouseIndicator(self._event, self.COLOR_ORIGIN, self.COLOR_MOUSE,
                                               self.RADIUS_MOUSE_CIRCLE, self.TIME_PRESS, self.DISTANCE_SWIPE)

        self._object = None  # type: ObjectModel
        self._object_origin = None  # type: List[int]
        self._object_rect = ObjectRect(event)
        self._object_rect.set_color(self.COLOR_OBJECT)

        self._actions = None  # type: List[ActionModel]
        self._creating = False

    def load_actions(self, object_: ObjectModel):
        actions = object_.actions
        self._actions = actions
        self._object = object_
        x, y, w, h = self._object.rect
        self._object_origin = [x + w / 2, y + h / 2]

        x, y, w, h = object_.rect
        self._object_rect.set_position(x, y)
        self._object_rect.set_size(w, h)

        operations = {}
        for action in actions:
            operation = self.new_operation(action.type, action.params, sync=False)
            operation.load_params(self._object_origin, **action.params)
            operations[operation] = action
        self._operations = operations
        self.set_current_operation(None, False)

    @property
    def operations(self):
        return list(self._operations.keys())

    def select(self, index):
        operations = self.operations
        if 0 <= index < len(operations):
            self.set_current_operation(operations[index], sync=False)
        else:
            self.set_current_operation(None, sync=False)

    @property
    def current_operation(self):
        return self._current_operation

    @property
    def current_action(self):
        return self._operations.get(self._current_operation)

    def set_current_operation(self, operation, sync=True):
        if self._current_operation is not None:
            self._current_operation.set_focus(False)

        self._current_operation = operation
        if operation is not None:
            operation.set_focus(True)

        if sync and operation in self._operations:
            self.event['select_action'](self.operations.index(operation))

    def update(self):
        mouse = self.mouse
        keyboard = self.keyboard

        mouse_l = mouse.button(mouse.BUTTON_LEFT)
        self._mouse_indicator.update()

        if self._creating:
            if mouse_l.click_end:
                cc = mouse_l.click_count_last
                press_time = int(mouse_l.press_time_last * 1000)
                if cc > 1:
                    dx, dy = mouse_l.down_position
                    dx, dy = list_math.reduce([dx, dy], self._object_origin)
                    self.new_operation(ActionModel.TYPE_TAP, dict(
                        x=dx, y=dy, count=cc, press_time=press_time
                    ))
                    self._creating = False
                elif cc > 0:
                    pt = mouse_l.press_time_last
                    cd = mouse_l.click_distance
                    dx, dy = mouse_l.down_position
                    rx, ry = mouse_l.release_position
                    dx, dy = list_math.reduce([dx, dy], self._object_origin)
                    rx, ry = list_math.reduce([rx, ry], self._object_origin)
                    if cd > self.DISTANCE_SWIPE:
                        self.new_operation(ActionModel.TYPE_SWIPE, dict(
                            start_x=dx, start_y=dy,
                            end_x=rx, end_y=ry,
                            time=press_time,
                        ))
                    else:
                        if pt >= self.TIME_PRESS:
                            self.new_operation(ActionModel.TYPE_TAP, dict(
                                x=dx, y=dy,
                                press_time=press_time,
                            ))
                        else:
                            if keyboard.key(keyboard.KEY_G).press:
                                self.new_operation(ActionModel.TYPE_GROUP, dict(
                                    x=dx, y=dy
                                ))
                            else:
                                self.new_operation(ActionModel.TYPE_TAP, dict(
                                    x=dx, y=dy, count=cc, press_time=press_time
                                ))
                    self._creating = False
        else:
            for operation in self._operations:
                operation.update()

            if self._current_operation is not None:
                if not self._current_operation.focus:
                    self.set_current_operation(None)

                if mouse_l.click_end and mouse_l.click_count_last == 2:
                    self._event['set_params']()

            if self._current_operation is None:
                if mouse_l.down:
                    for operation in reversed(self.operations):
                        if operation.check_point(*mouse.position):
                            self.set_current_operation(operation)
                            break
                    if self._current_operation is None:
                        if self._object_rect.check_point(*mouse.position):
                            self._creating = True
                    else:
                        self._current_operation.update()

    def new_operation(self, type_, params: dict, sync=True):
        operation_cls = self.TYPE_OPERATION.get(type_)
        operation = None
        if operation_cls is not None:
            operation = operation_cls(self._event)
            operation.load_params(self._object_origin, **params)
            operation.set_callback_moving(self.callback_operation_moving)
            operation.set_focus_color(self.COLOR_FOCUS, self.COLOR_UNFOCUS)
            if isinstance(operation, GroupOperation):
                operation.circle.set_radius(self.RADIUS_GROUP_CIRCLE)
            elif isinstance(operation, TapOperation):
                operation.circle.set_radius(self.RADIUS_TAP_CIRCLE)
            elif isinstance(operation, SwipeOperation):
                operation.circle_start.set_radius(self.RADIUS_SWIPE_CIRCLE / 2)
                operation.circle_end.set_radius(self.RADIUS_SWIPE_CIRCLE)

            if sync and self.add_item(operation):
                self.set_current_operation(operation)

        return operation

    def add_item(self, operation: BaseOperation):
        if self._actions is None:
            return False
        name = ''
        names = [action.name for action in self._actions]
        for i in range(10000):
            name = 'Untitiled_%s' % i
            if name not in names:
                break

        action = ActionModel()
        action.name = name
        action.type = self.TYPE_OPERATION_REV.get(type(operation))
        action.params = operation.params
        self._operations[operation] = action
        self._actions.append(action)
        self.sync()
        return True

    def draw(self):
        self._object_rect.draw()
        for operation in self._operations:
            operation.draw()
        if self._creating:
            self._mouse_indicator.draw()

    def callback_operation_modified(self, operation_modified: BaseOperation):
        self.sync()

    def callback_operation_moving(self, operation_moving: BaseOperation, moving):
        if not moving:
            self.callback_operation_modified(operation_moving)
        for operation in self._operations:
            if moving:
                if operation != operation_moving:
                    operation.set_color(self.COLOR_UNFOCUS_MOVING)
            else:
                if operation != operation_moving:
                    operation.set_color(self.COLOR_UNFOCUS)

    def sync(self):
        if self._actions is None:
            return

        for operation, action in self._operations.items():
            operation: BaseOperation
            action: ActionModel
            action.params = operation.params
        self.event['sync_actions'](self._actions)

    def callback_item_edited(self, edited_item):
        for operation, item in self._operations.items():
            if edited_item == item:
                operation.load_params(self._object_origin, **item.params)
                break

    def callback_item_deleted(self, deleted_item):
        for operation, item in self._operations.items():
            if deleted_item == item:
                self._operations.pop(operation)
                if operation == self._current_operation:
                    self.set_current_operation(None)
                break


# -*- coding: utf-8 -*-
"""
Trabalho 1 - Exercício 4: Um desenvolvedor de software para uma estação meteorológica
tem que fazer a leitura das seguintes variáveis, para o dia corrente e dar previsões
para o dia seguinte, conforme as condições:
- variáveis:
→ Temperatura;
→ Umidade Relativa do Ar;
- condições:
Se (Temperatura >= 28ºC e Umidade Relativa do Ar >= 50%) Previsão: “irá chover amanhã”;
Senão Previsão: “amanhã o dia será sem chuvas”;
- Escrever código em Python para ler as variáveis, mostrar os seus valores no console;
- Mostrar a previsão do tempo para o dia seguinte, simulando algumas possibilidades.
Created on Fri Aug 27 11:53:04 2021

@author: Renato
"""
# Leitura das variáveis
temperatura = float(input('Digite a temperatura ºC: '))
umidade = int(input('Digite a % da Umidade Relativa do Ar: '))
# Determinação da previsão do tempo
if temperatura >= 28 and umidade >= 50:
    previsão = 'irá chover amanhã.'
else:
    previsão = 'amanhã o dia será sem chuvas.'
# Exibição dos resultados
print()
print('*' * 10, 'Previsão do tempo', '*' * 10)
print(f'''Dadas as leituras:
Temperatura {temperatura:.1f}ºC
Umidade Relativa do Ar {umidade}%\n
A previsão do tempo é de que
{previsão}''')


"""
A solution to reddit's /r/dailyprogrammer challenge #165 found here:
http://www.reddit.com/r/dailyprogrammer/comments/278ptv/642014_challenge_165_intermediate_ascii_maze/

Author: Tom Faris <ta.faris@gmail.com>
"""
import sys

class MazeObject(object):

    def __init__(self, maze, x, y, token=None):
        self.maze = maze
        self.position = (x, y)
        self.token = token

    def can_move_to(self, obj):
        pass

    def can_pass(self):
        return False

    def is_goal(self):
        return False

    def __str__(self):
        return self.token or ''

class Wall(MazeObject):
    """
    Walls are impassible (go figure).
    """

class Room(MazeObject):
    """
    Rooms can be moved through.
    """
    def can_pass(self):
        return True

class Start(Room):
    """
    The maze starts here!
    """

class End(Room):
    """
    The maze ends here!
    """
    def is_goal(self):
        return True

tokens = {
    '#': Wall,
    ' ': Room,
    'S': Start,
    'E': End
}

class Maze(dict):
    up, right, down, left = (0, -1), (1, 0), (0, 1), (-1, 0)
    dirs = (up, right, down, left)

    def add(self, maze_obj):
        self[maze_obj.position] = maze_obj

    def get_relative(self, from_obj, direction):
        """
        Get the next maze object in the specified direction, relative
        to the specified position.
        """
        pos = (
            from_obj.position[0] + direction[0],
            from_obj.position[1] + direction[1]
        )
        # Use an impassible maze object as default if there's
        # nothing there.
        return self.get(pos, MazeObject(self, *pos))

    def navigate(self):
        """
        Navigate the maze. Returns a list of MazeObjects defining the
        path through the maze.
        """
        start = filter(lambda m: isinstance(m, Start), self.values())
        if start:
            path = self._next_move(None, start[0], list())
            if path:
                path.reverse()  # Path comes back in reverse order
                return path
            else:
                print("I can't find the way out! This maze has no exit that I can get to.")
        else:
            print("I can't find the way in! This maze has no start.")

    def _next_move(self, last, current, path):
        """
        Determine the next move to take from the current position, as
        arrived to from the last position, and entire current path
        list.
        """
        if current.is_goal():
            # Found the end
            path.append(current)
            return path
        else:
            for dir in Maze.dirs:
                next = self.get_relative(current, dir)
                if next != last and next.can_pass():
                    next_moves = list(path)
                    end_found = self._next_move(current, next, next_moves)
                    if isinstance(end_found, list):
                        end_found.append(current)
                        return end_found
        return False

    def print_maze(self, path=None):
        """
        Print the maze, optionally marking up the list of MazeObjects.
        """
        # Sort keys by row, then column, before printing
        s = ''
        w = 0
        # Don't draw path over start and end
        preserve_token = (Start, End)
        for pos in sorted(sorted(self.keys(), key=lambda p:p[0]), key=lambda p:p[1]):
            if w == self.width:
                w = 0
                s += '\n'
            r = self[pos]
            s += '*' if path and type(r) not in preserve_token and r in path else str(self[pos])
            w += 1
        print(s)

def parse_maze(filepath):
    """
    Parse the specified maze file. Returns a Maze instance.
    """
    maze = Maze()
    with open(filepath) as maze_file:
        w, h = maze_file.next().split(' ')
        maze.width = int(w)
        maze.height = int(h)
        x, y = 0, 0
        for line in maze_file:
            for token in line.replace('\r', '').replace('\n', ''):
                maze.add(tokens.get(token, MazeObject)(maze, x, y, token=token))
                x += 1
            x = 0
            y += 1
    return maze

if __name__ == '__main__':
    sys.setrecursionlimit(99999)  # For big mazes...
    maze_file = sys.argv[1]
    m = parse_maze(maze_file)
    path = m.navigate()

    print('Maze:')
    m.print_maze()
    print('')
    print('Solved:')
    m.print_maze(path=path)

Challenge #165 [Intermediate] ASCII Maze Master/challenge165.py


import datetime

from rating_movies.models import Actor
from rating_movies.forms import MovieForm, ActorDirectorForm
from rating_movies.services.crud import repositories, crud_utils, custom_validators
from rating_movies.services.crud.create import create_other_sources_rating
from rating_movies.services.crud.read import get_movie_by_parameters, get_other_sources_rating

def update_movie(form: MovieForm) -> bool:
    """Movie update"""
    repository = repositories.MovieRepository()
    movie_validator = custom_validators.MovieValidator(form=form, repository=repository)

    if movie_validator.can_be_saved():
        is_updated: bool = repository.update_obj(obj=form)
        if is_updated:
            update_movie_other_sources_rating(movie_cleaned_data=form.cleaned_data)
            return True
    return False

def update_actor_director(form: ActorDirectorForm) -> bool:
    """Actor/director update"""
    repository = repositories.ActorDirectorRepository()
    actor_director_validator = custom_validators.ActorDirectorValidator(form=form, repository=repository)

    if actor_director_validator.can_be_saved():
        return repository.update_obj(obj=form)
    return False

def update_movie_other_sources_rating(movie_cleaned_data: dict) -> None:
    """Other sources rating update"""
    title = movie_cleaned_data.get("title", "")
    world_premiere = movie_cleaned_data.get("world_premiere", datetime.date.today())
    movie_object = get_movie_by_parameters(title=title, world_premiere=world_premiere)

    if movie_object:
        if not get_other_sources_rating(movie=movie_object):
            create_other_sources_rating(title=title, movie=movie_object)

def update_actor_director_age(actor_director: Actor) -> None:
    """Update actor/directors age"""
    repository = repositories.ActorDirectorRepository()
    current_age = crud_utils.calculate_age(birth_date=actor_director.birth_date, death_date=actor_director.death_date)
    actor_director.age = current_age
    repository.update_obj(actor_director)


def char_len(s):
    assert s[0] == '"', "Unexpected first string char"
    assert s[-1] == '"', "Unexpected last string char"

    s = s[1:-1]

    str_length = len(s)
    length = 0
    index = 0
    while index < str_length:
        if s[index] == "\\":
            index += 1
            if s[index] == "x":
                index += 2
        index += 1
        length += 1
    return length

def char_len2(s):
    assert s[0] == '"', "Unexpected first string char"
    assert s[-1] == '"', "Unexpected last string char"

    length = len(s)
    length += 2  # initial and trailing quotes
    length += s.count('"') + s.count("\\")

    return length

def puzzle1():
    data = "tasks/2015/data/day8.txt"

    total = 0
    with open(data, "r") as f:
        for line in f.readlines():
            line = line.strip()
            total += len(line)
            total -= char_len(line)
    print(total)

def puzzle2():
    data = "tasks/2015/data/day8.txt"

    total = 0
    with open(data, "r") as f:
        for line in f.readlines():
            line = line.strip()
            total += char_len2(line)
            total -= len(line)
    print(total)


import paddle
import paddle.nn as nn
import paddle.nn.functional as F

import copy
import numpy as np
import math

class VisionTransformerUpHead(nn.Layer):
    """VisionTransformerUpHead

    VisionTransformerUpHead is the decoder of SETR-PUP, Ref https://arxiv.org/pdf/2012.15840.pdf

    Reference:
        Sixiao Zheng, et al. *"Rethinking Semantic Segmentation from a Sequence-to-Sequence Perspective with Transformers"*
    """

    def __init__(self, embed_dim=1024, num_conv=1, num_upsample_layer=1,
            conv3x3_conv1x1=True, align_corners=False, num_classes=60):
        super(VisionTransformerUpHead, self).__init__()
        self.num_classes = num_classes
        self.align_corners = align_corners
        self.num_conv = num_conv
        self.num_upsample_layer = num_upsample_layer
        self.conv3x3_conv1x1 = conv3x3_conv1x1

        norm_bias_attr = paddle.ParamAttr(initializer=paddle.nn.initializer.Constant(0.0))
        self.norm = nn.LayerNorm(embed_dim, epsilon=1e-06, weight_attr=self.get_norm_weight_attr(), bias_attr=norm_bias_attr)

        if self.num_conv == 2:
            if self.conv3x3_conv1x1:
                self.conv_0 = nn.Conv2D(embed_dim, 256, 3, stride=1, padding=1, bias_attr=True)
            else:
                self.conv_0 = nn.Conv2D(embed_dim, 256, 1, stride=1, bias_attr=True)
            self.conv_1 = nn.Conv2D(256, self.num_classes, 1, stride=1)
            self.syncbn_fc_0 = nn.SyncBatchNorm(256, weight_attr=self.get_norm_weight_attr(), bias_attr=norm_bias_attr)

        elif self.num_conv == 4:
            self.conv_0 = nn.Conv2D(embed_dim, 256, kernel_size=3, stride=1, padding=1)
            self.conv_1 = nn.Conv2D(256, 256, kernel_size=3, stride=1, padding=1)
            self.conv_2 = nn.Conv2D(256, 256, kernel_size=3, stride=1, padding=1)
            self.conv_3 = nn.Conv2D(256, 256, kernel_size=3, stride=1, padding=1)
            self.conv_4 = nn.Conv2D(256, self.num_classes, kernel_size=1, stride=1)
            self.syncbn_fc_0 = nn.SyncBatchNorm(256, weight_attr=self.get_norm_weight_attr(), bias_attr=norm_bias_attr)
            self.syncbn_fc_1 = nn.SyncBatchNorm(256, weight_attr=self.get_norm_weight_attr(), bias_attr=norm_bias_attr)
            self.syncbn_fc_2 = nn.SyncBatchNorm(256, weight_attr=self.get_norm_weight_attr(), bias_attr=norm_bias_attr)
            self.syncbn_fc_3 = nn.SyncBatchNorm(256, weight_attr=self.get_norm_weight_attr(), bias_attr=norm_bias_attr)

    def get_norm_weight_attr(self):
        return paddle.ParamAttr(initializer=paddle.nn.initializer.Constant(value=1.0))

    def to_2D(self, x):
        n, hw, c = x.shape
        h = w = int(math.sqrt(hw))
        x = x.transpose([0, 2, 1]).reshape([n, c, h, w])
        return x

    def forward(self, x):
        x = self.norm(x)
        # (b,hw,c) -> (b,c,h,w)
        x = self.to_2D(x)
        up4x_resolution = [ 4*item for item in x.shape[2:]]
        up16x_resolution = [ 16*item for item in x.shape[2:]]
        if self.num_conv == 2:
            if self.num_upsample_layer == 2:
                x = self.conv_0(x)
                x = self.syncbn_fc_0(x)
                x = F.relu(x)
                x = F.interpolate(x, up4x_resolution, mode='bilinear', align_corners=self.align_corners)
                x = self.conv_1(x)
                x = F.interpolate(x, up16x_resolution, mode='bilinear', align_corners=self.align_corners)
            elif self.num_upsample_layer == 1:
                x = self.conv_0(x)
                x = self.syncbn_fc_0(x)
                x = F.relu(x)
                x = self.conv_1(x)
                x = F.interpolate(x, up16x_resolution, mode='bilinear', align_corners=self.align_corners)
        elif self.num_conv == 4:
            if self.num_upsample_layer == 4:
                x = self.conv_0(x)
                x = self.syncbn_fc_0(x)
                x = F.relu(x)
                up2x_resolution = [ 2*item for item in x.shape[2:]]
                x = F.interpolate(x, up2x_resolution, mode='bilinear', align_corners=self.align_corners)
                x = self.conv_1(x)
                x = self.syncbn_fc_1(x)
                x = F.relu(x)
                up2x_resolution = [ 2*item for item in x.shape[2:]]
                x = F.interpolate(x, up2x_resolution, mode='bilinear', align_corners=self.align_corners)
                x = self.conv_2(x)
                x = self.syncbn_fc_2(x)
                x = F.relu(x)
                up2x_resolution = [ 2*item for item in x.shape[2:]]
                x = F.interpolate(x, up2x_resolution, mode='bilinear', align_corners=self.align_corners)
                x = self.conv_3(x)
                x = self.syncbn_fc_3(x)
                x = F.relu(x)
                x = self.conv_4(x)
                up2x_resolution = [ 2*item for item in x.shape[2:]]
                x = F.interpolate(x, up2x_resolution, mode='bilinear', align_corners=self.align_corners)
        return x


#!/usr/bin/env python
import sys
from gcSupport import *

(workDir, nJobs, jobList) = getWorkJobs(sys.argv[1:])
for jobNum in sorted(jobList):
	files = getFileInfo(workDir, jobNum, lambda retCode: retCode == 0)
	if files:
		for (hash, name_local, name_dest, pathSE) in files:
			pathSE = pathSE.replace("file://", "").replace("dir://", "")
			print("%s  %s/%s" % (hash, pathSE, name_dest))


""" O(nw) 8028ms(beats 5.12%), 424.8MB(beats5.36%) """

from typing import List, Iterable, Optional, Tuple
from dataclasses import dataclass, field

def solve(words: List[str]) -> List[List[int]]:
    postfix_tabs = []
    trie = PostfixTrie()

    for i, word in enumerate(words):
        prefix, postfix = prefix_postfix_palindrome_table(word)

        trie.add_word(i, word, prefix)
        postfix_tabs.append(postfix)

    ans = []

    for i, word in enumerate(words):
        pairs = trie.search_palindrome_pairs(i, word, postfix_tabs[i])

        ans.extend(pairs)

    return ans

class PostfixTrie:
    def __init__(self) -> None:
        self.root: TrieNode = TrieNode()

    def add_word(self, word_i: int, word: str, prefix_tab: List[bool]):
        root = self.root

        if prefix_tab and prefix_tab[-1]:
            root.rest_palindromes.append(word_i)

        for i in reversed(range(0, len(word))):
            cv = IDX[word[i]]

            if root.children[cv] is None:
                root.children[cv] = TrieNode()

            root: TrieNode = root.children[cv]

            if i > 0 and prefix_tab[i-1]:
                root.rest_palindromes.append(word_i)

        root.word_index = word_i

    def search_palindrome_pairs(
        self,
        word_i: int,
        word: str,
        postfix_tab: List[bool]
    ) -> List[List[int]]:
        pairs = []
        root = self.root
        i = 0

        while True:
            if i == len(word):
                if root.word_index is not None and word_i != root.word_index:
                    pairs.append([word_i, root.word_index])

                pairs.extend(map(lambda j: [word_i, j], root.rest_palindromes))

                break

            idx = IDX[word[i]]

            if root.word_index is not None and postfix_tab[i]:
                pairs.append([word_i, root.word_index])

            if root.children[idx] is None:
                break

            root: TrieNode = root.children[idx]
            i += 1

        return pairs

class TrieNode:
    pass

@dataclass
class TrieNode:
    word_index: Optional[int] = field(default=None)
    rest_palindromes: List[int] = field(default_factory=lambda: [])
    children: List[Optional[TrieNode]] = field(default_factory=lambda: [None] * 26)

BASE = ord('a')

IDX = {}

for i in range(0, 26):
    IDX[chr(BASE + i)] = i

def prefix_postfix_palindrome_table(s: str) -> Tuple[List[int], List[int]]:
    d1 = compute_d1(s)
    d2 = compute_d2(s)
    n = len(s)

    prefix = [False] * n
    postfix = [False] * n

    for i, r in enumerate(d1):
        rl = i-r+1
        rr = i+r-1

        if rl == 0:
            prefix[rr] = True
        if rr == n-1:
            postfix[rl] = True

    for i, r in enumerate(d2):
        if r == 0:
            continue

        rl = i-r
        rr = i+r-1

        if rl == 0:
            prefix[rr] = True
        if rr == n-1:
            postfix[rl] = True

    return prefix, postfix

def compute_d1(s: str) -> List[int]:
    """ return (i, r) """

    n = len(s)

    d1 = [1] * n

    rl = 0  # rightmost left
    rr = 0  # rightmost right

    for i in range(1, n-1):
        if i < rr:
            j = rr - i + rl

            if d1[j] < j - rl + 1:
                d1[i] = d1[j]
                continue
            else:
                r = j - rl + 1
        else:
            r = 1

        while i+r-1 < n-1 and i-(r-1) > 0 and s[i+r] == s[i-r]:
            r += 1

        if i+r-1 > rr:
            rr = i+r-1
            rl = i-(r-1)

        d1[i] = r

    return d1

def compute_d2(s: str) -> List[int]:
    """ return (i, r) """

    n = len(s)

    d2 = [0] * n

    rl = 0  # rightmost left
    rr = 0  # rightmost right

    for i in range(1, n):
        if i < rr:
            j = rr - i + rl + 1

            if d2[j] < j - rl:
                d2[i] = d2[j]
                continue
            else:
                r = j - rl
        else:
            r = 0

        while i+r-1 < n-1 and i-r > 0 and s[i-r-1] == s[i+r]:
            r += 1

        if i+r-1 > rr:
            rr = i+r-1
            rl = i-r

        d2[i] = r

    return d2

if __name__ == '__main__':
    def test(input, expect):
        found = solve(input)

        expect.sort()
        found.sort()

        assert expect == found, f"expect: {expect}, however found: {found}"

    test(["abcd", "dcba", "lls", "s", "sssll"],
         [[0, 1], [1, 0], [3, 2], [2, 4]])
    test(["bat", "tab", "cat"], [[0, 1], [1, 0]])
    test(["a", ""], [[0, 1], [1, 0]])


# -*- coding: utf-8 -*-
from whoosh.index import create_in,open_dir
from whoosh.fields import *
import os.path
from whoosh.qparser import QueryParser
from whoosh.query import *
from whoosh import index
import sys,traceback
from django.template import Context, RequestContext
from django.shortcuts import render_to_response

class Result():

    def __init__(self, title, url, date, highlights, keywords):
        self.title = title
        self.url = url
        self.date = date
        self.highlights = highlights
        self.keywords = keywords

def search(request):
    hits = []
    results = []
    query = request.GET.get('q', None)
    newspaper = request.GET.get('newspaper', None)
    if newspaper is not None:
        index_dir = "C:/Django Projects/searcher/modules/index" + newspaper
        ix = index.open_dir(index_dir)
        searcher = ix.searcher()
        if query is not None and query != u"":
            query = query.replace('+', ' AND ').replace(' -', ' NOT ')
            parser = QueryParser("content", schema=ix.schema)
            try:
                qry = parser.parse(query)
            except:
                qry = None
            if qry is not None:
                hits = searcher.search(qry)

        for hit in hits:
            title = hit['title']
            url = hit['url']
            date = hit['date']
            highlights = hit.highlights("content")
            keywords_list = [keyword for keyword, score in searcher.key_terms_from_text("content", hit['content'])]
            keywords = ", ".join(keywords_list)
            results.append(Result(title,url,date,highlights,keywords))

    variables = RequestContext(request, {
        'query': query,
        'hits': results
    })
    return render_to_response('search.html', variables)


import torch
import torch.nn as nn
import torch.nn.functional as F

from starter_code.networks import MLP, CNN

class SimpleValueFn(nn.Module):
    def __init__(self, state_dim, hdim):
        super(SimpleValueFn, self).__init__()
        self.value_head = MLP(dims=[state_dim, *hdim, 1])

    def forward(self, state):
        state_values = self.value_head(state)
        return state_values

class SimpleQFn(nn.Module):
    def __init__(self, state_dim, action_dim, hdim):
        super(SimpleQFn, self).__init__()
        self.Q_head = MLP(dims=[state_dim+action_dim, *hdim, 1])

    def forward(self, state, action):
        raise NotImplementedError('need to concatenate action and state')
        Q_values = self.Q_head(state)
        return Q_values

class CNNValueFn(nn.Module):
    def __init__(self, state_dim):
        super(CNNValueFn, self).__init__()
        self.encoder = CNN(*state_dim)
        self.decoder = nn.Linear(self.encoder.image_embedding_size, 1)

    def forward(self, state):
        state_values = self.decoder(self.encoder(state))
        return state_values

class CNNQFn(nn.Module):
    def __init__(self, state_dim, action_dim, hdim=16):
        """
            hdim is for embedding action.
            So if the action is discrete hdim=16 should be large enough
        """
        super(CNNQFn, self).__init__()
        self.encoder = CNN(*state_dim)
        self.action_encoder = nn.Linear(action_dim, hdim)
        self.decoder = nn.Linear(self.encoder.image_embedding_size+hdim, 1)

    def forward(self, state, action):
        image_encoded = self.encoder(state)
        action_encoded = F.relu(self.action_encoder(action))
        Q_values = self.decoder(
            torch.cat((image_encoded, action_encoded), dim=-1))
        return Q_values

class ValueFn(nn.Module):
    def __init__(self, state_dim, hidden_size=(128, 128), activation='relu'):
        super().__init__()
        if activation == 'tanh':
            self.activation = torch.tanh
        elif activation == 'relu':
            self.activation = torch.relu
        elif activation == 'sigmoid':
            self.activation = torch.sigmoid

        self.affine_layers = nn.ModuleList()
        last_dim = state_dim
        for nh in hidden_size:
            self.affine_layers.append(nn.Linear(last_dim, nh))
            last_dim = nh

        self.value_head = nn.Linear(last_dim, 1)
        self.value_head.weight.data.mul_(0.1)
        self.value_head.bias.data.mul_(0.0)

    def forward(self, x):
        for affine in self.affine_layers:
            x = self.activation(affine(x))

        value = self.value_head(x)
        return value


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @author: 'orleven'

from lib.utils.connect import ClientSession
from lib.core.enums import VUL_LEVEL
from lib.core.enums import VUL_TYPE
from lib.core.enums import SERVICE_PORT_MAP
from script import Script, VUL_TYPE, VUL_LEVEL

class POC(Script):
    def __init__(self, target=None):
        self.service_type = SERVICE_PORT_MAP.SOLR
        self.name = 'solr unauth'
        self.keyword = ['unauth', 'solr']
        self.info = 'solr unauth'
        self.type = VUL_TYPE.UNAUTH
        self.level = VUL_LEVEL.MEDIUM
        Script.__init__(self, target=target, service_type=self.service_type)

    async def prove(self):
        await self.get_url()
        if self.base_url:
            async with ClientSession() as session:
                for url in [self.base_url , self.base_url+"solr/"]:
                    async with session.get(url=url) as res:
                        if res and res.status == 200:
                            text = await res.text()
                            if 'Solr Admin' in text and 'Dashboard' in text:
                                self.flag = 1
                                self.res.append({"info": url, "key": "solr unauth"})
                                break


from keras.utils import np_utils
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense

# Data
(x_train, y_train), (x_test, y_test) = mnist.load_data()

print(x_train.shape, y_train.shape, x_test.shape, y_test.shape, sep="\n")

x_train = x_train.reshape([-1, 784]).astype('float32') / 255.
x_test = x_test.reshape([-1, 784]).astype('float32') / 255.

y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)

# Model
model = Sequential()
model.add(Dense(256, activation='relu'))
model.add(Dense(256, activation='relu'))
model.add(Dense(256, activation='relu'))
model.add(Dense(10, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])

# Train
model.fit(x_train, y_train, epochs=5, batch_size=32, verbose=1)
_, accuracy = model.evaluate(x_test, y_test)  # return cost, accuracy
print('Accuracy:', accuracy)
model.summary()


from string import printable
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
import time

options = Options()
options.headless = True
options.add_argument("--window-size=1920,1080")
driver = webdriver.Chrome(options=options)
driver.get('https://uk.shop.allpressespresso.com/')
driver.maximize_window()  # zwiekszamy wielkosc okna

time.sleep(1)

cookies = driver.find_element(by=By.XPATH, value='//*[@id="ccc-notify-accept"]')
cookies.click()

descriptions = []

description = driver.find_element(by=By.XPATH, value='//*[@id="shopify-section-coffee-section"]/div/div/div[2]/div[1]/div/div/form/div[2]/p').text
descriptions.append(description)

desctiption2 = driver.find_element(by=By.XPATH, value='//*[@id="shopify-section-coffee-section"]/div/div/div[2]/div[2]/div/div/form/div[2]/p').text
descriptions.append(desctiption2)

print(descriptions)

driver.quit()

class Scraper():
    def __init__(self) -> None:
        self.driver = webdriver.Chrome()

    def get_descriptions(self):
        descriptions = []

        description = driver.find_element_by_xpath('//*[@id="shopify-section-coffee-section"]/div/div/div[2]/div[1]/div/div/form/div[2]/p').text
        descriptions.append(description)

        description2 = driver.find_element_by_xpath('//*[@id="shopify-section-coffee-section"]/div/div/div[2]/div[2]/div/div/form/div[2]/p').text
        descriptions.append(description2)

        return descriptions


# -*- coding: utf-8 -*-
"""
Created on Fri Feb 17 12:39:08 2017

@author: Thomas PESNEAU
"""

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import doctest
import math
import scipy.ndimage.filters as filters
from PIL import Image
from importlib import reload

## Open test image
im_test = Image.open("../../data/test_sift.jpg")
image = np.array(im_test)

## Test
import SIFT
nb_levels = 5
k = 1.1
sigma = 1. / math.sqrt(2)
t_contrast = 1.2
t_edge = 10
wsize = 8

#%%
image = SIFT.rgb2gray(image)
Oct = SIFT.Octave(image, nb_levels, k, sigma)
#%%
print("Build octave")
Oct.build_octave()
for i in range(nb_levels):
    plt.figure()
    plt.imshow(Oct.octave[:,:,i],cmap='gray')
    plt.title("scale {}".format(i))
#%%
print("Log approximation")
Oct.log_approx()
for i in range(nb_levels-1):
    plt.figure()
    plt.imshow(Oct.DOG[:,:,i],cmap='gray')
    plt.title("DOG {}".format(i))
#%%
print("Extrema")
Oct.find_extrema()
#%%
print("Remove bad keypoints")
Oct.rm_bkeys(t_contrast, t_edge)
#%%
print("Assign orientation")
Oct.assign_orientation()
#%%
print("Generate features")
Oct.generate_features(wsize)

#%% Compute


# Skyscraper Project - 2- Scales + Button - Python Code - Elizabeth Tweedale
from tkinter import *

def newSkyscraper():
    winW = scaleWinW.get()                                                          # Get the number of windows wide from the scale
    winH = scaleWinH.get()                                                          # Get the number of windows high from the scale
    w = scaleW.get()                                                                # Get the width of the windows from the scale
    h = scaleH.get()                                                                # Get the height of the windows from the scale
    gap = scaleGap.get()                                                            # Get the window gap from the scale

    myBuilding.delete("all")                                                        # This will clear the drawing before drawing new squares

    # Draw main building
    myBuilding.create_rectangle(gap,gap,(winW+2)*gap+winW*w,(winH+2)*gap+winH*h,    # startX(left),starty(top),finishX(right),finishY(bottom)
                                        outline="gray", fill="gray")                # outline and fill colours
    # Draw windows
    for i in range(winW):
        for j in range(winH):
            myBuilding.create_rectangle(((w+gap)*i+2*gap),                          # startX(left)
                                        ((h+gap)*j+2*gap),                          # startY(top)
                                        ((w+gap)*i+(2*gap+w)),                      # finsihX(right)
                                        ((h+gap)*j+(2*gap+h)),                      # finishY(bottom)
                                        outline="black",fill="white")               # outline, fill colours
                                                                                # Try using different colours such as "blue" or "red"
    myBuilding.pack(fill=BOTH, expand=1)                                            # Add ALL of the rectangles to your Canvas

""" Main Program """
root = Tk()                                                                         # Set up Tkinter
myBuilding = Canvas(root, width=500, height=500)                                    # Set up Canvas
root.title("Skyscraper")                                                            # Set the title of your screen
myBuilding.pack()                                                                   # Pack adds everything to the Tkinter Canvas

""" Draw Scales """
scaleWinW = Scale(root, from_=5, to=30, orient=HORIZONTAL, label= "Windows Wide")   # Create a scale for the number of windows wide
scaleWinW.pack()                                                                    # Add it to the Canvas
# HINT - you can copy the above two lines for the next 4 scales and simply change the variable names - think of it like "SPOT THE DIFFERENCE"
scaleWinH = Scale(root, from_=5, to=30, orient=HORIZONTAL, label= "Windows High")   # Create a scale for the number of windows high
scaleWinH.pack()                                                                    # Add it to the Canvas

scaleW = Scale(root, from_=5, to=30, orient=HORIZONTAL, label= "Window Width")      # Create a scale for the windows' width
scaleW.pack()                                                                       # Add it to the Canvas

scaleH = Scale(root, from_=5, to=30, orient=HORIZONTAL, label= "Window Height")     # Create a scale for the windows' height
scaleH.pack()                                                                       # Add it to the Canvas

scaleGap = Scale(root, from_=2, to=20, orient=HORIZONTAL, label= "Window Gap")      # Create a scale for the size of the gap between windows...
scaleGap.pack()                                                                     # Did you notice the smaller numbers for the from_ and to?

""" Draw Button """
button = Button(root, text="Draw Skyscraper", command=newSkyscraper)                # Create a button to draw the skyscraper
button.pack()                                                                       # Add it to the Canvas

root.mainloop()                                                                    # start the main loop


#HomIEQ Visual Engine Version 0.1
#Steven Tanner McCullough
#Code to manage and run the visual aspects of this device.
#Library Import
import pygame

#Internal Library import
from sensor import *
from agent import *
from gui import *
from player import *
from plot import *

#Custom Functions
#Define timer object to keep time-----------------------------------------------
class Timer:
	def __init__(self,length):
		self.i=0
		self.length=length
		self.lapsed=False
		self.time = [0,0,0] #To record Runtime to data, [seconds,minutes,hours]
		self.logic = [0,0,0] #To be used for logic timing, [ticks,seconds,minutes]
	def update_time(self,dt):
		if(self.lapsed):
			self.lapsed=False
			print("Timer has reset")
			#60ticks/s
		#Count Ticks
		if(self.logic[0]<60):
			self.logic[0]+=dt
			#60ticks/s
		else:
			#Increase second count every 60 ticks
			#Reset Tick counter
			self.logic[0]=0
			#Increase second count
			if(self.logic[1]<60):
				self.logic[1]+=1 #Increase second count
				self.time[0]+=1 #Increase second count
			else:
				self.logic[1]=0 #Reset second count at 1 minute
				self.time[0]=0 #Reset second count at 1 minute

				#If logic timer is less than set tigger time than increase
				#Once trigger time is met, bool is triggered
				if(self.logic[2]<self.length):

					self.logic[2]+=1 #Increase minute count
					#print(self.logic[2])
				else:
					self.logic[2]=0 #Reset minute count at specified length
					self.lapsed=True
					print("Timer has lapsed")

				if(self.time[1]<60):
					self.time[1]+=1 #Increase minute count
				else:
					self.time[1]=0 #Reset minute count at 1 hour

					self.time[2]+=1 #Increase Hour count every 60 Minutes

#-------------------------------------------------------------------------------
#Defining Variables and Objects
timer =  Timer(1)
clock = pygame.time.Clock()
pygame.init()
res=(800,400)
screen = pygame.display.set_mode(res)

splash = pygame.image.load('graphics/splash.png').convert()
screen.blit(pygame.transform.scale(splash,res),(0,0))
pygame.display.update()

bg = pygame.transform.scale(pygame.image.load('graphics/map.png').convert(),res)

dark = pygame.Surface(res)
screen.blit(pygame.transform.scale(splash,res),(0,0))
time.sleep(0.5)
pygame.display.update()
dark.set_alpha(255)
dark.fill((0,0,0))
screen.blit(dark,(0,0))
bigfont = pygame.font.Font('font/Pixeltype.ttf',75)
text = bigfont.render("HomIEQ initializing...", False, (255,255,255))
screen.blit(text,(25,300))

pygame.display.update()

player = Player(screen)
sensor = Sensor()
agent = Agent()
player.state=1
player.subject=0

i=0
while(i<200):
	#Run Ingame Clock for event capture and visual logic
	dt = clock.tick(60) * 0.001 * 60

	#Run logical and Datakeeping clock for time
	timer.update_time(dt)

	agent.update(sensor.sensor_read())
	agent.comfort_check()
	agent.calc()
	i+=dt
	#print(sensor.s_data)
	dark.fill((255,255,255))
	screen.blit(pygame.transform.scale(dark,(int(i*1.5),50)),(500,300))
	pygame.display.update()
#print(agent.sensor_metrics)

compiled_df=pd.DataFrame()

while(True):
	#Run Ingame Clock for event capture and visual logic
	dt = clock.tick(60) * 0.001 * 60

	#Run logical and Datakeeping clock for time
	timer.update_time(dt)

	#Send Background pixels to screen
	screen.blit(pygame.transform.scale(bg,res),(0,0))

	#If timer lapses, then logic performs its tasks once
	if(timer.lapsed):
		agent.update(sensor.sensor_read())
		time.sleep(0.25)
		print("sleepy")
		agent.calc()
		agent.comfort_check()

		compiled_df = pd.concat([compiled_df , parse_to_df(sensor.s_data,agent.limits,
			timer.time[2],timer.time[1],player.response_given)] , ignore_index=True)
		#print(compiled_df)
		compiled_df.to_csv("output.csv")
		player.response_given=0
		#print(agent.conversation)
		if player.state==1:
			player.state=0
		if agent.conversation>0:
			player.subject=agent.conversation
			print(player.subject)
			agent.conversation=0
			player.state=1

	#For loop used to search through events for keyboard presses
	#Also works to grab mouse and touch clicks and presses
	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			pygame.quit()
			exit()
		elif event.type == pygame.MOUSEBUTTONDOWN and event.button:
			mouse_pos = pygame.mouse.get_pos()
			touch = False
		elif event.type == pygame.MOUSEBUTTONUP and event.button:
			touch = True
		keys = pygame.key.get_pressed()

	length = len(agent.sensor_metrics)
	#print(length)
	start = length-60
	if start < 0:
		start = 0

	t_graph = plot(agent.sensor_metrics,(133,115),'Temperature',(0,0),agent.limits.temp_offset[0],agent.limits.temp_size[0],(0,0,0),(start,length)," C")
	rh_graph = plot(agent.sensor_metrics,(133,115),'Humidity',(133,0),agent.limits.hum_offset[0],agent.limits.hum_size[0],(0,0,0),(start,length)," %")
	co2_graph = plot(agent.sensor_metrics,(134,115),'CO2',(266,0),agent.limits.co2[0],0,(0,0,0),(start,length)," ppm")
	pm_graph = plot(agent.sensor_metrics,(133,115),'PM25',(400,0),agent.limits.pmhigh[0],0,(0,0,0),(start,length)," ug/m3")
	sound_graph = plot(agent.sensor_metrics,(133,115),'Audio',(533,0),agent.limits.sound[0],0,(0,0,0),(start,length)," dB")
	light_graph = plot(agent.sensor_metrics,(134,115),'Light',(666,0),agent.limits.light[0],0,(0,0,0),(start,length)," lux")
	if(player.state == 0):
		t_graph.drawplot(screen)
		rh_graph.drawplot(screen)
		co2_graph.drawplot(screen)
		pm_graph.drawplot(screen)
		sound_graph.drawplot(screen)
		light_graph.drawplot(screen)

	player.update(dt)
	pygame.display.update()


class Solution(object):
    def calPoints(self, ops):
        out = []
        for i in ops:
            if i.lstrip('-').isdigit():
                out.append(int(i))
            if i == 'C':
                out.pop()
            if i == 'D':
                out.append(2 * out[-1])
            if i == '+':
                out.append(out[-1] + out[-2])
        return sum(out)

    def calPoints_daily(self, ops: List[str]) -> int:  # 84.23% 74.69%
        stack = []
        for operation in ops:
            if operation == '+':
                stack.append(stack[-2]+stack[-1])
            elif operation == 'D':
                stack.append(stack[-1]*2)
            elif operation == 'C':
                stack.pop()
            else:
                stack.append(int(operation))
        return sum(stack)

    def calPoints_best_memory(self, ops: List[str]) -> int:
        if not ops:
            return 0
        stack = []
        for op in ops:
            if op.isdigit() or (op[0] == '-' and op[1:].isdigit()):
                if op[0] == '-':
                    stack.append(-int(op[1:]))
                else:
                    stack.append(int(op))
            elif op == 'C':
                stack.pop()
            elif op == 'D':
                new_value = stack[-1] * 2
                stack.append(new_value)
            elif op == '+':
                new_value = stack[-1] + stack[-2]
                stack.append(new_value)
        return sum(stack)

600 - 699/682 - Baseball Game/682 - Baseball Game.py


from django.shortcuts import render

# 视图层
# Create your views here.
from django.http import HttpResponse
from . import models

def index(request):
    # return HttpResponse("Hello, world. You're at the polls index.")
    # sqlLite
    # user = models.User.objects.get(pk=1)
    users = models.User.objects.all()
    return render(request,"index.html",{"key":"this is key-value","users":users})

def userById(request,userById):
    # return HttpResponse("Hello, world. You're at the polls index.")
    # sqlLite
    user = models.User.objects.get(pk=userById)
    return render(request,"index.html",{"key":"this is key-value","user":user})

def edit(request):
    # return HttpResponse("Hello, world. You're at the polls index.")
    # sqlLite
    # name = request.POST.get("name","测试添加")
    a = models.User.objects.create(userName="测试添加",title="测试标题")
    print("===",a)
    users = models.User.objects.all()

    user = models.User.objects.get(pk=4)
    user.title = "修改标题"
    user.userName = "修改名字"
    user.save()
    return render(request,"index.html",{"key":"this is key-value","users":users})


# -*- coding:utf-8 -*-
"""
5) 외장함수

"""""""""""""""""""""
####################
import sys
####################
"""""""""""""""""""""

	명령행에서 인수를 전달(sys.argv)

"""
print(sys.argv)
print('')
"""

	강제 스크립트 종료법(sys.exit)

"""
#sys.exit()
"""

	자신이 만든 모듈 불러서 쓰기(sys.path)

"""
sys.path.append('/var/www')
print(sys.path)
"""

"""""""""""""""""""""
####################
import pickle
####################
"""""""""""""""""""""

	객체를 그 상태 그대로 파일에 저장하고 싶을 때(pickle)

"""
f = open("test", 'wb')
data = {1: 'python', 2: 'you need'}
pickle.dump(data, f)
f.close()

f = open("test", 'rb')
data = pickle.load(f)
print(data)
f.close()
print('')
# 딕셔너리 객체를 이용하였지만 어떤 자료형이든지 상관없다.
"""

"""""""""""""""""""""
####################
#import io			# ver3
import StringIO	# ver2
####################
"""""""""""""""""""""

	파일 흉내내기(StringIO) : StringIO는 파일처럼 취급되는 객체를 만들어낸다.
							  단 실제 파일객체는 아니고 흉내를 낼 뿐이다.

"""
#f = io.StringIO()	# ver3
f = StringIO.StringIO()
f.write("life is too short")
value = f.getvalue()
print(value)
f.close()
print('')
"""

"""""""""""""""""""""
####################
import os
####################
"""""""""""""""""""""

	현재 내 시스템 환경변수값을 알고싶을 때는? (os.environ)

"""
print(os.environ)
print(os.environ['PATH'])
print('')
"""

	디렉토리에 대한 것들(os.chdir, os.getcwd)

"""
# 현재 디렉토리의 위치 변경
#os.chdir('/var/www')

# 현재 디렉토리의 위치 출력
print(os.getcwd())
print('')
"""

	시스템 명령(os.system, os.popen)

"""
# 시스템 명령어 사용
print(os.system('ls -al'))

# 시스템 명령어를 실행시킨 결과값을 읽기 모드 형태의 파일객체로 반환
files = os.popen('dir')
print(files.read())
files.close()
"""
기타 유용한 os 관련 함수
		함수					설명
os.mkdir(디렉토리)		디렉토리를 생성한다.
os.rmdir(디렉토리)		디렉토리를 삭제한다.단, 디렉토리가 비어있어야 삭제가 가능하다.
os.unlink(파일)		파일을 지운다.
os.rename(src, dst)	src라는 이름의 파일을 dst라는 이름으로 바꾼다.

"""""""""""""""""""""
####################
import shutil
####################
"""""""""""""""""""""

	파일 복사(shutil)
	shutil.copy(src, dst)

"""
shutil.copy('test', 'copy')
"""

"""""""""""""""""""""
####################
import glob
####################
"""""""""""""""""""""

	디렉토리에 있는 파일들을 리스트로 만들려면 (glob)
	glob(pathname) *, ?등의 메타문자를 써서 원하는 파일만을 읽어들일 수도 있다.

"""
print(glob.glob("/var/www/*"))
print('')
"""

"""""""""""""""""""""
####################
import tempfile
####################
"""""""""""""""""""""

	임시파일 (tempfile)
	tempfile.mktemp()는 중복되지 않는 임시파일의 이름을 만들어서 돌려준다.

	tempfile.TemporaryFile()은 임시적인 저장공간으로 사용될 파일 객체를 돌려준다.
	기본적으로 w+b 의 모드를 갖는다. 이 파일객체는 f.close()가 호출될 때 자동으로 사라지게 된다.

"""
# mktemp()
filename = tempfile.mktemp()
print(filename)

# TemporaryFile()
f = tempfile.TemporaryFile()
f.close()
print('')
"""

"""""""""""""""""""""
####################
import time
####################
"""""""""""""""""""""

	time.time : UTC(Universal Time Coordinated 협정 세계 표준시)를 이용하여
				  현재의 시간을 실수형태로 반환하여 주는 함수이다.
				  1970년 1월 1일 0시 0분 0초를 기준으로 지난 시간을 초단위로 돌려준다.

"""
print(time.time())
"""

	time.localtime : time.time()에 의해서 반환된 실수값을 이용해서
						년도, 달, 월, 시, 분, 초,.. 의 형태로 바꾸어 주는 함수이다.

"""
print(time.localtime(time.time()))
"""

	time.asctime : 위의 time.localtime에 의해서 반환된 터플 형태의 값을 인수로 받아서
					 알아보기 쉬운 날짜와 시간 형태의 값을 반환하여 주는 함수이다.
					 가장 자주 사용되는 시간관련 함수이다.

"""
print(time.asctime(time.localtime(time.time())))
"""

	time.ctime : time.asctime을 쉽게 쓰기 위함

"""
print(time.ctime())
"""

	time.strftime('출력할 형식포맷코드', time.localtime(time.time()))
		strftime 함수는 시간에 관계된 것을 세밀하게 표현할 수 있는 여러 가지 포맷코드를 제공해 준다.

포맷코드			설명								예(조금 이상한듯)
%a		요일 줄임말							Mon
%A		요일									Monday
%b		달 줄임말							Jan
%B		달									January
%c		날짜와 시간을 출력함					Mon Jan 20 21:05:23 2014
%d		날(day)								[00,31]
%H		시간(hour)-24시간 출력 형태			[00,23]
%I		시간(hour)-12시간 출력 형태			[01,12]
%j		1년 중 누적 날짜						[001,366]
%m		달									[01,12]
%M		분									[01,59]
%p		AM or PM							AM
%S		초									[00,61]
%U		1년 중 누적 주-일요일을 시작으로		[00,53]
%w		숫자로 된 요일						[0(일요일),6]
%W		1년 중 누적 주-월요일을 시작으로		[00,53]
%x		현재 설정된 로케일에 기반한 날짜 출력	06/01/01
%X		현재 설정된 로케일에 기반한 시간 출력	17:22:21
%Y		년도 출력							2001
%Z		시간대 출력							대한민국 표준시
%%		문자									%
%y		세기부분을 제외한 년도 출력			01
"""
print(time.strftime('%x', time.localtime(time.time())))
print(time.strftime('%c', time.localtime(time.time())))
print('')
"""

	time.sleep : 보통 루프 안에서 많이 쓰이는데 일정한 시간 간격을 주기 위해서 주로 쓰이게 된다.

"""
for i in range(3):
	print(i)
	time.sleep(0.1)
"""

"""""""""""""""""""""
####################
import calendar
####################
"""""""""""""""""""""

	파이썬에서 달력쓰기(calendar)

"""
# 한 해의 달력 모두 출력
print(calendar.calendar(2014))
#print(calendar.prcal(2014))	# 개행문자 등이 조금씩 다른듯

# 한 월의 달력만 출력
print(calendar.prmonth(2014, 1))

# 무슨 요일인지 출력(0:월요일 ~ 6:일요일
print(calendar.weekday(2014, 1, 19))

# (1일이 무슨 요일인지, 몇 일까지 있는지)
print(calendar.monthrange(2014,1))
print('')
"""

"""""""""""""""""""""
####################
import random
####################
"""""""""""""""""""""

	난수 발생시키기 (random)

"""
# 0 ~ 1.0 사이의 수
print(random.random())

# 1 ~ 10 사이의 수
print(random.randint(1,10))
"""

"""""""""""""""""""""
####################
#import _thread	# ver3
import thread		# ver2
####################
"""""""""""""""""""""

	파이썬에서의 쓰레드 (_thread)
	thread.start_new_thread(함수, (인자))
"""
'''
def say(msg):
	while 1:
		print(msg)
		time.sleep(1)

thread.start_new_thread(say, ('you',))
thread.start_new_thread(say, ('need',))
thread.start_new_thread(say, ('python',))
for i in range(100):
	print(i)
	time.sleep(0.1)
'''
"""

"""""""""""""""""""""
####################
import webbrowser
####################
"""""""""""""""""""""

	웹브라우저 실행시키기 (webbrowser)

"""
# 실행중인 웹브라우저에서 이동
webbrowser.open("http://www.google.com")
# 새로운 창에서 이동???
webbrowser.open_new("http://www.google.com")


from typing import List

from src.domain.agent import AgentRepository, Contract, ContractRepository
from src.logging import configure_logger
from src.repositories.agent import HttpAndFileAgentRepository
from src.repositories.contract import HttpContractRepository

def get_contracts(
        agent_repo: AgentRepository,
        contracts_repo: ContractRepository,
    ) -> List[Contract]:
    agent = agent_repo.get_agent()
    return agent.get_contracts(contracts_repo)

def accept_contract(
        agent_repo: AgentRepository,
        contracts_repo: ContractRepository,
        contract_id: str,
    ) -> None:
    agent = agent_repo.get_agent()
    return agent.accept_contract(
        contract_id=contract_id,
        contract_repository=contracts_repo
    )

if __name__ == "__main__":
    configure_logger()
    agent_repo = HttpAndFileAgentRepository()
    contracts_repo = HttpContractRepository()
    contracts = get_contracts(agent_repo, contracts_repo)
    print(contracts)
    accept_contract(agent_repo, contracts_repo, contracts[0].contract_id)


from django.urls import path
from .views import CategoriaList, CategoriaMethodObject, ProdutoList, ProdutoMethodObject

urlpatterns = [
    path('categarias/',CategoriaList.as_view()),
    path('categoria/<int:id>',CategoriaMethodObject.as_view()),
    path('produtos/',ProdutoList.as_view()),
    path('produto/<int:id>',ProdutoMethodObject.as_view()),

]


#!/usr/bin/python
#
# Upload Terraform config values to S3
# Requires $TF_CONFIG_BUCKET and $TF_VALUES_FILE env variables to be set

import os
import boto3

s3 = boto3.resource('s3')

bucket = os.environ['TF_CONFIG_BUCKET'];

# Read the variables file
filename = os.environ['TF_VALUES_FILE'];
data = open(filename, 'rb')

# Upload the file
s3.Bucket(bucket).put_object(Key=filename, Body=data)


"""
An example script that fits the data with linear regression with a different orders of polynomial.

"""

# imports
import scipy as sp
import numpy as np
import scipy.io as sio
import sklearn.linear_model as linear_model
import matplotlib.pyplot as plt

# import data
ex5_data = sio.loadmat('ex5data1.mat') # Loads the matlab/octave file as a dict

# Define variables
X = ex5_data['X']
y = ex5_data["y"]
Xtest = ex5_data['Xtest']
ytest = ex5_data['ytest']
Xval = ex5_data['Xval']
yval = ex5_data['yval']

# Define higer order features up to polynomial 10
N = 10
X10 = np.array([X.squeeze()**n for n in range(1,N+1)]).transpose()
Xtest10 = np.array([Xtest.squeeze()**n for n in range(1,N+1)]).transpose()

# Define a lr model and fit for each order polynomial
lr_models = [linear_model.LinearRegression(normalize=True) for n in range(N)]
[lr_model.fit(X10[:,:n+1], y) for n, lr_model in zip(range(N), lr_models)]
lr_models_ridgeCV = [linear_model.RidgeCV([1e-5, 1e-4, 1e-3, 1e-2, 1e-1], normalize=True) for n in range(N)]
[lr_model_ridgeCV.fit(X10[:,:n+1], y) for n, lr_model_ridgeCV in zip(range(N), lr_models_ridgeCV)]

# Compute the training and test errors
for i, models in zip([0,1], [lr_models, lr_models_ridgeCV]):
    yfit_train = np.array([lr_model.predict(X10[:,:n+1]) for n, lr_model in zip(range(N), models)])
    yfit_test = np.array([lr_model.predict(Xtest10[:,:n+1]) for n, lr_model in zip(range(N), models)])

    # Cost functions for
    Npoly = sp.arange(1,11)
    J_train = 1 / (2.0 * yfit_train.shape[1]) * ((y - yfit_train)**2).sum(1)
    J_test = 1 / (2.0 * yfit_test.shape[1]) * ((ytest - yfit_test)**2).sum(1)

    # Make a plot
    if i == 0 :
        f0 = plt.figure(0, (5,5), facecolor='white')
        f0.clf()
        a0 = f0.add_axes([.1, .1, .85, .85])

        a0.plot(Npoly, J_train, 'b', linewidth=2, label="err-train")
        a0.plot(Npoly, J_test, 'g', linewidth=2, label="err-test")
        a0.set_title("Error as a function of polynomial order")
    else:
        a0.plot(Npoly, J_train, '--b', linewidth=2, label="err-train-RidgeCV")
        a0.plot(Npoly, J_test, '--g', linewidth=2, label="err-test-RidgeCV")

a0.set_ybound(.001, 40)
a0.set_xbound(.5, 9.5)
a0.legend()
f0.show()
f0.savefig("wgm-ex5-learning-curve.png")


class Protista:
    def __init__(this, name, type, isUnicellular):
        this.name = name
        this.type = type
        this.isUnicellular = isUnicellular

        def type(this):
            lwType = this.type.lower()
            if(lwType == "animal"):
                print("este es un organismo protista animal")
            if(lwType == "fungi"):
                print("este es un organismo protista hongo")
            if(lwType == "plant"):
                print("este es un organismo protista vegetal")
            else:
                print("Introduciste un valor erróneo en el tipo.\nValores válidos:\n1. Animal\n2.Fungi\n3. Planta")


from Bot.Basis import command_system
from Bot.Basis.Functions.getButtons import get_timetable_menu_buttons
from Bot.Basis.Functions.getSchedule import getTimetableByWeek

def fullWeekTimetable(values):
    group = values.users[values.item['from_id']]['group']
    message = ''

    isUpper = None
    if values.item['text'] == 'Текущая':
        isUpper = values.isUpper
    elif values.item['text'] == 'Следующая':
        isUpper = not values.isUpper

    if isUpper:
        message = 'Сейчас верхняя (красная, нечётная) неделя\n\n'
    elif not isUpper:
        message = 'Сейчас нижняя (синяя, чётная) неделя\n\n'

    message += getTimetableByWeek(values.timetableDict, group, isUpper)

    return message, None, get_timetable_menu_buttons(values)

command = command_system.Command()

command.keys = ['fullWeekTimetable']
command.description = 'Отправка расписания на полную неделю'
command.process = fullWeekTimetable


import tensorflow as tf
from tensorflow.keras import backend as K
from matplotlib import pyplot as plt
import os
import sys
sys.path.append(os.getcwd())
from opts import parser
args = parser.parse_args()
save_name = args.model
#save_name = r'fingerNet_ljyBlur_v2.0'
dir_name = list()
dir_name.extend([args.dataset, args.model, args.save_annotation])
if args.debug:
    dir_name.append('debug')
    print_rate = 1
    os.environ['CUDA_VISIBLE_DEVICES']="-1"
    CUDA_VISIBLE_DEVICES = -1
else:
    print_rate = args.print_rate
    os.environ['CUDA_VISIBLE_DEVICES']="0"
    CUDA_VISIBLE_DEVICES = 0
print(dir_name)
for d_name in dir_name:
    if len(d_name) == 0:
        dir_name.remove(d_name)
save_path = os.path.join(args.save_path, '_'.join(dir_name))

dataset = __import__(args.datasetfilename, fromlist=[args.dataset])
dataset = getattr(dataset, args.dataset)
#from dataset import ljyBlur
model = __import__("arch."+args.model, fromlist=[args.model_name], level=0)
model = getattr(model, args.model_name)
model = model()
import json
from utils.LapLoss import lapLoss
from utils.crossEntropy import crossEntropy
from utils.PerceptualLoss import perceptualLoss
print("debug=",args.debug)
print('losses=',args.losses)
from utils.total_variation_regularization import total_variation_regularization, gram_matrix
#exit()
def main():
    global train_dir, val_dir
    global save_path, save_name, dir_name
    global epochs
    epochs = args.epochs if not args.debug else 10
    save_name = args.model
    #save_name = r'fingerNet_ljyBlur_v2.0'
    dir_name = list()
    dir_name.extend([args.dataset, args.model, args.save_annotation])
    if args.debug:
        dir_name.append('debug')
        os.environ['CUDA_VISIBLE_DEVICES']="-1"
    print(dir_name)
    for d_name in dir_name:
        if len(d_name) == 0:
            dir_name.remove(d_name)
    save_path = os.path.join(args.save_path, '_'.join(dir_name))
    #save_path = os.path.join(r"/home/share/Han/novatek",save_name)
    print("{0:-^50}".format(save_path))
    #exit()
    try:
        os.makedirs(save_path)
    except:
        pass

    if len(args.train_path)>0:
        train_dir = args.train_path

    if len(args.val_path)>0:
        val_dir = args.val_path

    if len(args.dataset_path) > 0:
        train_dataset = dataset(mode="train" ,debug = args.debug , batch_size=args.batch_size, dirpath = args.dataset_path )
        val_dataset = dataset(mode='val', debug=args.debug,  batch_size=args.batch_size, dirpath = args.dataset_path)
    else:
        train_dataset = dataset(mode="train" ,debug = args.debug , batch_size=args.batch_size, )
        val_dataset = dataset(mode='val', debug=args.debug,  batch_size=args.batch_size, )
    #print(train_dataset.__next__())
    #exit()
    train(model=model, dataset=train_dataset,val_dataset= val_dataset, epochs = epochs)
    #evaluate()
    pass
def train_epoch(model, dataset):

    pass
def generate_arrays_from_file(path:str, batch_size=2):
    while 1:
        inputList = list()
        outputList = list()
        while len(inputList) < batch_size:
            for dirpath, dirnames, filenames in os.walk(path):
                print(dirpath)
                for filename in filenames:
                    print(filename)
                    if "jpg" or "png"  in filename:

                        image = tf.keras.preprocessing.image.load_img(os.path.join(dirpath, filename), target_size=(61,61))
                        img = tf.keras.preprocessing.image.img_to_array(image).reshape(61,61,3)

                        outputimage = tf.keras.preprocessing.image.load_img(os.path.join(dirpath, filename), target_size=(61,61))
                        output = tf.keras.preprocessing.image.img_to_array(outputimage).reshape(61,61,3)
                        label = np.array([1,0,0])
                        #yield ({"input_1": img}, {"output_1": label, "output_2": output})
                        inputList.append(img)
                        outputList.append([(label, output)])
                        if len(inputList) >= batch_size:
                            yield inputList, outputList
                            inputList = list()
                            outputList = list()

def train(model=None, dataset=None, val_dataset=None, epochs=int(10)):
    print(epochs)
    print(save_path)
    #exit()
    #loss_object  = {"orientationOutput": tf.keras.losses.categorical_crossentropy,"enhancementOutput": lapLoss}
    loss_object  = {"enhancementOutput": lapLoss}
    print("*"*50)
    optimizer = tf.keras.optimizers.Adam(lr=args.lr, beta_1=args.beta_1, beta_2=args.beta_2 )
    if 'enMSE' in args.losses:
        #en_gt = tf.keras.layers.Input(shape=(args.input_shape, args.input_shape,1,), name='enhanced_gt')
        en_gt = K.placeholder(shape=(args.batch_size, args.input_shape, args.input_shape,1,), name='enhanced_gt')
        print(model.get_layer('enhancementOutput').output)
        enMSE = lapLoss(en_gt,model.get_layer('enhancementOutput').output)
        model.add_loss(enMSE)
    if 'perceptual' in args.losses:
        content = tf.keras.Input(shape=(args.input_shape, args.input_shape, 1), name='content')
        p_en_gt = tf.keras.Input(shape=(args.input_shape, args.input_shape, 1), name='en_gt')
        vgg = tf.keras.applications.VGG16(
        include_top=False, weights='imagenet', input_tensor=None,
        input_shape=(50,50,3), pooling=None, classes=1000,)
        vgg.trainable = False
        layer_output_dict = dict([(layer.name, layer.output) for layer in vgg.layers])

        feature_extractor = tf.keras.Model(inputs=vgg.input, outputs=layer_output_dict, name='feature_extractor')
        feature_extractor.trainable = False

        rgb_style = tf.image.grayscale_to_rgb(en_gt)
        rgb_outputs = tf.image.grayscale_to_rgb(model.get_layer['enhancementOutput'].outputs)
        rgb_content = tf.image.grayscale_to_rgb(content)
        ploss = perceptualLoss(feature_extractor,rgb_content,rgb_style,rgb_outputs)
        model.add_loss(ploss)

    #model.compile(loss = loss_object, loss_weights=[1.0,1.0], optimizer=optimizer,)
    model.compile(loss = loss_object, optimizer=optimizer,)
    #model.compile(optimizer=optimizer,)
    #print("complie finish")
    #model.fit(x=dataset, epochs=epochs, batch_size=1)
    #model.fit(x=dataset['input_1'],y=[dataset['y0'], dataset['y1']], epochs=epochs, steps_per_epoch=2,)
    print(model.summary())
    print(os.path.join(save_path, save_name + r"_{epoch}-{loss:.2f}.ckpt"))
    callbacks = [tf.keras.callbacks.ModelCheckpoint(filepath=os.path.join(save_path, save_name + r"_{epoch}-{loss:.2f}.h5"), save_best_only=True, monitor="val_loss",save_weights_only=True,),
            tf.keras.callbacks.CSVLogger(os.path.join(save_path, "history.log")),]

    history = model.fit(dataset, epochs=epochs, callbacks=callbacks,validation_data=val_dataset )
    print(history.history)
    print(type(history.history))
    plt.plot(history.history["loss"], label='training loss', color='blue')
    plt.plot(history.history['val_loss'], label='validate loss', color='red')
    plt.legend()
    plt.title("model loss")
    plt.ylabel("loss")
    plt.xlabel("epoch")
    plt.savefig(os.path.join(save_path, save_name + "_result.jpg"))

    del model

    pass
def evaluate():
    model = tf.keras.models.load_model(os.path.join(save_path, "fingerNet_v0_2-0.02"))
    model.summary()
    input = np.random.randint(0,255, size=(1,61,61,1))
    print(input.shape)
    output = model.predict(input)
    print(output)
    print(output[1].shape)
    pass
def evaluate_epoch():
    pass

if __name__=="__main__":
    main()


import taichi

import sys
import datetime
import platform
import random
import copy

def get_os_name():
    name = platform.platform()
    # in python 3.8, platform.platform() uses mac_ver() on macOS
    # it will return 'macOS-XXXX' instead of 'Darwin-XXXX'
    if name.lower().startswith('darwin') or name.lower().startswith('macos'):
        return 'osx'
    elif name.lower().startswith('windows'):
        return 'win'
    elif name.lower().startswith('linux'):
        return 'linux'
    assert False, "Unknown platform name %s" % name

def get_unique_task_id():
    return datetime.datetime.now().strftime('task-%Y-%m-%d-%H-%M-%S-r') + (
        '%05d' % random.randint(0, 10000))

def config_from_dict(args):
    from taichi.core import ti_core
    d = copy.copy(args)
    for k in d:
        if isinstance(d[k], ti_core.Vector2f):
            d[k] = '({}, {})'.format(d[k].x, d[k].y)
        if isinstance(d[k], ti_core.Vector3f):
            d[k] = '({}, {}, {})'.format(d[k].x, d[k].y, d[k].z)
        d[k] = str(d[k])
    return ti_core.config_from_dict(d)

def veci(*args):
    from taichi.core import ti_core
    if isinstance(args[0], ti_core.Vector2i):
        return args[0]
    if isinstance(args[0], ti_core.Vector3i):
        return args[0]
    if isinstance(args[0], tuple):
        args = tuple(*args)
    if len(args) == 2:
        return ti_core.Vector2i(int(args[0]), int(args[1]))
    elif len(args) == 3:
        return ti_core.Vector3i(int(args[0]), int(args[1]), int(args[2]))
    elif len(args) == 4:
        return ti_core.Vector4i(int(args[0]), int(args[1]), int(args[2]),
                                int(args[3]))
    else:
        assert False, type(args[0])

def vec(*args):
    from taichi.core import ti_core
    if isinstance(args[0], ti_core.Vector2f):
        return args[0]
    if isinstance(args[0], ti_core.Vector3f):
        return args[0]
    if isinstance(args[0], ti_core.Vector4f):
        return args[0]
    if isinstance(args[0], ti_core.Vector2d):
        return args[0]
    if isinstance(args[0], ti_core.Vector3d):
        return args[0]
    if isinstance(args[0], ti_core.Vector4d):
        return args[0]
    if isinstance(args[0], tuple):
        args = tuple(*args)
    if ti_core.get_default_float_size() == 4:
        if len(args) == 2:
            return ti_core.Vector2f(float(args[0]), float(args[1]))
        elif len(args) == 3:
            return ti_core.Vector3f(float(args[0]), float(args[1]),
                                    float(args[2]))
        elif len(args) == 4:
            return ti_core.Vector4f(float(args[0]), float(args[1]),
                                    float(args[2]), float(args[3]))
        else:
            assert False, type(args[0])
    else:
        if len(args) == 2:
            return ti_core.Vector2d(float(args[0]), float(args[1]))
        elif len(args) == 3:
            return ti_core.Vector3d(float(args[0]), float(args[1]),
                                    float(args[2]))
        elif len(args) == 4:
            return ti_core.Vector4d(float(args[0]), float(args[1]),
                                    float(args[2]), float(args[3]))
        else:
            assert False, type(args[0])

class Tee():
    def __init__(self, name):
        self.file = open(name, 'w')
        self.stdout = sys.stdout
        self.stderr = sys.stderr
        sys.stdout = self
        sys.stderr = self

    def __del__(self):
        self.file.close()

    def write(self, data):
        self.file.write(data)
        self.stdout.write(data)
        self.file.flush()
        self.stdout.flush()

    def write_to_file(self, data):
        self.file.write(data)

import inspect

def get_file_name(asc=0):
    return inspect.stack()[1 + asc][1]

def get_function_name(asc=0):
    return inspect.stack()[1 + asc][3]

def get_line_number(asc=0):
    return inspect.stack()[1 + asc][2]

def get_logging(name):
    def logger(msg, *args, **kwargs):
        # Python inspection takes time (~0.1ms) so avoid it as much as possible
        if taichi.ti_core.logging_effective(name):
            msg_formatted = msg.format(*args, **kwargs)
            func = getattr(taichi.ti_core, name)
            frame = inspect.currentframe().f_back
            file_name, lineno, func_name, _, _ = inspect.getframeinfo(frame)
            msg = f'[{file_name}:{func_name}@{lineno}] {msg_formatted}'
            func(msg)

    return logger

DEBUG = 'debug'
TRACE = 'trace'
INFO = 'info'
WARN = 'warn'
ERROR = 'error'
CRITICAL = 'critical'

debug = get_logging(DEBUG)
trace = get_logging(TRACE)
info = get_logging(INFO)
warn = get_logging(WARN)
error = get_logging(ERROR)
critical = get_logging(CRITICAL)

def redirect_print_to_log():
    class Logger:
        def write(self, msg):
            taichi.core.info('[{}:{}@{}] {}'.format(get_file_name(1),
                                                    get_function_name(1),
                                                    get_line_number(1), msg))

        def flush(self):
            taichi.core.flush_log()

    sys.stdout = Logger()

def duplicate_stdout_to_file(fn):
    taichi.ti_core.duplicate_stdout_to_file(fn)

def set_logging_level(level):
    taichi.ti_core.set_logging_level(level)

def set_gdb_trigger(on=True):
    taichi.ti_core.set_core_trigger_gdb_when_crash(on)


import logging
import models

from google.appengine.ext import deferred
from google.appengine.ext import ndb

BATCH_SIZE = 100

def UpdateSchema(cursor=None, num_updated=0):
    query = models.Snippet.query()

    logging.info("+++ HELLO")

    to_put = []
    res, cursor, more = query.fetch_page(BATCH_SIZE, start_cursor=cursor)

    for snippet in res:
         snippet.label = 'Share your stories'
         snippet.button_text = 'Tell us your story...'
         to_put.append(snippet)

    if to_put:
        ndb.put_multi(to_put)
        num_updated += len(to_put)
        logging.info(
           'Put %d entitities to Datastore for a total of %d',
           len(to_put), num_updated
        )

    if more:
        deferred.defer(UpdateSchema, cursor=cursor, num_updated=num_updated)
    else:
        logging.info('Update schema complete with %d updates!', num_updated)


import pygame
import sys
import random

##### GLOBAL VARIABLES #####
screen_width = 576
screen_height = 1024
screen_center = (screen_width/2, screen_height/2)
dimensions = (screen_width, screen_height)

ul_corner = (0,0) # upper left corner
gap_size = 350
floor_height = 900

bird_center_x = 100
bird_center_y = 512
bird_center = (bird_center_x, bird_center_y)

gravity = 0.25
game_active = True

def draw_floor():
    screen.blit(floor_surface, (floor_x_pos,floor_height))
    screen.blit(floor_surface, (floor_x_pos + screen_width, floor_height)) # consecutive floor to the right

def create_pipe():
    rand_pipe_height = random.choice(pipe_height)
    bottom_pipe = pipe_surface.get_rect(midtop = (700, rand_pipe_height))
    top_pipe = pipe_surface.get_rect(midbottom = (700, rand_pipe_height - gap_size))
    return bottom_pipe, top_pipe

# Take a list of pipes and shift it to the left
def move_pipes(pipes):
    for pipe in pipes:
        pipe.centerx -= 5
    return pipes

def draw_pipes(pipes):
    for pipe in pipes:
        if pipe.bottom >= screen_height: # If bottom of pipe is lower than bottom of the screen
            screen.blit(pipe_surface, pipe)
        else:
            flip_surface = pygame.transform.flip(pipe_surface, False, True)
            screen.blit(flip_surface, pipe)

def check_collision(pipes):
    if bird_rect.top <= -100 or bird_rect.bottom >= floor_height:
        death_sound.play()
        return False
    for pipe in pipes:
        if bird_rect.colliderect(pipe): # warning - takes (bit more) processing power
            death_sound.play()
            return False
    return True

def rotate_bird(bird):
    new_bird = pygame.transform.rotozoom(bird, -bird_movement*3, 1) # second argument is rotation, third argument is zoom
    return new_bird

def bird_animation():
    new_bird = bird_frames[bird_index]
    new_bird_rect = new_bird.get_rect(center = (bird_center_x, bird_rect.centery)) # previous height
    return new_bird, new_bird_rect

def score_display(game_active):
    if game_active == False:
        high_score_surface = game_font.render(f" High Score: {int(high_score)}", True, (255, 255, 255))
        high_score_rect = high_score_surface.get_rect(center = (screen_width/2, 850))
        screen.blit(high_score_surface, high_score_rect)
    score_surface = game_font.render(str(int(score)), True, (255, 255, 255))
    score_rect = score_surface.get_rect(center = (screen_width/2, 100))
    screen.blit(score_surface, score_rect)

def update_score(score, high_score):
    if score > high_score:
        high_score = score
    return high_score

pygame.init()
screen = pygame.display.set_mode(dimensions)
clock = pygame.time.Clock()

# Game Variables
bird_movement = 0 # Loop over bird frames
score = -2
high_score = 0

# Blit background surface
bg_surface = pygame.image.load("sprites/background-day.png").convert()
bg_surface = pygame.transform.scale2x(bg_surface)
game_font = pygame.font.Font('04B_19.TTF', 40)

# Blit moving floor
floor_surface = pygame.image.load("sprites/base.png").convert()
floor_surface = pygame.transform.scale2x(floor_surface)
floor_x_pos = 0

# Bird
bird_downflap = pygame.transform.scale2x(pygame.image.load('sprites/bluebird-downflap.png').convert_alpha())
bird_midflap = pygame.transform.scale2x(pygame.image.load('sprites/bluebird-midflap.png').convert_alpha())
bird_upflap = pygame.transform.scale2x(pygame.image.load('sprites/bluebird-upflap.png').convert_alpha())
bird_frames = [bird_downflap, bird_midflap, bird_upflap]
bird_index = 0
bird_surface = bird_frames[bird_index]
bird_rect = bird_surface.get_rect(center = bird_center) # places a rectangle around the surface

# New event for animating bird frames
BIRDFLAP = pygame.USEREVENT + 1
pygame.time.set_timer(BIRDFLAP, 200) # 200 ms

# Pipes
pipe_surface = pygame.image.load('sprites/pipe-green.png').convert()
pipe_surface = pygame.transform.scale2x(pipe_surface)
pipe_list = []

# New event for spawning pipes
SPAWNPIPE = pygame.USEREVENT # Can be passed as a new event, but a system timer
pygame.time.set_timer(SPAWNPIPE, 1200) #ms
pipe_height = [400, 600, 800]

game_over_surface = pygame.transform.scale2x(pygame.image.load('sprites/message.png').convert_alpha())
game_over_rect = game_over_surface.get_rect(center = screen_center)

# Sounds
pygame.mixer.pre_init(frequency = 441000, size = 16, channels = 1, buffer = 512)
flap_sound = pygame.mixer.Sound('audio/sfx_wing.wav')
death_sound = pygame.mixer.Sound('audio/sfx_hit.wav')
score_sound = pygame.mixer.Sound('audio/sfx_point.wav')

while True:

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

        if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
            flap_sound.play()
            bird_movement = -8 # When we jump we ignore gravity
            if game_active == False:
                game_active = True
                pipe_list.clear()
                bird_rect.center = bird_center
                bird_movement = 0
                score = -2

        if event.type == SPAWNPIPE and game_active == True:
            pipe_list.extend(create_pipe()) # extend is append, but for tuples
            print(pipe_list)
            score += 1

        if event.type == BIRDFLAP:
            if bird_index < 2:
                bird_index += 1
            else:
                bird_index = 0
            bird_surface, bird_rect = bird_animation()

    screen.blit(bg_surface, ul_corner)

    if game_active:
        # Bird movement
        bird_movement += gravity
        rotated_bird = rotate_bird(bird_surface)
        bird_rect.centery += bird_movement
        screen.blit(rotated_bird, bird_rect)
        game_active = check_collision(pipe_list)

        # Pipes
        pipe_list = move_pipes(pipe_list)
        draw_pipes(pipe_list)
        score_display(True)
    else:
        screen.blit(game_over_surface, game_over_rect)
        high_score = update_score(score, high_score)
        score_display(False)

    # 2 floors moving to the left
    floor_x_pos -= 1
    draw_floor()
    if floor_x_pos <= -screen_width:
        floor_x_pos = 0

    pygame.display.update()
    clock.tick(120) # Can't run faster than 120Hz, but can run slower - depends on the efficiency of your code and your computer


class Node:
    def __init__(self, val):
        self.val = val
        self.children = []

    def buildOrder(self, d1):
        visited = []
        output = []

        # Perform DFS starting from nodes with no incoming edges
        for node in d1:
            if node.val not in visited:
                self.dfs(node)

        # Check if all nodes are included in the build order
        for node in d1:
                if node.children and node not in output:
                    return "Error: No valid build order exists."

        return output[::-1]

    def dfs(self, node):
        visited = []
        output = []
        visited.append(node)
        for child in node.children:
            if child not in visited:
                self.dfs(child)
        output.append(node.val)

a = Node("a")
b = Node("b")
c = Node("c")
d = Node("d")
e = Node("e")
f = Node("f")

a.children = [d]
f.children = [b, a]
b.children = [d]
d.children = [c]

projects = [a, b, c, d, e, f]
result = f.buildOrder(projects)
print(result)


# 202. 快乐数
#
# 编写一个算法来判断一个数是不是“快乐数”。
#
# 一个“快乐数”定义为：对于一个正整数，每一次将该数替换为它每个位置上的数字的平方和，然后重复这个过程直到这个数变为 1，也可能是无限循环但始终变不到 1。如果可以变为 1，那么这个数就是快乐数。
#
# 示例:
#
# 输入: 19
# 输出: true
# 解释:
# 1^2 + 9^2 = 82
# 8^2 + 2^2 = 68
# 6^2 + 8^2 = 100
# 1^2 + 0^2 + 0^2 = 1

def isHappy(n: int) -> bool:
    i = 0
    while i<100:
        ans = 0
        while n>=10:
            ans = ans + ( n % 10 ) * ( n % 10 )
            n = int( n / 10 )
        ans = ans + ( n * n )
        if ans == 1:
            return True
        else:
            n = ans
            i = i + 1
    return False

print(isHappy(190))

#大佬的循环解法
# 运算符中：//    表示向下取整
# 运算符中：**    表示乘方
def isHappy(n):

    num_list = {n}
    while (True):
        num = 0
        while (n >= 1):
            k = n % 10
            num = num + k ** 2
            n = n // 10
        if num == 1:
            return True
        elif num in num_list:
            return False
        else:
            num_list.add(num)
            n = num


from tensorflow import keras
import sklearn.preprocessing
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

fashion_mnist = keras.datasets.fashion_mnist
(X_train_full, y_train_full), (X_test, y_test) = fashion_mnist.load_data()

X_train_full = X_train_full.reshape(60000,784)
X_test = X_test.reshape(-1,784)

scaler = sklearn.preprocessing.StandardScaler()
X_train_full_scaled = scaler.fit_transform(X_train_full)
X_test = scaler.transform(X_test)

X_valid, X_train = X_train_full_scaled[:5000], X_train_full_scaled[5000:]
y_valid, y_train = y_train_full[:5000], y_train_full[5000:]

#  Subclassing keras.Model
class MyModel(keras.Model):
    def __init__(self, units = 300, activation='relu', **kwargs):
        super(MyModel, self).__init__(**kwargs)
        self.hidden1 = keras.layers.Dense(units, activation=activation)
        self.hidden2 = keras.layers.Dense(10, activation=activation)
        self.mainout = keras.layers.Dense(10, activation='softmax')

    def call(self, input_, training=None, mask=None):   #  Constructs model
        input_flattened = keras.layers.Flatten(input_shape=input_.shape)(input_)
        hidden1 = self.hidden1(input_flattened)
        hidden2 = self.hidden2(hidden1)
        mainout = self.mainout(hidden2)
        return mainout

    def get_config(self):
        base_conf = super().get_config()
        return base_conf

#inputs = keras.layers.Input(shape=[784])
model = MyModel()
model.compile(loss=keras.losses.SparseCategoricalCrossentropy(),
              optimizer=keras.optimizers.SGD(lr=0.02),
              metrics=['accuracy'])
history = model.fit(X_train, y_train,epochs = 20,validation_data=(X_valid, y_valid))

#model.save('Neural Networks and deep learning/mymodel')

#modelNew = keras.models.load_model('Neural Networks and deep learning/mymodel')

def plot_images(image, label):
    plt.matshow(image, cmap=plt.cm.gray)
    plt.title(f'{label}')
    frame1 = plt.gca()
    frame1.axes.xaxis.set_ticklabels([])
    frame1.axes.yaxis.set_ticklabels([])

class_names = [
    'T-shirt/top',
    'Trouser',
    'Pullover',
    'Dress',
    'Coat',
    'Sandal',
    'Shirt',
    'Sneaker',
    'Bag',
    'Ankle boot'
]
# EVALUATION
evaluation = model.evaluate(X_test, y_test)
y_pred = modelNew.predict(X_test)
i=27
#plot_images(scaler.inverse_transform(X_test[i].reshape(784)).reshape(28,28), class_names[np.argmax(y_pred[i])])
#plt.show()

#  plots
def evaluation_plot(history, epochs):
    pd.DataFrame(history.history).plot(figsize=(8,5))
    fig = plt.gcf()
    fig.set_size_inches(10, 4)
    plt.get_current_fig_manager().window.resizable(False, False)
    plt.axis([0,epochs,0,1])
    plt.xlabel('Epochs')
    plt.ylabel('Accuracy and Loss')
    plt.grid()
    plt.legend(loc='lower right')
    plt.gca().set_ylim(0,1)

evaluation_plot(history, epochs=20)
plt.show()

MNIST/Neural Networks and deep learning/fashion_mnist_model.py


class Solution:
		def count(self, num1: str, num2: str, min_sum: int, max_sum: int) -> int:
			s = ""
			mod = 10**9 + 7

			@lru_cache(None)
			def dfs(idx, tight, sm):
				nonlocal s,min_sum,max_sum,mod

				if idx == len(s):
					if sm >= min_sum and sm <= max_sum:
						return 1
					return 0

				up = int(s[idx]) if tight else 9
				res = 0
				for digit in range(up + 1):
					newSum = sm + digit
					if newSum > max_sum: # next digits are more greater than curr so newSum always greater
						break
					res += dfs(idx + 1, tight and digit == up, newSum)
					res %= mod
				return res

			s = num2
			res = dfs(0,1,0)

			dfs.cache_clear()  # clear the dp states for new dfs

			s = str(int(num1)-1)
			res -= dfs(0,1,0)

			return res % mod


BASE_SETTING = {
    "number_of_shards": 1,
    "number_of_replicas": 1,
    "analysis": {
        "filter": {
            "english_stop": {
                "type": "stop",
                "stopwords_path": "stoplist.txt"
            },
            "english_stemmer": {
                "type": "stemmer",
                "language": "english"
            },
        },
        "analyzer": {
            "rebuilt_english": {
                "type": "custom",
                "tokenizer": "standard",
                "filter": [
                    "lowercase",
                    "english_stop",
                    "english_stemmer"
                ]
            },
        }
    }
}

AP_DATASET_MAPPING = {
    "properties": {
        "text": {
            "type": "text",
            "fielddata": True,
            "analyzer": "rebuilt_english",
            "index_options": "positions"
        }
    }
}

AP_DATASET_INDEX_CONFIG = {
    "settings": BASE_SETTING,
    "mappings": AP_DATASET_MAPPING
}


import sqlite3
from urllib import request
import requests
import progressbar
from crawl_videos_by_tag import get_ahegao_hashtags
import os.path as osp

def main():
    hashtags_for_download = list(get_ahegao_hashtags().keys())
    hashtags_list = ', '.join(hashtags_for_download)
    conn = sqlite3.connect('hashtags.db')
    conn.row_factory = sqlite3.Row
    videos_info = conn.execute(f'select * from videos where tag_id in ({hashtags_list}) and downloaded = 0').fetchall()
    widgets = [progressbar.Percentage(), ' ', progressbar.Counter(), ' ', progressbar.Bar(), ' ',
               progressbar.FileTransferSpeed()]
    pbar = progressbar.ProgressBar(widgets=widgets, max_value=len(videos_info)).start()

    for i, video_info in enumerate(videos_info):
        pbar.update(i)
        video_info = dict(video_info)
        share_id = video_info['share_id']
        file_name = f'videos/{share_id}.mp4'
        if osp.exists(file_name):
            with conn:
                conn.execute(f'UPDATE videos SET downloaded = 1 where share_id = {share_id}')
            continue
        download_link = video_info['download_url'].replace('watermark=1', 'watermark=0')
        # must have here headers, otherwise it behaves as api and does not serve the video
        response = requests.get(download_link, allow_redirects=True, headers={
            'User-Agent': 'Mozilla/5.0',
            'X-Requested-With': 'XMLHttpRequest',
            'Referer': 'https://permit.pcta.org/application/'
        })
        request.urlretrieve(response.url, file_name)
        with conn:
            conn.execute(f'UPDATE videos SET downloaded = 1 where share_id = {share_id}')

    pbar.finish()
    print('done')

if __name__ == '__main__':
    main()


import os

from PySide2.QtGui import  QIcon
from PySide2.QtWidgets import QAction

class ActivateAction(QAction):
    def __init__(self, parent, controls, ros_executor):
        super().__init__(QIcon(os.path.dirname(__file__)+"/activate.png"),"Activate", parent)

        self.ros_executor = ros_executor
        self.isActive = False
        self.setToolTip("Activate/Deactivate")
        self.triggered.connect(self.trigger)

    def trigger(self):
        if self.isActive:
            self.ros_executor.deactivate()
            self.isActive = False
        else:
            self.ros_executor.activate()
            self.isActive = True


import unittest

from more_itertools import one

from azul import config
from azul.es import ESClientFactory
from azul.logging import configure_test_logging
from azul.transformer import Contribution
from indexer.test_hca_indexer import IndexerTestCase

def setUpModule():
    configure_test_logging()

class TestDataExtractorTestCase(IndexerTestCase):

    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.es_client = ESClientFactory.get()

    @classmethod
    def tearDownClass(cls):
        super().tearDownClass()

    def test_hca_extraction(self):
        bundle_fqids = [("17a3d288-01a0-464a-9599-7375fda3353d", "2018-03-28T151023.074974Z"),
                        ("2a87dc5c-0c3c-4d91-a348-5d784ab48b92", "2018-03-29T104041.822717Z"),
                        ("4afbb0ea-81ad-49dc-9b12-9f77f4f50be8", "2018-03-29T090403.442059Z"),
                        ("aaa96233-bf27-44c7-82df-b4dc15ad4d9d", "2018-11-04T113344.698028Z"),
                        ("b0850e79-5544-49fe-b54d-e29b9fc3f61f", "2018-03-29T090340.934358Z"),
                        ("c94a43f9-257f-4cd0-b2fe-eaf6d5d37d18", "2018-03-29T090343.782253Z")]
        for bundle_fqid in bundle_fqids:
            self._index_canned_bundle(bundle_fqid)
        for aggregate in True, False:
            with self.subTest(aggregate=aggregate):
                def index_name(entity_type):
                    return config.es_index_name(entity_type, aggregate=aggregate)

                total_projects = self.es_client.count(index=index_name('projects'), doc_type='doc')
                # Three unique projects, six project contributions
                self.assertEqual(3 if aggregate else 6, total_projects["count"])
                total_files = self.es_client.count(index=index_name('files'), doc_type='doc')
                self.assertEqual(776, total_files["count"])
                total_samples = self.es_client.count(index=index_name('samples'), doc_type='doc')
                self.assertEqual(129, total_samples["count"])

    # When two processes point at a file (this is the case for most files in production)
    # there was a bug where the files index contains duplicate dictionaries for the file.
    #
    def test_no_duplicate_files_in_specimen(self):
        bundle_fqid = ("8543d32f-4c01-48d5-a79f-1c5439659da3", "2018-03-29T143828.884167Z")
        self._index_canned_bundle(bundle_fqid)
        for aggregate in True, False:
            with self.subTest(aggregate=aggregate):
                entity_id = 'b3623b88-c369-46c9-a2e9-a16042d2c589'
                if aggregate:
                    document_id = entity_id
                else:
                    document_id = Contribution.make_document_id(entity_id, *bundle_fqid, bundle_deleted=False)
                result = self.es_client.get(index=config.es_index_name('samples', aggregate=aggregate),
                                            id=document_id)
                files = result['_source']['contents']['files']
                num_files = 2  # fastqs
                if aggregate:
                    self.assertEqual(num_files, one(files)['count'])
                else:
                    file_ids = [f['uuid'] for f in files]
                    self.assertEqual(num_files, len(file_ids))
                    self.assertEqual(num_files, len(set(file_ids)))

if __name__ == "__main__":
    unittest.main()


# import library socket karena akan menggunakan IPC socket
import socket
import json

TCP_IP = "127.0.0.1"        # definisikan tujuan IP server
TCP_PORT = 3000             # definisikan port dari server yang akan terhubung
BUFFER_SIZE = 1024          # definisikan ukuran buffer untuk mengirimkan pesan

# definisikan pesan yang akan disampaikan
res = "ya"
while (res == "ya"):
    PESAN = {}

    PESAN['NIKPelapor'] = input("Masukkan NIK pelapor :")
    while len(PESAN['NIKPelapor']) != 3:
        print("Maaf NIK anda tidak lengkap")
        PESAN['NIKPelapor'] = input("Masukkan NIK pelapor :")
    PESAN['namaPelapor'] = input("Masukkan nama pelapor :")
    while (type(PESAN['namaPelapor']) != list) and (len(PESAN['namaPelapor']) == 0):
        print("Maaf type nama anda tidak cocok")
        PESAN['namaPelapor'] = input("Masukkan nama pelapor :")
    PESAN['namaTerduga'] = input("Masukkan nama terduga pasien covid :")
    while type(PESAN['namaTerduga']) != list and (len(PESAN['namaTerduga']) == 0):
        print("Maaf type nama anda tidak cocok")
        PESAN['namaTerduga'] = input("Masukkan nama terduga pasien covid :")
    PESAN['alamatTerduga'] = input("Masukkan alamat terduga pasien covid :")
    while len(PESAN['alamatTerduga']) == 0:
        print("Maaf alamat anda kosong, mohon diisi!")
        PESAN['alamatTerduga'] = input("Masukkan alamat terduga pasien covid :")
    PESAN['gejala'] = input("Masukkan detail gejala yang dimiliki pasien covid :")
    while len(PESAN['gejala']) == 0:
        print("Maaf gejala anda kosong, mohon diisi!")
        PESAN['gejala'] = input("Masukkan detail gejala yang dimiliki pasien covid :")

    # buat socket TCP
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # lakukan koneksi ke server dengan parameter IP dan Port yang telah didefinisikan
    s.connect((TCP_IP, TCP_PORT))

    # kirim pesan ke server
    s.send(json.dumps(PESAN).encode())

    # terima pesan dari server
    data = s.recv(BUFFER_SIZE)

    # tampilkan pesan/reply dari server
    print("feedback : ", data.decode())
    res = input("Apakah anda masih ingin menambah data ? (ya/tidak) : ")
    if (res != "tidak" and res !="ya"):
        print("input salah ! ")
        res = input("Apakah anda masih ingin menambah data ? (ya/tidak) : ")
    else :
        if (res == "tidak"):
            print("Terimakasih telah menggunakan layanan Siaga Covid 19")

    print("\n")

# tutup koneksi
s.close()


num=int(input())
def fun(m):
    return m*(m+1);
for j in range(num):
    x =int(input())
    x -=1;
    p=int(x/3);
    q=int(x/5);
    r=int(x/15);
    print(int(int(3*fun(p) + 5*fun(q) - 15*fun(r))>>1));


#!/usr/bin/env python

# Open a new Window with a button Tkinter
# You may use this for any type of coding, including for professional use

from tkinter import *
import functions
import children

welcomestring="Welcome to BiologistsLittleHelper"
welcomestring1="This program performs calculations you might be confronted with in the lab"

master = Tk()
master.geometry("800x500")
master.title("BiologistsLittleHelper")

w = Label(master, text=welcomestring)
w.place(relx=0.4, rely=0)

w = Label(master, text=welcomestring1)
w.place(relx=0.25, rely=0.1)

newwindow = Button(master, text="Concentration-\nVolume-\nCalculation", command=children.cvc,height = 5, width = 10)
newwindow.place(relx=0.4, rely=0.2)

newwindow = Button(master, text="Unit-\nConversion", command=children.uc,height = 5, width = 10)
newwindow.place(relx=0.6, rely=0.2)

master.mainloop()


import demandimport
with demandimport.enabled():
    import tensorflow as tf

__all__ = ('leaky_relu', 'prelu')

def leaky_relu(_x, alpha=0.2, name='leaky_relu'):
    return prelu(_x, init=alpha, name=name, trainable=False)

def prelu(_x, init=0.0, name='prelu', trainable=True):
    with tf.variable_scope(name):
        alphas = tf.get_variable('alphas',
                                 shape=[int(_x.get_shape()[-1])],
                                 initializer=tf.constant_initializer(init),
                                 dtype=tf.float32,
                                 trainable=trainable)
        pos = tf.nn.relu(_x)
        neg = -alphas * tf.nn.relu(-_x)

        return pos + neg