Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Set README as the project long description | from setuptools import setup, find_packages
from wagtailnetlify import __version__
setup(
name='wagtailnetlify',
version=__version__,
description='Deploy Wagtail sites to Netlify',
long_description='See https://github.com/tomdyson/wagtail-netlify for details',
url='https://github.com/tomdyson/wagta... | from setuptools import setup, find_packages
from wagtailnetlify import __version__
with open('README.md', 'r') as fh:
long_description = fh.read()
setup(
name='wagtailnetlify',
version=__version__,
description='Deploy Wagtail sites to Netlify',
long_description=long_description,
long_descripti... |
Package data is not zip-safe | #!/usr/bin/python
from setuptools import setup, find_packages
from colorful import VERSION
github_url = 'https://github.com/charettes/django-colorful'
setup(
name='django-colorful',
version='.'.join(str(v) for v in VERSION),
description='An extension to the Django web framework that provides database an... | #!/usr/bin/python
from setuptools import setup, find_packages
from colorful import VERSION
github_url = 'https://github.com/charettes/django-colorful'
setup(
name='django-colorful',
version='.'.join(str(v) for v in VERSION),
description='An extension to the Django web framework that provides database an... |
Add python-dateutil as a project dependency. We need its handy "parse" function. | #!/usr/bin/env python3
import os
from setuptools import setup, find_packages
def get_readme():
return open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
setup(
author="Julio Gonzalez Altamirano",
author_email='devjga@gmail.com',
classifiers=[
'Intended Audience :: Developers',... | #!/usr/bin/env python3
import os
from setuptools import setup, find_packages
def get_readme():
return open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
setup(
author="Julio Gonzalez Altamirano",
author_email='devjga@gmail.com',
classifiers=[
'Intended Audience :: Developers',... |
Allow any newer pandas version | #! /usr/bin/env python
"""Setup information of demandlib.
"""
from setuptools import setup, find_packages
import os
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='demandlib',
version='0.1.7dev',
author='oemof developer group',
url='https://oem... | #! /usr/bin/env python
"""Setup information of demandlib.
"""
from setuptools import setup, find_packages
import os
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='demandlib',
version='0.1.7dev',
author='oemof developer group',
url='https://oem... |
Add long description to the project | from setuptools import setup, find_packages
setup(name='logs-analyzer',
version='0.5',
description='Logs-analyzer is a library containing functions that can help you extract usable data from logs.',
url='https://github.com/ddalu5/logs-analyzer',
author='Salah OSFOR',
author_email='osfor.... | from setuptools import setup, find_packages
with open("README.md", "r") as fh:
long_description = fh.read()
setup(name='logs-analyzer',
version='0.5.1',
description='Logs-analyzer is a library containing functions that can help you extract usable data from logs.',
long_description=long_descripti... |
Add dependencies, update for module name change | #! /usr/bin/env python
import os, glob
from distutils.core import setup
NAME = 'bacula_configuration'
VERSION = '0.1'
WEBSITE = 'http://gallew.org/bacula_configuration'
LICENSE = 'GPLv3 or later'
DESCRIPTION = 'Bacula configuration management tool'
LONG_DESCRIPTION = 'Bacula is a great backup tool, but ships with no w... | #! /usr/bin/env python
import os, glob
from distutils.core import setup
NAME = 'bacula_configuration'
VERSION = '0.1'
WEBSITE = 'http://gallew.org/bacula_configuration'
LICENSE = 'GPLv3 or later'
DESCRIPTION = 'Bacula configuration management tool'
LONG_DESCRIPTION = 'Bacula is a great backup tool, but ships with no w... |
Bring __VERSION__ inline with latest tag | __VERSION__ = "0.0.6"
__AUTHOR__ = "GDS Developers"
__AUTHOR_EMAIL__ = ""
| __VERSION__ = "0.0.8"
__AUTHOR__ = "GDS Developers"
__AUTHOR_EMAIL__ = ""
|
Remove unused ObjectDoesNotExist exception import | from django.core.exceptions import ObjectDoesNotExist
from django.core.management.base import BaseCommand, CommandError
from subscriptions.models import Subscription
class Command(BaseCommand):
help = ("Active subscription holders need to be informed via audio file "
"about the new missed call servic... | from django.core.management.base import BaseCommand, CommandError
from subscriptions.models import Subscription
class Command(BaseCommand):
help = ("Active subscription holders need to be informed via audio file "
"about the new missed call service.")
def add_arguments(self, parser):
par... |
Use os.name to detect OS | #!/usr/bin/env python
"""Setup script for MemeGen."""
import sys
import logging
import setuptools
from memegen import __project__, __version__
try:
README = open("README.rst").read()
CHANGELOG = open("CHANGELOG.rst").read()
except IOError:
DESCRIPTION = "<placeholder>"
else:
DESCRIPTION = README + ... | #!/usr/bin/env python
"""Setup script for MemeGen."""
import os
import logging
import setuptools
from memegen import __project__, __version__
try:
README = open("README.rst").read()
CHANGELOG = open("CHANGELOG.rst").read()
except IOError:
DESCRIPTION = "<placeholder>"
else:
DESCRIPTION = README + '... |
Add newer versions of Python 3.4 to classifier list. | from setuptools import setup, find_packages
import unormalize
import codecs
def long_description():
with codecs.open('README.rst', encoding='utf8') as f:
return f.read()
setup(
name='unormalize',
version=unormalize.__version__,
description=unormalize.__doc__.strip(),
long_description=lon... | from setuptools import setup, find_packages
import unormalize
import codecs
def long_description():
with codecs.open('README.rst', encoding='utf8') as f:
return f.read()
setup(
name='unormalize',
version=unormalize.__version__,
description=unormalize.__doc__.strip(),
long_description=lon... |
Fix django model field docstring. | """
******************
Django integration
******************
**Static Model** provides two custom Django model fields in the
``staticmodel.django.fields`` module:
* ``StaticModelCharField`` (sub-class of ``django.db.models.CharField``)
* ``StaticModelIntegerField`` (sub-class of ``django.db.models.IntegerField``)
... | """
************************
Django model integration
************************
**Static Model** provides custom Django model fields in the
``staticmodel.django.models`` package:
* ``StaticModelCharField`` (sub-class of ``django.db.models.CharField``)
* ``StaticModelTextField`` (sub-class of ``django.db.models.TextF... |
Extend list of supported python versions | #!/usr/bin/env python
from distutils.core import setup
from os.path import dirname, join
from codecs import open
setup(name='hashids',
version='1.1.0',
description='Python implementation of hashids (http://www.hashids.org).'
'Compatible with python 2.6-3.',
long_description=open(joi... | #!/usr/bin/env python
from distutils.core import setup
from os.path import dirname, join
from codecs import open
setup(name='hashids',
version='1.1.0',
description='Python implementation of hashids (http://www.hashids.org).'
'Compatible with python 2.6-3.',
long_description=open(joi... |
Update dependency on annotator -> 0.7.3 to fix datetime decoder bug. | from setuptools import setup, find_packages
setup(
name = 'annotateit',
version = '2.1.2',
packages = find_packages(),
install_requires = [
'annotator==0.7.2',
'Flask==0.8',
'Flask-Mail==0.6.1',
'Flask-SQLAlchemy==0.15',
'Flask-WTF==0.5.4',
'SQLAlchemy==... | from setuptools import setup, find_packages
setup(
name = 'annotateit',
version = '2.1.2',
packages = find_packages(),
install_requires = [
'annotator==0.7.3',
'Flask==0.8',
'Flask-Mail==0.6.1',
'Flask-SQLAlchemy==0.15',
'Flask-WTF==0.5.4',
'SQLAlchemy==... |
Clean up a little bit | from setuptools import setup
from fdep import __VERSION__
try:
ldsc = open("README.md").read()
except:
ldsc = ""
setup(
name="fdep",
packages=['fdep'],
version=__VERSION__,
author="Checkr",
author_email="eng@checkr.com",
url="http://github.com/checkr/fdep",
license="MIT LICENSE",
... | from setuptools import setup
from fdep import __VERSION__
try:
ldsc = open("README.md").read()
except:
ldsc = ""
setup(
name="fdep",
packages=['fdep'],
version=__VERSION__,
author="Checkr",
author_email="eng@checkr.com",
url="http://github.com/checkr/fdep",
license="MIT LICENSE",
... |
Upgrade to sendmail 4.3, fixed old bug with transaction | from setuptools import setup, find_packages
import sys, os
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.rst')).read()
except IOError:
README = ''
version = "0.1.0"
test_requirements = [
'nose',
'webtest',
]
setup(name='tgext.mailer',
version=versi... | from setuptools import setup, find_packages
import sys, os
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.rst')).read()
except IOError:
README = ''
version = "0.1.0"
test_requirements = [
'nose',
'webtest',
]
setup(name='tgext.mailer',
version=versi... |
Change development status from alpha to beta | from distutils.core import setup
import pykka
setup(
name='Pykka',
version=pykka.get_version(),
author='Stein Magnus Jodal',
author_email='stein.magnus@jodal.no',
packages=['pykka'],
url='http://jodal.github.com/pykka/',
license='Apache License, Version 2.0',
description='Pykka is easy... | from distutils.core import setup
import pykka
setup(
name='Pykka',
version=pykka.get_version(),
author='Stein Magnus Jodal',
author_email='stein.magnus@jodal.no',
packages=['pykka'],
url='http://jodal.github.com/pykka/',
license='Apache License, Version 2.0',
description='Pykka is easy... |
Install requires pycryptodome, not pycrypto | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('pandoc -o README.rst README.md')
os.system('python setup.py sdist upload')
sys.exit()
README = open(... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('pandoc -o README.rst README.md')
os.system('python setup.py sdist upload')
sys.exit()
README = open(... |
Fix package name in entry point | #!/usr/bin/env python
import sys
from setuptools import find_packages, setup
install_requires = ['robotframework']
if sys.version_info < (2, 7):
install_requires.append('argparse')
setup(
name='pre_commit_robotframework_tidy',
description='A pre-commit hook to run Robot Framework\'s tidy tool.',
ur... | #!/usr/bin/env python
import sys
from setuptools import find_packages, setup
install_requires = ['robotframework']
if sys.version_info < (2, 7):
install_requires.append('argparse')
setup(
name='pre_commit_robotframework_tidy',
description='A pre-commit hook to run Robot Framework\'s tidy tool.',
ur... |
Set GLib prgname and application name | from __future__ import absolute_import, print_function, unicode_literals
import sys
import textwrap
try:
import gi
gi.require_version('Gst', '1.0')
from gi.repository import GLib, GObject, Gst
except ImportError:
print(textwrap.dedent("""
ERROR: A GObject Python package was not found.
... | from __future__ import absolute_import, print_function, unicode_literals
import sys
import textwrap
try:
import gi
gi.require_version('Gst', '1.0')
from gi.repository import GLib, GObject, Gst
except ImportError:
print(textwrap.dedent("""
ERROR: A GObject Python package was not found.
... |
Fix 'unbuffered' test that somehow got broken | # Copyright (c) 2012 - 2014 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
import sys
from .framework import api_select
from jenkinsflow.flow import serial
from jenkinsflow.unbuffered import UnBuffered
def test_unbuffered():
sys.stdout = UnBuffered(s... | # Copyright (c) 2012 - 2014 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
import sys
from .framework import api_select
from jenkinsflow.flow import serial
from jenkinsflow.unbuffered import UnBuffered
def test_unbuffered():
sys.stdout = UnBuffered(s... |
Remove gc3pie session dir from config | import datetime
# Override this key with a secret one
SECRET_KEY = 'default_secret_key'
HASHIDS_SALT = 'default_secret_salt'
# This should be set to true in the production config when using NGINX
USE_X_SENDFILE = False
DEBUG = True
JWT_EXPIRATION_DELTA = datetime.timedelta(days=2)
JWT_NOT_BEFORE_DELTA = datetime.tim... | import datetime
# Override this key with a secret one
SECRET_KEY = 'default_secret_key'
HASHIDS_SALT = 'default_secret_salt'
# This should be set to true in the production config when using NGINX
USE_X_SENDFILE = False
DEBUG = True
JWT_EXPIRATION_DELTA = datetime.timedelta(days=2)
JWT_NOT_BEFORE_DELTA = datetime.tim... |
Remove h5py from pytest header | # this contains imports plugins that configure py.test for astropy tests.
# by importing them here in conftest.py they are discoverable by py.test
# no matter how it is invoked within the source tree.
from astropy.tests.pytest_plugins import *
## Uncomment the following line to treat all DeprecationWarnings as
## exc... | # this contains imports plugins that configure py.test for astropy tests.
# by importing them here in conftest.py they are discoverable by py.test
# no matter how it is invoked within the source tree.
from astropy.tests.pytest_plugins import *
## Uncomment the following line to treat all DeprecationWarnings as
## exc... |
FIX fiscal position no source tax on v7 api | from openerp import models, api, fields
class account_fiscal_position(models.Model):
_inherit = 'account.fiscal.position'
@api.v8 # noqa
def map_tax(self, taxes):
result = super(account_fiscal_position, self).map_tax(taxes)
taxes_without_src_ids = [
x.tax_dest_id.id for x... | from openerp import models, api, fields
class account_fiscal_position(models.Model):
_inherit = 'account.fiscal.position'
@api.v7
def map_tax(self, cr, uid, fposition_id, taxes, context=None):
result = super(account_fiscal_position, self).map_tax(
cr, uid, fposition_id, taxes, contex... |
Remove uniqueness of the order field | from django.db import models
from django.core.exceptions import ValidationError
class OrderedModel(models.Model):
order = models.PositiveIntegerField(blank=True, unique=True)
class Meta:
abstract = True
ordering = ['order']
def save(self, swapping=False, *args, **kwargs):
if not ... | from django.db import models
from django.core.exceptions import ValidationError
class OrderedModel(models.Model):
order = models.PositiveIntegerField(blank=True, default=1)
class Meta:
abstract = True
ordering = ['order']
def save(self, swapping=False, *args, **kwargs):
if not se... |
Add plain Python 2 and 3 to package metadata | import os
import setuptools
setuptools.setup(
name='factory_djoy',
version='0.5',
description='Factories for Django, creating valid instances every time',
url='http://github.com/jamescooke/factory_djoy',
author='James Cooke',
author_email='github@jamescooke.info',
license='MIT',
pac... | import os
import setuptools
setuptools.setup(
name='factory_djoy',
version='0.5',
description='Factories for Django, creating valid instances every time',
url='http://github.com/jamescooke/factory_djoy',
author='James Cooke',
author_email='github@jamescooke.info',
license='MIT',
pac... |
Make sur the rgb values are within [0, 255] range. | from .module import Module, interact
class Led(Module):
def __init__(self, id, alias, robot):
Module.__init__(self, 'LED', id, alias, robot)
self.color = (0, 0, 0)
@property
def color(self):
return self._value
@color.setter
def color(self, new_color):
if new_color... | from .module import Module, interact
class Led(Module):
def __init__(self, id, alias, robot):
Module.__init__(self, 'LED', id, alias, robot)
self.color = (0, 0, 0)
@property
def color(self):
return self._value
@color.setter
def color(self, new_color):
new_color = ... |
Add python_requires to help pip | #!/usr/bin/env python
import setuptools
setuptools.setup(
setup_requires=['pbr>=1.3', 'setuptools>=17.1'],
pbr=True)
| #!/usr/bin/env python
import setuptools
setuptools.setup(
setup_requires=['pbr>=1.3', 'setuptools>=17.1'],
python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*',
pbr=True)
|
Fix tfx-bsl error due to pyarrow package version requirement. | # Lint as: python3
# Copyright 2020 Google LLC.
#
# 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 a... | # Lint as: python3
# Copyright 2020 Google LLC.
#
# 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 a... |
Apply same fix as in 77a463b50a | from setuptools import setup
setup(
name="pptrees",
version="0.0.2",
description="Parallel Prefix tree generation library",
url="https://github.com/tdene/synth_opt_adders",
author="tdene",
author_email="teodord.ene@gmail.com",
license="Apache 2.0",
classifiers=[
"Development Sta... | from setuptools import setup, find_namespace_packages
setup(
name="pptrees",
version="0.0.2",
description="Parallel Prefix tree generation library",
url="https://github.com/tdene/synth_opt_adders",
author="tdene",
author_email="teodord.ene@gmail.com",
license="Apache 2.0",
classifiers=[... |
Set application name to "Lunasa Prismriver" | import sys
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication
from prismriver.qt.window import MainWindow
from prismriver import util
def run():
util.init_logging(False, True, None)
app = QApplication(sys.argv)
app.setWindowIcon(QIcon('prismriver/pixmaps/prismriver-lunasa.png'))
... | import sys
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication
from prismriver.qt.window import MainWindow
from prismriver import util
def run():
util.init_logging(False, True, None)
app = QApplication(sys.argv)
app.setWindowIcon(QIcon('prismriver/pixmaps/prismriver-lunasa.png'))
... |
Make pycrest mesh viz more capable | import matplotlib.pyplot as plt
from matplotlib.pyplot import triplot
from mpl_toolkits.mplot3d import Axes3D
from pycrest.mesh import Mesh2d
def plot_triangulation(tri: Mesh2d, standalone=True, *args, **kwargs):
figure = plt.figure() if standalone else None
triplot(tri.vertices[:, 0], tri.vertices[:, 1], tr... | import matplotlib.pyplot as plt
from matplotlib.pyplot import triplot
from mpl_toolkits.mplot3d import Axes3D
from pycrest.mesh import Mesh2d
def plot_triangulation(tri: Mesh2d, standalone=True, *args, **kwargs):
figure = plt.figure() if standalone else None
triplot(tri.vertices[:, 0], tri.vertices[:, 1], tr... |
Remove looping through items and appending them to list. | import sys
import boto3
BUCKET_NAME = 'mitLookit'
def get_all_study_attachments(study_uuid):
s3 = boto3.resource('s3')
bucket = s3.Bucket(BUCKET_NAME)
study_files = []
for key in bucket.objects.filter(Prefix=f'videoStream_{study_uuid}'):
study_files.append(key)
return study_files
if __na... | import sys
import boto3
BUCKET_NAME = 'mitLookit'
def get_all_study_attachments(study_uuid):
s3 = boto3.resource('s3')
bucket = s3.Bucket(BUCKET_NAME)
return bucket.objects.filter(Prefix=f'videoStream_{study_uuid}')
if __name__ == '__main__':
study_uuid = sys.argv[1]
get_study_keys(study_uuid)
|
Set depth for Lake Superior | #!/usr/bin/env python
"""
Reduced Gravity Shallow Water Model
based Matlab code by: Francois Primeau UC Irvine 2011
Kelsey Jordahl
kjordahl@enthought.com
Time-stamp: <Tue Apr 10 08:44:50 EDT 2012>
"""
from scipy.io.netcdf import netcdf_file
from ocean_model import ShallowWaterModel, OceanPlot
from traits.api import I... | #!/usr/bin/env python
"""
Reduced Gravity Shallow Water Model
based Matlab code by: Francois Primeau UC Irvine 2011
Kelsey Jordahl
kjordahl@enthought.com
Time-stamp: <Tue Apr 10 10:42:40 EDT 2012>
"""
from scipy.io.netcdf import netcdf_file
from ocean_model import ShallowWaterModel, OceanPlot
from traits.api import I... |
Revert "Hago un strip del output de subprocess" | #! coding: utf-8
import subprocess
import nose.tools as nt
from tests import TestPortalAndino
class TestFileSizeLimit(TestPortalAndino.TestPortalAndino):
@classmethod
def setUpClass(cls):
super(TestFileSizeLimit, cls).setUpClass()
def test_nginx_configuration_uses_1024_MB_as_file_size_limit(sel... | #! coding: utf-8
import subprocess
import nose.tools as nt
from tests import TestPortalAndino
class TestFileSizeLimit(TestPortalAndino.TestPortalAndino):
@classmethod
def setUpClass(cls):
super(TestFileSizeLimit, cls).setUpClass()
def test_nginx_configuration_uses_1024_MB_as_file_size_limit(sel... |
Remove vim header from source files | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# All Rights Reserved.
#
# 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://... | # Copyright 2013 Hewlett-Packard Development Company, L.P.
# All Rights Reserved.
#
# 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
#
# Unles... |
Fix tests for new index. | import os
import unittest
from application.default_settings import _basedir
from application import app, db
class ManagerTestCase(unittest.TestCase):
""" setup and teardown for the testing database """
def setUp(self):
create_db_dir = _basedir + '/db'
if not os.path.exists(create_db_dir):
... | import os
import unittest
from application.default_settings import _basedir
from application import app, db
class ManagerTestCase(unittest.TestCase):
""" setup and teardown for the testing database """
def setUp(self):
create_db_dir = _basedir + '/db'
if not os.path.exists(create_db_dir):
... |
Fix mistake in path in warning when config file is missing | import ConfigParser
import os
import yaml
class Database(object):
""" Generic class for handling database-related tasks. """
def select_config_for_environment(self):
""" Read the value of env variable and load the property
database configuration based on the value of DB_ENV.
Takes no ... | import ConfigParser
import os
import yaml
class Database(object):
""" Generic class for handling database-related tasks. """
def select_config_for_environment(self):
""" Read the value of env variable and load the property
database configuration based on the value of DB_ENV.
Takes no ... |
Change replacement string of named entity filth | from .base import Filth
class NamedEntityFilth(Filth):
"""
Named entity filth. Upon initialisation provide a label for named entity (e.g. name, org)
"""
type = 'named_entity'
def __init__(self, *args, label: str, **kwargs):
super(NamedEntityFilth, self).__init__(*args, **kwargs)
s... | from .base import Filth
class NamedEntityFilth(Filth):
"""
Named entity filth. Upon initialisation provide a label for named entity (e.g. name, org)
"""
type = 'named_entity'
def __init__(self, *args, label: str, **kwargs):
super(NamedEntityFilth, self).__init__(*args, **kwargs)
s... |
Move the SERVER_NAME to the start of the default config | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
# The URI for our PostgreSQL database.
SQLALCHEMY_DATABASE_URI = "postgres:///warehouse"
# The base domain name for this installation. Used to control linking to
# sub-domains.
SERVER_NAME = "warehouse.... | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
# The base domain name for this installation. Used to control linking to
# sub-domains.
SERVER_NAME = "warehouse.local"
# The URI for our PostgreSQL database.
SQLALCHEMY_DATABASE_URI = "postgres:///ware... |
Add Flask app variable to use with gunicorn | # TODO: migrate to Flask CLI instead of Flask-Script
'''This module enables command line interface for randompeople app.'''
from flask_script import Manager
from app import create_app, db
from app.models import Room, Member
manager = Manager(create_app)
@manager.shell
def make_shell_context():
''''''
return d... | # TODO: migrate to Flask CLI instead of Flask-Script
'''This module enables command line interface for randompeople app.'''
from flask_script import Manager
from app import create_app, db
from app.models import Room, Member
app = create_app()
manager = Manager(app)
@manager.shell
def make_shell_context():
''''''
... |
Change the default value for SELENIUM_SERVER | """
Central configuration module of webstr selenium tests.
This module provides configuration options along with default values and
function to redefine values.
"""
# Copyright 2016 Red Hat
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Li... | """
Central configuration module of webstr selenium tests.
This module provides configuration options along with default values and
function to redefine values.
"""
# Copyright 2016 Red Hat
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Li... |
Enhance swf errors wrapping via an exception helper | # -*- coding: utf-8 -*-
# Copyright (c) 2013, Theo Crevon
# Copyright (c) 2013, Greg Leclercq
#
# See the file LICENSE for copying permission.
class PollTimeout(Exception):
pass
class InvalidCredentialsError(Exception):
pass
class ResponseError(Exception):
pass
class DoesNotExistError(Exception):
... | # -*- coding: utf-8 -*-
# Copyright (c) 2013, Theo Crevon
# Copyright (c) 2013, Greg Leclercq
#
# See the file LICENSE for copying permission.
class SWFError(Exception):
def __init__(self, message, raw_error, *args):
Exception.__init__(self, message, *args)
self.kind, self.details = raw_error.spli... |
Remove ability to run module directly | #!/usr/bin/env python
"""{{ cookiecutter.description }}"""
# Copyright (C) {{cookiecutter.year}} {{cookiecutter.author_name}}. See LICENSE for terms of use.
import sys
import logging
import click
from click import echo
__version__ = '{{ cookiecutter.version }}'
@click.command()
@click.help_option('--help', '-h')
@c... | #!/usr/bin/env python
"""{{ cookiecutter.description }}"""
# Copyright (C) {{cookiecutter.year}} {{cookiecutter.author_name}}. See LICENSE for terms of use.
import sys
import logging
import click
from click import echo
__version__ = '{{ cookiecutter.version }}'
@click.command()
@click.help_option('--help', '-h')
@c... |
Remove test data folder with contents | import logging
import unittest
import os
from sqlalchemy import create_engine
from rtrss import config, database
logging.disable(logging.ERROR)
engine = create_engine(config.SQLALCHEMY_DATABASE_URI,
echo=False,
client_encoding='utf8')
# Reconfigure session factory to u... | import logging
import unittest
import os
import shutil
from sqlalchemy import create_engine
from rtrss import config, database
logging.disable(logging.ERROR)
engine = create_engine(config.SQLALCHEMY_DATABASE_URI,
echo=False,
client_encoding='utf8')
# Reconfigure sessio... |
Add and remove now work with minimal error checking. | #!/usr/bin/env python
# My solution to the following challenge: https://redd.it/39ws1x
from datetime import date
from collections import defaultdict
class Todo:
def __init__(self):
self.items = defaultdict(list)
def add_item(self, item, tag):
self.items[tag].append(item)
def remove_item(... | #!/usr/bin/env python
# My solution to the following challenge: https://redd.it/39ws1x
import os
from datetime import date
from collections import defaultdict
home = os.path.expanduser('~')
class Todo:
def __init__(self):
self.items = defaultdict(list)
def __load_items(self):
try:
... |
Fix the option and update the note | # Copyright (c) Metakernel Development Team.
# Distributed under the terms of the Modified BSD License.
from metakernel import Magic, option
class PlotMagic(Magic):
@option(
'-s', '--size', action='store',
help='Pixel size of plots, "width,height"'
)
@option(
'-f', '--format', ac... | # Copyright (c) Metakernel Development Team.
# Distributed under the terms of the Modified BSD License.
from metakernel import Magic, option
class PlotMagic(Magic):
@option(
'-s', '--size', action='store',
help='Pixel size of plots, "width,height"'
)
@option(
'-f', '--format', ac... |
Correct meervoud modellen van appolo | from django.db import models
class Locatie(models.Model):
def __unicode__(self):
return self.naam
naam = models.CharField(max_length=200)
lat = models.FloatField()
long = models.FloatField()
class Dag(models.Model):
def __unicode__(self):
return unicode(self.datum)
datum = mode... | from django.db import models
class Locatie(models.Model):
def __unicode__(self):
return self.naam
naam = models.CharField(max_length=200)
lat = models.FloatField()
long = models.FloatField()
class Meta:
verbose_name_plural = 'locaties'
class Dag(models.Model):
def __unicode__(... |
Add errors attribute with setter/getter | __version__ = (2014, 10, 0)
def get_version():
"""
:rtype: str
"""
return '.'.join(str(i) for i in __version__)
class Gignore(object):
BASE_URL = 'https://raw.githubusercontent.com/github/gitignore/master/'
name = None
file_content = None
valid = True
def get_base_url(self):
... | __version__ = (2014, 10, 0)
def get_version():
"""
:rtype: str
"""
return '.'.join(str(i) for i in __version__)
class Gignore(object):
BASE_URL = 'https://raw.githubusercontent.com/github/gitignore/master/'
name = None
file_content = None
valid = True
errors = []
def get_bas... |
Fix app error handler raising an attribute error | from flask import jsonify
from . import main
from ..models import ValidationError
@main.app_errorhandler(ValidationError)
def validatation_error(e):
return jsonify(error=e.message), 400
def generic_error_handler(e):
# TODO: log the error
headers = []
error = e.description
if e.code == 401:
... | from flask import jsonify
from . import main
from ..models import ValidationError
@main.app_errorhandler(ValidationError)
def validatation_error(e):
return jsonify(error=e.message), 400
def generic_error_handler(e):
headers = []
code = getattr(e, 'code', 500)
error = getattr(e, 'description', 'Inte... |
Test self request without authentication | from uuid import uuid4
from changes.config import db
from changes.models import Author
from changes.testutils import APITestCase
class AuthorBuildListTest(APITestCase):
def test_simple(self):
fake_author_id = uuid4()
self.create_build(self.project)
path = '/api/0/authors/{0}/builds/'.fo... | from uuid import uuid4
from changes.config import db
from changes.models import Author
from changes.testutils import APITestCase
class AuthorBuildListTest(APITestCase):
def test_simple(self):
fake_author_id = uuid4()
self.create_build(self.project)
path = '/api/0/authors/{0}/builds/'.fo... |
Use DATABASE_URL instead of CLEARDB_DATABASE_URL | import os
#
# This is the configuration file of the application
#
# Please make sure you don't store here any secret information and use environment
# variables
#
SQLALCHEMY_DATABASE_URI = os.environ.get('CLEARDB_DATABASE_URL')
SQLALCHEMY_POOL_RECYCLE = 60
SECRET_KEY = 'aiosdjsaodjoidjioewnioewfnoeijfoisdjf'
FACE... | import os
#
# This is the configuration file of the application
#
# Please make sure you don't store here any secret information and use environment
# variables
#
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL')
SQLALCHEMY_POOL_RECYCLE = 60
SECRET_KEY = 'aiosdjsaodjoidjioewnioewfnoeijfoisdjf'
FACEBOOK_KEY... |
Set minimum query length to 10 nts | """
Copyright [2009-2014] EMBL-European Bioinformatics Institute
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 a... | """
Copyright [2009-2014] EMBL-European Bioinformatics Institute
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 a... |
Add SQLALCHEMY_TRACK_MODIFICATION to supress warnings | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = 'f63f65a3f7274455bfd49edf9c6b36bd'
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
@staticmethod
def init_app(app):
pass
class DevelopmentConfig(Config):
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'sqlite:///... | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = 'f63f65a3f7274455bfd49edf9c6b36bd'
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
SQLALCHEMY_TRACK_MODIFICATIONS = False
@staticmethod
def init_app(app):
pass
class DevelopmentConfig(Config):
DEBUG = Tru... |
Fix script to update offering on instances | # coding: utf-8
class UpdateInstances(object):
@staticmethod
def do():
from dbaas_cloudstack.models import DatabaseInfraOffering
from dbaas_cloudstack.models import PlanAttr
infra_offerings = DatabaseInfraOffering.objects.all()
for infra_offering in infra_offerings:
... | # coding: utf-8
class UpdateInstances(object):
@staticmethod
def do():
from dbaas_cloudstack.models import DatabaseInfraOffering
from dbaas_cloudstack.models import PlanAttr
infra_offerings = DatabaseInfraOffering.objects.all()
for infra_offering in infra_offerings:
... |
Fix the database session init to work with the flask debug server. | from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
session = None
def init_session(connection_string=None, drop=False):
if connection_string is None:
connection_string = 'sqlite://'
from database.model import Base
global session
if drop:
t... | from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.pool import StaticPool
session = None
def init_session(connection_string=None, drop=False):
if connection_string is None:
engine = create_engine('sqlite://',
echo... |
Fix virtualenv path on PythonAnywhere | #!/usr/bin/env python
import argparse
import os
import requests
my_domain = "www.proporti.onl"
username = "emptysquare"
parser = argparse.ArgumentParser()
parser.add_argument(
"token",
metavar="PYTHON_ANYWHERE_TOKEN",
help="A Python Anywhere API token for your account",
)
args = parser.parse_args()
pri... | #!/usr/bin/env python
import argparse
import os
import requests
my_domain = "www.proporti.onl"
username = "emptysquare"
parser = argparse.ArgumentParser()
parser.add_argument(
"token",
metavar="PYTHON_ANYWHERE_TOKEN",
help="A Python Anywhere API token for your account",
)
args = parser.parse_args()
pri... |
Rename some copy pasted variable. | from graphql.core.type import GraphQLScalarType
class ScalarMeta(type):
def __new__(mcs, name, bases, attrs):
if attrs.pop('abstract', False):
return super(ScalarMeta, mcs).__new__(mcs, name, bases, attrs)
registry = mcs._get_registry()
cls = super(ScalarMeta, mcs).__new__(mc... | from graphql.core.type import GraphQLScalarType
class ScalarMeta(type):
def __new__(mcs, name, bases, attrs):
if attrs.pop('abstract', False):
return super(ScalarMeta, mcs).__new__(mcs, name, bases, attrs)
registry = mcs._get_registry()
cls = super(ScalarMeta, mcs).__new__(mc... |
Add new user form data to db | from flask import Flask, render_template, request
from models import db
from forms import SignupForm
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://localhost/strabo'
db.init_app(app)
app.secret_key = ""
@app.route("/")
def index():
return render_template("index.html")
@app.route("/ab... | from flask import Flask, render_template, request
from models import db, User
from forms import SignupForm
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://localhost/strabo'
db.init_app(app)
app.secret_key = ""
@app.route("/")
def index():
return render_template("index.html")
@app.rout... |
Remove the "3" from SublimeLinter3 | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jon LaBelle
# Copyright (c) 2018 Jon LaBelle
#
# License: MIT
#
"""This module exports the Markdownlint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Markdownlint(NodeLinter):
"""Provi... | #
# linter.py
# Markdown Linter for SublimeLinter, a code checking framework
# for Sublime Text 3
#
# Written by Jon LaBelle
# Copyright (c) 2018 Jon LaBelle
#
# License: MIT
#
"""This module exports the Markdownlint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Markdownlint(NodeLinter):
... |
Set log level to 2 when migrating so there is some indication it is running | #!/usr/bin/python
# Copyright (c) 2006 rPath, Inc
# All rights reserved
import sys
import os
import pwd
from conary.server import schema
from conary.lib import cfgtypes
from conary.repository.netrepos.netserver import ServerConfig
from conary import dbstore
cnrPath = '/srv/conary/repository.cnr'
cfg = ServerConfig(... | #!/usr/bin/python
# Copyright (c) 2006 rPath, Inc
# All rights reserved
import sys
import os
import pwd
from conary.server import schema
from conary.lib import cfgtypes, tracelog
from conary.repository.netrepos.netserver import ServerConfig
from conary import dbstore
cnrPath = '/srv/conary/repository.cnr'
cfg = Ser... |
Rename bot and prevent channel spamming | import os
import requests
from django.core.mail import send_mail
from clowder_account.models import ClowderUser
ADMIN_EMAIL = 'admin@clowder.io'
def send_alert(company, name):
for user in ClowderUser.objects.filter(company=company, allow_email_notifications=True):
subject = 'FAILURE: %s' % (name)
... | import os
import requests
from django.core.mail import send_mail
from clowder_account.models import ClowderUser
ADMIN_EMAIL = 'admin@clowder.io'
def send_alert(company, name):
slack_sent = False
for user in ClowderUser.objects.filter(company=company, allow_email_notifications=True):
subject = 'FAILUR... |
Allow altering the donation amount via a link and default to £3 | from django.http import HttpResponseRedirect
from .forms import DonationForm
from .helpers import GoCardlessHelper
class DonationFormMiddleware(object):
def get_initial(self):
return {
'payment_type': 'subscription',
'amount': 10,
}
def form_valid(self, request, form)... | from django.http import HttpResponseRedirect
from .forms import DonationForm
from .helpers import GoCardlessHelper, PAYMENT_UNITS
class DonationFormMiddleware(object):
def get_initial(self, request):
suggested_donation = request.GET.get('suggested_donation', 3)
form_initial = {
'payme... |
Add test case for read_arrange_mode() | from arrange_schedule import *
def test_read_system_setting():
keys = ['board_py_dir','shutdown','max_db_log','min_db_activity']
system_setting = read_system_setting()
for key in keys:
assert key in system_setting
return system_setting
def test_crawler_cwb_img(system_setting):
send_msg = ... | from arrange_schedule import *
def test_read_system_setting():
keys = ['board_py_dir','shutdown','max_db_log','min_db_activity']
system_setting = read_system_setting()
for key in keys:
assert key in system_setting
return system_setting
def test_read_arrange_mode():
keys = ['arrange_sn','a... |
Remove debug flag from app | from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run(debug=True)
| from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
|
Fix reference to static var | #! usr/bin/env python3
from docopt import docopt
from matplotlib import pyplot
import re
class Schema:
"""
Wraps the SQL source code for a schema and provides methods to get information about that schema.
"""
table_def = re.compile(r"CREATE TABLE|create table")
def __init__(self, source):
... | #! usr/bin/env python3
from docopt import docopt
from matplotlib import pyplot
import re
class Schema:
"""
Wraps the SQL source code for a schema and provides methods to get information about that schema.
"""
table_def = re.compile(r"CREATE TABLE|create table")
def __init__(self, source):
... |
Change exemple code to generate OTP link | import binascii
import base64
import os.path
def __content(f):
return open(os.path.join(os.path.dirname(__file__), f)).read()
crypto_js = __content('crypto.js')
hotp_js = __content('hotp.js')
myotp_js = __content('my-otp.js')
def dataize(document, type='text/html'):
return 'data:%s;base64,%s' % (type, base6... | import binascii
import base64
import os.path
def __content(f):
return open(os.path.join(os.path.dirname(__file__), f)).read()
crypto_js = __content('crypto.js')
hotp_js = __content('hotp.js')
myotp_js = __content('my-otp.js')
def dataize(document, type='text/html'):
return 'data:%s;base64,%s' % (type, base6... |
Fix import of 'reverse' for Django>1.9 | from django import template
from django.conf import settings
from django.core.urlresolvers import reverse
register = template.Library()
@register.simple_tag(takes_context=True)
def active_link(context, viewname, css_class=None, strict=None):
"""
Renders the given CSS class if the request path matches the pat... | from django import VERSION as DJANGO_VERSION
from django import template
from django.conf import settings
if DJANGO_VERSION[0] == 1 and DJANGO_VERSION[1] <= 9:
from django.core.urlresolvers import reverse
else:
from django.urls import reverse
register = template.Library()
@register.simple_tag(takes_context=T... |
Remove unused variable from `handle_cd_command` | import os
import subprocess
def handle_cd_command(arg):
"""Handles a `cd` shell command by calling python's os.chdir."""
CD_CMD = 'cd'
command = arg.strip()
directory = ''
error = False
tokens = arg.split(CD_CMD + ' ')
directory = tokens[-1]
try:
os.chdir(directory)
ou... | import os
import subprocess
def handle_cd_command(arg):
"""Handles a `cd` shell command by calling python's os.chdir."""
CD_CMD = 'cd'
directory = ''
error = False
tokens = arg.split(CD_CMD + ' ')
directory = tokens[-1]
try:
os.chdir(directory)
output = subprocess.check_ou... |
Remove password back door since database updates complete. | import hashlib
from os import urandom
from base64 import b64encode, b64decode
from itertools import izip
from lampost.util.pdkdf2 import pbkdf2_bin
SALT_LENGTH = 8
KEY_LENGTH = 20
COST_FACTOR = 800
def make_hash(password):
if isinstance(password, unicode):
password = password.encode('utf-8')
salt = ... | import hashlib
from os import urandom
from base64 import b64encode, b64decode
from itertools import izip
from lampost.util.pdkdf2 import pbkdf2_bin
SALT_LENGTH = 8
KEY_LENGTH = 20
COST_FACTOR = 800
def make_hash(password):
if isinstance(password, unicode):
password = password.encode('utf-8')
salt = ... |
Fix bool setting dump issue. | import os
from django.core.management import BaseCommand
from django.conf import settings
def dump_attrs(obj_instance):
for attr in dir(obj_instance):
if attr != attr.upper():
continue
yield attr, getattr(obj_instance, attr)
class Command(BaseCommand):
args = ''
help = 'Crea... | import os
from django.core.management import BaseCommand
from django.conf import settings
def dump_attrs(obj_instance):
for attr in dir(obj_instance):
if attr != attr.upper():
continue
yield attr, getattr(obj_instance, attr)
class Command(BaseCommand):
args = ''
help = 'Crea... |
Initialize engine with load_system parameter. | """
A simple standalone target for the prolog interpreter.
"""
import sys
from prolog.interpreter.translatedmain import repl, execute
# __________ Entry point __________
from prolog.interpreter.continuation import Engine
from prolog.interpreter import term
from prolog.interpreter import arithmetic # for side effec... | """
A simple standalone target for the prolog interpreter.
"""
import sys
from prolog.interpreter.translatedmain import repl, execute
# __________ Entry point __________
from prolog.interpreter.continuation import Engine
from prolog.interpreter import term
from prolog.interpreter import arithmetic # for side effec... |
Remove English [initialize] default block for now to get tests to pass | from typing import Optional
from thinc.api import Model
from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
from .stop_words import STOP_WORDS
from .lex_attrs import LEX_ATTRS
from .syntax_iterators import SYNTAX_ITERATORS
from .punctuation import TOKENIZER_INFIXES
from .lemmatizer import EnglishLemmatizer
from ...... | from typing import Optional
from thinc.api import Model
from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
from .stop_words import STOP_WORDS
from .lex_attrs import LEX_ATTRS
from .syntax_iterators import SYNTAX_ITERATORS
from .punctuation import TOKENIZER_INFIXES
from .lemmatizer import EnglishLemmatizer
from ...... |
Add capability to upvote/downvote yaks many times | import pyak
import time
class YikBot(Yakker):
def boot(self):
while True:
print "DEBUG: Scanning feed"
yaks = yikBot.get_yaks()
for yak in yaks:
if yak.message.startswith("@yikBot"):
yikBot.respond(yak)
print "DEBUG: Going ... | import pyak
import time
class YikBot(pyak.Yakker):
def boot(self):
while True:
print "DEBUG: Scanning feed"
yaks = self.get_yaks()
for yak in yaks:
if yak.message.startswith("@yikBot"):
print "DEBUG: Found a targeted yak"
... |
Add docstrings for most public API methods. | from collections import MutableMapping
class BetterOrderedDict(MutableMapping):
def __init__(self, **kwargs):
self._d = dict()
self._keys = []
def __len__(self):
return len(self._d)
def __iter__(self):
for key in self._keys:
yield key
def __setitem__(self... | from collections import MutableMapping
class BetterOrderedDict(MutableMapping):
'''BetterOrderedDict is a mapping object that allows for ordered access
and insertion of keys. With the exception of the key_index, insert, and
reorder_keys methods behavior is identical to stock dictionary objects.'''
de... |
Load all storage plugins in the printer application | from Cura.Wx.WxApplication import WxApplication
from Cura.Wx.MainWindow import MainWindow
class PrinterApplication(WxApplication):
def __init__(self):
super(PrinterApplication, self).__init__()
def run(self):
window = MainWindow("Cura Printer")
window.Show()
super(Print... | from Cura.Wx.WxApplication import WxApplication
from Cura.Wx.MainWindow import MainWindow
class PrinterApplication(WxApplication):
def __init__(self):
super(PrinterApplication, self).__init__()
def run(self):
self._plugin_registry.loadPlugins({ "type": "StorageDevice" })
... |
Allow trailing slash at the end of URLs | from django.conf.urls import url, include
from django.contrib import admin
from nextcloudappstore.core.views import CategoryAppListView, AppDetailView, \
app_description
urlpatterns = [
url(r'^$', CategoryAppListView.as_view(), {'id': None}, name='home'),
url(r'^', include('allauth.urls')),
url(r'^cat... | from django.conf.urls import url, include
from django.contrib import admin
from nextcloudappstore.core.views import CategoryAppListView, AppDetailView, \
app_description
urlpatterns = [
url(r'^$', CategoryAppListView.as_view(), {'id': None}, name='home'),
url(r'^', include('allauth.urls')),
url(r'^cat... |
Add warning if 'phantasy_apps' cannot be found. | # encoding: UTF-8
#
# Copyright (c) 2015-2016 Facility for Rare Isotope Beams
#
"""
Physics Applications
"""
from .latticemodel import lmapp
from phantasy_apps import *
| # encoding: UTF-8
#
# Copyright (c) 2015-2016 Facility for Rare Isotope Beams
#
"""
Physics Applications
"""
from .latticemodel import lmapp
try:
from phantasy_apps import *
except ImportError:
print("Package 'python-phantasy-apps' is required.")
|
Allow setting of postgres user via an environment variable | from __future__ import absolute_import
import os
os.environ['INBOX_TESTING'] = '1'
os.environ["INBOXEN_ADMIN_ACCESS"] = '1'
from settings import *
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.locmem.LocMemCache"
}
}
db = os.environ.get('DB')
SECRET_KEY = "This is a test, you don't ... | from __future__ import absolute_import
import os
os.environ['INBOX_TESTING'] = '1'
os.environ["INBOXEN_ADMIN_ACCESS"] = '1'
from settings import *
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.locmem.LocMemCache"
}
}
db = os.environ.get('DB')
postgres_user = os.environ.get('PG_USER',... |
Add dummy cache setting so code can be loaded | """
This is a home for shared dev settings. Feel free to add anything that all
devs should have set.
Add `from dev_settings import *` to the top of your localsettings file to use.
You can then override or append to any of these settings there.
"""
import os
LOCAL_APPS = (
'django_extensions',
)
####### Django E... | """
This is a home for shared dev settings. Feel free to add anything that all
devs should have set.
Add `from dev_settings import *` to the top of your localsettings file to use.
You can then override or append to any of these settings there.
"""
import os
LOCAL_APPS = (
'django_extensions',
)
####### Django E... |
Make application use log file if its name is not None | # -*- coding: utf-8 -*-
'''
url-shortener
==============
An application for generating and storing shorter aliases for
requested urls. Uses `spam-lists`__ to prevent generating a short url
for an address recognized as spam, or to warn a user a pre-existing
short alias has a target that has been later recognized as spa... | # -*- coding: utf-8 -*-
'''
url-shortener
==============
An application for generating and storing shorter aliases for
requested urls. Uses `spam-lists`__ to prevent generating a short url
for an address recognized as spam, or to warn a user a pre-existing
short alias has a target that has been later recognized as spa... |
Use the first mention for saving | #!/usr/bin/env python
import os
import random
import tweepy
import config
last_seen_path = os.path.join(os.path.dirname(__file__), 'last-seen')
def get_api():
auth = tweepy.OAuthHandler(config.consumer_key, config.consumer_secret)
auth.set_access_token(config.key, config.secret)
return tweepy.API(aut... | #!/usr/bin/env python
import os
import random
import tweepy
import config
last_seen_path = os.path.join(os.path.dirname(__file__), 'last-seen')
def get_api():
auth = tweepy.OAuthHandler(config.consumer_key, config.consumer_secret)
auth.set_access_token(config.key, config.secret)
return tweepy.API(aut... |
Fix tests to be moroe robust | from nose.tools import assert_equals
from .. import datasets
from ..pca import PCA
iris = datasets.load_iris()
X = iris.data
def test_pca():
"""
PCA
"""
pca = PCA(k=2)
X_r = pca.fit(X).transform(X)
assert_equals(X_r.shape[1], 2)
pca = PCA()
pca.fit(X)
assert_equals(pca.explaine... | import numpy as np
from .. import datasets
from ..pca import PCA
iris = datasets.load_iris()
X = iris.data
def test_pca():
"""
PCA
"""
pca = PCA(k=2)
X_r = pca.fit(X).transform(X)
np.testing.assert_equal(X_r.shape[1], 2)
pca = PCA()
pca.fit(X)
np.testing.assert_almost_equal(pca... |
Add sleep before new Chatbot instance is created on crash | import ConfigParser
import threading
import time
import chatbot
def runbot(t):
config = ConfigParser.ConfigParser()
config.readfp(open('./config.ini'))
ws = chatbot.Chatbot(config.get('Chatbot', 'server'),
protocols=['http-only', 'chat'])
try:
ws.connect()
ws... | import ConfigParser
import threading
import time
import chatbot
def runbot(t):
config = ConfigParser.ConfigParser()
config.readfp(open('./config.ini'))
ws = chatbot.Chatbot(config.get('Chatbot', 'server'),
protocols=['http-only', 'chat'])
try:
ws.connect()
ws... |
Add some info and outfile to prepare function | #!/usr/bin/env python
# encoding: utf-8
import sys
import re
import argparse
from patterns import pre_patterns
def prepare(infile):
"""
Apply pre_patterns from patterns to infile
:infile: input file
"""
try:
for line in infile:
result = line
for pattern in pre_p... | #!/usr/bin/env python
# encoding: utf-8
import sys
import re
import argparse
from argparse import RawDescriptionHelpFormatter
from patterns import pre_patterns
def prepare(infile, outfile=sys.stdout):
"""
Apply pre_patterns from patterns to infile
:infile: input file
"""
try:
for line ... |
Add unit tests for enqueue, dequeue and length for Queue | import unittest
from aids.queue.queue import Queue
class QueueTestCase(unittest.TestCase):
'''
Unit tests for the Queue data structure
'''
def setUp(self):
self.test_queue = Queue()
def test_queue_initialization(self):
self.assertTrue(isinstance(self.test_queue, Queue))
def test_queue... | import unittest
from aids.queue.queue import Queue
class QueueTestCase(unittest.TestCase):
'''
Unit tests for the Queue data structure
'''
def setUp(self):
self.test_queue = Queue()
def test_queue_initialization(self):
self.assertTrue(isinstance(self.test_queue, Queue))
def test_queue... |
Exclude tests and cmdline scripts | from setuptools import setup, find_packages
setup(
name='coverpy',
version='0.0.2dev',
packages=find_packages(),
install_requires=['requests'],
license='MIT License',
long_description=open('README.md').read(),
package_data = {
'': ['*.txt', '*.md'],
},
)
| from setuptools import setup, find_packages
setup(
name='coverpy',
version='0.8',
packages=find_packages(exclude=['scripts', 'tests']),
install_requires=['requests'],
license='MIT License',
author="fallenshell",
author_email='dev@mxio.us',
description="A wrapper for iTunes Search API",
long_description=open('... |
Add clean command and remove download tarball | from setuptools import setup, find_packages
__version__ = None
exec(open('tadtool/version.py').read())
setup(
name='tadtool',
version=__version__,
description='Assistant to find cutoffs in TAD calling algorithms.',
packages=find_packages(exclude=["test"]),
install_requires=[
'numpy>=1.9.0... | import os
from setuptools import setup, find_packages, Command
__version__ = None
exec(open('tadtool/version.py').read())
class CleanCommand(Command):
"""
Custom clean command to tidy up the project root.
"""
user_options = []
def initialize_options(self):
pass
def finalize_options(... |
Add missing comma to requirements. | import os
from setuptools import setup
version = '0.9.2.dev0'
def read_file(fname):
with open(os.path.join(os.path.dirname(__file__), fname)) as fp:
return fp.read()
setup(name='django-ogmios',
version=version,
author="Fusionbox, Inc.",
author_email="programmers@fusionbox.com",
... | import os
from setuptools import setup
version = '0.9.2.dev0'
def read_file(fname):
with open(os.path.join(os.path.dirname(__file__), fname)) as fp:
return fp.read()
setup(name='django-ogmios',
version=version,
author="Fusionbox, Inc.",
author_email="programmers@fusionbox.com",
... |
Modify the pin number due to the hardware case | # -*- coding: utf-8 -*-
import RPi.GPIO as gpio
pin_power=12
pin_light=16
# Setup
gpio.setmode(gpio.BOARD)
gpio.setup(pin_power, gpio.OUT)
gpio.setup(pin_light, gpio.OUT)
gpio.output(pin_power, gpio.HIGH)
gpio.output(pin_light, gpio.LOW)
| # -*- coding: utf-8 -*-
import RPi.GPIO as gpio
pin_power=3
pin_light=5
# Setup
gpio.setmode(gpio.BOARD)
gpio.setup(pin_power, gpio.OUT)
gpio.setup(pin_light, gpio.OUT)
gpio.output(pin_power, gpio.HIGH)
gpio.output(pin_light, gpio.LOW)
|
Allow customizing number of posts displayed | # -*- coding: utf-8 -*-
from django import template
from django.conf import settings
from Instanssi.ext_blog.models import BlogEntry
register = template.Library()
@register.inclusion_tag('ext_blog/blog_messages.html')
def render_blog(event_id):
entries = BlogEntry.objects.filter(event_id__lte=int(event_id), publ... | # -*- coding: utf-8 -*-
from django import template
from django.conf import settings
from Instanssi.ext_blog.models import BlogEntry
register = template.Library()
@register.inclusion_tag('ext_blog/blog_messages.html')
def render_blog(event_id, max_posts=10):
entries = BlogEntry.objects.filter(event_id__lte=int(e... |
Test package setup and teardown | import logging
import unittest
from cassandra.cluster import Cluster
from cassandra.connection import _loop
from cassandra.policies import HostDistance
log = logging.getLogger()
log.setLevel('DEBUG')
log.addHandler(logging.StreamHandler())
existing_keyspaces = None
def setup_package():
try:
cluster = Cl... | |
Update LICENSE in package metadata | __title__ = 'vcspull'
__package_name__ = 'vcspull'
__description__ = 'synchronize your repos'
__version__ = '1.0.3'
__author__ = 'Tony Narlock'
__email__ = 'tony@git-pull.com'
__license__ = 'BSD'
__copyright__ = 'Copyright 2013-2016 Tony Narlock'
| __title__ = 'vcspull'
__package_name__ = 'vcspull'
__description__ = 'synchronize your repos'
__version__ = '1.0.3'
__author__ = 'Tony Narlock'
__email__ = 'tony@git-pull.com'
__license__ = 'MIT'
__copyright__ = 'Copyright 2013-2016 Tony Narlock'
|
Add missing not-equal comparison for wbtypes | # -*- coding: utf-8 -*-
"""Wikibase data type classes."""
#
# (C) Pywikibot team, 2013-2015
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals
__version__ = '$Id$'
#
import json
from pywikibot.tools import StringTypes
class WbRepresentation(object):
... | # -*- coding: utf-8 -*-
"""Wikibase data type classes."""
#
# (C) Pywikibot team, 2013-2015
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals
__version__ = '$Id$'
#
import json
from pywikibot.tools import StringTypes
class WbRepresentation(object):
... |
Make sure Caller does not return |
import simuvex
######################################
# Caller
######################################
class Caller(simuvex.SimProcedure):
"""
Caller stub. Creates a Ijk_Call exit to the specified function
"""
def run(self, target_addr=None):
self.call(target_addr, [ ], self.after_call)
... |
import simuvex
######################################
# Caller
######################################
class Caller(simuvex.SimProcedure):
"""
Caller stub. Creates a Ijk_Call exit to the specified function
"""
NO_RET = True
def run(self, target_addr=None):
self.call(target_addr, [ ], se... |
Fix unit tests for Django 1.8 | from django.test import TestCase
from django.conf import settings
class SettingsTestCase(TestCase):
def test_modified_settings(self):
with self.settings(CHATTERBOT={'name': 'Jim'}):
self.assertIn('name', settings.CHATTERBOT)
self.assertEqual('Jim', settings.CHATTERBOT['name'])
... | from django.test import TestCase
from django.conf import settings
class SettingsTestCase(TestCase):
def test_modified_settings(self):
with self.settings(CHATTERBOT={'name': 'Jim'}):
self.assertIn('name', settings.CHATTERBOT)
self.assertEqual('Jim', settings.CHATTERBOT['name'])
... |
Add message in log with plotting process id. | import datetime
import multiprocessing
from lobster.cmssw.plotting import Plotter
logger = multiprocessing.get_logger()
class DummyPlotter(object):
def make_plots(*args, **kwargs):
pass
class Actions(object):
def __init__(self, config):
if 'plotdir' in config:
logger.info('plots ... | import datetime
import multiprocessing
from lobster.cmssw.plotting import Plotter
logger = multiprocessing.get_logger()
class DummyPlotter(object):
def make_plots(*args, **kwargs):
pass
class Actions(object):
def __init__(self, config):
if 'plotdir' in config:
logger.info('plots ... |
Use falcon methods as HTTP methods | from functools import wraps
from collections import OrderedDict
import sys
def call(url, methods=('ALL', )):
def decorator(api_function):
module = sys.modules[api_function.__name__]
api_definition = sys.modules['hug.hug'].__dict__.setdefault('API_CALLS', OrderedDict())
for method in method... | from functools import wraps
from collections import OrderedDict
import sys
from falcon import HTTP_METHODS
def call(url, methods=HTTP_METHODS):
def decorator(api_function):
module = sys.modules[api_function.__name__]
api_definition = sys.modules['hug.hug'].__dict__.setdefault('HUG_API_CALLS', Ord... |
Fix flake8 warning by adding flake annotation | # relative
from .passthrough import AcceptableSimpleType # type: ignore
from .passthrough import PassthroughTensor # type: ignore
from .passthrough import SupportedChainType # type: ignore
| from .passthrough import AcceptableSimpleType # type: ignore # NOQA
from .passthrough import PassthroughTensor # type: ignore # NOQA
from .passthrough import SupportedChainType # type: ignore # NOQA
|
Add a rudimentary view for tracking mapper errors | from flask import Blueprint, request
from json import dumps, loads
from redis import Redis
from plenario.settings import REDIS_HOST_SAFE
blueprint = Blueprint("apiary", __name__)
redis = Redis(REDIS_HOST_SAFE)
@blueprint.route("/apiary/send_message", methods=["POST"])
def send_message():
try:
data = lo... | from collections import defaultdict
from json import dumps, loads
from traceback import format_exc
from flask import Blueprint, make_response, request
from redis import Redis
from plenario.auth import login_required
from plenario.settings import REDIS_HOST_SAFE
blueprint = Blueprint("apiary", __name__)
redis = Redis... |
Fix script to pass pep8 | #!/usr/bin/env python3
import argparse
import random
import sys
DESCRIPTION = '''Shuffle the arguments received, if called without arguments
the lines read from stdin will be shuffled and printed to
stdout'''
def get_list():
return sys.stdin.readlines()
def print_list(list_):
... | #!/usr/bin/env python3
import argparse
import random
import sys
DESCRIPTION = '''Shuffle the arguments received, if called without arguments
the lines read from stdin will be shuffled and printed to
stdout'''
def get_list():
return sys.stdin.readlines()
def print_list(list_):... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.