<commit_before># -*- coding: utf-8 -*-
# Copyright (C) 2012  Renato Lima (Akretion)                                  #
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html

import re

from openerp import models, fields, api
from openerp.tools.translate import _
from openerp.exceptions import except_orm
from openerp.exceptions import Warning as UserError

class L10nBrZip(models.Model):
    """ Este objeto persiste todos os códigos postais que podem ser
    utilizados para pesquisar e auxiliar o preenchimento dos endereços.
    """
    _name = 'l10n_br.zip'
    _description = 'CEP'
    _rec_name = 'zip'

    zip = fields.Char('CEP', size=8, required=True)
    street_type = fields.Char('Tipo', size=26)
    street = fields.Char('Logradouro', size=72)
    district = fields.Char('Bairro', size=72)
    country_id = fields.Many2one('res.country', u'País')
    state_id = fields.Many2one(
        'res.country.state', 'Estado',
        domain="[('country_id','=',country_id)]")
    l10n_br_city_id = fields.Many2one(
        'l10n_br_base.city', 'Cidade',
        required=True, domain="[('state_id','=',state_id)]")

    def set_domain(self, country_id=False, state_id=False,
                   l10n_br_city_id=False, district=False,
                   street=False, zip_code=False):
        domain = []
        if zip_code:
            new_zip = re.sub('[^0-9]', '', zip_code or '')
            domain.append(('zip', '=', new_zip))
        else:
            if not state_id or not l10n_br_city_id or \
                    len(street or '') == 0:
                raise except_orm(
                    u'Parâmetros insuficientes',
                    u'Necessário informar Estado, município e logradouro')

            if country_id:
                domain.append(('country_id', '=', country_id))
            if state_id:
                domain.append(('state_id', '=', state_id))
            if l10n_br_city_id:
                domain.append(('l10n_br_city_id', '=', l10n_br_city_id))
            if district:
                domain.append(('district', 'ilike', district))
            if street:
                domain.append(('street', 'ilike', street))

        return domain

    def set_result(self, zip_obj=None):
        if zip_obj:
            zip_code = zip_obj.zip
            if len(zip_code) == 8:
                zip_code = '%s-%s' % (zip_code[0:5], zip_code[5:8])
            result = {
                'country_id': zip_obj.country_id.id,
                'state_id': zip_obj.state_id.id,
                'l10n_br_city_id': zip_obj.l10n_br_city_id.id,
                'district': zip_obj.district,
                'street': ((zip_obj.street_type or '') +
                           ' ' + (zip_obj.street or '')) if
                zip_obj.street_type else (zip_obj.street or ''),
                'zip': zip_code,
            }
        else:
            result = {}
        return result

    def zip_search_multi(self, country_id=False,
                         state_id=False, l10n_br_city_id=False,
                         district=False, street=False, zip_code=False):
        domain = self.set_domain(
            country_id=country_id,
            state_id=state_id,
            l10n_br_city_id=l10n_br_city_id,
            district=district,
            street=street,
            zip_code=zip_code)
        return self.search(domain)

    @api.multi
    def zip_search(self, obj):

        zip_ids = self.zip_search_multi(
            country_id=obj.country_id.id,
            state_id=obj.state_id.id,
            l10n_br_city_id=obj.l10n_br_city_id.id,
            district=obj.district,
            street=obj.street,
            zip_code=obj.zip,
        )

        if len(zip_ids) == 1:
            result = self.set_result(zip_ids[0])
            obj.write(result)
            return True
        else:
            if len(zip_ids) > 1:
                obj_zip_result = self.env['l10n_br.zip.result']
                zip_ids = obj_zip_result.map_to_zip_result(
                    zip_ids, obj._name, obj.id)

                return self.create_wizard(
                    obj._name,
                    obj.id,
                    country_id=obj.country_id.id,
                    state_id=obj.state_id.id,
                    l10n_br_city_id=obj.l10n_br_city_id.id,
                    district=obj.district,
                    street=obj.street,
                    zip_code=obj.zip,
                    zip_ids=[zip.id for zip in zip_ids]
                )
            else:
                raise UserError(_('Nenhum registro encontrado'))

    def create_wizard(self, object_name, address_id, country_id=False,
                      state_id=False, l10n_br_city_id=False,
                      district=False, street=False, zip_code=False,
                      zip_ids=False):
        context = dict(self.env.context)
        context.update({
            'zip': zip_code,
            'street': street,
            'district': district,
            'country_id': country_id,
            'state_id': state_id,
            'l10n_br_city_id': l10n_br_city_id,
            'zip_ids': zip_ids,
            'address_id': address_id,
            'object_name': object_name})

        result = {
            'name': 'Zip Search',
            'view_type': 'form',
            'view_mode': 'form',
            'res_model': 'l10n_br.zip.search',
            'view_id': False,
            'context': context,
            'type': 'ir.actions.act_window',
            'target': 'new',
            'nodestroy': True,
        }

        return result
<commit_msg>[FIX] Zip search não estava atribuindo o nome da cidade para o campo 'city' do res_partner (e outros cadastros que utilizam o mesmo campo).<commit_after># -*- coding: utf-8 -*-
# Copyright (C) 2012  Renato Lima (Akretion)                                  #
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html

import re

from openerp import models, fields, api
from openerp.tools.translate import _
from openerp.exceptions import except_orm
from openerp.exceptions import Warning as UserError

class L10nBrZip(models.Model):
    """ Este objeto persiste todos os códigos postais que podem ser
    utilizados para pesquisar e auxiliar o preenchimento dos endereços.
    """
    _name = 'l10n_br.zip'
    _description = 'CEP'
    _rec_name = 'zip'

    zip = fields.Char('CEP', size=8, required=True)
    street_type = fields.Char('Tipo', size=26)
    street = fields.Char('Logradouro', size=72)
    district = fields.Char('Bairro', size=72)
    country_id = fields.Many2one('res.country', u'País')
    state_id = fields.Many2one(
        'res.country.state', 'Estado',
        domain="[('country_id','=',country_id)]")
    l10n_br_city_id = fields.Many2one(
        'l10n_br_base.city', 'Cidade',
        required=True, domain="[('state_id','=',state_id)]")

    def set_domain(self, country_id=False, state_id=False,
                   l10n_br_city_id=False, district=False,
                   street=False, zip_code=False):
        domain = []
        if zip_code:
            new_zip = re.sub('[^0-9]', '', zip_code or '')
            domain.append(('zip', '=', new_zip))
        else:
            if not state_id or not l10n_br_city_id or \
                    len(street or '') == 0:
                raise except_orm(
                    u'Parâmetros insuficientes',
                    u'Necessário informar Estado, município e logradouro')

            if country_id:
                domain.append(('country_id', '=', country_id))
            if state_id:
                domain.append(('state_id', '=', state_id))
            if l10n_br_city_id:
                domain.append(('l10n_br_city_id', '=', l10n_br_city_id))
            if district:
                domain.append(('district', 'ilike', district))
            if street:
                domain.append(('street', 'ilike', street))

        return domain

    def set_result(self, zip_obj=None):
        if zip_obj:
            zip_code = zip_obj.zip
            if len(zip_code) == 8:
                zip_code = '%s-%s' % (zip_code[0:5], zip_code[5:8])
            result = {
                'country_id': zip_obj.country_id.id,
                'state_id': zip_obj.state_id.id,
                'l10n_br_city_id': zip_obj.l10n_br_city_id.id,
                'city': zip_obj.l10n_br_city_id.name,
                'district': zip_obj.district,
                'street': ((zip_obj.street_type or '') +
                           ' ' + (zip_obj.street or '')) if
                zip_obj.street_type else (zip_obj.street or ''),
                'zip': zip_code,
            }
        else:
            result = {}
        return result

    def zip_search_multi(self, country_id=False,
                         state_id=False, l10n_br_city_id=False,
                         district=False, street=False, zip_code=False):
        domain = self.set_domain(
            country_id=country_id,
            state_id=state_id,
            l10n_br_city_id=l10n_br_city_id,
            district=district,
            street=street,
            zip_code=zip_code)
        return self.search(domain)

    @api.multi
    def zip_search(self, obj):

        zip_ids = self.zip_search_multi(
            country_id=obj.country_id.id,
            state_id=obj.state_id.id,
            l10n_br_city_id=obj.l10n_br_city_id.id,
            district=obj.district,
            street=obj.street,
            zip_code=obj.zip,
        )

        if len(zip_ids) == 1:
            result = self.set_result(zip_ids[0])
            obj.write(result)
            return True
        else:
            if len(zip_ids) > 1:
                obj_zip_result = self.env['l10n_br.zip.result']
                zip_ids = obj_zip_result.map_to_zip_result(
                    zip_ids, obj._name, obj.id)

                return self.create_wizard(
                    obj._name,
                    obj.id,
                    country_id=obj.country_id.id,
                    state_id=obj.state_id.id,
                    l10n_br_city_id=obj.l10n_br_city_id.id,
                    district=obj.district,
                    street=obj.street,
                    zip_code=obj.zip,
                    zip_ids=[zip.id for zip in zip_ids]
                )
            else:
                raise UserError(_('Nenhum registro encontrado'))

    def create_wizard(self, object_name, address_id, country_id=False,
                      state_id=False, l10n_br_city_id=False,
                      district=False, street=False, zip_code=False,
                      zip_ids=False):
        context = dict(self.env.context)
        context.update({
            'zip': zip_code,
            'street': street,
            'district': district,
            'country_id': country_id,
            'state_id': state_id,
            'l10n_br_city_id': l10n_br_city_id,
            'zip_ids': zip_ids,
            'address_id': address_id,
            'object_name': object_name})

        result = {
            'name': 'Zip Search',
            'view_type': 'form',
            'view_mode': 'form',
            'res_model': 'l10n_br.zip.search',
            'view_id': False,
            'context': context,
            'type': 'ir.actions.act_window',
            'target': 'new',
            'nodestroy': True,
        }

        return result
<|endoftext|>


<commit_before>from __future__ import unicode_literals

import shlex
import subprocess
import copy
import logging
import tempfile
import shutil
import tornado.websocket
import tornado.ioloop
import tornado.web
from leapcast.services.websocket import App
from leapcast.utils import render
from leapcast.environment import Environment

class Browser(object):

    def __init__(self, appurl):
        args = [
            Environment.chrome,
            '--allow-running-insecure-content',
            '--no-default-browser-check',
            '--ignore-gpu-blacklist',
            '--incognito',
            '--no-first-run',
            '--kiosk',
            '--disable-translate',
            '--user-agent=%s' % Environment.user_agent.encode('utf8')
        ]
        self.tmpdir = tempfile.mkdtemp(prefix='leapcast-')
        args.append('--user-data-dir=%s' % self.tmpdir)
        if Environment.window_size:
            args.append('--window-size=%s' % Environment.window_size)
        if not Environment.fullscreen:
            args.append('--app=%s' % appurl.encode('utf8'))
        else:
            args.append(appurl.encode('utf8'))
        logging.debug(args)
        self.pid = subprocess.Popen(args)

    def destroy(self):
        self.pid.terminate()
        self.pid.wait()
        shutil.rmtree(self.tmpdir)

    def is_running(self):
        return self.pid.poll() is None

    def __bool__(self):
        return self.is_running()

class LEAPfactory(tornado.web.RequestHandler):
    application_status = dict(
        name='',
        state='stopped',
        link='',
        browser=None,
        connectionSvcURL='',
        protocols='',
        app=None
    )

    service = '''<?xml version='1.0' encoding='UTF-8'?>
    <service xmlns='urn:dial-multiscreen-org:schemas:dial'>
        <name>{{ name }}</name>
        <options allowStop='true'/>
        {% if state == "running" %}
        <servicedata xmlns='urn:chrome.google.com:cast'>
            <connectionSvcURL>{{ connectionSvcURL }}</connectionSvcURL>
            <protocols>
                {% for x in protocols %}
                <protocol>{{ x }}</protocol>
                {% end %}
            </protocols>
        </servicedata>
        {% end %}
        <state>{{ state }}</state>
        {% if state == "running" %}
        <activity-status xmlns="urn:chrome.google.com:cast">
          <description>{{ name }} Receiver</description>
        </activity-status>
        <link rel='run' href='web-1'/>
        {% end %}
    </service>
    '''

    ip = None
    url = '{{query}}'
    supported_protocols = ['ramp']

    @classmethod
    def get_subclasses(c):
        subclasses = c.__subclasses__()
        return list(subclasses)

    def get_name(self):
        return self.__class__.__name__

    def get_status_dict(self):
        status = copy.deepcopy(self.application_status)
        status['name'] = self.get_name()
        return status

    def prepare(self):
        self.ip = self.request.host

    def get_app_status(self):
        return Environment.global_status.get(self.get_name(), self.get_status_dict())

    def set_app_status(self, app_status):

        app_status['name'] = self.get_name()
        Environment.global_status[self.get_name()] = app_status

    def _response(self):
        self.set_header('Content-Type', 'application/xml')
        self.set_header(
            'Access-Control-Allow-Method', 'GET, POST, DELETE, OPTIONS')
        self.set_header('Access-Control-Expose-Headers', 'Location')
        self.set_header('Cache-control', 'no-cache, must-revalidate, no-store')
        self.finish(self._toXML(self.get_app_status()))

    @tornado.web.asynchronous
    def post(self, sec):
        '''Start app'''
        self.clear()
        self.set_status(201)
        self.set_header('Location', self._getLocation(self.get_name()))
        status = self.get_app_status()
        if status['browser'] is None:
            status['state'] = 'running'
            if self.url == "https://tv.pandora.com/cast?{{ query }}":
                appurl = render(self.url.replace("{{ query }}", self.request.body)).generate(query=self.request.body)
            else:
                appurl = render(self.url).generate(query=self.request.body)
            status['browser'] = Browser(appurl)
            status['connectionSvcURL'] = 'http://%s/connection/%s' % (
                self.ip, self.get_name())
            status['protocols'] = self.supported_protocols
            status['app'] = App.get_instance(sec)

        self.set_app_status(status)
        self.finish()

    def stop_app(self):
        self.clear()
        browser = self.get_app_status()['browser']
        if browser is not None:
            browser.destroy()
        else:
            logging.warning('App already closed in destroy()')
        status = self.get_status_dict()
        status['state'] = 'stopped'
        status['browser'] = None

        self.set_app_status(status)

    @tornado.web.asynchronous
    def get(self, sec):
        '''Status of an app'''
        self.clear()
        browser = self.get_app_status()['browser']
        if not browser:
            logging.debug('App crashed or closed')
            # app crashed or closed
            status = self.get_status_dict()
            status['state'] = 'stopped'
            status['browser'] = None
            self.set_app_status(status)

        self._response()

    @tornado.web.asynchronous
    def delete(self, sec):
        '''Close app'''
        self.stop_app()
        self._response()

    def _getLocation(self, app):
        return 'http://%s/apps/%s/web-1' % (self.ip, app)

    def _toXML(self, data):
        return render(self.service).generate(**data)

    @classmethod
    def toInfo(cls):
        data = copy.deepcopy(cls.application_status)
        data['name'] = cls.__name__
        data = Environment.global_status.get(cls.__name__, data)
        return render(cls.service).generate(data)
<commit_msg>Fix: for pep8 :)<commit_after>from __future__ import unicode_literals

import subprocess
import copy
import logging
import tempfile
import shutil
import tornado.websocket
import tornado.ioloop
import tornado.web
from leapcast.services.websocket import App
from leapcast.utils import render
from leapcast.environment import Environment

class Browser(object):

    def __init__(self, appurl):
        args = [
            Environment.chrome,
            '--allow-running-insecure-content',
            '--no-default-browser-check',
            '--ignore-gpu-blacklist',
            '--incognito',
            '--no-first-run',
            '--kiosk',
            '--disable-translate',
            '--user-agent=%s' % Environment.user_agent.encode('utf8')
        ]
        self.tmpdir = tempfile.mkdtemp(prefix='leapcast-')
        args.append('--user-data-dir=%s' % self.tmpdir)
        if Environment.window_size:
            args.append('--window-size=%s' % Environment.window_size)
        if not Environment.fullscreen:
            args.append('--app=%s' % appurl.encode('utf8'))
        else:
            args.append(appurl.encode('utf8'))
        logging.debug(args)
        self.pid = subprocess.Popen(args)

    def destroy(self):
        self.pid.terminate()
        self.pid.wait()
        shutil.rmtree(self.tmpdir)

    def is_running(self):
        return self.pid.poll() is None

    def __bool__(self):
        return self.is_running()

class LEAPfactory(tornado.web.RequestHandler):
    application_status = dict(
        name='',
        state='stopped',
        link='',
        browser=None,
        connectionSvcURL='',
        protocols='',
        app=None
    )

    service = '''<?xml version='1.0' encoding='UTF-8'?>
    <service xmlns='urn:dial-multiscreen-org:schemas:dial'>
        <name>{{ name }}</name>
        <options allowStop='true'/>
        {% if state == "running" %}
        <servicedata xmlns='urn:chrome.google.com:cast'>
            <connectionSvcURL>{{ connectionSvcURL }}</connectionSvcURL>
            <protocols>
                {% for x in protocols %}
                <protocol>{{ x }}</protocol>
                {% end %}
            </protocols>
        </servicedata>
        {% end %}
        <state>{{ state }}</state>
        {% if state == "running" %}
        <activity-status xmlns="urn:chrome.google.com:cast">
          <description>{{ name }} Receiver</description>
        </activity-status>
        <link rel='run' href='web-1'/>
        {% end %}
    </service>
    '''

    ip = None
    url = '{{query}}'
    supported_protocols = ['ramp']

    @classmethod
    def get_subclasses(c):
        subclasses = c.__subclasses__()
        return list(subclasses)

    def get_name(self):
        return self.__class__.__name__

    def get_status_dict(self):
        status = copy.deepcopy(self.application_status)
        status['name'] = self.get_name()
        return status

    def prepare(self):
        self.ip = self.request.host

    def get_app_status(self):
        return Environment.global_status.get(self.get_name(), self.get_status_dict())

    def set_app_status(self, app_status):

        app_status['name'] = self.get_name()
        Environment.global_status[self.get_name()] = app_status

    def _response(self):
        self.set_header('Content-Type', 'application/xml')
        self.set_header(
            'Access-Control-Allow-Method', 'GET, POST, DELETE, OPTIONS')
        self.set_header('Access-Control-Expose-Headers', 'Location')
        self.set_header('Cache-control', 'no-cache, must-revalidate, no-store')
        self.finish(self._toXML(self.get_app_status()))

    @tornado.web.asynchronous
    def post(self, sec):
        '''Start app'''
        self.clear()
        self.set_status(201)
        self.set_header('Location', self._getLocation(self.get_name()))
        status = self.get_app_status()
        if status['browser'] is None:
            status['state'] = 'running'
            if self.url == "https://tv.pandora.com/cast?{{ query }}":
                appurl = render(self.url.replace("{{ query }}", self.request.body)).generate(query=self.request.body)
            else:
                appurl = render(self.url).generate(query=self.request.body)
            status['browser'] = Browser(appurl)
            status['connectionSvcURL'] = 'http://%s/connection/%s' % (
                self.ip, self.get_name())
            status['protocols'] = self.supported_protocols
            status['app'] = App.get_instance(sec)

        self.set_app_status(status)
        self.finish()

    def stop_app(self):
        self.clear()
        browser = self.get_app_status()['browser']
        if browser is not None:
            browser.destroy()
        else:
            logging.warning('App already closed in destroy()')
        status = self.get_status_dict()
        status['state'] = 'stopped'
        status['browser'] = None

        self.set_app_status(status)

    @tornado.web.asynchronous
    def get(self, sec):
        '''Status of an app'''
        self.clear()
        browser = self.get_app_status()['browser']
        if not browser:
            logging.debug('App crashed or closed')
            # app crashed or closed
            status = self.get_status_dict()
            status['state'] = 'stopped'
            status['browser'] = None
            self.set_app_status(status)

        self._response()

    @tornado.web.asynchronous
    def delete(self, sec):
        '''Close app'''
        self.stop_app()
        self._response()

    def _getLocation(self, app):
        return 'http://%s/apps/%s/web-1' % (self.ip, app)

    def _toXML(self, data):
        return render(self.service).generate(**data)

    @classmethod
    def toInfo(cls):
        data = copy.deepcopy(cls.application_status)
        data['name'] = cls.__name__
        data = Environment.global_status.get(cls.__name__, data)
        return render(cls.service).generate(data)
<|endoftext|>


<commit_before>"""
Dummy web server that proxies incoming requests to local client that owns association keys

Installation:
	virtualenv -p python3 ~/env
	source ~/env/bin/activate
	pip install flask gunicorn pexpect

To run:
	gunicorn --bind 0.0.0.0:8000 server

"""
import flask

import decimal
import os
import pexpect
import platform
import random
import re
import sys

print(sys.version)
print(platform.python_version())

def setup_app():
    application = flask.Flask(__name__)
    ac_host = os.environ['AC_HOST']
    ac_port = os.environ['AC_PORT']

    # If we have comma separated list take a random one
    ac_hosts = ac_host.split(',')
    ac_host = random.choice(ac_hosts)

    print("Connecting to ac on: {}:{}".format(ac_host, ac_port))

    cmd = "/opt/libra/bin/client --host {} --port {} -m /opt/libra/etc/mint.key --validator_set_file /opt/libra/etc/trusted_peers.config.toml".format(
        ac_host, ac_port)
    application.client = pexpect.spawn(cmd)
    application.client.expect("Please, input commands")
    return application

application = setup_app()

MAX_MINT = 10 ** 12

@application.route("/")
def send_transaction():
    address = flask.request.args['address']

    # Return immediately if address is invalid
    if re.match('^[a-f0-9]{64}$', address) is None:
        return 'Malformed address', 400

    try:
        amount = decimal.Decimal(flask.request.args['amount'])
    except:
        return 'Bad amount', 400

    if amount > MAX_MINT:
        return 'Exceeded max mint amount of {}'.format(MAX_MINT), 400

    application.client.sendline("a m {} {}".format(address, amount / (10 ** 6)))
    application.client.expect("Mint request submitted", timeout=2)

    application.client.sendline("a la")
    application.client.expect(r"sequence_number: ([0-9]+)", timeout=1)
    return application.client.match.groups()[0]
<commit_msg>[faucet server] fix error message<commit_after>"""
Dummy web server that proxies incoming requests to local client that owns association keys

Installation:
	virtualenv -p python3 ~/env
	source ~/env/bin/activate
	pip install flask gunicorn pexpect

To run:
	gunicorn --bind 0.0.0.0:8000 server

"""
import flask

import decimal
import os
import pexpect
import platform
import random
import re
import sys

print(sys.version)
print(platform.python_version())

def setup_app():
    application = flask.Flask(__name__)
    ac_host = os.environ['AC_HOST']
    ac_port = os.environ['AC_PORT']

    # If we have comma separated list take a random one
    ac_hosts = ac_host.split(',')
    ac_host = random.choice(ac_hosts)

    print("Connecting to ac on: {}:{}".format(ac_host, ac_port))

    cmd = "/opt/libra/bin/client --host {} --port {} -m /opt/libra/etc/mint.key --validator_set_file /opt/libra/etc/trusted_peers.config.toml".format(
        ac_host, ac_port)
    application.client = pexpect.spawn(cmd)
    application.client.expect("Please, input commands")
    return application

application = setup_app()

MAX_MINT = 10 ** 12

@application.route("/")
def send_transaction():
    address = flask.request.args['address']

    # Return immediately if address is invalid
    if re.match('^[a-f0-9]{64}$', address) is None:
        return 'Malformed address', 400

    try:
        amount = decimal.Decimal(flask.request.args['amount'])
    except:
        return 'Bad amount', 400

    if amount > MAX_MINT:
        return 'Exceeded max mint amount of {}'.format(MAX_MINT / (10 ** 6)), 400

    application.client.sendline("a m {} {}".format(address, amount / (10 ** 6)))
    application.client.expect("Mint request submitted", timeout=2)

    application.client.sendline("a la")
    application.client.expect(r"sequence_number: ([0-9]+)", timeout=1)
    return application.client.match.groups()[0]
<|endoftext|>


<commit_before>"""
Dummy web server that proxies incoming requests to local client that owns association keys

Installation:
	virtualenv -p python3 ~/env
	source ~/env/bin/activate
	pip install flask gunicorn pexpect

To run:
	gunicorn --bind 0.0.0.0:8000 server

"""
import flask

import decimal
import os
import pexpect
import platform
import random
import re
import sys

print(sys.version)
print(platform.python_version())

def setup_app():
    application = flask.Flask(__name__)
    ac_host = os.environ['AC_HOST']
    ac_port = os.environ['AC_PORT']

    # If we have comma separated list take a random one
    ac_hosts = ac_host.split(',')
    ac_host = random.choice(ac_hosts)

    print("Connecting to ac on: {}:{}".format(ac_host, ac_port))

    cmd = "/opt/libra/bin/client --host {} --port {} -m /opt/libra/etc/mint.key --validator_set_file /opt/libra/etc/trusted_peers.config.toml".format(
        ac_host, ac_port)
    application.client = pexpect.spawn(cmd)
    application.client.expect("Please, input commands")
    return application

application = setup_app()

MAX_MINT = 10 ** 12

@application.route("/")
def send_transaction():
    address = flask.request.args['address']

    # Return immediately if address is invalid
    if re.match('^[a-f0-9]{64}$', address) is None:
        return 'Malformed address', 400

    try:
        amount = decimal.Decimal(flask.request.args['amount'])
    except:
        return 'Bad amount', 400

    if amount > MAX_MINT:
        return 'Exceeded max mint amount of {}'.format(MAX_MINT / (10 ** 6)), 400

    application.client.sendline("a m {} {}".format(address, amount / (10 ** 6)))
    application.client.expect("Mint request submitted", timeout=2)

    application.client.sendline("a la")
    application.client.expect(r"sequence_number: ([0-9]+)", timeout=1)
    return application.client.match.groups()[0]
<commit_msg>[mint server] increase max mint amount. Format code with pep8<commit_after>"""
Simple faucet server
Proxies mint requests to local client that owns association keys
"""
import decimal
import os
import platform
import random
import re
import sys

import flask
import pexpect

def setup_app():
    app = flask.Flask(__name__)
    # If we have comma separated list take a random one
    ac_hosts = os.environ['AC_HOST'].split(',')
    ac_host = random.choice(ac_hosts)
    ac_port = os.environ['AC_PORT']

    print(sys.version, platform.python_version())
    print("Connecting to ac on: {}:{}".format(ac_host, ac_port))

    cmd = "/opt/libra/bin/client --host {} --port {} -m {} -s {}".format(
        ac_host,
        ac_port,
        "/opt/libra/etc/mint.key",
        "/opt/libra/etc/trusted_peers.config.toml")
    app.client = pexpect.spawn(cmd)
    app.client.expect("Please, input commands")
    return app

application = setup_app()

MAX_MINT = 10 ** 19  # 10 trillion libras

@application.route("/")
def send_transaction():
    address = flask.request.args['address']

    # Return immediately if address is invalid
    if re.match('^[a-f0-9]{64}$', address) is None:
        return 'Malformed address', 400

    try:
        amount = decimal.Decimal(flask.request.args['amount'])
    except decimal.InvalidOperation:
        return 'Bad amount', 400

    if amount > MAX_MINT:
        return 'Exceeded max amount of {}'.format(MAX_MINT / (10 ** 6)), 400

    application.client.sendline(
        "a m {} {}".format(address, amount / (10 ** 6)))
    application.client.expect("Mint request submitted", timeout=2)

    application.client.sendline("a la")
    application.client.expect(r"sequence_number: ([0-9]+)", timeout=1)
    return application.client.match.groups()[0]
<|endoftext|>


<commit_before>###############################################################################
#   actionAngle: a Python module to calculate  actions, angles, and frequencies
#
#      class: actionAngleAdiabaticGrid
#
#             build grid in integrals of motion to quickly evaluate
#             actionAngleAdiabatic
#
#      methods:
#             __call__: returns (jr,lz,jz)
#
###############################################################################
import math
import numpy
from scipy import interpolate
from actionAngleAdiabatic import actionAngleAdiabatic
from galpy.actionAngle import actionAngle, UnboundError
import galpy.potential
from matplotlib import pyplot
_PRINTOUTSIDEGRID= False
class actionAngleAdiabaticGrid():
    """Action-angle formalism for axisymmetric potentials using the adiabatic approximation, grid-based interpolation"""
    def __init__(self,pot=None,zmax=3./8.,gamma=1.,Rmax=3.,
                 nR=25,nEz=25,nEr=25,nLz=25,**kwargs):
        """
        NAME:
           __init__
        PURPOSE:
           initialize an actionAngleAdiabaticGrid object
        INPUT:
           pot= potential or list of potentials (planarPotentials)
           zmax= zmax for building Ez grid
           Rmax = Rmax for building grids
           gamma= (default=1.) replace Lz by Lz+gamma Jz in effective potential
           nEz=, nEr=, nLz, nR= grid size
           +scipy.integrate.quad keywords
        OUTPUT:
        HISTORY:
            2012-07-27 - Written - Bovy (IAS@MPIA)
        """
        if pot is None:
            raise IOError("Must specify pot= for actionAngleAxi")
        self._gamma= gamma
        self._pot= pot
        self._zmax= zmax
        self._Rmax= Rmax
        self._Rmin= 0.01
        #Set up the actionAngleAdiabatic object that we will use to interpolate
        self._aA= actionAngleAdiabatic(pot=self._pot,gamma=self._gamma)
        #Build grid for Ez, first calculate Ez(zmax;R) function
        self._Rs= numpy.linspace(self._Rmin,self._Rmax,nR)
        self._EzZmaxs= numpy.array([galpy.potential.evaluatePotentials(r,self._zmax,self._pot)-
                                    galpy.potential.evaluatePotentials(r,0.,self._pot) for r in self._Rs])
        self._EzZmaxsInterp= interpolate.InterpolatedUnivariateSpline(self._Rs,numpy.log(self._EzZmaxs),k=3)
        y= numpy.linspace(0.,1.,nEz)
        jz= numpy.zeros((nR,nEz))
        jzEzzmax= numpy.zeros(nR)
        for ii in range(nR):
            for jj in range(nEz):
                #Calculate Jz
                jz[ii,jj]= self._aA.Jz(self._Rs[ii],0.,1.,#these two r dummies
                                       0.,math.sqrt(2.*y[jj]*self._EzZmaxs[ii]),
                                       **kwargs)[0]
                if jj == nEz-1:
                    jzEzzmax[ii]= jz[ii,jj]
        for ii in range(nR): jz[ii,:]/= jzEzzmax[ii]
        #First interpolate Ez=Ezmax
        self._jzEzmaxInterp= interpolate.InterpolatedUnivariateSpline(self._Rs,numpy.log(jzEzzmax+10.**-5.),k=3)
        self._jzInterp= interpolate.RectBivariateSpline(self._Rs,
                                                        y,
                                                        jz,
                                                        kx=3,ky=3,s=0.)
        #JR grid
        self._Lzmin= 0.01
        self._Lzs= numpy.linspace(self._Lzmin,
                                  self._Rmax\
                                      *galpy.potential.vcirc(self._pot,
                                                             self._Rmax),
                                  nLz)
        self._Lzmax= self._Lzs[-1]
        #Calculate ER(vr=0,R=RL)
        self._RL= numpy.array([galpy.potential.rl(self._pot,l) for l in self._Lzs])
        self._RLInterp= interpolate.InterpolatedUnivariateSpline(self._Lzs,
                                                                 self._RL,k=3)
        self._ERRL= numpy.array([galpy.potential.evaluatePotentials(self._RL[ii],0.,self._pot) +self._Lzs[ii]**2./2./self._RL[ii]**2. for ii in range(nLz)])
        self._ERRLmax= numpy.amax(self._ERRL)+1.
        self._ERRLInterp= interpolate.InterpolatedUnivariateSpline(self._Lzs,
                                                                   numpy.log(-(self._ERRL-self._ERRLmax)),k=3)
        self._Ramax= 99.
        self._ERRa= numpy.array([galpy.potential.evaluatePotentials(self._Ramax,0.,self._pot) +self._Lzs[ii]**2./2./self._Ramax**2. for ii in range(nLz)])
        self._ERRamax= numpy.amax(self._ERRa)+1.
        self._ERRaInterp= interpolate.InterpolatedUnivariateSpline(self._Lzs,
                                                                   numpy.log(-(self._ERRa-self._ERRamax)),k=3)
        y= numpy.linspace(0.,1.,nEr)
        jr= numpy.zeros((nLz,nEr))
        jrERRa= numpy.zeros(nLz)
        for ii in range(nLz):
            for jj in range(nEr-1): #Last one is zero by construction
                try:
                    jr[ii,jj]= self._aA.JR(self._RL[ii],
                                           numpy.sqrt(2.*(self._ERRa[ii]+y[jj]*(self._ERRL[ii]-self._ERRa[ii])-galpy.potential.evaluatePotentials(self._RL[ii],0.,self._pot))-self._Lzs[ii]**2./self._RL[ii]**2.),
                                           self._Lzs[ii]/self._RL[ii],
                                           0.,0.,
                                           **kwargs)[0]
                except UnboundError:
                    raise
                if jj == 0:
                    jrERRa[ii]= jr[ii,jj]
        for ii in range(nLz): jr[ii,:]/= jrERRa[ii]
        #First interpolate Ez=Ezmax
        self._jr= jr
        self._jrERRaInterp= interpolate.InterpolatedUnivariateSpline(self._Lzs,
                                                                     numpy.log(jrERRa+10.**-5.),k=3)
        self._jrInterp= interpolate.RectBivariateSpline(self._Lzs,
                                                        y,
                                                        jr,
                                                        kx=3,ky=3,s=0.)
        return None

    def __call__(self,*args,**kwargs):
        """
        NAME:
           __call__
        PURPOSE:
           evaluate the actions (jr,lz,jz)
        INPUT:
           Either:
              a) R,vR,vT,z,vz
              b) Orbit instance: initial condition used if that's it, orbit(t)
                 if there is a time given as well
           scipy.integrate.quadrature keywords
        OUTPUT:
           (jr,lz,jz)
        HISTORY:
           2012-07-27 - Written - Bovy (IAS@MPIA)
        NOTE:
           For a Miyamoto-Nagai potential, this seems accurate to 0.1% and takes ~0.13 ms
           For a MWPotential, this takes ~ 0.17 ms
        """
        meta= actionAngle(*args)
        #First work on the vertical action
        Phi= galpy.potential.evaluatePotentials(meta._R,meta._z,self._pot)
        Phio= galpy.potential.evaluatePotentials(meta._R,0.,self._pot)
        Ez= Phi-Phio+meta._vz**2./2.
        #Bigger than Ezzmax?
        thisEzZmax= numpy.exp(self._EzZmaxsInterp(meta._R))
        if meta._R > self._Rmax or meta._R < self._Rmin or (Ez != 0 and numpy.log(Ez) > thisEzZmax): #Outside of the grid
            if _PRINTOUTSIDEGRID:
                print "Outside of grid in Ez", meta._R > self._Rmax , meta._R < self._Rmin , (Ez != 0 and numpy.log(Ez) > thisEzZmax)
            jz= self._aA.Jz(meta._R,0.,1.,#these two r dummies
                            0.,math.sqrt(2.*Ez),
                            **kwargs)[0]
        else:
            jz= (self._jzInterp(meta._R,Ez/thisEzZmax)\
                *(numpy.exp(self._jzEzmaxInterp(meta._R))-10.**-5.))[0][0]
        #Radial action
        ERLz= math.fabs(meta._R*meta._vT)+self._gamma*jz
        ER= Phio+meta._vR**2./2.+ERLz**2./2./meta._R**2.
        thisRL= self._RLInterp(ERLz)
        thisERRL= -numpy.exp(self._ERRLInterp(ERLz))+self._ERRLmax
        thisERRa= -numpy.exp(self._ERRaInterp(ERLz))+self._ERRamax
        if (ER-thisERRa)/(thisERRL-thisERRa) > 1. \
                and ((ER-thisERRa)/(thisERRL-thisERRa)-1.) < 10.**-2.:
            ER= thisERRL
        elif (ER-thisERRa)/(thisERRL-thisERRa) < 0. \
                and (ER-thisERRa)/(thisERRL-thisERRa) > -10.**-2.:
            ER= thisERRa
        #Outside of grid?
        if ERLz < self._Lzmin or ERLz > self._Lzmax \
                or (ER-thisERRa)/(thisERRL-thisERRa) > 1. \
                or (ER-thisERRa)/(thisERRL-thisERRa) < 0.:
            if _PRINTOUTSIDEGRID:
                print "Outside of grid in ER/Lz", ERLz < self._Lzmin , ERLz > self._Lzmax \
                , (ER-thisERRa)/(thisERRL-thisERRa) > 1. \
                , (ER-thisERRa)/(thisERRL-thisERRa) < 0., ER, thisERRL, thisERRa, (ER-thisERRa)/(thisERRL-thisERRa)
            jr= self._aA.JR(thisRL,
                            numpy.sqrt(2.*(ER-galpy.potential.evaluatePotentials(thisRL,0.,self._pot))-ERLz**2./thisRL**2.),
                            ERLz/thisRL,
                            0.,0.,
                            **kwargs)[0]
        else:
            jr= (self._jrInterp(ERLz,
                               (ER-thisERRa)/(thisERRL-thisERRa))\
                *(numpy.exp(self._jrERRaInterp(ERLz))-10.**-5.))[0][0]
        return (jr,meta._R*meta._vT,jz)

    def Jz(self,*args,**kwargs):
        """
        NAME:
           Jz
        PURPOSE:
           evaluate the action jz
        INPUT:
           Either:
              a) R,vR,vT,z,vz
              b) Orbit instance: initial condition used if that's it, orbit(t)
                 if there is a time given as well
           scipy.integrate.quadrature keywords
        OUTPUT:
           jz
        HISTORY:
           2012-07-30 - Written - Bovy (IAS@MPIA)
        """
        meta= actionAngle(*args)
        Phi= galpy.potential.evaluatePotentials(meta._R,meta._z,self._pot)
        Phio= galpy.potential.evaluatePotentials(meta._R,0.,self._pot)
        Ez= Phi-Phio+meta._vz**2./2.
        #Bigger than Ezzmax?
        thisEzZmax= numpy.exp(self._EzZmaxsInterp(meta._R))
        if meta._R > self._Rmax or meta._R < self._Rmin or (Ez != 0. and numpy.log(Ez) > thisEzZmax): #Outside of the grid
            if _PRINTOUTSIDEGRID:
                print "Outside of grid in Ez"
            jz= self._aA.Jz(meta._R,0.,1.,#these two r dummies
                            0.,math.sqrt(2.*Ez),
                            **kwargs)[0]
        else:
            jz= (self._jzInterp(meta._R,Ez/thisEzZmax)\
                *(numpy.exp(self._jzEzmaxInterp(meta._R))-10.**-5.))[0][0]
        return jz
<commit_msg>vectorize actionAngleAdiabaticGrid call<commit_after>###############################################################################
#   actionAngle: a Python module to calculate  actions, angles, and frequencies
#
#      class: actionAngleAdiabaticGrid
#
#             build grid in integrals of motion to quickly evaluate
#             actionAngleAdiabatic
#
#      methods:
#             __call__: returns (jr,lz,jz)
#
###############################################################################
import math
import numpy
from scipy import interpolate
from actionAngleAdiabatic import actionAngleAdiabatic
from galpy.actionAngle import actionAngle, UnboundError
import galpy.potential
from matplotlib import pyplot
_PRINTOUTSIDEGRID= False
class actionAngleAdiabaticGrid():
    """Action-angle formalism for axisymmetric potentials using the adiabatic approximation, grid-based interpolation"""
    def __init__(self,pot=None,zmax=3./8.,gamma=1.,Rmax=3.,
                 nR=25,nEz=25,nEr=25,nLz=25,**kwargs):
        """
        NAME:
           __init__
        PURPOSE:
           initialize an actionAngleAdiabaticGrid object
        INPUT:
           pot= potential or list of potentials (planarPotentials)
           zmax= zmax for building Ez grid
           Rmax = Rmax for building grids
           gamma= (default=1.) replace Lz by Lz+gamma Jz in effective potential
           nEz=, nEr=, nLz, nR= grid size
           +scipy.integrate.quad keywords
        OUTPUT:
        HISTORY:
            2012-07-27 - Written - Bovy (IAS@MPIA)
        """
        if pot is None:
            raise IOError("Must specify pot= for actionAngleAxi")
        self._gamma= gamma
        self._pot= pot
        self._zmax= zmax
        self._Rmax= Rmax
        self._Rmin= 0.01
        #Set up the actionAngleAdiabatic object that we will use to interpolate
        self._aA= actionAngleAdiabatic(pot=self._pot,gamma=self._gamma)
        #Build grid for Ez, first calculate Ez(zmax;R) function
        self._Rs= numpy.linspace(self._Rmin,self._Rmax,nR)
        self._EzZmaxs= numpy.array([galpy.potential.evaluatePotentials(r,self._zmax,self._pot)-
                                    galpy.potential.evaluatePotentials(r,0.,self._pot) for r in self._Rs])
        self._EzZmaxsInterp= interpolate.InterpolatedUnivariateSpline(self._Rs,numpy.log(self._EzZmaxs),k=3)
        y= numpy.linspace(0.,1.,nEz)
        jz= numpy.zeros((nR,nEz))
        jzEzzmax= numpy.zeros(nR)
        for ii in range(nR):
            for jj in range(nEz):
                #Calculate Jz
                jz[ii,jj]= self._aA.Jz(self._Rs[ii],0.,1.,#these two r dummies
                                       0.,math.sqrt(2.*y[jj]*self._EzZmaxs[ii]),
                                       **kwargs)[0]
                if jj == nEz-1:
                    jzEzzmax[ii]= jz[ii,jj]
        for ii in range(nR): jz[ii,:]/= jzEzzmax[ii]
        #First interpolate Ez=Ezmax
        self._jzEzmaxInterp= interpolate.InterpolatedUnivariateSpline(self._Rs,numpy.log(jzEzzmax+10.**-5.),k=3)
        self._jzInterp= interpolate.RectBivariateSpline(self._Rs,
                                                        y,
                                                        jz,
                                                        kx=3,ky=3,s=0.)
        #JR grid
        self._Lzmin= 0.01
        self._Lzs= numpy.linspace(self._Lzmin,
                                  self._Rmax\
                                      *galpy.potential.vcirc(self._pot,
                                                             self._Rmax),
                                  nLz)
        self._Lzmax= self._Lzs[-1]
        #Calculate ER(vr=0,R=RL)
        self._RL= numpy.array([galpy.potential.rl(self._pot,l) for l in self._Lzs])
        self._RLInterp= interpolate.InterpolatedUnivariateSpline(self._Lzs,
                                                                 self._RL,k=3)
        self._ERRL= numpy.array([galpy.potential.evaluatePotentials(self._RL[ii],0.,self._pot) +self._Lzs[ii]**2./2./self._RL[ii]**2. for ii in range(nLz)])
        self._ERRLmax= numpy.amax(self._ERRL)+1.
        self._ERRLInterp= interpolate.InterpolatedUnivariateSpline(self._Lzs,
                                                                   numpy.log(-(self._ERRL-self._ERRLmax)),k=3)
        self._Ramax= 99.
        self._ERRa= numpy.array([galpy.potential.evaluatePotentials(self._Ramax,0.,self._pot) +self._Lzs[ii]**2./2./self._Ramax**2. for ii in range(nLz)])
        self._ERRamax= numpy.amax(self._ERRa)+1.
        self._ERRaInterp= interpolate.InterpolatedUnivariateSpline(self._Lzs,
                                                                   numpy.log(-(self._ERRa-self._ERRamax)),k=3)
        y= numpy.linspace(0.,1.,nEr)
        jr= numpy.zeros((nLz,nEr))
        jrERRa= numpy.zeros(nLz)
        for ii in range(nLz):
            for jj in range(nEr-1): #Last one is zero by construction
                try:
                    jr[ii,jj]= self._aA.JR(self._RL[ii],
                                           numpy.sqrt(2.*(self._ERRa[ii]+y[jj]*(self._ERRL[ii]-self._ERRa[ii])-galpy.potential.evaluatePotentials(self._RL[ii],0.,self._pot))-self._Lzs[ii]**2./self._RL[ii]**2.),
                                           self._Lzs[ii]/self._RL[ii],
                                           0.,0.,
                                           **kwargs)[0]
                except UnboundError:
                    raise
                if jj == 0:
                    jrERRa[ii]= jr[ii,jj]
        for ii in range(nLz): jr[ii,:]/= jrERRa[ii]
        #First interpolate Ez=Ezmax
        self._jr= jr
        self._jrERRaInterp= interpolate.InterpolatedUnivariateSpline(self._Lzs,
                                                                     numpy.log(jrERRa+10.**-5.),k=3)
        self._jrInterp= interpolate.RectBivariateSpline(self._Lzs,
                                                        y,
                                                        jr,
                                                        kx=3,ky=3,s=0.)
        return None

    def __call__(self,*args,**kwargs):
        """
        NAME:
           __call__
        PURPOSE:
           evaluate the actions (jr,lz,jz)
        INPUT:
           Either:
              a) R,vR,vT,z,vz
              b) Orbit instance: initial condition used if that's it, orbit(t)
                 if there is a time given as well
           scipy.integrate.quadrature keywords
        OUTPUT:
           (jr,lz,jz)
        HISTORY:
           2012-07-27 - Written - Bovy (IAS@MPIA)
        NOTE:
           For a Miyamoto-Nagai potential, this seems accurate to 0.1% and takes ~0.13 ms
           For a MWPotential, this takes ~ 0.17 ms
        """
        if len(args) == 5: #R,vR.vT, z, vz
            R,vR,vT, z, vz= args
        elif len(args) == 6: #R,vR.vT, z, vz, phi
            R,vR,vT, z, vz, phi= args
        else:
            meta= actionAngle(*args)
            R= meta._R
            vR= meta._vR
            vT= meta._vT
            z= meta._z
            vz= meta._vz
        #First work on the vertical action
        Phi= galpy.potential.evaluatePotentials(R,z,self._pot)
        Phio= galpy.potential.evaluatePotentials(R,0.,self._pot)
        Ez= Phi-Phio+vz**2./2.
        #Bigger than Ezzmax?
        thisEzZmax= numpy.exp(self._EzZmaxsInterp(R))
        if isinstance(R,numpy.ndarray):
            indx= (R > self._Rmax)
            indx+= (R < self._Rmin)
            indx+= (Ez != 0.)*(numpy.log(Ez) > thisEzZmax)
            indxc= True-indx
            jz= numpy.empty(R.shape)
            jz[indxc]= (self._jzInterp(R[indxc],Ez[indxc]/thisEzZmax[indxc])\
                            *(numpy.exp(self._jzEzmaxInterp(R[indxc]))-10.**-5.))
            jz[indx]= numpy.array([self._aA.Jz(R[indx][ii],0.,1.,#these two r dummies
                                               0.,numpy.sqrt(2.*Ez[indx][ii]),
                                               **kwargs)[0] for ii in range(numpy.sum(indx))])
        else:
            if R > self._Rmax or R < self._Rmin or (Ez != 0 and numpy.log(Ez) > thisEzZmax): #Outside of the grid
                if _PRINTOUTSIDEGRID:
                    print "Outside of grid in Ez", R > self._Rmax , R < self._Rmin , (Ez != 0 and numpy.log(Ez) > thisEzZmax)
                    jz= self._aA.Jz(R,0.,1.,#these two r dummies
                                    0.,math.sqrt(2.*Ez),
                                    **kwargs)[0]
            else:
                jz= (self._jzInterp(R,Ez/thisEzZmax)\
                         *(numpy.exp(self._jzEzmaxInterp(R))-10.**-5.))[0][0]
        #Radial action
        ERLz= numpy.fabs(R*vT)+self._gamma*jz
        ER= Phio+vR**2./2.+ERLz**2./2./R**2.
        thisRL= self._RLInterp(ERLz)
        thisERRL= -numpy.exp(self._ERRLInterp(ERLz))+self._ERRLmax
        thisERRa= -numpy.exp(self._ERRaInterp(ERLz))+self._ERRamax
        if isinstance(R,numpy.ndarray):
            indx= ((ER-thisERRa)/(thisERRL-thisERRa) > 1.)\
                *(((ER-thisERRa)/(thisERRL-thisERRa)-1.) < 10.**-2.)
            ER[indx]= thisERRL[indx]
            indx= ((ER-thisERRa)/(thisERRL-thisERRa) < 0.)\
                *((ER-thisERRa)/(thisERRL-thisERRa) > -10.**-2.)
            ER[indx]= thisERRa[indx]
            indx= (ERLz < self._Lzmin)
            indx+= (ERLz > self._Lzmax)
            indx+= ((ER-thisERRa)/(thisERRL-thisERRa) > 1.)
            indx+= ((ER-thisERRa)/(thisERRL-thisERRa) < 0.)
            indxc= True-indx
            jr= numpy.empty(R.shape)
            jr[indx]= numpy.array([self._aA.JR(thisRL[indx][ii],
                                               numpy.sqrt(2.*(ER[indx][ii]-galpy.potential.evaluatePotentials(thisRL[indx][ii],0.,self._pot))-ERLz[indx][ii]**2./thisRL[indx][ii]**2.),
                                               ERLz[indx][ii]/thisRL[indx][ii],
                                               0.,0.,
                                               **kwargs)[0] for ii in range(numpy.sum(indx))])
            jr[indxc]= (self._jrInterp(ERLz[indxc],
                                       (ER[indxc]-thisERRa[indxc])/(thisERRL[indxc]-thisERRa[indxc]))\
                            *(numpy.exp(self._jrERRaInterp(ERLz[indxc]))-10.**-5.))
        else:
            if (ER-thisERRa)/(thisERRL-thisERRa) > 1. \
                    and ((ER-thisERRa)/(thisERRL-thisERRa)-1.) < 10.**-2.:
                ER= thisERRL
            elif (ER-thisERRa)/(thisERRL-thisERRa) < 0. \
                    and (ER-thisERRa)/(thisERRL-thisERRa) > -10.**-2.:
                ER= thisERRa
            #Outside of grid?
            if ERLz < self._Lzmin or ERLz > self._Lzmax \
                    or (ER-thisERRa)/(thisERRL-thisERRa) > 1. \
                    or (ER-thisERRa)/(thisERRL-thisERRa) < 0.:
                if _PRINTOUTSIDEGRID:
                    print "Outside of grid in ER/Lz", ERLz < self._Lzmin , ERLz > self._Lzmax \
                        , (ER-thisERRa)/(thisERRL-thisERRa) > 1. \
                        , (ER-thisERRa)/(thisERRL-thisERRa) < 0., ER, thisERRL, thisERRa, (ER-thisERRa)/(thisERRL-thisERRa)
                    jr= self._aA.JR(thisRL,
                                    numpy.sqrt(2.*(ER-galpy.potential.evaluatePotentials(thisRL,0.,self._pot))-ERLz**2./thisRL**2.),
                                    ERLz/thisRL,
                                    0.,0.,
                                    **kwargs)[0]
            else:
                jr= (self._jrInterp(ERLz,
                                    (ER-thisERRa)/(thisERRL-thisERRa))\
                         *(numpy.exp(self._jrERRaInterp(ERLz))-10.**-5.))[0][0]
        return (jr,R*vT,jz)

    def Jz(self,*args,**kwargs):
        """
        NAME:
           Jz
        PURPOSE:
           evaluate the action jz
        INPUT:
           Either:
              a) R,vR,vT,z,vz
              b) Orbit instance: initial condition used if that's it, orbit(t)
                 if there is a time given as well
           scipy.integrate.quadrature keywords
        OUTPUT:
           jz
        HISTORY:
           2012-07-30 - Written - Bovy (IAS@MPIA)
        """
        meta= actionAngle(*args)
        Phi= galpy.potential.evaluatePotentials(meta._R,meta._z,self._pot)
        Phio= galpy.potential.evaluatePotentials(meta._R,0.,self._pot)
        Ez= Phi-Phio+meta._vz**2./2.
        #Bigger than Ezzmax?
        thisEzZmax= numpy.exp(self._EzZmaxsInterp(meta._R))
        if meta._R > self._Rmax or meta._R < self._Rmin or (Ez != 0. and numpy.log(Ez) > thisEzZmax): #Outside of the grid
            if _PRINTOUTSIDEGRID:
                print "Outside of grid in Ez"
            jz= self._aA.Jz(meta._R,0.,1.,#these two r dummies
                            0.,math.sqrt(2.*Ez),
                            **kwargs)[0]
        else:
            jz= (self._jzInterp(meta._R,Ez/thisEzZmax)\
                *(numpy.exp(self._jzEzmaxInterp(meta._R))-10.**-5.))[0][0]
        return jz
<|endoftext|>


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

from bigdl.nn.layer import Model
from bigdl.transform.vision.image import *
from bigdl.util.common import *
from pyspark.sql.functions import col, udf
from pyspark.sql.types import StringType

from zoo.common.nncontext import *
from zoo.pipeline.nnframes.nn_classifier import *
from zoo.pipeline.nnframes.nn_image_reader import *
from zoo.pipeline.nnframes.nn_image_transformer import *

def inference(image_path, model_path, sc):

    imageDF = NNImageReader.readImages(image_path, sc)
    getName = udf(lambda row: row[0], StringType())
    transformer = NNImageTransformer(
        Pipeline([Resize(256, 256), CenterCrop(224, 224),
                  ChannelNormalize(123.0, 117.0, 104.0),
                  MatToTensor()])
    ).setInputCol("image").setOutputCol("features")
    featureDF = transformer.transform(imageDF).withColumn("name", getName(col("image")))

    model = Model.loadModel(model_path)
    classifierModel = NNClassifierModel(model, [3, 224, 224]).setBatchSize(4)

    predictionDF = classifierModel.transform(featureDF)
    return predictionDF

if __name__ == "__main__":

    if len(sys.argv) != 3:
        print("Need parameters: <modelPath> <imagePath>")
        exit(-1)

    sc = get_nncontext()
    redire_spark_logs()

    model_path = sys.argv[1]
    image_path = sys.argv[2]

    predictionDF = inference(image_path, model_path, sc)
    predictionDF.select("name", "prediction").orderBy("name").show(20, False)
<commit_msg>support python object detector (#118)<commit_after>#
# Copyright 2018 Analytics Zoo Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

from bigdl.nn.layer import Model
from bigdl.transform.vision.image import *
from bigdl.util.common import *
from pyspark.sql.functions import col, udf
from pyspark.sql.types import StringType

from zoo.common.nncontext import *
from zoo.pipeline.nnframes.nn_classifier import *
from zoo.pipeline.nnframes.nn_image_reader import *
from zoo.pipeline.nnframes.nn_image_transformer import *

def inference(image_path, model_path, sc):

    imageDF = NNImageReader.readImages(image_path, sc)
    getName = udf(lambda row: row[0], StringType())
    transformer = NNImageTransformer(
        Pipeline([Resize(256, 256), CenterCrop(224, 224),
                  ChannelNormalize(123.0, 117.0, 104.0),
                  MatToTensor()])
    ).setInputCol("image").setOutputCol("features")
    featureDF = transformer.transform(imageDF).withColumn("name", getName(col("image")))

    model = Model.loadModel(model_path)
    classifierModel = NNClassifierModel(model, [3, 224, 224]).setBatchSize(4)

    predictionDF = classifierModel.transform(featureDF)
    return predictionDF

if __name__ == "__main__":

    if len(sys.argv) != 3:
        print("Need parameters: <modelPath> <imagePath>")
        exit(-1)

    sc = get_nncontext()

    model_path = sys.argv[1]
    image_path = sys.argv[2]

    predictionDF = inference(image_path, model_path, sc)
    predictionDF.select("name", "prediction").orderBy("name").show(20, False)
<|endoftext|>


<commit_before># Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt

from __future__ import unicode_literals
import frappe

from frappe.utils import getdate, validate_email_add, cint
from frappe.model.naming import make_autoname
from frappe import throw, _
import frappe.permissions
from frappe.defaults import get_restrictions
from frappe.model.document import Document
from frappe.model.mapper import get_mapped_doc

class Employee(Document):
	def onload(self):
		self.salary_structure_exists = frappe.db.get_value("Salary Structure",
			{"employee": self.name, "is_active": "Yes", "docstatus": ["!=", 2]})

	def as_dict(self, no_nulls=False):
		doc = super(Employee, self).as_dict(no_nulls)

		if hasattr(self, "salary_structure_exists"):
			doc["salary_structure_exists"] = self.salary_structure_exists

		return doc

	def autoname(self):
		naming_method = frappe.db.get_value("HR Settings", None, "emp_created_by")
		if not naming_method:
			throw(_("Please setup Employee Naming System in Human Resource > HR Settings"))
		else:
			if naming_method=='Naming Series':
				self.name = make_autoname(self.naming_series + '.####')
			elif naming_method=='Employee Number':
				self.name = self.employee_number

		self.employee = self.name

	def validate(self):
		from erpnext.utilities import validate_status
		validate_status(self.status, ["Active", "Left"])

		self.employee = self.name
		self.validate_date()
		self.validate_email()
		self.validate_status()
		self.validate_employee_leave_approver()

		if self.user_id:
			self.validate_for_enabled_user_id()
			self.validate_duplicate_user_id()

	def on_update(self):
		if self.user_id:
			self.update_user_default()
			self.update_user()

		self.update_dob_event()
		self.restrict_leave_approver()

	def restrict_user(self):
		"""restrict to this employee for user"""
		self.add_restriction_if_required("Employee", self.user_id)

	def update_user_default(self):
		self.restrict_user()
		frappe.db.set_default("employee_name", self.employee_name, self.user_id)
		frappe.db.set_default("company", self.company, self.user_id)

	def restrict_leave_approver(self):
		"""restrict to this employee for leave approver"""
		employee_leave_approvers = [d.leave_approver for d in self.get("employee_leave_approvers")]
		if self.reports_to and self.reports_to not in employee_leave_approvers:
			employee_leave_approvers.append(frappe.db.get_value("Employee", self.reports_to, "user_id"))

		for user in employee_leave_approvers:
			self.add_restriction_if_required("Employee", user)
			self.add_restriction_if_required("Leave Application", user)

	def add_restriction_if_required(self, doctype, user):
		if frappe.permissions.has_only_non_restrict_role(doctype, user) \
			and self.name not in get_restrictions(user).get("Employee", []):

			frappe.defaults.add_default("Employee", self.name, user, "Restriction")

	def update_user(self):
		# add employee role if missing
		user = frappe.get_doc("User", self.user_id)
		user.ignore_permissions = True

		if "Employee" not in user.get("user_roles"):
			user.add_roles("Employee")

		# copy details like Fullname, DOB and Image to User
		if self.employee_name:
			employee_name = self.employee_name.split(" ")
			if len(employee_name) >= 3:
				user.last_name = " ".join(employee_name[2:])
				user.middle_name = employee_name[1]
			elif len(employee_name) == 2:
				user.last_name = employee_name[1]

			user.first_name = employee_name[0]

		if self.date_of_birth:
			user.birth_date = self.date_of_birth

		if self.gender:
			user.gender = self.gender

		if self.image:
			if not user.user_image:
				user.user_image = self.image
				try:
					frappe.get_doc({
						"doctype": "File Data",
						"file_name": self.image,
						"attached_to_doctype": "User",
						"attached_to_name": self.user_id
					}).insert()
				except frappe.DuplicateEntryError, e:
					# already exists
					pass

		user.save()

	def validate_date(self):
		if self.date_of_birth and self.date_of_joining and getdate(self.date_of_birth) >= getdate(self.date_of_joining):
			throw(_("Date of Joining must be greater than Date of Birth"))

		elif self.scheduled_confirmation_date and self.date_of_joining and (getdate(self.scheduled_confirmation_date) < getdate(self.date_of_joining)):
			throw(_("Scheduled Confirmation Date must be greater than Date of Joining"))

		elif self.final_confirmation_date and self.date_of_joining and (getdate(self.final_confirmation_date) < getdate(self.date_of_joining)):
			throw(_("Final Confirmation Date must be greater than Date of Joining"))

		elif self.date_of_retirement and self.date_of_joining and (getdate(self.date_of_retirement) <= getdate(self.date_of_joining)):
			throw(_("Date Of Retirement must be greater than Date of Joining"))

		elif self.relieving_date and self.date_of_joining and (getdate(self.relieving_date) <= getdate(self.date_of_joining)):
			throw(_("Relieving Date must be greater than Date of Joining"))

		elif self.contract_end_date and self.date_of_joining and (getdate(self.contract_end_date)<=getdate(self.date_of_joining)):
			throw(_("Contract End Date must be greater than Date of Joining"))

	def validate_email(self):
		if self.company_email and not validate_email_add(self.company_email):
			throw(_("Please enter valid Company Email"))
		if self.personal_email and not validate_email_add(self.personal_email):
			throw(_("Please enter valid Personal Email"))

	def validate_status(self):
		if self.status == 'Left' and not self.relieving_date:
			throw(_("Please enter relieving date."))

	def validate_for_enabled_user_id(self):
		if not self.status == 'Active':
			return
		enabled = frappe.db.sql("""select name from `tabUser` where
			name=%s and enabled=1""", self.user_id)
		if not enabled:
			throw(_("User {0} is disabled").format(self.user_id))

	def validate_duplicate_user_id(self):
		employee = frappe.db.sql_list("""select name from `tabEmployee` where
			user_id=%s and status='Active' and name!=%s""", (self.user_id, self.name))
		if employee:
			throw(_("User {0} is already assigned to Employee {1}").format(self.user_id, employee[0]))

	def validate_employee_leave_approver(self):
		from frappe.utils.user import User
		from erpnext.hr.doctype.leave_application.leave_application import InvalidLeaveApproverError

		for l in self.get("employee_leave_approvers"):
			if "Leave Approver" not in User(l.leave_approver).get_roles():
				throw(_("{0} is not a valid Leave Approver").format(l.leave_approver), InvalidLeaveApproverError)

	def update_dob_event(self):
		if self.status == "Active" and self.date_of_birth \
			and not cint(frappe.db.get_value("HR Settings", None, "stop_birthday_reminders")):
			birthday_event = frappe.db.sql("""select name from `tabEvent` where repeat_on='Every Year'
				and ref_type='Employee' and ref_name=%s""", self.name)

			starts_on = self.date_of_birth + " 00:00:00"
			ends_on = self.date_of_birth + " 00:15:00"

			if birthday_event:
				event = frappe.get_doc("Event", birthday_event[0][0])
				event.starts_on = starts_on
				event.ends_on = ends_on
				event.save()
			else:
				frappe.get_doc({
					"doctype": "Event",
					"subject": _("Birthday") + ": " + self.employee_name,
					"description": _("Happy Birthday!") + " " + self.employee_name,
					"starts_on": starts_on,
					"ends_on": ends_on,
					"event_type": "Public",
					"all_day": 1,
					"send_reminder": 1,
					"repeat_this_event": 1,
					"repeat_on": "Every Year",
					"ref_type": "Employee",
					"ref_name": self.name
				}).insert()
		else:
			frappe.db.sql("""delete from `tabEvent` where repeat_on='Every Year' and
				ref_type='Employee' and ref_name=%s""", self.name)

@frappe.whitelist()
def get_retirement_date(date_of_birth=None):
	import datetime
	ret = {}
	if date_of_birth:
		dt = getdate(date_of_birth) + datetime.timedelta(21915)
		ret = {'date_of_retirement': dt.strftime('%Y-%m-%d')}
	return ret

@frappe.whitelist()
def make_salary_structure(source_name, target=None):
	target = get_mapped_doc("Employee", source_name, {
		"Employee": {
			"doctype": "Salary Structure",
			"field_map": {
				"name": "employee"
			}
		}
	})
	target.make_earn_ded_table()
	return target

def update_user_default(doc, method):
	# called via User hook
	try:
		employee = frappe.get_doc("Employee", {"user_id": doc.name})
		employee.update_user_default()
	except frappe.DoesNotExistError:
		pass
<commit_msg>removed confirmation date validations (wtf)<commit_after># Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt

from __future__ import unicode_literals
import frappe

from frappe.utils import getdate, validate_email_add, cint
from frappe.model.naming import make_autoname
from frappe import throw, _
import frappe.permissions
from frappe.defaults import get_restrictions
from frappe.model.document import Document
from frappe.model.mapper import get_mapped_doc

class Employee(Document):
	def onload(self):
		self.salary_structure_exists = frappe.db.get_value("Salary Structure",
			{"employee": self.name, "is_active": "Yes", "docstatus": ["!=", 2]})

	def as_dict(self, no_nulls=False):
		doc = super(Employee, self).as_dict(no_nulls)

		if hasattr(self, "salary_structure_exists"):
			doc["salary_structure_exists"] = self.salary_structure_exists

		return doc

	def autoname(self):
		naming_method = frappe.db.get_value("HR Settings", None, "emp_created_by")
		if not naming_method:
			throw(_("Please setup Employee Naming System in Human Resource > HR Settings"))
		else:
			if naming_method=='Naming Series':
				self.name = make_autoname(self.naming_series + '.####')
			elif naming_method=='Employee Number':
				self.name = self.employee_number

		self.employee = self.name

	def validate(self):
		from erpnext.utilities import validate_status
		validate_status(self.status, ["Active", "Left"])

		self.employee = self.name
		self.validate_date()
		self.validate_email()
		self.validate_status()
		self.validate_employee_leave_approver()

		if self.user_id:
			self.validate_for_enabled_user_id()
			self.validate_duplicate_user_id()

	def on_update(self):
		if self.user_id:
			self.update_user_default()
			self.update_user()

		self.update_dob_event()
		self.restrict_leave_approver()

	def restrict_user(self):
		"""restrict to this employee for user"""
		self.add_restriction_if_required("Employee", self.user_id)

	def update_user_default(self):
		self.restrict_user()
		frappe.db.set_default("employee_name", self.employee_name, self.user_id)
		frappe.db.set_default("company", self.company, self.user_id)

	def restrict_leave_approver(self):
		"""restrict to this employee for leave approver"""
		employee_leave_approvers = [d.leave_approver for d in self.get("employee_leave_approvers")]
		if self.reports_to and self.reports_to not in employee_leave_approvers:
			employee_leave_approvers.append(frappe.db.get_value("Employee", self.reports_to, "user_id"))

		for user in employee_leave_approvers:
			self.add_restriction_if_required("Employee", user)
			self.add_restriction_if_required("Leave Application", user)

	def add_restriction_if_required(self, doctype, user):
		if frappe.permissions.has_only_non_restrict_role(doctype, user) \
			and self.name not in get_restrictions(user).get("Employee", []):

			frappe.defaults.add_default("Employee", self.name, user, "Restriction")

	def update_user(self):
		# add employee role if missing
		user = frappe.get_doc("User", self.user_id)
		user.ignore_permissions = True

		if "Employee" not in user.get("user_roles"):
			user.add_roles("Employee")

		# copy details like Fullname, DOB and Image to User
		if self.employee_name:
			employee_name = self.employee_name.split(" ")
			if len(employee_name) >= 3:
				user.last_name = " ".join(employee_name[2:])
				user.middle_name = employee_name[1]
			elif len(employee_name) == 2:
				user.last_name = employee_name[1]

			user.first_name = employee_name[0]

		if self.date_of_birth:
			user.birth_date = self.date_of_birth

		if self.gender:
			user.gender = self.gender

		if self.image:
			if not user.user_image:
				user.user_image = self.image
				try:
					frappe.get_doc({
						"doctype": "File Data",
						"file_name": self.image,
						"attached_to_doctype": "User",
						"attached_to_name": self.user_id
					}).insert()
				except frappe.DuplicateEntryError, e:
					# already exists
					pass

		user.save()

	def validate_date(self):
		if self.date_of_birth and self.date_of_joining and getdate(self.date_of_birth) >= getdate(self.date_of_joining):
			throw(_("Date of Joining must be greater than Date of Birth"))

		elif self.date_of_retirement and self.date_of_joining and (getdate(self.date_of_retirement) <= getdate(self.date_of_joining)):
			throw(_("Date Of Retirement must be greater than Date of Joining"))

		elif self.relieving_date and self.date_of_joining and (getdate(self.relieving_date) <= getdate(self.date_of_joining)):
			throw(_("Relieving Date must be greater than Date of Joining"))

		elif self.contract_end_date and self.date_of_joining and (getdate(self.contract_end_date)<=getdate(self.date_of_joining)):
			throw(_("Contract End Date must be greater than Date of Joining"))

	def validate_email(self):
		if self.company_email and not validate_email_add(self.company_email):
			throw(_("Please enter valid Company Email"))
		if self.personal_email and not validate_email_add(self.personal_email):
			throw(_("Please enter valid Personal Email"))

	def validate_status(self):
		if self.status == 'Left' and not self.relieving_date:
			throw(_("Please enter relieving date."))

	def validate_for_enabled_user_id(self):
		if not self.status == 'Active':
			return
		enabled = frappe.db.sql("""select name from `tabUser` where
			name=%s and enabled=1""", self.user_id)
		if not enabled:
			throw(_("User {0} is disabled").format(self.user_id))

	def validate_duplicate_user_id(self):
		employee = frappe.db.sql_list("""select name from `tabEmployee` where
			user_id=%s and status='Active' and name!=%s""", (self.user_id, self.name))
		if employee:
			throw(_("User {0} is already assigned to Employee {1}").format(self.user_id, employee[0]))

	def validate_employee_leave_approver(self):
		from frappe.utils.user import User
		from erpnext.hr.doctype.leave_application.leave_application import InvalidLeaveApproverError

		for l in self.get("employee_leave_approvers"):
			if "Leave Approver" not in User(l.leave_approver).get_roles():
				throw(_("{0} is not a valid Leave Approver").format(l.leave_approver), InvalidLeaveApproverError)

	def update_dob_event(self):
		if self.status == "Active" and self.date_of_birth \
			and not cint(frappe.db.get_value("HR Settings", None, "stop_birthday_reminders")):
			birthday_event = frappe.db.sql("""select name from `tabEvent` where repeat_on='Every Year'
				and ref_type='Employee' and ref_name=%s""", self.name)

			starts_on = self.date_of_birth + " 00:00:00"
			ends_on = self.date_of_birth + " 00:15:00"

			if birthday_event:
				event = frappe.get_doc("Event", birthday_event[0][0])
				event.starts_on = starts_on
				event.ends_on = ends_on
				event.save()
			else:
				frappe.get_doc({
					"doctype": "Event",
					"subject": _("Birthday") + ": " + self.employee_name,
					"description": _("Happy Birthday!") + " " + self.employee_name,
					"starts_on": starts_on,
					"ends_on": ends_on,
					"event_type": "Public",
					"all_day": 1,
					"send_reminder": 1,
					"repeat_this_event": 1,
					"repeat_on": "Every Year",
					"ref_type": "Employee",
					"ref_name": self.name
				}).insert()
		else:
			frappe.db.sql("""delete from `tabEvent` where repeat_on='Every Year' and
				ref_type='Employee' and ref_name=%s""", self.name)

@frappe.whitelist()
def get_retirement_date(date_of_birth=None):
	import datetime
	ret = {}
	if date_of_birth:
		dt = getdate(date_of_birth) + datetime.timedelta(21915)
		ret = {'date_of_retirement': dt.strftime('%Y-%m-%d')}
	return ret

@frappe.whitelist()
def make_salary_structure(source_name, target=None):
	target = get_mapped_doc("Employee", source_name, {
		"Employee": {
			"doctype": "Salary Structure",
			"field_map": {
				"name": "employee"
			}
		}
	})
	target.make_earn_ded_table()
	return target

def update_user_default(doc, method):
	# called via User hook
	try:
		employee = frappe.get_doc("Employee", {"user_id": doc.name})
		employee.update_user_default()
	except frappe.DoesNotExistError:
		pass
<|endoftext|>


<commit_before>import urllib

from zope.interface import classProvides

from twisted.plugin import IPlugin
from twisted.web.client import getPage

from renamer.irenamer import IRenamerPlugin
from renamer.plugin import Plugin, command

from pyparsing import (alphanums, nums, Word, Literal, ParseException, SkipTo,
    FollowedBy, ZeroOrMore, Combine, NotAny, Optional, StringEnd)

from renamer.errors import PluginError
from renamer.util import Replacement, ConditionalReplacer

class TV(Plugin):
    classProvides(IPlugin, IRenamerPlugin)

    name = 'tv'

    def __init__(self, **kw):
        super(TV, self).__init__(**kw)
        self.filename = self._createParser()
        self.repl = {
            'show': Replacement.fromFile(self.openFile('shownames')),
            'ep':   Replacement.fromFile(self.openFile('epnames'), ConditionalReplacer)}

    def _createParser(self):
        def L(value):
            return Literal(value).suppress()

        number = Word(nums)
        digit = Word(nums, exact=1)

        separator = Literal('_-_') | Literal(' - ') | Literal('.-.') | Literal('-') | Literal('.') | Literal('_') | Literal(' ')
        separator = separator.suppress().leaveWhitespace()

        season = number.setResultsName('season')
        short_season = digit.setResultsName('season')
        epnum = number.setResultsName('ep')
        exact_epnum = Word(nums, exact=2).setResultsName('ep')
        episode = ( season + L('x') + epnum
                  | L('[') + season + L('x') + epnum + L(']')
                  | L('S') + season + L('E') + epnum
                  | L('s') + season + L('e') + epnum
                  | short_season + exact_epnum
                  )

        series_word = Word(alphanums)
        series = ZeroOrMore(series_word + separator + NotAny(episode + separator)) + series_word
        series = Combine(series, joinString=' ').setResultsName('series_name')

        extension = '.' + Word(alphanums).setResultsName('ext') + StringEnd()

        title = SkipTo(FollowedBy(extension))

        return series + separator + episode + Optional(separator + title) + extension

    @command
    def find_parts(self, src):
        """
        Get TV episode information from a filename.
        """
        try:
            parse = self.filename.parseString(src)
        except ParseException, e:
            raise PluginError('No patterns could be found in %r (%r)' % (src, e))
        else:
            return parse.series_name, parse.season, parse.ep, parse.ext

    @command
    def tvrage(self, key, showName):
        """
        Look up TV episode information on TV Rage.
        """
        qs = urllib.urlencode([('show', showName), ('ep', key)])
        url = 'http://www.tvrage.com/quickinfo.php?%s' % (qs,)

        def getParams(page):
            data = {}
            for line in page.splitlines():
                key, value = line.strip().split('@', 1)
                data[key] = value.split('^')

            showName = self.repl['show'].replace(data['Show Name'][0])
            season, epNumber = map(int, data['Episode Info'][0].split('x'))
            epName = self.repl['ep'].replace(data['Episode Info'][1], showName)

            return showName, season, epNumber, epName

        return getPage(url).addCallback(getParams)
<commit_msg>Docstring.<commit_after>import urllib

from zope.interface import classProvides

from twisted.plugin import IPlugin
from twisted.web.client import getPage

from renamer.irenamer import IRenamerPlugin
from renamer.plugin import Plugin, command

from pyparsing import (alphanums, nums, Word, Literal, ParseException, SkipTo,
    FollowedBy, ZeroOrMore, Combine, NotAny, Optional, StringEnd)

from renamer.errors import PluginError
from renamer.util import Replacement, ConditionalReplacer

class TV(Plugin):
    classProvides(IPlugin, IRenamerPlugin)

    name = 'tv'

    def __init__(self, **kw):
        super(TV, self).__init__(**kw)
        self.filename = self._createParser()
        self.repl = {
            'show': Replacement.fromFile(self.openFile('shownames')),
            'ep':   Replacement.fromFile(self.openFile('epnames'), ConditionalReplacer)}

    def _createParser(self):
        """
        Create the filename parser.
        """
        def L(value):
            return Literal(value).suppress()

        number = Word(nums)
        digit = Word(nums, exact=1)

        separator = Literal('_-_') | Literal(' - ') | Literal('.-.') | Literal('-') | Literal('.') | Literal('_') | Literal(' ')
        separator = separator.suppress().leaveWhitespace()

        season = number.setResultsName('season')
        short_season = digit.setResultsName('season')
        epnum = number.setResultsName('ep')
        exact_epnum = Word(nums, exact=2).setResultsName('ep')
        episode = ( season + L('x') + epnum
                  | L('[') + season + L('x') + epnum + L(']')
                  | L('S') + season + L('E') + epnum
                  | L('s') + season + L('e') + epnum
                  | short_season + exact_epnum
                  )

        series_word = Word(alphanums)
        series = ZeroOrMore(series_word + separator + NotAny(episode + separator)) + series_word
        series = Combine(series, joinString=' ').setResultsName('series_name')

        extension = '.' + Word(alphanums).setResultsName('ext') + StringEnd()

        title = SkipTo(FollowedBy(extension))

        return series + separator + episode + Optional(separator + title) + extension

    @command
    def find_parts(self, src):
        """
        Get TV episode information from a filename.
        """
        try:
            parse = self.filename.parseString(src)
        except ParseException, e:
            raise PluginError('No patterns could be found in %r (%r)' % (src, e))
        else:
            return parse.series_name, parse.season, parse.ep, parse.ext

    @command
    def tvrage(self, key, showName):
        """
        Look up TV episode information on TV Rage.
        """
        qs = urllib.urlencode([('show', showName), ('ep', key)])
        url = 'http://www.tvrage.com/quickinfo.php?%s' % (qs,)

        def getParams(page):
            data = {}
            for line in page.splitlines():
                key, value = line.strip().split('@', 1)
                data[key] = value.split('^')

            showName = self.repl['show'].replace(data['Show Name'][0])
            season, epNumber = map(int, data['Episode Info'][0].split('x'))
            epName = self.repl['ep'].replace(data['Episode Info'][1], showName)

            return showName, season, epNumber, epName

        return getPage(url).addCallback(getParams)
<|endoftext|>


<commit_before>from os.path import join
from os import getcwd
from devilry_settings.default_settings import *

basedir = getcwd()

DATABASES = {"default": {
                         'ENGINE': 'django.db.backends.sqlite3',  # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
                         'NAME': join(basedir, 'db.sqlite3'),    # Or path to database file if using sqlite3.
                         'USER': '',             # Not used with sqlite3.
                         'PASSWORD': '',         # Not used with sqlite3.
                         'HOST': '',             # Set to empty string for localhost. Not used with sqlite3.
                         'PORT': '',             # Set to empty string for default. Not used with sqlite3.
                        }
            }

INSTALLED_APPS += ['devilry.apps.asminimalaspossible_gradeeditor',
                   'seleniumhelpers',
                   'djangosenchatools',

                   # Not apps, but here for the Django test system to discover them:
                   'devilry.utils',
                   'devilry.restful',
                   'devilry.simplified']

INTERNAL_IPS = ["127.0.0.1"]
DEBUG = True
TEMPLATE_DEBUG = DEBUG
EXTJS4_DEBUG = True
STATIC_ROOT = 'static'

DEVILRY_ENABLE_MATHJAX = False

# Make this unique, and don't share it with anybody.
SECRET_KEY = '+g$%**q(w78xqa_2)(_+%v8d)he-b_^@d*pqhq!#2p*a7*9e9h'

# If no admins are set, no emails are sent to admins
ADMINS = (
     ('Devilry admin', 'admin@example.com'),
)
MANAGERS = ADMINS
MEDIA_ROOT = join(basedir, "filestore")
ROOT_URLCONF = 'devilry_developer.dev_urls'

DEVILRY_SCHEME_AND_DOMAIN = 'https://devilry.example.com'

DEVILRY_DELIVERY_STORE_BACKEND = 'devilry.apps.core.deliverystore.FsHierDeliveryStore'
#DELIVERY_STORE_ROOT = join(basedir, 'deliverystore')
DEVILRY_FSHIERDELIVERYSTORE_ROOT = join(basedir, 'deliverystorehier')
DEVILRY_FSHIERDELIVERYSTORE_INTERVAL = 10
DEVILRY_SYNCSYSTEM = 'FS (Felles Studentsystem)'

## django_seleniumhelpers
## - http://django_seleniumhelpers.readthedocs.org/
#SKIP_SELENIUMTESTS = True
SELENIUM_BROWSER = 'Firefox' # Default selenium browser

#DEVILRY_USERADMIN_USER_READONLY_FIELDS = ['email', 'is_superuser', 'is_staff', 'is_active']
#DEVILRY_USERADMIN_DEVILRYUSERPROFILE_READONLY_FIELDS = ['languagecode', 'full_name']
#DEVILRY_USERADMIN_USER_CHANGE_VIEW_MESSAGE = 'This is a test.'
#DEVILRY_USERADMIN_USER_ADD_VIEW_MESSAGE = 'This is a add test.'
#DEVILRY_USERADMIN_PASSWORD_HELPMESSAGE = 'Passwords are handled by Our Awesome External User Management System. Follow this link to reset passwords.'

##################################################################################
# Make Devilry speak in typical university terms (semester instead of period, ...)
##################################################################################
INSTALLED_APPS += ['devilry_university_translations']
DEVILRY_JAVASCRIPT_LOCALE_OVERRIDE_APPS = ('devilry_university_translations',)

##################################################################################
# Email
##################################################################################
DEVILRY_SEND_EMAIL_TO_USERS = True
EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'
EMAIL_FILE_PATH = join(basedir, 'email_log')
DEVILRY_EMAIL_DEFAULT_FROM = 'devilry-support@example.com'
DEVILRY_SYSTEM_ADMIN_EMAIL='devilry-support@example.com'
DEVILRY_DEFAULT_EMAIL_SUFFIX='@example.com'

## If you want to test with a "real" smtp server instead of the file backend, see:
##     https://docs.djangoproject.com/en/dev/topics/email/#testing-email-sending
## In short, uncomment the settings below and run the built in smtpd server in python:
##      python -m smtpd -n -c DebuggingServer localhost:1025
## The smtpd server prints emails to stdout.
#EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
#EMAIL_HOST = 'localhost'
#EMAIL_PORT = 1025

#######################################################################
# Various developertools/settings
#######################################################################

# The if's below is just to make it easy to toggle these settings on and off during development
profiler_middleware = False
if profiler_middleware:
    MIDDLEWARE_CLASSES = MIDDLEWARE_CLASSES + [
        'devilry.utils.profile.ProfilerMiddleware' # Enable profiling. Just add ?prof=yes to any url to see a profile report
    ]

#DELAY_MIDDLEWARE_TIME = (80, 120) # Wait for randint(*DELAY_MIDDLEWARE_TIME)/100.0 before responding to each request when using DelayMiddleware
#delay_middleware = True
#if delay_middleware:
    #MIDDLEWARE_CLASSES = MIDDLEWARE_CLASSES + [
        #'devilry.utils.delay_middleware.DelayMiddleware'
    #]

TEMPLATE_CONTEXT_PROCESSORS = TEMPLATE_CONTEXT_PROCESSORS + ('extjs4.context_processors.extjs4',)
MIDDLEWARE_CLASSES = MIDDLEWARE_CLASSES + ['devilry.apps.developertools.middleware.FakeLoginMiddleware']

#######################################################################
# Logging
#######################################################################

MIDDLEWARE_CLASSES = MIDDLEWARE_CLASSES + [
    'devilry.utils.logexceptionsmiddleware.TracebackLoggingMiddleware',
    #'devilry.utils.profile.ProfilerMiddleware' # Enable profiling. Just add ?prof=yes to any url to see a profile report
]

from .log import create_logging_conf
LOGGING = create_logging_conf(basedir)
<commit_msg>devilry_developer.settings.base: Added devilry_sandbox to INSTALLED_APPS.<commit_after>from os.path import join
from os import getcwd
from devilry_settings.default_settings import *

basedir = getcwd()

DATABASES = {"default": {
                         'ENGINE': 'django.db.backends.sqlite3',  # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
                         'NAME': join(basedir, 'db.sqlite3'),    # Or path to database file if using sqlite3.
                         'USER': '',             # Not used with sqlite3.
                         'PASSWORD': '',         # Not used with sqlite3.
                         'HOST': '',             # Set to empty string for localhost. Not used with sqlite3.
                         'PORT': '',             # Set to empty string for default. Not used with sqlite3.
                        }
            }

INSTALLED_APPS += ['devilry.apps.asminimalaspossible_gradeeditor',
                   'seleniumhelpers',
                   'djangosenchatools',
                   'devilry_sandbox',

                   # Not apps, but here for the Django test system to discover them:
                   'devilry.utils',
                   'devilry.restful',
                   'devilry.simplified']

INTERNAL_IPS = ["127.0.0.1"]
DEBUG = True
TEMPLATE_DEBUG = DEBUG
EXTJS4_DEBUG = True
STATIC_ROOT = 'static'

DEVILRY_ENABLE_MATHJAX = False

# Make this unique, and don't share it with anybody.
SECRET_KEY = '+g$%**q(w78xqa_2)(_+%v8d)he-b_^@d*pqhq!#2p*a7*9e9h'

# If no admins are set, no emails are sent to admins
ADMINS = (
     ('Devilry admin', 'admin@example.com'),
)
MANAGERS = ADMINS
MEDIA_ROOT = join(basedir, "filestore")
ROOT_URLCONF = 'devilry_developer.dev_urls'

DEVILRY_SCHEME_AND_DOMAIN = 'https://devilry.example.com'

DEVILRY_DELIVERY_STORE_BACKEND = 'devilry.apps.core.deliverystore.FsHierDeliveryStore'
#DELIVERY_STORE_ROOT = join(basedir, 'deliverystore')
DEVILRY_FSHIERDELIVERYSTORE_ROOT = join(basedir, 'deliverystorehier')
DEVILRY_FSHIERDELIVERYSTORE_INTERVAL = 10
DEVILRY_SYNCSYSTEM = 'FS (Felles Studentsystem)'

## django_seleniumhelpers
## - http://django_seleniumhelpers.readthedocs.org/
#SKIP_SELENIUMTESTS = True
SELENIUM_BROWSER = 'Firefox' # Default selenium browser

#DEVILRY_USERADMIN_USER_READONLY_FIELDS = ['email', 'is_superuser', 'is_staff', 'is_active']
#DEVILRY_USERADMIN_DEVILRYUSERPROFILE_READONLY_FIELDS = ['languagecode', 'full_name']
#DEVILRY_USERADMIN_USER_CHANGE_VIEW_MESSAGE = 'This is a test.'
#DEVILRY_USERADMIN_USER_ADD_VIEW_MESSAGE = 'This is a add test.'
#DEVILRY_USERADMIN_PASSWORD_HELPMESSAGE = 'Passwords are handled by Our Awesome External User Management System. Follow this link to reset passwords.'

##################################################################################
# Make Devilry speak in typical university terms (semester instead of period, ...)
##################################################################################
INSTALLED_APPS += ['devilry_university_translations']
DEVILRY_JAVASCRIPT_LOCALE_OVERRIDE_APPS = ('devilry_university_translations',)

##################################################################################
# Email
##################################################################################
DEVILRY_SEND_EMAIL_TO_USERS = True
EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'
EMAIL_FILE_PATH = join(basedir, 'email_log')
DEVILRY_EMAIL_DEFAULT_FROM = 'devilry-support@example.com'
DEVILRY_SYSTEM_ADMIN_EMAIL='devilry-support@example.com'
DEVILRY_DEFAULT_EMAIL_SUFFIX='@example.com'

## If you want to test with a "real" smtp server instead of the file backend, see:
##     https://docs.djangoproject.com/en/dev/topics/email/#testing-email-sending
## In short, uncomment the settings below and run the built in smtpd server in python:
##      python -m smtpd -n -c DebuggingServer localhost:1025
## The smtpd server prints emails to stdout.
#EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
#EMAIL_HOST = 'localhost'
#EMAIL_PORT = 1025

#######################################################################
# Various developertools/settings
#######################################################################

# The if's below is just to make it easy to toggle these settings on and off during development
profiler_middleware = False
if profiler_middleware:
    MIDDLEWARE_CLASSES = MIDDLEWARE_CLASSES + [
        'devilry.utils.profile.ProfilerMiddleware' # Enable profiling. Just add ?prof=yes to any url to see a profile report
    ]

#DELAY_MIDDLEWARE_TIME = (80, 120) # Wait for randint(*DELAY_MIDDLEWARE_TIME)/100.0 before responding to each request when using DelayMiddleware
#delay_middleware = True
#if delay_middleware:
    #MIDDLEWARE_CLASSES = MIDDLEWARE_CLASSES + [
        #'devilry.utils.delay_middleware.DelayMiddleware'
    #]

TEMPLATE_CONTEXT_PROCESSORS = TEMPLATE_CONTEXT_PROCESSORS + ('extjs4.context_processors.extjs4',)
MIDDLEWARE_CLASSES = MIDDLEWARE_CLASSES + ['devilry.apps.developertools.middleware.FakeLoginMiddleware']

#######################################################################
# Logging
#######################################################################

MIDDLEWARE_CLASSES = MIDDLEWARE_CLASSES + [
    'devilry.utils.logexceptionsmiddleware.TracebackLoggingMiddleware',
    #'devilry.utils.profile.ProfilerMiddleware' # Enable profiling. Just add ?prof=yes to any url to see a profile report
]

from .log import create_logging_conf
LOGGING = create_logging_conf(basedir)
<|endoftext|>