# coding=utf-8
import logging
import pytz
from datetime import datetime

from odoo import api, fields, models, _
from odoo.exceptions import ValidationError, UserError

_logger = logging.getLogger(__name__)

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

    busqueda_ruc = fields.Char(
        string='Busqueda RUC',
    )
    @api.onchange('busqueda_ruc')
    def onchange_busqueda_ruc(self):
        if(self.busqueda_ruc is not False):
            cli = self.env['res.partner'].search([('nro_documento','=',self.busqueda_ruc)])
            if(len(cli)>0):
                self.partner_id = cli[0]
                self.busqueda_ruc=False
            else:
                raise ValidationError(u'No se encuentra el Cliente con RUC: ' + self.busqueda_ruc)

    def _get_tipo_documento(self):
        param = self.env['sale.parameters.it'].search([])
        if param.type_document_id:
            return param.type_document_id.id

    def _get_serie(self):
        param = self.env['sale.parameters.it'].search([])
        if param.invoice_serie_id:
            return param.invoice_serie_id

    def _get_account_journal(self):
        param = self.env['sale.parameters.it'].search([])
        if param.account_journal_id:
            return param.account_journal_id.id

    def _get_einvoice_means_payment(self):
        param = self.env['sale.parameters.it'].search([])
        if param.means_payment_id:
            return param.means_payment_id.id

    def _get_partner_id(self):
        param = self.env['main.parameter'].search([])
        if param.partner_venta_boleta:
            return param.partner_venta_boleta.id

    doc_search = fields.Char(u'Buscar x nro documento')
    partner_id = fields.Many2one('res.partner', string='Customer', readonly=True,
                                 states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, required=True,
                                 change_default=True, index=True, track_visibility='always', default=_get_partner_id)
    it_type_document = fields.Many2one('einvoice.catalog.01', u'Tipo de documento',
                                       states={'draft': [('readonly', False)], 'sent': [('readonly', False)]})
    it_invoice_serie = fields.Many2one('it.invoice.serie', u'Serie',
                                       states={'draft': [('readonly', False)], 'sent': [('readonly', False)]})
    sequence_id = fields.Many2one('ir.sequence', related='it_invoice_serie.sequence_id')
    invoice_number = fields.Char(u'Número', store=True, readonly=False, required=True)
    account_journal = fields.Many2one('account.journal', u'Diario de pago', default=_get_account_journal,
                                      states={'draft': [('readonly', False)], 'sent': [('readonly', False)]})
    einvoice_means_payment = fields.Many2one('einvoice.means.payment', u'Medio de pago',
                                             default=_get_einvoice_means_payment,
                                             states={'draft': [('readonly', False)], 'sent': [('readonly', False)]})

    @api.onchange('warehouse_id')
    def onchange_warehouse_id(self):
        for order in self:
            warehouse_id = order.warehouse_id
            tipo_doc_id = warehouse_id.tipo_doc_id
            serie_id = warehouse_id.invoice_serie_id
            if not serie_id:
                tipo_doc_id = order._get_tipo_documento()
                serie_id = order._get_serie()
            invoice_number = self.obtener_numero(serie_id)
            order.update({
                'it_type_document': tipo_doc_id,
                'it_invoice_serie': serie_id,
                'invoice_number': invoice_number
            })

            # order.it_type_document = tipo_doc_id
            # order.it_invoice_serie = serie_id
            # order.invoice_number = self.obtener_numero(serie_id)

    @api.onchange('it_invoice_serie')
    def onchange_invoice_id(self):
        for order in self:
            self.invoice_number = self.obtener_numero(self.it_invoice_serie)

    @api.model
    @api.returns('self', lambda value: value.id)
    def create(self, vals):
        if not vals.get('invoice_number', False):
            serie_id = self.env['it.invoice.serie'].browse(vals.get('it_invoice_serie'))
            vals.update({'invoice_number': self.obtener_numero(serie_id)})
        return super(SaleOrder, self).create(vals)

    def obtener_numero(self, serie_id):

        sequence_id = serie_id.sequence_id
        padding = sequence_id.padding
        prefix = sequence_id.prefix
        numero = sequence_id.number_next
        siguiente = '%s%0{}d'.format(padding) % (prefix, numero)
        return siguiente

    @api.onchange('doc_search')
    def onchange_doc_search(self):
        partner = self.env['res.partner'].search([('nro_documento', '=', self.doc_search)], limit=1)
        if partner.exists():
            return {
                'value': {'partner_id': partner.id}
            }
        else:
            raise UserError(_('Cliente no encontrado'))


from tools.multireplace import MultiReplace
import logging

class Cleanup(object):
    def __new__(cls, data):
        """
        Strips given data.
        :param data: string
        :return: string
        """
        try:
            if data is not None:
                data = MultiReplace(str(data), {u'\xa0': u'', '\n': '', '  ': '', '\t': ''})
            else:
                data = ""
        except Exception as error:
            logging.warning("CLEANUP FOUT: data: " + str(data) + ". Error: {0}".format(error))

        return data


import json
import jsonschema

from django.core.management import call_command
from django.test.client import Client
from jsonschema import validate
from io import StringIO

from apps.dot_ext.tests.test_models import TestDotExtModels
from apps.test import BaseApiTest

from .audit_logger_schemas import GLOBAL_STATE_METRICS_LOG_SCHEMA

loggers = [
    'audit.global_state_metrics'
]

class TestLoggersGlobalMetricsManagementCommand(BaseApiTest):

    def setUp(self):
        # Setup the RequestFactory
        self.client = Client()
        self._redirect_loggers(loggers)

    def tearDown(self):
        self._cleanup_logger()

    def _get_log_content(self, logger_name):
        return self._collect_logs(loggers).get(logger_name)

    def _validateJsonSchema(self, schema, content):
        try:
            validate(instance=content, schema=schema)
        except jsonschema.exceptions.ValidationError as e:
            # Show error info for debugging
            print("jsonschema.exceptions.ValidationError: ", e)
            return False
        return True

    def test_management_command_logging(self):
        # Run test method from apps/dot_ext/tests/test_models.py to populate DB with applicaiton entries.
        TestDotExtModels().test_application_count_funcs()

        # Create 5x Real (positive FHIR_ID) users
        for cnt in range(5):
            self._create_user('johnsmith' + str(cnt), 'password',
                              first_name='John1' + str(cnt),
                              last_name='Smith',
                              email='john' + str(cnt) + '@smith.net',
                              fhir_id='2000000000000' + str(cnt),
                              user_hicn_hash='239e178537ed3bc486e6a7195a47a82a2cd6f46e911660fe9775f6e00000000' + str(cnt),
                              user_mbi_hash='9876543217ed3bc486e6a7195a47a82a2cd6f46e911660fe9775f6e00000000' + str(cnt))

        # Create 7x Synthetic (negative FHIR_ID) users and access tokens for application2
        for cnt in range(7):
            self._create_user('johndoe' + str(cnt), 'password',
                              first_name='John' + str(cnt),
                              last_name='Doe',
                              email='john' + str(cnt) + '@doe.net',
                              fhir_id='-2000000000000' + str(cnt),
                              user_hicn_hash='255e178537ed3bc486e6a7195a47a82a2cd6f46e911660fe9775f6e00000000' + str(cnt),
                              user_mbi_hash='987654321aaaa11111aaaa195a47a82a2cd6f46e911660fe9775f6e00000000' + str(cnt))

        '''
        Call management command that produces the following entry to be validated with JsonSchema:

            {"type": "global_state_metrics", "group_timestamp": "2021-04-12T19:24:00+00:00",
             "real_bene_cnt": 5, "synth_bene_cnt": 7, "global_apps_active_cnt": 7,
             "global_apps_inactive_cnt": 3, "global_apps_require_demographic_scopes_cnt": 5}
        '''
        out = StringIO()
        call_command("log_global_state_metrics", stdout=out, stderr=StringIO())

        # Validate log entry
        log_content = self._get_log_content('audit.global_state_metrics')
        self.assertIsNotNone(log_content)
        log_content_dict = json.loads(log_content)
        self.assertTrue(self._validateJsonSchema(GLOBAL_STATE_METRICS_LOG_SCHEMA, log_content_dict))


#!/usr/bin/python

#script to get the download links from the annotation file

import re
import sys

def getDownloadLinks(annot_file, filename):
   f = open(annot_file, 'r')
   with open(filename, 'w') as fh:
      for row in f:
         if row[0] == '#':
            continue

         #get the download link
         link = str(row.split(',')[8]) + '\n'
         fh.write(link)

if __name__ == '__main__':
   getDownloadLinks(sys.argv[1], sys.argv[2])


from setuptools import find_packages, setup
from package import Package

try:
    setup(
        version="1.0",
        author="Shreyansh Kumar",
        author_email="shreyansh.kumar2012@vitalum.ac.in",
        packages=find_packages(),
        include_package_data=True,
        cmdclass={
            "package": Package
        }
    )
except Exception as e:
    msg = e
    print("Error occurred:",msg)


import os
import json
import uuid
import datetime
from flask import Flask, jsonify, Response, request, session,\
    redirect, url_for
from sqlalchemy import Column, String, DateTime
from sqlalchemy.dialects.postgresql import JSON
from jianyue.database import init_db, db_session
from flask_restful import Api
from jianyue.models import JianYue, JianYueSchema
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow

from requests_oauthlib import OAuth2Session

import config

app = Flask(__name__)
api = Api(app)
app.config.from_object('config')
app.config.from_pyfile('config.py')
db = SQLAlchemy(app)
ma = Marshmallow(app)

class JianYue(db.Model):
    """

    """
    __tablename__ = 'jianyue'

    gid = Column(String, primary_key=True)
    openid = Column(String, unique=True)
    auth_type = Column(String)
    createtime = Column(DateTime)
    modifytime = Column(DateTime)
    jianyue = Column(JSON)

    def __init__(self, gid=None, openid=None, auth_type=None, createtime=None,
                 modifytime=None,jianyue=None):
        self.gid = gid
        self.openid = openid
        self.auth_type = auth_type
        self.createtime = createtime
        self.modifytime = modifytime
        self.jianyue = jianyue

    def __repr__(self):
        return self.__tablename__

class JianYueSchema(ma.Schema):
    class Meta:
        fields = ('gid', 'openid', 'auth_type',
                   'jianyue')

jianyue_schema = JianYueSchema()
jianyues_schema = JianYueSchema(many=True)

@app.teardown_request
def shutdown_seesion(exception=None):
    db_session.remove()

@app.route('/github', methods=['GET'])
def github_auth_login():
    github = OAuth2Session(config.client_id)
    authorization_url, state = github.authorization_url(config.authorization_base_url)
    session['oauth_state'] = state
    return redirect(authorization_url)

@app.route('/callback', methods=['GET'])
def callback():
    github = OAuth2Session(config.client_id, state=session['oauth_state'])
    token = github.fetch_token(config.token_url, client_secret=config.client_secret, authorization_response=request.url)
    session['oauth_token'] = token
    jy = JianYue.query.filter(JianYue.openid == token['access_token']).first()
    if jy == None:
        now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
        gid = uuid.uuid3(uuid.NAMESPACE_DNS, now)
        jianyue = JianYue(gid=str(gid), openid=token['access_token'], createtime=now, modifytime=now)
        db.session.add(jianyue)
        db.session.commit()
    return redirect(url_for('.profile'))

@app.route("/profile", methods=["GET"])
def profile():
    """Fetching a protected resource using an OAuth 2 token.
    """
    github = OAuth2Session(config.client_id, token=session['oauth_token'])
    return jsonify(github.get('https://api.github.com/user').json())

@app.route('/users/<int:page>')
def get_all_users(page):
    jianyues = JianYue.query.limit(page)
    result = jianyues_schema.dump(jianyues)
    return Response(json.dumps(result.data), mimetype='Application/json')

@app.route('/user')
def get_user():
    gid = request.args.get('gid')
    auth_type = request.args.get('auth_type')
    jianyues = JianYue.query.filter(JianYue.gid == gid and JianYue.auth_type == auth_type)
    result = jianyues_schema.dump(jianyues)
    return Response(json.dumps(result.data), mimetype='Application/json')

@app.route('/jianyue/api/v0.1', methods=['post'])
def jianyue_api():
    jianyue_data = request.get_json(force=True)
    gid = jianyue_data['gid']
    openid = jianyue_data['openid']
    auth_type = jianyue_data['auth_type']
    createtime = jianyue_data['createtime']
    modifytime = jianyue_data['modifytime']
    jianyue = jianyue_data['jianyue']
    jianyue_model = JianYue(gid=gid, openid=openid, auth_type=auth_type, createtime=createtime,
                            modifytime=modifytime, jianyue=jianyue)
    db.session.add(jianyue_model)
    db.session.commit()
    return jsonify({'status': 'ok'})

@app.route('/jianyue/api/v0.1/<gid>', methods=['PUT'])
def update_jianyue(gid):
    jianyue = JianYue.query.filter(JianYue.gid == gid).first()
    json_data = request.get_json(force=True)
    jianyue.createtime = json_data['createtime']
    jianyue.modifytime = json_data['modifytime']
    jianyue.jianyue = json_data['jianyue']
    jianyue.auth_type = json_data['auth_type']
    db.session.commit()
    return jsonify({'status': 'ok'})

@app.route('/jianyue/api/v0.1/<gid>', methods=['DELETE'])
def delete_jianyue(gid):
    JianYue.query.filter(JianYue.gid == gid).delete()
    db.session.commit()
    return jsonify({'status': 'ok'})

if __name__ == '__main__':
    #init_db()
    #os.environ['DEBUG'] = "1"
    os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
    app.secret_key = os.urandom(24)
    app.run(host='127.0.0.1', port=5000, debug=True)


import Global
import pygame
#constant
class Local(object):
	@staticmethod
	def init():
		Global.load_const(Local, "Combo")
		Local.font=pygame.font.SysFont(Local.font_name,
				Local.text_size, True, False)
Local.init()

class Combo(object):
	@classmethod
	def start(cls):
		cls.combo=0

	@classmethod
	def end(cls):
		pass

	@classmethod
	def draw(cls):
		if cls.combo == 0 :
			return
		if cls.combo > 1 :
			string="%d combos!" % cls.combo
		else :
			string="%d combo!" % cls.combo
		text=Local.font.render(string, True, Local.text_color)
		Global.screen.blit(text, Local.left_up_point)

	@classmethod
	def tick(cls):
		pass

	@classmethod
	def reset_combo(cls):
		cls.combo=0

	@classmethod
	def add_combo(cls, combo):
		cls.combo+=combo

	@classmethod
	def get_bonus(cls):
		return cls.combo

start=Combo.start
end=Combo.end
draw=Combo.draw
tick=Combo.tick
add_combo=Combo.add_combo
reset_combo=Combo.reset_combo
get_bonus=Combo.get_bonus


from node import Node

class LinkedList:
    """LinkedList Data Structure."""

    def __init__(self):
        """LinkedList initialisation."""
        self.head = None
        self.length = 0

    def __len__(self):
        return self.length

    def prepend(self, data):
        """Adding node at the start of LinkedList.
        Complexity is O(1)."""
        self.head = Node(data, self.head)
        self.length += 1

    def append(self, data):
        """Traverses throught the LinkedList and
        adds node at the end of LinkedList.
        Complexity is O(n)."""
        if self.head is None:
            self.prepend(data)
            return
        current_node = self.head
        while current_node.next:
            current_node = current_node.next
        current_node.next = Node(data, None)
        self.length += 1

    def insert(self, data, index):
        """Insert a Node at index i. Complexity O(n)."""
        current_node = self.head
        counter = 1

        if self.length <= index:
            raise IndexError('Index out of range!!!')

        while counter < index:
            current_node = current_node.next
            counter += 1

        current_node.next = Node(data, current_node.next)
        self.length += 1

    def remove(self, index):
        """Remove a Node at index i. Complexity O(n)."""
        pass

    def search(self, data):
        """Search for node in LinkedList and return position.
        Complexity O(n)."""
        current_node = self.head
        counter = 0
        while current_node:
            if current_node.data == data:
                return counter
            current_node = current_node.next
            counter += 1
        return -1

    def __str__(self):
        """String representation of Single LinkedList.
        For Eg: 1 <- 2 <- 3."""
        current_node = self.head
        output = ''
        while current_node:
            output += '{}'.format(current_node.data)
            if current_node.next is not None:
                output += '<-'
            current_node = current_node.next
        return output

ll = LinkedList()
ll.prepend(10)
ll.prepend(20)
print(ll)
ll.prepend(50)
print(ll)
ll.insert(100, 1)
print(ll)

print("-"*20)

ll1 = LinkedList()
ll1.append(10)
ll1.append(20)
ll1.append(50)
print(ll1)
ll1.insert(100, 1)
print(ll1)

print("-"*20)

ll1 = LinkedList()
ll1.insert(100, 0)
print(ll1)


import paddle
import data
from paddle.io import BatchSampler, DataLoader
import os
import classify
import cfg
from paddle import nn
from paddle import optimizer
from argparse import ArgumentParser, RawDescriptionHelpFormatter
import regularizer
from stats import *
from metrics import ClsMetric
from postprocess import ClsPostProcess
from utils import save_model, get_logger

def make_argparse():
    args = ArgumentParser("paddle train params")
    args.add_argument("--batch_size", type=int, default=256)
    args.add_argument("--log_smooth_window", type=int, default=20)
    args.add_argument("--resume", type=bool, default=False)
    args.add_argument("--layer", type=int, default=18)
    args.add_argument("--best_acc", type=float, default=0.8)
    args.add_argument("--save_model_path", type=str,
                      default="/data/yujiangyong/Projects/products/model_files/paddle_softmax3")
    args.add_argument("--save_epoch_step", type=int, default=10000)
    args.add_argument("--eval_epoch_step", type=int, default=10000)
    args.add_argument("--print_step", type=int, default=20)
    args.add_argument("--epoch_num", type=int, default=20)
    args.add_argument("--learning_rate", type=float, default=0.0001)
    return args.parse_args()

def build_dataloader(char_idx_dict, idx_char_dict, batch_size,
                     img_h, img_w, train_txt_path1, train_txt_path2, train_txt_path3):
    dataset = data.SimpleDataSet(char_idx_dict, idx_char_dict, batch_size,
                                 img_h, img_w, train_txt_path1, train_txt_path2, train_txt_path3)
    batch_sampler = BatchSampler(
        dataset=dataset,
        batch_size=batch_size,
        shuffle=False,
        drop_last=True)

    data_loader = DataLoader(
        dataset=dataset,
        batch_sampler=batch_sampler,
        places='gpu:0',
        num_workers=16,
        return_list=True,
        use_shared_memory=False)
    return data_loader

def build_eval_dataloader(char_idx_dict, idx_char_dict, batch_size,
                          img_h, img_w, eval_txt_path, eval_root_path):
    dataset = data.EvalDataSet(char_idx_dict, idx_char_dict, batch_size,
                               img_h, img_w, eval_txt_path, eval_root_path)
    batch_sampler = BatchSampler(
        dataset=dataset,
        batch_size=batch_size,
        shuffle=False,
        drop_last=False)

    data_loader = DataLoader(
        dataset=dataset,
        batch_sampler=batch_sampler,
        places='gpu:0',
        num_workers=1,
        return_list=True,
        use_shared_memory=True)
    return data_loader

class ClassifyLoss(nn.Layer):
    def __init__(self, **kwargs):
        super(ClassifyLoss, self).__init__()
        self.loss_func = nn.CrossEntropyLoss(reduction="mean")

    def forward(self, predicts, batch):
        label = batch["label"].astype("int64")
        loss = self.loss_func(predicts, label)
        return {"loss": loss}

class Adam(object):
    def __init__(self,
                 learning_rate=0.001,
                 beta1=0.9,
                 beta2=0.999,
                 epsilon=1e-08,
                 parameter_list=None,
                 weight_decay=None,
                 grad_clip=None,
                 name=None,
                 lazy_mode=False,
                 **kwargs):
        self.learning_rate = learning_rate
        self.beta1 = beta1
        self.beta2 = beta2
        self.epsilon = epsilon
        self.parameter_list = parameter_list
        self.learning_rate = learning_rate
        self.weight_decay = weight_decay
        self.grad_clip = grad_clip
        self.name = name
        self.lazy_mode = lazy_mode

    def __call__(self, parameters):
        opt = optimizer.Adam(
            learning_rate=self.learning_rate,
            beta1=self.beta1,
            beta2=self.beta2,
            epsilon=self.epsilon,
            weight_decay=self.weight_decay,
            grad_clip=self.grad_clip,
            name=self.name,
            lazy_mode=self.lazy_mode,
            parameters=parameters)
        return opt

def build_optimizer(learning_rate, parameters):
    reg = regularizer.L2Decay()()
    optim = Adam(learning_rate=learning_rate, weight_decay=reg)
    return optim(parameters)

def model_eval(model,
               valid_dataloader,
               post_process_class,
               eval_class):
    model.eval()
    with paddle.no_grad():
        max_iter = len(valid_dataloader)
        for idx, batch in enumerate(valid_dataloader):
            if idx >= max_iter:
                break
            images = batch["image"]
            preds = model(images)
            post_result = post_process_class(preds, batch["label"])
            eval_class(post_result, batch)
        metric = eval_class.get_metric()
    model.train()
    return metric

def main():
    flags = make_argparse()
    global_step = 0
    save_epoch_step = flags.save_epoch_step
    eval_epoch_step = flags.eval_epoch_step
    print_step = flags.print_step
    start_epoch = 0
    log_smooth_window = flags.log_smooth_window
    epoch_num = flags.epoch_num
    save_model_dir = flags.save_model_path
    if not os.path.exists(save_model_dir):
        os.makedirs(save_model_dir)
    log_file = '{}/train.log'.format(save_model_dir)
    logger = get_logger(name='root', log_file=log_file)
    if flags.layer == 50:
        model = classify.Classify(1, cfg.NUMBER_CLASSES, 2048, 50)
    else:
        model = classify.Classify(1, cfg.NUMBER_CLASSES, 512, 18)
    print(flags.best_acc)
    if flags.resume:
        best_model_dict = {"acc": flags.best_acc}
        old_model_path = os.path.join(flags.save_model_path, "best_accuracy.pdparams")
        para_dict = paddle.load(old_model_path)
        model.set_state_dict(para_dict)
    else:
        best_model_dict = {"acc": 0}
    model.train()

    loss_class = ClassifyLoss()
    postprocess_class = ClsPostProcess(label_list=cfg.idx_to_char)
    acc_class = ClsMetric(main_indicator="acc")

    optimizer_ocr = build_optimizer(flags.learning_rate, model.parameters())

    eval_data_loader = build_eval_dataloader(char_idx_dict=cfg.char_to_idx,
                                             idx_char_dict=cfg.idx_to_char,
                                             batch_size=flags.batch_size,
                                             img_h=cfg.img_h,
                                             img_w=cfg.img_w,
                                             eval_txt_path=cfg.eval_txt_path,
                                             eval_root_path=cfg.eval_data_dir)
    train_data_loader = build_dataloader(char_idx_dict=cfg.char_to_idx,
                                         idx_char_dict=cfg.idx_to_char,
                                         batch_size=flags.batch_size,
                                         img_h=cfg.img_h,
                                         img_w=cfg.img_w,
                                         train_txt_path1=cfg.train_txt_path1,
                                         train_txt_path2=cfg.train_txt_path2,
                                         train_txt_path3=cfg.train_npy_path3)

    for epoch in range(start_epoch, epoch_num + 1):
        max_iter = len(train_data_loader)
        train_stats = TrainingStats(log_smooth_window, ['lr'])
        for idx, batch in enumerate(train_data_loader):
            if idx > max_iter:
                break
            lr = optimizer_ocr.get_lr()
            preds = model(batch["image"])
            loss = loss_class(preds, batch)
            avg_loss = loss['loss']
            avg_loss.backward()
            optimizer_ocr.step()
            optimizer_ocr.clear_grad()

            stats = {k: v.numpy().mean() for k, v in loss.items()}
            stats['lr'] = lr

            train_stats.update(stats)
            post_result = postprocess_class(preds, batch["label"])

            acc_class(post_result)
            metric = acc_class.get_metric()
            train_stats.update(metric)
            logs = train_stats.log()
            if global_step > 0 and global_step % print_step == 0:
                strs = "epoch {}, iter {}, {}".format(epoch, idx, logs)
                logger.info(strs)
            if global_step > 0 and global_step % eval_epoch_step == 0:
                cur_metric = model_eval(model,
                                        eval_data_loader,
                                        postprocess_class,
                                        acc_class)
                cur_metric_str = 'cur metric, {}'.format(', '.join(
                    ['{}: {}'.format(k, v) for k, v in cur_metric.items()]))
                logger.info(cur_metric_str)
                if cur_metric["acc"] >= best_model_dict["acc"]:
                    best_model_dict.update(cur_metric)
                    best_model_dict['best_epoch'] = epoch
                    save_model(
                        model,
                        optimizer_ocr,
                        save_model_dir,
                        logger,
                        is_best=True,
                        prefix='best_accuracy',
                        best_model_dict=best_model_dict,
                        epoch=epoch,
                        global_step=global_step)
            if global_step > 0 and global_step % save_epoch_step == 0:
                save_model(
                    model,
                    optimizer_ocr,
                    save_model_dir,
                    logger,
                    is_best=False,
                    prefix='last',
                    epoch=epoch,
                    global_step=global_step)
            optimizer_ocr.clear_grad()
            global_step += 1

if __name__ == "__main__":
    main()


"""
Michael S. Emanuel
Sat Apr 21 22:36:33 2018

Counting fractions
Problem 72

Consider the fraction, n/d, where n and d are positive integers.
If n<d and HCF(n,d)=1, it is called a reduced proper fraction.

If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, we get:

1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7,
3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8

It can be seen that there are 21 elements in this set.

How many elements would be contained in the set of reduced proper fractions for d ≤ 1,000,000?

Solution Outline:
The number of fractions with denominator q is simply phi(q)...
"""

from Euler.Primes import PrimeTable
from Euler.Utility import range_inc

def main() -> int:
    # Maximum of integers to consider
    nMax: int = 10**6
    # Instantiate PrimeTable
    pt: PrimeTable = PrimeTable(nMax)

    # Alias phi function
    def phi(n: int) -> int:
        return pt.totient(n)

    # Print the answer
    ans: int = sum(phi(n) for n in range_inc(2, nMax))
    print(f'The answer is {ans}.')
    return ans

if __name__ == '__main__':
    main()


from root import ROOT_DIR
from cffi import FFI

ffi = FFI()
ffi.cdef("int times2(int x);")

C = ffi.dlopen(ROOT_DIR + "/target/release/liballegory.dylib")

if __name__ == "__main__":
    print(C.times2(9))


from udp_helper import udp
import numpy as np
import matplotlib.pyplot as plt
import sys
import time
from functools import wraps
from threading import Thread
import math
np.set_printoptions(precision=3)
#Supress scientific notation
np.set_printoptions(suppress=True)
# Prevent 0 from bein stripped from end of floats
np.set_printoptions(formatter={'float': '{: 0.3f}'.format})

def notify(func):
    '''
    Decorator that notify event start and ends
    '''
    @wraps(func)
    def wrapper(*args,**kwargs):
        print("Event:",func.__name__, " started")
        func(*args,**kwargs)
        print("Event:",func.__name__, " ended")
    return wrapper

def mapangle(angle,ll,ul):
    if angle < ll:
        controlangle =-1
    elif angle <0 and angle >= ll:
        controlangle = -angle/ll

    elif angle>=0 and angle <=ul:
        controlangle = angle/ul

    else:
        controlangle=1

    if angle ==-999:
        controlangle=-999

    return controlangle

class aircraft:
    def __init__(self,connection):
        self.con=connection
        self.t={}
        self.indexarray=[]
        self.valuearray=[]
        self.logdata=[]
        self.con.start()
    def elv(self,val):
        self.con.writedata([8],[[mapangle(val,-10,20),-999,-999,-999,-999,-999,
                           -999,-999]])

    def ail(self,val):
        self.con.writedata([8],[[-999,mapangle(val,-10,20),-999,-999,-999,-999,
                           -999,-999]])

    def rud(self,val):
        self.con.writedata([8],[[-999,-999,mapangle(val,-25,25),-999,-999,-999,
                           -999,-999]])

    def Vind(self):
        return self.con.readdata()[3][1]

    def pitch(self):
        return self.con.readdata()[17][0]

    def state(self):
        data=self.con.readdata()
        t = data[1][1]
        pitch = data[17][0]
        roll = data[17][1]
        yaw = data[17][2]
        aoa=data[18][0]
        sideslip=data[18][1]
        flightpath=data[18][3]
        lat = data[20][0]
        lon = data[20][1]
        alt = data[20][2]
        return (t,pitch,roll,yaw,aoa,sideslip,flightpath,lat,lon,alt)

    def controlsurface(self):
        data=self.con.readdata()
        t = data[1][1]
        elv = data[11][0]
        ail = data[11][1]
        rud = data[11][2]
        return (t,elv,ail,rud)

    def speed(self):
        data=self.con.readdata()
        t = data[1][1]
        Vias = data[3][0]
        Veas = data[3][1]
        Vktas = data[3][2]
        Vktgs = data[3][3]
        Q = data[16][0]
        P = data[16][1]
        R = data[16][2]
        return (t,Vias,Veas,Vktas,Vktgs,Q,P,R)

    def throttle(self,val):
        self.con.writedata([25],[[val,val,val,val,-999,-999,-999,-999]])

    def control(self,elv=-999,ail=-999,rud=-999):
        self.con.writedata([8],[[mapangle(elv,-10,20),mapangle(ail,-10,20),
            mapangle(rud,-25,25),-999,-999,-999,-999,-999]])

    def resetcontrol(self):
        self.control(elv=0,ail=0,rud=0)

    def brake(self,val):
        self.con.writedata([14],[[-999,val,-999,-999,-999,-999,-999,-999]])

    def gear(self,val):
        self.con.writedata([14],[[val,-999,-999,-999,-999,-999,-999,-999]])

    def elv_trim(self,val):
        self.con.writedata([13],[[val,-999,-999,-999,-999,-999,-999,-999]])

    @notify
    def takeoff(self,Vto=155,timeout=0):
        self.resetcontrol()
        self.throttle(1)
        self.brake(0)
        speed = self.speed()[1]
        while abs(speed - Vto) >= 10:
            state =self.state()
            speed = self.speed()[1]
        self.pitchpid(timeout=10,desired=20,Kp=1)
        self.run(b747.rollpid,timeout=10,Kp=0.8,Kd=0.3)
        self.run(b747.yawpid,timeout=10,desired=118,Kp=0.3)
        self.gear(0)

    @notify
    def pitchpid(self,timeout=60,Kp=0.0,Ki=0.0,Kd=0.0,desired = 0):
        state_old=self.state()
        error_old=0
        integral=0
        tstart = state_old[0]
        told=tstart
        t =0
        dt=0.001
        while t - tstart < timeout:
            #Get aircraft current state
            state=self.state()
            t= state[0]
            if t - told > dt:
                #PID control
                error = (desired - state[1])
                dt = t-told
                integral = integral + error * dt
                derivative = (error-error_old)/dt
                self.control(elv=Kp*(error)+Ki*(integral)+Kd*(derivative))
                #self.control(elv=Kp*(error))
                #Reset for new loop
                error_old=error
                told=t

    @notify
    def flightpathpid(self,timeout=60,Kp=0.0,Ki=0.0,Kd=0.0,desired = 0):
        state_old=self.state()
        error_old=0
        integral=0
        tstart = state_old[0]
        told=tstart
        t=0
        dt=0.001
        while t - tstart < timeout:
            #Get aircraft current state
            state=self.state()
            t= state[0]
            if t - told > dt:
                #PID control
                error = (desired - state[6])
                dt = t-told
                integral = integral + error * dt
                derivative = (error-error_old)/dt
                self.control(elv=Kp*(error)+Ki*(integral)+Kd*(derivative))
                #Reset for new loop
                error_old=error
                told=t

    @notify
    def altitudepid(self,timeout=60,Kp=0.0,Ki=0.0,Kd=0.0,desired = 0):
        state_old=self.state()
        error_old=0
        integral=0
        tstart = state_old[0]
        told=tstart
        t=0
        dt=0.001
        while t - tstart < timeout:
            #Get aircraft current state
            state=self.state()
            t= state[0]
            if t - told > dt:
                #PID control
                error = (desired - state[9])
                dt = t-told
                integral = integral + error * dt
                derivative = (error-error_old)/dt
                self.control(elv=Kp*(error)+Ki*(integral)+Kd*(derivative))
                #Reset for new loop
                error_old=error
                told=t
    @notify
    def rollpid(self,timeout=60,Kp=0.0,Ki=0.0,Kd=0.0,desired = 0):
        state_old=self.state()
        error_old=0
        integral=0
        tstart = state_old[0]
        told=tstart
        t=0
        dt=0.001
        while t - tstart < timeout:
            #Get aircraft current state
            state=self.state()
            t= state[0]
            if t - told > dt:
                #PID control
                error = (desired - state[2])
                dt = t-told
                integral = integral + error * dt
                derivative = (error-error_old)/dt
                self.control(ail=Kp*(error)+Ki*(integral)+Kd*(derivative))
                #self.control(ail=Kp*(error))
                #Reset for new loop
                error_old=error
                told=t

    @notify
    def yawpid(self,timeout=60,Kp=0.0,Ki=0.0,Kd=0.0,desired = 0.0):
        state_old=self.state()
        error_old=0
        integral=0
        tstart = state_old[0]
        told=tstart
        t=0
        dt=0.001
        while t - tstart < timeout:
            #Get aircraft current state
            state=self.state()
            t= state[0]
            if t - told > dt:
                #PID control
                error = (desired - state[3])
                integral = integral + error * dt
                derivative = (error-error_old)/dt
                control=Kp*(error)+Ki*(integral)+Kd*(derivative)
                #control=Kp*(error)
                self.control(rud=control)
                #Reset for new loop
                error_old=error
                told=t
                #print("Error,Control:",error,control)

    def run(self,event,*args,**kwargs):
        self.t[event.__name__] = Thread(target = event,args=args,kwargs=kwargs)
        self.t[event.__name__].start()

    def wait_speed(self,wait_speed,epsilon=5):
        speed =self.speed()[1]
        while abs(speed-wait_speed)<epsilon:
            pass

    def stop(self):
        for eventname,event in self.t.items():
            event.join()
        print("Events ended succesfully")

def b747_test():
    conn =udp('127.0.0.1',49003,'127.0.0.1',49000)
    b747 = aircraft(conn)

    t =[]
    pitch=[]
    #conn.start()
    b747.brake(0)
    b747.throttle(1)

    b747.run(b747.rollpid,timeout=180,Kp=0.8,Kd=0.3)
    b747.run(b747.yawpid,timeout=180,desired=191,Kp=0.3)
    b747.wait_speed(160)
    b747.run(b747.pitchpid,timeout=180,desired=20,Kp=0.5,Ki=0.0,Kd=0.0)

    b747.stop()
    conn.stop()

def pitch_control():
    conn =udp('127.0.0.1',49003,'127.0.0.1',49000)
    b747 = aircraft(conn)

    b747.run(b747.rollpid,timeout=18000,Kp=0.8,Kd=0.3)
    b747.run(b747.yawpid,timeout=18000,desired=191,Kp=0.3)
    b747.run(b747.pitchpid,timeout=18000,desired=20,Kp=0.5,Ki=0.0,Kd=0.0)

    b747.stop()
    conn.stop()

def vistest():
    conn =udp('127.0.0.1',49003,'127.0.0.1',49000)
    i=2285.0
    while True:
        i+=1/10
        try:
            conn.veh1([34.93,-117.8,i],[0.,0.,191.],[0.,0.,0.])
            time.sleep(1)
        except:
            conn.stop()
def setup():
    conn =udp('127.0.0.1',49003,'127.0.0.1',49000)
    #conn.veh1([34.93,-117.8,697.],[0.,0.,0.],[0.,0.,0.])
    conn.papt(type_start=12,rwy_ram=1)
    conn.stop()

if __name__=="__main__":
    b747_test()
    #pitch_control()
    #vistest()
    setup()


import math

class Solution:
    def minArea(self, image, x, y):
        """
        :type image: List[List[str]]
        :type x: int
        :type y: int
        :rtype: int
        """
        deltas = [(-1, 0), (1, 0), (0, -1), (0, 1)]
        xLen = len(image)
        yLen = len(image[0])
        minX = minY = math.inf
        maxX = maxY = -math.inf
        q = [(x, y)]
        visited = [[False for y in range(yLen)] for x in range(xLen)]
        while len(q) > 0:
            nq = []
            for x0, y0 in q:
                minX = min(minX, x0)
                maxX = max(maxX, x0)
                minY = min(minY, y0)
                maxY = max(maxY, y0)
                for dx, dy in deltas:
                    x1, y1 = x0 + dx, y0 + dy
                    if x1 < 0 or x1 >= xLen or y1 < 0 or y1 >= yLen or visited[x1][y1] or image[x1][y1] == '0':
                        continue
                    visited[x1][y1] = True
                    nq.append((x1, y1))
            q = nq
        return (maxX - minX + 1) * (maxY - minY + 1)


import tweepy
from Utils import Utils
from GetTUserDetails import  user
import time
import  multiprocessing as mp

#Intialize twwepy API Connection and Utility Object
util=Utils()
configs=util.ReadConfig()
apiDict={}

cnt=0
for config in configs:
    auth = tweepy.OAuthHandler(config['CONSUMER_KEY'],config['CONSUMER_SECRET'])
    auth.set_access_token(config['ACCESS_TOKEN'],config['ACCESS_SECRET'])
    api=Utils.InitiateAPi(auth)
    apiDict[cnt]=api
    cnt+=1

#Load Seed List
seedList=[]
seed=open('seedIdstest.txt','r')
for u in seed.readlines():
    seedList.append(u.replace('\n',''))

cnt2=0
for u in seedList:
    api=cnt2%5
    cnt2+=1

    try:
      u=user(u,apiDict[api])
      print(str(u) +'processed')
      #print(u  ::' +str(u.auth.consumer_key))

    except:
      Utils.WriteLog(" excpetion occured while extracting details user "+ str(u.username))

    #Get Data for User u
    try:
       start=time.time()
       #extract followers
       u.GetFollowers()
       telapsed=time.time()-start
       #print(" time to extract "+str(u.numFollowers)+ " followers of user "+ str(u.username) + " is " + str(telapsed))
       Utils.WriteLog(" time to extract "+str(u.numFollowers)+ " followers of user "+ str(u.username) + " is " + str(telapsed))
    except:
       Utils.WriteLog(" excpetion occured while extracting followers of user "+ str(u.username))

    try:
       #extract followee
       start=time.time()
       u.GetFollowing(u)
       telapsed=time.time()-start
       #print(" time to extract "+str(u.numFollowed)+ " people followed  by user "+ str(u.username) + " is " + str(telapsed))
       Utils.WriteLog(" time to extract "+str(u.numFollowed)+ " people followed  by user "+ str(u.username) + " is " + str(telapsed))
    except:
       Utils.WriteLog(" excpetion occured while extracting people  followed by user "+ str(u.username))

    try:
        start=time.time()
        #extract followers
        u.GetTweetsasJson()
        telapsed=time.time()-start
        Utils.WriteLog(" time to extract "+str(u.numFTweets)+ " tweets posted  by user "+ str(u.username) + " is " + str(telapsed))
    except:
       print(" time to extract "+str(u.numFTweets)+ " tweets posted  by user "+ str(u.username) + " is " + str(telapsed))
       Utils.WriteLog(" excpetion occured while extracting tweets of user  "+ str(u.username))


from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import numpy as np
from matplotlib import pyplot as plt

from astropy.stats import mad_std
from astropy.io import fits
from photutils import CircularAperture
from astroscrappy import detect_cosmics

from astropy.convolution import convolve_fft, Tophat2DKernel, Gaussian2DKernel
from pyfftw.interfaces.scipy_fftpack import fft2, ifft2

__all__ = ['init_centroids']

def init_centroids(first_image_path, master_flat, master_dark, target_centroid,
                   max_number_stars=10, min_flux=0.2, plots=False):

    first_image = (fits.getdata(first_image_path) - master_dark)/master_flat

    kernel = Gaussian2DKernel(5, 5)
    convolution = convolve_fft(first_image, kernel, fftn=fft2, ifftn=ifft2)

    convolution -= np.median(convolution)

    mad = mad_std(convolution)

    convolution[convolution < -5*mad] = 0.0

    from skimage.filters import threshold_otsu, threshold_yen
    from skimage.measure import label, regionprops

    thresh = threshold_yen(convolution)/4
    # thresh = threshold_otsu(image=convolution) # Use 10 for 20171104, 15 for all other nights

    masked = np.ones_like(convolution)
    masked[convolution <= thresh] = 0

    label_image = label(masked)

    plt.figure()
    plt.imshow(label_image, origin='lower', cmap=plt.cm.viridis)
    plt.show()

    regions = regionprops(label_image, convolution)

    # reject regions near to edge of detector
    buffer_pixels = 5
    regions = [region for region in regions
               if ((region.weighted_centroid[0] > buffer_pixels and
                   region.weighted_centroid[0] < label_image.shape[0] - buffer_pixels)
               and (region.weighted_centroid[1] > buffer_pixels and
                    region.weighted_centroid[1] < label_image.shape[1] - buffer_pixels))]

    # TYC 3561-1538-1 is a delta Scuti variable. Remove it:
    # variable_star = [1790.1645248,  1153.91737674]
    # tol = 100
    # regions = [region for region in regions
    #            if ((region.weighted_centroid[0] > variable_star[0] + tol) or
    #               (region.weighted_centroid[0] < variable_star[0] - tol)) and
    #               ((region.weighted_centroid[1] > variable_star[1] + tol) or
    #               (region.weighted_centroid[1] < variable_star[1] - tol))]

    centroids = np.array([region.weighted_centroid for region in regions])
    intensities = np.array([region.mean_intensity for region in regions])

    sort_order = np.argsort(intensities)[::-1]
    centroids = np.array(centroids)[sort_order]
    intensities = intensities[sort_order]

    positions = np.vstack([[y for x, y in centroids], [x for x, y in centroids]])

    flux_threshold = intensities > min_flux * intensities[0]
    positions = positions[:, flux_threshold]

    if plots:
        apertures = CircularAperture(positions, r=12.)
        apertures.plot(color='r', lw=2, alpha=1)
        plt.imshow(first_image, vmin=np.percentile(first_image, 0.01),
                   vmax=np.percentile(first_image, 99.9), cmap=plt.cm.viridis,
                   origin='lower')
        plt.show()
    return positions

    # target_index = np.argmin(np.abs(target_centroid - positions), axis=1)[0]
    # flux_threshold = sources['flux'] > min_flux * sources['flux'].data[target_index]
    #
    # fluxes = sources['flux'][flux_threshold]
    # positions = positions[:, flux_threshold]
    #
    # brightest_positions = positions[:, np.argsort(fluxes)[::-1][:max_number_stars]]
    # target_index = np.argmin(np.abs(target_centroid - brightest_positions),
    #                          axis=1)[0]
    #
    # apertures = CircularAperture(positions, r=12.)
    # brightest_apertures = CircularAperture(brightest_positions, r=12.)
    # apertures.plot(color='b', lw=1, alpha=0.2)
    # brightest_apertures.plot(color='r', lw=2, alpha=0.8)
    #
    # if plots:
    #     plt.imshow(first_image, vmin=np.percentile(first_image, 0.01),
    #                vmax=np.percentile(first_image, 99.9), cmap=plt.cm.viridis,
    #                origin='lower')
    #     plt.plot(target_centroid[0, 0], target_centroid[1, 0], 's')
    #
    #     plt.show()
    #
    # # Reorder brightest positions array so that the target comes first
    # indices = list(range(brightest_positions.shape[1]))
    # indices.pop(target_index)
    # indices = [target_index] + indices
    # brightest_positions = brightest_positions[:, indices]
    #
    # return brightest_positions


#!/usr/bin/env python
from collections import defaultdict

d1 = dict()
d2 = {'a': 5, 'm': 16, 'e': 42}
d3 = {}
d4 = dict(a=5, m=16, e=42)

keys = ['a', 'm', 'e']
values = [5, 16, 42]

d5 = dict(zip(keys, values))
print(d5)

airports = {
    'EWR': 'Newark',
    'SFO': 'San Francisco',
    'RDU': 'Raleigh-Durham',
    'SJC': 'San Jose',
    'ABQ': 'Albuquerque',
    'OAK': 'Oakland',
    'SAC': 'Sacramento',
    'MLB': 'Melbourne',
    'IAD': 'Dulles',
}

print(airports['MLB'], '\n')

print(airports.get('MLB'))
print(airports.get('MIA'))
print(airports.get('MIA', "NOT FOUND"))
print()

colors = defaultdict(list)

colors['red'] = [25, 15]

print(colors['blue'])

colors['blue'].append(5)
colors['red'].append(20)
colors['blue'].append(35)
print(colors)

things = defaultdict(lambda: 0)

print(things['spam'])
print(things['ham'])

print(airports.setdefault('MIA', 'Miami'))

print(airports, '\n')

more_airports = {'JFK': "Kennedy", "ELM": "Elmira, NY", "HLN": "Helena, MT",
            'MIA': "Miami International"}

airports.update(more_airports)

print(airports, '\n')

for abbr in 'JFK', 'MLB', 'MCO', 'TPA', 'EWR':
    print(abbr, abbr in airports)
print()

for abbr, name in airports.items():
    print(abbr, name)
print()

for abbr, name in sorted(airports.items()):
    print(abbr, name)
print()

for abbr, name in sorted(airports.items(), key=lambda e: (e[1], e[0])):
    print(abbr, name)
print()


'''
    This file is used to decode the bytes received from the bluetooth device and
    store that data for use.

    - Matthew Lee (matt@intellihq.com.au)
'''

class AliveCorModel:
    '''
        This class contains the structure for the decoded
        AliveCor bytestream to be stored.

        packet_header: (dict) {
            sequence: (int),
            battery: (int) 0 < x < 200 where 200 is 100%
        }

        ecg_header: (dict) {
            id: (int),
            length: (int) total num of bytes used for the ECG signal,
            format: (int)
        }

        acc_header: (dict) {
            id: (int),
            length: (int) total num of bytes used for the accelerometer signal,
            format: (int)
        }

        ecg: (list) contains the ECG signal. Length of list is defined in ecg_header['length']
        acc: (list) contains the accelerometer signal. Length of list is defined in acc_header['length']
    '''
    ecg = []
    acc = []

    packet_header = {}
    ecg_header = {}
    acc_header = {}

    def __str__(self):
        ret_str = """
        Packet Header: {} \n
        ECG Header: {} \n
        ACC Header: {} \n
        ECG: {} \n
        ACC: {}""".format(
            self.packet_header,
            self.ecg_header,
            self.acc_header,
            self.ecg,
            self.acc
        )
        return ret_str

def decoder(bytes):
    '''
    This function takes in the bytes from AliveCor's bluetooth device
    and creates an AliveCorModel object. See AliveCorModel class for documentation.
    :param bytes: The bytes receieved from the AliveCor bluetooth device
    :return: AliveCorModel object
    '''
    if isinstance(bytes, str) is False:
        raise TypeError("Bytes is not of type string")

    bytelist = [bin(x) for x in bytearray(bytes)]

    if bytelist[0:2] != ['0b101000', '0b100111'] and bytelist[0:2] != ['0b101000', '0b100010'] and bytelist[0:2] != ['0b0', '0b11111110']:
        raise ValueError("Initial 2 bytes are not in the correct format")

    model = AliveCorModel()
    packet_header = bytelist[0:5]
    # print(packet_header)
    model.packet_header = {
        "sequence": int(packet_header[4], 2),
        "battery": int(packet_header[2], 2)
    }

    ecg_header = bytelist[6:10]
    if ecg_header:
        model.ecg_header = {
            "id": int(ecg_header[0], 2),
            "length": int(ecg_header[1], 2) + int(ecg_header[2], 2),
            "format": int(ecg_header[3], 2),
        }

        ecg_len = model.ecg_header['length'] - len(ecg_header) - 1

        model.ecg = [int(x, 2) for x in bytelist[11:11 + ecg_len]]

        acc_header = bytelist[11 + ecg_len: 11 + ecg_len + 5]
        if acc_header:
            model.acc_header = {
                'id': int(acc_header[0], 2),
                'length': int(acc_header[1], 2) + int(acc_header[2], 2),
                'format': int(acc_header[3], 2)
            }

            acc_len = model.acc_header['length'] - len(acc_header) - 1
            model.acc = [int(x, 2) for x in bytelist[16 + ecg_len: 16 + ecg_len + acc_len + 1]]
        else:
            # If there is no acc header, acc is None
            model.acc = None
    else:
        # If there is no ecg header, both ecg and acc is None
        # Acc is discovered based on size of ecg length
        # Without ecg header, acc cannot be discovered
        model.ecg = None
        model.acc = None
    return model


#!/usr/bin/env python
""" Start the containers """

import argparse

from lib.docker_compose_tools import set_up

def main():
    """ Start the containers """

    parser = argparse.ArgumentParser(description='Set up testing environment.')
    parser.add_argument('version', help='PostgreSQL version')
    args = parser.parse_args()

    version = args.version
    print('Starting environment with PostgreSQL {version}'.format(version=version))
    set_up(version)

if __name__ == "__main__":
    main()


import numpy as np

with open("input") as f:
	octopi = np.array([[int(c) for c in l] for l in f.read().splitlines()])
h, w = octopi.shape

step = 1
while True:
	octopi += 1
	bfs = list(zip(*np.where(octopi == 10)))
	while len(bfs) > 0:
		y, x = bfs.pop()
		y0, x0, y1, x1 = max(y-1, 0), max(x-1, 0), min(y+2, h), min(x+2, w)
		for ny in range(y0, y1):
			for nx in range(x0, x1):
				if not (nx == x and ny == y):
					octopi[ny,nx] += 1
					if octopi[ny,nx] == 10:
						bfs.append((ny,nx))
	if np.count_nonzero(octopi > 9) == octopi.size: # Faster than np.sum
		break
	octopi[octopi > 9] = 0
	step += 1
print(step)


#!/usr/bin/env python
# -*- coding:utf-8 _*-
# Author: Wengs
# Time  : 2/20/2019 1:28 PM
# File  : magicians.py
# IDE   : PyCharm

# 8-9 and 8-10 and 8-11

def show_magicians(magicians):
    for magician in magicians:
        print(magician.title())

def make_great(magicians):
    changed_magicians = []
    for magician in magicians:
        changed_magicians.append("the Great " + magician)
    return changed_magicians

magicians = ['I', 'You', 'He', 'She']
show_magicians(make_great(magicians[:]))
show_magicians(magicians)


#!/usr/bin/env python

from plot_data.PlotHelper import PlotHelper
import numpy as np
import os
xtest=np.arange(-10,10,1)
ytest=np.sin(xtest)
ytest2=np.cos(xtest)
xdatalist=[xtest,xtest]
ydatalist=[ytest,ytest2]
xerrlist=[None,None]
yerrlist=[np.ones(len(ytest))*0.01,np.ones(len(ytest2))*0.02]
kwargs=dict()
kwargs['xdatalist'] = xdatalist
kwargs['ydatalist'] = ydatalist
kwargs['xerrlist'] = xerrlist
kwargs['yerrlist'] = yerrlist
kwargs['labellist'] = ['sine','cosine']
kwargs['marklargest'] = "2,3"
kwargs['mlabellist'] = None
kwargs['guideline'] = 1
kwargs['xlabel'] = "Number"
kwargs['ylabel'] = "Function value"
kwargs['plotlabel'] = "sine_cos_overlay"
kwargs['save_path'] = os.path.join(os.getcwd(),"save_testing")
kwargs['notelist'] = ["Test plot"]
myph = PlotHelper(**kwargs)
#myph.multiple_overlay()
myph2 = PlotHelper()
myph2.test_all()


from lxml import etree
from urllib import parse
import re

#获取源代码
def get_source(html,xpath):
    tree=etree.HTML(html)
    try:
        section = tree.xpath(xpath)[0]
        source =etree.tostring(section, encoding="utf-8")
        source =source.decode()
    except:
        source=None

    return source
#获取内容
def get_text(html,xpath):
    tree = etree.HTML(html)
    text=""
    try:
        text = tree.xpath(xpath+"/text()")[0]
    except:
        print("无内容")
    return text
#获得图片
def get_image(html):
    tree=etree.HTML(html)
    srcList=tree.xpath("//img/@src")
    for i in range(len(srcList)):
        srcList[i]=parse.unquote(srcList[i])
    return srcList
#获得样式
def get_style(html):
    tree=etree.HTML(html)
    list=tree.xpath("//link[@type=\"text/css\"]/@href")
    return list

#获得样式

#减去无用元素
def minus_element(html,*rules,regax=False):
    if regax:
        for rule in rules:
            try:
                html=re.sub(rule,"",html)
            except:
                continue
    else:
        for rule in rules:
            try:
                old=get_source(html, rule)
                # print(old.encode("utf-8"))
                index=html.find(old[:20])
                html = html[:index]+html[index+len(old):]
            except:
                continue
    return html

#生成标签

def tag(name,*content,cls=None,**attrs):
    if cls is not None:
        attrs['class']=cls
    if attrs:
        attr_str = " ".join(' %s="%s"'%(attr,value) for attr,value in sorted(attrs.items()))
    else:
        attr_str=''
    if content:
        return '\n'.join('<%s%s>%s</%s>\n'%(name,attr_str,c,name) for c in content)
    else:
        return '<%s%s/>\n' %(name,attr_str)


import argparse
import torch
from torchvision import utils
import torchvision.transforms.functional as TF
import torch.nn.functional as F

from model import Generator

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("-i", "--index", type=int, default=0)
    parser.add_argument("-d", "--degree", type=float, default=5, help='max degree')
    parser.add_argument('--m', type=int, default=3, help='imgs per latent')
    parser.add_argument("--ckpt", type=str, required=True)
    parser.add_argument("--size", type=int, default=256)
    parser.add_argument("-n", "--n_sample", type=int, default=7)
    parser.add_argument("--truncation", type=float, default=0.7)
    parser.add_argument("--device", type=str, default="cuda")
    parser.add_argument("--out_prefix", type=str, default="factor")
    parser.add_argument("--factor", type=str)
    args = parser.parse_args()
    assert args.m >= 0

    return args

def compare_axes():
    torch.set_grad_enabled(False)
    device = 'cuda'
    path_factor = 'factor.pt'
    m = 3
    degree = 10
    truncation = 0.7
    out_prefix = 'copmare_axes'
    imsize = 256

    # eigvec = torch.load(args.factor)["eigvec"].to(args.device)
    f_dict = torch.load(path_factor)
    eigvec = f_dict['V'].to(device)
    path_ckpt = f_dict['ckpt']
    print('loading eigenvector of %s' % path_ckpt)

    g = torch.load(path_ckpt).to(device)
    '''state_dict = g.state_dict()
    g = Generator(512, 512, 8).to(device)
    g.load_state_dict(state_dict)'''

    trunc = g.mean_latent(4096)
    torch.save(trunc, 'trunc.pt')

    latent = torch.randn(1, 512, device=device)
    latent = g.get_latent(latent)
    torch.save(latent, 'latent.pt')
    print(latent[0, :10])

    indices = torch.arange(10)
    imgs = torch.zeros((3, len(indices) * imsize, (2 * m + 1) * imsize))
    for i in range(len(indices)):
        index = indices[i]
        direction = degree * eigvec[:, index].unsqueeze(0)

        scales = torch.linspace(-1, 1, 2 * m + 1)
        for j in range(len(scales)):
            scale = scales[j]
            # TODO 이거 이렇게 안 넣고 batch로 g에 넣어주면 되지 않나?
            img, _ = g([latent + scale * direction], truncation=truncation, truncation_latent=trunc,
                       input_is_='latent', randomize_noise=False)
            img = F.interpolate(img, (imsize, imsize))
            imgs[:, i * imsize:(i + 1) * imsize, j * imsize:(j + 1) * imsize] = img[0]

    path_save = './control/%s_degree-%f.png' % (out_prefix, degree)
    imgs = torch.clamp(imgs * 256, 0, 255).type(torch.uint8)
    imgs = TF.to_pil_image(imgs.permute((1, 2, 0)).numpy())
    imgs.save(path_save)
    print(path_save)

def main():
    torch.set_grad_enabled(False)
    args = parse_args()

    # eigvec = torch.load(args.factor)["eigvec"].to(args.device)
    f_dict = torch.load(args.factor)
    eigvec = f_dict['V'].to(args.device)
    print('loading eigenvector of %s' % (f_dict['ckpt']))

    # ckpt = torch.load(args.ckpt)
    # g = Generator(args.size, 512, 8).to(args.device)
    # g.load_state_dict(ckpt["g_ema"], strict=False)
    g = torch.load(args.ckpt).to(args.device)

    trunc = g.mean_latent(4096)

    latent = torch.randn(args.n_sample, 512, device=args.device)
    latent = g.get_latent(latent)

    direction = args.degree * eigvec[:, args.index].unsqueeze(0)

    imgs = []
    scales = torch.linspace(-1, 1, 2 * args.m + 1)
    for scale in scales:
        img, _ = g([latent + scale * direction], truncation=args.truncation, truncation_latent=trunc,
                   input_is='latent', )
        imgs.append(img)
    imgs = torch.cat(imgs, 0)

    path_save = './control/%s_index-%d_degree-%f.png' % (args.out_prefix, args.index, args.degree)
    grid = utils.save_image(imgs, path_save, normalize=True, range=(-1, 1), nrow=args.n_sample, )
    print(path_save)

if __name__ == "__main__":
    # main()
    compare_axes()


import time

import torch
from torch.autograd import Variable
import torch.optim as optim

from model import SkipGram, CBOW

#DEBUG = True #False
DEBUG = False

if DEBUG:
    from dataset import Dataset
else:
    from dataset_old import Dataset, Sampler

import random
import numpy as np

import matplotlib.pyplot as plt

class word2vec:
    def __init__(self, input_file, model_name, vocabulary_size=100000,
                 embedding_dim=200, epoch=10, batch_size=256, windows_size=2, neg_sample_size=10):
        self.model_name = model_name
        if DEBUG:
            self.data_loader = Dataset(batch_size=batch_size, window_size=windows_size)
        else:
            self.data = Dataset([input_file, input_file], vocabulary_size)
            self.data_loader = Sampler(self.data, window_size=windows_size, neg_sample_size=neg_sample_size, batch_size=batch_size)
        self.vocabulary_size = vocabulary_size
        self.embedding_dim = embedding_dim
        self.epoch = epoch
        self.batch_size = batch_size
        self.windows_size = windows_size
        self.neg_sample_size = neg_sample_size

    def showPlot(self, points, title):
        plt.figure()
        fig, ax = plt.subplots()
        plt.plot(points)
        plt.show()

    def train(self, report=True):
        model = SkipGram(self.vocabulary_size, self.embedding_dim)

        loss_list = list()

        if torch.cuda.is_available():
            model.cuda()

        optimizer = optim.SGD(model.parameters(), lr=0.2)

        for epoch in range(self.epoch):

            start = time.time()
            self.data.process =True
            batch_num = 0
            batch_new = 0

            for data_word, data_sentence in self.data_loader():

                optimizer.zero_grad()
                loss = model(data_word) / self.batch_size
                # loss = model(pos_u, pos_v, neg_v, self.batch_size, target, contex, labels)
                loss_list.append(loss)
                loss.backward()
                optimizer.step()

                if report and batch_num % 7 == 0: # 3000
                    end = time.time()
                    print('epoch,batch = %2d %5d:   batch_size = %5d  loss = %4.3f\r'
                          % (epoch, batch_num, self.batch_size, loss.item()), end="\n")
                    batch_new = batch_num
                    start = time.time()
                batch_num += 1

        self.showPlot(loss_list, 'Losses')
        model.save_embeddings(self.data.idx2word, 'word_embdding.txt')

if __name__ == '__main__':

    fixed_seed = 1
    if fixed_seed is not None:
        torch.manual_seed(fixed_seed)
        random.seed(fixed_seed)
        np.random.seed(fixed_seed)
        torch.cuda.manual_seed(fixed_seed)

    # w2v = word2vec('text8', 'SkipGram')
    w2v = word2vec('toy', 'SkipGram', batch_size=1, epoch=10)
    # w2v = word2vec('democratic_cleaned_min.txt', 'SkipGram')
    w2v.train()


# coding: utf-8

# In[43]:

import os
import csv
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
import cv2
import matplotlib.pyplot as plt
from keras.models import Sequential,  Model
from keras.layers.core import Dense, Flatten, Activation, Dropout, Lambda
from keras.layers.convolutional import Convolution2D, Cropping2D
import numpy as np
import pandas as pd
from scipy.misc import imread
import matplotlib.pyplot as plt
from math import *
import cv2
from keras.callbacks import ModelCheckpoint

from sklearn.model_selection import train_test_split
get_ipython().magic('matplotlib inline')

print('All Packages Loaded')

# In[44]:

x = pd.read_csv('/home/carnd/test/data/driving_log.csv')
print("All Data Loaded")

# In[45]:

x.steering.plot(title='Steering data distribution', fontsize=17, figsize=(10,4), color= 'y')
plt.xlabel('frames')
plt.ylabel('Steering angle')
plt.show()

# In[46]:

x.throttle.plot(title='Throttle data distribution', fontsize=17, figsize=(10,4), color= 'b')
plt.xlabel('frames')
plt.ylabel('Throttle')
plt.show()

# In[47]:

x.brake.plot(title='Brake data distribution', fontsize=17, figsize=(10,4), color= 'k')
plt.xlabel('frames')
plt.ylabel('Brake')
plt.show()

# In[48]:

x.speed.plot(title='Speed data distribution', fontsize=17, figsize=(10,4), color= 'm')
plt.xlabel('frames')
plt.ylabel('Speed')
plt.show()

# In[49]:

samples = []

with open('/home/carnd/test/data/driving_log.csv') as csvfile:
    reader = csv.reader(csvfile)
    next(reader, None)
    for line in reader:
        samples.append(line)

# In[50]:

train_samples, validation_samples = train_test_split(samples,test_size=0.15) #simply splitting the dataset to train and validation set usking sklearn. .15 indicates 15% of the dataset is validation set

# In[51]:

def generator(samples, batch_size=32):
    num_samples = len(samples)

    while 1:
        shuffle(samples)
        for offset in range(0, num_samples, batch_size):

            batch_samples = samples[offset:offset+batch_size]

            images = []
            angles = []
            for batch_sample in batch_samples:
                    for i in range(0,3):

                        name = './data/IMG/'+batch_sample[i].split('/')[-1]
                        center_image = cv2.cvtColor(cv2.imread(name), cv2.COLOR_BGR2RGB)
                        center_angle = float(batch_sample[3])
                        images.append(center_image)

                        if(i==0):
                            angles.append(center_angle)
                        elif(i==1):
                            angles.append(center_angle+0.2)
                        elif(i==2):
                            angles.append(center_angle-0.2)

                        images.append(cv2.flip(center_image,1))
                        if(i==0):
                            angles.append(center_angle*-1)
                        elif(i==1):
                            angles.append((center_angle+0.2)*-1)
                        elif(i==2):
                            angles.append((center_angle-0.2)*-1)

            X_train = np.array(images)
            y_train = np.array(angles)

            yield sklearn.utils.shuffle(X_train, y_train)

# In[52]:

train_generator = generator(train_samples, batch_size=32)
validation_generator = generator(validation_samples, batch_size=32)

# ## Type of Problem : Regression
# ### Problem Statement: Find the Steering angle, given images from three cameras, i.e Left, Centre and Right.
#
# ##### Checklist for creating the pipeline of the NVIDIA model : https://tinyurl.com/y88xelpb
# 1. Preprocess incoming data, centered around zero with small standard deviation
# 2. Trim image the to train the network on the basis of the road and the steering angle only.
# 3. Layer 1 : Convolution Layer, Number of Filters : 24, Filter size= 5x5,  stride= 2x2.
# 4. Layer 2 : Convolution Layer, Number of Filters : 36, Filter Size = 5x5, stride = 2x2.
# 5. Layer 3 : Convolution Layer, Number of Filters : 48, Filter Size = 5x5, stride = 2x2.
# 6. Layer 4 : Convolution Layer, Number of Filters : 64, Filter Size = 3x3, stride = 1x1.
# 7. Layer 5 : Convolution Layer, Number of Filters : 64, Filter Size = 3x3, stride = 1x1.
# 8. Flatten the Image from a 2D format to a row based array.
# 9. Layer 6 : Fully Connected Layer
# 10. A dropout layer to avoid overfitting.
# 11. Layer 7 : Fully Connected Layer
# 12. Layer 8 : Fully Connected Layer

# In[53]:

model = Sequential()
model.add(Lambda(lambda x: x/127.5 - 1., input_shape=(160,320, 3), name='Normalization'))
model.add(Cropping2D(cropping=((60, 25),(0,0))))
model.add(Convolution2D(24, 5, 5, subsample=(2,2), activation='elu', name='Conv1'))
model.add(Convolution2D(36, 5, 5, subsample=(2,2), activation='elu', name='Conv2'))
model.add(Convolution2D(48, 5, 5, subsample=(2,2), activation='elu', name='Conv3'))
model.add(Convolution2D(64, 3, 3, activation='relu', name='Conv4'))
model.add(Convolution2D(64, 3, 3, activation='relu', name='Conv5'))
model.add(Flatten())
model.add(Dense(50, activation='elu', name='FC1'))
model.add(Dense(10, activation='elu', name='FC2'))
model.add(Dense(1, name='output'))
model.summary()

# In[54]:

class LossHistory(keras.callbacks.Callback):
    def on_train_begin(self, logs={}):
        print('BEGIN TRAINING')
        self.losses = []

    def on_batch_end(self, batch, logs={}):
        self.losses.append(logs.get('loss'))

# In[55]:

checkpoint = ModelCheckpoint('model-{epoch:03d}.h5',
                                 monitor='val_loss',
                                 verbose=0,
                                 save_best_only=True,
                                 mode='auto')

# In[56]:

batch_history = LossHistory()

# In[57]:

Early_Stopping=keras.callbacks.EarlyStopping(monitor='val_loss', min_delta=0, patience=0, verbose=0, mode='auto')

# In[58]:

Tensor_Board = keras.callbacks.TensorBoard(log_dir='./logs', histogram_freq=0, write_graph=True, write_images=False)

# In[59]:

model.compile(loss='mse',optimizer='adam')
plot_model = model.fit_generator(train_generator, samples_per_epoch= len(train_samples), validation_data=validation_generator,callbacks = [batch_history, Tensor_Board ],nb_val_samples=len(validation_samples), nb_epoch=5,verbose=1)
model.save('model_test_1.h5')
print('Hurray! The Model has been Saved!')

# In[60]:

def running_mean(x, N):
    cumsum = np.cumsum(np.insert(x, 0, 0))
    return (cumsum[N:] - cumsum[:-N]) / N

def plot_history(history):
    plt.plot(running_mean(history.losses, 50))
    plt.ylim(0, 0.06)
    plt.title('model loss')
    plt.ylabel('loss')
    plt.xlabel('batches')
    plt.show()

plot_history(batch_history)

# In[61]:

plt.plot(plot_model.history['loss'])
plt.plot(plot_model.history['val_loss'])
plt.title('model mean squared error loss')
plt.ylabel('mean squared error loss')
plt.xlabel('epoch')
plt.legend(['training set', 'validation set'], loc='upper right')
plt.show()

# In[ ]:


#!/usr/bin/env python3
"""
Exercise 6: String Lists

Ask the user for a string and print out whether this string is a palindrome or
not. (A palindrome is a string that reads the same forwards and backwards.)
"""

def is_palindrome(usr_str):
    """Checks if a given string is a palindrome.

    Takes punctuations and spaces into consideration.
    """
    return usr_str.lower() == usr_str.lower()[::-1]

USR_STR = input('Give a string: ')

print('Your string, "{usr_str}", is {palindrome} palindrome!'
      .format(usr_str=USR_STR,
              palindrome=('a' if is_palindrome(USR_STR)
                          else 'not a')))


import numpy as np
import scipy.stats
import matplotlib.pyplot as plt

# Primitives
alpha=0.4
beta=0.96
mu=0
s=0.1

def U_operator(w, grid, beta, u, f, shocks, cons_pol, Uw=None):
    """
    The approximate U operator, which computes and returns the
    updated value function Uw on the grid points.  An array to store
    the new set of values Uw is optionally supplied (to avoid having to
    allocate new arrays at each iteration).  If supplied, any existing data in
    Uw will be overwritten.

    Parameters
    ----------
    w : array_like(float, ndim = 1)
        The value of the input function on different grid points
    grid : array_like(float, ndim=1)
        The set of grid points
    beta : scalar
        The discount factor
    u : function
        The utility function
    f : function
        The production function
    shocks : numpy array
        An array of draws from the shock, for Monte Carlo integration (to
        compute expectations).
    Uw : array_like(float, ndim=1) optional (default=None)
        Array to write output values to
    cons_pol : Boolean to specify which consumption policy to use.
               If True, c = 0.95y. Otherwise, c = H(y)y

    """
    # === Apply linear interpolation to w === #
    w_func = lambda x: np.interp(x, grid, w)

    # == Initialize Uw if necessary == #
    if Uw is None:
        Uw = np.empty_like(w)

    # == set Uw[i] = u(c) + beta E w(f(y  - c) z) == #
    for i, y in enumerate(grid):
        if cons_pol:
            c = 0.95 * y
        else:
            c = scipy.stats.lognorm.cdf(y, 0.5)
        Uw[i] = u(c) + beta * np.mean(w_func(f(y - c) * shocks))
    return Uw

def u(c):
    " Utility Function "
    return np.log(c)

def f(k):
    " Deterministic part of production function.  "
    return k**alpha

# Generates Grids and Shocks
grid_max = 4         # Largest grid point
grid_size = 200      # Number of grid points
shock_size = 250     # Number of shock draws in Monte Carlo integral
n_iter = 300

grid = np.linspace(1e-5, grid_max, grid_size)
shocks = np.exp(mu + s * np.random.randn(shock_size))

w1 = 5 * np.log(grid)  # An initial condition
w2 = 5 * np.log(grid)

# Finds the value function for policy 1
for i in range(n_iter):
    w1 = U_operator(w1, grid, beta, u, f, shocks, cons_pol = True)

# Finds the value function for policy 2
for i in range(n_iter):
    w2 = U_operator(w2, grid, beta, u, f, shocks, cons_pol = False)
print(w1)
print(w2)
# Plots the value functions
fig, ax = plt.subplots(figsize=(9, 6))
ax.set_ylim(-40, 10)
ax.set_xlim(np.min(grid), np.max(grid))
ax.plot(grid, w1, 'k-', lw = 2, alpha = 0.7)
ax.plot(grid, w2, 'b-', lw = 2, alpha = 0.7)
plt.show()


# coding=utf-8

"""
retailCRM API client v5 tests
"""

import unittest
import os
import random
import retailcrm

class TestVersion5(unittest.TestCase):
    """
    TestClass for v5
    """

    def setUp(self):
        """
        Setup
        """
        self.client = retailcrm.v5(
            os.getenv('RETAILCRM_URL'), os.getenv('RETAILCRM_KEY'))

    def test_wrong_api_url(self):
        """
        V5 Test wrong api url
        """
        client = retailcrm.v5(
            'https://epoqwieqwpoieqpwoeiqpwoeiq.retailcrm.ru', '98sdf9sj8fsd9fjs9answer98')
        response = client.statistic_update()

        self.assertIsNot(response.is_successful(), True)
        self.assertEqual(response.get_error_msg(), 'Account does not exist.')

    def test_wrong_api_key(self):
        """
        V5 Test wrong api key
        """
        client = retailcrm.v5(os.getenv('RETAILCRM_URL'), '98sdf9sj8fsd9fjs9answer98')
        response = client.statistic_update()

        self.assertEqual(response.get_error_msg(), 'Wrong "apiKey" value.')

    def test_missing_api_key(self):
        """
        V5 Test missing api key
        """
        client = retailcrm.v5(os.getenv('RETAILCRM_URL'), None)
        response = client.statistic_update()

        self.assertEqual(response.get_error_msg(), '"apiKey" is missing.')

    def test_api_versions(self):
        """
        V5 Test api-versions method
        """
        response = self.client.api_versions()

        self.assertTrue(response.is_successful(), True)

    def test_api_credentials(self):
        """
        V5 Test api-credentials method
        """
        response = self.client.api_credentials()

        self.assertTrue(response.is_successful(), True)

    def test_set_user_status(self):
        response = self.client.user_status(os.getenv('RETAILCRM_USER'), 'dinner')

        self.assertTrue(response.is_successful(), True)
        self.assertTrue(response.get_status_code() < 400, True)

    def test_check_order_payment(self):
        rand = random.randint(10000, 99999)
        ex_id = 'test-case-payment' + str(rand)
        order = {
            'firstName': 'John',
            'lastName': 'Doe',
            'phone': '+79000000000',
            'email': 'john@example.com',
            'orderMethod': 'call-request',
            'delivery': {
                'code': 'self-delivery'
            },
            'payments': [
                {
                    'externalId': ex_id,
                    'amount': 100,
                    'type': 'cash'
                }
            ]
        }

        response = self.client.order_create(order)

        response_data = response.get_response()
        payment_id = response_data['order']['payments'][0]['id']
        print(payment_id)

        self.assertTrue(response.is_successful(), True)
        self.assertTrue(response.get_status_code() < 400, True)

        payment_response = self.client.order_payment_edit({'externalId': ex_id, 'status': 'invoice'}, 'externalId')

        self.assertTrue(payment_response.is_successful(), True)
        self.assertTrue(payment_response.get_status_code() < 400, True)

        payment_response = self.client.order_payment_edit({'id': payment_id, 'status': 'paid'})

        self.assertTrue(payment_response.is_successful(), True)
        self.assertTrue(payment_response.get_status_code() < 400, True)


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
from django.conf import settings
import audit_log.models.fields

class Migration(migrations.Migration):

    dependencies = [
        ('airplane', '0001_initial'),
        ('financial', '__first__'),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('configuration', '0002_auto_20171114_1703'),
    ]

    operations = [
        migrations.AddField(
            model_name='airplaneauditlogentry',
            name='action_user',
            field=audit_log.models.fields.LastUserField(related_name='_airplane_audit_log_entry', editable=False, to=settings.AUTH_USER_MODEL, null=True),
        ),
        migrations.AddField(
            model_name='airplane',
            name='account',
            field=models.OneToOneField(related_name='airplane_account', null=True, blank=True, to='financial.Account'),
        ),
        migrations.AddField(
            model_name='airplane',
            name='reservation_types',
            field=models.ManyToManyField(to='configuration.ReservationType'),
        ),
    ]


#!/usr/bin/env python
"""
Copyright (c) 2017 Christian Uhsat <christian@uhsat.de>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import os
import sys

from epiphyte import Epiphyte

try:
    import pytest
except ImportError:
    sys.exit("Requires pytest")

class TestEpiphyte:
    """
    Epiphyte unit tests.
    """
    def test_fuzzy(self):
        """
        Fuzzy tests.
        """
        thread = os.urandom(32)
        tests = [os.urandom(4096) for n in range(10)]

        epiphyte = Epiphyte(thread, b'epiphyte_test')

        for test in tests:
            epiphyte.append(test)

        epiphyte = Epiphyte(thread, b'epiphyte_test')

        for test, data in zip(tests, epiphyte):
            assert test == data

if __name__ == "__main__":
    sys.exit(pytest.main(list(sys.argv)))


import mrcnn_wrapper as mrcnn # this can take some time the first time, since its loading 2gb of data into the model
import myhelpers as mh
import matplotlib.pyplot as plt
import glob
import skimage.io
from skimage.segmentation import mark_boundaries

# %%
filelist = sorted(glob.glob('/home/filip/space-time-volumes/databases/jogger_midfoot/frames/*.jpg'))[0:2]
#filelist = sorted(glob.glob('/home/fil/uni/space-time-volumes/databases/runner/*.jpg'))

all_images = []

for tmp in filelist:
    all_images.append(skimage.io.imread(tmp))

# %%
n_segments = [150, 400, 4000]
compactness = [40, 40, 10]
sigmas = [8, 4, 0]
# %% compute image pyramid and slic pyramid
slic_pyramid, image_pyramid = mh.slic_pyramid(all_images, n_segments, compactness, sigmas)
# %% compute mrcnn
mrcnn_data = mh.mrcnn_batch_detect(all_images)
# %% load
mrcnn_data = mh.read_from_file("mrcnn_data.pickle")
slic_pyramid = mh.read_from_file("slic_pyramid.pickle")
image_pyramid = mh.read_from_file("image_pyramid.pickle")

# %% save
mh.write_to_file(mrcnn_data, "mrcnn_data.pickle")
mh.write_to_file(slic_pyramid, "slic_pyramid.pickle")
mh.write_to_file(image_pyramid, "image_pyramid.pickle")

# %% Plot images and mrccn mask[0]
for idx, img in all_images:
    plt.subplot(2,len(all_images),idx+1)
    plt.axis('off')
    plt.imshow(img)

    plt.subplot(2,len(filelist),(idx+1)+len(filelist))
    #                slice   feature   detected_obj
    #                  v      v         v
    mask = mrcnn_data[idx]['masks'][:,:,0]
    plt.axis('off')
    plt.imshow(mask, cmap="gray")

plt.show()

# %%

num_images = len(slic_pyramid[0])
num_levels = len(slic_pyramid)

for i, imagePath in enumerate(filelist):
    image = skimage.io.imread(imagePath)
    mask = mrcnn_data[i]['masks'][:,:,0]
    for lvl in range(1, 2):
        plt.subplot(num_levels,num_images, (i+1) + (num_images*lvl))
        lvl_segs = slic_pyramid[lvl][i]
        improved_mask = mh.estimate_mask_with_superpixel_segmentation(mask, lvl_segs, 0.9)
        plt.axis('off')

        plt.imshow(improved_mask, cmap="gray")
plt.show()

# %% plot slic pyramid
for idx, file in enumerate(filelist):
    image = skimage.io.imread(file)

    for j in range(0,len(slic_pyramid)):

        plt.subplot(len(slic_pyramid), len(filelist), (idx+1) + (len(filelist)*j))
        plt.axis("off")

        plt.title(" n_segs: " + str(n_segments[j]) +
                  " cmpct: " + str(compactness[j]) +
                  " sigma: " + str(sigmas[j]))

        plt.imshow(mark_boundaries(image_pyramid[j][idx][:,:], slic_pyramid[j][idx][:,:]))

# %% merging
from skimage import data, io, segmentation, color
from skimage.future import graph
import numpy as np
import matplotlib.pyplot as plt

def _weight_mean_color(graph, src, dst, n):
    """Callback to handle merging nodes by recomputing mean color.

    The method expects that the mean color of `dst` is already computed.

    Parameters
    ----------
    graph : RAG
        The graph under consideration.
    src, dst : int
        The vertices in `graph` to be merged.
    n : int
        A neighbor of `src` or `dst` or both.

    Returns
    -------
    data : dict
        A dictionary with the `"weight"` attribute set as the absolute
        difference of the mean color between node `dst` and `n`.
    """

    diff = graph.node[dst]['mean color'] - graph.node[n]['mean color']
    diff = np.linalg.norm(diff)
    return {'weight': diff}

def merge_mean_color(graph, src, dst):
    """Callback called before merging two nodes of a mean color distance graph.

    This method computes the mean color of `dst`.

    Parameters
    ----------
    graph : RAG
        The graph under consideration.
    src, dst : int
        The vertices in `graph` to be merged.
    """
    graph.node[dst]['total color'] += graph.node[src]['total color']
    graph.node[dst]['pixel count'] += graph.node[src]['pixel count']
    graph.node[dst]['mean color'] = (graph.node[dst]['total color'] /
                                     graph.node[dst]['pixel count'])

merged = []
for idx, img in enumerate(image_pyramid[2]):
    labels = slic_pyramid[2][idx]
    g = graph.rag_mean_color(img, labels)

    labels2 = graph.merge_hierarchical(labels, g, thresh=70, rag_copy=False,
                                   in_place_merge=True,
                                   merge_func=merge_mean_color,
                                   weight_func=_weight_mean_color)

    out = color.label2rgb(labels2, img)
    out = segmentation.mark_boundaries(out, labels2)
    merged.append(out)

for idx, image in enumerate(merged):
    plt.subplot(1,len(merged), idx+1)
    plt.imshow(image)


# Python
import logging

# isort: split

# dependencies
from grpc.experimental import aio

# isort: split

# module
# isort: off
# from search.proto.genesearch_service.v1 import genesearch_pb2
# from search.proto.genesearch_service.v1 import genesearch_pb2_grpc
# from search.proto.chromosomesearch_service.v1 import chromosomesearch_pb2
# from search.proto.chromosomesearch_service.v1 import chromosomesearch_pb2_grpc
# from search.proto.chromosomeregion_service.v1 import chromosomeregion_pb2
# from search.proto.chromosomeregion_service.v1 import chromosomeregion_pb2_grpc
# NOTE: the following imports are a temporary workaround for a known protobuf
# bug; the commented imports above should be used when the bug is fixed:
# https://github.com/protocolbuffers/protobuf/issues/10075
from search import proto  # noqa: F401
from genesearch_service.v1 import genesearch_pb2, genesearch_pb2_grpc
from chromosomesearch_service.v1 import chromosomesearch_pb2, chromosomesearch_pb2_grpc
from chromosomeregion_service.v1 import chromosomeregion_pb2, chromosomeregion_pb2_grpc

# isort: on

async def gene_search(query, address):
    # fetch channel every time to support dynamic services
    channel = aio.insecure_channel(address)
    await channel.channel_ready()
    stub = genesearch_pb2_grpc.GeneSearchStub(channel)
    try:
        results = await stub.Search(genesearch_pb2.GeneSearchRequest(query=query))
        return results.genes
    except Exception as e:
        logging.error(e)
        return []

async def chromosome_search(query, address):
    # fetch channel every time to support dynamic services
    channel = aio.insecure_channel(address)
    await channel.channel_ready()
    stub = chromosomesearch_pb2_grpc.ChromosomeSearchStub(channel)
    try:
        results = await stub.Search(
            chromosomesearch_pb2.ChromosomeSearchRequest(query=query)
        )
        return results.chromosomes
    except Exception as e:
        logging.error(e)
        return []

async def chromosome_region(chromosome, start, stop, address):
    # fetch channel every time to support dynamic services
    channel = aio.insecure_channel(address)
    await channel.channel_ready()
    stub = chromosomeregion_pb2_grpc.ChromosomeRegionStub(channel)
    try:
        response = await stub.Get(
            chromosomeregion_pb2.ChromosomeRegionGetRequest(
                chromosome=chromosome, start=start, stop=stop
            )
        )
        return [response.region]
    except Exception as e:
        logging.error(e)
        return []


# the observed state of car as seen by drivers
from pygame.math import Vector2

from src.car_command import car_command
from src.my_logger import my_logger
logger = my_logger(__name__)
from src.globals import SCREEN_WIDTH_PIXELS, SCREEN_HEIGHT_PIXELS, M_PER_PIXEL

VERSION='1.0'

class car_state:
    """
    Complete state of car. Updated by hidden model based on control input.

    """

    def __init__(self, x=M_PER_PIXEL * 490, y=M_PER_PIXEL * 615, body_angle_deg=0.0, length_m=4.5, width_m=2.0, max_steering=40, max_acceleration=100.0): # TODO car dimensions are not part of dynamic state, fix
        # todo constructor should put car at starting line, not middle of screen
        # intrinsic state
        # Screen coordinate system is computer vision standard, 0,0 is UL corner and y increases *downwards*.
        # It causes some confusion about angles.
        # (x, y) = tuple starting coordinates in m

        self.time=0
        self.position_m = Vector2(x, y) # x increases to right, y increases downwards
        self.velocity_m_per_sec = Vector2(0.0, 0.0) # vx and vy, with y increasing downwards, i.e. vy>0 means car is moving down the screen
        self.speed_m_per_sec=0.0 # length of velocity vector
        self.accel_m_per_sec_2 = Vector2(0.0, 0.0) # ax and ay *in frame of car*, *along* car body, i.e. ax>0 means car accelerating forwards. ay>0 means rightward acceleration on car body.
        self.steering_angle_deg = 0.0 # degrees of front wheel steering, increases CW/right with zero straight ahead
        self.body_angle_deg = body_angle_deg # degrees, increases CW (on screen!) with zero pointing to right/east
        self.yaw_rate_deg_per_sec = 0.0 # degrees/sec, increases CW on screen
        self.drift_angle_deg=0.0 # drift angle, (beta) relative to heading direction. Zero for no drift. +-90 for drifting entirely sideways. + is drift to left,- to right. TODO check description correct
        self.length_m = length_m # length in meters
        self.width_m = width_m # width in meters

        # current commanded control input
        self.command = car_command()

        self.time_results = []

        # other car(s) # todo add structure to send other car states to client for rendering

        self.other_cars: list = None  # list of other car_state for other cars

        self.server_msg=None # message from server to be displayed to driver

    def reset(self):
        pass

    def __str__(self):
        s='{}\npos=({:4.1f},{:4.1f})m vel=({:5.1f},{:5.1f})m/s, speed={:6.2f}m/s accel={:6.2f}m/s^2\nsteering_angle={:4.1f}deg body_angle={:4.1f}deg\nyaw_rate={:4.1f}deg/s drift_angle={:4.1f}\nmsg: {}'\
            .format(str(self.command),
                    self.position_m.x,
                    self.position_m.y,
                    self.velocity_m_per_sec.x,
                    self.velocity_m_per_sec.y,
                    self.speed_m_per_sec,
                    self.accel_m_per_sec_2.length(),
                    self.steering_angle_deg,
                    self.body_angle_deg,
                    self.yaw_rate_deg_per_sec,
                    self.drift_angle_deg,
                    self.server_msg)
        return s

    def get_record_headers(self, car):
        import datetime, time, getpass
        header ='# recorded output from l2race\n# format version: {}\n'.format(VERSION)
        header+=datetime.datetime.now().strftime('# Creation_time="%I:%M%p %B %d %Y"\n')  # Tue Jan 26 13:57:06 CET 2016
        header+='# Creation_time="{}" (epoch ms)\n'.format(int(time.time() * 1000.))
        header+='# Username="{}"\n'.format(getpass.getuser())
        header+='# Car_name="{}"\n'.format(car.name)
        header+='# Track_name="{}"\n'.format(car.track.name)
        h=[
            'time',
            'cmd.auto',
            'cmd.steering',
            'cmd.throttle',
            'cmd.brake',
            'cmd.reverse',
            'pos.x',
            'pos.y',
            'vel.x',
            'vel.y',
            'speed',
            'accel.x',
            'accel.y',
            'steering_angle',
            'body_angle',
            'yaw_rate',
            'drift_angle',
            'length',
            'width',
        ]
        for i in h[:-1]:
            header=header+i+','
        header+=h[-1]
        return header

    def get_record_csvrow(self):
        l=[
            self.time,
            1 if self.command.auto else 0,
            self.command.steering,
            self.command.throttle,
            self.command.brake,
            1 if self.command.reverse else 0,
            self.position_m.x,
            self.position_m.y,
            self.velocity_m_per_sec.x,
            self.velocity_m_per_sec.y,
            self.speed_m_per_sec,
            self.accel_m_per_sec_2.x,
            self.accel_m_per_sec_2.y,
            self.steering_angle_deg,
            self.body_angle_deg,
            self.yaw_rate_deg_per_sec,
            self.drift_angle_deg,
            self.length_m,
            self.width_m,
        ]
        s=''
        for v in l[:-1]:
            s=s+('{},'.format(v))
        s=s+('{:f}'.format(l[-1]))
        return s