#!/usr/bin/env python
import collections
from setuptools import setup

from pip.req import parse_requirements

dependency_links = []
install_requires = []

ReqOpts = collections.namedtuple('ReqOpts', ['skip_requirements_regex', 'default_vcs'])

opts = ReqOpts(None, 'git')

for ir in parse_requirements("requirements.txt", options=opts):
    if ir is not None:
        if ir.url is not None:
            dependency_links.append(str(ir.url))
        if ir.req is not None:
            install_requires.append(str(ir.req))

setup(
    name='vertica-python',
    version='0.1',
    description='A native Python client for the Vertica database.',
    author='Justin Berka',
    author_email='justin@uber.com',
    url='https://github.com/uber/vertica-python/',
    keywords="database vertica",
    packages=['vertica_python'],
    license="MIT",
    install_requires=install_requires,
    dependency_links=dependency_links,
    classifiers = [
        "Development Status :: 3 - Alpha",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python",
        "Topic :: Database",
        "Topic :: Database :: Database Engines/Servers",
        "Operating System :: OS Independent"
    ]
)

#!/usr/bin/env python
import collections
from setuptools import setup

from pip.req import parse_requirements

dependency_links = []
install_requires = []

ReqOpts = collections.namedtuple('ReqOpts', ['skip_requirements_regex', 'default_vcs'])

opts = ReqOpts(None, 'git')

for ir in parse_requirements("requirements.txt", options=opts):
    if ir is not None:
        if ir.url is not None:
            dependency_links.append(str(ir.url))
        if ir.req is not None:
            install_requires.append(str(ir.req))

setup(
    name='vertica-python',
    version='0.1',
    description='A native Python client for the Vertica database.',
    author='Justin Berka',
    author_email='justin@uber.com',
    url='https://github.com/uber/vertica-python/',
    keywords="database vertica",
    packages=['vertica_python'],
    package_data={
        '': ['*.txt', '*.md'],
    },
    license="MIT",
    install_requires=install_requires,
    dependency_links=dependency_links,
    classifiers = [
        "Development Status :: 3 - Alpha",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python",
        "Topic :: Database",
        "Topic :: Database :: Database Engines/Servers",
        "Operating System :: OS Independent"
    ]
)

Add .md and .txt files to package

Add .md and .txt files to package


#!/usr/bin/env python

from distutils.core import setup

with open('README.rst') as file:
    long_description = file.read()

classifiers = [
    'Programming Language :: Python :: 3',
    'Development Status :: 5 - Production/Stable',
    'License :: OSI Approved',
    'Intended Audience :: Developers',
    'Natural Language :: French',
    'Operating System :: OS Independent',
    'Topic :: Utilities',
]

setup(name='PyEventEmitter',
      version='1.0.2',
      description='Simple python events library',
      long_description=long_description,
      author='Etienne Tissieres',
      author_email='etienne.tissieres@gmail.com',
      url='https://github.com/etissieres/PyEventEmitter',
      packages=['event_emitter'],
      license='MIT',
      classifiers=classifiers)

#!/usr/bin/env python

from distutils.core import setup

with open('README.rst') as file:
    long_description = file.read()

classifiers = [
    'Programming Language :: Python :: 3',
    'Development Status :: 5 - Production/Stable',
    'License :: OSI Approved',
    'Intended Audience :: Developers',
    'Natural Language :: French',
    'Operating System :: OS Independent',
    'Topic :: Utilities',
]

setup(name='PyEventEmitter',
      version='1.0.3',
      description='Simple python events library',
      long_description=long_description,
      author='Etienne Tissieres',
      author_email='etienne.tissieres@gmail.com',
      url='https://github.com/etissieres/PyEventEmitter',
      packages=['event_emitter'],
      license='MIT',
      classifiers=classifiers)

Upgrade version to publish a release without tests


# coding=utf-8
import os
from unittest import main

from _jb_runner_tools import jb_start_tests, jb_doc_args
from teamcity import unittestpy

if __name__ == '__main__':
    path, targets, additional_args = jb_start_tests()

    args = ["python -m unittest"]
    if path:
        discovery_args = ["discover", "-s"]
        # Unittest does not support script directly, but it can use "discover" to find all tests in some folder
        # filtering by script
        assert os.path.exists(path), "{0}: No such file or directory".format(path)
        if os.path.isfile(path):
            discovery_args += [os.path.dirname(path), "-p", os.path.basename(path)]
        else:
            discovery_args.append(path)
        additional_args = discovery_args + additional_args
    else:
        additional_args += targets
    args += additional_args
    jb_doc_args("unittests", args)
    main(argv=args, module=None, testRunner=unittestpy.TeamcityTestRunner())

# coding=utf-8
import os
from unittest import main

from _jb_runner_tools import jb_start_tests, jb_doc_args
from teamcity import unittestpy

if __name__ == '__main__':
    path, targets, additional_args = jb_start_tests()

    args = ["python -m unittest"]
    if path:
        discovery_args = ["discover", "-s"]
        # Unittest does not support script directly, but it can use "discover" to find all tests in some folder
        # filtering by script
        assert os.path.exists(path), "{0}: No such file or directory".format(path)
        if os.path.isfile(path):
            discovery_args += [os.path.dirname(path), "-p", os.path.basename(path)]
        else:
            discovery_args.append(path)
        additional_args = discovery_args + additional_args
    elif targets:
        additional_args += targets
    args += additional_args
    jb_doc_args("unittests", args)
    main(argv=args, module=None, testRunner=unittestpy.TeamcityTestRunner())

Check variable before accessing it

PY-22460: Check variable before accessing it


"""Download genome files from the NCBI"""
from .config import (
    SUPPORTED_TAXONOMIC_GROUPS,
    NgdConfig
)
from .core import (
    args_download,
    download,
    argument_parser,
)

__version__ = '0.2.10'
__all__ = [
    'download',
    'args_download',
    'SUPPORTED_TAXONOMIC_GROUPS',
    'NgdConfig',
    'argument_parser'
]

"""Download genome files from the NCBI"""
from .config import (
    SUPPORTED_TAXONOMIC_GROUPS,
    NgdConfig
)
from .core import (
    args_download,
    download,
    argument_parser,
)

__version__ = '0.2.11'
__all__ = [
    'download',
    'args_download',
    'SUPPORTED_TAXONOMIC_GROUPS',
    'NgdConfig',
    'argument_parser'
]

Bump version number to 0.2.11

Bump version number to 0.2.11

Signed-off-by: Kai Blin <ad3597797f6179d503c382b2627cc19939309418@biosustain.dtu.dk>


from setuptools import setup

setup(
    name='tephi',
    version='0.2.0-alpha',
    url='https://github.com/SciTools/tephi',
    author='Bill Little',
    author_email='bill.james.little@gmail.com',
    packages=['tephi', 'tephi.tests'],
    package_dir={'': 'lib'},
    package_data={'tephi': ['etc/test_data/*.txt'] + ['etc/test_results/*.pkl']},
    classifiers=['License :: OSI Approved :: '
                 'GNU Lesser General Public License v3 (LGPLv3)'],
    description='Tephigram plotting in Python',
    long_description=open('README.rst').read(),
    test_suite='tephi.tests',
)

from setuptools import setup

setup(
    name='tephi',
    version='0.2.0-alpha',
    url='https://github.com/SciTools/tephi',
    author='Bill Little',
    author_email='bill.james.little@gmail.com',
    packages=['tephi', 'tephi.tests'],
    package_dir={'': 'lib'},
    package_data={'tephi': ['etc/test_data/*.txt'] + ['etc/test_results/*.pkl']},
    classifiers=['License :: OSI Approved :: '
                 'GNU Lesser General Public License v3 (LGPLv3)',
                 'Programming Language :: Python',
                 'Programming Language :: Python :: 2',
                 'Programming Language :: Python :: 2.7',
                 'Programming Language :: Python :: 3',
                 'Programming Language :: Python :: 3.3',
                 'Programming Language :: Python :: 3.4',],
    description='Tephigram plotting in Python',
    long_description=open('README.rst').read(),
    test_suite='tephi.tests',
)

Add Python 2 and 3 PyPI classifiers.

Add Python 2 and 3 PyPI classifiers.


def get_price_without_vat(price_to_show, vat_percent):
    raise NotImplementedError()

def get_price_without_vat_from_other_valuta(conversion_rate, origin_price,
                                            origin_vat, other_vat):
    raise NotImplementedError()

def show_pretty_price(value):
    raise NotImplementedError()

Use function described in readme

Use function described in readme


import glob
import shutil
from optparse import OptionParser

from perfrunner.helpers.remote import RemoteHelper
from perfrunner.settings import ClusterSpec

def get_options():
    usage = '%prog -c cluster'

    parser = OptionParser(usage)

    parser.add_option('-c', dest='cluster_spec_fname',
                      help='path to the cluster specification file',
                      metavar='cluster.spec')

    options, args = parser.parse_args()
    if not options.cluster_spec_fname:
        parser.error('Please specify a cluster specification')

    return options, args

def main():
    options, args = get_options()

    cluster_spec = ClusterSpec()
    cluster_spec.parse(options.cluster_spec_fname, args)

    remote = RemoteHelper(cluster_spec, test_config=None, verbose=False)

    remote.collect_info()
    for hostname in cluster_spec.yield_hostnames():
        for fname in glob.glob('{}/*.zip'.format(hostname)):
            shutil.move(fname, '{}.zip'.format(hostname))

if __name__ == '__main__':
    main()

import glob
import os.path
import shutil
from optparse import OptionParser

from perfrunner.helpers.remote import RemoteHelper
from perfrunner.settings import ClusterSpec

def get_options():
    usage = '%prog -c cluster'

    parser = OptionParser(usage)

    parser.add_option('-c', dest='cluster_spec_fname',
                      help='path to the cluster specification file',
                      metavar='cluster.spec')

    options, args = parser.parse_args()
    if not options.cluster_spec_fname:
        parser.error('Please specify a cluster specification')

    return options, args

def main():
    options, args = get_options()

    cluster_spec = ClusterSpec()
    cluster_spec.parse(options.cluster_spec_fname, args)

    remote = RemoteHelper(cluster_spec, test_config=None, verbose=False)

    remote.collect_info()
    for hostname in cluster_spec.yield_hostnames():
        for fname in glob.glob('{}/*.zip'.format(hostname)):
            shutil.move(fname, '{}.zip'.format(hostname))

    if cluster_spec.backup is not None:
        logs = os.path.join(cluster_spec.backup, 'logs')
        if os.path.exists(logs):
            shutil.make_archive('tools', 'zip', logs)

if __name__ == '__main__':
    main()

Archive logs from the tools

Archive logs from the tools

Change-Id: I184473d20cc2763fbc97c993bfcab36b80d1c864
Reviewed-on: http://review.couchbase.org/76571
Tested-by: Build Bot <80754af91bfb6d1073585b046fe0a474ce868509@couchbase.com>
Reviewed-by: Pavel Paulau <dd88eded64e90046a680e3a6c0828ceb8fe8a0e7@gmail.com>


#!/usr/bin/env python

from setuptools import setup

setup(name='drcli',
      version='0.1',
      description='Command-line tools for docrep',
      author = 'schwa lab',
      url='http://schwa.org/git/drcli.git',
      packages=['drcli'],
      scripts=['dr'],
      install_requires=['argparse'],
      package_data = {
        'drcli': ['plugins/*/*.py'],
      },
      license='Apache 2.0',
     )

#!/usr/bin/env python

from setuptools import setup

setup(name='drcli',
      version='0.2',
      description='Command-line tools for docrep',
      author = 'schwa lab',
      url='http://schwa.org/git/drcli.git',
      packages=['drcli'],
      scripts=['dr'],
      install_requires=['argparse', 'brownie'],
      package_data = {
        'drcli': ['plugins/*/*.py'],
      },
      license='Apache 2.0',
     )

Set version to 0.2; add brownie dependency


import csv
import sys
import urllib

from scheduleitem import ScheduleItem
from team import Team

def read(uri):
    """Open a File or a Web URL"""
    if uri.startswith('http://') or uri.startswith('https://'):
        return open_url(uri)
    else:
        return open_file(uri)

def open_url(url):
    """Return the games file data as an array"""
    try:
        with urllib.request.urlopen(url) as response:
            return response.read()
    except urllib.HTTPError as e:
        msg = "Could Not Open URL {}.\nThe Code is: {} "
        print(msg.format(url, e.code))
        sys.exit(1)
    except urllib.URLError as e:
        msg = "Could Not Open URL {}.\nThe Reason is: {} "
        print(msg.format(url.url, e.reason))
        sys.exit(1)

def open_file(uri):
    """Return the games file data as an array"""
    try:
        with open(uri, 'r') as f:
            return f.read()
    except IOError:
        msg = "Could not open file: `{}`"
        print(msg.format(uri))
        sys.exit(1)

def load_schedules(games_file):
    with open(games_file, 'r') as f:
        return [ScheduleItem.from_str(line) for line in f.readlines()]

def load_teams_data(data_file):
    with open(data_file, 'r') as csv_file:
        reader = csv.reader(csv_file)
        # Skip the header row
        next(reader)
        return [Team(row[0], row[2], row[3]) for row in reader]

import csv
import sys
import urllib.error
import urllib.request

from scheduleitem import ScheduleItem
from team import Team

def read(uri):
    """Open a File or a Web URL"""
    if uri.startswith('http://') or uri.startswith('https://'):
        return open_url(uri)
    else:
        return open_local_file(uri)

def open_url(url):
    """Return the game file data."""
    with urllib.request.urlopen(url) as response:
        if response.status != 200:
            msg = 'Status {}. Could Not Open URL {}. Reason: {}'
            raise urllib.error.HTTPError(
                msg.format(response.status, url, response.msg)
            )
        encoding = sys.getdefaultencoding()
        return [line.decode(encoding) for line in response.readlines()]

def open_local_file(uri):
    """Return the games file data as an array"""
    with open(uri, 'r') as f:
        return f.readlines()

def load_schedules(uri):
    data = read(uri)
    return [ScheduleItem.from_str(line) for line in data]

def load_teams_data(data_file):
    with open(data_file, 'r') as csv_file:
        reader = csv.reader(csv_file)
        next(reader)  # Skip the header row
        return [Team(row[0], row[2], row[3]) for row in reader]

Update file handlers to use Python3 urllib


from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path

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

with open("README.md", "r") as fh:
    long_description = fh.read()

setup(
    name='django-cra-helper',
    version='1.0.2',
    description='The missing piece of the Django + React puzzle',
    long_description=long_description,
    long_description_content_type="text/markdown",
    url='https://github.com/MasterKale/django-cra-helper',
    author='Matthew Miller',
    author_email='matthew@millerti.me',
    license='MIT',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3',
    ],
    keywords='django react create-react-app integrate',
    packages=find_packages(exclude=['contrib', 'docs', 'tests']),
    install_requires=[
        'bleach>=2'
    ],
)

from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path

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

with open("README.md", "r") as fh:
    long_description = fh.read()

setup(
    name='django-cra-helper',
    version='1.1.0',
    description='The missing piece of the Django + React puzzle',
    long_description=long_description,
    long_description_content_type="text/markdown",
    url='https://github.com/MasterKale/django-cra-helper',
    author='Matthew Miller',
    author_email='matthew@millerti.me',
    license='MIT',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3',
    ],
    keywords='django react create-react-app integrate',
    packages=find_packages(exclude=['contrib', 'docs', 'tests']),
    install_requires=[
        'bleach>=2'
    ],
)

Update package version to v1.1.0

Update package version to v1.1.0


#!/usr/bin/env python
# -*- coding: utf-8 -*-

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

with open('README.rst') as readme_file:
    readme = readme_file.read()

with open('HISTORY.rst') as history_file:
    history = history_file.read().replace('.. :changelog:', '')

requirements = [
    'SQLAlchemy',
    'python-dateutil',
    'python-magic',
    'elasticsearch',
]

test_requirements = [
    'coverage',
]

setup(
    name='esis',
    version='0.1.0',
    description="Elastic Search Index & Search",
    long_description=readme + '\n\n' + history,
    author="Javier Collado",
    author_email='jcollado@nowsecure.com',
    url='https://github.com/jcollado/esis',
    packages=[
        'esis',
    ],
    package_dir={'esis':
                 'esis'},
    include_package_data=True,
    install_requires=requirements,
    license="MIT",
    zip_safe=False,
    keywords='elastic search index sqlite',
    entry_points={
        'console_scripts': [
            'esis = esis.cli:main',
        ]
    },
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Programming Language :: Python :: 2.7',
    ],
    test_suite='tests',
    tests_require=test_requirements
)

#!/usr/bin/env python
# -*- coding: utf-8 -*-

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

with open('README.rst') as readme_file:
    readme = readme_file.read()

with open('HISTORY.rst') as history_file:
    history = history_file.read().replace('.. :changelog:', '')

requirements = [
    'SQLAlchemy',
    'python-dateutil',
    'python-magic',
    'elasticsearch',
]

test_requirements = [
    'coverage',
]

setup(
    name='esis',
    version='0.1.0',
    description="Elastic Search Index & Search",
    long_description=readme + '\n\n' + history,
    author="Javier Collado",
    author_email='jcollado@nowsecure.com',
    url='https://github.com/jcollado/esis',
    packages=[
        'esis',
    ],
    package_dir={'esis':
                 'esis'},
    include_package_data=True,
    install_requires=requirements,
    license="MIT",
    zip_safe=False,
    keywords='elastic search index sqlite',
    entry_points={
        'console_scripts': [
            'esis = esis.cli:main',
        ]
    },
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Programming Language :: Python :: 2.7',
    ],
    test_suite='tests',
    tests_require=test_requirements
)

Move development status to alpha

Move development status to alpha


from django.conf import settings

class TenantSyncRouter(object):
    """
    A router to control which applications will be synced,
    depending if we are syncing the shared apps or the tenant apps.
    """

    def allow_syncdb(self, db, model):
        # the imports below need to be done here else django <1.5 goes crazy
        # https://code.djangoproject.com/ticket/20704
        from django.db import connection
        from tenant_schemas.utils import get_public_schema_name, app_labels

        if connection.schema_name == get_public_schema_name():
            if model._meta.app_label not in app_labels(settings.SHARED_APPS):
                return False
        else:
            if model._meta.app_label not in app_labels(settings.TENANT_APPS):
                return False

        return None

from django.conf import settings

class TenantSyncRouter(object):
    """
    A router to control which applications will be synced,
    depending if we are syncing the shared apps or the tenant apps.
    """

    def allow_migrate(self, db, model):
        # the imports below need to be done here else django <1.5 goes crazy
        # https://code.djangoproject.com/ticket/20704
        from django.db import connection
        from tenant_schemas.utils import get_public_schema_name, app_labels

        if connection.schema_name == get_public_schema_name():
            if model._meta.app_label not in app_labels(settings.SHARED_APPS):
                return False
        else:
            if model._meta.app_label not in app_labels(settings.TENANT_APPS):
                return False

        return None

    def allow_syncdb(self, db, model):
        # allow_syncdb was changed to allow_migrate in django 1.7
        return self.allow_migrate(db, model)

Add database router allow_migrate() for Django 1.7


#!/usr/bin/env python

import sys
try:
    from setuptools import setup, Extension
except ImportError:
    from distutils.core import setup, Extension

uinput = Extension('libuinput',
                   sources = ['src/uinput.c'])

deps = ['libusb1', 'psutil']
if sys.version_info < (3,4):
    deps.append('enum34')

setup(name='python-steamcontroller',
      version='1.1',
      description='Steam Controller userland driver',
      author='Stany MARCEL',
      author_email='stanypub@gmail.com',
      url='https://github.com/ynsta/steamcontroller',
      package_dir={'steamcontroller': 'src'},
      packages=['steamcontroller'],
      scripts=['scripts/sc-dump.py',
               'scripts/sc-xbox.py',
               'scripts/sc-desktop.py',
               'scripts/sc-test-cmsg.py',
               'scripts/sc-gyro-plot.py',
               'scripts/vdf2json.py',
               'scripts/json2vdf.py'],
      license='MIT',
      platforms=['Linux'],
      install_requires=deps,
      ext_modules=[uinput, ])

#!/usr/bin/env python

import sys
try:
    from setuptools import setup, Extension
except ImportError:
    from distutils.core import setup, Extension

uinput = Extension('libuinput',
                   sources = ['src/uinput.c'])

deps = ['libusb1', 'psutil']
if sys.version_info < (3,4):
    deps.append('enum34')

setup(name='python-steamcontroller',
      version='1.1',
      description='Steam Controller userland driver',
      author='Stany MARCEL',
      author_email='stanypub@gmail.com',
      url='https://github.com/ynsta/steamcontroller',
      package_dir={'steamcontroller': 'src'},
      packages=['steamcontroller'],
      scripts=['scripts/sc-dump.py',
               'scripts/sc-xbox.py',
               'scripts/sc-desktop.py',
               'scripts/sc-mixed.py',
               'scripts/sc-test-cmsg.py',
               'scripts/sc-gyro-plot.py',
               'scripts/vdf2json.py',
               'scripts/json2vdf.py'],
      license='MIT',
      platforms=['Linux'],
      install_requires=deps,
      ext_modules=[uinput, ])

Add sc-mixed.py in installed scripts

Add sc-mixed.py in installed scripts

Signed-off-by: Stany MARCEL <3e139d47b96f775f4bc13af807cbc2ea7c67e72b@gmail.com>


from distutils.core import Extension, setup

from Cython.Build import cythonize

try:
    from Cython.Distutils import build_ext
except ImportError:
    use_cython = False
else:
    use_cython = True

if use_cython:
    extensions = [
        Extension('mathix.vector', ['mathix/vector.pyx']),
    ]

    cmdclass = {
        'build_ext': build_ext
    }
else:
    extensions = [
        Extension('mathix.vector', ['mathix/vector.c']),
    ]

    cmdclass = {}

setup(
    name='mathix',

    author='Peith Vergil',

    version='0.1',

    cmdclass=cmdclass,

    packages=[
        'mathix',
    ],

    keywords='useless simple math library',

    description='A useless simple math library.',

    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'Programming Language :: Cython',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
    ],

    ext_modules=cythonize(extensions)
)

from distutils.core import Extension, setup

try:
    from Cython.Distutils import build_ext
except ImportError:
    use_cython = False
else:
    use_cython = True

if use_cython:
    extensions = [
        Extension('mathix.vector', ['mathix/vector.pyx']),
    ]

    cmdclass = {
        'build_ext': build_ext
    }
else:
    extensions = [
        Extension('mathix.vector', ['mathix/vector.c']),
    ]

    cmdclass = {}

setup(
    name='mathix',

    author='Peith Vergil',

    version='0.1',

    cmdclass=cmdclass,

    packages=[
        'mathix',
    ],

    keywords='useless simple math library',

    description='A useless simple math library.',

    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'Programming Language :: Cython',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
    ],

    ext_modules=extensions
)

Remove the importing of the "cythonize" function.


#!/usr/bin/env python
#coding: utf-8
from distribute_setup import use_setuptools
use_setuptools()

from aero.__version__ import __version__, __title__, __authors__, __email__, __license__, __url__, __download_url__
from setuptools import setup

setup(
	name         = __title__,
	author       = __authors__,
	author_email = __email__,
	version      = __version__,
	license      = __license__,
	url          = __url__,
	download_url = __download_url__,
	packages     = ['aero', 'aero.adapters'],
    package_data ={'aero': ['assets/*.ascii']},
    description  = [descr for descr in open('README.txt').read().splitlines() if descr.strip() and '===' not in descr][1],
    long_description=open('README.txt').read(),
	scripts      = ["aero/aero"],

)

#!/usr/bin/env python
#coding: utf-8
from distribute_setup import use_setuptools
use_setuptools()

from aero.__version__ import __version__, __title__, __authors__, __email__, __license__, __url__, __download_url__
from setuptools import setup

setup(
	name         = __title__,
	author       = __authors__,
	author_email = __email__,
	version      = __version__,
	license      = __license__,
	url          = __url__,
	download_url = __download_url__,
	packages     = ['aero', 'aero.adapters'],
    package_data ={'aero': ['assets/*.ascii']},
    description  = [descr for descr in open('README.txt').read().splitlines() if descr.strip() and '===' not in descr][1],
    long_description=open('README.txt').read(),
	install_requires = ["argparse","Beaker","PyYAML"],
	scripts      = ["aero/aero"],

)

Add project dependencies to install

Add project dependencies to install


from setuptools import setup, find_packages

setup(
    name='django-lightweight-queue',

    url="https://chris-lamb.co.uk/projects/django-lightweight-queue",
    version='2.0.1',
    description="Lightweight & modular queue and cron system for Django",

    author="Chris Lamb",
    author_email='chris@chris-lamb.co.uk',
    license="BSD",

    packages=find_packages(),
)

from setuptools import setup, find_packages

setup(
    name='django-lightweight-queue',

    url="https://chris-lamb.co.uk/projects/django-lightweight-queue",
    version='2.0.1',
    description="Lightweight & modular queue and cron system for Django",

    author="Chris Lamb",
    author_email='chris@chris-lamb.co.uk',
    license="BSD",

    packages=find_packages(),

    install_requires=(
        'Django>=1.8',
    ),
)

Update Django requirement to latest LTS

Update Django requirement to latest LTS


# -*- coding: utf-8 -*-

'''
Flask-LDAPConn
--------------

Flask extension providing ldap3 connection object and ORM
to accessing LDAP servers.
'''

from setuptools import setup

setup(
    name='Flask-LDAPConn',
    version='0.6.5',
    url='http://github.com/rroemhild/flask-ldapconn',
    license='BSD',
    author='Rafael Römhild',
    author_email='rafael@roemhild.de',
    keywords='flask ldap ldap3 orm',
    description='Pure python, LDAP connection and ORM for Flask Applications',
    long_description=open('README.rst').read(),
    packages=[
        'flask_ldapconn'
    ],
    zip_safe=False,
    platforms='any',
    install_requires=[
        'Flask==0.10.1',
        'ldap3==0.9.9.1',
        'six==1.10.0'
    ],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Framework :: Flask',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
        'Topic :: Software Development :: Libraries :: Python Modules'
    ]
)

# -*- coding: utf-8 -*-

'''
Flask-LDAPConn
--------------

Flask extension providing ldap3 connection object and ORM
to accessing LDAP servers.
'''

from setuptools import setup

setup(
    name='Flask-LDAPConn',
    version='0.6.6',
    url='http://github.com/rroemhild/flask-ldapconn',
    license='BSD',
    author='Rafael Römhild',
    author_email='rafael@roemhild.de',
    keywords='flask ldap ldap3 orm',
    description='Pure python, LDAP connection and ORM for Flask Applications',
    long_description=open('README.rst').read(),
    packages=[
        'flask_ldapconn'
    ],
    zip_safe=False,
    platforms='any',
    install_requires=[
        'Flask==0.10.1',
        'ldap3==0.9.9.1',
        'six==1.10.0'
    ],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Framework :: Flask',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
        'Topic :: Software Development :: Libraries :: Python Modules'
    ]
)

Bump version 0.6.5 -> 0.6.6

Bump version 0.6.5 -> 0.6.6


from setuptools import setup

setup(
    name='pytest-flakes',
    description='pytest plugin to check source code with pyflakes',
    long_description=open("README.rst").read(),
    license="MIT license",
    version='1.0.1',
    author='Florian Schulze, Holger Krekel and Ronny Pfannschmidt',
    author_email='florian.schulze@gmx.net',
    url='https://github.com/fschulze/pytest-flakes',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Framework :: Pytest',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Topic :: Software Development :: Testing',
    ],
    py_modules=['pytest_flakes'],
    entry_points={'pytest11': ['flakes = pytest_flakes']},
    install_requires=['pytest-cache', 'pytest>=2.3.dev14', 'pyflakes'])

from setuptools import setup

setup(
    name='pytest-flakes',
    description='pytest plugin to check source code with pyflakes',
    long_description=open("README.rst").read(),
    license="MIT license",
    version='1.0.1',
    author='Florian Schulze, Holger Krekel and Ronny Pfannschmidt',
    author_email='florian.schulze@gmx.net',
    url='https://github.com/fschulze/pytest-flakes',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Framework :: Pytest',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Topic :: Software Development :: Testing',
    ],
    py_modules=['pytest_flakes'],
    entry_points={'pytest11': ['flakes = pytest_flakes']},
    install_requires=['pytest-cache', 'pytest>=2.3.dev14', 'pyflakes'])

Use correct MIT license classifier.

Use correct MIT license classifier.

`LICENSE` contains the MIT/Expat license but `setup.py` uses the LGPLv3
classifier. I assume the later is an oversight.


import os

from setuptools import setup

PACKAGE_VERSION = '0.3'

def version():
    if os.getenv('TRAVIS'):
        return os.getenv('TRAVIS_BUILD_NUMBER')
    else:
        import odintools

        return odintools.version(PACKAGE_VERSION, os.environ.get('BUILD_NUMBER'))

setup(
    name='osaapi',
    version_getter=version,
    author='apsliteteam, oznu',
    author_email='aps@odin.com',
    packages=['osaapi'],
    url='https://aps.odin.com',
    license='Apache License',
    description='A python client for the Odin Service Automation (OSA) and billing APIs.',
    long_description=open('README.md').read(),
    setup_requires=['odintools'],
    odintools=True,
)

import os

from setuptools import setup

PACKAGE_VERSION = '0.3'

def version():
    import odintools
    b = os.getenv('TRAVIS_BUILD_NUMBER') if os.getenv('TRAVIS') else os.environ.get('BUILD_NUMBER')
    return odintools.version(PACKAGE_VERSION, b)

setup(
    name='osaapi',
    version_getter=version,
    author='apsliteteam, oznu',
    author_email='aps@odin.com',
    packages=['osaapi'],
    url='https://aps.odin.com',
    license='Apache License',
    description='A python client for the Odin Service Automation (OSA) and billing APIs.',
    long_description=open('README.md').read(),
    setup_requires=['odintools'],
    odintools=True,
)

Fix issue with version setter

Fix issue with version setter


#!/usr/bin/env python
"""Django/PostgreSQL implementation of the Meteor DDP service."""
import os.path
from setuptools import setup, find_packages

setup(
    name='django-ddp',
    version='0.2.0',
    description=__doc__,
    long_description=open('README.rst').read(),
    author='Tyson Clugg',
    author_email='tyson@clugg.net',
    url='https://github.com/commoncode/django-ddp',
    packages=find_packages(),
    include_package_data=True,
    install_requires=[
        'Django>=1.7',
        'psycopg2>=2.5.4',
        'gevent>=1.0',
        'gevent-websocket>=0.9',
        'meteor-ejson>=1.0',
        'psycogreen>=1.0',
        'django-dbarray>=0.2',
    ],
    classifiers=[
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 3",
        "Topic :: Internet :: WWW/HTTP",
    ],
)

#!/usr/bin/env python
"""Django/PostgreSQL implementation of the Meteor DDP service."""
import os.path
from setuptools import setup, find_packages

setup(
    name='django-ddp',
    version='0.2.1',
    description=__doc__,
    long_description=open('README.rst').read(),
    author='Tyson Clugg',
    author_email='tyson@clugg.net',
    url='https://github.com/commoncode/django-ddp',
    packages=find_packages(),
    include_package_data=True,
    install_requires=[
        'Django>=1.7',
        'psycopg2>=2.5.4',
        'gevent>=1.0',
        'gevent-websocket>=0.9',
        'meteor-ejson>=1.0',
        'psycogreen>=1.0',
        'django-dbarray>=0.2',
    ],
    classifiers=[
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 3",
        "Topic :: Internet :: WWW/HTTP",
    ],
)

Bump version number in preparation for next release.


from datetime import datetime

from django.db import models
from django.contrib.auth.models import User

class Key(models.Model):
    user = models.ForeignKey(User)
    key = models.CharField(max_length=40)
    created = models.DateTimeField(auto_now_add=True)
    usage_left = models.IntegerField(null=True, default=1)
    expires = models.DateTimeField(null=True)
    next = models.CharField(null=True, max_length=200)

    def __unicode__(self):
        return '%s (%s)' % (self.key, self.user.username)

    def is_valid(self):
        if self.usage_left is not None and self.usage_left <= 0:
            return False
        if self.expires is not None and self.expires < datetime.now():
            return False
        return True

    def update_usage(self):
        if self.usage_left is not None:
            self.usage_left -= 1
            self.save()

from datetime import datetime

from django.db import models
from django.contrib.auth.models import User

class Key(models.Model):
    user = models.ForeignKey(User)
    key = models.CharField(max_length=40)
    created = models.DateTimeField(auto_now_add=True)
    usage_left = models.IntegerField(null=True, default=1)
    expires = models.DateTimeField(null=True)
    next = models.CharField(null=True, max_length=200)

    def __unicode__(self):
        return '%s (%s)' % (self.key, self.user.username)

    def is_valid(self):
        if self.usage_left is not None and self.usage_left <= 0:
            return False
        if self.expires is not None and self.expires < datetime.now():
            return False
        return True

    def update_usage(self):
        if self.usage_left is not None and self.usage_left > 0:
            self.usage_left -= 1
            self.save()

Update key usage when the usage_left counter is still greater than zero.


from re import split as resplit
from typing import Callable, Union

from dmoj.result import CheckerResult
from dmoj.utils.unicode import utf8bytes

verdict = u"\u2717\u2713"

def check(process_output: bytes, judge_output: bytes, point_value: float, feedback: bool = True,
          match: Callable[[bytes, bytes], bool] = lambda p, j: p.strip() == j.strip(),
          **kwargs) -> Union[CheckerResult, bool]:
    process_lines = list(filter(None, resplit(b'[\r\n]', utf8bytes(process_output))))
    judge_lines = list(filter(None, resplit(b'[\r\n]', utf8bytes(judge_output))))

    if len(process_lines) > len(judge_lines):
        return False

    if not judge_lines:
        return True

    if isinstance(match, str):
        match = eval(match)

    cases = [verdict[0]] * len(judge_lines)
    count = 0

    for i, (process_line, judge_line) in enumerate(zip(process_lines, judge_lines)):
        if match(process_line, judge_line):
            cases[i] = verdict[1]
            count += 1

    return CheckerResult(count == len(judge_lines), point_value * (1.0 * count / len(judge_lines)),
                         ''.join(cases) if feedback else "")

check.run_on_error = True  # type: ignore

from re import split as resplit
from typing import Callable, Union

from dmoj.result import CheckerResult
from dmoj.utils.unicode import utf8bytes

verdict = u"\u2717\u2713"

def check(process_output: bytes, judge_output: bytes, point_value: float, feedback: bool = True,
          **kwargs) -> Union[CheckerResult, bool]:
    process_lines = list(filter(None, resplit(b'[\r\n]', utf8bytes(process_output))))
    judge_lines = list(filter(None, resplit(b'[\r\n]', utf8bytes(judge_output))))

    if len(process_lines) > len(judge_lines):
        return False

    if not judge_lines:
        return True

    cases = [verdict[0]] * len(judge_lines)
    count = 0

    for i, (process_line, judge_line) in enumerate(zip(process_lines, judge_lines)):
        if process_line.strip() == judge_line.strip():
            cases[i] = verdict[1]
            count += 1

    return CheckerResult(count == len(judge_lines), point_value * (1.0 * count / len(judge_lines)),
                         ''.join(cases) if feedback else "")

check.run_on_error = True  # type: ignore

Remove the match param to fix RCE.

Remove the match param to fix RCE.


from nose.plugins.attrib import attr
from indra.sources.tas import process_from_web

@attr('slow')
def test_processor():
    tp = process_from_web(affinity_class_limit=10)
    assert tp
    assert tp.statements
    num_stmts = len(tp.statements)
    # This is the total number of statements about human genes
    assert num_stmts == 1130277, num_stmts
    assert all(len(s.evidence) >= 1 for s in tp.statements), \
        'Some statements lack any evidence'

from nose.plugins.attrib import attr
from indra.sources.tas import process_from_web

@attr('slow')
def test_processor():
    tp = process_from_web(affinity_class_limit=10)
    assert tp
    assert tp.statements
    num_stmts = len(tp.statements)
    # This is the total number of statements about human genes
    assert num_stmts == 1128585, num_stmts
    assert all(len(s.evidence) >= 1 for s in tp.statements), \
        'Some statements lack any evidence'

Update test again after better aggregation


import unittest

import numpy as np

from constraints import (generate_constraints_function,
                         generate_constraint_gradients_function, )
from robot_arm import RobotArm

class TestConstraintFunctions(unittest.TestCase):
    def setUp(self):
        self.lengths = (3, 2, 2,)
        self.destinations = (
            (5, 4, 6, 4, 5),
            (0, 2, 0.5, -2, -1),
        )
        self.theta = (np.pi, np.pi / 2, 0,)
        self.thetas = np.ones((3 * 5,))
        self.robot_arm = RobotArm(self.lengths, self.destinations, self.theta)
        self.constraints_func = generate_constraints_function(self.robot_arm)
        self.constraint_gradients_func = generate_constraint_gradients_function(self.robot_arm)

    def test_constraints_func_return_type(self):
        constraints = self.constraints_func(self.thetas)
        self.assertEqual(constraints.shape, (2 * 5,))

    def test_constraint_gradients_func_return_type(self):
        constraint_gradients = self.constraint_gradients_func(self.thetas)
        self.assertEqual(constraint_gradients.shape, (3 * 5, 2 * 5))
        # print(np.array2string(constraint_gradients, max_line_width=np.inf))

    def test_licq(self):
        constraint_gradients = self.constraint_gradients_func(self.thetas)
        rank = np.linalg.matrix_rank(constraint_gradients)
        self.assertEqual(rank, 2 * 5)

Test LICQ condition of constraint gradient


import numpy as np
import numpy.ma as ma

import projections.r2py.reval as reval
import projections.r2py.rparser as rparser

class SimpleExpr():
  def __init__(self, name, expr):
    self.name = name
    self.tree = reval.make_inputs(rparser.parse(expr))
    lokals = {}
    exec(reval.to_py(self.tree, name), lokals)
    self.func = lokals[name + '_st']

  @property
  def syms(self):
    return reval.find_inputs(self.tree)

  def eval(self, df):
    try:
      res = self.func(df)
    except KeyError as e:
      print("Error: input '%s' not defined" % e)
      raise e
    if not isinstance(res, np.ndarray):
      res = ma.masked_array(np.full(tuple(df.values())[0].shape, res,
                                    dtype=np.float32))
    return res

import numpy as np
import numpy.ma as ma

import projections.r2py.reval as reval
import projections.r2py.rparser as rparser

class SimpleExpr():
  def __init__(self, name, expr):
    self.name = name
    self.tree = reval.make_inputs(rparser.parse(expr))
    lokals = {}
    exec(reval.to_py(self.tree, name), lokals)
    self.func = lokals[name + '_st']

  @property
  def syms(self):
    return reval.find_inputs(self.tree)

  def eval(self, df):
    try:
      res = self.func(df)
    except KeyError as e:
      print("Error: input '%s' not defined" % e)
      raise e
    if not isinstance(res, np.ndarray):
      arrays = filter(lambda v: isinstance(v, np.ndarray), df.values())
      res = ma.masked_array(np.full(tuple(arrays)[0].shape, res,
                                    dtype=np.float32))
    return res

Improve determination of array shape for constant expressions

When Evaluating a constant expression, I only used to look at the first
column in the df dictionary.  But that could also be a constant or
expression.  So look instead at all columns and find the first numpy
array.


# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-24 02:39
from __future__ import unicode_literals

from django.db import migrations

def fix_realm_string_ids(apps, schema_editor):
    # type: (StateApps, DatabaseSchemaEditor) -> None
    Realm = apps.get_model('zerver', 'Realm')
    if Realm.objects.count() != 2:
        return

    zulip_realm = Realm.objects.get(string_id="zulip")
    try:
        user_realm = Realm.objects.exclude(id=zulip_realm.id)[0]
    except Realm.DoesNotExist:
        return

    user_realm.string_id = ""
    user_realm.save()

class Migration(migrations.Migration):

    dependencies = [
        ('zerver', '0107_multiuseinvite'),
    ]

    operations = [
        migrations.RunPython(fix_realm_string_ids,
                             reverse_code=migrations.RunPython.noop),
    ]

# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-24 02:39
from __future__ import unicode_literals

from django.db import migrations
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps

def fix_realm_string_ids(apps, schema_editor):
    # type: (StateApps, DatabaseSchemaEditor) -> None
    Realm = apps.get_model('zerver', 'Realm')
    if Realm.objects.count() != 2:
        return

    zulip_realm = Realm.objects.get(string_id="zulip")
    try:
        user_realm = Realm.objects.exclude(id=zulip_realm.id)[0]
    except Realm.DoesNotExist:
        return

    user_realm.string_id = ""
    user_realm.save()

class Migration(migrations.Migration):

    dependencies = [
        ('zerver', '0107_multiuseinvite'),
    ]

    operations = [
        migrations.RunPython(fix_realm_string_ids,
                             reverse_code=migrations.RunPython.noop),
    ]

Add imports needed for new migration.

mypy: Add imports needed for new migration.


# -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license

from .users import RolesResource, UsersResource
from .services import DBUsersService, RolesService, is_admin  # noqa
import superdesk

def init_app(app):
    endpoint_name = 'users'
    service = DBUsersService(endpoint_name, backend=superdesk.get_backend())
    UsersResource(endpoint_name, app=app, service=service)

    endpoint_name = 'roles'
    service = RolesService(endpoint_name, backend=superdesk.get_backend())
    RolesResource(endpoint_name, app=app, service=service)

    superdesk.privilege(name='users', label='User Management', description='User can manage users.')
    superdesk.privilege(name='roles', label='Roles Management', description='User can manage roles.')

    # Registering with intrinsic privileges because: A user should be allowed to update their own profile.
    superdesk.intrinsic_privilege(resource_name='users', method=['PATCH'])

# -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license

from .users import RolesResource, UsersResource
from .services import UsersService, DBUsersService, RolesService, is_admin  # noqa
import superdesk

def init_app(app):
    endpoint_name = 'users'
    service = DBUsersService(endpoint_name, backend=superdesk.get_backend())
    UsersResource(endpoint_name, app=app, service=service)

    endpoint_name = 'roles'
    service = RolesService(endpoint_name, backend=superdesk.get_backend())
    RolesResource(endpoint_name, app=app, service=service)

    superdesk.privilege(name='users', label='User Management', description='User can manage users.')
    superdesk.privilege(name='roles', label='Roles Management', description='User can manage roles.')

    # Registering with intrinsic privileges because: A user should be allowed to update their own profile.
    superdesk.intrinsic_privilege(resource_name='users', method=['PATCH'])

Make UsersResource reusable for LDAP

Make UsersResource reusable for LDAP


'''
.. moduleauthor:: Ian Chesal <ian.chesal@gmail.com>
'''

__version__ = '1.0.0'
__all__ = ['keybase']

'''
.. moduleauthor:: Ian Chesal <ian.chesal@gmail.com>
'''

__version__ = '1.0.1'
__all__ = ['keybase']

Bump version 1.0.0 -> 1.0.1

Bump version 1.0.0 -> 1.0.1


# -*- coding: utf-8 -*-
from django.conf import settings
from django.core.cache import cache

permission_cache_keys = []
all_keys = []

def get_cache_key(user, key):
    return "%s:permission:%s:%s" % (
        settings.CMS_CACHE_PREFIX, user.username, key)

def get_permission_cache(user, key):
    """
    Helper for reading values from cache
    """
    return cache.get(get_cache_key(user, key))

def set_permission_cache(user, key, value):
    """
    Helper method for storing values in cache. Stores used keys so
    all of them can be cleaned when clean_permission_cache gets called.
    """
    # store this key, so we can clean it when required
    cache_key = get_cache_key(user, key)

    if not cache_key in all_keys:
        all_keys.append(cache_key)
    if not key in permission_cache_keys:
        permission_cache_keys.append(key)
    cache.set(cache_key, value, settings.CMS_CACHE_DURATIONS['permissions'])

def clear_user_permission_cache(user):
    """
    Cleans permission cache for given user.
    """
    for key in permission_cache_keys:
        cache.delete(get_cache_key(user, key))

def clear_permission_cache():
    for key in all_keys:
        cache.delete(key)

# -*- coding: utf-8 -*-
from django.conf import settings
from django.core.cache import cache

from django.contrib.auth.models import User

PERMISSION_KEYS = [
    'can_change', 'can_add', 'can_delete',
    'can_change_advanced_settings', 'can_publish',
    'can_change_permissions', 'can_move_page',
    'can_moderate', 'can_view']

def get_cache_key(user, key):
    return "%s:permission:%s:%s" % (
        settings.CMS_CACHE_PREFIX, user.username, key)

def get_permission_cache(user, key):
    """
    Helper for reading values from cache
    """
    return cache.get(get_cache_key(user, key))

def set_permission_cache(user, key, value):
    """
    Helper method for storing values in cache. Stores used keys so
    all of them can be cleaned when clean_permission_cache gets called.
    """
    # store this key, so we can clean it when required
    cache_key = get_cache_key(user, key)
    cache.set(cache_key, value, settings.CMS_CACHE_DURATIONS['permissions'])

def clear_user_permission_cache(user):
    """
    Cleans permission cache for given user.
    """
    for key in PERMISSION_KEYS:
        cache.delete(get_cache_key(user, key))

def clear_permission_cache():
    users = User.objects.filter(is_active=True)
    for user in users:
        for key in PERMISSION_KEYS:
            cache_key = get_cache_key(user, key)
            cache.delete(cache_key)

Fix for issue 1423 * no longer rely on global variables for invalidating caches


""" Utility functions for PhotoScan processing """

import os, sys
import PhotoScan

def align_and_clean_photos(chunk):
    ncameras = len(chunk.cameras)
    for frame in chunk.frames:
        frame.matchPhotos()

    chunk.alignCameras()
    for camera in chunk.cameras:
        if camera.transform is None:
            chunk.remove(camera)

    naligned = len(chunk.cameras)
    print('%d/%d cameras aligned' % (naligned, ncameras))

def export_dems(resolution, formatstring, pathname)
    if not os.path.isdir(pathname):
        os.mkdir(pathname)

    nchunks = len(PhotoScan.app.document.chunks)
    nexported = nchunks
    for chunk in PhotoScan.app.document.chunks:
        filename = ''.join([pathname, chunk.label.split(' '), '.', formatstring])
        exported = chunk.exportDem(filename, format=formatstring, dx=resolution, dy=resolution)
        if not exported:
            print('Export failed:', chunk.label)
            nexported -= 1

    print('%d/%d DEMs exported' % (nexported, nchunks))

""" Utility functions for PhotoScan processing """

import os, sys
import PhotoScan

def align_and_clean_photos(chunk):
    ncameras = len(chunk.cameras)
    for frame in chunk.frames:
        frame.matchPhotos()

    chunk.alignCameras()
    for camera in chunk.cameras:
        if camera.transform is None:
            chunk.remove(camera)

    naligned = len(chunk.cameras)
    print('%d/%d cameras aligned' % (naligned, ncameras))

def export_dems(resolution, formatstring, pathname)
    if not os.path.isdir(pathname):
        os.mkdir(pathname)
    if pathname[-1:] is not '/':
        pathname = ''.join(pathname, '/')

    nchunks = len(PhotoScan.app.document.chunks)
    nexported = nchunks
    for chunk in PhotoScan.app.document.chunks:
        filename = ''.join([pathname, chunk.label.split(' '), '.', formatstring])
        exported = chunk.exportDem(filename, format=formatstring, dx=resolution, dy=resolution)
        if not exported:
            print('Export failed:', chunk.label)
            nexported -= 1

    print('%d/%d DEMs exported' % (nexported, nchunks))

Check for trailing slash in path

Check for trailing slash in path


#!/usr/bin/env python

# MAKE IT UNICODE OK
import sys
reload( sys )
sys.setdefaultencoding( 'utf-8' )

import os, sys
import Bot
import logging

if __name__ == '__main__':
	logging.basicConfig( level = logging.DEBUG, format = '[%(asctime)s] %(levelname)s: %(message)s' )
	logging.getLogger().addHandler( logging.FileHandler( 'ircbot.log' ) )
	logging.info( "Welcome to botje" )
	fork = True
	if len( sys.argv ) > 1:
		if sys.argv[1] == '-nofork':
			fork = False
	if fork:
		try:
			pid = os.fork()
			if pid > 0:
				logging.info( 'Forked into PID {0}'.format( pid ) )
				sys.exit(0)
			sys.stdout = open( '/tmp/ircbot.log', 'w' )
		except OSError as error:
			logging.error( 'Unable to fork. Error: {0} ({1})'.format( error.errno, error.strerror ) )
			sys.exit(1)
	botje = Bot.Bot()
	while True:
		try:
			botje.start()
		except Bot.BotReloadException:
			logging.info( 'Force reloading Bot class' )
			botje = None
			reload(Bot)
			botje = Bot.Bot()
		logging.info( 'Botje died, restarting in 5...' )
		import time
		time.sleep( 5 )

#!/usr/bin/env python

# MAKE IT UNICODE OK
import sys
reload( sys )
sys.setdefaultencoding( 'utf-8' )

import os, sys
import Bot
import logging

if __name__ == '__main__':
	logging.basicConfig( filename = 'ircbot.log', level = logging.DEBUG, format = '[%(asctime)s] %(levelname)s: %(message)s' )
	logging.info( "Welcome to botje" )
	fork = True
	if len( sys.argv ) > 1:
		if sys.argv[1] == '-nofork':
			fork = False
	if fork:
		try:
			pid = os.fork()
			if pid > 0:
				logging.info( 'Forked into PID {0}'.format( pid ) )
				sys.exit(0)
			sys.stdout = open( '/tmp/ircbot.log', 'w' )
		except OSError as error:
			logging.error( 'Unable to fork. Error: {0} ({1})'.format( error.errno, error.strerror ) )
			sys.exit(1)
	botje = Bot.Bot()
	while True:
		try:
			botje.start()
		except Bot.BotReloadException:
			logging.info( 'Force reloading Bot class' )
			botje = None
			reload(Bot)
			botje = Bot.Bot()
		logging.info( 'Botje died, restarting in 5...' )
		import time
		time.sleep( 5 )

Set default logger to file

Set default logger to file


# -*- coding: utf-8 -*-
# Copyright (c) 2013-2015, Sebastian Linke

# Released under the Simplified BSD license
# (see LICENSE file for details).

"""
Constants that are used by `shcol` in many places. This is meant to modified (if
needed) only *before* running `shcol`, since most of these constants are only
read during initialization of the `shcol`-package.
"""
import logging
import os
import sys

ENCODING = 'utf-8'
ERROR_STREAM = sys.stderr
INPUT_STREAM = sys.stdin
LINE_WIDTH = None
LINESEP = '\n'
LOGGER = logging.getLogger('shol')
MAKE_UNIQUE = False
ON_WINDOWS = 'windows' in os.getenv('os', '').lower()
PY_VERSION = sys.version_info[:2]
SORT_ITEMS = False
SPACING = 2
STARTER = os.path.join('bin', 'shcol' + ('.bat' if ON_WINDOWS else ''))
TERMINAL_STREAM = sys.stdout
UNICODE_TYPE = type(u'')

# -*- coding: utf-8 -*-
# Copyright (c) 2013-2015, Sebastian Linke

# Released under the Simplified BSD license
# (see LICENSE file for details).

"""
Constants that are used by `shcol` in many places. This is meant to modified (if
needed) only *before* running `shcol`, since most of these constants are only
read during initialization of the `shcol`-package.
"""
import logging
import os
import sys

ERROR_STREAM = sys.stderr
INPUT_STREAM = sys.stdin
LINE_WIDTH = None
LINESEP = '\n'
LOGGER = logging.getLogger('shol')
MAKE_UNIQUE = False
ON_WINDOWS = 'windows' in os.getenv('os', '').lower()
PY_VERSION = sys.version_info[:2]
SORT_ITEMS = False
SPACING = 2
STARTER = os.path.join('bin', 'shcol' + ('.bat' if ON_WINDOWS else ''))
TERMINAL_STREAM = sys.stdout
UNICODE_TYPE = type(u'')

ENCODING = TERMINAL_STREAM.encoding or 'utf-8'

Use output stream's encoding (if any). Blindly using UTF-8 would break output on Windows terminals.


import logging

__version__ = "0.17.0"
version = tuple(__version__.split('.'))

logging.getLogger(__name__).addHandler(logging.NullHandler())

import logging

__version__ = "0.17.1rc1"
version = tuple(__version__.split('.'))

logging.getLogger(__name__).addHandler(logging.NullHandler())

Bump version 0.17.0 --> 0.17.1rc1

Bump version 0.17.0 --> 0.17.1rc1

Signed-off-by: Jack Robison <40884020c67726395ea162083a125620dc32cdab@lbry.io>


"""Module for generating Barcode Checksum Poster resource."""

from PIL import Image
from utils.retrieve_query_parameter import retrieve_query_parameter

def resource_image(request, resource):
    """Create a image for Barcode Checksum Poster resource.

    Args:
        request: HTTP request object (QueryDict).
        resource: Object of resource data (Resource).

    Returns:
        A list of Pillow image objects.
    """
    # Retrieve parameters
    parameter_options = valid_options()
    barcode_length = retrieve_query_parameter(request, "barcode_length", parameter_options["barcode_length"])

    image_path = "static/img/resources/barcode-checksum-poster/{}-digits.png"
    image = Image.open(image_path.format(barcode_length))
    return image

def subtitle(request, resource):
    """Return the subtitle string of the resource.

    Used after the resource name in the filename, and
    also on the resource image.

    Args:
        request: HTTP request object (QueryDict).
        resource: Object of resource data (Resource).

    Returns:
        Text for subtitle (str).
    """
    barcode_length = retrieve_query_parameter(request, "barcode_length")
    paper_size = retrieve_query_parameter(request, "paper_size")
    return "{} digits - {}".format(barcode_length, paper_size)

def valid_options():
    """Provide dictionary of all valid parameters.

    This excludes the header text parameter.

    Returns:
        All valid options (dict).
    """
    return {
        "barcode_length": ["12", "13"],
        "paper_size": ["a4", "letter"],
    }

"""Module for generating Barcode Checksum Poster resource."""

from PIL import Image
from utils.retrieve_query_parameter import retrieve_query_parameter

def resource(request, resource):
    """Create a image for Barcode Checksum Poster resource.

    Args:
        request: HTTP request object (QueryDict).
        resource: Object of resource data (Resource).

    Returns:
        A dictionary for the resource page.
    """
    # Retrieve parameters
    parameter_options = valid_options()
    barcode_length = retrieve_query_parameter(request, "barcode_length", parameter_options["barcode_length"])

    image_path = "static/img/resources/barcode-checksum-poster/{}-digits.png"
    image = Image.open(image_path.format(barcode_length))
    return {"type": "image", "data": image}

def subtitle(request, resource):
    """Return the subtitle string of the resource.

    Used after the resource name in the filename, and
    also on the resource image.

    Args:
        request: HTTP request object (QueryDict).
        resource: Object of resource data (Resource).

    Returns:
        Text for subtitle (str).
    """
    barcode_length = retrieve_query_parameter(request, "barcode_length")
    paper_size = retrieve_query_parameter(request, "paper_size")
    return "{} digits - {}".format(barcode_length, paper_size)

def valid_options():
    """Provide dictionary of all valid parameters.

    This excludes the header text parameter.

    Returns:
        All valid options (dict).
    """
    return {
        "barcode_length": ["12", "13"],
        "paper_size": ["a4", "letter"],
    }

Update barcode resource to new resource specification


import shutil
import os

from django.core.files.storage import default_storage
from django.test import TestCase

class SampleFilesTestCase(TestCase):
    fixtures = ['sample']

    @classmethod
    def setUpClass(cls):
        default_storage.location = 'media' # force using source media folder to avoid real data erasing
    # @classmethod
    # def setUpClass(cls):
        # shutil.copytree('media', 'media-tmp')
        # default_storage.location = 'media-tmp'
#
    # @classmethod
    # def tearDownClass(self):
        # shutil.rmtree('media-tmp')

    def _fixture_setup(self):
        if os.path.exists('media/photos'):
            shutil.rmtree('media/photos')
        shutil.copytree('media/photos-sample', 'media/photos')
        super(SampleFilesTestCase, self)._fixture_setup()

    def tearDown(self):
        shutil.rmtree('media-tmp/photos')

from django_fixmystreet.fixmystreet.tests.views import *
from django_fixmystreet.fixmystreet.tests.reports import *
from django_fixmystreet.fixmystreet.tests.users import *
from django_fixmystreet.fixmystreet.tests.organisation_entity import *
from django_fixmystreet.fixmystreet.tests.mail import *
# from django_fixmystreet.fixmystreet.tests.api import *

import shutil
import os

from django.core.files.storage import default_storage
from django.test import TestCase

class SampleFilesTestCase(TestCase):
    fixtures = ['sample']

    @classmethod
    def setUpClass(cls):
        default_storage.location = 'media' # force using source media folder to avoid real data erasing
    # @classmethod
    # def setUpClass(cls):
        # shutil.copytree('media', 'media-tmp')
        # default_storage.location = 'media-tmp'
#
    # @classmethod
    # def tearDownClass(self):
        # shutil.rmtree('media-tmp')

    def _fixture_setup(self):
        if os.path.exists('media/photos'):
            shutil.rmtree('media/photos')
        shutil.copytree('media/photos-sample', 'media/photos')
        super(SampleFilesTestCase, self)._fixture_setup()

    def tearDown(self):
        shutil.rmtree('media/photos')

from django_fixmystreet.fixmystreet.tests.views import *
from django_fixmystreet.fixmystreet.tests.reports import *
from django_fixmystreet.fixmystreet.tests.users import *
from django_fixmystreet.fixmystreet.tests.organisation_entity import *
from django_fixmystreet.fixmystreet.tests.mail import *
# from django_fixmystreet.fixmystreet.tests.api import *

Fix unit test fixtures files

Fix unit test fixtures files


from graphene.types import Scalar
from graphql.language import ast

class AttributesFilterScalar(Scalar):

    @staticmethod
    def coerce_filter(value):
        if isinstance(value, tuple) and len(value) == 2:
            return ":".join(value)

    serialize = coerce_filter
    parse_value = coerce_filter

    @staticmethod
    def parse_literal(node):
        if isinstance(node, ast.StringValue):
            splitted = node.value.split(":")
            if len(splitted) == 2:
                return tuple(splitted)

from graphene.types import Scalar
from graphql.language import ast

class AttributesFilterScalar(Scalar):

    @staticmethod
    def parse_literal(node):
        if isinstance(node, ast.StringValue):
            splitted = node.value.split(":")
            if len(splitted) == 2:
                return tuple(splitted)

    @staticmethod
    def parse_value(value):
        if isinstance(value, basestring):
            splitted = value.split(":")
            if len(splitted) == 2:
                return tuple(splitted)

    @staticmethod
    def serialize(value):
        if isinstance(value, tuple) and len(value) == 2:
            return ":".join(value)

Fix parsing attributes filter values in GraphQL API


# coding: utf-8
from . import BaseTestCase

from ..models import Channel

class TestCoreModels(BaseTestCase):
    def setUp(self):
        # Create method was not returning the created object with
        # the create() method
        self.channel, new = Channel.objects.get_or_create(
            title=u'Monkey Island',
            description=u'The coolest pirate history ever',
        )

    def tearDown(self):
        self.channel.delete()

    def test_channel_fields(self):
        self.assertEqual(self.channel.title, u'Monkey Island')
        self.assertEqual(self.channel.slug, u'monkey-island')
        self.assertEqual(self.channel.description,
                         u'The coolest pirate history ever')

# coding: utf-8
from . import BaseTestCase

from ..models import Channel

class TestChannel(BaseTestCase):
    def setUp(self):
        # Create method was not returning the created object with
        # the create() method
        self.parent, new = Channel.objects.get_or_create(
            title=u'Father',
        )
        self.channel, new = Channel.objects.get_or_create(
            title=u'Monkey Island',
            description=u'The coolest pirate history ever',
            parent=self.parent,
            tags=['tag1', 'tag2'],
        )

    def tearDown(self):
        self.channel.delete()

    def test_channel_fields(self):
        self.assertEqual(self.channel.title, u'Monkey Island')
        self.assertEqual(self.channel.slug, u'monkey-island')
        self.assertEqual(self.channel.long_slug, u'father/monkey-island')
        self.assertEqual(self.channel.mpath, u',father,monkey-island,')
        self.assertEqual(self.channel.description,
                         u'The coolest pirate history ever')
        self.assertEqual(self.channel.tags, ['tag1', 'tag2'])
        self.assertEqual(self.channel.parent, self.parent)
        self.assertEqual(unicode(self.channel), u'father/monkey-island')

    def test_get_ancestors(self):
        self.assertEqual(list(self.channel.get_ancestors()), [self.channel,
                                                              self.parent])

    def test_get_ancestors_slug(self):
        self.assertEqual(self.channel.get_ancestors_slugs(),
                         [u'father/monkey-island', u'father'])

    def test_get_children(self):
        self.assertEqual(list(self.parent.get_children()), [self.channel])

    def test_get_descendants(self):
        self.assertEqual(list(self.parent.get_descendants()),
                         [self.parent, self.channel])

    def test_absolute_urls(self):
        self.assertEqual(self.channel.get_absolute_url(),
                         '/father/monkey-island/')
        self.assertEqual(self.parent.get_absolute_url(),
                         '/father/')

    def test_get_canonical_url(self):
        self.assertEqual(self.channel.get_canonical_url(),
                         '/father/monkey-island/')
        self.assertEqual(self.parent.get_canonical_url(),
                         '/father/')

Add more core tests / Rename test

Add more core tests / Rename test


try:
    from django.conf.urls import patterns, url
except ImportError:
    from django.conf.urls.defaults import patterns, url

urlpatterns = patterns(
    'robots.views',
    url(r'^$', 'rules_list', name='robots_rule_list'),
)

from django.conf.urls import url

from robots.views import rules_list

urlpatterns = [
    url(r'^$', rules_list, name='robots_rule_list'),
]

Fix warnings about URLconf in Django 1.9

* django.conf.urls.patterns will be removed in Django 1.10
* Passing a dotted path and not a view function will be deprecated in
  Django 1.10


import os

from flask import Flask
from flask.ext.assets import Bundle, Environment
from flask.ext.login import LoginManager
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)

# Load the app config
app.config.from_object("config.Config")

assets = Environment(app)
db= SQLAlchemy(app)

login = LoginManager()
login.init_app(app)

assets.load_path = [
    os.path.join(os.path.dirname(__file__), 'static'),
    os.path.join(os.path.dirname(__file__), 'static', 'bower_components')
]

assets.register(
    'js_all',
    Bundle(
        'jquery/dist/jquery.min.js',
        'bootstrap/dist/js/bootstrap.min.js',
        output='js_all.js'
    )
)

assets.register(
    'css_all',
    Bundle(
        'bootswatch/sandstone/bootstrap.css',
        'css/ignition.css',
        output='css_all.css'
    )
)

from manager.views import core
from manager.models import users

Add user table to module init

Add user table to module init


# -*- coding: utf-8 -*-
# vim: set ts=4

# Copyright 2013 Rémi Duraffort
# This file is part of RandoAmisSecours.
#
# RandoAmisSecours 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.
#
# RandoAmisSecours 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 RandoAmisSecours.  If not, see <http://www.gnu.org/licenses/>

from django.contrib import admin
from models import *

admin.site.register(FriendRequest)
admin.site.register(Outing)
admin.site.register(Profile)

# -*- coding: utf-8 -*-
# vim: set ts=4

# Copyright 2013 Rémi Duraffort
# This file is part of RandoAmisSecours.
#
# RandoAmisSecours 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.
#
# RandoAmisSecours 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 RandoAmisSecours.  If not, see <http://www.gnu.org/licenses/>

from django.contrib import admin
from RandoAmisSecours.models import *

admin.site.register(FriendRequest)
admin.site.register(Outing)
admin.site.register(Profile)

Fix import when using python3.3

Fix import when using python3.3


import logging

from functools import partial
from lala.util import command, msg
from twisted.internet.utils import getProcessOutput

@command
def fortune(user, channel, text):
    """Show a random, hopefully interesting, adage"""
    _call_fortune(user, channel)

@command
def ofortune(user, channel, text):
    """Show a random, hopefully interesting, offensive adage"""
    _call_fortune(user, channel, ["-o"])

def _call_fortune(user, channel, args=[]):
    """Call the ``fortune`` executable with ``args`` (a sequence of strings).
    """
    callback = partial(_send_output_to_channel, user, channel)
    errback = partial(_send_error_to_channel, user, channel)
    deferred = getProcessOutput("fortune", args)
    deferred.addCallback(callback)
    deferred.addErrback(errback)
    deferred.addErrback(logging.error)

def _send_output_to_channel(user, channel, text):
    msg(channel, "%s: %s" %(user, text.replace("\n","")))

def _send_error_to_channel(user, channel, exception):
    msg(channel, "%s: Sorry, no fortune for you today! Details are in the log." % user)
    return exception

import logging

from functools import partial
from lala.util import command, msg
from twisted.internet.utils import getProcessOutput

@command
def fortune(user, channel, text):
    """Show a random, hopefully interesting, adage"""
    _call_fortune(user, channel)

@command
def ofortune(user, channel, text):
    """Show a random, hopefully interesting, offensive adage"""
    _call_fortune(user, channel, ["-o"])

def _call_fortune(user, channel, args=[]):
    """Call the ``fortune`` executable with ``args`` (a sequence of strings).
    """
    callback = partial(_send_output_to_channel, user, channel)
    errback = partial(_send_error_to_channel, user, channel)
    deferred = getProcessOutput("fortune", args)
    deferred.addCallback(callback)
    deferred.addErrback(errback)
    deferred.addErrback(logging.error)

def _send_output_to_channel(user, channel, text):
    msg(channel, "%s: %s" %(user, text.replace("\n"," ")))

def _send_error_to_channel(user, channel, exception):
    msg(channel, "%s: Sorry, no fortune for you today! Details are in the log." % user)
    return exception

Replace newlines with spaces for readability


# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-05-01 16:41
from __future__ import unicode_literals

from django.db import migrations, models
import temba.utils.models

class Migration(migrations.Migration):

    dependencies = [
        ('msgs', '0093_populate_translatables'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='broadcast',
            name='language_dict',
        ),
        migrations.RemoveField(
            model_name='broadcast',
            name='media_dict',
        ),
        migrations.RemoveField(
            model_name='broadcast',
            name='text',
        ),
        migrations.AlterField(
            model_name='broadcast',
            name='base_language',
            field=models.CharField(help_text='The language used to send this to contacts without a language',
                                   max_length=4),
        ),
        migrations.AlterField(
            model_name='broadcast',
            name='translations',
            field=temba.utils.models.TranslatableField(help_text='The localized versions of the message text',
                                                       max_length=640, verbose_name='Translations'),
        ),
        migrations.RenameField(
            model_name='broadcast',
            old_name='translations',
            new_name='text',
        ),
    ]

# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-05-01 16:41
from __future__ import unicode_literals

from django.db import migrations, models
import temba.utils.models

class Migration(migrations.Migration):

    dependencies = [
        ('msgs', '0093_populate_translatables'),
    ]

    operations = [
        migrations.AlterField(
            model_name='broadcast',
            name='base_language',
            field=models.CharField(help_text='The language used to send this to contacts without a language',
                                   max_length=4),
        ),
        migrations.AlterField(
            model_name='broadcast',
            name='translations',
            field=temba.utils.models.TranslatableField(help_text='The localized versions of the message text',
                                                       max_length=640, verbose_name='Translations'),
        ),
        migrations.RemoveField(
            model_name='broadcast',
            name='language_dict',
        ),
        migrations.RemoveField(
            model_name='broadcast',
            name='media_dict',
        ),
        migrations.RemoveField(
            model_name='broadcast',
            name='text',
        ),
        migrations.RenameField(
            model_name='broadcast',
            old_name='translations',
            new_name='text',
        ),
    ]

Change order of operations within migration so breaking schema changes come last


# Copyright 2019 Akretion France <https://akretion.com/>
# @author: Alexis de Lattre <alexis.delattre@akretion.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

from odoo import _, models
from odoo.exceptions import UserError

class AccountMove(models.Model):
    _inherit = "account.move"

    def action_post(self):
        for move in self:
            for line in move.line_ids:
                if line.product_id and line.product_id.must_have_dates:
                    if not line.start_date or not line.end_date:
                        raise UserError(
                            _(
                                "Missing Start Date and End Date for invoice "
                                "line with Product '%s' which has the "
                                "property 'Must Have Start and End Dates'."
                            )
                            % (line.product_id.display_name)
                        )
        return super(AccountMove, self).action_post()

# Copyright 2019 Akretion France <https://akretion.com/>
# @author: Alexis de Lattre <alexis.delattre@akretion.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

from odoo import _, models
from odoo.exceptions import UserError

class AccountMove(models.Model):
    _inherit = "account.move"

    def action_post(self):
        for move in self:
            for line in move.line_ids:
                if line.product_id and line.product_id.must_have_dates:
                    if not line.start_date or not line.end_date:
                        raise UserError(
                            _(
                                "Missing Start Date and End Date for invoice "
                                "line with Product '%s' which has the "
                                "property 'Must Have Start and End Dates'."
                            )
                            % (line.product_id.display_name)
                        )
        return super().action_post()

Use super() instead of super(classname, self)


#!/usr/bin/env python3

# Touhou Community Reliant Automatic Patcher
# Scripts
#
# ----
#
"""Utility functions shared among all the scripts."""

from collections import OrderedDict
import json
import os

json_load_params = {
    'object_pairs_hook': OrderedDict
}

def patch_files_filter(files):
    """Filters all file names that can not be among the content of a patch."""
    for i in files:
        if i != 'files.js':
            yield i

json_dump_params = {
    'ensure_ascii': False,
    'indent': '\t',
    'separators': (',', ': '),
    'sort_keys': True
}

# Default parameters for JSON input and output
def json_load(fn):
    with open(fn, 'r', encoding='utf-8') as file:
        return json.load(file, **json_load_params)

def json_store(fn, obj, dirs=['']):
    """Saves the JSON object [obj] to [fn], creating all necessary
    directories in the process. If [dirs] is given, the function is
    executed for every root directory in the array."""
    for i in dirs:
        full_fn = os.path.join(i, fn)
        os.makedirs(os.path.dirname(full_fn), exist_ok=True)
        with open(full_fn, 'w', encoding='utf-8') as file:
            json.dump(obj, file, **json_dump_params)
            file.write('\n')

#!/usr/bin/env python3

# Touhou Community Reliant Automatic Patcher
# Scripts
#
# ----
#
"""Utility functions shared among all the scripts."""

from collections import OrderedDict
import json
import os

json_load_params = {
    'object_pairs_hook': OrderedDict
}

def patch_files_filter(files):
    """Filters all file names that can not be among the content of a patch."""
    for i in files:
        if i != 'files.js':
            yield i

json_dump_params = {
    'ensure_ascii': False,
    'indent': '\t',
    'separators': (',', ': '),
    'sort_keys': True
}

# Default parameters for JSON input and output
def json_load(fn, json_kwargs=json_load_params):
    with open(fn, 'r', encoding='utf-8') as file:
        return json.load(file, **json_kwargs)

def json_store(fn, obj, dirs=[''], json_kwargs=json_dump_params):
    """Saves the JSON object [obj] to [fn], creating all necessary
    directories in the process. If [dirs] is given, the function is
    executed for every root directory in the array."""
    for i in dirs:
        full_fn = os.path.join(i, fn)
        os.makedirs(os.path.dirname(full_fn), exist_ok=True)
        with open(full_fn, 'w', encoding='utf-8') as file:
            json.dump(obj, file, **json_kwargs)
            file.write('\n')

scripts: Allow to override the JSON loading and dumping parameters.


#!/usr/bin/env python
import sys
import h5py

infiles = sys.argv[1:]

for infile in infiles:
    with h5py.File(infile, 'a') as h5:
        print(infile)
        if 'format-version' in h5.attrs and h5.attrs['format-version'] < 1:

            if 'matrix' in h5 and not 'pixels' in h5:
                print('renaming matrix --> pixels')
                h5['pixels'] = h5['matrix']

            if 'scaffolds' in h5 and not 'chroms' in h5:
                print('renaming scaffolds --> chroms')
                h5['chroms'] = h5['scaffolds']

            h5.attrs['format-version'] = 1

#!/usr/bin/env python
import sys
import h5py

infiles = sys.argv[1:]

for infile in infiles:
    with h5py.File(infile, 'a') as h5:
        print(infile)
        if 'format-version' in h5.attrs and h5.attrs['format-version'] < 1:

            if 'matrix' in h5 and not 'pixels' in h5:
                print('renaming matrix --> pixels')
                h5['pixels'] = h5['matrix']
                del h5['matrix']

            if 'scaffolds' in h5 and not 'chroms' in h5:
                print('renaming scaffolds --> chroms')
                h5['chroms'] = h5['scaffolds']
                del h5['scaffolds']

            h5.attrs['format-version'] = 1

Drop old names from v0

Drop old names from v0


import logging
logging.basicConfig(level=logging.DEBUG)

import mdk_tracing
import time

import quark

tracer = mdk_tracing.Tracer.withURLsAndToken("ws://localhost:52690/ws", None, None)
# tracer = mdk_tracing.Tracer.withURLsAndToken("wss://tracing-develop.datawire.io/ws", None, None)

def goodHandler(result):
	# logging.info("Good!")

	for record in result:
		logging.info(record.toString())

def badHandler(result):
	logging.info("Failure: %s" % result.toString())

def formatLogRecord(record):
	return("%.3f %s %s" % (record.timestamp, record.record.level, record.record.text))

def poller(hrm=None):
	# logging.info("POLLING")

	tracer.poll() \
	      .andEither(goodHandler, badHandler) \
	      .andFinally(lambda x: quark.IO.schedule(1)) \
	      .andFinally(poller)

poller()

import logging
logging.basicConfig(level=logging.DEBUG)

import mdk_tracing
import time

import quark

# tracer = mdk_tracing.Tracer.withURLsAndToken("ws://localhost:52690/ws", None, None)
tracer = mdk_tracing.Tracer.withURLsAndToken("wss://tracing-develop.datawire.io/ws", None, None)

def goodHandler(result):
	# logging.info("Good!")

	for record in result:
		logging.info(record.toString())

def badHandler(result):
	logging.info("Failure: %s" % result.toString())

def formatLogRecord(record):
	return("%.3f %s %s" % (record.timestamp, record.record.level, record.record.text))

def poller(hrm=None):
	# logging.info("POLLING")

	tracer.poll() \
	      .andEither(goodHandler, badHandler) \
	      .andFinally(lambda x: quark.IO.schedule(1)) \
	      .andFinally(poller)

poller()

Switch console to use tracing-develop

Switch console to use tracing-develop


from twisted.trial.unittest import TestCase
import vumi.blinkenlights.message20110818 as message
import time

class TestMessage(TestCase):

    def test_to_dict(self):
        now = time.time()
        datapoint = ("vumi.w1.a_metric", now, 1.5)
        msg = message.MetricMessage()
        msg.append(datapoint)
        self.assertEqual(msg.to_dict(), {
            'datapoints': [datapoint],
            })

    def test_from_dict(self):
        now = time.time()
        datapoint = ("vumi.w1.a_metric", now, 1.5)
        msgdict = {"datapoints": [datapoint]}
        msg = message.MetricMessage.from_dict(msgdict)
        self.assertEqual(msg._datapoints, [datapoint])

    def test_extend(self):
        now = time.time()
        datapoint = ("vumi.w1.a_metric", now, 1.5)
        msg = message.MetricMessage()
        msg.extend([datapoint, datapoint, datapoint])
        self.assertEqual(msg._datapoints, [
            datapoint, datapoint, datapoint])

Add test for extend method.

Add test for extend method.


"""Render Jinja2 template."""
import logging
import os

import jinja2

LOG = logging.getLogger(__name__)

def get_template(template_file='', **kwargs):
    """Get the Jinja2 template and renders with dict _kwargs_.

    Args:
        kwargs: Keywords to use for rendering the Jinja2 template.

    Returns:
        String of rendered JSON template.
    """
    here = os.path.dirname(os.path.realpath(__file__))
    templatedir = '{0}/../templates/'.format(here)
    LOG.debug('Template directory: %s', templatedir)
    LOG.debug('Template file: %s', template_file)

    jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader(templatedir))
    template = jinjaenv.get_template(template_file)
    for k,v in kwargs.items():
        LOG.debug('%s => %s', k,v)
    rendered_json = template.render(**kwargs)

    LOG.debug('Rendered JSON:\n%s', rendered_json)
    return rendered_json

"""Render Jinja2 template."""
import logging
import os

import jinja2

LOG = logging.getLogger(__name__)

def get_template(template_file='', **kwargs):
    """Get the Jinja2 template and renders with dict _kwargs_.

    Args:
        kwargs: Keywords to use for rendering the Jinja2 template.

    Returns:
        String of rendered JSON template.
    """
    here = os.path.dirname(os.path.realpath(__file__))
    templatedir = '{0}/../templates/'.format(here)
    LOG.debug('Template directory: %s', templatedir)
    LOG.debug('Template file: %s', template_file)

    jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader(templatedir))
    template = jinjaenv.get_template(template_file)
    for key, value in kwargs.items():
        LOG.debug('%s => %s', key, value)
    rendered_json = template.render(**kwargs)

    LOG.debug('Rendered JSON:\n%s', rendered_json)
    return rendered_json

Use more descriptive variable names

style: Use more descriptive variable names

See also: PSOBAT-1197


from django.db import models

# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/

class Tag(models.Model):
    name = models.CharField(
        max_length=31, unique=True)
    slug = models.SlugField(
        max_length=31,
        unique=True,
        help_text='A label for URL config.')

class Startup(models.Model):
    name = models.CharField(max_length=31)
    slug = models.SlugField()
    description = models.TextField()
    founded_date = models.DateField()
    contact = models.EmailField()
    website = models.URLField()
    tags = models.ManyToManyField(Tag)

class NewsLink(models.Model):
    title = models.CharField(max_length=63)
    pub_date = models.DateField()
    link = models.URLField()
    startup = models.ForeignKey(Startup)

from django.db import models

# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/

class Tag(models.Model):
    name = models.CharField(
        max_length=31, unique=True)
    slug = models.SlugField(
        max_length=31,
        unique=True,
        help_text='A label for URL config.')

class Startup(models.Model):
    name = models.CharField(max_length=31)
    slug = models.SlugField()
    description = models.TextField()
    founded_date = models.DateField()
    contact = models.EmailField()
    website = models.URLField()
    tags = models.ManyToManyField(Tag)

class NewsLink(models.Model):
    title = models.CharField(max_length=63)
    pub_date = models.DateField('date published')
    link = models.URLField(max_length=255)
    startup = models.ForeignKey(Startup)

Add options to NewsLink model fields.

Ch03: Add options to NewsLink model fields. [skip ci]

Field options allow us to easily customize behavior of a field.

Verbose name documentation:

    https://docs.djangoproject.com/en/1.8/ref/models/fields/#verbose-name
    https://docs.djangoproject.com/en/1.8/topics/db/models/#verbose-field-names

The max_length field option is defined in CharField and inherited by all
CharField subclasses (but is typically optional in these subclasses,
unlike CharField itself).

The 255 character limit of the URLField is based on RFC 3986.

    https://tools.ietf.org/html/rfc3986


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import time

from watchdog.observers import Observer

from specchio.handlers import SpecchioEventHandler
from specchio.utils import init_logger, logger

def main():
    """Main function for specchio

    Example: specchio test/ user@host:test/

    :return: None
    """
    if len(sys.argv) == 3:
        src_path = sys.argv[1].strip()
        dst_ssh, dst_path = sys.argv[2].strip().split(":")
        event_handler = SpecchioEventHandler(
            src_path=src_path, dst_ssh=dst_path, dst_path=dst_path
        )
        init_logger()
        logger.info("Initialize Specchio")
        observer = Observer()
        observer.schedule(event_handler, src_path, recursive=True)
        observer.start()
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            observer.stop()
        observer.join()
    else:
        print """Specchio is a tool that can help you rsync your file,
it use `.gitignore` in git to discern which file is ignored.

Usage: specchio src/ user@host:dst"""

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import time

from watchdog.observers import Observer

from specchio.handlers import SpecchioEventHandler
from specchio.utils import init_logger, logger

def main():
    """Main function for specchio

    Example: specchio test/ user@host:test/

    :return: None
    """
    if len(sys.argv) == 3:
        src_path = sys.argv[1].strip()
        dst_ssh, dst_path = sys.argv[2].strip().split(":")
        event_handler = SpecchioEventHandler(
            src_path=src_path, dst_ssh=dst_path, dst_path=dst_path
        )
        init_logger()
        logger.info("Initialize Specchio")
        observer = Observer()
        observer.schedule(event_handler, src_path, recursive=True)
        observer.start()
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            observer.stop()
        observer.join()
    else:
        print """Usage: specchio src/ user@host:dst/"""

Fix the output when there is wrong usage


import logging.handlers

import coloredlogs

def configure(verbose=False):
    logging_level = logging.INFO if verbose else logging.DEBUG

    logging.captureWarnings(True)

    log_format = "%(asctime)-20s %(module)-11s %(levelname)-8s %(message)s"

    coloredlogs.install(
        level=logging_level,
        fmt=log_format
    )

    logger = logging.getLogger("virtool")

    handler = logging.handlers.RotatingFileHandler("virtool.log", maxBytes=1000000, backupCount=5)
    handler.setFormatter(logging.Formatter(log_format))

    logger.addHandler(handler)

    return logger

import logging.handlers

import coloredlogs

def configure(verbose=False):
    logging_level = logging.INFO if verbose else logging.DEBUG

    logging.captureWarnings(True)

    log_format = "%(asctime)-20s %(module)-11s %(levelname)-8s %(message)s"

    coloredlogs.install(
        level=logging_level,
        fmt=log_format
    )

    logger = logging.getLogger()

    handler = logging.handlers.RotatingFileHandler("virtool.log", maxBytes=1000000, backupCount=5)
    handler.setFormatter(logging.Formatter(log_format))

    logger.addHandler(handler)

    return logger

Write all log lines to log files

Write all log lines to log files

Only the virtool logger was being written before.


from django.views.generic import DetailView

from .models import Videodisc

class VideodiscDetailView(DetailView):
    model = Videodisc
    template_name = 'merchandise/media/videodisc_detail.html'

Create a small detail view for videodiscs.


from django.apps import AppConfig

class DomainsConfig(AppConfig):
    name = "domains"

from django.apps import AppConfig

class DomainsConfig(AppConfig):
    name = "feder.domains"

Fix DomainsConfig.name to fix rtfd build


from django import forms
from django.forms import widgets

from . import models

class ThreadCreateForm(forms.ModelForm):

    class Meta:
        model = models.Thread
        fields = ['title']

class MessageCreateForm(forms.ModelForm):

    class Meta:
        model = models.Message
        fields = ['body']

class TagFilterForm(forms.Form):
    tag = forms.ModelMultipleChoiceField(
        queryset=models.Tag.objects.all(),
        required=True,
        widget=widgets.CheckboxSelectMultiple
    )

from django import forms
from django.forms import widgets

from . import models

class ThreadCreateForm(forms.ModelForm):

    class Meta:
        model = models.Thread
        fields = ['title']

class MessageCreateForm(forms.ModelForm):

    class Meta:
        model = models.Message
        fields = ['body']

class TagFilterForm(forms.Form):
    tag = forms.ModelMultipleChoiceField(
        queryset=models.Tag.objects.all(),
        required=False,
        widget=widgets.CheckboxSelectMultiple
    )

Mark tags as not required in filter form


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

"""Import API modules."""

import t5x.adafactor
import t5x.checkpoints
import t5x.decoding
import t5x.gin_utils
import t5x.models
import t5x.multihost_utils
import t5x.partitioning
import t5x.state_utils
import t5x.train_state
import t5x.trainer
import t5x.utils

# Version number.
from t5x.version import __version__

# TODO(adarob): Move clients to t5x.checkpointing and rename
# checkpoints.py to checkpointing.py
checkpointing = t5x.checkpoints

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

"""Import API modules."""

import t5x.adafactor
import t5x.checkpoints
import t5x.decoding
import t5x.gin_utils
import t5x.losses
import t5x.models
import t5x.multihost_utils
import t5x.partitioning
import t5x.state_utils
import t5x.train_state
import t5x.trainer
import t5x.utils

# Version number.
from t5x.version import __version__

# TODO(adarob): Move clients to t5x.checkpointing and rename
# checkpoints.py to checkpointing.py
checkpointing = t5x.checkpoints

Add t5x.losses to public API.

Add t5x.losses to public API.

PiperOrigin-RevId: 417631806


from colorama import Fore
from pkgutil import iter_modules

def check_import(packagename):
    """
    Checks that a package is present. Returns true if it is available, and
    false if not available.
    """
    if packagename in (name for _, name, _ in iter_modules()):
        return True
    else:
        return False

packages = ['missingno', 'pytest', 'pytest_cov', 'tinydb', 'yaml',
            'pandas_summary', 'environment_kernels', 'hypothesis']

try:
    for pkg in packages:
        assert check_import(pkg)
    print(Fore.GREEN + 'All packages found; environment checks passed.')
except AssertionError:
    print(Fore.RED + f"{pkg} cannot be found. Please pip or conda install.")

from colorama import Fore, Style
from pkgutil import iter_modules

def check_import(packagename):
    """
    Checks that a package is present. Returns true if it is available, and
    false if not available.
    """
    if packagename in (name for _, name, _ in iter_modules()):
        return True
    else:
        return False

packages = ['missingno', 'pytest', 'pytest_cov', 'tinydb', 'yaml',
            'pandas_summary', 'environment_kernels', 'hypothesis']

try:
    for pkg in packages:
        assert check_import(pkg)
    print(Fore.GREEN + 'All packages found; environment checks passed.')
except AssertionError:
    print(Fore.RED + f"{pkg} cannot be found. Please pip or conda install.")

Style.RESET_ALL

Reset colors at the end

Reset colors at the end