"""
Code for serializing datasets (which takes very long and a lot of memory)
into pickle-format. The point is to do this once, and then let other
tests use much less memory and time.

Run this once for all your experiments (unless you want to randomize the
data again).
"""

import pickle
import random
import load_data

CRITEO_FORMAT = load_data.DATA_FORMAT
# CRITEO_FORMAT['file_name'] = 'criteo_100k.csv'  # This is for testing.
CRITEO_FORMAT['file_name'] = 'criteo-uplift-v2.1.csv'  # This is the actual experiment data.

HILLSTROM_FORMAT = load_data.HILLSTROM_FORMAT_1
# Already contains filename.

DATASETS = [HILLSTROM_FORMAT, CRITEO_FORMAT]

def create_pickles(path='./datasets/'):
    """
    Function for pickling datasets.

    Args:
    path (str): Path of datasets. Actual file names are
     specified in DATASETS-list above.
    """
    for dataset in DATASETS:
        seed = random.randrange(2**32 - 1)
        dataset['random_seed'] = seed
        # Load data and do preprocessing:
        data = load_data.DatasetCollection(path + dataset['file_name'],
                                           dataset)
        # Write as pickle to disk:
        with open(path + dataset['file_name'] + str(seed) + '.pickle',
                  'wb') as handle:
            pickle.dump(data, handle)

def load_pickle(file_name, path='./datasets/'):
    """
    Function for loading pickled datasets.

    Args:
    file_name (str): Name of file
    path (str): Location of file
    """
    from load_data import DatasetCollection
    with open(path + file_name, 'rb') as handle:
        data = pickle.load(handle)
    return data

if __name__ == '__main__':
    # If main program,
    # create pickle-files.
    create_pickles()


import pytest
import requests
import json
from urllib.parse import urljoin
import logging

logging.basicConfig(format='%(levelname)-8s [%(asctime)s] %(message)-70s (%(filename)s:%(lineno)d)',
                    level=logging.DEBUG, filename='logs_headers.txt')
headers_valid = {'User-Agent': 'Random'}
headers_invalid = {'Host': 'ya.ru'}
testdata = [
    (True, headers_valid),
    (False, headers_invalid),
]

@pytest.mark.parametrize("response_success, headers", testdata)
def test_headers(response_success, headers):
    logging.info(f"------ Starting test with headers = {headers}, expecting response.ok == {response_success} ------")
    host = 'https://httpbin.org'
    endpoint = 'headers'
    final_url = urljoin(host, endpoint)
    response = requests.get(final_url, headers=headers)
    assert response.ok == response_success
    if response.ok:
        response_dict = json.loads(response.text)
        headers_from_response = response_dict['headers']
        for key in headers.keys():
            assert headers[key] == headers_from_response[key]


# -*- coding: utf-8 -*-
#	python 3.6 ile derlenirse daha iyi olur
#       Rıdvan Demirci
#               141044070
#
#
#
def compareScales (leftScaleList, rightScaleList):
	print (leftScaleList ,"-" , rightScaleList)
	result = sum(leftScaleList) - sum(rightScaleList)
	if result < 0:
		return 1
	elif result > 0:
		return -1
	else:
		return 0
def findRotten(listOfwalnut,size):	#logaritmik time da olması icin array size da girilmeli

	if(size == 1):
		return 0
	if(size % 2 == 0):		# cift ise direk yarirsi ile islemler yapar
		temp = compareScales(listOfwalnut[0:int(size/2)],listOfwalnut[int(size/2):]) # sol ve sag tarafın farkı alınır
		#print temp
		if(temp == 1):
			return findRotten(listOfwalnut[0:int(size/2)],int(size/2)) # sag taraf buyuk ise rotten sol taraftadir
		elif(temp == -1):
			return int(size/2) + findRotten(listOfwalnut[int(size/2):],int(size/2))
		else:
			return -1;
	else:
		temp = size/2
		tempSum = compareScales(listOfwalnut[0:int(temp)],listOfwalnut[int(temp+1):])
		if(tempSum == 0):			#sag ve sol esit ise ortadaki eleman en kucuktur
			if(listOfwalnut[int(temp)]==listOfwalnut[int(temp)-1]):
				return -1
			return int(temp)
		elif(tempSum == -1):
			return int(temp) + 1 + findRotten(listOfwalnut[int(temp+1):],int(temp))	#yaridan sonra
		else:
			return findRotten(listOfwalnut[0:int(temp)],int(temp))	#yaridan once

sample = [1,1,1,1,1,0.5,1,1,1]	#ornek
print (len(sample))
print ("index: ",findRotten(sample,len(sample)))	#drive kısmı


import os
import boto3
from botocore.exceptions import ClientError

# aws ses config
AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY")
AWS_REGION = os.getenv("AWS_REGION")

class Email:

    def __init__(self, sender, recipients=[]):
        self.client = boto3.client('ses',
                                   region_name=AWS_REGION,
                                   aws_access_key_id=AWS_ACCESS_KEY_ID,
                                   aws_secret_access_key=AWS_SECRET_ACCESS_KEY
                                   )
        self.sender = sender
        self.recipients = recipients

    def __body(self, body, is_html):
        content = ""
        if is_html:
            content = {
                'Html': {
                    'Charset': "UTF-8",
                    'Data': body,
                }
            }
        else:
            content = {'Text': {
                'Charset': "UTF-8",
                'Data': body,
            }}
        return content

    def send_mail(self, subject, body, is_html=False):
        body_json_content = self.__body(body, is_html)
        try:
            response = self.client.send_email(
                Source=self.sender,
                Destination={
                    'ToAddresses': self.recipients,
                },
                Message={
                    'Body': body_json_content,
                    'Subject': {
                        'Charset': "UTF-8",
                        'Data': subject,
                    }
                }
            )
        except ClientError as e:
            print(e.response['Error']['Message'])
        else:
            print("Email sent! Message ID:"),
            print(response['MessageId'])

email = Email("noreply@yourdomain.com", ["recipient1@gmail.com","recipient2@gmail.com"])
email.send_mail(subject="Subject", body="
Body
", is_html=True)


import torch

class Trainer:
    def __init__(self, model, loss):
        self.model = model
        self.loss = loss
        self.epoch = 0
        self.last_epoch_history = None

    def _reset_last_epoch_history(self):
        self.last_epoch_history = {
            'loss': 0.0,
            'src_metrics': {},
            'trg_metrics': {}
        }

    def train_on_batch(self, src_batch, trg_batch, opt):
        self.model.train()
        batch = self._merge_batches(src_batch, trg_batch)
        metadata = {'epoch': self.epoch, 'n_epochs': self.n_epochs}
        loss = self.loss(self.model, batch, **metadata)
        self.last_epoch_history['loss'] += loss

        opt.zero_grad()
        loss.backward()
        opt.step()

    def _merge_batches(self, src_batch, trg_batch):
        src_images, src_classes = src_batch
        trg_images, trg_classes = trg_batch
        batch = dict()
        batch['src_images'] = src_images
        batch['trg_images'] = trg_images
        batch['src_classes'] = src_classes
        batch['trg_classes'] = trg_classes
        return batch

    def fit(self, src_data, trg_data, n_epochs=1000, steps_per_epoch=100, val_freq=1,
            opt='adam', opt_kwargs=None, validation_data=None, metrics=None, callback=None):
        self.n_epochs = n_epochs

        if opt_kwargs is None:
            opt_kwargs = dict()

        if opt == 'adam':
            opt = torch.optim.Adam(self.model.parameters(), **opt_kwargs)
        else:
            raise NotImplementedError

        for self.epoch in range(self.epoch, n_epochs):
            self._reset_last_epoch_history()
            for step, (src_batch, trg_batch) in enumerate(zip(src_data, trg_data)):
                if step == steps_per_epoch:
                    break
                self.train_on_batch(src_batch, trg_batch, opt)

            if metrics is not None and self.epoch % val_freq == 0:
                src_val_data, trg_val_data = validation_data
                self.model.eval()
                if src_val_data is not None:
                    src_metrics = self.score(src_val_data, metrics)
                    self.last_epoch_history['src_metrics'] = src_metrics
                if trg_val_data is not None:
                    trg_metrics = self.score(trg_val_data, metrics)
                    self.last_epoch_history['trg_metrics'] = trg_metrics

            if callback is not None:
                self.last_epoch_history['loss'] /= steps_per_epoch
                callback(self.last_epoch_history, self.epoch, n_epochs)

    def score(self, data, metrics):
        for metric in metrics:
            metric.reset()

        data.reload_iterator()
        for images, true_classes in data:
            pred_classes = self.model.predict(images)
            for metric in metrics:
                metric(true_classes, pred_classes)
        return {metric.name: metric.score for metric in metrics}

    def predict(self, data):
        predictions = []
        for batch in data:
            predictions.append(self.model.predict(batch))
        return torch.cat(predictions)


# Giorgia Corrado (s1017255)
# Diego Garcia Cerdas (s1020485)

from pacman import agents, search, util
from typing import NamedTuple, FrozenSet
import exceptions
import ass2
import itertools

# State includes a vector with the current position and a list of remaining corners
CornerSearchState = NamedTuple('CornerSearchState', [('vector', util.Vector), ('corners', FrozenSet[util.Vector])])

class CornersSearchRepresentation(search.SearchRepresentation):
    def __init__(self, gstate):
        super().__init__(gstate)
        self.walls = gstate.walls
        self.start_position = gstate.pacman
        left, bottom = 1, 1
        right, top = gstate.shape - 2 * util.Vector.unit
        self.corners = frozenset([util.Vector(left, bottom),
                                  util.Vector(left, top),
                                  util.Vector(right, bottom),
                                  util.Vector(right, top)])

    @property
    def start(self):
        return CornerSearchState(self.start_position, self.corners)  # create a new starting CornerSearchState

    def is_goal(self, state):
        super().is_goal(state.vector)
        return not state.corners  # check if there is no remaining corner

    def successors(self, state):
        successors = []
        for move in util.Move.no_stop:  # for every possible move
            new_vector = state.vector + move.vector  # create a new vector
            if not self.walls[new_vector]:  # if new vector is not a wall
                new_corners = state.corners - {new_vector}  # remove a possible corner
                successor = (CornerSearchState(new_vector, new_corners), [move], 1)  # create successor state
                successors.append(successor)  # add successor to the list
        return successors

    def pathcost(self, path):
        return search.standard_pathcost(path, self.start_position, self.walls)

# Many choices are possible here, as long as they are admissible.
# Examples include the Manhattan distance to the closest corner, fastest corner, etc.
# It is also possible to use the costs of Manhattan paths from the player through
# all remaining corners, but admissibility must be ensured.
# An often-chosen but *inadmissible* heuristic is choosing a Manhattan path greedily.
# By trying all possible corner orders, we can ensure that there is no path
# with less cost than the returned heuristic value.
def corners_heuristic(state: tuple, representation: CornersSearchRepresentation) -> int:
    """
    Calculates the heuristic to the closest unvisited corner for a given position.

    :param state: (tuple) the vector of the position in question and a tuple of bools for the visited corners.
    :param representation: (CornersSearchRepresentation) the search representation.

    :returns: (int) the heuristic value to the closest corner.
    """
    position, visited = state
    corners = [c for c, vis in zip(representation.corners, visited) if not vis]
    return min(manhattan_path_cost((position,) + corner_path) for corner_path in itertools.permutations(corners))

# Again, many choices possible, as long as they are admissible
# and not prohibitively inefficient. This heuristic is the same
# as the corners heuristic above, but for the foods closest to each corner
# rather than the corners themselves.
def dots_heuristic(state: tuple, representation: CornersSearchRepresentation) -> int:
    """
    Calculates the heuristic to the foods closest to each corner.

    :param state: (tuple) the vector of the position in question and a tuple of bools for the visited corners.
    :param representation: (CornersSearchRepresentation) the search representation.

    :returns: (int) the heuristic value to the closest corner.
    """
    if state.dots:
        left, bottom = 1, 1
        right, top = representation.walls.shape - 2 * util.Vector.unit
        corners = frozenset([util.Vector(left, bottom), util.Vector(left, top),
                             util.Vector(right, bottom), util.Vector(right, top)])

        def closest_dot(corner):
            return min(state.dots, key=lambda dot: sum(abs(dot - corner)))

        closest_to_corners = {closest_dot(corner) for corner in corners}
        return min(manhattan_path_cost((state.vector,) + corner_path) for corner_path in itertools.permutations(closest_to_corners))
    else:
        return 0

def manhattan_path_cost(path: tuple) -> int:
    """
    Manhattan cost for a path

    :param path: (tuple) the path for which to calculate a cost

    :returns: (int) the cost
    """
    position = path[0]
    cost = 0
    for next_position in path[1:]:
        cost += util.manhattan(next_position, position)
        position = next_position
    return cost

class ClosestDotSearchAgent(agents.SearchAgent):
    def prepare(self, gstate):
        self.actions = []
        pacman = gstate.pacman
        while gstate.dots:
            next_segment = self.path_to_closest_dot(gstate)
            self.actions += next_segment
            for move in next_segment:
                if move not in gstate.legal_moves_vector(gstate.agents[self.id]):
                    raise Exception('path_to_closest_dot returned an illegal move: {}, {}'.format(move, gstate))
                gstate.apply_move(self.id, move)

        print(f'[ClosestDotSearchAgent] path found with length {len(self.actions)}'
              f' and pathcost {search.standard_pathcost(self.actions, pacman, gstate.walls)}')

    @staticmethod
    def path_to_closest_dot(gstate):
        representation = AnyDotSearchRepresentation(gstate)  # Create a new representation
        return ass2.uniformcost(representation)  # Use a uniform cost search

class AnyDotSearchRepresentation(search.PositionSearchRepresentation):
    def __init__(self, gstate):
        super().__init__(gstate)
        self.dots = gstate.dots

    def is_goal(self, state):
        super().is_goal(state)
        return state in self.dots.list()  # Pacman is currently in a dot position

class ApproximateSearchAgent(agents.SearchAgent):
    def prepare(self, gstate):
        pass

    def move(self, gstate):
        raise exceptions.EmptyBonusAssignmentError


import logging
import sys

from jinja2 import TemplateError

from kluctl.cli.utils import project_target_command_context
from kluctl.kluctl_project.kluctl_project import load_kluctl_project_from_args
from kluctl.kluctl_project.secrets import SecretsLoader
from kluctl.seal.deployment_sealer import DeploymentSealer
from kluctl.utils.exceptions import InvalidKluctlProjectConfig, CommandError
from kluctl.utils.jinja2_utils import render_dict_strs, print_template_error
from kluctl.utils.dict_utils import merge_dict, get_dict_value

logger = logging.getLogger(__name__)

def find_secrets_entry(kluctl_project, name):
    for e2 in get_dict_value(kluctl_project.config, "secretsConfig.secretSets", []):
        if name == e2["name"]:
            return e2
    raise InvalidKluctlProjectConfig("Secret Set with name %s was not found" % name)

def merge_deployment_vars(deployment, jinja_var):
    for d in deployment.get_children(True, True):
        merge_dict(d.jinja_vars, jinja_var, False)

def load_secrets(kluctl_project, target, secrets_loader, deployment):
    secrets = {}
    for e in get_dict_value(target, "sealingConfig.secretSets", []):
        secrets_entry = find_secrets_entry(kluctl_project, e)
        for source in secrets_entry.get("sources", []):
            rendered_source = render_dict_strs(source, deployment.jinja_vars)
            s = secrets_loader.load_secrets(rendered_source)
            merge_dict(secrets, s, False)

    merge_deployment_vars(deployment, {"secrets": secrets})

def seal_command_for_target(kwargs, kluctl_project, target, sealing_config, secrets_loader):
    logger.info("Sealing for target %s" % target["name"])

    # pass for_seal=True so that .sealme files are rendered as well
    with project_target_command_context(kwargs, kluctl_project, target, for_seal=True) as cmd_ctx:
        load_secrets(kluctl_project, target, secrets_loader, cmd_ctx.deployment)
        cmd_ctx.deployment_collection.render_deployments()

        s = DeploymentSealer(cmd_ctx.deployment, cmd_ctx.deployment_collection, cmd_ctx.cluster_vars,
                             cmd_ctx.kluctl_project.sealed_secrets_dir, kwargs["force_reseal"])
        s.seal_deployment()

def seal_command(obj, kwargs):
    with load_kluctl_project_from_args(kwargs) as kluctl_project:
        secrets_loader = SecretsLoader(kluctl_project, kwargs["secrets_dir"])

        base_targets = []
        for target in kluctl_project.targets:
            if kwargs["target"] is not None and kwargs["target"] != target["name"]:
                continue
            sealing_config = target.get("sealingConfig")
            if sealing_config is None:
                logger.warning("Target %s has no sealingConfig" % target["name"])
                continue

            dynamic_sealing = sealing_config.get("dynamicSealing", True)
            if not dynamic_sealing and "baseTarget" in target:
                target = target["baseTarget"]
                if any(target is x for x in base_targets):
                    # Skip this target as it was already sealed
                    continue
                base_targets.append(target)

            try:
                seal_command_for_target(kwargs, kluctl_project, target, sealing_config, secrets_loader)
            except TemplateError as e:
                print_template_error(e)
            except CommandError as e:
                print(e, file=sys.stderr)
            except Exception as e:
                logger.exception("Sealing for target %s failed. Error=%s" % (target["name"], str(e)))


""" A steady incompressible Navier-Stokes simulation class """
import firedrake as fe
import sapphire.simulation

inner, dot, grad, div, sym = \
        fe.inner, fe.dot, fe.grad, fe.div, fe.sym

def variational_form_residual(sim, solution):

    u, p = fe.split(solution)

    psi_u, psi_p = fe.TestFunctions(solution.function_space())

    mass = psi_p*div(u)

    momentum = dot(psi_u, grad(u)*u) - div(psi_u)*p + \
        2.*inner(sym(grad(psi_u)), sym(grad(u)))

    dx = fe.dx(degree = sim.quadrature_degree)

    return (mass + momentum)*dx

def element(cell, degree):

    return fe.MixedElement(
        fe.VectorElement("P", cell, degree + 1),
        fe.FiniteElement("P", cell, degree))

def strong_residual(sim, solution):

    u, p = solution

    r_u = grad(u)*u + grad(p) - 2.*div(sym(grad(u)))

    r_p = div(u)

    return r_u, r_p

class Simulation(sapphire.simulation.Simulation):

    def __init__(self, *args, mesh, element_degree, **kwargs):

        super().__init__(*args,
            mesh = mesh,
            element = element(
                cell = mesh.ufl_cell(), degree = element_degree),
            variational_form_residual = variational_form_residual,
            time_dependent = False,
            **kwargs)


#Lista de sandwich ordenados por los clientes
sandwich_orders = ['tuna','pastrani', 'chicken','pastrani','beef','pastrani']

#Sacar Pastrani del las ordenes
print("Deli has run out of pastrani")

while 'pastrani' in sandwich_orders:
    sandwich_orders.remove('pastrani')

finished_sandwiches = []

#Valida que los sandwiches esten listos
while sandwich_orders:
    orders = sandwich_orders.pop()
    finished_sandwiches.append(orders)
    print("I made your "+orders+" sandwich.")

#Imprime los sandwich terminados
print("\nList of sandwich finished:")
for sandwich in finished_sandwiches:
    print(sandwich)


# mic_filter.py
# Record from micrphone, filter signal, play output to speaker

import pyaudio
import struct
import math
import wave

from math import pi

def clip16( x ):
    # Clipping for 16 bits
    if x > 32767:
        x = 32767
    elif x < -32768:
        x = -32768
    else:
        x = x
    return (x)

WIDTH       = 2         # Number of bytes per sample
CHANNELS    = 1         # mono
RATE        = 16000     # Sampling rate (frames/second)
DURATION    = 10         # duration of processing (seconds)

N = DURATION * RATE     # N : Number of samples to process

# Set parameters of delay system
Gdp = 1.0           # direct-path gain
Gff = 0.8           # feed-forward gain
delay_sec = 0.5    # 50 milliseconds
# delay_sec = 0.02
delay_samples = int( RATE * delay_sec )

# Create a buffer to store past values. Initialize to zero.
BUFFER_LEN = delay_samples   # set the length of buffer
buffer = [ 0 for i in range(BUFFER_LEN) ]

p = pyaudio.PyAudio()

# Open audio stream
stream = p.open(
    format      = p.get_format_from_width(WIDTH),
    channels    = CHANNELS,
    rate        = RATE,
    input       = True,
    output      = True)

k = 0
print('* Start')

w = wave.open("C:\\Users\\hp\\Desktop\\22.wav","wb")
w.setnchannels(1)
w.setsampwidth(2)
w.setframerate(RATE)

for n in range(0, N):

    # Get one frame from audio input (microphone)
    # input_string = stream.read(1)
    # If you get run-time time input overflow errors, try:
    input_string = stream.read(1, exception_on_overflow = False)

    # Convert binary string to tuple of numbers
    input_tuple = struct.unpack('h', input_string)

    # Convert one-element tuple to number
    input_value = input_tuple[0]

    # Compute output value
    output_value = int(clip16(Gdp * input_value + Gff * buffer[k]))    # Number

        # Update buffer
    buffer[k] = input_value

    # Increment buffer index
    k = k + 1
    if k >= BUFFER_LEN:
        # The index has reached the end of the buffer. Circle the index back to the front.
        k = 0

    # Convert output value to binary string
    output_string = struct.pack('h', int(clip16(output_value)))

    # Write binary string to audio stream
    stream.write(output_string)

    w.writeframes(output_string)

print('* Finished')

stream.stop_stream()
stream.close()
w.close()
p.terminate()


#!/usr/bin/python3

"""
Function that divides all elements of a matrix.
"""

def matrix_divided(matrix, div):

    """
    matrix must be a list of lists of integers or floats
    """
    if type(matrix) is not list:
        raise TypeError("matrix must be a matrix (list of lists) " +
                        "of integers/floats")
    if type(div) is not int and type(div) is not float:
        raise TypeError("div must be a number")
    if div == 0:
        raise ZeroDivisionError("division by zero")

    for row in range(0, len(matrix)):
        if len(matrix[0]) != len(matrix[row]):
            raise TypeError("Each row of the matrix must have the same size")

    new_matrix = []
    for position in range(len(matrix)):
        new_matrix.append([])
        for nbr in matrix[position]:
            new_matrix[position].append(round((nbr / div), 2))
    return new_matrix


# import necessary packages
from pyimagesearch.transform import four_point_transform
from skimage.filters import threshold_local
import numpy as np
import argparse
import os, sys
import cv2
import imutils
from hand_writing import pred_matrix

def add_second_image(origin, sec_image):
    x_offset = origin.shape[1] - 20
    y_offset = origin.shape[0] - 20
    origin[y_offset - sec_image.shape[0]:y_offset, x_offset - sec_image.shape[1]:x_offset] = sec_image

def contour_detect(edge):
    # find the contours in the edged image, keeping only the
    # largest ones, and initialize the screen contour
    cnts = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
    cnts = imutils.grab_contours(cnts)
    cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:5]
    screenCnt = None
    h,w = edge.shape[0], edge.shape[1]
    min_square_size = h * w / 3
    print('height: ' + str(h) + ' width = ' + str(w))
    print('min_square= ' + str(min_square_size))

    # loop over the contours
    for c in cnts:
        # approximate the contour
        peri = cv2.arcLength(c, True)
        approx = cv2.approxPolyDP(c, 0.02 * peri, True)
        area = cv2.contourArea(c)
        area = np.int(area)
        print('contour_detect area = ' + str(area))
        print('approx = ' + str(len(approx)))

        # if our approximated contour has four points, then we
        # can assume that we have found our screen
        if len(approx) == 4 and (area > min_square_size):
            screenCnt = approx
            print(area)
            #cv2.drawContours(edge, [screenCnt], -1, (255, 255, 0), 2)
            #cv2.imshow('origin', edge)
            #cv2.waitKey()
            break
    print('final result: ')
    print('contour_detect area = ' + str(area))
    print('approx = ' + str(len(approx)))
    return screenCnt

def edge_detect(image):
    # convert the image to grayscale, blur it, and find edges
    # in the image
    #gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
    #gray = cv2.bilateralFilter(gray, 11, 17, 17)
    gray = cv2.GaussianBlur(gray, (5, 5), 0)
    edged = cv2.Canny(gray, 75, 200)

    return edged

def text_area_detect(img):
    #rgb = cv2.pyrDown(img)
    #rgb = img
    small = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    locs = []

    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
    grad = cv2.morphologyEx(small, cv2.MORPH_GRADIENT, kernel)

    _, bw = cv2.threshold(grad, 0.0, 255.0, cv2.THRESH_BINARY | cv2.THRESH_OTSU)

    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 1))
    connected = cv2.morphologyEx(bw, cv2.MORPH_CLOSE, kernel)
    # using RETR_EXTERNAL instead of RETR_CCOMP
    contours, hierarchy = cv2.findContours(connected.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    #For opencv 3+ comment the previous line and uncomment the following line
    #_, contours, hierarchy = cv2.findContours(connected.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

    mask = np.zeros(bw.shape, dtype=np.uint8)

    for idx in range(len(contours)):
        x, y, w, h = cv2.boundingRect(contours[idx])
        # compute the bounding box of the contour, then use the
        # bounding box coordinates to derive the aspect ratio
        ar = w / float(h)

        # since credit cards used a fixed size fonts with 4 groups
        # of 4 digits, we can prune potential contours based on the
        # aspect ratio
        if ar > 2.5 and ar < 4.0:
            # contours can further be pruned on minimum/maximum width
            # and height
            print(ar)
            print('w is ' + str(w) + ' and height is ' + str(h))
            if (w > 90 and w < 100) and (h > 28 and h < 35):
                locs.append((x, y, w, h))
                #cv2.rectangle(img, (x, y), (x+w-1, y+h-1), (0, 255, 0), 2)
                #roi = img[y:y+h, x:x+w]
                #cv2.imshow(str(idx), roi)

    return locs

def sort_contours(cnts, method="left-to-right"):
    # initialize the reverse flag and sort index
    reverse = False
    i = 0

    # handle if we need to sort in reverse
    if method == "right-to-left" or method == "bottom-to-top":
        reverse = True

    # handle if we are sorting against the y-coordinate rather than
    # the x-coordinate of the bounding box
    if method == "top-to-bottom" or method == "bottom-to-top":
        i = 1

    # construct the list of bounding boxes and sort them from top to
    # bottom
    boundingBoxes = [cv2.boundingRect(c) for c in cnts]
    (cnts, boundingBoxes) = zip(*sorted(zip(cnts, boundingBoxes),
    key=lambda b:b[1][i], reverse=reverse))

    # return the list of sorted contours and bounding boxes
    return (cnts, boundingBoxes)

def extract_text_images(gray, locs):
    # initialize the list of group digits
    rois = []
    pad = 5
    for (i, (gX, gY, gW, gH)) in enumerate(locs):
        # extract the group ROI of 4 digits from the grayscale image,
        # then apply thresholding to segment the digits from the
        # background of the credit card
        group = gray[gY - 5:gY + gH + 5, gX - 5:gX + gW + 5]
        #group = cv2.threshold(group, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
        group = cv2.threshold(group, 127, 255, cv2.THRESH_BINARY_INV)[1]

        # detect the contours of each individual digit in the group,
        # then sort the digit contours from left to right
        digitCnts = cv2.findContours(group.copy(), cv2.RETR_EXTERNAL,
        	cv2.CHAIN_APPROX_SIMPLE)
        digitCnts = imutils.grab_contours(digitCnts)
        digitCnts = sort_contours(digitCnts,method="left-to-right")[0]
        # loop over the digit contours
        for cnt, c in enumerate(digitCnts):
            print(cv2.contourArea(c))
            # compute the bounding box of the individual digit, extract
            # the digit, and resize it to have the same fixed size as
            # the reference OCR-A images
            (x, y, w, h) = cv2.boundingRect(c)
            roi = group[y - pad :y + h + pad, x - pad:x + w + pad]
            #cv2.imshow(str(i) + '-' + str(cnt) + '-----.jpg', roi)
            roi = cv2.resize(roi.copy(), (28, 28))
            cv2.imshow(str(i) + '-' + str(cnt) + '-----.jpg', roi)
            rois.append(roi)

    return rois

"""For perspective transformation, you need a 3x3 transformation matrix. Straight lines will remain straight even after the transformation.
To find this transformation matrix, you need 4 points on the input image and corresponding points on the output image.
Among these 4 points, 3 of them should not be collinear. Then transformation matrix can be found by the function cv2.getPerspectiveTransform.
Then apply cv2.warpPerspective with this 3x3 transformation matrix."""
def draw_contour(contour, img):
    min_square_size = 987
    images = []
    area = cv2.contourArea(contour)
    rect = cv2.minAreaRect(screenCnt)
    # If the contour is not really small, or really big
    h,w = img.shape[0], img.shape[1]
    print('area == ' + str(area))
    if area > min_square_size and area < h*w-(2*(h+w)):
        # Get the four corners of the contour
        epsilon = .1 * cv2.arcLength(contour, True)
        approx = cv2.approxPolyDP(contour, epsilon, True)

        print("========================================================")

        # now that we have our screen contour, we need to determine
        # the top-left, top-right, bottom-right, and bottom-left
        # points so that we can later warp the image -- we'll start
        # by reshaping our contour to be our finals and initializing
        # our output rectangle in top-left, top-right, bottom-right,
        # and bottom-left order
        pts = screenCnt.reshape(4, 2)
        rect = np.zeros((4, 2), dtype = "float32")

        # the top-left point has the smallest sum whereas the
        # bottom-right has the largest sum
        s = pts.sum(axis = 1)
        rect[0] = pts[np.argmin(s)]
        rect[2] = pts[np.argmax(s)]

        # compute the difference between the points -- the top-right
        # will have the minumum difference and the bottom-left will
        # have the maximum difference
        diff = np.diff(pts, axis = 1)
        rect[1] = pts[np.argmin(diff)]
        rect[3] = pts[np.argmax(diff)]

        # now that we have our rectangle of points, let's compute
        # the width of our new image
        (tl, tr, br, bl) = rect
        widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2))
        widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2))

        # ...and now for the height of our new image
        heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2))
        heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2))

        # take the maximum of the width and height values to reach
        # our final dimensions
        maxWidth = max(int(widthA), int(widthB))
        maxHeight = max(int(heightA), int(heightB))

        # construct our destination points which will be used to
        # map the screen to a top-down, "birds eye" view
        dst = np.array([
        	[0, 0],
        	[maxWidth - 1, 0],
        	[maxWidth - 1, maxHeight - 1],
        	[0, maxHeight - 1]], dtype = "float32")

        # calculate the perspective transform matrix and warp
        # the perspective to grab the screen
        M = cv2.getPerspectiveTransform(rect, dst)
        warp = cv2.warpPerspective(frame, M, (maxWidth, maxHeight))

        #cv2.imshow('warp', warp)
        #cv2.waitKey()
        locs = text_area_detect(warp)

        print("========================================================")

        images.append(warp.copy())
    return images, locs

# Capture frame-by-frame
#frame = cv2.imread("./images/receipt.jpg")
# frame = cv2.imread("./images/credit_1.png")
# frame = cv2.imread("./images/credit_2.png")
frame = cv2.imread("./images/vcard.png")
#frame = cv2.imread("./images/credit.jpg")
frame = imutils.resize(frame, height=500)

# convert the image to grayscale, blur it, and find edges
# in the image
#gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
#gray = cv2.bilateralFilter(gray, 11, 17, 17)
#edged = cv2.Canny(gray, 0, 200)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
gray = cv2.GaussianBlur(gray, (5, 5), 0)
edged = cv2.Canny(gray, 75, 200)

cv2.imshow('edged', edged)
cv2.waitKey()

# find contours
screenCnt = contour_detect(edged)

if (screenCnt is not None):
    print('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>There is contour...')
    images, locs = draw_contour(screenCnt, frame)
    img_arr = []
    if(len(images) > 0):
        add_second_image(frame, images[0])
        gray = cv2.cvtColor(images[0], cv2.COLOR_BGR2GRAY)
        if(len(locs) > 0):
            rois = extract_text_images(gray, locs)
            if(len(rois) > 0):
                for i, roi in enumerate(rois):
                    h,w = roi.shape[0], roi.shape[1]
                    # print('height: ' + str(h) + ' width = ' + str(w))
                    img_arr.append(pred_matrix(roi , "../hand_writing/param/cnn_params.pkl")[0])
                    cv2.imshow(str(i) + '.jpg' , roi)
            cv2.waitKey()
            print("img_arr", img_arr)
else:
    print('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>There is no contour...')

# Display the resulting frame
cv2.imshow('origin', frame)

cv2.waitKey()

# When everything done, release the capture
cv2.destroyAllWindows()


###################################################################################
# Author: Ricardo Pereira
# Date: 06-06-2021
# Last Modified data: 09-07-2021
# Abstract: GSF2App: Training file
###################################################################################

import numpy as np
import time
import glob
import cv2
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import datasets, models, transforms
import torch.optim as optim
from torch.autograd import Variable
from torch.utils import data
import argparse
import torchsummary
import sys

from GSF2App_data import *
from GSF2App_network import *
from GSF2App_eval import *

def check_GPU():
	device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
	print ("\nDevice: " + str(device))
	return device

def training_gsf2app(trainloader, learning_rate, classes, cnn_model_path, gsf2app_model_path, n_epochs, training_stage):
	# Initializations
	device = check_GPU()

	if training_stage == 1:
		model = load_pre_trained_model(len(classes), training_stage, cnn_model_path)

	elif training_stage == 2:
		model = GSF2App(cnn_model_path, len(classes))

	model.to(device)

	criterion = nn.CrossEntropyLoss()
	optimizer = optim.Adam(model.parameters(), lr = learning_rate, weight_decay = 0.0005)
	#optimizer = optim.SGD(model.parameters(), lr = learning_rate, momentum =0.9, weight_decay = 0.0005)

	print("Training...")
	for epoch in range(n_epochs):
		for local_batch, data in enumerate(trainloader, 0):
			if training_stage == 1:
				images, labels = data
				images, labels = images.to(device), labels.to(device)
				outputs = model(images)

			elif training_stage == 2:
				images, sfv_data, labels = data
				images, sfv_data, labels = images.to(device), sfv_data.to(device), labels.to(device)
				outputs = model(images, sfv_data)

			optimizer.zero_grad()
			loss = criterion(outputs, labels)
			loss.backward()
			optimizer.step()

			# print loss per batch
			if local_batch == 0:
				print ('[%d, %5d] loss: %.3f' % (epoch + 1, local_batch + 1,  loss.item()))

	# Save the model
	if training_stage == 1:
		torch.save(model.state_dict(), cnn_model_path)
		print('\nGSF2App\'s learning stage ' + str(training_stage) + ' was successfully trained!')
		print('Model saved in: ' + cnn_model_path)
	elif training_stage == 2:
		torch.save(model.state_dict(), gsf2app_model_path)
		print('\nGSF2App\'s learning stage ' + str(training_stage) + ' was successfully trained!')
		print('Model saved in: ' + gsf2app_model_path)

if __name__ == '__main__':
	print("PyTorch version = {}".format(torch.__version__))

	parser = argparse.ArgumentParser()
	parser.add_argument("--stage_1_n_epochs", type = int, default=1, help="stage 1 number of epochs") # 75
	parser.add_argument("--stage_1_lr", type=float, default=0.0001, help="stage 1 learning rate")
	parser.add_argument("--stage_2_n_epochs", type = int, default=1, help="stage 2 number of epochs") # 25
	parser.add_argument("--stage_2_lr", type=float, default=0.0001, help="stage 2 learning rate")
	parser.add_argument("--batch_size", type=int, default=32, help="size of each image batch")
	parser.add_argument("--dataset", type=str, default="nyu", help="dataset") #nyu or sun
	opt = parser.parse_args()
	print(opt)

	# --------------- Load Dataset --------------- #
	print("\n# ----- " + opt.dataset + " Dataset ----- #")

	X_train_datapath= os.path.join('folder_data_path')
	X_test_datapath= os.path.join('folder_data_path')

	scene_classes = open(os.path.join('folder_path','file.names'), "r").read().split("\n")[:-1]
	print("Number of classes: " + str(len(scene_classes)))

	# --------------- Prepare Dataset --------------- #
	training_set = Dataset(X_train_datapath)
	test_set = Dataset(X_test_datapath)

	train_loader = data.DataLoader(dataset=training_set, batch_size = opt.batch_size, shuffle = False)
	test_loader = data.DataLoader(dataset=test_set, batch_size = opt.batch_size, shuffle = False)

	# --------------- Training --------------- #

	if not os.path.isdir(os.path.join('models','cnn',opt.dataset)):
		os.makedirs(os.path.join('models','cnn',opt.dataset))
	if not os.path.isdir(os.path.join('models','gsf2app',opt.dataset)):
		os.makedirs(os.path.join('models','gsf2app',opt.dataset))

	cnn_model_path = os.path.join('models','cnn',opt.dataset,opt.dataset+'.ckpt')
	gsf2app_model_path = os.path.join('models','gsf2app',opt.dataset,'gsf2app_'+opt.dataset+'.ckpt')

	# Train CNN model
	training_gsf2app(train_loader, opt.stage_1_lr, scene_classes, cnn_model_path,
		gsf2app_model_path, opt.stage_1_n_epochs, 1)

	# Eval CNN model
	eval_gsf2app(test_loader, scene_classes, cnn_model_path, gsf2app_model_path, 1)

	# Train GSF2App model
	training_set.training_stage = 2
	training_gsf2app(train_loader, opt.stage_2_lr, scene_classes, cnn_model_path,
		gsf2app_model_path, opt.stage_2_n_epochs, 2)

	# Eval GSF2App model
	test_set.training_stage = 2
	eval_gsf2app(test_loader, scene_classes, cnn_model_path, gsf2app_model_path, 2)


import numpy as np
import gym
from gym import spaces
from gym_fast_envs import get_game_module

class FastEnvs(gym.Env):
    metadata = {'render.modes': ['human', 'rgb_array']}

    def __init__(self, **kwargs):

        game_module = get_game_module(kwargs['game_module'])
        print('Initialising {}.'.format(kwargs["game_id"]))

        kwargs.pop('game_module')
        kwargs.pop('game_id')

        self.game = game_module(**kwargs)

        self._action_set = self.game.get_action_set()
        self.action_space = spaces.Discrete(len(self._action_set))
        self.screen_width, self.screen_height = self.game.get_screen_dims()
        shape = (self.screen_width, self.screen_height, 3)
        self.observation_space = spaces.Box(low=0, high=255,
                                            shape=shape, dtype=np.uint8)
        self.viewer = None

    def step(self, action):
        observation, terminal, reward = self.game.step(action)
        return observation, reward, terminal, {}

    def _get_image(self):
        return self.game.get_screen()

    @property
    def _n_actions(self):
        return len(self._action_set)

    def reset(self):
        observation, _, _ = self.game.reset()
        return observation

    def _render(self, mode='human', close=False):
        if close:
            if self.viewer is not None:
                self.viewer.close()
                self.viewer = None
            return
        img = self._get_image()
        if mode == 'rgb_array':
            return img
        elif mode == 'human':
            from gym.envs.classic_control import rendering
            if self.viewer is None:
                self.viewer = rendering.SimpleImageViewer()
            self.viewer.imshow(img)

    def _seed(self, seed):
        self.game.set_seed(seed)


# -*- coding: utf-8 -*-
from db import db_handler
from interface.user import check_user_shopping_cart
from interface import bank
from lib import common

logger = common.get_logger('shop')

def show_commodity_interface(commodity='commodity'):
    commodity_dic = db_handler.check_commodity(commodity)
    for commodity_name, commodity_info in commodity_dic.items():
        price = commodity_info['price']
        count = commodity_info['count']
        show_info = '商品名称:%s|商品价格:%s|商品库存:%s' % (commodity_name, price, count)
        print(show_info)
    return commodity_dic

def add_commodity_to_shopping_cart(name, commodity_name, commodity_count, commodity='commodity'):
    user_dic = check_user_shopping_cart(name)
    user_shopping_cart = user_dic['shopping_cart']
    commodity_dic = db_handler.check_commodity(commodity)
    if commodity_name in user_shopping_cart:
        user_shopping_cart[commodity_name]['count'] += commodity_count
        print('商品已添加购物车')
    else:
        user_shopping_cart[commodity_name] = \
            {'price': commodity_dic[commodity_name]['price'], 'count': commodity_count}
        print('商品已添加到购物车')
    db_handler.save(user_dic)

def check_shopping_cart_interface(name):
    user_dic = db_handler.select(name)
    shopping_cart = user_dic['shopping_cart']
    return True, shopping_cart

def shopping_interface(name, commodity_name, commodity_count, commodity='commodity', cost=0):
    user_dic = db_handler.select(name)
    user_shopping_cart = user_dic['shopping_cart']
    commodity_dic = db_handler.check_commodity(commodity)
    while True:
        if commodity_dic[commodity_name]['count'] >= commodity_count:
            is_add = input('按Y/y键，确认加入购物车，任意键取消')
            if is_add == 'y':
                add_commodity_to_shopping_cart(name, commodity_name, commodity_count, commodity)
                continue
            else:
                if user_shopping_cart:
                    is_buy = input('是否确认购买？Y/y确认购买，任意键取消操作')
                    if is_buy == 'y':
                        k_cost = 0
                        for k, v in user_shopping_cart.items():
                            k_cost += v['price'] * v['count']
                            cost += k_cost
                            print('商品名称:%s|商品单价:%s|商品数量:%s' % (k, v['price'], v['count']))
                        print('商品总价格:%s' % cost)
                        is_buy2 = input('请再次确认商品Y/y，任意键取消购买').lower().strip()
                        if is_buy2 == 'y':
                            flag, msg = bank.pay_interface(name, cost)
                            return flag, msg
                        else:
                            return False, '您已取消购买'
                    else:
                        return False, '您购物车里存在商品，但是取消购买'
        else:
            return False, '库存不足'


import torch
from torchvision import transforms
import os,shutil,glob
import cv2
from PIL import Image

class Predictor:
    def __init__(self, model_path='model.pkl', input_size=(224,224),classes=None,classes_path=None,transform=None):
        self.model_path = model_path
        self.model = torch.load(model_path)
        self.device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
        self.model.to(self.device)

        transform = transform or  transforms.Compose([
            transforms.Resize(input_size),
            transforms.CenterCrop(input_size),
            transforms.ToTensor(),
            transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
        ])
        self.transform=transform
        if classes_path:
            classes=open(classes_path).read().strip().split('\n')
        self.classes=classes
    def predict(self,img):
        im=img
        im = self.transform(im).float()
        im = torch.tensor(im, requires_grad=False)
        im = im.unsqueeze(0)
        im = im.to(self.device)
        y = self.model(im)
        y = torch.argmax(y).cpu().int()
        y = int(y)
        return self.classes[y]
    def predict_from_file(self,fp):
        img=Image.open(fp)
        return self.predict(img)
    def test_dir(self,dir,out_dir,verbose=True,font_path=None,font_size=64):
        from wpkit.cv.utils import mark_img,set_font_path
        if not font_path:
            if os.path.exists('msyh.ttf'):
                font_path='msyh.ttf'
        if font_path:
            set_font_path(font_path)
        fs = glob.glob(dir+'/*.jpg')
        res = {}
        if os.path.exists(out_dir):
            shutil.rmtree(out_dir)
        os.makedirs(out_dir)
        for i, f in enumerate(fs):
            name = os.path.basename(f)
            y = self.predict_from_file(f)
            img=Image.open(f)
            img=mark_img(img,y,font_size=font_size)
            f2=out_dir+'/'+os.path.basename(f)
            img.save(f2)
            if verbose:
                print(i, f, y)
        return res
    def predict_dir(self,dir,verbose=True):
        fs=glob.glob(dir+'/*.jpg')
        res={}
        for i,f in enumerate(fs):
            name=os.path.basename(f)
            y=self.predict_from_file(f)
            res[name]=y
            if verbose:
                print(i,f,y)
        return res

if __name__ == '__main__':
    predictor=Predictor(
        model_path='model.pkl',
        classes_path='classes.txt'
    )
    predictor.test_dir(
        '/home/ars/disk/chaoyuan/dataset/汽车分类/raw',
        out_dir="/home/ars/disk/chaoyuan/dataset/汽车分类/raw_test_results",
        font_path='arsocr/utils/msyh.ttf'
    )


from django.core.exceptions import ValidationError
from django.core.validators import validate_email, URLValidator

from django.db import models
from django.utils.translation import gettext_lazy as _
import uuid

# from db_mixing import TimeStampMixin

class Title(models.Model):
    title = models.CharField(max_length=255)
    abbr = models.CharField(max_length=10, null=True, blank=True)
    description = models.TextField(blank=True, null=True)

    def __str__(self):
        return self.title if self.abbr is None else self.abbr

class Suffix(models.Model):
    class Suffix(models.TextChoices):
        SENIOR = "SR", _('Sr.')
        JUNIOR = "JR", _('Jr.')
        FIRST = "01" , _('I')
        SECOND = "02", _('II')
        THIRD = "03", _('III')
        FOURTH = "04", _('IV')
        FIFTH = "05", _('V')
        SIX = "06", _('VI')
        SEVENTH = "07", _('VII')
        EIGHTH = "08", _('VIII')
        NINTH = "09", _('XI')
        TENTH = "10", _('X')
        REQUEST = "XX"

        __empty__ = "(NONE)"

    suffix = models.CharField(max_length=2, choices=Suffix.choices, null=True, blank=True)

    def __str__(self):
        return self.get_suffix_display()

class Contact(models.Model):
    type = models.CharField(max_length=25)
    value = models.CharField(max_length=255, unique=True)

    def __str__(self):
        return "{}".format(self.value)

    def clean(self):
        errors={}
        self.type = str(self.type).lower()
        if  self.type == 'url':
            URLValidator(self.value)
        if  self.type == 'email':
            print(validate_email(self.value))
        else:
            errors['type'] = _("not accepting type of {}".format(self.type))
        if errors:
            raise ValidationError(errors)

class Address(models.Model):
    address_line_one = models.CharField(max_length=255)
    address_line_two = models.CharField(max_length=255, blank=True, null=True)
    street = models.CharField(max_length=255)
    city = models.CharField(max_length=255)
    apt_building = models.CharField(max_length=255, blank=True, null=True)
    postal_code = models.CharField(max_length=10, blank=True, null=True)
    providence = models.CharField(max_length=255, blank=True, null=True)
    state = models.CharField(max_length=255, blank=True, null=True)
    country = models.ForeignKey('Country', on_delete=models.CASCADE)
    label = models.CharField(max_length=10, blank=True, null=True)
    longitude = models.CharField(max_length=10, blank=True, null=True)
    latitude = models.CharField(max_length=10, blank=True, null=True)

    def __str__(self):
        return self.address_line_one

class Document(models.Model):
    path = models.CharField(max_length=255, blank=True, null=True)
    type = models.CharField(max_length=25, blank=True, null=True)
    title = models.CharField(max_length=255, unique=True, blank=True, null=True)
    label = models.CharField(max_length=10, blank=True, null=True)
    issue_date = models.DateField(blank=True, null=True)
    expire_date = models.DateField(blank=True, null=True)
    issuer = models.CharField(max_length=10, blank=True, null=True)
    validation_url = models.URLField(blank=True, null=True)
    validation_code = models.CharField(max_length=100, blank=True, null=True)

    def __str__(self):
        return "{}".format(self.title)

class Personal(models.Model):
    class Gender(models.TextChoices):
        FEMALE = "F"
        MALE = "M"
        NOT_SAY = "X"
        OTHER = "O"

    class MaritalStatus(models.TextChoices):
        DIVORCED = "DI"
        MARRIED = "MA"
        SEPARATED = "SE"
        SINGLE = "SI"
        WIDOWED = "WI"
        __empty__ = "(NONE)"

    class EyesColor(models.TextChoices):
        AMBER = "AR"
        BLACK = "BK"
        BLUE = "BE"
        BROWN = "BN"
        GRAY = "GY"
        GREEN = "GN"
        HAZEL = "HL"
        RED_ALBINO = "RA"
        __empty__ = "(UNKNOWN)"

    class SkinColor(models.TextChoices):
        IVORY = 'IV'
        BEIGE = 'BE'
        ALABASTER = 'AB'
        HONEY = 'HO'
        CAROTENOID = 'CT'
        TAN = 'TA'
        CARAMEL = 'CA'
        BRONZE = 'BR'
        MAHOGANY = 'MA'
        CHESTNUT = 'CH'
        BUFF = 'BU'
        PEACHESCREAM = 'PC'
        UMBER = 'UM'
        PRALINE = 'PR'
        ESPRESSOBROWN = 'EB'
        PORCELAIN = 'PO'
        HICKORY = 'HI'
        MUSTARD = 'MU'
        SABLE = 'SA'
        ALMOND = 'AL'
        BISQUE = 'BI'
        TEAK = 'TE'
        CACAO = 'CC'
        PECAN = 'PE'
        SADDLEBROWN = 'SB'

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    first_name = models.CharField(max_length=25)
    given_name = models.CharField(max_length=25)
    middle_name = models.CharField(max_length=50, null=True, blank=True)
    maiden_name = models.CharField(max_length=25, null=True, blank=True)
    gender = models.CharField(max_length=2, choices=Gender.choices)
    date_of_birth = models.DateField(max_length=255)
    marital_status = models.CharField(max_length=2,  choices=MaritalStatus.choices, null=True, blank=True)
    skin_color = models.CharField(max_length=2, choices=SkinColor.choices, null=True, blank=True)
    eyes_color = models.CharField(max_length=2, choices=EyesColor.choices, null=True, blank=True)
    height  = models.CharField(max_length=255, null=True, blank=True)
    weight = models.CharField(max_length=255, null=True, blank=True)
    nationality = models.ForeignKey('Country', on_delete=models.CASCADE)
    titles = models.ManyToManyField(Title, through='PersonalTitle')
    suffixes = models.ManyToManyField(Suffix, through='PersonalSuffix')
    contacts = models.ManyToManyField(Contact, through='PersonalContact')
    addresses = models.ManyToManyField(Address, through='PersonalAddress')
    documents = models.ManyToManyField(Document, through='PersonalDocument')

    def __str__(self):
        full_name = ""
        full_name += self.first_name

        if self.middle_name: full_name += " " + self.middle_name
        if self.maiden_name: full_name += " " + self.maiden_name
        else: full_name += " " + self.given_name

        return full_name

    def clean(self):

        errors={}

        if self.maiden_name:
            if self.gender != self.Gender.FEMALE:
                errors['maiden_name'] = _('For female only')
            if self.marital_status is None:
                errors['maiden_name'] = _('Please select a Marital Status before setting this field')
            if self.marital_status == self.MaritalStatus.SINGLE:
                errors['maiden_name'] = _('Cannot be set for Single individuals')
        if self.weight:
            try:
                value, unit = str(self.weight).split('_')
                value = float(value)
            except ValueError as e:
                errors['weight'] = _('Error: did you include a unit in the format VALUE_UNIT')
        if self.height:
            try:
                values = str(self.height).split('-')
                for value in values:
                    value, unit = str(value).split('_')
                    value = float(value)
            except ValueError as e:
                errors['height'] = _('Please check your height')

        if errors:
            raise ValidationError(errors)

class PersonalTitle(models.Model):
    personal = models.ForeignKey(Personal, on_delete=models.CASCADE)
    title = models.ForeignKey(Title, on_delete=models.CASCADE)
    order = models.IntegerField(default=0, null=True, blank=True)

    class Meta:
        unique_together = ('personal','title')

    def __str__(self):
        return "{} {}".format(self.title, self.personal)

class PersonalSuffix(models.Model):
    personal = models.ForeignKey(Personal, on_delete=models.CASCADE)
    suffix = models.ForeignKey(Suffix, on_delete=models.CASCADE)
    order = models.IntegerField(default=0, null=True, blank=True)

    class Meta:
        unique_together = ('personal','suffix')

class PersonalAddress(models.Model):
    personal = models.ForeignKey(Personal, on_delete=models.CASCADE)
    address = models.ForeignKey(Address, on_delete=models.CASCADE)
    label = models.CharField(max_length=10, blank=True, null=True)

    class Meta:
        unique_together = ('personal','address')

class PersonalContact(models.Model):
    personal = models.ForeignKey(Personal, on_delete=models.CASCADE)
    contact = models.OneToOneField(Contact, on_delete=models.CASCADE)
    label = models.CharField(max_length=10, blank=True, null=True)

    class Meta:
        unique_together = ('personal','contact')

class PersonalDocument(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    personal = models.ForeignKey(Personal, on_delete=models.CASCADE)
    document = models.ForeignKey(Document, on_delete=models.CASCADE)

class Country(models.Model):
    name = models.CharField(max_length=100)
    code = models.CharField(max_length=2)

    def __str__(self):
        return self.name

class CountryState(models.Model):
    pass


"Code copied from `Tensorflow/keras/callbacks.py <https://github.com/tensorflow/tensorflow/blob/b36436b087bd8e8701ef51718179037cccdfc26e/tensorflow/python/keras/callbacks.py#L1057>`_ just inserting a few lines on the prints to avoid this `error <https://github.com/tensorflow/tensorflow/issues/35100>`_."

import warnings
import tensorflow as tf
import numpy as np

class ModelCheckpoint(tf.keras.callbacks.Callback):
    """Save the model after every epochimport tensorflow.keras.callbacks.Callback .
       `filepath` can contain named formatting options,
       which will be filled with the values of `epoch` and
       keys in `logs` (passed in `on_epoch_end`).
       For example: if `filepath` is `weights.{epoch:02d}-{val_loss:.2f}.hdf5`,
       then the model checkpoints will be saved with the epoch number and
       the validation loss in the filename.

       Parameters
       ----------
       filepath : str
           Path to save the model file.

       monitor: str
           Quantity to monitor.

       verbose : int
           Verbosity mode, 0 or 1.

       save_best_only : bool
           If ``save_best_only=True``, the latest best model according to the
           quantity monitored will not be overwritten.

       save_weights_only : bool
           If ``True``, then only the model's weights will be saved
           (``model.save_weights(filepath)``), else the full model is saved
           (``model.save(filepath)``).

       mode : str
           One of ``{auto, min, max}``. If ``save_best_only=True``, the decision
           to overwrite the current save file is made based on either the
           maximization or the minimization of the monitored quantity. For
           ``val_acc``, this should be ``max``, for ``val_loss`` this should
           be ``min``, etc. In ``auto`` mode, the direction is automatically
           inferred from the name of the monitored quantity.

       period : int
           Interval (number of epochs) between checkpoints.
    """

    def __init__(self, filepath, monitor='val_loss', verbose=0,
                 save_best_only=False, save_weights_only=False,
                 mode='auto', period=1):
        super(ModelCheckpoint, self).__init__()
        self.monitor = monitor
        self.verbose = verbose
        self.filepath = filepath
        self.save_best_only = save_best_only
        self.save_weights_only = save_weights_only
        self.period = period
        self.epochs_since_last_save = 0

        if mode not in ['auto', 'min', 'max']:
            warnings.warn('ModelCheckpoint mode %s is unknown, '
                          'fallback to auto mode.' % (mode),
                          RuntimeWarning)
            mode = 'auto'

        if mode == 'min':
            self.monitor_op = np.less
            self.best = np.Inf
        elif mode == 'max':
            self.monitor_op = np.greater
            self.best = -np.Inf
        else:
            if 'acc' in self.monitor or self.monitor.startswith('fmeasure'):
                self.monitor_op = np.greater
                self.best = -np.Inf
            else:
                self.monitor_op = np.less
                self.best = np.Inf

    def on_epoch_end(self, epoch, logs=None):
        logs = logs or {}
        self.epochs_since_last_save += 1
        if self.epochs_since_last_save >= self.period:
            self.epochs_since_last_save = 0
            filepath = self.filepath.format(epoch=epoch + 1, **logs)
            if self.save_best_only:
                current = logs.get(self.monitor)
                if current is None:
                    warnings.warn('Can save best model only with %s available, '
                                  'skipping.' % (self.monitor), RuntimeWarning)
                else:
                    if self.monitor_op(current, self.best):
                        if self.verbose > 0:
                            print('\n\nEpoch %05d: %s improved from %0.5f to %0.5f,'
                                  ' saving model to %s\n\n'
                                  % (epoch + 1, self.monitor, self.best,
                                     current, filepath))
                        self.best = current
                        if self.save_weights_only:
                            self.model.save_weights(filepath, overwrite=True)
                        else:
                            self.model.save(filepath, overwrite=True)
                    else:
                        if self.verbose > 0:
                            print('\n\nEpoch %05d: %s did not improve from %0.5f\n\n' %
                                  (epoch + 1, self.monitor, self.best))
            else:
                if self.verbose > 0:
                    print('\n\nEpoch %05d: saving model to %s\n\n' % (epoch + 1, filepath))
                if self.save_weights_only:
                    self.model.save_weights(filepath, overwrite=True)
                else:
                    self.model.save(filepath, overwrite=True)


from PyQt5 import QtGui,QtCore,QtWidgets
from PyQt5.QtCore import QObject, pyqtSignal,QTimer,QThread,Qt,QEvent
from PyQt5.QtGui import QImage,QPainter,QFont
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import os,os.path,sys,math,socket
import operator
import ui_udpsendbyqt as uiMain
import struct
import binascii
import ctypes
import random

class CUdp(QThread):
    def __init__(self,parent = None):
        QThread.__init__(self,parent)
        self.initSock()
        self._bInit = False

    def initSock(self):
        self._sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
        if not self._sock:
            print('sock error!')
        self._sock.setblocking(1)
        self._sock.settimeout(1)
        self._bInit = True

    def Init(self,port,addr):

        self.Quit()
        if not self._bInit:
            self.initSock()
        self._addr = addr
        if not self._sock:
            return

        localAddr = ('',port)
        self._sock.bind(localAddr)
        self._peerAddr = (addr[0],int(addr[1]))

    def Quit(self):

        if not self._sock:
            return
        self._sock.close()
        self._bInit = False

    def sendMsg(self,data):
        if not self._sock:
            return
        self._sock.sendto(data,self._peerAddr)

    def run(self):
        print(QThread.currentThread(),' is running ...')
        while self.isRunning():
            if self.isInterruptionRequested():
                break
            if not self._sock:
                QThread.sleep(1)
                continue
            try:
                data = self._sock.recvfrom(1024)
                if not data:
                    print('socket error here!!')
            except socket.error as msg:
                data = None
                continue

        print(QThread.currentThread(),' quitting ...')

class myWindow(QMainWindow):
    nPos = 0
    def __init__(self,parent = None):
        QMainWindow.__init__(self,parent)
        self.ui = uiMain.Ui_UDPSendByQtClass()
        self.ui.setupUi(self)
        self._timerSroll = QTimer()
        self.m_scrollCaptionStr = '模拟西安Udp叠加发送端，包含 GPS、单播、组播'
        shadow = QGraphicsDropShadowEffect(self)
        shadow.setOffset(-5, self.ui.scrollCaptionLabel.fontMetrics().height());
        self._timerSroll.start(500);
        shadow.setColor(Qt.darkMagenta);
        shadow.setBlurRadius(8)
        self.ui.scrollCaptionLabel.setText(self.m_scrollCaptionStr);
        self.ui.scrollCaptionLabel.setGraphicsEffect(shadow);
        self.ui.textEdit.document().setMaximumBlockCount(102400)
        self.relayoutUi()
        self._timeGPs = QTimer(self)
        self._timerMulti = QTimer(self)
        self._timeSingle = QTimer(self)

        self.m_udpMulti = CUdp(self)
        self.m_udpSingle = CUdp(self)
        self.m_udpSingle2 = CUdp(self)
        self.m_udpGps = CUdp(self)

        self.m_udpMulti.start()
        self.m_udpSingle.start()
        self.m_udpSingle2.start()
        self.m_udpGps.start()

        self.connect()

    def connect(self):
        self._timerSroll.timeout.connect(self.on_wordRun)
        self._timeGPs.timeout.connect(self.on_timeOut_gps)
        self._timerMulti.timeout.connect(self.on_timeOut_Multi)
        self._timeSingle.timeout.connect(self.on_timeOut_Single)
        self.ui.btn_start.clicked.connect(self.on_Init)
        self.ui.btn_stop.clicked.connect(self.on_Quit)

    def on_timeOut_gps(self):
        dt = QDateTime.currentDateTime()
        time = dt.time().msecsSinceStartOfDay()
        str = struct.pack('=BIBBB',0xAA,time,65,66,0xAA)
        self.m_udpGps.sendMsg(str)
        str = 'tData._time:%d'%(time)
        self.ui.textEdit.append(str)

    si_Cnt = 0
    def on_timeOut_Single(self):
        if self.ui.cmb_data.currentIndex() == 0: ##顺序递增  模拟
            myWindow.si_Cnt += 1
            myWindow.si_Cnt %= 100
            _fraps = 5000 + myWindow.si_Cnt*100
            _focus = 1000 + myWindow.si_Cnt*10
            _distance = 5000 + myWindow.si_Cnt*10
        else:
            a = int(random.uniform(1,1000))
            _fraps = 5000 + a%1000
            _focus = 1000 + a%1000
            _distance = 5000 + a%1000

        if self.m_check_single1.isChecked():
            str = struct.pack('8sLLLL40s',
            b'',_focus,_distance,_fraps,0,b'')
            # print ('After pack:',len(str),binascii.hexlify(str))
            self.m_udpSingle.sendMsg(str)
            str = 'tData._focus:%d,tData._fraps:%d,cnt:%d'%(_focus,_fraps,myWindow.si_Cnt)
            self.ui.textEdit.append(str)
        if self.m_check_single2.isChecked():
            str = struct.pack('=64s',b'')
            self.m_udpSingle2.sendMsg(str)

    sf_angle = 0.0
    def on_timeOut_Multi(self):

        angle = random.uniform(0,1)
        myWindow.sf_angle += 0.1
        if self.ui.cmb_data.currentIndex() == 0: ##顺序递增  模拟
            if myWindow.sf_angle > 1:
                myWindow.sf_angle -= 1
            angle = myWindow.sf_angle

        azimuth_angle = []
        pitch_angle= []
        for i in range(10):
            azimuth_angle.append(10*i + angle)
            pitch_angle.append(10*i + angle)
        strA = bytes()
        strE = bytes()
        for i in range(10):
            strA += struct.pack('=f',azimuth_angle[i])
            strE += struct.pack('=f',pitch_angle[i])

        str = struct.pack('=28s',b'')
        str += strA
        str += struct.pack('=40s',b'')
        str += strE
        str += struct.pack('=364s',b'')

        self.m_udpMulti.sendMsg(str)
        # print(len(str),type(str))
        # print(str)
        self.ui.textEdit.append(binascii.hexlify(strA).decode())

    def closeEvent(self,evt):
        self.on_Quit()
        list = [self.m_udpMulti,self.m_udpSingle,self.m_udpSingle2,self.m_udpGps]
        for ii in list:
            ii.requestInterruption()
            ii.quit()

        for ii in list:
            ii.Quit()
            ii.wait(1000)

    def relayoutUi(self):
        hLayout = QHBoxLayout()
        label_single2 = QLabel('单播2:',self.ui.groupBox)
        self.addr_single2 = QLineEdit('192.168.1.220:15000',self.ui.groupBox)
        hLayout.setSpacing(6);
        hLayout.addWidget(label_single2);
        hLayout.addWidget(self.addr_single2);
        self.m_check_single2 = QCheckBox(self.ui.groupBox);
        self.m_check_single2.setChecked(True);
        self.ReplaceWidgets(hLayout, self.m_check_single2);

        self.m_check_mutil = QCheckBox(self);
        self.m_check_mutil.setChecked(True);
        self.m_check_single1 = QCheckBox(self);
        self.m_check_single1.setChecked(True);
        self.m_check_gps = QCheckBox(self);
        self.m_check_gps.setChecked(True);

        self.ReplaceWidgets(self.ui.hlay_gps,self.m_check_gps);
        self.ReplaceWidgets(self.ui.hlay_single,self.m_check_single1);
        self.ReplaceWidgets(self.ui.hlay_mutil,self.m_check_mutil);
        # 重新排序 [4/27/2017 xystar]
        self.ui.hlay_group.removeItem(self.ui.hlay_gps);
        self.ui.hlay_group.addItem(hLayout);
        self.ui.hlay_group.addItem(self.ui.hlay_gps);
        self.ui.hlay_group.setSpacing(2);

    def ReplaceWidgets(self,lay,check):
        nCnt = lay.count()
        wgetList = []
        while 1:
            wgetList.append(lay.itemAt(0).widget())
            lay.removeItem(lay.itemAt(0))
            nCnt = lay.count()
            if nCnt == 0:
                break
        lay.addWidget(check)

        for var in wgetList:
            lay.addWidget(var);
            edit = var
            edit.setMinimumWidth(edit.fontMetrics().averageCharWidth()*len(edit.text()) + 10);
        lay.setStretch(2,1)
        lay.addStretch(1)

    def on_Init(self):
        value = self.ui.addr_Muti.text().split(':')
        self.m_udpMulti.Init(int(value[1]) + 1,tuple(value))
        value = self.ui.Addr_Single.text().split(':')
        self.m_udpSingle.Init(int(value[1])+ 1,tuple(value))
        value = self.addr_single2.text().split(':')
        self.m_udpSingle2.Init(int(value[1])+ 1,tuple(value))
        value = self.ui.Addr_Gps.text().split(':')
        self.m_udpGps.Init(int(value[1])+ 1,tuple(value))

        if self.m_check_mutil.isChecked():
            self._timerMulti.start(500)
        if self.m_check_single1.isChecked():
            self._timeSingle.start(500)
        if self.m_check_gps.isChecked():
            self._timeGPs.start(500)

    def on_Quit(self):
        self._timeGPs.stop()
        self._timerMulti.stop()
        self._timeSingle.stop()

    def on_wordRun(self):

        if myWindow.nPos > len(self.m_scrollCaptionStr):
            myWindow.nPos = 0
        self.ui.scrollCaptionLabel.setText(self.m_scrollCaptionStr[myWindow.nPos:])
        myWindow.nPos += 1

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    dlg = myWindow()
    dlg.show()
    sys.exit(app.exec_())


# -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) Browseinfo (http://browseinfo.in)
#
#    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/>.
#
##############################################################################
from openerp.osv import fields, osv

#class account_invoice(osv.osv):
#    _inherit = 'account.invoice'
#    _columns = {
#                }
#    def create(self, cr, uid, vals, context=None):
#        res = super(account_invoice,self).create(cr, uid, vals, context=context)
#        if self.browse(cr, uid,res,context=context).type == 'out_invoice':
#            self.send_mail_sasmar(cr, uid, res, context=context)
#        return res
#    def send_mail_sasmar(self, cr, uid,ids, context=None):
#        email_temp = self.pool.get('email.template')
#        template_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'send_email_finance', 'email_template_sasmar_invoice')[1]
#        if isinstance(ids, (int,float,long)):
#           ids = [ids]
#        email_temp.send_mail(cr, uid, template_id, ids[0], force_send=False, context=context)
#        return True
#    def confirm_paid(self, cr, uid, ids, context=None):
#        res = super(account_invoice,self).confirm_paid(cr, uid, ids, context=context)
#        if isinstance(ids, (int)):
#            ids = [ids]
#        if self.browse(cr, uid,ids[0],context=context).type == 'out_invoice':
#            self.send_mail_sasmar(cr, uid, ids, context=context)
#        return res
#    def invoice_validate(self, cr, uid, ids, context=None):
#        res = super(account_invoice,self).invoice_validate(cr, uid, ids, context=context)
#        if isinstance(ids, (int)):
#            ids = [ids]
#        if self.browse(cr, uid,ids[0],context=context).type == 'out_invoice':
#            self.send_mail_sasmar(cr, uid, ids, context=context)
#        return res
#
#    def set_to_proforma(self, cr, uid, ids, context=None):
#        self.write(cr, uid, ids, {'state':'proforma2'}, context=context)
#        if isinstance(ids, (int)):
#            ids = [ids]
#        if self.browse(cr, uid,ids[0],context=context).type == 'out_invoice':
#            self.send_mail_sasmar(cr, uid, ids, context=context)
#        return True
#
#account_invoice()
class sale_order(osv.osv):
    _inherit = 'sale.order'
    _columns = {
                }
    def create(self, cr, uid, vals, context=None):
        res = super(sale_order,self).create(cr, uid, vals, context=context)
        self.send_mail_sasmar(cr, uid, res, context=context)
        return res
    def send_mail_sasmar(self, cr, uid,ids, context=None):
        email_temp = self.pool.get('email.template')
        template_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'send_email_finance', 'email_template_sasmar_invoice')[1]
        if isinstance(ids, (int,float,long)):
           ids = [ids]
        email_temp.send_mail(cr, uid, template_id, ids[0], force_send=False, context=context)
        return True


import sqlite3
import os
from pathlib import Path
"""
Commands:
    add -pub  file_path/dir_path
    add -pri  file_path/dir_path alias/ip
    rm -pub  file_path/dir_path
    rm -pri  file_path/dir_path
    search  file_path/dir_path
"""

class fileHandle:

    def __init__(self):
        self.a = 5
        path = 'fileData.db'
        self.dbConnection = sqlite3.connect(path)
        self.db = self.dbConnection.cursor()

    def createDB(self):
        q = """
                CREATE TABLE pub(
                Name VARCHAR(100) ,
                Path VARCHAR(100) PRIMARY KEY UNIQUE,
                TYPE INTEGER
                );"""
        self.db.execute(q)
        self.dbConnection.commit()
        print('pub Table created')

        q = """
                CREATE TABLE pri(
                Name VARCHAR(100) ,
                Path VARCHAR(100) PRIMARY KEY UNIQUE,
                TYPE INTEGER,
                mac INTEGER
                );"""
        self.db.execute(q)
        self.dbConnection.commit()
        print('pub Table created')

    def handleCMD(self, recData):
        recData = recData.lstrip()
        recData = recData.rstrip()
        index = self.getindex(recData, ' ')
        if index >0:
            cmd = recData[:index]
            opData = recData[index+1:]

            if cmd == "add":
                self.__handleADD__(opData)
            elif cmd == "get":
                self.__handleGET__(opData)
            elif cmd == "rm":
                self.__handleRM__(opData)
        else:
            return "illegalCMD"

    def __handleADD__(self, opData):
        opData = (opData.lstrip()).rstrip()
        index = self.getindex(opData, ' ')
        if index > 0:
            option = opData[:index]
            pS = opData[index + 1:]
            p = Path(pS)
            name = pS[pS.rfind('\\')+1:]
            if p.is_dir():
                type = 1
            elif p.is_file():
                type = 0
            else:
                return 'fdir_not_exist'
            if option == "-pub":
                q = """REPLACE INTO pub (name, path, type) VALUES (?, ?, ?)"""
                try:
                    self.db.execute(q, (name, pS, type))
                except:
                    print('Something Went Wrong')

            elif option == "-pri":
                q = """REPLACE INTO pri (name, path, type)"""
                try:
                    self.db.execute(q, (name, pS, type))
                except:
                    print('Something Went Wrong')
            else:
                return "illegalCMD"
        else:
            return "illegalCMD"

    def __handleGET__(self, opData):
        return 1

    def __handleRM__(self, opData):
        return 1

    def getindex(self, str, indexOf):
        try:
            return str.index(indexOf)
        except:
            return -1


import rosnode

def execute(self, inputs, outputs, gvm):
    self.logger.info("Checking speech nodes...")

    # check nodes
    nodesToCheck = ['/tts',
                    '/stt_google',
                    '/nlp',
                    '/stt_offline']

    self.logger.verbose("Nodes to check {}".format(nodesToCheck))

    nodeList = rosnode.get_node_names()

    nodeNotFound = False

    for nodeToCheck in nodesToCheck:
        if nodeToCheck not in nodeList:
            self.logger.warning("The Node '{}' is not running!".format(nodeToCheck))
            nodeNotFound = True

    if nodeNotFound:
        # atleast one node was not found
        self.logger.info("Not all speech nodes were found!")
    else:
        self.logger.info("All speech nodes were found!")

    return "success"


import pytest

from napier.operators import Addition, Subtraction, Multiplication, Division
from napier.numbers import NaturalNumber

def test_constructors():
    x, y = NaturalNumber(1), NaturalNumber(2)

    s = Addition(x, y)
    d = Subtraction(x, y)
    p = Multiplication(x, y)
    q = Division(x, y)

def test_typecheck():
    x, y = NaturalNumber(1), NaturalNumber(2)

    for C in [Addition, Subtraction, Multiplication, Division]:
        C(x, y)

        with pytest.raises(TypeError):
            C(1, y)

        with pytest.raises(TypeError):
            C(x, 1)

def test_addition_simplification():
    s = Addition(NaturalNumber(4), NaturalNumber(5))
    assert s.simplify() == NaturalNumber(9)

    s = Addition(NaturalNumber(12), NaturalNumber(6))
    assert s.simplify() == NaturalNumber(18)

def test_subtraction_simplification():
    d = Subtraction(NaturalNumber(12), NaturalNumber(2))
    assert d.simplify() == NaturalNumber(10)

    d = Subtraction(NaturalNumber(5), NaturalNumber(4))
    assert d.simplify() == NaturalNumber(1)

def test_multiplication_simplification():
    p = Multiplication(NaturalNumber(3), NaturalNumber(4))
    assert p.simplify() == NaturalNumber(12)

    p = Multiplication(NaturalNumber(5), NaturalNumber(5))
    assert p.simplify() == NaturalNumber(25)

def test_division_simplification():
    q = Division(NaturalNumber(12), NaturalNumber(3))
    assert q.simplify() == NaturalNumber(4)

    q = Division(NaturalNumber(5), NaturalNumber(5))
    assert q.simplify() == NaturalNumber(1)

def test_complex_addition_simplifications():
    e = Addition(
        Addition(NaturalNumber(5), NaturalNumber(6)),
        NaturalNumber(7)
    )

    assert e.simplify() == NaturalNumber(18)

    e = Addition(
        NaturalNumber(5),
        Addition(NaturalNumber(2), NaturalNumber(1)),
    )

    assert e.simplify() == NaturalNumber(8)

def test_complex_subtraction_simplifications():
    e = Subtraction(
        NaturalNumber(10),
        Multiplication(NaturalNumber(3), NaturalNumber(3)),
    )

    assert e.simplify() == NaturalNumber(1)

    e = Subtraction(
        Multiplication(NaturalNumber(4), NaturalNumber(3)),
        NaturalNumber(10),
    )

    assert e.simplify() == NaturalNumber(2)

def test_complex_multiplication_simplifications():
    e = Multiplication(
        Division(NaturalNumber(4), NaturalNumber(2)),
        NaturalNumber(5),
    )

    assert e.simplify() == NaturalNumber(10)

    e = Multiplication(
        NaturalNumber(5),
        Division(NaturalNumber(4), NaturalNumber(2)),
    )

    assert e.simplify() == NaturalNumber(10)

def test_complex_division_simplifications():
    e = Division(
        NaturalNumber(10),
        Subtraction(NaturalNumber(5), NaturalNumber(3)),
    )

    assert e.simplify() == NaturalNumber(5)

    e = Division(
        Addition(NaturalNumber(5), NaturalNumber(5)),
        NaturalNumber(5),
    )

    assert e.simplify() == NaturalNumber(2)

def test_complex_nested_simplifications():
    e = Addition(
        NaturalNumber(2),
        Multiplication(
            NaturalNumber(3),
            Subtraction(
                NaturalNumber(10),
                Division(
                    NaturalNumber(12),
                    Addition(
                        NaturalNumber(1),
                        NaturalNumber(2),
                    ),
                ),
            ),
        ),
    )

    assert e.simplify() == NaturalNumber(20)


# -*- coding: utf-8 -*-
from django.conf.urls.defaults import *
from django.contrib import admin
from django.conf import settings
from patch import sites_flatpages_patch
from django.views.generic.simple import direct_to_template

admin.autodiscover()
sites_flatpages_patch()

urlpatterns = patterns('',
    (r'^admin/', include(admin.site.urls)),
    url(r'^help/$', direct_to_template, {'template': 'help.html'}, name='help'),
    (r'^registration/', include('registration.urls')),
    url(r'^login/$', 'django.contrib.auth.views.login', name='login'),
    url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}, name='logout'),
    (r'^', include('app.main.urls',  namespace='main')),
    (r'^lectures/', include('app.lectures.urls',  namespace='lectures')),
    (r'^statistic/', include('app.statistic.urls',  namespace='statistic')),
    (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
)


# Stack in python is a linear data structure that stores items in Last in/First out
# or First in /Last out manner.
# In stack, a new element is added at one end and an element is removed at the same end only.
# The insert and delete operations are often called push and pop
# Unlike lists or arrays, random access is not allowed for the objects contained in the stack.

# The functions are associated with stack are
# is_empty - Returns true if stack is empty, else false
# push - Adds an item in the stack
# pop - Removes an item from the stack
# peek - Returns the top element of the stack
# size - Returns the number of items in stack

class Empty(Exception):
    """Error attempting to access an element from an empty container"""
    pass

class Stack:
    """LiFO stack implementation using python list as underlying storage"""

    def __init__(self):
        """Crate an empty stack"""
        self.items = []

    def is_empty(self):
        return self.items == []

    def push(self, item):
        """ Add element to the top of the stack"""
        self.items.append(item) # new item stored at the end of the list

    def pop(self):
        """ Remove and return element from the top of the stack"""
        """Raise Empty exception if the stack is empty"""
        if self.is_empty():
            raise Empty("stack is empty")
        return self.items.pop() # remove last item from the list

    def peek(self):
        """Return the top element of the stack"""
        """Raise Empty exception if the stack is empty"""
        if self.is_empty():
            raise Empty("stack is empty")
        return self.items[-1] # the last item in the list

    def size(self):
        """Return the number of elements in the stack"""
        """ Raise the Empty exception is the stack is empty"""
        if self.is_empty():
            raise Empty("stack is empty")
        return len(self.items)

s = Stack()
s.push(2)
s.push(4)
s.push(6)
s.push(8)
s.push(10)

print(s)

print(s.is_empty())
print(s.peek())
s.push(12)
print(s.size())
print(s.is_empty())
print(s.pop())
print(s.pop())
print(s.size())


import csv
import rospy
import mavros
from mavros_msgs.msg import Waypoint
import rospy
def create_waypoint_list(name):

    known_versions = (110, 120)
    csv.register_dialect('mission_planer', delimiter = '\t', doublequote=False, skipinitialspace = True,
                     lineterminator = '\r\n', quoting=csv.QUOTE_NONE)
    rospy.logwarn('WARNING')
    with  open(name, 'r') as file_wp:
        rospy.logwarn('@@@WARNING@@@')
        waypoint_list=[]
        got_header = False
        for data in csv.reader(file_wp,dialect='mission_planer'):
            if data[0].startswith('#'):
                 continue; # skip comments (i think in next format version they add this)
            if not got_header:
                 qgc, wpl, ver = data[0].split(' ', 3)
                 ver = int(ver)
                 if qgc == 'QGC' and wpl == 'WPL' and ver in known_versions:
                     got_header = True
            else:
                waypoint_list.append(Waypoint(
                    frame=int(data[2]),
                    is_current = bool(int(data[1])),
                    command = int(data[3]),
                    param1 = float(data[4]),
                    param2 = float(data[5]),
                    param3 = float(data[6]),
                    param4 = float(data[7]),
                    x_lat = float(data[8]),
                    y_long = float(data[9]),
                    z_alt = float(data[10]),
                    autocontinue = bool(int(data[11]))
                ))
    #print waypoint_list
    return waypoint_list

#if __name__ == '__main__':
    #create_waypoint_list('/home/andrea/waypoint/wp_fileMP2.waypoints')


# -*- coding: utf-8 -*-
"""Daily bonus handler module.

"""
from tornado import gen
from translation import _T
from web import RequestHandler, set_path
from eventshandler import EventsHandler
from datetime import date
import logger
import redisutils
import time

NOT_RECEIVED = 0
RECEIVED = 1
FUTURE = 2
IGNORED = -1

@set_path(r"/dailybonus")
class GetDailyBonusHandler(EventsHandler):

    """Get daily bonus handler class.

    This class implements HTTP GET request '/dailybonus'.
    The query for this handler are:

        - id: facebook id user

        - cookie: user cookie

    Examples::

        /dailybonus?id=83273827&cookie=83u2832iu3h23hu32hu3

    """

    @gen.coroutine
    def get(self):
        """Implements HTTP GET method."""

        try:
            fid = self.get_argument('id')
            cookie = self.get_argument('cookie', '')

            verify_cookie = self.rd.get(redisutils.user_cookie(fid))

            if self.config.server['verify'] and cookie != verify_cookie:
                self.write(
                    {"error_code": -1, "error_msg": _T("Permission denied or your transaction is expired")})
                raise StopIteration

            available = yield self.events_available()
            if not available:
                self.write(
                    {"error_code": 1, "error_msg": _T("Can not get daily bonus")})
                raise StopIteration

            query = """SELECT d.`day`, d.`coin`, d.`status`, d.`active_date`
                FROM daily_bonus_users d, events e
                WHERE d.fid = '%s'
                AND e.`status` = 1 AND e.event_id = 'DAILYBONUS'
                AND e.start_time <= NOW() AND e.end_time >= NOW() """ % fid
            data = yield self.db.query(query)
            if data:
                today = date.today()

                async_data = []

                for bonus in data:
                    if bonus['status'] != NOT_RECEIVED:
                        continue

                    if bonus.active_date < today:
                        bonus['status'] = IGNORED
                        async_data.append(bonus)
                    elif bonus.active_date > today:
                        bonus['status'] = FUTURE

                if async_data:
                    values = ", ".join(
                        "('%s',%d,%d)" % (fid, bonus.day, bonus.status) for bonus in async_data)
                    query = """INSERT INTO daily_bonus_users(`fid`, `day`, `status`) VALUES %s
                            ON DUPLICATE KEY UPDATE `status` = VALUES(`status`)""" % values
                    yield self.db.insert(query)

                self.write({"error_code": 0, "data": data})
            else:
                self.write({
                    "error_code": 1,
                    "error_msg": _T("Can not get daily bonus")
                })
        except StopIteration:
            pass
        except:
            self.log_stack_trace()
            self.write({
                "error_code": 1,
                "error_msg": _T("Can not get daily bonus")
            })

@set_path(r"/receivedailybonus")
class ReceiveDailyBonusHandler(RequestHandler):

    """Receive daily bonus handler class.

    This class implements HTTP GET request '/receivedailybonus'.
    The query for this handler are:

        - id: facebook id user

        - cookie: user cookie

        - day: day of daily-bonus

        - coin: coin of daily-bonus

    Examples::

        /receivedailybonus?id=83273827&cookie=218921&day=3&coin=2121

    """

    @gen.coroutine
    def get(self):
        """Implements HTTP GET method."""

        try:
            fid = self.get_argument('id')
            cookie = self.get_argument('cookie', '')

            verify_cookie = self.rd.get(redisutils.user_cookie(fid))

            if self.config.server['verify'] and cookie != verify_cookie:
                self.write(
                    {"error_code": -1, "error_msg": _T("Permission denied or your transaction is expired")})
                raise StopIteration

            day = int(self.get_argument('day'))
            coin = int(self.get_argument('coin'))

            query = """UPDATE daily_bonus_users SET `status` = %d
                WHERE fid = '%s' AND `day` = %d AND `coin` = %d
                AND active_date = CURRENT_DATE()
            """ % (RECEIVED, fid, day, coin)

            data = yield self.db.update(query)

            if not data:
                self.write(
                    {"error_code": 1, "error_msg": _T("This day is received or expired")})
                raise StopIteration

            user_coin = self.rd.incrby(redisutils.user_coin(fid), coin)

            self.write({
                "error_code": 0,
                "data": {
                    "add_coin": coin,
                    "user_coin": user_coin,
                    "day": day,
                }
            })
            logger.trans_log.put({
                'time': time.strftime('%Y-%m-%d %H:%M:%S'),
                'fid': fid,
                'gameid': 'DAILY_BONUS',
                'room_coin': 0,
                'bet_coin': 0,
                'win_coin': coin,
                'win_type': 0,
                'user_coin': user_coin,
            })
            redisutils.async_user(self.rd, fid)

        except StopIteration:
            pass
        except:
            self.log_stack_trace()
            self.write({
                "error_code": 2,
                "error_msg": _T("Can not receive daily bonus")
            })


import numpy as np
import matplotlib.pyplot as py
from math import pi

def euler(xs, fs, h):
    return xs + h * fs(xs)

def solver(method, x0, fs, tmax, h = 1E-3, maxsteps = 1E+5, skip_t = 0.1):
    steps = 0
    xs = [x0] # list of values of the solution
    last_t = 0 # last recorded time
    x = x0 # current value of the solution
    while x[0] <= tmax and steps <= maxsteps:
        steps += 1 # increment the value of steps
        x = method(x, fs, h)
        if abs(x[0] - last_t) > skip_t:
            xs.append(x)
            last_t = x[0]
    if steps > maxsteps:
        print("Warning: max number of steps reached")
    return xs
# x = [x, p]
# dx/dt = p, dp/dt = - omega**2 * x
def oscillator(x, omega = 1):
    return np.array([1, x[2], - omega**2 * x[1]])

sol = solver(
    euler, # method
    np.array([0, 1, 0]), # initial state t=0, x=1, p=0
    oscillator, # fs - vector of first derivatives
    10, # tmax
    h = 1E-3
)

py.figure()

T, X, P = zip(*sol)
py.plot(T, X, color='black', label='position')
py.plot(T, P, '--', color='orange', label='velocity')
py.legend()
py.show()


f1=open("f1.txt","r+")
print(f1.read())
f1.write("wgdugae\n")
try:
    f2=open("f2.txt","r+")
except(Exception):
    from file import f2c
    f2=f2c()
f2.write(f1.read)
print("f2 reading\n",f2.read())

def f2c():
    f2=open("f2.txt","w+")
    return f2


# -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
#    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/>.
#
##############################################################################
from openerp.osv import osv, fields

class prog_lenguajes(osv.osv):
  _name = 'prog.lenguajes'
  _description = 'lenguajes'
  _rac_name='name'
  _columns = {
    'image': fields.binary("Imagen", help="Seleccionar imagen aqui"),
    'name': fields.char('Lenguajes', size=400, required=True),
    }
prog_lenguajes()


import os

freq =800
fs = 16000//2
cir = fs//freq
n_window = 128      # windows size for FFT
n_overlap = 64     # overlap of window

frame_count = 6
n_rightward_extent = 4
n_leftward_extent = 3
n_forward_hop = 1
n_concat = n_rightward_extent + n_leftward_extent

###global parameter
batch_size = 256
epochs = 4
echo_times = 1
save_times = 10

train_snr = 10
test_snr = 10

magnification = 2
n_concat = 7
n_hop = 1
isOut = True

n_MFCC = 41
n_MFCC_IRM = 40
n_GFCC = 30
n_GFCC_IRM = 64

distance = 100
###path parameter
workspace = os.path.join("..", "Data", "multiObjectLearning_%d"%distance, "workspace")
mixed_audio_dir = os.path.join(workspace, "mixed_audio")
feature_dir = os.path.join(workspace, "feature")
packed_feature_dir = os.path.join(workspace, "packed_feature")
model_dir = os.path.join(workspace, "model")
enhanced_wav_dir = os.path.join(workspace, "enh_wavs")

mini_data_dir = os.path.join("..", "Data", "multiObjectLearning_%d"%distance, "mini_data")

tr_speech_dir = os.path.join(mini_data_dir, "train_speech")
tr_noise_dir = os.path.join(mini_data_dir, "train_noise")
te_speech_dir = os.path.join(mini_data_dir, "test_speech")
te_noise_dir = os.path.join(mini_data_dir, "test_noise")
train_dir = os.path.join(mini_data_dir, "train")
test_dir = os.path.join(mini_data_dir, "test")
rev_dir = os.path.join(mini_data_dir, "rev")
des_dir = os.path.join(mini_data_dir, "des")

###网络配置
#n_freq = 257
#n_freq = 129
n_freq = 65
n_concat = n_leftward_extent + n_rightward_extent + 1

mol_input = [['mixed_LPS', (n_concat, n_freq)], ['mixed_MFCC', (n_concat, n_MFCC)],
	['mixed_GFCC', (n_concat, n_GFCC)]]

mol_output = [['speech_LPS', 'linear', n_freq], ['dynamic_noise_LPS', 'linear', n_freq],
	['LPS_IRM', 'sigmoid', n_freq], ['speech_MFCC', 'linear', n_MFCC],
	['dynamic_noise_MFCC', 'linear', n_MFCC], ['MFCC_IRM','sigmoid', n_MFCC_IRM],
	['speech_GFCC', 'linear', n_GFCC], ['dynamic_noise_GFCC', 'linear', n_GFCC],
	['GFCC_IRM', 'sigmoid', n_GFCC_IRM]]

moe_input = [['mixed_LPS', n_freq], ['speech_LPS', n_freq], ['dynamic_noise_LPS', n_freq],
	['LPS_IRM', n_freq], ['mixed_MFCC', n_MFCC], ["speech_MFCC", n_MFCC],
	['dynamic_noise_MFCC', n_MFCC], ['MFCC_IRM', n_MFCC_IRM],
	['mixed_GFCC', n_GFCC], ['speech_GFCC', n_GFCC], ['dynamic_noise_GFCC', n_GFCC],
	['GFCC_IRM', n_GFCC_IRM]]

moe_output = [["main_speech_LPS", "linear", n_freq], ["main_LPS_IRM", 'sigmoid', n_freq],
	['main_speech_MFCC', 'linear', n_MFCC], ['main_MFCC_IRM', 'sigmoid', n_MFCC_IRM],
	['main_speech_GFCC', 'linear', n_GFCC], ['main_GFCC_IRM', 'sigmoid', n_GFCC_IRM] ]

mol_predict_attributes = ['mixed_LPS', 'mixed_MFCC', 'mixed_GFCC', 'speech_LPS', 'dynamic_noise_LPS', 'LPS_IRM',
	'speech_MFCC', 'dynamic_noise_MFCC', 'MFCC_IRM', 'speech_GFCC', 'dynamic_noise_GFCC', 'GFCC_IRM']

test_mol_iter = 40
test_moe_iter = 40
verbose = 2


import tensorflow as tf
import tensorflow.contrib.keras as keras
import numpy as np

class KERAS():
    def build(X_train, y_train_onehot, param, layers):
        model = keras.models.Sequential()

        model.add(keras.layers.Dense(
                units=param,
                input_dim=X_train.shape[1],
                kernel_initializer='glorot_uniform',
                bias_initializer='zeros',
                activation='relu'))

        for i in range(layers):
                model.add(keras.layers.Dense(
                        units=param,
                        input_dim=param,
                        kernel_initializer='glorot_uniform',
                        bias_initializer='zeros',
                        activation='relu'))

        model.add(keras.layers.Dense(
                units=y_train_onehot.shape[1],
                input_dim=param,
                kernel_initializer='glorot_uniform',
                bias_initializer='zeros',
                activation='softmax'))

        optimizer = keras.optimizers.Adam(lr=0.001)

        model.compile(optimizer=optimizer, loss='categorical_crossentropy')
        return model

    def fit(model, X_train, y_train_onehot, epochs, batch_size):
        history = model.fit(X_train, y_train_onehot, batch_size=batch_size, epochs=epochs,
                            verbose=1,
                            validation_split=None)
        return model, history.history['loss']

    def predict(model, X_test):
        return model.predict_classes(X_test, verbose=0)