Пример #1
0
def main(*args):
    """Does not ``sys.exit()`` like a when invoked as script, throws exceptions instead."""

    opts = docopt.docopt(__doc__, argv=args or sys.argv[1:])

    verbose = opts['--verbose']
    quiet = opts['--quite']
    level = None  # Let `init_logging()` decide.
    if verbose:
        level = logging.DEBUG
    if quiet:
        level = logging.WARNING
    init_logging(level=level, logconf_file=opts.get('--logconf'))

    if opts['--version']:
        v = build_version_string(verbose)
        # noinspection PyBroadException
        try:
            sys.stdout.buffer.write(v.encode() + b'\n')
            sys.stdout.buffer.flush()
        except:
            print(v)
    elif opts['--interp-methods']:
        msg = 'List of all interpolation methods:\n%s\n'
        msg %= ', '.join(sorted(_interpolation_methods()))
        # noinspection PyBroadException
        try:
            sys.stdout.buffer.write(msg)
            sys.stdout.buffer.flush()
        except:
            print(msg)
    elif opts['template']:
        _cmd_template(opts)
    else:
        do_datasync(opts['<x-label>'],
                    opts['<y-label>'],
                    opts['<ref-table>'],
                    *opts['<sync-table>'],
                    out_path=opts['-O'],
                    prefix_cols=opts['--prefix-cols'],
                    force=opts['--force'],
                    no_clone=opts['--no-clone'],
                    interpolation_method=opts['--interp'],
                    interpolation_methods=parse_overrides(opts['-i'],
                                                          option_name='-i'))
Пример #2
0
def create_app(configfile=None, logconf_file=None):
    from .frontend import frontend

    # We are using the "Application Factory"-pattern here, which is described
    # in detail inside the Flask docs:
    # http://flask.pocoo.org/docs/patterns/appfactories/

    ## log-configuration must come before Flask-config.
    #
    os.environ.get('%s_LOGCONF_FILE' % __name__)
    init_logging(logconf_file=logconf_file, not_using_numpy=True)

    app = Flask(__name__)  #, instance_relative_config=True)

    app.config.from_object('webstamp.default_config')
    app.config.from_envvar('WEBSTAMP_CONFIG')

    app.config['POLYVERSION'] = __version__
    app.config['POLYTIME'] = __updated__

    ## Automatically discover DSN key:
    #  https://docs.sentry.io/clients/python/integrations/flask/#setup
    #
    if 'SENTRY_DSN' in app.config:
        sentry = Sentry()
        sentry_log_level = app.config.get('SENTRY_LOG_LEVEL')
        sentry.init_app(app,
                        logging=bool(sentry_log_level),
                        level=sentry_log_level)

    # Install our Bootstrap extension
    Bootstrap(app)

    # Our application uses blueprints as well; these go well with the
    # application factory. We already imported the blueprint, now we just need
    # to register it:
    app.register_blueprint(frontend)

    # Because we're security-conscious developers, we also hard-code disabling
    # the CDN support (this might become a default in later versions):
    #app.config['BOOTSTRAP_SERVE_LOCAL'] = True

    return app
Пример #3
0
def main(argv=None, log_level=None, **app_init_kwds):
    """
    :param argv:
        If `None`, use :data:`sys.argv`; use ``[]`` to explicitely use no-args.
    """
    init_logging(level=log_level)
    try:
        ##MainCmd.launch_instance(argv or None, **app_init_kwds) ## NO No, does not return `start()`!
        app = MainCmd.instance(**app_init_kwds)
        run_cmd(app, argv)
    except (CmdException, trt.TraitError) as ex:
        ## Suppress stack-trace for "expected" errors.
        log.debug('App exited due to: %s', ex, exc_info=1)
        exit(ex.args[0])
    except Exception as ex:
        ## Shell will see any exception x2, but we have to log it anyways,
        #  in case log has been redirected to a file.
        #
        log.error('Launch failed due to: %s', ex, exc_info=1)
        raise ex
Пример #4
0
import tempfile
from unittest import mock
import unittest

import ddt
import git
import gnupg
from traitlets.config import get_config
import yaml

from co2mpas.__main__ import init_logging
from co2mpas.sampling import baseapp, dice, project
import os.path as osp


init_logging(level=logging.DEBUG)

log = logging.getLogger(__name__)

mydir = osp.dirname(__file__)

#
# _test_cfg = """
# sampling:
#     sender: '*****@*****.**'
#     dice_recipients:
#         - [email protected]
#         - [email protected]
#     mail_server:
#         host: email.jrc.it
#         ssl: true
Пример #5
0
# You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl
from co2mpas import datasync, __main__ as cmain
import logging
import os
import io
import tempfile
import unittest

import ddt
from numpy import testing as npt
import numpy as np
import os.path as osp
import pandas as pd
from pandalone import xleash

cmain.init_logging(level=logging.WARNING)

log = logging.getLogger(__name__)

mydir = osp.dirname(__file__)

_sync_fname = 'datasync.xlsx'
_synced_fname = 'datasync.sync.xlsx'


def _abspath(fname):
    return osp.join(mydir, _sync_fname)


def _file_url(fname):
    return ('file://' + _abspath(fname)).replace('\\', '/')
Пример #6
0
#! python
# -*- coding: UTF-8 -*-
#
# Copyright 2015 European Commission (JRC);
# Licensed under the EUPL (the 'Licence');
# You may not use this work except in compliance with the Licence.
# You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl

import unittest

import ddt

from co2mpas import plot as co2plot
from co2mpas.__main__ import init_logging

init_logging(True)


@ddt.ddt
class TPlot(unittest.TestCase):
    @ddt.data(*co2plot.get_model_paths())
    def test_plot_all_models(self, model):
        dot_graphs = co2plot.plot_model_graphs([model],
                                               view_in_browser=False,
                                               depth=1)
        self.assertGreaterEqual(len(dot_graphs), 1, model)
Пример #7
0

## Set this to `True` to update setbelt data.
# NOTE: Do not commit it as `True`!
OVERWRITE_SEATBELT = _bool_env_var('OVERWRITE_SEATBELT', False)
RUN_ALL_FILES = _bool_env_var('RUN_ALL_FILES', False)
RUN_INPUT_FOLDER = os.environ.get('RUN_INPUT_FOLDER', None)
SEATBELT_FILE = os.environ.get('SEATBELT_FILE', None)

EPS = 2 * sys.float_info.epsilon

## Set to 0 to compare EXACT.
# NOTE: Do not commit it as none-zer0
DATA_DIFF_RATIO = 0  # 2 * EPS

init_logging(level=logging.WARNING)
#logging.getLogger('pandalone.xleash').setLevel(logging.INFO)
log = logging.getLogger(__name__)


class SeatBelt(unittest.TestCase):
    def _check_results(self, new_res, old_res):

        msg = "AssertionError: %f not less than or equal to %f\n" \
              "Failed [%r]: %s !~= %s"

        fail = []

        if len(new_res) != len(old_res):
            fail.append('Mismatch in the number of vehicles: '
                        'new(%i) != old(%i)' % (len(new_res), len(old_res)))
Пример #8
0
# You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl
from co2mpas import datasync, __main__ as cmain
import logging
import os
import io
import tempfile
import unittest

import ddt
from numpy import testing as npt
import numpy as np
import os.path as osp
import pandas as pd
from pandalone import xleash

cmain.init_logging(False)
log = logging.getLogger(__name__)

mydir = osp.dirname(__file__)

_sync_fname = 'datasync.xlsx'
_synced_fname = 'datasync.sync.xlsx'


def _abspath(fname):
    return osp.join(mydir, _sync_fname)


def _file_url(fname):
    return ('file://' + _abspath(fname)).replace('\\', '/')
Пример #9
0

## Set this to `True` to update setbelt data.
# NOTE: Do not commit it as `True`!
OVERWRITE_SEATBELT = _bool_env_var('OVERWRITE_SEATBELT', False)
RUN_ALL_FILES = _bool_env_var('RUN_ALL_FILES', False)
RUN_INPUT_FOLDER = os.environ.get('RUN_INPUT_FOLDER', None)
SEATBELT_FILE = os.environ.get('SEATBELT_FILE', None)

EPS = 2 * sys.float_info.epsilon

## Set to 0 to compare EXACT.
# NOTE: Do not commit it as none-zer0
DATA_DIFF_RATIO = 0 # 2 * EPS

init_logging(False)
#logging.getLogger('pandalone.xleash').setLevel(logging.INFO)
log = logging.getLogger(__name__)


class SeatBelt(unittest.TestCase):

    def _check_results(self, new_res, old_res):

        msg = "AssertionError: %f not less than or equal to %f\n" \
              "Failed [%r]: %s !~= %s"

        fail = []

        if len(new_res) != len(old_res):
            fail.append('Mismatch in the number of vehicles: '