commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4
values | license stringclasses 13
values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
0d2079b1dcb97708dc55c32d9e2c1a0f12595875 | salt/runners/launchd.py | salt/runners/launchd.py | # -*- coding: utf-8 -*-
'''
Manage launchd plist files
'''
# Import python libs
import os
import sys
def write_launchd_plist(program):
'''
Write a launchd plist for managing salt-master or salt-minion
CLI Example:
.. code-block:: bash
salt-run launchd.write_launchd_plist salt-master
''... | # -*- coding: utf-8 -*-
'''
Manage launchd plist files
'''
# Import python libs
import os
import sys
def write_launchd_plist(program):
'''
Write a launchd plist for managing salt-master or salt-minion
CLI Example:
.. code-block:: bash
salt-run launchd.write_launchd_plist salt-master
''... | Replace string substitution with string formatting | Replace string substitution with string formatting
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -18,7 +18,7 @@
salt-run launchd.write_launchd_plist salt-master
'''
- plist_sample_text = """
+ plist_sample_text = '''
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"... |
69e760e4a571d16e75f30f1e97ea1a917445f333 | recipes/recipe_modules/gitiles/__init__.py | recipes/recipe_modules/gitiles/__init__.py | DEPS = [
'recipe_engine/json',
'recipe_engine/path',
'recipe_engine/python',
'recipe_engine/raw_io',
'url',
]
| DEPS = [
'recipe_engine/json',
'recipe_engine/path',
'recipe_engine/python',
'recipe_engine/raw_io',
'recipe_engine/url',
]
| Switch to recipe engine "url" module. | Switch to recipe engine "url" module.
BUG=None
TEST=expectations
R=40f3d43a28ebae3cb819288542e1c84d73d962d5@chromium.org
Change-Id: I43a65405c957cb6dddd64f61846b926d81046752
Reviewed-on: https://chromium-review.googlesource.com/505278
Reviewed-by: Robbie Iannucci <40f3d43a28ebae3cb819288542e1c84d73d962d5@chromium.org... | Python | bsd-3-clause | CoherentLabs/depot_tools,CoherentLabs/depot_tools | ---
+++
@@ -3,5 +3,5 @@
'recipe_engine/path',
'recipe_engine/python',
'recipe_engine/raw_io',
- 'url',
+ 'recipe_engine/url',
] |
d926c984e895b68ad0cc0383926451c0d7249512 | astropy/tests/tests/test_imports.py | astropy/tests/tests/test_imports.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import pkgutil
def test_imports():
"""
This just imports all modules in astropy, making sure they don't have any
dependencies that sneak through
"""
def onerror(name):
# We should raise any legitimate error that occurred, but... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import pkgutil
def test_imports():
"""
This just imports all modules in astropy, making sure they don't have any
dependencies that sneak through
"""
def onerror(name):
# We should raise any legitimate error that occurred, but... | Fix use of deprecated find_module | Fix use of deprecated find_module
| Python | bsd-3-clause | saimn/astropy,lpsinger/astropy,mhvk/astropy,lpsinger/astropy,pllim/astropy,astropy/astropy,lpsinger/astropy,larrybradley/astropy,StuartLittlefair/astropy,astropy/astropy,pllim/astropy,saimn/astropy,saimn/astropy,StuartLittlefair/astropy,astropy/astropy,StuartLittlefair/astropy,astropy/astropy,mhvk/astropy,astropy/astro... | ---
+++
@@ -19,7 +19,7 @@
for imper, nm, ispkg in pkgutil.walk_packages(['astropy'], 'astropy.',
onerror=onerror):
- imper.find_module(nm)
+ imper.find_spec(nm)
def test_toplevel_namespace(): |
394954fc80230e01112166db4fe133c107febead | gitautodeploy/parsers/common.py | gitautodeploy/parsers/common.py |
class WebhookRequestParser(object):
"""Abstract parent class for git service parsers. Contains helper
methods."""
def __init__(self, config):
self._config = config
def get_matching_repo_configs(self, urls):
"""Iterates over the various repo URLs provided as argument (git://,
s... |
class WebhookRequestParser(object):
"""Abstract parent class for git service parsers. Contains helper
methods."""
def __init__(self, config):
self._config = config
def get_matching_repo_configs(self, urls):
"""Iterates over the various repo URLs provided as argument (git://,
s... | Allow more than one GitHub repo from the same user | Allow more than one GitHub repo from the same user
GitHub does not allow the same SSH key to be used for multiple
repositories on the same server belonging to the same user, see:
http://snipe.net/2013/04/multiple-github-deploy-keys-single-server
The fix there doesn't work because the "url" field is used both to
get ... | Python | mit | evoja/docker-Github-Gitlab-Auto-Deploy,evoja/docker-Github-Gitlab-Auto-Deploy | ---
+++
@@ -16,7 +16,7 @@
for repo_config in self._config['repositories']:
if repo_config in configs:
continue
- if repo_config['url'] == url:
+ if repo_config.get('repo', repo_config.get('url')) == url:
configs.appe... |
bb9d1255548b46dc2ba7a85e26606b7dd4c926f3 | examples/greeting.py | examples/greeting.py | # greeting.py
#
# Demonstration of the pyparsing module, on the prototypical "Hello, World!"
# example
#
# Copyright 2003, by Paul McGuire
#
from pyparsing import Word, alphas
# define grammar
greet = Word( alphas ) + "," + Word( alphas ) + "!"
# input string
hello = "Hello, World!"
# parse input stri... | # greeting.py
#
# Demonstration of the pyparsing module, on the prototypical "Hello, World!"
# example
#
# Copyright 2003, 2019 by Paul McGuire
#
import pyparsing as pp
# define grammar
greet = pp.Word(pp.alphas) + "," + pp.Word(pp.alphas) + pp.oneOf("! ? .")
# input string
hello = "Hello, World!"
# parse input stri... | Update original "Hello, World!" parser to latest coding, plus runTests | Update original "Hello, World!" parser to latest coding, plus runTests
| Python | mit | pyparsing/pyparsing,pyparsing/pyparsing | ---
+++
@@ -3,15 +3,23 @@
# Demonstration of the pyparsing module, on the prototypical "Hello, World!"
# example
#
-# Copyright 2003, by Paul McGuire
+# Copyright 2003, 2019 by Paul McGuire
#
-from pyparsing import Word, alphas
+import pyparsing as pp
# define grammar
-greet = Word( alphas ) + "," + Word( alph... |
bc6c3834cd8383f7e1f9e109f0413bb6015a92bf | go/scheduler/views.py | go/scheduler/views.py | import datetime
from django.views.generic import ListView
from go.scheduler.models import Task
class SchedulerListView(ListView):
paginate_by = 12
context_object_name = 'tasks'
template = 'scheduler/task_list.html'
def get_queryset(self):
now = datetime.datetime.utcnow()
return Task.... | from django.views.generic import ListView
from go.scheduler.models import Task
class SchedulerListView(ListView):
paginate_by = 12
context_object_name = 'tasks'
template = 'scheduler/task_list.html'
def get_queryset(self):
return Task.objects.filter(
account_id=self.request.user_... | Remove unneeded datetime from view | Remove unneeded datetime from view
| Python | bsd-3-clause | praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go | ---
+++
@@ -1,4 +1,3 @@
-import datetime
from django.views.generic import ListView
from go.scheduler.models import Task
@@ -10,7 +9,6 @@
template = 'scheduler/task_list.html'
def get_queryset(self):
- now = datetime.datetime.utcnow()
return Task.objects.filter(
account_id=... |
ebfaf30fca157e83ea9e4bf33173221fc9525caf | demo/examples/employees/forms.py | demo/examples/employees/forms.py | from datetime import date
from django import forms
from django.utils import timezone
from .models import Employee, DeptManager, Title, Salary
class ChangeManagerForm(forms.Form):
manager = forms.ModelChoiceField(queryset=Employee.objects.all()[:100])
def __init__(self, *args, **kwargs):
self.depart... | from django import forms
from .models import Employee, DeptManager, Title, Salary
class ChangeManagerForm(forms.Form):
manager = forms.ModelChoiceField(queryset=Employee.objects.all()[:100])
def __init__(self, *args, **kwargs):
self.department = kwargs.pop('department')
super(ChangeManagerFo... | Fix emplorrs demo salary db error | Fix emplorrs demo salary db error
| Python | bsd-3-clause | viewflow/django-material,viewflow/django-material,viewflow/django-material | ---
+++
@@ -1,7 +1,4 @@
-from datetime import date
-
from django import forms
-from django.utils import timezone
from .models import Employee, DeptManager, Title, Salary
@@ -43,7 +40,7 @@
class ChangeSalaryForm(forms.Form):
- salary = forms.IntegerField()
+ salary = forms.IntegerField(max_value=10000... |
06f78c21e6b7e3327244e89e90365169f4c32ea1 | calaccess_campaign_browser/api.py | calaccess_campaign_browser/api.py | from tastypie.resources import ModelResource, ALL
from .models import Filer, Filing
from .utils.serializer import CIRCustomSerializer
class FilerResource(ModelResource):
class Meta:
queryset = Filer.objects.all()
serializer = CIRCustomSerializer()
filtering = { 'filer_id_raw': ALL }
... | from tastypie.resources import ModelResource, ALL
from .models import Filer, Filing
from .utils.serializer import CIRCustomSerializer
class FilerResource(ModelResource):
class Meta:
queryset = Filer.objects.all()
serializer = CIRCustomSerializer()
filtering = {'filer_id_raw': ALL}
... | Fix style issues raised by pep8. | Fix style issues raised by pep8.
| Python | mit | myersjustinc/django-calaccess-campaign-browser,dwillis/django-calaccess-campaign-browser,myersjustinc/django-calaccess-campaign-browser,california-civic-data-coalition/django-calaccess-campaign-browser,dwillis/django-calaccess-campaign-browser,california-civic-data-coalition/django-calaccess-campaign-browser | ---
+++
@@ -7,12 +7,13 @@
class Meta:
queryset = Filer.objects.all()
serializer = CIRCustomSerializer()
- filtering = { 'filer_id_raw': ALL }
- excludes = [ 'id' ]
+ filtering = {'filer_id_raw': ALL}
+ excludes = ['id']
+
class FilingResource(ModelResource):
... |
a473b2cb9af95c1296ecae4d2138142f2be397ee | examples/variants.py | examples/variants.py | #!/usr/bin/env python
# -*- coding: utf8 - *-
from __future__ import print_function, unicode_literals
from cihai.bootstrap import bootstrap_unihan
from cihai.core import Cihai
def variant_list(unihan, field):
for char in unihan.with_fields(field):
print("Character: {}".format(char.char))
for var... | #!/usr/bin/env python
# -*- coding: utf8 - *-
from __future__ import print_function, unicode_literals
from cihai.bootstrap import bootstrap_unihan
from cihai.core import Cihai
def variant_list(unihan, field):
for char in unihan.with_fields(field):
print("Character: {}".format(char.char))
for var... | Add variant extension in example script | Add variant extension in example script
| Python | mit | cihai/cihai,cihai/cihai-python,cihai/cihai | ---
+++
@@ -24,6 +24,8 @@
bootstrap_unihan(c.sql.metadata, options=unihan_options)
c.sql.reflect_db() # automap new table created during bootstrap
+ c.unihan.add_extension('cihai.unihan.UnihanVariants', namespace='variants')
+
print("## ZVariants")
variant_list(c.unihan, "kZVariant")... |
0727ad29721a3dad4c36113a299f5c67bda70822 | importlib_resources/__init__.py | importlib_resources/__init__.py | """Read resources contained within a package."""
import sys
__all__ = [
'contents',
'is_resource',
'open_binary',
'open_text',
'path',
'read_binary',
'read_text',
'Package',
'Resource',
'ResourceReader',
]
if sys.version_info >= (3,):
from importlib_resources._py3 im... | """Read resources contained within a package."""
import sys
__all__ = [
'Package',
'Resource',
'ResourceReader',
'contents',
'is_resource',
'open_binary',
'open_text',
'path',
'read_binary',
'read_text',
]
if sys.version_info >= (3,):
from importlib_resources._py3 im... | Sort everything alphabetically on separate lines. | Sort everything alphabetically on separate lines.
| Python | apache-2.0 | python/importlib_resources | ---
+++
@@ -4,6 +4,9 @@
__all__ = [
+ 'Package',
+ 'Resource',
+ 'ResourceReader',
'contents',
'is_resource',
'open_binary',
@@ -11,22 +14,33 @@
'path',
'read_binary',
'read_text',
- 'Package',
- 'Resource',
- 'ResourceReader',
]
if sys.version_info >= (3... |
7f974b87c278ef009535271461b5e49686057a9a | avatar/management/commands/rebuild_avatars.py | avatar/management/commands/rebuild_avatars.py | from django.core.management.base import NoArgsCommand
from avatar.conf import settings
from avatar.models import Avatar
class Command(NoArgsCommand):
help = ("Regenerates avatar thumbnails for the sizes specified in "
"settings.AVATAR_AUTO_GENERATE_SIZES.")
def handle_noargs(self, **options):
... | from django.core.management.base import BaseCommand
from avatar.conf import settings
from avatar.models import Avatar
class Command(BaseCommand):
help = ("Regenerates avatar thumbnails for the sizes specified in "
"settings.AVATAR_AUTO_GENERATE_SIZES.")
def handle(self, *args, **options):
... | Fix for django >= 1.10 | Fix for django >= 1.10
The class django.core.management.NoArgsCommand is removed. | Python | bsd-3-clause | grantmcconnaughey/django-avatar,jezdez/django-avatar,grantmcconnaughey/django-avatar,ad-m/django-avatar,ad-m/django-avatar,jezdez/django-avatar | ---
+++
@@ -1,14 +1,14 @@
-from django.core.management.base import NoArgsCommand
+from django.core.management.base import BaseCommand
from avatar.conf import settings
from avatar.models import Avatar
-class Command(NoArgsCommand):
+class Command(BaseCommand):
help = ("Regenerates avatar thumbnails for th... |
6e2362351d9ccaa46a5a2bc69c4360e4faff166d | iclib/qibla.py | iclib/qibla.py | from . import formula
def direction(lat, lng):
return formula.qibla(lat, lng)
def direction_dms(lat, lng):
return _dms(formula.qibla(lat, lng))
def direction_str(lat, lng, prec=0):
d, m, s = direction_dms(lat, lng)
# negative input might returns wrong result
return '{}° {}\' {:.{}f}"'.format(d, m, s, prec)
def... | # -*- coding: utf-8 -*-
from . import formula
def direction(lat, lng):
return formula.qibla(lat, lng)
def direction_dms(lat, lng):
return _dms(formula.qibla(lat, lng))
def direction_str(lat, lng, prec=0):
d, m, s = direction_dms(lat, lng)
# negative input might returns wrong result
return '{}° {}\' {:.{}f}"'.fo... | Add encoding spec to comply Python 2 | Add encoding spec to comply Python 2
| Python | apache-2.0 | fikr4n/iclib-python | ---
+++
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
from . import formula
def direction(lat, lng): |
eb1fdf3419bdfd1d5920d73a877f707162b783b0 | cfgrib/__init__.py | cfgrib/__init__.py | #
# Copyright 2017-2021 European Centre for Medium-Range Weather Forecasts (ECMWF).
#
# 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... | #
# Copyright 2017-2021 European Centre for Medium-Range Weather Forecasts (ECMWF).
#
# 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... | Drop unused and dangerous entrypoint `open_fileindex` | Drop unused and dangerous entrypoint `open_fileindex`
| Python | apache-2.0 | ecmwf/cfgrib | ---
+++
@@ -17,14 +17,7 @@
# cfgrib core API depends on the ECMWF ecCodes C-library only
from .cfmessage import CfMessage
-from .dataset import (
- Dataset,
- DatasetBuildError,
- open_container,
- open_file,
- open_fileindex,
- open_from_index,
-)
+from .dataset import Dataset, DatasetBuildErro... |
e3548d62aa67472f291f6d3c0c8beca9813d6032 | gym/envs/toy_text/discrete.py | gym/envs/toy_text/discrete.py | from gym import Env
from gym import spaces
import numpy as np
def categorical_sample(prob_n):
"""
Sample from categorical distribution
Each row specifies class probabilities
"""
prob_n = np.asarray(prob_n)
csprob_n = np.cumsum(prob_n)
return (csprob_n > np.random.rand()).argmax()
class Di... | from gym import Env
from gym import spaces
import numpy as np
def categorical_sample(prob_n):
"""
Sample from categorical distribution
Each row specifies class probabilities
"""
prob_n = np.asarray(prob_n)
csprob_n = np.cumsum(prob_n)
return (csprob_n > np.random.rand()).argmax()
class Di... | Make it possible to step() in a newly created env, rather than throwing AttributeError | Make it possible to step() in a newly created env, rather than throwing AttributeError
| Python | mit | d1hotpep/openai_gym,Farama-Foundation/Gymnasium,dianchen96/gym,machinaut/gym,dianchen96/gym,d1hotpep/openai_gym,machinaut/gym,Farama-Foundation/Gymnasium | ---
+++
@@ -34,6 +34,7 @@
self.P = P
self.isd = isd
self.lastaction=None # for rendering
+ self._reset()
@property
def nS(self): |
eb57a07277f86fc90b7845dc48fb5cde1778c8d4 | test/unit_test/test_cut_number.py | test/unit_test/test_cut_number.py | from lexos.processors.prepare.cutter import split_keep_whitespace, \
count_words, cut_by_number
class TestCutByNumbers:
def test_split_keep_whitespace(self):
assert split_keep_whitespace("Test string") == ["Test", " ", "string"]
assert split_keep_whitespace("Test") == ["Test"]
assert s... | from lexos.processors.prepare.cutter import split_keep_whitespace, \
count_words, cut_by_number
class TestCutByNumbers:
def test_split_keep_whitespace(self):
assert split_keep_whitespace("Test string") == ["Test", " ", "string"]
assert split_keep_whitespace("Test") == ["Test"]
assert s... | Test cut_by_number with words and normal chunk numbers | Test cut_by_number with words and normal chunk numbers
| Python | mit | WheatonCS/Lexos,WheatonCS/Lexos,WheatonCS/Lexos | ---
+++
@@ -13,3 +13,10 @@
assert count_words(["word", "word", " ", "not", "word"]) == 4
assert count_words(['\n', '\t', ' ', '', '\u3000', "word"]) == 1
assert count_words([""]) == 0
+
+ def test_cut_by_number_normal(self):
+ assert cut_by_number("Text", 1) == ["Text"]
+ a... |
91e916cb67867db9ce835be28b31904e6efda832 | spacy/tests/regression/test_issue1727.py | spacy/tests/regression/test_issue1727.py | from __future__ import unicode_literals
import numpy
from ...pipeline import Tagger
from ...vectors import Vectors
from ...vocab import Vocab
from ..util import make_tempdir
def test_issue1727():
data = numpy.ones((3, 300), dtype='f')
keys = [u'I', u'am', u'Matt']
vectors = Vectors(data=data, keys=keys)
... | '''Test that models with no pretrained vectors can be deserialized correctly
after vectors are added.'''
from __future__ import unicode_literals
import numpy
from ...pipeline import Tagger
from ...vectors import Vectors
from ...vocab import Vocab
from ..util import make_tempdir
def test_issue1727():
data = numpy.... | Add comment to new test | Add comment to new test
| Python | mit | aikramer2/spaCy,recognai/spaCy,aikramer2/spaCy,recognai/spaCy,explosion/spaCy,recognai/spaCy,explosion/spaCy,recognai/spaCy,recognai/spaCy,aikramer2/spaCy,honnibal/spaCy,explosion/spaCy,spacy-io/spaCy,aikramer2/spaCy,explosion/spaCy,spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,explosion/spaCy,honnibal/spaCy,aikramer2/s... | ---
+++
@@ -1,3 +1,5 @@
+'''Test that models with no pretrained vectors can be deserialized correctly
+after vectors are added.'''
from __future__ import unicode_literals
import numpy
from ...pipeline import Tagger |
9df00bbfa829006396c2a6718e4540410b27c4c6 | kolibri/tasks/apps.py | kolibri/tasks/apps.py | from __future__ import absolute_import, print_function, unicode_literals
from django.apps import AppConfig
class KolibriTasksConfig(AppConfig):
name = 'kolibri.tasks'
label = 'kolibritasks'
verbose_name = 'Kolibri Tasks'
def ready(self):
pass
| from __future__ import absolute_import, print_function, unicode_literals
from django.apps import AppConfig
class KolibriTasksConfig(AppConfig):
name = 'kolibri.tasks'
label = 'kolibritasks'
verbose_name = 'Kolibri Tasks'
def ready(self):
from kolibri.tasks.api import client
client.cl... | Clear the job queue upon kolibri initialization. | Clear the job queue upon kolibri initialization.
| Python | mit | MingDai/kolibri,mrpau/kolibri,benjaoming/kolibri,DXCanas/kolibri,lyw07/kolibri,learningequality/kolibri,rtibbles/kolibri,mrpau/kolibri,mrpau/kolibri,rtibbles/kolibri,DXCanas/kolibri,indirectlylit/kolibri,MingDai/kolibri,lyw07/kolibri,mrpau/kolibri,christianmemije/kolibri,DXCanas/kolibri,learningequality/kolibri,jonbois... | ---
+++
@@ -9,4 +9,5 @@
verbose_name = 'Kolibri Tasks'
def ready(self):
- pass
+ from kolibri.tasks.api import client
+ client.clear(force=True) |
bb5cbae79ef8efb8d0b7dd3ee95e76955317d3d7 | tests/integration/api/test_sc_test_jobs.py | tests/integration/api/test_sc_test_jobs.py | from tests.base import BaseTest
from tenable_io.api.models import ScTestJob
class TestScTestJobsApi(BaseTest):
def test_status(self, client, image):
jobs = client.sc_test_jobs_api.list()
assert len(jobs) > 0, u'At least one job exists.'
test_job = client.sc_test_jobs_api.status(jobs[0].j... | from tests.base import BaseTest
from tenable_io.api.models import ScTestJob
class TestScTestJobsApi(BaseTest):
def test_status(self, client, image):
jobs = client.sc_test_jobs_api.list()
assert len(jobs) > 0, u'At least one job exists.'
test_job = client.sc_test_jobs_api.status(jobs[0].j... | Fix for broken container security test | Fix for broken container security test
| Python | mit | tenable/Tenable.io-SDK-for-Python | ---
+++
@@ -16,7 +16,7 @@
assert isinstance(job, ScTestJob), u'The method returns type.'
def test_by_image_digest(self, client, image):
- job = client.sc_test_jobs_api.by_image(image['digest'])
+ job = client.sc_test_jobs_api.by_image_digest(image['digest'])
assert isinstance(jo... |
f6be438e01a499dc2bde6abfa5a00fb281db7b83 | kamboo/core.py | kamboo/core.py |
import botocore
from kotocore.session import Session
class KambooConnection(object):
"""
Kamboo connection with botocore session initialized
"""
session = botocore.session.get_session()
def __init__(self, service_name="ec2", region_name="us-east-1",
credentials=None):
se... |
import botocore
from kotocore.session import Session
class KambooConnection(object):
"""
Kamboo connection with botocore session initialized
"""
session = botocore.session.get_session()
def __init__(self, service_name="ec2", region_name="us-east-1",
account_id=None,
... | Add account_id as the element of this class | Add account_id as the element of this class
| Python | apache-2.0 | henrysher/kamboo,henrysher/kamboo | ---
+++
@@ -10,8 +10,10 @@
session = botocore.session.get_session()
def __init__(self, service_name="ec2", region_name="us-east-1",
+ account_id=None,
credentials=None):
self.region = region_name
+ self.account_id = account_id
self.credentials = c... |
29d151366d186ed75da947f2861741ed87af902b | website/addons/badges/settings/__init__.py | website/addons/badges/settings/__init__.py | from .defaults import * # noqa
logger = logging.getLogger(__name__)
try:
from .local import * # noqa
except ImportError as error:
logger.warn('No local.py settings file found')
| # -*- coding: utf-8 -*-
import logging
from .defaults import * # noqa
logger = logging.getLogger(__name__)
try:
from .local import * # noqa
except ImportError as error:
logger.warn('No local.py settings file found')
| Add missing import to settings | Add missing import to settings
| Python | apache-2.0 | samchrisinger/osf.io,himanshuo/osf.io,jinluyuan/osf.io,chrisseto/osf.io,zachjanicki/osf.io,njantrania/osf.io,chrisseto/osf.io,reinaH/osf.io,billyhunt/osf.io,RomanZWang/osf.io,aaxelb/osf.io,arpitar/osf.io,mattclark/osf.io,sbt9uc/osf.io,jolene-esposito/osf.io,rdhyee/osf.io,amyshi188/osf.io,kwierman/osf.io,njantrania/osf.... | ---
+++
@@ -1,3 +1,6 @@
+# -*- coding: utf-8 -*-
+import logging
+
from .defaults import * # noqa
logger = logging.getLogger(__name__) |
959897478bbda18f02aa6e38f2ebdd837581f1f0 | tests/test_sct_verify_signature.py | tests/test_sct_verify_signature.py | from os.path import join, dirname
from utlz import flo
from ctutlz.sct.verification import verify_signature
def test_verify_signature():
basedir = join(dirname(__file__), 'data', 'test_sct_verify_signature')
signature_input = \
open(flo('{basedir}/signature_input_valid.bin'), 'rb').read()
signa... | from os.path import join, dirname
from utlz import flo
from ctutlz.sct.verification import verify_signature
def test_verify_signature():
basedir = join(dirname(__file__), 'data', 'test_sct_verify_signature')
signature_input = \
open(flo('{basedir}/signature_input_valid.bin'), 'rb').read()
signa... | Fix test for changed SctVerificationResult | Fix test for changed SctVerificationResult
| Python | mit | theno/ctutlz,theno/ctutlz | ---
+++
@@ -13,18 +13,8 @@
signature = open(flo('{basedir}/signature.der'), 'rb').read()
pubkey = open(flo('{basedir}/pubkey.pem'), 'rb').read()
- got_verified, got_output, got_cmd_res = \
- verify_signature(signature_input, signature, pubkey)
-
- assert got_verified is True
- assert got_o... |
1d10582d622ce6867a85d9e4e8c279ab7e4ab5ab | src/etc/tidy.py | src/etc/tidy.py | #!/usr/bin/python
import sys, fileinput, subprocess
err=0
cols=78
config_proc=subprocess.Popen([ "git", "config", "core.autocrlf" ],
stdout=subprocess.PIPE)
result=config_proc.communicate()[0]
autocrlf=result.strip() == b"true" if result is not None else False
def report_err(s):
global err
print("%s:%d:... | #!/usr/bin/python
import sys, fileinput
err=0
cols=78
def report_err(s):
global err
print("%s:%d: %s" % (fileinput.filename(), fileinput.filelineno(), s))
err=1
for line in fileinput.input(openhook=fileinput.hook_encoded("utf-8")):
if line.find('\t') != -1 and fileinput.filename().find("Makefile") =... | Revert "Don't complain about \r when core.autocrlf is on in Git" | Revert "Don't complain about \r when core.autocrlf is on in Git"
This reverts commit 828afaa2fa4cc9e3e53bda0ae3073abfcfa151ca.
| Python | apache-2.0 | ejjeong/rust,omasanori/rust,quornian/rust,mvdnes/rust,barosl/rust,aturon/rust,carols10cents/rust,mdinger/rust,AerialX/rust,krzysz00/rust,krzysz00/rust,sarojaba/rust-doc-korean,SiegeLord/rust,l0kod/rust,philyoon/rust,KokaKiwi/rust,nwin/rust,ktossell/rust,victorvde/rust,dwillmer/rust,0x73/rust,waynenilsen/rand,fabricedes... | ---
+++
@@ -1,14 +1,9 @@
#!/usr/bin/python
-import sys, fileinput, subprocess
+import sys, fileinput
err=0
cols=78
-
-config_proc=subprocess.Popen([ "git", "config", "core.autocrlf" ],
- stdout=subprocess.PIPE)
-result=config_proc.communicate()[0]
-autocrlf=result.strip() == b"true" if result is not None el... |
a378649f85f0bc55060ad0238e426f587bc2ff1a | core/exceptions.py | core/exceptions.py | """
exceptions - Core exceptions
"""
class InvalidMembership(Exception):
"""
The membership provided is not valid
"""
pass
class SourceNotFound(Exception):
"""
InstanceSource doesn't have an associated source.
"""
pass
class RequestLimitExceeded(Exception):
"""
A limit was ... | """
exceptions - Core exceptions
"""
class InvalidMembership(Exception):
"""
The membership provided is not valid
"""
pass
class SourceNotFound(Exception):
"""
InstanceSource doesn't have an associated source.
"""
pass
class RequestLimitExceeded(Exception):
"""
A limit was ... | Send location only when printing exception (Avoid leaking ID/UUID) | Send location only when printing exception (Avoid leaking ID/UUID)
| Python | apache-2.0 | CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend | ---
+++
@@ -37,6 +37,6 @@
The provider that was requested is not active
"""
def __init__(self, provider, *args, **kwargs):
- self.message = "Cannot create driver on an inactive provider:%s" \
- % (provider,)
+ self.message = "Cannot create driver on an inactive provi... |
99c3eba0d6384cd42c90ef347823e6d66659d6e3 | viper/interpreter/prelude/operators.py | viper/interpreter/prelude/operators.py | from ..value import ForeignCloVal
def plus(a: int, b: int) -> int:
return a + b
def minus(a: int, b: int) -> int:
return a - b
def times(a: int, b: int) -> int:
return a * b
def divide(a: int, b: int) -> float:
return a / b
env = {
'+': ForeignCloVal(plus, {}),
'-': ForeignCloVal(minus... | from ..value import ForeignCloVal
def plus(a: int, b: int) -> int:
return a + b
def minus(a: int, b: int) -> int:
return a - b
def times(a: int, b: int) -> int:
return a * b
def divide(a: int, b: int) -> float:
return a / b
env = {
'+': ForeignCloVal(plus, {}),
'-': ForeignCloVal(minus... | Fix typo in division operator | Fix typo in division operator
| Python | apache-2.0 | pdarragh/Viper | ---
+++
@@ -21,5 +21,5 @@
'+': ForeignCloVal(plus, {}),
'-': ForeignCloVal(minus, {}),
'*': ForeignCloVal(times, {}),
- '//': ForeignCloVal(divide, {}),
+ '/': ForeignCloVal(divide, {}),
} |
5a8199744bf658d491721b16fea7639303e47d3f | july/people/views.py | july/people/views.py | from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.template.context import RequestContext
#from google.appengine.ext import db
from july.people.models import Commit
from gae_django.auth.models import User
from django.http import Http404, HttpResponseRed... | from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.template.context import RequestContext
#from google.appengine.ext import db
from july.people.models import Commit
from gae_django.auth.models import User
from django.http import Http404, HttpResponseRed... | Edit view pre-populates with data from user object | Edit view pre-populates with data from user object
| Python | mit | ChimeraCoder/GOctober,ChimeraCoder/GOctober,julython/julython.org,ChimeraCoder/GOctober,julython/julython.org,julython/julython.org,julython/julython.org | ---
+++
@@ -23,14 +23,13 @@
from forms import EditUserForm
user = request.user
- #CONSIDER FILES with no POST? Can that happen?
- form = EditUserForm(request.POST or None, request.FILES or None)
+ form = EditUserForm(request.POST or None, user=request.user)
if form.is_valid():
for ... |
a8e43dcdbdd00de9d4336385b3f3def1ae5c2515 | main/modelx.py | main/modelx.py | # -*- coding: utf-8 -*-
import hashlib
class BaseX(object):
@classmethod
def retrieve_one_by(cls, name, value):
cls_db_list = cls.query(getattr(cls, name) == value).fetch(1)
if cls_db_list:
return cls_db_list[0]
return None
class ConfigX(object):
@classmethod
def get_master_db(cls):
r... | # -*- coding: utf-8 -*-
import hashlib
class BaseX(object):
@classmethod
def retrieve_one_by(cls, name, value):
cls_db_list = cls.query(getattr(cls, name) == value).fetch(1)
if cls_db_list:
return cls_db_list[0]
return None
class ConfigX(object):
@classmethod
def get_master_db(cls):
r... | Update UserX, with back compatibility | Update UserX, with back compatibility | Python | mit | vanessa-bell/hd-kiosk-v2,carylF/lab5,gmist/fix-5studio,lipis/the-smallest-creature,NeftaliYagua/gae-init,gmist/my-gae-init-auth,jakedotio/gae-init,carylF/lab5,lipis/gae-init,lipis/gae-init,lovesoft/gae-init,gae-init/gae-init-docs,mdxs/gae-init,tonyin/optionstg,gmist/my-gae-init,gae-init/gae-init-babel,terradigital/gae-... | ---
+++
@@ -19,8 +19,10 @@
class UserX(object):
- def avatar_url(self, size=None):
+ def avatar_url_size(self, size=None):
return '//gravatar.com/avatar/%(hash)s?d=identicon&r=x%(size)s' % {
'hash': hashlib.md5((self.email or self.name).encode('utf-8')).hexdigest().lower(),
'size': '&s=%d' %... |
73b9246164994049d291d5b482d4dbf2ca41a124 | tests/app/test_accessibility_statement.py | tests/app/test_accessibility_statement.py | import re
import subprocess
from datetime import datetime
def test_last_review_date():
statement_file_path = "app/templates/views/accessibility_statement.html"
# test local changes against master for a full diff of what will be merged
statement_diff = subprocess.run(
[f"git diff --exit-code origi... | import re
import subprocess
from datetime import datetime
def test_last_review_date():
statement_file_path = "app/templates/views/accessibility_statement.html"
# test local changes against main for a full diff of what will be merged
statement_diff = subprocess.run(
[f"git diff --exit-code origin/... | Rename master branch to main | Rename master branch to main
| Python | mit | alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin | ---
+++
@@ -6,9 +6,9 @@
def test_last_review_date():
statement_file_path = "app/templates/views/accessibility_statement.html"
- # test local changes against master for a full diff of what will be merged
+ # test local changes against main for a full diff of what will be merged
statement_diff = subp... |
99e9ef79178d6e2dffd8ec7ed12b3edbd8b7d0f1 | longclaw/longclawbasket/views.py | longclaw/longclawbasket/views.py | from django.shortcuts import render
from django.views.generic import ListView
from longclaw.longclawbasket.models import BasketItem
from longclaw.longclawbasket import utils
class BasketView(ListView):
model = BasketItem
template_name = "longclawbasket/basket.html"
def get_context_data(self, **kwargs):
... | from django.shortcuts import render
from django.views.generic import ListView
from longclaw.longclawbasket.models import BasketItem
from longclaw.longclawbasket import utils
class BasketView(ListView):
model = BasketItem
template_name = "longclawbasket/basket.html"
def get_context_data(self, **kwargs):
... | Add basket total to context | Add basket total to context
| Python | mit | JamesRamm/longclaw,JamesRamm/longclaw,JamesRamm/longclaw,JamesRamm/longclaw | ---
+++
@@ -8,4 +8,5 @@
template_name = "longclawbasket/basket.html"
def get_context_data(self, **kwargs):
items, _ = utils.get_basket_items(self.request)
- return {"basket": items}
+ total_price = sum(item.total() for item in items)
+ return {"basket": items, "total_price": to... |
6bec22cd51288c94dff40cf0c973b975538040d5 | tests/integration/minion/test_timeout.py | tests/integration/minion/test_timeout.py | # -*- coding: utf-8 -*-
'''
Tests for various minion timeouts
'''
# Import Python libs
from __future__ import absolute_import
import os
import sys
import salt.utils.platform
# Import Salt Testing libs
from tests.support.case import ShellCase
class MinionTimeoutTestCase(ShellCase):
'''
Test minion timing fu... | # -*- coding: utf-8 -*-
'''
Tests for various minion timeouts
'''
# Import Python libs
from __future__ import absolute_import
import os
import sys
import salt.utils.platform
# Import Salt Testing libs
from tests.support.case import ShellCase
class MinionTimeoutTestCase(ShellCase):
'''
Test minion timing fu... | Increase timeout for test_long_running_job test | Increase timeout for test_long_running_job test
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -31,7 +31,7 @@
popen_kwargs = None
ret = self.run_salt(
'minion test.sleep {0}'.format(sleep_length),
- timeout=45,
+ timeout=90,
catch_stderr=True,
popen_kwargs=popen_kwargs,
) |
6cfc94d8a03439c55808090aa5e3a4f35c288887 | menpodetect/tests/opencv_test.py | menpodetect/tests/opencv_test.py | from menpodetect.opencv import (load_opencv_frontal_face_detector,
load_opencv_eye_detector)
import menpo.io as mio
takeo = mio.import_builtin_asset.takeo_ppm()
def test_frontal_face_detector():
takeo_copy = takeo.copy()
opencv_detector = load_opencv_frontal_face_detector()
... | from numpy.testing import assert_allclose
from menpodetect.opencv import (load_opencv_frontal_face_detector,
load_opencv_eye_detector)
import menpo.io as mio
takeo = mio.import_builtin_asset.takeo_ppm()
def test_frontal_face_detector():
takeo_copy = takeo.copy()
opencv_detecto... | Use assert_allclose so we can see the appveyor failure | Use assert_allclose so we can see the appveyor failure
| Python | bsd-3-clause | yuxiang-zhou/menpodetect,jabooth/menpodetect,yuxiang-zhou/menpodetect,jabooth/menpodetect | ---
+++
@@ -1,3 +1,4 @@
+from numpy.testing import assert_allclose
from menpodetect.opencv import (load_opencv_frontal_face_detector,
load_opencv_eye_detector)
import menpo.io as mio
@@ -26,6 +27,6 @@
takeo_copy = takeo.copy()
opencv_detector = load_opencv_eye_detector()
... |
1f98e497136ce3d9da7e63a6dc7c3f67fedf50b5 | observations/views.py | observations/views.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import messages
from django.core.urlresolvers import reverse_lazy
from django.utils.translation import ugettext_lazy as _
from django.views.generic.edit import FormView
from braces.views import LoginRequiredMixin
from .forms import O... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import messages
from django.core.urlresolvers import reverse_lazy
from django.utils.translation import ugettext_lazy as _
from django.views.generic.edit import FormView
from braces.views import LoginRequiredMixin
from .forms import O... | Save the observation if the form was valid. | Save the observation if the form was valid.
| Python | mit | zsiciarz/variablestars.net,zsiciarz/variablestars.net,zsiciarz/variablestars.net | ---
+++
@@ -19,6 +19,12 @@
template_name = "observations/add_observation.html"
success_url = reverse_lazy('observations:add_observation')
+ def form_valid(self, form):
+ observation = form.save(commit=False)
+ observation.observer = self.request.observer
+ observation.save()
+ ... |
091ebd935c6145ac233c03bedeb52c65634939f4 | Lib/xml/__init__.py | Lib/xml/__init__.py | """Core XML support for Python.
This package contains three sub-packages:
dom -- The W3C Document Object Model. This supports DOM Level 1 +
Namespaces.
parsers -- Python wrappers for XML parsers (currently only supports Expat).
sax -- The Simple API for XML, developed by XML-Dev, led by David
Meggins... | """Core XML support for Python.
This package contains three sub-packages:
dom -- The W3C Document Object Model. This supports DOM Level 1 +
Namespaces.
parsers -- Python wrappers for XML parsers (currently only supports Expat).
sax -- The Simple API for XML, developed by XML-Dev, led by David
Meggins... | Include the version-detecting code to allow PyXML to override the "standard" xml package. Require at least PyXML 0.6.1. | Include the version-detecting code to allow PyXML to override the "standard"
xml package. Require at least PyXML 0.6.1.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | ---
+++
@@ -13,10 +13,27 @@
"""
+__all__ = ["dom", "parsers", "sax"]
+
+__version__ = "$Revision$"[1:-1].split()[1]
+
+
+_MINIMUM_XMLPLUS_VERSION = (0, 6, 1)
+
+
try:
import _xmlplus
except ImportError:
pass
else:
- import sys
- sys.modules[__name__] = _xmlplus
+ try:
+ v = _xmlplus.... |
3a27568211c07cf614aa9865a2f08d2a9b9bfb71 | dinosaurs/views.py | dinosaurs/views.py | import os
import json
import httplib as http
import tornado.web
import tornado.ioloop
from dinosaurs import api
from dinosaurs import settings
class SingleStatic(tornado.web.StaticFileHandler):
def initialize(self, path):
self.dirname, self.filename = os.path.split(path)
super(SingleStatic, self... | import os
import json
import httplib as http
import tornado.web
import tornado.ioloop
from dinosaurs import api
from dinosaurs import settings
class SingleStatic(tornado.web.StaticFileHandler):
def initialize(self, path):
self.dirname, self.filename = os.path.split(path)
super(SingleStatic, self... | Return errors in json only | Return errors in json only
| Python | mit | chrisseto/dinosaurs.sexy,chrisseto/dinosaurs.sexy | ---
+++
@@ -26,6 +26,12 @@
class EmailAPIHandler(tornado.web.RequestHandler):
+ def write_error(self, status_code, **kwargs):
+ self.finish({
+ "code": status_code,
+ "message": self._reason,
+ })
+
def post(self):
try:
req_json = json.loads(self.... |
f574e19b14ff861c45f6c66c64a2570bdb0e3a3c | crawl_comments.py | crawl_comments.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__doc__ = '''
Crawl comment from nicovideo.jp
Usage:
main_crawl.py [--sqlite <sqlite>] [--csv <csv>]
Options:
--sqlite <sqlite> (optional) path of comment DB [default: comments.sqlite3]
--csv <csv> (optional) path of csv file contains urls of videos ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__doc__ = '''
Crawl comment from nicovideo.jp
Usage:
crawl_comments.py [--sqlite <sqlite>] [--csv <csv>]
Options:
--sqlite <sqlite> (optional) path of comment DB [default: comments.sqlite3]
--csv <csv> (optional) path of csv file contains urls of vid... | Apply change of file name | Apply change of file name
| Python | mit | tosh1ki/NicoCrawler | ---
+++
@@ -6,7 +6,7 @@
Crawl comment from nicovideo.jp
Usage:
- main_crawl.py [--sqlite <sqlite>] [--csv <csv>]
+ crawl_comments.py [--sqlite <sqlite>] [--csv <csv>]
Options:
--sqlite <sqlite> (optional) path of comment DB [default: comments.sqlite3] |
317926c18ac2e139d2018acd767d10b4f53428f3 | installer/installer_config/views.py | installer/installer_config/views.py | from django.shortcuts import render
from django.shortcuts import render_to_response
from django.views.generic import CreateView, UpdateView, DeleteView
from installer_config.models import EnvironmentProfile, UserChoice, Step
from installer_config.forms import EnvironmentForm
from django.core.urlresolvers import reverse... | from django.shortcuts import render
from django.shortcuts import render_to_response
from django.views.generic import CreateView, UpdateView, DeleteView
from installer_config.models import EnvironmentProfile, UserChoice, Step
from installer_config.forms import EnvironmentForm
from django.core.urlresolvers import reverse... | Remove unneeded post method from CreateEnvProfile view | Remove unneeded post method from CreateEnvProfile view
| Python | mit | ezPy-co/ezpy,alibulota/Package_Installer,ezPy-co/ezpy,alibulota/Package_Installer | ---
+++
@@ -4,7 +4,7 @@
from installer_config.models import EnvironmentProfile, UserChoice, Step
from installer_config.forms import EnvironmentForm
from django.core.urlresolvers import reverse
-from django.http import HttpResponseRedirect
+
class CreateEnvironmentProfile(CreateView):
model = EnvironmentPro... |
c24dbc2d4d8b59a62a68f326edb350b3c633ea25 | interleaving/interleaving_method.py | interleaving/interleaving_method.py | class InterleavingMethod(object):
'''
Interleaving
'''
def interleave(self, k, a, b):
'''
k: the maximum length of resultant interleaving
a: a list of document IDs
b: a list of document IDs
Return an instance of Ranking
'''
raise NotImplementedErr... | class InterleavingMethod(object):
'''
Interleaving
'''
def interleave(self, k, a, b):
'''
k: the maximum length of resultant interleaving
a: a list of document IDs
b: a list of document IDs
Return an instance of Ranking
'''
raise NotImplementedErr... | Change the comment of InterleavingMethod.evaluate | Change the comment of InterleavingMethod.evaluate
| Python | mit | mpkato/interleaving | ---
+++
@@ -26,10 +26,11 @@
ranking: an instance of Ranking generated by Balanced.interleave
clicks: a list of indices clicked by a user
- Return one of the following tuples:
- - (1, 0): Ranking 'a' won
- - (0, 1): Ranking 'b' won
- - (0, 0): Tie
+ Return a list ... |
85769162560d83a58ccc92f818559ddd3dce2a09 | pages/index.py | pages/index.py | import web
from modules.base import renderer
from modules.login import loginInstance
from modules.courses import Course
#Index page
class IndexPage:
#Simply display the page
def GET(self):
if loginInstance.isLoggedIn():
userInput = web.input();
if "logoff" in userInput:
... | import web
from modules.base import renderer
from modules.login import loginInstance
from modules.courses import Course
#Index page
class IndexPage:
#Simply display the page
def GET(self):
if loginInstance.isLoggedIn():
userInput = web.input();
if "logoff" in userInput:
... | Fix another bug in the authentication | Fix another bug in the authentication
| Python | agpl-3.0 | layus/INGInious,GuillaumeDerval/INGInious,GuillaumeDerval/INGInious,layus/INGInious,layus/INGInious,GuillaumeDerval/INGInious,GuillaumeDerval/INGInious,layus/INGInious | ---
+++
@@ -13,14 +13,13 @@
loginInstance.disconnect();
return renderer.index(False)
else:
- courses = Course.GetAllCoursesIds()
- return renderer.main(courses)
+ return renderer.main(Course.GetAllCoursesIds())
else:
... |
6d8dbb6621da2ddfffd58303131eb6cda345e37c | pombola/south_africa/urls.py | pombola/south_africa/urls.py | from django.conf.urls import patterns, include, url
from pombola.south_africa.views import LatLonDetailView,SAPlaceDetailSub
urlpatterns = patterns('pombola.south_africa.views',
url(r'^place/latlon/(?P<lat>[0-9\.-]+),(?P<lon>[0-9\.-]+)/', LatLonDetailView.as_view(), name='latlon'),
url(r'^place/(?P<slug>[-\w]... | from django.conf.urls import patterns, include, url
from pombola.core.views import PersonDetailSub
from pombola.south_africa.views import LatLonDetailView,SAPlaceDetailSub
urlpatterns = patterns('pombola.south_africa.views',
url(r'^place/latlon/(?P<lat>[0-9\.-]+),(?P<lon>[0-9\.-]+)/', LatLonDetailView.as_view(), ... | Make person experience the default tab for ZA | Make person experience the default tab for ZA
| Python | agpl-3.0 | hzj123/56th,mysociety/pombola,geoffkilpin/pombola,hzj123/56th,mysociety/pombola,geoffkilpin/pombola,patricmutwiri/pombola,hzj123/56th,mysociety/pombola,patricmutwiri/pombola,ken-muturi/pombola,geoffkilpin/pombola,ken-muturi/pombola,hzj123/56th,patricmutwiri/pombola,patricmutwiri/pombola,patricmutwiri/pombola,hzj123/56t... | ---
+++
@@ -1,8 +1,10 @@
from django.conf.urls import patterns, include, url
+from pombola.core.views import PersonDetailSub
from pombola.south_africa.views import LatLonDetailView,SAPlaceDetailSub
urlpatterns = patterns('pombola.south_africa.views',
url(r'^place/latlon/(?P<lat>[0-9\.-]+),(?P<lon>[0-9\.-]... |
b65283984b1be7e8bb88d3281bb3654a3dd12233 | nova/tests/scheduler/__init__.py | nova/tests/scheduler/__init__.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 Openstack LLC.
# 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/... | Make sure test setup is run for subdirectories | Make sure test setup is run for subdirectories | Python | apache-2.0 | n0ano/ganttclient | ---
+++
@@ -0,0 +1,19 @@
+# vim: tabstop=4 shiftwidth=4 softtabstop=4
+
+# Copyright 2011 Openstack LLC.
+# 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... | |
84ee720fd2d8403de5f49c54fc41bfcb67a78f78 | stdnum/tr/__init__.py | stdnum/tr/__init__.py | # __init__.py - collection of Turkish numbers
# coding: utf-8
#
# Copyright (C) 2016 Arthur de Jong
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, ... | # __init__.py - collection of Turkish numbers
# coding: utf-8
#
# Copyright (C) 2016 Arthur de Jong
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, ... | Add missing vat alias for Turkey | Add missing vat alias for Turkey
| Python | lgpl-2.1 | arthurdejong/python-stdnum,arthurdejong/python-stdnum,arthurdejong/python-stdnum | ---
+++
@@ -19,3 +19,4 @@
# 02110-1301 USA
"""Collection of Turkish numbers."""
+from stdnum.tr import vkn as vat # noqa: F401 |
cf07c34fe3a3d7b8767e50e77e609253dd177cff | moulinette/utils/serialize.py | moulinette/utils/serialize.py | import logging
from json.encoder import JSONEncoder
import datetime
logger = logging.getLogger('moulinette.utils.serialize')
# JSON utilities -------------------------------------------------------
class JSONExtendedEncoder(JSONEncoder):
"""Extended JSON encoder
Extend default JSON encoder to recognize mor... | import logging
from json.encoder import JSONEncoder
import datetime
logger = logging.getLogger('moulinette.utils.serialize')
# JSON utilities -------------------------------------------------------
class JSONExtendedEncoder(JSONEncoder):
"""Extended JSON encoder
Extend default JSON encoder to recognize mor... | Use isoformat date RFC 3339 | [enh] Use isoformat date RFC 3339 | Python | agpl-3.0 | YunoHost/moulinette | ---
+++
@@ -27,7 +27,7 @@
# Convert compatible containers into list
if isinstance(o, datetime.datetime) or isinstance(o, datetime.date):
- return str(o)
+ return o.isoformat()
# Return the repr for object that json can't encode
logger.warning('cannot prope... |
25e71a56d48e5bdc4d73522333196d69d735707a | ports/nrf/boards/pca10056/examples/buttons.py | ports/nrf/boards/pca10056/examples/buttons.py | import board
import digitalio
import gamepad
import time
pad = gamepad.GamePad(
digitalio.DigitalInOut(board.PA11),
digitalio.DigitalInOut(board.PA12),
digitalio.DigitalInOut(board.PA24),
digitalio.DigitalInOut(board.PA25),
)
prev_buttons = 0
while True:
buttons = pad.get_pressed()
if button... | import board
import digitalio
import gamepad
import time
pad = gamepad.GamePad(
digitalio.DigitalInOut(board.P0_11),
digitalio.DigitalInOut(board.P0_12),
digitalio.DigitalInOut(board.P0_24),
digitalio.DigitalInOut(board.P0_25),
)
prev_buttons = 0
while True:
buttons = pad.get_pressed()
if bu... | Update the PCA10056 example to use new pin naming | nrf: Update the PCA10056 example to use new pin naming
| Python | mit | adafruit/micropython,adafruit/circuitpython,adafruit/circuitpython,adafruit/circuitpython,adafruit/circuitpython,adafruit/circuitpython,adafruit/micropython,adafruit/micropython,adafruit/micropython,adafruit/circuitpython,adafruit/micropython | ---
+++
@@ -4,10 +4,10 @@
import time
pad = gamepad.GamePad(
- digitalio.DigitalInOut(board.PA11),
- digitalio.DigitalInOut(board.PA12),
- digitalio.DigitalInOut(board.PA24),
- digitalio.DigitalInOut(board.PA25),
+ digitalio.DigitalInOut(board.P0_11),
+ digitalio.DigitalInOut(board.P0_12),
+ ... |
396ab20874a0c3492482a8ae03fd7d61980917a5 | chatterbot/adapters/logic/closest_match.py | chatterbot/adapters/logic/closest_match.py | # -*- coding: utf-8 -*-
from fuzzywuzzy import fuzz
from .base_match import BaseMatchAdapter
class ClosestMatchAdapter(BaseMatchAdapter):
"""
The ClosestMatchAdapter logic adapter creates a response by
using fuzzywuzzy's process class to extract the most similar
response to the input. This adapter s... | # -*- coding: utf-8 -*-
from fuzzywuzzy import fuzz
from .base_match import BaseMatchAdapter
class ClosestMatchAdapter(BaseMatchAdapter):
"""
The ClosestMatchAdapter logic adapter selects a known response
to an input by searching for a known statement that most closely
matches the input based on the L... | Update closest match adapter docstring. | Update closest match adapter docstring.
| Python | bsd-3-clause | Reinaesaya/OUIRL-ChatBot,vkosuri/ChatterBot,gunthercox/ChatterBot,Gustavo6046/ChatterBot,maclogan/VirtualPenPal,Reinaesaya/OUIRL-ChatBot,davizucon/ChatterBot | ---
+++
@@ -1,16 +1,13 @@
# -*- coding: utf-8 -*-
from fuzzywuzzy import fuzz
-
from .base_match import BaseMatchAdapter
class ClosestMatchAdapter(BaseMatchAdapter):
"""
- The ClosestMatchAdapter logic adapter creates a response by
- using fuzzywuzzy's process class to extract the most similar
- ... |
2947fe97d466872de05ada289d9172f41895969c | tests/templates/components/test_radios_with_images.py | tests/templates/components/test_radios_with_images.py | import json
def test_govuk_frontend_jinja_overrides_on_design_system_v3():
with open("package.json") as package_file:
package_json = json.load(package_file)
assert package_json["dependencies"]["govuk-frontend"].startswith("3."), (
"After upgrading the Design System, manually validate that "
... | import json
from importlib import metadata
from packaging.version import Version
def test_govuk_frontend_jinja_overrides_on_design_system_v3():
with open("package.json") as package_file:
package_json = json.load(package_file)
govuk_frontend_version = Version(package_json["dependencies"]["govuk-fr... | Update GOV.UK Frontend/Jinja lib test | Update GOV.UK Frontend/Jinja lib test
Check both the javascript and python packages, and make sure they're
both on our expected versions. If not, prompt the developer to check
macros.
| Python | mit | alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin | ---
+++
@@ -1,12 +1,23 @@
import json
+from importlib import metadata
+
+from packaging.version import Version
def test_govuk_frontend_jinja_overrides_on_design_system_v3():
with open("package.json") as package_file:
package_json = json.load(package_file)
+ govuk_frontend_version = Version(... |
15ae458f7cf1a8257967b2b3b0ceb812547c4766 | IPython/utils/tests/test_pycolorize.py | IPython/utils/tests/test_pycolorize.py | """Test suite for our color utilities.
Authors
-------
* Min RK
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING.txt, distributed as pa... | # coding: utf-8
"""Test suite for our color utilities.
Authors
-------
* Min RK
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING.txt, d... | Test more edge cases of the highlighting parser | Test more edge cases of the highlighting parser
| Python | bsd-3-clause | ipython/ipython,ipython/ipython | ---
+++
@@ -1,3 +1,4 @@
+# coding: utf-8
"""Test suite for our color utilities.
Authors
@@ -21,14 +22,57 @@
# our own
from IPython.utils.PyColorize import Parser
+import io
#-----------------------------------------------------------------------------
# Test functions
#-----------------------------------... |
6cb0822aade07999d54e5fcd19eb2c7322abc80a | measurement/admin.py | measurement/admin.py | from django.contrib import admin
from .models import Measurement
admin.site.register(Measurement)
| from django.contrib import admin
from .models import Measurement
class MeasurementAdmin(admin.ModelAdmin):
model = Measurement
def get_queryset(self, request):
return super(MeasurementAdmin, self).get_queryset(request).select_related('patient__user')
admin.site.register(Measurement, MeasurementAdmin... | Improve performance @ Measurement Admin | Improve performance @ Measurement Admin
| Python | mit | sigurdsa/angelika-api | ---
+++
@@ -1,4 +1,11 @@
from django.contrib import admin
from .models import Measurement
-admin.site.register(Measurement)
+
+class MeasurementAdmin(admin.ModelAdmin):
+ model = Measurement
+
+ def get_queryset(self, request):
+ return super(MeasurementAdmin, self).get_queryset(request).select_relat... |
b9b3837937341e6b1b052bbfdd979e3bb57d87c4 | tests/integration/test_with_ssl.py | tests/integration/test_with_ssl.py | from . import base
class SSLTestCase(base.IntegrationTestCase):
'''RabbitMQ integration test case.'''
CTXT = {
'plugin.activemq.pool.1.port': 61614,
'plugin.activemq.pool.1.password': 'marionette',
'plugin.ssl_server_public': 'tests/fixtures/server-public.pem',
'plugin.ssl_clie... | import os
from pymco.test import ctxt
from . import base
FIXTURES_PATH = os.path.join(ctxt.ROOT, 'fixtures')
class SSLTestCase(base.IntegrationTestCase):
'''RabbitMQ integration test case.'''
CTXT = {
'plugin.activemq.pool.1.port': 61614,
'plugin.activemq.pool.1.password': 'marionette',
... | Fix SSL security provider integration tests | Fix SSL security provider integration tests
They were running with none provider instead.
| Python | bsd-3-clause | rafaduran/python-mcollective,rafaduran/python-mcollective,rafaduran/python-mcollective,rafaduran/python-mcollective | ---
+++
@@ -1,4 +1,9 @@
+import os
+
+from pymco.test import ctxt
from . import base
+
+FIXTURES_PATH = os.path.join(ctxt.ROOT, 'fixtures')
class SSLTestCase(base.IntegrationTestCase):
@@ -9,6 +14,10 @@
'plugin.ssl_server_public': 'tests/fixtures/server-public.pem',
'plugin.ssl_client_private'... |
66284e57accec5977d606fc91a0b28177b352eb4 | test/test_producer.py | test/test_producer.py | import pytest
from kafka import KafkaConsumer, KafkaProducer
from test.conftest import version
from test.testutil import random_string
@pytest.mark.skipif(not version(), reason="No KAFKA_VERSION set")
def test_end_to_end(kafka_broker):
connect_str = 'localhost:' + str(kafka_broker.port)
producer = KafkaProdu... | import pytest
from kafka import KafkaConsumer, KafkaProducer
from test.conftest import version
from test.testutil import random_string
@pytest.mark.skipif(not version(), reason="No KAFKA_VERSION set")
@pytest.mark.parametrize("compression", [None, 'gzip', 'snappy', 'lz4'])
def test_end_to_end(kafka_broker, compressi... | Add end-to-end integration testing for all compression types | Add end-to-end integration testing for all compression types
| Python | apache-2.0 | dpkp/kafka-python,ohmu/kafka-python,Yelp/kafka-python,ohmu/kafka-python,zackdever/kafka-python,Aloomaio/kafka-python,DataDog/kafka-python,Aloomaio/kafka-python,wikimedia/operations-debs-python-kafka,mumrah/kafka-python,scrapinghub/kafka-python,mumrah/kafka-python,dpkp/kafka-python,Yelp/kafka-python,scrapinghub/kafka-py... | ---
+++
@@ -6,10 +6,17 @@
@pytest.mark.skipif(not version(), reason="No KAFKA_VERSION set")
-def test_end_to_end(kafka_broker):
+@pytest.mark.parametrize("compression", [None, 'gzip', 'snappy', 'lz4'])
+def test_end_to_end(kafka_broker, compression):
+
+ # LZ4 requires 0.8.2
+ if compression == 'lz4' and v... |
4cbbe7c3ab891a11492f368d780a1416d37358ff | feedzilla/syndication.py | feedzilla/syndication.py | # -*- coding: utf-8 -*-
# Copyright: 2011, Grigoriy Petukhov
# Author: Grigoriy Petukhov (http://lorien.name)
# License: BSD
from django.contrib.syndication.views import Feed
from django.conf import settings
from feedzilla.models import Post
class PostFeed(Feed):
title_template = 'feedzilla/feed/post_title.html... | # -*- coding: utf-8 -*-
# Copyright: 2011, Grigoriy Petukhov
# Author: Grigoriy Petukhov (http://lorien.name)
# License: BSD
from django.contrib.syndication.views import Feed
from django.conf import settings
from feedzilla.models import Post
class PostFeed(Feed):
title_template = 'feedzilla/feed/post_title.html... | Change the method of generating content of GUID element | Change the method of generating content of GUID element
| Python | bsd-3-clause | feedzilla/feedzilla,feedzilla/feedzilla,feedzilla/feedzilla | ---
+++
@@ -31,4 +31,4 @@
return item.created
def item_guid(self, item):
- return str(item.guid)
+ return item.link |
f127f0e9bb0b8778feafbdbc1fa68e79a923d639 | whats_fresh/whats_fresh_api/tests/views/entry/test_list_products.py | whats_fresh/whats_fresh_api/tests/views/entry/test_list_products.py | from django.test import TestCase
from django.core.urlresolvers import reverse
from whats_fresh_api.models import *
from django.contrib.gis.db import models
import json
class ListProductTestCase(TestCase):
fixtures = ['test_fixtures']
def test_url_endpoint(self):
url = reverse('entry-list-products')
... | from django.test import TestCase
from django.core.urlresolvers import reverse
from whats_fresh_api.models import *
from django.contrib.gis.db import models
import json
class ListProductTestCase(TestCase):
fixtures = ['test_fixtures']
def test_url_endpoint(self):
url = reverse('entry-list-products')
... | Update product listing test to use product ids rather than index | Update product listing test to use product ids rather than index
| Python | apache-2.0 | osu-cass/whats-fresh-api,osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api,osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api,iCHAIT/whats-fresh-api,osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api | ---
+++
@@ -14,23 +14,30 @@
def test_list_items(self):
"""
- Tests to see if the list of products contains the proper productss and
+ Tests to see if the list of products contains the proper products and
proper product data
"""
response = self.client.get(revers... |
12b34fc09baa5060495e25e57680d1f6170559c5 | addons/bestja_configuration_fpbz/__openerp__.py | addons/bestja_configuration_fpbz/__openerp__.py | # -*- coding: utf-8 -*-
{
'name': "Bestja: FBŻ",
'summary': "Installation configuration for FPBŻ",
'description': "Installation configuration for Federacja Polskich Banków Żywności",
'author': "Laboratorium EE",
'website': "http://www.laboratorium.ee",
'version': '0.1',
'category': 'Specific... | # -*- coding: utf-8 -*-
{
'name': "Bestja: FBŻ",
'summary': "Installation configuration for FPBŻ",
'description': "Installation configuration for Federacja Polskich Banków Żywności",
'author': "Laboratorium EE",
'website': "http://www.laboratorium.ee",
'version': '0.1',
'category': 'Specific... | Enable estimation reports for FPBŻ | Enable estimation reports for FPBŻ
| Python | agpl-3.0 | KamilWo/bestja,EE/bestja,ludwiktrammer/bestja,KrzysiekJ/bestja,ludwiktrammer/bestja,KrzysiekJ/bestja,KrzysiekJ/bestja,ludwiktrammer/bestja,EE/bestja,KamilWo/bestja,EE/bestja,KamilWo/bestja | ---
+++
@@ -20,6 +20,7 @@
'bestja_stores',
'bestja_requests',
'bestja_detailed_reports',
+ 'bestja_estimation_reports',
'bestja_offers',
'bestja_offers_by_org',
'bestja_files', |
fc75f5843af70c09e0d63284277bf88689cbb06d | invocations/docs.py | invocations/docs.py | import os
from invoke.tasks import task
from invoke.runner import run
docs_dir = 'docs'
build = os.path.join(docs_dir, '_build')
@task
def clean_docs():
run("rm -rf %s" % build)
@task
def browse_docs():
run("open %s" % os.path.join(build, 'index.html'))
@task
def docs(clean=False, browse=False):
if... | import os
from invoke.tasks import task
from invoke.runner import run
docs_dir = 'docs'
build = os.path.join(docs_dir, '_build')
@task
def clean_docs():
run("rm -rf %s" % build)
@task
def browse_docs():
run("open %s" % os.path.join(build, 'index.html'))
@task
def api_docs(target, output="api", exclude=... | Add apidoc to doc building | Add apidoc to doc building
| Python | bsd-2-clause | mrjmad/invocations,pyinvoke/invocations,alex/invocations,singingwolfboy/invocations | ---
+++
@@ -19,7 +19,41 @@
@task
-def docs(clean=False, browse=False):
+def api_docs(target, output="api", exclude=""):
+ """
+ Runs ``sphinx-apidoc`` to autogenerate your API docs.
+
+ Must give target directory/package as ``target``. Results are written out
+ to ``docs/<output>`` (``docs/api`` by d... |
a9ac098ec492739f37005c9bd6278105df0261c5 | parliamentsearch/items.py | parliamentsearch/items.py | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class MemberofParliament(scrapy.Item):
"""
Data structure to define Member of Parliament information
"""
mp_id = scrapy.Field()
mp_name = scrapy.F... | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class MemberofParliament(scrapy.Item):
"""
Data structure to define Member of Parliament information
"""
mp_id = scrapy.Field()
mp_name = scrapy.F... | Add fields to save question url and annexure links | Add fields to save question url and annexure links
Details of each question is in another link and some questions have annexures
(in English/Hindi), add fields to save all these items
Signed-off-by: Arun Siluvery <66692e34e783869a1e5829b4c5eee5e1a471c4f7@gmail.com>
| Python | mit | mthipparthi/parliament-search | ---
+++
@@ -43,3 +43,5 @@
q_ministry = scrapy.Field()
q_member = scrapy.Field()
q_subject = scrapy.Field()
+ q_url = scrapy.Field()
+ q_annex = scrapy.Field() |
376b8aa5b77066e06c17f41d65fe32a3c2bdef1f | geo.py | geo.py | #! /usr/bin/python3
# -*- coding-utf-8 -*-
"""
This script transform a md into a plain html in the context of a
documentation for Kit&Pack.
"""
import mmap
import yaml
print("---------------------------- geo --")
print("-- by antoine.delhomme@espci.org --")
print("-----------------------------------")
doc_in = "./0... | #! /usr/bin/python3
# -*- coding-utf-8 -*-
"""
This script transform a md into a plain html in the context of a
documentation for Kit&Pack.
"""
import mmap
import yaml
print("---------------------------- geo --")
print("-- by antoine.delhomme@espci.org --")
print("-----------------------------------")
doc_in = "./0... | Add a default value to the header limit | Add a default value to the header limit
| Python | mit | a2ohm/geo | ---
+++
@@ -20,6 +20,7 @@
def __init__(self, doc_in):
self.doc_in = doc_in
self.header = None
+ self.header_limit = -1
def __enter__(self):
"""Open the file. |
fdae17a50223c2f9b8ba4a665fc24726e2c2ce14 | tests/lib/es_tools.py | tests/lib/es_tools.py | """ Commands for interacting with Elastic Search """
# pylint: disable=broad-except
from os.path import join
import requests
from lib.tools import TEST_FOLDER
def es_is_available():
""" Test if Elastic Search is running """
try:
return (
requests.get("http://localhost:9200").json()["ta... | """ Commands for interacting with Elastic Search """
# pylint: disable=broad-except
from os.path import join
import requests
from lib.tools import TEST_FOLDER
def es_is_available():
""" Test if Elastic Search is running """
try:
return (
requests.get("http://localhost:9200", auth=("ela... | Add auth header to the fixture loader | Add auth header to the fixture loader
It seems to work fine with the unauthenticated es instance
| Python | mit | matthewfranglen/postgres-elasticsearch-fdw | ---
+++
@@ -13,7 +13,9 @@
try:
return (
- requests.get("http://localhost:9200").json()["tagline"]
+ requests.get("http://localhost:9200", auth=("elastic", "changeme")).json()[
+ "tagline"
+ ]
== "You Know, for Search"
)
except ... |
87244598ed08e790835818656ecba0178bb7ca89 | fsplit/__init__.py | fsplit/__init__.py | #!/usr/bin/env python2
##
# fsplit
# https://github.com/leosartaj/fsplit.git
#
# Copyright (c) 2014 Sartaj Singh
# Licensed under the MIT license.
##
from info import __version__ # define __version__ variable
from info import __desc__ # define __desc__ variable for description
| #!/usr/bin/env python2
##
# fsplit
# https://github.com/leosartaj/fsplit.git
#
# Copyright (c) 2014 Sartaj Singh
# Licensed under the MIT license.
##
from .info import __version__ # define __version__ variable
from .info import __desc__ # define __desc__ variable for description
| Upgrade to a better version | Upgrade to a better version
from info import __version__ # define __version__ variable ModuleNotFoundError: No module named 'info
Gave error while building
Coz of missing . | Python | mit | leosartaj/fsplit | ---
+++
@@ -8,5 +8,5 @@
# Licensed under the MIT license.
##
-from info import __version__ # define __version__ variable
-from info import __desc__ # define __desc__ variable for description
+from .info import __version__ # define __version__ variable
+from .info import __desc__ # define __desc__ variable for des... |
bafdbd28e35d80d28bfb82c23532533cb2915066 | fuel/exceptions.py | fuel/exceptions.py | class AxisLabelsMismatchError(ValueError):
"""Raised when a pair of axis labels tuples do not match."""
class ConfigurationError(Exception):
"""Error raised when a configuration value is requested but not set."""
class MissingInputFiles(Exception):
"""Exception raised by a converter when input files are... | class AxisLabelsMismatchError(ValueError):
"""Raised when a pair of axis labels tuples do not match."""
class ConfigurationError(Exception):
"""Error raised when a configuration value is requested but not set."""
class MissingInputFiles(Exception):
"""Exception raised by a converter when input files are... | Add docs for MissingInputFiles 'message' arg. | Add docs for MissingInputFiles 'message' arg.
| Python | mit | hantek/fuel,rodrigob/fuel,dmitriy-serdyuk/fuel,codeaudit/fuel,udibr/fuel,mjwillson/fuel,dribnet/fuel,capybaralet/fuel,aalmah/fuel,glewis17/fuel,glewis17/fuel,vdumoulin/fuel,dmitriy-serdyuk/fuel,dwf/fuel,bouthilx/fuel,mila-udem/fuel,chrishokamp/fuel,udibr/fuel,janchorowski/fuel,dwf/fuel,dribnet/fuel,markusnagel/fuel,aal... | ---
+++
@@ -11,6 +11,8 @@
Parameters
----------
+ message : str
+ The error message to be associated with this exception.
filenames : list
A list of filenames that were not found.
|
0fdb93fb73142315fe404b9a161ef19af0d920cd | tests/test_bawlerd.py | tests/test_bawlerd.py | import io
import os
from textwrap import dedent
from pg_bawler import bawlerd
class TestBawlerdConfig:
def test_build_config_location_list(self):
assert not bawlerd.conf.build_config_location_list(locations=())
user_conf = os.path.join(
os.path.expanduser('~'),
bawlerd.c... | import io
import os
from textwrap import dedent
from pg_bawler import bawlerd
class TestBawlerdConfig:
def test_build_config_location_list(self):
assert not bawlerd.conf.build_config_location_list(locations=())
user_conf = os.path.join(
os.path.expanduser('~'),
bawlerd.c... | Add simple test for config builder | Add simple test for config builder
Signed-off-by: Michal Kuffa <005ee1c97edba97d164343c993afee612ac25a0c@gmail.com>
| Python | bsd-3-clause | beezz/pg_bawler,beezz/pg_bawler | ---
+++
@@ -39,3 +39,16 @@
propagate: True
""")))
assert 'logging' in config
+
+ def test_read_config_files(self):
+ config_base = os.path.join(
+ os.path.abspath(os.path.dirname(__file__)), 'configs')
+ locations = [
+ os.path.join(config_ba... |
ea3ad65d3d0976ec24c15703fafacb805a6b5351 | students/psbriant/final_project/clean_data.py | students/psbriant/final_project/clean_data.py | """
Name: Paul Briant
Date: 12/11/16
Class: Introduction to Python
Assignment: Final Project
Description:
Code for Final Project
"""
import pandas
from datetime import datetime
def clean(data):
"""
Take in data and return cleaned version.
"""
# Remove Date Values column
data = data.drop(["Date V... | """
Name: Paul Briant
Date: 12/11/16
Class: Introduction to Python
Assignment: Final Project
Description:
Code for Final Project
"""
import pandas
import matplotlib.pyplot as plt
from datetime import datetime
def clean(data):
"""
Take in data and return cleaned version.
"""
# Remove Date Values colu... | Add simple plots of downtown LA wateruse. | Add simple plots of downtown LA wateruse.
| Python | unlicense | UWPCE-PythonCert/IntroPython2016,UWPCE-PythonCert/IntroPython2016,UWPCE-PythonCert/IntroPython2016,weidnem/IntroPython2016,weidnem/IntroPython2016,weidnem/IntroPython2016 | ---
+++
@@ -9,6 +9,7 @@
"""
import pandas
+import matplotlib.pyplot as plt
from datetime import datetime
@@ -35,6 +36,15 @@
print(under25)
+def plot_zipcode(data, zipcode):
+ """
+
+ """
+ # data["90012"].plot(kind="bar", rot=10)
+ plt.plot(data[zipcode])
+ plt.show()
+
+
def main():... |
c99e0ac2e463302d41838f11ea28ea8a62990671 | wafer/kv/serializers.py | wafer/kv/serializers.py | from django.core.exceptions import PermissionDenied
from rest_framework import serializers
from wafer.kv.models import KeyValue
class KeyValueSerializer(serializers.ModelSerializer):
class Meta:
model = KeyValue
# There doesn't seem to be a better way of handling the problem
# of filtering the g... | from django.core.exceptions import PermissionDenied
from rest_framework import serializers
from wafer.kv.models import KeyValue
class KeyValueSerializer(serializers.ModelSerializer):
class Meta:
model = KeyValue
fields = ('group', 'key', 'value')
# There doesn't seem to be a better way of ha... | Add catchall fields property to KeyValueSerializer | Add catchall fields property to KeyValueSerializer
With the latest django-restframework, not explicitly setting the
fields for a serializer causes errors. This explicitly sets the
fields to those of the model.
| Python | isc | CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer | ---
+++
@@ -7,6 +7,7 @@
class Meta:
model = KeyValue
+ fields = ('group', 'key', 'value')
# There doesn't seem to be a better way of handling the problem
# of filtering the groups. |
f802111f1f241444f874119e5949f3da4abd1c85 | python/raindrops/raindrops.py | python/raindrops/raindrops.py | def raindrops(number):
if is_three_a_factor(number):
return "Pling"
if is_five_a_factor(number):
return "Plang"
return "{}".format(number)
def is_three_a_factor(number):
return number % 3 == 0
def is_five_a_factor(number):
return number % 5 == 0
| def raindrops(number):
if is_three_a_factor(number):
return "Pling"
if is_five_a_factor(number):
return "Plang"
if is_seven_a_factor(number):
return "Plong"
return "{}".format(number)
def is_three_a_factor(number):
return number % 3 == 0
def is_five_a_factor(number):
re... | Handle 7 as a factor | Handle 7 as a factor
| Python | mit | rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism | ---
+++
@@ -3,6 +3,8 @@
return "Pling"
if is_five_a_factor(number):
return "Plang"
+ if is_seven_a_factor(number):
+ return "Plong"
return "{}".format(number)
def is_three_a_factor(number):
@@ -10,3 +12,6 @@
def is_five_a_factor(number):
return number % 5 == 0
+
+def i... |
21844df3e266803cc119d049faadddb5bf5410f0 | run.py | run.py | import serial
import threading
print('Starting server...')
temperature_usb = '/dev/ttyAMA0'
BAUD_RATE = 9600
temperature_ser = ser.Serial(temperature_usb, BAUD_RATE)
def process_line(line):
print('Need to process line: {}'.format(line))
def temperature_loop():
line = ""
while True:
data = temperature_ser.read(... | import serial
import threading
print('Starting server...')
temperature_usb = '/dev/ttyAMA0'
BAUD_RATE = 9600
temperature_ser = serial.Serial(temperature_usb, BAUD_RATE)
def process_line(line):
print('Need to process line: {}'.format(line))
def temperature_loop():
line = ""
while True:
data = temperature_ser.re... | Use serial instead of ser, DUH | Use serial instead of ser, DUH
| Python | mit | illumenati/duwamish-sensor,tipsqueal/duwamish-sensor | ---
+++
@@ -5,7 +5,7 @@
temperature_usb = '/dev/ttyAMA0'
BAUD_RATE = 9600
-temperature_ser = ser.Serial(temperature_usb, BAUD_RATE)
+temperature_ser = serial.Serial(temperature_usb, BAUD_RATE)
def process_line(line):
print('Need to process line: {}'.format(line)) |
bb86433e80c1361b57c58fb32a2e250e915b1b05 | thinglang/__init__.py | thinglang/__init__.py | import os
from thinglang import utils
from thinglang.execution.execution import ExecutionEngine
from thinglang.lexer.lexer import lexer
from thinglang.parser.analyzer import Analyzer
from thinglang.parser.parser import parse
from thinglang.parser.simplifier import Simplifier
BASE_DIR = os.path.join(os.path.dirname(os... | import os
from thinglang import utils
from thinglang.execution.execution import ExecutionEngine
from thinglang.lexer.lexer import lexer
from thinglang.parser.analyzer import Analyzer
from thinglang.parser.parser import parse
from thinglang.parser.simplifier import Simplifier
BASE_DIR = os.path.join(os.path.dirname(os... | Print C++ code during parsing | Print C++ code during parsing
| Python | mit | ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang | ---
+++
@@ -28,6 +28,7 @@
Simplifier(ast).run()
+ utils.print_header('C++ Transpilation', ast.transpile_children())
utils.print_header('Parsed AST', ast.tree())
Analyzer(ast).run() |
baacda228682a50acc5a4528d43f5d3a88c7c6ec | salt/client/netapi.py | salt/client/netapi.py | # encoding: utf-8
'''
The main entry point for salt-api
'''
# Import python libs
import logging
import multiprocessing
# Import salt-api libs
import salt.loader
logger = logging.getLogger(__name__)
class NetapiClient(object):
'''
Start each netapi module that is configured to run
'''
def __init__(se... | # encoding: utf-8
'''
The main entry point for salt-api
'''
# Import python libs
import logging
import multiprocessing
import signal
# Import salt-api libs
import salt.loader
logger = logging.getLogger(__name__)
class NetapiClient(object):
'''
Start each netapi module that is configured to run
'''
d... | Make sure to not leave hanging children processes if the parent is killed | Make sure to not leave hanging children processes if the parent is killed
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -5,6 +5,7 @@
# Import python libs
import logging
import multiprocessing
+import signal
# Import salt-api libs
import salt.loader
@@ -18,6 +19,7 @@
'''
def __init__(self, opts):
self.opts = opts
+ self.processes = []
def run(self):
'''
@@ -27,4 +29,17 @@
... |
a3b119e14df4aff213231492470587f88457a241 | setuptools/command/upload.py | setuptools/command/upload.py | import getpass
from distutils.command import upload as orig
class upload(orig.upload):
"""
Override default upload behavior to obtain password
in a variety of different ways.
"""
def finalize_options(self):
orig.upload.finalize_options(self)
# Attempt to obtain password. Short cir... | import getpass
from distutils.command import upload as orig
class upload(orig.upload):
"""
Override default upload behavior to obtain password
in a variety of different ways.
"""
def finalize_options(self):
orig.upload.finalize_options(self)
# Attempt to obtain password. Short cir... | Add carriage return for symmetry | Add carriage return for symmetry
| Python | mit | pypa/setuptools,pypa/setuptools,pypa/setuptools | ---
+++
@@ -13,7 +13,8 @@
# Attempt to obtain password. Short circuit evaluation at the first
# sign of success.
self.password = (
- self.password or self._load_password_from_keyring() or
+ self.password or
+ self._load_password_from_keyring() or
... |
1dade842098292f2201502fa55239a98628dfc2b | scheduler/schedule.py | scheduler/schedule.py | import sys
import time
import logging
logging.basicConfig(level=logging.DEBUG)
from redis import StrictRedis
from rq import Queue
from apscheduler.schedulers.blocking import BlockingScheduler
from d1lod import jobs
conn = StrictRedis(host='redis', port='6379')
q = Queue(connection=conn)
sched = BlockingScheduler()
... | import sys
import time
import logging
logging.basicConfig(level=logging.DEBUG)
from redis import StrictRedis
from rq import Queue
from apscheduler.schedulers.blocking import BlockingScheduler
from d1lod import jobs
conn = StrictRedis(host='redis', port='6379')
q = Queue(connection=conn)
sched = BlockingScheduler()
... | Set update job timeout back to a more reasonable value | Set update job timeout back to a more reasonable value
| Python | apache-2.0 | ec-geolink/d1lod,ec-geolink/d1lod,ec-geolink/d1lod,ec-geolink/d1lod | ---
+++
@@ -16,7 +16,7 @@
@sched.scheduled_job('interval', minutes=1)
def queue_update_job():
- q.enqueue(jobs.update_graph, timeout=604800) # 7 day timeout
+ q.enqueue(jobs.update_graph, timeout=3600) # 1 hour timeout
@sched.scheduled_job('interval', minutes=1)
def queue_stats_job(): |
0b8cc130f00b51b18e55805f82ba661fdf66fba6 | saml2idp/saml2idp_metadata.py | saml2idp/saml2idp_metadata.py | """
Django Settings that more closely resemble SAML Metadata.
Detailed discussion is in doc/SETTINGS_AND_METADATA.txt.
"""
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
CERTIFICATE_DATA = 'certificate_data'
CERTIFICATE_FILENAME = 'certificate_file'
PRIVATE_KEY_DATA = 'privat... | """
Django Settings that more closely resemble SAML Metadata.
Detailed discussion is in doc/SETTINGS_AND_METADATA.txt.
"""
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
CERTIFICATE_DATA = 'certificate_data'
CERTIFICATE_FILENAME = 'certificate_file'
PRIVATE_KEY_DATA = 'privat... | Implement suggested changes in PR review | Implement suggested changes in PR review
| Python | mit | mobify/dj-saml-idp,mobify/dj-saml-idp,mobify/dj-saml-idp | ---
+++
@@ -13,11 +13,11 @@
def check_configuration_contains(config, keys):
- available_keys = set(keys).intersection(set(config.keys()))
+ available_keys = frozenset(keys).intersection(frozenset(config.keys()))
if not available_keys:
raise ImproperlyConfigured(
- 'one of the fol... |
b6c63bedc6fcd2294aae60643f41df4acb2ee681 | pdfminer/pdfcolor.py | pdfminer/pdfcolor.py | import collections
from .psparser import LIT
import six #Python 2+3 compatibility
## PDFColorSpace
##
LITERAL_DEVICE_GRAY = LIT('DeviceGray')
LITERAL_DEVICE_RGB = LIT('DeviceRGB')
LITERAL_DEVICE_CMYK = LIT('DeviceCMYK')
class PDFColorSpace(object):
def __init__(self, name, ncomponents):
self.name = na... | import collections
from .psparser import LIT
import six #Python 2+3 compatibility
## PDFColorSpace
##
LITERAL_DEVICE_GRAY = LIT('DeviceGray')
LITERAL_DEVICE_RGB = LIT('DeviceRGB')
LITERAL_DEVICE_CMYK = LIT('DeviceCMYK')
class PDFColorSpace(object):
def __init__(self, name, ncomponents):
self.name = na... | Make DeviceGray the default color as it should be | Make DeviceGray the default color as it should be
| Python | mit | goulu/pdfminer,pdfminer/pdfminer.six | ---
+++
@@ -23,12 +23,12 @@
PREDEFINED_COLORSPACE = collections.OrderedDict()
for (name, n) in [
+ ('DeviceGray', 1), # default value first
('CalRGB', 3),
('CalGray', 1),
('Lab', 3),
('DeviceRGB', 3),
('DeviceCMYK', 4),
- ('DeviceGray', 1),
('Separation', 1),
('Indexed', ... |
70ba84dc485ed3db4ccf5008db87b2c9f003634b | tests/fixtures/__init__.py | tests/fixtures/__init__.py | """Test data"""
from pathlib import Path
def patharg(path):
"""
Back slashes need to be escaped in ITEM args,
even in Windows paths.
"""
return str(path).replace('\\', '\\\\\\')
FIXTURES_ROOT = Path(__file__).parent
FILE_PATH = FIXTURES_ROOT / 'test.txt'
JSON_FILE_PATH = FIXTURES_ROOT / 'test.j... | """Test data"""
from pathlib import Path
def patharg(path):
"""
Back slashes need to be escaped in ITEM args,
even in Windows paths.
"""
return str(path).replace('\\', '\\\\\\')
FIXTURES_ROOT = Path(__file__).parent
FILE_PATH = FIXTURES_ROOT / 'test.txt'
JSON_FILE_PATH = FIXTURES_ROOT / 'test.j... | Fix fixture encoding on Windows | Fix fixture encoding on Windows
| Python | bsd-3-clause | PKRoma/httpie,jakubroztocil/httpie,jkbrzt/httpie,jakubroztocil/httpie,jkbrzt/httpie,jakubroztocil/httpie,jkbrzt/httpie,PKRoma/httpie | ---
+++
@@ -23,9 +23,9 @@
# Strip because we don't want new lines in the data so that we can
# easily count occurrences also when embedded in JSON (where the new
# line would be escaped).
-FILE_CONTENT = FILE_PATH.read_text().strip()
+FILE_CONTENT = FILE_PATH.read_text('utf8').strip()
-JSON_FILE_CONTENT = JSON... |
4d7df38e056d0132af41759062cf8e380c736250 | django_backend_test/noras_menu/urls.py | django_backend_test/noras_menu/urls.py | # -*- encoding: utf-8 -*-
from django.conf.urls import url, include
from django.views.decorators.csrf import csrf_exempt
from .views import CreateMenu,ListMenu,UpdateMenu,CreateSelection,ListSelection,CreateSubscriber
urlpatterns = [
url(r'^menu/new$',CreateMenu.as_view(),name='Create Menu'),
url(r'^menu/edit/... | Update Urls from nora_menu app | Update Urls from nora_menu app
| Python | mit | semorale/backend-test,semorale/backend-test,semorale/backend-test | ---
+++
@@ -0,0 +1,14 @@
+# -*- encoding: utf-8 -*-
+from django.conf.urls import url, include
+from django.views.decorators.csrf import csrf_exempt
+from .views import CreateMenu,ListMenu,UpdateMenu,CreateSelection,ListSelection,CreateSubscriber
+
+urlpatterns = [
+ url(r'^menu/new$',CreateMenu.as_view(),name='Cr... | |
4be668a7d8cdb692c20be2eabf65c20e294e16a8 | scopus/utils/get_encoded_text.py | scopus/utils/get_encoded_text.py | # Namespaces for Scopus XML
ns = {'dtd': 'http://www.elsevier.com/xml/svapi/abstract/dtd',
'dn': 'http://www.elsevier.com/xml/svapi/abstract/dtd',
'ait': "http://www.elsevier.com/xml/ani/ait",
'cto': "http://www.elsevier.com/xml/cto/dtd",
'xocs': "http://www.elsevier.com/xml/xocs/dtd",
'ce... | # Namespaces for Scopus XML
ns = {'dtd': 'http://www.elsevier.com/xml/svapi/abstract/dtd',
'dn': 'http://www.elsevier.com/xml/svapi/abstract/dtd',
'ait': "http://www.elsevier.com/xml/ani/ait",
'cto': "http://www.elsevier.com/xml/cto/dtd",
'xocs': "http://www.elsevier.com/xml/xocs/dtd",
'ce... | Use itertext() to skip children in elements with text | Use itertext() to skip children in elements with text
| Python | mit | scopus-api/scopus,jkitchin/scopus | ---
+++
@@ -28,6 +28,6 @@
result : str
"""
try:
- return container.find(xpath, ns).text
+ return "".join(container.find(xpath, ns).itertext())
except AttributeError:
return None |
e924f67b37c1a7612e520cca9715152029ddf338 | test/integration/ggrc/services/test_query_snapshots.py | test/integration/ggrc/services/test_query_snapshots.py | # coding: utf-8
# Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Tests for /query api endpoint."""
from datetime import datetime
from operator import itemgetter
from flask import json
from nose.plugins.skip import SkipTest
from ggrc import db
from gg... | # coding: utf-8
# Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Tests for /query api endpoint."""
from ggrc import views
from ggrc import models
from integration.ggrc.converters import TestCase
from integration.ggrc.models import factories
class ... | Update snapshot query test generation | Update snapshot query test generation
| Python | apache-2.0 | selahssea/ggrc-core,plamut/ggrc-core,andrei-karalionak/ggrc-core,VinnieJohns/ggrc-core,josthkko/ggrc-core,AleksNeStu/ggrc-core,j0gurt/ggrc-core,j0gurt/ggrc-core,j0gurt/ggrc-core,andrei-karalionak/ggrc-core,VinnieJohns/ggrc-core,VinnieJohns/ggrc-core,selahssea/ggrc-core,josthkko/ggrc-core,AleksNeStu/ggrc-core,josthkko/g... | ---
+++
@@ -5,14 +5,9 @@
"""Tests for /query api endpoint."""
-from datetime import datetime
-from operator import itemgetter
-from flask import json
-from nose.plugins.skip import SkipTest
-from ggrc import db
from ggrc import views
-from ggrc.models import CustomAttributeDefinition as CAD
+from ggrc import ... |
aaa3f6b8154f03eab16528c05d889c6160e63f22 | server/siege/views/devices.py | server/siege/views/devices.py | from flask import request
from flask import url_for
from flask import abort
from siege.service import app, db
from siege.models import Device
from view_utils import jsonate
@app.route('/devices')
def devices_index():
response = jsonate([d.to_dict() for d in Device.query.all()])
return response
@app.route('... | from flask import request
from flask import url_for
from flask import abort
from siege.service import app, db
from siege.models import Device
from view_utils import jsonate
@app.route('/devices')
def devices_index():
response = jsonate([d.to_dict() for d in Device.query.all()])
return response
@app.route('... | Put the user agent in the device object | Put the user agent in the device object
| Python | bsd-2-clause | WalterCReel3/siege,WalterCReel3/siege,WalterCReel3/siege,WalterCReel3/siege | ---
+++
@@ -24,7 +24,9 @@
@app.route('/devices', methods=['POST'])
def devices_create():
- new_device = Device(comment=request.access_route)
+ comment = '%s, %s' % (request.remote_addr, request.user_agent)
+
+ new_device = Device(comment=comment)
db.session.add(new_device)
db.session.commit()
|
95d0461cf2f06534f81a954b1f95658cbb019ec6 | tests/startsymbol_tests/NonterminalNotInGrammarTest.py | tests/startsymbol_tests/NonterminalNotInGrammarTest.py | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 10.08.2017 23:20
:Licence GNUv3
Part of grammpy
"""
from unittest import TestCase, main
from grammpy import *
from grammpy.exceptions import NonterminalDoesNotExistsException
class NonterminalNotInGrammarTest(TestCase):
pass
if __name__ == '__main__':... | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 10.08.2017 23:20
:Licence GNUv3
Part of grammpy
"""
from unittest import TestCase, main
from grammpy import *
from grammpy.exceptions import NonterminalDoesNotExistsException
class A(Nonterminal):
pass
class B(Nonterminal):
pass
class Nontermina... | Add tests of setting nonterminal, which is not in grammar, as start symbol | Add tests of setting nonterminal, which is not in grammar, as start symbol
| Python | mit | PatrikValkovic/grammpy | ---
+++
@@ -12,8 +12,36 @@
from grammpy.exceptions import NonterminalDoesNotExistsException
+class A(Nonterminal):
+ pass
+
+
+class B(Nonterminal):
+ pass
+
+
class NonterminalNotInGrammarTest(TestCase):
- pass
+ def test_shouldNotSetStartSymbol(self):
+ g = Grammar(nonterminals=[A])
+ ... |
7e88a5d648d8e9aec82be14cd55667136adb3754 | pytest-{{cookiecutter.plugin_name}}/test_{{cookiecutter.plugin_name}}.py | pytest-{{cookiecutter.plugin_name}}/test_{{cookiecutter.plugin_name}}.py | # -*- coding: utf-8 -*-
def test_bar_fixture(testdir):
testdir.tmpdir.join('test_foo.py').write('''
def test_a(bar):
assert bar == "something"
'''
result = testdir.runpytest('--foo=something')
def test_foo_option():
pass
| # -*- coding: utf-8 -*-
def test_bar_fixture(testdir):
"""Make sure that pytest accepts our fixture."""
# create a temporary pytest test module
testdir.makepyfile("""
def test_sth(bar):
assert bar == "europython2015"
""")
# run pytest with the following cmd args
result = t... | Implement test for help and cli args | Implement test for help and cli args
| Python | mit | luzfcb/cookiecutter-pytest-plugin,pytest-dev/cookiecutter-pytest-plugin,s0undt3ch/cookiecutter-pytest-plugin | ---
+++
@@ -1,12 +1,35 @@
# -*- coding: utf-8 -*-
def test_bar_fixture(testdir):
- testdir.tmpdir.join('test_foo.py').write('''
-def test_a(bar):
- assert bar == "something"
-'''
- result = testdir.runpytest('--foo=something')
+ """Make sure that pytest accepts our fixture."""
+ # create a tempor... |
9dad4033e4a66208ca00bcb0340f6a2271f1090f | montage_wrapper/mpi.py | montage_wrapper/mpi.py | MPI_COMMAND = 'mpirun -n {n_proc} {executable}'
def set_mpi_command(command):
"""
Set the MPI Command to use.
This should contain {n_proc} to indicate the number of processes, and
{executable} to indicate the name of the executable.
Parameters
----------
command: str
The M... | MPI_COMMAND = 'mpirun -n {n_proc} {executable}'
def set_mpi_command(command):
"""
Set the MPI Command to use.
This should contain {n_proc} to indicate the number of processes, and
{executable} to indicate the name of the executable.
Parameters
----------
command: str
The M... | Fix setting of custom MPI command | Fix setting of custom MPI command | Python | bsd-3-clause | vterron/montage-wrapper,astrofrog/montage-wrapper,astropy/montage-wrapper,astrofrog/montage-wrapper,jat255/montage-wrapper | ---
+++
@@ -23,6 +23,7 @@
>>> set_mpi_command('mpiexec -f mpd.hosts -np {n_proc} {executable}')
"""
+ global MPI_COMMAND
MPI_COMMAND = command
def _get_mpi_command(executable=None, n_proc=None): |
bd97e698d3a2a795f4c38d7e54eae63737ed74a6 | multi_schema/management/commands/syncdb.py | multi_schema/management/commands/syncdb.py | import os.path
from django.core.management.commands import syncdb
from django.db import models, connection, transaction
try:
from south.management.commands import syncdb
except ImportError:
pass
from ...models import Schema, template_schema
class Command(syncdb.Command):
def handle_noargs(self, **option... | import os.path
from django.core.management.commands import syncdb
from django.db import models, connection, transaction
try:
from south.management.commands import syncdb
except ImportError:
pass
from ...models import Schema, template_schema
class Command(syncdb.Command):
def handle_noargs(self, **option... | Allow for comments in the sql file that do not start the line. | Allow for comments in the sql file that do not start the line.
| Python | bsd-3-clause | schinckel/django-boardinghouse,schinckel/django-boardinghouse,schinckel/django-boardinghouse | ---
+++
@@ -14,7 +14,7 @@
def handle_noargs(self, **options):
# Ensure we have the clone_schema() function
clone_schema_file = os.path.join(os.path.abspath(__file__ + '/../../../'), 'sql', 'clone_schema.sql')
- clone_schema_function = " ".join([x.strip() for x in open(clone_schema_file).... |
a09689c570e70c80ad7cadd9702133b3851c63b9 | providers/provider.py | providers/provider.py | import json
import requests
from requests.utils import get_unicode_from_response
from lxml import html as lxml_html
class BaseProvider(object):
# ==== HELPER METHODS ====
def parse_html(self, url, css_selector):
html = self._http_get(url)
document = lxml_html.document_fromstring(html)
r... | import json
import requests
from requests.utils import get_unicode_from_response
from lxml import html as lxml_html
class BaseProvider(object):
# ==== HELPER METHODS ====
def parse_html(self, url, css_selector, timeout=60):
html = self._http_get(url, timeout=timeout)
document = lxml_html.docume... | Increase timeout to 60 sec and make available to external callers. | Increase timeout to 60 sec and make available to external callers.
| Python | mit | EmilStenstrom/nephele | ---
+++
@@ -5,8 +5,8 @@
class BaseProvider(object):
# ==== HELPER METHODS ====
- def parse_html(self, url, css_selector):
- html = self._http_get(url)
+ def parse_html(self, url, css_selector, timeout=60):
+ html = self._http_get(url, timeout=timeout)
document = lxml_html.document... |
cdbcc903c72ba7bf8acb45d69248e62fdc10efcd | rtrss/util.py | rtrss/util.py | import csv
import logging
import os
import datetime
from rtrss import config
from rtrss.models import User
from rtrss.database import session_scope
_logger = logging.getLogger(__name__)
def save_debug_file(filename, contents):
ts_prefix = datetime.datetime.now().strftime('%d-%m-%Y_%H_%M_%S')
filename = "{}_... | import csv
import logging
import os
import datetime
from rtrss import config
from rtrss.models import User
from rtrss.database import session_scope
_logger = logging.getLogger(__name__)
def save_debug_file(filename, contents):
ts_prefix = datetime.datetime.now().strftime('%d-%m-%Y_%H_%M_%S')
filename = "{}... | Add log message at start of user import | Add log message at start of user import
| Python | apache-2.0 | notapresent/rtrss,notapresent/rtrss,notapresent/rtrss,notapresent/rtrss | ---
+++
@@ -2,6 +2,7 @@
import logging
import os
import datetime
+
from rtrss import config
from rtrss.models import User
from rtrss.database import session_scope
@@ -23,6 +24,8 @@
reader = csv.DictReader(csvfile, skipinitialspace=True)
lines = [line for line in reader]
+ _logger.info("Im... |
fe1e6e4af9bf9b85be1046dd9b831e9741aaa677 | src/artgraph/miner.py | src/artgraph/miner.py | import pymw
import pymw.interfaces
import artgraph.plugins.infobox
from artgraph.node import NodeTypes
from artgraph.node import Node
class Miner(object):
nodes = []
relationships = []
master = None
task_queue = []
def __init__(self, debug=False):
mwinterface = pymw.interfaces.Generi... | import pymw
import pymw.interfaces
import artgraph.plugins.infobox
from artgraph.node import NodeTypes
from artgraph.node import Node
class Miner(object):
nodes = []
relationships = []
master = None
task_queue = []
def __init__(self, debug=False):
mwinterface = pymw.interfaces.Generi... | Correct implementation of the while loop | Correct implementation of the while loop | Python | mit | dMaggot/ArtistGraph | ---
+++
@@ -26,6 +26,8 @@
if n.get_predicate() not in self.nodes:
self.mine_internal(n.get_predicate())
+
+ (finished_task, new_relationships) = self.master.get_result()
def mine_internal(self, current_node, level=0,... |
df91557edb813fc4b62b040b54e914f2f9b5237e | lpthw/ex30.py | lpthw/ex30.py | people = 30
cars = 40
buses = 55
if cars > people:
print "We should take the cars."
elif cars < people:
print "We should not take the cars."
else:
print "We can't decide."
if buses > cars:
print "That's too many buses."
elif buses < cars:
print "Maybe we could take the buses."
else:
print "We... | people = 30
cars = 40
buses = 55
if cars > people:
print "We should take the cars."
elif cars < people:
print "We should not take the cars."
else:
print "We can't decide."
if buses > cars:
print "That's too many buses."
elif buses < cars:
print "Maybe we could take the buses."
else:
print "We... | Fix on teeny tiny little typo... Also remember to write commit messages in the present tense. | Fix on teeny tiny little typo... Also remember to write commit messages in the present tense.
| Python | mit | jaredmanning/learning,jaredmanning/learning | ---
+++
@@ -25,7 +25,7 @@
# Study Drills
if (buses > cars and cars > people):
- print "The buses out numbers us... DECEPTICONS!!"
+ print "The buses out number us... DECEPTICONS!!"
elif (buses > cars and cars < people):
print "This line won't print... just trust me. *peers through console*"
else: |
a229e1737542a5011e70c3fa63c360638e96e754 | lettuce_webdriver/css_selector_steps.py | lettuce_webdriver/css_selector_steps.py | from lettuce import step
from lettuce import world
from lettuce_webdriver.util import assert_true
from lettuce_webdriver.util import assert_false
import logging
log = logging.getLogger(__name__)
def wait_for_elem(browser, xpath, timeout=15):
start = time.time()
elems = []
while time.time() - start < time... | import time
from lettuce import step
from lettuce import world
from lettuce_webdriver.util import assert_true
from lettuce_webdriver.util import assert_false
import logging
log = logging.getLogger(__name__)
def wait_for_elem(browser, sel, timeout=15):
start = time.time()
elems = []
while time.time() - s... | Make the step actually do something. | Make the step actually do something.
| Python | mit | koterpillar/aloe_webdriver,aloetesting/aloe_webdriver,macndesign/lettuce_webdriver,ponsfrilus/lettuce_webdriver,aloetesting/aloe_webdriver,macndesign/lettuce_webdriver,infoxchange/aloe_webdriver,bbangert/lettuce_webdriver,aloetesting/aloe_webdriver,koterpillar/aloe_webdriver,infoxchange/lettuce_webdriver,infoxchange/al... | ---
+++
@@ -1,3 +1,5 @@
+import time
+
from lettuce import step
from lettuce import world
@@ -7,11 +9,11 @@
import logging
log = logging.getLogger(__name__)
-def wait_for_elem(browser, xpath, timeout=15):
+def wait_for_elem(browser, sel, timeout=15):
start = time.time()
elems = []
while time.ti... |
6926ddbb9cdbf05808339412cee5106e581f66cb | tests/import_wordpress_and_build_workflow.py | tests/import_wordpress_and_build_workflow.py | # -*- coding: utf-8 -*-
"""
Script to test the import workflow.
It will remove an existing Nikola installation and then install from the
package directory.
After that it will do create a new site with the import_wordpress
command and use that newly created site to make a build.
"""
from __future__ import unicode_liter... | # -*- coding: utf-8 -*-
"""
Script to test the import workflow.
It will remove an existing Nikola installation and then install from the
package directory.
After that it will do create a new site with the import_wordpress
command and use that newly created site to make a build.
"""
from __future__ import unicode_liter... | Use the more or less new options for importing | Use the more or less new options for importing
| Python | mit | damianavila/nikola,xuhdev/nikola,getnikola/nikola,berezovskyi/nikola,TyberiusPrime/nikola,kotnik/nikola,atiro/nikola,servalproject/nikola,gwax/nikola,schettino72/nikola,kotnik/nikola,lucacerone/nikola,okin/nikola,s2hc-johan/nikola,andredias/nikola,masayuko/nikola,x1101/nikola,s2hc-johan/nikola,Proteus-tech/nikola,techd... | ---
+++
@@ -31,7 +31,8 @@
os.system('nikola')
import_file = os.path.join(test_directory, 'wordpress_export_example.xml')
os.system(
- 'nikola import_wordpress -f %s -o %s' % (import_file, import_directory))
+ 'nikola import_wordpress -o {folder} {file}'.format(file=import_file,
+ ... |
48394c55599968c456f1f58c0fcdf58e1750f293 | amplpy/tests/TestBase.py | amplpy/tests/TestBase.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, absolute_import, division
from builtins import map, range, object, zip, sorted
from .context import amplpy
import unittest
import tempfile
import shutil
import os
class TestBase(unittest.TestCase):
def setUp(self):
self.... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, absolute_import, division
from builtins import map, range, object, zip, sorted
from .context import amplpy
import unittest
import tempfile
import shutil
import os
# For MSYS2, MINGW, etc., run with:
# $ REAL_ROOT=`cygpath -w /` pyth... | Add workaround for tests on MSYS2 and MINGW | Add workaround for tests on MSYS2 and MINGW
| Python | bsd-3-clause | ampl/amplpy,ampl/amplpy,ampl/amplpy | ---
+++
@@ -10,19 +10,33 @@
import os
+# For MSYS2, MINGW, etc., run with:
+# $ REAL_ROOT=`cygpath -w /` python -m amplpy.tests
+REAL_ROOT = os.environ.get('REAL_ROOT', None)
+
+
class TestBase(unittest.TestCase):
def setUp(self):
self.ampl = amplpy.AMPL()
self.dirpath = tempfile.mkdtemp(... |
b121b98516beae23b5517aea1810a6eeed7a4fff | fedoracommunity/mokshaapps/packages/controllers/overview.py | fedoracommunity/mokshaapps/packages/controllers/overview.py | from moksha.lib.base import Controller
from moksha.lib.helpers import Category, MokshaApp, Not, not_anonymous, MokshaWidget
from moksha.api.widgets.containers import DashboardContainer
from moksha.api.widgets import ContextAwareWidget
from tg import expose, tmpl_context, require, request
from bugs import BugsControll... | from moksha.lib.base import Controller
from moksha.lib.helpers import Category, MokshaApp, Not, not_anonymous, MokshaWidget
from moksha.api.widgets.containers import DashboardContainer
from moksha.api.widgets import ContextAwareWidget
from tg import expose, tmpl_context, require, request
from bugs import BugsControll... | Fix the use of the moksha.templates.widget template, in one place. This needs to be fixed in many places | Fix the use of the moksha.templates.widget template, in one place. This needs to be fixed in many places
| Python | agpl-3.0 | fedora-infra/fedora-packages,fedora-infra/fedora-packages,fedora-infra/fedora-packages,fedora-infra/fedora-packages,Fale/fedora-packages,Fale/fedora-packages,Fale/fedora-packages | ---
+++
@@ -35,8 +35,9 @@
@expose('mako:moksha.templates.widget')
def index(self, package):
tmpl_context.widget = overview_dashboard
- return {'package': package}
+ return dict(package=package, options={})
@expose('mako:moksha.templates.widget')
def overview(self, package)... |
43afda1fa0ae2d0011d6b87b5c05e3eb1fe13a21 | viewer_examples/viewers/collection_viewer.py | viewer_examples/viewers/collection_viewer.py | """
=====================
CollectionViewer demo
=====================
Demo of CollectionViewer for viewing collections of images. This demo uses
successively darker versions of the same image to fake an image collection.
You can scroll through images with the slider, or you can interact with the
viewer using your key... | """
=====================
CollectionViewer demo
=====================
Demo of CollectionViewer for viewing collections of images. This demo uses
successively darker versions of the same image to fake an image collection.
You can scroll through images with the slider, or you can interact with the
viewer using your key... | Use gaussian pyramid function for collection viewer example | Use gaussian pyramid function for collection viewer example
| Python | bsd-3-clause | rjeli/scikit-image,juliusbierk/scikit-image,vighneshbirodkar/scikit-image,Midafi/scikit-image,newville/scikit-image,SamHames/scikit-image,bennlich/scikit-image,vighneshbirodkar/scikit-image,ofgulban/scikit-image,blink1073/scikit-image,GaZ3ll3/scikit-image,keflavich/scikit-image,michaelpacer/scikit-image,chintak/scikit-... | ---
+++
@@ -21,9 +21,11 @@
import numpy as np
from skimage import data
from skimage.viewer import CollectionViewer
+from skimage.transform import build_gaussian_pyramid
+
img = data.lena()
-img_collection = [np.uint8(img * 0.9**i) for i in range(20)]
+img_collection = tuple(build_gaussian_pyramid(img))
view ... |
710c77b2805058364e326d26c9e0c7cfcfed6453 | repugeng/Compat3k.py | repugeng/Compat3k.py | from repugeng.StaticClass import StaticClass
import sys
class Compat3k(StaticClass):
@classmethod
def str_to_bytes(cls, s):
"""Convert a string of either width to a byte string."""
try:
try:
return bytes(s)
except NameError:
ret... | from repugeng.StaticClass import StaticClass
import sys
class Compat3k(StaticClass):
@classmethod
def str_to_bytes(cls, s):
"""Convert a string of either width to a byte string."""
try:
try:
return bytes(s)
except NameError:
ret... | Fix yet another 3k issue (stderr not flushing automatically). | Fix yet another 3k issue (stderr not flushing automatically).
Signed-off-by: Thomas Hori <7133b3a0da8e60bd3295f2c8559ef184054a68ed@liddicott.com>
| Python | mpl-2.0 | thomas-hori/Repuge-NG | ---
+++
@@ -19,4 +19,5 @@
def prompt_user(cls, s="", file=None):
"""Substitute of py2k's raw_input()."""
(file or sys.stderr).write(s)
+ (file or sys.stderr).flush()
return sys.stdin.readline().rstrip("\r\n") |
c0ff6cbf293bca3f0757a62e05a14c56dbdf12a4 | installscripts/jazz-terraform-unix-noinstances/scripts/health_check.py | installscripts/jazz-terraform-unix-noinstances/scripts/health_check.py | import boto3
import sys
import time
def health_check_tg(client, tg_arn, max_tries):
if max_tries == 1:
return False
else:
max_tries -= 1
try:
response = client.describe_target_health(TargetGroupArn=str(tg_arn))
if response['TargetHealthDescriptio... | import boto3
import sys
import time
def health_check_tg(client, tg_arn, max_tries):
if max_tries == 1:
return False
else:
max_tries -= 1
try:
response = client.describe_target_health(TargetGroupArn=str(tg_arn))
if response['TargetHealthDescriptions'][0]['TargetHealth']['Sta... | Fix travis issue for v1.13.1 release | Fix travis issue for v1.13.1 release
| Python | apache-2.0 | tmobile/jazz-installer,tmobile/jazz-installer,tmobile/jazz-installer,tmobile/jazz-installer | ---
+++
@@ -4,21 +4,21 @@
def health_check_tg(client, tg_arn, max_tries):
- if max_tries == 1:
- return False
+ if max_tries == 1:
+ return False
+ else:
+ max_tries -= 1
+ try:
+ response = client.describe_target_health(TargetGroupArn=str(tg_arn))
+ if resp... |
8ad795f86e16209007537cbf47a3466733653e2d | snippets/__main__.py | snippets/__main__.py | import argparse
import sys
from .generator import Generator
from .repository import Repository
def run(args=sys.argv[1:]):
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--source', default='snippets')
parser.add_argument('-o', '--output', default='output')
parser.add_argument('-t', '--... | import argparse
import sys
from .generator import Generator
from .repository import Repository
def run(args=sys.argv[1:]):
parser = argparse.ArgumentParser()
parser.add_argument('-r', '--repository', default='snippets')
parser.add_argument('-o', '--output', default='output')
parser.add_argument('-t',... | Fix cli argument name for repository path | Fix cli argument name for repository path
| Python | isc | trilan/snippets,trilan/snippets | ---
+++
@@ -7,13 +7,13 @@
def run(args=sys.argv[1:]):
parser = argparse.ArgumentParser()
- parser.add_argument('-s', '--source', default='snippets')
+ parser.add_argument('-r', '--repository', default='snippets')
parser.add_argument('-o', '--output', default='output')
parser.add_argument('-t',... |
cd38101f097edc60312f0c083385968ed40fd54a | src/control.py | src/control.py | #!/usr/bin/env python
import rospy
from gazebo_msgs.msg import ModelStates
from geometry_msgs.msg import Twist
from constants import DELTA_T, STEPS
from controller import create_controller
from plotter import Plotter
def get_pose(message):
global current_pose
current_pose = message.pose[2]
def compute_cont... | #!/usr/bin/env python
import rospy
from gazebo_msgs.msg import ModelStates
from geometry_msgs.msg import Twist
from constants import DELTA_T, STEPS
from controller import create_controller
from plotter import Plotter
def get_pose(message):
global current_pose, current_twist
current_pose = message.pose[2]
... | Store current twist in a global variable | Store current twist in a global variable
| Python | mit | bit0001/trajectory_tracking,bit0001/trajectory_tracking | ---
+++
@@ -9,8 +9,9 @@
def get_pose(message):
- global current_pose
+ global current_pose, current_twist
current_pose = message.pose[2]
+ current_twist = message.twist[2]
def compute_control_actions():
@@ -29,10 +30,11 @@
if __name__ == '__main__':
rospy.init_node('control')
curren... |
7d03a6bfa32d2bf20a95769b2937e098972285af | src/scs_mfr/test/opc_test.py | src/scs_mfr/test/opc_test.py | """
Created on 18 May 2017
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
"""
import sys
from scs_dfe.particulate.opc_n2 import OPCN2
from scs_host.bus.i2c import I2C
from scs_host.sys.host import Host
from scs_mfr.test.test import Test
# --------------------------------------------------------------... | """
Created on 18 May 2017
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
"""
import sys
from scs_dfe.particulate.opc_n2 import OPCN2
from scs_host.bus.i2c import I2C
from scs_host.sys.host import Host
from scs_mfr.test.test import Test
# --------------------------------------------------------------... | Put SPI slave configurations on Host. | Put SPI slave configurations on Host.
| Python | mit | south-coast-science/scs_mfr,south-coast-science/scs_mfr | ---
+++
@@ -39,7 +39,7 @@
I2C.open(Host.I2C_SENSORS)
# resources...
- opc = OPCN2(Host.OPC_SPI_BUS, Host.OPC_SPI_DEVICE)
+ opc = OPCN2(Host.opc_spi_bus(), Host.opc_spi_device())
opc.power_on()
opc.operations_on() |
6b819174557a1dffbcb397dc1d6e2a3f7e01a12b | milestones/migrations/0002_data__seed_relationship_types.py | milestones/migrations/0002_data__seed_relationship_types.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from milestones.data import fetch_milestone_relationship_types
def seed_relationship_types(apps, schema_editor):
"""Seed the relationship types."""
MilestoneRelationshipType = apps.get_model("milestones"... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from milestones.data import fetch_milestone_relationship_types
def seed_relationship_types(apps, schema_editor):
"""Seed the relationship types."""
MilestoneRelationshipType = apps.get_model("milestones"... | Remove uses of using() from migrations | Remove uses of using() from migrations
This hardcoded the db_alias fetched from schema_editor and forces django
to try and migrate any second database you use, rather than routing to
the default database. In testing a build from scratch, these do not
appear needed.
Using using() prevents us from using multiple datab... | Python | agpl-3.0 | edx/edx-milestones | ---
+++
@@ -9,9 +9,8 @@
def seed_relationship_types(apps, schema_editor):
"""Seed the relationship types."""
MilestoneRelationshipType = apps.get_model("milestones", "MilestoneRelationshipType")
- db_alias = schema_editor.connection.alias
for name in fetch_milestone_relationship_types().values():
-... |
6bdb91aefc6acb9b0065c7edae19887778dedb22 | .ci/package-version.py | .ci/package-version.py | #!/usr/bin/env python3
import os.path
import sys
def main():
setup_py = os.path.join(os.path.dirname(os.path.dirname(__file__)),
'setup.py')
with open(setup_py, 'r') as f:
for line in f:
if line.startswith('VERSION ='):
_, _, version = line.pa... | #!/usr/bin/env python3
import os.path
import sys
def main():
version_file = os.path.join(
os.path.dirname(os.path.dirname(__file__)), 'uvloop', '__init__.py')
with open(version_file, 'r') as f:
for line in f:
if line.startswith('__version__ ='):
_, _, version = l... | Fix ci / package_version.py script to support __version__ | Fix ci / package_version.py script to support __version__
| Python | apache-2.0 | 1st1/uvloop,MagicStack/uvloop,MagicStack/uvloop | ---
+++
@@ -6,17 +6,18 @@
def main():
- setup_py = os.path.join(os.path.dirname(os.path.dirname(__file__)),
- 'setup.py')
+ version_file = os.path.join(
+ os.path.dirname(os.path.dirname(__file__)), 'uvloop', '__init__.py')
- with open(setup_py, 'r') as f:
+ with o... |
261cb5aecc52d07b10d826e8b22d17817d1c3529 | web/backend/backend_django/apps/capacity/management/commands/importpath.py | web/backend/backend_django/apps/capacity/management/commands/importpath.py | from __future__ import unicode_literals
from optparse import make_option
import os
from csv import reader
from codecs import BOM_UTF8
import pickle
from django.utils.six import string_types, PY3
from django.core.management.base import BaseCommand, CommandError
from ...models import Path
class Command(BaseCommand):
... | from __future__ import unicode_literals
from optparse import make_option
import os
from csv import reader
from codecs import BOM_UTF8
import pickle
from django.utils.six import string_types, PY3
from django.core.management.base import BaseCommand, CommandError
from ...models import Path
class Command(BaseCommand):
... | Update import path method to reflect behaviour | Update import path method to reflect behaviour
| Python | apache-2.0 | tOverney/ADA-Project,tOverney/ADA-Project,tOverney/ADA-Project | ---
+++
@@ -26,10 +26,12 @@
trips = pickle.load(open(i, "rb"))
print(len(trips))
-
+ i = 0
for k, path in trips.items():
trip_id = k[0]
stop_id = k[1]
+
+ if i%1000==0: print(i)
try:
_, created = Path.objects.get_... |
24d7f9f05e4d597358b62a50d2d0f5fad6a61c63 | package_name/__meta__.py | package_name/__meta__.py | name = "package-name" # See https://www.python.org/dev/peps/pep-0008/
path = name.lower().replace("-", "_").replace(" ", "_")
version = "0.1.dev0" # https://python.org/dev/peps/pep-0440 https://semver.org
author = "Author Name"
author_email = ""
description = "" # One-liner
url = "" # your project homepage
license ... | # `name` is the name of the package as used for `pip install package`
name = "package-name"
# `path` is the name of the package for `import package`
path = name.lower().replace("-", "_").replace(" ", "_")
# Your version number should follow https://python.org/dev/peps/pep-0440 and
# https://semver.org
version = "0.1.de... | Clarify comments on what name and path are | DOC: Clarify comments on what name and path are
| Python | mit | scottclowe/python-continuous-integration,scottclowe/python-ci,scottclowe/python-ci,scottclowe/python-continuous-integration | ---
+++
@@ -1,6 +1,10 @@
-name = "package-name" # See https://www.python.org/dev/peps/pep-0008/
+# `name` is the name of the package as used for `pip install package`
+name = "package-name"
+# `path` is the name of the package for `import package`
path = name.lower().replace("-", "_").replace(" ", "_")
-version = "... |
1869b79d49419799cecf1f5e19eb0aa3987e215b | tests/test_vector2_scalar_multiplication.py | tests/test_vector2_scalar_multiplication.py | import pytest # type: ignore
from ppb_vector import Vector2
@pytest.mark.parametrize("x, y, expected", [
(Vector2(6, 1), 0, Vector2(0, 0)),
(Vector2(6, 1), 2, Vector2(12, 2)),
(Vector2(0, 0), 3, Vector2(0, 0)),
(Vector2(-1.5, 2.4), -2, Vector2(3.0, -4.8)),
(Vector2(1, 2), 0.1, Vector2(0.1, 0.2))
... | import pytest # type: ignore
from hypothesis import given
from hypothesis.strategies import floats
from utils import vectors
from ppb_vector import Vector2
@pytest.mark.parametrize("x, y, expected", [
(Vector2(6, 1), 0, Vector2(0, 0)),
(Vector2(6, 1), 2, Vector2(12, 2)),
(Vector2(0, 0), 3, Vector2(0, 0))... | Add a test of the associativity of scalar multiplication | Add a test of the associativity of scalar multiplication
| Python | artistic-2.0 | ppb/ppb-vector,ppb/ppb-vector | ---
+++
@@ -1,4 +1,7 @@
import pytest # type: ignore
+from hypothesis import given
+from hypothesis.strategies import floats
+from utils import vectors
from ppb_vector import Vector2
@@ -11,3 +14,14 @@
])
def test_scalar_multiplication(x, y, expected):
assert x * y == expected
+
+
+@given(
+ x=floats... |
6b14c9e5683d41ca9d8b9138c25af7526c83d1e4 | test/integration/ggrc/converters/test_import_delete.py | test/integration/ggrc/converters/test_import_delete.py | # Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
from ggrc.converters import errors
from integration.ggrc import TestCase
class TestBasicCsvImport(TestCase):
def setUp(self):
TestCase.setUp(self)
self.client.get("/login")
def test_policy_ba... | # Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
from integration.ggrc import TestCase
class TestBasicCsvImport(TestCase):
def setUp(self):
TestCase.setUp(self)
self.client.get("/login")
def test_policy_basic_import(self):
filename = "c... | Optimize basic delete import tests | Optimize basic delete import tests
The dry-run check is now automatically performed on each import and we
do not need to duplicate the work in the delete test.
| Python | apache-2.0 | selahssea/ggrc-core,selahssea/ggrc-core,AleksNeStu/ggrc-core,plamut/ggrc-core,selahssea/ggrc-core,plamut/ggrc-core,AleksNeStu/ggrc-core,VinnieJohns/ggrc-core,VinnieJohns/ggrc-core,VinnieJohns/ggrc-core,AleksNeStu/ggrc-core,VinnieJohns/ggrc-core,plamut/ggrc-core,plamut/ggrc-core,AleksNeStu/ggrc-core,selahssea/ggrc-core | ---
+++
@@ -1,7 +1,6 @@
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
-from ggrc.converters import errors
from integration.ggrc import TestCase
@@ -16,9 +15,7 @@
self.import_file(filename)
filename = "ca_deletion.csv"
- response... |
e4079d7cdeb59a3cac129813b7bb14a6639ea9db | plugins/Webcam_plugin.py | plugins/Webcam_plugin.py | info = {
'id': 'webcam',
'name': 'Webcam',
'description': 'Generic webcam driver',
'module name': 'Webcam',
'class name': 'Webcam',
'author': 'Philip Chimento',
'copyright year': '2011',
}
| info = {
'id': 'webcam',
'name': 'OpenCV',
'description': 'Video camera interfacing through OpenCV',
'module name': 'Webcam',
'class name': 'Webcam',
'author': 'Philip Chimento',
'copyright year': '2011',
}
| Rename 'webcam' plugin to OpenCV | Rename 'webcam' plugin to OpenCV
| Python | mit | ptomato/Beams | ---
+++
@@ -1,7 +1,7 @@
info = {
'id': 'webcam',
- 'name': 'Webcam',
- 'description': 'Generic webcam driver',
+ 'name': 'OpenCV',
+ 'description': 'Video camera interfacing through OpenCV',
'module name': 'Webcam',
'class name': 'Webcam',
'author': 'Philip Chimento', |
6fb30db07457fb231827cfa4c8215f8ff107cb74 | tests/testapp/tests/utils.py | tests/testapp/tests/utils.py | # coding: utf-8
import datetime
from django.core.management import CommandError
from django.core.management.color import no_style
from django.core.management.sql import sql_delete, sql_all
from django.db import connections, transaction, DEFAULT_DB_ALIAS
import elephantblog.models
def mock_datetime():
class MockD... | # coding: utf-8
import datetime
from django.core.management import CommandError
from django.core.management.color import no_style
from django.core.management.sql import sql_delete, sql_all
from django.db import connections, transaction, DEFAULT_DB_ALIAS
import elephantblog.models
def mock_datetime():
class MockD... | Fix an old-style except: statement | Fix an old-style except: statement
| Python | bsd-3-clause | feincms/feincms-elephantblog,sbaechler/feincms-elephantblog,michaelkuty/feincms-elephantblog,joshuajonah/feincms-elephantblog,sbaechler/feincms-elephantblog,joshuajonah/feincms-elephantblog,matthiask/feincms-elephantblog,michaelkuty/feincms-elephantblog,sbaechler/feincms-elephantblog,joshuajonah/feincms-elephantblog,mi... | ---
+++
@@ -33,7 +33,7 @@
cursor = connection.cursor()
for sql in sql_list:
cursor.execute(sql)
- except Exception, e:
+ except Exception as e:
transaction.rollback_unless_managed()
raise CommandError("Error: database couldn't be reset: %s" % e)
else: |
df6642256806e0a501e83c06e64b35f187efaf60 | rally/benchmark/scenarios/authenticate/authenticate.py | rally/benchmark/scenarios/authenticate/authenticate.py | # Copyright 2014 Red Hat, Inc. <http://www.redhat.com>
#
# 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 b... | # Copyright 2014 Red Hat, Inc. <http://www.redhat.com>
#
# 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 b... | Fix for Authentication scenario to correctly use self.clients | Fix for Authentication scenario to correctly use self.clients
Scenario has recently been refactored, self.clients in Scenario
now takes the name of the CLI client. During the refactoring,
the Authenticate scenario was not correctly updated, which
causes the authentication scenario to fail. This patch fixes
that.
Chan... | Python | apache-2.0 | pandeyop/rally,go-bears/rally,vefimova/rally,aplanas/rally,group-policy/rally,amit0701/rally,shdowofdeath/rally,ytsarev/rally,go-bears/rally,vefimova/rally,group-policy/rally,shdowofdeath/rally,openstack/rally,gluke77/rally,ytsarev/rally,redhat-openstack/rally,varunarya10/rally,amit0701/rally,gluke77/rally,vganapath/ra... | ---
+++
@@ -13,7 +13,6 @@
# under the License.
from rally.benchmark.scenarios import base
-from rally import osclients
class Authenticate(base.Scenario):
@@ -21,6 +20,4 @@
types of clients like Keystone.
"""
def keystone(self, **kwargs):
- keystone_endpoint = self.clients("endpoint")... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.