commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4
values | license stringclasses 13
values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
46328b5baaf25b04703ca04fd376f3f79a26a00f | sockjs/cyclone/proto.py | sockjs/cyclone/proto.py | import simplejson
json_encode = lambda data: simplejson.dumps(data, separators=(',', ':'))
json_decode = lambda data: simplejson.loads(data)
JSONDecodeError = ValueError
# Protocol handlers
CONNECT = 'o'
DISCONNECT = 'c'
MESSAGE = 'm'
HEARTBEAT = 'h'
# Various protocol helpers
def disconnect(code, reason):
"""R... | try:
import simplejson
except ImportError:
import json as simplejson
json_encode = lambda data: simplejson.dumps(data, separators=(',', ':'))
json_decode = lambda data: simplejson.loads(data)
JSONDecodeError = ValueError
# Protocol handlers
CONNECT = 'o'
DISCONNECT = 'c'
MESSAGE = 'm'
HEARTBEAT = 'h'
# Vari... | Use the json module from stdlib (Python 2.6+) as fallback | Use the json module from stdlib (Python 2.6+) as fallback
| Python | mit | flaviogrossi/sockjs-cyclone | ---
+++
@@ -1,4 +1,7 @@
-import simplejson
+try:
+ import simplejson
+except ImportError:
+ import json as simplejson
json_encode = lambda data: simplejson.dumps(data, separators=(',', ':'))
json_decode = lambda data: simplejson.loads(data) |
5288a47a3a68e216b9c59a46f70b4a2de79bba37 | server/api/registration/serializers.py | server/api/registration/serializers.py | from rest_framework import serializers
from django.core import exceptions
from django.contrib.auth import password_validation
from user.models import User
class CaptchaSerializer(serializers.Serializer):
OPERATION_CHOICES = (
('+', '+'),
('-', '-'),
# ('/', '/'),
# ('*', '*'),
... | from rest_framework import serializers
from django.core import exceptions
from django.contrib.auth import password_validation
from user.models import User
class CaptchaSerializer(serializers.Serializer):
OPERATION_CHOICES = (
('+', '+'),
('-', '-'),
# ('/', '/'),
# ('*', '*'),
... | Update user creation method in register serializer. | Update user creation method in register serializer.
| Python | mit | olegpshenichniy/truechat,olegpshenichniy/truechat,olegpshenichniy/truechat | ---
+++
@@ -46,4 +46,4 @@
def create(self, validated_data):
del validated_data['password_repeat']
- return User.objects.create(**validated_data)
+ return User.objects.create_user(**validated_data) |
196b5aabe2bcee8677c34481f19099f65699a44e | billjobs/tests/tests_user_admin_api.py | billjobs/tests/tests_user_admin_api.py | from django.test import TestCase
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.test import APIClient, APIRequestFactory, \
force_authenticate
from billjobs.views import UserAdmin
class UserAdminAPI(TestCase):
""" Test User Admin API REST endpoint """
... | from django.test import TestCase
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.test import APIClient, APIRequestFactory, \
force_authenticate
from billjobs.views import UserAdmin, UserAdminDetail
class UserAdminAPI(TestCase):
""" Test User Admin API REST ... | Add test admin to retrieve a user detail | Add test admin to retrieve a user detail
| Python | mit | ioO/billjobs | ---
+++
@@ -3,7 +3,7 @@
from rest_framework import status
from rest_framework.test import APIClient, APIRequestFactory, \
force_authenticate
-from billjobs.views import UserAdmin
+from billjobs.views import UserAdmin, UserAdminDetail
class UserAdminAPI(TestCase):
""" Test User Admin API REST endpoi... |
f34afd52aa1b89163d90a21feac7bd9e3425639d | gapipy/resources/booking/agency_chain.py | gapipy/resources/booking/agency_chain.py | # Python 2 and 3
from __future__ import unicode_literals
from gapipy.resources.base import Resource
from gapipy.resources.booking_company import BookingCompany
class AgencyChain(Resource):
_resource_name = 'agency_chains'
_as_is_fields = [
'id',
'href',
'name',
'agencies',
... | # Python 2 and 3
from __future__ import unicode_literals
from gapipy.resources.base import Resource
from gapipy.resources.booking_company import BookingCompany
class AgencyChain(Resource):
_resource_name = 'agency_chains'
_is_parent_resource = True
_as_is_fields = [
'id',
'href',
... | Make `AgencyChain.agencies` a "resource collection" field | Make `AgencyChain.agencies` a "resource collection" field
We can now get a `Query` when accessing the `agencies` attribute on an
`AgencyChain` instead of a dict with an URI to the agencies list.
| Python | mit | gadventures/gapipy | ---
+++
@@ -7,12 +7,12 @@
class AgencyChain(Resource):
_resource_name = 'agency_chains'
+ _is_parent_resource = True
_as_is_fields = [
'id',
'href',
'name',
- 'agencies',
'agent_notifications',
'communication_preferences',
'flags',
@@ -28,... |
a42d238fcc33a18cd90267864f0d308e27319ec5 | rbtools/utils/checks.py | rbtools/utils/checks.py | import os
import subprocess
import sys
from rbtools.utils.process import die, execute
GNU_DIFF_WIN32_URL = 'http://gnuwin32.sourceforge.net/packages/diffutils.htm'
def check_install(command):
"""
Try executing an external command and return a boolean indicating whether
that command is installed or not.... | import os
import subprocess
import sys
from rbtools.utils.process import die, execute
GNU_DIFF_WIN32_URL = 'http://gnuwin32.sourceforge.net/packages/diffutils.htm'
def check_install(command):
"""
Try executing an external command and return a boolean indicating whether
that command is installed or not.... | Fix the GNU diff error to not mention Subversion. | Fix the GNU diff error to not mention Subversion.
The GNU diff error was specifically saying Subversion was required,
which didn't make sense when other SCMClients triggered the check.
Instead, make the error more generic.
| Python | mit | davidt/rbtools,datjwu/rbtools,halvorlu/rbtools,datjwu/rbtools,davidt/rbtools,bcelary/rbtools,clach04/rbtools,halvorlu/rbtools,datjwu/rbtools,reviewboard/rbtools,reviewboard/rbtools,haosdent/rbtools,beol/rbtools,1tush/rbtools,beol/rbtools,Khan/rbtools,haosdent/rbtools,reviewboard/rbtools,beol/rbtools,haosdent/rbtools,ha... | ---
+++
@@ -37,8 +37,8 @@
if not has_gnu_diff:
sys.stderr.write('\n')
- sys.stderr.write('GNU diff is required for Subversion '
- 'repositories. Make sure it is installed\n')
+ sys.stderr.write('GNU diff is required in order to generate diffs. '
+ ... |
408ccc648d48725271db36a83c71aed1f03ff8c7 | gntp/test/__init__.py | gntp/test/__init__.py | import unittest
from gntp.config import GrowlNotifier
class GNTPTestCase(unittest.TestCase):
def setUp(self):
self.growl = GrowlNotifier('GNTP unittest', ['Testing'])
self.growl.register()
self.notification = {
'noteType': 'Testing',
'title': 'Unittest Title',
'description': 'Unittest Description',
... | import unittest
from gntp.config import GrowlNotifier
class GNTPTestCase(unittest.TestCase):
notification = {
'noteType': 'Testing',
'title': 'Unittest Title',
'description': 'Unittest Description',
}
def setUp(self):
self.growl = GrowlNotifier('GNTP unittest', ['Testing'])
self.growl.register()
def _... | Move variables to class variables so that we have to duplicate less for child classes | Move variables to class variables so that we have to duplicate less for child classes
| Python | mit | kfdm/gntp | ---
+++
@@ -3,15 +3,15 @@
class GNTPTestCase(unittest.TestCase):
+ notification = {
+ 'noteType': 'Testing',
+ 'title': 'Unittest Title',
+ 'description': 'Unittest Description',
+ }
+
def setUp(self):
self.growl = GrowlNotifier('GNTP unittest', ['Testing'])
self.growl.register()
-
- self.notificatio... |
5ce17bba417d6d9edff970c1bc775797f29b7ec4 | pysat/_constellation.py | pysat/_constellation.py |
class Constellation(object):
"""Manage and analyze data from multiple pysat Instruments.
FIXME document this.
"""
def __init__(self, instruments = None, name = None):
if instruments and name:
raise ValueError('When creating a constellation, please specify a '
... |
class Constellation(object):
"""Manage and analyze data from multiple pysat Instruments.
FIXME document this.
"""
def __init__(self, instruments=None, name=None):
if instruments and name:
raise ValueError('When creating a constellation, please specify a '
... | Fix bugs and style issues. | Fix bugs and style issues.
Fix __getitem__, improve documentation, partially implement __init__.
This got rid of some of pylint's complaints.
| Python | bsd-3-clause | jklenzing/pysat,rstoneback/pysat | ---
+++
@@ -4,7 +4,7 @@
FIXME document this.
"""
- def __init__(self, instruments = None, name = None):
+ def __init__(self, instruments=None, name=None):
if instruments and name:
raise ValueError('When creating a constellation, please specify a '
... |
b5240580e1786185bc6a889b0106d404cddc78e0 | AnnotationToXMLConverter/AnnotationToXMLConverter.py | AnnotationToXMLConverter/AnnotationToXMLConverter.py | import os
from TextFileReader import *
def main():
# get the base directory
base_directory = os.getcwd()
# counter for percentage print
stage_counter = 0
total_stage = len(os.listdir(base_directory + "/Annotation"))
for filename in os.listdir(base_directory + "/Annotation"):
# print t... | import os
import time
from TextFileReader import *
def main():
# get the base directory
base_directory = os.getcwd()
# counter for percentage print
stage_counter = 0
total_stage = len(os.listdir(base_directory + "/Annotation"))
start_time = time.time()
for filename in os.listdir(base_dir... | Add display for running states | Add display for running states
| Python | mit | Jamjomjara/snu-artoon,Jamjomjara/snu-artoon | ---
+++
@@ -1,5 +1,7 @@
import os
+import time
from TextFileReader import *
+
def main():
# get the base directory
@@ -8,6 +10,7 @@
# counter for percentage print
stage_counter = 0
total_stage = len(os.listdir(base_directory + "/Annotation"))
+ start_time = time.time()
for filename ... |
493314bb1d8778c10033f7011cd865526c34b6ce | boardinghouse/contrib/template/apps.py | boardinghouse/contrib/template/apps.py | from django.apps import AppConfig
from django.db import models
from django.dispatch import receiver
from boardinghouse.schema import activate_schema
class BoardingHouseTemplateConfig(AppConfig):
name = 'boardinghouse.contrib.template'
def ready(self):
from boardinghouse import signals
from .... | from django.apps import AppConfig
from django.db import models
from django.dispatch import receiver
from boardinghouse.schema import activate_schema
class BoardingHouseTemplateConfig(AppConfig):
name = 'boardinghouse.contrib.template'
def ready(self):
from boardinghouse import signals
from .... | Debug version to check codeship. | Debug version to check codeship.
--HG--
branch : schema-templates/fix-codeship-issue
| Python | bsd-3-clause | schinckel/django-boardinghouse,schinckel/django-boardinghouse,schinckel/django-boardinghouse | ---
+++
@@ -22,4 +22,6 @@
def execute_on_all_templates(sender, db_table, function, **kwargs):
for schema in SchemaTemplate.objects.all():
activate_schema(schema.schema)
+ print schema.schema
+ print kwargs
function(*kwargs.get('args... |
e8acef69e01e7a38b6497c03db3c993b67fd1e45 | dependency_to_prioritize/prioritize.py | dependency_to_prioritize/prioritize.py | class Prioritize(object):
'''
Class which convert dependency relationship to priority level
'''
def __init__(self):
self._priorityLevel = {}
def getPrioritizeLevel(self, item):
if item in self._priorityLevel:
return self._priorityLevel[item]
return -1
def re... | import logging
class Prioritize(object):
'''
Class which convert dependency relationship to priority level
'''
def __init__(self):
self._priorityLevel = {}
def getPrioritizeLevel(self, item):
if item in self._priorityLevel:
return self._priorityLevel[item]
retur... | Use logging instead of print logs. | Use logging instead of print logs.
| Python | mit | scott-zhou/algorithms | ---
+++
@@ -1,3 +1,5 @@
+import logging
+
class Prioritize(object):
'''
Class which convert dependency relationship to priority level
@@ -42,7 +44,7 @@
exclude.add(f)
curLevItem = todo - exclude
if not curLevItem:
- print("ERROR: dependency relation... |
9e0633207c5fc881821e9be1b8db34bc609d582d | censusreporter/config/prod/settings.py | censusreporter/config/prod/settings.py | from config.base.settings import *
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ROOT_URLCONF = 'config.prod.urls'
WSGI_APPLICATION = "config.prod.wsgi.application"
ALLOWED_HOSTS = [
'.censusreporter.org',
'.compute-1.amazonaws.com', # allows viewing of instances directly
'cr-prod-409865157.us-east-1.elb.amazona... | from config.base.settings import *
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ROOT_URLCONF = 'config.prod.urls'
WSGI_APPLICATION = "config.prod.wsgi.application"
ALLOWED_HOSTS = [
'.censusreporter.org',
'.compute-1.amazonaws.com', # allows viewing of instances directly
'cr-prod-409865157.us-east-1.elb.amazona... | Add back the EC2 metadata-based private IP fetch for ALLOWED_HOSTS | Add back the EC2 metadata-based private IP fetch for ALLOWED_HOSTS
| Python | mit | censusreporter/censusreporter,censusreporter/censusreporter,censusreporter/censusreporter,censusreporter/censusreporter | ---
+++
@@ -12,6 +12,19 @@
'cr-prod-409865157.us-east-1.elb.amazonaws.com', # from the load balancer
]
+# From https://forums.aws.amazon.com/thread.jspa?messageID=423533:
+# "The Elastic Load Balancer HTTP health check will use the instance's internal IP."
+# From https://dryan.com/articles/elb-django-allowe... |
30f47656f7e288153b452ec355bb17a0c3cda85f | chnnlsdmo/chnnlsdmo/settings_heroku.py | chnnlsdmo/chnnlsdmo/settings_heroku.py | import os
from os.path import abspath, basename, dirname, join, normpath
from sys import path
from .settings import *
DEBUG = True
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')
STATIC_URL = '/static/'
# Extra places for collectstatic to find stat... | import os
from os.path import abspath, basename, dirname, join, normpath
from sys import path
import dj_database_url
from .settings import *
DEBUG = True
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')
STATIC_URL = '/static/'
# Extra places for col... | Fix up import problem with dj-database-url | Fix up import problem with dj-database-url
| Python | bsd-3-clause | shearichard/django-channels-demo,shearichard/django-channels-demo,shearichard/django-channels-demo | ---
+++
@@ -1,6 +1,7 @@
import os
from os.path import abspath, basename, dirname, join, normpath
from sys import path
+import dj_database_url
from .settings import *
|
43a7f6a2130f57bd1e94aa418c4b7d6e085c09ea | tests/test_api_info.py | tests/test_api_info.py | from tests import string
def test_get(test):
def handle_connect(handler):
info = handler.api.get_info()
assert isinstance(info['api_version'], string)
assert isinstance(info['server_timestamp'], string)
if info.get('rest_server_url'):
assert info['websocket_server_url'... | from tests import string
def test_get(test):
def handle_connect(handler):
info = handler.api.get_info()
assert isinstance(info['api_version'], string)
assert isinstance(info['server_timestamp'], string)
if info.get('rest_server_url'):
assert info['websocket_server_url'... | Remove skip of test_get_cluster function for websocket transport | Remove skip of test_get_cluster function for websocket transport
| Python | apache-2.0 | devicehive/devicehive-python | ---
+++
@@ -18,8 +18,6 @@
def test_get_cluster(test):
- # TODO: implement websocket support when API will be added.
- test.only_http_implementation()
def handle_connect(handler):
cluster_info = handler.api.get_cluster_info() |
8e623faa44ad767baf4c92596a2501f98dfd2bbb | src/masterfile/validators/__init__.py | src/masterfile/validators/__init__.py | from __future__ import absolute_import
from . import io_validator
from . import index_column_validator
| from __future__ import absolute_import
from . import ( # noqa
io_validator,
index_column_validator
)
| Clean up validator package imports | Clean up validator package imports | Python | mit | njvack/masterfile | ---
+++
@@ -1,5 +1,6 @@
from __future__ import absolute_import
-from . import io_validator
-from . import index_column_validator
-
+from . import ( # noqa
+ io_validator,
+ index_column_validator
+) |
6cfebbf4548db9d52ba0c94997e81196705b4cc8 | mimesis_project/apps/mimesis/managers.py | mimesis_project/apps/mimesis/managers.py | from django.db import models
from django.contrib.contenttypes.models import ContentType
class MediaAssociationManager(models.Manager):
def for_model(self, model, content_type=None):
content_type = content_type or ContentType.objects.get_for_model(model)
objects = self.get_query_set().filter(... | from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.utils.encoding import force_unicode
class MediaAssociationManager(models.Manager):
def for_model(self, model, content_type=None):
"""
QuerySet for all media for a particular model (either an instanc... | Allow both instance and model classes in Media.objects.for_model() | Allow both instance and model classes in Media.objects.for_model()
| Python | bsd-3-clause | eldarion/mimesis,eldarion/mimesis | ---
+++
@@ -1,14 +1,17 @@
from django.db import models
-
from django.contrib.contenttypes.models import ContentType
-
+from django.utils.encoding import force_unicode
class MediaAssociationManager(models.Manager):
-
+
def for_model(self, model, content_type=None):
- content_type = content_type or... |
d760c42b1abb37087e9d5cf97d1bd1f2c0d76279 | application/__init__.py | application/__init__.py | import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_mail import Mail
from flask_login import LoginManager
from rauth import OAuth2Service
app = Flask(__name__)
BASE_FOLDER = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..'))
app.static_f... | import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_mail import Mail
from flask_login import LoginManager
from rauth import OAuth2Service
app = Flask(__name__)
BASE_FOLDER = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..'))
app.static_f... | Allow cross-origin headers on dev builds | Allow cross-origin headers on dev builds
| Python | bsd-3-clause | Alveo/alveo-transcriber,Alveo/alveo-transcriber,Alveo/alveo-transcriber,Alveo/alveo-transcriber | ---
+++
@@ -29,4 +29,13 @@
base_url='https://example.com/'
)
+# Allow cross origin headers only on dev mode
+if app.config['DEVELOPMENT'] == True:
+ @app.after_request
+ def after_request(response):
+ response.headers.add('Access-Control-Allow-Origin', '*')
+ response.headers.add('Access-C... |
680271d4669a309977e5fcfe89f92ea35ebc8d6f | common/djangoapps/dark_lang/migrations/0002_data__enable_on_install.py | common/djangoapps/dark_lang/migrations/0002_data__enable_on_install.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
# Converted from the original South migration 0002_enable_on_install.py
#
from django.db import migrations, models
def create_dark_lang_config(apps, schema_editor):
"""
Enable DarkLang by default when it is installed, to prevent accidental
r... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
# Converted from the original South migration 0002_enable_on_install.py
#
from django.db import migrations, models
def create_dark_lang_config(apps, schema_editor):
"""
Enable DarkLang by default when it is installed, to prevent accidental
r... | Correct the darklang migration, since many darklang configs can exist. | Correct the darklang migration, since many darklang configs can exist.
| Python | agpl-3.0 | waheedahmed/edx-platform,hamzehd/edx-platform,ovnicraft/edx-platform,hamzehd/edx-platform,miptliot/edx-platform,Lektorium-LLC/edx-platform,kursitet/edx-platform,Ayub-Khan/edx-platform,marcore/edx-platform,teltek/edx-platform,analyseuc3m/ANALYSE-v1,msegado/edx-platform,franosincic/edx-platform,marcore/edx-platform,kmooc... | ---
+++
@@ -14,7 +14,8 @@
dark_lang_model = apps.get_model("dark_lang", "DarkLangConfig")
db_alias = schema_editor.connection.alias
- dark_lang_model.objects.using(db_alias).get_or_create(enabled=True)
+ if not dark_lang_model.objects.using(db_alias).exists():
+ dark_lang_model.objects.using(... |
8cac0c660eee774c32b87d2511e4d2eeddf0ffe8 | scripts/slave/chromium/dart_buildbot_run.py | scripts/slave/chromium/dart_buildbot_run.py | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Entry point for the dartium buildbots.
This script is called from buildbot and reports results using the buildbot
annotation sc... | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Entry point for the dartium buildbots.
This script is called from buildbot and reports results using the buildbot
annotation sc... | Call dartium_tools/buildbot_annotated_steps.py directly, there is no need for moving this as part of the dartium patching process. | Call dartium_tools/buildbot_annotated_steps.py directly, there is no need for moving this as part of the dartium patching process.
Additionally, start calling a new script for release builds (there are none yet, but this is what will be used to build the sdk and editor)
TBR=foo
Review URL: https://chromiumcodereview... | Python | bsd-3-clause | eunchong/build,eunchong/build,eunchong/build,eunchong/build | ---
+++
@@ -9,16 +9,21 @@
annotation scheme.
"""
+import os
import sys
from common import chromium_utils
+def main():
+ builder_name = os.getenv('BUILDBOT_BUILDERNAME', default='')
+ is_release_bot = builder_name.startswith('release')
+ script = ''
+ if is_release_bot:
+ script = 'src/dartium_tools/b... |
0daae44acaefcc40b749166a1ee4ab8fe6ace368 | fix_virtualenv.py | fix_virtualenv.py | from __future__ import unicode_literals, print_function
import os
import argparse
import sys
import shutil
def main():
ap = argparse.ArgumentParser()
ap.add_argument("virtualenv", help="The path to the virtual environment.")
args = ap.parse_args()
target = "{}/include/python{}.{}".format(args.virtual... | from __future__ import unicode_literals, print_function
import os
import argparse
import sys
import shutil
import sysconfig
def main():
target = os.path.dirname(sysconfig.get_config_h_filename())
try:
source = os.readlink(target)
except:
print(target, "is not a symlink. Perhaps this scrip... | Use sysconfig to find the include directory. | Use sysconfig to find the include directory.
| Python | lgpl-2.1 | renpy/pygame_sdl2,renpy/pygame_sdl2,renpy/pygame_sdl2,renpy/pygame_sdl2 | ---
+++
@@ -4,14 +4,10 @@
import argparse
import sys
import shutil
+import sysconfig
def main():
- ap = argparse.ArgumentParser()
- ap.add_argument("virtualenv", help="The path to the virtual environment.")
- args = ap.parse_args()
-
- target = "{}/include/python{}.{}".format(args.virtualenv, sys.ve... |
703c0f20215e63cb92436875a1798c1becf4b89f | tests/test_examples.py | tests/test_examples.py | import requests
import time
import multiprocessing
from examples import minimal
def test_minimal():
port = minimal.app.get_port()
p = multiprocessing.Process(
target=minimal.app.start_server)
p.start()
try:
time.sleep(3)
r = requests.get('http://127.0.0.1:{port}/hello'.format(... | import requests
import time
import multiprocessing
from examples import minimal
class TestExamples(object):
servers = {}
@classmethod
def setup_class(self):
""" setup any state specific to the execution of the given module."""
self.servers['minimal'] = {'port': minimal.app.get_port()}
... | Reorganize tests in a class | Reorganize tests in a class
| Python | mit | factornado/factornado | ---
+++
@@ -5,17 +5,27 @@
from examples import minimal
-def test_minimal():
- port = minimal.app.get_port()
- p = multiprocessing.Process(
- target=minimal.app.start_server)
- p.start()
- try:
+class TestExamples(object):
+ servers = {}
+
+ @classmethod
+ def setup_class(self):
+ ... |
4078743923befac99672b67ea53fd1fe11af2e8c | tests/test_mjviewer.py | tests/test_mjviewer.py | """
Test mujoco viewer.
"""
import unittest
from mujoco_py import mjviewer, mjcore
class MjLibTest(unittest.TestCase):
xml_path = 'tests/models/cartpole.xml'
def setUp(self):
self.width = 100
self.height = 100
self.viewer = mjviewer.MjViewer(visible=False,
... | """
Test mujoco viewer.
"""
import unittest
from mujoco_py import mjviewer, mjcore
class MjLibTest(unittest.TestCase):
xml_path = 'tests/models/cartpole.xml'
def setUp(self):
self.width = 100
self.height = 100
self.viewer = mjviewer.MjViewer(visible=False,
... | Stop using ord with ints | Stop using ord with ints
| Python | mit | pulkitag/mujoco140-py,pulkitag/mujoco140-py,pulkitag/mujoco140-py | ---
+++
@@ -38,4 +38,4 @@
# the width and height are scaled
self.assertEqual(len(data), 3 * width * height)
# make sure the image is not pitch black
- self.assertTrue(any(map(ord, data)))
+ self.assertTrue(any(map(lambda x: x > 0, data))) |
94e13e5d00dc5e2782cf4a1346f098e3c2ad2fc0 | iotendpoints/endpoints/urls.py | iotendpoints/endpoints/urls.py | import os
from django.conf.urls import url
from . import views
OBSCURE_URL = r'^{}$'.format(os.environ.get('OBSCURE_URL', 'this_should_be_in_env_var'))
urlpatterns = [
url(r'^$', views.index, name='index'),
url(OBSCURE_URL, views.obscure_dump_request_endpoint, name='dump_request'),
] | import os
from django.conf.urls import url
from . import views
DUMMY_OBSCURE_URL = 'this_should_be_in_env_var'
OBSCURE_URL = os.environ.get('OBSCURE_URL', DUMMY_OBSCURE_URL)
if DUMMY_OBSCURE_URL == OBSCURE_URL:
print("Warning: you should set OBSCURE_URL environment variable in this env\n\n")
OBSCURE_URL_PATTERN ... | Add warning if OBSCURE_URL env var is not set | Add warning if OBSCURE_URL env var is not set
| Python | mit | aapris/IoT-Web-Experiments | ---
+++
@@ -2,9 +2,15 @@
from django.conf.urls import url
from . import views
-OBSCURE_URL = r'^{}$'.format(os.environ.get('OBSCURE_URL', 'this_should_be_in_env_var'))
+
+DUMMY_OBSCURE_URL = 'this_should_be_in_env_var'
+OBSCURE_URL = os.environ.get('OBSCURE_URL', DUMMY_OBSCURE_URL)
+if DUMMY_OBSCURE_URL == OBSCUR... |
8895cd5090bd1014d3fe16976c56d6c24bad0ded | parlai/agents/local_human/local_human.py | parlai/agents/local_human/local_human.py | # Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
"""Agent does gets the loca... | # Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
"""Agent does gets the loca... | Send episode_done=True from local human agent | Send episode_done=True from local human agent
| Python | mit | facebookresearch/ParlAI,calee88/ParlAI,facebookresearch/ParlAI,facebookresearch/ParlAI,calee88/ParlAI,facebookresearch/ParlAI,calee88/ParlAI,facebookresearch/ParlAI | ---
+++
@@ -15,6 +15,7 @@
def __init__(self, opt, shared=None):
super().__init__(opt)
self.id = 'localHuman'
+ self.done = False
def observe(self, msg):
print(display_messages([msg]))
@@ -24,4 +25,11 @@
reply = {}
reply['id'] = self.getID()
repl... |
a5b7dabcb4450cadd931421738c0ee6f6b63ea4a | helpers/config.py | helpers/config.py | import os
from os.path import join, dirname, abspath
from dotenv import load_dotenv
class Config:
loaded = False
@staticmethod
def load(file_name='../config/.env'):
load_dotenv(join(dirname(__file__), file_name))
env_file_path = abspath(join(dirname(__file__), '../config', os.environ.get(... | import os
from os.path import join, dirname, abspath
from dotenv import load_dotenv
class Config:
max_seq_size = 1000
loaded = False
@staticmethod
def load(file_name='../config/.env'):
load_dotenv(join(dirname(__file__), file_name))
env_file_path = abspath(join(dirname(__file__), '../... | Move seq size to const | Move seq size to const
| Python | mit | Holovin/D_GrabDemo | ---
+++
@@ -4,6 +4,7 @@
class Config:
+ max_seq_size = 1000
loaded = False
@staticmethod
@@ -25,7 +26,7 @@
value = os.environ.get(key)
if not value:
- if default_value:
+ if default_value is not None:
return default_value
ra... |
1ae097291a42022013969287ecb91bafa60ae625 | examples/send_transfer.py | examples/send_transfer.py | # coding=utf-8
"""
Example script that shows how to use PyOTA to send a transfer to an address.
"""
from iota import *
# Create the API instance.
api =\
Iota(
# URI of a locally running node.
'http://localhost:14265/',
# Seed used for cryptographic functions.
seed = b'SEED9GOES9HERE'
)
# For mor... | # coding=utf-8
"""
Example script that shows how to use PyOTA to send a transfer to an address.
"""
from iota import *
SEED1 = b"THESEEDOFTHEWALLETSENDINGGOESHERE999999999999999999999999999999999999999999999999"
ADDRESS_WITH_CHECKSUM_SECURITY_LEVEL_2 = b"RECEIVINGWALLETADDRESSGOESHERE9WITHCHECKSUMANDSECURITYLEVEL29999... | Clarify Address usage in send example | Clarify Address usage in send example
Improved the script to explain the recipient address a little better.
Changed the address concat to a reference to a specific kind of Iota address.
This is loosely inspired by the JAVA sen transaction test case. | Python | mit | iotaledger/iota.lib.py | ---
+++
@@ -4,6 +4,8 @@
"""
from iota import *
+SEED1 = b"THESEEDOFTHEWALLETSENDINGGOESHERE999999999999999999999999999999999999999999999999"
+ADDRESS_WITH_CHECKSUM_SECURITY_LEVEL_2 = b"RECEIVINGWALLETADDRESSGOESHERE9WITHCHECKSUMANDSECURITYLEVEL2999999999999999999999999999999"
# Create the API instance.
api =\... |
a029c6f4fce36693a9dee53ff8bc797890cfe71e | plugins/basic_info_plugin.py | plugins/basic_info_plugin.py | import string
import textwrap
from plugins import BasePlugin
__author__ = 'peter'
class BasicInfoPlugin(BasePlugin):
name = 'BasicInfoPlugin'
short_description = 'Basic info:'
default = True
description = textwrap.dedent('''
This plugin provides some basic info about the string such as:
- Len... | import string
import textwrap
from veryprettytable import VeryPrettyTable
from plugins import BasePlugin
__author__ = 'peter'
class BasicInfoPlugin(BasePlugin):
name = 'BasicInfoPlugin'
short_description = 'Basic info:'
default = True
description = textwrap.dedent('''
This plugin provides some ba... | Use table instead of separate lines | Use table instead of separate lines
| Python | mit | Sakartu/stringinfo | ---
+++
@@ -1,5 +1,6 @@
import string
import textwrap
+from veryprettytable import VeryPrettyTable
from plugins import BasePlugin
__author__ = 'peter'
@@ -20,9 +21,10 @@
for s in self.args['STRING']:
if len(self.args['STRING']) > 1:
result += '{0}:\n'.format(s)
- ... |
1ff53eade7c02a92f5f09c371b766e7b176a90a1 | speyer/ingest/gerrit.py | speyer/ingest/gerrit.py | from __future__ import print_function
import select
import paramiko
class GerritEvents(object):
def __init__(self, userid, host, key=None):
self.userid = userid
self.host = host
self.port = 29418
self.key = key
def _read_events(self, stream, use_poll=False):
if not... | from __future__ import print_function
import select
import paramiko
class GerritEvents(object):
def __init__(self, userid, host, key=None):
self.userid = userid
self.host = host
self.port = 29418
self.key = key
def _read_events(self, stream, use_poll=False):
if not... | Allow connecting to unknown hosts but warn | Allow connecting to unknown hosts but warn
| Python | apache-2.0 | locke105/streaming-python-testdrive | ---
+++
@@ -32,6 +32,7 @@
def events(self):
client = paramiko.SSHClient()
client.load_system_host_keys()
+ client.set_missing_host_key_policy(paramiko.WarningPolicy())
connargs = {
'hostname': self.host, |
8614f782196a86507c1b659f0b1d9ee293ddc309 | virtool/job_classes.py | virtool/job_classes.py | import virtool.subtraction
import virtool.virus_index
import virtool.sample_create
import virtool.job_analysis
import virtool.job_dummy
#: A dict containing :class:`~.job.Job` subclasses keyed by their task names.
TASK_CLASSES = {
"rebuild_index": virtool.virus_index.RebuildIndex,
"pathoscope_bowtie": virtool... | import virtool.subtraction
import virtool.virus_index
import virtool.sample_create
import virtool.job_analysis
import virtool.job_dummy
#: A dict containing :class:`~.job.Job` subclasses keyed by their task names.
TASK_CLASSES = {
"rebuild_index": virtool.virus_index.RebuildIndex,
"pathoscope_bowtie": virtool... | Change job class name from add_host to create_subtraction | Change job class name from add_host to create_subtraction
| Python | mit | igboyes/virtool,virtool/virtool,virtool/virtool,igboyes/virtool | ---
+++
@@ -10,7 +10,7 @@
"rebuild_index": virtool.virus_index.RebuildIndex,
"pathoscope_bowtie": virtool.job_analysis.PathoscopeBowtie,
"nuvs": virtool.job_analysis.NuVs,
- "add_subtraction": virtool.subtraction.CreateSubtraction,
+ "create_subtraction": virtool.subtraction.CreateSubtraction,
... |
df0b04ec5142631a0fb1e2051b622f8c2568fec6 | pyoracc/model/oraccobject.py | pyoracc/model/oraccobject.py | from mako.template import Template
class OraccObject(object):
template = Template(r"""@${objecttype}
% for child in children:
${child.serialize()}
% endfor""", output_encoding='utf-8')
def __init__(self, objecttype):
self.objecttype = objecttype
self.children = []
self.query ... | from mako.template import Template
class OraccObject(object):
template = Template(r"""@${objecttype}
% for child in children:
${child.serialize()}
% endfor""", output_encoding='utf-8')
def __init__(self, objecttype):
self.objecttype = objecttype
self.children = []
self.query =... | Remove trailing space after object type. | Remove trailing space after object type.
| Python | mit | UCL/pyoracc | ---
+++
@@ -2,7 +2,7 @@
class OraccObject(object):
- template = Template(r"""@${objecttype}
+ template = Template(r"""@${objecttype}
% for child in children:
${child.serialize()}
% endfor""", output_encoding='utf-8') |
5954196d3c81083f7f94eca147fe1a76a6dfb301 | vc_vidyo/indico_vc_vidyo/blueprint.py | vc_vidyo/indico_vc_vidyo/blueprint.py | # This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (a... | # This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (a... | Fix "make me room owner" | VC/Vidyo: Fix "make me room owner"
| Python | mit | ThiefMaster/indico-plugins,ThiefMaster/indico-plugins,ThiefMaster/indico-plugins,indico/indico-plugins,ThiefMaster/indico-plugins,indico/indico-plugins,indico/indico-plugins,indico/indico-plugins | ---
+++
@@ -23,5 +23,7 @@
blueprint = IndicoPluginBlueprint('vc_vidyo', 'indico_vc_vidyo')
# Room management
-blueprint.add_url_rule('/event/<confId>/manage/videoconference/vidyo/<int:event_vc_room_id>/room-owner/',
- 'set_room_owner', RHVidyoRoomOwner, methods=('POST',), defaults={'service'... |
e1a1a19408c052c93ccc1684b2e1408ba229addc | tests/test_cookiecutter_invocation.py | tests/test_cookiecutter_invocation.py | # -*- coding: utf-8 -*-
"""
test_cookiecutter_invocation
----------------------------
Tests to make sure that cookiecutter can be called from the cli without
using the entry point set up for the package.
"""
import pytest
import subprocess
def test_should_raise_error_without_template_arg(capfd):
with pytest.ra... | # -*- coding: utf-8 -*-
"""
test_cookiecutter_invocation
----------------------------
Tests to make sure that cookiecutter can be called from the cli without
using the entry point set up for the package.
"""
import os
import pytest
import subprocess
from cookiecutter import utils
def test_should_raise_error_witho... | Implement test to make sure cookiecutter main is called | Implement test to make sure cookiecutter main is called
| Python | bsd-3-clause | michaeljoseph/cookiecutter,luzfcb/cookiecutter,benthomasson/cookiecutter,atlassian/cookiecutter,kkujawinski/cookiecutter,christabor/cookiecutter,audreyr/cookiecutter,Springerle/cookiecutter,takeflight/cookiecutter,cguardia/cookiecutter,moi65/cookiecutter,christabor/cookiecutter,pjbull/cookiecutter,michaeljoseph/cookiec... | ---
+++
@@ -8,8 +8,11 @@
using the entry point set up for the package.
"""
+import os
import pytest
import subprocess
+
+from cookiecutter import utils
def test_should_raise_error_without_template_arg(capfd):
@@ -19,3 +22,27 @@
_, err = capfd.readouterr()
exp_message = 'Error: Missing argument "t... |
5eaca14a3ddf7515f5b855aee4b58d21048ca9a9 | avena/utils.py | avena/utils.py | #!/usr/bin/env python
from os.path import exists, splitext
from random import randint
_depth = lambda x, y, z=1: z
_invert_dict = lambda d: dict((v, k) for k, v in list(d.items()))
_PREFERRED_RGB = {
'R': 0,
'G': 1,
'B': 2,
}
def depth(array):
'''Return the depth (the third dimension) of an array... | #!/usr/bin/env python
from os.path import exists, splitext
from random import randint
def _depth(x, y, z=1):
return z
_invert_dict = lambda d: dict((v, k) for k, v in list(d.items()))
_PREFERRED_RGB = {
'R': 0,
'G': 1,
'B': 2,
}
def depth(array):
'''Return the depth (the third dimension) of a... | Use a function instead of a lambda expression. | Use a function instead of a lambda expression.
| Python | isc | eliteraspberries/avena | ---
+++
@@ -4,7 +4,8 @@
from random import randint
-_depth = lambda x, y, z=1: z
+def _depth(x, y, z=1):
+ return z
_invert_dict = lambda d: dict((v, k) for k, v in list(d.items()))
|
e36caab07168d3884b55970e5fa6ee5146df1b1c | src/waldur_mastermind/booking/processors.py | src/waldur_mastermind/booking/processors.py | import mock
BookingCreateProcessor = mock.MagicMock()
BookingDeleteProcessor = mock.MagicMock()
| from waldur_mastermind.marketplace import processors
class BookingCreateProcessor(processors.CreateResourceProcessor):
def get_serializer_class(self):
pass
def get_viewset(self):
pass
def get_post_data(self):
pass
def get_scope_from_response(self, response):
pass
c... | Fix using mock in production | Fix using mock in production [WAL-2530]
| Python | mit | opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur | ---
+++
@@ -1,4 +1,29 @@
-import mock
+from waldur_mastermind.marketplace import processors
-BookingCreateProcessor = mock.MagicMock()
-BookingDeleteProcessor = mock.MagicMock()
+
+class BookingCreateProcessor(processors.CreateResourceProcessor):
+ def get_serializer_class(self):
+ pass
+
+ def get_vie... |
48f15196bdbdf6c86491ff4ab966f4ae82932b80 | libact/labelers/interactive_labeler.py | libact/labelers/interactive_labeler.py | """Interactive Labeler
This module includes an InteractiveLabeler.
"""
import matplotlib.pyplot as plt
from libact.base.interfaces import Labeler
from libact.utils import inherit_docstring_from
class InteractiveLabeler(Labeler):
"""Interactive Labeler
InteractiveLabeler is a Labeler object that shows the ... | """Interactive Labeler
This module includes an InteractiveLabeler.
"""
import matplotlib.pyplot as plt
from libact.base.interfaces import Labeler
from libact.utils import inherit_docstring_from
class InteractiveLabeler(Labeler):
"""Interactive Labeler
InteractiveLabeler is a Labeler object that shows the ... | Fix compatibility issues with "input()" in python2 | Fix compatibility issues with "input()" in python2
override input with raw_input if in python2 | Python | bsd-2-clause | ntucllab/libact,ntucllab/libact,ntucllab/libact | ---
+++
@@ -36,6 +36,10 @@
if self.label_name is not None:
banner += str(self.label_name) + ' '
+
+ try: input = raw_input # input fix for python 2.x
+ except NameError: pass
+
lbl = input(banner)
while (self.label_name is not None) and (l... |
c26ebf61079fc783d23000ee4e023e1111d8a75e | blog/manage.py | blog/manage.py | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
if socket.gethostname() == 'blog':
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.production")
else:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.local"
from django.core.management import execute_... | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
if socket.gethostname() == 'blog':
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.base")
else:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.base")
from django.core.management import execute_from_c... | Switch settings used to just settings/base.py | Switch settings used to just settings/base.py
| Python | bsd-3-clause | giovannicode/giovanniblog,giovannicode/giovanniblog | ---
+++
@@ -4,9 +4,9 @@
if __name__ == "__main__":
if socket.gethostname() == 'blog':
- os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.production")
+ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.base")
else:
- os.environ.setdefault("DJANGO_SETTINGS_MODULE", "s... |
270b1a1d970d866b5de7e3b742166e2e0d13c513 | patrol_mission.py | patrol_mission.py | #!/usr/bin/python
"""
Cyril Robin -- LAAS-CNRS -- 2014
TODO Descriptif
"""
from mission import *
from constant import *
from sys import argv, exit
from timer import Timer
if __name__ == "__main__":
with Timer('Loading mission file'):
json_mission = loaded_mission(argv[1])
mission = Mission ( ... | #!/usr/bin/python
"""
Cyril Robin -- LAAS-CNRS -- 2014
TODO Descriptif
"""
from mission import *
from constant import *
from sys import argv, exit
from timer import Timer
if __name__ == "__main__":
with Timer('Loading mission file'):
json_mission = loaded_mission(argv[1])
mission = Mission ( ... | Update launcher for new features | Update launcher for new features
| Python | bsd-3-clause | cyrobin/patrolling,cyrobin/patrolling | ---
+++
@@ -40,9 +40,14 @@
print "Starting Loop !"
#mission.loop_once()
+ #mission.loop(5,True)
mission.loop(10)
mission.update()
+ #for robot in mission.team:
+ #robot.display_weighted_map()
mission.display_situation()
+ mission.print_metrics()
+
print "Done." |
f5c41e3f85db152028dab7026c13958269e7b6d9 | nazs/test_settings.py | nazs/test_settings.py | from .settings import * # noqa
DEBUG = True
TEMPLATE_DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'db.sqlite',
},
'volatile': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
# Non root user (root under devel... | from .settings import * # noqa
DEBUG = True
TEMPLATE_DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'db.sqlite',
},
'volatile': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
# Non root user, ROOT for current... | Use current user for tests | Use current user for tests
| Python | agpl-3.0 | exekias/droplet,exekias/droplet,exekias/droplet | ---
+++
@@ -14,8 +14,8 @@
}
}
-# Non root user (root under development)
-RUN_AS_USER = 'nobody'
+# Non root user, ROOT for current one
+RUN_AS_USER = None
LOGGING = {
'version': 1, |
3f59fd3762c45f4d8b56576103b1d5664f7ea426 | openedx/features/job_board/models.py | openedx/features/job_board/models.py | from django.db import models
from django_countries.fields import CountryField
from model_utils.models import TimeStampedModel
from .constants import JOB_COMPENSATION_CHOICES, JOB_HOURS_CHOICES, JOB_TYPE_CHOICES
class Job(TimeStampedModel):
"""
This model contains all the fields related to a job being
po... | from django.db import models
from django_countries.fields import CountryField
from model_utils.models import TimeStampedModel
from .constants import JOB_COMPENSATION_CHOICES, JOB_HOURS_CHOICES, JOB_TYPE_CHOICES
class Job(TimeStampedModel):
"""
This model contains all the fields related to a job being
po... | Replace double quotes with single quotes as requested | Replace double quotes with single quotes as requested
| Python | agpl-3.0 | philanthropy-u/edx-platform,philanthropy-u/edx-platform,philanthropy-u/edx-platform,philanthropy-u/edx-platform | ---
+++
@@ -23,5 +23,5 @@
responsibilities = models.TextField(blank=True, null=True)
website_link = models.URLField(max_length=255, blank=True, null=True)
contact_email = models.EmailField(max_length=255)
- logo = models.ImageField(upload_to="job-board/uploaded-logos/", blank=True, null=True)
+ l... |
4e378dc4a44781e59bc63abb64c0fffb114a5adc | spacy/tests/regression/test_issue1506.py | spacy/tests/regression/test_issue1506.py | # coding: utf8
from __future__ import unicode_literals
import gc
from ...lang.en import English
def test_issue1506():
nlp = English()
def string_generator():
for _ in range(10001):
yield "It's sentence produced by that bug."
yield "Oh snap."
for _ in range(10001):
... | # coding: utf8
from __future__ import unicode_literals
import gc
from ...lang.en import English
def test_issue1506():
nlp = English()
def string_generator():
for _ in range(10001):
yield "It's sentence produced by that bug."
for _ in range(10001):
yield "I erase lem... | Remove all obsolete code and test only initial problem | Remove all obsolete code and test only initial problem
| Python | mit | explosion/spaCy,honnibal/spaCy,spacy-io/spaCy,spacy-io/spaCy,recognai/spaCy,explosion/spaCy,honnibal/spaCy,recognai/spaCy,explosion/spaCy,honnibal/spaCy,recognai/spaCy,aikramer2/spaCy,recognai/spaCy,aikramer2/spaCy,spacy-io/spaCy,aikramer2/spaCy,aikramer2/spaCy,recognai/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spa... | ---
+++
@@ -13,8 +13,6 @@
for _ in range(10001):
yield "It's sentence produced by that bug."
- yield "Oh snap."
-
for _ in range(10001):
yield "I erase lemmas."
@@ -24,23 +22,11 @@
for _ in range(10001):
yield "It's sentence produced by that... |
432bbebbfa6376779bc605a45857ccdf5fef4b59 | soundgen.py | soundgen.py | from wavebender import *
import sys
start = 10
final = 200
end_time= 10
def val(i):
time = float(i) / 44100
k = (final - start) / end_time
return math.sin(2.0 * math.pi * (start * time + ((k * time * time) / 2)))
def sweep():
return (val(i) for i in count(0))
channels = ((sweep(),),)
samples = comp... | from wavebender import *
import sys
from common import *
def sweep():
return (val(i) for i in count(0))
channels = ((sweep(),),)
samples = compute_samples(channels, 44100 * 60 * 1)
write_wavefile(sys.stdout, samples, 44100 * 60 * 1, nchannels=1)
| Make sound generator use common | Make sound generator use common
Signed-off-by: Ian Macalinao <57a33a5496950fec8433e4dd83347673459dcdfc@giza.us>
| Python | isc | simplyianm/resonance-finder | ---
+++
@@ -1,15 +1,6 @@
from wavebender import *
import sys
-
-start = 10
-final = 200
-
-end_time= 10
-
-def val(i):
- time = float(i) / 44100
- k = (final - start) / end_time
- return math.sin(2.0 * math.pi * (start * time + ((k * time * time) / 2)))
+from common import *
def sweep():
return (va... |
1237e75486ac0ae5c9665ec10d6701c530d601e8 | src/petclaw/__init__.py | src/petclaw/__init__.py | # =====================================================================
# Package: petclaw
# File: __init__.py
# Authors: Amal Alghamdi
# David Ketcheson
# Aron Ahmadia
# ======================================================================
"""Main petclaw package"""
im... | # =====================================================================
# Package: petclaw
# File: __init__.py
# Authors: Amal Alghamdi
# David Ketcheson
# Aron Ahmadia
# ======================================================================
"""Main petclaw package"""
im... | Add ImplicitClawSolver1D to base namespace | Add ImplicitClawSolver1D to base namespace
| Python | bsd-3-clause | unterweg/peanoclaw,unterweg/peanoclaw,unterweg/peanoclaw,unterweg/peanoclaw,unterweg/peanoclaw,unterweg/peanoclaw | ---
+++
@@ -33,6 +33,7 @@
from clawpack import ClawSolver2D
from sharpclaw import SharpClawSolver1D
from sharpclaw import SharpClawSolver2D
+from implicitclawpack import ImplicitClawSolver1D
__all__.append('BC')
from pyclaw.solver import BC |
40f9f82289d0b15c1bc42415460325ce2a447eaf | cla_backend/apps/cla_eventlog/management/commands/find_and_delete_old_cases.py | cla_backend/apps/cla_eventlog/management/commands/find_and_delete_old_cases.py | from django.core.management.base import BaseCommand
from dateutil.relativedelta import relativedelta
from legalaid.models import Case
from cla_butler.tasks import DeleteOldData
class FindAndDeleteCasesUsingCreationTime(DeleteOldData):
def get_eligible_cases(self):
two_years = self.now - relativedelta(yea... | from django.core.management.base import BaseCommand
from dateutil.relativedelta import relativedelta
from legalaid.models import Case
from cla_butler.tasks import DeleteOldData
class FindAndDeleteCasesUsingCreationTime(DeleteOldData):
def get_eligible_cases(self):
super(FindAndDeleteCasesUsingCreationTim... | Refactor class so the now time is always defined | Refactor class so the now time is always defined
Added code to class to run the setup method which assigns a variable to self.now (ie. defines a time for now) | Python | mit | ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend | ---
+++
@@ -7,6 +7,7 @@
class FindAndDeleteCasesUsingCreationTime(DeleteOldData):
def get_eligible_cases(self):
+ super(FindAndDeleteCasesUsingCreationTime, self)._setup()
two_years = self.now - relativedelta(years=2)
return Case.objects.filter(created__lte=two_years).exclude(log__c... |
682fa674d63120c10b99b357e4370d3490ea234d | xanmel_web/settings/env/production.py | xanmel_web/settings/env/production.py | DEBUG = False
ALLOWED_HOSTS = ['xon.teichisma.info', 'portal.exe.pub']
| DEBUG = False
ALLOWED_HOSTS = ['xon.teichisma.info', 'portal.exe.pub', 'samovar.teichisma.info']
| Add samovar as allowed host | Add samovar as allowed host
| Python | agpl-3.0 | nsavch/xanmel-web | ---
+++
@@ -1,3 +1,3 @@
DEBUG = False
-ALLOWED_HOSTS = ['xon.teichisma.info', 'portal.exe.pub']
+ALLOWED_HOSTS = ['xon.teichisma.info', 'portal.exe.pub', 'samovar.teichisma.info'] |
a87d927acc42ba2fe4a82004ce919882024039a9 | kboard/board/forms.py | kboard/board/forms.py | from django import forms
from django.forms.utils import ErrorList
from django_summernote.widgets import SummernoteWidget
from .models import Post
EMPTY_TITLE_ERROR = "제목을 입력하세요"
EMPTY_CONTENT_ERROR = "내용을 입력하세요"
class DivErrorList(ErrorList):
def __str__(self):
return self.as_divs()
def as_divs(sel... | from django import forms
from django.forms.utils import ErrorList
from django_summernote.widgets import SummernoteWidget
from .models import Post
EMPTY_TITLE_ERROR = "제목을 입력하세요"
EMPTY_CONTENT_ERROR = "내용을 입력하세요"
class DivErrorList(ErrorList):
def __str__(self):
return self.as_divs()
def as_divs(sel... | Remove unnecessary attrs 'name' in title | Remove unnecessary attrs 'name' in title
| Python | mit | hyesun03/k-board,cjh5414/kboard,guswnsxodlf/k-board,hyesun03/k-board,darjeeling/k-board,cjh5414/kboard,kboard/kboard,kboard/kboard,kboard/kboard,guswnsxodlf/k-board,hyesun03/k-board,cjh5414/kboard,guswnsxodlf/k-board | ---
+++
@@ -23,7 +23,7 @@
model = Post
fields = ('title', 'content', 'file')
widgets = {
- 'title': forms.TextInput(attrs={'id': 'id_post_title', 'class': 'form-control', 'name': 'post_title_text', 'placeholder': 'Insert Title'}),
+ 'title': forms.TextInput(attrs={'id'... |
c39163bd6e91ca17f123c5919885b90105efc7c4 | SimPEG/Mesh/__init__.py | SimPEG/Mesh/__init__.py | from TensorMesh import TensorMesh
from CylMesh import CylMesh
from Cyl1DMesh import Cyl1DMesh
from LogicallyRectMesh import LogicallyRectMesh
from TreeMesh import TreeMesh
| from TensorMesh import TensorMesh
from CylMesh import CylMesh
from Cyl1DMesh import Cyl1DMesh
from LogicallyRectMesh import LogicallyRectMesh
from TreeMesh import TreeMesh
from BaseMesh import BaseMesh
| Add BaseMesh to the init file. | Add BaseMesh to the init file.
| Python | mit | simpeg/discretize,simpeg/simpeg,simpeg/discretize,simpeg/discretize | ---
+++
@@ -3,3 +3,4 @@
from Cyl1DMesh import Cyl1DMesh
from LogicallyRectMesh import LogicallyRectMesh
from TreeMesh import TreeMesh
+from BaseMesh import BaseMesh |
eba0a56f4334d95e37da3946a6a0b053dbe2e19f | tfx/orchestration/test_pipelines/custom_exit_handler.py | tfx/orchestration/test_pipelines/custom_exit_handler.py | # Copyright 2021 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | # Copyright 2021 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | Test fix for exit handler | Test fix for exit handler
PiperOrigin-RevId: 436937697
| Python | apache-2.0 | tensorflow/tfx,tensorflow/tfx | ---
+++
@@ -13,7 +13,7 @@
# limitations under the License.
"""Custom component for exit handler."""
-from tfx.orchestration.kubeflow.v2 import decorators
+from tfx.orchestration.kubeflow import decorators
from tfx.utils import io_utils
import tfx.v1 as tfx
@@ -23,4 +23,3 @@
file_dir: tf... |
a319691a057423a610d91521e2f569250117db09 | run_migrations.py | run_migrations.py | """
Run all migrations
"""
import imp
import os
import sys
import pymongo
from os.path import join
import logging
from backdrop.core.database import Database
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger(__name__)
ROOT_PATH = os.path.abspath(os.path.dirname(__file__))
def load_config(env):
co... | """
Run all migrations
"""
import imp
import os
import re
import sys
from os.path import join
import logging
from backdrop.core.database import Database
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger(__name__)
ROOT_PATH = os.path.abspath(os.path.dirname(__file__))
def load_config(env):
config_... | Allow specific migrations to be run | Allow specific migrations to be run
| Python | mit | alphagov/backdrop,alphagov/backdrop,alphagov/backdrop | ---
+++
@@ -3,8 +3,8 @@
"""
import imp
import os
+import re
import sys
-import pymongo
from os.path import join
import logging
from backdrop.core.database import Database
@@ -34,10 +34,10 @@
config.MONGO_HOSTS, config.MONGO_PORT, config.DATABASE_NAME)
-def get_migrations():
+def get_migrations(mig... |
ee649468df406877ccc51a1042e5657f11caa57d | oauthenticator/tests/test_openshift.py | oauthenticator/tests/test_openshift.py | from pytest import fixture, mark
from ..openshift import OpenShiftOAuthenticator
from .mocks import setup_oauth_mock
def user_model(username):
"""Return a user model"""
return {
'metadata': {
'name': username,
}
}
@fixture
def openshift_client(client):
setup_oauth_mock(... | from pytest import fixture, mark
from ..openshift import OpenShiftOAuthenticator
from .mocks import setup_oauth_mock
def user_model(username):
"""Return a user model"""
return {
'metadata': {
'name': username,
}
}
@fixture
def openshift_client(client):
setup_oauth_mock(... | Update test harness to use new REST API path for OpenShift. | Update test harness to use new REST API path for OpenShift.
| Python | bsd-3-clause | minrk/oauthenticator,NickolausDS/oauthenticator,jupyter/oauthenticator,jupyter/oauthenticator,maltevogl/oauthenticator,jupyterhub/oauthenticator | ---
+++
@@ -19,7 +19,7 @@
setup_oauth_mock(client,
host=['localhost'],
access_token_path='/oauth/token',
- user_path='/oapi/v1/users/~',
+ user_path='/apis/user.openshift.io/v1/users/~',
)
return client
|
60759f310f0354d4940c66f826e899bf4c2b76b4 | src/foremast/app/aws.py | src/foremast/app/aws.py | """AWS Spinnaker Application."""
from pprint import pformat
from foremast.app import base
from foremast.utils import wait_for_task
class SpinnakerApp(base.BaseApp):
"""Create AWS Spinnaker Application."""
provider = 'aws'
def create(self):
"""Send a POST to spinnaker to create a new application... | """AWS Spinnaker Application."""
from pprint import pformat
from foremast.app import base
from foremast.utils import wait_for_task
class SpinnakerApp(base.BaseApp):
"""Create AWS Spinnaker Application."""
provider = 'aws'
def create(self):
"""Send a POST to spinnaker to create a new application... | Return useful data from App creation | fix: Return useful data from App creation
| Python | apache-2.0 | gogoair/foremast,gogoair/foremast | ---
+++
@@ -24,7 +24,7 @@
wait_for_task(jsondata)
self.log.info("Successfully created %s application", self.appname)
- return
+ return jsondata
def delete(self):
"""Delete AWS Spinnaker Application.""" |
47970281f9cdf10f8429cfb88c7fffc3c9c27f2a | python/testData/inspections/PyArgumentListInspection/dictFromKeys.py | python/testData/inspections/PyArgumentListInspection/dictFromKeys.py | print(dict.fromkeys(<warning descr="Parameter 'seq' unfilled">)</warning>)
print(dict.fromkeys(['foo', 'bar']))
| print(dict.fromkeys(<warning descr="Parameter(s) unfilledPossible callees:dict.fromkeys(seq: Sequence[TypeVar('_T')])dict.fromkeys(seq: Sequence[TypeVar('_T')], value: TypeVar('_S'))">)</warning>)
print(dict.fromkeys(['foo', 'bar']))
| Fix test data for PyArgumentListInspectionTest.testDictFromKeys. | Fix test data for PyArgumentListInspectionTest.testDictFromKeys.
| Python | apache-2.0 | signed/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,da1z/intellij-community,allotria/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-communi... | ---
+++
@@ -1,2 +1,2 @@
-print(dict.fromkeys(<warning descr="Parameter 'seq' unfilled">)</warning>)
+print(dict.fromkeys(<warning descr="Parameter(s) unfilledPossible callees:dict.fromkeys(seq: Sequence[TypeVar('_T')])dict.fromkeys(seq: Sequence[TypeVar('_T')], value: TypeVar('_S'))">)</warning>)
print(dict.fromkeys... |
64d00e0c17855baaef6562c08f26f30b17ce38bf | panopticon/gtkvlc.py | panopticon/gtkvlc.py | """Container classes for VLC under GTK"""
import gtk
import sys
# pylint: disable-msg=R0904
class VLCSlave(gtk.DrawingArea):
"""VLCSlave provides a playback window with an underlying player
Its player can be controlled through the 'player' attribute, which
is a vlc.MediaPlayer() instance.
"""
def... | """Container classes for VLC under GTK"""
import gtk
import sys
# pylint: disable-msg=R0904
class VLCSlave(gtk.DrawingArea):
"""VLCSlave provides a playback window with an underlying player
Its player can be controlled through the 'player' attribute, which
is a vlc.MediaPlayer() instance.
"""
def... | Refactor and add playback funcs. | Refactor and add playback funcs.
| Python | agpl-3.0 | armyofevilrobots/Panopticon | ---
+++
@@ -27,3 +27,16 @@
return True
self.connect("map", handle_embed)
self.set_size_request(width, height)
+
+ def actions(self, action):
+ if hasattr(self.player, action):
+ return getattr(self.player, action)
+ else:
+ return lambda x: None
+
... |
d608ba0892da052f2515d6796e88013c0730dc0b | corehq/ex-submodules/auditcare/management/commands/gdpr_scrub_user_auditcare.py | corehq/ex-submodules/auditcare/management/commands/gdpr_scrub_user_auditcare.py | from __future__ import absolute_import
from __future__ import unicode_literals
from corehq.util.log import with_progress_bar
from corehq.util.couch import iter_update, DocUpdate
from django.core.management.base import BaseCommand
from auditcare.utils.export import navigation_event_ids_by_user
import logging
from auditc... | from __future__ import absolute_import
from __future__ import unicode_literals
from corehq.util.log import with_progress_bar
from corehq.util.couch import iter_update, DocUpdate
from django.core.management.base import BaseCommand
from auditcare.utils.export import navigation_event_ids_by_user
import logging
from auditc... | Update dict instead of doc | Update dict instead of doc
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -19,10 +19,8 @@
def handle(self, username, **options):
def update_username(event_dict):
- audit_doc = NavigationEventAudit.wrap(event_dict)
- audit_doc.user = new_username
event_dict['user'] = new_username
- return DocUpdate(doc=audit_doc)
+ ... |
a7ba0c94b656346ee1ceb4a34f62650898cc3428 | abe/document_models/label_documents.py | abe/document_models/label_documents.py | #!/usr/bin/env python3
"""Document models for mongoengine"""
from mongoengine import *
from bson import ObjectId
class Label(Document):
"""Model for labels of events"""
name = StringField(required=True, unique=True) # TODO: set to primary key?
description = StringField()
url = URLField()
| #!/usr/bin/env python3
"""Document models for mongoengine"""
from mongoengine import *
from bson import ObjectId
class Label(Document):
"""Model for labels of events"""
name = StringField(required=True, unique=True) # TODO: set to primary key?
description = StringField()
url = URLField()
default ... | Add new fields to label document | Add new fields to label document
- Make default default value False
| Python | agpl-3.0 | olinlibrary/ABE,olinlibrary/ABE,olinlibrary/ABE | ---
+++
@@ -9,3 +9,7 @@
name = StringField(required=True, unique=True) # TODO: set to primary key?
description = StringField()
url = URLField()
+ default = BooleanField(default=False) # suggested to display by default
+ parent_labels = ListField(StringField()) # rudimentary hierarchy of labels... |
a96eae8333104f11974f8944f93c66c0f70275d7 | telemetry/telemetry/core/platform/power_monitor/ippet_power_monitor_unittest.py | telemetry/telemetry/core/platform/power_monitor/ippet_power_monitor_unittest.py | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import unittest
from telemetry import decorators
from telemetry.core.platform import win_platform_backend
from telemetry.core.platform.power_... | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import unittest
from telemetry import decorators
from telemetry.core.platform import win_platform_backend
from telemetry.core.platform.power_... | Disable IppetPowerMonitorTest.testFindOrInstallIppet which is failing on new trybots. | Disable IppetPowerMonitorTest.testFindOrInstallIppet which is failing on new trybots.
BUG=424027
TBR=dtu@chromium.org
Review URL: https://codereview.chromium.org/643763005
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#299833}
| Python | bsd-3-clause | catapult-project/catapult,catapult-project/catapult-csm,sahiljain/catapult,benschmaus/catapult,SummerLW/Perf-Insight-Report,catapult-project/catapult-csm,catapult-project/catapult-csm,benschmaus/catapult,catapult-project/catapult,sahiljain/catapult,catapult-project/catapult-csm,SummerLW/Perf-Insight-Report,catapult-pro... | ---
+++
@@ -11,7 +11,7 @@
class IppetPowerMonitorTest(unittest.TestCase):
- @decorators.Enabled('win')
+ @decorators.Disabled
def testFindOrInstallIppet(self):
self.assertTrue(ippet_power_monitor.IppetPath())
|
8aa0813402f5083cb230ba3d457b76dafc371fe5 | cache_purge_hooks/backends/varnishbackend.py | cache_purge_hooks/backends/varnishbackend.py | import varnish
import logging
from django.conf import settings
#STUB config options here
VARNISH_HOST = settings.VARNISH_HOST
VARNISH_PORT = settings.VARNISH_PORT
VARNISH_DEBUG = settings.DEBUG
VARNISH_SITE_DOMAIN = ".*"
class VarnishManager(object):
def __init__(self):
self.handler = varnish.VarnishHandler([VAR... | import varnish
import logging
from django.conf import settings
#STUB config options here
VARNISH_HOST = settings.VARNISH_HOST
VARNISH_PORT = settings.VARNISH_PORT
VARNISH_DEBUG = settings.DEBUG
VARNISH_SECRET = settings.VARNISH_SECRET or None
VARNISH_SITE_DOMAIN = settings.VARNISH_SITE_DOMAIN or '.*'
class VarnishMan... | Add support for varnish backend secret and pass a domain when it's defined in settings | Add support for varnish backend secret and pass a domain when it's defined in settings
| Python | mit | RealGeeks/django-cache-purge-hooks,RealGeeks/django-cache-purge-hooks | ---
+++
@@ -5,14 +5,14 @@
#STUB config options here
VARNISH_HOST = settings.VARNISH_HOST
VARNISH_PORT = settings.VARNISH_PORT
-
VARNISH_DEBUG = settings.DEBUG
-
-VARNISH_SITE_DOMAIN = ".*"
+VARNISH_SECRET = settings.VARNISH_SECRET or None
+VARNISH_SITE_DOMAIN = settings.VARNISH_SITE_DOMAIN or '.*'
class Varnis... |
568dce643d9e88ebd9e5b395accb3027e02febb7 | backend/conferences/models/duration.py | backend/conferences/models/duration.py | from django.core.validators import MinValueValidator
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Duration(models.Model):
conference = models.ForeignKey(
"conferences.Conference",
on_delete=models.CASCADE,
verbose_name=_("conference"),
... | from django.core.validators import MinValueValidator
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Duration(models.Model):
conference = models.ForeignKey(
"conferences.Conference",
on_delete=models.CASCADE,
verbose_name=_("conference"),
... | Fix Duration.__str__ to show Conference name and code | Fix Duration.__str__ to show Conference name and code
| Python | mit | patrick91/pycon,patrick91/pycon | ---
+++
@@ -21,7 +21,10 @@
)
def __str__(self):
- return f"{self.name} - {self.duration} mins ({self.conference_id})"
+ return (
+ f"{self.name} - {self.duration} mins (at Conference "
+ f"{self.conference.name} <{self.conference.code}>)"
+ )
class Meta:
... |
f909d0a49e0e455e34673f2b6efc517bc76738d2 | build/fbcode_builder/specs/fbthrift.py | build/fbcode_builder/specs/fbthrift.py | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.rsocket as rsocket
import spec... | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.rsocket as rsocket
import spec... | Cut fbcode_builder dep for thrift on krb5 | Cut fbcode_builder dep for thrift on krb5
Summary: [Thrift] Cut `fbcode_builder` dep for `thrift` on `krb5`. In the past, Thrift depended on Kerberos and the `krb5` implementation for its transport-layer security. However, Thrift has since migrated fully to Transport Layer Security for its transport-layer security and... | Python | mit | facebook/bistro,facebook/bistro,facebook/bistro,facebook/bistro,facebook/bistro,facebook/bistro | ---
+++
@@ -21,15 +21,12 @@
'no1msd/mstch:git_hash',
ShellQuoted('$(git describe --abbrev=0 --tags)')
)
- builder.add_option('krb5/krb5:git_hash', 'krb5-1.16.1-final')
return {
'depends_on': [folly, fizz, sodium, rsocket, wangle, zstd],
'steps': [
# This i... |
ad042127cadc2fd779bdea4d6853102b5d8d0ad0 | api/tests/test_login.py | api/tests/test_login.py | import unittest
from api.test import BaseTestCase
class TestLogin(BaseTestCase):
@unittest.skip("")
def test_login(self):
login_credentials = {
"password": "qwerty@123",
"username": "EdwinKato"
}
response = self.client.post('/api/v1/auth/login',
... | import unittest
import json
from api.test import BaseTestCase
class TestLogin(BaseTestCase):
@unittest.skip("")
def test_login(self):
login_credentials = {
"password": "qwerty@123",
"username": "EdwinKato"
}
response = self.client.post('/api/v1/auth/login',
... | Add test for non-registered user | Add test for non-registered user
| Python | mit | EdwinKato/bucket-list,EdwinKato/bucket-list,EdwinKato/bucket-list,EdwinKato/bucket-list,EdwinKato/bucket-list | ---
+++
@@ -1,4 +1,5 @@
import unittest
+import json
from api.test import BaseTestCase
@@ -16,3 +17,21 @@
data=json.dumps(login_credentials),
content_type='application/json')
self.assertEqual(response.status_code, 200)
+
+
+def t... |
b9c175059f0f2f3321ffd495fd46c6f5770afd22 | bluebottle/payouts_dorado/adapters.py | bluebottle/payouts_dorado/adapters.py | import json
import requests
from django.core.exceptions import ImproperlyConfigured
from django.db import connection
from requests.exceptions import MissingSchema
from bluebottle.clients import properties
class PayoutValidationError(Exception):
pass
class PayoutCreationError(Exception):
pass
class Dorad... | import json
import requests
from django.core.exceptions import ImproperlyConfigured
from django.db import connection
from requests.exceptions import MissingSchema
from bluebottle.clients import properties
class PayoutValidationError(Exception):
pass
class PayoutCreationError(Exception):
pass
class Dorad... | Set the payout status to created BEFORE we call out to dorado. This way we do not override that status that dorado set. | Set the payout status to created BEFORE we call out to dorado. This way
we do not override that status that dorado set.
BB-9471 #resolve
| Python | bsd-3-clause | onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle | ---
+++
@@ -31,11 +31,11 @@
}
try:
+ self.project.payout_status = 'created'
+ self.project.save()
+
response = requests.post(self.settings['url'], data)
response.raise_for_status()
-
- self.project.payout_status = 'created'
- se... |
a9052428e1eee8ec566bd496e1247dae0873d9c9 | test/wordfilter_test.py | test/wordfilter_test.py | import nose
from lib.wordfilter import Wordfilter
# Run with `python -m test.wordfilter_test`
class Wordfilter_test:
def setup(self):
self.wordfilter = Wordfilter()
def teardown(self):
self.wordfilter = []
def test_loading(self):
assert type(self.wordfilter.blacklist) is list
def test_badWords(s... | import nose
from lib.wordfilter import Wordfilter
# Run with `python -m test.wordfilter_test`
class Wordfilter_test:
def setup(self):
self.wordfilter = Wordfilter()
def teardown(self):
self.wordfilter = []
def test_loading(self):
assert type(self.wordfilter.blacklist) is list
def test_badWords(s... | Add another test case - add multiple words | Add another test case - add multiple words
| Python | mit | dariusk/wordfilter,dariusk/wordfilter,mwatson/wordfilter,hugovk/wordfilter,mwatson/wordfilter,dariusk/wordfilter,hugovk/wordfilter,mwatson/wordfilter,hugovk/wordfilter,dariusk/wordfilter,hugovk/wordfilter,mwatson/wordfilter | ---
+++
@@ -25,11 +25,23 @@
assert self.wordfilter.blacklisted('this string is clean!')
def test_clearList(self):
- self.wordfilter.clearList();
+ self.wordfilter.clearList()
assert not self.wordfilter.blacklisted('this string contains the word skank')
self.wordfilter.addWords(['skank'])
... |
0a6072621570464522cbfa6d939dffccc0fa6503 | spacy/cli/converters/iob2json.py | spacy/cli/converters/iob2json.py | # coding: utf8
from __future__ import unicode_literals
import cytoolz
from ...gold import iob_to_biluo
def iob2json(input_data, n_sents=10, *args, **kwargs):
"""
Convert IOB files into JSON format for use with train cli.
"""
docs = []
for group in cytoolz.partition_all(n_sents, docs):
gr... | # coding: utf8
from __future__ import unicode_literals
from ...gold import iob_to_biluo
from ...util import minibatch
def iob2json(input_data, n_sents=10, *args, **kwargs):
"""
Convert IOB files into JSON format for use with train cli.
"""
docs = []
for group in minibatch(docs, n_sents):
... | Remove cytoolz usage in CLI | Remove cytoolz usage in CLI
| Python | mit | explosion/spaCy,spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spaCy,explosion/spaCy,honnibal/spaCy,explosion/spaCy,spacy-io/spaCy,explosion/spaCy,spacy-io/spaCy,honnibal/spaCy,explosion/spaCy,honnibal/spaCy | ---
+++
@@ -1,9 +1,8 @@
# coding: utf8
from __future__ import unicode_literals
-import cytoolz
-
from ...gold import iob_to_biluo
+from ...util import minibatch
def iob2json(input_data, n_sents=10, *args, **kwargs):
@@ -11,7 +10,7 @@
Convert IOB files into JSON format for use with train cli.
"""
... |
fb837585264e6abe4b0488e3a9dd5c5507e69bf6 | tensorflow/python/distribute/__init__.py | tensorflow/python/distribute/__init__.py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | Fix asan test for various targets. | PSv2: Fix asan test for various targets.
PiperOrigin-RevId: 325441069
Change-Id: I1fa1b2b10670f34739323292eab623d5b538142e
| Python | apache-2.0 | aam-at/tensorflow,cxxgtxy/tensorflow,frreiss/tensorflow-fred,paolodedios/tensorflow,paolodedios/tensorflow,karllessard/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-Corporation/tensorflow,aldian/tensorflow,sarvex/tensorflow,aldian/tensorflow,davidzchen/tensorflow,ten... | ---
+++
@@ -25,7 +25,6 @@
from tensorflow.python.distribute import distribution_strategy_context
from tensorflow.python.distribute import mirrored_strategy
from tensorflow.python.distribute import one_device_strategy
-from tensorflow.python.distribute.client import parameter_server_client
from tensorflow.python.d... |
35fe7bb6411c8009253bf66fb7739a5d49a7028d | scuole/counties/management/commands/bootstrapcounties.py | scuole/counties/management/commands/bootstrapcounties.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import csv
import os
from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils.text import slugify
from ...models import County
from scuole.states.models import State
class Command(BaseComm... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import csv
import os
from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils.text import slugify
from ...models import County
from scuole.states.models import State
class Command(BaseComm... | Add feedback during county loader | Add feedback during county loader
| Python | mit | texastribune/scuole,texastribune/scuole,texastribune/scuole,texastribune/scuole | ---
+++
@@ -32,6 +32,9 @@
County.objects.bulk_create(counties)
def create_county(self, county):
+ self.stdout.write(
+ 'Creating {} County...'.format(county['County Name']))
+
return County(
name=county['County Name'],
slug=slugify(county['Count... |
4e2cbe770161e9d88acb68e95698b4ec184be7e0 | tests/testapp/manage.py | tests/testapp/manage.py | #!/usr/bin/env python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to ... | #!/usr/bin/env python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to ... | Make sure current dynamic_choices module has priority over possible installed one for tests. | Make sure current dynamic_choices module has priority over possible installed one for tests.
| Python | mit | charettes/django-dynamic-choices,charettes/django-dynamic-choices,charettes/django-dynamic-choices | ---
+++
@@ -11,7 +11,7 @@
import dynamic_admin #@UnusedImport
except ImportError:
import sys, os
- sys.path.append(os.path.abspath('%s/../..' % os.getcwd()))
+ sys.path.insert(0, os.path.abspath('%s/../..' % os.getcwd()))
if __name__ == "__main__":
execute_manager(settings) |
388d6feb2703b1badb3cb194b58deff831681a0a | toga_cocoa/widgets/progressbar.py | toga_cocoa/widgets/progressbar.py | from __future__ import print_function, absolute_import, division, unicode_literals
from ..libs import *
from .base import Widget
class ProgressBar(Widget):
def __init__(self, max=None, value=None, **style):
super(ProgressBar, self).__init__(**style)
self.max = max
self.startup()
... | from __future__ import print_function, absolute_import, division, unicode_literals
from ..libs import *
from .base import Widget
class ProgressBar(Widget):
def __init__(self, max=None, value=None, **style):
super(ProgressBar, self).__init__(**style)
self.max = max
self.startup()
... | Make progress bar visible by default. | Make progress bar visible by default.
| Python | bsd-3-clause | pybee-attic/toga-cocoa,pybee/toga-cocoa | ---
+++
@@ -16,7 +16,7 @@
def startup(self):
self._impl = NSProgressIndicator.new()
self._impl.setStyle_(NSProgressIndicatorBarStyle)
- self._impl.setDisplayedWhenStopped_(False)
+ self._impl.setDisplayedWhenStopped_(True)
if self.max:
self._impl.setIndetermi... |
63241b7fb62166f4a31ef7ece38edf8b36129f63 | dictionary/management/commands/writeLiblouisTables.py | dictionary/management/commands/writeLiblouisTables.py | from daisyproducer.dictionary.brailleTables import writeWhiteListTables, writeLocalTables
from daisyproducer.dictionary.models import Word
from daisyproducer.documents.models import Document
from django.core.management.base import BaseCommand
class Command(BaseCommand):
args = ''
help = 'Write Liblouis tables ... | from daisyproducer.dictionary.brailleTables import writeWhiteListTables, writeLocalTables
from daisyproducer.dictionary.models import Word
from daisyproducer.documents.models import Document
from django.core.management.base import BaseCommand
class Command(BaseCommand):
args = ''
help = 'Write Liblouis tables ... | Make sure the verbosity stuff actually works | Make sure the verbosity stuff actually works
| Python | agpl-3.0 | sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer | ---
+++
@@ -9,10 +9,11 @@
def handle(self, *args, **options):
# write new global white lists
- if options['verbosity'] >= 2:
+ verbosity = int(options['verbosity'])
+ if verbosity >= 2:
self.stderr.write('Writing new global white lists...\n')
writeWhiteListTa... |
69ade2e8dfcaac3769d0b75929eb89cf3e775a74 | tests/unit/test_util.py | tests/unit/test_util.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import os
from ava.util import time_uuid, base_path, defines, misc
class TestTimeUUID(object):
def test_uuids_should_be_in_alaphabetical_order(self):
old = time_uuid.oid()
for i in range(10... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import os
from ava.util import time_uuid, base_path, defines, misc
class TestTimeUUID(object):
def test_uuids_should_be_in_alaphabetical_order(self):
old = time_uuid.oid()
for i in range(10... | Fix issue in get_app_dir() test which is caused by platfrom-dependent problem | Fix issue in get_app_dir() test which is caused by platfrom-dependent problem
| Python | apache-2.0 | eavatar/eavatar-me,eavatar/eavatar-me,eavatar/eavatar-me,eavatar/eavatar-me | ---
+++
@@ -30,7 +30,7 @@
def test_get_app_dir():
app_dir = misc.get_app_dir('TestApp')
- assert 'TestApp' in app_dir
+ assert 'TestApp'.lower() in app_dir.lower()
def test_get_app_dir_via_env(): |
d8af86a0fedb8e7225e5ad97f69cd40c9c2abd8f | nimp/commands/cis_wwise_build_banks.py | nimp/commands/cis_wwise_build_banks.py | # -*- coding: utf-8 -*-
from nimp.commands._cis_command import *
from nimp.utilities.wwise import *
#-------------------------------------------------------------------------------
class BuildWwiseBanksCommand(CisCommand):
abstract = 0
#-------------------------------------------------------------------------... | # -*- coding: utf-8 -*-
from nimp.commands._cis_command import *
from nimp.utilities.wwise import *
#-------------------------------------------------------------------------------
class BuildWwiseBanksCommand(CisCommand):
abstract = 0
#-------------------------------------------------------------------------... | Replace "<platform>" with "-p <platform>" in CIS wwise command. | Replace "<platform>" with "-p <platform>" in CIS wwise command.
This is what the Buildbot configuration uses, and it makes sense. It
used to not break because we were ignoring unknown commandline flags.
| Python | mit | dontnod/nimp | ---
+++
@@ -12,9 +12,10 @@
#---------------------------------------------------------------------------
def cis_configure_arguments(self, env, parser):
- parser.add_argument('platform',
+ parser.add_argument('-p',
+ '--platform',
help ... |
99c0804edebd94e0054e324833028ba450806f7f | documentchain/server.py | documentchain/server.py | from flask import Flask, jsonify, request
from .chain import DocumentChain
from .storage import DiskStorage
app = Flask(__name__)
chain = DocumentChain(DiskStorage('data/'))
@app.route('/entries', methods=['GET', 'POST'])
def entries():
if request.method == 'POST':
if not request.json:
return ... | from flask import Flask, jsonify, request
from .chain import DocumentChain
from .storage import DiskStorage
app = Flask(__name__)
chain = DocumentChain(DiskStorage('data/'))
@app.route('/entries', methods=['GET', 'POST'])
def entry_list():
if request.method == 'POST':
if not request.json:
retu... | Add entry detail HTTP endpoint | Add entry detail HTTP endpoint
| Python | mit | LandRegistry-Attic/concept-system-of-record,LandRegistry-Attic/concept-system-of-record,LandRegistry-Attic/concept-system-of-record | ---
+++
@@ -6,7 +6,7 @@
chain = DocumentChain(DiskStorage('data/'))
@app.route('/entries', methods=['GET', 'POST'])
-def entries():
+def entry_list():
if request.method == 'POST':
if not request.json:
return '', 400
@@ -16,3 +16,8 @@
return res
else:
return jsonif... |
581f16e30aeb465f80fd28a77404b0375bd197d4 | code/python/knub/thesis/topic_model.py | code/python/knub/thesis/topic_model.py | import logging, gensim, bz2
from knub.thesis.util.memory import limit_memory
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
def main():
logging.info("Starting Wikipedia LDA")
# limit memory to 32 GB
limit_memory(32000)
id2word = gensim.corpora.Dictionary.l... | import logging, gensim, bz2
import mkl
from knub.thesis.util.memory import limit_memory
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
mkl.set_num_threads(8)
def main():
logging.info("Starting Wikipedia LDA")
# limit memory to 32 GB
limit_memory(32000)
id2... | Set max threads for MKL. | Set max threads for MKL.
| Python | apache-2.0 | knub/master-thesis,knub/master-thesis,knub/master-thesis,knub/master-thesis | ---
+++
@@ -1,7 +1,9 @@
import logging, gensim, bz2
+import mkl
from knub.thesis.util.memory import limit_memory
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
+mkl.set_num_threads(8)
def main():
logging.info("Starting Wikipedia LDA") |
d000a2e3991c54b319bc7166d9d178b739170a46 | polling_stations/apps/data_collection/management/commands/import_sheffield.py | polling_stations/apps/data_collection/management/commands/import_sheffield.py | """
Import Sheffield
"""
from data_collection.management.commands import BaseShpShpImporter
class Command(BaseShpShpImporter):
"""
Imports the Polling Station data from Sheffield
"""
council_id = 'E08000019'
districts_name = 'SCCPollingDistricts2015'
stations_name = 'SCCPollingStations2015... | """
Import Sheffield
"""
from data_collection.management.commands import BaseShpShpImporter
class Command(BaseShpShpImporter):
"""
Imports the Polling Station data from Sheffield
"""
council_id = 'E08000019'
districts_name = 'SCCPollingDistricts2015'
stations_name = 'SCCPollingStations2015... | Add polling_district_id in Sheffield import script | Add polling_district_id in Sheffield import script
| Python | bsd-3-clause | DemocracyClub/UK-Polling-Stations,andylolz/UK-Polling-Stations,andylolz/UK-Polling-Stations,andylolz/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations,chris48s/UK-Polling-Stations | ---
+++
@@ -13,8 +13,9 @@
def district_record_to_dict(self, record):
return {
- 'internal_council_id': record[0],
- 'name': record[1],
+ 'internal_council_id': record[1],
+ 'extra_id': record[0],
+ 'name': record[1],
... |
4f351f34f3a0d5d2870639bb972d41b459595704 | settei/version.py | settei/version.py | """:mod:`settei.version` --- Version data
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. versionadded:: 0.2.0
"""
#: (:class:`typing.Tuple`\ [:class:`int`, :class:`int`, :class:`int`])
#: The triple of version numbers e.g. ``(1, 2, 3)``.
VERSION_INFO = (0, 5, 3)
#: (:class:`str`) The version string e.g. ``'1.2.3'``.
... | """:mod:`settei.version` --- Version data
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. versionadded:: 0.2.0
"""
#: (:class:`typing.Tuple`\ [:class:`int`, :class:`int`, :class:`int`])
#: The triple of version numbers e.g. ``(1, 2, 3)``.
VERSION_INFO = (0, 5, 2)
#: (:class:`str`) The version string e.g. ``'1.2.3'``.
... | Revert "Bump up to 0.5.3" | Revert "Bump up to 0.5.3"
This reverts commit bc8e02970ee80a6cd0a57f4fe1553cc8faf092dc.
| Python | apache-2.0 | spoqa/settei | ---
+++
@@ -7,7 +7,7 @@
#: (:class:`typing.Tuple`\ [:class:`int`, :class:`int`, :class:`int`])
#: The triple of version numbers e.g. ``(1, 2, 3)``.
-VERSION_INFO = (0, 5, 3)
+VERSION_INFO = (0, 5, 2)
#: (:class:`str`) The version string e.g. ``'1.2.3'``.
VERSION = '{}.{}.{}'.format(*VERSION_INFO) |
c1330851105df14367bec5ed87fc3c45b71932fd | project_euler/solutions/problem_35.py | project_euler/solutions/problem_35.py | from typing import List
from ..library.sqrt import fsqrt
from ..library.number_theory.primes import is_prime, prime_sieve
def is_circular_prime(n: int, sieve: List[int]) -> bool:
for i in range(len(str(n))):
if not is_prime(int(str(n)[i:] + str(n)[:i]), sieve):
return False
print(n)
... | from typing import List
from ..library.base import number_to_list, list_to_number
from ..library.sqrt import fsqrt
from ..library.number_theory.primes import is_prime, prime_sieve
def is_circular_prime(n: int, sieve: List[int]) -> bool:
rep_n = number_to_list(n)
for i in range(len(rep_n)):
if not is... | Make 35 use number_to_list and inverse | Make 35 use number_to_list and inverse
| Python | mit | cryvate/project-euler,cryvate/project-euler | ---
+++
@@ -1,13 +1,15 @@
from typing import List
-
+from ..library.base import number_to_list, list_to_number
from ..library.sqrt import fsqrt
from ..library.number_theory.primes import is_prime, prime_sieve
def is_circular_prime(n: int, sieve: List[int]) -> bool:
- for i in range(len(str(n))):
- ... |
299fadcde71558bc1e77ba396cc544619373c2b1 | conditional/blueprints/spring_evals.py | conditional/blueprints/spring_evals.py | from flask import Blueprint
from flask import render_template
from flask import request
spring_evals_bp = Blueprint('spring_evals_bp', __name__)
@spring_evals_bp.route('/spring_evals/')
def display_spring_evals():
# get user data
user_name = request.headers.get('x-webauth-user')
members = [
... | from flask import Blueprint
from flask import render_template
from flask import request
spring_evals_bp = Blueprint('spring_evals_bp', __name__)
@spring_evals_bp.route('/spring_evals/')
def display_spring_evals():
# get user data
user_name = request.headers.get('x-webauth-user')
members = [
... | Add social events to spring evals 😿 | Add social events to spring evals 😿
| Python | mit | RamZallan/conditional,ComputerScienceHouse/conditional,RamZallan/conditional,ComputerScienceHouse/conditional,RamZallan/conditional,ComputerScienceHouse/conditional | ---
+++
@@ -17,6 +17,7 @@
'house_meetings_missed': [{'date': "aprial fools fayas ads", 'reason': "I was playing videogames"}],
'major_project': 'open_container',
'major_project_passed': True,
+ 'social_events': "",
... |
8194f327032c064fe71ba3dc918e28ee2a586b12 | sqlalchemy_mixins/serialize.py | sqlalchemy_mixins/serialize.py | from collections.abc import Iterable
from .inspection import InspectionMixin
class SerializeMixin(InspectionMixin):
"""Mixin to make model serializable."""
__abstract__ = True
def to_dict(self,nested = False, hybrid_attributes = False, exclude = None):
"""Return dict object with model's data.
... | from collections.abc import Iterable
from .inspection import InspectionMixin
class SerializeMixin(InspectionMixin):
"""Mixin to make model serializable."""
__abstract__ = True
def to_dict(self,nested = False, hybrid_attributes = False, exclude = None):
"""Return dict object with model's data.
... | Check if relation objects are class of SerializeMixin | Check if relation objects are class of SerializeMixin
| Python | mit | absent1706/sqlalchemy-mixins | ---
+++
@@ -37,6 +37,9 @@
if isinstance(obj, SerializeMixin):
result[key] = obj.to_dict(hybrid_attributes=hybrid_attributes)
elif isinstance(obj, Iterable):
- result[key] = [o.to_dict(hybrid_attributes=hybrid_attributes) for o in obj]
+ ... |
5a6c8b1c9c13078462bec7ba254c6a6f95dd3c42 | contrib/linux/tests/test_action_dig.py | contrib/linux/tests/test_action_dig.py | #!/usr/bin/env python
# Copyright 2020 The StackStorm Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | #!/usr/bin/env python
# Copyright 2020 The StackStorm Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | Test that returned result is a str instance | Test that returned result is a str instance
| Python | apache-2.0 | nzlosh/st2,StackStorm/st2,StackStorm/st2,Plexxi/st2,Plexxi/st2,Plexxi/st2,StackStorm/st2,StackStorm/st2,nzlosh/st2,nzlosh/st2,Plexxi/st2,nzlosh/st2 | ---
+++
@@ -35,3 +35,7 @@
queryopts='')
self.assertIsInstance(result, list)
self.assertGreater(len(result), 0)
+
+ first_result = result[0]
+ self.assertIsInstance(first_result, str)
+ self.assertGreater(len(first_result)) |
0ba7c20f3ddea73f8d1f92c66b3ab0abf1ea8861 | asciimatics/__init__.py | asciimatics/__init__.py | __author__ = 'Peter Brittain'
from .version import version
__version__ = version
| __author__ = 'Peter Brittain'
try:
from .version import version
except ImportError:
# Someone is running straight from the GIT repo - dummy out the version
version = "0.0.0"
__version__ = version
| Patch up version for direct running of code in repo. | Patch up version for direct running of code in repo.
| Python | apache-2.0 | peterbrittain/asciimatics,peterbrittain/asciimatics | ---
+++
@@ -1,4 +1,9 @@
__author__ = 'Peter Brittain'
-from .version import version
+try:
+ from .version import version
+except ImportError:
+ # Someone is running straight from the GIT repo - dummy out the version
+ version = "0.0.0"
+
__version__ = version |
4f24071185140ef98167e470dbac97dcdfc65b90 | via/requests_tools/error_handling.py | via/requests_tools/error_handling.py | """Helpers for capturing requests exceptions."""
from functools import wraps
from requests import RequestException, exceptions
from via.exceptions import BadURL, UnhandledException, UpstreamServiceError
REQUESTS_BAD_URL = (
exceptions.MissingSchema,
exceptions.InvalidSchema,
exceptions.InvalidURL,
e... | """Helpers for capturing requests exceptions."""
from functools import wraps
from requests import RequestException, exceptions
from via.exceptions import BadURL, UnhandledException, UpstreamServiceError
REQUESTS_BAD_URL = (
exceptions.MissingSchema,
exceptions.InvalidSchema,
exceptions.InvalidURL,
e... | Fix error handling to show error messages | Fix error handling to show error messages
We removed this during a refactor, but it means we get very generic
messages in the UI instead of the actual error string.
| Python | bsd-2-clause | hypothesis/via,hypothesis/via,hypothesis/via | ---
+++
@@ -20,6 +20,10 @@
)
+def _get_message(err):
+ return err.args[0] if err.args else None
+
+
def handle_errors(inner):
"""Translate errors into our application errors."""
@@ -29,13 +33,13 @@
return inner(*args, **kwargs)
except REQUESTS_BAD_URL as err:
- raise... |
a0aab3a12cae251cbdef3f1da4aadcad930ef975 | telemetry/telemetry/internal/backends/chrome_inspector/inspector_console_unittest.py | telemetry/telemetry/internal/backends/chrome_inspector/inspector_console_unittest.py | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import absolute_import
import re
from telemetry.testing import tab_test_case
import py_utils
class TabConsoleTest(tab_test_case.TabTestCa... | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import absolute_import
import re
from telemetry.testing import tab_test_case
import py_utils
class TabConsoleTest(tab_test_case.TabTestCa... | Increase timeout in TabConsoleTest.testConsoleOutputStream twice. | Increase timeout in TabConsoleTest.testConsoleOutputStream twice.
On machines with low performance this test can fail by timeout.
Increasing timeout improves stability of this unittest passing.
Change-Id: I83a97022bbf96a4aaca349211ae7cfb9d19359b1
Reviewed-on: https://chromium-review.googlesource.com/c/catapult/+/2909... | Python | bsd-3-clause | catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult | ---
+++
@@ -18,7 +18,7 @@
def GotLog():
current = self._tab.EvaluateJavaScript('window.__logCount')
return current > initial
- py_utils.WaitFor(GotLog, 5)
+ py_utils.WaitFor(GotLog, 10)
console_output = (
self._tab._inspector_backend.GetCurrentConsoleOutputBuffer()) |
7ab465aaaf69ba114b3411204dd773781a147c41 | longclaw/project_template/products/models.py | longclaw/project_template/products/models.py | from django.db import models
from wagtail.wagtailcore.fields import RichTextField
from longclaw.longclawproducts.models import ProductVariantBase
class ProductVariant(ProductVariantBase):
# Enter your custom product variant fields here
# e.g. colour, size, stock and so on.
# Remember, ProductVariantBase p... | from django.db import models
from wagtail.wagtailcore.fields import RichTextField
from longclaw.longclawproducts.models import ProductVariantBase
class ProductVariant(ProductVariantBase):
# Enter your custom product variant fields here
# e.g. colour, size, stock and so on.
# Remember, ProductVariantBase p... | Remove 'stock' field from template products | Remove 'stock' field from template products
| Python | mit | JamesRamm/longclaw,JamesRamm/longclaw,JamesRamm/longclaw,JamesRamm/longclaw | ---
+++
@@ -9,4 +9,3 @@
# Remember, ProductVariantBase provides 'price', 'ref', 'slug' fields
# and the parental key to the Product model.
description = RichTextField()
- stock = models.IntegerField(default=0) |
0feb1810b1e3ca61ef15deb71aec9fd1eab3f2da | py101/introduction/__init__.py | py101/introduction/__init__.py | """"
Introduction Adventure
Author: Ignacio Avas (iavas@sophilabs.com)
"""
import codecs
import io
import sys
import unittest
from story.adventures import AdventureVerificationError, BaseAdventure
from story.translation import gettext as _
class TestOutput(unittest.TestCase):
"Introduction Adventure test"
de... | """"
Introduction Adventure
Author: Ignacio Avas (iavas@sophilabs.com)
"""
import codecs
import io
import sys
import unittest
from story.adventures import AdventureVerificationError, BaseAdventure
from story.translation import gettext as _
class TestOutput(unittest.TestCase):
"Introduction Adventure test"
de... | Refactor introduction to make it the same as the other tests | Refactor introduction to make it the same as the other tests
| Python | mit | sophilabs/py101 | ---
+++
@@ -13,10 +13,11 @@
class TestOutput(unittest.TestCase):
"Introduction Adventure test"
- def __init__(self, sourcefile):
- "Inits the test"
+ def __init__(self, candidate_code, file_name='<inline>'):
+ """Init the test"""
super(TestOutput, self).__init__()
- self.so... |
8c159ee5fa6aa1d10cef2268a373b90f6cb72896 | px/px_loginhistory.py | px/px_loginhistory.py | def get_users_at(timestamp, last_output=None, now=None):
"""
Return a set of strings corresponding to which users were logged in from
which addresses at a given timestamp.
Optional argument last_output is the output of "last". Will be filled in by
actually executing "last" if not provided.
Opt... | import sys
import re
USERNAME_PART = "([^ ]+)"
DEVICE_PART = "([^ ]+)"
ADDRESS_PART = "([^ ]+)?"
FROM_PART = "(.*)"
DASH_PART = " . "
TO_PART = "(.*)"
DURATION_PART = "([0-9+:]+)"
LAST_RE = re.compile(
USERNAME_PART +
" +" +
DEVICE_PART +
" +" +
ADDRESS_PART +
" +" +
FROM_PART +
DASH_PART +
TO_PART ... | Create regexp to match at least some last lines | Create regexp to match at least some last lines
| Python | mit | walles/px,walles/px | ---
+++
@@ -1,3 +1,30 @@
+import sys
+
+import re
+
+USERNAME_PART = "([^ ]+)"
+DEVICE_PART = "([^ ]+)"
+ADDRESS_PART = "([^ ]+)?"
+FROM_PART = "(.*)"
+DASH_PART = " . "
+TO_PART = "(.*)"
+DURATION_PART = "([0-9+:]+)"
+LAST_RE = re.compile(
+ USERNAME_PART +
+ " +" +
+ DEVICE_PART +
+ " +" +
+ ADDRESS_PART +
+ ... |
daca2bb7810b4c8eaf9f6a0598d8c6b41e0f2e10 | froide_theme/settings.py | froide_theme/settings.py | # -*- coding: utf-8 -*-
from froide.settings import Base, ThemeBase, HerokuPostmark, HerokuPostmarkS3 # noqa
class CustomThemeBase(ThemeBase):
FROIDE_THEME = 'froide_theme.theme'
SITE_NAME = "My Froide"
SITE_EMAIL = "info@example.com"
SITE_URL = 'http://localhost:8000'
SECRET_URLS = {
"... | # -*- coding: utf-8 -*-
import os
from froide.settings import Base, ThemeBase, HerokuPostmark, HerokuPostmarkS3 # noqa
class CustomThemeBase(ThemeBase):
FROIDE_THEME = 'froide_theme.theme'
SITE_NAME = "My Froide"
SITE_EMAIL = "info@example.com"
SITE_URL = 'http://localhost:8000'
SECRET_URLS = ... | Add own locale directory to LOCALE_PATHS | Add own locale directory to LOCALE_PATHS | Python | mit | CodeforHawaii/uipa_org,CodeforHawaii/uipa_org,CodeforHawaii/uipa_org,okfde/froide-theme | ---
+++
@@ -1,4 +1,6 @@
# -*- coding: utf-8 -*-
+import os
+
from froide.settings import Base, ThemeBase, HerokuPostmark, HerokuPostmarkS3 # noqa
@@ -12,6 +14,14 @@
SECRET_URLS = {
"admin": "admin",
}
+
+ @property
+ def LOCALE_PATHS(self):
+ return list(super(CustomThemeBase, s... |
fb22d49ca3ef41a22a5bb68261c77f24d6d39f7b | froide/helper/search.py | froide/helper/search.py | from haystack.fields import NgramField
try:
from .elasticsearch import SuggestField
except ImportError:
class SuggestField(NgramField):
pass
class SearchQuerySetWrapper(object):
"""
Decorates a SearchQuerySet object using a generator for efficient iteration
"""
def __init__(self, sqs... | from haystack.fields import NgramField
try:
from .elasticsearch import SuggestField
except ImportError:
class SuggestField(NgramField):
pass
class SearchQuerySetWrapper(object):
"""
Decorates a SearchQuerySet object using a generator for efficient iteration
"""
def __init__(self, sqs... | Fix object access on None | Fix object access on None | Python | mit | fin/froide,stefanw/froide,fin/froide,fin/froide,stefanw/froide,stefanw/froide,fin/froide,stefanw/froide,stefanw/froide | ---
+++
@@ -21,7 +21,8 @@
def __iter__(self):
for result in self.sqs:
- yield result.object
+ if result is not None:
+ yield result.object
def __getitem__(self, key):
if isinstance(key, int) and (key >= 0 or key < self.count()): |
3203d685479ba3803a81bd2101afa7f5bced754d | rplugin/python3/deoplete/sources/go.py | rplugin/python3/deoplete/sources/go.py | import deoplete.util
from .base import Base
class Source(Base):
def __init__(self, vim):
Base.__init__(self, vim)
self.name = 'go'
self.mark = '[go]'
self.filetypes = ['go']
self.min_pattern_length = 0
self.is_bytepos = True
def get_complete_api(self, findstar... | import deoplete.util
from .base import Base
class Source(Base):
def __init__(self, vim):
Base.__init__(self, vim)
self.name = 'go'
self.mark = '[go]'
self.filetypes = ['go']
self.input_pattern = '[^. \t0-9]\.\w*'
self.is_bytepos = True
def get_complete_api(sel... | Add input_pattern instead of min_pattern_length | Add input_pattern instead of min_pattern_length
Signed-off-by: Koichi Shiraishi <13fbd79c3d390e5d6585a21e11ff5ec1970cff0c@zchee.io>
| Python | mit | zchee/deoplete-go,zchee/deoplete-go | ---
+++
@@ -9,7 +9,7 @@
self.name = 'go'
self.mark = '[go]'
self.filetypes = ['go']
- self.min_pattern_length = 0
+ self.input_pattern = '[^. \t0-9]\.\w*'
self.is_bytepos = True
def get_complete_api(self, findstart): |
cb73b357d50603a1bce1184b28266fb55a4fd4ae | django_ethereum_events/web3_service.py | django_ethereum_events/web3_service.py | from django.conf import settings
from web3 import HTTPProvider, Web3
from web3.middleware import geth_poa_middleware
from .utils import Singleton
class Web3Service(metaclass=Singleton):
"""Creates a `web3` instance based on the given Provider."""
def __init__(self, *args, **kwargs):
"""Initializes ... | from django.conf import settings
from web3 import HTTPProvider, Web3
from web3.middleware import geth_poa_middleware
from .utils import Singleton
class Web3Service(metaclass=Singleton):
"""Creates a `web3` instance based on the given Provider."""
def __init__(self, *args, **kwargs):
"""Initializes t... | Change env variables for node setup to single URI varieable | Change env variables for node setup to single URI varieable
| Python | mit | artemistomaras/django-ethereum-events,artemistomaras/django-ethereum-events | ---
+++
@@ -1,5 +1,4 @@
from django.conf import settings
-
from web3 import HTTPProvider, Web3
from web3.middleware import geth_poa_middleware
@@ -19,11 +18,7 @@
if not rpc_provider:
timeout = getattr(settings, "ETHEREUM_NODE_TIMEOUT", 10)
- uri = "{scheme}://{host}:{port}".for... |
ee3428d98d9cf322233ac9abfa9cd81513b530e0 | medical_medicament_us/__manifest__.py | medical_medicament_us/__manifest__.py | # -*- coding: utf-8 -*-
# © 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
'name': 'Medical Medicament - US Locale',
'version': '10.0.1.0.0',
'author': "LasLabs, Odoo Community Association (OCA)",
'category': 'Medical',
'depends': [
'medical_base_u... | # -*- coding: utf-8 -*-
# © 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
'name': 'Medical Medicament - US Locale',
'version': '10.0.1.0.0',
'author': "LasLabs, Odoo Community Association (OCA)",
'category': 'Medical',
'depends': [
'medical_base_u... | Add missing dependency * medical.medicament.ndc relates to medical.manufacturer, which does not exist without it defined as a dependency. | [FIX] medical_medicament_us: Add missing dependency
* medical.medicament.ndc relates to medical.manufacturer, which does not exist without it defined as a dependency.
| Python | agpl-3.0 | laslabs/vertical-medical,laslabs/vertical-medical | ---
+++
@@ -11,6 +11,7 @@
'depends': [
'medical_base_us',
'medical_medication',
+ 'medical_manufacturer',
],
'website': 'https://laslabs.com',
'license': 'AGPL-3', |
ca6a8f554dcde5e570a61459da63ff9037dfceae | cumulusci/tasks/tests/test_apexdoc.py | cumulusci/tasks/tests/test_apexdoc.py | import mock
import re
import unittest
from cumulusci.core.config import BaseGlobalConfig
from cumulusci.core.config import BaseProjectConfig
from cumulusci.core.config import TaskConfig
from cumulusci.core.config import OrgConfig
from cumulusci.tasks.apexdoc import GenerateApexDocs
class TestGenerateApexDocs(unittes... | import mock
import re
import unittest
from cumulusci.core.config import BaseGlobalConfig
from cumulusci.core.config import BaseProjectConfig
from cumulusci.core.config import TaskConfig
from cumulusci.core.config import OrgConfig
from cumulusci.tasks.apexdoc import GenerateApexDocs
class TestGenerateApexDocs(unittes... | Update TestGenerateApexDocs regex to fix windows test | Update TestGenerateApexDocs regex to fix windows test
This commit updates the test regex to match either windows or unix file
separators.
The command generated on Windows:
java -jar c:\users\ieuser\appdata\local\temp\tmp9splyd\apexdoc.jar -s \Users\IEUser\Documents\GitHub\CumulusCI-Test\src\classes -t \Users\IEUs... | Python | bsd-3-clause | SalesforceFoundation/CumulusCI,SalesforceFoundation/CumulusCI | ---
+++
@@ -22,7 +22,7 @@
task()
self.assertTrue(
re.match(
- r"java -jar .*/apexdoc.jar -s .*/src/classes -t .*",
+ r"java -jar .*.apexdoc.jar -s .*.src.classes -t .*",
task.options["command"],
)
) |
6cbfe86677b108181deb756ecf8276fe9521f691 | mopidy/internal/gi.py | mopidy/internal/gi.py | from __future__ import absolute_import, print_function, unicode_literals
import sys
import textwrap
try:
import gi
gi.require_version('Gst', '1.0')
gi.require_version('GstPbutils', '1.0')
from gi.repository import GLib, GObject, Gst, GstPbutils
except ImportError:
print(textwrap.dedent("""
... | from __future__ import absolute_import, print_function, unicode_literals
import sys
import textwrap
try:
import gi
gi.require_version('Gst', '1.0')
gi.require_version('GstPbutils', '1.0')
from gi.repository import GLib, GObject, Gst, GstPbutils
except ImportError:
print(textwrap.dedent("""
... | Send in an argument to Gst.init | gst1: Send in an argument to Gst.init
As of gst-python 1.5.2, the init call requires one argument. The
argument is a list of the command line options. I don't think we need to
send any.
This relates to #1432.
| Python | apache-2.0 | tkem/mopidy,adamcik/mopidy,vrs01/mopidy,ZenithDK/mopidy,vrs01/mopidy,tkem/mopidy,mokieyue/mopidy,kingosticks/mopidy,jodal/mopidy,tkem/mopidy,kingosticks/mopidy,jodal/mopidy,mopidy/mopidy,kingosticks/mopidy,mokieyue/mopidy,adamcik/mopidy,vrs01/mopidy,mokieyue/mopidy,jcass77/mopidy,mopidy/mopidy,adamcik/mopidy,tkem/mopid... | ---
+++
@@ -22,7 +22,7 @@
"""))
raise
else:
- Gst.is_initialized() or Gst.init()
+ Gst.is_initialized() or Gst.init([])
REQUIRED_GST_VERSION = (1, 2, 3) |
a4c247f5243c8ee637f1507fb9dc0281541af3b1 | pambox/speech/__init__.py | pambox/speech/__init__.py | """
The :mod:`pambox.speech` module gather speech intelligibility
models.
"""
from __future__ import absolute_import
from .sepsm import Sepsm
from .mrsepsm import MrSepsm
from .sii import Sii
from .material import Material
__all__ = [
'Sepsm',
'MrSepsm',
'Sii',
'Material'
]
| """
The :mod:`pambox.speech` module gather speech intelligibility
models.
"""
from __future__ import absolute_import
from .sepsm import Sepsm
from .mrsepsm import MrSepsm
from .sii import Sii
from .material import Material
from .experiment import Experiment
__all__ = [
'Sepsm',
'MrSepsm',
'Sii',
'Mate... | Add Experiment to the init file of speech module | Add Experiment to the init file of speech module
| Python | bsd-3-clause | achabotl/pambox | ---
+++
@@ -8,10 +8,12 @@
from .mrsepsm import MrSepsm
from .sii import Sii
from .material import Material
+from .experiment import Experiment
__all__ = [
'Sepsm',
'MrSepsm',
'Sii',
- 'Material'
+ 'Material',
+ 'Experiment'
] |
e655bbd79c97473003f179a3df165e6e548f121e | letsencryptae/models.py | letsencryptae/models.py | # THIRD PARTY
from djangae.fields import CharField
from django.db import models
class Secret(models.Model):
created = models.DateTimeField(auto_now_add=True)
url_slug = CharField(primary_key=True)
secret = CharField()
class Meta(object):
ordering = ('-created',)
def __unicode__(self):
... | # THIRD PARTY
from djangae.fields import CharField
from django.db import models
class Secret(models.Model):
created = models.DateTimeField(auto_now_add=True)
url_slug = CharField(primary_key=True)
secret = CharField()
class Meta(object):
ordering = ('-created',)
def __unicode__(self):
... | Make sure that there's a dot separating the first and second halves of the secret. | Make sure that there's a dot separating the first and second halves of the secret.
| Python | mit | adamalton/letsencrypt-appengine | ---
+++
@@ -15,6 +15,9 @@
return self.url_slug
def clean(self, *args, **kwargs):
+ """ Check that the secret starts with the URL slug plus a dot, as that's the format that
+ Let's Encrypt creates them in.
+ """
return_value = super(Secret, self).clean(*args, **kwargs)... |
af3525bf174d0774b61464f9cc8ab8441babc7ae | examples/flask_alchemy/test_demoapp.py | examples/flask_alchemy/test_demoapp.py | import os
import unittest
import tempfile
import demoapp
import demoapp_factories
class DemoAppTestCase(unittest.TestCase):
def setUp(self):
demoapp.app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
demoapp.app.config['TESTING'] = True
self.app = demoapp.app.test_client()
self.d... | import unittest
import demoapp
import demoapp_factories
class DemoAppTestCase(unittest.TestCase):
def setUp(self):
demoapp.app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
demoapp.app.config['TESTING'] = True
self.app = demoapp.app.test_client()
self.db = demoapp.db
se... | Remove useless imports from flask alchemy demo | Remove useless imports from flask alchemy demo
| Python | mit | FactoryBoy/factory_boy | ---
+++
@@ -1,9 +1,8 @@
-import os
import unittest
-import tempfile
import demoapp
import demoapp_factories
+
class DemoAppTestCase(unittest.TestCase):
|
1f1e1a78f56e890777ca6f88cc30be7710275aea | blackbelt/deployment.py | blackbelt/deployment.py | from subprocess import check_call
from blackbelt.handle_github import get_current_branch
from blackbelt.messages import post_message
def deploy_staging():
branch_name = get_current_branch()
post_message("Deploying branch %s to staging" % branch_name, "#deploy-queue")
check_call(['grunt', 'deploy', '--a... | from subprocess import check_call
from blackbelt.handle_github import get_current_branch
from blackbelt.messages import post_message
def deploy_staging():
branch_name = get_current_branch()
post_message("Deploying branch %s to staging" % branch_name, "#deploy-queue")
check_call(['grunt', 'deploy', '--a... | Update deploy and stage with new environ | feat: Update deploy and stage with new environ | Python | mit | apiaryio/black-belt | ---
+++
@@ -9,9 +9,10 @@
post_message("Deploying branch %s to staging" % branch_name, "#deploy-queue")
- check_call(['grunt', 'deploy', '--app=apiary-staging', '--force', "--branch=%s" % branch_name])
+ check_call(['grunt', 'deploy', '--app=apiary-staging-pool1', '--force', "--branch=%s" % branch_name]... |
847e864df300304ac43e995a577eaa93ae452024 | streak-podium/render.py | streak-podium/render.py | import matplotlib.pyplot as plt
import numpy as np
def horizontal_bar(sorted_streaks, sort):
"""
Render a horizontal bar chart of streaks.
Values have already been sorted by sort.
"""
# Only extract those users & streaks for streaks that are non-zero:
users, streaks = zip(*[(user, streak.get(... | import matplotlib.pyplot as plt
import numpy as np
def horizontal_bar(sorted_streaks, sort):
"""
Render a horizontal bar chart of streaks.
Values have already been sorted by sort.
"""
# Only extract those users & streaks for streaks that are non-zero:
users, streaks = zip(*[(user, streak.get(... | Remove y-axis ticks and top x-axis ticks | Remove y-axis ticks and top x-axis ticks
| Python | mit | jollyra/hubot-streak-podium,jollyra/hubot-commit-streak,supermitch/streak-podium,jollyra/hubot-streak-podium,supermitch/streak-podium,jollyra/hubot-commit-streak | ---
+++
@@ -22,6 +22,9 @@
plt.xlim([0, max(streaks) + 10]) # x-limits a bit wider at right
plt.subplots_adjust(left=0.25) # Wider left margin
plt.title(title)
+ ax = plt.gca()
+ ax.yaxis.set_ticks_position('none')
+ ax.xaxis.set_ticks_position('bottom')
for format in ('png', 'svg'):
... |
1ed49dae9d88e1e277a0eef879dec53ed925417a | highlander/exceptions.py | highlander/exceptions.py | class InvalidPidFileError(Exception):
""" An exception when an invalid PID file is read."""
class PidFileExistsError(Exception):
""" An exception when a PID file already exists."""
| class InvalidPidFileError(Exception):
""" An exception when an invalid PID file is read."""
class PidFileExistsError(Exception):
""" An exception when a PID file already exists."""
class InvalidPidDirectoryError(Exception):
""" An exception when an invalid PID directory is detected."""
| Add a new exception since we are making a directory now. | Add a new exception since we are making a directory now.
| Python | mit | chriscannon/highlander | ---
+++
@@ -3,3 +3,6 @@
class PidFileExistsError(Exception):
""" An exception when a PID file already exists."""
+
+class InvalidPidDirectoryError(Exception):
+ """ An exception when an invalid PID directory is detected.""" |
644df0955d1a924b72ffdceaea9d8da14100dae0 | scipy/weave/tests/test_inline_tools.py | scipy/weave/tests/test_inline_tools.py | from numpy import *
from numpy.testing import *
from scipy.weave import inline_tools
class TestInline(TestCase):
""" These are long running tests...
I'd like to benchmark these things somehow.
"""
@dec.slow
def test_exceptions(self):
a = 3
code = """
if (a < 2)... | from numpy import *
from numpy.testing import *
from scipy.weave import inline_tools
class TestInline(TestCase):
""" These are long running tests...
I'd like to benchmark these things somehow.
"""
@dec.slow
def test_exceptions(self):
a = 3
code = """
if (a < 2)... | Disable weave tests that cause compilation failure, since this causes distutils to do a SystemExit, which break the test suite. | Disable weave tests that cause compilation failure, since this causes
distutils to do a SystemExit, which break the test suite.
git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@5402 d6536bca-fef9-0310-8506-e4c0a848fbcf
| Python | bsd-3-clause | scipy/scipy-svn,lesserwhirls/scipy-cwt,scipy/scipy-svn,jasonmccampbell/scipy-refactor,scipy/scipy-svn,lesserwhirls/scipy-cwt,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor,scipy/scipy-svn,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor | ---
+++
@@ -21,21 +21,25 @@
result = inline_tools.inline(code,['a'])
assert(result == 4)
- try:
- a = 1
- result = inline_tools.inline(code,['a'])
- assert(1) # should've thrown a ValueError
- except ValueError:
- pass
+## Unfortunately, it... |
26e947c91980cf6ccb83a99cbb5c6fefb0837d4f | mopidy/backends/libspotify/library.py | mopidy/backends/libspotify/library.py | import logging
import multiprocessing
from spotify import Link
from mopidy.backends.base import BaseLibraryController
from mopidy.backends.libspotify import ENCODING
from mopidy.backends.libspotify.translator import LibspotifyTranslator
logger = logging.getLogger('mopidy.backends.libspotify.library')
class Libspoti... | import logging
import multiprocessing
from spotify import Link
from mopidy.backends.base import BaseLibraryController
from mopidy.backends.libspotify import ENCODING
from mopidy.backends.libspotify.translator import LibspotifyTranslator
logger = logging.getLogger('mopidy.backends.libspotify.library')
class Libspoti... | Add TODO on how to make a better libspotify lookup | Add TODO on how to make a better libspotify lookup
| Python | apache-2.0 | dbrgn/mopidy,jcass77/mopidy,pacificIT/mopidy,ali/mopidy,bacontext/mopidy,bencevans/mopidy,ali/mopidy,dbrgn/mopidy,bacontext/mopidy,kingosticks/mopidy,mokieyue/mopidy,SuperStarPL/mopidy,hkariti/mopidy,abarisain/mopidy,jmarsik/mopidy,liamw9534/mopidy,pacificIT/mopidy,vrs01/mopidy,abarisain/mopidy,glogiotatidis/mopidy,wou... | ---
+++
@@ -15,6 +15,8 @@
def lookup(self, uri):
spotify_track = Link.from_string(uri).as_track()
+ # TODO Block until metadata_updated callback is called. Before that the
+ # track will be unloaded, unless it's already in the stored playlists.
return LibspotifyTranslator.to_mop... |
8a605f21e6c11b8176214ce7082c892566a6b34e | telethon/tl/message_container.py | telethon/tl/message_container.py | from . import TLObject, GzipPacked
from ..extensions import BinaryWriter
class MessageContainer(TLObject):
constructor_id = 0x73f1f8dc
def __init__(self, messages):
super().__init__()
self.content_related = False
self.messages = messages
def to_bytes(self):
# TODO Change ... | import struct
from . import TLObject
class MessageContainer(TLObject):
constructor_id = 0x73f1f8dc
def __init__(self, messages):
super().__init__()
self.content_related = False
self.messages = messages
def to_bytes(self):
return struct.pack(
'<Ii', MessageCon... | Remove BinaryWriter dependency on MessageContainer | Remove BinaryWriter dependency on MessageContainer
| Python | mit | LonamiWebs/Telethon,andr-04/Telethon,LonamiWebs/Telethon,expectocode/Telethon,LonamiWebs/Telethon,LonamiWebs/Telethon | ---
+++
@@ -1,5 +1,6 @@
-from . import TLObject, GzipPacked
-from ..extensions import BinaryWriter
+import struct
+
+from . import TLObject
class MessageContainer(TLObject):
@@ -11,14 +12,9 @@
self.messages = messages
def to_bytes(self):
- # TODO Change this to delete the on_send from this... |
2bf0872a176fd8b97a31a15bd3feb49d7f8cf7d7 | hubbot/Utils/timeout.py | hubbot/Utils/timeout.py | import signal
class Timeout(Exception):
"""Context manager which wraps code in a timeout.
If the timeout is exceeded, the context manager will be raised.
Example usage:
try:
with Timeout(5):
time.sleep(10)
except Timeout:
pass
"""
def __init__(self, duration):
self.d... | import signal
class Timeout(Exception):
"""Context manager which wraps code in a timeout.
If the timeout is exceeded, the context manager will be raised.
Example usage:
try:
with Timeout(5):
time.sleep(10)
except Timeout:
pass
"""
def __init__(self, duration):
self.d... | Revert "[Timeout] Fix an assert" | Revert "[Timeout] Fix an assert"
This reverts commit 05f0fb77716297114043d52de3764289a1926752.
| Python | mit | HubbeKing/Hubbot_Twisted | ---
+++
@@ -27,7 +27,7 @@
def __exit__(self, *exc_info):
signal.alarm(0) # cancel any pending alarm
my_handler = signal.signal(signal.SIGALRM, self._old_handler)
- assert my_handler == self._handler, "Wrong SIGALRM handler on __exit__, is something else messing with signal handlers?"
+ ... |
864d23ab3996e471b659ded6cfc13447b2497107 | example.py | example.py | from __future__ import print_function
import io
import string
import random
from boggle.boggle import list_words
def main():
with io.open("/usr/share/dict/words", encoding='latin-1') as word_file:
english_words = set(word.strip() for word in word_file)
available_tiles = [letter for letter in string.... | from __future__ import print_function
import io
import string
import random
from boggle.boggle import list_words
def main():
with io.open("/usr/share/dict/words", encoding='latin-1') as word_file:
english_words = set(word.strip() for word in word_file)
available_tiles = [letter for letter in string.... | Use range instead of xrange as it is also available in python 3 | Use range instead of xrange as it is also available in python 3
| Python | mit | adamtheturtle/boggle-solver | ---
+++
@@ -15,11 +15,11 @@
available_tiles.append('Qu')
# A boggle board is an n * n square. Set n:
- size = 15
+ size = 10
board = []
for row in range(size):
- board.append([random.choice(available_tiles) for i in xrange(size)])
+ board.append([random.choice(available_til... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.