commit stringlengths 40 40 | old_file stringlengths 4 236 | new_file stringlengths 4 236 | old_contents stringlengths 1 3.26k | new_contents stringlengths 16 4.43k | subject stringlengths 16 624 | message stringlengths 17 3.29k | lang stringclasses 5
values | license stringclasses 13
values | repos stringlengths 5 91.5k |
|---|---|---|---|---|---|---|---|---|---|
be23c953f8f27a8d178022d3ecb44f461100bbc5 | tests/__init__.py | tests/__init__.py | """Tests for running TopoFlow components in CMI."""
import os
def locate_topoflow(cache_dir):
for x in os.listdir(cache_dir):
if x.startswith('topoflow'):
return x
root_dir = '/home/csdms/wmt/topoflow.0'
cache_dir = os.path.join(root_dir, 'cache')
topoflow_dir = locate_topoflow(cache_dir)
ex... | """Tests for running TopoFlow components in CMI."""
import os
def locate_topoflow(cache_dir):
for x in os.listdir(cache_dir):
if x.startswith('topoflow'):
return x
root_dir = '/home/csdms/wmt/topoflow.0'
cache_dir = os.path.join(root_dir, 'cache')
topoflow_dir = locate_topoflow(cache_dir)
ex... | Add path to data directory | Add path to data directory
| Python | mit | mdpiper/topoflow-cmi-testing |
ef82619995ce71b5877228988bce2830eb25baff | download_and_unzip_files.py | download_and_unzip_files.py | import os
import datetime
current_year = datetime.datetime.now().year
years_with_data = range(2011, current_year + 1)
remote_path = "https://ssl.netfile.com/pub2/excel/COAKBrowsable/"
for year in years_with_data:
print "Downloading " + str(year) + " data..."
filename_for_year = "efile_newest_COAK_" + str(year) + ... | import os
import datetime
current_year = datetime.datetime.now().year
years_with_data = range(2011, current_year + 1)
remote_path = "https://ssl.netfile.com/pub2/excel/COAKBrowsable/"
for year in years_with_data:
print "Downloading " + str(year) + " data..."
filename_for_year = "efile_newest_COAK_" + str(year) + ... | Replace wget with curl to avoid Heroku buildpack sadness | Replace wget with curl to avoid Heroku buildpack sadness
| Python | bsd-3-clause | daguar/netfile-etl,daguar/netfile-etl |
0c9bf270a7a2d8a4184f644bbe8a50995e155b0a | buddy/error.py | buddy/error.py | from functools import wraps
import botocore.exceptions
from click import ClickException
EXC_TO_ECHO = [
botocore.exceptions.NoRegionError,
]
def handle_exception(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as exc:
... | from functools import wraps
import botocore.exceptions
from click import ClickException
EXC_TO_ECHO = [
botocore.exceptions.NoRegionError,
botocore.exceptions.ParamValidationError,
]
def handle_exception(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, ... | Add boto ParamValidationError to exc list | Add boto ParamValidationError to exc list
| Python | mit | pior/buddy |
f1e516e8002425f5f4f9904096848798b2bc97fa | jesusmtnez/python/kata/game.py | jesusmtnez/python/kata/game.py | class Game():
def __init__(self):
self._rolls = [0] * 21
self._current_roll = 0
def roll(self, pins):
self._rolls[self._current_roll] += pins
self._current_roll += 1
def score(self):
score = 0
for frame in range(0, 20, 2):
if self._is_spare(frame... | class Game():
def __init__(self):
self._rolls = [0] * 21
self._current_roll = 0
def roll(self, pins):
self._rolls[self._current_roll] += pins
self._current_roll += 1 if pins < 10 else 2
def score(self):
score = 0
for frame in range(0, 20, 2):
if ... | Add strikes support when rolling | [Python] Add strikes support when rolling
| Python | mit | JesusMtnez/devexperto-challenge,JesusMtnez/devexperto-challenge |
d957301018fa47ce61fcb004880ecd5acd18f2a9 | features/events/utils.py | features/events/utils.py | from django.utils import timezone
def get_requested_time(request):
query = request.GET
month, year = query.get('month', None), query.get('year', None)
if month and year:
return timezone.datetime(year=int(year), month=int(month), day=1)
else:
return None
| from django.utils import timezone
def get_requested_time(request):
query = request.GET
month, year = query.get('month', None), query.get('year', None)
if month and year:
try:
return timezone.datetime(year=int(year), month=int(month), day=1)
except ValueError:
pass
... | Fix handling of invalid parameters | Fix handling of invalid parameters
| Python | agpl-3.0 | stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten |
d6929fa152bb8149fa9b4033135441030dd71260 | authentic2/idp/idp_openid/context_processors.py | authentic2/idp/idp_openid/context_processors.py | def get_url():
return reverse('openid-provider-xrds')
def openid_meta(request):
context = {
'openid_server': context['request'].build_absolute_uri(get_url())
}
content = '''<meta http-equiv="X-XRDS-Location" content="%(openid_server)s"/>
<meta http-equiv="X-YADIS-Location" content="%(openid... | from django.core.urlresolvers import reverse
def get_url():
return reverse('openid-provider-xrds')
def openid_meta(request):
context = {
'openid_server': request.build_absolute_uri(get_url())
}
content = '''<meta http-equiv="X-XRDS-Location" content="%(openid_server)s"/>
<meta http-equiv="... | Remove dependency on openid in the base template (bis) | Remove dependency on openid in the base template (bis)
Fixes #1357
| Python | agpl-3.0 | BryceLohr/authentic,BryceLohr/authentic,incuna/authentic,incuna/authentic,adieu/authentic2,incuna/authentic,adieu/authentic2,adieu/authentic2,BryceLohr/authentic,pu239ppy/authentic2,adieu/authentic2,pu239ppy/authentic2,BryceLohr/authentic,pu239ppy/authentic2,incuna/authentic,pu239ppy/authentic2,incuna/authentic |
e62469c3572cf9bfa02cd153becc1b36ecf8b3df | run-hooks.py | run-hooks.py | # -*- coding: utf-8 -*-
"""
Eve Demo
~~~~~~~~
A demostration of a simple API powered by Eve REST API.
The live demo is available at eve-demo.herokuapp.com. Please keep in mind
that the it is running on Heroku's free tier using a free MongoHQ
sandbox, which means that the first request to the ... | # -*- coding: utf-8 -*-
"""
Eve Demo
~~~~~~~~
A demostration of a simple API powered by Eve REST API.
The live demo is available at eve-demo.herokuapp.com. Please keep in mind
that the it is running on Heroku's free tier using a free MongoHQ
sandbox, which means that the first request to the ... | Prepare for Codemotion Rome 2017 demo | Prepare for Codemotion Rome 2017 demo
| Python | bsd-3-clause | nicolaiarocci/eve-demo |
8f1e094d8abc8317d8e802c556e695d117f0fac1 | globus_cli/commands/task/event_list.py | globus_cli/commands/task/event_list.py | import click
from globus_cli.parsing import common_options, task_id_arg
from globus_cli.safeio import formatted_print
from globus_cli.services.transfer import iterable_response_to_dict, get_client
@click.command('event-list', help='List Events for a given task')
@common_options
@task_id_arg
@click.option(
"--li... | import click
from globus_cli.parsing import common_options, task_id_arg
from globus_cli.safeio import formatted_print
from globus_cli.services.transfer import iterable_response_to_dict, get_client
@click.command('event-list', help='List Events for a given task')
@common_options
@task_id_arg
@click.option(
"--li... | Make task event-list filters mutually exclusive | Make task event-list filters mutually exclusive
| Python | apache-2.0 | globus/globus-cli,globus/globus-cli |
3b9a86bdb85aa04c2f2a0e40387f56d65fb54d46 | bin/trigger_upload.py | bin/trigger_upload.py | #!/bin/env python
# -*- coding: utf8 -*-
""" Triggers an upload process with the specified raw.xz URL. """
import argparse
import logging
import logging.config
import multiprocessing.pool
import fedmsg.config
import fedimg.uploader
logging.config.dictConfig(fedmsg.config.load_config()['logging'])
log = logging.getLo... | #!/bin/env python
# -*- coding: utf8 -*-
""" Triggers an upload process with the specified raw.xz URL. """
import argparse
import logging
import logging.config
import multiprocessing.pool
import fedmsg.config
import fedimg.uploader
logging.config.dictConfig(fedmsg.config.load_config()['logging'])
log = logging.getLo... | Fix the script to send proper format of compose id | scripts: Fix the script to send proper format of compose id
Signed-off-by: Sayan Chowdhury <5f0367a2b3b757615b57f51d912cf16f2c0ad827@gmail.com>
| Python | agpl-3.0 | fedora-infra/fedimg,fedora-infra/fedimg |
b03bc28da7476ca27e64b8cc01b685e11eb6d505 | menpodetect/pico/conversion.py | menpodetect/pico/conversion.py | from menpo.shape import PointDirectedGraph
import numpy as np
def pointgraph_from_circle(fitting):
y, x = fitting.center
radius = fitting.diameter / 2.0
return PointDirectedGraph(np.array(((y, x),
(y + radius, x),
(y + radius,... | from menpo.shape import PointDirectedGraph
import numpy as np
def pointgraph_from_circle(fitting):
diameter = fitting.diameter
radius = diameter / 2.0
y, x = fitting.center
y -= radius
x -= radius
return PointDirectedGraph(np.array(((y, x),
(y + diameter... | Fix the circle to rectangle code | Fix the circle to rectangle code
Was totally incorrect previously
| Python | bsd-3-clause | jabooth/menpodetect,yuxiang-zhou/menpodetect,yuxiang-zhou/menpodetect,jabooth/menpodetect |
bec268ef554e6f30c2cecd52ecddcafc34c5b0db | tutorials/cmake_python_wrapper/v1/python/foo/__init__.py | tutorials/cmake_python_wrapper/v1/python/foo/__init__.py | import ctypes
import numpy as np
import os
__all__ = ['square']
lib = ctypes.cdll.LoadLibrary("libfoo.so")
lib.square.restype = ctypes.c_int
lib.square.argtypes = [ctypes.c_int]
def square(value):
"""
Parameters
----------
value: int
Returns
--------
value square
"""
return lib.... | import ctypes
import numpy as np
import os
import sys
__all__ = ['square']
_path = os.path.dirname(__file__)
libname = None
if sys.platform.startswith('linux'):
libname = 'libfoo.so'
elif sys.platform == 'darwin':
libname = 'libfoo.dylib'
elif sys.platform.startswith('win'):
libname = 'foo.dll'
if libname ==None:... | Change to cmake to 3.4 and test sys.platform to choose lib extension to resolve import error on MacOSX | Change to cmake to 3.4 and test sys.platform to choose lib extension to resolve import error on MacOSX
| Python | bsd-3-clause | gammapy/PyGamma15,gammapy/2015-MPIK-Workshop,gammapy/2015-MPIK-Workshop,gammapy/PyGamma15,gammapy/PyGamma15,gammapy/2015-MPIK-Workshop |
def92e47ce05497e6a83cd8b8a569113956c6dc2 | events/serializers.py | events/serializers.py | from .models import Event, EventActivity
from rest_framework import serializers
class EventSerializer(serializers.ModelSerializer):
class Meta(object):
model = Event
depth = 1
class EventSimpleSerializer(serializers.Serializer):
pk = serializers.IntegerField()
name = serializers.CharFiel... | from .models import Event, EventActivity
from rest_framework import serializers
class EventSerializer(serializers.ModelSerializer):
class Meta(object):
model = Event
depth = 1
fields = ("pk", "name", "image", "datetime", "address", "description", "is_active", "is_upcoming", "location")
c... | Add explicit fields on EventSerializer | Add explicit fields on EventSerializer
| Python | apache-2.0 | belatrix/BackendAllStars |
16b663441c0d994b02e68b8c785ec6c7a2805f03 | onepercentclub/settings/payments.py | onepercentclub/settings/payments.py | from bluebottle.payments_docdata.settings import DOCDATA_SETTINGS, DOCDATA_PAYMENT_METHODS
PAYMENT_METHODS = DOCDATA_PAYMENT_METHODS
VAT_RATE = 0.21
| from bluebottle.payments_docdata.settings import DOCDATA_SETTINGS
PAYMENT_METHODS = (
{
'provider': 'docdata',
'id': 'docdata-ideal',
'profile': 'ideal',
'name': 'iDEAL',
'restricted_countries': ('NL', 'Netherlands'),
'supports_recurring': False,
},
{
... | Disable Paypal, up Direct debit | Disable Paypal, up Direct debit
| Python | bsd-3-clause | onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site |
460460cb95906a71f66a969ab0f2e9d5285b4d21 | kokki/cookbooks/aws/recipes/default.py | kokki/cookbooks/aws/recipes/default.py |
import os
from kokki import *
# Package("python-boto")
Execute("pip install git+http://github.com/boto/boto.git#egg=boto",
not_if = 'python -c "import boto"')
Execute("mv /usr/lib/pymodules/python2.6/boto /tmp/boto.orig",
only_if = lambda:os.path.exists("/usr/lib/pymodules/python2.6/boto"))
# Mount volumes a... |
import os
from kokki import *
# Package("python-boto")
Execute("mv /usr/lib/pymodules/python2.6/boto /tmp/boto.orig",
only_if = lambda:os.path.exists("/usr/lib/pymodules/python2.6/boto"))
Execute("pip install git+http://github.com/boto/boto.git#egg=boto",
not_if = 'python -c "import boto"')
# Mount volumes a... | Update boto on the server | Update boto on the server
| Python | bsd-3-clause | samuel/kokki |
f12b6383f5e18c8e76760f535c630bf256ec0f8a | incunafein/module/page/extensions/prepared_date.py | incunafein/module/page/extensions/prepared_date.py | from django.db import models
def register(cls, admin_cls):
cls.add_to_class('_prepared_date', models.TextField('Date of Preparation', blank=True, null=True))
def getter():
if not cls._prepared_date:
try:
return cls.get_ancestors(ascending=True).filter(_prepared_date__isnull... | from django.db import models
def register(cls, admin_cls):
cls.add_to_class('_prepared_date', models.TextField('Date of Preparation', blank=True, null=True))
def getter(obj):
if not obj._prepared_date:
try:
return obj.get_ancestors(ascending=True).filter(_prepared_date__isn... | Use the object instead of the class | Use the object instead of the class
| Python | bsd-2-clause | incuna/incuna-feincms,incuna/incuna-feincms,incuna/incuna-feincms |
5ac176fafd35bfa675e1718b74a8c6ef4dc74629 | skoleintra/pgWeekplans.py | skoleintra/pgWeekplans.py | #
# -*- encoding: utf-8 -*-
#
import re
import config
import surllib
import semail
import datetime
import urllib
URL_PREFIX = 'http://%s/Infoweb/Fi/' % config.HOSTNAME
URL_MAIN = URL_PREFIX + 'Ugeplaner.asp'
def docFindWeekplans(bs):
trs = bs.findAll('tr')
for line in trs:
if not line.has_key('clas... | #
# -*- encoding: utf-8 -*-
#
import re
import config
import surllib
import semail
import datetime
import urllib
URL_PREFIX = 'http://%s/Infoweb/Fi/' % config.HOSTNAME
URL_MAIN = URL_PREFIX + 'Ugeplaner.asp'
def docFindWeekplans(bs):
trs = bs.findAll('tr')
for line in trs:
if not line.has_key('cla... | Make code comply to PEP8 | Make code comply to PEP8
| Python | bsd-2-clause | bennyslbs/fskintra |
e3a3e729eb60f5a7e134da5b58bb52d672e1d8b2 | sitenco/config/sphinx.py | sitenco/config/sphinx.py | """
Docs with Sphinx.
"""
import sys
import abc
import os.path
import subprocess
from . import vcs
from .. import DOCS_PATH
class Sphinx(vcs.VCS):
"""Abstract class for project folder tools."""
__metaclass__ = abc.ABCMeta
def __init__(self, path, branch='master', url=None):
path = os.path.join... | """
Docs with Sphinx.
"""
import sys
import abc
import os.path
import subprocess
from . import vcs
from .. import DOCS_PATH
class Sphinx(vcs.VCS):
"""Abstract class for project folder tools."""
__metaclass__ = abc.ABCMeta
def __init__(self, path, branch='master', url=None):
path = os.path.join... | Use python interpreter instead of sys.executable | Use python interpreter instead of sys.executable
| Python | bsd-3-clause | Kozea/sitenco |
cb69adc8727048ac9e1f7a1205a0f1b5ed269dad | Native/Scripts/finalize.py | Native/Scripts/finalize.py |
# This script just copies the generated .pyd file to the current directory.
import platform
from shutil import copyfile
from os.path import isfile
source_file = None
if platform.system() == "Windows":
possible_files = [
"Windows/Release/RSNative.pyd",
"Windows/x64/Release/RSNative.pyd",
]
... |
# This script just copies the generated .pyd file to the current directory.
import platform
from shutil import copyfile
from os.path import isfile
source_file = None
if platform.system() == "Windows":
possible_files = [
"Windows/Release/RSNative.pyd",
"Windows/x64/Release/RSNative.pyd",
]
... | Fix typo in build system | Fix typo in build system
| Python | mit | croxis/SpaceDrive,eswartz/RenderPipeline,eswartz/RenderPipeline,croxis/SpaceDrive,croxis/SpaceDrive,eswartz/RenderPipeline |
33cf4e996d1ff230ae7e8a55e57f0bd5a046ea0f | dlstats/configuration.py | dlstats/configuration.py | import configobj
import validate
import os
def _get_filename():
"""Return the configuration file path."""
appname = 'dlstats'
if os.name == 'posix':
if os.path.isfile(os.environ["HOME"]+'/.'+appname):
return os.environ["HOME"]+'/.'+appname
elif os.path.isfile('/etc/'+appname):
... | import configobj
import validate
import os
def _get_filename():
"""Return the configuration file path."""
appname = 'dlstats'
if os.name == 'posix':
if os.path.isfile(os.environ["HOME"]+'/.'+appname):
return os.environ["HOME"]+'/.'+appname
elif os.path.isfile('/etc/'+appname):
... | Remove copy from the validator | Remove copy from the validator
We are not providing default values to the configuration object. Those
are distributed with the package; the expected behavior is to throw an
exception if the options are not explicitly passed.
| Python | agpl-3.0 | MichelJuillard/dlstats,Widukind/dlstats,mmalter/dlstats,Widukind/dlstats,MichelJuillard/dlstats,mmalter/dlstats,mmalter/dlstats,MichelJuillard/dlstats |
f0c53900a62159249240dedc486678d451932cb1 | opps/articles/tests/models.py | opps/articles/tests/models.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.test import TestCase
from django.contrib.sites.models import Site
from django.contrib.auth import get_user_model
from django.core.files import File
from opps.articles.models import Post
from opps.channels.models import Channel
from opps.images.models import Ima... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.test import TestCase
from opps.articles.models import Post
class PostModelTest(TestCase):
fixtures = ['tests/initial_data.json']
def test_basic_post_exist(self):
post = Post.objects.all()
self.assertTrue(post)
self.assertEqu... | Fix articles test, used test initial_data | Fix articles test, used test initial_data
| Python | mit | williamroot/opps,jeanmask/opps,jeanmask/opps,opps/opps,williamroot/opps,jeanmask/opps,YACOWS/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,williamroot/opps,opps/opps,opps/opps,opps/opps,YACOWS/opps |
daf6468079e7ff3e00550db0f3a16bc109184027 | osgtest/tests/test_49_jobs.py | osgtest/tests/test_49_jobs.py | #pylint: disable=C0301
#pylint: disable=C0111
#pylint: disable=R0201
#pylint: disable=R0904
import osgtest.library.core as core
import osgtest.library.files as files
import osgtest.library.osgunittest as osgunittest
class TestCleanupJobs(osgunittest.OSGTestCase):
"""Clean any configuration we touched for running ... | #pylint: disable=C0301
#pylint: disable=C0111
#pylint: disable=R0201
#pylint: disable=R0904
import osgtest.library.core as core
import osgtest.library.files as files
import osgtest.library.osgunittest as osgunittest
class TestCleanupJobs(osgunittest.OSGTestCase):
"""Clean any configuration we touched for running ... | Drop job env backup cleanup dependence on osg-configure | Drop job env backup cleanup dependence on osg-configure
We already dropped the creation of the job env files in 840ea8
| Python | apache-2.0 | efajardo/osg-test,efajardo/osg-test |
97e60ffa741bafbd34bcee18d0dce9f323b0132a | project/settings/prod.py | project/settings/prod.py | # Local
from .base import *
# Heroku Settings
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_SSL_REDIRECT = True
ALLOWED_HOSTS = [
'.barberscore.com',
'.herokuapp.com',
]
DATABASES['default']['TEST'] = {
'NAME': DATABASES['default']['NAME'],
}
# Email
EMAIL_HOST = 'smtp.sendgrid.ne... | # Local
from .base import *
# Heroku Settings
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_SSL_REDIRECT = True
ALLOWED_HOSTS = [
'testserver',
'.barberscore.com',
'.herokuapp.com',
]
DATABASES['default']['TEST'] = {
'NAME': DATABASES['default']['NAME'],
}
# Email
EMAIL_HOST =... | TEst adding test server to allowed hosts | TEst adding test server to allowed hosts
| Python | bsd-2-clause | dbinetti/barberscore,barberscore/barberscore-api,barberscore/barberscore-api,barberscore/barberscore-api,dbinetti/barberscore-django,dbinetti/barberscore,barberscore/barberscore-api,dbinetti/barberscore-django |
23d3bd38fc9ee94a4f9a9e829473007354a534ed | auditlog/__manifest__.py | auditlog/__manifest__.py | # -*- coding: utf-8 -*-
# © 2015 ABF OSIELL <http://osiell.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
'name': "Audit Log",
'version': "9.0.1.0.0",
'author': "ABF OSIELL,Odoo Community Association (OCA)",
'license': "AGPL-3",
'website': "http://www.osiell.com",
'categ... | # -*- coding: utf-8 -*-
# © 2015 ABF OSIELL <http://osiell.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
'name': "Audit Log",
'version': "9.0.1.0.0",
'author': "ABF OSIELL,Odoo Community Association (OCA)",
'license': "AGPL-3",
'website': "http://www.osiell.com",
'categ... | Remove pre_init_hook reference from openerp, no pre_init hook exists any more | auditlog: Remove pre_init_hook reference from openerp, no pre_init hook exists any more
| Python | agpl-3.0 | YannickB/server-tools,YannickB/server-tools,OCA/server-tools,OCA/server-tools,YannickB/server-tools,OCA/server-tools |
cc741215fa5ff6a2a64d7bee3ff6108a4d85a16f | bootstrap3/components.py | bootstrap3/components.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.forms.widgets import flatatt
from django.utils.safestring import mark_safe
from bootstrap3.utils import render_tag
from .text import text_value
def render_icon(icon, title=''):
"""
Render a Bootstrap glyphicon icon
"""
attrs... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.forms.widgets import flatatt
from django.utils.safestring import mark_safe
from bootstrap3.utils import render_tag
from .text import text_value
def render_icon(icon, **kwargs):
"""
Render a Bootstrap glyphicon icon
"""
class... | Allow passing extra classes into render_icon, for example to set text-success | Allow passing extra classes into render_icon, for example to set text-success
| Python | bsd-3-clause | dyve/django-bootstrap3,zostera/django-bootstrap4,dyve/django-bootstrap3,zostera/django-bootstrap4 |
a600d75133f01aa9cc30767634f3d77379e6ba56 | keyring/py27compat.py | keyring/py27compat.py | """
Compatibility support for Python 2.7. Remove when Python 2.7 support is
no longer required.
"""
try:
import configparser
except ImportError:
import ConfigParser as configparser
try:
input = raw_input
except NameError:
input = input
try:
text_type = unicode
except NameError:
text_type = str... | """
Compatibility support for Python 2.7. Remove when Python 2.7 support is
no longer required.
"""
try:
import configparser
except ImportError:
import ConfigParser as configparser
try:
input = raw_input
except NameError:
input = input
try:
text_type = unicode
except NameError:
text_type = str... | Add 'string_types' as found in six. | Add 'string_types' as found in six.
| Python | mit | jaraco/keyring |
3386a32d0bae3433fad9f7c4960bdcb6a14a3835 | kobo/apps/__init__.py | kobo/apps/__init__.py | # coding: utf-8
import kombu.exceptions
from django.apps import AppConfig
from django.core.checks import register, Tags
from kpi.utils.two_database_configuration_checker import \
TwoDatabaseConfigurationChecker
class KpiConfig(AppConfig):
name = 'kpi'
def ready(self, *args, **kwargs):
# Once it'... | # coding: utf-8
import kombu.exceptions
from django.apps import AppConfig
from django.core.checks import register, Tags
from kpi.utils.two_database_configuration_checker import \
TwoDatabaseConfigurationChecker
class KpiConfig(AppConfig):
name = 'kpi'
def ready(self, *args, **kwargs):
# Once it'... | Add explanatory comment for odd use of `delay()` | Add explanatory comment for odd use of `delay()`
| Python | agpl-3.0 | kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi |
fb33fa9fef21bbe1e8d2d82dd986b69f8c3bdb64 | jp-holidays.py | jp-holidays.py | import requests
u = 'http://www.google.com/calendar/feeds/ja.japanese%23holiday@group.v.calendar.google.com/public/full?alt=json&max-results=100&futureevents=true'
data = requests.get(u).json()
print data.get('feed').get('title').get('$t')
for item in data.get('feed').get('entry'):
# gd$when
# 'title']['$t']... | import requests
import sys
u = 'http://www.google.com/calendar/feeds/ja.japanese%23holiday@group.v.calendar.google.com/public/full'
params = {
'alt': 'json',
'max-results': 100,
'futureevents': 'true'
}
res = requests.get(u, params=params)
res.raise_for_status()
data = res.json()
print data.get('feed').... | Use dict for uri params. | Use dict for uri params.
| Python | mit | shoma/python.tools |
a8b2f1ad738709fb49c5e3f9175822cc1bafa11d | dataset/__init__.py | dataset/__init__.py | import os
# shut up useless SA warning:
import warnings
warnings.filterwarnings(
'ignore', 'Unicode type received non-unicode bind param value.')
from dataset.persistence.util import sqlite_datetime_fix
from dataset.persistence.database import Database
from dataset.persistence.table import Table
from dataset.freez... | import os
# shut up useless SA warning:
import warnings
warnings.filterwarnings(
'ignore', 'Unicode type received non-unicode bind param value.')
from dataset.persistence.util import sqlite_datetime_fix
from dataset.persistence.database import Database
from dataset.persistence.table import Table
from dataset.freez... | Add more instructions for engine_kwargs, to avoid DB connection timeout issues | Add more instructions for engine_kwargs, to avoid DB connection timeout issues
| Python | mit | askebos/dataset,twds/dataset,stefanw/dataset,vguzmanp/dataset,reubano/dataset,pudo/dataset,saimn/dataset |
88fcd9e1ae2a8fe21023816304023526eb7b7e35 | fb_import.py | fb_import.py | import MySQLdb
# Download Guest List.csv from Facebook event page and copy it to a file named
# 'list.csv'. Remove the first line (column title) and the '"'s around each
# name (they cause trouble with MySQL)
filename = "list.csv"
data = open(filename, 'r');
guests = [];
db_host = "" # Add your host
db_user = "" # Ad... | import MySQLdb
import json
# Download Guest List.csv from Facebook event page and copy it to a file named
# 'list.csv'. Remove the first line (column title) and the '"'s around each
# name (they cause trouble with MySQL)
filename = "list.csv"
data = open(filename, 'r')
guests = []
# Config Setup
config_file = open('c... | Use config file in import script | Use config file in import script
| Python | mit | copperwall/Attendance-Checker,copperwall/Attendance-Checker,copperwall/Attendance-Checker |
1f91a0eed0f336ac559cfbca5c4a86f313b48bb5 | tests/test_postgres_processor.py | tests/test_postgres_processor.py | import pytest
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings")
import django
from django.test import TestCase
from scrapi.processing.postgres import PostgresProcessor, Document
from . import utils
from scrapi.linter.document import RawDocument
django.setup()
test_db = PostgresProcessor... | # import pytest
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings")
import django
from django.test import TestCase
from scrapi.processing.postgres import PostgresProcessor, Document
from . import utils
from scrapi.linter.document import RawDocument, NormalizedDocument
django.setup()
test_... | Add test for process normalized | Add test for process normalized
| Python | apache-2.0 | erinspace/scrapi,erinspace/scrapi,fabianvf/scrapi,mehanig/scrapi,CenterForOpenScience/scrapi,CenterForOpenScience/scrapi,felliott/scrapi,felliott/scrapi,fabianvf/scrapi,mehanig/scrapi |
5d39c34994d2c20b02d60d6e9f19cfd62310828b | sumy/models/dom/_paragraph.py | sumy/models/dom/_paragraph.py | # -*- coding: utf8 -*-
from __future__ import absolute_import
from __future__ import division, print_function, unicode_literals
from itertools import chain
from ..._compat import unicode_compatible
from ...utils import cached_property
from ._sentence import Sentence
@unicode_compatible
class Paragraph(object):
... | # -*- coding: utf8 -*-
from __future__ import absolute_import
from __future__ import division, print_function, unicode_literals
from itertools import chain
from ..._compat import unicode_compatible
from ...utils import cached_property
from ._sentence import Sentence
@unicode_compatible
class Paragraph(object):
... | Create immutable objects for paragraph instances | Create immutable objects for paragraph instances
There a lot of paragraph objects in parsed document.
It saves some memory during summarization.
| Python | apache-2.0 | miso-belica/sumy,miso-belica/sumy |
ca4dc40c14426a97c532263135b885c45dcc8e77 | account_payment_mode/models/res_partner_bank.py | account_payment_mode/models/res_partner_bank.py | # -*- coding: utf-8 -*-
# © 2016 Akretion (Alexis de Lattre <alexis.delattre@akretion.com>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import models, fields
class ResPartnerBank(models.Model):
_inherit = 'res.partner.bank'
# TODO: It doesn't work, I don't understand wh... | # -*- coding: utf-8 -*-
# © 2016 Akretion (Alexis de Lattre <alexis.delattre@akretion.com>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import models, fields
class ResPartnerBank(models.Model):
_inherit = 'res.partner.bank'
# I also have to change the label of the field... | Store field acc_type on res.partner.bank, so that we can search and groupby on it | Store field acc_type on res.partner.bank, so that we can search and groupby on it
| Python | agpl-3.0 | CompassionCH/bank-payment,CompassionCH/bank-payment |
e2e730c7f8fb8b0c536971082374171d1eacdf73 | main.py | main.py | import datetime
import os
import json
import aiohttp
from discord.ext import commands
config = json.load(open('config.json'))
class Bot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.session = aiohttp.ClientSession(loop=self.loop)
self.config = ... | import datetime
import os
import json
import aiohttp
import discord
from discord.ext import commands
config = json.load(open('config.json'))
class Bot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.session = aiohttp.ClientSession(loop=self.loop)
... | Change game status to -help | Change game status to -help
| Python | mit | r-robles/rd-bot |
2d1798eb26614d87fca94efff25ea0384ae811b5 | Sketches/MPS/Experiments/Likefile2/likefile/TestLikeFile.py | Sketches/MPS/Experiments/Likefile2/likefile/TestLikeFile.py | #!/usr/bin/python
import time
from background import background
from Kamaelia.UI.Pygame.Text import Textbox, TextDisplayer
from LikeFile import LikeFile
background().start()
import Queue
TD = LikeFile(
TextDisplayer(position=(20, 90),
text_height=36,
screen_width... | #!/usr/bin/python
import time
from background import background
from Kamaelia.UI.Pygame.Text import Textbox, TextDisplayer
from LikeFile import LikeFile
background().start()
import Queue
TD = LikeFile(
TextDisplayer(position=(20, 90),
text_height=36,
screen_width... | Test harness changed to forward the message recieved over the like-file interface to the other one, using it's like-file interface | Test harness changed to forward the message recieved over the like-file
interface to the other one, using it's like-file interface
Michael
| Python | apache-2.0 | sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia |
ff73134e836b3950ba15410bac6e1bfe1dcd6d65 | django_rq/decorators.py | django_rq/decorators.py | from rq.decorators import job as _rq_job
from .queues import get_queue
def job(func_or_queue, connection=None, *args, **kwargs):
"""
The same as RQ's job decorator, but it works automatically works out
the ``connection`` argument from RQ_QUEUES.
And also, it allows simplified ``@job`` syntax to put ... | from django.utils import six
from rq.decorators import job as _rq_job
from .queues import get_queue
def job(func_or_queue, connection=None, *args, **kwargs):
"""
The same as RQ's job decorator, but it works automatically works out
the ``connection`` argument from RQ_QUEUES.
And also, it allows simpl... | Replace basestring to six.string_types. Now python 3.3, 3.2 pass tests. | Replace basestring to six.string_types. Now python 3.3, 3.2 pass tests.
Take django.utils.six dependency
| Python | mit | ryanisnan/django-rq,viaregio/django-rq,lechup/django-rq,viaregio/django-rq,ui/django-rq,1024inc/django-rq,sbussetti/django-rq,meteozond/django-rq,sbussetti/django-rq,ryanisnan/django-rq,ui/django-rq,lechup/django-rq,mjec/django-rq,meteozond/django-rq,1024inc/django-rq,mjec/django-rq |
0332284ce3ef43af7d3010688514f457ffaac774 | support/appveyor-build.py | support/appveyor-build.py | #!/usr/bin/env python
# Build the project on AppVeyor.
import os
from subprocess import check_call
build = os.environ['BUILD']
config = os.environ['CONFIG']
path = os.environ['PATH']
cmake_command = ['cmake', '-DFMT_PEDANTIC=ON', '-DCMAKE_BUILD_TYPE=' + config]
if build == 'mingw':
cmake_command.append('-GMinGW Mak... | #!/usr/bin/env python
# Build the project on AppVeyor.
import os
from subprocess import check_call
build = os.environ['BUILD']
config = os.environ['CONFIG']
path = os.environ['PATH']
cmake_command = ['cmake', '-DFMT_PEDANTIC=ON', '-DCMAKE_BUILD_TYPE=' + config]
if build == 'mingw':
cmake_command.append('-GMinGW Mak... | Fix MinGW build on Appveyor by changing search path order | Fix MinGW build on Appveyor by changing search path order
C:\MinGW\bin should go first to prevent executables from older
version of MinGW in C:\MinGW\mingw32 being picked up.
| Python | bsd-2-clause | cppformat/cppformat,seungrye/cppformat,dean0x7d/cppformat,dean0x7d/cppformat,seungrye/cppformat,mojoBrendan/fmt,lightslife/cppformat,nelson4722/cppformat,lightslife/cppformat,blaquee/cppformat,alabuzhev/fmt,lightslife/cppformat,Jopie64/cppformat,cppformat/cppformat,seungrye/cppformat,wangshijin/cppformat,blaquee/cppfor... |
d1a2a4c2ee7fda2bfde369bb6311719e72c75a3d | corehq/blobs/tasks.py | corehq/blobs/tasks.py | from __future__ import absolute_import
from datetime import datetime
from celery.task import periodic_task
from celery.schedules import crontab
from corehq.util.datadog.gauges import datadog_counter
from corehq.blobs.models import BlobExpiration
from corehq.blobs import get_blob_db
@periodic_task(run_every=crontab(... | from __future__ import absolute_import
from datetime import datetime
from celery.task import periodic_task
from celery.schedules import crontab
from corehq.util.datadog.gauges import datadog_counter
from corehq.blobs.models import BlobExpiration
from corehq.blobs import get_blob_db
@periodic_task(run_every=crontab(... | Delete expired blobs in batches | Delete expired blobs in batches | Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq |
d98829d34e49b542097b113d17e6216199483986 | rbopt.py | rbopt.py | #-----------------------------------------------------------------------------#
# MODULE DESCRIPTION #
#-----------------------------------------------------------------------------#
"""RedBrick Options Module; contains RBOpt class."""
#------------------------... | #-----------------------------------------------------------------------------#
# MODULE DESCRIPTION #
#-----------------------------------------------------------------------------#
"""RedBrick Options Module; contains RBOpt class."""
#------------------------... | Change to new attribute names. | Change to new attribute names.
| Python | unlicense | gruunday/useradm,gruunday/useradm,gruunday/useradm |
53b22654b015d1450fe124bc01a2f1bffba816a2 | test_hpack_integration.py | test_hpack_integration.py | # -*- coding: utf-8 -*-
"""
This module defines substantial HPACK integration tests. These can take a very
long time to run, so they're outside the main test suite, but they need to be
run before every change to HPACK.
"""
from hyper.http20.hpack import Decoder
from binascii import unhexlify
class TestHPACKDecoderInte... | # -*- coding: utf-8 -*-
"""
This module defines substantial HPACK integration tests. These can take a very
long time to run, so they're outside the main test suite, but they need to be
run before every change to HPACK.
"""
from hyper.http20.hpack import Decoder
from hyper.http20.huffman import HuffmanDecoder
from hyper... | Use the correct decoder for the test. | Use the correct decoder for the test.
| Python | mit | Lukasa/hyper,masaori335/hyper,lawnmowerlatte/hyper,fredthomsen/hyper,irvind/hyper,lawnmowerlatte/hyper,masaori335/hyper,jdecuyper/hyper,irvind/hyper,fredthomsen/hyper,plucury/hyper,plucury/hyper,Lukasa/hyper,jdecuyper/hyper |
86b447be632c18292369c100f93d3c036231b832 | setup.py | setup.py | from distutils.core import setup
from perfection import __version__ as VERSION
setup(
name='perfection',
version=VERSION,
url='https://github.com/eddieantonio/perfection',
license='MIT',
author='Eddie Antonio Santos',
author_email='easantos@ualberta.ca',
description='Perfect hashing utiliti... | from distutils.core import setup
from perfection import __version__ as VERSION
from codecs import open
setup(
name='perfection',
version=VERSION,
url='https://github.com/eddieantonio/perfection',
license='MIT',
author='Eddie Antonio Santos',
author_email='easantos@ualberta.ca',
description... | Use codecs in Python 2. | Use codecs in Python 2.
| Python | mit | eddieantonio/perfection |
cf3322e1e85418e480f75d960244e506c0df4505 | setup.py | setup.py | #
# setup.py
#
# Copyright (c) 2013 Luis Garcia.
# This source file is subject to terms of the MIT License. (See file LICENSE)
#
"""Setup script for the scope library."""
from distutils.core import setup
NAME = 'scope'
VERSION = '0.1.1'
DESCRIPTION = 'Template library for multi-language code generation'
AUTHOR = 'Lu... | #
# setup.py
#
# Copyright (c) 2013 Luis Garcia.
# This source file is subject to terms of the MIT License. (See file LICENSE)
#
"""Setup script for the scope library."""
from distutils.core import setup
NAME = 'scope'
VERSION = '0.1.1'
DESCRIPTION = 'Python library for creating code templates'
AUTHOR = 'Luis Garcia... | Update description and add more classifiers | Update description and add more classifiers
| Python | mit | lrgar/scope |
3f9a6944763a75171388c3c8b812d71bf45c1219 | test/test_integration.py | test/test_integration.py | import unittest
import http.client
import time
class TestStringMethods(unittest.TestCase):
def test_404NoConfig(self):
connRouter = http.client.HTTPConnection("localhost", 8666)
connConfig = http.client.HTTPConnection("localhost", 8888)
connRouter.request("GET", "/google2")
respons... | import unittest
import http.client
import time
class TestStringMethods(unittest.TestCase):
def test_404NoConfig(self):
connRouter = http.client.HTTPConnection("localhost", 8666)
connConfig = http.client.HTTPConnection("localhost", 8888)
connRouter.request("GET", "/google")
response... | Fix test to use /google instead of /google2 | Fix test to use /google instead of /google2
| Python | apache-2.0 | dhiaayachi/dynx,dhiaayachi/dynx |
8c46e91ec66fc1ee15f037109e78030c2fcd1bf8 | tests/test_middleware.py | tests/test_middleware.py | from os import environ
from unittest import TestCase
environ['DJANGO_SETTINGS_MODULE'] = 'test_settings'
from incuna_auth.middleware import LoginRequiredMiddleware
class AuthenticatedUser(object):
def is_authenticated(self):
return True
class AnonymousUser(object):
def is_authenticated(self):
... | from os import environ
from unittest import TestCase
environ['DJANGO_SETTINGS_MODULE'] = 'test_settings'
from incuna_auth.middleware import LoginRequiredMiddleware
class AuthenticatedUser(object):
def is_authenticated(self):
return True
class AnonymousUser(object):
def is_authenticated(self):
... | Add test for non-exempt, non-protected URLs. | Add test for non-exempt, non-protected URLs.
| Python | bsd-2-clause | incuna/incuna-auth,incuna/incuna-auth,ghickman/incuna-auth,ghickman/incuna-auth |
297ba0a2a3e1d91031093881bcd8d57977e9597c | setup.py | setup.py | from distutils.core import setup
setup(
name='Supermega',
version='0.1.0',
author='Lorenz Bauer',
packages=['supermega', 'supermega.schemata'],
# scripts=['bin/*.py'],
# url='http://pypi.python.org/pypi/TowelStuff/',
license='LICENSE.txt',
description='The overengineered way to access t... | from distutils.core import setup
setup(
name='Supermega',
version='0.1.0',
author='Lorenz Bauer',
packages=['supermega', 'supermega.schemata'],
# scripts=['bin/*.py'],
# url='http://pypi.python.org/pypi/TowelStuff/',
license='LICENSE.txt',
description='The overengineered way to access t... | Update dependencies and add tested version information | Update dependencies and add tested version information
| Python | bsd-3-clause | lmb/Supermega |
3721067c0b18b1f8fb90057bccb206dc9e374f21 | srrun.py | srrun.py | #!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at http://mozilla.org/MPL/2.0/.
import copy
import os
import subprocess
import sys
mypath = os.path.abspath(__file__)
mydir = os.... | #!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at http://mozilla.org/MPL/2.0/.
import copy
import os
import subprocess
import sys
mypath = os.path.abspath(__file__)
mydir = os.... | Set umask appropriately for all processes | Set umask appropriately for all processes
| Python | mpl-2.0 | mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge |
dad401390178c9f96a0a68f1fa9e5c82304ad60d | mail_factory/previews.py | mail_factory/previews.py | from base64 import b64encode
from django.conf import settings
from mail_factory.messages import EmailMultiRelated
class PreviewMessage(EmailMultiRelated):
def has_body_html(self):
"""Test if a message contains an alternative rendering in text/html"""
return 'text/html' in self.alternatives
... | # -*- coding: utf-8 -*-
from django.conf import settings
from django.utils.encoding import smart_str
from mail_factory.messages import EmailMultiRelated
class PreviewMessage(EmailMultiRelated):
def has_body_html(self):
"""Test if a message contains an alternative rendering in text/html"""
return ... | Remove `body_html_escaped`. Add rendering filtered by formats. | Remove `body_html_escaped`.
Add rendering filtered by formats.
| Python | bsd-3-clause | novafloss/django-mail-factory,novafloss/django-mail-factory |
3045f6ffbd8433d60178fee59550d30064015b46 | tm/tm.py | tm/tm.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import subprocess
import argparse
__version__ = 1.0
__description__ = "A tmux wrapper featuring shortcuts and session presets."
def main(argv):
parser = argparse.ArgumentParser(description=__description__)
parser.add_argument("session",
... | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import subprocess
import argparse
__version__ = 1.0
__description__ = "A tmux wrapper featuring shortcuts and session presets."
def main(argv):
parser = argparse.ArgumentParser(description=__description__)
parser.add_argument("session",
... | Add kill, list, and create commands | Add kill, list, and create commands
| Python | mit | ethanal/tm |
ba4a20ee94355464ec8b35750660f7b8fe0cc3db | tests/test_yaml2ncml.py | tests/test_yaml2ncml.py | from __future__ import (absolute_import, division, print_function)
import subprocess
import tempfile
def test_call():
output = subprocess.check_output(['yaml2ncml', 'roms_0.yaml'])
with open('base_roms_test.ncml') as f:
expected = f.read()
assert output.decode() == expected
def test_save_file()... | from __future__ import (absolute_import, division, print_function)
import subprocess
import tempfile
import pytest
import ruamel.yaml as yaml
from yaml2ncml import build
def test_call():
output = subprocess.check_output(['yaml2ncml', 'roms_0.yaml'])
with open('base_roms_test.ncml') as f:
expected =... | Test bad call/better error msg | Test bad call/better error msg
| Python | mit | ocefpaf/yaml2ncml,USGS-CMG/yaml2ncml |
42710918df931a6839364e58548dcce2d1346324 | src/tests/gopigo_stub.py | src/tests/gopigo_stub.py | """A stub for the gopigo module."""
calls = []
def servo(angle):
calls.append('servo({0})'.format(angle))
def set_speed(speed):
calls.append('set_speed({0}'.format(speed))
def stop():
calls.append('stop()')
def trim_write(trim):
calls.append('trim_write({0})'.format(trim))
def us_dist(pin):
calls.append('us_... | """A stub for the gopigo module."""
calls = []
def servo(angle):
calls.append('servo({0})'.format(angle))
def set_speed(speed):
calls.append('set_speed({0})'.format(speed))
def set_left_speed(speed):
calls.append('set_left_speed({0})'.format(speed))
def set_right_speed(speed):
calls.append('set_right_speed({0}... | Support for testing robot steering. | Support for testing robot steering.
| Python | mit | RLGarner1/robot_maze,mattskone/robot_maze |
6683bf5e248bdd52f0ebc175dc7c94d5677ba6dd | tools/manifest/utils.py | tools/manifest/utils.py | import os
from contextlib import contextmanager
@contextmanager
def effective_user(uid, gid):
"""
A ContextManager that executes code in the with block with effective uid / gid given
"""
original_uid = os.geteuid()
original_gid = os.getegid()
os.setegid(gid)
os.seteuid(uid)
yield
o... | import os
from contextlib import contextmanager
@contextmanager
def effective_user(uid, gid):
"""
A ContextManager that executes code in the with block with effective uid / gid given
"""
original_uid = os.geteuid()
original_gid = os.getegid()
os.setegid(gid)
os.seteuid(uid)
try:
... | Make effective_user handle exceptions properly | Make effective_user handle exceptions properly
Right now the context manager is just syntactic sugar - setegid
and seteuid aren't called if there's an exception.
Change-Id: I9e2f1d0ada00b03099fe60a8735db1caef8527e9
| Python | mit | wikimedia/operations-software-tools-manifest |
004345f50edd4c4b08727efaf5de7ee60f1f1e48 | caffe2/python/operator_test/softplus_op_test.py | caffe2/python/operator_test/softplus_op_test.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core
from hypothesis import given
import caffe2.python.hypothesis_test_util as hu
import unittest
class TestSoftplus(hu.HypothesisTestCase):
... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core
from hypothesis import given
import caffe2.python.hypothesis_test_util as hu
import unittest
class TestSoftplus(hu.HypothesisTestCase):
... | Fix gradient checking for softplus op | Fix gradient checking for softplus op
Summary:
kmatzen why did you set the stepsize in https://github.com/caffe2/caffe2/commit/ff84e7dea6e118710859d62a7207c06b87ae992e?
The test is flaky before this change. Solid afterwards.
Closes https://github.com/caffe2/caffe2/pull/841
Differential Revision: D5292112
Pulled By:... | Python | apache-2.0 | sf-wind/caffe2,xzturn/caffe2,sf-wind/caffe2,pietern/caffe2,sf-wind/caffe2,xzturn/caffe2,Yangqing/caffe2,Yangqing/caffe2,davinwang/caffe2,sf-wind/caffe2,xzturn/caffe2,pietern/caffe2,bwasti/caffe2,sf-wind/caffe2,bwasti/caffe2,davinwang/caffe2,davinwang/caffe2,xzturn/caffe2,pietern/caffe2,pietern/caffe2,davinwang/caffe2,Y... |
a06c3845b2e827ff34bdd34844db39a74826f123 | meteocalc/mimicfloat.py | meteocalc/mimicfloat.py | import operator
def math_method(name, right=False):
def wrapper(self, other):
value = self.value
math_func = getattr(operator, name)
if right:
value, other = other, value
result = math_func(value, other)
return type(self)(result, units=self.units)
return ... | from functools import wraps
import operator
def math_method(name, right=False):
math_func = getattr(operator, name)
@wraps(math_func)
def wrapper(self, other):
value = self.value
if right:
value, other = other, value
result = math_func(value, other)
return ty... | Make math method wrapping nicer | Make math method wrapping nicer
| Python | mit | malexer/meteocalc |
a8b4553b76f3303017818e60df5504445a6556d0 | dj_experiment/conf.py | dj_experiment/conf.py | import os
from appconf import AppConf
from django.conf import settings
class DjExperimentAppConf(AppConf):
DATA_DIR = "./"
BASE_DATA_DIR = os.path.join(settings.BASE_DIR, 'data')
SEPARATOR = "."
OUTPUT_PREFIX = ""
OUTPUT_SUFFIX = ".nc"
CELERY_BROKER_URL = 'amqp://guest:guest@localhost:5672//'... | import os
from appconf import AppConf
from django.conf import settings
class DjExperimentAppConf(AppConf):
DATA_DIR = "./"
BASE_DATA_DIR = os.path.join(settings.BASE_DIR, 'data')
SEPARATOR = "."
OUTPUT_PREFIX = ""
OUTPUT_SUFFIX = ".nc"
CELERY_BROKER_URL = 'amqp://guest:guest@localhost:5672//'... | Make taggit case-insensitive by default | Make taggit case-insensitive by default
| Python | mit | francbartoli/dj-experiment,francbartoli/dj-experiment |
5eb9c9bf89904f25785955050d991bd4ec20db66 | PRESUBMIT.py | PRESUBMIT.py | # Copyright (c) 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Top-level presubmit script for catapult.
See https://www.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the pres... | # Copyright (c) 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Top-level presubmit script for catapult.
See https://www.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the pres... | Remove custom project name, since it changes copyright statements. | Remove custom project name, since it changes copyright statements.
R=qyearsley@chromium.org
Review URL: https://codereview.chromium.org/1212843006.
| Python | bsd-3-clause | SummerLW/Perf-Insight-Report,catapult-project/catapult-csm,catapult-project/catapult-csm,benschmaus/catapult,SummerLW/Perf-Insight-Report,scottmcmaster/catapult,catapult-project/catapult-csm,danbeam/catapult,benschmaus/catapult,scottmcmaster/catapult,benschmaus/catapult,benschmaus/catapult,modulexcite/catapult,catapult... |
686a71b4493adf39ed0b9335a1c8f83cf8ce5bfe | ml_metadata/__init__.py | ml_metadata/__init__.py | # Copyright 2019 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 agreed to in writing, ... | # Copyright 2019 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 agreed to in writing, ... | Add import exception module init. | Add import exception module init.
PiperOrigin-RevId: 421941098
| Python | apache-2.0 | google/ml-metadata,google/ml-metadata,google/ml-metadata,google/ml-metadata |
fd3ee57a352fd815d2746f3a72196ac62fdceb5c | src/integrationtest/python/shutdown_daemon_tests.py | src/integrationtest/python/shutdown_daemon_tests.py | #!/usr/bin/env python
from __future__ import print_function, absolute_import, division
import os
import shutil
import subprocess
import tempfile
import time
import unittest2
class ShutdownDaemonTests(unittest2.TestCase):
def setUp(self):
self.temp_dir = tempfile.mkdtemp(prefix="succubus-test")
sel... | #!/usr/bin/env python
from __future__ import print_function, absolute_import, division
import os
import shutil
import subprocess
import tempfile
import time
import unittest2
class ShutdownDaemonTests(unittest2.TestCase):
def setUp(self):
self.temp_dir = tempfile.mkdtemp(prefix="succubus-test")
sel... | Revert debugging changes: clean up tempfiles | Revert debugging changes: clean up tempfiles
| Python | apache-2.0 | ImmobilienScout24/succubus |
055c15a8e837014bb74a601df776eae642edfd61 | auth_mac/models.py | auth_mac/models.py | from django.db import models
from django.contrib.auth.models import User
import datetime
def default_expiry_time():
return datetime.datetime.now() + datetime.timedelta(days=1)
def random_string():
return User.objects.make_random_password(16)
class Credentials(models.Model):
"Keeps track of issued MAC credentia... | from django.db import models
from django.contrib.auth.models import User
import datetime
def default_expiry_time():
return datetime.datetime.now() + datetime.timedelta(days=1)
def random_string():
return User.objects.make_random_password(16)
class Credentials(models.Model):
"Keeps track of issued MAC credentia... | Add a unicode method for the Nonces | Add a unicode method for the Nonces
| Python | mit | ndevenish/auth_mac |
97a068d7a83fffd6ed9307ac33da3835e449a935 | obj_sys/default_settings.py | obj_sys/default_settings.py | __author__ = 'weijia'
INSTALLED_APPS += (
'mptt',
'django_mptt_admin',
'tagging',
'ajax_select',
'django_extensions',
'geoposition',
'obj_sys',
# "obj_sys.apps.ObjSysConfig",
)
TEMPLATE_CONTEXT_PROCESSORS += (
'django.core.context_processors.request',
) | __author__ = 'weijia'
INSTALLED_APPS += (
'mptt',
'reversion',
'django_mptt_admin',
'tagging',
'ajax_select',
'django_extensions',
'geoposition',
'obj_sys',
# "obj_sys.apps.ObjSysConfig",
)
TEMPLATE_CONTEXT_PROCESSORS += (
'django.core.context_processors.request',
)
# MIDDLEW... | Add reversion middle ware, but not work. | Add reversion middle ware, but not work.
| Python | bsd-3-clause | weijia/obj_sys,weijia/obj_sys |
df131a8f482e712546555e0cb28a58edcf960bf2 | apps/planet/management/commands/update_all_feeds.py | apps/planet/management/commands/update_all_feeds.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand
from planet.management.commands import process_feed
from planet.models import Feed
from planet.signals import feeds_updated
class Command(BaseCommand):
"""
Command to add a complete blog feed to our db.
Us... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime
from django.core.management.base import BaseCommand
from planet.management.commands import process_feed
from planet.models import Feed
from planet.signals import feeds_updated
class Command(BaseCommand):
"""
Command to add a complete... | Print total number of posts added and total elapsed time | Print total number of posts added and total elapsed time
| Python | bsd-3-clause | matagus/django-planet,matagus/django-planet,jilljenn/django-planet,jilljenn/django-planet |
4c2b4d10beac508747364680d9e9a5d7c3488f97 | confab/api.py | confab/api.py | """
Non-init module for doing convenient * imports from.
"""
from confab.diff import diff
from confab.generate import generate
from confab.pull import pull
from confab.push import push
| """
Non-init module for doing convenient * imports from.
"""
# core
from confab.conffiles import ConfFiles
# jinja2 environment loading
from confab.loaders import load_environment_from_dir, load_environment_from_package
# data loading
from confab.data import load_data_from_dir
# fabric tasks
from confab.diff import... | Add loaders and ConfFiles model to public API. | Add loaders and ConfFiles model to public API.
| Python | apache-2.0 | locationlabs/confab |
1a7bf8c3fd5560a8f6cba88607facf8321a97818 | police_api/exceptions.py | police_api/exceptions.py | from requests.exceptions import HTTPError
class BaseException(Exception):
pass
class APIError(BaseException, HTTPError):
"""
The API responded with a non-200 status code.
"""
def __init__(self, http_error):
self.message = getattr(http_error, 'message', None)
self.response = geta... | from requests.exceptions import HTTPError
class BaseException(Exception):
pass
class APIError(BaseException, HTTPError):
"""
The API responded with a non-200 status code.
"""
def __init__(self, http_error):
self.message = getattr(http_error, 'message', None)
self.response = geta... | Add the 'status_code' attribute to the APIError exception if it's available | Add the 'status_code' attribute to the APIError exception if it's available
| Python | mit | rkhleics/police-api-client-python |
bc20949f8e5461d6ffa901d24677acb1bae922dd | mangopaysdk/types/payinexecutiondetailsdirect.py | mangopaysdk/types/payinexecutiondetailsdirect.py | from mangopaysdk.types.payinexecutiondetails import PayInExecutionDetails
class PayInExecutionDetailsDirect(PayInExecutionDetails):
def __init__(self):
# direct card
self.CardId = None
self.SecureModeReturnURL = None
self.SecureModeRedirectURL = None
# Mode3DSType ... | from mangopaysdk.types.payinexecutiondetails import PayInExecutionDetails
class PayInExecutionDetailsDirect(PayInExecutionDetails):
def __init__(self):
# direct card
self.CardId = None
self.SecureModeReturnURL = None
self.SecureModeRedirectURL = None
# Mode3DSType ... | Add StatementDescriptor for card direct payins | Add StatementDescriptor for card direct payins | Python | mit | chocopoche/mangopay2-python-sdk,Mangopay/mangopay2-python-sdk |
b7a8711afdbd4eaf7dfbf4ae4daab9d340c192b3 | numdifftools/testing.py | numdifftools/testing.py | '''
Created on Apr 4, 2016
@author: pab
'''
import inspect
import numpy as np
def rosen(x):
"""Rosenbrock function
This is a non-convex function used as a performance test problem for
optimization algorithms introduced by Howard H. Rosenbrock in 1960.[1]
"""
x = np.atleast_1d(x)
return (1 - ... | '''
Created on Apr 4, 2016
@author: pab
'''
import inspect
import numpy as np
def rosen(x):
"""Rosenbrock function
This is a non-convex function used as a performance test problem for
optimization algorithms introduced by Howard H. Rosenbrock in 1960.[1]
"""
x = np.atleast_1d(x)
return (1 - ... | Replace string interpolation with format() | Replace string interpolation with format()
| Python | bsd-3-clause | pbrod/numdifftools,pbrod/numdifftools |
f4d1cebe889e4c55bab104f9a2c993c8ed153d34 | ubitflashtool/__main__.py | ubitflashtool/__main__.py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
import sys
from ubitflashtool.cli import main
from ubitflashtool.gui import open_editor
if __name__ == "__main__":
if len(sys.argv) > 1 and (sys.argv[1] == '-g' or sys.argv[1] == '--gui'):
open_editor()
else:
main(sys.argv[1:])
| #!/usr/bin/env python2
# -*- coding: utf-8 -*-
import sys
from ubitflashtool.cli import main as cli_main
from ubitflashtool.gui import open_editor
def main():
if len(sys.argv) > 1 and (sys.argv[1] == '-g' or sys.argv[1] == '--gui'):
open_editor()
else:
cli_main(sys.argv[1:])
if __name__ == "__... | Fix command line entry point | Fix command line entry point
| Python | mit | carlosperate/ubitflashtool |
aafb16a0f96f31a5371ae19bfc1dfc38cc2bb878 | romanesco/executors/python.py | romanesco/executors/python.py | import imp
import json
import sys
def run(task, inputs, outputs, task_inputs, task_outputs, **kwargs):
custom = imp.new_module("custom")
for name in inputs:
custom.__dict__[name] = inputs[name]["script_data"]
custom.__dict__['_job_manager'] = kwargs.get('_job_manager')
try:
exec tas... | import imp
import json
import sys
def run(task, inputs, outputs, task_inputs, task_outputs, **kwargs):
custom = imp.new_module("custom")
custom.__dict__['_job_manager'] = kwargs.get('_job_manager')
for name in inputs:
custom.__dict__[name] = inputs[name]["script_data"]
try:
exec tas... | Allow _job_manager special object to be overriden by task if desired | Allow _job_manager special object to be overriden by task if desired
| Python | apache-2.0 | Kitware/romanesco,girder/girder_worker,girder/girder_worker,Kitware/romanesco,Kitware/romanesco,Kitware/romanesco,girder/girder_worker |
caf6514b6af278583d9816b722fab9456d0ad9f1 | pelicanconf.py | pelicanconf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'DLR'
SITENAME = u'RCE'
SITEURL = ''
PATH = 'content'
TIMEZONE = 'Europe/Paris'
DEFAULT_LANG = u'en'
DEFAULT_DATE_FORMAT = '%a %d %B %Y'
THEME = 'themes/polar'
# Feed generation is usually not desired when developi... | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'DLR'
SITENAME = u'RCE'
SITEURL = ''
PATH = 'content'
TIMEZONE = 'Europe/Paris'
DEFAULT_LANG = u'en'
DEFAULT_DATE_FORMAT = '%a %d %B %Y'
THEME = 'themes/polar'
# Feed generation is usually not desired when developi... | Update link to institute in footer to say "Institute for Software Technology" | Update link to institute in footer to say "Institute for Software Technology" | Python | cc0-1.0 | DLR-SC/rce-website,DLR-SC/rce-website,DLR-SC/rce-website,DLR-SC/rce-website,DLR-SC/rce-website |
4511fef9b2c6521197dc64963c58c1a77e3475b3 | counterid.py | counterid.py | #!/usr/bin/env python
"""counterid - Simple utility to discover perfmon counter paths"""
# Compile to EXE using c:\Python27\scripts\pyinstaller.exe -F counterid.py
__author__ = 'scottv@rbh.com (Scott Vintinner)'
import win32pdh
# Will display a window with available counters. Click add to print out counter ... | #!/usr/bin/env python
"""counterid - Simple utility to discover perfmon counter paths"""
# pip install pyinstaller
# Compile to EXE using pyinstaller.exe -F counterid.py
__author__ = 'scottv@rbh.com (Scott Vintinner)'
import win32pdh
# Will display a window with available counters. Click add to print out counter na... | Update to make compatible with Python 3 | Update to make compatible with Python 3
| Python | mit | flakshack/pyPerfmon |
828be5ee4640ddd9ee595b4ba15fa973ccbcb82f | account_fiscal_position_no_source_tax/account.py | account_fiscal_position_no_source_tax/account.py | 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... | FIX fiscal position no source tax on v7 api | FIX fiscal position no source tax on v7 api
| Python | agpl-3.0 | ingadhoc/partner,ingadhoc/odoo-addons,maljac/odoo-addons,bmya/odoo-addons,levkar/odoo-addons,ingadhoc/odoo-addons,ingadhoc/sale,levkar/odoo-addons,ingadhoc/account-financial-tools,sysadminmatmoz/ingadhoc,ClearCorp/account-financial-tools,HBEE/odoo-addons,jorsea/odoo-addons,sysadminmatmoz/ingadhoc,adhoc-dev/odoo-addons,... |
6a0ab2b681b4a9ce9392687b6b7d9e1d14015147 | nustack/doc/genall.py | nustack/doc/genall.py | #!python3
import os, glob, sys
import nustack
import nustack.doc.gen as gen
exportdir = sys.argv[1]
# Get module names
path = os.path.join(os.path.dirname(nustack.__file__), "stdlib")
print("Path to standard library:", path)
os.chdir(path)
modnames = (f[:-3] for f in glob.iglob("*.py") if f != '__init__.py')
for mod... | #!python3
import os, glob, sys
import nustack
import gen
exportdir = sys.argv[1]
# Get module names
path = os.path.join(nustack.__path__[0], "stdlib")
print("Path to standard library:", path)
os.chdir(path)
modnames = (f[:-3] for f in glob.iglob("*.py") if f != '__init__.py')
for mod in modnames:
print("Generati... | Update documentation generator for new directory structure. | Update documentation generator for new directory structure.
| Python | mit | BookOwl/nustack |
8760fa44a7acb8d79ed177349d8c148c0682a2ab | pybossa/auth/category.py | pybossa/auth/category.py | from flask.ext.login import current_user
def create(app=None):
if current_user.is_authenticated():
if current_user.admin is True:
return True
else:
return False
else:
return False
def read(app=None):
return True
def update(app):
return create(app)
... | from flask.ext.login import current_user
def create(category=None):
if current_user.is_authenticated():
if current_user.admin is True:
return True
else:
return False
else:
return False
def read(category=None):
return True
def update(category):
return... | Fix a typo in the variable name | Fix a typo in the variable name
| Python | agpl-3.0 | geotagx/geotagx-pybossa-archive,Scifabric/pybossa,proyectos-analizo-info/pybossa-analizo-info,geotagx/geotagx-pybossa-archive,CulturePlex/pybossa,geotagx/pybossa,proyectos-analizo-info/pybossa-analizo-info,jean/pybossa,harihpr/tweetclickers,CulturePlex/pybossa,geotagx/pybossa,harihpr/tweetclickers,stefanhahmann/pybossa... |
244a51de04410335309446bb9a051338ea6d2a6a | pycnic/data.py | pycnic/data.py | STATUSES = {
200: "200 OK",
201: "201 Created",
202: "202 Accepted",
300: "300 Multiple Choices",
301: "301 Moved Permanently",
302: "302 Found",
304: "304 Not Modified",
400: "400 Bad Request",
401: "401 Unauthorized",
403: "403 Forbidden"... | STATUSES = {
200: "200 OK",
201: "201 Created",
202: "202 Accepted",
204: "204 No Content",
300: "300 Multiple Choices",
301: "301 Moved Permanently",
302: "302 Found",
303: "303 See Other",
304: "304 Not Modified",
307: "307 Temporary Redi... | Add more HTTP/1.1 status codes | Add more HTTP/1.1 status codes
| Python | mit | nullism/pycnic,nullism/pycnic |
ce380319562eb94e252c74de7b6b1ac18a357466 | chainer/training/extensions/value_observation.py | chainer/training/extensions/value_observation.py | import time
from chainer.training import extension
def observe_value(key, target_func):
"""Returns a trainer extension to continuously record a value.
Args:
key (str): Key of observation to record.
target_func (function): Function that returns the value to record.
It must take on... | import time
from chainer.training import extension
def observe_value(key, target_func):
"""Returns a trainer extension to continuously record a value.
Args:
key (str): Key of observation to record.
target_func (function): Function that returns the value to record.
It must take on... | Add links for the document | Add links for the document
| Python | mit | ktnyt/chainer,hvy/chainer,aonotas/chainer,niboshi/chainer,okuta/chainer,chainer/chainer,anaruse/chainer,niboshi/chainer,ronekko/chainer,okuta/chainer,jnishi/chainer,wkentaro/chainer,cupy/cupy,chainer/chainer,okuta/chainer,wkentaro/chainer,jnishi/chainer,delta2323/chainer,rezoo/chainer,hvy/chainer,hvy/chainer,jnishi/cha... |
2b6fcb362a6dbf875075af13787bba76928098c3 | kinoreel_backend/urls.py | kinoreel_backend/urls.py | from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth.views import login
from movies.urls import urlpatterns as movie_urls
urlpatterns = [
url(r'^', movie_urls, name='movies'),
url(r'^admin/', admin.site.urls),
]
| from django.conf.urls import include, url
from django.contrib import admin
from movies.urls import urlpatterns as movie_urls
urlpatterns = [
url(r'^', include(movie_urls), name='movies'),
url(r'^admin/', admin.site.urls),
]
| Include is still needed for the url patterns | Include is still needed for the url patterns
| Python | mit | kinoreel/kinoreel-backend,kinoreel/kinoreel-backend |
46a30fa8d52c1c36e110a8e028444b27e39c9b6d | radio/management/commands/export_talkgroups.py | radio/management/commands/export_talkgroups.py | import sys
import datetime
import csv
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from django.utils import timezone
from radio.models import *
class Command(BaseCommand):
help = 'Import talkgroup info'
def add_arguments(self, parser):
parser.add_... | import sys
import datetime
import csv
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from django.utils import timezone
from radio.models import *
class Command(BaseCommand):
help = 'Export talkgroup info'
def add_arguments(self, parser):
parser.add_... | Update help line and print system number | Update help line and print system number
| Python | mit | ScanOC/trunk-player,ScanOC/trunk-player,ScanOC/trunk-player,ScanOC/trunk-player |
0c29ab9f906ca73605e3626c06dd14f573d5fa8f | TM1py/Exceptions/Exceptions.py | TM1py/Exceptions/Exceptions.py | # -*- coding: utf-8 -*-
# TM1py Exceptions are defined here
class TM1pyException(Exception):
""" The default exception for TM1py
"""
def __init__(self, response, status_code, reason, headers):
self._response = response
self._status_code = status_code
self._reason = reason
... | # -*- coding: utf-8 -*-
# TM1py Exceptions are defined here
class TM1pyException(Exception):
""" The default exception for TM1py
"""
def __init__(self, response, status_code, reason, headers):
self._response = response
self._status_code = status_code
self._reason = reason
... | Update to expand exception string | Update to expand exception string
| Python | mit | OLAPLINE/TM1py |
188ac85b8e8f82a06426467554d608d713d258ef | test/test_get_new.py | test/test_get_new.py | from __future__ import absolute_import, print_function
from ..pyautoupdate.launcher import Launcher
from .pytest_skipif import needinternet
from .pytest_makevers import fixture_update_dir
import os
import sys
import pytest
@needinternet
def test_check_get_new(fixture_update_dir):
"""Test that gets new version f... | from __future__ import absolute_import, print_function
from ..pyautoupdate.launcher import Launcher
from .pytest_skipif import needinternet
from .pytest_makevers import fixture_update_dir
import os
@needinternet
def test_check_get_new(fixture_update_dir):
"""Test that gets new version from internet"""
packag... | Remove unused imports from test_check_get_new | Remove unused imports from test_check_get_new
| Python | lgpl-2.1 | rlee287/pyautoupdate,rlee287/pyautoupdate |
4cfc0967cef576ab5d6ddd0fff7d648e77739727 | test_scriptrunner.py | test_scriptrunner.py | from antZoo.ant import AntJobRunner
ant = AntJobRunner( None )
ant.start()
class Job:
def __init__( self, source ):
self.source = source
j = Job( "/Users/elchupa/code/school/antZoo/localenv/bin/python /Users/elchupa/code/school/antZoo/example_code/word_count.py" )
ant.push( j )
for i in range( 100 ):
ant.... | from antZoo.ant import AntJobRunner
ant = AntJobRunner( None )
ant.start()
class Job:
def __init__( self, source ):
self.source = source
j = Job( "/Users/elchupa/code/school/antZoo/localenv/bin/python /Users/elchupa/code/school/antZoo/example_code/word_count.py" )
ant.push( j )
for i in range( 100 ):
ant.... | Test runs two jobs and 200 tasks | Test runs two jobs and 200 tasks
| Python | mit | streed/antZoo,streed/antZoo |
4661a04d159e0583f16c28d087427fab31c676f6 | foodsaving/management/tests/test_makemessages.py | foodsaving/management/tests/test_makemessages.py | from django.test import TestCase
from ..commands.makemessages import Command as MakeMessagesCommand
class CustomMakeMessagesTest(TestCase):
def test_update_options(self):
options = {
'locale': [],
}
modified_options = MakeMessagesCommand.update_options(**options)
self... | from unittest.mock import patch
from django.test import TestCase
from ..commands.makemessages import Command as MakeMessagesCommand
from django_jinja.management.commands.makemessages import Command as DjangoJinjaMakeMessagesCommand
makemessages = MakeMessagesCommand
django_jinja_makemessages = DjangoJinjaMakeMessages... | Add additional test to increase test coverage | Add additional test to increase test coverage
| Python | agpl-3.0 | yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend |
6f0d09ff5f81518daf30b00311ce4ac052e08c14 | admission_notes/models.py | admission_notes/models.py | import datetime
#from labsys.patients import Patient
from django.db import models
class AdmissionNote(models.Model):
id_gal = models.CharField(max_length=30)
requester = models.CharField(
max_length=255,
help_text="LACEN ou instituto que solicitou o exame",
)
health_unit = models.Char... | import datetime
#from labsys.patients import Patient
from django.db import models
class AdmissionNote(models.Model):
id_gal = models.CharField(
'Número da requisição (GAL interno)',
max_length=30
)
requester = models.CharField(
'Instituto solicitante',
max_length=255,
... | Rename fields and remove verbose_name attr (1st arg is it by default) | :art: Rename fields and remove verbose_name attr (1st arg is it by default)
| Python | mit | gems-uff/labsys,gems-uff/labsys,gems-uff/labsys |
85878d23d598b7d7622f8aa70ef82b7a627aed23 | integration-test/912-missing-building-part.py | integration-test/912-missing-building-part.py | # http://www.openstreetmap.org/way/287494678
z = 18
x = 77193
y = 98529
while z >= 16:
assert_has_feature(
z, x, y, 'buildings',
{ 'kind': 'building',
'id': 287494678 })
z -= 1
x /= 2
y /= 2
| # http://www.openstreetmap.org/way/287494678
z = 18
x = 77193
y = 98529
while z >= 16:
assert_has_feature(
z, x, y, 'buildings',
{ 'kind': 'building_part',
'id': 287494678,
'min_zoom': 16 })
z -= 1
x /= 2
y /= 2
| Update feature kind to account for normalisation and test min_zoom. | Update feature kind to account for normalisation and test min_zoom.
| Python | mit | mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource |
2a0c9cc447e1dffe2eb03c49c0c6801f4303a620 | plugins/imagetypes.py | plugins/imagetypes.py | #
# Copyright (c) SAS Institute Inc.
#
# 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 w... | #
# Copyright (c) SAS Institute Inc.
#
# 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 w... | Swap order of name and description when listing image types | Swap order of name and description when listing image types
Uses the same order as target types, which puts the most important information,
the name, in front.
Refs APPENG-3419
| Python | apache-2.0 | sassoftware/rbuild,sassoftware/rbuild |
405cc83e1532f5277d180964907e964ded5f5da7 | routeros_api/api_communicator/async_decorator.py | routeros_api/api_communicator/async_decorator.py | class AsyncApiCommunicator(object):
def __init__(self, inner):
self.inner = inner
def call(self, *args, **kwargs):
tag = self.inner.send(*args, **kwargs)
return ResponsePromise(self.inner, tag)
class ResponsePromise(object):
def __init__(self, receiver, tag):
self.receiver ... | class AsyncApiCommunicator(object):
def __init__(self, inner):
self.inner = inner
def call(self, *args, **kwargs):
tag = self.inner.send(*args, **kwargs)
return ResponsePromise(self.inner, tag)
class ResponsePromise(object):
def __init__(self, receiver, tag):
self.receiver ... | Allow to run get on promise multiple times. | Allow to run get on promise multiple times.
| Python | mit | kramarz/RouterOS-api,pozytywnie/RouterOS-api,socialwifi/RouterOS-api |
0ed72241dc9f540615954f58995d96401d954a41 | courtreader/opener.py | courtreader/opener.py | import cookielib
import os
import pickle
import urllib2
class Opener:
user_agent = u"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; " + \
u"en-US; rv:1.9.2.11) Gecko/20101012 Firefox/3.6.11"
def __init__(self, name):
self.name = name
# Create page opener that stores cookie
sel... | import cookielib
import os
import pickle
import mechanize
class Opener:
def __init__(self, name):
self.opener = mechanize.Browser()
self.opener.set_handle_robots(False)
def set_cookie(self, name, value):
self.opener.set_cookie(str(name) + '=' + str(value))
def save_cookies(self):
... | Use mechanize instead of urllib2 | Use mechanize instead of urllib2
| Python | mit | bschoenfeld/va-court-scraper,bschoenfeld/va-court-scraper |
90b9a1e6638fd638450b46c6b12439eeb8e40f90 | cumulusci/tasks/github/tests/test_pull_request.py | cumulusci/tasks/github/tests/test_pull_request.py | import mock
import unittest
from cumulusci.core.config import ServiceConfig
from cumulusci.core.config import TaskConfig
from cumulusci.tasks.github import PullRequests
from cumulusci.tests.util import create_project_config
@mock.patch("cumulusci.tasks.github.base.get_github_api_for_user", mock.Mock())
class TestPul... | import mock
import unittest
from cumulusci.core.config import ServiceConfig
from cumulusci.core.config import TaskConfig
from cumulusci.tasks.github import PullRequests
from cumulusci.tests.util import create_project_config
class TestPullRequests(unittest.TestCase):
def test_run_task(self):
project_confi... | Fix test that wasn't running | Fix test that wasn't running
| Python | bsd-3-clause | SalesforceFoundation/CumulusCI,SalesforceFoundation/CumulusCI |
5839e1e551df96b3766722d8a87d42b12b3cfa5d | cronos/accounts/models.py | cronos/accounts/models.py | from cronos.teilar.models import Departments
from django.contrib.auth.models import User
from django.db import models
class UserProfile(models.Model):
user = models.ForeignKey(User, unique = True)
dionysos_username = models.CharField(max_length = 15, unique = True)
dionysos_password = models.CharField(max_... | from cronos.teilar.models import Departments, Teachers, EclassLessons, Websites
from django.contrib.auth.models import User
from django.db import models
class UserProfile(models.Model):
user = models.OneToOneField(User, primary_key = True, unique = True)
dionysos_username = models.CharField(max_length = 15, un... | Improve db relations: - User->UserProfile is One to One - UserProfile <-> Teachers/Websites/EclassLessons are Many to Many | Improve db relations:
- User->UserProfile is One to One
- UserProfile <-> Teachers/Websites/EclassLessons are Many to Many
| Python | agpl-3.0 | LinuxTeam-teilar/cronos.teilar.gr,LinuxTeam-teilar/cronos.teilar.gr,LinuxTeam-teilar/cronos.teilar.gr |
4c7ea928782c976919a055379a921983c5bbf97a | memegen/routes/_cache.py | memegen/routes/_cache.py | import logging
import yorm
from yorm.types import List, Object
log = logging.getLogger(__name__)
@yorm.attr(items=List.of_type(Object))
@yorm.sync("data/images/cache.yml")
class Cache:
SIZE = 9
def __init__(self):
self.items = []
def add(self, **kwargs):
log.info("Caching: %s", kwarg... | import logging
import yorm
from yorm.types import List, Object
log = logging.getLogger(__name__)
@yorm.attr(items=List.of_type(Object))
@yorm.sync("data/images/cache.yml")
class Cache:
SIZE = 9
def __init__(self):
self.items = []
def add(self, **kwargs):
if kwargs['key'] == 'custom':... | Disable caching on custom images | Disable caching on custom images
| Python | mit | DanLindeman/memegen,DanLindeman/memegen,DanLindeman/memegen,DanLindeman/memegen |
fd11e57f736fff6ef23972dee642554c6e8f5495 | urls.py | urls.py | from django.conf.urls import url
from . import views
from django.conf import settings
urlpatterns=[
url(r'^login/$', views.login, name='login'),
url(r'^logout/$', views.logout, name='logout'),
url(r'^users/$', views.users, name='users'),
url(r'^users/(?P<username>[^/]*)/$', views.user, name='user'),
]
| from django.conf.urls import url
from . import views
from django.conf import settings
urlpatterns=[
url(r'^login/$', views.login, name='login'),
url(r'^logout/$', views.logout, name='logout'),
url(r'^users/$', views.users, name='users'),
url(r'^users/(?P<user>[^/]*)/$', views.user, name='user'),
url(r'^users/(?P<... | Add the prefs and pref url | Add the prefs and pref url
| Python | apache-2.0 | kensonman/webframe,kensonman/webframe,kensonman/webframe |
db2fdb6a1df9324a4661967069488e981d06b0f1 | bi_view_editor/wizard/wizard_ir_model_menu_create.py | bi_view_editor/wizard/wizard_ir_model_menu_create.py | # -*- coding: utf-8 -*-
# Copyright 2017 Onestein (<http://www.onestein.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, models
class WizardModelMenuCreate(models.TransientModel):
_inherit = 'wizard.ir.model.menu.create'
@api.multi
def menu_create(self):
... | # -*- coding: utf-8 -*-
# Copyright 2017 Onestein (<http://www.onestein.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, models
class WizardModelMenuCreate(models.TransientModel):
_inherit = 'wizard.ir.model.menu.create'
@api.multi
def menu_create(self):
... | Refresh page when creating menus, module bi_view_editor | Refresh page when creating menus, module bi_view_editor
| Python | agpl-3.0 | VitalPet/addons-onestein,VitalPet/addons-onestein,VitalPet/addons-onestein |
e01eb66aeb853261c80cb476e71f91a9569b1676 | client.py | client.py | import requests
from Adafruit_BMP085 import BMP085
import json
#initialise sensor
print ('Initialising sensor...')
bmp = BMP085(0x77, 3) # ULTRAHIRES Mode
print ('Reading sensor...')
temp = bmp.readTemperature()
pressure = bmp.readPressure()
payload = {'temperature': temp, 'pressure': pressure}
print ('POSTing dat... | import requests
from Adafruit_BMP085 import BMP085
import json
#initialise sensor
print ('Initialising sensor...')
bmp = BMP085(0x77, 3) # ULTRAHIRES Mode
print ('Reading sensor...')
temp = bmp.readTemperature()
pressure = bmp.readPressure()
payload = {'temperature': temp, 'pressure': pressure}
print ('POSTing dat... | Set content-type header of POST. | Set content-type header of POST.
| Python | mit | JTKBowers/kelvin |
c7ccfd82298c2c8c90c230f846ca9319bcf40441 | lib/tagnews/__init__.py | lib/tagnews/__init__.py | from . import utils
from . import crimetype
from .crimetype.tag import CrimeTags
from .geoloc.tag import GeoCoder, get_lat_longs_from_geostrings
from .utils.load_data import load_data
from .utils.load_data import load_ner_data
from .utils.load_vectorizer import load_glove
__version__ = '1.0.2'
def test(verbosity=Non... | from . import utils
from . import crimetype
from .crimetype.tag import CrimeTags
from .geoloc.tag import GeoCoder, get_lat_longs_from_geostrings
from .utils.load_data import load_data
from .utils.load_data import load_ner_data
from .utils.load_vectorizer import load_glove
__version__ = '1.0.2'
| Remove unused test function at top level. | Remove unused test function at top level.
| Python | mit | kbrose/article-tagging,kbrose/article-tagging,chicago-justice-project/article-tagging,chicago-justice-project/article-tagging |
1f8845f89aa936379fbea4d8707fbb4887c62696 | examples/pystray_icon.py | examples/pystray_icon.py | from PIL import Image
from pystray import Icon, Menu, MenuItem
import webview
import sys
if sys.platform == 'darwin':
# System tray icon needs to run in it's own process on Mac OS X
from multiprocessing import Process as Thread, Queue
else:
from threading import Thread
from queue import Queue
"""
Thi... | from PIL import Image
from pystray import Icon, Menu, MenuItem
import webview
import sys
if sys.platform == 'darwin':
# System tray icon needs to run in it's own process on Mac OS X
import multiprocessing
from multiprocessing import Process as Thread, Queue
multiprocessing.set_start_method('spawn')
els... | Fix process spawn on Mac os, simplify logic | Fix process spawn on Mac os, simplify logic
| Python | bsd-3-clause | r0x0r/pywebview,r0x0r/pywebview,r0x0r/pywebview,r0x0r/pywebview,r0x0r/pywebview |
1cec2df8bcb7f877c813d6470d454244630b050a | semantic_release/pypi.py | semantic_release/pypi.py | """PyPI
"""
from invoke import run
def upload_to_pypi(
dists: str = 'sdist bdist_wheel',
username: str = None,
password: str = None,
skip_existing: bool = False
):
"""Creates the wheel and uploads to pypi with twine.
:param dists: The dists string passed to setup.py. Default: ... | """PyPI
"""
from invoke import run
def upload_to_pypi(
dists: str = 'sdist bdist_wheel',
username: str = None,
password: str = None,
skip_existing: bool = False
):
"""Creates the wheel and uploads to pypi with twine.
:param dists: The dists string passed to setup.py. Default: ... | Add dists to twine call | fix: Add dists to twine call
| Python | mit | relekang/python-semantic-release,relekang/python-semantic-release |
f959e9213f27cee5ed5739655d4f85c7d0d442aa | tests/functional/customer/test_notification.py | tests/functional/customer/test_notification.py | from http import client as http_client
from oscar.test.testcases import WebTestCase
from oscar.apps.customer.notifications import services
from oscar.test.factories import UserFactory
from django.urls import reverse
from oscar.apps.customer.models import Notification
class TestAUserWithUnreadNotifications(WebTestCa... | from http import client as http_client
from oscar.test.testcases import WebTestCase
from oscar.apps.customer.notifications import services
from oscar.test.factories import UserFactory
from django.urls import reverse
from oscar.apps.customer.models import Notification
class TestAUserWithUnreadNotifications(WebTestCa... | Update test in case if home page has redirection. | Update test in case if home page has redirection.
| Python | bsd-3-clause | solarissmoke/django-oscar,django-oscar/django-oscar,django-oscar/django-oscar,solarissmoke/django-oscar,sasha0/django-oscar,sasha0/django-oscar,solarissmoke/django-oscar,django-oscar/django-oscar,solarissmoke/django-oscar,sasha0/django-oscar,sasha0/django-oscar,django-oscar/django-oscar |
b00d93901a211a35bdb30e00da530dde823c4a2d | frontends/etiquette_flask/etiquette_flask_launch.py | frontends/etiquette_flask/etiquette_flask_launch.py | import gevent.monkey
gevent.monkey.patch_all()
import logging
handler = logging.StreamHandler()
log_format = '{levelname}:etiquette.{module}.{funcName}: {message}'
handler.setFormatter(logging.Formatter(log_format, style='{'))
logging.getLogger().addHandler(handler)
import etiquette_flask
import gevent.pywsgi
import ... | import gevent.monkey
gevent.monkey.patch_all()
import logging
handler = logging.StreamHandler()
log_format = '{levelname}:etiquette.{module}.{funcName}: {message}'
handler.setFormatter(logging.Formatter(log_format, style='{'))
logging.getLogger().addHandler(handler)
import etiquette_flask
import gevent.pywsgi
import ... | Apply werkzeug ProxyFix so that request.remote_addr is correct. | Apply werkzeug ProxyFix so that request.remote_addr is correct.
| Python | bsd-3-clause | voussoir/etiquette,voussoir/etiquette,voussoir/etiquette |
a2b4b53635ab1188e95efd68f64104a469e7ff66 | scheduler/executor.py | scheduler/executor.py | import threading
import subprocess
class TestExecutor(threading.Thread):
"""
The general thread to perform the tests executions
"""
def __init__(self, run_id, test_name, queue):
super().__init__()
self.run_id = run_id
self.test_name = test_name
self.queue = queue
#... | import threading
import subprocess
import os
class TestExecutor(threading.Thread):
"""
The general thread to perform the tests executions
"""
def __init__(self, run_id, test_name, queue):
super().__init__()
self.run_id = run_id
self.test_name = test_name
self.queue = q... | Fix bug related to creating the log directory | Fix bug related to creating the log directory
| Python | mit | jfelipefilho/test-manager,jfelipefilho/test-manager,jfelipefilho/test-manager |
327428de0267de773a850daa9d376891fe02308f | splitword.py | splitword.py | #!/usr/bin/env python3
# encoding: utf-8
# Splits a word into multiple parts
def split_word(word):
if len(word) < 2:
raise Exception(
"You obviously need at least two letters to split a word")
split_indexes = list(range(1, len(word)))
for i in split_indexes:
first_part = word[:... | #!/usr/bin/env python3
# encoding: utf-8
# Splits a word into multiple parts
def split_word(word):
split_indexes = list(range(0, len(word)))
for i in split_indexes:
first_part = word[:i]
second_part = word[i:]
yield (first_part, second_part)
| Allow splitting to zero-length parts | Allow splitting to zero-length parts
| Python | unlicense | andyn/kapunaattori |
0887e200f31edd8d61e0dd1d3fefae7e828c9269 | mindbender/maya/plugins/validate_single_assembly.py | mindbender/maya/plugins/validate_single_assembly.py | import pyblish.api
class ValidateMindbenderSingleAssembly(pyblish.api.InstancePlugin):
"""Each asset must have a single top-level group
The given instance is test-exported, along with construction
history to test whether more than 1 top-level DAG node would
be included in the exported file.
"""
... | import pyblish.api
class SelectAssemblies(pyblish.api.Action):
label = "Select Assemblies"
on = "failed"
def process(self, context, plugin):
from maya import cmds
cmds.select(plugin.assemblies)
class ValidateMindbenderSingleAssembly(pyblish.api.InstancePlugin):
"""Each asset must ha... | Add action to select the multiple assemblies. | Add action to select the multiple assemblies.
| Python | mit | getavalon/core,MoonShineVFX/core,MoonShineVFX/core,mindbender-studio/core,mindbender-studio/core,getavalon/core |
92e96c010b54bf4c9e35d49de492cf9f061f345a | micromodels/models.py | micromodels/models.py | from fields import FieldBase
class Model(object):
class __metaclass__(type):
def __init__(cls, name, bases, attrs):
fields = {}
for name, value in attrs.items():
if isinstance(value, FieldBase):
fields[name] = value
setattr(cls, '_fie... | from fields import FieldBase
class Model(object):
class __metaclass__(type):
def __init__(cls, name, bases, attrs):
cls._fields = {}
for name, value in attrs.items():
if isinstance(value, FieldBase):
cls._fields[name] = value
def __init__(se... | Change to make metaclass clearer | Change to make metaclass clearer
| Python | unlicense | j4mie/micromodels |
7a0da88638c3d0fe0f9088c0d9008ff60503fe06 | plotly/plotly/__init__.py | plotly/plotly/__init__.py | """
plotly
======
This module defines functionality that requires interaction between your
local machine and Plotly. Almost all functionality used here will require a
verifiable account (username/api-key pair) and a network connection.
"""
from __future__ import absolute_import
from plotly.plotly.plotly import *
__... | """
plotly
======
This module defines functionality that requires interaction between your
local machine and Plotly. Almost all functionality used here will require a
verifiable account (username/api-key pair) and a network connection.
"""
from . plotly import (
sign_in, update_plot_options, get_plot_options, get... | Remove `import *`. Replace with explicit public interface. | Remove `import *`. Replace with explicit public interface.
| Python | mit | plotly/python-api,ee-in/python-api,plotly/plotly.py,plotly/plotly.py,ee-in/python-api,plotly/plotly.py,ee-in/python-api,plotly/python-api,plotly/python-api |
4b379e82dd503afc04569a50c08a7cdd9abfe4b0 | passpie/validators.py | passpie/validators.py | import click
from .history import clone
from . import config
def validate_remote(ctx, param, value):
if value:
try:
remote, branch = value.split('/')
return (remote, branch)
except ValueError:
raise click.BadParameter('remote need to be in format <remote>/<bran... | import click
from .history import clone
from . import config
def validate_remote(ctx, param, value):
if value:
try:
remote, branch = value.split('/')
return (remote, branch)
except ValueError:
raise click.BadParameter('remote need to be in format <remote>/<bran... | Fix load config from local db config file | Fix load config from local db config file
| Python | mit | scorphus/passpie,scorphus/passpie,marcwebbie/passpie,marcwebbie/passpie |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.