<commit_before># Tools/paths finder resolves external paths from settings and/or environment
# variables
#
# Currently supported:
#
#   PYLMM_PATH finds the root of the git repository of the pylmm_gn2 tool

import os

def get_setting():
    """
    Resolve a setting from the environment or the global settings in app.config
    """
    pass

def pylmm_command(default=None):
    def get_valid_path(path):
        if path and os.path.isfile(path+'/lmm.py'):
            return path
        else:
            None

    # ---- Check whether environment exists
    path = get_valid_path(os.environ['PYLMM_PATH'])
    # ---- Check whether setting exists
    if not path:
        path = get_valid_path(app.config.get('PYLMM_PATH'))
    # ---- Check whether default exists
    if not path:
        path = get_valid_path(default)
    home = get_valid_path(os.environ['HOME']+'/pylmm_gn2')
    if not path:
        path = get_valid_path(home)
    if not path:
        raise Exception('PYLMM_PATH '+home+' unknown or faulty (add PYLMM_PATH to settings.py)')
    pylmm_command = 'python '+path+'/lmm.py'
    return path,pylmm_command
<commit_msg>More elaborate handling of finding pylmm<commit_after># Tools/paths finder resolves external paths from settings and/or environment
# variables
#
# Currently supported:
#
#   PYLMM_PATH finds the root of the git repository of the pylmm_gn2 tool

import os
import sys
from wqflask import app

def get_setting(id,default,guess,get_valid_path):
    """
    Resolve a setting from the environment or the global settings in app.config
    """
    # ---- Check whether environment exists
    path = get_valid_path(os.environ.get(id))
    # ---- Check whether setting exists
    setting = app.config.get(id)
    if not path:
        path = get_valid_path(setting)
    # ---- Check whether default exists
    if not path:
        path = get_valid_path(default)
    # ---- Guess directory
    if not path:
        if not setting:
            setting = guess
        path = get_valid_path(guess)
    if not path:
        raise Exception(id+' '+setting+' path unknown or faulty (update settings.py?)')

    return path

def pylmm_command(default=None):
    """
    Return the path to the repository and the python command to call
    """
    def get_valid_path(path):
        """Test for a valid repository"""
        if path:
            sys.stderr.write("Trying PYLMM_PATH in "+path+"\n")
        if path and os.path.isfile(path+'/pylmm_gn2/lmm.py'):
            return path
        else:
            None

    guess = os.environ.get('HOME')+'/pylmm_gn2'
    path = get_setting('PYLMM_PATH',default,guess,get_valid_path)
    pylmm_command = 'python '+path+'/pylmm_gn2/lmm.py'
    return path,pylmm_command
<|endoftext|>


<commit_before>import numpy

from ...import describe
from ...describe import Dimension, Synapses, Gradient
from .._lsuv import LSUVinit
from ..ops import NumpyOps
from ...api import layerize
from .model import Model

try:
    import cupy
except ImportError:
    cupy = None

@layerize
def get_word_ids(docs, drop=0.):
    '''Get word forms.'''
    seqs = []
    ops = Model.ops
    for doc in docs:
        arr = ops.xp.zeros((len(doc)+1,), dtype='uint64')
        for token in doc:
            arr[token.i] = token.orth
        arr[len(doc)] = 0
        seqs.append(arr)
    return seqs, None

@describe.on_data(LSUVinit)
@describe.attributes(
        nM=Dimension("Vector dimensions"),
        nO=Dimension("Size of output"),
        W=Synapses(
            "A projection matrix, to change vector dimensionality",
            lambda obj: (obj.nO, obj.nM),
            lambda W, ops: ops.xavier_uniform_init(W)),
        d_W=Gradient("W"),
)
class SpacyVectors(Model):
    ops = NumpyOps()
    name = 'spacy-vectors'
    def __init__(self, nlp, nO):
        Model.__init__(self)
        self._id_map = {0: 0}
        self.nO = nO
        self.nM = nlp.vocab.vectors_length
        self.nlp = nlp

    @property
    def nV(self):
        return len(self.nlp.vocab)

    def begin_update(self, ids, drop=0.):
        if not isinstance(ids, numpy.ndarray):
            ids = ids.get()
            gpu_in = True
        else:
            gpu_in = False
        uniqs, inverse = numpy.unique(ids, return_inverse=True)
        vectors = self.ops.allocate((uniqs.shape[0], self.nM))
        for i, orth in enumerate(uniqs):
            vectors[i] = self.nlp.vocab[orth].vector
        def finish_update(gradients, sgd=None):
            if gpu_in:
                gradients = gradients.get()
            self.d_W += self.ops.batch_outer(gradients, vectors[inverse, ])
            if sgd is not None:
                ops = sgd.ops
                sgd.ops = self.ops
                sgd(self._mem.weights, self._mem.gradient, key=id(self._mem))
                sgd.ops = ops
            return None
        dotted = self.ops.batch_dot(vectors, self.W)
        if gpu_in:
            return cupy.asarray(dotted[inverse, ]), finish_update
        else:
            return dotted[inverse, ], finish_update
<commit_msg>Normalize the GloVe vectors in SpacyVectors<commit_after>import numpy

from ...import describe
from ...describe import Dimension, Synapses, Gradient
from .._lsuv import LSUVinit
from ..ops import NumpyOps
from ...api import layerize
from .model import Model

try:
    import cupy
except ImportError:
    cupy = None

@layerize
def get_word_ids(docs, drop=0.):
    '''Get word forms.'''
    seqs = []
    ops = Model.ops
    for doc in docs:
        arr = ops.xp.zeros((len(doc)+1,), dtype='uint64')
        for token in doc:
            arr[token.i] = token.orth
        arr[len(doc)] = 0
        seqs.append(arr)
    return seqs, None

@describe.on_data(LSUVinit)
@describe.attributes(
        nM=Dimension("Vector dimensions"),
        nO=Dimension("Size of output"),
        W=Synapses(
            "A projection matrix, to change vector dimensionality",
            lambda obj: (obj.nO, obj.nM),
            lambda W, ops: ops.xavier_uniform_init(W)),
        d_W=Gradient("W"),
)
class SpacyVectors(Model):
    ops = NumpyOps()
    name = 'spacy-vectors'
    def __init__(self, nlp, nO):
        Model.__init__(self)
        self._id_map = {0: 0}
        self.nO = nO
        self.nM = nlp.vocab.vectors_length
        self.nlp = nlp

    @property
    def nV(self):
        return len(self.nlp.vocab)

    def begin_update(self, ids, drop=0.):
        if not isinstance(ids, numpy.ndarray):
            ids = ids.get()
            gpu_in = True
        else:
            gpu_in = False
        uniqs, inverse = numpy.unique(ids, return_inverse=True)
        vectors = self.ops.allocate((uniqs.shape[0], self.nM))
        for i, orth in enumerate(uniqs):
            lex = self.nlp.vocab[orth]
            if lex.vector_norm:
                vectors[i] = lex.vector / lex.vector_norm
        def finish_update(gradients, sgd=None):
            if gpu_in:
                gradients = gradients.get()
            self.d_W += self.ops.batch_outer(gradients, vectors[inverse, ])
            if sgd is not None:
                ops = sgd.ops
                sgd.ops = self.ops
                sgd(self._mem.weights, self._mem.gradient, key=id(self._mem))
                sgd.ops = ops
            return None
        dotted = self.ops.batch_dot(vectors, self.W)
        if gpu_in:
            return cupy.asarray(dotted[inverse, ]), finish_update
        else:
            return dotted[inverse, ], finish_update
<|endoftext|>


<commit_before># Tai Sakuma <tai.sakuma@gmail.com>
import logging
import pytest
from collections import deque

try:
    import unittest.mock as mock
except ImportError:
    import mock

from alphatwirl.concurrently import TaskPackageDropbox

##__________________________________________________________________||
@pytest.fixture()
def packages():
    return [
        mock.Mock(name='package0'),
        mock.Mock(name='package1'),
        mock.Mock(name='package2'),
        mock.Mock(name='package3'),
        mock.Mock(name='package4'),
    ]

@pytest.fixture()
def pkgidx_result_pairs(results):
    # e.g., [(0, package0), (1, package1), ...]
    return list(enumerate(results))

@pytest.fixture()
def results():
    return [
        mock.Mock(name='result0'),
        mock.Mock(name='result1'),
        mock.Mock(name='result2'),
        mock.Mock(name='result3'),
        mock.Mock(name='result4'),
    ]

@pytest.fixture()
def collect_results(results):
    ret = {i: deque([r]) for i, r in enumerate(results)}
    # e.g., {0: deque([result0]), 1:deque([result1]), ...}

    # 3rd job fails twice before succeed
    ret[2].extendleft([None, None])
    # e.g., deque([None, None, result2])

    return ret

@pytest.fixture()
def workingarea(collect_results):
    ret = mock.MagicMock()
    ret.put_package.side_effect = [0, 1, 2, 3, 4] # package indices
    ret.collect_result.side_effect = lambda i: collect_results[i].popleft()
    return ret

@pytest.fixture()
def dispatcher():
    ret = mock.MagicMock()
    ret.run_multiple.return_value = [1000, 1001, 1002, 1003, 1004]

    # jobs finish in steps
    ret.poll.side_effect = [
        [1001, 1003],
        [ ],
        [1002],
        [1004, 1000, 1005],
        [1006]
    ]

    # for resubmission
    ret.run.side_effect = [1005, 1006]

    return ret

@pytest.fixture()
def obj(workingarea, dispatcher, packages):
    ret = TaskPackageDropbox(workingArea=workingarea, dispatcher=dispatcher, sleep=0.01)
    ret.open()
    ret.put_multiple(packages)
    yield ret
    ret.close()

##__________________________________________________________________||
def test_one(workingarea, collect_results):
    print workingarea.collect_result(0)
    print collect_results

##__________________________________________________________________||
def test_receive(obj, pkgidx_result_pairs):
    assert pkgidx_result_pairs == obj.receive()

def test_receive_dispatcher_received_failed_runids(obj, dispatcher):
    obj.receive()
    assert [
        mock.call([]), mock.call([]), mock.call([1002]),
        mock.call([1005]), mock.call([])
    ] == dispatcher.failed_runids.call_args_list

def test_receive_logging_resubmission(obj, caplog):
    with caplog.at_level(logging.WARNING):
        obj.receive()
    assert len(caplog.records) == 2
    assert caplog.records[0].levelname == 'WARNING'
    assert caplog.records[1].levelname == 'WARNING'
    assert 'TaskPackageDropbox' in caplog.records[0].name
    assert 'TaskPackageDropbox' in caplog.records[1].name
    assert 'resubmitting' in caplog.records[0].msg
    assert 'resubmitting' in caplog.records[1].msg

def test_receive_in_one_step(obj, pkgidx_result_pairs, dispatcher, collect_results):

    # make all jobs finish by the first poll
    dispatcher.poll.side_effect = [[1000, 1001, 1002, 1003, 1004]]

    # make the 3rd job successful by removing two None's
    collect_results[2].popleft() # deque([None, result2])
    collect_results[2].popleft() # deque([result2])

    assert pkgidx_result_pairs == obj.receive()

##__________________________________________________________________||
def test_poll(obj, pkgidx_result_pairs):
    print pkgidx_result_pairs
    actual = [ ]
    while len(actual) < len(pkgidx_result_pairs):
        actual.extend(obj.poll())
    assert sorted(pkgidx_result_pairs) == sorted(actual)

def test_poll_then_receive(obj, pkgidx_result_pairs):
    actual = [ ]
    actual.extend(obj.poll())
    actual.extend(obj.receive())

    assert sorted(pkgidx_result_pairs) == sorted(actual)

##__________________________________________________________________||
def test_receive_one(obj, pkgidx_result_pairs):
    actual = [ ]
    while len(actual) < len(pkgidx_result_pairs):
        pair = obj.receive_one()
        if pair is None:
            break
        actual.append(pair)
    assert obj.receive_one() is None
    assert sorted(pkgidx_result_pairs) == sorted(actual)

def test_receive_one_then_receive(obj, pkgidx_result_pairs):
    actual = [ ]

    actual.append(obj.receive_one())

    actual.extend(obj.receive())

    assert sorted(pkgidx_result_pairs) == sorted(actual)

def test_receive_one_then_poll(obj, pkgidx_result_pairs):
    actual = [ ]

    actual.append(obj.receive_one())

    actual.extend(obj.poll())
    actual.extend(obj.poll())
    actual.extend(obj.poll())
    actual.extend(obj.poll())

    assert sorted(pkgidx_result_pairs) == sorted(actual)

##__________________________________________________________________||
<commit_msg>remove print statements from tests<commit_after># Tai Sakuma <tai.sakuma@gmail.com>
import logging
import pytest
from collections import deque

try:
    import unittest.mock as mock
except ImportError:
    import mock

from alphatwirl.concurrently import TaskPackageDropbox

##__________________________________________________________________||
@pytest.fixture()
def packages():
    return [
        mock.Mock(name='package0'),
        mock.Mock(name='package1'),
        mock.Mock(name='package2'),
        mock.Mock(name='package3'),
        mock.Mock(name='package4'),
    ]

@pytest.fixture()
def pkgidx_result_pairs(results):
    # e.g., [(0, package0), (1, package1), ...]
    return list(enumerate(results))

@pytest.fixture()
def results():
    return [
        mock.Mock(name='result0'),
        mock.Mock(name='result1'),
        mock.Mock(name='result2'),
        mock.Mock(name='result3'),
        mock.Mock(name='result4'),
    ]

@pytest.fixture()
def collect_results(results):
    ret = {i: deque([r]) for i, r in enumerate(results)}
    # e.g., {0: deque([result0]), 1:deque([result1]), ...}

    # 3rd job fails twice before succeed
    ret[2].extendleft([None, None])
    # e.g., deque([None, None, result2])

    return ret

@pytest.fixture()
def workingarea(collect_results):
    ret = mock.MagicMock()
    ret.put_package.side_effect = [0, 1, 2, 3, 4] # package indices
    ret.collect_result.side_effect = lambda i: collect_results[i].popleft()
    return ret

@pytest.fixture()
def dispatcher():
    ret = mock.MagicMock()
    ret.run_multiple.return_value = [1000, 1001, 1002, 1003, 1004]

    # jobs finish in steps
    ret.poll.side_effect = [
        [1001, 1003],
        [ ],
        [1002],
        [1004, 1000, 1005],
        [1006]
    ]

    # for resubmission
    ret.run.side_effect = [1005, 1006]

    return ret

@pytest.fixture()
def obj(workingarea, dispatcher, packages):
    ret = TaskPackageDropbox(workingArea=workingarea, dispatcher=dispatcher, sleep=0.01)
    ret.open()
    ret.put_multiple(packages)
    yield ret
    ret.close()

##__________________________________________________________________||
def test_receive(obj, pkgidx_result_pairs):
    assert pkgidx_result_pairs == obj.receive()

def test_receive_dispatcher_received_failed_runids(obj, dispatcher):
    obj.receive()
    assert [
        mock.call([]), mock.call([]), mock.call([1002]),
        mock.call([1005]), mock.call([])
    ] == dispatcher.failed_runids.call_args_list

def test_receive_logging_resubmission(obj, caplog):
    with caplog.at_level(logging.WARNING):
        obj.receive()
    assert len(caplog.records) == 2
    assert caplog.records[0].levelname == 'WARNING'
    assert caplog.records[1].levelname == 'WARNING'
    assert 'TaskPackageDropbox' in caplog.records[0].name
    assert 'TaskPackageDropbox' in caplog.records[1].name
    assert 'resubmitting' in caplog.records[0].msg
    assert 'resubmitting' in caplog.records[1].msg

def test_receive_in_one_step(obj, pkgidx_result_pairs, dispatcher, collect_results):

    # make all jobs finish by the first poll
    dispatcher.poll.side_effect = [[1000, 1001, 1002, 1003, 1004]]

    # make the 3rd job successful by removing two None's
    collect_results[2].popleft() # deque([None, result2])
    collect_results[2].popleft() # deque([result2])

    assert pkgidx_result_pairs == obj.receive()

##__________________________________________________________________||
def test_poll(obj, pkgidx_result_pairs):
    actual = [ ]
    while len(actual) < len(pkgidx_result_pairs):
        actual.extend(obj.poll())
    assert sorted(pkgidx_result_pairs) == sorted(actual)

def test_poll_then_receive(obj, pkgidx_result_pairs):
    actual = [ ]
    actual.extend(obj.poll())
    actual.extend(obj.receive())

    assert sorted(pkgidx_result_pairs) == sorted(actual)

##__________________________________________________________________||
def test_receive_one(obj, pkgidx_result_pairs):
    actual = [ ]
    while len(actual) < len(pkgidx_result_pairs):
        pair = obj.receive_one()
        if pair is None:
            break
        actual.append(pair)
    assert obj.receive_one() is None
    assert sorted(pkgidx_result_pairs) == sorted(actual)

def test_receive_one_then_receive(obj, pkgidx_result_pairs):
    actual = [ ]

    actual.append(obj.receive_one())

    actual.extend(obj.receive())

    assert sorted(pkgidx_result_pairs) == sorted(actual)

def test_receive_one_then_poll(obj, pkgidx_result_pairs):
    actual = [ ]

    actual.append(obj.receive_one())

    actual.extend(obj.poll())
    actual.extend(obj.poll())
    actual.extend(obj.poll())
    actual.extend(obj.poll())

    assert sorted(pkgidx_result_pairs) == sorted(actual)

##__________________________________________________________________||
<|endoftext|>


<commit_before>""" Setup file.
"""
import os
from setuptools import setup, find_packages

here = os.path.abspath(os.path.dirname(__file__))

with open(os.path.join(here, 'README.rst')) as f:
    README = f.read()

setup(name='corniceapp',
    version=0.1,
    description='corniceapp',
    long_description=README,
    classifiers=[
        "Programming Language :: Python",
        "Framework :: Pylons",
        "Topic :: Internet :: WWW/HTTP",
        "Topic :: Internet :: WWW/HTTP :: WSGI :: Application"
    ],
    keywords="web services",
    author='',
    author_email='',
    url='',
    packages=find_packages(),
    include_package_data=True,
    zip_safe=False,
    install_requires=[
        'cornice',
        'PasteScript',
        'waitress',
        'sqlalchemy',
    #    'MySQL-python',
        'zope.sqlalchemy',
        'WebError',
        'sh',
        'BeautifulSoup',
        'GitPython',
    ],
    entry_points = """\
    [paste.app_factory]
    main = corniceapp:main
    """,
    paster_plugins=['pyramid'],
)
<commit_msg>Added requests<commit_after>""" Setup file.
"""
import os
from setuptools import setup, find_packages

here = os.path.abspath(os.path.dirname(__file__))

with open(os.path.join(here, 'README.rst')) as f:
    README = f.read()

setup(name='corniceapp',
    version=0.1,
    description='corniceapp',
    long_description=README,
    classifiers=[
        "Programming Language :: Python",
        "Framework :: Pylons",
        "Topic :: Internet :: WWW/HTTP",
        "Topic :: Internet :: WWW/HTTP :: WSGI :: Application"
    ],
    keywords="web services",
    author='',
    author_email='',
    url='',
    packages=find_packages(),
    include_package_data=True,
    zip_safe=False,
    install_requires=[
        'cornice',
        'PasteScript',
        'waitress',
        'sqlalchemy',
    #    'MySQL-python',
        'zope.sqlalchemy',
        'WebError',
        'sh',
        'BeautifulSoup',
        'GitPython',
        'requests'
    ],
    entry_points = """\
    [paste.app_factory]
    main = corniceapp:main
    """,
    paster_plugins=['pyramid'],
)
<|endoftext|>


<commit_before>"""
The command line interface for the Threema Gateway Callback Server.
"""
import functools
import asyncio

import click

from threema.gateway import __version__ as _version
from threema.gateway import util, Connection
from threema.gateway.key import Key
from threema.gateway.e2e import AbstractCallback

class Callback(AbstractCallback):
    @asyncio.coroutine
    def receive_message(self, message):
        click.echo('Got message ({}): {}'.format(repr(message), message))

def aio_run(func, run_forever=False):
    func = asyncio.coroutine(func)

    def _wrapper(*args, **kwargs):
        loop = asyncio.get_event_loop()
        task = loop.create_task(func(*args, **kwargs))
        loop.run_until_complete(task)
        if run_forever:
            loop.run_forever()
        return task.result()
    return functools.update_wrapper(_wrapper, func)

def aio_serve(func):
    return aio_run(func, run_forever=True)

@click.group()
@click.pass_context
def cli(ctx):
    """
    Command Line Interface. Use --help for details.
    """
    ctx.obj = {}

@cli.command(short_help='Show version information.', help="""
Show the current version of the Threema Gateway Callback Server.
""")
def version():
    click.echo('Version: {}'.format(_version))

@cli.command(short_help='Start the callback server.', help="""
Start the Threema Gateway Callback Server.
FROM is the API identity and SECRET is the API secret.
CERT represents the path to a file in PEM format containing the SSL
certificate of the server.""")
@click.argument('identity')
@click.argument('secret')
@click.argument('private_key')
@click.argument('cert', type=click.Path(exists=True))
@click.option('-k', '--keyfile', type=click.Path(exists=True), help="""
Path to a file that contains the private key. Will be read from
CERTFILE if not present.""")
@click.option('-h', '--host', help='Bind to a specific host.')
@click.option('-p', '--port', default=443, help='Listen on a specific port.')
@aio_serve
def serve(**arguments):
    # Get arguments
    identity = arguments['identity']
    secret = arguments['secret']
    private_key = util.read_key_or_key_file(arguments['private_key'], Key.Type.private)
    certfile = arguments['cert']
    keyfile = arguments.get('keyfile')
    host = arguments.get('host')
    port = arguments['port']

    # Create connection and callback instances
    connection = Connection(identity=identity, secret=secret, key=private_key)
    callback = Callback(connection, certfile=certfile, keyfile=keyfile)

    # Create server
    yield from callback.create_server(host=host, port=port)

def main():
    # with server.logging_handler.applicationbound():
    try:
        cli()
    except Exception as exc:
        click.echo('An error occurred:', err=True)
        click.echo(exc, err=True)
        raise
<commit_msg>Properly shut down in threema-callback-server<commit_after>"""
The command line interface for the Threema Gateway Callback Server.
"""
import functools
import asyncio

import click

from threema.gateway import __version__ as _version
from threema.gateway import util, Connection
from threema.gateway.key import Key
from threema.gateway.e2e import AbstractCallback

class Callback(AbstractCallback):
    @asyncio.coroutine
    def receive_message(self, message):
        click.echo('Got message ({}): {}'.format(repr(message), message))

def aio_serve(close_func):
    loop = asyncio.get_event_loop()

    def decorator(func):
        func = asyncio.coroutine(func)

        def wrapper(*args, **kwargs):
            # Start
            click.echo('Starting')
            task = loop.create_task(func(*args, **kwargs))
            loop.run_until_complete(task)
            open_result = task.result()
            click.echo('Started')
            try:
                loop.run_forever()
            except KeyboardInterrupt:
                pass
            click.echo('Closing')
            task = loop.create_task(close_func(open_result))
            loop.run_until_complete(task)
            close_result = task.result()
            click.echo('Closed')
            return open_result, close_result

        return functools.update_wrapper(wrapper, func)

    return decorator

@click.group()
@click.pass_context
def cli(ctx):
    """
    Command Line Interface. Use --help for details.
    """
    ctx.obj = {}

@cli.command(short_help='Show version information.', help="""
Show the current version of the Threema Gateway Callback Server.
""")
def version():
    click.echo('Version: {}'.format(_version))

@asyncio.coroutine
def close_server(server_and_callback):
    server, callback = server_and_callback
    yield from callback.handler.finish_connections(1.0)
    server.close()
    yield from server.wait_closed()
    yield from callback.application.finish()

@cli.command(short_help='Start the callback server.', help="""
Start the Threema Gateway Callback Server.
FROM is the API identity and SECRET is the API secret.
CERT represents the path to a file in PEM format containing the SSL
certificate of the server.""")
@click.argument('identity')
@click.argument('secret')
@click.argument('private_key')
@click.argument('cert', type=click.Path(exists=True))
@click.option('-k', '--keyfile', type=click.Path(exists=True), help="""
Path to a file that contains the private key. Will be read from
CERTFILE if not present.""")
@click.option('-h', '--host', help='Bind to a specific host.')
@click.option('-p', '--port', default=443, help='Listen on a specific port.')
@aio_serve(close_server)
def serve(**arguments):
    # Get arguments
    identity = arguments['identity']
    secret = arguments['secret']
    private_key = util.read_key_or_key_file(arguments['private_key'], Key.Type.private)
    certfile = arguments['cert']
    keyfile = arguments.get('keyfile')
    host = arguments.get('host')
    port = arguments['port']

    # Create connection and callback instances
    connection = Connection(identity=identity, secret=secret, key=private_key)
    callback = Callback(connection, certfile=certfile, keyfile=keyfile)

    # Create server
    return (yield from callback.create_server(host=host, port=port)), callback

def main():
    # with server.logging_handler.applicationbound():
    try:
        cli()
    except Exception as exc:
        click.echo('An error occurred:', err=True)
        click.echo(exc, err=True)
        raise
<|endoftext|>


<commit_before>"""
Initialize tiddlyspace as a tiddlyweb plugin.
"""

from tiddlyweb.util import merge_config

from tiddlywebplugins.instancer.util import get_tiddler_locations

from tiddlywebplugins.tiddlyspace.commands import establish_commands
from tiddlywebplugins.tiddlyspace.config import config as space_config
from tiddlywebplugins.tiddlyspace.instance import store_contents
from tiddlywebplugins.tiddlyspace.www import establish_www

def init_plugin(config):
    import tiddlywebwiki
    import tiddlywebplugins.logout
    import tiddlywebplugins.virtualhosting  # calling init not required
    import tiddlywebplugins.magicuser
    import tiddlywebplugins.socialusers
    import tiddlywebplugins.mselect
    import tiddlywebplugins.oom
    import tiddlywebplugins.cookiedomain
    import tiddlywebplugins.tiddlyspace.validator
    import tiddlywebplugins.prettyerror
    import tiddlywebplugins.pathinfohack
    import tiddlywebplugins.hashmaker
    import tiddlywebplugins.form
    import tiddlywebplugins.reflector
    import tiddlywebplugins.privateer
    import tiddlywebplugins.relativetime
    import tiddlywebplugins.jsonp

    # Only load and run dispatcher if we are specifically configured
    # to use it.
    if config.get('use_dispatcher', False):
        import tiddlywebplugins.dispatcher
        import tiddlywebplugins.dispatcher.listener

    establish_commands(config)

    merge_config(config, space_config)

    if config.get('tiddlyspace.enable_profile', False):
        from werkzeug.contrib.profiler import ProfilerMiddleware
        config['server_request_filters'].insert(0, ProfilerMiddleware)

    tiddlywebwiki.init(config)
    tiddlywebplugins.logout.init(config)
    tiddlywebplugins.magicuser.init(config)
    tiddlywebplugins.socialusers.init(config)
    tiddlywebplugins.mselect.init(config)
    tiddlywebplugins.oom.init(config)
    tiddlywebplugins.cookiedomain.init(config)
    tiddlywebplugins.prettyerror.init(config)
    tiddlywebplugins.pathinfohack.init(config)
    tiddlywebplugins.hashmaker.init(config)
    tiddlywebplugins.form.init(config)
    tiddlywebplugins.reflector.init(config)
    tiddlywebplugins.privateer.init(config)
    tiddlywebplugins.jsonp.init(config)

    if config.get('use_dispatcher', False):
        tiddlywebplugins.dispatcher.init(config)
        tiddlywebplugins.dispatcher.listener.init(config)

    # XXX: The following is required to work around issues with twp.instancer.
    # Without this, config settings from tiddlywebwiki take precedence.
    config['serializers']['text/x-tiddlywiki'] = space_config[
            'serializers']['text/x-tiddlywiki']
    # This only fixes 'twanager update', instance creation still does not have
    # the right information, thus requiring a twanager update after instance
    # creation. Presumably the instance script needs to do something similar.
    config['instance_tiddlers'] = get_tiddler_locations(store_contents,
            'tiddlywebplugins.tiddlyspace')

    # inject lazy serialization information
    config['extension_types'].update({'lwiki': 'text/x-ltiddlywiki'})
    config['serializers'].update({'text/x-ltiddlywiki':
        ['tiddlywebplugins.tiddlyspace.betalazyserialization',
            'text/html; charset=UTF-8']})

    if 'selector' in config:  # system plugin
        establish_www(config)

    # update html serialization
    new_serializer = ['tiddlywebplugins.tiddlyspace.htmlserialization',
            'text/html; charset=UTF-8']
    config['serializers']['text/html'] = new_serializer
<commit_msg>Add a tiddlyspace.frontpage_installed config boolean.<commit_after>"""
Initialize tiddlyspace as a tiddlyweb plugin.
"""

from tiddlyweb.util import merge_config

from tiddlywebplugins.instancer.util import get_tiddler_locations

from tiddlywebplugins.tiddlyspace.commands import establish_commands
from tiddlywebplugins.tiddlyspace.config import config as space_config
from tiddlywebplugins.tiddlyspace.instance import store_contents
from tiddlywebplugins.tiddlyspace.www import establish_www

def init_plugin(config):
    import tiddlywebwiki
    import tiddlywebplugins.logout
    import tiddlywebplugins.virtualhosting  # calling init not required
    import tiddlywebplugins.magicuser
    import tiddlywebplugins.socialusers
    import tiddlywebplugins.mselect
    import tiddlywebplugins.oom
    import tiddlywebplugins.cookiedomain
    import tiddlywebplugins.tiddlyspace.validator
    import tiddlywebplugins.prettyerror
    import tiddlywebplugins.pathinfohack
    import tiddlywebplugins.hashmaker
    import tiddlywebplugins.form
    import tiddlywebplugins.reflector
    import tiddlywebplugins.privateer
    import tiddlywebplugins.relativetime
    import tiddlywebplugins.jsonp

    # Only load and run dispatcher if we are specifically configured
    # to use it.
    if config.get('use_dispatcher', False):
        import tiddlywebplugins.dispatcher
        import tiddlywebplugins.dispatcher.listener

    establish_commands(config)

    merge_config(config, space_config)

    if config.get('tiddlyspace.enable_profile', False):
        from werkzeug.contrib.profiler import ProfilerMiddleware
        config['server_request_filters'].insert(0, ProfilerMiddleware)

    tiddlywebwiki.init(config)
    tiddlywebplugins.logout.init(config)
    tiddlywebplugins.magicuser.init(config)
    tiddlywebplugins.socialusers.init(config)
    tiddlywebplugins.mselect.init(config)
    tiddlywebplugins.oom.init(config)
    tiddlywebplugins.cookiedomain.init(config)
    tiddlywebplugins.prettyerror.init(config)
    tiddlywebplugins.pathinfohack.init(config)
    tiddlywebplugins.hashmaker.init(config)
    tiddlywebplugins.form.init(config)
    tiddlywebplugins.reflector.init(config)
    tiddlywebplugins.privateer.init(config)
    tiddlywebplugins.jsonp.init(config)

    if config.get('use_dispatcher', False):
        tiddlywebplugins.dispatcher.init(config)
        tiddlywebplugins.dispatcher.listener.init(config)

    # XXX: The following is required to work around issues with twp.instancer.
    # Without this, config settings from tiddlywebwiki take precedence.
    config['serializers']['text/x-tiddlywiki'] = space_config[
            'serializers']['text/x-tiddlywiki']
    # This only fixes 'twanager update', instance creation still does not have
    # the right information, thus requiring a twanager update after instance
    # creation. Presumably the instance script needs to do something similar.
    config['instance_tiddlers'] = get_tiddler_locations(store_contents,
            'tiddlywebplugins.tiddlyspace')

    # When tiddlyspace.frontpage_installed is True, don't update
    # the frontpage_public bag, thus not overwriting what's there.
    if config.get('tiddlyspace.frontpage_installed', False):
        config['instance_tiddlers']['frontpage_public'] = []

    # inject lazy serialization information
    config['extension_types'].update({'lwiki': 'text/x-ltiddlywiki'})
    config['serializers'].update({'text/x-ltiddlywiki':
        ['tiddlywebplugins.tiddlyspace.betalazyserialization',
            'text/html; charset=UTF-8']})

    if 'selector' in config:  # system plugin
        establish_www(config)

    # update html serialization
    new_serializer = ['tiddlywebplugins.tiddlyspace.htmlserialization',
            'text/html; charset=UTF-8']
    config['serializers']['text/html'] = new_serializer
<|endoftext|>


<commit_before>from nose.tools import assert_equal, assert_in, assert_is_none

import requests
from ..cache import CachingSession, MemoryCache, FileCache

DUMMY_URL = 'http://dummy/'
HTTPBIN = 'http://httpbin.org/'

def test_default_key_for_request():
    cs = CachingSession()

    # non-get methods
    for method in ('post', 'head', 'put', 'delete', 'patch'):
        assert_equal(cs.key_for_request(method, DUMMY_URL), None)

    # simple get method
    assert_equal(cs.key_for_request('get', DUMMY_URL), DUMMY_URL)
    # now with params
    assert_equal(cs.key_for_request('get', DUMMY_URL, params={'foo':'bar'}),
                 DUMMY_URL+'?foo=bar')
    # params in both places
    assert_equal(cs.key_for_request('get', DUMMY_URL+'?abc=def',
                                    params={'foo':'bar'}),
                 DUMMY_URL+'?abc=def&foo=bar')

def test_default_should_cache_response():
    cs = CachingSession()
    resp = requests.Response()
    # only 200 should return True
    resp.status_code = 200
    assert_equal(cs.should_cache_response(resp), True)
    for code in (203, 301, 302, 400, 403, 404, 500):
        resp.status_code = code
        assert_equal(cs.should_cache_response(resp), False)

def test_no_cache_request():
    cs = CachingSession()
    # call twice, to prime cache (if it were enabled)
    resp = cs.request('get', HTTPBIN + 'status/200')
    resp = cs.request('get', HTTPBIN + 'status/200')
    assert_equal(resp.status_code, 200)
    assert_equal(resp.fromcache, False)

def test_simple_cache_request():
    cs = CachingSession(cache_storage=MemoryCache())
    url = HTTPBIN + 'get'

    # first response not from cache
    resp = cs.request('get', url)
    assert_equal(resp.fromcache, False)

    assert_in(url, cs.cache_storage.cache)

    # second response comes from cache
    cached_resp = cs.request('get', url)
    assert_equal(resp.text, cached_resp.text)
    assert_equal(cached_resp.fromcache, True)

# test storages #####

def _test_cache_storage(storage_obj):
    # unknown key returns None
    assert_is_none(storage_obj.get('one'))

    # set 'one'
    resp = requests.Response()
    resp.headers['x-num'] = 'one'
    resp.status_code = 200
    resp._content = b'content is king'
    storage_obj.set('one', resp)
    cached_resp = storage_obj.get('one')
    assert_equal(resp.headers, {'x-num': 'one'})
    assert_equal(resp.status_code, 200)
    assert_equal(resp.text, 'content is king')

def test_memory_cache():
    _test_cache_storage(MemoryCache())

def test_file_cache():
    fc = FileCache('cache')
    fc.clear()
    _test_cache_storage(fc)
    fc.clear()
<commit_msg>Py2.6 doesn't have assert_in?<commit_after>from nose.tools import assert_equal, assert_true, assert_is_none

import requests
from ..cache import CachingSession, MemoryCache, FileCache

DUMMY_URL = 'http://dummy/'
HTTPBIN = 'http://httpbin.org/'

def test_default_key_for_request():
    cs = CachingSession()

    # non-get methods
    for method in ('post', 'head', 'put', 'delete', 'patch'):
        assert_equal(cs.key_for_request(method, DUMMY_URL), None)

    # simple get method
    assert_equal(cs.key_for_request('get', DUMMY_URL), DUMMY_URL)
    # now with params
    assert_equal(cs.key_for_request('get', DUMMY_URL, params={'foo':'bar'}),
                 DUMMY_URL+'?foo=bar')
    # params in both places
    assert_equal(cs.key_for_request('get', DUMMY_URL+'?abc=def',
                                    params={'foo':'bar'}),
                 DUMMY_URL+'?abc=def&foo=bar')

def test_default_should_cache_response():
    cs = CachingSession()
    resp = requests.Response()
    # only 200 should return True
    resp.status_code = 200
    assert_equal(cs.should_cache_response(resp), True)
    for code in (203, 301, 302, 400, 403, 404, 500):
        resp.status_code = code
        assert_equal(cs.should_cache_response(resp), False)

def test_no_cache_request():
    cs = CachingSession()
    # call twice, to prime cache (if it were enabled)
    resp = cs.request('get', HTTPBIN + 'status/200')
    resp = cs.request('get', HTTPBIN + 'status/200')
    assert_equal(resp.status_code, 200)
    assert_equal(resp.fromcache, False)

def test_simple_cache_request():
    cs = CachingSession(cache_storage=MemoryCache())
    url = HTTPBIN + 'get'

    # first response not from cache
    resp = cs.request('get', url)
    assert_equal(resp.fromcache, False)

    assert_true(url in cs.cache_storage.cache)

    # second response comes from cache
    cached_resp = cs.request('get', url)
    assert_equal(resp.text, cached_resp.text)
    assert_equal(cached_resp.fromcache, True)

# test storages #####

def _test_cache_storage(storage_obj):
    # unknown key returns None
    assert_is_none(storage_obj.get('one'))

    # set 'one'
    resp = requests.Response()
    resp.headers['x-num'] = 'one'
    resp.status_code = 200
    resp._content = b'content is king'
    storage_obj.set('one', resp)
    cached_resp = storage_obj.get('one')
    assert_equal(resp.headers, {'x-num': 'one'})
    assert_equal(resp.status_code, 200)
    assert_equal(resp.text, 'content is king')

def test_memory_cache():
    _test_cache_storage(MemoryCache())

def test_file_cache():
    fc = FileCache('cache')
    fc.clear()
    _test_cache_storage(fc)
    fc.clear()
<|endoftext|>


<commit_before>### - CLASSES - ###

# ATTACK CLASS
class Attack:
    def __init__(self, name, damage, hit_chance, modifier):
        self.name = name
        self.damage = damage
        self.hit_chance = hit_chance
        # modifier = (name, DMG effect, hit effect, target opponent)
        self.modifier = modifier

    # methods for calling retrieving properties
    def modifier_name(self):
        """ return the name of the modifier"""
        return self.modifier[0]

    def modifier_damage(self):
        """ return modifier effect on damage"""
        return self.modifier[1]

    def modifier_hit_chance(self):
        """ return modifier effect on hit chance"""
        return self.modifier[2]

    def target_opponent(self):
        """ checks if the modifier affects the opponent"""
        # if it doesn't target the opponent it's modifies the active player
        return self.modifier[3]

# MONSTER CLASS
class Monster:
    def __init__(self, name, hp, attack1, attack2, attack3, attack4):
        # the attack arguments belong to Attack class!
        self.name = name
        self.hp = hp
        self.attack1 = attack1
        self.attack2 = attack2
        self.attack3 = attack3
        self.attack4 = attack4
        self.active_modifiers = []

# CONSTRUCTION FUNCTIONS
def create_char():
    """ constructs and returns Monster "charmander" """
    # create the attacks first
    # attack = (name, damage, hit chance, modifier)
    # modifier = (name, DMG effect, hit effect, target opponent)
    attack1 = Attack('Fire', 55, 70, ('Burn', -15, -5, True))
    attack2 = Attack('Scratch', 50, 80, ('Bleed', -10, 0, True))
    attack3 = Attack('Kick', 45, 70, ('Knockdown', -5, -12, True))
    attack4 = Attack('Bite', 60, 60, ('Frenzy', 10, 0, False))

    # monster = (name, HP, attack1, attack2, attack3, attack4)
    char = Monster('Charmander', 500, attack1, attack2, attack3, attack4)

    return char

def create_pika():
    """ constructs and returns Monster "pikachu" """
    # create the attacks first
    # attack = (name, damage, hit chance, modifier)
    # modifier = (name, DMG effect, hit effect, target opponent)
    attack1 = Attack('Lightning', 70, 60, ('Shock', -10, -10, True))
    attack2 = Attack('Scratch', 50, 80, ('Bleed', -10, 0, True))
    attack3 = Attack('Tackle', 50, 67, ('Knockdown', -5, -12, True))
    attack4 = Attack('Paralyze', 20, 80, ('Paralysis', -10, -25, True))

    # monster = (name, HP, attack1, attack2, attack3, attack4)
    pika = Monster('Pikachu', 500, attack1, attack2, attack3, attack4)

    return pika

def copy_monster(monster):
    """ returns a copy of the given monster """
    # check the monter type, generate a monster of the same type
    if monster.name == 'Pikachu':
        monster_copy = create_pika()
    elif monster.name == 'Charmander':
        monster_copy = create_char()

    # change life and modifier to match the given monster
    monster_copy.hp = monster.hp
    monster_copy.active_modifiers = [mod for mod in monster.active_modifiers]

    # return the copy
    return monster_copy

# UTILITY
def possible_attacks(monster):
    """ returns a list of the attacks a monster can make """
    attacks = [monster.attack1, monster.attack2, monster.attack3, monster.attack4]
    return attacks<commit_msg>majhna sprememba enega napada<commit_after>### - CLASSES - ###

# ATTACK CLASS
class Attack:
    def __init__(self, name, damage, hit_chance, modifier):
        self.name = name
        self.damage = damage
        self.hit_chance = hit_chance
        # modifier = (name, DMG effect, hit effect, target opponent)
        self.modifier = modifier

    # methods for calling retrieving properties
    def modifier_name(self):
        """ return the name of the modifier"""
        return self.modifier[0]

    def modifier_damage(self):
        """ return modifier effect on damage"""
        return self.modifier[1]

    def modifier_hit_chance(self):
        """ return modifier effect on hit chance"""
        return self.modifier[2]

    def target_opponent(self):
        """ checks if the modifier affects the opponent"""
        # if it doesn't target the opponent it's modifies the active player
        return self.modifier[3]

# MONSTER CLASS
class Monster:
    def __init__(self, name, hp, attack1, attack2, attack3, attack4):
        # the attack arguments belong to Attack class!
        self.name = name
        self.hp = hp
        self.attack1 = attack1
        self.attack2 = attack2
        self.attack3 = attack3
        self.attack4 = attack4
        self.active_modifiers = []

# CONSTRUCTION FUNCTIONS
def create_char():
    """ constructs and returns Monster "charmander" """
    # create the attacks first
    # attack = (name, damage, hit chance, modifier)
    # modifier = (name, DMG effect, hit effect, target opponent)
    attack1 = Attack('Fire', 55, 70, ('Burn', -15, -5, True))
    attack2 = Attack('Scratch', 50, 80, ('Bleed', -10, 0, True))
    attack3 = Attack('Kick', 45, 70, ('Knockdown', -5, -12, True))
    attack4 = Attack('Bite', 60, 60, ('Frenzy', 10, 0, False))

    # monster = (name, HP, attack1, attack2, attack3, attack4)
    char = Monster('Charmander', 500, attack1, attack2, attack3, attack4)

    return char

def create_pika():
    """ constructs and returns Monster "pikachu" """
    # create the attacks first
    # attack = (name, damage, hit chance, modifier)
    # modifier = (name, DMG effect, hit effect, target opponent)
    attack1 = Attack('Lightning', 70, 60, ('Shock', -10, -10, True))
    attack2 = Attack('Scratch', 50, 80, ('Bleed', -10, 0, True))
    attack3 = Attack('Tackle', 50, 67, ('Knockdown', -5, -12, True))
    attack4 = Attack('Paralyze', 35, 80, ('Paralysis', -10, -25, True))

    # monster = (name, HP, attack1, attack2, attack3, attack4)
    pika = Monster('Pikachu', 500, attack1, attack2, attack3, attack4)

    return pika

def copy_monster(monster):
    """ returns a copy of the given monster """
    # check the monter type, generate a monster of the same type
    if monster.name == 'Pikachu':
        monster_copy = create_pika()
    elif monster.name == 'Charmander':
        monster_copy = create_char()

    # change life and modifier to match the given monster
    monster_copy.hp = monster.hp
    monster_copy.active_modifiers = [mod for mod in monster.active_modifiers]

    # return the copy
    return monster_copy

# UTILITY
def possible_attacks(monster):
    """ returns a list of the attacks a monster can make """
    attacks = [monster.attack1, monster.attack2, monster.attack3, monster.attack4]
    return attacks<|endoftext|>


<commit_before>DEBUG = False

ELASTIC_TIMEOUT = 10
ELASTIC_INDEX = 'share_v2'
ELASTIC_URI = 'localhost:9200'

BROKER_URL = 'amqp://guest@localhost'

CELERY_EAGER_PROPAGATES_EXCEPTIONS = True

RECORD_HTTP_TRANSACTIONS = False

NORMALIZED_PROCESSING = []
RAW_PROCESSING = []

SENTRY_DSN = None

USE_FLUENTD = False
FLUENTD_ARGS = {
    'tag': 'app.scrapi'
}

disabled = []

CASSANDRA_URI = ['127.0.0.1']
CASSANDRA_KEYSPACE = 'scrapi'

FRONTEND_KEYS = [
    "uris",
    "contributors",
    "providerUpdatedDateTime",
    "description",
    "title",
    "freeToRead",
    "languages",
    "licenses",
    "publisher",
    "subjects",
    "tags",
    "sponsorships",
    "otherProperties",
    "shareProperties"
]

PLOS_API_KEY = None
HARVARD_DATAVERSE_API_KEY = None
<commit_msg>Add springer key to local-dist<commit_after>DEBUG = False

ELASTIC_TIMEOUT = 10
ELASTIC_INDEX = 'share_v2'
ELASTIC_URI = 'localhost:9200'

BROKER_URL = 'amqp://guest@localhost'

CELERY_EAGER_PROPAGATES_EXCEPTIONS = True

RECORD_HTTP_TRANSACTIONS = False

NORMALIZED_PROCESSING = []
RAW_PROCESSING = []

SENTRY_DSN = None

USE_FLUENTD = False
FLUENTD_ARGS = {
    'tag': 'app.scrapi'
}

disabled = []

CASSANDRA_URI = ['127.0.0.1']
CASSANDRA_KEYSPACE = 'scrapi'

FRONTEND_KEYS = [
    "uris",
    "contributors",
    "providerUpdatedDateTime",
    "description",
    "title",
    "freeToRead",
    "languages",
    "licenses",
    "publisher",
    "subjects",
    "tags",
    "sponsorships",
    "otherProperties",
    "shareProperties"
]

PLOS_API_KEY = None
HARVARD_DATAVERSE_API_KEY = None
SPRINGER_KEY = None
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
#
# Copyright (c) 2017 Thomas Fillon <thomas@parisson.com>

# This file is part of TimeSide.

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Author: Thomas Fillon <thomas@parisson.com>

from timeside.core import implements, interfacedoc
from timeside.core.api import IAnalyzer
from timeside.core.tools.parameters import HasTraits
from timeside.core.tools.parameters import store_parameters

import vamp
import vampyhost
from .vampyhost_wrapper import VampAnalyzer

import numpy as np

class VampSpectralSlope(VampAnalyzer):
    """Extract the spectral slope of an audio spectrum"""

    implements(IAnalyzer)

    class _Param(HasTraits):
        pass

    _schema = {'$schema': 'http://json-schema.org/schema#',
               'properties': {},
               'type': 'object'}

    @store_parameters
    def __init__(self):
        super(VampSpectralSlope, self).__init__()
        self.input_blocksize = 1024
        self.input_stepsize = self.input_blocksize
        # Define Vamp plugin key and output
        self.plugin_key = 'vamp-libxtract:spectral_slope'
        self.plugin_output = 'spectral_slope'

    @interfacedoc
    def setup(self, channels=None, samplerate=None,
              blocksize=None, totalframes=None):
        super(VampSpectralSlope, self).setup(
            channels, samplerate, blocksize, totalframes)

    @staticmethod
    @interfacedoc
    def id():
        return "vamp_spectral_slope"

    @staticmethod
    @interfacedoc
    def name():
        return "Spectral slope (vamp)"

    @staticmethod
    @interfacedoc
    def version():
        return "1.0.0"

    @staticmethod
    @interfacedoc
    def unit():
        return ""

    def post_process(self):
        super(VampSpectralSlope, self).post_process()  # get remaining results

        result = self.new_result(data_mode='value', time_mode='framewise')
        result.data_object.value = self.vamp_results['vector'][1]
        result.data_object.y_value = self.vamp_results['vector'][0]
        self.add_result(result)
<commit_msg>[analyzers] remove scalar from VampSpectralSlope output (see #279)<commit_after># -*- coding: utf-8 -*-
#
# Copyright (c) 2017 Thomas Fillon <thomas@parisson.com>

# This file is part of TimeSide.

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Author: Thomas Fillon <thomas@parisson.com>

from timeside.core import implements, interfacedoc
from timeside.core.api import IAnalyzer
from timeside.core.tools.parameters import HasTraits
from timeside.core.tools.parameters import store_parameters

import vamp
import vampyhost
from .vampyhost_wrapper import VampAnalyzer

import numpy as np

class VampSpectralSlope(VampAnalyzer):
    """Extract the spectral slope of an audio spectrum"""

    implements(IAnalyzer)

    class _Param(HasTraits):
        pass

    _schema = {'$schema': 'http://json-schema.org/schema#',
               'properties': {},
               'type': 'object'}

    @store_parameters
    def __init__(self):
        super(VampSpectralSlope, self).__init__()
        self.input_blocksize = 1024
        self.input_stepsize = self.input_blocksize
        # Define Vamp plugin key and output
        self.plugin_key = 'vamp-libxtract:spectral_slope'
        self.plugin_output = 'spectral_slope'

    @interfacedoc
    def setup(self, channels=None, samplerate=None,
              blocksize=None, totalframes=None):
        super(VampSpectralSlope, self).setup(
            channels, samplerate, blocksize, totalframes)

    @staticmethod
    @interfacedoc
    def id():
        return "vamp_spectral_slope"

    @staticmethod
    @interfacedoc
    def name():
        return "Spectral slope (vamp)"

    @staticmethod
    @interfacedoc
    def version():
        return "1.0.0"

    @staticmethod
    @interfacedoc
    def unit():
        return ""

    def post_process(self):
        super(VampSpectralSlope, self).post_process()  # get remaining results

        result = self.new_result(data_mode='value', time_mode='framewise')
        result.data_object.value = self.vamp_results['vector'][1]
        self.add_result(result)
<|endoftext|>


<commit_before>import os
import re
import zipfile

current_path = os.path.dirname(os.path.abspath(__file__))

out_zip_name = os.path.join(current_path, "..",
                            os.path.basename(current_path) + ".esriaddin")

backup_patterns = {
    'PLUGIN_BACKUP_PATTERN': re.compile(".*_addin_[0-9]+[.]py$", re.IGNORECASE),
    'VIM_SWAP_PATTERN': re.compile(".*_addin*.py.swp$", re.IGNORECASE)
}

def looks_like_a_backup(filename):
    is_backup = False
    for name, pattern in backup_patterns.items():
        if bool(pattern.match(filename)):
            is_backup = True
    return is_backup

zip_file = zipfile.ZipFile(out_zip_name, 'w')
for filename in ('config.xml', 'README.md', 'makeaddin.py'):
    zip_file.write(os.path.join(current_path, filename), filename)
dirs_to_add = ['Images', 'Install']
for directory in dirs_to_add:
    for (path, dirs, files) in os.walk(os.path.join(current_path, directory)):
        archive_path = os.path.relpath(path, current_path)
        found_file = False
        for file in (f for f in files if not looks_like_a_backup(f)):
            archive_file = os.path.join(archive_path, file)
            print archive_file
            zip_file.write(os.path.join(path, file), archive_file)
            found_file = True
        if not found_file:
            zip_file.writestr(os.path.join(archive_path, 'placeholder.txt'),
                              "(Empty directory)")
zip_file.close()
<commit_msg>more robust exclusions for building files in plugin.<commit_after>import os
import re
import zipfile

current_path = os.path.dirname(os.path.abspath(__file__))

out_zip_name = os.path.join(current_path, "..",
                            os.path.basename(current_path) + ".esriaddin")

backup_patterns = {
    'PLUGIN_BACKUP_PATTERN': re.compile(".*_addin_[0-9]+[.]py$", re.IGNORECASE),
    'VIM_SWAP_PATTERN': re.compile(".*\.sw[op]$", re.IGNORECASE),
    'COMPLIED_PYTHON_PATTERN': re.compile(".*\.pyc$", re.IGNORECASE),
    'TODO_PATTERN': re.compile('todo.txt')
}

def looks_like_a_backup(filename):
    is_backup = False
    for name, pattern in backup_patterns.items():
        if bool(pattern.match(filename)):
            is_backup = True
    return is_backup

zip_file = zipfile.ZipFile(out_zip_name, 'w')
for filename in ('config.xml', 'README.md', 'makeaddin.py'):
    zip_file.write(os.path.join(current_path, filename), filename)
dirs_to_add = ['Images', 'Install']
for directory in dirs_to_add:
    for (path, dirs, files) in os.walk(os.path.join(current_path, directory)):
        archive_path = os.path.relpath(path, current_path)
        found_file = False
        for file in (f for f in files if not looks_like_a_backup(f)):
            archive_file = os.path.join(archive_path, file)
            print archive_file
            zip_file.write(os.path.join(path, file), archive_file)
            found_file = True
        if not found_file:
            zip_file.writestr(os.path.join(archive_path, 'placeholder.txt'),
                              "(Empty directory)")
zip_file.close()
<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of sbpipe.
#
# sbpipe is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# sbpipe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with sbpipe.  If not, see <http://www.gnu.org/licenses/>.
#
#
#
# $Revision: 3.0 $
# $Author: Piero Dalle Pezze $
# $Date: 2016-11-01 15:43:32 $

import os
import sys
import argparse
import logging
logger = logging.getLogger('sbpipe')

SBPIPE = os.environ["SBPIPE"]
sys.path.insert(0, SBPIPE)

from sbpipe.tasks.utils import call_proc

def ps1_analyse_data(model_name, scanned_par, inhibition_only, outputdir,
        sim_data_folder, sim_plots_folder, repeat, percent_levels, min_level,
        max_level, levels_number, homogeneous_lines, xaxis_label, yaxis_label):
    """
    Plot model single parameter scan time courses (Python wrapper).

    :param model_name: the model name without extension
    :param scanned_par: the model variable to scan
    :param inhibition_only: true if the scanning only decreases the variable amount (inhibition only)
    :param outputdir: the output directory
    :param sim_data_folder: the name of the folder containing the simulated data
    :param sim_plots_folder: the name of the folder containing the simulated plots
    :param repeat: the simulation number
    :param percent_levels: true if scanning levels are in percent
    :param min_level: the minimum level
    :param max_level: the maximum level
    :param levels_number: the number of levels
    :param homogeneous_lines: true if lines should be plotted homogeneously
    :param xaxis_label: the label for the x axis (e.g. Time [min])
    :param yaxis_label: the label for the y axis (e.g. Level [a.u.])
    """

    command = 'Rscript --vanilla ' + os.path.join(SBPIPE, 'sbpipe', 'R', 'sbpipe_ps1_main.r') + \
        ' ' + model_name + ' ' + scanned_par + ' ' + inhibition_only + ' ' + outputdir + \
        ' ' + sim_data_folder + ' ' + sim_plots_folder + ' ' + repeat + ' ' + percent_levels + ' ' + min_level + \
        ' ' + max_level + ' ' + levels_number + ' ' + homogeneous_lines + ' ' + xaxis_label + ' ' + yaxis_label
    call_proc(command)

# this is a Python wrapper for ps1 analysis in R.
def main(argv=None):
    parser = argparse.ArgumentParser()
    parser.add_argument('-m', '--model')
    parser.add_argument('--scanned-par')
    parser.add_argument('--inhibition-only')
    parser.add_argument('--outputdir')
    parser.add_argument('--sim-data-folder')
    parser.add_argument('--sim-plot-folder')
    parser.add_argument('--repeat', type=int, nargs='+')
    parser.add_argument('--percent-levels')
    parser.add_argument('--min-level')
    parser.add_argument('--max-level')
    parser.add_argument('--levels-number')
    parser.add_argument('--homogeneous-lines')
    parser.add_argument('--xaxis-label')
    parser.add_argument('--yaxis-label')

    args = parser.parse_args()
    ps1_analyse_data(args.model, args.scanned_par, args.inhibition_only, args.outputdir, args.sim_data_folder, \
        args.sim_plot_folder, args.repeat, args.percent_levels, args.min_level, args.max_level, args.levels_number, \
        args.homogeneous_lines, args.xaxis_label, args.yaxis_label)
    return 0

if __name__ == "__main__":
    sys.exit(main())
<commit_msg>Escape x/y labels.<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of sbpipe.
#
# sbpipe is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# sbpipe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with sbpipe.  If not, see <http://www.gnu.org/licenses/>.
#
#
#
# $Revision: 3.0 $
# $Author: Piero Dalle Pezze $
# $Date: 2016-11-01 15:43:32 $

import os
import sys
import argparse
import logging
logger = logging.getLogger('sbpipe')

SBPIPE = os.environ["SBPIPE"]
sys.path.insert(0, SBPIPE)

from sbpipe.utils.re_utils import escape_special_chars
from sbpipe.tasks.utils import call_proc

def ps1_analyse_data(model_name, scanned_par, inhibition_only, outputdir,
        sim_data_folder, sim_plots_folder, repeat, percent_levels, min_level,
        max_level, levels_number, homogeneous_lines, xaxis_label, yaxis_label):
    """
    Plot model single parameter scan time courses (Python wrapper).

    :param model_name: the model name without extension
    :param scanned_par: the model variable to scan
    :param inhibition_only: true if the scanning only decreases the variable amount (inhibition only)
    :param outputdir: the output directory
    :param sim_data_folder: the name of the folder containing the simulated data
    :param sim_plots_folder: the name of the folder containing the simulated plots
    :param repeat: the simulation number
    :param percent_levels: true if scanning levels are in percent
    :param min_level: the minimum level
    :param max_level: the maximum level
    :param levels_number: the number of levels
    :param homogeneous_lines: true if lines should be plotted homogeneously
    :param xaxis_label: the label for the x axis (e.g. Time [min])
    :param yaxis_label: the label for the y axis (e.g. Level [a.u.])
    """
    # We do this to make sure that characters like [ or ] don't cause troubles.
    xaxis_label = escape_special_chars(xaxis_label)
    yaxis_label = escape_special_chars(yaxis_label)

    command = 'Rscript --vanilla ' + os.path.join(SBPIPE, 'sbpipe', 'R', 'sbpipe_ps1_main.r') + \
        ' ' + model_name + ' ' + scanned_par + ' ' + inhibition_only + ' ' + outputdir + \
        ' ' + sim_data_folder + ' ' + sim_plots_folder + ' ' + repeat + ' ' + percent_levels + ' ' + min_level + \
        ' ' + max_level + ' ' + levels_number + ' ' + homogeneous_lines + ' ' + xaxis_label + ' ' + yaxis_label
    call_proc(command)

# this is a Python wrapper for ps1 analysis in R.
def main(argv=None):
    parser = argparse.ArgumentParser()
    parser.add_argument('-m', '--model')
    parser.add_argument('--scanned-par')
    parser.add_argument('--inhibition-only')
    parser.add_argument('--outputdir')
    parser.add_argument('--sim-data-folder')
    parser.add_argument('--sim-plot-folder')
    parser.add_argument('--repeat', type=int, nargs='+')
    parser.add_argument('--percent-levels')
    parser.add_argument('--min-level')
    parser.add_argument('--max-level')
    parser.add_argument('--levels-number')
    parser.add_argument('--homogeneous-lines')
    parser.add_argument('--xaxis-label')
    parser.add_argument('--yaxis-label')

    args = parser.parse_args()
    ps1_analyse_data(args.model, args.scanned_par, args.inhibition_only, args.outputdir, args.sim_data_folder, \
        args.sim_plot_folder, args.repeat, args.percent_levels, args.min_level, args.max_level, args.levels_number, \
        args.homogeneous_lines, args.xaxis_label, args.yaxis_label)
    return 0

if __name__ == "__main__":
    sys.exit(main())
<|endoftext|>


<commit_before>from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame
from random import randrange
black = Color(0x000000, 1.0)
blue = Color(0x2D9FC2,1.0)
white = Color(0xFFFFFF, 1.0)
red = Color(0xFC5D5D,1.0)
thinline = LineStyle(1, black)
celld = 35
rectangle3 = RectangleAsset(celld, celld, thinline, red)
rectangle = RectangleAsset(celld, celld, thinline, blue)
rectangle2 = RectangleAsset(celld, celld, thinline, white)
rectangle4 = RectangleAsset(celld, celld, thinline, black)
ocean = {}
oceanself = {}
enemyBoats = {}
selfBoats = {}
enemyboatsalive = {}
length = 5
height = 10
width = 10

class cell(Sprite):
    def __init__(self, asset, position):
        super().__init__(asset, position)
        self.visible = False

class enemyships(Sprite):
    def __init__(self, asset, position):
        super().__init__(asset, position)
        self.visible = False

for x in range(0, height):
    for y in range(0, width):
        #screen one set up
        Sprite(rectangle2, (x*celld, y*celld))
        enemyBoats[(x,y)] = enemyships(rectangle3, (x*celld, y*celld))
        ocean[(x,y)] = cell(rectangle, (x*celld, y*celld))
        #screen two set up
        yshift = height*celld + 20
        Sprite(rectangle2, (x*celld, y*celld + yshift))
        oceanself[(x,y)] = cell(rectangle, (x*celld, y*celld + yshift))
        #selfBoats[(x,y)] = cell(rectangle3, (x*celld, y*celld + yshift))

for a in range(0, 3):
    randx = randrange(1, 10)
    randy = randrange(1, 10)
    if randx > 5:
        nsx = -1
    else:
        nsx = 1
    if randy > 5:
        nsy = -1
    else:
        nsy = 1
    randxy = randrange(1, 3)
    for u in range(0, length-1):
        enemyBoats[(randx+nsx,randy+nsy)].visible = True
        enemyboatsalive
        if randxy == 2:
            randx = randx + 1
        else:
            randy = randy + 1
    length = length - 1

class Battleship(App):

    def __init__(self):
        #Battleship.listenKeyEvent("keydown", "space", self.spaceclick)
        SCREEN_WIDTH = 1000
        SCREEN_HEIGHT = 1000
        self.going = False
        super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT)
        Battleship.listenMouseEvent("click",self.breathlife)

    def breathlife(self, event):
        self.cx = int(event.x/celld)
        self.cy = int(event.y/celld)
        ocean[(self.cx, self.cy)].visible = False

myapp = Battleship()
myapp.run()

"""
from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame

black = Color(0x000000, 1.0)
green = Color(0x00ff00, 1.0)
orange = Color(0xFF8400,1.0)
thinline = LineStyle(1, black)
a = 0
b = 0
height = 20
width = 20
ocean = {}
thinline = LineStyle(1, black)
rectangle = RectangleAsset(20, 20, thinline, green)
rectangle2 = RectangleAsset(20, 20, thinline, orange)

class cell(Sprite):
    def __init__(self, asset, position):
        super().__init__(asset, position)
        self.visible = False
        self.sca = 0

for x in range(0, height):
            for y in range(0, width):
                Sprite(rectangle2, (x*height, y*width))
                ocean[(x,y)] = cell(rectangle, (x*height, y*width))

class ConwayGame(App):

    def __init__(self):
        ConwayGame.listenKeyEvent("keydown", "space", self.spaceclick)
        SCREEN_WIDTH = 640
        SCREEN_HEIGHT = 480
        self.going = False
        super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT)
        ConwayGame.listenMouseEvent("click",self.breathlife)

    def breathlife(self, event):
        self.cx = int(event.x/20)
        self.cy = int(event.y/20)
        ocean[(self.cx, self.cy)].visible = not ocean[(self.cx, self.cy)].visible

    def spaceclick(self,event):
        self.going = not self.going

    def step(self):
        if self.going == True:
            for g in range(0, height):
                for f in range(0, width):
                    if ocean[(g,f)].visible == True:
                                ocean[(g,f)].sca = ocean[(g,f)].sca - 1
                    for w in range(-1, 2):
                        for h in range(-1, 2):
                            if (w+g, h+f) in ocean and ocean[(w+g, h+f)].visible == True:
                                ocean[(g,f)].sca = ocean[(g,f)].sca + 1

            for s in range(0, height):
                for d in range(0, width):
                    if ocean[(s, d)].visible == True and ocean[(s, d)].sca < 2:
                        ocean[(s, d)].visible = False
                    elif ocean[(s, d)].visible == True and ocean[(s, d)].sca > 3:
                        ocean[(s, d)].visible = False
                    elif ocean[(s, d)].visible == False and ocean[(s, d)].sca == 3:
                        ocean[(s, d)].visible = True
                    ocean[(s,d)].sca = 0
myapp = ConwayGame()
myapp.run()
"""<commit_msg>Updated from Brython Server: May 16, 2016 2:36:10 PM EDT<commit_after>from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame
from random import randrange
black = Color(0x000000, 1.0)
blue = Color(0x2D9FC2,1.0)
white = Color(0xFFFFFF, 1.0)
red = Color(0xFC5D5D,1.0)
thinline = LineStyle(1, black)
celld = 35
rectangle3 = RectangleAsset(celld, celld, thinline, red)
rectangle = RectangleAsset(celld, celld, thinline, blue)
rectangle2 = RectangleAsset(celld, celld, thinline, white)
rectangle4 = RectangleAsset(celld, celld, thinline, black)
ocean = {}
oceanself = {}
enemyBoats = {}
selfBoats = {}
enemyboatsalive = {}
length = 5
height = 10
width = 10

class cell(Sprite):
    def __init__(self, asset, position):
        super().__init__(asset, position)
        self.visible = True

class enemyships(Sprite):
    def __init__(self, asset, position):
        super().__init__(asset, position)
        self.visible = False

for x in range(0, height):
    for y in range(0, width):
        #screen one set up
        Sprite(rectangle2, (x*celld, y*celld))
        enemyBoats[(x,y)] = enemyships(rectangle3, (x*celld, y*celld))
        ocean[(x,y)] = cell(rectangle, (x*celld, y*celld))
        #screen two set up
        yshift = height*celld + 20
        Sprite(rectangle2, (x*celld, y*celld + yshift))
        oceanself[(x,y)] = cell(rectangle, (x*celld, y*celld + yshift))
        #selfBoats[(x,y)] = cell(rectangle3, (x*celld, y*celld + yshift))

for a in range(0, 3):
    randx = randrange(1, 10)
    randy = randrange(1, 10)
    if randx > 5:
        nsx = -1
    else:
        nsx = 1
    if randy > 5:
        nsy = -1
    else:
        nsy = 1
    randxy = randrange(1, 3)
    for u in range(0, length-1):
        enemyBoats[(randx+nsx,randy+nsy)].visible = True
        enemyboatsalive
        if randxy == 2:
            randx = randx + 1
        else:
            randy = randy + 1
    length = length - 1

class Battleship(App):

    def __init__(self):
        #Battleship.listenKeyEvent("keydown", "space", self.spaceclick)
        SCREEN_WIDTH = 1000
        SCREEN_HEIGHT = 1000
        self.going = False
        super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT)
        Battleship.listenMouseEvent("click",self.breathlife)

    def breathlife(self, event):
        self.cx = int(event.x/celld)
        self.cy = int(event.y/celld)
        ocean[(self.cx, self.cy)].visible = False

myapp = Battleship()
myapp.run()

"""
from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame

black = Color(0x000000, 1.0)
green = Color(0x00ff00, 1.0)
orange = Color(0xFF8400,1.0)
thinline = LineStyle(1, black)
a = 0
b = 0
height = 20
width = 20
ocean = {}
thinline = LineStyle(1, black)
rectangle = RectangleAsset(20, 20, thinline, green)
rectangle2 = RectangleAsset(20, 20, thinline, orange)

class cell(Sprite):
    def __init__(self, asset, position):
        super().__init__(asset, position)
        self.visible = False
        self.sca = 0

for x in range(0, height):
            for y in range(0, width):
                Sprite(rectangle2, (x*height, y*width))
                ocean[(x,y)] = cell(rectangle, (x*height, y*width))

class ConwayGame(App):

    def __init__(self):
        ConwayGame.listenKeyEvent("keydown", "space", self.spaceclick)
        SCREEN_WIDTH = 640
        SCREEN_HEIGHT = 480
        self.going = False
        super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT)
        ConwayGame.listenMouseEvent("click",self.breathlife)

    def breathlife(self, event):
        self.cx = int(event.x/20)
        self.cy = int(event.y/20)
        ocean[(self.cx, self.cy)].visible = not ocean[(self.cx, self.cy)].visible

    def spaceclick(self,event):
        self.going = not self.going

    def step(self):
        if self.going == True:
            for g in range(0, height):
                for f in range(0, width):
                    if ocean[(g,f)].visible == True:
                                ocean[(g,f)].sca = ocean[(g,f)].sca - 1
                    for w in range(-1, 2):
                        for h in range(-1, 2):
                            if (w+g, h+f) in ocean and ocean[(w+g, h+f)].visible == True:
                                ocean[(g,f)].sca = ocean[(g,f)].sca + 1

            for s in range(0, height):
                for d in range(0, width):
                    if ocean[(s, d)].visible == True and ocean[(s, d)].sca < 2:
                        ocean[(s, d)].visible = False
                    elif ocean[(s, d)].visible == True and ocean[(s, d)].sca > 3:
                        ocean[(s, d)].visible = False
                    elif ocean[(s, d)].visible == False and ocean[(s, d)].sca == 3:
                        ocean[(s, d)].visible = True
                    ocean[(s,d)].sca = 0
myapp = ConwayGame()
myapp.run()
"""<|endoftext|>


<commit_before>from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame
from random import randrange
black = Color(0x000000, 1.0)
blue = Color(0x2D9FC2,1.0)
white = Color(0xFFFFFF, 1.0)
red = Color(0xFC5D5D,1.0)
thinline = LineStyle(1, black)
celld = 35
rectangle3 = RectangleAsset(celld, celld, thinline, red)
rectangle = RectangleAsset(celld, celld, thinline, white)
rectangle2 = RectangleAsset(celld, celld, thinline, blue)
rectangle4 = RectangleAsset(celld, celld, thinline, black)
ocean = {}
oceanself = {}
enemyBoats = {}
selfBoats = {}
length = 5
height = 10
width = 10

class cell(Sprite):
    def __init__(self, asset, position):
        super().__init__(asset, position)
        self.visible = False
        self.sca = 0

for x in range(0, height):
    for y in range(0, width):
        #screen one set up
        enemyBoats[(x,y)] = cell(rectangle3, (x*celld, y*celld))
        Sprite(rectangle2, (x*celld, y*celld))
        ocean[(x,y)] = cell(rectangle, (x*celld, y*celld))
        #screen two set up
        Sprite(rectangle2, (x*celld, y*celld + height*celld + 20))
        oceanself[(x,y)] = cell(rectangle, (x*celld, y*celld))
        selfBoats[(x,y)] = cell(rectangle3, (x*celld, y*celld))

for a in range(0, 4):
    c = randrange(1, 10)
    d = randrange(1, 10)
    for u in range(0, length):
        enemyBoats[(c,d)].visible = True
        c = c+1
        d = d+1
    length = length - 1

class Battleship(App):

    def __init__(self):
        #Battleship.listenKeyEvent("keydown", "space", self.spaceclick)
        SCREEN_WIDTH = 1000
        SCREEN_HEIGHT = 1000
        self.going = False
        super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT)
        Battleship.listenMouseEvent("click",self.breathlife)

    def breathlife(self, event):
        self.cx = int(event.x/celld)
        self.cy = int(event.y/celld)
        ocean[(self.cx, self.cy)].visible = not ocean[(self.cx, self.cy)].visible

myapp = Battleship()
myapp.run()

"""
from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame

black = Color(0x000000, 1.0)
green = Color(0x00ff00, 1.0)
orange = Color(0xFF8400,1.0)
thinline = LineStyle(1, black)
a = 0
b = 0
height = 20
width = 20
ocean = {}
thinline = LineStyle(1, black)
rectangle = RectangleAsset(20, 20, thinline, green)
rectangle2 = RectangleAsset(20, 20, thinline, orange)

class cell(Sprite):
    def __init__(self, asset, position):
        super().__init__(asset, position)
        self.visible = False
        self.sca = 0

for x in range(0, height):
            for y in range(0, width):
                Sprite(rectangle2, (x*height, y*width))
                ocean[(x,y)] = cell(rectangle, (x*height, y*width))

class ConwayGame(App):

    def __init__(self):
        ConwayGame.listenKeyEvent("keydown", "space", self.spaceclick)
        SCREEN_WIDTH = 640
        SCREEN_HEIGHT = 480
        self.going = False
        super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT)
        ConwayGame.listenMouseEvent("click",self.breathlife)

    def breathlife(self, event):
        self.cx = int(event.x/20)
        self.cy = int(event.y/20)
        ocean[(self.cx, self.cy)].visible = not ocean[(self.cx, self.cy)].visible

    def spaceclick(self,event):
        self.going = not self.going

    def step(self):
        if self.going == True:
            for g in range(0, height):
                for f in range(0, width):
                    if ocean[(g,f)].visible == True:
                                ocean[(g,f)].sca = ocean[(g,f)].sca - 1
                    for w in range(-1, 2):
                        for h in range(-1, 2):
                            if (w+g, h+f) in ocean and ocean[(w+g, h+f)].visible == True:
                                ocean[(g,f)].sca = ocean[(g,f)].sca + 1

            for s in range(0, height):
                for d in range(0, width):
                    if ocean[(s, d)].visible == True and ocean[(s, d)].sca < 2:
                        ocean[(s, d)].visible = False
                    elif ocean[(s, d)].visible == True and ocean[(s, d)].sca > 3:
                        ocean[(s, d)].visible = False
                    elif ocean[(s, d)].visible == False and ocean[(s, d)].sca == 3:
                        ocean[(s, d)].visible = True
                    ocean[(s,d)].sca = 0
myapp = ConwayGame()
myapp.run()
"""<commit_msg>Updated from Brython Server: May 11, 2016 1:29:40 PM EDT<commit_after>from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame
from random import randrange
black = Color(0x000000, 1.0)
blue = Color(0x2D9FC2,1.0)
white = Color(0xFFFFFF, 1.0)
red = Color(0xFC5D5D,1.0)
thinline = LineStyle(1, black)
celld = 35
rectangle3 = RectangleAsset(celld, celld, thinline, red)
rectangle = RectangleAsset(celld, celld, thinline, white)
rectangle2 = RectangleAsset(celld, celld, thinline, blue)
rectangle4 = RectangleAsset(celld, celld, thinline, black)
ocean = {}
oceanself = {}
enemyBoats = {}
selfBoats = {}
length = 5
height = 10
width = 10

class cell(Sprite):
    def __init__(self, asset, position):
        super().__init__(asset, position)
        self.visible = False
        self.sca = 0

for x in range(0, height):
    for y in range(0, width):
        #screen one set up
        enemyBoats[(x,y)] = cell(rectangle3, (x*celld, y*celld))
        Sprite(rectangle2, (x*celld, y*celld))
        ocean[(x,y)] = cell(rectangle, (x*celld, y*celld))
        #screen two set up
        Sprite(rectangle2, (x*celld, y*celld + height*celld + 20))
        oceanself[(x,y)] = cell(rectangle, (x*celld, y*celld))
        selfBoats[(x,y)] = cell(rectangle3, (x*celld, y*celld))

for a in range(0, 4):
    c = randrange(1, 10)
    d = randrange(1, 10)
    for u in range(0, length):
        enemyBoats[(c,d)].visible = not enemyBoats[(c,d)].visible
        c = c+1
        d = d+1
    length = length - 1

class Battleship(App):

    def __init__(self):
        #Battleship.listenKeyEvent("keydown", "space", self.spaceclick)
        SCREEN_WIDTH = 1000
        SCREEN_HEIGHT = 1000
        self.going = False
        super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT)
        Battleship.listenMouseEvent("click",self.breathlife)

    def breathlife(self, event):
        self.cx = int(event.x/celld)
        self.cy = int(event.y/celld)
        ocean[(self.cx, self.cy)].visible = not ocean[(self.cx, self.cy)].visible

myapp = Battleship()
myapp.run()

"""
from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame

black = Color(0x000000, 1.0)
green = Color(0x00ff00, 1.0)
orange = Color(0xFF8400,1.0)
thinline = LineStyle(1, black)
a = 0
b = 0
height = 20
width = 20
ocean = {}
thinline = LineStyle(1, black)
rectangle = RectangleAsset(20, 20, thinline, green)
rectangle2 = RectangleAsset(20, 20, thinline, orange)

class cell(Sprite):
    def __init__(self, asset, position):
        super().__init__(asset, position)
        self.visible = False
        self.sca = 0

for x in range(0, height):
            for y in range(0, width):
                Sprite(rectangle2, (x*height, y*width))
                ocean[(x,y)] = cell(rectangle, (x*height, y*width))

class ConwayGame(App):

    def __init__(self):
        ConwayGame.listenKeyEvent("keydown", "space", self.spaceclick)
        SCREEN_WIDTH = 640
        SCREEN_HEIGHT = 480
        self.going = False
        super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT)
        ConwayGame.listenMouseEvent("click",self.breathlife)

    def breathlife(self, event):
        self.cx = int(event.x/20)
        self.cy = int(event.y/20)
        ocean[(self.cx, self.cy)].visible = not ocean[(self.cx, self.cy)].visible

    def spaceclick(self,event):
        self.going = not self.going

    def step(self):
        if self.going == True:
            for g in range(0, height):
                for f in range(0, width):
                    if ocean[(g,f)].visible == True:
                                ocean[(g,f)].sca = ocean[(g,f)].sca - 1
                    for w in range(-1, 2):
                        for h in range(-1, 2):
                            if (w+g, h+f) in ocean and ocean[(w+g, h+f)].visible == True:
                                ocean[(g,f)].sca = ocean[(g,f)].sca + 1

            for s in range(0, height):
                for d in range(0, width):
                    if ocean[(s, d)].visible == True and ocean[(s, d)].sca < 2:
                        ocean[(s, d)].visible = False
                    elif ocean[(s, d)].visible == True and ocean[(s, d)].sca > 3:
                        ocean[(s, d)].visible = False
                    elif ocean[(s, d)].visible == False and ocean[(s, d)].sca == 3:
                        ocean[(s, d)].visible = True
                    ocean[(s,d)].sca = 0
myapp = ConwayGame()
myapp.run()
"""<|endoftext|>


<commit_before>from django.db import models
from django.conf import settings
from incunafein.content import BaseFkeyContent

class ArticleFkeyContent(BaseFkeyContent):

    class Meta:
        abstract = True

    def template_hierarchy(self):
        return ['content/articles/category_%s.html' % self.category.slug,
                'content/articles/default.html',
               ]

class ArticleCalendarFkeyContent(BaseFkeyContent):

    class Meta:
        abstract = True

    @classmethod
    def initialize_type(cls):
        if cls.app_label not in settings.INSTALLED_APPS:
            raise ImproperlyConfigured, "You have to add '%s' to your INSTALLED_APPS before creating a %s" % (cls.app_label, cls.__name__)

        cls.add_to_class(cls.fkey_name or cls.object_name.lower(),
                         models.ForeignKey('%s.%s' % (cls.app_label, cls.object_name),
                                           related_name='%s_%s_set' % (cls._meta.app_label, cls._meta.module_name),
                                           limit_choices_to = {'calendar_feed__isnull': False}

        ))

    def template_hierarchy(self):
        return ['content/articles/calendar_%s.html' % self.category.slug,
                'content/articles/calendar.html',
               ]

<commit_msg>Fixed feed / id issue<commit_after>from django.db import models
from django.conf import settings
from incunafein.content import BaseFkeyContent

class ArticleFkeyContent(BaseFkeyContent):

    class Meta:
        abstract = True

    def template_hierarchy(self):
        return ['content/articles/category_%s.html' % self.category.slug,
                'content/articles/default.html',
               ]

class ArticleCalendarFkeyContent(BaseFkeyContent):

    class Meta:
        abstract = True

    @classmethod
    def initialize_type(cls):
        if cls.app_label not in settings.INSTALLED_APPS:
            raise ImproperlyConfigured, "You have to add '%s' to your INSTALLED_APPS before creating a %s" % (cls.app_label, cls.__name__)

        cls.add_to_class(cls.fkey_name or cls.object_name.lower(),
                         models.ForeignKey('%s.%s' % (cls.app_label, cls.object_name),
                                           related_name='%s_%s_set' % (cls._meta.app_label, cls._meta.module_name),
                                           limit_choices_to = {'calendar_id__isnull': False}

        ))

    def template_hierarchy(self):
        return ['content/articles/calendar_%s.html' % self.category.slug,
                'content/articles/calendar.html',
               ]

<|endoftext|>


<commit_before>import re

names = re.compile(r'(?:^|\s)(@\w+)')
droggelbecher = re.compile(
    r'[Dd].*r.*o.*g.*g.*e.*l.*b.*e.*c.*h.*e.*r.*').search

message = 'Droggelbecher? ... Droggelbecher!\n\nhttps://youtu.be/6V3eESJ66Nk'

def get_mentions(message):
    return {x.group(1) for x in names.finditer(message)}

def has_droggelbecher(bot_stuff):
    if droggelbecher(bot_stuff['message']) is not None:
        bot_stuff['sendMessage'](chat_id=bot_stuff['chat_id'],
                                 text=message)
        return True
    return False
<commit_msg>ignore cases... much more fun!<commit_after>import re

names = re.compile(r'(?:^|\s)(@\w+)')
droggelbecher = re.compile(
    r'd.*r.*o.*g.*g.*e.*l.*b.*e.*c.*h.*e.*r.*', flags=re.IGNORECASE).search

message = 'Droggelbecher? ... Droggelbecher!\n\nhttps://youtu.be/6V3eESJ66Nk'

def get_mentions(message):
    return {x.group(1) for x in names.finditer(message)}

def has_droggelbecher(bot_stuff):
    if droggelbecher(bot_stuff['message']) is not None:
        bot_stuff['sendMessage'](chat_id=bot_stuff['chat_id'],
                                 text=message)
        return True
    return False
<|endoftext|>


<commit_before>#!/usr/bin/env python3
"""Minecraft IRC bot.

Usage:
  wurstminebot [options] [start | stop | restart | status]
  wurstminebot -h | --help
  wurstminebot --version

Options:
  -h, --help         Print this message and exit.
  --config=<config>  Path to the config file [default: /opt/wurstmineberg/config/wurstminebot.json].
  --version          Print version info and exit.
"""
import sys

sys.path.append('/opt/py')

from wurstminebot import core
import daemon
import daemon.pidlockfile
from docopt import docopt
from wurstminebot import loops
import os
import pwd
import signal

__version__ = core.__version__

def newDaemonContext(pidfilename):
    if not os.geteuid() == 0:
        sys.exit('[!!!!] Only root can start/stop the daemon!')
    pidfile = daemon.pidlockfile.PIDLockFile(pidfilename)
    logfile = open('/opt/wurstmineberg/log/wurstminebot.log', 'a')
    wurstmineberg_user = pwd.getpwnam('wurstmineberg')
    daemoncontext = daemon.DaemonContext(working_directory='/opt/wurstmineberg/', pidfile=pidfile, uid=wurstmineberg_user.pw_uid, gid=wurstmineberg_user.pw_gid, stdout=logfile, stderr=logfile)
    daemoncontext.files_preserve = [logfile]
    daemoncontext.signal_map = {
        signal.SIGTERM: core.cleanup,
        signal.SIGHUP: core.cleanup
    }
    return daemoncontext

def start(context):
    print('[....] Starting wurstminebot version', __version__, end='\r')
    if core.status(context.pidfile):
        print('[FAIL]')
        print('[ !! ] Wurstminebot is already running!')
        return
    else:
        print('[ ok ]')
        # Removes the PID file
        stop(context)
    print('[....] Daemonizing', end='\r')
    with context:
        print('[ ok ]')
        core.run()
        print('[ ** ] Terminating')

def stop(context):
    core.cleanup()
    if core.status(context.pidfile):
        print('[....] Stopping the service', end='\r')
        if context.is_open:
            context.close()
        else:
            # We don't seem to be able to stop the context so we just kill the bot
            os.kill(context.pidfile.read_pid(), signal.SIGKILL)
        try:
            context.pidfile.release()
        except lockfile.NotMyLock:
            context.pidfile.break_lock()
    if context.pidfile.is_locked():
        print('[FAIL]')
        print('[....] Service did not shutdown correctly. Cleaning up', end='\r')
        context.pidfile.break_lock()
        print('[ ok ]')
    else:
        print('[ ok ]')

if __name__ == '__main__':
    arguments = docopt(__doc__, version='wurstminebot ' + __version__)
    core.state['config_path'] = arguments['--config']
    pidfilename = "/var/run/wurstmineberg/wurstminebot.pid"
    if arguments['start']:
        context = newDaemonContext(pidfilename)
        start(context)
    elif arguments['stop']:
        context = newDaemonContext(pidfilename)
        stop(context)
    elif arguments['restart']:
        context = newDaemonContext(pidfilename)
        stop(context)
        start(context)
    elif arguments['status']:
        pidfile = daemon.pidlockfile.PIDLockFile(pidfilename)
        print('[info] wurstminebot ' + ('is' if core.status(pidfile) else 'is not') + ' running.')
    else:
        core.run()
<commit_msg>Add missing import<commit_after>#!/usr/bin/env python3
"""Minecraft IRC bot.

Usage:
  wurstminebot [options] [start | stop | restart | status]
  wurstminebot -h | --help
  wurstminebot --version

Options:
  -h, --help         Print this message and exit.
  --config=<config>  Path to the config file [default: /opt/wurstmineberg/config/wurstminebot.json].
  --version          Print version info and exit.
"""
import sys

sys.path.append('/opt/py')

from wurstminebot import core
import daemon
import daemon.pidlockfile
from docopt import docopt
import lockfile
from wurstminebot import loops
import os
import pwd
import signal

__version__ = core.__version__

def newDaemonContext(pidfilename):
    if not os.geteuid() == 0:
        sys.exit('[!!!!] Only root can start/stop the daemon!')
    pidfile = daemon.pidlockfile.PIDLockFile(pidfilename)
    logfile = open('/opt/wurstmineberg/log/wurstminebot.log', 'a')
    wurstmineberg_user = pwd.getpwnam('wurstmineberg')
    daemoncontext = daemon.DaemonContext(working_directory='/opt/wurstmineberg/', pidfile=pidfile, uid=wurstmineberg_user.pw_uid, gid=wurstmineberg_user.pw_gid, stdout=logfile, stderr=logfile)
    daemoncontext.files_preserve = [logfile]
    daemoncontext.signal_map = {
        signal.SIGTERM: core.cleanup,
        signal.SIGHUP: core.cleanup
    }
    return daemoncontext

def start(context):
    print('[....] Starting wurstminebot version', __version__, end='\r')
    if core.status(context.pidfile):
        print('[FAIL]')
        print('[ !! ] Wurstminebot is already running!')
        return
    else:
        print('[ ok ]')
        # Removes the PID file
        stop(context)
    print('[....] Daemonizing', end='\r')
    with context:
        print('[ ok ]')
        core.run()
        print('[ ** ] Terminating')

def stop(context):
    core.cleanup()
    if core.status(context.pidfile):
        print('[....] Stopping the service', end='\r')
        if context.is_open:
            context.close()
        else:
            # We don't seem to be able to stop the context so we just kill the bot
            os.kill(context.pidfile.read_pid(), signal.SIGKILL)
        try:
            context.pidfile.release()
        except lockfile.NotMyLock:
            context.pidfile.break_lock()
    if context.pidfile.is_locked():
        print('[FAIL]')
        print('[....] Service did not shutdown correctly. Cleaning up', end='\r')
        context.pidfile.break_lock()
        print('[ ok ]')
    else:
        print('[ ok ]')

if __name__ == '__main__':
    arguments = docopt(__doc__, version='wurstminebot ' + __version__)
    core.state['config_path'] = arguments['--config']
    pidfilename = "/var/run/wurstmineberg/wurstminebot.pid"
    if arguments['start']:
        context = newDaemonContext(pidfilename)
        start(context)
    elif arguments['stop']:
        context = newDaemonContext(pidfilename)
        stop(context)
    elif arguments['restart']:
        context = newDaemonContext(pidfilename)
        stop(context)
        start(context)
    elif arguments['status']:
        pidfile = daemon.pidlockfile.PIDLockFile(pidfilename)
        print('[info] wurstminebot ' + ('is' if core.status(pidfile) else 'is not') + ' running.')
    else:
        core.run()
<|endoftext|>