commit stringlengths 40 40 | old_file stringlengths 4 236 | new_file stringlengths 4 236 | old_contents stringlengths 1 3.26k | new_contents stringlengths 16 4.43k | subject stringlengths 16 624 | message stringlengths 17 3.29k | lang stringclasses 5
values | license stringclasses 13
values | repos stringlengths 5 91.5k |
|---|---|---|---|---|---|---|---|---|---|
f9c51c592483ab08417d4df33898d32f7700ffe9 | sal/management/commands/update_admin_user.py | sal/management/commands/update_admin_user.py | '''
Creates an admin user if there aren't any existing superusers
'''
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User
from optparse import make_option
class Command(BaseCommand):
help = 'Creates/Updates an Admin user'
def add_arguments(self, pars... | """Creates an admin user if there aren't any existing superusers."""
from optparse import make_option
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
help = 'Creates/Updates an Admin user'
def add_arguments(self, par... | Fix exception handling in management command. Clean up. | Fix exception handling in management command. Clean up.
| Python | apache-2.0 | salopensource/sal,sheagcraig/sal,sheagcraig/sal,salopensource/sal,salopensource/sal,sheagcraig/sal,sheagcraig/sal,salopensource/sal |
a5f60d664e7758b113abc31b405657952dd5eccd | tests/conftest.py | tests/conftest.py | import os
import pytest
from pywatson.watson import Watson
@pytest.fixture
def config():
"""Get Watson configuration from the environment
:return: dict with keys 'url', 'username', and 'password'
"""
try:
return {
'url': os.environ['WATSON_URL'],
'username': os.environ... | import json
import os
import pytest
from pywatson.watson import Watson
@pytest.fixture
def config():
"""Get Watson configuration from the environment
:return: dict with keys 'url', 'username', and 'password'
"""
try:
return {
'url': os.environ['WATSON_URL'],
'username'... | Implement test data JSON loader | Implement test data JSON loader
| Python | mit | sherlocke/pywatson |
904db705daf24d68fcc9ac6010b55b93c7dc4544 | txircd/modules/core/accounts.py | txircd/modules/core/accounts.py | from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from txircd.utils import ircLower
from zope.interface import implements
class Accounts(ModuleData):
implements(IPlugin, IModuleData)
name = "Accounts"
core = True
def actions(self):
return [ ("usercansetmetadata", ... | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IModuleData, ModuleData
from txircd.utils import ircLower
from zope.interface import implements
# Numerics and names are taken from the IRCv3.1 SASL specification at http://ircv3.net/specs/extensions/sasl-3.1... | Add automatic sending of 900/901 numerics for account status | Add automatic sending of 900/901 numerics for account status
| Python | bsd-3-clause | Heufneutje/txircd,ElementalAlchemist/txircd |
f3c1e5bdf25b46e96a77221ace7438eb3b55cb05 | bluebottle/common/management/commands/makemessages.py | bluebottle/common/management/commands/makemessages.py | import json
import codecs
import tempfile
from django.core.management.commands.makemessages import Command as BaseCommand
class Command(BaseCommand):
""" Extend the makemessages to include some of the fixtures """
fixtures = [
('bb_projects', 'project_data.json'),
('bb_tasks', 'skills.json'),... | import json
import codecs
import tempfile
from django.core.management.commands.makemessages import Command as BaseCommand
class Command(BaseCommand):
""" Extend the makemessages to include some of the fixtures """
fixtures = [
('bb_projects', 'project_data.json'),
('bb_tasks', 'skills.json'),... | Make loop a little more readable | Make loop a little more readable
| Python | bsd-3-clause | onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle |
ecc56eec0ebee4a93d5052280ae5d8c649e1e6da | tests/test_api.py | tests/test_api.py | from nose.tools import eq_
import mock
from lcp import api
@mock.patch('lcp.api.requests.request')
def _assert_calls_requests_with_url(original_url, expected_url, request_mock):
api.Client('BASE_URL').request('METHOD', original_url)
expected_headers = {'Content-Type': 'application/json'}
eq_(request_mock... | from nose.tools import eq_
import mock
from lcp import api
class TestApiClient(object):
def setup(self):
self.client = api.Client('BASE_URL')
def test_request_does_not_alter_absolute_urls(self):
for absolute_url in [
'http://www.points.com',
'https://www.point... | Refactor api test to setup test client in setup +review PLAT-127 DCORE-1109 | Refactor api test to setup test client in setup +review PLAT-127 DCORE-1109
| Python | bsd-3-clause | bradsokol/PyLCP,Points/PyLCP,bradsokol/PyLCP,Points/PyLCP |
7bdfb1ef77d23bc868434e8d74d6184dd68c0a6e | tests/test_api.py | tests/test_api.py | # coding: utf-8
"""
Test the backend API
Written so that after creating a new backend, you can immediately see which
parts are missing!
"""
from unittest import TestCase
import inspect
from pycurlbrowser.backend import *
from pycurlbrowser import Browser
def is_http_backend_derived(t):
if t is HttpBackend:
... | # coding: utf-8
"""
Test the backend API
Written so that after creating a new backend, you can immediately see which
parts are missing!
"""
from unittest import TestCase
import inspect
from pycurlbrowser.backend import *
from pycurlbrowser import Browser
def is_http_backend_derived(t):
if t is HttpBackend:
... | Improve API test by only comparing args and varargs. | Improve API test by only comparing args and varargs.
| Python | agpl-3.0 | ahri/pycurlbrowser |
cfaaf421bb9627f1741a9ef4074517fd5daaec86 | wsgi/setup.py | wsgi/setup.py |
import subprocess
import sys
import setup_util
import os
def start(args):
subprocess.Popen("gunicorn hello:app -b 0.0.0.0:8080 -w " + str((args.max_threads * 2)) + " --log-level=critical", shell=True, cwd="wsgi")
return 0
def stop():
p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE)
out, err = p.com... |
import subprocess
import sys
import setup_util
import os
def start(args):
subprocess.Popen('gunicorn hello:app --worker-class="egg:meinheld#gunicorn_worker" -b 0.0.0.0:8080 -w '
+ str((args.max_threads * 2)) + " --log-level=critical", shell=True, cwd="wsgi")
return 0
def stop():
p = subproces... | Use meinheld worker (same as other Python Frameworks) | wsgi: Use meinheld worker (same as other Python Frameworks)
| Python | bsd-3-clause | torhve/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,denkab/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,grob/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,jetty-project/FrameworkBenchmark... |
1d4777f810388ee87cceb01c2b53367723fb3a71 | PyFBA/cmd/__init__.py | PyFBA/cmd/__init__.py | from .citation import cite_me_please
from .fluxes import measure_fluxes
from .gapfill_from_roles import gapfill_from_roles
from .assigned_functions_to_reactions import to_reactions
from .fba_from_reactions import run_the_fba
from .gapfill_from_reactions_multiple_conditions import gapfill_multiple_media
from .media impo... | from .citation import cite_me_please
from .fluxes import measure_fluxes
from .gapfill_from_roles import gapfill_from_roles
from .assigned_functions_to_reactions import to_reactions
from .fba_from_reactions import run_the_fba
from .gapfill_from_reactions_multiple_conditions import gapfill_multiple_media
from .media impo... | Add a function to retrieve roles from reactions | Add a function to retrieve roles from reactions
| Python | mit | linsalrob/PyFBA |
6fd7f3cb01f621d2ea79e15188f8000c7b6fa361 | tools/add_feed.py | tools/add_feed.py | import os
from urllib.parse import urlencode, quote
from autobit import Client
def add_rarbg_feed(client, name, directory, filter_kwargs):
url = 'http://localhost:5555/{}?{}'.format(
quote(name),
urlencode(filter_kwargs)
)
return client.add_feed(name, url, directory)
def main():
cl... | import os
from autobit import Client
def main():
client = Client('http://localhost:8081/gui/', auth=('admin', '20133'))
client.get_torrents()
name = input('name> ')
directory = input('directory> ')
os.makedirs(directory, exist_ok=True)
client.add_feed(
name,
input('url> '),... | Remove code specific to my system | Remove code specific to my system
| Python | mit | Mause/autobit |
894203d67e88e8bac8ec4f8948d940789387b648 | tests/data/questions.py | tests/data/questions.py | QUESTIONS = [
{
'questionText': 'What is the Labour Code?'
},
{
'questionText': 'When can a union start a strike?'
}
]
| QUESTIONS = [
{
'questionText': 'What is the Labour Code?'
},
{
'questionText': 'When can a union start a strike?',
'items': 0,
'evidenceRequest': {
'items': 0,
'profile': ''
},
'answerAssertion': '',
'category': '',
'co... | Add all blank parameters to sample question | Add all blank parameters to sample question
| Python | mit | sherlocke/pywatson |
111d0bd356c18d0c028c73cd8c84c9d3e3ae591c | astropy/io/misc/asdf/tags/tests/helpers.py | astropy/io/misc/asdf/tags/tests/helpers.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# -*- coding: utf-8 -*-
import os
import urllib.parse
import yaml
import numpy as np
def run_schema_example_test(organization, standard, name, version, check_func=None):
import asdf
from asdf.tests import helpers
from asdf.types import for... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# -*- coding: utf-8 -*-
import os
import urllib.parse
import urllib.request
import yaml
import numpy as np
def run_schema_example_test(organization, standard, name, version, check_func=None):
import asdf
from asdf.tests import helpers
from... | Fix ASDF tag test helper to load schemas correctly | Fix ASDF tag test helper to load schemas correctly
| Python | bsd-3-clause | pllim/astropy,astropy/astropy,lpsinger/astropy,larrybradley/astropy,StuartLittlefair/astropy,mhvk/astropy,pllim/astropy,MSeifert04/astropy,saimn/astropy,dhomeier/astropy,lpsinger/astropy,pllim/astropy,stargaser/astropy,larrybradley/astropy,larrybradley/astropy,bsipocz/astropy,StuartLittlefair/astropy,astropy/astropy,dh... |
e2f1787601e7c05c9c5ab2efe26b6d1cb90b2ccb | saleor/account/migrations/0040_auto_20200415_0443.py | saleor/account/migrations/0040_auto_20200415_0443.py | # Generated by Django 3.0.5 on 2020-04-15 09:43
from django.db import migrations
def change_extension_permission_to_plugin_permission(apps, schema_editor):
permission = apps.get_model("auth", "Permission")
users = apps.get_model("account", "User")
plugin_permission = permission.objects.filter(
c... | # Generated by Django 3.0.5 on 2020-04-15 09:43
from django.db import migrations
def change_extension_permission_to_plugin_permission(apps, schema_editor):
permission = apps.get_model("auth", "Permission")
users = apps.get_model("account", "User")
service_account = apps.get_model("account", "ServiceAccou... | Fix plugin permission data migration | Fix plugin permission data migration
| Python | bsd-3-clause | mociepka/saleor,mociepka/saleor,mociepka/saleor |
03e0e11491c64ae546134eb6c963a31958fe6d6d | address_book/address_book.py | address_book/address_book.py | from person import Person
__all__ = ['AddressBook']
class AddressBook(object):
def __init__(self):
self.persons = []
def add_person(self, person):
self.persons.append(person)
def __contains__(self, item):
if isinstance(item, Person):
return item in self.persons
... | from person import Person
__all__ = ['AddressBook']
class AddressBook(object):
def __init__(self):
self.persons = []
self.groups = []
def add_person(self, person):
self.persons.append(person)
def add_group(self, group):
self.groups.append(group)
def __contains__(se... | Add `add_group` method to `AddressBook` class - to make it possible to add groups to the address book | Add `add_group` method to `AddressBook` class - to make it possible to add groups to the address book
| Python | mit | dizpers/python-address-book-assignment |
72466cb328fb56bfe28f5c3a1f8fca082db24319 | typer/__init__.py | typer/__init__.py | """Typer, build great CLIs. Easy to code. Based on Python type hints."""
__version__ = "0.0.4"
from click.exceptions import ( # noqa
Abort,
BadArgumentUsage,
BadOptionUsage,
BadParameter,
ClickException,
FileError,
MissingParameter,
NoSuchOption,
UsageError,
)
from click.termui im... | """Typer, build great CLIs. Easy to code. Based on Python type hints."""
__version__ = "0.0.4"
from click.exceptions import Abort, Exit # noqa
from click.termui import ( # noqa
clear,
confirm,
echo_via_pager,
edit,
get_terminal_size,
getchar,
launch,
pause,
progressbar,
promp... | Clean exports from typer, remove unneeded Click components, add needed ones | :fire: Clean exports from typer, remove unneeded Click components, add needed ones
Clean exports from typer, remove unneeded Click components | Python | mit | tiangolo/typer,tiangolo/typer |
6709944d7e856fbce0434da0dc731fc83b55feb1 | tests/test_cli_update.py | tests/test_cli_update.py | # -*- coding: utf-8 -*-
import pathlib
def test_should_write_json(cli_runner, tmp_rc, tmp_templates_file):
result = cli_runner([
'-c', tmp_rc, 'update'
])
assert result.exit_code == 0
templates = pathlib.Path(tmp_templates_file)
assert templates.exists()
| # -*- coding: utf-8 -*-
import pathlib
import json
def test_store_template_data_to_json(cli_runner, tmp_rc, tmp_templates_file):
result = cli_runner([
'-c', tmp_rc, 'update'
])
assert result.exit_code == 0
templates = pathlib.Path(tmp_templates_file)
assert templates.exists()
with ... | Extend integration test to check correctness of dumped json data | Extend integration test to check correctness of dumped json data
| Python | bsd-3-clause | hackebrot/cibopath |
9ee1db76af2a1afdf59bf9099008715d9bca2f4d | tests/test_collection.py | tests/test_collection.py | from bukkit import Collection
def test_creation():
buckets = Collection(rate=5, limit=23, timeout=31, clock=lambda: 0)
assert buckets.rate == 5
assert buckets.limit == 23
assert buckets.timeout == 31
assert buckets.head_node.prev_node is buckets.tail_node
assert buckets.tail_node.next_node is ... | from bukkit import Collection
def test_creation():
buckets = Collection(rate=5, limit=23, timeout=31, clock=lambda: 0)
assert buckets.rate == 5
assert buckets.limit == 23
assert buckets.timeout == 31
assert buckets.head_node.prev_node is buckets.tail_node
assert buckets.tail_node.next_node is ... | Make sure getting buckets and checking for their presence work. | Make sure getting buckets and checking for their presence work.
| Python | mit | kgaughan/bukkit |
80c4b0fe0a654ef4ec56faac73af993408b846f1 | test_client.py | test_client.py | from client import client
import pytest
def test_string_input():
assert client("String") == "You sent: String"
def test_int_input():
assert client(42) == "You sent: 42"
def test_empty_input():
with pytest.raises(TypeError):
client()
def test_over32_input():
assert client("A long message ... | from client import client
import pytest
def test_response_ok():
msg = "GET /path/to/myindex.html HTTP/1.1\r\nHost: localhost:50000\r\n"
result = "HTTP/1.1 200 OK\r\n"
con_type = "Content-Type: text/plain\r\n"
body = "Content length: {}".format(21)
# Length of message from file name to end of line
... | Add first test for a good response | Add first test for a good response
| Python | mit | nbeck90/network_tools |
6d6528182eb5dc21f41eb4ea5e4cfd08163edc96 | sara_flexbe_states/src/sara_flexbe_states/Wonderland_Request.py | sara_flexbe_states/src/sara_flexbe_states/Wonderland_Request.py | #!/usr/bin/env python
# encoding=utf8
import requests
from flexbe_core import EventState, Logger
class Wonderland_Request(EventState):
'''
MoveArm receive a ROS pose as input and launch a ROS service with the same pose
># url string url to call
<= response string Finish job.
'''
def __init__(sel... | #!/usr/bin/env python
# encoding=utf8
import requests
from flexbe_core import EventState, Logger
class Wonderland_Request(EventState):
'''
Send requests to Wonderland server
># url string url to call
<= response string Finish job.
'''
def __init__(self):
# See example_state.py for basic explan... | Simplify state and save server URL | Simplify state and save server URL
| Python | bsd-3-clause | WalkingMachine/sara_behaviors,WalkingMachine/sara_behaviors |
f275c8cc020119b52ed01bc6b56946279853d854 | src/mmw/apps/bigcz/clients/cuahsi/details.py | src/mmw/apps/bigcz/clients/cuahsi/details.py | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from datetime import date, timedelta
from rest_framework.exceptions import ValidationError
DATE_FORMAT = '%m/%d/%Y'
def details(wsdl, site):
if not wsdl:
raise Validatio... | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from datetime import date, timedelta
from rest_framework.exceptions import ValidationError
DATE_FORMAT = '%m/%d/%Y'
def details(wsdl, site):
if not wsdl:
raise Validatio... | Stop ulmo caching for suds-jurko compliance | Stop ulmo caching for suds-jurko compliance
Previously we were using ulmo with suds-jurko 0.6, which is
the current latest release, but it is 4 years old. Most recent
work on suds-jurko has been done on the development branch,
including optimizations to memory use (which we need).
Unfortunately, the development branch... | Python | apache-2.0 | WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed |
366316b0ea20ae178670581b61c52c481682d2b0 | cosmic_ray/operators/exception_replacer.py | cosmic_ray/operators/exception_replacer.py | import ast
import builtins
from .operator import Operator
class OutOfNoWhereException(Exception):
pass
setattr(builtins, OutOfNoWhereException.__name__, OutOfNoWhereException)
class ExceptionReplacer(Operator):
"""An operator that modifies exception handlers."""
def visit_ExceptHandler(self, node): ... | import ast
import builtins
from .operator import Operator
class CosmicRayTestingException(Exception):
pass
setattr(builtins, CosmicRayTestingException.__name__, CosmicRayTestingException)
class ExceptionReplacer(Operator):
"""An operator that modifies exception handlers."""
def visit_ExceptHandler(s... | Change exception name to CosmicRayTestingException | Change exception name to CosmicRayTestingException
| Python | mit | sixty-north/cosmic-ray |
132309e91cc7e951d4a7f326d9e374dc8943f2f3 | tests/core/providers/test_testrpc_provider.py | tests/core/providers/test_testrpc_provider.py | import pytest
from web3.manager import (
RequestManager,
)
from web3.providers.tester import (
TestRPCProvider,
is_testrpc_available,
)
from web3.utils.compat import socket
def get_open_port():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("", 0))
s.listen(1)
port = s.gets... | import pytest
from web3.manager import (
RequestManager,
)
from web3.providers.tester import (
TestRPCProvider as TheTestRPCProvider,
is_testrpc_available,
)
from web3.utils.compat import socket
def get_open_port():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("", 0))
s.liste... | Resolve pytest warning about TestRPCProvider | Resolve pytest warning about TestRPCProvider
| Python | mit | pipermerriam/web3.py |
17e26fa55e70de657d52e340cb6b66691310a663 | bettertexts/forms.py | bettertexts/forms.py | from django_comments.forms import CommentForm
from django import forms
from django.utils.translation import ugettext_lazy as _
from bettertexts.models import TextComment
class TextCommentForm(CommentForm):
def __init__(self, *args, **kwargs):
super(TextCommentForm, self).__init__(*args, **kwargs)
... | from django_comments.forms import CommentForm
from django import forms
from django.utils.translation import ugettext_lazy as _
from bettertexts.models import TextComment
class TextCommentForm(CommentForm):
def __init__(self, *args, **kwargs):
super(TextCommentForm, self).__init__(*args, **kwargs)
... | Fix checkboxes inform and involved | CL011: Fix checkboxes inform and involved
| Python | mit | citizenline/citizenline,citizenline/citizenline,citizenline/citizenline,citizenline/citizenline |
ee66811628ea81e0540816e012c71d90457cc933 | test/utils/filesystem/name_sanitizer_spec.py | test/utils/filesystem/name_sanitizer_spec.py | from tempfile import TemporaryDirectory
from expects import expect
from hypothesis import given, assume, example
from hypothesis.strategies import text, characters
from mamba import description, it
from pathlib import Path
from crowd_anki.utils.filesystem.name_sanitizer import sanitize_anki_deck_name, \
invalid_f... | from tempfile import TemporaryDirectory
from expects import expect
from hypothesis import given, assume, example
from hypothesis.strategies import text, characters
from mamba import description, it
from pathlib import Path
from crowd_anki.utils.filesystem.name_sanitizer import sanitize_anki_deck_name, \
invalid_f... | Add explicit example filtering based on the byte length of the content | Add explicit example filtering based on the byte length of the content
| Python | mit | Stvad/CrowdAnki,Stvad/CrowdAnki,Stvad/CrowdAnki |
c10be759ad2ddbd076a1fe0a887d3cf9325aba3d | src/scheduler.py | src/scheduler.py | from collections import namedtuple
import sched_utils
import check
ScheduleConfiguration = namedtuple('ScheduleConfiguration',
['zones', 'teams', 'weight_zones',
'round_length', 'imbalance_action',
'match_count']... | """Match scheduler.
Usage:
scheduler.py full <teams> <matches> [options]
scheduler.py partial <teams> <previous> <matches> [options]
Options:
-w --weight Try to balance out between starting zones.
--zones=<z> Number of start zones [default: 4].
--empty Leave empty spaces to balance out th... | Switch to a new command-line interface | Switch to a new command-line interface
| Python | mit | prophile/match-scheduler,prophile/match-scheduler |
729d3160f974c521ab6605c02cf64861be0fb6ab | fri/utils.py | fri/utils.py | import numpy as np
def distance(u, v):
"""
Distance measure custom made for feature comparison.
Parameters
----------
u: first feature
v: second feature
Returns
-------
"""
u = np.asarray(u)
v = np.asarray(v)
# Euclidean differences
diff = (u - v) ** 2
# Null... | import numpy as np
def distance(u, v):
"""
Distance measure custom made for feature comparison.
Parameters
----------
u: first feature
v: second feature
Returns
-------
"""
u = np.asarray(u)
v = np.asarray(v)
# Euclidean differences
diff = (u - v) ** 2
# Null... | Revert removal of necessary function | Revert removal of necessary function
| Python | mit | lpfann/fri |
02522262692554a499d7c0fbc8f2efe4361023f1 | bmi_ilamb/__init__.py | bmi_ilamb/__init__.py | import os
from .bmi_ilamb import BmiIlamb
__all__ = ['BmiIlamb']
__version__ = 0.1
package_dir = os.path.dirname(__file__)
data_dir = os.path.join(package_dir, 'data')
| import os
from .bmi_ilamb import BmiIlamb
from .config import Configuration
__all__ = ['BmiIlamb', 'Configuration']
__version__ = 0.1
package_dir = os.path.dirname(__file__)
data_dir = os.path.join(package_dir, 'data')
| Add Configuration to package definition | Add Configuration to package definition
| Python | mit | permamodel/bmi-ilamb |
af2687703bc13eeabfe715e35988ad8c54ce9117 | builds/format_json.py | builds/format_json.py | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
import json
import os
import subprocess
import sys
def find_json_files():
for root, _, filenames in os.walk('.'):
if any(
d in root
for d in ['/WIP', '/.terraform', '/target']
):
continue
for f in filenam... | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
import json
import os
import subprocess
import sys
def find_json_files():
for root, _, filenames in os.walk('.'):
if any(
d in root
for d in ['/WIP', '/.terraform', '/target']
):
continue
for f in filenam... | Tweak the JSON we export | Tweak the JSON we export
| Python | mit | wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api |
0b5cc3f4702081eb565ef83c3175efc4e8b30e75 | circuits/node/node.py | circuits/node/node.py | # Module: node
# Date: ...
# Author: ...
"""Node
...
"""
from .client import Client
from .server import Server
from circuits import handler, BaseComponent
class Node(BaseComponent):
"""Node
...
"""
channel = "node"
def __init__(self, bind=None, channel=channel, **kwargs):
su... | # Module: node
# Date: ...
# Author: ...
"""Node
...
"""
from .client import Client
from .server import Server
from circuits import handler, BaseComponent
class Node(BaseComponent):
"""Node
...
"""
channel = "node"
def __init__(self, bind=None, channel=channel, **kwargs):
su... | Fix channel definition in add method | Fix channel definition in add method
| Python | mit | eriol/circuits,eriol/circuits,treemo/circuits,nizox/circuits,eriol/circuits,treemo/circuits,treemo/circuits |
3234d929d22d7504d89753ce6351d0efe1bfa8ac | whitepy/lexer.py | whitepy/lexer.py | from .lexerconstants import *
from .ws_token import Tokeniser
class Lexer(object):
def __init__(self, line):
self.line = line
self.pos = 0
self.tokens = []
def _get_int(self):
token = Tokeniser()
if self.line[-1] == '\n':
const = 'INT'
token.sca... | from .lexerconstants import *
from .ws_token import Tokeniser
class IntError(ValueError):
'''Exception when invalid integer is found'''
class Lexer(object):
def __init__(self, line):
self.line = line
self.pos = 0
self.tokens = []
def _get_int(self):
token = Tokeniser()
... | Add Execption for invalid Integer | Add Execption for invalid Integer
Exception class created for invalid integer and raise it if a bad integer is
found
| Python | apache-2.0 | yasn77/whitepy |
9d0ea4eaf8269350fabc3415545bebf4da4137a7 | source/segue/backend/processor/background.py | source/segue/backend/processor/background.py | # :coding: utf-8
# :copyright: Copyright (c) 2013 Martin Pengelly-Phillips
# :license: See LICENSE.txt.
import multiprocessing
from .base import Processor
class BackgroundProcessor(Processor):
'''Local background processor.'''
def process(self, command, args=None, kw=None):
'''Process *command*... | # :coding: utf-8
# :copyright: Copyright (c) 2013 Martin Pengelly-Phillips
# :license: See LICENSE.txt.
import multiprocessing
from .base import Processor
class BackgroundProcessor(Processor):
'''Local background processor.'''
def process(self, command, args=None, kw=None):
'''Process *command*... | Fix passing invalid None to multiprocessing Process class. | Fix passing invalid None to multiprocessing Process class.
| Python | apache-2.0 | 4degrees/segue |
34334bdb85644a5553ba36af5dc98942ea5fbf21 | launch_control/__init__.py | launch_control/__init__.py | # This file is part of the ARM Validation Dashboard Project.
# for the Linaro organization (http://linaro.org/)
#
# For more details see:
# https://blueprints.launchpad.net/ubuntu/+spec/arm-m-validation-dashboard
__version__ = "0.0.1"
| # This file is part of the ARM Validation Dashboard Project.
# for the Linaro organization (http://linaro.org/)
#
# For more details see:
# https://blueprints.launchpad.net/ubuntu/+spec/arm-m-validation-dashboard
"""
Public API for Launch Control.
Please see one of the available packages for more information.
"""
... | Add docstring to launch_control package | Add docstring to launch_control package
| Python | agpl-3.0 | Linaro/lava-server,Linaro/lava-server,OSSystems/lava-server,OSSystems/lava-server,Linaro/lava-server,Linaro/lava-server,OSSystems/lava-server |
cb1af2160952c7065e236d2cd544f46e5b252e92 | account_partner_account_summary/__openerp__.py | account_partner_account_summary/__openerp__.py | # -*- coding: utf-8 -*-
{
'name': 'Partner Account Summary',
'version': '1.0',
'description': """Partner Account Summary""",
'category': 'Aeroo Reporting',
'author': 'Ingenieria ADHOC',
'website': 'www.ingadhoc.com',
'depends': [
'sale',
'report_aeroo',
],
'data':... | # -*- coding: utf-8 -*-
{
'name': 'Partner Account Summary',
'version': '1.0',
'description': """Partner Account Summary""",
'category': 'Aeroo Reporting',
'author': 'Ingenieria ADHOC',
'website': 'www.ingadhoc.com',
'depends': [
'sale',
'report_aeroo',
'l10n_ar_invoi... | ADD dependency of l10n_ar_invoice for account summary | ADD dependency of l10n_ar_invoice for account summary
| Python | agpl-3.0 | maljac/odoo-addons,adhoc-dev/odoo-addons,syci/ingadhoc-odoo-addons,dvitme/odoo-addons,ingadhoc/account-payment,jorsea/odoo-addons,ingadhoc/stock,jorsea/odoo-addons,ingadhoc/account-financial-tools,sysadminmatmoz/ingadhoc,levkar/odoo-addons,syci/ingadhoc-odoo-addons,ingadhoc/partner,ingadhoc/product,ClearCorp/account-fi... |
517d25cf79c4d04661309ab7b3ab0638a2f968ee | api/docbleach/utils/__init__.py | api/docbleach/utils/__init__.py | import os
import random
import string
def secure_uuid():
"""
Strength: 6*3 random characters from a list of 62, approx. 64^18 possible
strings, or 2^100. Should be enough to prevent a successful bruteforce, as
download links are only valid for 3 hours
:return:
"""
return id_generator() + "... | import os
import string
from random import SystemRandom
cryptogen = SystemRandom()
def secure_uuid():
"""
Strength: 6*3 random characters from a list of 62, approx. 64^18 possible
strings, or 2^100. Should be enough to prevent a successful bruteforce, as
download links are only valid for 3 hours
... | Use SystemRandom to generate security-viable randomness | Use SystemRandom to generate security-viable randomness
| Python | mit | docbleach/DocBleach-Web,docbleach/DocBleach-Web,docbleach/DocBleach-Web,docbleach/DocBleach-Web |
a4df3f966e232e8327522a3db32870f5dcea0c03 | cartridge/shop/middleware.py | cartridge/shop/middleware.py |
from mezzanine.conf import settings
from cartridge.shop.models import Cart
class ShopMiddleware(object):
def __init__(self):
old = ("SHOP_SSL_ENABLED", "SHOP_FORCE_HOST", "SHOP_FORCE_SSL_VIEWS")
for name in old:
try:
getattr(settings, name)
except Attribu... |
from mezzanine.conf import settings
from cartridge.shop.models import Cart
class SSLRedirect(object):
def __init__(self):
old = ("SHOP_SSL_ENABLED", "SHOP_FORCE_HOST", "SHOP_FORCE_SSL_VIEWS")
for name in old:
try:
getattr(settings, name)
except AttributeE... | Add deprecated fallback for SSLMiddleware. | Add deprecated fallback for SSLMiddleware.
| Python | bsd-2-clause | traxxas/cartridge,traxxas/cartridge,Parisson/cartridge,Kniyl/cartridge,syaiful6/cartridge,jaywink/cartridge-reservable,wbtuomela/cartridge,syaiful6/cartridge,ryneeverett/cartridge,wbtuomela/cartridge,dsanders11/cartridge,wbtuomela/cartridge,dsanders11/cartridge,wyzex/cartridge,jaywink/cartridge-reservable,Parisson/cart... |
d7624defd7d05e721aeb0ccd074c7172c51295bf | nvchecker_source/git.py | nvchecker_source/git.py | # MIT licensed
# Copyright (c) 2020 Felix Yan <felixonmars@archlinux.org>, et al.
import re
from nvchecker_source.cmd import run_cmd
async def get_version(
name, conf, *, cache, keymanager=None
):
git = conf['git']
cmd = f"git ls-remote -t --refs {git}"
data = await cache.get(cmd, run_cmd)
regex = "(?<=refs... | # MIT licensed
# Copyright (c) 2020 Felix Yan <felixonmars@archlinux.org>, et al.
import re
from .cmd import run_cmd # type: ignore
async def get_version(
name, conf, *, cache, keymanager=None
):
git = conf['git']
cmd = f"git ls-remote -t --refs {git}"
data = await cache.get(cmd, run_cmd)
regex = "(?<=refs/... | Fix mypy and regex flag | Fix mypy and regex flag
| Python | mit | lilydjwg/nvchecker |
47f495e7e5b8fa06991e0c263bc9239818dd5b4f | airpy/list.py | airpy/list.py | import os
import airpy
def airlist():
installed_docs = os.listdir(airpy.data_directory)
for dir in installed_docs:
print(dir, end= ' ')
print(end = '\n') | from __future__ import print_function
import os
import airpy
def airlist():
installed_docs = os.listdir(airpy.data_directory)
for dir in installed_docs:
print(dir, end= ' ')
print(end = '\n')
| Add a Backwards compatibility for python 2.7 by adding a __future__ import | Add a Backwards compatibility for python 2.7 by adding a __future__ import
| Python | mit | kevinaloys/airpy |
6656493c3bf9b24d67c6de8cb33a1ca3defa4db8 | code/python/yum-check-update.py | code/python/yum-check-update.py | #!/usr/bin/python
import json
import subprocess
process = subprocess.Popen(["yum", "check-update", "-q"], stdout=subprocess.PIPE)
(output, err) = process.communicate()
exit_code = process.wait()
if exit_code == 0 and output == "":
print "Up to date"
else:
print json.dumps({"exit_code": exit_code, "raw... | #!/usr/bin/python
import json
import subprocess
process = subprocess.Popen(["yum", "check-update", "-q"], stdout=subprocess.PIPE)
(output, err) = process.communicate()
exit_code = process.wait()
if exit_code == 0 and output == "":
print json.dumps({"exit_code": exit_code, "raw": "Up to date"})
else:
p... | Make output types consistent for policy creation purposes | Make output types consistent for policy creation purposes
| Python | mit | ScriptRock/content,ScriptRock/content,ScriptRock/content,ScriptRock/content,ScriptRock/content,ScriptRock/content |
68b0f560322884967b817ad87cef8c1db9600dbd | app/main/errors.py | app/main/errors.py | from flask import render_template
from app.main import main
@main.app_errorhandler(400)
def page_not_found(e):
return _render_error_page(500)
@main.app_errorhandler(404)
def page_not_found(e):
return _render_error_page(404)
@main.app_errorhandler(500)
def exception(e):
return _render_error_page(500)
... | from flask import render_template
from app.main import main
@main.app_errorhandler(400)
def page_not_found(e):
print(e.message)
return _render_error_page(500)
@main.app_errorhandler(404)
def page_not_found(e):
print(e.message)
return _render_error_page(404)
@main.app_errorhandler(500)
def exceptio... | Add print statements for all error types | Add print statements for all error types
| Python | mit | alphagov/notify-frontend,alphagov/notify-frontend,alphagov/notify-frontend,alphagov/notify-frontend |
1dbb1e0f8751f37271178665a727c4eefc49a88c | partner_firstname/exceptions.py | partner_firstname/exceptions.py | # -*- encoding: utf-8 -*-
# Odoo, Open Source Management Solution
# Copyright (C) 2014-2015 Grupo ESOC <www.grupoesoc.es>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either versio... | # -*- encoding: utf-8 -*-
# Odoo, Open Source Management Solution
# Copyright (C) 2014-2015 Grupo ESOC <www.grupoesoc.es>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either versio... | Remove subclassing of exception, since there is only one. | Remove subclassing of exception, since there is only one.
| Python | agpl-3.0 | BT-fgarbely/partner-contact,diagramsoftware/partner-contact,andrius-preimantas/partner-contact,BT-jmichaud/partner-contact,Antiun/partner-contact,Therp/partner-contact,idncom/partner-contact,gurneyalex/partner-contact,Endika/partner-contact,Ehtaga/partner-contact,QANSEE/partner-contact,raycarnes/partner-contact,open-sy... |
ef0d0fa26bfd22c281c54bc348877afd0a7ee9d7 | tests/integration/blueprints/metrics/test_metrics.py | tests/integration/blueprints/metrics/test_metrics.py | """
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import pytest
# To be overridden by test parametrization
@pytest.fixture
def config_overrides():
return {}
@pytest.fixture
def client(admin_app, config_overrides, make_admin_app):
app = make_admin_app(**conf... | """
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import re
import pytest
# To be overridden by test parametrization
@pytest.fixture
def config_overrides():
return {}
@pytest.fixture
def client(admin_app, config_overrides, make_admin_app):
app = make_admin... | Use regex to match user metrics | Use regex to match user metrics
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps |
9011b359bdf164994734f8d6890a2d5acb5fa865 | project_euler/solutions/problem_32.py | project_euler/solutions/problem_32.py | from itertools import permutations
def solve() -> int:
pandigital = []
for permutation in permutations(range(1, 10)):
result = int(''.join(str(digit) for digit in permutation[:4]))
for i in range(1, 4):
left = int(''.join(str(digit) for digit in permutation[4:4 + i]))
... | from itertools import permutations
from ..library.base import list_to_number
def solve() -> int:
pandigital = []
for permutation in permutations(range(1, 10)):
result = list_to_number(permutation[:4])
for i in range(1, 4):
left = list_to_number(permutation[4:4 + i])
... | Replace joins with list_to_number in 32 | Replace joins with list_to_number in 32
| Python | mit | cryvate/project-euler,cryvate/project-euler |
a3c582df681aae77034e2db08999c89866cd6470 | utilities.py | utilities.py | import collections
def each(function, iterable):
for item in iterable:
function(item)
def each_unpack(function, iterable):
for item in iterable:
function(*item)
def minmax(*args):
min = None
max = None
for x in args:
if max < x:
max = x
if x > min:
min = x
return min, max
... | import collections
def each(function, iterable):
for item in iterable:
function(item)
def each_unpack(function, iterable):
for item in iterable:
function(*item)
def minmax(*args):
min = None
max = None
for x in args:
if max < x:
max = x
if x > min:
min = x
return min, max
... | Refactor earth mover's distance implementation | Refactor earth mover's distance implementation
| Python | mit | davidfoerster/schema-matching |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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... |
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... |
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 |
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.... |
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 |
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... |
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 |
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 |
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-... |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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... |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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... |
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 |
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 |
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 |
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 |
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 |
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 |
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... |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.