# https://leetcode-cn.com/problems/climbing-stairs/
# 把每一步的结果存储在 memo 数组之中
# 每当函数再次被调用，我们就直接从 memo 数组返回结果

class Solution:
    def climb(self, i, n, memo):
        if i > n:
            return 0
        if i == n:
            return 1
        if memo[i] > 0:
            return memo[i]
        memo[i] = Solution().climb(i+1, n, memo) + \
            Solution().climb(i+2, n, memo)
        print(i, n, memo)
        return memo[i]

    def climbStairs(self, n) -> int:
        memo = [0] * n
        return Solution().climb(0, n, memo)

print(Solution().climbStairs(5))

# 比如算memo[3]的时候会用到memo[4]和memo[5]，总之省下了一些重复计算的
# 直到最后一步memo[0] = 8
# 0 5 [0, 0, 0, 0, 0]
# 1 5 [0, 0, 0, 0, 0]
# 2 5 [0, 0, 0, 0, 0]
# 3 5 [0, 0, 0, 0, 0]
# 4 5 [0, 0, 0, 0, 0]
# 4 5 [0, 0, 0, 0, 1]
# 3 5 [0, 0, 0, 2, 1]
# 2 5 [0, 0, 3, 2, 1]
# 1 5 [0, 5, 3, 2, 1]
# 0 5 [8, 5, 3, 2, 1]


"""Make a new thread by calling clone

That is to say, make a new thread the normal way.

"""
from __future__ import annotations
from dataclasses import dataclass
from rsyscall._raw import ffi # type: ignore
from rsyscall.concurrency import OneAtATime
from rsyscall.epoller import AsyncFileDescriptor
from rsyscall.handle import Stack, WrittenPointer, Pointer, FutexNode, FileDescriptor, Task, FutexNode
from rsyscall.loader import Trampoline, NativeLoader
from rsyscall.memory.allocator import Arena
from rsyscall.memory.ram import RAM
from rsyscall.monitor import AsyncChildProcess, ChildProcessMonitor
from rsyscall.struct import Int32
from rsyscall.tasks.base_sysif import BaseSyscallInterface
from rsyscall.tasks.connection import SyscallConnection
from rsyscall.near.sysif import SyscallHangup
import contextlib
import logging
import rsyscall.far as far
import trio
import typing as t

from rsyscall.sched import CLONE
from rsyscall.signal import SIG
from rsyscall.sys.mman import PROT, MAP
from rsyscall.sys.wait import W

__all__ = [
    'ChildExit',
    'MMRelease',
    'ChildSyscallInterface',
    'launch_futex_monitor',
    'clone_child_task',
    'ForkThread',
]

class ChildExit(SyscallHangup):
    "The task we were sending syscalls to has exited"
    pass

class MMRelease(SyscallHangup):
    """The task we were sending syscalls to has either exited or exec'd; either way it can no longer respond

    More concretely, the task has left its old address space - it has called the
    mm_release kernel function (hence the name of this class).

    """
    pass

class ChildSyscallInterface(BaseSyscallInterface):
    """A connection to an rsyscall server that is one of our child processes

    We take as arguments here not only a SyscallConnection, but also an
    AsyncChildProcess monitoring the child process to which we will send
    syscalls.

    This is useful for situations where we can't rely on getting an EOF if the
    other side of a connection dies. That will happen, for example, whenever the
    child process is sharing a file descriptor table with us. In those
    situations, we need some other means to detect that a syscall will never be
    responded to, and signal it to the caller by throwing SyscallHangup.

    In this class, we detect a hangup while waiting for a syscall response by
    simultaneously monitoring the child process. If the child process exits, we
    stop waiting for the syscall response and throw SyscallHangup back to the
    caller.

    This is not just a matter of failure cases, it's also important for normal
    functionality. Detecting a hangup is our only way to discern whether a call
    to exit() was successful, and rsyscall.near.exit treats receiving an
    RsycallHangup as successful.

    We also take a futex_process: AsyncChildProcess. This is also used for
    normal functionality: futex_process should exit when the process has
    successfully called exec. This is again our only way of detecting a
    successful call to exec, and rsyscall.near.execve treats receiving an
    RsycallHangup as successful. (Concretely, futex_process will also exit when
    the process exits, not just when it execs, but that's harmless)

    A better way of detecting exec success would be great...

    """
    def __init__(self,
                 rsyscall_connection: SyscallConnection,
                 server_process: AsyncChildProcess,
                 futex_process: t.Optional[AsyncChildProcess],
    ) -> None:
        super().__init__(rsyscall_connection)
        self.server_process = server_process
        self.futex_process = futex_process
        self.logger = logging.getLogger(f"rsyscall.ChildSyscallInterface.{int(self.server_process.process.near)}")
        self.running_read = OneAtATime()

    @contextlib.asynccontextmanager
    async def _throw_on_child_exit(self) -> t.AsyncGenerator[None, None]:
        """Monitor the child process and throw if it exits or execs

        Naturally, if the child does exit or exec while we're in the context
        manager body, we'll cancel the context manager body so that we don't
        spend forever waiting on a dead child.

        This is useful for detecting a situation where we've sent a request and
        will never receive a response, particularly for syscalls as documented
        in the module docstring.

        The application to syscalls is the primary purpose of this method; but
        this method is also useful for some other thread implementations, so we
        expose it with this relatively generic interface.

        """
        child_exited = False
        futex_exited = False
        got_result = False
        async with trio.open_nursery() as nursery:
            async def server_exit() -> None:
                await self.server_process.waitpid(W.EXITED)
                nonlocal child_exited
                child_exited = True
                nursery.cancel_scope.cancel()
            async def futex_exit() -> None:
                if self.futex_process is not None:
                    await self.futex_process.waitpid(W.EXITED)
                    nonlocal futex_exited
                    futex_exited = True
                    nursery.cancel_scope.cancel()
            nursery.start_soon(server_exit)
            nursery.start_soon(futex_exit)
            yield
            got_result = True
            nursery.cancel_scope.cancel()
        if got_result:
            return
        elif child_exited:
            # this takes precedence over MMRelease, since it gives us more information
            raise ChildExit()
        elif futex_exited:
            raise MMRelease()

    async def _read_syscall_responses_direct(self) -> None:
        async with self._throw_on_child_exit():
            await self.rsyscall_connection.read_pending_responses()
        self.logger.debug("returning after reading some syscall responses")

    async def _read_pending_responses(self) -> None:
        async with self.running_read.needs_run() as needs_run:
            if needs_run:
                self.logger.debug("running read_syscall_responses_direct")
                await self._read_syscall_responses_direct()
                self.logger.debug("done with read_syscall_responses_direct")

async def launch_futex_monitor(ram: RAM,
                               loader: NativeLoader, monitor: ChildProcessMonitor,
                               futex_pointer: WrittenPointer[FutexNode]) -> AsyncChildProcess:
    """Launch a process to wait on a futex; then we monitor the process to monitor the futex

    This process calls futex(futex_pointer, FUTEX_WAIT, futex_pointer.value) and
    then exits, so this process will exit if and when the futex has FUTEX_WAKE
    called on it.

    Sadly, this is the best we can do with integrating futexes into our event
    loop. There used to be a way to get a file descriptor to represent a futex,
    but it was removed because it was racy.

    Something better would be really great - especially because it would allow
    incorporating pthreads locks and other shared memory concurrency mechanisms
    based on futexes, into a normal event loop.

    """
    async def op(sem: RAM) -> t.Tuple[Pointer[Stack], WrittenPointer[Stack]]:
        stack_value = loader.make_trampoline_stack(Trampoline(
            loader.futex_helper_func, [
                int(futex_pointer.near + ffi.offsetof('struct futex_node', 'futex')),
                futex_pointer.value.futex]))
        stack_buf = await sem.malloc(Stack, 4096)
        stack = await stack_buf.write_to_end(stack_value, alignment=16)
        return stack
    stack = await ram.perform_batch(op)
    futex_process = await monitor.clone(CLONE.VM|CLONE.FILES, stack)
    # wait for futex helper to SIGSTOP itself,
    # which indicates the trampoline is done and we can deallocate the stack.
    state = await futex_process.waitpid(W.EXITED|W.STOPPED)
    if state.state(W.EXITED):
        raise Exception("thread internal futex-waiting task died unexpectedly", state)
    # resume the futex_process so it can start waiting on the futex
    await futex_process.kill(SIG.CONT)
    # TODO uh we need to actually call something to free the stack
    return futex_process

async def clone_child_task(
        parent: ForkThread,
        flags: CLONE,
        trampoline_func: t.Callable[[FileDescriptor], Trampoline],
) -> t.Tuple[AsyncChildProcess, Task]:
    """Clone a new child process and setup the sysif and task to manage it

    We rely on trampoline_func to take a socket and give us a native function call with
    arguments that will speak the rsyscall protocol over that socket.

    We also create a futex process, which we use to monitor the ctid futex.
    This process allows us to detect when the child successfully finishes an
    exec; see the docstring of ChildSyscallInterface.  Because we set
    CLONE.CHILD_CLEARTID, the ctid futex will receive a FUTEX_WAKE when the
    child process exits or execs, and the futex process will accordingly exit.

    """
    # Open a channel which we'll use for the rsyscall connection
    [(access_sock, remote_sock)] = await parent.connection.open_async_channels(1)
    # Create a trampoline that will start the new process running an rsyscall server
    trampoline = trampoline_func(remote_sock)
    # Force these flags to be used
    flags |= CLONE.VM|CLONE.FILES|CLONE.IO|CLONE.SYSVSEM
    # TODO it is unclear why we sometimes need to make a new mapping here, instead of
    # allocating with our normal allocator; all our memory is already MAP.SHARED, I think.
    # We should resolve this so we can use the normal allocator.
    arena = Arena(await parent.task.mmap(4096*2, PROT.READ|PROT.WRITE, MAP.SHARED))
    async def op(sem: RAM) -> t.Tuple[t.Tuple[Pointer[Stack], WrittenPointer[Stack]],
                                                       WrittenPointer[FutexNode]]:
        stack_value = parent.loader.make_trampoline_stack(trampoline)
        stack_buf = await sem.malloc(Stack, 4096)
        stack = await stack_buf.write_to_end(stack_value, alignment=16)
        futex_pointer = await sem.ptr(FutexNode(None, Int32(0)))
        return stack, futex_pointer
    # Create the stack we'll need, and the zero-initialized futex
    stack, futex_pointer = await parent.ram.perform_batch(op, arena)
    # it's important to start the processes in this order, so that the thread
    # process is the first process started; this is relevant in several
    # situations, including unshare(NEWPID) and manipulation of ns_last_pid
    child_process = await parent.monitor.clone(flags|CLONE.CHILD_CLEARTID, stack, ctid=futex_pointer)
    futex_process = await launch_futex_monitor(
        parent.ram, parent.loader, parent.monitor, futex_pointer)
    # Create the new syscall interface, which needs to use not just the connection,
    # but also the child process and the futex process.
    syscall = ChildSyscallInterface(SyscallConnection(access_sock, access_sock),
                                    child_process, futex_process)
    # Set up the new task with appropriately inherited namespaces, tables, etc.
    # TODO correctly track all the namespaces we're in
    if flags & CLONE.NEWPID:
        pidns = far.PidNamespace(child_process.process.near.id)
    else:
        pidns = parent.task.pidns
    task = Task(syscall, child_process.process,
                parent.task.fd_table, parent.task.address_space, pidns)
    task.sigmask = parent.task.sigmask
    # Move ownership of the remote sock into the task and store it so it isn't closed
    remote_sock_handle = remote_sock.move(task)
    syscall.store_remote_side_handles(remote_sock_handle, remote_sock_handle)
    return child_process, task

from rsyscall.epoller import Epoller
from rsyscall.network.connection import Connection, ConnectionThread
class ForkThread(ConnectionThread):
    def __init__(self,
                 task: Task,
                 ram: RAM,
                 epoller: Epoller,
                 connection: Connection,
                 loader: NativeLoader,
                 monitor: ChildProcessMonitor,
    ) -> None:
        super().__init__(task, ram, epoller, connection)
        self.loader = loader
        self.monitor = monitor

    def _init_from(self, thr: ForkThread) -> None: # type: ignore
        super()._init_from(thr)
        self.loader = thr.loader
        self.monitor = thr.monitor

    async def _fork_task(self, flags: CLONE) -> t.Tuple[AsyncChildProcess, Task]:
        return await clone_child_task(
            self, flags, lambda sock: Trampoline(self.loader.server_func, [sock, sock]))


# -*- coding: utf-8 -*-
from __future__ import division
import math

cv = input("Nº de Vitórias do Cormengo: ")
ce = input("Nº de Empate do Cormengo: ")
cs = input("Saldo de Gol do Cormengo: ")
fv = input("Nº de Vitórias do Flaminthians: ")
fe = input("Nº de Empate do Flaminthians: ")
fs = input("Saldo de Gol do Flaminthians: ")

pc = (cv*3+ce)
pf = (fv*3+fe)

if pc>pf:
    print("C")
elif pf>pc:
    print("F")
else:
    if cs>fs:
        print("C")
    elif fs>cs:
        print("F")
    elif cs==fs:
        print("=")


# -*- coding: utf-8 -*-
"""
Created on Thu Sep 24 21:13:34 2020
# =============================================================================
# Coin change problem: Maximum number of ways
# =============================================================================
Problem is basically combination of Unbounded Knapsack and cound the no of subset
Recursion+Momonisation
Time complexity- n**2
@author: RAVI
"""

from prettytable import PrettyTable
def CountWay(arr,n,s):
    if l[n][s]!=-1:
        return l[n][s]
    else:
        if n==0 and s!=0:
            l[n][s]=0
            return 0
        elif n!=0 and s==0:
            l[n][s]=1
            return 1
        elif n==0 and s==0:
            l[n][s]=1
            return 1
        elif arr[n-1]<=s:
            l[n][s]=CountWay(arr,n,s-arr[n-1])+CountWay(arr,n-1,s)
            return l[n][s]
        else:
            l[n][s]=CountWay(arr,n-1,s)
            return l[n][s]

n=int(input("Enter No of Coin type:"))
arr=sorted(list(map(int,input("Enter Coin Value:").split())))
s=int(input("Enter sum to get:"))
l=[[-1]*(s+1) for i in range(n+1)]
ans=CountWay(arr,n,s)
print(ans)

x=PrettyTable()
x.field_names=[i for i in range(s+1)]
for i in l:
    x.add_row(i)
print(x)

Coin change problem_Maximum number of ways.py


import re

sub_first_cap = re.compile('(.)([A-Z][a-z]+)').sub
sub_all_caps = re.compile('([a-z0-9])([A-Z])').sub

def camel_to_snake(name):
    # Based on https://stackoverflow.com/a/1176023/1843865
    s1 = sub_first_cap(r'\1_\2', name)
    return sub_all_caps(r'\1_\2', s1).lower()


'''
Created on May 14, 2014

@author: bernard
'''
import maya.cmds as cmds

def getMaxAndMinAxis (objectName, preview=False):
    """
    send a object to get the Max and Min X,Y and Z
    @param objectName: Name of Object
    @type objectName: String
    --------------------------------------------
    @param preview: to see the preview
    @type preview: Bool
    --------------------------------------------
    @return: 0-maxX, 1-minX, 2-maxY, 3-minY, 4-maxZ, 5-minZ
    """
    maxX,maxY,maxZ,minX,minY,minZ = 0,0,0,0,0,0
    vertexList = cmds.getAttr("%s.vrts"%objectName, multiIndices=True )
    i = 0
    for i in vertexList:
        cmds.select("%s.pnts[%s]"%(objectName,i))
        vertexPositionX, vertexPositionY, vertexPositionZ = cmds.xform("%s.pnts[%s]"%(objectName,i), query=True, translation=True, worldSpace=True )
        if vertexPositionX > maxX or i == 0:
            maxX = vertexPositionX
        if vertexPositionY > maxY or i == 0:
            maxY = vertexPositionY
        if vertexPositionZ > maxZ or i == 0:
            maxZ = vertexPositionZ
        if vertexPositionX < minX or i == 0:
            minX = vertexPositionX
        if vertexPositionY < minY or i == 0:
            minY = vertexPositionY
        if vertexPositionZ < minZ or i == 0:
            minZ = vertexPositionZ

    if preview == True:
        cmds.spaceLocator(name="minX", p=(0, 0, 0))
        cmds.spaceLocator(name="minY", p=(0, 0, 0))
        cmds.spaceLocator(name="minZ", p=(0, 0, 0))
        cmds.spaceLocator(name="maxX", p=(0, 0, 0))
        cmds.spaceLocator(name="maxY", p=(0, 0, 0))
        cmds.spaceLocator(name="maxZ", p=(0, 0, 0))
        meshX,meshY,meshZ = cmds.xform(objectName, query=True, translation=True, worldSpace=True )
        cmds.move( minX, meshY, meshZ, 'minX')
        cmds.move( maxX, meshY, meshZ, 'maxX')
        cmds.move( meshX, minY, meshZ, 'minY')
        cmds.move( meshX, maxY, meshZ, 'maxY')
        cmds.move( meshX, meshY, minZ, 'minZ')
        cmds.move( meshX, meshY, maxZ, 'maxZ')

    return maxX,minX,maxY,minY,maxZ,minZ

def renameShape (currentName='', changNameTo=''):
    """
    send a shapeName and change the name and transform
    @param currentName: The name of shape
    @type currentName: String
    --------------------------------------------
    @param changeNameTo: The new name
    @type changeNameTo: String
    --------------------------------------------
    @return: 0-Shape, 1-Transform
    """
    returnNewName=[]
    getParentTransform = cmds.listRelatives(currentName, parent = True)
    returnNewName.append(cmds.rename(currentName, '%sShape' % changNameTo))
    returnNewName.append(cmds.rename(getParentTransform, '%s' % changNameTo))
    return returnNewName

def renameTransform (currentName='', changNameTo=''):
    """
    send a transformName and change the name and shape
    @param currentName: The name of transform
    @type currentName: String
    --------------------------------------------
    @param changeNameTo: The new name
    @type changeNameTo: String
    --------------------------------------------
    @return: 0-Shape , 1-Transform
    """
    returnNewName=[]
    if cmds.listRelatives(currentName, parent = False, type='shape'):
        getChild = cmds.listRelatives(currentName, parent = False)
        returnNewName.append(cmds.rename(getChild[0], '%sShape' % changNameTo))
    returnNewName.append(cmds.rename(currentName, '%s' % changNameTo))
    return returnNewName

def oceanBuilder(projectName):
    import BBmaya.tools_fx.modules.BB_SplashGenerator as generator
    reload(generator)
    objectName = "Apple"

    # create Node
    objectOceanShader_S = cmds.createNode("oceanShader",name="%s_OceanShader"%objectName)
    objectHeightField = cmds.createNode("heightField",name="%s_OceanPreviewPlane"%objectName)
    objectShadingEngine_S = cmds.createNode("shadingEngine",name="%s_OceanShader"%objectName)
    objectMakeNurbPlane_S = cmds.createNode("makeNurbPlane",name="%s_MakeNurbPlane"%objectName)
    objectNurbSurface = cmds.createNode("nurbsSurface",name="%s_OceanPlane"%objectName)

    # Renaming Shape and Transform
    objectHeightField_S, objectHeightField_T = generator.renameShape(objectHeightField,"%s_OceanPreviewPlane"%objectName)
    objectNurbSurface_S, objectNurbSurface_T = generator.renameShape(objectNurbSurface,"%s_OceanPlane"%objectName)

    # Connecting Ocean Shaders
    cmds.connectAttr("%s.outColor"%objectOceanShader_S,"%s.color"%objectHeightField_S)
    cmds.connectAttr("%s.displacement"%objectOceanShader_S,"%s.displacement"%objectHeightField_S)
    cmds.connectAttr("%s.outColor"%objectOceanShader_S,"%s.surfaceShader"%objectShadingEngine_S)
    cmds.connectAttr("%s.displacement"%objectOceanShader_S,"%s.displacementShader"%objectShadingEngine_S)
    cmds.connectAttr("time1.outTime","%s.time"%objectOceanShader_S)
    cmds.connectAttr("%s.instObjGroups"%objectNurbSurface_S,"%s.dagSetMembers[0]"%objectShadingEngine_S)
    cmds.connectAttr("%s.outputSurface"%objectMakeNurbPlane_S,"%s.create"%objectNurbSurface_S)
    cmds.connectAttr("%s.message"%objectShadingEngine_S,"lightLinker1.link[2].object")
    cmds.connectAttr("%s.message"%objectShadingEngine_S,"lightLinker1.shadowLink[2].shadowObject")
    cmds.connectAttr("%s.partition"%objectShadingEngine_S,"renderPartition.sets[2]")

    # HeightField preset
    cmds.setAttr("%s.resolution"%objectHeightField_S,20)
    cmds.setAttr("%s.scaleX"%objectHeightField_T,10)
    cmds.setAttr("%s.scaleZ"%objectHeightField_T,10)

def expressionVeriableBuilder():
    '''float $particleSprayRate = 3000;
        float $particleBubblesRate = 100;
        float $fluidDisplacement = 6.0;
        float $fluidFoam = 2.0;
        float $u = .I[0];
        float $v = .I[1];
        float $disp[] = `colorAtPoint -u $u -v $v oceanShader1`;
        float $lastY = `getAttr -time (frame - 2) %s.translateY`;
        float $curY = %s.translateY;
        float $ydiff = $lastY - $curY;'''


from __future__ import absolute_import

import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable

from program_synthesis.algolisp.dataset import data
from program_synthesis.algolisp.models import prepare_spec

from program_synthesis.common.modules import decoders
from program_synthesis.algolisp.models.modules import encoders

class Seq2Seq(nn.Module):

    def __init__(self, inp_vocab_size, out_vocab_size, args):
        super(Seq2Seq, self).__init__()
        self.args = args
        self.inp_embed = nn.Embedding(inp_vocab_size + args.num_placeholders, args.num_units)
        self.encoder = nn.GRU(args.num_units, args.num_units, args.num_encoder_layers, batch_first=True)
        # Same vocab flag
        self.decoder = decoders.SeqDecoder(out_vocab_size, args)

    def encode(self, inputs):
        emb_inputs = self.inp_embed(data.replace_pad_with_end(inputs))
        init = Variable(torch.zeros(args.num_encoder_layers, emb_inputs.size(0), self.args.num_units))
        if self.args.cuda:
            init = init.cuda()
        _, hidden = self.encoder(emb_inputs, init)
        return hidden

    def forward(self, inputs, outputs):
        hidden = self.encode(inputs)
        return self.decoder(data.replace_pad_with_end(outputs), init=hidden)

    def sample(self, inputs, sampler=decoders.argmax_sampler):
        hidden = self.encode(inputs)
        return self.decoder.sample(hidden=hidden, sampler=sampler)

class Seq2SeqAttn(nn.Module):

    def __init__(self, word_vocab_size, code_vocab_size, args):
        super(Seq2SeqAttn, self).__init__()
        self.args = args
        self.num_units = args.num_units
        self.num_placeholders = args.num_placeholders
        self.bidirectional = args.bidirectional
        self._cuda = args.cuda
        self.word_embed = nn.Embedding(
            word_vocab_size + self.num_placeholders, self.num_units)
        self.code_embed = nn.Embedding(
            code_vocab_size + self.num_placeholders, self.num_units)
        self.encoder = encoders.SpecEncoder(args)
        num_directions = 2 if self.bidirectional else 1
        mem_dim = self.num_units * num_directions
        DECODERS = {
            'attn_decoder': decoders.SeqDecoderAttn,
            'multi_attn_decoder': decoders.SeqDecoderMultiAttn,
            'past_attn_decoder': decoders.SeqDecoderPastAttn,
            'luong_attn_decoder': decoders.SeqDecoderAttnLuong,
        }
        self.decoder = DECODERS[args.seq2seq_decoder](
            code_vocab_size, mem_dim, args, embed=self.code_embed)

    def encode_text(self, inputs):
        # inputs: PackedSequencePlus
        return self.encoder.text_encoder(inputs.apply(self.word_embed))

    def encode_io(self, input_keys, inputs, arg_nums, outputs):
        input_keys_embed = self.code_embed(input_keys)
        return self.encoder.io_encoder(input_keys_embed, inputs, arg_nums, outputs)

    def encode_code(self, code_seqs):
        # code_seqs: PackedSequencePlus
        return self.encoder.code_encoder(code_seqs.apply(self.code_embed))

    def encode_trace(self, prepared_trace):
        return self.encoder.trace_encoder(prepared_trace)

    def extend_tensors(
            self, code_info, batch_size, batch_ids):
        # TODO: should be a separate module probably with its parameters.
        if code_info:
            code_enc, code_memory, orig_seq_lengths  = code_info

            # Every item in the batch has code.
            if len(batch_ids) == batch_size:
                return code_enc, code_memory, orig_seq_lengths

            # Otherwise, stagger empty encodings/memories with real ones
            enc_to_stack = [self.empty_candidate_code_hidden] * batch_size
            memory_to_stack = [torch.zeros_like(code_memory[0])] * batch_size
            seq_lengths = [0] * batch_size

            for i, batch_id in enumerate(batch_ids):
                enc_to_stack[batch_id] = code_enc[i]
                memory_to_stack[batch_id] = code_memory[i]
                seq_lengths[batch_id] = orig_seq_lengths[i]

            enc = torch.stack(enc_to_stack)
            memory = torch.stack(memory_to_stack)
            return enc, memory, seq_lengths

        enc = self.empty_candidate_code_hidden.expand(batch_size, -1)
        return enc, None, None

    def decode(self, hidden, memory_attn_mask, outputs):
        return self.decoder(hidden, memory_attn_mask, data.replace_pad_with_end(outputs))

    def decode_token(self, t, hidden, memory_attn_mask, attentions=None):
        return self.decoder.decode_token(t, hidden, memory_attn_mask, attentions)

    def sample(self, hidden, memory_attn_mask, attentions=None):
        return self.decoder.sample(hidden, memory_attn_mask, attentions=attentions)


# https://www.acmicpc.net/problem/2212
import sys

def solve():
    diffs = []
    for i in range(n-1):
        diffs.append(censors[i+1] - censors[i])
    diffs.sort()
    if k > 1:
        diffs = diffs[:-(k-1)]
    return sum(diffs)

input = sys.stdin.readline
n = int(input().strip())
k = int(input().strip())
censors = sorted([int(x) for x in input().split()])

print(solve())


from collections import Counter
import operator
import numpy as np
import pandas as pd
from sklearn.metrics.pairwise import cosine_similarity as cs

# vectors_path = "data/vectors_filtered_by_vet/"
vectors_path = "data/vectors_vet_as_label/"

f_label = open("data/ads_category.txt","r")

labels = []
for line in f_label:
	labels.append(line.strip())

f_label.close()

n = len(labels)
label_frequency = Counter(labels)
sorted_label_frequency = sorted(label_frequency.items(), key=operator.itemgetter(1), reverse = True)

filter_label_with_most_frequency = [label for label,count in sorted_label_frequency][:20]

# 'BusinessAndManagement', 'Banking,FinanceAndRelatedFields', 'Building', 'ElectricalAndElectronicEngineeringAndTechnology', 'SalesAndMarketing', 'FoodAndHospitality', 'ProcessAndResourcesEngineering', 'HumanWelfareStudiesAndServices', 'OfficeStudies', 'Nursing'

sample_size = 5000
ind_lists = []
for label in filter_label_with_most_frequency:
	ind_list = []
	for i in range(n):
		if labels[i] == label:
			ind_list.append(i)
		if len(ind_list) == sample_size:
			break
	ind_lists.extend(ind_list)

ads_vectors = np.zeros((n,100))
# f = open("data/sentence_vectors_new_with_punctuation.txt")
f = open(vectors_path + "ads_vectors.txt","r")
for i,line in enumerate(f):
	ads_vectors[i] = line.split()

ads = ads_vectors[ind_lists]
# similarity_matrix = cs(test_vectors, test_vectors)

# for i in range(10 - 1):
# 	print np.mean(similarity_matrix[170][ sample_size * i : sample_size * (i+1) ])

def read_txt(filename, filetype):
	l = []
	f = open(filename, "r")
	if filetype == "vectors":
		for line in f:
			l.append(line.strip().split())
	elif filetype == "label":
		for line in f:
			l.append(line.strip())
	return l

vet_label = read_txt("data/vet_category.txt", "label")
vet_vectors = read_txt("data/vet_vectors.txt", "vectors")
vets = np.array(vet_vectors, dtype = np.float)

similarity_matrix = cs(ads, vets)

mean_matrix = np.zeros((len(filter_label_with_most_frequency),len(vet_label)))
for i in range(len(vet_label)):
	c = similarity_matrix[:,i]
	for j in range(len(filter_label_with_most_frequency)):
		mean_matrix[j,i] = np.mean(c[j*sample_size:(j+1)*sample_size])

df = pd.DataFrame(mean_matrix.T, index = vet_label, columns = filter_label_with_most_frequency).to_csv(vectors_path + "similarity_result.csv")


# coding:utf-8
import pandas as pd
import numpy as np
import datetime
from datetime import datetime
from sklearn.utils import shuffle
from sklearn.metrics import roc_auc_score, f1_score
from sklearn.model_selection import KFold, StratifiedKFold
from sklearn.preprocessing import StandardScaler, LabelEncoder
import xgboost as xgb
import copy
import lightgbm as lgb
from tqdm import tqdm
import os
from datetime import timedelta
from sklearn.feature_selection import chi2, SelectPercentile
from matplotlib import pyplot as plt
import time
import gc
pd.set_option('display.max_columns', None)

scaler = StandardScaler()

def get_fea(train, test, user, app):
    # test['target'] = 'test'
    test['is_test'] = 1

    user['mark'] = 0
    user['deviceid_count'] = user.groupby('deviceid').mark.transform('count')
    user['guid_count'] = user.groupby('guid').mark.transform('count')

    def get_same_tag(x, y):
        x = str(x)
        y = str(y)

        if '|' not in x or '|' not in y:
            return 0

        x = x.split('|')
        x = [i.split(':')[0] for i in x]

        y = y.split('|')
        y = [i.split(':')[0] for i in y]

        return len(set(x).intersection(set(y)))

    user['tag_same'] = user.apply(lambda x: get_same_tag(x['outertag'], x['tag']), axis=1)

    app['applist'] = app['applist'].apply(lambda x: str(x)[1:-2])
    app['applist'] = app['applist'].apply(lambda x: str(x).replace(' ', '|'))
    app = app.groupby('deviceid')['applist'].apply(lambda x: '|'.join(x)).reset_index()
    app['app_len'] = app['applist'].apply(lambda x: len(x.split('|')))

    df = pd.concat((train, test)).reset_index(drop=True)
    user_duplicate = user.drop_duplicates(subset=['deviceid', 'guid'])
    app_duplicate = app.drop_duplicates(subset=['deviceid'])
    df = pd.merge(df, user_duplicate, on=['deviceid', 'guid'], how='left')
    df = pd.merge(df, app_duplicate, on=['deviceid'], how='left')

    cat_list = [i for i in df.columns if i not in ['id', 'lat', 'lng', 'target', 'timestamp', 'ts']] + ['level']

    # 排序 相减
    df = df.sort_values(by=['guid', 'ts'], ascending=False)
    df['ts_1'] = df['ts'].shift(1)
    df['ts_1'].fillna(1573142399626, inplace=True)
    df['ts_diff'] = df['ts'] - df['ts_1']
    df['ts_diff'] = df['ts_diff']/10000
    print(df[['ts', 'ts_1', 'ts_diff']])

    # # 把相隔广告曝光相隔时间较短的数据视为同一个事件，这里暂取间隔为3min
    # # rank按时间排序同一个事件中每条数据发生的前后关系
    # group = df.groupby('deviceid')
    # df['gap_before'] = group['ts'].shift(0) - group['ts'].shift(1)
    # df['gap_before'] = df['gap_before'].fillna(3 * 60 * 1000)
    # INDEX = df[df['gap_before'] > (3 * 60 * 1000 - 1)].index
    # df['gap_before'] = np.log(df['gap_before'] // 1000 + 1)
    # df['gap_before_int'] = np.rint(df['gap_before'])
    # LENGTH = len(INDEX)
    # ts_group = []
    # ts_len = []
    # for i in tqdm(range(1, LENGTH)):
    #     ts_group += [i - 1] * (INDEX[i] - INDEX[i - 1])
    #     ts_len += [(INDEX[i] - INDEX[i - 1])] * (INDEX[i] - INDEX[i - 1])
    # ts_group += [LENGTH - 1] * (len(df) - INDEX[LENGTH - 1])
    # ts_len += [(len(df) - INDEX[LENGTH - 1])] * (len(df) - INDEX[LENGTH - 1])
    # df['ts_before_group'] = ts_group
    # df['ts_before_len'] = ts_len
    # df['ts_before_rank'] = group['ts'].apply(lambda x: (x).rank())
    # df['ts_before_rank'] = (df['ts_before_rank'] - 1) / \
    #                          (df['ts_before_len'] - 1)
    #
    # group = df.groupby('deviceid')
    # df['gap_after'] = group['ts'].shift(-1) - group['ts'].shift(0)
    # df['gap_after'] = df['gap_after'].fillna(3 * 60 * 1000)
    # INDEX = df[df['gap_after'] > (3 * 60 * 1000 - 1)].index
    # df['gap_after'] = np.log(df['gap_after'] // 1000 + 1)
    # df['gap_after_int'] = np.rint(df['gap_after'])
    # LENGTH = len(INDEX)
    # ts_group = [0] * (INDEX[0] + 1)
    # ts_len = [INDEX[0]] * (INDEX[0] + 1)
    # for i in tqdm(range(1, LENGTH)):
    #     ts_group += [i] * (INDEX[i] - INDEX[i - 1])
    #     ts_len += [(INDEX[i] - INDEX[i - 1])] * (INDEX[i] - INDEX[i - 1])
    # df['ts_after_group'] = ts_group
    # df['ts_after_len'] = ts_len
    # df['ts_after_rank'] = group['ts'].apply(lambda x: (-x).rank())
    # df['ts_after_rank'] = (df['ts_after_rank'] - 1) / (df['ts_after_len'] - 1)
    #
    # df.loc[df['ts_before_rank'] == np.inf, 'ts_before_rank'] = 0
    # df.loc[df['ts_after_rank'] == np.inf, 'ts_after_rank'] = 0
    # df['ts_before_len'] = np.log(df['ts_before_len'] + 1)
    # df['ts_after_len'] = np.log(df['ts_after_len'] + 1)

    df['ts'] = df['ts'].apply(lambda x: datetime.fromtimestamp(x / 1000))
    df['ts_day'] = df['ts'].apply(lambda x: x.day)
    df['ts_hour'] = df['ts'].apply(lambda x: x.hour)

    df['minute'] = df['ts'].apply(lambda x: x.minute)
    df['time1'] = np.int64(df['ts_hour']) * 60 + np.int64(df['minute'])
    df.loc[~df['newsid'].isna(), 'isLog'] = 1
    df.loc[df['newsid'].isna(), 'isLog'] = 0

    # 类别特征count特征
    cat_list.append('ts_day')
    cat_list.append('ts_hour')

    no_features = ['id', 'target', 'timestamp', 'ID', 'fold', 'is_test', 'ts_1']

    print(cat_list)
    print(df[cat_list])
    for i in tqdm(cat_list):
        df['{}_count'.format(i)] = df.groupby(['{}'.format(i)])['id'].transform('count')
        df['{}_ts_day_hour_count'.format(i)] = df.groupby(['{}'.format(i), 'ts_day', 'ts_hour'])['id'].transform('count')

    # 类别特征五折转化率特征
    df['ID'] = df.index
    df['fold'] = df['ID'] % 5
    df.loc[df.target.isnull(), 'fold'] = 5
    target_feat = []
    for i in tqdm(cat_list):
        target_feat.extend([i + '_mean_last_1'])
        df[i + '_mean_last_1'] = None
        for fold in range(6):
            df.loc[df['fold'] == fold, i + '_mean_last_1'] = df[df['fold'] == fold][i].map(
                df[(df['fold'] != fold) & (df['fold'] != 5)].groupby(i)['target'].mean()
            )
        df[i + '_mean_last_1'] = df[i + '_mean_last_1'].astype(float)

    for feas in [('guid', 'netmodel'), ('guid', 'osversion'), ('guid', 'device_version')]:
        i, j = feas
        df['%s_%s_unique'%(i, j)] = df.groupby([i])[j].transform('nunique')

    def tag_score_sum(x):
        x = str(x)

        if '|' not in x:
            return 0

        x = x.split('|')
        x = [float(i.split(':')[1]) for i in x if len(i.split(':')) > 1]
        return sum(x)
    df['tag_sum'] = df['tag'].apply(lambda x: tag_score_sum(x))
    df['outertag_sum'] = df['outertag'].apply(lambda x: tag_score_sum(x))

    # print(df[['tag', 'tag_sum', 'outertag', 'outertag_sum']])

    lb_feas = ['app_version', 'device_vendor', 'device_version', 'deviceid', 'guid', 'netmodel', 'newsid', 'osversion',
               'timestamp', 'outertag', 'tag', 'applist', 'ts']

    for fea in lb_feas:
        print(fea)
        df[fea].fillna('w', inplace=True)
        df[fea] = df[fea].astype(str)
        df[fea] = LabelEncoder().fit_transform(df[fea])

    train = df[df['is_test'] != 1]
    test = df[df['is_test'] == 1]

    print(train.shape)
    print(test.shape)

    train = train[train['target'].notnull()].reset_index(drop=True)

    print(train.shape)
    return train, test, no_features

train = pd.read_csv('data/train.csv')
test = pd.read_csv('data/test.csv')
user = pd.read_csv('data/user.csv')
app = pd.read_csv('data/app.csv')
sample = pd.read_csv('data/sample.csv')

train, test, no_features = get_fea(train, test, user, app)
print('get_fea ok')

# label = train['target']
# sub = test[['id']]

features = [fea for fea in train.columns if fea not in no_features]

# train_df = train[features]
#
# test_df = test[features]

# print(train)
def load_data():
    return train, test, no_features, features


def isPow(n: int) -> bool:
    cnt = 1
    while True :
        if cnt * cnt == n :
            return True
        elif cnt * cnt < n :
            cnt += 1
            continue
        else:
            return False

n = int(input())
print(isPow(n))


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

from pyqtgraph.Qt import QtGui, QtCore

import json
import os
import requests
from koheron import connect

class ConnectWidget(QtGui.QWidget):
    def __init__(self, parent, ip_path=None):
        super(ConnectWidget, self).__init__()

        self.parent = parent
        self.app_list = self.parent.app_list
        self.ip_path = ip_path
        self.is_connected = False

        # IP address
        self.create_ip_layout()

        # Connect button and connection information
        self.lay_connection = QtGui.QHBoxLayout()
        self.connect_button = QtGui.QPushButton()
        self.connect_button.setStyleSheet('QPushButton {color: green;}')
        self.connect_button.setText('Connect')
        self.connect_button.setFixedWidth(80)
        self.connection_info = QtGui.QLabel('')
        self.lay_connection.addWidget(self.connect_button)
        self.lay_connection.addWidget(self.connection_info)

        # Add layouts to main layout
        self.lay = QtGui.QVBoxLayout()
        self.lay.addLayout(self.lay_ip)
        self.lay.addLayout(self.lay_connection)
        self.setLayout(self.lay)

        self.retrieve_ip_address()

        for i, line in enumerate(self.lines):
            def make_callback(idx):
                return lambda : self.ip_changed(idx)
            line.textChanged.connect(make_callback(i))

        self.connect_button.clicked.connect(self.connect_onclick)

    def retrieve_ip_address(self):
        if not os.path.exists(self.ip_path):
            os.makedirs(self.ip_path)

        if os.path.exists(self.ip_path):
            try:
                fp = open(os.path.join(self.ip_path, 'ip_address' + '.json'))
                parameters = json.loads(fp.read())
                ip = parameters['ip_address']
            except:
                ip = '192.168.1.100'
            self.set_text_from_ip(ip)

        self.host = self.get_host_from_text()

    def create_ip_layout(self):
        self.lay_ip = QtGui.QHBoxLayout()

        self.lines = []
        for i in range(4):
            self.lines.append(QtGui.QLineEdit())
            self.lines[i].setFixedWidth(40)
            self.lines[i].setAlignment(QtCore.Qt.AlignCenter)

        self.points = []
        for i in range(3):
            self.points.append(QtGui.QLabel('.'))

        self.lay_ip.addWidget(QtGui.QLabel('IP address: '))
        for i in range(3):
            self.lay_ip.addWidget(self.lines[i])
            self.lay_ip.addWidget(self.points[i])
        self.lay_ip.addWidget(self.lines[3])

    def set_text_from_ip(self, ip):
        for i, num in enumerate(ip.split('.')):
            self.lines[i].setText(num)

    def get_host_from_text(self):
        return '.'.join(map(lambda x:str(x.text()), self.lines))

    def ip_changed(self, index):
        self.host = self.get_host_from_text()
        parameters = {}
        parameters['ip_address'] = self.host
        if not os.path.exists(self.ip_path):
            os.makedirs(self.ip_path)
        with open(os.path.join(self.ip_path, 'ip_address' + '.json'), 'w') as fp:
            json.dump(parameters, fp)
        if self.lines[index].cursorPosition() == 3 and index < 3:
            self.lines[index+1].setFocus()
            self.lines[index+1].selectAll()

    def load_instrument(self, instrument_name):
        self.client = load_instrument(self.host, instrument_name)

    def disconnect(self):
        self.is_connected = False
        self.connect_button.setStyleSheet('QPushButton {color: green;}')
        self.connect_button.setText('Connect')
        self.local_instruments = {}
        self.parent.instrument_list = [''] * len(self.app_list)
        self.parent.update_buttons()
        self.connection_info.setText('Disconnected')

    def connect(self):
        QtGui.QApplication.setOverrideCursor(QtGui.QCursor(QtCore.Qt.WaitCursor))
        self.connection_info.setText('Connecting to ' + self.host + ' ...')
        self.local_instruments = requests.get('http://{}/api/instruments/local'.format(self.host)).json()
        for i, app in enumerate(self.app_list):
            try:
               instrument = next(instr for instr in self.local_instruments if app in instr)
               self.parent.instrument_list[i] = instrument
            except StopIteration:
               self.parent.instrument_list[i] = ''

        # Load the first instrument available by default
        instrument_name = (next(instr for instr in self.parent.instrument_list if instr))
        self.client = connect(self.host, name=instrument_name)

        self.connection_info.setText('Connected to ' + self.host)
        self.is_connected = True
        self.connect_button.setStyleSheet('QPushButton {color: red;}')
        self.connect_button.setText('Disconnect')
        self.parent.update_buttons()
        QtGui.QApplication.restoreOverrideCursor()

    def connect_onclick(self):
        if self.is_connected:
            self.disconnect()
        else:
            self.connect()


from typing import Dict
import operator
import secrets
import asyncio
from collections import Counter

from vbet.game.tickets import Bet, Event, Ticket
from vbet.utils.log import get_logger, async_exception_logger
from vbet.game.players.base import Player

NAME = 'thiago'

logger = get_logger(NAME)

class CustomPlayer(Player):

    def __init__(self, **kwargs):
        super().__init__(NAME, **kwargs)
        self.game_hash = {key: {} for key in self.live_session.competitions.keys()}
        self.match_future = 1
        self.match_past = 2
        self.game_queue: Dict[int, bool] = {}
        self.next_comp = 0
        self.round_map = []
        self.round_flag = False
        self.round_key = 0

    async def forecast(self, competition_id, active_week: int):
        competition = self.live_session.user.get_competition(competition_id)
        league_games = competition.league_games  # type: Dict[int, Dict]
        week_games = league_games.get(active_week)  # type: Dict[int, Dict]
        game_data = self.game_hash.get(competition_id, {})
        week_stats = competition.table.get_week_stats(active_week)
        if not game_data:
            table = competition.table.table
            for top_player in table:
                streak = top_player.get('streak')
                t_streak = sorted(streak.items(), key=operator.itemgetter(0))
                f_streak = t_streak[active_week - (self.match_past + 1):active_week - 1]
                u_streak = [x[1] for x in f_streak if isinstance(x[1], int)]
                if len(u_streak) >= self.match_past:
                    if sum(u_streak) == (3 * self.match_past):
                        v_streak = t_streak[active_week: active_week + self.match_future]
                        valid = True
                        for event_id, event_data in week_games.items():
                            player_a = event_data.get('A')
                            player_b = event_data.get('B')
                            if player_a == top_player.get('team') or player_b == top_player.get('team'):
                                event_stats = week_stats.get(event_id)
                                team_to_team = event_stats.get("teamToTeam")
                                head_to_head = team_to_team.get("headToHead")
                                u, v = self.pick_winner(head_to_head)
                                if player_a == top_player.get('team'):
                                    if u == 0 and v == 5:
                                        valid = True
                                else:
                                    if u == 1 and v == 5:
                                        valid = True
                                odds = event_data.get('odds')
                                if player_a == top_player.get('team'):
                                    odd_id = 0
                                else:
                                    odd_id = 1
                                market_id, odd_name, odd_index = Player.get_market_info(str(odd_id))
                                odd_value = float(odds[odd_index])
                                if odd_value < 1.4:
                                    valid = False
                                    break
                                else:
                                    break
                        if not valid:
                            continue
                        if len(v_streak) >= self.match_future:
                            game_data['team'] = top_player.get('team')
                            game_data['enabled'] = True
                            self.game_queue[competition_id] = True
                            competition.wait_event = True  # Disable competition
                            game_data['start_week'] = active_week
                            game_data['quiz'] = []
                            logger.info('%r Possible event League : %d Week: %d %s', competition, competition.league,
                                        active_week, str(game_data.get('quiz')))
                            break
                break
        if not game_data:
            return []
        # enabled = game_data.get('enabled')

        if not (len(self.game_queue) == len(self.game_hash)):
            return []

        if not self.round_flag:
            self.round_map = list(self.game_queue.keys())
            secrets.SystemRandom().shuffle(self.round_map)
            self.round_flag = True
            self.round_key = 0

            print(self.game_hash, self.round_map, self.round_key)

        yy = self.round_map[self.round_key]
        if yy != competition_id:
            comp = self.live_session.user.get_competition(yy)
            comp.wait_event = False
            asyncio.ensure_future(comp.dispatch_events())
            return []

        self.game_queue[yy] = False
        competition.wait_event = False  # Enable competition
        game_data = self.game_hash.get(yy, {})
        target_games = {}
        target_team = game_data.get("team")
        for event_id, event_data in week_games.items():
            player_a = event_data.get('A')
            player_b = event_data.get('B')
            if player_a == target_team or player_b == target_team:
                if player_a == target_team:
                    odd_id = 0
                else:
                    odd_id = 1
                target_games[event_id] = ({"odd_id": odd_id})
        tickets = []
        for event_id, event_config in target_games.items():
            odd_id = event_config.get('odd_id')
            ticket = Ticket(competition.competition_id, self.name)
            event_data = week_games.get(event_id)
            participants = event_data.get('participants')
            odds = event_data.get('odds')
            event = Event(event_id, competition.league, active_week, participants)
            ticket.add_event(event)
            market_id, odd_name, odd_index = Player.get_market_info(str(odd_id))
            odd_value = float(odds[odd_index])
            bet = Bet(odd_id, market_id, odd_value, odd_name, 0)
            event.add_bet(bet)
            stake = await self.live_session.account.get_stake(odd_value=odd_value)
            total_odd = 1
            for event in ticket.events:
                for bet in event.bets:
                    bet.stake = stake
                    total_odd *= bet.odd_value
            win = round(stake * total_odd, 2)
            min_win = win
            max_win = win
            ticket._stake = stake
            ticket._min_winning = min_win
            ticket._max_winning = max_win
            ticket._total_won = 0
            ticket._grouping = 1
            ticket._winning_count = 1
            ticket._system_count = 1
            tickets.append(ticket)
        # print(competition, tickets)
        return tickets

    async def on_new_league(self, competition_id: int):
        self.game_map[competition_id] = True
        self.game_hash[competition_id] = {}

    async def on_ticket_resolve(self, ticket: Ticket):
        if ticket.total_won > ticket.stake:
            self.game_hash = {key: {} for key in self.live_session.competitions.keys()}
            self.round_key = 0
            self.round_flag = False
            self.game_queue.clear()
            self.game_map[ticket.game_id] = False
            self.game_hash[ticket.game_id].clear()
            for k, v in self.game_hash.items():
                competition = self.live_session.user.get_competition(k)
                competition.wait_event = False
                asyncio.ensure_future(competition.dispatch_events())

        else:
            competition = self.live_session.user.get_competition(ticket.game_id)
            competition.wait_event = True
            if self.round_key >= len(self.game_queue) - 1:
                self.game_hash = {key: {} for key in self.live_session.competitions.keys()}
                self.round_key = 0
                self.round_flag = False
                self.game_queue.clear()
                self.game_map[ticket.game_id] = False
                self.game_hash[ticket.game_id].clear()
                for k, v in self.game_hash.items():
                    competition = self.live_session.user.get_competition(k)
                    competition.wait_event = False
                    asyncio.ensure_future(competition.dispatch_events())
                return
            self.round_key += 1
            yy = self.round_map[self.round_key]
            competition = self.live_session.user.get_competition(yy)
            competition.wait_event = False
            asyncio.ensure_future(competition.dispatch_events())

    def get_required_weeks(self, competition_id: int):
        competition = self.live_session.user.get_competition(competition_id)
        required_weeks = self.required_map.get(competition_id, [])
        required_weeks.clear()
        y = [x for x in range(self.match_past + 1, competition.max_week + 1)]
        required_weeks.extend(y)


from django.core.management.base import BaseCommand, CommandError
from bs4 import BeautifulSoup

import os
import errno
import requests
import json
import re
import urllib
import datetime
from django.conf import settings
from PIL import Image

from selenium import webdriver

from finder.models import ItemCategory, Brand, FashionImage, FashionItem, Designer

"""
Management command to get images from Proenza Schouler site
"""

def get_soup(url):
	response = requests.get(url)
	soup = BeautifulSoup(response.text, 'html.parser')
	return soup

def create_proenza_data_request(rows):
	url = 'https://www.proenzaschouler.com/search/'
	rows = 20
	headers = {'X-Requested-With': 'XMLHttpRequest'}
	query_params = {'wt':'json','start':0,'rows':100,'sort':'score desc','q':'attr_cat_id:4','facet':'true','facet.mincount':1,'facet.sort':'count','facet.field':'facet_color','facet.field':'facet_material'}
	json_data = query_params
	response = requests.post(url=url, headers=headers, data=json_data)
	return response.text

def get_proenza_items(results):
	data = json.loads(results)
	clothing = ['Skirts', 'Tops', 'Dresses', 'Coats']
	bags = ['Clutch', 'Shoulder', 'Tote', 'Cross Body']
	shoes = ['Flats', 'Shoes', 'Sandals']
	image_url_base = 'https://d3ga9u8vvdh1ko.cloudfront.net/images/skus/'
	price = "0.00"
	for d in data['response']['docs']:
		for piece in d:
			item_id = d['product_name_t']
			item_name = d['product_name_to']
			item_description = d['description_t']
			category_list = d['attr_cat_name']
			item_name_words = str(item_name).split()
			ps = Designer.objects.get_or_create(name="Proenza Schouler")[0]
			prosch = Brand.objects.get_or_create(brand_name="Proenza Schouler")[0]
			prosch.designer.add(ps)
			fashion_item = FashionItem.objects.get_or_create(category_number=item_id, name=item_name, description=item_description, price=price)[0]
			fashion_item.brand.add(prosch)
			for category in category_list:
				if category in clothing:
					category = category
				elif category in bags:
					category = 'bag'
				elif category in shoes:
					category = 'shoe'
				else:
					category = item_name
			categories = fashion_item.determine_categories(str(category))
			if categories:
				image_url = str(d[piece])
				if image_url.endswith('jpg'):
					image_url = image_url_base + image_url
					images = FashionImage.objects.filter(fashion_item=fashion_item)
					print(fashion_item.name)
					image_number = int(len(images))
					image_number += 1
					item_name = item_name + " " + str(image_number)
					print("image name " + item_name)
					fashion_image = FashionImage.objects.get_or_create(image=settings.MEDIA_ROOT + item_name, fashion_item=fashion_item)
					if fashion_image[1]:
						try:
							image_response = requests.get(image_url)
							fashion_image[0].create_thumbnail(item_name, image_response)
							fashion_image[0].save()
						except requests.exceptions.ReadTimeout:
							print("requests timed out for " + description)
							time_out = image_url
				fashion_item.save()
			else:
				print("no categories == no images!")
	return

class Command(BaseCommand):
	def handle(self, *args, **options):
		results = create_proenza_data_request(20)
		get_proenza_items(results)


# This module contains functions to extract feature vectors from the trained CNN models

from skimage import io

from models import InceptionModel
from data_generator import validation_generator

import os
import numpy as np

def extract_feature_vector(img,model,inception_model,out_path):

    intermediate_output = inception_model.extract_layer_output(img,model)

    np.savetxt(out_path,intermediate_output)

def extract_feature_vector_of_all_imgs(dir_,out,weights_path):

    inception_model = InceptionModel()

    model = inception_model.create()

    model.load_weights(weights_path)

    print('[INFO].....Model weights loaded......')

    train_imgs_dir = os.path.join(dir_,'vn_train_512_overlap')

    val_imgs_dir = os.path.join(dir_,'vn_validation_512_overlap')

    imgs_dirs = [val_imgs_dir]
    imgs_dirs = [train_imgs_dir,val_imgs_dir]

    imgs_classes = ['Benign','InSitu','Invasive','Normal']

    for i in range(2):

        if (i == 0):

            out_dir = os.path.join(out,'train')

            print('[INFO].....Processing train imgs......')

        else:

            out_dir = os.path.join(out,'val')

            print('[INFO].....Processing val imgs......')

        imgs_dir = imgs_dirs[i]

        for imgs_class in imgs_classes:

            print('[INFO].....Processing ',imgs_class,' ......')

            class_dir = os.path.join(imgs_dir,imgs_class)
            out_class_dir = os.path.join(out_dir,imgs_class)

            imnames = os.listdir(class_dir)

            for imname in imnames:

                impath = os.path.join(class_dir,imname)

                print('[INFO].....Processing ',impath,' ......')

                out_fname = imname[:-4] + '.csv'
                out_path = os.path.join(out_class_dir,out_fname)
                print('[INFO].....out_path',out_path,' ......')

                img = io.imread(impath)

                if img is None:

                    raise ValueError('Inappropriate value of impath')

                extract_feature_vector(img,model,inception_model,out_path)

if __name__ == "__main__":

    '''

    impath = '/media/rtb7syl/New Volume/Projects-Workspace/Breast-Cancer-Classification-from-Histopathology-Images/data/stain_norm_imgs_validation/Invasive'

    impath = os.path.join(impath,'iv003.tif')
    weights_path = 'inceptionv3_model_weights_checkpoint/weights-improvement-post_6-03-0.78.h5'
    out_path = 'yy.csv'
    img = io.imread(impath)

    if img is None:

        raise ValueError('Inappropriate value of impath')

    extract_feature_vector(img,weights_path,out_path)

    '''
    dir_ = '/media/rtb7syl/New Volume/Projects-Workspace/Breast-Cancer-Classification-from-Histopathology-Images/data/patch'
    out_dir = 'feature_vectors/Inceptionv3'
    weights_path = 'inceptionv3_model_weights_checkpoint/weights-improvement-post_6-03-0.78.h5'
    extract_feature_vector_of_all_imgs(dir_,out_dir,weights_path)


from pyrogram import Client, Filters, StopPropagation, InlineKeyboardButton, InlineKeyboardMarkup

@Client.on_message(Filters.command(["start"]), group=-2)
async def start(client, message):
    # return
    joinButton = InlineKeyboardMarkup([
        [InlineKeyboardButton("Visit My Master's Website", url="www.softfreakz.com")],
        [InlineKeyboardButton(
            "Contact My Master!", url="https://t.me/Softfreakz")]
    ])
    welcomed = f"Hey there Hello! <b>{message.from_user.first_name}</b>\n Send me any youtube link to get direct Telegram File 😉 \n My master Softfreakz ordered me to work only 12 Hours a day from 10 AM IST to 10 PM IST, for any help/support/report you can contact my master Softfreakz!"
    await message.reply_text(welcomed, reply_markup=joinButton)
    raise StopPropagation


import serial

ser=serial.Serial("COM13",timeout=1)

cnt=0
while True:
    resp=ser.readline()
    cnt+=1
    print("moving remote car",cnt)
    print(resp)
    if resp !=b"":
        resp=resp.decode()
        b=resp.strip()
        c=b.split(",")
        print(c)
        d=list(map(int,c))
        print(d)
        leftspeed=d[0]
        rightspeed=d[1]
        print("car wheel speed is",d)


from openpyxl import Workbook
from openpyxl import load_workbook
from Model import BuildMatchCode
import sys

def CountAndMatchTestcode(path, TargetPath):
    workbookData = load_workbook(path)
    try:
        workbook = load_workbook(TargetPath)
    except:
        workbook = Workbook()

    workbookDataSheet = workbookData.active

    workbook.save(TargetPath)
    return 0

#Run
print("Hello World")
path = ""
TargetPath = "C:/Users/Administrator/Desktop/SipH Summary/Others/Compare.xlsx"
couter = 1
CountAndMatchTestcode()


import usb.core
import usb.util

VENDOR_ID = 0x0922
PRODUCT_ID = 0x8005

device = usb.core.find(idVendor=VENDOR_ID, idProduct=PRODUCT_ID)

for cfg in device:
  for intf in cfg:
    if device.is_kernel_driver_active(intf.bInterfaceNumber):
      try:
        device.detach_kernel_driver(intf.bInterfaceNumber)
      except usb.core.USBError as e:
        sys.exit("Could not detach kerner driver from interface({0}): {1}".format(intf.bInterfaceNumber, str(e)))

device.set_configuration()

endpoint = device[0][(0,0)][0]

attempts = 10
data = None

while data is None and attempts > 0:
    try:
        data = device.read(endpoint.bEndpointAddress, endpoint.wMaxPacketSize)

    except usb.core.USBError as e:
        data = None
        if e.args == ('Operation timed out',):
            attempts -= 1
            continue
        else:
            print('ERROR {}'.format(e.args))
            attempts -= 1
            continue

print(data)


#
# GPOS.py -- Top-level support for GPOS tables
#
# Copyright © 2016 Monotype Imaging Inc. All Rights Reserved.
#

"""
Support for OpenType GPOS tables.
"""

# System imports
import logging

# Other imports
from fontio3.GPOS import GPOS_v10, GPOS_v11
from fontio3.opentype import fontworkersource

# -----------------------------------------------------------------------------

#
# Public functions
#

def GPOS(w, **kwArgs):
    """
    Factory function to make a GPOS object (of whatever version) from the
    contents of the specified walker.
    """

    w.reset()
    version = w.unpack("L", advance=False)

    otcd = None
    GDEF = kwArgs.get('GDEF')
    if GDEF:
        ce = GDEF.__dict__.get('_creationExtras')
        if ce:
            otcd = ce.get('otcommondeltas')

    if version == 0x10000:
        return GPOS_v10.GPOS.fromwalker(w, otcommondeltas=otcd, **kwArgs)

    elif version == 0x10001:
        return GPOS_v11.GPOS.fromwalker(w, otcommondeltas=otcd, **kwArgs)

    raise ValueError("Unknown GPOS version: 0x%08x" % (version,))

def GPOS_fromValidatedFontWorkerSource(s, **kwArgs):
    """
    Creates and returns a new GPOS from the specified stream containing
    FontWorker Source code with extensive validation via the logging module
    (the client should have done a logging.basicConfig call prior to calling
    this method, unless a logger is passed in via the 'logger' keyword
    argument).

    We will always generate a GPOS_v11 from Font Worker source.
    """
    fws = fontworkersource.FontWorkerSource(s)

    return GPOS_v11.GPOS.fromValidatedFontWorkerSource(fws, **kwArgs)

def GPOS_validated(w, **kwArgs):
    """
    Factory function to make a GPOS object (of whatever version) from the
    contents of the specified walker, with validation at all levels.
    """

    logger = kwArgs.pop('logger', None)

    if logger is None:
        logger = logging.getLogger().getChild('GPOS')
    else:
        logger = logger.getChild('GPOS')

    otcd = None
    GDEF = kwArgs.get('GDEF')
    if GDEF:
        ce = GDEF.__dict__.get('_creationExtras')
        if ce:
            otcd = ce.get('otcommondeltas')

    logger.debug(('V0001', (w.length(),), "Walker has %d remaining bytes."))

    if w.length() < 4:
        logger.error(('V0004', (), "Insufficient bytes."))
        return None

    version = w.unpack("L", advance=False)

    if version == 0x10000:
        logger.info(('V0115', (), "GPOS is pre-OpenType 1.8."))
        fvw = GPOS_v10.GPOS.fromvalidatedwalker
        return fvw(w, logger=logger, otcommondeltas=otcd, **kwArgs)

    elif version == 0x10001:
        logger.info(('V0115', (), "GPOS is OpenType 1.8 (table version 1.1)"))
        fvw = GPOS_v11.GPOS.fromvalidatedwalker
        return fvw(w, logger=logger, otcommondeltas=otcd, **kwArgs)

    logger.error(('V0116', (version,), "Unknown version: 0x%08X."))
    return None

# -----------------------------------------------------------------------------

#
# Test code
#

if 0:
    def __________________(): pass

def _test():
    import doctest
    doctest.testmod()

if __name__ == "__main__":
    if __debug__:
        _test()


import tkinter as tk
from View.GUI.StudentView import StudentView
from View.GUI.DisciplineView import DisciplineView

class Demo1:
    def __init__(self, master, catalogController, commandController):
        self._catalogController = catalogController
        self._commandController = commandController
        self.master = master
        self.frame = tk.Frame(self.master)
        self.button1 = tk.Button(self.frame, text='Student View', width=50, command=self.openStudentView)
        self.button1.pack()
        self.button2 = tk.Button(self.frame, text='Discipline View', width=50, command=self.openDisciplineView)
        self.button2.pack()
        self.button3 = tk.Button(self.frame, text='Undo', width=50, command=lambda: self._catalogController.undo())
        self.button3.pack()
        self.button4 = tk.Button(self.frame, text='Redo', width=50, command=lambda: self._catalogController.redo())
        self.button4.pack()
        self.button5 = tk.Button(self.frame, text='Save', width=50, command=lambda: self._catalogController.save())
        self.button5.pack()
        self.button6 = tk.Button(self.frame, text='Exit', width=50, command=self.kill)
        self.button6.pack()
        self.frame.pack()

    def new_window(self):
        self.newWindow = tk.Toplevel(self.master)
        self.app = Demo2(self.newWindow)

    def openStudentView(self):
        self.newWindow = tk.Toplevel(self.master)
        self.app = StudentView(self.newWindow, self._catalogController, self._commandController)

    def openDisciplineView(self):
        self.newWindow = tk.Toplevel(self.master)
        self.app = DisciplineView(self.newWindow, self._catalogController, self._commandController)

    def kill(self):
        self.master.destroy()

class Demo2:
    def __init__(self, master):
        self.master = master
        self.frame = tk.Frame(self.master)
        self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
        self.quitButton.pack()
        self.frame.pack()
    def close_windows(self):
        self.master.destroy()

class MainMenu:
    def __init__(self, catalogController, commandController):
        self._catalogController = catalogController
        self._commandController = commandController

    def run(self):
        root = tk.Tk()
        app = Demo1(root, self._catalogController, self._commandController)
        root.mainloop()


'''
Created on 2015-08-18

@author: Magee_yang
'''

import wx
import bitmapLoader

class CachingImageList(wx.ImageList):
    def __init__(self,width,height):
        wx.ImageList.__init__(self,width,height)
        self.map = {}

    def GetImageIndex(self,*loaderArgs):
        id = self.map.get(loaderArgs)
        if id is None:
            bitmap = bitmapLoader.getBitmap(*loaderArgs)
            if bitmap is None:
                return -1
            id = self.map[loaderArgs] = wx.ImageList.Add(self,bitmap)
        return id


#! /usr/bin/env python
# -*- coding: UTF-8 -*-
#  @author:  peng tao
#
#    Mar 14, 2018 14:53:45 PM

#from tkinter import*
from tkinter import filedialog as fdialog
from tkinter.dialog import*
from tkinter.messagebox import*
import tkinter.ttk as ttk
py3 = 1
#import camera_single_face
from VideoCapture import Device
import cv2
import numpy
import os
#import threading
import winsound
import detect_face

#winsound.Beep(100,500)

#PlaySound(sound)

path0 = os.getcwd()
father_path=os.path.abspath(os.path.dirname(path0)+os.path.sep+".")

saveimagepath = os.path.join(father_path,'collectImagequick')
if not os.path.exists(saveimagepath):
    os.mkdir(saveimagepath)
    #os.makedirs()
#imagepathnum = 0

imagepathnum = len(os.listdir(saveimagepath))

def save_file():
    pass
    '''
    file=fdialog.asksaveasfile(mode="wb", title="Save Figure", defaultextension=".png", filetypes = (("png files","*.png"),("all files","*.*")))
    if file is None:
        return None
    img_to_save=open(".temp/generated_plot.png","rb").read()
    file.write(img_to_save)
    file.close()
    '''
def showAbout():
        showinfo("face detect version 1.0","quit key: 'q','Esc'\n directiong key:'2''4''6''8'\n delete key :'d'\n save key:'s'\n data: 2018/3/20 \n, other maybe call me 110114112")

class Menubar:
    def __init__(self, master):
        menubar = Menu(root)
        filemenu = Menu(menubar, tearoff=0)
        menubar.add_cascade(label="File", menu=filemenu)
        filemenu.add_command(label="Save", command=save_file)
        filemenu.add_command(label="Quit", command=root.destroy)
        helpmenu = Menu(menubar, tearoff=0)
        helpmenu.add_command(label="About facedetect",command= showAbout)
        menubar.add_cascade(label="Help", menu=helpmenu)
        root.config(menu=menubar)

def destroy_app():
    global root
    root.destroy()
    exit(0)
# global colors variables for theme switch
_activebgcolordark = '#808080'
_bgcolorlight = '#ffffff'
_fgcolorlight = '#000000'
_lightwindowbackground = '#f2f2f2'

def callback(event):
    print("当前位置：",event.x,event.y)
    print(event.char)
    if event.x>543 and event.y>525:
        return
    savePicmethod()

class New_Toplevel_1:
    def __init__(self, top=None):
        """This class configures and populates the toplevel window.
           top is the toplevel containing window."""
        top.geometry("640x660+408+185")#("555x398+408+185")  x  y
        top.title("collectfaceapp")
        #frame = Frame(app, width = 200, height = 200)
        #frame.bind("<Motion>",callback)
        top.bind("<Button-1>",callback)
        top.bind("<Button-2>",callback)
        top.bind("<Button-3>",callback)
        top.bind("<Key>",callback)
        top.focus_set()

        root.configure(background=_lightwindowbackground)

        self.next = Button(top)
        self.next.place(relx=0.86, rely=0.80 , height=50, width=70)
        self.next.configure(activebackground=_activebgcolordark)
        self.next.configure(command=lambda: self.detectDot(1))
        self.next.configure(cursor="left_ptr")
        self.next.configure(text='face_de')
        #self.next.configure(width=47)
        self.next.configure(background=_bgcolorlight)
        self.next.configure(fg=_fgcolorlight)

        self.auto = Button(top)
        self.auto.place(relx=0.86, rely=0.90, height=50, width=70)
        self.auto.configure(activebackground=_activebgcolordark)
        self.auto.configure(command=lambda: self.fastCollect())
        self.auto.configure(cursor="left_ptr")
        self.auto.configure(text='fast')
        #self.auto.configure(width=47)
        self.auto.configure(background=_bgcolorlight)
        self.auto.configure(fg=_fgcolorlight)

    def detectDot(self,method):
        print('not add ')
        pass

    def fastCollect(self):
        savePicmethod()

    @staticmethod
    def popup1(event):
        Popupmenu1 = Menu(root, tearoff=0)
        Popupmenu1.configure(activebackground="#f9f9f9")
        Popupmenu1.post(event.x_root, event.y_root)

def Manage_main():
    """ inter the main routine"""
    global  root
    root=Tk()
    #root.state("zoomed")
    root.resizable(width=False, height=False)
    top = New_Toplevel_1(root)
    m = Menubar(root)
    root.protocol('WM_DELETE_WINDOW', destroy_app)
    root.mainloop()

singleFoldNum = 600

def savePicmethod():
    pic_num =0
    global imagepathnum
    global saveimagepath
    cap = Device(0)
    cap1 = Device(1)
    if cap is None :

        winsound.Beep(50,400)
        return
    if cap1 is None:

        winsound.Beep(50,400)
        return
    '''
    if not ret :
        print('camera 1 is not OK!')
    if not ret1:
        print('camera 2 is not OK!')
    '''
    #while ret and ret1:
    while 1:
        '''
        ret, frame = cap.read()
        ret1, frame1 = cap1.read()
        '''
        frame = cap.getImage()
        frame = cv2.cvtColor(numpy.asarray(frame),cv2.COLOR_RGB2BGR)
        #frameor = frame
        frame1 = cap1.getImage()
        frame1 = cv2.cvtColor(numpy.asarray(frame1),cv2.COLOR_RGB2BGR)
        #frame1or = frame1

        save_color_path = os.path.join(saveimagepath,'%s/color'%imagepathnum)
        if not os.path.exists(save_color_path):
            os.makedirs(save_color_path)
        save_gray_path = os.path.join(saveimagepath,'%s/gray'%imagepathnum)
        if not os.path.exists(save_gray_path):
            os.mkdir(save_gray_path)

        color_file = os.path.join(save_color_path, "%s.jpg"%pic_num)
        gray_file = os.path.join(save_gray_path, "%s.jpg"%pic_num)

        cv2.imwrite(color_file, frame)
        cv2.imshow('clor',frame)
        cv2.imshow('gray',frame1)
        cv2.waitKey(3)#
        cv2.imwrite(gray_file, frame1)
        pic_num+=1
        if pic_num>singleFoldNum:
            pic_num = 0
            print('collect fold num %s OK!'%imagepathnum)
            imagepathnum +=1
            cv2.destroyAllWindows()
            break

    winsound.Beep(100,500)

if __name__ == "__main__":
    Manage_main()


# -*- coding: utf-8 -*-
"""
Created on Mon Oct 15 15:32:36 2012

@author: huanxin

This use for plot track of drifter, use ctl file "getcodar_ctl.txt"

JManning modifications:
    It apparently uses "raw" drifter data rather then the webserved ORACLE data.

"""
from matplotlib.dates import date2num, num2date
import datetime
import pylab
import sys
import numpy as np
import matplotlib.pyplot as plt
pydir='../'
sys.path.append(pydir)
from hx import getcodar_ctl_file,getdrift_raw_range_latlon,getdrift_raw

###############################################
inputfilename='./getcodar_bydrifter_ctl.txt'
(datetime_wanted,filename,driftnumber,url,model_option,num,interval_dtime,interval,step_size)=getcodar_ctl_file(inputfilename)
id3=int(driftnumber)  #change format

(maxlon,minlon,maxlat,minlat)=getdrift_raw_range_latlon(filename,id3,interval,datetime_wanted,num,step_size)
for i in range(5):
    if maxlat-minlat<=0.1:
        maxlat=maxlat+0.01
        minlat=minlat-0.01
    if maxlon-minlon<=0.1:
        maxlon=maxlon+0.01
        minlon=minlon-0.01
gbox=[minlon-0.03,maxlon+0.03, minlat-0.03, maxlat+0.03]
# get the edge of the picture

for x in range(num):
  (lat,lon,time1)=getdrift_raw(filename,id3,interval,datetime_wanted)
  fig = plt.figure()
  ax = fig.add_subplot(111)
  plt.title(str(num2date(datetime_wanted).strftime("%d-%b-%Y %H"))+'h')
  lat_wanted=lat[-1]
  lon_wanted=lon[-1]
  plt.plot(lon_wanted,lat_wanted,'.',markersize=30,color='r',label='end')

    #plt.plot(np.reshape(lon,np.size(lon)),np.reshape(lat,np.size(lat)))
  plt.plot(np.reshape(lon,np.size(lon)),np.reshape(lat,np.size(lat)),color='black')

    #basemap_usgs([minlat-1,maxlat+1],[minlon-1,maxlon+1],'True')
  plt.plot(lon[0],lat[0],'.',markersize=20,color='g',label='start')  # start time
  pylab.ylim([minlat-0.02,maxlat+0.02])
  pylab.xlim([minlon-0.02,maxlon+0.02])
  ax.patch.set_facecolor('lightblue')

  plt.legend( numpoints=1,loc=2)
  plt.savefig('./'+str(num2date(datetime_wanted).strftime("%d-%b-%Y %H"))+'h' + '.png')

  datetime_wanted=date2num(num2date(datetime_wanted)+datetime.timedelta( 0,step_size*60*60 ))
  plt.close()

plt.close()


from xmlrpc.server import SimpleXMLRPCServer
from subprocess import Popen
import sys,ctypes
from multiprocessing import freeze_support
import os

data_server_p = None
file_server_p = None
controller_p = None

def execute_launch_device(dev):
    print('Request to launch device {} received'.format(dev))
    command = 'python launch device {}'.format(dev)
    p = Popen(command)

    return dev

def execute_launch_data_server():
    global data_server_p
    print('Request to launch data server received')

    if data_server_p:
        data_server_p.kill()
    try:
        command = 'python launch data_server'
        data_server_p = Popen(command)
    except Exception as e:
        return False, e
    return True, ''

def execute_launch_file_server():
    global file_server_p
    print('Request to launch file server received')

    if file_server_p:
        file_server_p.kill()
    try:
        command = 'python launch file_server'
        print(command)
        file_server_p = Popen(command)
    except Exception as e:
        return False, e
    return True, ''

def execute_launch_controller():
    global controller_p
    print('Request to launch controller received')

    if controller_p:
        controller_p.kill()
    try:
        command = 'python launch controller'
        controller_p = Popen(command)
    except Exception as e:
        return False, e
    return True, ''

def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False

freeze_support()

os.chdir(u"C:\\Networked-data-acquisition")

server = SimpleXMLRPCServer(("0.0.0.0", 5050))
server.register_function(execute_launch_device, "execute_launch_device")
server.register_function(execute_launch_file_server, "execute_launch_file_server")
server.register_function(execute_launch_data_server, "execute_launch_data_server")
server.register_function(execute_launch_controller, "execute_launch_controller")

server.serve_forever()


from tkinter import *

"""
    Необходимо создать программу для отметĸи стран, ĸоторые посетили 2 друга.
    Изначально стран у ĸаждого друга не введено. Пользователь вводит поочередно
    или вразнобой посещенные страны для друзей. Страны в перечне ĸаждого друга
    не должны повторяться (Пример: если друг1 посетил Испанию, Италию, Испанию
    и Грецию, то посещенные страны друга1 будут выглядеть ĸаĸ Испания, Италия, Греция)
    Введенные страны без запроса на эĸране не выводятся. По требованию * вывести
    на эĸран пунĸтов задания:
    - Общие посещенные страны (без повторений)
    - Страны, в ĸоторых побывал тольĸо один из друзей.
    - Весь списоĸ стран посещенных друзьями (без повторений)

    Нужно использовать множества и их методы в решении.
"""
# -> создание окна и его параметры
root = Tk()
root.geometry('500x500+200+200')
root.title('Посещения стран')
root.config(bg='MediumAquamarine')

# -> виджеты окна
title_label = Label(root)
friend_1_label = Label(root)  # -> текст предшествующий вводу для первого друга
friend_2_label = Label(root)  # -> текст предшествующий вводу для второго друга
friend_1_entry = Entry(root)  # -> поле ввода данных для первого друга
friend_2_entry = Entry(root)  # -> поле ввода данных для второго друга
result_label = Label(root)  # -> отображает результат

button_confirm_f1 = Button(root)  # -> подтверждение ввода для первого друга
button_confirm_f2 = Button(root)  # -> подтверждение ввода для второго друга
button_result = Button(root)  # -> вызывает результат

# -> переменные типа str для хранения данных из entry
input_country_f1 = ''  # -> данные из entry первого друга (friend_1_entry)
input_country_f2 = ''  # -> данные из entry второго друга (friend_2_entry)

# -> параметры виджетов
def widgets_config():
    title_label.config(bg='MediumAquamarine', fg='CadetBlue', font=('Comic Sans Ms', 15), text='Посещения стран',
                       width=25)
    title_label.place(x=100, y=10)

    friend_1_label.config(text='Введите страну(-ы) для первого друга:', width=35, bg='MediumAquamarine', font='Arial 9')
    friend_1_label.place(x=10, y=60)

    friend_2_label.config(text='Введите страну(-ы) для второго друга:', width=35, bg='MediumAquamarine', font='Arial 9')
    friend_2_label.place(x=10, y=130)

    friend_1_entry.config(width=35, bd=3, relief=RIDGE)
    friend_1_entry.place(x=250, y=60)

    friend_2_entry.config(width=35, bd=3, relief=RIDGE)
    friend_2_entry.place(x=250, y=130)

    button_confirm_f1.config(width=12, text='Подтвердить', command=country_friend_1, font='Arial 9', bg='CadetBlue',
                             fg='white')
    button_confirm_f1.place(x=372, y=90)

    button_confirm_f2.config(width=12, text='Подтвердить', command=country_friend_2, font='Arial 9', bg='CadetBlue',
                             fg='white')
    button_confirm_f2.place(x=372, y=160)

    button_result.config(text='Вывести результаты посещения друзьями стран', width=60, command=result_country,
                         font='Arial 9', bg='CadetBlue', fg='white')
    button_result.place(x=35, y=200)

    result_label.config(bg='Aquamarine', width=60, height=15)
    result_label.place(x=35, y=235)

# -> получает данные из entry для первого друга
def country_friend_1() -> str:
    global input_country_f1
    if not input_country_f1:  # -> если переменная пустая
        # -> присваивает переменной строку из entry в нижнем регистре, удаляет пробелы по краям и заменяет , на пробел
        input_country_f1 = friend_1_entry.get().replace(',', ' ').strip().lower()
    else:
        new_input = friend_1_entry.get().replace(',', ' ').strip().lower()  # -> получает новый ввод из entry
        input_country_f1 = input_country_f1 + ' ' + new_input  # -> конкатенирует с уже существующими данными
    friend_1_entry.delete(0, END)  # -> очищает entry
    return input_country_f1

# -> получает данные из entry для второго друга
def country_friend_2() -> str:
    global input_country_f2
    if not input_country_f2:  # -> если переменная пустая
        # -> присваивает переменной строку из entry в нижнем регистре, удаляет пробелы по краям и заменяет , на пробел
        input_country_f2 = friend_2_entry.get().replace(',', ' ').strip().lower()
    else:
        new_input = friend_2_entry.get().replace(',', ' ').strip().lower()  # -> получает новый ввод из entry
        input_country_f2 = input_country_f2 + ' ' + new_input  # -> конкатенирует с уже существующими данными
    friend_2_entry.delete(0, END)  # -> очищает entry
    return input_country_f2

# -> находит общие страны, полный список стран и посещённые только одним из друзей. Выводит результат в label
def result_country():
    # -> сохраняет в переменную (type: set) одинаковые данные из двух entry (общие посещенные страны)
    general_countries = set.intersection(set(input_country_f1.split()), set(input_country_f2.split()))

    # -> сохраняет в переменную (type: set) уникальные элементы из двух entry (где побывал тольĸо один из друзей)
    visited_by_one_friend = set.symmetric_difference(set(input_country_f1.split()), set(input_country_f2.split()))

    # -> сохраняет в переменную (type: set) все элементы из двух entry (весь списоĸ стран посещенных друзьями)
    all_countries = set.union(set(input_country_f1.split()), set(input_country_f2.split()))

    # -> конверт.в str и переводит в верхний регистр первую букву каждого элемента
    general_countries_str = ', '.join(list(general_countries)).title()
    visited_by_one_friend_str = ', '.join(list(visited_by_one_friend)).title()
    all_countries_str = ', '.join(list(all_countries)).title()

    # -> устанавливает параметры для вывода результата в label
    result_label.config(text=f'- Общие посещенные страны:\n{general_countries_str}\n\n'
                             f'- Страны, в ĸоторых побывал тольĸо один из друзей:\n{visited_by_one_friend_str}\n\n'
                             f'- Весь списоĸ стран посещенных друзьями:\n{all_countries_str}', wraplength=370,
                        justify=LEFT, font='Arial 10', width=53)

# Ukraine canada Estonia usa Italy spain China hungary Japan - для проверки


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 24 12:45:13 2018

@author: ruben.ramirez
"""

##Imports
import pandas as pd
from bs4 import BeautifulSoup
import requests as r

##Base link to connect to PhoneDB
baseURL = 'http://phonedb.net/'

##Generate all pages links###################################################################
links_df = pd.DataFrame()
base_devices_detail_url = 'http://phonedb.net/index.php?m=device&s=list&filter='

for i in range(228):
    global links_df
    page = i * 59
    url = base_devices_detail_url + str(page)
    links_df = links_df.append(pd.DataFrame({'full_link': url}, index = [0]),ignore_index=True)
##########################################################################################

##CREATE AN EMPTY LINK DF DATA FRAME
df = pd.DataFrame()
##Get all link: For each phone
for link in links_df['full_link']:
    source_code=r.get(link)
    plain_text=source_code.text
    soup = BeautifulSoup(plain_text)
    soup_data = soup.find_all('div', class_='content_block')
    ##FOR EACH LINK, STORE IT IN THE DF
    for each in soup_data:
        if len(each.find_all('a')) > 0:
            detail_link = each.find_all('a')[0]['href']
            full_url =  baseURL+detail_link
            df = df.append(pd.DataFrame({'full_link': full_url}, index = [0]),ignore_index=True)

##Phone Specs ################################################################
device_specs = pd.DataFrame()

#for link in df['full_link']:
for link in df.full_link[11908:]:
    phone_source_code=r.get(link)
    phone_plain_text=phone_source_code.text
    phone_soup = BeautifulSoup(phone_plain_text, 'lxml')
    table = phone_soup.find('table')
    if table.find('a', id='datasheet_item_id2') is not None:
        name = table.find('a', id='datasheet_item_id2').parent.text #Title
    if table.find('a', id='datasheet_item_id49') is not None:
        ram = table.find('a', id='datasheet_item_id49').parent.text.split(' ')[0] #Ram
    if table.find('a', id='datasheet_item_id147') is not None:
        gpu = table.find('a', id='datasheet_item_id147').parent.text #GPU
    if table.find('a', id='datasheet_item_id36') is not None:
        cpu = table.find('a', id='datasheet_item_id36').parent.text #CPU
    device_specs = device_specs.append(pd.DataFrame({'model': name, 'ram': ram, 'gpu': gpu, 'cpu': cpu}, index = [0]),ignore_index=True)
    print("finish row" + " " + str(link))

device_specs.to_csv('spec_list_full.csv')


import sys
import os.path
import pickle
from collections import OrderedDict

def main():

    # command line arguments
    args = sys.argv

    # given command
    command = " ".join(args[1:])

    # open the log file if exists already, otherwise create one
    logfile = "aggiestack-log.txt"
    if fileExists(logfile):
        logfile = open(logfile, "a")
    else:
        logfile = open(logfile, "w")

    # command length should be atleast 4
    if (len(args) < 4):
        error(command, logfile)
        sys.exit(0)

    if args[1] == "aggiestack":
        # takes care of the config comamnds
        if args[2] == "config":
            if args[3] == "--hardware" and args[4]:
                status = readInputFile(args[4], "hardwareConfiguration.dct")
                if status == "SUCCESS":
                    status = updateCurrentHardware()
                logfile.write(command + "     " + status +"\n")
            elif args[3] == "-images" and args[4]:
                status = readInputFile(args[4], "imageConfiguration.dct")
                logfile.write(command + "     " + status +"\n")
            elif args[3] == "--flavors" and args[4]:
                status = readInputFile(args[4], "flavorConfiguration.dct")
                logfile.write(command + "     " + status +"\n")
            else:
                error(command, logfile)

        # takes care of the show commands
        elif args[2] == "show":
            if args[3] == "hardware":
                status = showContent("hardwareConfiguration.dct")
                logfile.write(command + "     " + status +"\n")
            elif args[3] == "images":
                status = showContent("imageConfiguration.dct")
                logfile.write(command + "     " + status +"\n")
            elif args[3] == "flavors":
                status = showContent("flavorConfiguration.dct")
                logfile.write(command + "     " + status +"\n")
            elif args[3] == "all":
                status = showAll()
                logfile.write(command + "     " + status +"\n")
            else:
                error(command, logfile)

        # takes care of the admin commands
        elif args[2] == "admin":
            if args[3] == "show":
                if args[4] == "hardware":
                    status = showContent("currentHardwareConfiguration.dct")
                    logfile.write(command + "     " + status +"\n")
                else:
                    error(command, logfile)
            elif args[3] == "can_host":
                if len(args) > 4 and args[4] and args[5]:
                    status = canHost(args[4],args[5])
                    logfile.write(command + "     " + status +"\n")
                else:
                    error(command, logfile)
            else:
                error(command, logfile)
        else:
            error(command, logfile)
    else:
        error(command, logfile)

# print error
def error(command, logfile):
    logfile.write(command + "     FAILURE" +"\n")
    print("Not a valid command \n", file=sys.stderr)
    helpMessage()
    return

# print help message
def helpMessage():
    print("Below are the only valid commands for this program:")
    print("aggiestack config --hardware <file name>\naggiestack config –images <file name>\n"\
    "aggiestack config --flavors <file name>'\naggiestack show hardware\n"\
    "aggiestack show images\naggiestack show flavors\naggiestack show all\n"\
    "aggiestack admin show hardware\naggiestack admin can_host <machine name> <flavor>")

# check if the given file exits
def fileExists(fileName):
    # get the current working directory
    cwd = os.getcwd()
    filePath = cwd + "/" + fileName

    if os.path.isfile(filePath):
        return True
    else:
        return False

# print the hardware config info
def printMachineHardwareDict(dict):
    for machine, configuration in dict.items():
        print('%s : %s' % (machine, configuration))

def fileNotEmpty(fileName):
    cwd = os.getcwd()

    if (os.path.getsize(cwd + "/" + fileName) > 0):
        return True
    else:
        return False

"""
Reads the given file and
save the content into a file
"""
def readInputFile(fileToRead, savedFile):
    status = "FAILURE"

    # a dictionary to store all the configurations
    contentList = {}

    # a dictionary to store only one instance's config
    config = {}

    # chekc if the file exists
    fileExist= fileExists(fileToRead)

    if fileExist:

        hardware = ["ip", "mem", "num-disks", "num-vcpus"]
        image = ["path"]
        flavor = ["mem", "num-disks", "num-vcpus"]

        if (savedFile == "hardwareConfiguration.dct"):
            listToLoop = hardware
        elif (savedFile == "imageConfiguration.dct"):
            listToLoop = image
        else:
            listToLoop = flavor

        # open the input file to read
        f = open(fileToRead, "r")
        lines = f.readlines()

        if fileExists(savedFile) and fileNotEmpty(savedFile):
            with open(savedFile, "rb") as f:
                contentList = pickle.load(f)

        # save the file data
        for line in lines[1:]:
            tokens = line.split()

            for i, val in enumerate(listToLoop):
                config[val] = tokens[i+1]

            contentList[tokens[0]] = config
            config = {}

        with open(savedFile, "wb") as f:
            pickle.dump(contentList, f)

        status = "SUCCESS"

    else:
        print("Given file does not exist")

    return status

"""
showContent method - sub-method
Used in various methods
"""
def showContent(fileToRead):
    status = "SUCCESS"

    if fileExists(fileToRead) and fileNotEmpty(fileToRead):
        with open(fileToRead, "rb") as f:
            config = pickle.load(f)

        configDict = OrderedDict(sorted(config.items(), key=lambda x: x[0]))

        printMachineHardwareDict(configDict)

    else:
        print("No information available")
    return status

"""
showAll - Used in show -all
Giving the statistics of all the resources
"""
def showAll():
    status = "SUCCESS"

    print("Hardware Info: \n")
    showContent("hardwareConfiguration.dct")
    print("Image Info: \n")
    showContent("imageConfiguration.dct")
    print("Flavor Info: \n")
    showContent("flavorConfiguration.dct")

    return status

"""
updateCurrentHardware - Updates currentHardwareConfiguration.dct whenever hardwareConfiguration.dct is updated
TODO: handle all cases when vCPUs can be allocated, as some entries should not be overwritten
"""
def updateCurrentHardware():
    status = "FAILURE"
    hardwareFile = "hardwareConfiguration.dct"
    currHardwareFile = "currentHardwareConfiguration.dct"
    columns = ["mem", "num-disks", "num-vcpus"]

    # a dictionary to store all the configurations
    currHardwareDict = {}

    if fileExists(hardwareFile) and fileNotEmpty(hardwareFile):
        with open(hardwareFile, "rb") as f:
            hardwareDict = pickle.load(f)

        # copy data from one dictionary to the other
        for machineName, machineInfo in hardwareDict.items():
            config = {}
            for val in columns:
                config[val] = machineInfo[val]

            currHardwareDict[machineName] = config

        # save to currHardwareDict
        with open(currHardwareFile, "wb") as f:
            pickle.dump(currHardwareDict, f)

        status = "SUCCESS"
    else:
        print("No information available")
    return status

"""
canHost - Checks if a particular machine currently has the resources to host a vCPU of the given flavor
"""
def canHost(machineName, flavorName):
    status = "FAILURE"
    flavorFile = "flavorConfiguration.dct"
    currHardwareFile = "currentHardwareConfiguration.dct"
    columns = ["mem", "num-disks", "num-vcpus"]

    if fileExists(flavorFile)  and fileExists(currHardwareFile) and fileNotEmpty(flavorFile) and fileNotEmpty(currHardwareFile):
		# retrieve the flavor and current hardware dicts from their files
        with open(flavorFile, "rb") as f:
            flavorDict = pickle.load(f)
        with open(currHardwareFile, "rb") as f:
            currentHardwareDict = pickle.load(f)

		# find the correct machine and flavor
        if (flavorName in flavorDict) and (machineName in currentHardwareDict):
            status = "SUCCESS"
			# check if the number of resources required is <= those available
            for val in columns:
                if int(flavorDict[flavorName][val]) > int(currentHardwareDict[machineName][val]):
                    print("No")
                    return status
            print("Yes")
        else:
            print("Record not found")
    else:
        print("No information available")
    return status

if __name__ == "__main__":
    main()


# -*- coding: utf-8 -*-
'''
将一张图片填充为正方形后切为9张图
Author:
'''
from PIL import Image
import sys

#将图片填充为正方形
def fill_image(image):
    width, height = image.size
    #选取长和宽中较大值作为新图片的
    new_image_length = width if width > height else height
    #生成新图片[白底]
    new_image = Image.new(image.mode, (new_image_length, new_image_length), color='white')
    #将之前的图粘贴在新图上，居中
    if width > height:#原图宽大于高，则填充图片的竖直维度
        #(x,y)二元组表示粘贴上图相对下图的起始位置
        new_image.paste(image, (0, int((new_image_length - height) / 2)))
    else:
        new_image.paste(image,(int((new_image_length - width) / 2),0))

    return new_image

#切图
def cut_image(image):
    width, height = image.size
    item_width = int(width / 8)
    box_list = []
    # (left, upper, right, lower)
    for i in range(0,8):#两重循环，生成9张图片基于原图的位置
        for j in range(0,8):
            #print((i*item_width,j*item_width,(i+1)*item_width,(j+1)*item_width))
            box = (j*item_width,i*item_width,(j+1)*item_width,(i+1)*item_width)
            box_list.append(box)

    image_list = [image.crop(box) for box in box_list]
    return image_list

#保存
def save_images(image_list):
    index = 1
    for image in image_list:
        image.save('./b/'+str(index) + '.jpg', 'PNG')
        index += 1


# -*- coding: utf-8-*-
import random
import re
import jasperpath

#mark1
new_word = "FEELING BETTER"
message = "yes i feel great now"

WORDS = ("%s" %new_word)

PRIORITY = 4
image = 'h9.png'

size = width, height = 320, 320
red = (255,0,0)
white = (255,255,255)
black = 0, 0, 0
x=0
y=0
def handle(self, text, mic, profile):

    self.blitimg(image, size, black, x, y)

    mic.speaker.play(jasperpath.data("audio/hal/better.wav"))

def isValid(text):
    """
        Returns True if the input is related to the meaning of life.

        Arguments:
        text -- user-input, typically transcribed speech
    """
    return bool(re.search(r'\b%s\b' %new_word, text, re.IGNORECASE))


"""

Leetcode 73
Zero Matrix: Write an algorithm such that if an element in an MxN matrix is 0, its entire row and
column are set to 0.

"""

class Solution(object):
    def setZeroes(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: void Do not return anything, modify matrix in-place instead.
        """

        row_flag = False
        col_flag = False

        row = len(matrix)
        col = len(matrix[0])

        for i in range(row):
            for j in range(col):
                if matrix[i][j] == 0:
                    if i == 0:
                        row_flag = True
                    if j == 0:
                        col_flag = True
                    matrix[0][j] = 0
                    matrix[i][0] = 0

        for i in range(1, row):
            for j in range(1, col):
                if matrix[i][0] == 0 or matrix[0][j] == 0:
                    matrix[i][j] = 0

        if row_flag:
            for j in range(col):
                matrix[0][j] = 0
        if col_flag:
            for i in range(row):
                matrix[i][0] = 0


import numpy as np
import tensorflow as tf
from tensorflow.python.ops import rnn, rnn_cell

class LSTM(object):
    def __init__(self, config):

        self.config = config
        assert self.config.num_hidden % len(self.config.periods) == 0
        self.global_step = tf.Variable(0, name='global_step', trainable=False)

        self.inputs  = tf.placeholder(tf.float32, shape=[None, self.config.num_steps, self.config.num_input], name="inputs")
        self.targets = tf.placeholder(tf.float32, shape=[None, self.config.num_output], name="targets")

        self._build_model()

        self._init_optimizer()

    def _build_model(self):
        weights = {
            'out': tf.Variable(tf.random_normal([self.config.num_hidden, self.config.num_output]))
        }
        biases = {
            'out': tf.Variable(tf.random_normal([self.config.num_output]))
        }

        self.inputs = tf.transpose(self.inputs, [1, 0, 2])
        self.inputs = tf.reshape(self.inputs, [-1, self.config.num_input])
        self.inputs = tf.split(0, self.config.num_steps, self.inputs)
        lstm_cell = rnn_cell.BasicLSTMCell(self.config.num_hidden, forget_bias=1.0)

        outputs, states = rnn.rnn(lstm_cell, self.inputs, dtype=tf.float32)
        self.prediction = tf.matmul(outputs[-1], weights['out']) + biases['out']

    def _init_optimizer(self):

        # Learning rate decay, note that is self.learning_rate_decay == 1.0,
        # the decay schedule is disabled, i.e. learning rate is constant.
        self.learning_rate = tf.train.exponential_decay(
            self.config.learning_rate,
            self.global_step,
            self.config.learning_rate_step,
            self.config.learning_rate_decay,
            staircase=True
        )
        self.learning_rate = tf.maximum(self.learning_rate, self.config.learning_rate_min)
        tf.scalar_summary("learning_rate", self.learning_rate)

        # Definition of the optimizer and computing gradients operation
        if self.config.optimizer == 'adam':
            # Adam optimizer
            self.optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate)
        elif self.config.optimizer == 'rmsprop':
            # RMSProper optimizer
            self.optimizer = tf.train.RMSPropOptimizer(learning_rate=self.learning_rate)
        elif self.config.optimizer == 'adagrad':
            # AdaGrad optimizer
            self.optimizer = tf.train.AdagradOptimizer(learning_rate=self.learning_rate)
        else:
            raise ValueError("Unknown optimizer specified")

        # Evaluate model
        correct_pred = tf.equal(tf.argmax(self.prediction,1), tf.argmax(self.targets,1))
        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))