import taichi as ti
import math

################################################################################
ti.init(arch = ti.gpu)
#
@ti.data_oriented
class StarSystem():
    def __init__(self, sn, pn, dt):
        self.sn = sn
        self.pn = pn
        self.dt = dt
        self.x = ti.Vector.field(2, dtype = ti.f32, shape = pn)
        self.v = ti.Vector.field(2, dtype = ti.f32, shape = pn)
        self.centers = ti.Vector.field(2, dtype = ti.f32, shape = sn)
    #
    @staticmethod
    @ti.func
    def random_vector(radius):
        theta = ti.random() * 2 * math.pi
        r = ti.random() * radius
        return r * ti.Vector([ti.cos(theta), ti.sin(theta)])
    #
    @ti.kernel
    def initialize_particles(self):
        for i in range(self.pn):
            print(i)
            self.x[i] = [0.5, 0.5] + self.random_vector(0.3)
            self.v[i] = [0.0, 0.0]
            for j in range(self.sn):
                offset = -(self.centers[j] - self.x[i])
                self.v[i] += [-offset.y / offset.norm() ** 1.5, offset.x / offset.norm() ** 1.5]
                #self.v[i] *= 1 / offset.norm() ** 1.5   # 开普勒第三定律近似
    #
    @ti.func
    def gravity(self, pos, center):
        offset = -(pos - center)
        return offset / offset.norm() ** 3
    #
    @ti.kernel
    def integrate(self):
        for i in range(self.pn):
            for j in range(self.sn):
                self.v[i] += self.dt * self.gravity(self.x[i], self.centers[j])
            self.x[i] += self.dt * self.v[i]
    #
    def render(self, gui):
        gui.circle([0.5, 0.35], radius = 10, color = 0xffaa88)
        gui.circle([0.4, 0.65], radius = 10, color = 0xffaa88)
        gui.circle([0.6, 0.65], radius = 10, color = 0xffaa88)
        gui.circles(self.x.to_numpy(), radius = 3, color = 0xffffff)

################################################################################
solar = StarSystem(3, 8, 0.0001)
solar.centers[0] = [0.5, 0.35]
solar.centers[1] = [0.4, 0.65]
solar.centers[2] = [0.6, 0.65]
solar.initialize_particles()

gui = ti.GUI('Solar System', (1280, 720), background_color = 0x0071a)
while gui.running:
    for e in gui.get_events():
        if e.key == ti.GUI.ESCAPE:
            exit()
        elif e.key == ti.GUI.SPACE:
            solar.initialize_particles()
    #if gui.get_event() and gui.is_pressed(gui.SPACE):
    #    solar.initialize_particles()
    for i in range(10):
        solar.integrate()
    solar.render(gui)
    gui.show()


from collections import defaultdict
class Graph:
    def __init__(self,vertices):
        self.graph = defaultdict(list) #dictionary containing adjacency List
        self.V = vertices #No. of vertices

    # function to add an edge to graph
    def addEdge(self,u,v):
        self.graph[u].append(v)

    def topo_rec(self,v,visited,stack):
    	visited[v]=True

    #	print(self.graph)

    	print(self.graph[v])
    	for i in self.graph[v]:
    		if visited[i] == False:
    			self.topo_rec(i,visited,stack)
    	stack.insert(0,v)

    def topo(self):
    	visited=[False]*self.V
    	stack=[]
    	for i in range(self.V):
    		if visited[i]==False:
    			self.topo_rec(i,visited,stack)
    	print (stack)

g= Graph(6)
g.addEdge(5, 2);
g.addEdge(5, 0);
g.addEdge(4, 0);
g.addEdge(4, 1);
g.addEdge(2, 3);
g.addEdge(3, 1);

g.topo()


from telemetry_consumer.utils import get_create_objdict
from telemetry_consumer.TelemetryHandler import TelemetryHandler, SchemaHandler

class NodeRedundancy(SchemaHandler):
    def __init__(self, container):
        super(NodeRedundancy, self).\
            __init__(container,\
                     ['RootOper.Redundancy.Node',\
                      'RootOper.Redundancy.Summary'],\
                     ['Cisco-IOS-XR-infra-rmf-oper:redundancy/nodes/node',\
                      'Cisco-IOS-XR-infra-rmf-oper:redundancy/summary']\
                 )

    def process(self, pmsg):
        dev_state, opath = self.process_header(pmsg)
        if pmsg.schema == self.schema[1]:
            row = pmsg.rows[0]
            self.update_fields(pmsg.schema, opath, row)
        else:
            for row in pmsg.rows.itervalues():
                row.node_id = row.get('node_id', 'MDT')
                node_state = get_create_objdict(dev_state, row.node_id)
                opath.extend([row.node_id, node_state])
                del row.node_id
                self.update_fields(pmsg.schema, opath, row)
                del opath[-2:]
        return opath

class SystemMonitoring(SchemaHandler):
    def __init__(self, container):
        super(SystemMonitoring, self).\
            __init__(container,\
                     ['RootOper.SystemMonitoring.CPUUtilization'],\
                     ['Cisco-IOS-XR-wdsysmon-fd-oper:'
                      'system-monitoring/cpu-utilization']\
            )

    def process(self, pmsg):
        dev_state, opath = self.process_header(pmsg)
        for row in pmsg.rows.itervalues():
            node_state = get_create_objdict(dev_state, row.node_name)
            opath.extend([row.node_name, node_state])
            del row.node_name

            proc_states = get_create_objdict(node_state, 'process_cpu')
            opath.extend(['process_cpu', proc_states])
            for proc in row.process_cpu:
                proc_state = get_create_objdict(proc_states, proc.process_name)
                opath.extend([proc.process_name, proc_state])
                del proc.process_name
                self.update_fields(pmsg.schema, opath, proc)
                del opath[-2:]
            del row.process_cpu
            self.update_fields(pmsg.schema, opath, row)
            del opath[-4:]
        return opath

class SoftwareInstall(SchemaHandler):
    def __init__(self, container):
        super(SoftwareInstall, self).\
            __init__(\
                     container,
                     ['RootOper.SoftwareInstall.Active',
                      'RootOper.SoftwareInstall.Version',
                      'RootOper.SoftwareInstall.Committed'],
                     ['Cisco-IOS-XR-spirit-install-instmgr-oper:'
                      'software-install/active',
                      'Cisco-IOS-XR-spirit-install-instmgr-oper:'
                      'software-install/version',
                      'Cisco-IOS-XR-spirit-install-instmgr-oper:'
                      'software-install/committed']
                    )

    def process(self, pmsg):
        dev_state, opath = self.process_header(pmsg)
        row = pmsg.rows[0]
        if pmsg.schema == self.schema[1]:
            dev_state.log = row.log
            self.update_fields(pmsg.schema, opath, row)
        else:
            if  pmsg.schema == self.schema[0]:
                pkg_type = 'active'
            else:
                pkg_type = 'committed'
            pkgs = row.get(pkg_type + '_package_info')

            if pkgs:
                pkg_state = get_create_objdict(dev_state, pkg_type)
                opath.extend([pkg_type, pkg_state])
                for pkg in pkgs:
                    node_state = get_create_objdict(pkg_state, pkg.location)
                    opath.extend([pkg.location, node_state])
                    del pkg.location

                    lpkgs = pkg_type + '_packages'
                    pkg.packages = pkg[lpkgs].lstrip().split('\n')[:-1]
                    del pkg[lpkgs]

                    npkgs = 'number_of_' + lpkgs
                    del lpkgs
                    pkg.num_packages = pkg[npkgs]
                    del pkg[npkgs]
                    del npkgs

                    self.update_fields(pmsg.schema, opath, pkg)
                    del opath[-2:]
                del pkgs[:]
                del pkgs
            del pkg_type
        return opath

class InterfaceStats(SchemaHandler):
    def __init__(self, container):
        super(InterfaceStats, self).__init__(
            container,
            ['RootOper.InfraStatistics.Interface.Latest.Protocol',
             'RootOper.InfraStatistics.Interface.Latest.GenericCounters',
             'RootOper.InfraStatistics.Interface.Latest.DataRate'],
            ['Cisco-IOS-XR-infra-statsd-oper:'
             'infra-statistics/interfaces/interface/latest/protocols/protocol',
             'Cisco-IOS-XR-infra-statsd-oper:'
             'infra-statistics/interfaces/interface/latest/generic-counters',
             'Cisco-IOS-XR-infra-statsd-oper:'
             'infra-statistics/interfaces/interface/latest/data-rate']
        )

    def process(self, pmsg):

        dev_state, opath = self.process_header(pmsg)
        for row in pmsg.rows.itervalues():
            istate = get_create_objdict(dev_state, row.interface_name)
            opath.extend([row.interface_name, istate])
            del row.interface_name
            if pmsg.schema == self.schema[0]:
                ipstate = get_create_objdict(istate, 'protocols')
                opath.extend(['protocols', ipstate])
                ipstate = get_create_objdict(ipstate, row.protocol_name)
                opath.extend([row.protocol_name, ipstate])
                del row.protocol_name
                self.update_fields(pmsg.schema, opath, row)
                del opath[-4:]
            else:
                self.update_fields(pmsg.schema, opath, row)
            del opath[-2:]
            row.clear()
        return opath

class InterfaceStatus(SchemaHandler):
    def __init__(self, container):
        super(InterfaceStatus, self).\
            __init__(
                container,
                ['RootOper.Interfaces.Interface'],
                ['Cisco-IOS-XR-pfi-im-cmd-oper'
                 ':interfaces/interfaces/interface']
            )

    def process(self, pmsg):
        return self.process_with_indices(pmsg, ['interface_name'])

class ISISInterface(SchemaHandler):
    def __init__(self, container):
        super(ISISInterface, self).__init__(
            container,
            ['RootOper.ISIS.Instance.Interface'],
            ['Cisco-IOS-XR-clns-isis-oper:isis/instances/instance/interfaces/interface']
            )

    def process(self, pmsg):
        return self.process_with_indices(pmsg, ['instance_name', 'interface_name'])

class ISISNeighbor(SchemaHandler):
    def __init__(self, container):
        super(ISISNeighbor, self).__init__(
            container,
            ['RootOper.ISIS.Instance.Neighbor'],
            ['Cisco-IOS-XR-clns-isis-oper:isis/instances/instance/neighbors/neighbor']
            )

    def process(self, pmsg):
        return self.process_with_indices(pmsg, ['instance_name', 'interface_name'])

class ISISTopology(SchemaHandler):
    def __init__(self, container):
        super(ISISTopology, self).\
            __init__(
                container,
                ['RootOper.ISIS.Instance.Topology.IPV4Route'],
                ['Cisco-IOS-XR-clns-isis-oper:'\
                 'isis/instances/instance/topologies/topology/ipv4-routes/'\
                 'ipv4-route']
            )

    def process(self, pmsg):
        return self.process_with_indices(pmsg, ['instance_name', 'prefix'])

class RobotTelemetryHandler(TelemetryHandler):

    def __init__(self):
        self.handlers = [NodeRedundancy(self), SystemMonitoring(self),
                         SoftwareInstall(self), InterfaceStats(self),
                         InterfaceStatus(self), ISISInterface(self),
                         ISISNeighbor(self), ISISTopology(self)]

        self.set_schema_type()
        super(RobotTelemetryHandler, self).__init__(self.handlers)

    def set_schema_type(self):
        return

class MDTRobotTelemetryHandler(RobotTelemetryHandler):
    def __init__(self):
        super(MDTRobotTelemetryHandler, self).__init__()

    def set_schema_type(self):
        for handler in self.handlers:
            handler.set_schema_type(mdt=True)


"""
Author: Sikder Tahsin Al-Amin
Problem: Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
"""
def maxSubArray(nums):
    max_so_far = max(nums)
    max_ending_here = 0
    if len(nums)==1:
        return nums[0]
    for i in range(0,len(nums)):
        max_ending_here = max_ending_here + nums[i]
        if max_ending_here<0:
            max_ending_here =0
        else:
            if max_so_far <max_ending_here:
                max_so_far = max_ending_here
    return max_so_far

def maxSubArray2(nums):
    n=len(nums)
    maxsofar=max(nums)
    temp=0
    for i in range(n):
        temp+=nums[i]
        if temp>=0:
            maxsofar=max(maxsofar, temp)
        else: temp=0

    return maxsofar


import numpy as np
from skimage import color
from fin_detect import fin_detect

def orientation(image):

    """
    Determines the orientation of the sharkfin in the image.

    Parameters
    ----------
    image : ndarray
        Input image.

    Returns
    -------
    orientation : {'left', 'right'}
        Estimated fin orientation.  The direction returned is the
        direction the shark is swimming.

    Notes
    -----
    - Compute the magnitude of the gradient of the path.
    - Take its first derivative to see how much it varies.
    - Take the median of the first derivative (median to avoid noise by
      outliers).
    - This should give an indication of the smoothness of the gradient,
      which is typically much greater for one side of the fin than the other.

    """

    image = color.rgb2gray(image)

    left_path = fin_detect(image, startpoint=(0, image.shape[1] // 2),
                           endpoint=(image.shape[0] - 1, 0))
    right_path = fin_detect(image,
                            startpoint=(0, image.shape[1] // 2),
                            endpoint=(image.shape[0] - 1, image.shape[1] - 1))

    left_path = left_path[:len(left_path) * 2 / 3]
    right_path = right_path[:len(right_path) * 2 / 3]

    def median_grad_der(path):
        x, y = np.gradient(path)
        g = np.sqrt(x**2 + y**2)

        return np.median(np.diff(g))

    g_left = median_grad_der(left_path)
    g_right = median_grad_der(right_path)

    if g_left > g_right:
        return 'left'
    else:
        return 'right'


from aichi.models import AiTreaty
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from django.core.urlresolvers import reverse
from django.template.context import RequestContext
from django.shortcuts import redirect
from forms import AiGoalActivitiesForm
from django.shortcuts import get_object_or_404
from models import AiGoals, AiGoalActivities
from aichi_activities import inject_permissions_into_context, \
    user_can_change_aichi_activity

@login_required
def index(request):
    ctx = RequestContext(request)

    rows = list()
    for row in AiGoalActivities.objects.order_by('odata_name'):
        treaty = AiTreaty.objects.get(odata_name=row.odata_name)
        target = AiGoals.objects.get(pk=row.target_id)
        rows.append({
            'treaty': treaty,
            'target': target,
            'activity': row,
            'can_change': user_can_change_aichi_activity(request, row.odata_name)
        })
    ctx['rows'] = rows
    return render(request, 'aichi_activities/index.html',
                  context_instance=ctx)

@login_required
def goal_activity_edit(request, id_target, odata_name):
    ctx = inject_permissions_into_context(RequestContext(request), request, odata_name)
    if not ctx['change_aigoalactivities']:
        return render(request, 'permissions.html',
                      context_instance=RequestContext(request))

    target = get_object_or_404(AiGoals, pk=id_target)
    if not odata_name or len(odata_name) <= 0:
        messages.error(request, "Please specify instrument's OData identifier")
        return redirect(reverse('aichi_activities.views.index'), request={})
    try:
        ob = AiGoalActivities.objects.get(target=target, odata_name=odata_name)
    except:
        ob = AiGoalActivities(target=target, odata_name=odata_name)

    ctx['form'] = AiGoalActivitiesForm(user=request.user, instance=ob)
    ctx['target'] = target
    ctx['odata_name'] = odata_name
    ctx['instrument'] = AiTreaty.get_instrument_name(odata_name)

    if request.method == 'POST':
        if 'delete' in request.POST.keys():
            if ctx['delete_aigoalactivities']:
                if 'confirmed' in request.POST.keys():
                    ob.delete()
                    messages.success(request, 'Activity has been successfully removed')
                    return redirect(reverse('aichi_activities.views.index'), request={})

                elif request.POST.has_key('cancel'):
                    return render(request, 'aichi_activities/edit.html',
                                  context_instance=ctx)

                else:
                    return render(request, 'aichi_activities/delete.html',
                                  context_instance=ctx)
            else:
                messages.error(request, 'You do not have sufficient privileges to delete this record')
        elif 'save' in request.POST.keys():
            form = AiGoalActivitiesForm(request.POST, user=request.user, instance=ob)
            if form.is_valid():
                messages.success(request, 'Activity successfully updated')
                form.save()

    return render(request, 'aichi_activities/edit.html',
                  context_instance=ctx)


"""
* MSSV: 1713454
"""
"""
 * @author nhphung
"""
from AST import *
from Visitor import *
from Utils import Utils
from StaticError import *
from functools import*
from copy import deepcopy

class MType:
    def __init__(self, partype, rettype):
        self.partype = partype
        self.rettype = rettype
    def __str__(self):
        return 'MType(['+','.join(str(x) for x in self.partype )+ '],'+str(self.rettype)+')'
class Symbol:
    def __init__(self, name, mtype, value=None):
        self.name = name
        self.mtype = mtype
        self.value = value
    def __str__(self):
        return 'Symbol("'+self.name+'",'+str(self.mtype) +', '+str(self.value) +')'
@dataclass  # automatically init
#contain some utils for general purposes
class CheckUtils:
    @staticmethod
    def checkRedeclared(self, id: str, kind: Kind, env: list):
        if id in env:
            raise Redeclared(kind, id)
        else:
            return False
    #function check if two objects are of same class
    #mode = 0: 1 direction (int -> float: true)
    #mode = 1: 2 direction (int ->float : false)
    @staticmethod
    def checkCompatible(src,dest,mode=0):
        if mode ==1:
            if type(src) is type(dest):
                if isinstance(src,(ArrayType,ArrayPointerType)):
                    return type(src.eleType) is type(dest.eleType)
                else: return True
            else: return False
        elif mode ==0:
            if type(src) is type(dest):
                if isinstance(src,(ArrayType,ArrayPointerType)):
                    return type(src.eleType) is type(dest.eleType)
                else: return True
            elif isinstance(src,IntType) and isinstance(dest,FloatType):
                return True
            elif isinstance(src,ArrayType) and isinstance(dest,ArrayPointerType):
                return type(src.eleType) is type(dest.eleType)
            else: return False
        else:
            raise Exception("error in CheckCompatible()")

    @staticmethod
    #this method is to visit stmt
    def visitElement(checker,ast,envi,info):

        # CheckUtils.Print(envi)
        # print("ast: "+str(ast))
        isTerminal=[False,False] #isreturn , isBreak/continue
        if ast is None: return isTerminal
        if isinstance(ast,Block):
            envi.append([("block",info)])
            isTerminal=checker.visit(ast,envi)
            envi.pop()
        else:
            isTerminal=checker.visit(ast,envi)
        return isTerminal

    @staticmethod
    def isInLoop(envi):
        for x in envi[2:][::-1]:
            if x[0][0] in ("for","while"): return True
        return False

defaultValue=0
class StaticChecker(BaseVisitor, Utils):

    #Initial global_evi with built-in functions of MC Parser
    built_in = [[
        ("outermost",),
        Symbol("getInt", MType([], IntType())),
        Symbol("putInt", MType([IntType()], VoidType())),
        Symbol("putIntLn", MType([IntType()], VoidType())),
        Symbol("getFloat", MType([], FloatType())),
        Symbol("putFloat", MType([FloatType()], VoidType())),
        Symbol("putFloatLn", MType([FloatType()], VoidType())),
        Symbol("putBool", MType([BoolType()], VoidType())),
        Symbol("putBoolLn", MType([BoolType()], VoidType())),
        Symbol("putString", MType([StringType()], VoidType())),
        Symbol("putStringLn", MType([StringType()], VoidType())),
        Symbol("putLn", MType([], VoidType()))
    ]]

    def __init__(self, ast):
        self.ast = ast
        self.unreachableFunc=[]

    def check(self):
        return self.visit(self.ast, StaticChecker.built_in)
    #return an entire global_envi
    def visitProgram(self, ast:Program, builtIn):
        #copy built-in into global_envi
        global_envi=deepcopy(builtIn)

        #create global_envi first:
        for x in ast.decl:
            if isinstance(x,VarDecl): #vardecl
                if self.lookup(x.variable, global_envi[0][1:], lambda x: x.name) is not None:
                    raise Redeclared(Variable(),x.variable)
                else:
                    global_envi[0].append(Symbol(x.variable,x.varType,defaultValue))

            else: #funcdecl

                if self.lookup(x.name.name,global_envi[0][1:],lambda x: x.name) is not None:
                    raise Redeclared(Function(),x.name.name)
                else:
                    paramType=[y.varType for y in x.param]
                    global_envi[0].append(Symbol(x.name.name,MType(paramType,x.returnType)))
                    if x.name.name!="main":
                        self.unreachableFunc.append(x.name.name)

        #check entry point:
        mainFunc=self.lookup("main",global_envi[0][1:],lambda x:x.name)
        if mainFunc is None:
            raise NoEntryPoint()
        elif not isinstance(mainFunc.mtype,MType):
            raise NoEntryPoint()

        #visit every FuncDecl:
        for x in ast.decl:
            if isinstance(x,FuncDecl):
                self.visit(x, global_envi)
        #check unreachable functon:
        if len(self.unreachableFunc)>0:
            raise UnreachableFunction(self.unreachableFunc[0])

    def visitFuncDecl(self, ast:FuncDecl, envi):

        #add local envi
        paramType=[y.varType for y in ast.param]
        # add symbol of current function for checking Return stmt, like: [global envi] [current function is visiting,local envi] ...
        envi.append([Symbol(ast.name.name,MType(paramType,ast.returnType))])
        #check parameters

        for x in ast.param:
            if self.lookup(x.variable, envi[-1][1:], lambda y: y.name) is not None:
                raise Redeclared(Parameter(),x.variable)
            else:
                envi[-1].append(Symbol(x.variable,x.varType,defaultValue))

        isReturn=False
        if self.visit(ast.body,envi)[0] is True: isReturn=True # <isReturn>, <isBreak/Continue>
        envi.pop()
        if not isinstance(ast.returnType,VoidType) and not isReturn: raise FunctionNotReturn(ast.name.name)

    def visitVarDecl(self, ast:VarDecl, envi):
        #here we just visit vardecl in function
        if self.lookup(ast.variable, envi[-1][1:], lambda x: x.name) is not None:
            raise Redeclared(Variable(),ast.variable)
        else:
            envi[-1].append(Symbol(ast.variable,ast.varType))

    def visitDowhile(self, ast, envi):
        isTerminal = [False,False] # <isReturn>, <isBreak/Continue>

        envi.append([["while"]])
        for x in ast.sl:
            if True in isTerminal:
                raise UnreachableStatement(x)
            checkTerminal=CheckUtils.visitElement(self,x,envi,"while")
            if type(checkTerminal)==list:
                if checkTerminal[0] is True: isTerminal[0]=True
                if True in checkTerminal : isTerminal[1]=True # 1 return 2 break -> [false,true] để có thể terminal cho vòng lặp, mạnh(return) + yếu(break/continue) -> yếu (break/continue)
        envi.pop()
        exprType=self.visit(ast.exp,envi)
        if not isinstance(exprType[0],BoolType): raise TypeMismatchInStatement(ast)
        return isTerminal
    #envi[1] is element contains current function visited
    def visitReturn(self, ast:Return, envi):
        FuncRetType= envi[1][0].mtype.rettype
        #case: ast.expr = None
        if ast.expr is None:
            if not isinstance(FuncRetType, VoidType):
                raise TypeMismatchInStatement(ast)
        else:
        #case: ast.expr != None
            ExpType = self.visit(ast.expr,envi)

            if not CheckUtils.checkCompatible(ExpType[0],FuncRetType):
                raise TypeMismatchInStatement(ast)
        #has Return stmt
        return [True,False]

    def visitContinue(self, ast, envi):
        for x in envi[2:][::-1]:
            if x[0][0] in ("for","while"):  return [False,True]
        raise ContinueNotInLoop()

    def visitBreak(self, ast, envi):

        for x in envi[2:][::-1]:
            if x[0][0] in ("for","while"):  return [False,True]
        raise BreakNotInLoop()

    def visitFor(self, ast:For, envi):
        envi.append([["for"]])
        expr1Type=self.visit(ast.expr1,envi)
        if not isinstance(expr1Type[0],IntType): raise TypeMismatchInStatement(ast)
        expr2Type=self.visit(ast.expr2,envi)
        if not isinstance(expr2Type[0],BoolType): raise TypeMismatchInStatement(ast)
        expr3Type=self.visit(ast.expr3,envi)
        if not isinstance(expr3Type[0],IntType): raise TypeMismatchInStatement(ast)
        Temp=CheckUtils.visitElement(self,ast.loop,envi,"for")
        mixEnvi=reduce(lambda  x,y:x+y[1:], envi,[])
        for x in envi[-1][0][1:]:# delete value initialized in for
            y=self.lookup(x,mixEnvi[::-1],lambda z:z.name)
            if y is not None:
                y.value=None
        envi.pop()
        if type(Temp) is list:
            return [False,Temp[1]] # return in For loop is ignored

    def visitIf(self, ast:If, envi):
        envi.append([["if"]])
        #check expr
        exprType=self.visit(ast.expr,envi)
        if not isinstance(exprType[0],BoolType):
            raise TypeMismatchInStatement(ast)
        #visit thenStmt and elseStmt
        envi.append([["then"]])
        isTerminal1= CheckUtils.visitElement(self,ast.thenStmt,envi,"then")
        envi.pop()
        envi.append([["else"]])
        isTerminal2= CheckUtils.visitElement(self,ast.elseStmt,envi,"else")
        envi.pop()
        isTerminal=[False,False]
        isTerminal[0]=isTerminal1[0] and isTerminal2[0]
        isTerminal[1] = (isTerminal1[0] or isTerminal1[1]) and(isTerminal2[0] or isTerminal2[1])

        mixEnvi=reduce(lambda  x,y:x+y[1:], envi,[])
        for x in envi[-1][0][1:]:# delete value initialized in for
            y=self.lookup(x,mixEnvi[::-1],lambda z:z.name)
            if y is not None:
                y.value=None
        envi.pop()
        return isTerminal

    def visitBlock(self, ast, envi):
        isTerminal =[False,False]
        if CheckUtils.isInLoop(envi):
            for x in ast.member:
                if (True in isTerminal) and isinstance(x,AST.Stmt): raise UnreachableStatement(x)
                checkTerminal=CheckUtils.visitElement(self,x,envi,"block")
                if type(checkTerminal)==list:
                    #if checkTerminal[0] or checkTerminal[1] is True: isTerminal[1] =True
                    isTerminal[1] = True in checkTerminal
                    isTerminal[0] = False #DO NOT CONSIDER VALUE OF EXPRESSION IN LOOP, SO  RETURN IN LOOP IS IGNORED

        else:

            for x in ast.member:
                if isTerminal[0] and isinstance(x,AST.Stmt): raise UnreachableStatement(x)
                checkTerminal=CheckUtils.visitElement(self,x,envi,"block")
                if type(checkTerminal)==list:
                    if checkTerminal[0] is True: isTerminal[0] =True
        return isTerminal
# literal: abstract

    def visitBooleanLiteral(self, ast, c):
        return BoolType(), True, ast.value

    def visitStringLiteral(self, ast, c):
        return StringType(), True, ast.value

    def visitFloatLiteral(self, ast, c):
        return FloatType(), True,ast.value

    def visitIntLiteral(self, ast, c):
        return IntType(), True, ast.value

    def visitCallExpr(self, ast:CallExpr, envi):

    #check undeclared function, except envi[1] is current dupplicated function
        mixEnvi= reduce(lambda x,y:x+y[1:],envi,[])
        CallExprSymbol=self.lookup(ast.method.name,mixEnvi[::-1],lambda x:x.name )

        if CallExprSymbol is None:
            raise Undeclared(Function(),ast.method.name)
        if not isinstance(CallExprSymbol.mtype,MType): #avoid lookup return a variable
            raise TypeMismatchInExpression(ast)
    #mark this funciton that called (delete this function name in unreachable func list)
        if (CallExprSymbol.name in self.unreachableFunc) and (CallExprSymbol.name!= envi[1][0].name): #just delete 1 time
            self.unreachableFunc.remove(CallExprSymbol.name)

    #check mismatch parameter
        if not isinstance(CallExprSymbol.mtype,MType) or len(ast.param) != len(CallExprSymbol.mtype.partype):
            raise TypeMismatchInExpression(ast)
        for i in range(len(ast.param)):
            thisParaType=self.visit(ast.param[i],envi)
            if not CheckUtils.checkCompatible(thisParaType[0],CallExprSymbol.mtype.partype[i]):
                raise TypeMismatchInExpression(ast)

    #return type for later checking
        return CallExprSymbol.mtype.rettype, False, None #<type> <isConstant>

    def visitUnaryOp(self, ast:UnaryOp, envi):
    #check inside UnaryOp
    #return Type for later check

        bodyType=self.visit(ast.body,envi) #<type> <isConstant> <value>
        expression=ast.op+str(bodyType[2])
        try:
            result=eval(expression)
        except:
            result = None
        if ast.op =='!' and isinstance(bodyType[0],BoolType):
            return BoolType(), bodyType[1],result
        if ast.op =='-' and isinstance(bodyType[0],(IntType,FloatType)):
            return bodyType[0],bodyType[1],result
        raise TypeMismatchInExpression(ast)

    def visitBinaryOp(self, ast:BinaryOp, envi):

        assignOp =['=']
        boolOp=['==', '!=', '!', '&&', '||']
        intOp1=['+', '-', '*', '/', '%']
        intOp2=[ '<', '<=', '>', '>=', '==', '!=' ]
        floatOp1=[ '+', '-', '*', '/']
        floatOp2=['<', '<=', '>' , '>=' ]

        right=self.visit(ast.right,envi)
        # initialize for variable: in for / dowhile / if (not else) not consider initialized
        if ast.op in assignOp:
            mixEnvi= reduce(lambda x,y:x+y[1:],envi,[])
            if isinstance(ast.left,Id): # i =5+6, consider array cell A[10] there is only 1 value eg, A[10]= {x}
                idLHS=self.lookup(ast.left.name,mixEnvi[::-1],lambda x:x.name)
                if idLHS is not None:
                    if idLHS.value is None:
                        idLHS.value=defaultValue
                        for x in list(range(2,len(envi)))[::-1]:
                            if envi[x][0][0] in ("for", "while"):
                                envi[x][0].append(idLHS.name)
                            elif envi[x][0][0] =="if":
                                if len(envi)>x+1:
                                    if envi[x+1][0][0]=="then":
                                        envi[x][0].append(idLHS.name)
                    else:
                         for x in list(range(2,len(envi)))[::-1]:
                            if envi[x][0][0] =="if":
                                if len(envi)>x+1:
                                    if envi[x+1][0][0] =="else" and (idLHS.name in envi[x][0]):
                                        envi[x][0].remove(idLHS.name)

        left=self.visit(ast.left,envi)

        isConstant= left[1] and right[1]
        expression= str(left[2])+ast.op+str(right[2])

        try:
            result=eval(expression);
        except :
            result=None

    #check assign Op
        if ast.op in assignOp:

            #check not left value:
            if not isinstance(ast.left,(Id,ArrayCell)):
                raise NotLeftValue(ast.left)
            #LHS is not void type, array type, array pointer type
            if isinstance(left[0],(VoidType,ArrayType,ArrayPointerType)):
                raise TypeMismatchInExpression(ast)

            if CheckUtils.checkCompatible(right[0],left[0]):
                return left[0],isConstant, result

    #check other Ops:
        #check bool exp:
        if isinstance(left[0],BoolType) and isinstance(right[0],BoolType):
            if ast.op  in boolOp:
                return BoolType(), isConstant, result

        #check int exp:
        if isinstance(left[0],IntType) and isinstance(right[0],IntType):
            if ast.op in intOp1:
                if ast.op=='/' and type(eval(str(left[2]))) is int and type(eval(str(right[2]))) :
                    expression= str(left[2])+"//"+str(right[2])
                try:
                    result=eval(expression);
                except :
                    result=None
                return IntType(), isConstant, result
            if ast.op in intOp2:
                return BoolType(), isConstant, result

        #check float exp:
        if isinstance(left[0],(IntType,FloatType)) and isinstance(right[0],(IntType,FloatType)):
            if isinstance(left[0],FloatType) or isinstance(right[0],FloatType):
                if ast.op in floatOp1:
                    return FloatType(), isConstant, result
                if ast.op in floatOp2:
                    return BoolType(), isConstant, result

        #check string exp: in "check assign Op" on the top
        raise TypeMismatchInExpression(ast)

    def visitArrayCell(self, ast:ArrayCell, envi):

    # arrayCell: a[i] or foo(..)[i] support i is integer exp, a is name of variable of ArrType|ArrPorterType, foo(): return type of ArrayPointerType
    #check mismatch inside of ArrayCell
        arrType=self.visit(ast.arr,envi)
        idxType=self.visit(ast.idx,envi)

        if not isinstance(arrType[0],(ArrayType,ArrayPointerType)):
            raise TypeMismatchInExpression(ast)
        if not isinstance(idxType[0],IntType):
            raise TypeMismatchInExpression(ast)

    #get value of index expression
        valueIndexExpr = idxType[2]
        isConstant = idxType[1]
    #return Type for later checking mismatch in Expr
        mixEnvi= reduce(lambda x,y:x+y[1:],envi,[])
        # a[i]: with a is ArrayType or ArrayPointerType
        if isinstance(ast.arr,Id):
            arraySymbol=self.lookup(ast.arr.name,mixEnvi[::-1],lambda x:x.name)
            if arraySymbol is None:
                raise Undeclared(Identifier(),ast.arr.name)

            #check index out of range, just with arraytype (arraytype just in vardecl)
            if isConstant and type(arraySymbol.mtype) is ArrayType : # index expr is constants
                if valueIndexExpr not in range(int(str(arraySymbol.mtype.dimen))): #cast type since arraySymbol.mtype.dimen is a TerminalNode???
                    raise IndexOutOfRange(ast)
            return arraySymbol.mtype.eleType,False , arraySymbol.value
        #foo(..)[i]
        else:
            arraySymbol=self.lookup(ast.arr.method.name,mixEnvi[::-1],lambda x:x.name)
            if arraySymbol is None:
                raise Undeclared(Function(),ast.arr.method)
            if not isinstance(arraySymbol.mtype,MType): #case foo is a variable (int foo;)
                raise TypeMismatchInExpression(ast.arr)
            return arraySymbol.mtype.rettype.eleType, False, arraySymbol.value

    def visitId(self, ast, envi):
        mixEnvi= reduce(lambda x,y:x+y[1:],envi,[])
        idSymbol=self.lookup(ast.name,mixEnvi[::-1],lambda x:x.name)

        if idSymbol is None:
            raise Undeclared(Identifier(),ast.name)

        if not isinstance(idSymbol.mtype,(MType,ArrayType,ArrayPointerType)) and idSymbol.value is None:
            raise UninitializedVariable(ast.name)
        return idSymbol.mtype, False, idSymbol.value #<type> <isConstant> <value>


# -*- encoding: utf-8 -*-
from collections import OrderedDict
from PIL import Image
from datetime import datetime
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import models
from django.dispatch import receiver
from django.utils.translation import gettext_lazy as _
from core import image_utils

MEDIA_ROOT = settings.MEDIA_ROOT

ITEM_SECTIONS = (
    ('school', _('School literature')),
    ('recommended', _('Good books to read')),
)

ITEM_SCHOOL_CLASSES = (
    (1, 1),
    (2, 2),
    (3, 3),
    (4, 4),
    (5, 5),
    (6, 6),
    (7, 7),
    (8, 8),
    (9, 9),
    (10, 10),
    (11, 11),
)

class Item(models.Model):
    section = models.CharField(
        verbose_name='Раздел',
        max_length=32,
        db_index=True,
        choices=ITEM_SECTIONS
    )

    cover = models.ImageField(
        verbose_name=u'Обложка',
        upload_to='recommended_reading/covers/%Y/%m',
        blank=True
    )

    title = models.CharField(
        verbose_name=u'Заглавие',
        max_length=2048,
    )

    school_class = models.IntegerField(
        verbose_name=u'Класс',
        null=True,
        blank=True,
        choices=ITEM_SCHOOL_CLASSES,
        help_text=u'Если издание рекомендуется школьникам - указать класс'
    )

    author = models.CharField(
        verbose_name=u'Автор',
        max_length=2048,
        help_text=u'Если авторов несколько, то указывать через запятую',
        blank=True
    )

    date_of_publication = models.IntegerField(
        verbose_name=u'Год публикации',
        null=True,
        blank=True
    )

    publisher = models.CharField(
        verbose_name=u'Издатель',
        max_length=2048,
        blank=True
    )

    annotation = models.TextField(
        verbose_name=u'Аннотация',
        max_length=10 * 1024,
        blank=True
    )

    record_id = models.CharField(
        verbose_name=u'Идентификатор записи в каталоге',
        max_length=128,
        blank=True
    )

    published = models.BooleanField(
        verbose_name=u'Опубликовано',
        default=False,
        db_index=True
    )

    created = models.DateTimeField(
        verbose_name=u'Дата создания',
        auto_now_add=True,
        db_index=True,
    )

    updated = models.DateTimeField(
        verbose_name=u'Дата Обновления',
        auto_now=True,
        db_index=True,
    )

    class Meta:
        verbose_name = u'Издание'
        verbose_name_plural = u'Рекомендуемая литература'

    def clean(self):
        if self.section == 'school' and not self.school_class:
            raise ValidationError({
                'school_class': 'Небходимо выбрать класс'
            })

        self.record_id = self.record_id.strip()

    def get_attrs(self):

        attrs = OrderedDict()

        attrs['school_class'] = {
            'title': u'Класс',
            'value': self.school_class
        }

        attrs['author'] = {
            'title': u'Автор',
            'value': self.author
        }

        attrs['date_of_publication'] = {
            'title': u'Год публикации',
            'value': self.date_of_publication
        }

        attrs['publisher'] = {
            'title': u'Издатель',
            'value': self.publisher
        }

        return attrs

ITEM_ATTACHMENT_TYPE_CHOICES = (
    ('pdf', 'pdf'),
    ('fb2', 'fb2'),
    ('epub', 'epub'),
)

ALLOWED_EXTENSIONS = ['pdf', 'fb2', 'epub']

def attachment_path(instance, filename):
    now = datetime.now()
    return u'recommended_reading/attachments/{0}/{1}/{2}_{3}'.format(now.year, now.month, instance.item_id, filename)

class ItemAttachment(models.Model):
    item = models.ForeignKey(Item)
    type = models.CharField(
        verbose_name=u'Тип файла',
        max_length=16,
        choices=ITEM_ATTACHMENT_TYPE_CHOICES,
        editable=False
    )
    title = models.CharField(
        verbose_name=u'Название',
        max_length=256,
        blank=True,
    )
    file = models.FileField(
        verbose_name=u'Файл',
        upload_to=attachment_path,
        help_text=u'Только файлы с расширение .pdf .fb2 .epub'
    )

    class Meta:
        verbose_name = u'Файл'
        verbose_name_plural = u'Файлы'

    def clean(self):
        cleaned_file = unicode(self.file).lower().strip()

        allowed = False
        for allow_extension in ALLOWED_EXTENSIONS:
            if cleaned_file.endswith('.' + allow_extension):
                allowed = True
                break

        if not allowed:
            raise ValidationError({
                'file': u'Файл имеет недопустимый формат'
            })

        cleaned_file = unicode(self.file).lower().strip()
        for choice in ITEM_ATTACHMENT_TYPE_CHOICES:
            if cleaned_file.endswith('.' + choice[0]):
                self.type = choice[0]
                break

ITEM_ATTRIBUTE_TYPE = (
    ('string', u'Строка'),
    ('number', u'Число'),
)

class ItemAttribute(models.Model):
    code = models.SlugField(
        verbose_name=u'Код',
        max_length=64,
        unique=True,
        help_text=u'Толькл прописные буквы латинского алфавита'
    )

    title = models.CharField(
        verbose_name=u'Название',
        max_length=256,
        help_text=u'Человекочитаемое название атрибута'
    )

    type = models.CharField(
        verbose_name=u'Тип',
        max_length=16,
        choices=ITEM_ATTRIBUTE_TYPE,
        default=ITEM_ATTRIBUTE_TYPE[0][0]
    )

    def clean(self):
        self.code = self.code.lower().strip()
        self.title = self.title.strip()

    class Meta:
        verbose_name = u'Атрибут'
        verbose_name_plural = u'Атрибуты'

class ItemAttributeValue(models.Model):
    item = models.ForeignKey(Item)
    attribute = models.ForeignKey(ItemAttribute, verbose_name=u'Атрибут')
    value = models.CharField(
        verbose_name=u'Значение',
        max_length=1024
    )

    def clean(self):
        self.value = self.value.strip()

    class Meta:
        verbose_name = u'Значение атрибута'
        verbose_name_plural = u'Значения атрибутов'

@receiver(models.signals.post_save, sender=Item)
def compress_item_cover(sender, **kwargs):
    instance = kwargs['instance']
    cover = unicode(instance.cover)
    if not cover:
        return

    image_path = MEDIA_ROOT + unicode(instance.cover)

    im = Image.open(image_path).convert('RGB')
    im = image_utils.image_crop_center(im, crop_height=600, ratio=0.67)
    im.save(image_path, "JPEG", quality=95, optimize=True, progressive=True)


#! python3

# GET DATA FROM GOOGLE SHEETS

import ezsheets
import os
import os.path
import datetime
import pandas as pd

DATE_TODAY = datetime.date.today().strftime('%d/%m/%Y')
DATE_CODE = datetime.date.today().strftime('%Y%m%d')
CSV_NAME = f'weight_data_{DATE_CODE}.csv'

def download_data():
    ss = ezsheets.Spreadsheet('...')
    sheet = ss[0]
    rows = sheet.getRows()
    for i, row in enumerate(rows):
        if row[0] == DATE_TODAY:
            row_today = i + 1
    rows = rows[1:row_today]
    return rows

def clean_data(rows):
    for row in rows:
        # Replace empty values with None
        row[1] = None if row[1] == '' else row[1]
    # print(rows[-4:])
    return rows

def create_csv(weight_data):
    df = pd.DataFrame(weight_data, columns=['date', 'weight'])
    df.to_csv(f'data/{CSV_NAME}', index=False)

def delete_old_data():
    for file in os.listdir('data/'):
        if file != CSV_NAME:
            os.remove(f'data/{file}')
            print(f'File {file} deleted.')

def main():

    # Check if file "weight_data_{DATE_CODE}.csv" exists
    data_exist = os.path.isfile(CSV_NAME)

    # If file doesn't exist, download and clean data from Google Sheets
    if not data_exist:
        print('Downloading data from Google Sheets.')
        raw_data = download_data()
        weight_data = clean_data(raw_data)
        create_csv(weight_data)

    delete_old_data()

if __name__ == '__main__':
    main()


import logging
import os

import torch
from tqdm import tqdm

from ssd.data.datasets.evaluation import evaluate
from ssd.utils.comm import all_gather
from ssd.utils.comm import get_world_size
from ssd.utils.comm import is_main_process
from ssd.utils.comm import synchronize
from ssd.utils.timer import get_time_str
from ssd.utils.timer import Timer

def inference(cfg, model, data_loader, dataset_name, device='cuda', output_dir=None):
    device = torch.device(device)
    num_devices = get_world_size()
    logger = logging.getLogger('ssd.inference')
    dataset = data_loader.dataset
    logger.info(f'Start evaluation on {dataset_name} dataset ({len(dataset)} images)')

    total_timer = Timer()
    inference_timer = Timer()

    total_timer.tic()

    predictions = compute_on_dataset(model, data_loader, device, inference_timer)
    synchronize()
    total_time = total_timer.toc()
    total_time_str = get_time_str(total_time)
    logger.info(
        f"Total run time: {total_time_str} ({total_time * num_devices / len(dataset)} s / img per device, on {num_devices} devices)"
    )
    total_infer_time = get_time_str(inference_timer.total_time)
    logger.info(
        f"Model inference time: {total_infer_time} ({inference_timer.total_time * num_devices / len(dataset)} s / img per device, on {num_devices} devices)"
    )

    predictions = _accumulate_predictions_from_multiple_gpus(predictions)
    if not is_main_process():
        return

    if output_dir:
        torch.save(predictions, os.path.join(output_dir, 'predictions.pth'))

    size = (cfg.INPUT.SIZE, cfg.INPUT.SIZE)
    return evaluate(dataset, predictions, output_dir, size=size)

def compute_on_dataset(model, data_loader, device, timer=None):
    model.eval()
    results_dict = {}
    cpu_device = torch.device('cpu')

    for _, batch in enumerate(tqdm(data_loader)):
        images, targets, labels, image_ids = batch
        with torch.no_grad():
            if timer:
                timer.tic()
            output = model(images.to(device))
            if timer:
                if not device.type == 'cpu':
                    torch.cuda.synchronize()
                timer.toc()
            boxes, labels, scores = list(zip(*output))
            boxes = [boxes_per_image.to(cpu_device) for boxes_per_image in boxes]
            labels = [labels_per_image.to(cpu_device) for labels_per_image in labels]
            scores = [scores_per_image.to(cpu_device) for scores_per_image in scores]

        results_dict.update(
            {img_id: result for img_id, *result in zip(image_ids, boxes, labels, scores)}
        )
    return results_dict

def _accumulate_predictions_from_multiple_gpus(predictions_per_gpu):
    all_predictions = all_gather(predictions_per_gpu)
    if not is_main_process():
        return
    predictions = {}
    for p in all_predictions:
        predictions.update(p)
    image_ids = list(sorted(predictions.keys()))
    if len(image_ids) != image_ids[-1] + 1:
        logger = logging.getLogger("ssd.inference")
        logger.warning(
            "Number of images that were gathered from multiple processes is not "
            "a contiguous set. Some images might be missing from the evaluation"
        )

    predictions = [predictions[i] for i in image_ids]
    return predictions


#!/usr/bin/env python-mr

from collections import defaultdict
from _.data.formatting.blocks import Block

# This is an example implementation that you could build based on the puzzle
# description. It uses memory proportional to fish, and is very slow.
class SlowSwarm:
  @staticmethod
  def from_list(days):
    return SlowSwarm(days)
  def __init__(self, days):
    self._days = days
  def count_fish(self):
    return len(self._days)
  def increment_days(self):
    new = 0
    next_state = []
    for d in self._days:
      if d == 0:
        new += 1
        next_state.append(6)
      else:
        next_state.append(d - 1)
    next_state.extend([8] * new)
    return SlowSwarm(next_state)

# This is the better implementation, because the puzzles turns out not to
# care about the ordering of the fish in the list. By using a dict, there is
# constant memory usage (one entry per day in the fish lifecycle), and
# computing the next state is O(lifecycle days) instead of O(fish).
class LanternFishSwarm:
  @staticmethod
  def from_list(days):
    state = defaultdict(int)
    for d in days:
      state[d] += 1
    return LanternFishSwarm(state)

  def __init__(self, state):
    # Map counting days remaining -> # of fish
    self._days = state

  def __str__(self):
    remaining = []
    for days, count in self._days.items():
      remaining.append(",".join([str(days)] * count))
    return ",".join(remaining)

  def count_fish(self):
    return sum(self._days.values())

  def increment_days(self) -> "LanternFishSwarm":
    next_state = defaultdict(int)
    for i in self._days:
      if i == 0:
        next_state[6] += self._days[i]
        next_state[8] += self._days[i]
      else:
        next_state[i - 1] += self._days[i]

    return LanternFishSwarm(next_state)

LOAD = "content"
def REWRITE(lines):
  state, = lines
  return LanternFishSwarm.from_list([int(i) for i in state.split(",")])
  #return SlowSwarm.from_list([int(i) for i in state.split(",")])

def PART1(inputs):
  #print(inputs)
  swarm = inputs
  for _day in range(80):
    swarm = swarm.increment_days()
    #print(swarm)

  #print("Fish", swarm.count_fish())
  return swarm.count_fish()

def PART2(inputs):
  #print(inputs)
  swarm = inputs
  for _day in range(256):
    swarm = swarm.increment_days()
    #print(swarm)

  #print("Fish", swarm.count_fish())
  return swarm.count_fish()


import random
import torch
import numpy as np
from copy import deepcopy
from src.utils import *
from src.constants import *
from tqdm import tqdm
import torch.nn.functional as F

import matplotlib.pyplot as plt

def scale(data, low):
    return torch.max(torch.tensor(low), torch.min(data, torch.tensor(1)))

def gen(model, data_type, trainloader, num_examples, label, notstart, epsilon=1e-5):
    lr = 0.02
    iteration = 0; equal = 0
    diffs, data, labels = [], [], []
    l, label_vec = torch.nn.CrossEntropyLoss(), torch.LongTensor([label])
    dim = (1,1,28,28) if 'mnist' in data_type else (1, 3, 32, 32)
    for restart in range(num_examples):
        init = torch.rand(dim, dtype=torch.float)
        init = init*2 - 1 if 'mnist' in data_type else init
        if not notstart:
            data.append(init); labels.append(label_vec+N_CLASSES); continue
        init.requires_grad = True
        copyz = 10; optimizer = torch.optim.Adam([init] , lr=lr); zs = []
        scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=50)
        for _ in range(1000):
            copy = deepcopy(init.data)
            res = model(init)
            z = l(res.view(1,-1), label_vec)
            # if iteration % 1000 == 0: plot_image(init.data.view(1,28,28).numpy().squeeze(), iteration)
            optimizer.zero_grad(); z.backward(); optimizer.step(); scheduler.step()
            init.data = scale(init.data, -1 if 'mnist' in data_type else 0)
            equal = equal + 1 if torch.all(abs(copy - init.data) < epsilon) or (0 < copyz - z.item() < epsilon) else 0
            if equal > 30: break
            # print(equal, end=' ')
            copyz = z.item()
            # if iteration % 10 == 0: zs.append(copyz)
            iteration += 1
        # plt.plot(zs); plt.show(); plt.clf()
        init.requires_grad = False
        diffs.append(z.item()); data.append(init); labels.append(label_vec+N_CLASSES)
    return data, labels, diffs


# import matplotlib as mpl
# mpl.use('Agg')
import logging

import pandas as pd

from phdlib.misc import logger_settings
from phdlib.data.api import get_monthly_data, get_crsp_monthly, \
    weighted_corr_mat
from phdlib import settings
from phdlib.output import tex_tables
from phdlib.metrics import linear_models

logger = logging.getLogger(__name__)

def mv_weighted_average(fc_raw_data, output='mean'):
    """ Calculates a market valued weighted average, equally weighted periods

    Parameters
    ----------
    fc_raw_data: pandas.DataFrame
        Containing columns 'PERMNO', 'date' and the desired FC columns
    output: str
        what output format 'mean' (mean over all periods), 'series¨(values
        at each point in time)

    Returns
    -------

    """
    # get market caps
    mkt_cap = monthly.get_crsp_monthly(['mkt_cap'])['mkt_cap']
    mkt_cap = mkt_cap.stack().reset_index().rename(columns={'level0': 'date',
                                                            'level1': 'PERMNO',
                                                            0: 'mkt_cap'})  # merge data together
    fc_raw_data = fc_raw_data.merge(mkt_cap, left_on=['PERMNO', 'date'],
                                    right_on=['PERMNO', 'date'], how='left')
    grouped_date = fc_raw_data.groupby(by='date')

    vw_avg = dict()
    dates = list()

    # initialize each column
    for column in fc_raw_data:
        if column in ['PERMNO', 'index', 'date']:
            continue
        vw_avg[column] = list()
    #
    for date, group in grouped_date:
        logger.info('Current Date: {}'.format(date))
        for column in fc_raw_data:
            if column in ['PERMNO', 'index', 'date']:
                continue
            tmp_data = group['mkt_cap'].where(group[column].isnull() == False)
            weight = tmp_data / tmp_data.sum()
            vw_avg[column].append((weight * group[column]).sum())

        dates.append(date)

    vw_avg = pd.DataFrame(vw_avg, index=dates)

    if output == 'mean':
        return vw_avg.mean()
    elif output == 'series':
        return vw_avg
    else:
        raise NotImplementedError

def first_data_date(fc_raw_data):
    """ Returns the first date where no na_entries are found for fc
    Parameters
    ----------
    fc_raw_data

    Returns
    -------

    """
    min_dates = dict()

    for column in fc_raw_data:
        logger.info('Current Columns: {}'.format(column))
        if column in ['PERMNO', 'index', 'date']:
            continue
        tmp_data = fc_raw_data[['date', column]].dropna()

        min_dates[column] = tmp_data['date'].min().strftime('%Y-%m')

    return pd.Series(min_dates)

def top_ten_correlations(value_weighted=True):
    """ Writes to ten highest and lowest correlation to tables

    Returns
    -------

    """
    size = 'all'
    start_date = '19740630'
    df = get_monthly_data(start_date=start_date, drop_na=True, normalize=True,
                          winsorize_prc=0.05, drop_columns=['ceq', 'mkt_cap'],
                          size=size, fc_lead=0)

    if value_weighted:
        mkt_cap = get_monthly_data(start_date=start_date, size=size, fc_lead=0,
                                   keep_columns=['mkt_cap'], drop_na=True,
                                   normalize=False, columns=['mkt_cap'])

        mkt_cap = mkt_cap.dropna().set_index(['date', 'PERMNO'])
        mkt_cap, _ = mkt_cap.align(df.set_index(['date', 'PERMNO']),
                                   join='right', axis=0)

        weights = linear_models.market_cap_weight(mkt_cap=mkt_cap)['mkt_cap']

    logger.info('Calculating weighted correlations...')

    df.drop(['PERMNO', 'date', 'ret'], axis=1, inplace=True)
    if value_weighted:
        corr = weighted_corr_mat(df, weights=weights)
    else:
        corr = df.corr()

    logger.info(f'Correlation: {corr}')

    corr_st = corr.stack().reset_index()
    corr_st.rename(columns={0: 'corr'}, inplace=True)
    corr_st = corr_st[corr_st['level_0'] != corr_st['level_1']]
    corr_st['pairs'] = corr_st.apply(
        lambda row: row[['level_0', 'level_1']].tolist(), axis=1)
    corr_st['pairs'].map(lambda x: x.sort())
    corr_st['pairs'] = corr_st['pairs'].map(lambda x: ''.join(x))
    corr_st.drop_duplicates(subset='pairs', inplace=True)
    corr_st = corr_st.sort_values(by='corr').reset_index(drop=True)
    corr_st.drop(corr_st[10:-10].index, inplace=True)

    corr_st.rename(columns={'level_1': 'FC_1', 'level_0': 'FC_2'},
                   inplace=True)
    path = str(settings.LASSO_TABLES.joinpath('top_corr_{}.tex'.format(size)))
    desc = 'The table shows the ten highest and ten lowest correlations ' \
           'pairs of FC based on the normalized and pooled data. In case of' \
           ' an absolute correlation > 0.95 between two FC, we exclude the' \
           ' more recently published FC.'

    tex_tables.df_to_latex(
        corr_st[['FC_1', 'FC_2', 'corr']], path, table_description=desc,
        label='top_corr_' + size, centering=True, caption='top_corr_' + size)

def data_summary():
    """ Writes summary of raw data statistics to latex

    Returns
    -------

    """

    # get raw data without normalization and winsorizing
    start = '19650101'
    df = manager.get_monthly_data(start,
                                  normalize=False,
                                  drop_columns=['mkt_cap', 'ceq', 'roic'])
    print(df.columns)
    df_ad = manager.get_monthly_data(start, normalize=False,
                                     columns=['roic'], winsorize_prc=0.025)
    df_ad.drop(['mkt_cap', 'ceq'], axis=1, inplace=True)
    df = df.merge(df_ad, on=['date', 'PERMNO'])
    #
    df.drop(['ceq', 'mkt_cap'], axis=1, inplace=True)
    summary = df.describe(
        percentiles=[0.05, 0.5, 0.95]).transpose().reset_index()
    path = settings.TABLE_PATH.joinpath('summary_raw_fc.tex')
    summary['count'] /= len(df)
    # Calculate vw-weighted mean and add to summary
    vw_avg = pd.DataFrame({'vw_mean': mv_weighted_average(df, output='mean'),
                           'data_start': first_data_date(df)})
    summary = summary.merge(vw_avg, left_on='index',
                            right_index=True).sort_values(by='index')

    desc = 'Data description of raw data before any data adjustments ' \
           '(z-scores, winsorizing etc.) for the period 1965-01-01 to ' \
           '2014-12-31, based on {} obs. Note also, that it is the summary ' \
           'over all periods for each FC. The column vw-mean measures the ' \
           'market value weighted average. For that, we calculate vw averages ' \
           'for each period, which are then used to obtain an equally weighted' \
           ' average over all periods. Data start indicates the date on' \
           ' which the FC was calculated for at least one' \
           ' stock. Note, we display \\textit{{roic}} winsorized at 2.5% to' \
           ' control for data points which are scaled by numbers close to zero' \
           '.'.format(len(df))
    logger.info('Writing data to in file: {}...'.format(str(path)))
    summary.rename(columns={'count': 'coverage', 'index': 'FC'}, inplace=True)
    col_order = ['FC', 'coverage', 'mean', 'vw_mean', 'std', 'min',
                 '5%', '50%', '95%', 'max', 'data_start']
    print(summary.loc[summary.FC == 'roic', col_order])
    tex_tables.df_to_latex(summary[col_order], str(path), table=True,
                           scaling=0.7, table_description=desc,
                           label='raw_data_summary',
                           centering=True, caption='RawDataSummary')

def data_zero_mean_converage():
    df_drop_na = get_monthly_data(start_date='19700101', size='large',
                                  fill_na=False)
    df_fill_na = get_monthly_data(start_date='19700101', size='large',
                                  fill_na=True)

    # calculate coverage ratio
    ratio = df_drop_na.groupby('date').count().div(
        df_fill_na.groupby('date').count())

def data_density(data, group_by='date', ref_col='PERMNO', columns=None):
    grouped = data.groupby(group_by)
    if columns is None:
        density = grouped.count().div(grouped[ref_col].count(), axis=0)
    else:
        density = grouped[columns].count().div(grouped[ref_col].count(),
                                               axis=0)

    return density

def avg_NAs_data(data):
    avg_month = data.isnull().sum() / len(set(data.date.tolist()))

    avg_month.to_latex()

def number_stocks_shrcd():
    """ returns the number of securities in the CRSP database and count of
    stocks used left after filtering data with respect to exchange, shr code
    and missing data of market cap and book value

    Returns
    -------

    """
    start_date = '19650101'

    # load all stocks data
    file = settings.RAW_DATA_PATH.joinpath(settings.FILE_NAMES['CRSP_ID'])
    crsp = pd.read_csv(str(file), engine='c', compression='gzip',
                       low_memory=False, usecols=['date', 'PERMNO', 'SHRCD'])
    crsp['date'] = pd.to_datetime(crsp['date'], format='%Y%m%d')
    crsp = crsp.loc[(crsp.date > start_date) & (crsp.date <= '20141231'), :]
    all = crsp.pivot(index='date', columns='PERMNO', values='SHRCD')
    all.index = all.index.to_period('M').to_timestamp('M')

    # load only stocks which are used
    used_stocks = manager.get_monthly_data(start_date, columns=['SHRCD'])
    used = used_stocks.pivot(index='date', columns='PERMNO', values='ceq')

    total_stocks = all.count(axis=1)
    relevant_stocks = used.count(axis=1)

    stock_count = pd.concat([total_stocks, relevant_stocks, ], axis=1)

    return stock_count['1965-02-01':]

def main():
    logging.config.dictConfig(logger_settings.log_set_ups)
    logger.setLevel('INFO')
    top_ten_correlations()

if __name__ == '__main__':
    data_zero_mean_converage()
    main()
    # pv = number_stocks_shrcd()


import tweepy
from bs4 import BeautifulSoup #pip3 install lxml
import requests
import re

consumer_key = "XXXXXXXXXXXXXXXXXXXXXXX"
consumer_secret = "XXXXXXXXXXXXXXXXXXXXXXX"
access_key = "XXXXXXXXXXXXXXXXXXXXXXX"
access_secret = "XXXXXXXXXXXXXXXXXXXXXXX"

def Tweets(username):

        auth = tweepy.OAuthHandler(consumer_key, consumer_secret)

        auth.set_access_token(access_key, access_secret)

        api = tweepy.API(auth)

        number_of_tweets=10
        tweets = api.user_timeline(screen_name=username, count=number_of_tweets)

        sum=""
        tweets_for_csv = [tweet.text for tweet in tweets] # CSV file created
        for j in tweets_for_csv:

            # sum tweets in a variable to count their words later
            sum=sum+j

        # counting words
        count = len(re.findall(r'\w+', sum))
        print (count)

        #followers count
        temp = requests.get('https://twitter.com/'+username)
        bs = BeautifulSoup(temp.text,'lxml')
        try:
         follow_box = bs.find('li',{'class':'ProfileNav-item ProfileNav-item--followers'})
         followers = follow_box.find('a').find('span',{'class':'ProfileNav-value'})
         followers=int(format(followers.get('data-count')))
         print(followers)
         Tweets.multi=int(followers*count)  #creating number(followers X words)
        except:
         print('Account name not found...')

#first profile
if __name__ == '__main__':
    username=input("Όνομα 1ου χρήστη: ")
    username1=username
    Tweets(username)
    multi1=Tweets.multi

#second profile
if __name__ == '__main__':
    username=input("Όνομα 2ου χρήστη: ")
    Tweets(username)
    username2=username
    multi2=Tweets.multi

#Final result
if multi1>multi2:
    diafora=multi1-multi2
    print("Ο",username1,"έχει το μεγαλύτερο γινόμενο με ",diafora," διαφορά")
elif multi1<multi2:
    diafora=(multi2-multi1)
    print("Ο",username2,"έχει το μεγαλύτερο γινόμενο με ",diafora," διαφορά")
else:
    print("το γινόμενο των followers ΕΠΙ τον αριθμό λέξεων των 10 τελευταίων tweets των δυο χρηστών είναι ίσα")


import sys
sys.stdin = open("03_string_and_list\input.txt", "rt")

N = 10
list = []

for i in range(20):
    list.append(i+1)

for r in range(N):
    a, b = map(int, input().split())

    p = a-1
    q = b-1

    while p < q:
        list[p], list[q] = list[q], list[p]
        p += 1
        q -= 1

for v in list:
    print(v, end=' ')


#!/usr/bin/python3
from pathlib import Path
import datetime
import json
import logging
import os
import urllib
from logging.handlers import RotatingFileHandler

import requests
from bs4 import BeautifulSoup
from dotenv import load_dotenv

DIRECTORY = Path('.')

logger = logging.getLogger('tuenviofinder')
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
fh = RotatingFileHandler(str(DIRECTORY / 'logs' / 'sync.log'), mode='a', maxBytes=5 * 1024 * 1024, backupCount=1)
fh.setFormatter(formatter)
logger.addHandler(fh)

env_path = DIRECTORY / '.env'
load_dotenv(dotenv_path=env_path)

TOKEN = os.getenv('TOKEN')
URL = f'https://api.telegram.org/bot{TOKEN}/'

USER = {

}

PROVINCIAS = {
    'pr': ['Pinar del Río', {'pinar': 'Pinar del Río'}],
    'ar': ['Artemisa', {'artemisa': 'Artemisa'}],
    'my': ['Mayabeque', {'mayabeque-tv': 'Mayabeque'}],
    'mt': ['Matanzas', {'matanzas': 'Matanzas'}],
    'cf': ['Cienfuegos', {'cienfuegos': 'Cienfuegos'}],
    'vc': ['Villa Clara', {'villaclara': 'Villa Clara'}],
    'ss': ['Sancti Spíritus', {'sancti': 'Sancti Spíritus'}],
    'ca': ['Ciego de Ávila', {'ciego': 'Ciego de Ávila'}],
    'cm': ['Camagüey', {'camaguey': 'Camagüey'}],
    'lt': ['Las Tunas', {'tunas': 'Las Tunas'}],
    'hg': ['Holguín', {'holguin': 'Holguín'}],
    'gr': ['Granma', {'granma': 'Granma'}],
    'st': ['Santiago de Cuba', {'santiago': 'Santiago de Cuba'}],
    'gt': ['Guantánamo', {'guantanamo': 'Guantánamo'}],
    'ij': ['La Isla', {'isla': 'La Isla'}],
    'lh': ['La Habana', {'carlos3': 'Carlos Tercero', '4caminos': 'Cuatro Caminos'}]
}

RESULTADOS = {

}

PRODUCTOS = {

}

# Tiempo en segundos que una palabra de búsqueda permanece válida
TTL = 300

session = requests.Session()

def update(offset):
    # Llamar al metodo getUpdates del bot, utilizando un offset
    respuesta = session.get(f'{URL}getUpdates?offset={str(offset)}&timeout={str(100)}')

    # Decodificar la respuesta recibida a formato UTF8
    mensajes_js = respuesta.content.decode('utf8')

    # Convertir y retornar el string de JSON a un diccionario de Python
    return json.loads(mensajes_js)

def info_mensaje(mensaje):
    # Comprobar el tipo de mensaje
    if "text" in mensaje["message"]:
        tipo = "texto"
    elif "sticker" in mensaje["message"]:
        tipo = "sticker"
    elif "animation" in mensaje["message"]:
        tipo = "animacion"  # Nota: los GIF cuentan como animaciones
    elif "photo" in mensaje["message"]:
        tipo = "foto"
    else:
        # Para no hacer mas largo este ejemplo, el resto de tipos entran
        # en la categoria "otro"
        tipo = "otro"

    # Recoger la info del mensaje (remitente, id del chat e id del mensaje)
    persona = mensaje["message"]["from"]["first_name"]
    id_chat = mensaje["message"]["chat"]["id"]
    id_update = mensaje["update_id"]

    # Devolver toda la informacion
    return tipo, id_chat, persona, id_update

def leer_mensaje(mensaje):
    # Extraer el texto, nombre de la persona e id del último mensaje recibido
    texto = mensaje["message"]["text"]

    # Devolver las dos id, el nombre y el texto del mensaje
    return texto

def enviar_mensaje(idchat, texto):
    logger.debug(f'Sending message {idchat} >> {texto}')
    # Llamar el metodo sendMessage del bot, passando el texto y la id del chat
    session.get(f'{URL}sendMessage?text={texto}&chat_id={str(idchat)}&parse_mode=html')

def update_soup(url, mensaje, ahora, tienda):
    respuesta = session.get(url)
    data = respuesta.content.decode('utf8')
    soup = BeautifulSoup(data, 'html.parser')
    if mensaje not in RESULTADOS:
        RESULTADOS[mensaje] = dict()
    RESULTADOS[mensaje][tienda] = {'tiempo': ahora, 'soup': soup}
    return soup

def obtener_soup(mensaje, nombre, idchat):
    # Arreglo con una tupla para cada tienda con sus valores
    result = []
    if idchat in USER:
        # Seleccionar provincia que tiene el usuario en sus ajustes
        prov = USER[idchat]['prov']

        # Se hace el procesamiento para cada tienda en cada provincia
        for tienda in PROVINCIAS[prov][1]:
            url_base = f'https://www.tuenvio.cu/{tienda}'
            url = f'{url_base}/Search.aspx?keywords=%22{mensaje}%22&depPid=0'
            respuesta, data, soup_str = '', '', ''
            ahora = datetime.datetime.now()

            # Si el resultado no se encuentra cacheado buscar y guardar
            if mensaje not in RESULTADOS or tienda not in RESULTADOS[mensaje]:
                debug_print(f'Buscando: "{mensaje}" para {nombre}')
                soup_str = update_soup(url, mensaje, ahora, tienda)
            # Si el resultado está cacheado
            elif tienda in RESULTADOS[mensaje]:
                delta = ahora - RESULTADOS[mensaje][tienda]['tiempo']
                # Si aún es válido se retorna lo que hay en cache
                if delta.total_seconds() <= TTL:
                    debug_print(f'"{mensaje}" aún en cache, no se realiza la búsqueda.')
                    soup_str = RESULTADOS[mensaje][tienda]["soup"]
                # Si no es válido se actualiza la cache
                else:
                    debug_print(f'Actualizando : "{mensaje}" para {nombre}')
                    soup_str = update_soup(url, mensaje, ahora, tienda)
            result.append((soup_str, url_base, tienda))
    return result

def procesar_comando(mensaje, idchat):
    # texto_respuesta, salida = '', ''
    if mensaje.startswith('/start'):
        texto_respuesta = 'Búsqueda de productos en tuenvio.cu. Envíe una o varias palabras y se le responderá la disponibilidad. También puede probar la /ayuda. Suerte!'
        salida = 'ha iniciado chat con el bot.'
    elif mensaje.startswith('/ayuda'):
        texto_respuesta = 'Envíe una palabra para buscar. O puede seleccionar una provincia:\n\n'
        for prov in PROVINCIAS:
            texto_respuesta += f'/{prov}: {PROVINCIAS[prov][0]}\n'
        salida = 'ha solicitado la ayuda.'
    else:
        comando = mensaje.split('/')[1]
        # Vemos si comando es una provincia
        if comando in PROVINCIAS:
            USER[idchat] = {'prov': comando}
            texto_respuesta = f'Ha seleccionado la provincia: {PROVINCIAS[comando][0]}.'
            salida = f'ha cambiado la provincia de búsqueda a {PROVINCIAS[comando][0]}.'
        # Si no entonces comando es un identificador de producto
        elif comando in PRODUCTOS:
            prov = USER[idchat]['prov']
            producto = PRODUCTOS[comando][prov]['producto']
            link = PRODUCTOS[comando][prov]['link']
            texto_respuesta = f'Consultando: {producto}\n\nClick para ver en: {link}'
            salida = f'ha consultado el link del producto {producto}.'
        else:
            texto_respuesta = 'Ha seleccionado incorrectamente el comando de provincia. Por favor, utilice la /ayuda.'
            salida = 'ha utilizado incorrectamente la ayuda.'
    return texto_respuesta, salida

def debug_print(message):
    print(message)
    logger.debug(message)

# Variable para almacenar la ID del ultimo mensaje procesado
ultima_id = 0

while (True):
    try:
        mensajes_diccionario = update(ultima_id)
        for i in mensajes_diccionario['result']:

            # Guardar la informacion del mensaje
            try:
                tipo, idchat, nombre, id_update = info_mensaje(i)
            except (IndexError, Exception):
                tipo, idchat, nombre, id_update = 'delete', '744256293', 'Disnel 56', 1

            answer = False
            # Generar una respuesta dependiendo del tipo de mensaje
            if tipo == "texto":
                mensaje = leer_mensaje(i)
                texto_respuesta = ""
                answer = False
                if mensaje.startswith("/"):
                    texto_respuesta, salida = procesar_comando(mensaje, idchat)
                    debug_print(nombre + " " + salida)
                else:
                    try:
                        for soup, url_base, tienda in obtener_soup(mensaje, nombre, idchat):
                            prov = USER[idchat]['prov']
                            nombre_tienda = PROVINCIAS[prov][1][tienda]
                            thumb_setting = soup.select('div.thumbSetting')
                            texto_respuesta += f'[Resultados en: {nombre_tienda}]\n\n'
                            for child in thumb_setting:
                                answer = True
                                producto = child.select('div.thumbTitle a')[0].contents[0]
                                phref = child.select('div.thumbTitle a')[0]['href']
                                pid = phref.split('&')[0].split('=')[1]
                                plink = f'{url_base}/{phref}'
                                if pid not in PRODUCTOS:
                                    PRODUCTOS[pid] = dict()
                                    PRODUCTOS[pid][prov] = {'producto': producto, 'link': plink}
                                else:
                                    if prov not in PRODUCTOS[pid]:
                                        PRODUCTOS[pid][prov] = {'producto': producto, 'link': plink}
                                precio = child.select('div.thumbPrice span')[0].contents[0]
                                texto_respuesta += producto + ' --> ' + precio + urllib.parse.quote(f' [ver más]') + '\n'
                            texto_respuesta += "\n"
                    except Exception as inst:
                        texto_respuesta = f'Ocurrió la siguiente excepción: {str(inst)}'
            else:
                texto_respuesta = 'Solo se admiten textos.'

            # Si la ID del mensaje es mayor que el ultimo, se guarda la ID + 1
            if id_update > (ultima_id - 1):
                ultima_id = id_update + 1

            # Enviar la respuesta
            respuestas_posibles = ['Búsqueda', 'Ha seleccionado', 'Consultando', 'Envíe']
            hay_resp_posible = False
            for rp in respuestas_posibles:
                if texto_respuesta.startswith(rp):
                    hay_resp_posible = True
                    break

            if texto_respuesta:
                if texto_respuesta.startswith('Ocurrió'):
                    enviar_mensaje('744256293', texto_respuesta)
                    debug_print('error')
                elif hay_resp_posible:
                    enviar_mensaje(idchat, texto_respuesta)
                    debug_print('Busqueda o seleccion de provincia o consulta de producto')
                else:
                    if answer:
                        texto_respuesta = f'🎉🎉🎉¡¡¡Encontrado!!! 🎉🎉🎉\n\n{texto_respuesta}'
                        enviar_mensaje(idchat, texto_respuesta)
                        debug_print(texto_respuesta)
                    else:
                        enviar_mensaje(idchat, 'No hay productos que contengan la palabra buscada ... 😭')
                        debug_print('no hubo respuesta')
                        debug_print(texto_respuesta)
            else:
                enviar_mensaje(idchat, 'No hay productos que contengan la palabra buscada ... 😭')
                debug_print('mensaje vacio')

        # Vaciar el diccionario
        mensajes_diccionario = []
    except Exception as ex:
        logger.error(f'Unhandled error >> {ex}')


import dash
import dash_html_components as html
import dash_core_components as dcc

app = dash.Dash()

app.layout = html.Div([

                    html.P(''),
                    html.Label('Dropdown'),
                    dcc.Dropdown(options =[{'label': 'NewDelhi', 'value': 'DEL'},
                                            {'label': 'Mumbai', 'value': 'MUM'}],
                                            value = 'DEL'),
                    html.P(''),
                    html.Label('Slider'),
                    dcc.Slider(min = -10, max = 10, step = 0.5, value = 0,
                                marks = {i: i for i in range(-10, 10, 1)})

])

if __name__ == '__main__':
    app.run_server()


notas=[]

#Inputs
nome=input('Digite o nome do aluno: ')
idade=int(input('Digite a Idade do aluno:'))
provas=int(input('Digite quantas provas o aluno fez:'))
while provas<=2:
    provas=int(input('Não entendi, digite a quantidade de provas novamente: '))

for i in range(provas):
    nota=float(input(f'Digite a {i+1}ª nota do aluno:'))
    while (nota<0 or nota>10):
        nota= float(input(f'Não entendi, digite a {i+1}ª nota do aluno novamente: '))
    notas.append(nota)
notas2=sorted(notas)
notas2.pop(0)
notas2.pop(-1)
#Calcula a média
media=sum(notas2)/len(notas2)
media>5

print([nome,idade,notas,float(f'{media:.2}'),media>5])


#!/usr/bin/python

# This script is meant to demo the VPRO robot conversation
# It is very basic and starts a prompt in which a user can type some text
# This text is enriched with semantic information after which a suitable response or
# set of responses is returned

# Author: Marieke.van.Erp@vu.nl
# Date: 9 December 2016

import spacy
import json
import sys
import os
import readability

# A small warning that it may take a while for the data to load
print('------------\nLoading the language model, this may take a while\n\n-------------\n')

# Make sure the spacy module is loaded (this may take a while)
nlp = spacy.load('en')

def annotate(text):
	doc = nlp(text)
	entities = {}
	for i in doc:
		if len(i.ent_type_) > 0:
			entities[i.text] = i.ent_type_
			print(i.text, i.ent_type_)

def getcmd(cmdlist):
	cmd = input('\nP3PP3R:> ')
	annotate(cmd)

def start():
	print('\n-------')
	cmd = getcmd(input)
	start()

def structure_processor(text):
    result = readability.getmeasures(text)
    return result

if __name__ == "__main__":
    start()


from os import kill, system
from redis import StrictRedis, WatchError
from multiprocessing import Process
from Queue import Empty
from msgpack import packb
from time import time, sleep
from ring import RedisRing
import zmq

import logging
import settings

logger = logging.getLogger("HorizonLog")

class Worker(Process):
    """
    The worker processes chunks from the queue and appends
    the latest datapoints to their respective timesteps in Redis.
    """
    def __init__(self, parent_pid, context, canary=False):
        super(Worker, self).__init__()
        self.context = context
        self.ring = RedisRing(settings.REDIS_BACKENDS)
        self.parent_pid = parent_pid
        self.daemon = True
        self.canary = canary

    def check_if_parent_is_alive(self):
        """
        Self explanatory.
        """
        try:
            kill(self.parent_pid, 0)
        except:
            exit(0)

    def in_skip_list(self, metric_name):
        """
        Check if the metric is in SKIP_LIST.
        """
        for to_skip in settings.SKIP_LIST:
            if to_skip in metric_name:
                return True

        return False

    def run(self):
        """
        Called when the process intializes.
        """
        logger.info('started worker')

        FULL_NAMESPACE = settings.FULL_NAMESPACE
        MINI_NAMESPACE = settings.MINI_NAMESPACE
        MAX_RESOLUTION = settings.MAX_RESOLUTION

        self.conn = self.context.socket(zmq.PULL)
        self.conn.connect(
            '{0}:{0}'.format(settings.RELAY_HOST, settings.RELAY_PUBLISH_PORT))
        self.poller = zmq.Poller()
        self.poller.register(self.conn, zmq.POLLIN)

        while 1:
            sockets = dict(self.poller.poll())
            if self.conn in sockets and sockets[self.conn] == zmq.POLLIN:
            # Make sure Redis is up
                try:
                    self.ring.check_connections()
                except:
                    sleep(10)
                    self.ring = RedisRing(settings.REDIS_BACKENDS)
                    continue

                try:
                    # Get a chunk from the queue with a 15 second timeout
                    chunk = self.q.get(True, 15)
                    now = time()

                    for metric in chunk:

                        # Check if we should skip it
                        if self.in_skip_list(metric[0]):
                            continue

                        # Bad data coming in
                        if metric[1][0] < now - MAX_RESOLUTION:
                            continue

                        for ns in [FULL_NAMESPACE, MINI_NAMESPACE]:
                            key = ''.join((ns, metric[0]))
                            self.ring.run('append', key, packb(metric[1]))
                            ukey = ''.join((ns,'unique_metrics.',metric[0]))
                            self.ring.run('sadd', ukey, key)

                except Exception as e:
                    logger.error("worker error: " + str(e))


import os

def CreateStrProj():
  print("Give a name of project: ")
  inNameProj = input()
  try:
    if not os.path.exists('./' + inNameProj + '/'):
      os.makedirs(inNameProj)
    os.chdir(inNameProj)
    # Create folders
    os.makedirs('_poject')
    os.makedirs('_documentation')
    os.makedirs('_cs_structs')
    os.makedirs('_uml_structs')
    os.makedirs('_addons_soft')
    os.makedirs('_other')
  except OSError:
    print('Error: Creating folders of project. ' + inNameProj)

if __name__ == '__main__':
  CreateStrProj()

#walk in the directory, for future
#*********************************
#from_dir = input()  # get dir
#print("***************************************")
#for crtgs in os.walk(from_dir):  # Generate a cortages
#  print (crtgs)                  # and print whole
#print("***************************************")


# Copyright 2017 BrainPad Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================

from __future__ import absolute_import, division, print_function, unicode_literals

import argparse
import os
import logging
import json
import sys
import tensorflow as tf
import threading
import multiprocessing
import time
import random
import math
import numpy as np
from itertools import islice

INPUT_DATA_TENSOR_NAME = 'DecodeJpeg:0'
FEATURE_TENSOR_NAME = 'pool_3/_reshape:0'

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s %(name)-7s %(levelname)-7s %(message)s'
)
logger = logging.getLogger(__name__)

# Mute logging of warnings to avoid spam with deprecated use of .op_scope
tf.logging.set_verbosity(tf.logging.ERROR)

class FeatureExtractor(object):
    """
    FeatureExtractor extracts 2048-dimension feature vectors from image files
    using inception-v3.
    """

    def __init__(self, model_file):
        # load inception-v3 model
        self.graph = tf.Graph()
        with tf.gfile.FastGFile(model_file, 'rb') as f:
            graph_def = tf.GraphDef()
            graph_def.ParseFromString(f.read())
            with self.graph.as_default():
                _ = tf.import_graph_def(graph_def, name='')

            feature = tf.reshape(self.graph.get_tensor_by_name(FEATURE_TENSOR_NAME), [-1])
        self.feature_op = feature

        self.saver = None

    @classmethod
    def from_model_dir(cls, model_dir):
        return cls(os.path.join(model_dir, 'classify_image_graph_def.pb'))

    def get_feature_vector(self, img_bgr):
        with tf.Session(graph=self.graph) as sess:
            feature_data = sess.run(
                self.feature_op,
                {INPUT_DATA_TENSOR_NAME: img_bgr}
            )
        return feature_data.reshape(-1, feature_data.shape[0])

    def get_feature_vectors_from_files(self, image_paths, turn=0, gamma_min=1, gamma_max=1):

        # Decode image
        with self.graph.as_default():
            image = tf.image.decode_jpeg(tf.read_file(image_paths[0]))

        # Extract features
        features = []
        with tf.Session(graph=self.graph) as sess:
            if turn > 0:
                rotate = tf.image.rot90(image, k=turn)
                image = sess.run(rotate)
                image = tf.convert_to_tensor(image)

            if gamma_min != 1 or gamma_max != 1:
                image = tf.image.convert_image_dtype(image, tf.float32)
                gamma = tf.image.adjust_gamma(image, gamma=random.uniform(gamma_min, gamma_min))
                image = sess.run(gamma)

                image = tf.convert_to_tensor(image)

            for path in image_paths:
                image_data = sess.run(
                    image
                )
                feature_data = sess.run(
                    self.feature_op,
                    {INPUT_DATA_TENSOR_NAME: image_data}
                )
                features.append(feature_data)
        return features

class ImagePathGeneratorForTraining(object):
    def __init__(self, image_dir, extension='jpg'):
        self.image_dir = image_dir
        self.extension = extension

    def get_labels(self):
        return sorted(
            [sub_dir for sub_dir in tf.gfile.ListDirectory(self.image_dir)
             if tf.gfile.IsDirectory('/'.join((self.image_dir, sub_dir)))
             ]
        )

    def __iter__(self):
        for label_id, label in enumerate(self.get_labels()):
            dir_path = os.path.join(self.image_dir, label)
            paths = tf.gfile.Glob('{}/*.{}'.format(dir_path, self.extension))
            for path in paths:
                yield path, label_id
        raise StopIteration()

class ImagePathGeneratorForPrediction(object):
    def __init__(self, image_dir, extension='jpg'):
        self.image_dir = image_dir
        self.extension = extension

    def __iter__(self):
        paths = tf.gfile.Glob('{}/*.{}'.format(self.image_dir, self.extension))
        for path in paths:
            yield path, None
        raise StopIteration()

def write_labels(labels, labels_data_path):
    with tf.gfile.FastGFile(labels_data_path, 'w') as f:
        f.write(json.dumps(labels))

def main():
    args = _parse_arguments()

    labels_file = os.path.join(args.output_dir, 'labels.json')
    features_file_train = os.path.join(args.output_dir, 'features.json')
    features_file_test = os.path.join(args.output_dir, 'testfeatures.json')

    _ensure_dir_exists(args.output_dir)

    path_gen_train, path_gen_test = _get_path_generators(args)

    logger.info("Writing label file: {}".format(labels_file))
    write_labels(path_gen_train.get_labels(), labels_file)

    _run_multiprocess_extraction(args, path_gen_train, "train-output-", features_file_train)

    if args.active_test_mode:
        _run_multiprocess_extraction(args, path_gen_test, "test-output-", features_file_test)

    logger.info("Process completed successfully")

def _ensure_dir_exists(directory):
    if not tf.gfile.Exists(directory):
        tf.gfile.MakeDirs(directory)

def _get_path_generators(args):
    path_gen_train, path_gen_test = None, None

    if args.for_prediction:
        path_gen_train = ImagePathGeneratorForPrediction(args.image_dir_train)
        if args.active_test_mode:
            path_gen_test = ImagePathGeneratorForPrediction(args.image_dir_test)

    else:
        path_gen_train = ImagePathGeneratorForTraining(args.image_dir_train)
        if args.active_test_mode:
            path_gen_test = ImagePathGeneratorForTraining(args.image_dir_test)

    return path_gen_train, path_gen_test

def _run_multiprocess_extraction(args, path_generator, temp_files_prefix, output_feature_file):
    num_of_files = len(list(path_generator))

    progress_queue = multiprocessing.Queue()
    progress_printer = threading.Thread(target=ProgressPrinter, args=(progress_queue, num_of_files))
    progress_printer.start()

    image_chunks = generate_image_chunks(path_generator, args.processes)

    test_processes = [multiprocessing.Process(target=ExtractionProcess,
                                              args=(args, image_chunks[i], temp_files_prefix, i, progress_queue))
                      for i in range(args.processes)]

    _start_and_join_processes(test_processes)

    progress_queue.put(("CLOSE", 0))
    progress_printer.join()

    _merge_files(output_feature_file, args.output_dir, temp_files_prefix)

def _merge_files(output_file, output_dir, prefix):
    logger.info("Merging files prefixed with {} into file {}".format(prefix, output_file))
    with tf.gfile.FastGFile(output_file, 'w') as f:
        for _, _, filenames in os.walk(output_dir):
            for filename in filenames:
                if filename.startswith(prefix):
                    path = os.path.join(output_dir, filename)
                    with tf.gfile.FastGFile(path, 'r') as g:
                        f.write(g.read())
                    os.remove(path)

def _start_and_join_processes(processes):
    logger.info("Starting {} processes and waiting for completion".format(len(processes)))
    for t in processes:
        t.start()

    for t in processes:
        t.join()

# -------------------------------------------------
#
#
#               PROCESS
#
#
# -------------------------------------------------
def generate_image_chunks(generator, split_into):
    all_files = list(generator)
    number_of_files = len(all_files)
    chunk_size = math.ceil(number_of_files / float(split_into))

    chunks = []
    for start_index in range(0, number_of_files, chunk_size):
            chunks.append(all_files[start_index: start_index + chunk_size])

    return chunks

class FeaturesDataWriterProcess(object):
    """
    FeatureDataWriter extracts feature data from images and write to json lines
    """

    def __init__(self, image_list, feature_extractor, progress_queue):
        self.image_list = image_list
        self.extractor = feature_extractor
        self.progress_queue = progress_queue

    def write_features(self, features_data_path, rotations):
        with tf.gfile.FastGFile(features_data_path, 'w') as f:
            for index, (path, label_id) in enumerate(self.image_list):
                for i in range(rotations + 1):
                    for gamma_min, gamma_max in [(0.9, 1), (0.5, 0.9), (1, 1.3)]:
                        line = self.extract_data_for_path(path, label_id, i, gamma_min, gamma_max)
                        f.write(json.dumps(line) + '\n')

                if (index + 1) % 20 == 0:
                    self.progress_queue.put(("PROGRESS", 20))

    def extract_data_for_path(self, image_path, label_id, turn, gamma_min, gamma_max):
        vector = self.extractor.get_feature_vectors_from_files([image_path], turn, gamma_min, gamma_max)
        line = {
            'image_uri': image_path,
            'feature_vector': vector[0].tolist()
        }
        if label_id is not None:
            line['label_id'] = label_id
        return line

def ExtractionProcess(args, image_list, output_prefix, index, progress_queue):
    print("Extraction process " + str(index) + " started")

    extractor = FeatureExtractor(args.model_file)
    writer_train = FeaturesDataWriterProcess(image_list, extractor, progress_queue)

    output_file = os.path.join(args.output_dir, output_prefix + str(index) + '.json')

    writer_train.write_features(output_file, args.rotations)

def ProgressPrinter(progress_queue, total):
    start_time = time.time()
    completed = 0

    while True:
        message_type, data = progress_queue.get()
        if message_type == "CLOSE":
            return
        elif message_type == "PROGRESS":
            completed += data

        time_per_image = (time.time() - start_time) / completed
        time_left = (time_per_image * (total - completed)) / 60
        percent_complete = (completed / total) * 100
        sys.stdout.write("\rProcessing image {}/{} (Not counting rotations) - {:.1f}% "
                         "- Estimated time left: {:.0f} minutes"
                         .format(completed, total, percent_complete, math.ceil(time_left)))
        sys.stdout.flush()

def _parse_arguments():
    parser = argparse.ArgumentParser(description='Run feature extraction')
    parser.add_argument(
        '--output_dir',
        default='output',
        nargs=1,
        type=str
    )
    parser.add_argument(
        '--image_dir_train',
        default='../image/train',
        type=str
    )
    parser.add_argument(
        '--active_test_mode',
        default=False,
        action='store_true',
        help='Use this flag to enable generating test features'
    )
    parser.add_argument(
        '--image_dir_test',
        default='../image/test',
        type=str
    )
    parser.add_argument(
        '--model_file',
        type=str,
        default='classify_image_graph_def.pb'
    )
    parser.add_argument(
        '--for_prediction',
        action='store_true'
    )
    parser.add_argument(
        '--processes',
        default=1,
        type=int,
        help="The number of processes to use for the extraction. More processes might help speeding up the "
             "extraction process. Rule of thumb might be to use approx one process per 4 logical cores"
    )
    parser.add_argument(
        '--rotations',
        default=0,
        type=int,
        help="Number of 90deg rotations of the training image to use. 0 will only use the image as is, "
             "while 1 will use the image as is as well as rotating the image 1 time, doubling the number"
             "of extracted features")

    return parser.parse_args()

if __name__ == "__main__":
    main()


import pygame
import invader
import tower
import path
import bullet

def main():
	pygame.init()
	screen = pygame.display.set_mode((600,600))
	pygame.display.set_caption("Tower Defense")

	#Invader
	print("Testing one Invader----------------------")
	test_invader = invader.Invader("slime.png",(0,100)) #Creates object

	#############################################
	print("Positioning test for Invader----------------")
	#############################################
	print("Standard LEFT test for Invader----------------")
	test_invader.move("right")
	assert test_invader.rect == (30,100,20,20)

	print("Zero Input LEFT test for Invader----------------")
	test_invader.move("up")
	assert test_invader.rect == (30,70,20,20)

	print("Standard UP test for Invader----------------")
	test_invader.move("down")
	assert test_invader.rect == (30,100,20,20)

	print("Zero Input UP test for Invader----------------")
	test_invader.move("left")
	assert test_invader.rect == (0,100,20,20)

	#############################################
	print("Direction test for Invader----------------")
	#############################################
	print("Standard First Path")
	direction = test_invader.getDirection(path.Path())
	assert direction == "right"

	#Tower
	print("Testing one Tower ----------------------")
	test_tower = tower.Tower((0,0)) #Creates object

	############################################
	print("Testing positioning of tower icon ----------------------")
	#############################################
	print("Following x change----------")
	test_tower.followmouse((2,0))
	assert test_tower.rect == (2,0,50,50)

	print("Following y change----------")
	test_tower.followmouse((0,5))
	assert test_tower.rect == (2,5,50,50)

	print("Following both x and y change---------")
	test_tower.followmouse((3,5))
	assert test_tower.rect == (5,10,50,50)

	############################################
	print("Invader in Range ----------------------")
	#############################################
	print("Invader in Range---------")
	range = test_tower.inRange(4,8)
	assert range == True

	print("Invader NOT in Range---------")
	notrange = test_tower.inRange(500,200)
	assert notrange == False

	#Path
	print("Testing Path --------------------------")
	test_path = path.Path() #Creates object

	############################################
	print("Getting Path ----------------------")
	#############################################
	print("Coordinates of First Path-------")
	coordinates = test_path.getPathXY(1)
	assert coordinates == (0,50)

	print("Coordinates of First Path-------")
	pathnum = test_path.getNextPath(test_invader)
	assert pathnum == 2

main()


from time import sleep

# 生产
from myutils import coroutine

def countdown_gen(n, consumer):
    # 预先激活，为了让代码来到yield这一句
    # next(consumer)
    while n > 0:
        consumer.send(n)
        n -= 1

# 消费
@coroutine
def countdown_con():
    while True:
        n = yield  # 我要拿到一个,消费一个，并且赋值给n

        print('Countdown:', n)
        sleep(1)

def main():
    consumer = countdown_con()
    countdown_gen(4, consumer)  # 消费者传入生产者里，来消费生产的东西。相互配合，微线程。

if __name__ == '__main__':
    main()