import gym
import copy
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
class JapanMaze(object):
    def __init__(self,radius=0.5,seed=0):
        np.random.seed(seed=seed)
        self.action_limit = 0.1
        self.ini_posi = np.array([-0.9,-0.9])
        self.ini_cov = np.array([[0.005,0.],[0.,0.005]])
        self.whereami = copy.deepcopy(self.ini_posi)
        self.goal = np.array([0.9,0.9])
        self.reward_f = lambda y:np.exp(-(np.linalg.norm(y-self.goal)**2)/2)
        self.center = np.array([0.0,0.0])
        self.radius = radius
        self.timelimit =40
        self.N = 30 # Collision determination　resolution
        high = np.ones(2)*1
        self.observation_space = gym.spaces.Box(low=-np.ones(2)*1, high=np.ones(2)*1,dtype=np.float32)
        self.action_space = gym.spaces.Box(low=-np.ones(2)*0.1, high=np.ones(2)*0.1,dtype=np.float32)

    def reset(self):
        self.timestep = 0
        self.whereami = np.random.multivariate_normal(self.ini_posi, self.ini_cov)
        return self.whereami

    def isvalid(self,wai):
        return np.linalg.norm(self.center-wai) >= 0.5

    def step_near_circle(self,ac):
        wai = copy.deepcopy(self.whereami)
        for i in range(1,self.N+1):
            ratio = i/self.N
            n_wai = self.whereami+ac*ratio
            if not self.isvalid(n_wai): # 丸の中入ったら，一個前を返す
                return wai
            else:
                wai = copy.deepcopy(n_wai)
        return wai

    def step(self,ac):
        self.timestep +=1
        ac = copy.deepcopy(np.array([max(-self.action_limit,min(ac[0],self.action_limit)),
                           max(-self.action_limit,min(ac[1],self.action_limit))]))
        ac += np.random.normal(0.0, 0.005, 2)
        nwai = self.whereami+ ac
        nwai[0] = min(max(-1.,nwai[0]),1.)
        nwai[1] = min(max(-1.,nwai[1]),1.)
        if nwai[0] < 0.5 and nwai[0] > -0.5 and nwai[1] < 0.5 and nwai[1] > -0.5:
            self.whereami = self.step_near_circle(ac)
        else:
            self.whereami = nwai
        rew = self.reward_f(self.whereami)
        return self.whereami, rew, self.timestep>=self.timelimit,{}

    def render(self):
        fig = plt.figure(figsize=(5,5))
        ax = plt.axes()
        ax.plot([-1,-1,1,1,-1],[-1,1,1,-1,-1],c='black')
        c = patches.Circle(xy=(self.center[0], self.center[1]), radius=self.radius, fc='r', ec='r')
        ax.add_patch(c)
        ax.scatter(self.whereami[0],self.whereami[1],c='black')
        ax.scatter(self.goal[0],self.goal[1],marker='x',c='black')

    def calc_sum_rews(self,X):
        return sum([self.reward_f(x[:2]) for x in X])

    def vis_gpr(self,pilco,save_name=False):
        posi = [[-0.7,-0.7],[0.7,-0.7],[-0.7,0.7],[0.7,0.7]]
        th = lambda t:[np.cos(t)*0.1,np.sin(t)*0.1]
        vec = [th(np.pi/2),th(np.pi/2 + 2/3*np.pi),th(np.pi/2 + 4/3*np.pi)]
        posi_vec = np.array([p+v for p in posi for v in vec])
        xmean,xvar = pilco.mgpr.models[0].predict_y(posi_vec)
        ymean,yvar = pilco.mgpr.models[1].predict_y(posi_vec)
        means = np.hstack((xmean,ymean))
        std = np.sqrt(np.hstack((xvar,yvar)))
        # get ready lets draw!
        fig = plt.figure(figsize=(10,10))
        ax = plt.axes()
        ax.plot([-1,-1,1,1,-1],[-1,1,1,-1,-1],c='black')
        c = patches.Circle(xy=(self.center[0], self.center[1]), radius=self.radius, fc='r', ec='r')
        ax.add_patch(c)
        for i in range(len(ymean)):
            ax.arrow(x=posi_vec[i][0],y=posi_vec[i][1],dx=posi_vec[i][2],dy=posi_vec[i][3],
                 width=0.001,head_width=0.01,
                 head_length=0.01,
                 length_includes_head=True,color='k')
            errorx = means[i][0]+posi_vec[i][:2][0]-(posi_vec[i][0]+posi_vec[i][2])
            errory = means[i][1]+posi_vec[i][:2][1]-(posi_vec[i][1]+posi_vec[i][3])
            ax.arrow(x=posi_vec[i][0]+posi_vec[i][2],y=posi_vec[i][1]+posi_vec[i][3],
                     dx=errorx,dy=errory,width=0.001,head_width=0.01,head_length=0.01,
                     length_includes_head=True,color='red')
            e2 = patches.Ellipse(xy = means[i]+posi_vec[i][:2], width = std[i][0], height = std[i][1],
                 alpha = 1.0, ec = "red", fill=False)
            ax.add_patch(e2)
        if save_name:
            plt.title(save_name)
            plt.savefig(save_name,format = 'png', dpi=200)
            plt.close()

    def vis_policy(self,pilco,save_name=False,ppo=False):
        if ppo:
            import torch
            pol = lambda x: pilco.deterministic_ac_real(torch.tensor(x, dtype=torch.float))[1].detach().numpy() [0]
        else:
            pol = lambda x:pilco.compute_action(x[None, :])[0, :]
        centers = [np.array([i/10-1,j/10-1]) for i in range(0,21) for j in range(0,21)]
        vecs = [pol(c) for c in centers]
        fig = plt.figure(figsize=(10,10))
        ax = plt.axes()
        ax.plot([-1,-1,1,1,-1],[-1,1,1,-1,-1],c='black')
        c = patches.Circle(xy=(self.center[0], self.center[1]), radius=self.radius, fc='r', ec='r')
        ax.add_patch(c)
        for cent,v in zip(centers,vecs):
            ax.arrow(x=cent[0],y=cent[1],dx=v[0],dy=v[1],
                 width=0.002,head_width=0.03,
                 head_length=0.02,
                 length_includes_head=False,color='k')
        ax.scatter(self.goal[0],self.goal[1],marker='x',c='black')
        if save_name:
            plt.title(save_name)
            plt.savefig(save_name,format = 'png', dpi=200)
            plt.close()

    def vis_reward(self):
        fig, ax = plt.subplots(1, 2, figsize=(13, 5))
        # colormap
        rew = [self.reward_f([i/100-1,j/100-1]) for i in range(200) for j in range(200)]
        x = np.array([[i/100-1,j/100-1] for i in range(200) for j in range(200)])
        c = patches.Circle(xy=(self.center[0], self.center[1]), radius=self.radius, fc='r', ec='r')
        ax[1].add_patch(c)
        ax[1].plot([-1,-1,1,1,-1],[-1,1,1,-1,-1],c='black')
        ax[1].plot([-1,1],[-1,1], ':',c='black', alpha=0.7)
        im = ax[1].scatter(x[:,0],x[:,1],c=rew)
        ax[1].scatter(self.goal[0],self.goal[1],marker='x',c='black')
        fig.colorbar(im)
        # Cross section
        rews = [self.reward_f([i/100-1,i/100-1]) for i in range(200)]
        ax[0].plot([j/100-1 for j in range(200)],rews, ':', c='black')
        ax[0].set_xlabel('x=y=')
        ax[0].set_ylabel('reward')
        # ax[0].vlines([self.goal[0]], min(rews), max(rews), "black", linestyles='dashed')
        ax[0].scatter(self.goal[0],max(rews),marker='x',c='black')

    def vis_kernel2d(self):
        other=np.array([0.9,0.9, 0.1, 0.0])
        import gpflow
        base_vec = np.array([0.1,0.])
        fig, ax = plt.subplots(1, 3, figsize=(20, 5))
        k = gpflow.kernels.RBF(input_dim=4, variance=1., ARD=True)
        calk = lambda xy,vec:(k.compute_K(np.array([[xy[0],xy[1], vec[0], vec[1]]]),
                      other.reshape(1,4))[0][0])
        x = np.array([[i/50-1,j/50-1] for i in range(100) for j in range(100)])
        k_val = np.array([calk([i/50-1,j/50-1],base_vec) for i in range(100) for j in range(100)])
        c = patches.Circle(xy=(self.center[0], self.center[1]), radius=self.radius, fc='r', ec='r')
        ax[2].add_patch(c)
        ax[2].plot([-1,-1,1,1,-1],[-1,1,1,-1,-1],c='black')
        ax[2].plot([-1,1],[-1,1], ':',c='black', alpha=0.7)
        im = ax[2].scatter(x[:,0],x[:,1],c=k_val)
        ax[2].arrow(x=other[0],y=other[1],dx=other[2],dy=other[3],
                         width=0.002,head_width=0.05,
                         head_length=0.02,
                         length_includes_head=True,color='black')
        fig.colorbar(im)
        k_val0 = np.array([calk([i/100-1,i/100-1],
                0.1*np.array([np.cos(0),np.sin(0)])) for i in range(200)])

        # Cross section
        for i in range(7):
            deg = i*30
            rad = np.deg2rad(i*10)
            k_val = np.array([calk([i/100-1,i/100-1],
                    0.1*np.array([np.cos(rad),np.sin(rad)])) for i in range(200)])
            if i:
                ax[0].plot([j/100-1 for j in range(200)],
                           k_val,
                           label='diff='+str(deg)+'[deg]')

                ax[1].plot([j/100-1 for j in range(200)],
                           k_val-k_val0,
                           label='diff='+str(deg)+'[deg]')
            else:
                ax[0].plot([j/100-1 for j in range(200)],
                           k_val,  ':',
                           label='diff(base)='+str(deg)+'[deg]',
                           c='black')
                ax[1].plot([j/100-1 for j in range(200)],
                           k_val-k_val0,  ':',
                           label='diff(base)='+str(deg)+'[deg]',
                           c='black')
        ax[0].set_xlabel('x=y=')
        ax[1].set_xlabel('x=y=')
        ax[0].set_ylabel('k(x,x*_angle)')
        ax[1].set_ylabel('k(x,x*_angle)-k(x,x*_0)')
        ax[0].arrow(x=other[1], y=1.0, dx=other[2],dy=other[3],
                         width=0.002,head_width=0.05,
                         head_length=0.02,
                         length_includes_head=True,color='black')
        ax[0].legend()
        ax[1].legend()

    def vis_kernel(self,other=np.array([0.9,0.9, 0.1, 0.0]),vec=np.array([0.1,0.])):
        from mpl_toolkits.mplot3d import Axes3D
        import matplotlib.pyplot as plt
        import mpl_toolkits.mplot3d.art3d as art3d
        from mpl_toolkits.mplot3d import Axes3D
        import matplotlib.pyplot as plt
        import mpl_toolkits.mplot3d.art3d as art3d
        import numpy as np
        import gpflow
        def func1(x, y,k,other):
            ar = []
            for xx, yy in zip(x,y):
                arr = []
                for xxx, yyy in zip(xx,yy):
                    arr.append(k.compute_K(np.array([[xxx,yyy, vec[0], vec[1]]]),
                               np.zeros((1,4)) + other.reshape(1,4))[0][0])
                ar.append(arr)
            return np.array(ar)

        k = gpflow.kernels.RBF(input_dim=4, variance=1., ARD=True)
        x = np.arange(-1.0, 1.0, 0.1)
        y = np.arange(-1.0, 1.0, 0.1)
        X, Y = np.meshgrid(x, y)
        Z = func1(X, Y,k,other)
        fig = plt.figure(figsize=(10,10))
        ax = Axes3D(fig)
        ax.set_xlabel("x")
        ax.set_ylabel("y")
        ax.set_zlabel("k(x, x*)")
        name = 'vec1:green('+str(other[2])+','+str(other[3])+') vs vec2:blue('+str(vec[0])+','+str(vec[1])+')'
        ax.set_title(name)
        ax.plot_surface(X, Y, Z)
        # ax.scatter([other[0]],[other[1]],[0.],marker = 'o',color='green',s=100)
        ax.plot([-1.,-1.,1.,1.,-1.],[-1.,1.,1.,-1.,-1.],[0.,0.,0.,0.,0.],c='black')
        c = patches.Circle(xy=(self.center[0], self.center[1]), radius=self.radius, fc='r', ec='r')
        ax.add_patch(c)
        ax.view_init(30, 40)
        art3d.pathpatch_2d_to_3d(c, z=0, zdir="z")
        ax.quiver(other[0], other[1], 0.0 , vec[0], vec[1], 0.0, color='green')
        ax.invert_xaxis()
        ax.set_zlim(-0.01,1.01)
        plt.show()

    def vis_trace(self,X,Y,save_name=False):
        fig = plt.figure(figsize=(5,5))
        ax = plt.axes()
        ax.plot([-1,-1,1,1,-1],[-1,1,1,-1,-1],c='black')
        c = patches.Circle(xy=(self.center[0], self.center[1]), radius=self.radius, fc='r', ec='r')
        ax.add_patch(c)
        for x,y in zip(X,Y):
            if  y[0] == 0 and y[1] == 0:
                ax.scatter(x[0],x[1],c='black',s=5)
            else:
                ax.arrow(x=x[0],y=x[1],dx=y[0],dy=y[1],
                         width=0.002,head_width=0.05,
                         head_length=0.02,
                         length_includes_head=True,color='k')
        ax.scatter(self.goal[0],self.goal[1],marker='x',c='black')
        if save_name:
            plt.title(save_name)
            plt.savefig(save_name,format = 'png', dpi=200)
            plt.close()

    def vis_scatter(self,X,save_name=False):
        fig = plt.figure(figsize=(5,5))
        ax = plt.axes()
        ax.plot([-1,-1,1,1,-1],[-1,1,1,-1,-1],c='black')
        c = patches.Circle(xy=(self.center[0], self.center[1]), radius=self.radius, fc='r', ec='r')
        ax.add_patch(c)
        ax.scatter(X[:,0],X[:,1],c='black',s=1,alpha=0.5)
        ax.scatter(self.goal[0],self.goal[1],marker='x',c='black')
        if save_name:
            plt.title(save_name)
            plt.savefig(save_name,format = 'png', dpi=200)
            plt.close()


from bayesian_optimization import UtilityFunction, BayesianOptimization
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from ThreeDEnv import environment_array

utility_function = UtilityFunction(kind="ei",xi=0,kappa=0)
def target(x,y,z):
    return environment_array(x,y,z)

optimizer = BayesianOptimization(target, {'z': (2, 4),'y':(40,65),'x':(1000,4000)}, random_state=250)
#optimizer.maximize(init_points=int(input('Enter the number of random steps: ')),n_iter=0)

'''probe_point(np.min(x),np.max(y))
probe_point(np.max(x),np.max(y))
probe_point(np.max(x),np.min(y))'''

def probe_point(x,y,z):
    return optimizer.probe(params={"x": x, "y": y, "z": z},lazy=True,)
probe_point(1000,40,2)
probe_point(1000,40,4)
probe_point(4000,40,4)
probe_point(4000,65,4)
probe_point(4000,65,2)
probe_point(1000,65,2)
probe_point(1000,65,4)
probe_point(2500,52.5,3)
optimizer.maximize(n_iter=0,init_points=0)
optimizer.maximize(n_iter=20, init_points = 2)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
a = []
b = []
j = []
cv = []
def utilitytarget(xtarget,ytarget,ztarget):
    xyparam = np.array([[xtarget,ytarget,ztarget]])
    return float((utility_function.utility(xyparam, optimizer._gp, 0)))

for i in range(10000):

    x = np.random.uniform(1000,4000)
    y = 40
    z = np.random.uniform(2,4)
    c = utilitytarget(x,y,z)
    i = i +1
    a.append(x)
    b.append(y)
    j.append(z)
    cv.append(c)
    i = i + 1

for i in range(10000):

    x = np.random.uniform(1000,4000)
    y = np.random.uniform(40,65)
    z = 4
    c = utilitytarget(x,y,z)
    i = i +1
    a.append(x)
    b.append(y)
    j.append(z)
    cv.append(c)
    i = i + 1

for i in range(10000):

    x = np.random.uniform(1000,4000)
    y = np.random.uniform(40,65)
    z = 2
    c = utilitytarget(x,y,z)
    i = i +1
    a.append(x)
    b.append(y)
    j.append(z)
    cv.append(c)
    i = i + 1

for i in range(10000):

    x = 1000
    y = np.random.uniform(40,65)
    z = np.random.uniform(2,4)
    c = utilitytarget(x,y,z)
    i = i +1
    a.append(x)
    b.append(y)
    j.append(z)
    cv.append(c)
    i = i + 1

for i in range(10000):

    x = 4000
    y = np.random.uniform(40,65)
    z = np.random.uniform(2,4)
    c = utilitytarget(x,y,z)
    i = i +1
    a.append(x)
    b.append(y)
    j.append(z)
    cv.append(c)
    i = i + 1

for i in range(10000):

    x = np.random.uniform(1000,4000)
    y = 65
    z = np.random.uniform(2,4)
    c = utilitytarget(x,y,z)
    i = i +1
    a.append(x)
    b.append(y)
    j.append(z)
    cv.append(c)
    i = i + 1

img = ax.scatter(a, b, j,c=cv, cmap=plt.jet(),marker="s")
fig.colorbar(img)
ax.set_xlabel('Welding Energy (J)')
ax.set_ylabel('Vibration amplitude(um)')
ax.set_zlabel('Clamping pressure (bar)')
plt.show()
plt.savefig('3D utility 24 opt steps 3 random')


import time
from datetime import datetime
from enum import Enum
from importlib import import_module
from json import JSONEncoder
from os import listdir
from os.path import splitext

def loadHandlers(ctx, dirType, prefix):
    cL = len(dirType)
    handlerNames = [splitext(f)[0] for f in sorted(listdir(prefix + "/" + dirType.lower() + "s")) if
                splitext(f)[0][-cL:] == dirType]
    handlers = {}

    for moduleName in handlerNames:
        module = import_module(prefix.replace('/', '.') + "." + dirType.lower() + "s." + moduleName)
        handlerClass = getattr(module, moduleName)
        handler = handlerClass(ctx)
        handlers[moduleName[:-cL]] = handler

    return handlers

class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

class EntityJSONEncoder(JSONEncoder):
    def default(self, obj):

        if (hasattr(obj, 'toDict')):
            return obj.toDict()
        elif isinstance(obj, Enum):
            return obj.value
        elif isinstance(obj, datetime):
            return time.mktime(obj.timetuple())
        #else:
        #    return obj.__dict__

        return JSONEncoder.default(self, obj)

class EntityPatch():
    def __init__(self, content=None, **kwargs):
        if not content:
            self.__dict__ = kwargs
        elif isinstance(content, dict):
            self.__dict__ = content
        else:
            self.__dict__ = content.__dict__

    def toDict(self):
        return self.__dict__

    def toView(self):
        return EntityView(self, entityClass='Entity')

class EntityView():

    def __init__(self, entity, entityClass=None):
        self.entity = entity
        if entityClass is None:
            self.entityClass = self.__class__.__name__[:-4]
        else:
            self.entityClass = entityClass

    def toDict(self):
        _dict = dict(self.__dict__)

        for objName in dir(self):
            if objName.startswith('__') or objName == 'toDict':
                continue

            obj = _dict[objName]
            if objName == 'entity':
                del _dict[objName]
            elif isinstance(obj, set):
                _dict[objName] = list(obj)
            elif isinstance(obj, bytes):
                _dict[objName] = obj.decode("utf-8")
            elif isinstance(obj, EntityView):
                _dict[objName] = obj.toDict()
            elif isinstance(obj, list):
                subEntList = []
                for subEnt in obj:
                    if isinstance(subEnt, EntityView):
                        subEntList.append(subEnt.toDict())
                    else:
                        subEntList.append(subEnt)

                _dict[objName] = subEntList
            else:
                del _dict[objName]

        return _dict


"""Serializer fields"""
import os

from django.contrib.gis import forms
from rest_framework.fields import Field, FileField
from greenwich.io import MemFileIO
from greenwich.raster import Raster, driver_for_path
import numpy as np

from spillway.compat import json

class GeometryField(Field):
    def to_internal_value(self, data):
        # forms.GeometryField cannot handle geojson dicts.
        if isinstance(data, dict):
            data = json.dumps(data)
        return forms.GeometryField().to_python(data)

    def to_representation(self, value):
        # Create a dict from the GEOSGeometry when the value is not previously
        # serialized from the spatial db.
        try:
            return {'type': value.geom_type, 'coordinates': value.coords}
        # Value is already serialized as geojson, kml, etc.
        except AttributeError:
            return value

class NDArrayField(FileField):
    def to_representation(self, value):
        geom = self.context.get('g')
        stat = self.context.get('stat')
        with Raster(getattr(value, 'path', value)) as r:
            if geom:
                if geom.num_coords > 1:
                    with r.clip(geom) as clipped:
                        arr = clipped.masked_array()
                else:
                    coord_px = r.affine.transform((geom.coords,)).pop()
                    arr = r.ReadAsArray(*(coord_px + (1, 1)))
            else:
                arr = r.masked_array()
            if stat:
                arr = getattr(np.ma, stat)(arr)
            if arr.size == 1:
                arr = arr.item()
            return arr
        raise ValueError('Failure reading array values')

class GDALField(FileField):
    def to_representation(self, value):
        imgpath = value.path
        geom = self.context.get('g')
        # Handle format as .tif, tif, or tif.zip
        ext = self.context.get('format') or os.path.splitext(imgpath)[-1][1:]
        ext = os.path.splitext(ext)[0]
        # No conversion is needed if the original format without clipping
        # is requested.
        if not geom and imgpath.endswith(ext):
            return imgpath
        driver = driver_for_path('base.%s' % ext)
        memio = MemFileIO()
        if geom:
            with Raster(imgpath) as r:
                with r.clip(geom) as clipped:
                    clipped.save(memio, driver)
        else:
            driver.copy(imgpath, memio.name)
        return memio


#!/bin/python3

import turtle
elsa = turtle.Turtle()
turtle.Screen().bgcolor("#ECEFF8")
elsa.color("#78ADCE")
for i in range(10):
    for i in range(2):
        elsa.forward(100)
        elsa.right(60)
        elsa.forward(100)
        elsa.right(120)
    elsa.right(36)

elsa.hideturtle()


# -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Business Applications
#    Copyright (C) 2004-2012 OpenERP S.A. (<http://openerp.com>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

import time
import datetime
from dateutil.relativedelta import relativedelta

import openerp
from openerp import SUPERUSER_ID
from openerp.tools import DEFAULT_SERVER_DATE_FORMAT as DF
from openerp.tools.translate import _
from openerp.osv import fields, osv

class fleet_config_settings(osv.osv_memory):
    _name = 'fleet.config.settings'
    _inherit = 'fleet.config.settings'

    _columns = {
        'default_coupon_creation': fields.boolean(_('Automatic Coupon Creation'), help=_("Automatically create coupons based on fueling policy")),
        'default_price_per_lt': fields.float(_('Fuel Price per Liter')),
        'default_efficiency_alert_buffer': fields.float(_('Fuel Efficiency Alert Buffer'), help=_('Alerts managers to fuel log efficiency that if this amount greater than or lesser than average')),

    }

    _defaults = {
        'default_coupon_creation' : False,
        'default_price_per_lt': 3750.00,
    }

    def set_default_coupon_creation(self, cr, uid, ids, context=None):
        ir_values = self.pool.get('ir.values')
        config = self.browse(cr, uid, ids[0], context)
        ir_values.set_default(cr, SUPERUSER_ID, 'fleet.fuel.coupon', 'default_coupon_creation',
            config.default_coupon_creation)

    def get_default_coupon_creation(self, cr, uid, fields, context=None):
        ir_values = self.pool.get('ir.values')
        create_coupon = ir_values.get_default(cr, SUPERUSER_ID, 'fleet.fuel.coupon', 'default_coupon_creation')
        return {'default_coupon_creation': create_coupon}

    def set_default_price_per_lt(self, cr, uid, ids, context=None):
        ir_values = self.pool.get('ir.values')
        config = self.browse(cr, uid, ids[0], context)
        ir_values.set_default(cr, SUPERUSER_ID, 'fleet.fuel.log', 'default_price_per_lt',
            config.default_price_per_lt)

    def get_default_price_per_lt(self, cr, uid, fields, context=None):
        ir_values = self.pool.get('ir.values')
        price = ir_values.get_default(cr, SUPERUSER_ID, 'fleet.fuel.log', 'default_price_per_lt')
        return {'default_price_per_lt': price}

    def set_default_efficiency_alert_buffer(self, cr, uid, ids, context=None):
        ir_values = self.pool.get('ir.values')
        config = self.browse(cr, uid, ids[0], context)
        ir_values.set_default(cr, SUPERUSER_ID, 'fleet.fuel.log', 'default_efficiency_alert_buffer',
            config.default_efficiency_alert_buffer)

    def get_default_efficiency_alert_buffer(self, cr, uid, fields, context=None):
        ir_values = self.pool.get('ir.values')
        price = ir_values.get_default(cr, SUPERUSER_ID, 'fleet.fuel.log', 'default_efficiency_alert_buffer')
        return {'default_efficiency_alert_buffer': price}

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:


from telegram import InlineQueryResultArticle, ParseMode,InputTextMessageContent
from uuid import uuid4
import requests
from decimal import Decimal

class GeneralStats:

	def __init__(self):

		self.URL = 'https://api.coinmarketcap.com/v1/global/'
		self.data = requests.get(self.URL).json()

		self.activeCryptoCount = self.get_active_cryptos(self.data)
		self.dominanceBTC = self.get_BTC_dominance(self.data)
		self.marketCount = self.get_market_count(self.data)
		self.volume24h = self.get_volume_24h(self.data)
		self.marketCap = self.get_market_cap(self.data)

	def get_market_cap(self, data):

		unformatted = data['total_market_cap_usd']
		cap = Decimal(unformatted).quantize(Decimal('1.00'), rounding = 'ROUND_HALF_DOWN')
		cap = str("{:,}".format(cap))
		return cap

	def get_BTC_dominance(self, data):

		dominance = Decimal(data['bitcoin_percentage_of_market_cap']).quantize(Decimal('1.00'), rounding = 'ROUND_HALF_DOWN')
		dominance = str("{:,}".format(dominance))
		return dominance

	def get_active_cryptos(self, data):

		return data['active_currencies']

	def get_market_count(self, data):

		return data['active_markets']

	def get_volume_24h(self, data):

		volume = Decimal(data['total_24h_volume_usd']).quantize(Decimal('1.00'), rounding = 'ROUND_HALF_DOWN')
		volume = str("{:,}".format(volume))
		return volume

def get_stats_list():

	data = GeneralStats()

	results = [

		InlineQueryResultArticle(
			id=uuid4(),
			title=("Total Market Capitalization"),
			thumb_url="https://i.imgur.com/UMczLVP.png",
			description=("$" + str(data.marketCap)),
			input_message_content=InputTextMessageContent("***Total Market Capitalization:*** " \
				+ "$" + str(data.marketCap), ParseMode.MARKDOWN)),

		InlineQueryResultArticle(
			id=uuid4(),
			title=("Total 24 Hour Volume"),
			thumb_url="https://imgur.com/Qw4y4Ed.png",
			description=("$" + str(data.volume24h)),
			input_message_content=InputTextMessageContent("***Total 24 Hour Volume:*** $" \
				+ str(data.volume24h),  ParseMode.MARKDOWN)),

		InlineQueryResultArticle(
			id=uuid4(),
			title=("Bitcoin Dominance"),
			description=(str(data.dominanceBTC) + "%"),
			thumb_url="https://imgur.com/tXiapTn.png",
			input_message_content=InputTextMessageContent("***Bitcoin Dominance:*** " \
				+ str(data.dominanceBTC) + "%",  ParseMode.MARKDOWN)),

		InlineQueryResultArticle(
    		id=uuid4(),
    		title=("Active Cryptocurrencies"),
    		thumb_url="https://imgur.com/g6YajTp.png",
    		description=(str(data.activeCryptoCount) + " active cryptocurrencies"),
    		input_message_content=InputTextMessageContent(str(data.activeCryptoCount) \
    			+ " active cryptocurrencies on CoinMarketCap.", ParseMode.MARKDOWN)),

		InlineQueryResultArticle(
    		id=uuid4(),
    		thumb_url="https://imgur.com/qO0rcCI.png",
    		title=("Markets"),
    		description=(str(data.marketCount) + " markets"),
    		input_message_content=InputTextMessageContent(str(data.marketCount) \
    			+ " markets on CoinMarketCap." , ParseMode.MARKDOWN)),

	]

	return results


import os

# REDIS CONFIGS
REDIS_HOST = '0.0.0.0'
REDIS_PORT = 6379
BROKER_URL = os.environ.get(
    'REDIS_URL',
    'redis://{host}:{port}/0'.format(
        host=REDIS_HOST,
        port=REDIS_PORT
    )
)

# APP CONFIGS
SECRET_KEY='dev',
CACHE_TYPE='null',


#!/usr/bin/python
import os

os.write(1,"ingrese el nombre del archivo origen:")
archivo_origen = os.read(0,10000).strip()
#si con read alcanza el final del archivo, devuelve una cadena vacia(hay un \n)
#archivo_origen = raw_input()

os.write(1,"ingrese el nombre del archivo destino:")
archivo_destino = os.read(0,10000).strip()

fd = os.open(archivo_origen,os.O_RDWR)
#os.open() es otro file descriptor
var_origen= os.read(fd,10000)
os.close(fd)

#with os.open(fd,os.O_RDONLY) as open_file:
#    var_origen = open_file.os.read(fd)

fdd = os.open(archivo_destino,os.O_RDWR|os.O_CREAT)

final = os.write(fdd,var_origen)
os.close(fdd)


import torch
from transformers import *

#import pretrained model and output all hidden states from model

tokenizer = AutoTokenizer.from_pretrained("emilyalsentzer/Bio_ClinicalBERT")
config = BertConfig.from_pretrained("emilyalsentzer/Bio_ClinicalBERT", output_hidden_states=True)
model = AutoModel.from_pretrained("emilyalsentzer/Bio_ClinicalBERT", config=config)
model.eval()

#do not have actual notes but tokenize an example (get word indices)...

example_note = "patient has severe case of epithelial trauma in lungs"
marked_note = "[CLS] " + example_note + " [SEP]"

tokenized_note = tokenizer.tokenize(marked_note)
indexed_note = tokenizer.convert_tokens_to_ids(tokenized_note)
segments_ids = [1] * len(indexed_note)

tokenized_note = tokenizer.tokenize(marked_note)

# Convert inputs to PyTorch tensors

tokens_tensor = torch.tensor([indexed_note])
segments_tensors = torch.tensor([segments_ids])

# Acquire hidden states

with torch.no_grad():
    last_hidden_state, pooler_output, hidden_states  = model(tokens_tensor)

print(torch.eq(hidden_states[-1], last_hidden_state))
print(hidden_states[-2].shape)

sent_embedding = torch.mean(hidden_states[-2][0], dim = 0)

# Check out cosine similarity between embeddings..

example_note_2 = "long history of frequent respiratory infections, shortness of breath, or wheezing"
example_note_3 = "Patient is showing nausea, persistent diarrhea, and vomiting,"

marked_note_2 = "[CLS] " + example_note_2 + " [SEP]"
marked_note_3 = "[CLS] " + example_note_3 + " [SEP]"

tokenized_note_2 = tokenizer.tokenize(marked_note_2)
tokenized_note_3 = tokenizer.tokenize(marked_note_3)

indexed_note_2 = tokenizer.convert_tokens_to_ids(tokenized_note_2)
indexed_note_3 = tokenizer.convert_tokens_to_ids(tokenized_note_3)

tokens_tensor_2 = torch.tensor([indexed_note_2])
tokens_tensor_3 = torch.tensor([indexed_note_3])

with torch.no_grad():
    _, _, hidden_states_2  = model(tokens_tensor_2)
    _, _, hidden_states_3 = model(tokens_tensor_3)

sent_embedding_2 = torch.mean(hidden_states_2[-2][0], dim = 0)
sent_embedding_3 = torch.mean(hidden_states_3[-2][0], dim = 0)

from scipy.spatial.distance import cosine

close_sent = 1 - cosine(sent_embedding, sent_embedding_2)

diff_sent = 1 - cosine(sent_embedding, sent_embedding_3)

print(close_sent)
print(diff_sent)


#!/usr/bin/env python
# fmt:off
s = [
    [int(i) for i in l.split()]
    for l in open(0).read().splitlines()
]
print(sum(max(r) - min(r) for r in s))
print(sum(
    a // b
    for r in s
    for a in r
    for b in r
    if a != b and a % b == 0
))


from .base import *
import pyNN
#import pyNN
class pyNNBackend(Backend):

    backend = 'pyNN'

    def init_backend(self, attrs=None, simulator='neuron', DTC = None):
        from pyNN import neuron
        self.neuron = neuron
        from pyNN.neuron import simulator as sim
        from pyNN.neuron import setup as setup
        from pyNN.neuron import Izhikevich
        from pyNN.neuron import Population
        from pyNN.neuron import DCSource
        self.Izhikevich = Izhikevich
        self.Population = Population
        self.DCSource = DCSource
        self.setup = setup
        self.model_path = None
        self.related_data = {}
        self.lookup = {}
        self.attrs = {}
        super(pyNNBackend,self).init_backend()#*args, **kwargs)

        self.model._backend.use_memory_cache = False
        self.model.unpicklable += ['h','ns','_backend']

        if type(DTC) is not type(None):
            if type(DTC.attrs) is not type(None):

                self.set_attrs(**DTC.attrs)
                assert len(self.model.attrs.keys()) > 0

            if hasattr(DTC,'current_src_name'):
                self._current_src_name = DTC.current_src_name

            if hasattr(DTC,'cell_name'):
                self.cell_name = DTC.cell_name
        #if DTC is not None:
        #    self.set_attrs(**DTC.attrs)

    def get_membrane_potential(self):
        """Must return a neo.core.AnalogSignal.
        And must destroy the hoc vectors that comprise it.
        """
        dt = float(copy.copy(self.neuron.dt))
        data = self.population.get_data().segments[0]
        return data.filter(name="v")[0]

    def _local_run(self):
        '''
        pyNN lazy array demands a minimum population size of 3. Why is that.
        '''
        import numpy as np
        results={}
        #self.population.record('v')
        #self.population.record('spikes')
        # For ome reason you need to record from all three neurons in a population
        # In order to get the membrane potential from only the stimulated neuron.

        self.population[0:2].record(('v', 'spikes','u'))
        '''
        self.Iz.record('v')
        self.Iz.record('spikes')
        # For ome reason you need to record from all three neurons in a population
        # In order to get the membrane potential from only the stimulated neuron.

        self.Iz.record(('v', 'spikes','u'))
        '''
        #self.neuron.run(650.0)
        DURATION = 1000.0
        self.neuron.run(DURATION)

        data = self.population.get_data().segments[0]
        vm = data.filter(name="v")[0]#/10.0
        results['vm'] = vm
        #print(vm)
        sample_freq = DURATION/len(vm)
        results['t'] = vm.times #np.arange(0,len(vm),DURATION/len(vm))
        results['run_number'] = results.get('run_number',0) + 1
        return results

    def load_model(self):
        self.Iz = None
        self.population = None
        self.setup(timestep=0.01, min_delay=1.0)
        pop = self.neuron.Population(3, pyNN.neuron.Izhikevich(a=0.02, b=0.2, c=-65, d=6, i_offset=[0.014, -65.0, 0.0]))#,v=-65))
        self.population = pop

    def set_attrs(self, **attrs):
        #attrs = copy.copy(self.model.attrs)
        self.init_backend()
        #self.set_attrs(**attrs)
        self.model.attrs.update(attrs)
        assert type(self.model.attrs) is not type(None)
        attrs['i_offset']=None
        attrs_ = {x:attrs[x] for x in ['a','b','c','d','i_offset']}
        attrs_['i_offset'] = [0.014,attrs_['vr'],0.0]
        #self.population[0].initialize()
        self.population[0].set_parameters(**attrs_)

        print(self.population[0].get_parameters())
        self.neuron.h.psection()
        return self

    def inject_square_current(self, current):
        import copy
        attrs = copy.copy(self.model.attrs)
        self.init_backend()
        self.set_attrs(**attrs)
        c = copy.copy(current)
        if 'injected_square_current' in c.keys():
            c = current['injected_square_current']

        stop = float(c['delay'])+float(c['duration'])
        start = float(c['delay'])
        amplitude = float(c['amplitude'])
        #print('amplitude',amplitude)
        electrode = self.neuron.DCSource(start=start, stop=stop, amplitude=amplitude)
        print(self.population[0])
        print(type(self.population[0]))
        print(self.population[0].get_parameters())

        electrode.inject_into(self.population[0:1])


#run me third
#input midi pit data ,origin csv  output final data

import csv
f_org = open('midi_org.csv', 'r')
f_pit = open('outfile/midi_pit.csv', 'r')
wf = open('outfile/midi_final.csv', 'w')

def cpstr(org_data):
    wf.write(','.join(org_data))
    wf.write('\n')

org_data = list(csv.reader(f_org))
pit_data = list(csv.reader(f_pit))

t_rows = len(org_data)

t=0
start_output_f0 = False
from_t = 0;
while t in range(0,t_rows):
    if start_output_f0:
        if org_data[t][1] != from_str:
            from_t = int(from_str)
            to_t = int(org_data[t][1])
            if to_t<from_t:
                cpstr(org_data[t])
                break
            for i in range(from_t,to_t-1):
                wf.write('2, '+str(i)+', Pitch_bend_c, 0, '+str(pit_data[i][0])+'\n')
            cpstr(org_data[t])
            from_str = org_data[t][1]
        else:
            cpstr(org_data[t])
    elif 'Note_on' in org_data[t][2]:
        from_str = org_data[t][1]
        start_output_f0 = True
        cpstr(org_data[t])
#         wf.write(str(org_data[t])+'\n')
    else:
        cpstr(org_data[t])
    t+=1

#         print(my_csv_data[t][2])
#         wf.write(my_csv_data[t][1]+','+my_csv_data[t][4]+'\n')

f_org.close()
f_pit.close()
wf.close()


# This is called by scrape.sh, for reporting utilization numbers

import gspread
import pygsheets
import sys
import os
from oauth2client.service_account import ServiceAccountCredentials
import datetime
import socket

def write(wksh, row, col, txt):
	try:
		wksh.update_cell((row,col),txt)
	except:
		print("WARN: pygsheets failed... -_-")

def readAllVals(wksh):
	try:
		return wksh.get_all_values()
	except:
		print("WARN: pygsheets failed... -_-")
		exit()

#1 = tid
#2 = appname1
#3 = lut
#4 = reg
#5 = ram
#6 = uram
#7 = dsp
#8 = lut as logic
#9 = lut as mem
#10 = synth time
#11 = timing met?
#12 = backend
#13 = hash
#14 = apphash

# tid = sys.argv[1]

# # gspread auth
# json_key = '/home/mattfel/regression/synth/key.json'
# scope = [
#     'https://spreadsheets.google.com/feeds',
#     'https://www.googleapis.com/auth/drive'
# ]
# credentials = ServiceAccountCredentials.from_json_keyfile_name(json_key, scope)

# pygsheets auth
json_key = '/home/mattfel/regression/synth/pygsheets_key.json'
gc = pygsheets.authorize(outh_file = json_key)

if (sys.argv[12] == "Zynq"):
	# sh = gc.open("Zynq Regression") # Open by name
	try:
		sh = gc.open_by_key("1jZxVO8VFODR8_nEGBHfcmfeIJ3vo__LCPdjt4osb3aE")
	except:
		print("WARN: Could not get sheet")
		exit()
	word="Slice"
elif (sys.argv[12] == "ZCU"):
	try:
		sh = gc.open_by_key("181pQqQXV_DsoWZyRV4Ve3y9QI6I0VIbVGS3TT0zbEv8")
	except:
		print("WARN: Could not get sheet")
		exit()
	word="CLB"
elif (sys.argv[12] == "Arria10"):
	try:
		sh = gc.open_by_key("1IgPolABXEo58kG0cCQTr-lLwuPtzwPUqbkAF74hnss8")
	except:
		print("WARN: Could not get sheet")
		exit()
	word="CLB"  # TODO: Tian
elif (sys.argv[12] == "AWS"):
	# sh = gc.open("AWS Regression") # Open by name
	try:
		sh = gc.open_by_key("19G95ZMMoruIsi1iMHYJ8Th9VUSX87SGTpo6yHsSCdvU")
	except:
		print("WARN: Could not get sheet")
		exit()
	word="CLB"

# Get column
worksheet = sh.worksheet_by_title("Timestamps") # Select worksheet by index
lol = readAllVals(worksheet)
if (sys.argv[2] in lol[0]):
	col=lol[0].index(sys.argv[2])+1
else:
	col=len(lol[0])+1
	numsheets = len(sh.worksheets())
	for x in range(0,numsheets):
		worksheet = sh.worksheet('index', x)
		write(worksheet,1,col,sys.argv[2])
# Find row, since tid is now unsafe
tid = -1
for i in range(2, len(lol)):
	if (lol[i][0] == sys.argv[13] and lol[i][1] == sys.argv[14] and lol[i][4] == socket.gethostname()):
		tid = i + 1
		break

# Page 0 - Timestamps
stamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

worksheet = sh.worksheet_by_title('Timestamps') # Select worksheet by index
write(worksheet,tid,col, stamp)

# Page 1 - Slice LUT
worksheet = sh.worksheet_by_title(word + ' LUTs') # Select worksheet by index
write(worksheet,tid,col,sys.argv[3])

# Page 2 - Slice Reg
worksheet = sh.worksheet_by_title(word + ' Regs') # Select worksheet by index
write(worksheet,tid,col,sys.argv[4])

# Page 3 - Mem
worksheet = sh.worksheet_by_title('BRAMs') # Select worksheet by index
write(worksheet,tid,col,sys.argv[5])

if (sys.argv[12] == "AWS"):
	# Page 4 - URAM
	worksheet = sh.worksheet_by_title('URAMs') # Select worksheet by index
	write(worksheet,tid,col,sys.argv[6])

# Page 5 - DSP
worksheet = sh.worksheet_by_title('DSPs') # Select worksheet by index
write(worksheet,tid,col,sys.argv[7])

# Page 6 - LUT as Logic
worksheet = sh.worksheet_by_title('LUT as Logic') # Select worksheet by index
write(worksheet,tid,col,sys.argv[8])

# Page 7 - LUT as Memory
worksheet = sh.worksheet_by_title('LUT as Memory') # Select worksheet by index
write(worksheet,tid,col,sys.argv[9])

# Page 8 - Synth time
worksheet = sh.worksheet_by_title('Synth Time') # Select worksheet by index
write(worksheet,tid,col,float(sys.argv[10]) / 3600.)

# Page 9 - Timing met
worksheet = sh.worksheet_by_title('Timing Met') # Select worksheet by index
write(worksheet,tid,col,sys.argv[11])

# Tell last update
worksheet = sh.worksheet_by_title('STATUS')
write(worksheet,22,3,stamp)
write(worksheet,22,4,os.uname()[1])


from flask import Flask, request
from flask_restful import Resource, Api
import json

app = Flask(__name__)
api = Api(app)

tasks=[{'id': 1, 'owner': 'Andrews','task': 'Building a API of tasks', 'status': 'pending'},
       {'id': 2, 'owner': 'Boby','task': 'Start a diet', 'status': 'pending'}]

class Task(Resource):

    def get(self, position):
        try:
            response = tasks[position]
        except IndexError:
            response = {'status': 'error','message': 'Has no task in this position'}
        except Exception:
            response = {'status': 'error','message': 'Unknown error. Please contact API administrator'}
        return response

    def put(self, position):
        try:
            data = json.loads(request.data)
            if (data == 'done' or data == 'pending') and data != tasks[position]['status']:
                tasks[position]['status'] = data
                return {'status': 'success', 'message': 'update status task'}
        except IndexError:
            return {'status': 'error', 'message': 'Has no task in this position'}
        return {'status': 'error',
        'message': "You can only change "
        + "the status of the task and the status must be 'done' or 'pending'"}

    def delete(self, position):
        try:
            del(tasks[position])
            return {'status': 'success', 'message': 'record deleted'}
        except IndexError:
            return {'status': 'error', 'message': 'Has no task in this position'}

class List_All_Tasks(Resource):

    def get(self):
        return tasks

    def post(self):
        data = json.loads(request.data)
        data['id'] = tasks[len(tasks)-1]['id'] + 1
        tasks.append(data)
        return {'status': 'success', 'message': 'inserted task'}

api.add_resource(Task, '/task/<int:position>/')
api.add_resource(List_All_Tasks, '/task/')

if __name__=='__main__':
    app.run(debug=True)


from math import fmod, pi
import numpy as np

def wrap_angle(angle, l_wrap, u_wrap):
    angle_range = abs(l_wrap)+ abs(u_wrap)
    angle1 = fmod((angle + u_wrap), pi)
    if angle1 < 0:
        angle1 += angle_range
    return angle1

def wrap(angle, index=None):
    if index:
        angle[index] -= 2*np.pi * np.floor((angle[index] + np.pi) / (2*np.pi))
    else:
        angle -= 2*np.pi * np.floor((angle + np.pi) / (2*np.pi))
    return angle

if __name__ == "__main__":
    val1 = wrap_angle(6.7, -pi, pi)
    print(val1)


from util.image.image import MemeTemplate

IMAGE = "https://i.imgur.com/o1NzXyW.jpg"

spontaneousAnger = MemeTemplate(
    "spontaneous anger",
    IMAGE,
    {
        "angerText": {
            "location": [135, 20],
            "size": 35, "max": 10
        },
        "questionText": {
            "location": [385, 20],
            "size": 35, "max": 10
        }
    }
)

def generateImage(angerText, questionText):
    return spontaneousAnger.generateImage(
        angerText = angerText,
        questionText = questionText
    )


#!/usr/bin/env python3
# usage:
#   python server.py --help
import argparse
import logging
import socketserver
from http import server

import index

logging.basicConfig(format='%(message)s')
logging.getLogger().setLevel(logging.INFO)

def get_opts():
    parser = argparse.ArgumentParser(description='Start a simple PyPI server')
    parser.add_argument(
        '-b', '--base-path',
        dest='base_path',
        default='simple',
        help='Base path.',
        metavar='STR',
        type=str,
    )
    parser.add_argument(
        '-p', '--port',
        dest='port',
        default='8000',
        help='Port number.',
        metavar='INT',
        type=int,
    )
    return parser.parse_args()

class PyPI(server.SimpleHTTPRequestHandler):
    def log_headers(self):
        for key, val in self.headers.items():
            msg = f'HEADER -- {key}: {val}'
            msg = f'{msg[:76]}...' if len(msg) > 79 else msg
            logging.info(msg)

    def get_response(self, httpMethod):
        # Log request headers
        self.log_headers()
        logging.info(f'PATH -- {self.path}')

        # Construct event
        event = {
            'httpMethod': httpMethod,
            'path': self.path,
        }

        # Get response
        response = index.proxy_request(event)
        status = response.get('statusCode')
        headers = response.get('headers')
        self.send_response(status)
        for key, val in headers.items():
            self.send_header(key, val)
        self.end_headers()

    def do_GET(self):
        self.get_response('GET')

    def do_HEAD(self):
        self.get_response('HEAD')

if __name__ == '__main__':
    opts = get_opts()
    index.BASE_PATH = opts.base_path
    with socketserver.TCPServer(('', opts.port), PyPI) as httpd:
        logging.info(
            f'Starting PyPI at http://localhost:{opts.port}/{opts.base_path}/')
        httpd.serve_forever()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Author      : Bhishan Poudel; Physics PhD Student, Ohio University
# Date        : Jun-24-2017 Sat

RANKS = list(range(-8, 0)) + list(range(1, 9))

class User:

    def __init__(self):
        self._rank = 0
        self.progress = 0

    @property
    def rank(self):
        return RANKS[self._rank]

    def update_rank(self):
        while self.progress >= 100 and self._rank < 15:
            self._rank += 1
            self.progress -= 100
        if self._rank == 15:
            self.progress = 0

    def inc_progress(self, rank):
        if not rank or rank < -8 or rank > 8:
            raise ValueError()

        rank += 7 if rank > 0 else 8
        if self._rank == rank:
            self.progress += 3
        elif self._rank - rank == 1:
            self.progress += 1
        elif self._rank < rank:
            self.progress += 10*(rank - self._rank)**2
        self.update_rank()

u = User()
u.rank = 6
u.progress = 10

print(u.rank())


"""
TO DO steps
1. Create a snake body
2. Move the snake
3. Control the snake
4. Detect collision with food
5. Create a scoreboard
6. Detect collision with wall
7. Detect collision with tail
"""
from turtle import Screen
from time import sleep
from snake import Snake
from food import Food
from scoreboard import Scoreboard
from settings import SETTINGS

WIDTH = SETTINGS['width']
HEIGHT = SETTINGS['height']
SNAKE_MOVE_DELAY = SETTINGS['move_delay']

global screen, snake, food

def init_screen():
    global screen
    screen = Screen()
    screen.setup(width=WIDTH, height=HEIGHT)
    screen.bgcolor("black")
    screen.title("My Snake Game")
    screen.tracer(0)

def enable_keys():
    screen.onkey(key='a', fun=snake.to_the_left)
    screen.onkey(key='d', fun=snake.to_the_right)

def is_food_collision():
    return snake.head.distance(food) <= 15

def is_wall_collision():
    x = WIDTH // 2 - 20
    y = HEIGHT // 2 - 20
    return snake.head.xcor() > x or snake.head.xcor() < -x or snake.head.ycor() > y or snake.head.ycor() < -y

def is_self_collision():
    for segment in snake[1:]:
        if snake.head.distance(segment) < 10:
            return True
    return False

def main():
    global snake, food
    init_screen()
    screen.update()
    snake = Snake()
    food = Food()
    score = Scoreboard()
    enable_keys()
    screen.listen()
    game_is_on = True
    while game_is_on:
        snake.move_forward()
        screen.update()
        if is_food_collision():
            food.move()
            snake.add_segment()
            score.refresh_score()
        if is_wall_collision() or is_self_collision():
            # score.game_over()
            snake.reset()
            score.reset()
        sleep(SNAKE_MOVE_DELAY)

if __name__ == '__main__':
    main()
    screen.mainloop()


# read (x, y, length) and draw squares on images
import sys
import cv2

img = cv2.imread("tests/Lenna.png")
# img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
for square in sys.stdin:
    x, y, w = map(int, square.split(" "))
    cv2.rectangle(img, (x, y), (x + w, y + w), (255, 0, 0), 2)

cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()


from __future__ import absolute_import

import time

from conf import (
    TRAIN_MODE,
    ARTIST_NAME,
)
from logger_conf import logger
from lyrics_generation import vectors_into_song, compose_rap, generate_lyrics
from neural_network import train, build_dataset, create_network
from utils import split_lyrics_file, prepare_list_of_all_rhymes

def main(depth, train_mode):
    start = time.time()
    model = create_network(depth, ARTIST_NAME=ARTIST_NAME, TRAIN_MODE=TRAIN_MODE)
    # change the lyrics file to the file with the lyrics you want to be trained on
    text_file = "ostr_lyrics.txt"

    if train_mode == True:
        bars = split_lyrics_file(text_file)

    if train_mode == False:
        bars = generate_lyrics(text_file)
        logger.debug("Generated lyrics:")
        logger.debug(bars)

    rhyme_list = prepare_list_of_all_rhymes(bars)
    if train_mode == True:
        x_data, y_data = build_dataset(bars, rhyme_list)
        train(x_data, y_data, model)

    if train_mode == False:
        vectors = compose_rap(bars, rhyme_list, text_file, model)
        rap = vectors_into_song(vectors, bars, rhyme_list)
        # f = open(FILE_WITH_GENERATED_LYRICS, "w")
        # for bar in rap:
        #     f.write(bar)
        #     f.write("\n")
        return rap
    stop = time.time()
    logger.DEBUG("Execution time in sec:{}".format(stop - start))

# main(DEPTH_OF_THE_N_NETWORK, TRAIN_MODE)


# SPDX-License-Identifier: BSD-3-Clause
# Copyright (c) 2021 Scipp contributors (https://github.com/scipp)
# flake8: noqa: E501
"""
This is the implementation of the ORSO header information.
"""

# author: Andrew R. McCluskey (arm61)

import yaml
import socket
import datetime
import pathlib
import getpass
from ess import __version__ as VERSION

OSRO_VERSION = 0.1

def noop(self, *args, **kw):
    pass

yaml.emitter.Emitter.process_tag = noop

def _repr(class_to_represent):
    """
    The representation object for all the Header sub-classes. This returns a string in a yaml format which will be ORSO compatible.

    Args:
        class_to_represent (:py:class:`object`): The class to be represented.

    Returns:
        (:py:attr:`str`): A string representation.
    """
    return yaml.dump(class_to_represent, sort_keys=False)

class Header:
    """
    The super class for all of the __repr__ items in the orso module
    """
    def __repr__(self):
        """
        The string representation for the Header class objects.
        """
        return _repr(self)

class Orso:
    """
    The class for the Orso header object.

    Args:
        creator (:py:class:`orso.Creator`): Information about the creation of the reduction.
        data_source (:py:class:`orso.DataSource`): Details of the data being reduced.
        reduction (:py:class:`orso.Reduction`): Information about the reduction that is performed.
        columns (:py:attr:`list` of :py:class:`orso.Column`): A list of the different columns persent in the data.
    """
    def __init__(self, creator, data_source, reduction, columns):
        self.creator = creator
        self.data_source = data_source
        self.reduction = reduction
        self.columns = columns

    def __repr__(self):
        """
        To ensure the prescence of the ORSO top line, the `orso.Orso` class has a slightly different :code:`__repr__`.
        """
        return f'# ORSO reflectivity data file | {OSRO_VERSION:.1f} standard | YAML encoding | https://reflectometry.org\n' + _repr(
            self)

class Creator(Header):
    """
    The information about who and when the reduced data was created, ie. when the reduction was performed and by whom.

    Args:
        name (:py:attr:`str`, optional): The name of the person that performed the reduction, can also include an email address. Optional, defaults to the machine username.
        affiliation (:py:attr:`str`, optional): The affiliation of the person that performed the reduction. Optional, defaults to :code:`None`.
        time (:py:attr:`str`, optional): The time that the reduction was performed, in the format :code:`"%Y-%m-%dT%H:%M:%S"`. Optional, defaults to the current time.
        system (:py:attr:`str`, optional): The machine that the reduction was performed on. Optional, defaults to the machine's host name.
    """
    def __init__(self, name=None, affiliation=None, time=None, system=None):
        self.name = name
        if name is None:
            self.name = getpass.getuser()
        if affiliation is not None:
            self.affiliation = affiliation
        self.time = time
        if time is None:
            self.time = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
        self.system = system
        if system is None:
            self.system = socket.gethostname()

class Sample(Header):
    """
    Sample information.

    Args:
        name (:py:attr:`str`, optional): A identifiable description for the sample. Optional, defaults to :code:`'Sample'`.
    """
    def __init__(self, name='Sample'):
        self.name = name

class ValueScalar(Header):
    """
    A single value with an unit.

    Args:
        magnitude (:py:attr:`float`): The value.
        unit (:py:attr:`str`, optional): The unit. Optional, defaults to :code:`'dimensionless'`.
    """
    def __init__(self, magnitude, unit='dimensionless'):
        self.magnitude = magnitude
        if unit == '\xC5':
            unit = 'angstrom'
        self.unit = unit

class ValueRange(Header):
    """
    A range with an upper and lower limit and a unit.

    Args:
        min (:py:attr:`float`): The minimum value.
        max (:py:attr:`float`): The maximum value.
        unit (:py:attr:`str`, optional): The unit. Optional, defaults to :code:`'dimensionless'`.
    """
    def __init__(self, min, max, unit='dimensionless'):
        self.min = min
        self.max = max
        if unit == '\xC5':
            unit = 'angstrom'
        self.unit = unit

class Measurement(Header):
    """
    Details of the measurement that is performed.

    Args:
        scheme (:py:attr:`str`, optional): The measurement scheme (ie. :code:`'energy-dispersive'`). Optional, defaults to :code:`'None'`.
        omega (:py:class:`orso.ValueScalar` or :py:class:`orso.ValueRange`, optional): The incident angle value or range. Optional, defaults to :code:`'None'`.
        wavelength (:py:class:`orso.ValueScalar` or :py:class:`orso.ValueRange`, optional): The measured wavelength value or range. Optional, defaults to :code:`'None'`.
        polarisation (:py:attr:`str`, optional): The polarisation present, typically as a :code:`'+'` or :code:`'-'` or combination. Optional, defaults to :code:`'None'`.
    """
    def __init__(self, scheme=None, omega=None, wavelength=None, polarisation=None):
        if scheme is not None:
            self.scheme = scheme
        if omega is not None:
            self.omega = omega
        if wavelength is not None:
            self.wavelength = wavelength
        if polarisation is not None:
            self.polarisation = polarisation

class Experiment(Header):
    """
    Experimental details.

    Args:
        instrument (:py:attr:`str`, optional): The name of the instrument. Optional, defaults to :code:`'None'`.
        probe (:py:attr:`str`, optional): The name of the probing radiation. Optional, defaults to :code:`'None'`.
        sample (:py:class:`orso.Sample`, optional): A description of the sample. Optional, defaults to :code:`'None'`.
    """
    def __init__(self, instrument=None, probe=None, sample=None):
        if instrument is not None:
            self.instrument = instrument
        if probe is not None:
            self.probe = probe
        if sample is not None:
            self.sample = sample

class DataSource(Header):
    """
    Details of where and who the data came from.

    Args:
        owner (:py:attr:`str`, optional): The name (and affiliation/email address) of the owner of the data. Optional, defaults to :code:`'None'`.
        facility (:py:attr:`str`, optional): The name of the facility the data was generated at. Optional, defaults to :code:`'None'`.
        experiment_id (:py:attr:`str`, optional): An identifier for the experiment (ie. proposal ID). Optional, defaults to :code:`'None'`.
        experiment_date (:py:attr:`str`, optional): The date or date range that the experiment was conducted on, in the format :code:`"%Y-%m-%d"`. Optional, defaults to :code:`'None'`.
        title (:py:attr:`str`, optional): A name of the data source. Optional, defaults to :code:`'None'`.
        experiment (:py:class:`orso.Experiment`, optional): Information about the experimental setup. Optional, defaults to :code:`'None'`.
        measurement (:py:class:`orso.Measurement`, optional): Details of the measurement scheme. Optional, defaults to :code:`'None'`.
    """
    def __init__(self,
                 owner=None,
                 facility=None,
                 experiment_id=None,
                 experiment_date=None,
                 title=None,
                 experiment=None,
                 measurement=None):
        if owner is not None:
            self.owner = owner
        if facility is not None:
            self.facility = facility
        if experiment_id is not None:
            self.experiment_id = experiment_id
        self.experiment_date = experiment_date
        if experiment_date is None:
            self.experiment_date = datetime.datetime.now().strftime("%Y-%m-%d")
        if title is not None:
            self.title = title
        if experiment is not None:
            self.experiment = experiment
        if measurement is not None:
            self.measurement = measurement

class File(Header):
    """
    Information for a given file.

    Attributes:
        creation (:py:attr:`str`): The date and time of the file creation.

    Args:
        file (:py:attr:`str`): The file name/path.
    """
    def __init__(self, file):
        self.file = file
        fpath = pathlib.Path(file)
        if not fpath.exists():
            raise FileNotFoundError(f'The file {file} could not be found.')
        else:
            self.creation = datetime.datetime.fromtimestamp(
                fpath.stat().st_ctime).strftime("%Y-%m-%dT%H:%M:%S")

class Files(Header):
    """
    Information on data files and associated reference files.

    Args:
        data_files (:py:attr:`list` of :py:class:`orso.File`): The experimental data files.
        reference_files (:py:attr:`list` of :py:class:`orso.File`, optional): The reference files. Optional, defaults to :code:`'None'`.
    """
    def __init__(self, data_files, reference_files=None):
        self.data_files = data_files
        if reference_files is not None:
            self.reference_files = reference_files

class Reduction(Header):
    """
    Details of the reduction processes.

    Args:
        script (:py:attr:`str`, optional): The file name/path for the reduction script or notebook. Optional, defaults to :code:`'None'`.
        input_files (:py:class:`orso.Files`, optional): The input files for the reduction. Optional defaults to :code:`'None'`.
        comments (:py:attr:`str`, optional): An additional comment on the reduction. Optional, defaults to :code:`'None'`.
    """
    def __init__(self, script=None, input_files=None, comment=None):
        self.software = f'ess-{VERSION}'
        if script is not None:
            self.script = script
        if input_files is not None:
            self.input_files = input_files
        if comment is not None:
            self.comment = comment

class Column:
    """
    Information on a data column.

    Args:
        quantity (:py:attr:`str`): The name of the column.
        unit (:py:attr:`str`, optional): The unit. Optional, defaults to :code:`'dimensionless'`.
        comments (:py:attr:`str`, optional): An additional comment on the column (ie. the definition for an uncertainty column). Optional, defaults to :code:`'None'`.
    """
    def __init__(self, quantity, unit='dimensionless', comment=None):
        self.quantity = quantity
        self.unit = unit
        if comment is not None:
            self.comment = comment


import pygame
import math
from copy import deepcopy
import random

__author__ = 'katja'

pygame.init()
clock = pygame.time.Clock()

UNIT = 10
BORDER = UNIT*2
WIDTH = 600
HEIGHT = 500

screen = pygame.display.set_mode((WIDTH, HEIGHT))
done = False

class Agent:
    def __init__(self, center):
        self.center = center
        self.angle = 90
        self.get_vertices()

    def get_vertices(self):
        """center is an x,y-tuple; angle is a float"""
        a = self.rotate_point((self.center[0]-1*UNIT, self.center[1]-1*UNIT))
        b = self.rotate_point((self.center[0]-1*UNIT, self.center[1]+1*UNIT))
        c = self.rotate_point((self.center[0]+2*UNIT, self.center[1]))  # triangle head
        self.vertices = [a,b,c]

    def rotate_point(self, point):
        """Rotates a point around another centerPoint. Angle is in degrees.
        Rotation is counter-clockwise"""
        a = math.radians(self.angle)
        temp_point = point[0]-self.center[0], point[1]-self.center[1]
        temp_point = (temp_point[0]*math.cos(a)-temp_point[1]*math.sin(a), temp_point[0]*math.sin(a)+temp_point[1]*math.cos(a))
        temp_point = temp_point[0]+self.center[0] , temp_point[1]+self.center[1]
        return temp_point

    def move(self, steps):
        a = math.radians(self.angle)
        sine = math.sin(a)
        cosine = math.cos(a)
        old_vertices = deepcopy(self.vertices)
        old_center = deepcopy(self.center)
        self.center = (self.center[0]+steps*UNIT*cosine, self.center[1]+steps*UNIT*sine)
        self.get_vertices()
        if not self.check_inside():
            self.vertices = old_vertices
            self.center = old_center

    def rotate(self, angle):
        self.angle += angle
        old_vertices = deepcopy(self.vertices)
        self.get_vertices()
        if not self.check_inside():
            self.vertices = old_vertices
            self.angle -= angle

    def check_inside(self):
        """returns true or false for whether any of the vertices is inside the field"""
        if self.center[0]-BORDER < 0 or self.center[0]+BORDER > WIDTH:
            return False
        if self.center[1]-BORDER < 0 or self.center[1]+BORDER > HEIGHT:
            return False
        return True

kenny = Agent((random.randint(BORDER,WIDTH-BORDER), random.randint(BORDER,HEIGHT-BORDER)))

while not done:
    screen.fill((0, 0, 0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_DOWN:
                kenny.move(1)
            if event.key == pygame.K_LEFT:
                kenny.rotate(5)
            if event.key == pygame.K_RIGHT:
                kenny.rotate(-5)

    pygame.draw.polygon(screen, (0, 128, 255), kenny.vertices)
    pygame.display.flip()
    clock.tick(60)


S, T, F = map (int,input().split())
Hora = S + T + F

if Hora == 24 :
	print ("0")
elif Hora > 24 or Hora < 0 :
	nHora = Hora % 24
	print (nHora)
else :
	print (Hora)


import os

def docker_rmi(img_id):
    """ """
    os.system("docker rmi {}".format(img_id))

def docker_rm(container_id):
    """ """
    os.system("docker rm {}".format(container_id))

if __name__ == "__main__":
    container_ids = [

    ]
    for id_ in container_ids:
        docker_rm(id_)
    img_ids = [
        "07b47d940122",
        "0ff9c7b19c6f",
        "de7dc4706e02",
        "8f37f32a53d7",
    ]
    for img_id in img_ids:
        docker_rmi(img_id)


# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:

# Copyright 2014 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# qutebrowser is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with qutebrowser.  If not, see <http://www.gnu.org/licenses/>.

"""Launcher for an external editor."""

import os
import tempfile

from PyQt5.QtCore import pyqtSignal, QProcess, QObject

from qutebrowser.config import config
from qutebrowser.utils import message, log

class ExternalEditor(QObject):

    """Class to simplify editing a text in an external editor.

    Attributes:
        _text: The current text before the editor is opened.
        _oshandle: The OS level handle to the tmpfile.
        _filehandle: The file handle to the tmpfile.
        _proc: The QProcess of the editor.
        _win_id: The window ID the ExternalEditor is associated with.
    """

    editing_finished = pyqtSignal(str)

    def __init__(self, win_id, parent=None):
        super().__init__(parent)
        self._text = None
        self._oshandle = None
        self._filename = None
        self._proc = None
        self._win_id = win_id

    def _cleanup(self):
        """Clean up temporary files after the editor closed."""
        try:
            os.close(self._oshandle)
            os.remove(self._filename)
        except OSError as e:
            # NOTE: Do not replace this with "raise CommandError" as it's
            # executed async.
            message.error(self._win_id,
                          "Failed to delete tempfile... ({})".format(e))

    def on_proc_closed(self, exitcode, exitstatus):
        """Write the editor text into the form field and clean up tempfile.

        Callback for QProcess when the editor was closed.
        """
        log.procs.debug("Editor closed")
        if exitstatus != QProcess.NormalExit:
            # No error/cleanup here, since we already handle this in
            # on_proc_error
            return
        try:
            if exitcode != 0:
                # NOTE: Do not replace this with "raise CommandError" as it's
                # executed async.
                message.error(
                    self._win_id, "Editor did quit abnormally (status "
                                  "{})!".format(exitcode))
                return
            encoding = config.get('general', 'editor-encoding')
            try:
                with open(self._filename, 'r', encoding=encoding) as f:
                    text = ''.join(f.readlines())
            except OSError as e:
                # NOTE: Do not replace this with "raise CommandError" as it's
                # executed async.
                message.error(self._win_id, "Failed to read back edited file: "
                                            "{}".format(e))
                return
            log.procs.debug("Read back: {}".format(text))
            self.editing_finished.emit(text)
        finally:
            self._cleanup()

    def on_proc_error(self, error):
        """Display an error message and clean up when editor crashed."""
        messages = {
            QProcess.FailedToStart: "The process failed to start.",
            QProcess.Crashed: "The process crashed.",
            QProcess.Timedout: "The last waitFor...() function timed out.",
            QProcess.WriteError: ("An error occurred when attempting to write "
                                  "to the process."),
            QProcess.ReadError: ("An error occurred when attempting to read "
                                 "from the process."),
            QProcess.UnknownError: "An unknown error occurred.",
        }
        # NOTE: Do not replace this with "raise CommandError" as it's
        # executed async.
        message.error(self._win_id,
                      "Error while calling editor: {}".format(messages[error]))
        self._cleanup()

    def edit(self, text):
        """Edit a given text.

        Args:
            text: The initial text to edit.
        """
        if self._text is not None:
            raise ValueError("Already editing a file!")
        self._text = text
        try:
            self._oshandle, self._filename = tempfile.mkstemp(text=True)
            if text:
                encoding = config.get('general', 'editor-encoding')
                with open(self._filename, 'w', encoding=encoding) as f:
                    f.write(text)
        except OSError as e:
            message.error(self._win_id, "Failed to create initial file: "
                                        "{}".format(e))
            return
        self._proc = QProcess(self)
        self._proc.finished.connect(self.on_proc_closed)
        self._proc.error.connect(self.on_proc_error)
        editor = config.get('general', 'editor')
        executable = editor[0]
        args = [self._filename if arg == '{}' else arg for arg in editor[1:]]
        log.procs.debug("Calling \"{}\" with args {}".format(executable, args))
        self._proc.start(executable, args)


# -*- coding: utf-8 -*-
# @Time    : 19-1-26 下午12:51
# @Author  : MaxCentaur
# @Email   : ambition_x@163.com
# @File    : copy_image.py
# @Software: PyCharm

import sys

def save_string_2_file(file_path, file_content):
    f = open(file_path, 'w')
    f.write(file_content)
    f.close()

def main():
    commands = sys.argv
    if len(commands) == 1:
        raise RuntimeError("在python xx.py 后面加上文件夹")
    folder, label, num = commands[1], commands[2], commands[3]
    print("target folder : {}".format(folder))
    print("target label : {}".format(label))
    print("target num : {}".format(num))
    import os
    image_paths = [os.path.join(folder, str(i) + '.jpg') for i in range(len(os.listdir(folder)))]
    labels = open(label, 'r').read().strip().split('#')
    print(len(labels))
    new_list = list()
    for i in range(len(image_paths)):
        new_list.append((image_paths[i], labels[i]))
    import random
    random.shuffle(new_list)
    num = int(num)
    if num <= len(new_list):
        new_list = new_list[:num]
    else:
        raise RuntimeError("input num bigger than num image num")
    target_folder = str(num) + '_' + folder
    new_label_path = str(num) + '_' + label
    if not os.path.exists(target_folder):
        os.makedirs(target_folder)
    target_labels = list()
    import shutil
    for i, (path, label) in enumerate(new_list):
        print('source path', path)
        print('target path', os.path.join(target_folder, str(i) + '.jpg'))
        shutil.copy(path, os.path.join(target_folder, str(i) + '.png'))
        target_labels.append(label)
        print("num {} is complete".format(str(i)))
    save_string_2_file(new_label_path, '#'.join(target_labels))

if __name__ == '__main__':
    main()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Gillett Hernandez
# @Date:   2016-07-14 17:06:40
# @Last Modified by:   Gillett Hernandez
# @Last Modified time: 2017-08-26 11:47:44
from euler_funcs import timed

class Coin:
    def __init__(self, value):
        self.value = value

    def __repr__(self):
        return "<Coin instance> with value %i" % self.value

def times_fits(coin, total):
    assert hasattr(coin, "value"), coin
    assert isinstance(coin.value, int), coin.value
    return (total-total%(coin.value))//coin.value

def combinations(total=200, coins=[200, 100, 50, 20, 10, 5, 2, 1]):
    coins_ = [Coin(value) for value in coins]
    if total == 0:
        return 1
    s = 0
    coin = coins_[0]
    tf = times_fits(coin, total)
    assert(tf*coin.value <= total)
    if not coin.value == 1:
        for n in reversed(range(0, tf+1)):
            v = total-n*coin.value
            if v == 0:
                s += 1
                continue
            s += combinations(total-n*coin.value, coins[1:])
    else:
            s += 1
    return s

@timed
def main():
    print(combinations())
    # 73682
    # print(combinations(500, [100, 50, 25, 10, 5, 1]))
    # 98411

if __name__ == '__main__':
    main()


 # -*- coding: utf-8 -*-
from datetime import datetime

from odoo import models, fields, api, _

class CustomerCreditLimitReportWizard(models.TransientModel):
    _name = 'credit.limit.report.wizard'
    _description = 'Customer Credit Limit Report'

    start_date = fields.Date(
        string="Start Date",
        required=True
    )
    end_date = fields.Date(
        string="End Date",
        required=True
    )

    def view_customer_credit_limit_report(self):

        domain = []

        domain.append(('invoice_date','>=',self.start_date))
        domain.append(('invoice_date','<=',self.end_date))

        all_records = self.env['credit.limit.report'].search(domain)

        return {
            'type': 'ir.actions.act_window',
            'name': ('Customer Credit Limit Report'),
            'res_model': 'credit.limit.report',
            'view_mode': 'tree,pivot',
            'domain' : [('id','in', all_records.ids)],
            'context': {'group_by': 'partner_id'}
        }


from flask import Blueprint, jsonify, request
from api.ocrs.helpers import get_table_structure
from api.ocrs.process_image import process_image_with_vision
from api.ocrs.process_invoice_v1 import process_invoice_v1
from api.ocrs.process_image_v4 import process_image_v4

import json
import time

from models.exam import Exams
from models.ocr_data import Ocrdata
from models.student import Student

from models.response import CustomResponse
from models.status import Status

import os

controllers = Blueprint('controllers', __name__)
workspace_dir       = '/home/ubuntu/workspace/output'
input_dir           = '/tmp/nginx'

@controllers.route('/check-ocr-data', methods=['POST'])
def check_ocr_data():
    body = request.get_json()
    if body['student_id'] is None or body['exam_id'] is None or body['ocr_data'] is None:
        res = CustomResponse(
            Status.ERR_GLOBAL_MISSING_PARAMETERS.value, None)
        return res.getres(), Status.ERR_GLOBAL_MISSING_PARAMETERS.value['http']['status']
    student_fromdb = Student.objects(student_id=body['student_id'])
    exam_fromdb = Exams.objects(exam_id=body['exam_id'])
    if not (student_fromdb is not None and len(student_fromdb) > 0):
        res = CustomResponse(
            Status.WRONG_STUDENT_CODE.value, None)
        return res.getres()
    elif not (exam_fromdb is not None and len(exam_fromdb) > 0):
        res = CustomResponse(
            Status.WRONG_CODE.value, None)
        return res.getres()
    else:
        try:
            exam_obj = json.loads(exam_fromdb.to_json())
            student_obj = json.loads(student_fromdb.to_json())
            map_obj = conver_list_to_map(exam_obj[0]['data'])
            ocr_data = body['ocr_data']
            table_data = ocr_data['response'][1]['data']
            students_data = ocr_data['response'][0]['data']
            student_obj[0]['exam_id'] = body['exam_id']
            ocr_data['metadata'] = student_obj[0]
            if len(ocr_data['response'][0]['data']) > len(ocr_data['response'][1]['data']):
                table_data = ocr_data['response'][0]['data']
                students_data = ocr_data['response'][1]['data']
            for marks_data in table_data:
                key = str(marks_data['col'])+str(marks_data['row'])
                if key in map_obj:
                    marks_data['text'] = map_obj[key]
                elif str(marks_data['col']) == '0' or str(marks_data['col']) == '1' or str(marks_data['col']) == '2':
                    marks_data['text'] = ''
            if 'exam_date' in exam_obj[0]:
                for student_data in students_data:
                    if student_data['col'] == 1 and student_data['row'] == 3:
                        student_data['text'] = exam_obj[0]['exam_date']

            res = CustomResponse(Status.SUCCESS.value, ocr_data)
            return res.getres()
        except Exception as e:
            res = CustomResponse(Status.ERR_GLOBAL_SYSTEM.value, ocr_data)
            return res.getres(), Status.ERR_GLOBAL_SYSTEM.value['http']['status']

def conver_list_to_map(data):
    map_obj = {}
    for d in data:
        map_obj[str(d['col'])+str(d['row'])] = d['text']
    return map_obj

@controllers.route('/save-student-masterdata', methods=['POST'])
def save_student_masterdata():
    body = request.get_json()
    if body['student'] is None or body['student']['student_id'] is None:
        res = CustomResponse(
            Status.ERR_GLOBAL_MISSING_PARAMETERS.value, None)
        return res.getres(), Status.ERR_GLOBAL_MISSING_PARAMETERS.value['http']['status']
    student_fromdb = Student.objects(student_id=body['student']['student_id'])
    if student_fromdb is not None and len(student_fromdb) > 0:
        res = CustomResponse(
            Status.USER_ALREADY_EXISTS.value, None)
        return res.getres(), Status.USER_ALREADY_EXISTS.value['http']['status']
    else:
        student = Student(student_id=body['student']['student_id'],student_name=body['student']['student_name'])
        student.save()
    res = CustomResponse(Status.SUCCESS.value, None)
    return res.getres()

@controllers.route('/save-ocr-data', methods=['POST'])
def save_ocr_data():
    body = request.get_json()
    if body['ocr_data'] is None:
        res = CustomResponse(
            Status.ERR_GLOBAL_MISSING_PARAMETERS.value, None)
        return res.getres(), Status.ERR_GLOBAL_MISSING_PARAMETERS.value['http']['status']
    ocr_data = Ocrdata(created_on=str(int(time.time())), data=body['ocr_data']['response'])
    ocr_data.save()
    res = CustomResponse(Status.SUCCESS.value, None)
    return res.getres()

@controllers.route('/save-exam-masterdata', methods=['POST'])
def save_exam_masterdata():
    body = request.get_json()
    if body['exam'] is None or body['exam']['exam_id'] is None or body['exam']['data'] is None:
        res = CustomResponse(
            Status.ERR_GLOBAL_MISSING_PARAMETERS.value, None)
        return res.getres(), Status.ERR_GLOBAL_MISSING_PARAMETERS.value['http']['status']
    exam_fromdb = Exams.objects(exam_id=body['exam']['exam_id'])
    if exam_fromdb is not None and len(exam_fromdb) > 0:
        exam_fromdb.update(set__data=body['exam']['data'])
    else:
        exam = Exams(exam_id=body['exam']['exam_id'],data=body['exam']['data'],exam_date=body['exam']['exam_date'])
        exam.save()
    res = CustomResponse(Status.SUCCESS.value, None)
    return res.getres()

@controllers.route('/process', methods=['POST'])
def process_ocr():
    json_data           = request.get_json(force=True)
    filename            = json_data['filename']
    absolute_filepath   = os.path.join(input_dir, filename)

    print('received file [%s] for processing is present at [%s]' % (filename, absolute_filepath))
    return process_image_v4(absolute_filepath, workspace_dir)

@controllers.route('/invoice', methods=['POST'])
def process_invoice_ocr():
    json_data           = request.get_json(force=True)
    filename            = json_data['filename']
    absolute_filepath   = os.path.join(input_dir, filename)

    print('received file [%s] for processing is present at [%s]' % (filename, absolute_filepath))
    return process_invoice_v1(absolute_filepath, workspace_dir)


def cashpoint(truepin,balance):
    if checkPIN(truepin):
        print("\nPlease choose your transaction type")
        print("   - to request a balance  - enter 1")
        print("   - to make a withdrawal  - enter 2")
        print("   - to top-up a telephone - enter 3")
        transactionType = input('\nEnter your choice: ')
        if (transactionType == '1'):
            print("Your balance is", balance, 'GBP')
            print("Thank you for using this service.")
            return "balance-request"
        elif transactionType == '2':
            return withdrawal(balance)
        elif transactionType == '3':
            return mobileTopUp(balance)
        else:
            print("Error: transaction type not recognised.")
            return "transaction-error"
    else:
        print("\nError: PIN authorisation failed - exiting.")
        return "PIN-error"

def checkPIN_once(truepin):
    attempt = input('Please enter your PIN: ')
    if attempt == truepin:
        return True
    else:
        print("PIN incorrect")
        return False

def checkPIN(truepin):
    if checkPIN_once(truepin):
        return True
    print("\nPlease try again (2nd attempt).")
    if checkPIN_once(truepin):
        return True
    print("\nPlease try again (final attempt).")
    if checkPIN_once(truepin):
        return True
    return False

def withdrawal(balance):
    maxWithdrawalAmount = 100.00
    print("Withdrawal amount must be a multiple of 10 pounds.")
    amount = float(input('Please enter your withdrawal amount: '))
    if amount > maxWithdrawalAmount:
        print("Amount exceeds maximum permitted withdrawal amount")
        print("Request refused")
        return "withdrawal-request:refused"
    elif amount > balance:
        print("Amount exceeds available funds")
        print("Request refused")
        return "withdrawal-request:refused"
    elif multpleOfTen(amount):
        print("Please take your cash.")
        print("Your new balance is", balance - amount, 'GBP')
        return ("withdrawal-request",amount)
    else:
        print("Amount is not a multiple of 10")
        print("Request refused")
        return "withdrawal-request:refused"

def multpleOfTen(amount):
    return amount == int(amount / 10.0) * 10

def mobileTopUp(balance):
    maxTopUp = 100.00
    print("Please enter the number of the mobile phone you wish to top-up: ",)
    number1 = input()
    print("Please RE-enter the number of the phone: ",)
    number2 = input()
    if number1 == number2:
        print("Top-up amount must be a multiple of 10 pounds.")
        amount = float(input('Please enter your top-up amount: '))
        if amount > maxTopUp:
            print("Amount exceeds maximum permitted top-up")
            print("Request refused")
            return "top-up-request:refused"
        elif amount > balance:
            print("Amount exceeds available funds")
            print("Request refused")
            return "top-up-request:refused"
        elif multpleOfTen(amount):
            print("Transaction authorised.")
            print("Your new account balance is", balance - amount, 'GBP')
            return ("top-up-request",amount)
        else:
            print("Amount is not a multiple of 10")
            print("Request refused")
            return "top-up-request:refused"
    else:
        print("Error: the two numbers entered are different.")
        print("Transaction cancelled.")
        return "top-up-request:refused"


import pandas as pd
from sklearn.linear_model import LinearRegression
import numpy as np
import matplotlib.pyplot as plt

pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)

hd = pd.DataFrame(data=pd.read_csv("house_data.csv"))
bedroom_column = np.array([])
bathroom_column = np.array([])
sqrft_column = np.array([])
price_column = np.array([])

for i in range(len(hd)):
    price_column = np.append(price_column, hd.iloc[i, 2])
    bedroom_column = np.append(bedroom_column, hd.iloc[i, 3])
    bathroom_column = np.append(bathroom_column, hd.iloc[i, 4])
    sqrft_column = np.append(sqrft_column, hd.iloc[i, 5])

stacked = np.vstack((bedroom_column, bathroom_column, sqrft_column)).T

model = LinearRegression()

model = model.fit(stacked, price_column)

# print(model.score(stacked, price_column))

price_column_pred = model.predict(stacked)

# example_predict = model.predict((3, 1, 1180))
# print(example_predict)

def pred_formula(x1, x2, x3):
    result = model.intercept_ + model.coef_[0]*x1 + model.coef_[1]*x2 + model.coef_[2]*x3
    return result

print(pred_formula(3, 1, 1180))
# plt.scatter(stacked[:, 0], stacked[:, 1], stacked[:, 2], price_column)
plt.plot(stacked[:, 0], stacked[:, 1], stacked[:, 2], price_column_pred, "o")
plt.show()
# print(str(len(stacked)) + "   " + str(len(price_column)))


import smart_imports

smart_imports.all()

def create_test_map_info():
    from . import prototypes
    storage.map_info.set_item(prototypes.MapInfoPrototype.create(turn_number=0,
                                                                 width=conf.settings.WIDTH,
                                                                 height=conf.settings.HEIGHT,
                                                                 terrain=[[relations.TERRAIN.PLANE_GREENWOOD for j in range(conf.settings.WIDTH)] for i in range(conf.settings.HEIGHT)],  # pylint: disable=W0612
                                                                 world=prototypes.WorldInfoPrototype.create(w=conf.settings.WIDTH, h=conf.settings.HEIGHT)))

_TERRAIN_LINGUISTICS_CACHE = {}

def get_terrain_linguistics_restrictions(terrain):

    if _TERRAIN_LINGUISTICS_CACHE:
        return _TERRAIN_LINGUISTICS_CACHE[terrain]

    for terrain_record in relations.TERRAIN.records:
        _TERRAIN_LINGUISTICS_CACHE[terrain_record] = (linguistics_restrictions.get(terrain_record),
                                                      linguistics_restrictions.get(terrain_record.meta_terrain),
                                                      linguistics_restrictions.get(terrain_record.meta_height),
                                                      linguistics_restrictions.get(terrain_record.meta_vegetation))

    return _TERRAIN_LINGUISTICS_CACHE[terrain]

def region_url(turn=None):
    arguments = {'api_version': conf.settings.REGION_API_VERSION,
                 'api_client': django_settings.API_CLIENT}

    if turn is not None:
        arguments['turn'] = turn

    return dext_urls.url('game:map:api-region', **arguments)

def region_versions_url():
    arguments = {'api_version': conf.settings.REGION_API_VERSION,
                 'api_client': django_settings.API_CLIENT}

    return dext_urls.url('game:map:api-region-versions', **arguments)


from .Config import Config

# configuration class for instance manager

class AWSConfig(Config):
    # passing config dictionary to init
    #  used as parameter to instance manager init.
    def __init__(self, **kargs):
        self.session_param={
            "region_name":kargs["region"],
            "aws_access_key_id":kargs["aws_access_key_id"],
            "aws_secret_access_key":kargs["aws_secret_access_key"]
        }
        self.ami = kargs["ami"]
        self.securityGroups = kargs["security_groups"]
        self.zone = kargs["zone"]
        self.instType = kargs["InstType"]
        self.role = kargs["role"]
        self.s3_role = kargs["s3_role"]
        self.s3bucket = kargs["s3_bucket"]
        self.KeyName = kargs["pemFilePath"].split("/")[-1].split(".")[0]


#Merosha Govender(GVNMER006)
#Assignment 5

def get_integer(x):
    value =0
    if x == 'n':
        n=input("Enter n:\n")
        while not n.isdigit():
            n=input("Enter n:\n")
        num=eval(n)
    elif x == 'k':
        k=input("Enter k:\n")
        while not k.isdigit():
            k=input("Enter n:\n")
        num=eval(k)
    return num

def calc_factorial(x):

    factorial=1

    for i in range(1, x+1):
        factorial = factorial*i
    return factorial


# Authors: Joan Massich <mailsik@gmail.com>
#          Alexandre Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD (3-clause)
import os.path as op
import numpy as np

from functools import partial

from .montage import make_dig_montage
from ..transforms import _sph_to_cart
from . import __file__ as _CHANNELS_INIT_FILE

MONTAGE_PATH = op.join(op.dirname(_CHANNELS_INIT_FILE), 'data', 'montages')

HEAD_SIZE_DEFAULT = 0.085  # in [m]

def _egi_256():
    fname = op.join(MONTAGE_PATH, 'EGI_256.csd')
    options = dict(
        comments='//',
        unpack=True,
        dtype={
            'names': ('Label', 'Theta', 'Phi', 'Radius', 'X', 'Y', 'Z',
                      'off sphere surface'),
            'formats': (object, 'f4', 'f4', 'f4', 'f4', 'f4', 'f4', 'f4')
        }
    )

    ch_names, _, _, _, xs, ys, zs, _ = np.loadtxt(fname, **options)
    pos = np.stack([xs, ys, zs], axis=-1)

    # Fix pos to match Montage code
    # pos -= np.mean(pos, axis=0)
    pos = HEAD_SIZE_DEFAULT * (pos / np.linalg.norm(pos, axis=1).mean())

    return make_dig_montage(
        ch_pos=dict(zip(ch_names, pos)),
        coord_frame='head',
    )

def _easycap(basename):
    fname = op.join(MONTAGE_PATH, basename)
    options = dict(
        skiprows=1,
        unpack=True,
        dtype={'names': ('Site', 'Theta', 'Phi'),
               'formats': (object, 'i4', 'i4')},
    )
    ch_names, theta, phi = np.loadtxt(fname, **options)

    radii = np.full_like(phi, 1)  # XXX: HEAD_SIZE_DEFAULT should work
    pos = _sph_to_cart(np.stack(
        [radii, np.deg2rad(phi), np.deg2rad(theta)],
        axis=-1,
    ))

    # scale up to realistic head radius (8.5cm == 85mm):
    pos *= HEAD_SIZE_DEFAULT  # XXXX: this should be done through radii

    return make_dig_montage(
        ch_pos=dict(zip(ch_names, pos)),
        coord_frame='head',
    )

def _hydrocel(basename, fid_names=('FidNz', 'FidT9', 'FidT10')):
    fname = op.join(MONTAGE_PATH, basename)
    options = dict(
        unpack=True,
        dtype={'names': ('ch_names', 'x', 'y', 'z'),
               'formats': (object, 'f4', 'f4', 'f4')},
    )
    ch_names, xs, ys, zs = np.loadtxt(fname, **options)

    pos = np.stack([xs, ys, zs], axis=-1) * 0.01
    ch_pos = dict(zip(ch_names, pos))
    _ = [ch_pos.pop(n, None) for n in fid_names]

    return make_dig_montage(ch_pos=ch_pos, coord_frame='head')

def _biosemi(basename, fid_names=('Nz', 'LPA', 'RPA')):
    fname = op.join(MONTAGE_PATH, basename)
    options = dict(
        skiprows=1,
        unpack=True,
        dtype={'names': ('Site', 'Theta', 'Phi'),
               'formats': (object, 'i4', 'i4')},
    )
    ch_names, theta, phi = np.loadtxt(fname, **options)

    radii = np.full_like(phi, 1)  # XXX: HEAD_SIZE_DEFAULT should work
    pos = _sph_to_cart(np.stack(
        [radii, np.deg2rad(phi), np.deg2rad(theta)],
        axis=-1,
    ))

    # scale up to realistic head radius (8.5cm == 85mm):
    pos *= HEAD_SIZE_DEFAULT  # XXXX: this should be done through radii

    ch_pos = dict(zip(ch_names, pos))
    _ = [ch_pos.pop(n, None) for n in fid_names]

    return make_dig_montage(ch_pos=ch_pos, coord_frame='head')

def _mgh_or_standard(basename, fid_names=('Nz', 'LPA', 'RPA')):
    fname = op.join(MONTAGE_PATH, basename)

    ch_names_, pos = [], []
    with open(fname) as fid:
        # Default units are meters
        for line in fid:
            if 'UnitPosition' in line:
                units = line.split()[1]
                scale_factor = dict(m=1., mm=1e-3)[units]
                break
        else:
            raise RuntimeError('Could not detect units in file %s' % fname)
        for line in fid:
            if 'Positions\n' in line:
                break
        pos = []
        for line in fid:
            if 'Labels\n' in line:
                break
            pos.append(list(map(float, line.split())))
        for line in fid:
            if not line or not set(line) - {' '}:
                break
            ch_names_.append(line.strip(' ').strip('\n'))

    pos = np.array(pos) * scale_factor

    ch_pos = dict(zip(ch_names_, pos))
    _ = [ch_pos.pop(n, None) for n in fid_names]

    return make_dig_montage(ch_pos=ch_pos, coord_frame='head')

standard_montage_look_up_table = {
    'EGI_256': _egi_256,

    'easycap-M1': partial(_easycap, basename='easycap-M1.txt'),
    'easycap-M10': partial(_easycap, basename='easycap-M1.txt'),

    'GSN-HydroCel-128': partial(_hydrocel, basename='GSN-HydroCel-128.sfp'),
    'GSN-HydroCel-129': partial(_hydrocel, basename='GSN-HydroCel-129.sfp'),
    'GSN-HydroCel-256': partial(_hydrocel, basename='GSN-HydroCel-256.sfp'),
    'GSN-HydroCel-257': partial(_hydrocel, basename='GSN-HydroCel-257.sfp'),
    'GSN-HydroCel-32': partial(_hydrocel, basename='GSN-HydroCel-32.sfp'),
    'GSN-HydroCel-64_1.0': partial(_hydrocel,
                                   basename='GSN-HydroCel-64_1.0.sfp'),
    'GSN-HydroCel-65_1.0': partial(_hydrocel,
                                   basename='GSN-HydroCel-65_1.0.sfp'),

    'biosemi128': partial(_biosemi, basename='biosemi128.txt'),
    'biosemi16': partial(_biosemi, basename='biosemi16.txt'),
    'biosemi160': partial(_biosemi, basename='biosemi160.txt'),
    'biosemi256': partial(_biosemi, basename='biosemi256.txt'),
    'biosemi32': partial(_biosemi, basename='biosemi32.txt'),
    'biosemi64': partial(_biosemi, basename='biosemi64.txt'),

    'mgh60': partial(_mgh_or_standard, basename='mgh60.elc'),
    'mgh70': partial(_mgh_or_standard, basename='mgh70.elc'),
    'standard_1005': partial(_mgh_or_standard,
                             basename='standard_1005.elc'),
    'standard_1020': partial(_mgh_or_standard,
                             basename='standard_1020.elc'),
    'standard_alphabetic': partial(_mgh_or_standard,
                                   basename='standard_alphabetic.elc'),
    'standard_postfixed': partial(_mgh_or_standard,
                                  basename='standard_postfixed.elc'),
    'standard_prefixed': partial(_mgh_or_standard,
                                 basename='standard_prefixed.elc'),
    'standard_primed': partial(_mgh_or_standard,
                               basename='standard_primed.elc'),
}


import random

from ..suit.suit import Suit
from .factoryfunction3 import factoryfunction as card

club, diamond, heart, spade = (
    Suit('Club', '♣'),
    Suit('Diamond', '♦'),
    Suit('Heart', '♥'),
    Suit('Spade', '♠'),
)

# Instead of using the built in list class as follow to create a deck,
# we can wrap the behavior inside a class Deck as show below:
# deck = [
#     CardFactory().rank(rank).suit(suit)
#     for rank in range(1, 14)
#     for suit in (club, diamond, heart, spade)
# ]

# random.shuffle(deck)

# hand = [deck.pop(), deck.pop()]

# Composite objects are like containers
# This is an example of wrapped composite object
# This wrapper around a list leads to a bit of repetition
# since we have to define pop in the class when list already implement pop
# by default
class Deck:
    def __init__(self):
        self._cards = [
            card(rank, suit)
            for rank in range(1, 14)
            for suit in (club, diamond, heart, spade)
        ]
        random.shuffle(self._cards)

    def pop(self):
        return self._cards.pop()

d = Deck()
hand = [d.pop(), d.pop()]


from requests import get, post
from yaml import load, FullLoader, dump
from re import findall, search
from bs4 import BeautifulSoup

yaml = get("https://www.w3schools.io/file/yaml-sample-example/")
yaml_tags = BeautifulSoup(yaml.text, "html5lib")

exemplo = yaml_tags.find_all("pre", attrs = {"class" : "chroma"})
exemplos = [pre.text for pre in exemplo]

comentarios = yaml_tags.find_all("span", attrs = {"class" : "c"})
comentarios = [span.text for span in comentarios]
for cada in range(len(comentarios)):
    comentario = " ".join(findall(r"\w+", comentarios[cada]))
    print(comentario)

with open("novo_yaml.yml", "w") as file:
    dump(exemplos, file)

with open("novo_yaml.yml") as file:
    yaml_file = load(file, Loader=FullLoader)
print(yaml_file)