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

class ResNeXtBottleneck(nn.Module):
    def __init__(self, in_channels=256, out_channels=256, stride=1, cardinality=32, dilate=1):
        super(ResNeXtBottleneck, self).__init__()
        D = out_channels // 2
        self.conv_reduce = nn.Conv2d(in_channels, D, kernel_size=1, stride=1, padding=0, bias=False)
        self.conv_conv = nn.Conv2d(D, D, kernel_size=3, stride=stride, padding=dilate, dilation=dilate,
                                   groups=cardinality,
                                   bias=False)
        self.conv_expand = nn.Conv2d(D, out_channels, kernel_size=1, stride=1, padding=0, bias=False)

    def forward(self, x):
        if isinstance(x, tuple):
            bottleneck = self.conv_reduce.forward(torch.cat([x[0], x[1]], 1))
            bottleneck = F.relu(bottleneck, inplace=True)
            bottleneck = self.conv_conv.forward(bottleneck)
            bottleneck = F.relu(bottleneck, inplace=True)
            bottleneck = self.conv_expand.forward(bottleneck)
            return x[0] + bottleneck, x[1]
        else:
            bottleneck = self.conv_reduce.forward(x)

            bottleneck = F.relu(bottleneck, inplace=True)
            bottleneck = self.conv_conv.forward(bottleneck)
            bottleneck = F.relu(bottleneck, inplace=True)
            bottleneck = self.conv_expand.forward(bottleneck)
            return x + bottleneck

class DResNeXtBottleneck(nn.Module):
    """
    RexNeXt bottleneck type C (https://github.com/facebookresearch/ResNeXt/blob/master/models/resnext.lua)
    """

    def __init__(self, in_channels=256, out_channels=256, stride=1, cardinality=32):
        """ Constructor
        Args:
            in_channels: input channel dimensionality
            out_channels: output channel dimensionality
            stride: conv stride. Replaces pooling layer.
            cardinality: num of convolution groups.
        """
        super(DResNeXtBottleneck, self).__init__()
        D = out_channels // 2
        self.conv_reduce = nn.Conv2d(in_channels, D, kernel_size=1, stride=1, padding=0, bias=False)
        self.conv_conv = nn.Conv2d(D, D, kernel_size=3, stride=stride, padding=1, groups=cardinality, bias=False)
        self.conv_expand = nn.Conv2d(D, out_channels, kernel_size=1, stride=1, padding=0, bias=False)
        self.shortcut = nn.Sequential()
        if in_channels != out_channels:
            self.shortcut.add_module('shortcut_conv',
                                     nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, padding=0,
                                               bias=False))

    def forward(self, x):
        bottleneck = self.conv_reduce.forward(x)
        bottleneck = F.leaky_relu(bottleneck, 0.2, True)
        bottleneck = self.conv_conv.forward(bottleneck)
        bottleneck = F.leaky_relu(bottleneck, 0.2, True)
        bottleneck = self.conv_expand.forward(bottleneck)
        residual = self.shortcut.forward(x)
        return residual + bottleneck

class Tunnel(nn.Module):
    def __init__(self, len=1, *args):
        super(Tunnel, self).__init__()

        tunnel = [DResNeXtBottleneck(*args) for _ in range(len)]
        self.tunnel = nn.Sequential(*tunnel)

    def forward(self, x):
        return self.tunnel(x)

class DilateTunnel(nn.Module):
    def __init__(self, depth=4):
        super(DilateTunnel, self).__init__()

        tunnel = [ResNeXtBottleneck(dilate=1) for _ in range(depth)]
        tunnel += [ResNeXtBottleneck(dilate=2) for _ in range(depth)]
        tunnel += [ResNeXtBottleneck(dilate=4) for _ in range(depth)]
        tunnel += [ResNeXtBottleneck(dilate=8) for _ in range(depth)]
        tunnel += [ResNeXtBottleneck(dilate=1) for _ in range(14)]

        self.tunnel = nn.Sequential(*tunnel)

    def forward(self, x):
        return self.tunnel(x)

class Pyramid(nn.Module):
    def __init__(self):
        super(Pyramid, self).__init__()
        self.entrance1 = nn.Sequential(nn.Conv2d(3, 64, kernel_size=7, stride=1, padding=3),
                                       nn.ReLU(inplace=True))
        self.entrance2 = nn.Sequential(nn.Conv2d(64, 128, kernel_size=4, stride=2, padding=1),
                                       nn.ReLU(inplace=True))
        self.entrance3 = nn.Conv2d(128, 256, kernel_size=4, stride=2, padding=1)

        self.up3 = nn.Sequential(nn.Conv2d(256, 32 * 4, 3, 1, 1, bias=False),
                                 nn.PixelShuffle(2),
                                 nn.ReLU(inplace=True))
        self.con2 = nn.Conv2d(160 + 32, 32, 5, 1, 2, bias=False)

        self.up2 = nn.Sequential(nn.Conv2d(32, 32 * 4, 3, 1, 1, bias=False),
                                 nn.PixelShuffle(2),
                                 nn.ReLU(inplace=True))
        self.con1 = nn.Conv2d(96 + 32, 32, 5, 1, 2, bias=False)

        tunnel = [DResNeXtBottleneck() for _ in range(30)]
        self.tunnel3 = nn.Sequential(*tunnel)

        depth = 3
        tunnel = [ResNeXtBottleneck(64, 32, cardinality=8, dilate=1) for _ in range(depth)]
        tunnel += [ResNeXtBottleneck(64, 32, cardinality=8, dilate=2) for _ in range(depth)]
        tunnel += [ResNeXtBottleneck(64, 32, cardinality=8, dilate=4) for _ in range(depth)]
        tunnel += [ResNeXtBottleneck(64, 32, cardinality=8, dilate=2),
                   ResNeXtBottleneck(64, 32, cardinality=8, dilate=1)]
        self.tunnel2 = nn.Sequential(*tunnel)

        tunnel = [ResNeXtBottleneck(64, 32, cardinality=8, dilate=1) for _ in range(depth)]
        tunnel += [ResNeXtBottleneck(64, 32, cardinality=8, dilate=2) for _ in range(depth)]
        tunnel += [ResNeXtBottleneck(64, 32, cardinality=8, dilate=4) for _ in range(depth)]
        tunnel += [ResNeXtBottleneck(64, 32, cardinality=8, dilate=8) for _ in range(depth)]
        tunnel += [ResNeXtBottleneck(64, 32, cardinality=8, dilate=2),
                   ResNeXtBottleneck(64, 32, cardinality=8, dilate=1)]
        self.tunnel1 = nn.Sequential(*tunnel)

        self.exit = nn.Conv2d(32, 3, kernel_size=3, stride=1, padding=1)

    def forward(self, x):
        lv1 = self.entrance1(x)
        lv2 = self.entrance2(lv1)
        lv3 = self.entrance3(lv2)  # need discussion

        lv3_up = self.up3(lv3)
        lv3 = self.up3(self.tunnel3(lv3))

        lv2_up = self.up2(lv3)
        lv2 = self.tunnel2((self.con2(torch.cat([lv2, lv3, lv3_up], 1)), lv3))[0] + lv3
        lv2 = self.up2(lv2)

        lv1 = self.tunnel1((self.con1(torch.cat([lv1, lv2, lv2_up], 1)), lv2))[0] + lv2
        return self.exit(lv1)

class PatchD(nn.Module):
    def __init__(self, ndf=64):
        super(PatchD, self).__init__()

        sequence = [
            nn.Conv2d(6, ndf, kernel_size=4, stride=2, padding=1, bias=False),  # 128
            nn.LeakyReLU(0.2, True),

            Tunnel(2, ndf, ndf),
            DResNeXtBottleneck(ndf, ndf * 2, 2),  # 64

            Tunnel(3, ndf * 2, ndf * 2),
            DResNeXtBottleneck(ndf * 2, ndf * 4, 2),  # 32

            Tunnel(4, ndf * 4, ndf * 4),
            DResNeXtBottleneck(ndf * 4, ndf * 8, 2),  # 16

            Tunnel(4, ndf * 8, ndf * 8),
            DResNeXtBottleneck(ndf * 8, ndf * 16, 2),  # 8

            Tunnel(2, ndf * 16, ndf * 16),
            DResNeXtBottleneck(ndf * 16, ndf * 32, 2),  # 4

            nn.Conv2d(ndf * 32, 1, kernel_size=4, stride=1, padding=0, bias=False)

        ]

        self.model = nn.Sequential(*sequence)

    def forward(self, input):
        return self.model(input)

        # TODO: fix relu bug


import django

try:
    from django.apps import apps
except ImportError:
    apps = None

if apps is not None:
    get_model = apps.get_model
else:
    from django.db.models import get_model

try:
    from django.db.models.fields.related_descriptors import create_forward_many_to_many_manager
except ImportError:
    # Django <= 1.8 support.
    from django.db.models.fields.related import create_many_related_manager as create_forward_many_to_many_manager

def get_model_name(model):
    # Django 1.5 support.
    if not hasattr(model._meta, 'model_name'):
        return model._meta.object_name.lower()
    else:
        return model._meta.model_name

def get_foreignkey_field_kwargs(field):
    # Django 1.5 support.
    if django.VERSION < (1, 6):
        return {}
    else:
        return dict(
            db_tablespace=field.db_tablespace,
            db_constraint=field.rel.db_constraint)

def get_field(model, field_name):
    if django.VERSION < (1, 8):
        return model._meta.get_field_by_name(field_name)[0]
    else:
        return model._meta.get_field(field_name)

def get_apps_from_state(migration_state):
    if django.VERSION < (1, 8):
        return migration_state.render()
    else:
        return migration_state.apps

def allow_migrate_model(self, connection_alias, model):
    if django.VERSION < (1, 8):
        return self.allowed_to_migrate(connection_alias, model)
    else:
        return self.allow_migrate_model(connection_alias, model)


# OOP?
import superGlobals as sg

def moveIsLegal(move, silent = False):
	# VECTOR COORDINATES ARE X-Y, IN sg.pieceMatrix THAT WOULD
	# CORRESPOND TO [Y][X], NOT [X][Y]

	def printError(msg):
		if not silent:
			print(msg)
	# Make sure there's even a piece on the given tile

	piece = sg.pieceMatrix[move[0][1]][move[0][0]]
	if piece == '':
		printError('No piece on that tile')
		return False

	# First make sure that we're the right color
	if sg.blackTurn != sg.isLower(piece) and piece != '':
		printError('That\'s the wrong color')
		return False

	# And that we're not about to step on our own piece
	target = sg.pieceMatrix[move[1][1]][move[1][0]]
	if sg.blackTurn == sg.isLower(target) and target != '':
		printError('You already have a piece on that tile')
		return False

	# Make sure we move at all

	# REDUNDANT, would have stepped on own piece
	v = makeVector(move) # We do need this tho
	if v[0] == 0 and v[1] == 0:
		printError('0 length move')
		return False

	# Then we find out if the move fits legal pattern for the given piece
	if not moveFitsPattern(piece,v):
		printError('Illegal move')
		return False

	# Also check if our move is obstructed by anything
	if moveIsObstructed(move):
		printError('Something is in the way')
		return False

	# Extra pawn stuff
	if not rickHarrison(move,v,piece):
		printError('I\'m Rick Harrison and this is my pawn shop')
		return False

	# Otherwise
	return True

def rickHarrison(move,v,piece):
		if piece.lower() != 'p': return True
		def targetEmpty():
			target = sg.pieceMatrix[move[1][1]][move[1][0]]
			return target == ''

		def pieceInSecondRow():
			boardLength = 8 # Make superglobal
			row = move[0][1]
			return row == boardLength - 2 and not sg.blackTurn or row == 1 and sg.blackTurn

		direction = getDirection()

		pawnStraight = [0,1 * direction]
		pawnLong = [0,2 * direction]
		pawnDiag = [[1 * direction, 1 * direction],[-1 * direction, 1 * direction]]

		def debug():
			print('targetEmpty',targetEmpty())
			print('v == pawnStraight',v == pawnStraight)
			print('v == pawnLong',v == pawnLong)
			print('pieceInSecondRow()',pieceInSecondRow())
			print('v in pawnDiag',v in pawnDiag)
			print('v in pawnDiag and not targetEmpty()',v in pawnDiag and not targetEmpty())
			print('rickHarrison',targetEmpty() and (v == pawnStraight or v == pawnLong and pieceInSecondRow()) or v in pawnDiag and not targetEmpty())
		#debug()

		return targetEmpty() and (v == pawnStraight or v == pawnLong and pieceInSecondRow()) or v in pawnDiag and not targetEmpty()

def moveIsObstructed(move):
	# Only handles straight moves
	v = makeVector(move)
	if not (abs(v[0]) == abs(v[1]) or v[0] == 0 or v[1] == 0):
		return False
	for i in range(max((max(v),abs(min(v))))):
		if sg.pieceMatrix[move[0][1] + v[1]][move[0][0] + v[0]] != '':
			return True
		v[0] = sub(v[0])
		v[1] = sub(v[1])

def moveFitsPattern(piece,v):
	# Assuming no shit has made it's way into our board

	# Pawn
	if piece.lower() == 'p':
		# Pawn movement direction depends on player color
		# Black side is upper side
		direction = getDirection()
		pawnMoves = [[0, 1 * direction], [0, 2 * direction], [1 * direction, 1 * direction],[-1 * direction, 1 * direction]]
		return v in pawnMoves

	# Knight
	if piece.lower() == 'n':
		#knightMoves = [[-1,2], [1,2], [1,-2], [-1,-2], [-2,1], [2,1], [2,-1], [-2,-1]]
		# Move is valid if for a given vector [a,b]:
			# abs(a) != abs(b)
			# abs(a) in (1,2) and abs(b) in (1,2)

		def happyHorse(v):
			""".  ,    ___________
	           |\/|    |Jolly gee|
	           bd "n.  /----------
	          /   _,"n.___.,--x.
	         <co>'\             Y
	          ~~   \       L   7|
	                H l--'~\  (||
	                H l     H |`'
	                H [     H [
	           ____//,]____//,]___"""
			if abs(v[0]) == abs(v[1]):
				return False
			if abs(v[0]) not in (1,2):
				return False
			if abs(v[1]) not in (1,2):
				return False
			return True

		return happyHorse(v)

	def bish(v):
		# Ya bish
		return abs(v[0]) == abs(v[1])

	def rook(v):
		return not abs(v[0]) or not abs(v[1])

	# Bishop
	if piece.lower() == 'b':
		return bish(v)

	# Rook
	if piece.lower() == 'r':
		return rook(v)

	# Queen
	if piece.lower() == 'q':
		return bish(v) or rook(v)

	# King
	if piece.lower() == 'k':
		return abs(v[0]) <= 1 and abs(v[1]) <= 1

def makeVector(move):
	return [move[1][0] - move[0][0], move[1][1] - move[0][1]]

def sub(n):
	# Subtract one until val reaches zero
	if not n:
		return n
	else:
		return sign(n) * (abs(n) - 1)

def sign(n):
	if n > 0: return 1
	if n < 0: return -1

def getDirection():
	direction = -1
	if sg.blackTurn:
		direction = 1
	return direction


from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm

from django.shortcuts import render

from django.http import Http404
from .models import Product
from .forms import ProductForm
from .phash import Phash
import io
import cv2
import numpy as np

def login(request):
    if request.method == 'POST':
        form = AuthenticationForm(request.POST)

        if form.confirm_login_allowed():
            return render(request, 'login.html', context={
                'created': True
            })

        return render(request, 'login.html')
    elif request.method == 'GET':
        return render(request, 'login.html')

def signup(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)

        if form.is_valid():
            form.save()
            return render(request, 'signup.html', context={
                'created': True
            })

    return render(request, 'signup.html', )

def feed(request):
    products = Product.objects.all()

    context = {
        'products': products
    }

    return render(request, 'feed.html', context=context)

def search(request):
    src_img = ""
    products = Product.objects.all()
    scores = Phash.phash_list(src_img, products)
    # get second element from each tuple and save in dict
    scores_dict = {product.id: score for product, score in scores}
    return render(request, 'feed.html', context = scores_dict )

def profile(request):
    return render(request, 'profile.html')

def product_add(request):
    return render(request, 'add_product.html')

def product_save(request):
    if request.method != 'POST':
        return

    form = ProductForm(request.POST, request.FILES)

    # get image from django form
    image = request.FILES['image']
    # download image form request
    image_file = io.BytesIO(image.read())
    # open image_file image
    img = cv2.imdecode(np.fromstring(image_file.getvalue(), np.uint8), cv2.IMREAD_UNCHANGED)

    hash = Phash.get_phash(img)
    # save hash to form
    form.instance.hash = hash
    if form.is_valid():
        form.save()
    else:
        print("form is not valid")
    return render(request, 'add_product.html')


import pandas as pd
import similarity

def tokenize_column(df, column):
    df['tokens'] = df.apply(lambda row: ["".join(k) for k in row[column].split()], axis=1)
    return df

def create_blocks_from_clusters(clusters, datasetMapping):
    clusterBlocks = []
    for cluster in clusters:
        entitiesInCluster = pd.DataFrame()
        for propertyNameWithDfInfo in cluster:
            splittedProperty = propertyNameWithDfInfo.split("*")
            rowTokenized = tokenize_column(datasetMapping[splittedProperty[0]], splittedProperty[1])
            explodedRow = rowTokenized.explode('tokens')
            if entitiesInCluster.empty:
                entitiesInCluster = explodedRow
            else:
                entitiesInCluster = entitiesInCluster.reset_index().merge(explodedRow.reset_index(), how='outer').set_index('index')
        groupedBlock = group_by_blocks(entitiesInCluster)
        clusterBlocks.append(groupedBlock)
    return clusterBlocks

def group_by_blocks(initialBlock):
    grouped = initialBlock.groupby(by=["tokens"], dropna=False)
    return grouped

def process_block_by_block_name(block, already_compared, duplicates):
    total_comparisons = 0
    for mainIndex, mainRow in block.iterrows():
        for secondaryIndex, secondaryRow in block.iterrows():
            compared_id = f"{mainRow['dataset_name']}-{mainIndex}*{secondaryRow['dataset_name']}-{secondaryIndex}"
            reverse_compared_id = f"{secondaryRow['dataset_name']}-{secondaryIndex}*{mainRow['dataset_name']}-{mainIndex}"
            if mainRow['dataset_name'] != secondaryRow['dataset_name'] and compared_id not in already_compared:
                already_compared.add(compared_id)
                already_compared.add(reverse_compared_id)
                already_compared.add(f"{secondaryRow['dataset_name']}-{secondaryIndex}*{mainRow['dataset_name']}-{mainIndex}")
                mainRowDuplicateCleaned = mainRow.drop(labels=['dataset_name', 'tokens']).dropna()
                secondaryRowDuplicateCleaned = secondaryRow.drop(labels=['dataset_name', 'tokens']).dropna()
                total_comparisons = total_comparisons + 1
                if(similarity.is_duplicate(mainRow, secondaryRow)):
                    duplicates.append({'item1': mainRowDuplicateCleaned, 'item2': secondaryRowDuplicateCleaned})
    return total_comparisons

def get_duplicates(setOfClustersOfEntities):
    already_compared = set()
    duplicates = []
    total_comparisons = 0
    for clusterOrEntities in setOfClustersOfEntities:
        for blockName in clusterOrEntities.groups:
            if blockName not in ['df1', 'df2']:
                block = clusterOrEntities.get_group(blockName)
                if len(block.index) > 1:
                   total_comparisons += process_block_by_block_name(block, already_compared, duplicates)
    return (duplicates, total_comparisons)

def get_comparisons_according_to_entity_clustering(setOfClusters):
    comparisons = pd.DataFrame()
    blockId = 0
    for cluster in setOfClusters:
        for blockName in cluster.groups:
            if blockName not in ['df1', 'df2']:
                block = cluster.get_group(blockName)
                if len(block.index) > 1:
                    blockId = blockId + 1
                    iteratedComparisons = iterate_block_to_comparisons(block, blockId)
                    if comparisons.empty:
                        comparisons = iteratedComparisons
                    else:
                        comparisons = pd.concat([comparisons, iteratedComparisons])
    return comparisons

def iterate_block_to_comparisons(block, blockId):
    comparisons = []
    for mainIndex, mainRow in block.iterrows():
        for secondaryIndex, secondaryRow in block.iterrows():
            if mainRow['dataset_name'] != secondaryRow['dataset_name']:
                comparisons.append([mainIndex, mainRow['dataset_name'], secondaryIndex, secondaryRow['dataset_name'], blockId])
    return pd.DataFrame(comparisons, columns=['mainIndex', 'mainDf', 'secondaryIndex', 'secondaryDf', 'blockId'])


"""empty message

Revision ID: 441975213ebc
Revises:
Create Date: 2021-03-11 14:52:50.717868

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '441975213ebc'
down_revision = None
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('booking',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('name', sa.String(length=80), nullable=True),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_table('books',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('bookTitle', sa.String(length=100), nullable=True),
    sa.Column('bookText', sa.String(), nullable=True),
    sa.Column('author', sa.String(), nullable=True),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_table('user',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('username', sa.String(length=80), nullable=True),
    sa.Column('email', sa.String(length=120), nullable=True),
    sa.PrimaryKeyConstraint('id')
    )
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('user')
    op.drop_table('books')
    op.drop_table('booking')
    # ### end Alembic commands ###


from Node import Node

class LinkedList:
    def __init__ (self):
        self.head = None
        self.size = 0
    def append(self, elem):
        if self.head:
            pointer = self.head
            while (pointer.next):
                pointer = pointer.next
            pointer.next = Node(elem)
        else:
            self.head = Node(elem)
        self.size +=1
    def __len__ (self):
        return self.size

    def get(self, index):
        pass

    def set (self, index, elem):
        pass

    def __getitem__(self, index):
        pointer = self.head
        for i in range (index):
            if pointer:
                pointer = pointer.next
            else:
                raise IndexError("list index out of range")
        if pointer:
            return pointer.data
        raise IndexError("list index out of range")

    def __setitem__(self, index, elem):
        pointer = self.head
        for i in range (index):
            if pointer:
                pointer = pointer.next
            else:
                raise IndexError("list index out of range")
        if pointer:
            pointer.data = elem
        else:
            raise IndexError("list index out of range")
    def index(self, elem):
        pointer = self.head
        i = 0
        while(pointer):
            if pointer.data == elem:
                return i
            pointer = pointer.next
            i +=1
        raise ValueError("{} is not in the list".format(elem))


import can
from can import CanError
from ...connections.can_tmcl_interface import CanTmclInterface

class SocketcanTmclInterface(CanTmclInterface):
    """
    This class implements a TMCL connection over a SocketCAN adapter.

    Use following command under linux to activate can socket
    sudo ip link set can0 down type can bitrate 1000000
    """
    _CHANNELS = ["can0",  "can1",  "can2",  "can3",  "can4",  "can5",  "can6",  "can7"]

    def __init__(self, port, datarate=1000000, host_id=2, module_id=1, timeout_s=5):
        if not isinstance(port, str):
            raise TypeError

        if port not in self._CHANNELS:
            raise ValueError("Invalid port")

        CanTmclInterface.__init__(self, port, datarate, host_id, module_id, timeout_s)

        self.logger.info("Connect to bus with bit-rate %s.", self._bitrate)
        try:
            self._connection = can.Bus(interface="socketcan", channel=self._channel, bitrate=self._bitrate)
            self._connection.set_filters([{"can_id": host_id, "can_mask": 0x7F}])
        except CanError as e:
            self._connection = None
            raise ConnectionError("Failed to connect to SocketCAN bus") from e

    @classmethod
    def list(cls):
        """
            Return a list of available connection ports as a list of strings.

            This function is required for using this interface with the
            connection manager.
        """
        return cls._CHANNELS


from aoc import aoc
from aoc.point import point
from aoc.grid import grid
import re

pattern = '^(\d+),(\d+)$'
pattern_fold = '^fold along (\w)=(\d+)'

lines = aoc.read_lines('data/13.txt')

dots = []
folds = []

for line in lines:
    digits = re.match(pattern, line)
    if digits:
        x, y = digits.groups()
        dots.append(point(int(x),int(y)))
        continue

    fold_instr = re.match(pattern_fold, line)
    if fold_instr:
        axis, num = fold_instr.groups()
        folds.append((axis, int(num)))

def print_dots(dots):
    x_max = max([p.x for p in dots])
    y_max = max([p.y for p in dots])
    g = grid(x_max + 1, y_max + 1, '.')
    for dot in dots:
        g.set(dot, '#')
    g.print_condensed()

def fold_hor(dots, y):
    copy = [p for p in dots if p.y < y]
    for p in [p for p in dots if p.y > y]:
        copy.append(point(p.x, y - (p.y - y)))
    return copy

def fold_vert(dots, x):
    copy = [p for p in dots if p.x < x]
    for p in [p for p in dots if p.x > x]:
        copy.append(point(x - (p.x - x), p.y))
    return copy

def fold(dots: list[point], fold_instr: tuple):
    if fold_instr[0] == 'x':
        return fold_vert(dots, fold_instr[1])
    else:
        return fold_hor(dots, fold_instr[1])

dots = fold(dots, folds[0])
print(len(set(dots)))

for i in range(1, len(folds)):
    dots = fold(dots, folds[i])

print_dots(dots)


from flask import Blueprint, render_template, abort, request

from auth import edit_permission
from db import mongo

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

@norm_page.route('<name>', defaults={'page': 1})
@norm_page.route('<name>/<int:page>')
@edit_permission.require()
def norm(name, page):
    coll = 'norm/' + name
    if coll in mongo.db.collection_names():
        corp = mongo.db[coll]
    else:
        return abort(404)

    item_num = mongo.db.corpora.find_one({'coll': coll})['num']

    if page > item_num or page < 1:
        return abort(404)

    item = corp.find_one({'id': page - 1})

    if not item:
        return abort(404)

    return render_template('norm.html', name=name, page=page, page_num=item_num, item=item)

@norm_page.route('<name>/saved', defaults={'page': 0})
@norm_page.route('<name>/saved/<int:page>')
@edit_permission.require()
def saved(name, page):
    coll = 'norm/' + name
    if coll in mongo.db.collection_names():
        corp = mongo.db[coll]
    else:
        return abort(404)

    item_num = mongo.db.corpora.find_one({'coll': coll})['num']

    if page >= item_num or page < 0:
        return abort(404)

    item = corp.find_one({'id': page})

    if not item:
        return abort(404)

    if 'corr' in item and item['corr']:
        return item['corr']
    else:
        return 'NIE ZAPISANO ZMIAN!'

@norm_page.route('<name>/modify', methods=['POST'])
@edit_permission.require()
def modify(name):
    coll = 'norm/' + name
    id = int(request.form['id'])
    value = request.form['value']
    if coll in mongo.db.collection_names():
        corp = mongo.db[coll]
    else:
        return abort(404)

    corp.update_one({'id': id}, {'$set': {'corr': value}})

    return ''

@norm_page.route('<name>/revert', methods=['POST'])
@edit_permission.require()
def revert(name):
    coll = 'norm/' + name
    id = int(request.form['id'])
    if coll in mongo.db.collection_names():
        corp = mongo.db[coll]
    else:
        return abort(404)

    corp.update_one({'id': id}, {'$set': {'corr': ''}})

    return ''

@norm_page.route('<name>/list')
@edit_permission.require()
def list(name):
    coll = 'norm/' + name
    if coll in mongo.db.collection_names():
        corp = mongo.db[coll]
    else:
        return abort(404)

    pages = []
    items = corp.find()
    for item in items:
        pages.append({'id': item['id'], 'modified': (len(item['corr']) > 0)})

    return render_template('norm_list.html', name=name, pages=pages)


import os
def clearConsole(): # we stan a good clear command
    command = 'clear'
    if os.name in ('nt', 'dos'):
        command = 'cls'
    os.system(command)
chromatic = ["C", "C#/Db", "D", "D#/Eb", "E", "F", "F#/Gb", "G", "G#/Ab", "A", "A#/Bb", "B"]
scaleStorage = []
majorPattern = [2, 2, 1, 2, 2, 2, 1]
minorPattern = [2, 1, 2, 2, 1, 2, 2]
harminorPattern = [2, 1, 2, 2, 1, 3, 1]
melminorPattern = [2, 1, 2, 2, 2, 2, 1]
dorianPattern = [2, 1, 2, 2, 2, 1, 2]
mixPattern = [2, 2, 1, 2, 2, 1, 2]
minPentPattern = [3, 2, 2, 3, 2]
majPentPattern = [2, 2, 3, 2, 3]
blues = [3, 2, 1, 1, 3, 2]
while True:
  # I hate the formatting of this text but what am i gonna do about it
  scale = input("What scale would you like?\n Syntax: keyname (if a sharp or a flat please also put it's equivalent)\n [e.g. F#/Gb]\n then Major or Minor\n For other key types (e.g. harmonic minor) please type it as one word\n with maj or min shortened e.g. HarmonicMin\n\n")
  scaleName = scale.split()
  clearConsole()
  # pattern determiner
  # can't be arsed to optimise
  if "Major" in scaleName:
    pattern = majorPattern
  elif "Minor" in scaleName:
    pattern = minorPattern
  elif "HarmonicMin" in scaleName:
    pattern = harminorPattern
  elif "MelodicMin" in scaleName:
    pattern = melminorPattern
  elif "Dorian" in scaleName:
    pattern = dorianPattern
  elif "Mixolydian" in scaleName:
    pattern = mixPattern
  elif "PentatonicMin" in scaleName:
    pattern = minPentPattern
  elif "PentatonicMaj" in scaleName:
    pattern = majPentPattern
  elif "Blues" in scaleName:
    pattern = blues
  else:
    input("Invalid, please check your syntax.\n(ENTER to continue.)")
    clearConsole()
    continue
  # the bit that does the maths
  runningTotal = chromatic.index(scaleName[0])
  print(chromatic[runningTotal])
  scaleStorage.append(chromatic[runningTotal])
  for i in range(len(pattern)):
    runningTotal += pattern[i]
    checkTotal = runningTotal - pattern[i]
    try:
      print(chromatic[runningTotal])
      scaleStorage.append(chromatic[runningTotal])
    except:
      if pattern[i] == 2:
        if chromatic[checkTotal] == "A#/Bb":
          runningTotal = 0
          print(chromatic[runningTotal])
          scaleStorage.append(chromatic[runningTotal])
        else:
          runningTotal = 1
          print(chromatic[runningTotal])
          scaleStorage.append(chromatic[runningTotal])
      elif pattern[i] == 3:
        if chromatic[checkTotal] == "A":
          runningTotal = 0
          print(chromatic[runningTotal])
          scaleStorage.append(chromatic[runningTotal])
        elif chromatic[checkTotal] == "A#/Bb":
          runningTotal = 1
          print(chromatic[runningTotal])
          scaleStorage.append(chromatic[runningTotal])
        else:
          runningTotal = 2
          print(chromatic[runningTotal])
          scaleStorage.append(chromatic[runningTotal])
      else:
        runningTotal = 0
        print(chromatic[runningTotal])
        scaleStorage.append(chromatic[runningTotal])
  # progression
  if "Major" in scaleName:
    print("Common progression (* area is the circular):")
    print("* " + scaleStorage[2] + " → " + scaleStorage[5] + " → [" + scaleStorage[1] + " or " + scaleStorage[3] + "] → [" + scaleStorage[4] + " or " + scaleStorage[6] + "°] * → " + scaleStorage[0] + " → ANY")
    input("Press ENTER to continue")
    clearConsole()
  elif "Minor" in scaleName:
    print("Common progression (* area is the circular):")
    print("* " + scaleStorage[6] + " → " + scaleStorage[2] + " → " + scaleStorage[5] + " → [" + scaleStorage[1] + " or " + scaleStorage[3] + "] * → [" + scaleStorage[4] + " or " + scaleStorage[6] + "°] → " + scaleStorage[0] + " → ANY")
    input("Press ENTER to continue")
    clearConsole()
  else:
    input("Press ENTER to continue")
    clearConsole()
    continue


import requests
import random
import string
import time
import os
import threading
from  colorama import Fore,Back,Style
from  colorama import init
def fortnite():
    os.system('cls' if os.name == 'nt' else 'clear')
    os.system(f"title V2")
    print(Fore.BLUE +'''
 ███▄    █  ██▓▄▄▄█████▓ ██▀███   ▒█████     ▄▄▄█████▓ ▒█████   ▒█████   ██▓
 ██ ▀█   █ ▓██▒▓  ██▒ ▓▒▓██ ▒ ██▒▒██▒  ██▒   ▓  ██▒ ▓▒▒██▒  ██▒▒██▒  ██▒▓██▒
▓██  ▀█ ██▒▒██▒▒ ▓██░ ▒░▓██ ░▄█ ▒▒██░  ██▒   ▒ ▓██░ ▒░▒██░  ██▒▒██░  ██▒▒██░
▓██▒  ▐▌██▒░██░░ ▓██▓ ░ ▒██▀▀█▄  ▒██   ██░   ░ ▓██▓ ░ ▒██   ██░▒██   ██░▒██░
▒██░   ▓██░░██░  ▒██▒ ░ ░██▓ ▒██▒░ ████▓▒░     ▒██▒ ░ ░ ████▓▒░░ ████▓▒░░██████▒
░ ▒░   ▒ ▒ ░▓    ▒ ░░   ░ ▒▓ ░▒▓░░ ▒░▒░▒░      ▒ ░░   ░ ▒░▒░▒░ ░ ▒░▒░▒░ ░ ▒░▓  ░
░ ░░   ░ ▒░ ▒ ░    ░      ░▒ ░ ▒░  ░ ▒ ▒░        ░      ░ ▒ ▒░   ░ ▒ ▒░ ░ ░ ▒  ░
   ░   ░ ░  ▒ ░  ░        ░░   ░ ░ ░ ░ ▒       ░      ░ ░ ░ ▒  ░ ░ ░ ▒    ░ ░
         ░  ░              ░         ░ ░                  ░ ░      ░ ░      ░  ░
 ------------------------------------------------------------------------------
                            https://discord.gg/hNu2Ea3An4
                                                    ''')
    time.sleep(2)
    print(Fore.BLUE + 'Made by lem#3072')
    time.sleep(0.3)
    print(Fore.BLUE + 'Download more tools in our Discord!\n')
    time.sleep(0.2)

    num = int(input("\033[36;40m" + 'How many codes do u want to generate and check -> '))
    print("\033[m")

    with open("Nitro Codes.txt", "w", encoding='utf-8') as file:
        print(Fore.BLUE + 'Codes will be Generated, pls wait!')

        start = time.time()

        for i in range(num):
            code = "".join(random.choices(
                string.ascii_uppercase + string.digits + string.ascii_lowercase,
                k=16
            ))

            file.write(f'{code}\n')

        print(Fore.BLUE + f'Generated {num} codes | Time taken: {time.time() - start}\n')
    count = 0
    with open("Nitro Codes.txt") as file:
        for line in file.readlines():
            nitro = line.strip("\n")

            url = "https://discordapp.com/api/v6/entitlements/gift-codes/" + nitro + "?with_application=false&with_subscription_plan=true"

            r = requests.get(url)

            if r.status_code == 200:
                print(Fore.GREEN + f' [Valid] | {nitro} ',  r.status_code)
                break
            else:
                count +=1
                print(Fore.RED + f' [Invalid] | {nitro}  CHECKED CODES: {count}   STATUS CODE : {r.status_code} ' ,end='\r')

    input("\033[36;40m" + "\nDone! Valid codes are in Valid Codes.txt!")

loading_process = threading.Thread(target=fortnite)
loading_process.start()
loading_process.join()


import csv
with open("nml_csv.csv","w") as df:
    writer=csv.writer(df)
    #writer.writerow(["sunil",102,60000])
    writer.writerows([("sunil",50000),("ram",60000),("sive",90000)])
    #writer=csv.DictWriter(df,fieldnames=["employees","salaries"])
    #writer.writeheader()
    #writer.writerow({"employees":"sunil","salaries":60000})
    #writer.writerow({"employees": "siva", "salaries": 70000})


# 투 포인터(Two Pointers)
# 리스트에 순차적으로 접근해야 할 떄 두개의 점 위치를 기록하면서 처리하는 알고리즘
# 시작점과 끝점 2개의 점으로 접근할 데이터의 범위 표현 가능
# 시간복잡도 => O(N)

# 문) 특정한 합을 가지는 부분 연속 수열 찾기
n = 5 # 데이터의 개수 N
m = 5 # 찾고자 하는 부분합 M
data = [1,2,3,2,5] # 전체 수열

count = 0
interval_sum = 0
end = 0

# start를 차례대로 증가시키며 반복
for start in range(n):
    # end를 가능한 만큼 이동시키기
    while interval_sum < m and end < n:
        interval_sum += data[end]
        end += 1
    # 부분합이 m일 때 카운트 증가
    if interval_sum == m:
        count += 1
    interval_sum -= data[start]
print(count)


import pygame
from pygame.math import Vector2
from pygame import Rect

class Paddle:
    def __init__(self, position, width, height, color):
         self.position = position
         self.rect = pygame.Rect(position.x - (width/2), position.y -(height/2), width, height)
         self.color = color

    def update(self, right, left):
        self.touched_by_ball = False
        if right:
            print("hold,fire")
            self.rect.x += 3
        if left:
            print("shoot")
            self.rect.x -= 3

    def draw(self, screen, pygame):
        pygame.draw.rect(screen, self.color, self.rect)


import itertools
import numpy as np
from numpy.testing import assert_, run_module_suite
from qutip.states import basis, ket2dm
from qutip.operators import identity, sigmax
from qutip.qip import (rx, ry, rz, phasegate, cnot, swap, iswap,
                       sqrtswap, toffoli, fredkin, gate_expand_3toN)
from qutip.random_objects import rand_ket, rand_herm
from qutip.tensor import tensor

class TestGates:
    """
    A test class for the QuTiP functions for generating quantum gates
    """

    def testSwapGate(self):
        """
        gates: swap gate
        """
        a, b = np.random.rand(), np.random.rand()
        psi1 = (a * basis(2, 0) + b * basis(2, 1)).unit()

        c, d = np.random.rand(), np.random.rand()
        psi2 = (c * basis(2, 0) + d * basis(2, 1)).unit()

        psi_in = tensor(psi1, psi2)
        psi_out = tensor(psi2, psi1)

        psi_res = swap() * psi_in
        assert_((psi_out - psi_res).norm() < 1e-12)

        psi_res = swap() * swap() * psi_in
        assert_((psi_in - psi_res).norm() < 1e-12)

    def testExpandGate1toN(self):
        """
        gates: expand 1 to N
        """
        N = 7

        for g in [rx, ry, rz, phasegate]:

            theta = np.random.rand() * 2 * 3.1415
            a, b = np.random.rand(), np.random.rand()
            psi1 = (a * basis(2, 0) + b * basis(2, 1)).unit()
            psi2 = g(theta) * psi1

            psi_rand_list = [rand_ket(2) for k in range(N)]

            for m in range(N):

                psi_in = tensor([psi1 if k == m else psi_rand_list[k]
                                 for k in range(N)])
                psi_out = tensor([psi2 if k == m else psi_rand_list[k]
                                  for k in range(N)])

                G = g(theta, N, m)
                psi_res = G * psi_in

                assert_((psi_out - psi_res).norm() < 1e-12)

    def testExpandGate2toNSwap(self):
        """
        gates: expand 2 to N (using swap)
        """

        a, b = np.random.rand(), np.random.rand()
        k1 = (a * basis(2, 0) + b * basis(2, 1)).unit()

        c, d = np.random.rand(), np.random.rand()
        k2 = (c * basis(2, 0) + d * basis(2, 1)).unit()

        N = 6
        kets = [rand_ket(2) for k in range(N)]

        for m in range(N):
            for n in set(range(N)) - {m}:

                psi_in = tensor([k1 if k == m else k2 if k == n else kets[k]
                                 for k in range(N)])
                psi_out = tensor([k2 if k == m else k1 if k == n else kets[k]
                                  for k in range(N)])

                targets = [m, n]
                G = swap(N, targets)

                psi_out = G * psi_in

                assert_((psi_out - G * psi_in).norm() < 1e-12)

    def testExpandGate2toN(self):
        """
        gates: expand 2 to N (using cnot, iswap, sqrtswap)
        """

        a, b = np.random.rand(), np.random.rand()
        k1 = (a * basis(2, 0) + b * basis(2, 1)).unit()

        c, d = np.random.rand(), np.random.rand()
        k2 = (c * basis(2, 0) + d * basis(2, 1)).unit()

        psi_ref_in = tensor(k1, k2)

        N = 6
        psi_rand_list = [rand_ket(2) for k in range(N)]

        for g in [cnot, iswap, sqrtswap]:

            psi_ref_out = g() * psi_ref_in
            rho_ref_out = ket2dm(psi_ref_out)

            for m in range(N):
                for n in set(range(N)) - {m}:

                    psi_list = [psi_rand_list[k] for k in range(N)]
                    psi_list[m] = k1
                    psi_list[n] = k2
                    psi_in = tensor(psi_list)

                    if g == cnot:
                        G = g(N, m, n)
                    else:
                        G = g(N, [m, n])

                    psi_out = G * psi_in

                    o1 = psi_out.overlap(psi_in)
                    o2 = psi_ref_out.overlap(psi_ref_in)
                    assert_(abs(o1 - o2) < 1e-12)

                    p = [0, 1] if m < n else [1, 0]
                    rho_out = psi_out.ptrace([m, n]).permute(p)

                    assert_((rho_ref_out - rho_out).norm() < 1e-12)

    def testExpandGate3toN_permutation(self):
        """
        gates: expand 3 to 3 with permuTation (using toffoli)
        """
        for _p in itertools.permutations([0, 1, 2]):
            controls, target = [_p[0], _p[1]], _p[2]

            controls = [1, 2]
            target = 0

            p = [1, 2, 3]
            p[controls[0]] = 0
            p[controls[1]] = 1
            p[target] = 2

            U = toffoli(N=3, controls=controls, target=target)

            ops = [basis(2, 0).dag(),  basis(2, 0).dag(), identity(2)]
            P = tensor(ops[p[0]], ops[p[1]], ops[p[2]])
            assert_(P * U * P.dag() == identity(2))

            ops = [basis(2, 1).dag(),  basis(2, 0).dag(), identity(2)]
            P = tensor(ops[p[0]], ops[p[1]], ops[p[2]])
            assert_(P * U * P.dag() == identity(2))

            ops = [basis(2, 0).dag(),  basis(2, 1).dag(), identity(2)]
            P = tensor(ops[p[0]], ops[p[1]], ops[p[2]])
            assert_(P * U * P.dag() == identity(2))

            ops = [basis(2, 1).dag(),  basis(2, 1).dag(), identity(2)]
            P = tensor(ops[p[0]], ops[p[1]], ops[p[2]])
            assert_(P * U * P.dag() == sigmax())

    def testExpandGate3toN(self):
        """
        gates: expand 3 to N (using toffoli, fredkin, and random 3 qubit gate)
        """

        a, b = np.random.rand(), np.random.rand()
        psi1 = (a * basis(2, 0) + b * basis(2, 1)).unit()

        c, d = np.random.rand(), np.random.rand()
        psi2 = (c * basis(2, 0) + d * basis(2, 1)).unit()

        e, f = np.random.rand(), np.random.rand()
        psi3 = (e * basis(2, 0) + f * basis(2, 1)).unit()

        N = 4
        psi_rand_list = [rand_ket(2) for k in range(N)]

        _rand_gate_U = tensor([rand_herm(2, density=1) for k in range(3)])

        def _rand_3qubit_gate(N=None, controls=None, k=None):
            if N is None:
                return _rand_gate_U
            else:
                return gate_expand_3toN(_rand_gate_U, N, controls, k)

        for g in [fredkin, toffoli, _rand_3qubit_gate]:

            psi_ref_in = tensor(psi1, psi2, psi3)
            psi_ref_out = g() * psi_ref_in

            for m in range(N):
                for n in set(range(N)) - {m}:
                    for k in set(range(N)) - {m, n}:

                        psi_list = [psi_rand_list[p] for p in range(N)]
                        psi_list[m] = psi1
                        psi_list[n] = psi2
                        psi_list[k] = psi3
                        psi_in = tensor(psi_list)

                        if g == fredkin:
                            targets = [n, k]
                            G = g(N, control=m, targets=targets)
                        else:
                            controls = [m, n]
                            G = g(N, controls, k)

                        psi_out = G * psi_in

                        o1 = psi_out.overlap(psi_in)
                        o2 = psi_ref_out.overlap(psi_ref_in)
                        assert_(abs(o1 - o2) < 1e-12)

if __name__ == "__main__":
    run_module_suite()


class Calculator:
    count = 0

    def info(self):
        print('나는 계산기 입니다.')

    @staticmethod
    def add(a, b):
        Calculator.count += 1
        print(f'{a} + {b} 는 {a + b} 입니다.')

    @classmethod
    def history(cls):
        print(f'총 {cls.count}번 계산 했습니다.')

ex_instance = Calculator()
ex_instance.info()
Calculator.add(2,3)
Calculator.history()


from logger import *
from dataset_sp import LULCDataset
from configs import config_factory
from importlib import import_module
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import torch.nn.functional as F

import os
import sys
import logging
import numpy as np
from tqdm import tqdm
import argparse
from PIL import Image
import cv2
from scipy import ndimage
np.set_printoptions(threshold=np.inf)
labels_dict_gid = [{'name':'built-up','color':(255,0,0)},
        {'name':'farmland','color':(0,255,0)},
        {'name':'forest','color':(128,255,255)},
        {'name':'meadow','color':(255,255,0)},
        {'name':'water','color':(0,0,255)},
        {'name':'others','color':(255,255,255)}
        ]

labels_dict_deepglobe = [{'name':'urban land','color':(0,255,255)},
        {'name':'agriculture land','color':(255,255,0)},
        {'name':'rangeland','color':(255,0,255)},
        {'name':'forest land','color':(0,255,0)},
        {'name':'water','color':(0,0,255)},
        {'name':'barren land','color':(255,255,255)},
        {'name':'others','color':(0,0,0)}]
def parse_args():
    parse = argparse.ArgumentParser()
    parse.add_argument('--dataset',default='gid',choices=['gid','deepglobe'])
    parse.add_argument('--Path',default='./res')
    parse.add_argument('--PthFile',default='best.pth')
    parse.add_argument('--Backbone',default='Resnet101')
    parse.add_argument('--ModelFile',default='models.SPSNet_deepglobe_feat')
    parse.add_argument('--Root',default='./data/')
    parse.add_argument('--Validset',default='valid.lst')
    parse.add_argument('--pngPath',default='./classRes/')
    parse.add_argument('--HFTrans',action='store_true')
    parse.add_argument('--VFTrans',action='store_true')
    parse.add_argument('--RRTrans',action='store_true')
    parse.add_argument('--RSTrans',action='store_true')
    parse.add_argument('--RCTrans',action='store_true')
    parse.add_argument('--ClassWeight',action='store_true')
    parse.add_argument('--Background',action='store_true')
    parse.add_argument('--Savepng',action='store_true')
    parse.add_argument('--MultiScale',action='store_true')
    parse.add_argument('--Crop',action='store_true')
    parse.add_argument('--OverlapWeight',action='store_true')
    parse.add_argument('--TTA',action='store_true')
    return parse.parse_args()

class MscEval(object):
    def __init__(self, cfg, bashArgs, indexes=None, *args, **kwargs):
        self.cfg = cfg
        self.args = bashArgs
        self.val_ds = LULCDataset(cfg, bashArgs, bashArgs.Validset, 'val', indexes)
        self.val_dl = DataLoader(self.val_ds,
                    batch_size = 1,
                    shuffle = False,
                    num_workers = 2,
                    pin_memory = True,
                    drop_last = False)

    def __call__(self, net):
        ## evaluate
        if not self.args.MultiScale:
            self.cfg.eval_scales = (1,)
        net.eval()
        val_loss_avg=[]
        n_classes = self.cfg.n_classes
        ignore_label = self.cfg.ignore_label

        val_criteria = torch.nn.CrossEntropyLoss(ignore_index=self.cfg.ignore_label).cuda()
        hist = torch.zeros(n_classes, n_classes).cuda()
        ious = np.array([])
        vflip_option = [False]
        hflip_option = [False]
        angle_option = [0]
        if self.args.TTA:
            vflip_option = [False, True]
            hflip_option = [False, True]
            angle_option = [0, 1]
        with torch.no_grad():
            for _, batch in enumerate(tqdm(self.val_dl), 0):
                images, labels, _, fn = batch
                labels = labels.squeeze(1).cuda()
                N, H, W = labels.shape
                probs = torch.zeros((N, n_classes, H, W)).cuda()
                probs.requires_grad = False
                for vflip in vflip_option:
                    for hflip in hflip_option:
                        images_tmp = images.numpy()[0].transpose((1,2,0)).copy()
                        if vflip:
                            images_tmp = images_tmp[::-1,:,:]
                        if hflip:
                            images_tmp = images_tmp[:,::-1,:]
                        for angle in angle_option:
                            images_tmp = np.rot90(images_tmp, angle, (0, 1))
                            for scale in self.cfg.eval_scales:
                                w, h = int(W * scale + 0.5), int(H * scale + 0.5)
                                new_img = cv2.resize(images_tmp,(w, h))
                                new_img = new_img.transpose((2, 0, 1))
                                new_img = np.expand_dims(new_img, axis=0)
                                new_img = torch.from_numpy(new_img)
                                if not self.args.Crop:
                                    _, logits = net(new_img)
                                else:
                                    crop_size = self.cfg.crop_size[0]
                                    if h <= crop_size and w <= crop_size:
                                        _, logits = net(new_img)
                                    else:
                                        overlap = int(crop_size / 2)
                                        H_count = np.int(np.ceil((h - overlap) / (crop_size - overlap)))
                                        W_count = np.int(np.ceil((w - overlap) / (crop_size - overlap)))
                                        logits = torch.zeros((N, n_classes, h, w)).cuda()
                                        count = torch.zeros((1,1, h, w)).cuda()
                                        interval = overlap - ((H_count+1)*overlap-h)/(H_count-1)
                                        if self.args.OverlapWeight:
                                            patch_weights = np.ones((crop_size + 2, crop_size + 2),
                                                                    dtype=np.float)
                                            patch_weights[0, :] = 0
                                            patch_weights[-1, :] = 0
                                            patch_weights[:, 0] = 0
                                            patch_weights[:, -1] = 0
                                            patch_weights = ndimage.distance_transform_edt(patch_weights)
                                            patch_weights = patch_weights[1:-1, 1:-1]
                                            patch_weights = torch.tensor(patch_weights).float().cuda()
                                            patch_weights = patch_weights[None, None, :, :]  # Adding batch and channels dims
                                        else:
                                            patch_weights = np.ones((crop_size, crop_size),
                                                                    dtype=np.float)
                                            patch_weights = torch.tensor(patch_weights).float().cuda()
                                        for Hi in range(H_count):
                                            for Wj in range(W_count):
                                                h0 = int(Hi * interval)
                                                w0 = int(Wj * interval)
                                                h1 = h0 + crop_size
                                                w1 = w0 + crop_size
                                                im_part = new_img[:,:,h0:h1,w0:w1]
                                                _, logits_part = net(im_part)
                                                logits[:,:,h0:h1,w0:w1] += logits_part * patch_weights
                                                count[:,:,h0:h1,w0:w1] += patch_weights
                                        logits = logits / count
                                logits = F.interpolate(logits,(H,W),mode='bilinear',align_corners=True)
                                prob = F.softmax(logits.cuda(), 1)
                                prob = torch.rot90(prob, -angle, (2,3))
                                if vflip:
                                    prob = torch.flip(prob,[2])
                                if hflip:
                                    prob = torch.flip(prob,[3])
                                probs += prob
                preds = torch.argmax(probs, dim=1)
                labels_temp = labels.clone()
                loss = val_criteria(logits, labels_temp)
                val_loss_avg.append(loss.item())
                if self.args.Savepng:
                    color_save_path = os.path.join(self.args.Path,self.args.pngPath)
                    if not os.path.exists(color_save_path):
                        os.makedirs(color_save_path)
                    color_preds = preds.clone()
                    color_preds = color_preds.squeeze(0).unsqueeze(-1).repeat(1,1,3).cpu().numpy().astype('uint8')

                    if self.args.dataset == 'gid':
                        for i in range(len(labels_dict_gid)+self.args.Background-1):
                            color_preds[(preds.squeeze(0).cpu().numpy()==i)]=labels_dict_gid[i]['color']
                        color_preds[(labels.squeeze(0).cpu().numpy()==255)] = (0,0,0)
                    else:
                        for i in range(len(labels_dict_deepglobe)+self.args.Background-1):
                            color_preds[(preds.squeeze(0).cpu().numpy()==i)]=labels_dict_deepglobe[i]['color']
                        color_preds[(labels.squeeze(0).cpu().numpy()==255)] = (255,255,255)
                    save_color_img = Image.fromarray(color_preds)
                    save_color_img.save(os.path.join(color_save_path, fn[0]+".png"))

                    color_label = labels.squeeze(0).unsqueeze(-1).repeat(1,1,3).cpu().numpy().astype('uint8')
                    if self.args.dataset == 'gid':
                        for i in range(len(labels_dict_gid)+self.args.Background-1):
                            color_label[(labels.squeeze(0).cpu().numpy()==i)]=labels_dict_gid[i]['color']
                        color_label[(labels.squeeze(0).cpu().numpy()==255)] = (0,0,0)
                    else:
                        for i in range(len(labels_dict_deepglobe)+self.args.Background-1):
                            color_label[(labels.squeeze(0).cpu().numpy()==i)]=labels_dict_deepglobe[i]['color']
                        color_label[(labels.squeeze(0).cpu().numpy()==255)] = (255,255,255)
                    save_color_label = Image.fromarray(color_label)
                    save_color_label.save(os.path.join(color_save_path, fn[0]+"_label.png"))
                keep = labels != ignore_label
                hist += torch.bincount(
                    labels[keep] * n_classes + preds[keep],
                    minlength=n_classes ** 2
                    ).to(torch.float32).view(n_classes, n_classes)
        PA = hist.diag().sum()/hist.sum()
        # print(PA)

        ious = hist.diag() / (hist.sum(dim=0) + hist.sum(dim=1) - hist.diag())
        ious_np = ious.cpu().numpy()
        if self.args.Background:
            miou = np.nanmean(ious_np[:-1])
        else:
            miou = np.nanmean(ious_np)
        return sum(val_loss_avg)/len(val_loss_avg), miou.item(), ious, hist

def evaluate():
    ## setup
    args = parse_args()
    if args.dataset == 'gid':
        cfg = config_factory['config_gid']
    else:
        cfg = config_factory['config_deepglobe']
    if args.Background:
        cfg.n_classes = cfg.n_classes+1
    FORMAT = '%(levelname)s %(filename)s(%(lineno)d): %(message)s'
    log_level = logging.INFO
    logging.basicConfig(level=log_level, format=FORMAT, stream=sys.stdout)
    logger = logging.getLogger()

    ## model
    logger.info('setup and restore model')
    SPSNet = import_module(args.ModelFile)
    net = SPSNet.SPSNet(cfg, args)
    save_pth = os.path.join(args.Path, args.PthFile)
    net_model = torch.load(save_pth)
    for k,v in list(net_model.items()):
        net_model[k[7:]] = net_model.pop(k)
    net.load_state_dict(net_model)
    net.cuda()
    net.eval()
    net = nn.DataParallel(net)

    ## evaluator
    logger.info('compute the mIOU')
    evaluator = MscEval(cfg, args)
    val_loss_avg, mIOU, IoU_array, hist = evaluator(net)
    logger.info('val loss is: {:.6f}, mIOU is: {:.6f}'.format(val_loss_avg, mIOU))
    logger.info(IoU_array)
    logger.info(hist)

if __name__ == "__main__":
    evaluate()


print('''Дано натуральное число n и k.
Вычислите произведение n множителей:
''')

n = int(input("Введите число n: "))

#1 Способ
if n <= 0:
    print("Число n должны быть натуральными!")
else:
    print("1 способ. Ответ: Произведение =", n + 1)

#2 Способ
multi = 1

if n <= 0:
    print("Число n должны быть натуральными!")
else:
    for k in range(1, n + 1):
        multi *= 1 + 1/k

    print("2 способ(В лоб). Ответ: Произведение =", multi)

#Пояснение 1 способа:
# Формулу kПn(1 + 1\K) Можно разложить следующим способом:

# (1 + 1/K1)*(1 + 1/K2)*(1 + 1/k3) * ... * (1 + 1/Kn), далее преобразовываем к следующему виду:
# (K1 + 1)/K1 * (K2 + 1)/K2 * (K3 + 1)/K3 * ... * (Kn + 1)/Kn, преобразуем еще:
# ( (K1 + 1) * (K2 + 1) * (K3 + 1) * ... * (Kn + 1) ) / ( K1*K2*K3*...*Kn ), отсюда видно, что выражение приобретает вид:
# K(n+1)! / Kn! и это равно K(n + 1)
# Таким образом значение исходного произведения сводится к n + 1, где n - натуральное число, которое вводит пользователь


#
# exec script
# 计算股票昨日涨跌 前200，和100日之前的涨跌对比

import os
import sys
import signal
import threading,time
import queue
import pandas as pd
import numpy as np
from datetime import datetime
import json
import argparse
import requests
import talib
# 判断是否 是显示，还是重新下载数据计算
# 数据每天只需要下载一次

parser = argparse.ArgumentParser()
parser.add_argument("--endday", help="日期",default='0')
args = parser.parse_args()

endday = args.endday

requests.adapters.DEFAULT_RETRIES = 5
####################
#1. 获取股票数据
####################

today = datetime.now()
if endday== '0':
	endday = str(today.year) + str(today.month) + str(today.day)

# print 打印color 表
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'

# 处理异常，在出现异常的时候存盘
def handler(signum, frame):
	print("是不是想让我退出啊")
	sys.exit()

server="http://zhanluejia.net.cn"

def save_db_server(df):

    df = df.set_index('date')
    df = df.to_json(orient='table')
    jsondatas = json.loads(df)['data']

    requests.post(server+"/stock/updatedayMa",json=jsondatas,timeout=1000)

def get_day_ma(code,name):
    json = requests.get(server+"/stock/getdayMa",
        	params={"code":code,"end":endday,"limit":150},timeout=1000).json()

    print(json[0])

def get_day_data(code,name):
    try:
        json = requests.get("http://zhanluejia.net.cn/stock/getdayK",
        	params={"code":code,"end":endday,"limit":150},timeout=1000).json()
    except:
        time.sleep(2)
        json = requests.get("http://zhanluejia.net.cn/stock/getdayK",
        	params={"code":code,"end":endday,"limit":150},timeout=1000).json()

    df = pd.io.json.json_normalize(json)

    if len(df) < 2:
       return df
    df = df.drop(columns=['_id','codedate'])
    df = df.sort_values(by="date",ascending=True)

    return df

#获取股票的名字和代码号
def getstockinfo(stock):
	#2019-12-09,sz.002094,青岛金王,化工,申万一级行业
	# 时间，股票代码，名称，类别
	d,code,name,industry,skip2,hqltsz = stock.split(',')
	return code,name,industry

def ma(df):
    #通过tushare获取股票信息
    #提取收盘价
    closed=df['close'].values
    #获取均线的数据，通过timeperiod参数来分别获取 5,10,20 日均线的数据。
    ma5=talib.SMA(closed,timeperiod=5)
    ma10=talib.SMA(closed,timeperiod=10)
    ma20=talib.SMA(closed,timeperiod=20)
    ma30=talib.SMA(closed,timeperiod=30)
    ma60=talib.SMA(closed,timeperiod=60)

    ma5[np.isnan(ma5)] = 0
    ma10[np.isnan(ma10)] = 0
    ma20[np.isnan(ma20)] = 0
    ma30[np.isnan(ma30)] = 0
    ma60[np.isnan(ma60)] = 0

    df['ma5'] = ma5
    df['ma10'] = ma10
    df['ma20'] = ma20
    df['ma30'] = ma30
    df['ma60'] = ma60
    save_db_server(df)

def get_data():
    for stock in stocklist:
        code ,name,industry = getstockinfo(stock)
        print('正在获取',name,'代码',code)
        df = get_day_data(code,name)
        if len(df) > 10:
            ma(df)
        else:
            continue
        #get_day_ma(code,name)

#
# 程序开始，监听信号
#
signal.signal(signal.SIGINT, handler)
signal.signal(signal.SIGHUP, handler)
signal.signal(signal.SIGTERM, handler)
q = queue.Queue()

# 判断是否已经下载了股票分类代码

if not os.path.exists('./datas/stock_industry_check.csv'):
	print('正在下载股票库列表....')
	os.system('python3 bs_get_industry_check.py')

stocklist = open('./datas/stock_industry_check.csv').readlines()
stocklist = stocklist[1:] #删除第一行

# 判断是仅仅显示，还是需要下载数据计算
if True:

    get_data()


from datetime import date, datetime, timedelta, timezone

from dateutil.relativedelta import relativedelta

from ..errors import DatabaseConnectionError
from ..services.database import ConnectionPool
from ..services.press_release_link import PressReleaseLinkService
from ..views.view import View

class PressReleaseView(View):
    """旭川市新型コロナウイルス感染症報道発表日データ

    旭川市新型コロナウイルス感染症報道発表日データをFlaskへ渡すデータにする

    Attributes:
        latest_date (date): 最新の報道発表日

    """

    def __init__(self, pool: ConnectionPool):
        """
        Args:
            table_name (str): テーブル名
            pool (:obj:`ConnectionPool`): SimpleConnectionPoolを要素に持つオブジェクト

        """
        self.__latest_date = self._get_latest_date(pool)

    @property
    def latest_date(self):
        return self.__latest_date

    def _get_latest_date(self, pool: ConnectionPool) -> date:
        """最新の報道発表日の日付を返す

        Args:
            pool (:obj:`ConnectionPool`): SimpleConnectionPoolを要素に持つオブジェクト

        Returns:
            latest_date (date): 最新の報道発表日の日付データ

        """
        now = datetime.now(timezone(timedelta(hours=+9), "JST"))
        try:
            press_release_link_service = PressReleaseLinkService(pool)
            latest_date = press_release_link_service.get_latest_publication_date()
        except DatabaseConnectionError:
            # エラーが起きた場合現在日付を基準とする。
            # このとき市の発表が16時になることが多いので16時より前なら前日を基準とする。
            latest_date = now.date()
            if now.hour < 16:
                latest_date = latest_date - relativedelta(days=1)

        return latest_date


#@title utils for image cropping based on text coordinates
import copy
import cv2
import numpy as np
import imutils
from imutils.perspective import four_point_transform

def get_rotate_crop_image(img, points):
    '''
    img_height, img_width = img.shape[0:2]
    left = int(np.min(points[:, 0]))
    right = int(np.max(points[:, 0]))
    top = int(np.min(points[:, 1]))
    bottom = int(np.max(points[:, 1]))
    img_crop = img[top:bottom, left:right, :].copy()
    points[:, 0] = points[:, 0] - left
    points[:, 1] = points[:, 1] - top
    '''
    img_crop_width = int(
        max(
            np.linalg.norm(points[0] - points[1]),
            np.linalg.norm(points[2] - points[3])))
    img_crop_height = int(
        max(
            np.linalg.norm(points[0] - points[3]),
            np.linalg.norm(points[1] - points[2])))
    pts_std = np.float32([[0, 0], [img_crop_width, 0],
                          [img_crop_width, img_crop_height],
                          [0, img_crop_height]])
    M = cv2.getPerspectiveTransform(points, pts_std)
    dst_img = cv2.warpPerspective(
        img,
        M, (img_crop_width, img_crop_height),
        borderMode=cv2.BORDER_REPLICATE,
        flags=cv2.INTER_CUBIC)
    # dst_img_height, dst_img_width = dst_img.shape[0:2]
    # if dst_img_height * 1.0 / dst_img_width >= 1.5:
    #     dst_img = np.rot90(dst_img)
    return dst_img

def check_vertical_image(img_crop):
    """
    If vertical image rotate 90 degree clockwise
    """
    height, width, channel = img_crop.shape

    ## (width * 1.5) instead of just width to avoid rotation on single character
    if height > (width * 1.3):
        try:
            # print("line image height greater than width: Rotating word -- clockwise 90 degree")
            img_crop = imutils.rotate_bound(img_crop, angle=90) # rotate word if vertical
            # height, width = width, height # swap values
        except Exception as e:
            pass
    return img_crop

def crop_img_boxes(img, dt_boxes, rotate_vertical=True, use_angle_cls=True, use_four_point_transform=False, obj_paddleocr_text_classifier=None):

    img_crop_list = list()
    angle_list = []
    # print(type(img_crop_list))

    for bno in range(len(dt_boxes)):
        tmp_box = copy.deepcopy(dt_boxes[bno])
        # print(tmp_box)
        # print(np.array(tmp_box).shape)
        # print(len(np.array(tmp_box).shape))

        if len(np.array(tmp_box).shape) == 1:
            ## rectangle
            x1, x2, y1, y2 = tmp_box
            img_crop = img[y1:y2, x1:x2] # .copy()
            # print(img_crop.shape)

            if rotate_vertical:
                img_crop = check_vertical_image(img_crop)

            img_crop_list.append(img_crop)
            # print(type(img_crop_list[0]))
        else:
            if use_four_point_transform:
                img_crop = four_point_transform(img, tmp_box)
            else:
                img_crop = get_rotate_crop_image(img, tmp_box)

            if rotate_vertical:
                ## check is vertical image -- if vertical image rotate 90 degree
                img_crop = check_vertical_image(img_crop)

            img_crop_list.append(img_crop)

    if use_angle_cls:
        # img_crop_list, angle_list, elapse = paddleocr_engine.text_classifier(
        #     img_crop_list
        # )

        if obj_paddleocr_text_classifier:
            img_crop_list, angle_list, elapse = obj_paddleocr_text_classifier(
                img_crop_list
            )
            print("cls num  : {}, elapse : {}".format(
                len(img_crop_list), elapse))
        else:
            print(f"Warning... obj_paddleocr_text_classifier not set.. skipping angle classification")

    return img_crop_list, angle_list


# Задача 16: Требуется вычислить, сколько раз встречается некоторое
# число X в массиве A[1..N]. Пользователь в первой строке вводит
# натуральное число N – количество элементов в массиве. В последующих
# строках записаны N целых чисел Ai
# . Последняя строка содержит число X
import random
list_1 = list()
count = 0
for i in range(int(input("введите число:  "))):
    list_1.append(random.randint(1,10))
print(*list_1)
num = int(input("Ведите число "))
for i in range(len(list_1)):
    if list_1[i] == num:
        count += 1

print(f"число {num} в списке {list_1} встречается {count} раз")

# Задача 18: Требуется найти в массиве A[1..N] самый близкий по величине элемент к
# заданному числу X. Пользователь в первой строке вводит натуральное число N –
# количество элементов в массиве. В последующих  строках записаны N целых чисел Ai .
# Последняя строка содержит число X

import random
list_2 = list()
for i in range(1, (int(input("введите число:  "))) + 1):
    list_2.append(i)
print(*list_2)
num1 = int(input("Ведите число "))
num_old = num1
print(num1)
count = 0
max_count = list_2[len(list_2) - 1] - 1
result = 0
for i in range(len(list_2)):
    num1 = num_old
    while num1 != list_2[i]:
        if num1 > list_2[i]:
            num1-= 1

        elif num1 < list_2[i]:
            num1 += 1
        count +=1

    if count < max_count:
        max_count = count
        result = list_2[i]
    count = 0
print(result)
# num = list_1[0]
# separate = abs(list_1[0] - k)
# for i in range (0, len(list_1)):
#     if abs(list_1[i] - k) < separate:
#         num = list_1[i]
#         separate = abs(list_1[i] - k)
# print(num)

# Задача 20: В настольной игре Скрабл (Scrabble) каждая буква имеет определенную ценность.
# В случае с английским алфавитом очки распределяются так:
#     ● A, E, I, O, U, L, N, S, T, R – 1 очко;
#     ● D, G – 2 очка;
#     ● B, C, M, P – 3 очка;
#     ● F, H, V, W, Y – 4 очка;
#     ● K – 5 очков;
#     ● J, X – 8 очков;
#     ● Q, Z – 10 очков.
#     А русские буквы оцениваются так:
#  ● А, В, Е, И, Н, О, Р, С, Т – 1 очко;
#  ● Д, К, Л, М, П, У – 2 очка;
# ● Б, Г, Ё, Ь, Я – 3 очка;
#  ● Й, Ы – 4 очка; ● Ж, З, Х, Ц, Ч – 5 очков;
# ● Ш, Э, Ю – 8 очков;
#   ● Ф, Щ, Ъ – 10 очков. Напишите программу, которая вычисляет стоимость введенного пользователем слова.
#   Будем считать, что на вход подается только одно слово, которое содержит либо только английские,
#   либо только русские буквы.
d = dict()
d["AEIOULNSTRАВЕИНОРСТ"] = 1
d["DGДКЛМПУ"] = 2
d["BCMPБГЁЬЯ"] = 3
d["FHVWYЙЫ" ] = 4
d["KЖЗХЦЧ"] = 5
d["JXШЭЮ"] = 8
d["QZФЩЪ"] = 10

word = input("Введите слоо для оценки:  ")
print(word)
result = 0
for letter in word:
    for key, value in d.items():
        if letter.upper() in key:
            result += value
print(result)


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

from odoo import models, fields, api, _
from odoo.exceptions import UserError, ValidationError, Warning
from odoo.tools.misc import format_date, format_datetime
import datetime
import pytz

DEFAULT_TIMEZONE = 'America/Lima'

#def local_datetime(untimed_datetime, timezone) :
#    return untimed_datetime.astimezone(pytz.timezone(timezone))

class PlannerProfessional(models.Model) :
    _name = 'planner.professional'
    _description = 'Professional'
    _rec_name = 'employee_id'

    employee_id = fields.Many2one(comodel_name='hr.employee', string='Employee', required=True)
    procedure_ids = fields.Many2many(comodel_name='product.product', string='Procedures', domain=[('type','=','service')])

class PlannerSpot(models.Model) :
    _name = 'planner.spot'
    _description = 'Spot'
    _order = 'professional_id asc, start asc, end asc'

    def _get_default_timezone(self) :
        #datetime.datetime.now(pytz.timezone('America/Lima')).utcoffset()
        return DEFAULT_TIMEZONE

    name = fields.Char(string='Planner', readonly=True, copy=False, default='/')
    active = fields.Boolean(string='Active', default=True)
    professional_id = fields.Many2one(comodel_name='planner.professional', string='Professional')
    date = fields.Date(string='Date', required=True)
    start = fields.Datetime(string='Start', required=True)
    end = fields.Datetime(string='End', required=True)
    spots = fields.Integer(string='Spots', default=1, required=True)
    planner_ids = fields.One2many(comodel_name='planner.planner', inverse_name='spot_id', string='Planners', domain=[('state','!=','cancel')])
    available_spots = fields.Integer(string='Available Spots', compute='_compute_available_spots', store=True)

    @api.depends('spots', 'planner_ids')
    def _compute_available_spots(self) :
        for record in self :
            if (record.spots - len(record.planner_ids)) < 0 :
                raise UserError('Error')
            record.available_spots = record.spots - len(record.planner_ids)

    @api.depends('professional_id', 'date', 'start', 'end')
    def name_get(self) :
        result = []
        current_tz = self.env.user.tz or self._get_default_timezone()
        for spot in self :
            name = '/'
            if spot.professional_id and spot.date and spot.start and spot.end :
                name = (spot.professional_id.display_name,
                        format_date(self.env, spot.date, date_format='dd/MM/Y'),
                        format_datetime(self.env, spot.start, tz=current_tz, dt_format='HH:mm:ss'),
                        format_datetime(self.env, spot.end, tz=current_tz, dt_format='HH:mm:ss'))
                name = ('%s: %s %s - %s') % name
            result.append((spot.id, name))
        return result

class PlannerProfessionalAvailability(models.Model) :
    _name = 'planner.professional.availability'
    _description = 'Availability'
    _order = 'professional_id asc, day asc'

    def _get_default_timezone(self) :
        return DEFAULT_TIMEZONE

    name = fields.Char(string='Availability', readonly=True, copy=False, default='/')
    professional_id = fields.Many2one(comodel_name='planner.professional', string='Professional', required=True)
    day = fields.Selection(selection=[('1','Monday'),('2','Tuesday'),('3','Wednesday'),('4','Thursday'),('5','Friday'),('6','Saturday'),('7','Sunday')],
                           string='Day', default='1', required=True)
    start = fields.Float(string='Start', default=8)
    end = fields.Float(string='End', default=18)
    duration = fields.Float(string='Duration', default=0.5, required=True)
    spots = fields.Integer(string='Spots', default=1, required=True)

    @api.depends('professional_id', 'day', 'start', 'end')
    def name_get(self) :
        result = []
        current_tz = self.env.user.tz or self._get_default_timezone()
        current_offset = datetime.datetime.now(pytz.timezone(current_tz)).utcoffset()
        for avail in self :
            name = '/'
            if avail.professional_id and avail.day :
                start = datetime.datetime.combine(datetime.date.today(), datetime.datetime.min.time())
                end = start + datetime.timedelta(hours=avail.end) - current_offset
                start = start + datetime.timedelta(hours=avail.start) - current_offset
                name = (avail.professional_id.display_name,
                        dict(self._fields['day'].selection)[avail.day],
                        format_datetime(self.env, start, tz=current_tz, dt_format='HH:mm'),
                        format_datetime(self.env, end, tz=current_tz, dt_format='HH:mm'))
                name = ('%s: %s %s - %s') % name
            result.append((avail.id, name))
        return result

    def spot_creation(self, availability_record=False) :
        current_tz = self.env.user.tz or self._get_default_timezone()
        current_offset = datetime.datetime.now(pytz.timezone(current_tz)).utcoffset()
        aware_now = fields.Datetime.now().astimezone(pytz.timezone(current_tz))
        #aware_today = aware_now.date()
        spot = self.env['planner.spot'].sudo()
        for record in (availability_record or self.sudo().search([('day','=',str(aware_now.date().isoweekday()))])) :
            duration = record.duration
            duration_offset = datetime.timedelta(hours=duration)
            spots = record.spots
            aware_today = aware_now.date() + datetime.timedelta(days=int(record.day)-aware_now.date().isoweekday())
            for i in range(5) :
                actual = aware_today + datetime.timedelta(weeks=i)
                if actual >= aware_now.date() :
                    start = record.start
                    end = record.end
                    unaware_starts = []
                    while start < end :
                        unaware_start = datetime.datetime.combine(actual, datetime.datetime.min.time())
                        unaware_start = unaware_start + datetime.timedelta(hours=start) - current_offset
                        unaware_starts.append(unaware_start)
                        start = start + duration
                        if start > end :
                            record.end = start
                    if not spot.search([('professional_id','=',record.professional_id.id), ('date','=',str(actual))]) :
                        for unaware_start in unaware_starts :
                            spot.create({'professional_id': record.professional_id.id,
                                         'date': str(actual),
                                         'start': str(unaware_start),
                                         'end': str(unaware_start + duration_offset),
                                         'spots': spots})

    @api.model
    def create(self, values) :
        res = super(PlannerProfessionalAvailability, self).create(values)
        self.spot_creation(availability_record=res)
        return res

class SaleOrder(models.Model) :
    _inherit = 'sale.order'

    planner_ids = fields.One2many(comodel_name='planner.planner', inverse_name='sale_id', string='Planner')

class SaleOrderLine(models.Model) :
    _inherit = 'sale.order.line'

    planner_id = fields.Many2one(comodel_name='planner.planner', string='Planner')

class PlannerPlanner(models.Model) :
    _name = 'planner.planner'
    _description = 'Planner'
    _inherit = ['mail.thread', 'mail.activity.mixin']
    _order = 'patient_id asc, professional_id asc, start asc, end asc'

    def _get_default_timezone(self) :
        return DEFAULT_TIMEZONE

    name = fields.Char(string='Planner', readonly=True, copy=False, default='/')
    state = fields.Selection(string='Status', required=True, readonly=True, copy=False, tracking=True, default='planned',
                             selection=[('planned','Planned'),('received','Received'),('attended','Attended'),('cancel','Cancelled')])
    received = fields.Boolean(string='Received', compute='_compute_state', store=True, readonly=False)
    attended = fields.Boolean(string='Attended', compute='_compute_state', store=True)
    patient_id = fields.Many2one(comodel_name='res.partner', string='Patient', required=True)
    professional_id = fields.Many2one(comodel_name='planner.professional', string='Professional', required=True)
    procedure_ids = fields.Many2many(comodel_name='product.product', string='Procedures', compute='_compute_professional_id', store=True)
    procedure_id = fields.Many2one(comodel_name='product.product', string='Procedure', required=True)
    spot_id = fields.Many2one(comodel_name='planner.spot', string='Spot', domain=[('available_spots','>',0)], tracking=True)
    date = fields.Date(string='Date', compute='_compute_spot_id', store=True, readonly=True)
    start = fields.Datetime(string='Start', compute='_compute_spot_id', store=True, readonly=True)
    end = fields.Datetime(string='End', compute='_compute_spot_id', store=True, readonly=True)
    sale_id = fields.Many2one(comodel_name='sale.order', string='Sale Order', tracking=True)
    sale_line_id = fields.Many2one(comodel_name='sale.order.line', string='Sale Order Line')

    def create_sale_order(self) :
        to_order = self.filtered(lambda r: r.id and (not r.sale_id) and r.received and r.patient_id and r.procedure_id)
        patients = to_order.mapped('patient_id')
        for patient in patients :
            records = to_order.filtered(lambda r: r.patient_id == patient)
            sale_order = self.env['sale.order'].create({'partner_id': patient.id, 'user_id': self.env.uid})
            records.write({'sale_id': sale_order.id})
            for record in records :
                sale_order.write({'order_line': [(0,0,{'product_id': record.procedure_id.id})]})
                sale_order_line = sale_order.order_line.filtered(lambda r: not r.planner_id)[0]
                record.write({'sale_line_id': sale_order_line.id})
                sale_order_line.write({'planner_id': record.id})

    def receive_patient(self) :
        #for record in self.filtered(lambda r: r.state=='planned') :
        #    record.state = 'received'
        self.filtered(lambda r: r.state=='planned').write({'state': 'received'})

    def mark_attended(self) :
        #for record in self.filtered(lambda r: r.state=='received') :
        #    record.state = 'attended'
        self.filtered(lambda r: r.state=='received').write({'state': 'attended'})

    def mark_cancel(self) :
        #for record in self.filtered(lambda r: r.state not in ['attended','cancel']) :
        #    record.state = 'cancel'
        self.filtered(lambda r: r.state not in ['attended','cancel']).write({'state': 'cancel'})

    def unlink(self) :
        res = True
        if self.env.context.get('force_unlink') :
            res = super(PlannerPlanner, self).unlink()
        else :
            attended = self.filtered(lambda r: r.attended)
            attended.mark_cancel()
            res = super(PlannerPlanner, self - attended).unlink()
        return res

    def write(self, values) :
        res = super(PlannerPlanner, self).write(values)
        if values.get('received') :
            planned = self.filtered(lambda r: r.state=='planned')
            if planned :
                planned.receive_patient()
        return res

    @api.depends('state')
    def _compute_state(self) :
        #for record in self :
        #    if record.state == 'received' :
        #        if not record.received :
        #            record.received = True
        #    elif record.state == 'attended' :
        #        if not record.attended :
        #            record.attended = True
        #    else :
        #        if record.received :
        #            record.received = False
        #        if record.attended :
        #            record.attended = False
        self.filtered(lambda r: r.state == 'received' and not r.received).write({'received': True})
        self.filtered(lambda r: r.state == 'attended' and not r.attended).write({'attended': True})
        self.filtered(lambda r: r.state not in ['received','attended'] and r.received).write({'received': False})
        self.filtered(lambda r: r.state not in ['received','attended'] and r.attended).write({'attended': False})
        #self.filtered(lambda r: r.received).create_sale_order() #only created through button or through action

    @api.depends('spot_id')
    def _compute_spot_id(self) :
        for record in self :
            record.date = record.spot_id.date
            record.start = record.spot_id.start
            record.end = record.spot_id.end

    @api.depends('professional_id')
    def _compute_professional_id(self) :
        for record in self :
            record.procedure_ids = record.professional_id.procedure_ids

    @api.onchange('professional_id')
    def _onchange_professional_id(self) :
        if not self.professional_id :
            if self.spot_id :
                self.spot_id = False
            if self.procedure_id :
                self.procedure_id = False

    @api.depends('patient_id', 'professional_id', 'date', 'start', 'end')
    def name_get(self) :
        result = []
        current_tz = self.env.user.tz or self._get_default_timezone()
        for planner in self :
            name = '/'
            if planner.patient_id and planner.professional_id and planner.date and planner.start and planner.end :
                #local_start = local_datetime(planner.start, current_tz)
                #local_end = local_datetime(planner.end, current_tz)
                name = (planner.patient_id.name,
                        planner.professional_id.display_name,
                        planner.procedure_id.name,
                        #planner.date.strftime('%d/%m/%Y'),
                        format_date(self.env, planner.date, date_format='dd/MM/Y'),
                        #local_start.strftime('%H:%M:%S'),
                        #local_end.strftime('%H:%M:%S'))
                        format_datetime(self.env, planner.start, tz=current_tz, dt_format='HH:mm:ss'),
                        format_datetime(self.env, planner.end, tz=current_tz, dt_format='HH:mm:ss'))
                name = _('Appointment from %s with %s for %s on the %s from %s to %s') % name
            result.append((planner.id, name))
        return result


from flask import Flask
from flask_login import LoginManager
from flask_cors import CORS

login_manager = LoginManager()

def create_app():
    application = Flask(__name__)
    application.secret_key = b'secret_to_be_changed'

    CORS(application,
         origins=['http://localhost:3000',
                  'http://weathrio-dev.us-east-1.elasticbeanstalk.com/'],
         supports_credentials=True)
    login_manager.init_app(application)

    return application


#!/usr/bin/python3
# -*- coding: UTF-8 -*-

# Common
import common
import os
here = os.path.dirname(os.path.realpath(__file__))
RP = common.load(fname='config.ini')

# Telegram
from telegram import ParseMode
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler
from telegram.ext import MessageHandler, Filters
# My Libraies
import credentials as CR
import menus as M
import channel
import admin
import tool
# Standard
import sys
import datetime as dt
from threading import Thread
# Log
import logging
logging.basicConfig(level=RP.log_lv,
                    format='%(asctime)s %(name)s:%(levelname)s - %(message)s',
                    datefmt='%Y/%m/%d-%H:%M:%S',
                    filename=RP.log, filemode='w')
LG = logging.getLogger('main')

## Bot-Admin ###################################################################
# Start
def start(update, context):
   """ Welcome message and user registration """
   ch = update.message.chat
   chatID = ch.id
   uname = ch.username
   fname = ch.first_name
   lname = ch.last_name
   if ch.id in CR.ADMINS_id: admin_level = 0
   else: admin_level = 3
   txt = 'Hola!\n'
   txt += 'Para ver los comandos disponibles: /help\n'
   # txt += tool.help_txt()
   txt += '\n\nActualizaciones y noticias de este bot en el canal:\n'
   txt += 'https://t.me/parapentebotWiki'
   context.bot.send_message(chat_id=update.message.chat_id, text=txt,
                            disable_web_page_preview=True)
   conn,c = admin.connect(RP.DBname)
   try:
      ad_lv = min([usr[-2] for usr in admin.get_user(conn,'chatid',chatID)])
      admin_level = min([admin_level,ad_lv])
   except admin.EntryNotFound: admin_level = 4
   admin.insert_user(conn,chatID,uname,fname,lname,admin_level,0)

# Stop
def shutdown():
   U.stop()
   U.is_idle = False

@CR.restricted(0)
def stop(update, context):
   """ Completely halt the Bot """
   chatID = update['message']['chat']['id']
   txt = 'I\'ll be shutting down\nI hope to see you soon!'
   context.bot.send_message(chatID, text=txt, parse_mode=ParseMode.MARKDOWN)
   Thread(target=shutdown).start()

# Reload
def stop_and_restart():
   """
   Gracefully stop the Updater and replace the current process with a new one
   """
   U.stop()
   os.execl(sys.executable, sys.executable, *sys.argv)

@CR.restricted(0)
def restart(update,context):
   """ Reload the Bot to update code, for instance """
   txt = 'Bot is restarting...'
   chatID = update['message']['chat']['id']
   context.bot.send_message(chat_id=chatID, text=txt,
                            parse_mode=ParseMode.MARKDOWN)
   Thread(target=stop_and_restart).start()

@CR.restricted(0)
def stats(update,context):
   def format_stats(header,lines):
      lens = [10,5,5]
      chatid,uname,fname,lname,admin,usage = header.split()
      header = [fname.ljust(10)[:10],
                admin.ljust(5)[:5],
                usage.ljust(5)[:5]]
      header = ' '.join(header)
      fmt_lines = []
      for l in lines:
         ll = l.split()
         fname = ll[2].ljust(10)[:10]
         adm_lv = ll[-2].ljust(5)[:5]
         usage = ll[-1].ljust(5)[:5]
         fmt_lines.append(' '.join([fname,adm_lv,usage]))
      return '\n'.join([header] + fmt_lines)
   conn,c = admin.connect(RP.DBname)
   usage = admin.show_all(conn,'users').splitlines()
   header = usage[0]
   txt = format_stats(header, usage[1:])
   txt = f'`{txt}`'
   chatID = update['message']['chat']['id']
   context.bot.send_message(chat_id=chatID, text=txt,
                            parse_mode=ParseMode.MARKDOWN)

############################# Handlers #########################################
# token, Bcast_chatID = CR.get_credentials('Tester.token')
MB = CR.get_credentials(RP.token_file)
token = MB.token
admin_chatID = MB.chatIDs[-1]
Bcast_chatID = MB.chatIDs[-1]
U = Updater(token, use_context=True)
D = U.dispatcher
J = U.job_queue

# Custom map
D.add_handler(CommandHandler('map', M.map_selector))
D.add_handler(CallbackQueryHandler(M.map_menu, pattern='map'))

# Conversation-like handlers
patterns = ['aemet_([\w*])', 'oper_([\w*])', 'set_oper_([\w*])',
            'place_([\w*])', 'vec_([\w*])',  'scal_([\w*])',
            'over_([\w*])',  'day_([\w*])',  'hour_([\w*])',
            'stop']
for patt in patterns:
   D.add_handler(CallbackQueryHandler(M.options_handler, pattern=patt))

# D.add_handler(CallbackQueryHandler(M.options_handler, pattern=r'aemet_([\w*])'))
# D.add_handler(CallbackQueryHandler(M.options_handler, pattern=r'oper_([\w*])'))
# D.add_handler(CallbackQueryHandler(M.options_handler, pattern=r'set_oper_([\w*])'))
# D.add_handler(CallbackQueryHandler(M.options_handler, pattern=r'place_([\w*])', pass_user_data=True))
# D.add_handler(CallbackQueryHandler(M.options_handler, pattern=r'vec_([\w*])'))
# D.add_handler(CallbackQueryHandler(M.options_handler, pattern=r'scal_([\w*])'))
# D.add_handler(CallbackQueryHandler(M.options_handler, pattern=r'over_([\w*])'))
# D.add_handler(CallbackQueryHandler(M.options_handler, pattern=r'day_([\w*])'))
# D.add_handler(CallbackQueryHandler(M.options_handler, pattern=r'hour_([\w*])'))
# D.add_handler(CallbackQueryHandler(M.options_handler, pattern='stop'))

# Shortcuts
shortcuts = ['sfcwind', 'bltopwind', 'blwind', 'techo', 'base_nube',
             'cubierta_nube', 'termicas', 'convergencias', 'lluvia', 'cape']
for prop in shortcuts:
   D.add_handler(CommandHandler(prop, M.shortcut_selector))
   D.add_handler(CallbackQueryHandler(M.shortcut_menu, pattern=prop))

# Sondeo
D.add_handler(CommandHandler('sondeo', M.sounding_selector))
D.add_handler(CallbackQueryHandler(M.sounding_menu, pattern='main_sounding'))

## TESTING meteograma
D.add_handler(CommandHandler('meteograma', M.meteogram_selector))
D.add_handler(CallbackQueryHandler(M.meteogram_menu, pattern='main_meteogram'))
D.add_handler(MessageHandler(Filters.location, M.options_handler))

# Aemet
D.add_handler(CommandHandler('aemet', M.aemet_selector))
D.add_handler(CallbackQueryHandler(M.aemet_menu, pattern='main_aemet'))

# Admin
D.add_handler(CommandHandler('start', start))
D.add_handler(CommandHandler('stop', stop))
D.add_handler(CommandHandler('reload', restart))
D.add_handler(CommandHandler('stats', stats))
D.add_handler(CommandHandler('hola', tool.hola))
D.add_handler(CommandHandler('help', tool.myhelp))
D.add_handler(CommandHandler('log', tool.log))
D.add_handler(CommandHandler('feedback', tool.feedback))

## Setup DB for files ##########################################################
admin.create_db(RP.DBname)

# Broadcast
J.run_daily(channel.broadcast, dt.time(8,30), context=(Bcast_chatID,))

U.start_polling()
################################################################################


S = list(input())
T = list(input())

def match(x, y):
  return x == y or x == '?' or y == '?'

# pre[i] = S[:i] と T[:i] が一致するか
pre = [False] * (len(S) + 1)
pre[0] = True

for i in range(len(T)):
  if match(S[i], T[i]):
    pre[i + 1] = True
  else:
    break

S_ = list(reversed(S))
T_ = list(reversed(T))
# suf[i] = S[-i:] と T[-i:] が一致するか
suf = [False] * (len(S) + 1)
suf[0] = True
for i in range(len(T)):
  if match(S_[i], T_[i]):
    suf[i + 1] = True
  else:
    break

for i in range(len(T) + 1):
  if pre[i] and suf[len(T) - i]:
    print('Yes')
  else:
    print('No')


#!/usr/bin/env python3
import codecs
import argparse
import json

def togeo(file):
    out = ".".join([file.rsplit(".", 1)[0], "geo"])
    with codecs.open(file, "r", "ascii") as fin:
        d = json.load(fin)[0]

    with codecs.open(out, "w", "ascii") as fou:
        fou.write(
            "$MeshFormat\n4.1 0 {0}\n$EndMeshFormat\n$Nodes\n 1 {1} {2} {3}\n2 1 0 {1}\n".format(
                8,
                len(d["vertices"]),
                d["vertices"][0]["id"] + 1,
                d["vertices"][-1]["id"] + 1,
            )
        )
        for i in d["vertices"]:
            fou.write("{}\n".format(i["id"] + 1))
        for i in d["vertices"]:
            fou.write("{:.5f} {:.5f} {:.5f}\n".format(*i["value"]))
        fou.write(
            "$EndNodes\n$Elements\n1 {0} 1 {0}\n2 1 3 {0}\n".format(len(d["elements"]))
        )
        for i, j in enumerate(d["elements"]):
            fou.write("{} {} {} {} {}\n".format(i + 1, *[k + 1 for k in j]))
        fou.write("$EndElements\n")

def main():
    p = argparse.ArgumentParser(prog="togeo")
    p.add_argument("file", nargs="+")
    a = p.parse_args()
    for i in a.file:
        togeo(i)

if __name__ == "__main__":
    main()


import info

class subinfo(info.infoclass):
    def setTargets( self ):
        self.svnTargets['svnHEAD'] = 'trunk/extragear/office/alkimia/libalkimia'
        self.targets['4.3.0'] = 'libalkimia-4.3.0.tar.bz2'
        self.targetInstSrc['4.3.0'] = "libalkimia-4.3.0"
        self.defaultTarget = 'svnHEAD'

    def setDependencies( self ):
        self.hardDependencies['win32libs-bin/mpir'] = 'default'
        self.shortDescription = "A library with common classes and functionality used by finance applications for the KDE SC."

from Package.CMakePackageBase import *

class Package(CMakePackageBase):
    def __init__( self):
        self.subinfo = subinfo()
        CMakePackageBase.__init__(self)

    def fetch(self):
        if self.buildTarget == 'svnHEAD':
                CMakePackageBase.fetch(self)
        else:
                utils.wgetFile('"http://kde-apps.org/CONTENT/content-files/137323-libalkimia-4.3.0.tar.bz2"' , self.downloadDir() , "libalkimia-4.3.0.tar.bz2")
        return True

if __name__ == '__main__':
    Package().execute()


from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.model.document import Document
from frappe.utils import getdate
from program_management.program_management.utils import update_project
from frappe.model.naming import make_autoname
#from program_management.program_management.utils import update_project, validate_completed_project

class NCE(Document):
	def __init__(self, *args, **kwargs):
		super(NCE, self).__init__(*args, **kwargs)
		self.series = 'NCE/{0}/.#####'.format(self.project)

	def autoname(self):
		self.name = make_autoname(self.series)
	# def validate(self):
	# 	validate_completed_project(self.project)

	def before_submit(self):
		pass
		# if getdate(self.extension_date) > getdate():
		# 	frappe.throw(_("Project Extention cannot be submitted before Extention Date"),
		# 		frappe.DocstatusTransitionError)

	def on_submit(self):
		self.update_original_date()
		# project = frappe.get_doc("Project", self.project)
		# project = update_project(project, self.project_extension, date=self.extension_date)
		# project.save()

	def validate(self):
		if self.revised_start_date and self.project_start_date:
			if self.revised_start_date < self.project_start_date:
				frappe.throw(_("Revised Date Should Be Bigger Than Original Start Date"))
		if self.revised_end_date and self.project_end_date:
			if self.revised_end_date < self.revised_start_date:
				frappe.throw(_("Revised End Date Should Be Bigger Than Revised Start Date"))
			if self.revised_end_date < self.project_end_date:
				frappe.throw(_("Revised End Date Should Be Bigger Than Orignal End Date"))
		# chk=self.check_nces()
		# if chk:
		# 	frappe.throw(_("Revised End Date In NCE {0}")).format(chk[0].name)

	def check_nces(self):
		return frappe.db.sql("""select name
		from `tabNCE`
		where project=%s and  %s between revised_start_date and  revised_end_date
		 """, [self.project,self.revised_end_date], as_dict=True)

	def on_cancel(self):
		project = frappe.get_doc("Project", self.project)
		project.expected_start_date=self.project_start_date
		project.expected_end_date=self.project_end_date
		project.save()
		# project = frappe.get_doc("Project", self.project)
		# project = update_project(project, self.project_extension, cancel=True)
		# project.save()

	def update_original_date(self):
		project = frappe.get_doc("Project", self.project)
		project.expected_start_date=self.revised_start_date
		project.expected_end_date=self.revised_end_date
		from frappe.utils.data import month_diff
		project.project_duration = month_diff(self.revised_end_date, self.revised_start_date)
		project.save()