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 |
|---|---|---|---|---|---|---|---|---|---|---|
baf4f922a9f473a4351c3fd9832000244a73a40a | chainerrl/explorers/additive_gaussian.py | chainerrl/explorers/additive_gaussian.py | from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases()
import numpy as np
from chainerrl import explorer
class AdditiveG... | from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases()
import numpy as np
from chainerrl import explorer
class AdditiveG... | Remove spaces in empty lines | Remove spaces in empty lines | Python | mit | toslunar/chainerrl,toslunar/chainerrl | ---
+++
@@ -13,9 +13,9 @@
class AdditiveGaussian(explorer.Explorer):
"""Additive Gaussian noise to actions.
-
+
Each action must be numpy.ndarray.
-
+
Args:
scale (float or array_like of floats): Scale parameter.
""" |
147c53115864cc3b3194fb9c585179d12197c998 | settings_example.py | settings_example.py | import os
import re
from imap import EmailCheckError, EmailServer
from postgresql import DatabaseServer
# If this is set to a valid path, all CSV files extracted from emails will be
# stored in sub-folders within it.
CSV_FOLDER = os.getcwd()
# Values come from `EMAIL_SUBJECT_RE`.
CSV_NAME_FORMAT = '{year}-{month}-{... | import logging
import os
import re
from imap import EmailCheckError, EmailServer
from postgresql import DatabaseServer
# If this is set to a valid path, all CSV files extracted from emails will be
# stored in sub-folders within it.
CSV_FOLDER = os.getcwd()
# Values come from `EMAIL_SUBJECT_RE`.
CSV_NAME_FORMAT = '{... | Add logging level to settings | Add logging level to settings
| Python | mit | AustralianAntarcticDataCentre/save_emails_to_files,AustralianAntarcticDataCentre/save_emails_to_files | ---
+++
@@ -1,3 +1,4 @@
+import logging
import os
import re
@@ -34,6 +35,8 @@
time: %(asctime)s
'''.strip()
+LOGGING_LEVEL = logging.DEBUG
+
# Values come from `EMAIL_SUBJECT_RE`.
TABLE_NAME_FORMAT = 'data_{year}{month}'
|
84fbe1eebc2c19b72ab4bba8017e1cb37818afc1 | scripts/reactions.py | scripts/reactions.py | import argparse
from lenrmc.nubase import System
from lenrmc.terminal import TerminalView, StudiesTerminalView
class App(object):
def __init__(self, **kwargs):
self.kwargs = kwargs
if 'studies' == self.kwargs.get('view'):
self.view_cls = StudiesTerminalView
else:
... | import argparse
from lenrmc.nubase import System
from lenrmc.terminal import TerminalView, StudiesTerminalView
class App(object):
def __init__(self, **kwargs):
self.kwargs = kwargs
if 'studies' == self.kwargs.get('view') or kwargs.get('studies'):
self.view_cls = StudiesTerminalView
... | Add --studies as an alias for --view studies. | Add --studies as an alias for --view studies.
| Python | mit | emwalker/lenrmc | ---
+++
@@ -8,7 +8,7 @@
def __init__(self, **kwargs):
self.kwargs = kwargs
- if 'studies' == self.kwargs.get('view'):
+ if 'studies' == self.kwargs.get('view') or kwargs.get('studies'):
self.view_cls = StudiesTerminalView
else:
self.view_cls = TerminalV... |
530297a29150736208cd30c018a427f9d7e2d2eb | swift3/__init__.py | swift3/__init__.py | # Copyright (c) 2012-2014 OpenStack Foundation.
#
# 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 agre... | # Copyright (c) 2012-2014 OpenStack Foundation.
#
# 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 agre... | Remove pbr dependency at run time | Remove pbr dependency at run time
This change is based on the following commit in the Swift tree.
0717133 Make pbr a build-time only dependency
Change-Id: I43956f531a9928ade296236b3b605e52dc2f86f3
| Python | apache-2.0 | swiftstack/swift3-stackforge,stackforge/swift3,stackforge/swift3,tumf/swift3,KoreaCloudObjectStorage/swift3,KoreaCloudObjectStorage/swift3,swiftstack/swift3-stackforge,tumf/swift3 | ---
+++
@@ -12,20 +12,24 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-"""
-Static Web Middleware for OpenStack Swift
-"""
-import pbr.version
+import pkg_resources
__all__ = ['version_info', 'version']
-# get version info using pbr.version.
-# pbr... |
f731cef20b07998dd5ec76e20af20cb9e60d9afb | UM/Operations/RemoveSceneNodeOperation.py | UM/Operations/RemoveSceneNodeOperation.py | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import Operation
from UM.Scene.SceneNode import SceneNode
## An operation that removes an list of SceneNode from the scene.
class RemoveSceneNodeOperation(Operation.Operation):
def __init__(self, node):
... | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import Operation
from UM.Scene.SceneNode import SceneNode
from UM.Scene.Selection import Selection
## An operation that removes an list of SceneNode from the scene.
class RemoveSceneNodeOperation(Operation.Oper... | Remove the object from selection if it is selected | Remove the object from selection if it is selected
This cleans up any leftovers due to the object being selected.
Fixes #42
| Python | agpl-3.0 | onitake/Uranium,onitake/Uranium | ---
+++
@@ -4,6 +4,7 @@
from . import Operation
from UM.Scene.SceneNode import SceneNode
+from UM.Scene.Selection import Selection
## An operation that removes an list of SceneNode from the scene.
class RemoveSceneNodeOperation(Operation.Operation):
@@ -17,3 +18,5 @@
def redo(self):
self._nod... |
59055a9f8d6093e2fc82bb4f656200b71279da1c | tml/rules/contexts/genders.py | tml/rules/contexts/genders.py | from .gender import Gender
from _ctypes import ArgumentError
class Genders(object):
@classmethod
def match(cls, data):
""" Check is data list of genders """
if type(data) is str:
raise ArgumentError('String is not genders list', data)
try:
ret = []
... | from .gender import Gender
from _ctypes import ArgumentError
class Genders(object):
""" List of objects having gender """
@classmethod
def match(cls, data):
""" Check is data list of genders """
if type(data) is str:
raise ArgumentError('String is not genders list', data)
... | Add comment to gender class | Add comment to gender class
| Python | mit | translationexchange/tml-python,translationexchange/tml-python | ---
+++
@@ -2,6 +2,7 @@
from _ctypes import ArgumentError
class Genders(object):
+ """ List of objects having gender """
@classmethod
def match(cls, data):
""" Check is data list of genders """ |
9de8bae6b310473c1e42448b3fbca64a4807678a | astrobin/tasks.py | astrobin/tasks.py | from __future__ import absolute_import
from django.core.cache import cache
from celery import shared_task
from haystack.query import SearchQuerySet
from astrobin.models import Image
@shared_task()
def update_top100_ids():
sqs = SearchQuerySet().models(Image).order_by('-likes')
top100_ids = [int(x.pk) for x... | from __future__ import absolute_import
from hashlib import md5
from django.core.cache import cache
from celery import shared_task
from celery.utils.log import get_task_logger
from haystack.query import SearchQuerySet
from astrobin.models import Image
logger = get_task_logger(__name__)
LOCK_EXPIRE = 60 * 5 # Lock... | Make task for top100_ids atomic | Make task for top100_ids atomic
| Python | agpl-3.0 | astrobin/astrobin,astrobin/astrobin,astrobin/astrobin,astrobin/astrobin | ---
+++
@@ -1,15 +1,38 @@
from __future__ import absolute_import
+
+from hashlib import md5
from django.core.cache import cache
from celery import shared_task
+from celery.utils.log import get_task_logger
from haystack.query import SearchQuerySet
from astrobin.models import Image
+logger = get_task_log... |
d70014d317f7abc9dffe674aca5eaf77d20a002f | djangosaml2/urls.py | djangosaml2/urls.py | # Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# ... | # Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# ... | Fix imports for Django 1.6 and above | Fix imports for Django 1.6 and above
| Python | apache-2.0 | bernii/djangosaml2,azavea/djangosaml2 | ---
+++
@@ -13,7 +13,11 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-from django.conf.urls.defaults import patterns, handler500, url
+try:
+ from django.conf.urls import patterns, handler500, url
+# Fallback for Django versions < 1.4
+except ImportE... |
ebadbdda9b522588d534697696d3270542d3167e | zinnia/migrations/__init__.py | zinnia/migrations/__init__.py | """Migrations for Zinnia"""
from django.contrib.auth import get_user_model
User = get_user_model()
user_name = User.__name__
user_table = User._meta.db_table
user_orm_label = '%s.%s' % (User._meta.app_label, User._meta.object_name)
user_model_label = '%s.%s' % (User._meta.app_label, User._meta.module_name)
| """Migrations for Zinnia"""
from django.contrib.auth import get_user_model
User = get_user_model()
user_name = User.__name__
user_table = User._meta.db_table
user_orm_label = '%s.%s' % (User._meta.app_label, User._meta.object_name)
user_model_label = '%s.%s' % (User._meta.app_label, User._meta.model_name)
| Use _meta.model_name instead of _meta.module_name | Use _meta.model_name instead of _meta.module_name
| Python | bsd-3-clause | ghachey/django-blog-zinnia,ZuluPro/django-blog-zinnia,Zopieux/django-blog-zinnia,petecummings/django-blog-zinnia,extertioner/django-blog-zinnia,Zopieux/django-blog-zinnia,ZuluPro/django-blog-zinnia,petecummings/django-blog-zinnia,aorzh/django-blog-zinnia,extertioner/django-blog-zinnia,petecummings/django-blog-zinnia,gh... | ---
+++
@@ -5,4 +5,4 @@
user_name = User.__name__
user_table = User._meta.db_table
user_orm_label = '%s.%s' % (User._meta.app_label, User._meta.object_name)
-user_model_label = '%s.%s' % (User._meta.app_label, User._meta.module_name)
+user_model_label = '%s.%s' % (User._meta.app_label, User._meta.model_name) |
7ea630074262beed16c70649809fe8115bcc6105 | saleor/account/templatetags/i18n_address_tags.py | saleor/account/templatetags/i18n_address_tags.py | import i18naddress
from django import template
from django.utils.translation import pgettext
register = template.Library()
@register.inclusion_tag("formatted_address.html")
def format_address(address, include_phone=True, inline=False, latin=False):
address_data = address.as_data()
address_data["name"] = (
... | import i18naddress
from django import template
from django.utils.translation import pgettext
register = template.Library()
@register.inclusion_tag("formatted_address.html")
def format_address(address, include_phone=True, inline=False, latin=False):
address_data = address.as_data()
address_data["name"] = (
... | Fix phone number formatting in emails | Fix phone number formatting in emails
| Python | bsd-3-clause | mociepka/saleor,mociepka/saleor,mociepka/saleor | ---
+++
@@ -17,5 +17,5 @@
)
address_lines = i18naddress.format_address(address_data, latin).split("\n")
if include_phone and address.phone:
- address_lines.append(address.phone)
+ address_lines.append(str(address.phone))
return {"address_lines": address_lines, "inline": inline} |
c62b42eb528babebf96e56738031dcda97868e80 | flowfairy/app.py | flowfairy/app.py | import tensorflow as tf
import numpy as np
import itertools as it
import importlib
from flowfairy.conf import settings
from flowfairy.utils import take
from flowfairy import data
from flowfairy.feature import FeatureManager
from flowfairy.core.queue import FlowQueue
from flowfairy.core.stage import stage
def load_ne... | import tensorflow as tf
import numpy as np
import itertools as it
import importlib
from flowfairy.conf import settings
from flowfairy.utils import take
from flowfairy import data
from flowfairy.feature import FeatureManager
from flowfairy.core.queue import FlowQueue
from flowfairy.core.stage import stage
def load_ne... | Set name_scope of entire network to the dataset it handles | Set name_scope of entire network to the dataset it handles
| Python | mit | WhatDo/FlowFairy | ---
+++
@@ -21,8 +21,8 @@
net = load_net()
queues = []
- with tf.variable_scope('network') as scope:
- for data_loader in data.provider:
+ for data_loader in data.provider:
+ with tf.variable_scope(data_loader.name) as scope:
fts = FeatureManager(data_loader)
... |
8ea996de13e1ad3c9865866385fa0ecb49d6cbca | tests/help_test.py | tests/help_test.py | from __future__ import unicode_literals
import os
import subprocess
import sys
import unittest
import mopidy
class HelpTest(unittest.TestCase):
def test_help_has_mopidy_options(self):
mopidy_dir = os.path.dirname(mopidy.__file__)
args = [sys.executable, mopidy_dir, '--help']
python_path ... | from __future__ import unicode_literals
import os
import subprocess
import sys
import unittest
import mopidy
class HelpTest(unittest.TestCase):
def test_help_has_mopidy_options(self):
mopidy_dir = os.path.dirname(mopidy.__file__)
args = [sys.executable, mopidy_dir, '--help']
process = su... | Revert "tests: Don't redefine PYTHONPATH" | Revert "tests: Don't redefine PYTHONPATH"
This reverts commit 6be5cc0f1b1d34521fa8d8c91ca1cc2a96a65b69.
| Python | apache-2.0 | jodal/mopidy,adamcik/mopidy,mokieyue/mopidy,jcass77/mopidy,glogiotatidis/mopidy,diandiankan/mopidy,bencevans/mopidy,quartz55/mopidy,dbrgn/mopidy,abarisain/mopidy,swak/mopidy,rawdlite/mopidy,jcass77/mopidy,ZenithDK/mopidy,mopidy/mopidy,bacontext/mopidy,diandiankan/mopidy,jodal/mopidy,diandiankan/mopidy,ali/mopidy,swak/m... | ---
+++
@@ -12,11 +12,9 @@
def test_help_has_mopidy_options(self):
mopidy_dir = os.path.dirname(mopidy.__file__)
args = [sys.executable, mopidy_dir, '--help']
- python_path = sys.path[:]
- python_path.insert(0, os.path.join(mopidy_dir, '..'))
process = subprocess.Popen(
... |
f2af85f7e9de7ca7494a849856a9274a5d969378 | icekit_events/apps.py | icekit_events/apps.py | """
App configuration for ``icekit_events`` app.
"""
# Register signal handlers, but avoid interacting with the database.
# See: https://docs.djangoproject.com/en/1.8/ref/applications/#django.apps.AppConfig.ready
from django.apps import AppConfig
from django.utils.module_loading import autodiscover_modules
from any_... | """
App configuration for ``icekit_events`` app.
"""
# Register signal handlers, but avoid interacting with the database.
# See: https://docs.djangoproject.com/en/1.8/ref/applications/#django.apps.AppConfig.ready
from django.apps import AppConfig
from django.utils.module_loading import autodiscover_modules
from any_... | Fix test run failures with double-registration on ICEkitURLField | Fix test run failures with double-registration on ICEkitURLField
Use the new `ICEkitURLField.register_model_once` method available in
django-icekit to safely register base events for `ICEkitURLField`
without the risk that they will be re-registered (and therefore fail)
because of the way the unit tests reload this app... | Python | mit | ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/icekit-events,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/icekit-events,ic-labs/icekit-events | ---
+++
@@ -23,5 +23,5 @@
autodiscover_modules('event_type_plugins')
from .models import EventBase
- ICEkitURLField.register_model(
+ ICEkitURLField.register_model_once(
EventBase, widget=SimpleRawIdWidget(EventBase), title='Event') |
9a64f7b08704f2f343564698d83dd73bb1f0d4b2 | slackbot_settings.py | slackbot_settings.py | DEFAULT_REPLY = "Sorry, I did not understand you."
ERRORS_TO = 'general'
PLUGINS = [
'plugins.witai'
]
| DEFAULT_REPLY = "Sorry, I did not understand you."
PLUGINS = [
'plugins.witai'
]
| Remove sending error to general channel | Remove sending error to general channel
| Python | mit | sanjaybv/netbot | ---
+++
@@ -1,5 +1,4 @@
DEFAULT_REPLY = "Sorry, I did not understand you."
-ERRORS_TO = 'general'
PLUGINS = [
'plugins.witai' |
827644a143a0fae0a1fa34ce2c624b199d0c1b63 | bisnode/models.py | bisnode/models.py | from django.db import models
from .constants import COMPANY_RATING_REPORT, RATING_CHOICES
from .bisnode import get_bisnode_company_report
class BisnodeRatingReport(models.Model):
organization_number = models.CharField(max_length=10)
rating = models.CharField(max_length=3, choices=RATING_CHOICES,
... | from datetime import datetime, date
from django.db import models
from .constants import COMPANY_RATING_REPORT, RATING_CHOICES
from .bisnode import get_bisnode_company_report
def bisnode_date_to_date(bisnode_date):
formatted_datetime = datetime.strptime(bisnode_date, "%Y%m%d")
return formatted_datetime.date(... | Save dates from Bisnode correctly | Save dates from Bisnode correctly
| Python | mit | FundedByMe/django-bisnode | ---
+++
@@ -1,8 +1,14 @@
+from datetime import datetime, date
+
from django.db import models
from .constants import COMPANY_RATING_REPORT, RATING_CHOICES
+from .bisnode import get_bisnode_company_report
-from .bisnode import get_bisnode_company_report
+
+def bisnode_date_to_date(bisnode_date):
+ formatted_da... |
f5fd149316d1a5bfc0e271c2c0e0fc6ee74daa96 | models/augmented_user.py | models/augmented_user.py | # coding: utf-8
#
# Copyright 2013 Google Inc. 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 ... | # coding: utf-8
#
# Copyright 2013 Google Inc. 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 ... | Add TODO to think about. | Add TODO to think about.
| Python | apache-2.0 | sanyaade-teachings/oppia,danieljjh/oppia,kaffeel/oppia,whygee/oppia,kennho/oppia,directorlive/oppia,sarahfo/oppia,toooooper/oppia,fernandopinhati/oppia,VictoriaRoux/oppia,danieljjh/oppia,Atlas-Sailed-Co/oppia,fernandopinhati/oppia,DewarM/oppia,brylie/oppia,oppia/oppia,aldeka/oppia,amgowano/oppia,AllanYangZhou/oppia,sdu... | ---
+++
@@ -25,6 +25,8 @@
class AugmentedUser(ndb.Model):
"""Stores information about a particular user."""
+ # TODO(sll): Should this class be keyed by user.email()?
+
# The corresponding user.
user = ndb.UserProperty(required=True)
# The list of explorations that this user has editing righ... |
a6c6175c6d15cd9d7fd711431a6741afa35e78fb | smartbot/storage.py | smartbot/storage.py | import yaml
class _Storage:
def __getitem__(self, key):
pass
def __setitem__(self, key, value):
pass
def __delitem__(self, key):
pass
class _DictionaryStorage(_Storage):
def __init__(self):
self.data = {}
def __del__(self):
self.commit()
def commit... | import yaml
class _Storage:
def __getitem__(self, key):
pass
def __setitem__(self, key, value):
pass
def __delitem__(self, key):
pass
class _DictionaryStorage(_Storage):
def __init__(self):
self.data = {}
def __del__(self):
self.commit()
def commit... | Update setdefault to ensure commit is called | Update setdefault to ensure commit is called
| Python | mit | Cyanogenoid/smartbot,Muzer/smartbot,thomasleese/smartbot-old,tomleese/smartbot | ---
+++
@@ -26,7 +26,9 @@
return self.data.get(key, default)
def setdefault(self, key, default=None):
- return self.data.setdefault(key, default)
+ if key not in self.data:
+ self[key] = default
+ return self[key]
def __getitem__(self, key):
return self.... |
617ac4a745afb07299c73977477f52911f3e6e4c | flask_skeleton_api/app.py | flask_skeleton_api/app.py | from flask import Flask, g, request
import uuid
import requests
app = Flask(__name__)
app.config.from_pyfile("config.py")
@app.before_request
def before_request():
# Sets the transaction trace id into the global object if it has been provided in the HTTP header from the caller.
# Generate a new one if it ha... | from flask import Flask, g, request
import uuid
import requests
app = Flask(__name__)
app.config.from_pyfile("config.py")
@app.before_request
def before_request():
# Sets the transaction trace id into the global object if it has been provided in the HTTP header from the caller.
# Generate a new one if it ha... | Add API version into response header | Add API version into response header
| Python | mit | matthew-shaw/thing-api | ---
+++
@@ -19,3 +19,12 @@
# These lines can be removed if the app will not make requests to other LR APIs!
g.requests = requests.Session()
g.requests.headers.update({'X-Trace-ID': trace_id})
+
+
+@app.after_request
+def after_request(response):
+ # Add the API version (as in the interface spec, not... |
bcf4c5e632ae3ee678ac10e93887b14c63d4eb4a | examples/plain_actor.py | examples/plain_actor.py | #!/usr/bin/env python3
import pykka
class PlainActor(pykka.ThreadingActor):
def __init__(self):
super().__init__()
self.stored_messages = []
def on_receive(self, message):
if message.get('command') == 'get_messages':
return self.stored_messages
else:
s... | #!/usr/bin/env python3
import pykka
GetMessages = object()
class PlainActor(pykka.ThreadingActor):
def __init__(self):
super().__init__()
self.stored_messages = []
def on_receive(self, message):
if message is GetMessages:
return self.stored_messages
else:
... | Use custom message instead of dict | examples: Use custom message instead of dict
| Python | apache-2.0 | jodal/pykka | ---
+++
@@ -1,6 +1,9 @@
#!/usr/bin/env python3
import pykka
+
+
+GetMessages = object()
class PlainActor(pykka.ThreadingActor):
@@ -9,7 +12,7 @@
self.stored_messages = []
def on_receive(self, message):
- if message.get('command') == 'get_messages':
+ if message is GetMessages:
... |
3dda5003b3ce345a08369b15fc3447d2a4c7d1ad | examples/plotting_2d.py | examples/plotting_2d.py | from bluesky.examples import *
from bluesky.standard_config import RE
from matplotlib import pyplot as plt
from xray_vision.backend.mpl.cross_section_2d import CrossSection
import numpy as np
import filestore.api as fsapi
import time as ttime
from filestore.handlers import NpyHandler
fsapi.register_handler('npy', NpyH... | from bluesky.examples import *
from bluesky.tests.utils import setup_test_run_engine
from matplotlib import pyplot as plt
from xray_vision.backend.mpl.cross_section_2d import CrossSection
import numpy as np
import filestore.api as fsapi
import time as ttime
from filestore.handlers import NpyHandler
fsapi.register_hand... | Set up RunEngine with required metadata. | FIX: Set up RunEngine with required metadata.
| Python | bsd-3-clause | ericdill/bluesky,sameera2004/bluesky,sameera2004/bluesky,klauer/bluesky,klauer/bluesky,dchabot/bluesky,ericdill/bluesky,dchabot/bluesky | ---
+++
@@ -1,5 +1,5 @@
from bluesky.examples import *
-from bluesky.standard_config import RE
+from bluesky.tests.utils import setup_test_run_engine
from matplotlib import pyplot as plt
from xray_vision.backend.mpl.cross_section_2d import CrossSection
import numpy as np
@@ -22,4 +22,5 @@
ic = LiveImage('det_2... |
c02dc4c0717d15f4f042c992b4b404056e0e0a14 | braubuddy/tests/thermometer/test_dummy.py | braubuddy/tests/thermometer/test_dummy.py | """
Braubuddy Dummy thermometer unit tests
"""
import unittest
from mock import patch, call, MagicMock
from braubuddy.thermometer import dummy
from braubuddy.thermometer import DeviceError
from braubuddy.thermometer import ReadError
class TestDummy(unittest.TestCase):
def test_within_bounds(self):
"""Du... | """
Braubuddy Dummy thermometer unit tests
"""
import unittest
from mock import patch, call, MagicMock
from braubuddy.thermometer import dummy
class TestDummy(unittest.TestCase):
def test_within_bounds(self):
"""Dummy thermometer returns values within bounds."""
lower_bound = 20
upper_b... | Remove unnecessary imports form dummy tests. | Remove unnecessary imports form dummy tests.
| Python | bsd-3-clause | amorphic/braubuddy,amorphic/braubuddy,amorphic/braubuddy | ---
+++
@@ -5,8 +5,6 @@
import unittest
from mock import patch, call, MagicMock
from braubuddy.thermometer import dummy
-from braubuddy.thermometer import DeviceError
-from braubuddy.thermometer import ReadError
class TestDummy(unittest.TestCase):
|
e543a6e12f34dfdde4f55630fcd1514d7622e0ee | countBob.py | countBob.py | """ Q7- Assume s is a string of lower case characters. Write a program that
prints the number of times the string 'bob' occurs in s. For example, if s =
'azcbobobegghakl', then your program should print Number of times bob occurs
is: 2
"""
def countBob( string ):
count = 0
start = 0
while string.find( "bob" ) !... | """
Q7- Assume s is a string of lower case characters. Write a program that
prints the number of times the string 'bob' occurs in s. For example, if s =
'azcbobobegghakl', then your program should print Number of times bob occurs
is: 2
"""
def countBob( string ):
count = 0
start = 0
while string.find( "bob" ) ... | Add the answer of seventh question of Assignment 3 | Add the answer of seventh question of Assignment 3
| Python | mit | SuyashD95/python-assignments | ---
+++
@@ -1,4 +1,5 @@
-""" Q7- Assume s is a string of lower case characters. Write a program that
+"""
+Q7- Assume s is a string of lower case characters. Write a program that
prints the number of times the string 'bob' occurs in s. For example, if s =
'azcbobobegghakl', then your program should print Number of... |
602d0f487f8926f41577adb442830796d6612998 | nurseconnect/services.py | nurseconnect/services.py | import logging
import requests
from django.conf import settings
logger = logging.getLogger("nurseconnect.services")
def get_clinic_code(clinic_code):
if settings.FAKE_CLINIC_CODE_VALIDATION and settings.DEBUG:
return [0, 1, "fake_clinic_name"]
url = settings.CLINIC_CODE_API
try:
respons... | import logging
import requests
from django.conf import settings
logger = logging.getLogger("nurseconnect.services")
def get_clinic_code(clinic_code):
if settings.FAKE_CLINIC_CODE_VALIDATION and settings.DEBUG:
return [0, 1, "fake_clinic_name"]
try:
response = requests.get(
setti... | Update how get_clinic_code fetches/extracts info from external service | Update how get_clinic_code fetches/extracts info from external service
We were sending the external API a message to ask for a list of clinic codes and then checking whether the code was in that list of clinic codes.
Instead we send a message which includes the clinic code, to check against that specific clinic.
| Python | bsd-2-clause | praekelt/nurseconnect,praekelt/nurseconnect,praekelt/nurseconnect | ---
+++
@@ -10,9 +10,10 @@
if settings.FAKE_CLINIC_CODE_VALIDATION and settings.DEBUG:
return [0, 1, "fake_clinic_name"]
- url = settings.CLINIC_CODE_API
try:
- response = requests.get(url)
+ response = requests.get(
+ settings.CLINIC_CODE_API,
+ params={"cr... |
09418ae8fa652a5f8d2d3b3058e4acc774cbcbe9 | genes/nginx/main.py | genes/nginx/main.py | from genes.apt import commands as apt
from genes.brew import commands as brew
from genes.debian.traits import is_debian
from genes.mac.traits import is_osx
from genes.ubuntu.traits import is_ubuntu
def main():
if is_ubuntu() or is_debian():
apt.update()
apt.install('nginx')
elif is_osx():
... | from typing import Callable, Optional
from genes.apt import commands as apt
from genes.brew import commands as brew
from genes.debian.traits import is_debian
from genes.mac.traits import is_osx
from genes.ubuntu.traits import is_ubuntu
def main(config: Optional[Callable[[], None]]=None):
# Install nginx
if is... | Add config option for nginx | Add config option for nginx | Python | mit | hatchery/genepool,hatchery/Genepool2 | ---
+++
@@ -1,3 +1,4 @@
+from typing import Callable, Optional
from genes.apt import commands as apt
from genes.brew import commands as brew
from genes.debian.traits import is_debian
@@ -5,7 +6,8 @@
from genes.ubuntu.traits import is_ubuntu
-def main():
+def main(config: Optional[Callable[[], None]]=None):
+ ... |
aed4d20d4e101891d2dd1149a6c111f06036ec73 | libnacl/utils.py | libnacl/utils.py | # -*- coding: utf-8 -*-
# Import nacl libs
import libnacl
import libnacl.encode
# Import python libs
import datetime
import binascii
class BaseKey(object):
'''
Include methods for key management convenience
'''
def hex_sk(self):
if hasattr(self, 'sk'):
return libnacl.encode.hex_e... | # -*- coding: utf-8 -*-
# Import nacl libs
import libnacl
import libnacl.encode
# Import python libs
import time
import binascii
class BaseKey(object):
'''
Include methods for key management convenience
'''
def hex_sk(self):
if hasattr(self, 'sk'):
return libnacl.encode.hex_encod... | Make the nonce more secure and faster to generate | Make the nonce more secure and faster to generate
| Python | apache-2.0 | cachedout/libnacl,saltstack/libnacl,mindw/libnacl,johnttan/libnacl,RaetProtocol/libnacl,coinkite/libnacl | ---
+++
@@ -5,7 +5,7 @@
import libnacl.encode
# Import python libs
-import datetime
+import time
import binascii
@@ -46,7 +46,7 @@
The nonce generated here is done by grabbing the 20 digit microsecond
timestamp and appending 4 random chars
'''
- nonce = '{0:%Y%m%d%H%M%S%f}{1}'.format(
- ... |
73e50feae8fb6c06ace5f268e11c8df985e5eace | login/routers.py | login/routers.py | # List of apps that will use the users database
USERS_DATABASE_APPS = ['auth','login','sessions']
class UserRouter(object):
"""
A router to control all database operations on models in the
login application.
"""
def db_for_read(self, model, **hints):
"""
Attempts to read login model... | # List of apps that will use the users database
USERS_DATABASE_APPS = ['auth', 'login', 'sessions', 'contenttypes', 'sites']
class UserRouter(object):
"""
A router to control all database operations on models in the
login application.
"""
def db_for_read(self, model, **hints):
"""
A... | Add apps on list that will be used on the test databases | [login] Add apps on list that will be used on the test databases
Added apps sites and contenttypes to the list.
These apps were causing troubles on the test databases.
Signed off by: Heitor Reis <marcheing@gmail.com>
Signed off by: Filipe Vaz <vazfilipe92@gmail.com>
| Python | agpl-3.0 | SuperNovaPOLIUSP/supernova,SuperNovaPOLIUSP/supernova,SuperNovaPOLIUSP/supernova,SuperNovaPOLIUSP/supernova | ---
+++
@@ -1,5 +1,5 @@
# List of apps that will use the users database
-USERS_DATABASE_APPS = ['auth','login','sessions']
+USERS_DATABASE_APPS = ['auth', 'login', 'sessions', 'contenttypes', 'sites']
class UserRouter(object):
"""
@@ -12,8 +12,6 @@
"""
if model._meta.app_label in USERS_DATA... |
6f5e4ff4f8e4002566a9ac18bcb22778be9409bd | electro/api.py | electro/api.py | # -*- coding: utf-8 -*-
from electro.errors import ResourceDuplicatedDefinedError
class API(object):
def __init__(self, app=None, decorators=None,
catch_all_404s=None):
self.app = app
self.endpoints = set()
self.decorators = decorators or []
self.catch_all_404s = catch... | # -*- coding: utf-8 -*-
from electro.errors import ResourceDuplicatedDefinedError
class API(object):
def __init__(self, app=None, decorators=None,
catch_all_404s=None):
self.app = app
self.endpoints = set()
self.decorators = decorators or []
self.catch_all_404s = catch... | Add endpoint for flask app. | Add endpoint for flask app.
| Python | mit | soasme/electro | ---
+++
@@ -24,4 +24,4 @@
resource_func = resource.as_view(endpoint)
for decorator in self.decorators:
resource_func = decorator(resource_func)
- self.app.add_url_rule(url, view_func=resource_func, **kw)
+ self.app.add_url_rule(url, view_func=resource_func, endpoint=endpoi... |
92b2c210133d1be628330db37b1ac69278bf99b5 | config.py | config.py | import os
import jinja2
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = False
SECRET_KEY = 'this is not secret'
STATIC_URL_PATH = '/supplier/static'
ASSET_PATH = STATIC_URL_PATH + '/'
BASE_TEMPLATE_DATA = {
'asset_path': ASSET_PATH,
'header_class... | import os
import jinja2
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = False
SECRET_KEY = 'this is not secret'
STATIC_URL_PATH = '/suppliers/static'
ASSET_PATH = STATIC_URL_PATH + '/'
BASE_TEMPLATE_DATA = {
'asset_path': ASSET_PATH,
'header_clas... | Fix static path to match the /suppliers URL prefix | Fix static path to match the /suppliers URL prefix
| Python | mit | alphagov/digitalmarketplace-supplier-frontend,mtekel/digitalmarketplace-supplier-frontend,mtekel/digitalmarketplace-supplier-frontend,mtekel/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,mtekel/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,alphag... | ---
+++
@@ -7,7 +7,7 @@
class Config(object):
DEBUG = False
SECRET_KEY = 'this is not secret'
- STATIC_URL_PATH = '/supplier/static'
+ STATIC_URL_PATH = '/suppliers/static'
ASSET_PATH = STATIC_URL_PATH + '/'
BASE_TEMPLATE_DATA = {
'asset_path': ASSET_PATH, |
d0ae974d737ff173cd8af159f869be7d69db08cd | tests/functional/test_l10n.py | tests/functional/test_l10n.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import random
import pytest
from ..pages.home import HomePage
@pytest.mark.nondestructive
def test_change_language(b... | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import random
import pytest
from ..pages.home import HomePage
@pytest.mark.nondestructive
def test_change_language(b... | Exclude redirected locales from homepage language selector functional tests | Exclude redirected locales from homepage language selector functional tests
| Python | mpl-2.0 | MichaelKohler/bedrock,glogiotatidis/bedrock,gerv/bedrock,pascalchevrel/bedrock,sylvestre/bedrock,gerv/bedrock,mkmelin/bedrock,sgarrity/bedrock,alexgibson/bedrock,gauthierm/bedrock,TheJJ100100/bedrock,CSCI-462-01-2017/bedrock,glogiotatidis/bedrock,gerv/bedrock,mkmelin/bedrock,mkmelin/bedrock,mermi/bedrock,analytics-pros... | ---
+++
@@ -13,9 +13,10 @@
def test_change_language(base_url, selenium):
page = HomePage(base_url, selenium).open()
initial = page.footer.language
- available = page.footer.languages
- available.remove(initial) # avoid selecting the same language
- new = random.choice(available) # pick a random ... |
6daa585138413b38e04cae940d973bb9e13aa387 | registration/__init__.py | registration/__init__.py | VERSION = (0, 9, 0, 'beta', 1)
def get_version():
from django.utils.version import get_version as django_get_version
return django_get_version(VERSION) # pragma: no cover
| VERSION = (1, 0, 0, 'final', 0)
def get_version():
"Returns a PEP 386-compliant version number from VERSION."
assert len(VERSION) == 5
assert VERSION[3] in ('alpha', 'beta', 'rc', 'final')
# Now build the two parts of the version number:
# main = X.Y[.Z]
# sub = .devN - for pre-alpha releases... | Fix version number reporting so we can be installed before Django. | Fix version number reporting so we can be installed before Django.
| Python | bsd-3-clause | stillmatic/django-registration,matejkloska/django-registration,yorkedork/django-registration,wda-hb/test,alawnchen/django-registration,PSU-OIT-ARC/django-registration,memnonila/django-registration,kazitanvirahsan/django-registration,allo-/django-registration,PetrDlouhy/django-registration,Geffersonvivan/django-registra... | ---
+++
@@ -1,6 +1,22 @@
-VERSION = (0, 9, 0, 'beta', 1)
+VERSION = (1, 0, 0, 'final', 0)
def get_version():
- from django.utils.version import get_version as django_get_version
- return django_get_version(VERSION) # pragma: no cover
+ "Returns a PEP 386-compliant version number from VERSION."
+ asse... |
b73691f2c9f10f44ecd87fe9a6a18bb14a570e6d | modules/admin.py | modules/admin.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from flask import Blueprint, render_template
import subprocess
import tempfile
import os
admin_controller = Blueprint('admin_controller', 'admin_controller',
template_folder='templates')
@admin_controller.route('/admin/exportlanguages')
def exportlan... | #!/usr/bin/python
# -*- coding: utf-8 -*-
from flask import Blueprint, render_template
import subprocess
import tempfile
import os
admin_controller = Blueprint('admin_controller', 'admin_controller',
template_folder='templates')
@admin_controller.route('/admin/exportlanguages')
def exportlan... | Use a secondary language database for development | Use a secondary language database for development
| Python | bsd-3-clause | xlexi/pastedirectory,xlexi/pastedirectory,xlexi/pastedirectory,xlexi/pastedirectory | ---
+++
@@ -13,7 +13,7 @@
@admin_controller.route('/admin/exportlanguages')
def exportlanguages():
tempfilename = tempfile.TemporaryFile()
- subprocess.Popen(['mongoexport', '-d', 'pastedirectory', '-c', 'languages', '-o', tempfilename])
+ subprocess.Popen(['mongoexport', '-d', 'pastedirectory', '-c', 'languages_... |
a2444bd563b2e8e5b774e2f229583532f4d454ed | myhdl/_compat.py | myhdl/_compat.py | import sys
import types
PY2 = sys.version_info[0] == 2
PYPY = hasattr(sys, 'pypy_translation_info')
_identity = lambda x: x
if not PY2:
string_types = (str,)
integer_types = (int,)
long = int
class_types = (type,)
from io import StringIO
import builtins
def to_bytes(s):
return s... | from __future__ import print_function
from __future__ import division
import sys
import types
from ast import PyCF_ONLY_AST
PY2 = sys.version_info[0] == 2
PYPY = hasattr(sys, 'pypy_translation_info')
_identity = lambda x: x
if not PY2:
string_types = (str,)
integer_types = (int,)
long = int
class_typ... | Create a compatible ast.parse with PY3 | Create a compatible ast.parse with PY3
Created a function compatible with both PY2 and PY3 equivalent to
ast.parse.
| Python | lgpl-2.1 | jmgc/myhdl-numeric,jmgc/myhdl-numeric,jmgc/myhdl-numeric | ---
+++
@@ -1,5 +1,8 @@
+from __future__ import print_function
+from __future__ import division
import sys
import types
+from ast import PyCF_ONLY_AST
PY2 = sys.version_info[0] == 2
PYPY = hasattr(sys, 'pypy_translation_info')
@@ -31,3 +34,7 @@
to_bytes = _identity
to_str = _identity
+
+def ast_pars... |
c5e2b375cc722f717c2b159451b8ca1e45060e83 | models.py | models.py | from django.db import models
from django.conf import settings
import urllib, urllib2
C2DM_URL = 'https://android.apis.google.com/c2dm/send'
class C2DMProfile(models.Model):
deviceId = models.CharField(max_length = 64)
registrationId = models.CharField(max_length = 140)
collapseKey = models.CharField(max_... | from django.db import models
from django.conf import settings
import urllib, urllib2
C2DM_URL = 'https://android.apis.google.com/c2dm/send'
class C2DMProfile(models.Model):
'''
Profile of a c2dm-enabled Android device
device_id - Unique ID for the device. Simply used as a default method to specify a de... | Add documentation and utility functions | Add documentation and utility functions
| Python | bsd-3-clause | scottferg/django-c2dm | ---
+++
@@ -6,14 +6,30 @@
C2DM_URL = 'https://android.apis.google.com/c2dm/send'
class C2DMProfile(models.Model):
- deviceId = models.CharField(max_length = 64)
- registrationId = models.CharField(max_length = 140)
- collapseKey = models.CharField(max_length = 50)
+ '''
+ Profile of a c2dm-enabled ... |
d042f4ced40d8d03bd65edf798a29058f26e98c6 | test/test_wsstat.py | test/test_wsstat.py | import hashlib
from wsstat.main import WebsocketTestingClient, ConnectedWebsocketConnection
class Tests(object):
def setup(self):
self.client = WebsocketTestingClient('wss://testserver/', total_connections=1, max_connecting_sockets=1)
def teardown(self):
pass
class TestConnectedWebsocketConn... | import hashlib
from wsstat.main import WebsocketTestingClient, ConnectedWebsocketConnection
class Tests(object):
def setup(self):
self.client = WebsocketTestingClient('wss://testserver/', total_connections=3, max_connecting_sockets=3)
def test_coroutines(self):
print(self.client)
asse... | Add a test for running tasks | Add a test for running tasks
| Python | mit | Fitblip/wsstat | ---
+++
@@ -4,10 +4,12 @@
class Tests(object):
def setup(self):
- self.client = WebsocketTestingClient('wss://testserver/', total_connections=1, max_connecting_sockets=1)
+ self.client = WebsocketTestingClient('wss://testserver/', total_connections=3, max_connecting_sockets=3)
- def teardow... |
c9f2ecea38711db75235aca2879f9a0b14762c9f | tests/test_spell.py | tests/test_spell.py | # -*- coding: utf-8 -*-
import datetime
import os
import sys
import unittest
from pythainlp.spell import NorvigSpellChecker, correct, spell
class TestSpellPackage(unittest.TestCase):
def test_spell(self):
self.assertEqual(spell(None), [""])
self.assertEqual(spell(""), [""])
result = sp... | # -*- coding: utf-8 -*-
import datetime
import os
import sys
import unittest
from pythainlp.spell import NorvigSpellChecker, correct, spell
class TestSpellPackage(unittest.TestCase):
def test_spell(self):
self.assertEqual(spell(None), [""])
self.assertEqual(spell(""), [""])
result = sp... | Add unittest for correct function in spell module | Add unittest for correct function in spell module
| Python | apache-2.0 | PyThaiNLP/pythainlp | ---
+++
@@ -25,6 +25,9 @@
def test_word_correct(self):
self.assertEqual(correct(None), "")
self.assertEqual(correct(""), "")
+ self.assertEqual(correct("1"), "1")
+ self.assertEqual(correct("56"), "56")
+ self.assertEqual(correct("1.01"), "1.01")
result = correct... |
5984c55a555ef88068f33a28c45a449416ee2896 | src/models/invalidated_token.py | src/models/invalidated_token.py | from src.main import db
from sqlalchemy.sql import func
class InvalidatedToken(db.Model):
token = db.Column(db.String(120), primary_key=True)
invalidated_date = db.Column(db.DateTime(timezone = True), server_default = func.now())
def __init__(self, token):
self.token = token
def __repr__(self... | from src.main import db
from sqlalchemy.sql import func
class InvalidatedToken(db.Model):
token = db.Column(db.String(120), primary_key=True)
invalidated_date = db.Column(db.DateTime(timezone = True), server_default = func.now())
def __init__(self, token):
self.token = token
def __repr__(self... | Fix for representation of InvalidatedToken model. | Fix for representation of InvalidatedToken model.
| Python | apache-2.0 | tomaszguzialek/flask-api,tomaszguzialek/flask-api,tomaszguzialek/flask-api | ---
+++
@@ -9,7 +9,7 @@
self.token = token
def __repr__(self):
- return '<InvalidatedToken %s, %s>' % self.token, str(self.invalidated_date)
+ return '<InvalidatedToken %s, %s>' % (self.token, str(self.invalidated_date))
def jsonify(self):
"""Return JSON representation of ... |
b12ff9bbdea517a9ac70f9ea2f06c50e110da003 | pyramid/__init__.py | pyramid/__init__.py | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# The pyramid module
__version__ = "0.6.1-dev0"
try:
# this var is injected in the setup build to enable
# the retrieval of the version number without actually
# importing the un-built submodules.
__PYRAMID_SETUP__
excep... | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# The pyramid module
__version__ = "0.6.2"
try:
# this var is injected in the setup build to enable
# the retrieval of the version number without actually
# importing the un-built submodules.
__PYRAMID_SETUP__
except Nam... | Increment minor version for :fire: HOTFIX release | Increment minor version for :fire: HOTFIX release
| Python | mit | alkaline-ml/pmdarima,tgsmith61591/pyramid,tgsmith61591/pyramid,tgsmith61591/pyramid,alkaline-ml/pmdarima,alkaline-ml/pmdarima | ---
+++
@@ -4,7 +4,7 @@
#
# The pyramid module
-__version__ = "0.6.1-dev0"
+__version__ = "0.6.2"
try:
# this var is injected in the setup build to enable |
bc313462e7d1d1e45cfa0b15baf668b96569f52f | python/wordcount.py | python/wordcount.py | import sys, re
counts = {}
for line in sys.stdin:
for word in re.findall(r'[A-Za-z\']+', line.lower()):
counts[word] = counts.get(word, 0) + 1
for word, count in sorted(counts.items()):
print(word, count)
| import sys, re
counts = {}
for line in sys.stdin:
for word in re.findall(r'[a-z\']+', line.lower()):
counts[word] = counts.get(word, 0) + 1
for word, count in sorted(counts.items()):
print(word, count)
| Use a more efficient regex | Use a more efficient regex
| Python | mit | rtoal/ple,rtoal/ple,rtoal/ple,rtoal/ple,rtoal/polyglot,rtoal/ple,rtoal/ple,rtoal/polyglot,rtoal/polyglot,rtoal/polyglot,rtoal/ple,rtoal/polyglot,rtoal/polyglot,rtoal/polyglot,rtoal/polyglot,rtoal/ple,rtoal/ple,rtoal/ple,rtoal/ple,rtoal/ple,rtoal/ple,rtoal/ple,rtoal/ple,rtoal/polyglot,rtoal/polyglot,rtoal/polyglot,rtoal... | ---
+++
@@ -2,7 +2,7 @@
counts = {}
for line in sys.stdin:
- for word in re.findall(r'[A-Za-z\']+', line.lower()):
+ for word in re.findall(r'[a-z\']+', line.lower()):
counts[word] = counts.get(word, 0) + 1
for word, count in sorted(counts.items()): |
f5d9fbf618f44e8572344e04e9a09c7cae3302bb | neurodsp/plts/__init__.py | neurodsp/plts/__init__.py | """Plotting functions."""
from .time_series import plot_time_series, plot_bursts
from .filt import plot_filter_properties, plot_frequency_response, plot_impulse_response
from .rhythm import plot_swm_pattern, plot_lagged_coherence
from .spectral import plot_power_spectra, plot_scv, plot_scv_rs_lines, plot_scv_rs_matrix... | """Plotting functions."""
from .time_series import plot_time_series, plot_bursts, plot_instantaneous_measure
from .filt import plot_filter_properties, plot_frequency_response, plot_impulse_response
from .rhythm import plot_swm_pattern, plot_lagged_coherence
from .spectral import plot_power_spectra, plot_scv, plot_scv_... | Make plot_instantaneous_measure accessible from root of plots | Make plot_instantaneous_measure accessible from root of plots
| Python | apache-2.0 | voytekresearch/neurodsp | ---
+++
@@ -1,6 +1,6 @@
"""Plotting functions."""
-from .time_series import plot_time_series, plot_bursts
+from .time_series import plot_time_series, plot_bursts, plot_instantaneous_measure
from .filt import plot_filter_properties, plot_frequency_response, plot_impulse_response
from .rhythm import plot_swm_patte... |
a06c4da0cc683162b8ecf8569f6d8878b8d45872 | examples/esp8266/lux_sensor_demo.py | examples/esp8266/lux_sensor_demo.py | # Simple demo of reading the tsl2591 lux sensor from the
# ESP8266 running micropython.
from antevents import *
from tsl2591 import Tsl2591
tsl = Tsl2591('lux-1')
tsl.sample()
sched = Scheduler()
class Output:
def on_next(self, x):
print(x)
def on_completed():
pass
def on_error(self, e):
... | # Simple demo of reading the tsl2591 lux sensor from the
# ESP8266 running micropython.
from antevents import *
from tsl2591 import Tsl2591
tsl = Tsl2591('lux-1')
tsl.sample()
sched = Scheduler()
class Output:
def on_next(self, x):
print(x)
def on_completed():
pass
def on_error(self, e):
... | Fix missing paren (copy and paste error) | Fix missing paren (copy and paste error) | Python | apache-2.0 | mpi-sws-rse/antevents-python,mpi-sws-rse/antevents-python,mpi-sws-rse/thingflow-python,mpi-sws-rse/thingflow-python | ---
+++
@@ -15,5 +15,5 @@
def on_error(self, e):
pass
-sched.schedule_sensor(tsl, 2.0, Output()
+sched.schedule_sensor(tsl, 2.0, Output())
sched.run_forever() |
372cb5cfb74e207c169bec473eeed48497748d51 | nipype/utils/setup.py | nipype/utils/setup.py | from os.path import join
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('utils', parent_package, top_path)
config.add_data_dir('tests')
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
... | from os.path import join
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('utils', parent_package, top_path)
config.add_data_dir('tests')
try:
# If the user has IPython installed, this will install the
# nip... | Add install for nipype ipython profile. | Add install for nipype ipython profile.
git-svn-id: 24f545668198cdd163a527378499f2123e59bf9f@1352 ead46cd0-7350-4e37-8683-fc4c6f79bf00
| Python | bsd-3-clause | wanderine/nipype,JohnGriffiths/nipype,iglpdc/nipype,blakedewey/nipype,Leoniela/nipype,FredLoney/nipype,arokem/nipype,Leoniela/nipype,mick-d/nipype,glatard/nipype,dmordom/nipype,pearsonlab/nipype,pearsonlab/nipype,rameshvs/nipype,pearsonlab/nipype,sgiavasis/nipype,grlee77/nipype,arokem/nipype,wanderine/nipype,iglpdc/nip... | ---
+++
@@ -6,6 +6,18 @@
config.add_data_dir('tests')
+ try:
+ # If the user has IPython installed, this will install the
+ # nipype profile under their '~/.ipython' directory so they
+ # can launch ipython with 'ipython -p nipype' and the traits
+ # completer will be enabled b... |
259b212c68233ed56f9bc3123d85ea28f885af78 | dijkstraNew.py | dijkstraNew.py | class DijkstraNew:
def __init__(self,edges,start):
self.edges = edges
self.take_shorter_edges() # Bei doppelten Kanten kürzere nehmen
self.start = start
self.edges_in_dijkstra = [] # Kanten, über die Dijkstra geht
self.visible_edges = [] # Sichtbare Kanten
self.visibl... | class DijkstraNew:
def __init__(self,edges,start):
self.edges = edges
self.take_shorter_edges() # Bei doppelten Kanten kürzere nehmen
self.start = start
self.edges_in_dijkstra = [] # Kanten, über die Dijkstra geht
self.visible_edges = [] # Sichtbare Kanten
self.visibl... | Delete long edges if there are multiple edges between the same two nodes | Delete long edges if there are multiple edges between the same two nodes
| Python | apache-2.0 | NWuensche/DijkstraInPython | ---
+++
@@ -6,3 +6,31 @@
self.edges_in_dijkstra = [] # Kanten, über die Dijkstra geht
self.visible_edges = [] # Sichtbare Kanten
self.visible_nodes = [start] # Besuchte Knoten
+
+ # Falls doppelte Kanten zwischen Knoten, dann nur kürzesten lassen
+ def take_shorter_edges(self):
+ ... |
b5871e451955e993ea368cb832714612a6dd48d1 | fog-aws-testing/scripts/test_all.py | fog-aws-testing/scripts/test_all.py | #!/usr/bin/python
from threading import Thread
import subprocess
from functions import *
def runTest(branch,os):
subprocess.call(test_script + " " + branch + " " + os, shell=True)
for branch in branches:
threads = []
for os in OSs:
instance = get_instance("Name","fogtesting-" + os)
sna... | #!/usr/bin/python
from threading import Thread
import subprocess
from functions import *
def runTest(branch,os):
subprocess.call(test_script + " " + branch + " " + os, shell=True)
from functions import *
threads = []
for os in OSs:
instance = get_instance("Name","fogtesting-" + os)
snapshot = get_snapsho... | Use threading when restoring snapshots during testing | Use threading when restoring snapshots during testing
| Python | mit | FOGProject/fog-community-scripts,FOGProject/fog-community-scripts,FOGProject/fog-community-scripts | ---
+++
@@ -5,18 +5,55 @@
def runTest(branch,os):
subprocess.call(test_script + " " + branch + " " + os, shell=True)
-
+
+from functions import *
+
+threads = []
+for os in OSs:
+ instance = get_instance("Name","fogtesting-" + os)
+ snapshot = get_snapshot("Name",os + '-clean')
+ if os == "debian... |
30a81d64c513d23aae6dc6cc51fa047d6479150f | halo/_utils.py | halo/_utils.py | """Utilities for Halo library.
"""
import platform
import six
import codecs
from colorama import init, Fore
from termcolor import colored
init(autoreset=True)
def is_supported():
"""Check whether operating system supports main symbols or not.
Returns
-------
boolean
Whether operating sys... | """Utilities for Halo library.
"""
import platform
import six
import codecs
from colorama import init, Fore
from termcolor import colored
init(autoreset=True)
def is_supported():
"""Check whether operating system supports main symbols or not.
Returns
-------
boolean
Whether operating sys... | Remove support for windows till fully tested | Halo: Remove support for windows till fully tested
| Python | mit | ManrajGrover/halo,manrajgrover/halo | ---
+++
@@ -18,9 +18,9 @@
Whether operating system supports main symbols or not
"""
- os_arch = platform.system() + str(platform.architecture()[0])
+ os_arch = platform.system()
- if os_arch != 'Windows32bit':
+ if os_arch != 'Windows':
return True
return False |
0bd93ad8fa88287452326ee635bbbb5d2c685a06 | permissions/tests/base.py | permissions/tests/base.py | from django.test import TestCase as BaseTestCase
from django.test import RequestFactory
from permissions import PermissionsRegistry as BasePermissionsRegistry
class PermissionsRegistry(BasePermissionsRegistry):
def _get_user_model(self):
return User
def _get_model_instance(self, model, **kwargs):
... | from django.test import TestCase as BaseTestCase
from django.test import RequestFactory
from permissions import PermissionsRegistry as BasePermissionsRegistry
class PermissionsRegistry(BasePermissionsRegistry):
def _get_user_model(self):
return User
def _get_model_instance(self, model, **kwargs):
... | Make mock Model class extend object for Python 2 compat | Make mock Model class extend object for Python 2 compat
| Python | mit | PSU-OIT-ARC/django-perms,wylee/django-perms | ---
+++
@@ -14,7 +14,7 @@
return model(**kwargs)
-class Model:
+class Model(object):
def __init__(self, **kwargs):
for k, v in kwargs.items(): |
a2f13a262e22187adaf9586aac951005f43c81b3 | searchlight/opts.py | searchlight/opts.py | import itertools
import searchlight.common.wsgi
def list_opts():
return [
('DEFAULT',
itertools.chain(searchlight.common.wsgi.bind_opts,
searchlight.common.wsgi.socket_opts,
searchlight.common.wsgi.eventlet_opts)),
('profiler',
i... | import itertools
import searchlight.common.wsgi
import searchlight.common.property_utils
import searchlight.common.config
def list_opts():
return [
('DEFAULT',
itertools.chain(searchlight.common.wsgi.bind_opts,
searchlight.common.wsgi.socket_opts,
... | Add some common config options | Add some common config options
| Python | apache-2.0 | openstack/searchlight,openstack/searchlight,lakshmisampath/searchlight,openstack/searchlight | ---
+++
@@ -1,6 +1,8 @@
import itertools
import searchlight.common.wsgi
+import searchlight.common.property_utils
+import searchlight.common.config
def list_opts():
@@ -8,7 +10,11 @@
('DEFAULT',
itertools.chain(searchlight.common.wsgi.bind_opts,
searchlight.common... |
2c11dd51db3a7663aa31913fa68656f60a80fcf6 | select2/__init__.py | select2/__init__.py | __version_info__ = (1, 0, 6)
__version__ = '.'.join(map(str, __version_info__))
| __version_info__ = (1, 1, 0)
__version__ = '.'.join(map(str, __version_info__))
| Increment version number to 1.1.0 | Increment version number to 1.1.0
| Python | bsd-2-clause | hkmshb/django-select2-forms,sandow-digital/django-select2-forms,sandow-digital/django-select2-forms,SpectralAngel/django-select2-forms,hkmshb/django-select2-forms,SpectralAngel/django-select2-forms,sandow-digital/django-select2-forms,hkmshb/django-select2-forms,JP-Ellis/django-select2-forms,SpectralAngel/django-select2... | ---
+++
@@ -1,2 +1,2 @@
-__version_info__ = (1, 0, 6)
+__version_info__ = (1, 1, 0)
__version__ = '.'.join(map(str, __version_info__)) |
6e6aa02907b3d156174cfe1a5f8e9c274c080778 | SegNetCMR/helpers.py | SegNetCMR/helpers.py | import tensorflow as tf
def add_output_images(images, logits, labels):
cast_labels = tf.cast(labels, tf.uint8) * 128
cast_labels = cast_labels[...,None]
tf.summary.image('input_labels', cast_labels, max_outputs=3)
classification1 = tf.nn.softmax(logits = logits, dim=-1)[...,1]
output_image_gb = im... | import tensorflow as tf
def add_output_images(images, logits, labels):
cast_labels = tf.cast(labels, tf.uint8) * 128
cast_labels = cast_labels[...,None]
tf.summary.image('input_labels', cast_labels, max_outputs=3)
classification1 = tf.nn.softmax(logits = logits, dim=-1)[...,1]
output_image_gb = im... | Add output with images mixed with binary version of output labels | Add output with images mixed with binary version of output labels
| Python | mit | mshunshin/SegNetCMR,mshunshin/SegNetCMR | ---
+++
@@ -15,5 +15,9 @@
output_image_binary = tf.cast(output_image_binary[...,None], tf.float32) * 128/255
tf.summary.image('output_labels', output_image_binary, max_outputs=3)
+ output_labels_mixed_r = output_image_binary[...,0] + tf.multiply(images[...,0], (1-output_image_binary[...,0]))
+ outpu... |
0751ee8ea1153ca1227fafcfbca1dc00fc148c4b | qual/calendar.py | qual/calendar.py | from datetime import date, timedelta
class DateWithCalendar(object):
def __init__(self, calendar_class, date):
self.calendar = calendar_class
self.date = date
def convert_to(self, calendar):
return calendar.from_date(self.date)
def __eq__(self, other):
return self.calendar... | from datetime import date, timedelta
class DateWithCalendar(object):
def __init__(self, calendar_class, date):
self.calendar = calendar_class
self.date = date
def convert_to(self, calendar):
return calendar.from_date(self.date)
def __eq__(self, other):
return self.calendar... | Move from_date() into an abstract base class. | Move from_date() into an abstract base class.
| Python | apache-2.0 | jwg4/qual,jwg4/calexicon | ---
+++
@@ -11,20 +11,18 @@
def __eq__(self, other):
return self.calendar == other.calendar and self.date == other.date
-class ProlepticGregorianCalendar(object):
+class Calendar(object):
+ def from_date(self, date):
+ return DateWithCalendar(self.__class__, date)
+
+class ProlepticGregorian... |
d42c0c31f040ff684c738de975e94270b93f399a | logTemps.py | logTemps.py | ######################################################
# logs time, fahrenheit and humidity every 5 minutes
#
######################################################
import time
import HTU21DF
import logging
logging.basicConfig(filename='sampleDay.log',level=logging.DEBUG,format='%(asctime)s\t%(message)s',datefmt='%m/%... | ######################################################
# logs time, fahrenheit and humidity every 5 minutes
#
######################################################
import time
import HTU21DF
import logging
logging.basicConfig(filename='sampleDay.log',level=logging.DEBUG,format='%(asctime)s\t%(message)s',datefmt='%Y-%... | Update log time, remove messages | Update log time, remove messages
| Python | mit | khuisman/project-cool-attic | ---
+++
@@ -6,7 +6,7 @@
import time
import HTU21DF
import logging
-logging.basicConfig(filename='sampleDay.log',level=logging.DEBUG,format='%(asctime)s\t%(message)s',datefmt='%m/%d/%Y %I:%M:%S %p')
+logging.basicConfig(filename='sampleDay.log',level=logging.DEBUG,format='%(asctime)s\t%(message)s',datefmt='%Y-%m-%d... |
43f4d3394e184f9984f10cbeec51ca561a8d548c | shellish/logging.py | shellish/logging.py | """
A logging handler that's tty aware.
"""
import logging
from . import rendering
class VTMLHandler(logging.StreamHandler):
""" Parse VTML messages to colorize and embolden logs. """
log_format = '[<blue>%(asctime)s</blue>] [%(levelname)s] %(message)s'
level_fmt = {
10: '<dim>%s</dim>',
... | """
A logging handler that's tty aware.
"""
import logging
from . import rendering
class VTMLHandler(logging.StreamHandler):
""" Parse VTML messages to colorize and embolden logs. """
log_format = '[<blue>%(asctime)s</blue>] [<cyan>%(name)s</cyan>] ' \
'[%(levelname)s] %(message)s'
level_fmt = {... | Add logger name to default log format. | Add logger name to default log format.
| Python | mit | mayfield/shellish | ---
+++
@@ -9,7 +9,8 @@
class VTMLHandler(logging.StreamHandler):
""" Parse VTML messages to colorize and embolden logs. """
- log_format = '[<blue>%(asctime)s</blue>] [%(levelname)s] %(message)s'
+ log_format = '[<blue>%(asctime)s</blue>] [<cyan>%(name)s</cyan>] ' \
+ '[%(levelname)s] %(message)... |
c218603fc429f60a6935de88bee50bc1db3f6fb9 | app/awards/models.py | app/awards/models.py | from enum import Enum
from app import db
class AwardCategory(Enum):
Champions = 0
Research = 1
Presentation = 2
Innovative_Solution = 3
Mechanical_Design = 4
Programming = 5
Strategy_and_Innovation = 6
Teamwork = 7
Inspiration = 8
Gracious_Professionalism = 9
Robot_Performa... | from enum import Enum
from app import db
class AwardCategory(Enum):
Champions = 0
Research = 1
Presentation = 2
Innovative_Solution = 3
Mechanical_Design = 4
Programming = 5
Strategy_and_Innovation = 6
Teamwork = 7
Inspiration = 8
Gracious_Professionalism = 9
Robot_Performa... | Fix formatting to follow PEP8 | Fix formatting to follow PEP8
| Python | mit | rtfoley/scorepy,rtfoley/scorepy,rtfoley/scorepy | ---
+++
@@ -35,9 +35,9 @@
@property
def friendly_award_name(self):
- if self.place==0:
+ if self.place == 0:
place_text = "1st"
- elif self.place==1:
+ elif self.place == 1:
place_text = "2nd"
else:
place_text = "3rd" |
71a182665e0e131f14bcefe52e8a8e7b2ffe674d | server/run.py | server/run.py | """Run a server that takes all GET requests and dumps them."""
from flask import Flask, request, send_from_directory
from flask_cors import CORS
from w3lib.html import replace_entities
app = Flask(__name__)
CORS(app)
@app.route('/')
def route():
"""Get all GET and POST requests and dump them to logs."""
# ... | """Run a server that takes all GET requests and dumps them."""
from flask import Flask, request, send_from_directory
from flask_cors import CORS
from w3lib.html import replace_entities
app = Flask(__name__)
CORS(app)
@app.route('/')
def route():
"""Get all GET and POST requests and dump them to logs."""
# ... | Add seperate key log handler | Add seperate key log handler
| Python | apache-2.0 | umisc/listenserv | ---
+++
@@ -17,6 +17,11 @@
with open("cap.log", "a") as f:
f.write(replace_entities(str(request.url)) + "\n")
+ with open("key.log", "a") as f:
+ if "c" in request.get:
+ keys = replace_entities(request.get['c'])
+ f.write(keys + '\n')
+
return "WARNING: This site ... |
bb195d3290d2e9921df8b989ac0d2123a6b9a7f8 | server/run.py | server/run.py | """Run a server that takes all GET requests and dumps them."""
from flask import Flask, request, send_from_directory
from flask_cors import CORS
from w3lib.html import replace_entities
app = Flask(__name__)
CORS(app)
@app.route('/')
def route():
"""Get all GET and POST requests and dump them to logs."""
# ... | """Run a server that takes all GET requests and dumps them."""
from json import loads
from flask import Flask, request, send_from_directory
from flask_cors import CORS
from w3lib.html import replace_entities
app = Flask(__name__)
CORS(app)
@app.route('/')
def route():
"""Get all GET and POST requests and dump... | Make it yet even easier to read key logger output | Make it yet even easier to read key logger output
| Python | apache-2.0 | umisc/listenserv | ---
+++
@@ -1,4 +1,6 @@
"""Run a server that takes all GET requests and dumps them."""
+
+from json import loads
from flask import Flask, request, send_from_directory
@@ -19,7 +21,13 @@
with open("key.log", "a") as f:
if "c" in request.args:
- keys = replace_entities(request.args.get(... |
440cd5bdd7806d7e67345153dd37a8aa4e50e283 | site/pelicanconf.py | site/pelicanconf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = 'Mike'
SITENAME = 'Conversations with Mike the Turtle'
SITEURL = ''
RELATIVE_URLS = True
PATH = 'content'
TIMEZONE = 'America/New_York'
DEFAULT_LANG = 'en'
# Feed generation is usually not desired when developing
FEED_... | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = 'Mike'
SITENAME = 'Conversations with Mike the Turtle'
SITEURL = ''
RELATIVE_URLS = True
PATH = 'content'
TIMEZONE = 'America/New_York'
DEFAULT_LANG = 'en'
# Feed generation is usually not desired when developing
FEED_... | Update pelcian conf to reflect theme change | Update pelcian conf to reflect theme change
| Python | mit | dankolbman/CleverTind,dankolbman/CleverTind | ---
+++
@@ -28,8 +28,8 @@
STATIC_PATHS = ['images']
-THEME = 'themes/blueidea'
-THEME_STATIC_DIR = 'blueidea/static'
+THEME = 'themes/blue_idea'
+THEME_STATIC_DIR = 'blue_idea/static'
DEFAULT_PAGINATION = 100
|
a49b000dc5426542aadc4b4fb4d244a4186ed7bb | bot/action/standard/admin/fail.py | bot/action/standard/admin/fail.py | from bot.action.core.action import Action
from bot.action.util.textformat import FormattedText
class FailAction(Action):
def process(self, event):
api = self.api
error = NotARealError("simulated error")
response = FormattedText().bold("Simulating bot error...")
args = event.command... | from bot.action.core.action import Action
from bot.action.util.textformat import FormattedText
class FailAction(Action):
def process(self, event):
api = self.api.no_async
error = NotARealError("simulated error")
response = FormattedText().bold("Simulating bot error...")
args = even... | Use no_async api by default in FailAction | Use no_async api by default in FailAction
| Python | agpl-3.0 | alvarogzp/telegram-bot,alvarogzp/telegram-bot | ---
+++
@@ -4,7 +4,7 @@
class FailAction(Action):
def process(self, event):
- api = self.api
+ api = self.api.no_async
error = NotARealError("simulated error")
response = FormattedText().bold("Simulating bot error...")
args = event.command_args.split() |
7d8c724abc4b5a692bd046313774921bc288f7a4 | src/unittest/python/daemonize_tests.py | src/unittest/python/daemonize_tests.py | from __future__ import print_function, absolute_import, division
from unittest2 import TestCase
from mock import patch
from succubus import Daemon
class TestDaemonize(TestCase):
@patch('succubus.daemonize.sys')
def test_must_pop_sys_argv_before_loading_config(self, mock_sys):
"""The sys.argv.pop() ... | from __future__ import print_function, absolute_import, division
from unittest2 import TestCase
from mock import patch
from succubus import Daemon
class TestDaemonize(TestCase):
@patch('succubus.daemonize.sys')
def test_must_pop_sys_argv_before_loading_config(self, mock_sys):
"""The sys.argv.pop() ... | Test that set_(g|u)id actually changes the id | Test that set_(g|u)id actually changes the id
| Python | apache-2.0 | ImmobilienScout24/succubus | ---
+++
@@ -24,3 +24,21 @@
mock_sys.argv = ['foo', 'start', '--config=xyz']
a = MyDaemon(pid_file='foo.pid')
+
+ @patch("succubus.daemonize.os.setgid")
+ def test_set_gid_translates_group_name(self, mock_setgid):
+ daemon = Daemon(pid_file="foo")
+ daemon.group = "root"
+
+ ... |
a894e53d48737f5b9ddc3cc2f5ffe4de98b558dd | forum/forms.py | forum/forms.py | from django.forms import ModelForm,Textarea,TextInput
from .models import Post
class PostForm(ModelForm):
class Meta:
model = Post
fields = ('subject','body')
widgets = {
'subject': TextInput(attrs={'autofocus':'autofocus'}),
'body': Textarea(
... | from django.forms import ModelForm,Textarea,TextInput
from .models import Post
class PostForm(ModelForm):
class Meta:
model = Post
fields = ('subject','body')
widgets = {
'subject': TextInput(attrs={'autofocus':'autofocus'}),
'body': Textarea(
... | Allow Markdown editor to be resized | Allow Markdown editor to be resized
| Python | mit | Kromey/fbxnano,Kromey/fbxnano,Kromey/fbxnano,Kromey/akwriters,Kromey/akwriters,Kromey/akwriters,Kromey/fbxnano,Kromey/akwriters | ---
+++
@@ -15,6 +15,7 @@
'data-provide':'markdown',
'data-hidden-buttons':'cmdHeading',
'data-iconlibrary':'octicons',
+ 'data-resize': 'vertical',
}),
}
|
53a442ac37bf58bca16dee2ad0787bdf2df98555 | nltk/test/gluesemantics_malt_fixt.py | nltk/test/gluesemantics_malt_fixt.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
def setup_module(module):
from nose import SkipTest
from nltk.parse.malt import MaltParser
try:
depparser = MaltParser()
except LookupError:
raise SkipTest("MaltParser is not available")
| # -*- coding: utf-8 -*-
from __future__ import absolute_import
def setup_module(module):
from nose import SkipTest
from nltk.parse.malt import MaltParser
try:
depparser = MaltParser('maltparser-1.7.2')
except LookupError:
raise SkipTest("MaltParser is not available")
| Add the malt parser directory name in the unittest | Add the malt parser directory name in the unittest
Fixes https://nltk.ci.cloudbees.com/job/nltk/TOXENV=py34-jenkins,jdk=jdk8latestOnlineInstall/lastCompletedBuild/testReport/%3Cnose/suite/ContextSuite_context_gluesemantics_malt_fixt__setup/ | Python | apache-2.0 | nltk/nltk,nltk/nltk,nltk/nltk | ---
+++
@@ -6,6 +6,6 @@
from nltk.parse.malt import MaltParser
try:
- depparser = MaltParser()
+ depparser = MaltParser('maltparser-1.7.2')
except LookupError:
raise SkipTest("MaltParser is not available") |
a1300dc059bd4eeb44654b75132c3e542caa29cc | staticgen_demo/blog/staticgen_views.py | staticgen_demo/blog/staticgen_views.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from staticgen.staticgen_pool import staticgen_pool
from staticgen.staticgen_views import StaticgenView
from .models import Post
class BlogPostListView(StaticgenView):
is_paginated = True
i18n = True
def items(self):
return ('blog... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from staticgen.staticgen_pool import staticgen_pool
from staticgen.staticgen_views import StaticgenView
from .models import Post
class BlogPostListView(StaticgenView):
is_paginated = True
i18n = True
def items(self):
return ('blog... | Add print statements to debug BlogPostListView | Add print statements to debug BlogPostListView
| Python | bsd-3-clause | mishbahr/staticgen-demo,mishbahr/staticgen-demo,mishbahr/staticgen-demo | ---
+++
@@ -15,6 +15,20 @@
def items(self):
return ('blog:posts_list', )
+ def _get_paginator(self, url):
+ response = self.client.get(url)
+ print response.status_code
+ print response.__dict__
+
+ if not response.status_code == 200:
+ pass
+ else:
+ ... |
79f60cdb3853a60fd2cf6e69a141ed7b756f86cb | giphy_magic.py | giphy_magic.py | from IPython.display import Image
import requests
API_ENDPOINT = 'http://api.giphy.com/v1/gifs/random'
API_KEY = 'dc6zaTOxFJmzC'
def giphy(tag):
params = {
'api_key': API_KEY,
'tag': tag
}
r = requests.get(API_ENDPOINT, params=params)
json = r.json()
data = json['data']
retu... | from IPython.display import Image
import requests
API_ENDPOINT = 'http://api.giphy.com/v1/gifs/random'
# This is the Giphy API's public beta key, see https://github.com/Giphy/GiphyAPI
API_KEY = 'dc6zaTOxFJmzC'
def giphy(tag):
params = {
'api_key': API_KEY,
'tag': tag
}
r = requests.get(... | Call out public beta key | Call out public beta key
| Python | mit | AustinRochford/giphy-ipython-magic,AustinRochford/giphy-ipython-magic | ---
+++
@@ -3,6 +3,8 @@
import requests
API_ENDPOINT = 'http://api.giphy.com/v1/gifs/random'
+
+# This is the Giphy API's public beta key, see https://github.com/Giphy/GiphyAPI
API_KEY = 'dc6zaTOxFJmzC'
def giphy(tag): |
aaaf8ef7433418f7a195c79674db56e03fc58f10 | apps/bplan/models.py | apps/bplan/models.py | from django.db import models
from adhocracy4.models.base import TimeStampedModel
from adhocracy4.modules import models as module_models
from apps.extprojects.models import ExternalProject
class Bplan(ExternalProject):
office_worker_email = models.EmailField()
class AnonymousItem(TimeStampedModel):
module =... | from django.contrib.auth.models import AnonymousUser
from django.db import models
from adhocracy4.models.base import TimeStampedModel
from adhocracy4.modules import models as module_models
from apps.extprojects.models import ExternalProject
class Bplan(ExternalProject):
office_worker_email = models.EmailField()
... | Add mockup creator property to AnonymousItems | Add mockup creator property to AnonymousItems
| Python | agpl-3.0 | liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin | ---
+++
@@ -1,3 +1,4 @@
+from django.contrib.auth.models import AnonymousUser
from django.db import models
from adhocracy4.models.base import TimeStampedModel
@@ -16,6 +17,14 @@
def project(self):
return self.module.project
+ @property
+ def creator(self):
+ return AnonymousUser()
+
+... |
d25167937a6e0f923d9c03cd94c227e96fdf12ba | pyalysis/analysers/raw.py | pyalysis/analysers/raw.py | # coding: utf-8
"""
pyalysis.analysers.raw
~~~~~~~~~~~~~~~~~~~~~~
:copyright: 2014 by Daniel Neuhäuser and Contributors
:license: BSD, see LICENSE.rst for details
"""
import codecs
from pyalysis.utils import detect_encoding
from pyalysis.warnings import LineTooLong
class LineAnalyser(object):
""... | # coding: utf-8
"""
pyalysis.analysers.raw
~~~~~~~~~~~~~~~~~~~~~~
:copyright: 2014 by Daniel Neuhäuser and Contributors
:license: BSD, see LICENSE.rst for details
"""
import codecs
from blinker import Signal
from pyalysis.utils import detect_encoding
from pyalysis.warnings import LineTooLong
class ... | Switch to signal based dispatch in LineAnalyser | Switch to signal based dispatch in LineAnalyser
| Python | bsd-3-clause | DasIch/pyalysis,DasIch/pyalysis | ---
+++
@@ -8,6 +8,8 @@
"""
import codecs
+from blinker import Signal
+
from pyalysis.utils import detect_encoding
from pyalysis.warnings import LineTooLong
@@ -16,6 +18,9 @@
"""
Line-level analyser of Python source code.
"""
+ on_analyse = Signal()
+ on_line = Signal()
+
def __init_... |
91162995c6425307cb586e663d4bf0241f68d588 | alg_fibonacci.py | alg_fibonacci.py | """Fibonacci series:
0, 1, 1, 2, 3, 5, 8,...
- Fib(0) = 0
- Fib(1) = 1
- Fib(n) = Fib(n - 1) + Fib(n - 2)
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def fibonacci_recur(n):
"""Get nth number of Fibonacci series by recursion."""
if n <= 1... | """Fibonacci series:
0, 1, 1, 2, 3, 5, 8,...
- Fib(0) = 0
- Fib(1) = 1
- Fib(n) = Fib(n - 1) + Fib(n - 2)
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def fibonacci_recur(n):
"""Get nth number of Fibonacci series by recursion."""
if n <= 1... | Complete fiboncci_dp() by dynamic programming | Complete fiboncci_dp() by dynamic programming
| Python | bsd-2-clause | bowen0701/algorithms_data_structures | ---
+++
@@ -19,14 +19,31 @@
return fibonacci_recur(n - 1) + fibonacci_recur(n - 2)
+def fibonacci_dp(n):
+ """Get nth number of Fibonacci series by dynamic programming.
+
+ DP performs much faster than recursion.
+ """
+ a, b = 0, 1
+ for _ in xrange(n):
+ a, b = a+b, a
+ return ... |
28a35d1434cb8dfdc9da130bd86518df4e8c6d4a | uniqueids/admin.py | uniqueids/admin.py | from django.contrib import admin
from .models import Record
from .tasks import send_personnel_code
class RecordAdmin(admin.ModelAdmin):
list_display = [
"id", "identity", "write_to", "created_at", "updated_at"]
list_filter = ["write_to", "created_at"]
search_fields = ["identity", "write_to"]
... | from django.contrib import admin
from .models import Record
from .tasks import send_personnel_code
class RecordAdmin(admin.ModelAdmin):
list_display = [
"id", "identity", "write_to", "created_at", "updated_at"]
list_filter = ["write_to", "created_at"]
search_fields = ["identity", "write_to"]
... | Improve formatting of resend action description | Improve formatting of resend action description
| Python | bsd-3-clause | praekelt/hellomama-registration,praekelt/hellomama-registration | ---
+++
@@ -24,7 +24,7 @@
created_text = "%s Records were" % created
self.message_user(request, "%s resent." % created_text)
- resend_personnel_code.short_description = "Send code by SMS (personnel "\
- "code only)"
+ resend_personnel_code.short_description = (
+ "Send code... |
d55dfc5152f6ebeabe761b627a26a9f00cc4e37c | {{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/libs/templatetags/url_tags.py | {{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/libs/templatetags/url_tags.py | # encoding: utf-8
from django import template
from django.http import QueryDict
from classytags.core import Tag, Options
from classytags.arguments import MultiKeywordArgument, MultiValueArgument
from libs.utils import canonical_url
register = template.Library()
@register.filter('canonical')
def _get_canonical_url... | # encoding: utf-8
from django import template
from django.http import QueryDict
from classytags.core import Tag, Options
from classytags.arguments import MultiKeywordArgument, MultiValueArgument
register = template.Library()
class QueryParameters(Tag):
name = 'query'
options = Options(
MultiKeyword... | Remove an old filter reference | Remove an old filter reference
| Python | mit | dulaccc/cookiecutter-django-herokuapp,dulaccc/cookiecutter-django-herokuapp,dulaccc/cookiecutter-django-herokuapp,dulaccc/cookiecutter-django-herokuapp | ---
+++
@@ -6,14 +6,7 @@
from classytags.core import Tag, Options
from classytags.arguments import MultiKeywordArgument, MultiValueArgument
-from libs.utils import canonical_url
-
register = template.Library()
-
-
-@register.filter('canonical')
-def _get_canonical_url(url):
- return canonical_url(url, protoco... |
128a9a98879fdd52f1f3fb04355fc3094f3769ba | scipy/signal/setup.py | scipy/signal/setup.py | #!/usr/bin/env python
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('signal', parent_package, top_path)
config.add_data_dir('tests')
config.add_extension('sigtools',
sources=['sigtoolsmodule.c',... | #!/usr/bin/env python
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('signal', parent_package, top_path)
config.add_data_dir('tests')
config.add_extension('sigtools',
sources=['sigtoolsmodule.c',... | Add newsig.c as a dependency to sigtools module. | Add newsig.c as a dependency to sigtools module.
git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@5176 d6536bca-fef9-0310-8506-e4c0a848fbcf
| Python | bsd-3-clause | lesserwhirls/scipy-cwt,scipy/scipy-svn,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor,scipy/scipy-svn,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,scipy/scipy-svn,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor,scipy/scipy-svn | ---
+++
@@ -10,7 +10,7 @@
config.add_extension('sigtools',
sources=['sigtoolsmodule.c',
'firfilter.c','medianfilter.c'],
- depends = ['sigtools.h']
+ depends = ['sigtools.h', 'newsig.c']
)
con... |
9aad4c5f22b8dd84711df2c85147f4cb37c23802 | tools/initialcompdata/abundomegacen.py | tools/initialcompdata/abundomegacen.py | from abundsolar import elsolarlogepsilon
zfactor = 10 ** -1.92
# Smith et al. (2000) ROA 219 in Omega Centauri
# [Fe/H] is about ~-1.7
#logxtofe = log epsilon(X) - log epsilon(Fe)
targetlogxtofe = {'rb': 1.34 - 6.25,
'y': 1.15 - 6.25,
'zr': 2.01 - 6.25,
'ba': 1.88... | from abundsolar import elsolarlogepsilon
zfactor = 10 ** -1.92
# Smith et al. (2000) ROA 219 in Omega Centauri
# [Fe/H] is about ~-1.7
#logxtofe = log epsilon(X) - log epsilon(Fe)
targetlogxtofe = {'rb': 1.34 - 6.25,
'y': 1.15 - 6.25,
'zr': 2.01 - 6.25,
'ba': 1.88... | Fix missing newline at EOF | Fix missing newline at EOF
| Python | mit | lukeshingles/evelchemevol | |
3c69ace12b7aadd094ce3325cf935c66b9e27e0b | example_config.py | example_config.py | """
File to easily switch between configurations between production and
development, etc.
"""
import os
# You must set each of these in your heroku environment with the heroku
# config:set command. See README.md for more information.
HEROKU_ENV_REQUIREMENTS = ('HEROKU', 'SECRET_KEY', 'GITHUB_CLIENT_ID',
... | """
File to easily switch between configurations between production and
development, etc.
"""
import os
# You must set each of these in your heroku environment with the heroku
# config:set command. See README.md for more information.
HEROKU_ENV_REQUIREMENTS = ('HEROKU', 'SECRET_KEY', 'GITHUB_CLIENT_ID',
... | Add placeholders for new secondary repo details | Add placeholders for new secondary repo details
| Python | agpl-3.0 | pluralsight/guides-cms,pluralsight/guides-cms,paulocheque/guides-cms,pluralsight/guides-cms,paulocheque/guides-cms,paulocheque/guides-cms | ---
+++
@@ -12,7 +12,9 @@
'GITHUB_SECRET', 'DATABASE_URL',
'SQLALCHEMY_DATABASE_URI', 'REPO_OWNER',
'REPO_NAME', 'REPO_OWNER_ACCESS_TOKEN',
- 'REDISCLOUD_URL')
+ 'REDISCLOUD_URL', 'S... |
64b4abde42b653e66444876dee0700afa64e6c6b | releasetasks/test/__init__.py | releasetasks/test/__init__.py | import os
import yaml
def read_file(path):
with open(path) as f:
return f.read()
PVT_KEY_FILE = os.path.join(os.path.dirname(__file__), "id_rsa")
PVT_KEY = read_file(PVT_KEY_FILE)
PUB_KEY = read_file(os.path.join(os.path.dirname(__file__), "id_rsa.pub"))
OTHER_PUB_KEY = read_file(os.path.join(os.path.di... | import os
import yaml
def read_file(path):
with open(path) as f:
return f.read()
PVT_KEY_FILE = os.path.join(os.path.dirname(__file__), "id_rsa")
PVT_KEY = read_file(PVT_KEY_FILE)
PUB_KEY = read_file(os.path.join(os.path.dirname(__file__), "id_rsa.pub"))
OTHER_PUB_KEY = read_file(os.path.join(os.path.di... | Remove redundant keyword argument from create_test_args | Remove redundant keyword argument from create_test_args
| Python | mpl-2.0 | mozilla/releasetasks,bhearsum/releasetasks,rail/releasetasks | ---
+++
@@ -15,16 +15,8 @@
DUMMY_PUBLIC_KEY = os.path.join(os.path.dirname(__file__), "public.key")
-def create_test_args(non_standard_arguments, permitted_defaults=None):
+def create_test_args(non_standard_arguments):
with open(os.path.join(os.path.dirname(__file__), 'test_graph_parameters.yml')) as f:
... |
effbffd67d52561ca1ba09201782aafc6cfc52f7 | blog/posts/models.py | blog/posts/models.py | from django.db import models
# Create your models here.
| from django.db import models
class Author(models.Model):
name = models.CharField(max_length=20)
email = models.EmailField(max_length=254)
def __unicode__(self):
return self.name
class Post(models.Model):
body = models.TextField()
title = models.CharField(max_length=50)
author = models... | Set up the DB schema for posts. | Set up the DB schema for posts.
| Python | mit | Lukasa/minimalog | ---
+++
@@ -1,3 +1,18 @@
from django.db import models
-# Create your models here.
+class Author(models.Model):
+ name = models.CharField(max_length=20)
+ email = models.EmailField(max_length=254)
+
+ def __unicode__(self):
+ return self.name
+
+class Post(models.Model):
+ body = models.TextField... |
e5c4d03a8c0ef66299d30fb0ecca6dfc54c15506 | cerberus/__init__.py | cerberus/__init__.py | __all__ = ['client', 'user_auth', 'aws_auth', 'util']
CLIENT_VERSION = '1.2.0'
class CerberusClientException(Exception):
"""Wrap third-party exceptions expected by the Cerberus client."""
pass
| __all__ = ['client', 'user_auth', 'aws_auth', 'util']
CLIENT_VERSION = '1.3.0'
class CerberusClientException(Exception):
"""Wrap third-party exceptions expected by the Cerberus client."""
pass
| Update client version to 1.3.0 | Update client version to 1.3.0
| Python | apache-2.0 | Nike-Inc/cerberus-python-client | ---
+++
@@ -1,6 +1,6 @@
__all__ = ['client', 'user_auth', 'aws_auth', 'util']
-CLIENT_VERSION = '1.2.0'
+CLIENT_VERSION = '1.3.0'
class CerberusClientException(Exception): |
8cfe4d9ef565502b247b7ac3b438b49f257c7012 | enable/layout/ab_constrainable.py | enable/layout/ab_constrainable.py | #------------------------------------------------------------------------------
# Copyright (c) 2012, Enthought, Inc.
# All rights reserved.
#------------------------------------------------------------------------------
from abc import ABCMeta
class ABConstrainable(object):
""" An abstract base class for objec... | #------------------------------------------------------------------------------
# Copyright (c) 2012, Enthought, Inc.
# All rights reserved.
#------------------------------------------------------------------------------
from abc import ABCMeta
class ABConstrainable(object):
""" An abstract base class for objec... | Fix a small docstring bug. | Fix a small docstring bug.
| Python | bsd-3-clause | tommy-u/enable,tommy-u/enable,tommy-u/enable,tommy-u/enable | ---
+++
@@ -10,8 +10,8 @@
layout helpers.
Minimally, instances need to have `top`, `bottom`, `left`, `right`,
- `width`, `height`, `v_center` and `h_center` attributes which are
- `LinearSymbolic` instances.
+ `layout_width`, `layout_height`, `v_center` and `h_center` attributes
+ which are `L... |
62abb800b1b40cfbce120c0f3fb5169e32daaa60 | accounts/management/__init__.py | accounts/management/__init__.py | from accounts import models, names
def ensure_core_accounts_exists(sender, **kwargs):
# We only create core accounts the first time syncdb is run
if models.Account.objects.all().count() > 0:
return
# Create asset accounts
assets = models.AccountType.add_root(name='Assets')
assets.accounts... | from accounts import models, names
def ensure_core_accounts_exists(sender, **kwargs):
# We only create core accounts the first time syncdb is run
if models.Account.objects.all().count() > 0:
return
# Create asset accounts
assets = models.AccountType.add_root(name='Assets')
assets.accounts... | Change code-account name triggered during creation | Change code-account name triggered during creation
| Python | bsd-3-clause | Jannes123/django-oscar-accounts,amsys/django-account-balances,michaelkuty/django-oscar-accounts,michaelkuty/django-oscar-accounts,Mariana-Tek/django-oscar-accounts,machtfit/django-oscar-accounts,carver/django-account-balances,machtfit/django-oscar-accounts,amsys/django-account-balances,Mariana-Tek/django-oscar-accounts... | ---
+++
@@ -15,7 +15,7 @@
liabilities = models.AccountType.add_root(name='Liabilities')
liabilities.accounts.create(name=names.MERCHANT_SOURCE,
credit_limit=None)
- liabilities.add_child(name="Giftcards")
+ liabilities.add_child(name=names.UNIT_NAME_PLURAL)
liabil... |
332bbd84477498a045cfdd7b56b21127fa366a2b | socli/sentry.py | socli/sentry.py | # Initialize Sentry
import sentry_sdk
sentry_sdk.init(
"https://95c4106659044cbda2ea0fe499f4be7e@o323465.ingest.sentry.io/5445901",
traces_sample_rate=0.5
)
from socli.socli import main
main()
| # Initialize Sentry
import sentry_sdk
sentry_sdk.init(
"https://95c4106659044cbda2ea0fe499f4be7e@o323465.ingest.sentry.io/5445901",
traces_sample_rate=1.0
)
from socli.socli import main
main()
| Set sample rate to 1.0 | Set sample rate to 1.0
| Python | bsd-3-clause | gautamkrishnar/socli | ---
+++
@@ -3,7 +3,7 @@
sentry_sdk.init(
"https://95c4106659044cbda2ea0fe499f4be7e@o323465.ingest.sentry.io/5445901",
- traces_sample_rate=0.5
+ traces_sample_rate=1.0
)
from socli.socli import main |
e6d4ca44f3f71468c40842c53e3963b425ac2527 | mss/factory.py | mss/factory.py | """
This is part of the MSS Python's module.
Source: https://github.com/BoboTiG/python-mss
"""
import platform
from typing import TYPE_CHECKING
from .exception import ScreenShotError
if TYPE_CHECKING:
from typing import Any # noqa
from .base import MSSMixin # noqa
def mss(**kwargs):
# type: (Any) -... | """
This is part of the MSS Python's module.
Source: https://github.com/BoboTiG/python-mss
"""
import platform
from typing import TYPE_CHECKING
from .exception import ScreenShotError
if TYPE_CHECKING:
from typing import Any # noqa
from .base import MSSMixin # noqa
def mss(**kwargs):
# type: (Any) -... | Fix pylint: Import outside toplevel (%s) (import-outside-toplevel) | MSS: Fix pylint: Import outside toplevel (%s) (import-outside-toplevel)
| Python | mit | BoboTiG/python-mss | ---
+++
@@ -26,6 +26,7 @@
It then proxies its arguments to the class for
instantiation.
"""
+ # pylint: disable=import-outside-toplevel
os_ = platform.system().lower()
|
65b2dd9e0293265d528059a3a240d555661d1460 | main/models.py | main/models.py | from django.db import models
from django.contric.auth.models import User
from django.template.defaultfilters import slugify
#class MyModel(models.Model):
# title = models.CharField(max_length=255)
# slug = models.SlugField()
# author = models.ForeignKey(User)
# content = models.TextField()
# created_at... | from django.db import models
from django.contrib.auth.models import User
from django.template.defaultfilters import slugify
#class Document(models.Model):
# title = models.CharField(max_length=255)
# slug = models.SlugField()
# author = models.ForeignKey(User)
# content = models.TextField()
# created_a... | Rename the generic model to Document | Rename the generic model to Document
| Python | bsd-3-clause | strycore/djung,strycore/djung,strycore/djung,strycore/djung | ---
+++
@@ -1,9 +1,9 @@
from django.db import models
-from django.contric.auth.models import User
+from django.contrib.auth.models import User
from django.template.defaultfilters import slugify
-#class MyModel(models.Model):
+#class Document(models.Model):
# title = models.CharField(max_length=255)
# sl... |
760a543cf13552ce951fee12c6e9a9d5d335a168 | formation/output_specification.py | formation/output_specification.py | # -*- coding: utf-8 -*-
import json
from . import ATTRIBUTE_SPECIFICATION_PATH, REF_SPECIFICATION_PATH
class OutputSpecification(object):
def __init__(
self, attribute_specification_path=ATTRIBUTE_SPECIFICATION_PATH,
ref_specification_path=REF_SPECIFICATION_PATH
):
self.attr... | # -*- coding: utf-8 -*-
import json
from . import ATTRIBUTE_SPECIFICATION_PATH, REF_SPECIFICATION_PATH
class OutputSpecification(object):
def __init__(
self, attribute_specification_path=ATTRIBUTE_SPECIFICATION_PATH,
ref_specification_path=REF_SPECIFICATION_PATH
):
self.attr... | Handle resources with no outputs | Handle resources with no outputs
| Python | apache-2.0 | jamesroutley/formation | ---
+++
@@ -27,7 +27,7 @@
return data
def get_refs(self, resource_type):
- return self.ref_specification[resource_type]
+ return self.ref_specification.get(resource_type, [])
def get_attributes(self, resource_type):
- return self.attribute_specification[resource_type]
+ ... |
7a7afea2539048d172b1d5abfc4a4d9dff0827e7 | runtests.py | runtests.py | #!/usr/bin/env python
import sys
from os.path import dirname, abspath
from django.conf import settings
if not settings.configured:
settings.configure(
DATABASE_ENGINE = 'sqlite3',
SITE_ID = 1,
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
... | #!/usr/bin/env python
import sys
from os.path import dirname, abspath
from django.conf import settings
if len(sys.argv) > 1 and 'postgres' in sys.argv:
sys.argv.remove('postgres')
db_engine = 'postgresql_psycopg2'
db_name = 'test_main'
else:
db_engine = 'sqlite3'
db_name = ''
if not settings.conf... | Allow running tests with postgres | Allow running tests with postgres
| Python | mit | coleifer/django-relationships,maroux/django-relationships,coleifer/django-relationships,maroux/django-relationships | ---
+++
@@ -4,9 +4,18 @@
from django.conf import settings
+if len(sys.argv) > 1 and 'postgres' in sys.argv:
+ sys.argv.remove('postgres')
+ db_engine = 'postgresql_psycopg2'
+ db_name = 'test_main'
+else:
+ db_engine = 'sqlite3'
+ db_name = ''
+
if not settings.configured:
settings.configure... |
039d326907d88e24a48100b7f3cb0b8e0eb843d0 | rocket_snake/__init__.py | rocket_snake/__init__.py | # -*- coding: utf-8 -*-
__author__ = 'Hugo Berg'
__email__ = 'hb11002@icloud.com'
__version__ = '0.1.0'
from rocket_snake.constants import *
| # -*- coding: utf-8 -*-
__author__ = 'Hugo Berg'
__email__ = 'hb11002@icloud.com'
__version__ = '0.1.0'
from rocket_snake.client import RLS_Client
from rocket_snake.constants import *
| Add the RLS client import to init file | Add the RLS client import to init file
Signed-off-by: drummersbrother <d12fd520b57756512907f841763cabff8eb36464@icloud.com>
| Python | apache-2.0 | Drummersbrother/rocket-snake | ---
+++
@@ -4,4 +4,5 @@
__email__ = 'hb11002@icloud.com'
__version__ = '0.1.0'
+from rocket_snake.client import RLS_Client
from rocket_snake.constants import * |
4065f8edc61ae9078238219dad674ae114c78003 | moocng/wsgi.py | moocng/wsgi.py | """
WSGI config for moocng project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` s... | """
WSGI config for moocng project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` s... | Allow to configure the virtualenv path from the Apache configuration | Allow to configure the virtualenv path from the Apache configuration
| Python | apache-2.0 | OpenMOOC/moocng,GeographicaGS/moocng,GeographicaGS/moocng,GeographicaGS/moocng,OpenMOOC/moocng,GeographicaGS/moocng | ---
+++
@@ -20,9 +20,18 @@
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
-from django.core.wsgi import get_wsgi_application
-application = get_wsgi_application()
+#from django.core.wsgi i... |
bd1a244aa3d9126a12365611372e6449e47e5693 | pelicanconf.py | pelicanconf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'Mappy'
SITENAME = u'Mappy Labs'
SITEURL = ''
TIMEZONE = 'Europe/Paris'
DEFAULT_LANG = u'en'
THEME = 'theme/mappy'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = 'feeds/rss.xml'
CATEGORY_FEED... | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'Mappy'
SITENAME = u'Mappy Labs'
SITEURL = ''
TIMEZONE = 'Europe/Paris'
DEFAULT_LANG = u'en'
THEME = 'theme/mappy'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = 'feeds/rss.xml'
CATEGORY_FEED... | Add links to Android/iOS apps | Add links to Android/iOS apps
| Python | mit | paulgreg/mappy.github.io-source,paulgreg/mappy.github.io-source,Mappy/mappy.github.io-source,Mappy/mappy.github.io-source,paulgreg/mappy.github.io-source,Mappy/mappy.github.io-source,paulgreg/mappy.github.io-source,Mappy/mappy.github.io-source | ---
+++
@@ -19,6 +19,8 @@
# Blogroll
LINKS = (('Mappy', 'https://www.mappy.com/'),
+ ('Appli Android', 'https://play.google.com/store/apps/details?id=com.mappy.app'),
+ ('Appli iOS', 'https://itunes.apple.com/fr/app/mappy-itineraire-et-recherche/id313834655?mt=8'),
('Blog Mappy', 'ht... |
835cae8c7bb8a9120008657e5641d6fbbdc5782b | tba_config.py | tba_config.py | import os
DEBUG = os.environ['SERVER_SOFTWARE'].startswith('Dev')
# The CONFIG variables should have exactly the same structure between environments
# Eventually a test environment should be added. -gregmarra 17 Jul 2012
if DEBUG:
CONFIG = {
"env": "dev",
"memcache": False,
}
else:
CONFIG ... | import os
DEBUG = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')
# The CONFIG variables should have exactly the same structure between environments
# Eventually a test environment should be added. -gregmarra 17 Jul 2012
if DEBUG:
CONFIG = {
"env": "dev",
"memcache": False,
}
else:
... | Work around for SERVER_SOFTWARE not being set | Work around for SERVER_SOFTWARE not being set
| Python | mit | phil-lopreiato/the-blue-alliance,1fish2/the-blue-alliance,verycumbersome/the-blue-alliance,fangeugene/the-blue-alliance,nwalters512/the-blue-alliance,jaredhasenklein/the-blue-alliance,synth3tk/the-blue-alliance,1fish2/the-blue-alliance,synth3tk/the-blue-alliance,bdaroz/the-blue-alliance,synth3tk/the-blue-alliance,josep... | ---
+++
@@ -1,6 +1,6 @@
import os
-DEBUG = os.environ['SERVER_SOFTWARE'].startswith('Dev')
+DEBUG = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')
# The CONFIG variables should have exactly the same structure between environments
# Eventually a test environment should be added. -gregmarra 17 Jul 2012 |
321b627c3c7d241d6e6cc4e319911cfbcd1533fb | src/temp_functions.py | src/temp_functions.py | def k_to_c(temp):
return temp - 273.15
| def k_to_c(temp):
return temp - 273.15
def f_to_k(temp):
return ((temp - 32) * (5 / 9)) + 273.15
| Write a function to covert far to kelvin | Write a function to covert far to kelvin
| Python | mit | xykang/2015-05-12-BUSM-git,xykang/2015-05-12-BUSM-git | ---
+++
@@ -1,2 +1,5 @@
def k_to_c(temp):
return temp - 273.15
+
+def f_to_k(temp):
+ return ((temp - 32) * (5 / 9)) + 273.15 |
d676a1b1e7e3efbbfc72f1d7e522865b623783df | utils/etc.py | utils/etc.py | def reverse_insort(seq, val):
lo = 0
hi = len(seq)
while lo < hi:
mid = (lo + hi) // 2
if val > seq[mid]:
hi = mid
else:
lo = mid + 1
seq.insert(lo, val)
| def reverse_insort(seq, val, lo=0, hi=None):
if hi is None:
hi = len(seq)
while lo < hi:
mid = (lo + hi) // 2
if val > seq[mid]:
hi = mid
else:
lo = mid + 1
seq.insert(lo, val)
| Add optional hi and lo params to reverse_insort | Add optional hi and lo params to reverse_insort
| Python | mit | BeatButton/beattie,BeatButton/beattie-bot | ---
+++
@@ -1,6 +1,6 @@
-def reverse_insort(seq, val):
- lo = 0
- hi = len(seq)
+def reverse_insort(seq, val, lo=0, hi=None):
+ if hi is None:
+ hi = len(seq)
while lo < hi:
mid = (lo + hi) // 2
if val > seq[mid]: |
b13efa6234c2748515a9c3f5a8fbb3ad43093083 | test/test_device.py | test/test_device.py | from pml.exceptions import PvException
import pml.device
import pytest
import mock
@pytest.fixture
def create_device(readback, setpoint):
_rb = readback
_sp = setpoint
device = pml.device.Device(rb_pv=_rb, sp_pv=_sp, cs=mock.MagicMock())
return device
def test_set_device_value():
rb_pv = 'SR01A-... | from pml.exceptions import PvException
import pml.device
import pytest
import mock
@pytest.fixture
def create_device(readback, setpoint):
_rb = readback
_sp = setpoint
device = pml.device.Device(rb_pv=_rb, sp_pv=_sp, cs=mock.MagicMock())
return device
def test_set_device_value():
rb_pv = 'SR01A-... | Raise assertion error when creating a device with no pv | Raise assertion error when creating a device with no pv
| Python | apache-2.0 | willrogers/pml,willrogers/pml | ---
+++
@@ -32,5 +32,5 @@
with pytest.raises(PvException):
device.get_value('non_existent')
- with pytest.raises(PvException):
+ with pytest.raises(AssertionError):
create_device(None, None) |
4607c2fdb39301cc60d49280dd1253e3d62845be | st2api/setup.py | st2api/setup.py | # -*- coding: utf-8 -*-
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "Licen... | # -*- coding: utf-8 -*-
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "Licen... | Fix a packaging bug and make sure we also include templates directory. | Fix a packaging bug and make sure we also include templates directory.
| Python | apache-2.0 | pixelrebel/st2,jtopjian/st2,nzlosh/st2,Itxaka/st2,Plexxi/st2,grengojbo/st2,lakshmi-kannan/st2,armab/st2,Plexxi/st2,peak6/st2,pixelrebel/st2,emedvedev/st2,emedvedev/st2,Plexxi/st2,Itxaka/st2,tonybaloney/st2,lakshmi-kannan/st2,pixelrebel/st2,jtopjian/st2,jtopjian/st2,dennybaa/st2,punalpatel/st2,dennybaa/st2,alfasin/st2,a... | ---
+++
@@ -30,6 +30,9 @@
install_requires=[
"pecan",
],
+ package_data={
+ 'st2api': ['templates/*.html']
+ },
test_suite='st2api',
zip_safe=False,
include_package_data=True, |
b77622311c69cd74c9c3c3b7c66747c79ea41bec | troposphere/qldb.py | troposphere/qldb.py | # Copyright (c) 2012-2019, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
# Resource specification version: 16.1.0
from troposphere import Tags
from . import AWSObject, AWSProperty
from .validators import boolean
class ... | # Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
# Resource specification version: 39.7.0
from troposphere import Tags
from . import AWSObject, AWSProperty
from .validators import boolean
class ... | Update QLDB per 2021-07-22 changes | Update QLDB per 2021-07-22 changes
| Python | bsd-2-clause | cloudtools/troposphere,cloudtools/troposphere | ---
+++
@@ -1,10 +1,10 @@
-# Copyright (c) 2012-2019, Mark Peek <mark@peek.org>
+# Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
-# Resource specification version: 16.1.0
+# Resource specific... |
315e6da0dc3d7424a14c65ac243af1faef36b710 | test/parse_dive.py | test/parse_dive.py | #! /bin/python
import argparse
from xml.dom import minidom
parser = argparse.ArgumentParser(description='Parse a dive in xml formt.')
parser.add_argument('-f', '--file', required=True,
dest='path', help='path to xml file')
args = parser.parse_args()
path = args.path
doc = minidom.parse(path)
nodes = doc.getElem... | #! /bin/python
import argparse
from xml.dom import minidom
parser = argparse.ArgumentParser(description='Parse a dive in xml formt.')
parser.add_argument('-f', '--file', required=True,
dest='path', help='path to xml file')
args = parser.parse_args()
path = args.path
doc = minidom.parse(path)
nodes = doc.getElem... | Add a correct parsing of the file | Add a correct parsing of the file
| Python | isc | AquaBSD/libbuhlmann,AquaBSD/libbuhlmann,AquaBSD/libbuhlmann | ---
+++
@@ -12,7 +12,11 @@
nodes = doc.getElementsByTagName('Dive.Sample')
for node in nodes:
- depth = (float(node.childNodes[2].childNodes[0].nodeValue) / 10 )+ 1
- time = float(node.childNodes[8].childNodes[0].nodeValue) / 60
-
- print ("%.2f %.2f" % (time , depth))
+ if node.hasChildNodes() and len(node.c... |
1b085180ff6d9cb4e395551682c5a628545cb70c | twython/advisory.py | twython/advisory.py | # -*- coding: utf-8 -*-
"""
twython.advisory
~~~~~~~~~~~~~~~~
This module contains Warning classes for Twython to specifically
alert the user about.
This mainly is because Python 2.7 > mutes DeprecationWarning and when
we deprecate a method or variable in Twython, we want to use to see
the Warning but don't want ALL... | # -*- coding: utf-8 -*-
"""
twython.advisory
~~~~~~~~~~~~~~~~
This module contains Warning classes for Twython to specifically
alert the user about.
This mainly is because Python 2.7 > mutes DeprecationWarning and when
we deprecate a method or variable in Twython, we want to use to see
the Warning but don't want ALL... | Fix simple typo: specifcally -> specifically | Fix simple typo: specifcally -> specifically
Closes #526
| Python | mit | ryanmcgrath/twython | ---
+++
@@ -17,6 +17,6 @@
class TwythonDeprecationWarning(DeprecationWarning):
"""Custom DeprecationWarning to be raised when methods/variables
are being deprecated in Twython. Python 2.7 > ignores DeprecationWarning
- so we want to specifcally bubble up ONLY Twython Deprecation Warnings
+ so we want... |
5a4a71aaed65bb2ea676a0ec1fa75a8a801f1013 | django_enumfield/contrib/drf.py | django_enumfield/contrib/drf.py | from django.utils import six
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class EnumField(serializers.ChoiceField):
default_error_messages = {"invalid_choice": _('"{input}" is not a valid choice.')}
def __init__(self, enum, **kwargs):
self.enum = enum... | from django.utils import six
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class EnumField(serializers.ChoiceField):
default_error_messages = {"invalid_choice": _('"{input}" is not a valid choice.')}
def __init__(self, enum, **kwargs):
self.enum = enum... | Document the type of NamedEnumField properly | Document the type of NamedEnumField properly
| Python | mit | 5monkeys/django-enumfield | ---
+++
@@ -39,3 +39,6 @@
class NamedEnumField(EnumField):
def get_choice_value(self, enum_value):
return enum_value.name
+
+ class Meta:
+ swagger_schema_fields = {"type": "string"} |
bbfa404e4679f4229e44fd7e641e62fdd2e7bdd5 | djangorestframework/__init__.py | djangorestframework/__init__.py | __version__ = '0.3.2-dev'
VERSION = __version__ # synonym
| __version__ = '0.3.3-dev'
VERSION = __version__ # synonym
| Fix silly error. This makes more sense. | Fix silly error. This makes more sense. | Python | bsd-2-clause | kylefox/django-rest-framework,sbellem/django-rest-framework,jerryhebert/django-rest-framework,atombrella/django-rest-framework,rafaelcaricio/django-rest-framework,brandoncazander/django-rest-framework,hnakamur/django-rest-framework,YBJAY00000/django-rest-framework,maryokhin/django-rest-framework,ezheidtmann/django-rest... | ---
+++
@@ -1,3 +1,3 @@
-__version__ = '0.3.2-dev'
+__version__ = '0.3.3-dev'
VERSION = __version__ # synonym |
fbea1cdd96ef259e8affc87ee72d8bbaef40c00d | salt/config.py | salt/config.py | '''
All salt configuration loading and defaults should be in this module
'''
# Import python modules
import os
import sys
import socket
# Import third party libs
import yaml
def minion_config(path):
'''
Reads in the minion configuration file and sets up special options
'''
opts = {'master': 'mcp',
... | '''
All salt configuration loading and defaults should be in this module
'''
# Import python modules
import os
import sys
import socket
# Import third party libs
import yaml
def minion_config(path):
'''
Reads in the minion configuration file and sets up special options
'''
opts = {'master': 'mcp',
... | Add the default options for the salt master | Add the default options for the salt master
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -34,7 +34,15 @@
'''
Reads in the master configuration file and sets up default options
'''
- opts = {}
+ opts = {'interface': '0.0.0.0',
+ 'publish_port': 7777,
+ 'worker_threads': 5,
+ 'worker_port': 7778,
+ 'ret_port': 7776,
+ 'l... |
baf08cb5aedd7a75dad8f79601ce31244544a3dd | elections/uk_general_election_2015/views/parties.py | elections/uk_general_election_2015/views/parties.py | from candidates.views import PartyDetailView
class UKPartyDetailView(PartyDetailView):
def get_context_data(self, **kwargs):
context = super(UKPartyDetailView, self).get_context_data(**kwargs)
party_ec_id = context['party'].identifiers.get(scheme='electoral-commission')
context['ec_url'] ... | from candidates.views import PartyDetailView
from popolo.models import Identifier
class UKPartyDetailView(PartyDetailView):
def get_context_data(self, **kwargs):
context = super(UKPartyDetailView, self).get_context_data(**kwargs)
context['ec_url'] = ''
context['register'] = ''
try... | Fix the 'Independent' party pages for UK elections | Fix the 'Independent' party pages for UK elections
There's no Electoral Commission identifier for the 'Independent'
pseudo-party, so the party page for independents was failing.
| Python | agpl-3.0 | mysociety/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,datamade/yournextmp-popit,neavouli/yournextrepresentative,neavouli/yournextrepresentative,neavouli/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextrepresentativ... | ---
+++
@@ -1,15 +1,20 @@
from candidates.views import PartyDetailView
+from popolo.models import Identifier
class UKPartyDetailView(PartyDetailView):
def get_context_data(self, **kwargs):
context = super(UKPartyDetailView, self).get_context_data(**kwargs)
- party_ec_id = context['party']... |
e0f296e776e2aaed2536eeebfb4900a23973aaf5 | tests/test_json.py | tests/test_json.py | from __future__ import absolute_import
import fnmatch
import os
import unittest
from . import validate_json_format
class TestSettings(unittest.TestCase):
def _get_json_files(self, file_pattern, folder='.'):
for root, dirnames, filenames in os.walk(folder):
for filename in fnmatch.filter(file... | from __future__ import absolute_import
import fnmatch
import os
import unittest
from . import validate_json_format
class TestSettings(unittest.TestCase):
def _get_json_files(self, file_pattern, folder='.'):
for root, dirnames, filenames in os.walk(folder):
for filename in fnmatch.filter(file... | Add '*.json' file extensions to test pattern list. | Add '*.json' file extensions to test pattern list.
| Python | mit | jonlabelle/SublimeJsPrettier,jonlabelle/SublimeJsPrettier | ---
+++
@@ -24,6 +24,7 @@
'*.sublime-settings',
'*.sublime-commands',
'*.sublime-menu',
+ '*.json'
)
for file_pattern in file_patterns:
for f in self._get_json_files(file_pattern): |
1e2edd3ff285e71feffac932592e08a483e002be | git_pre_commit_hook/builtin_plugins/flake8_check.py | git_pre_commit_hook/builtin_plugins/flake8_check.py | """Check files with flake8."""
import flake8.main
import re
DEFAULTS = {
'ignore': '',
'complexity': '10',
}
PYTHON_SHEBANG_REGEX = re.compile(r'''^#!.*python''')
def check(file_staged_for_commit, options):
if file_staged_for_commit.path.endswith('.py') or \
PYTHON_SHEBANG_REGEX.search(fil... | """Check files with flake8."""
import flake8.main
import re
DEFAULTS = {
'ignore': 'E226',
'complexity': '10',
}
PYTHON_SHEBANG_REGEX = re.compile(r'''^#!.*python''')
def check(file_staged_for_commit, options):
if file_staged_for_commit.path.endswith('.py') or \
PYTHON_SHEBANG_REGEX.search... | Add E226 to default ignores for pep8 | Add E226 to default ignores for pep8
E226 - missing whitespace around arithmetic operator
2*3 + 5*6 must pass
| Python | mit | evvers/git-pre-commit-hook | ---
+++
@@ -4,7 +4,7 @@
DEFAULTS = {
- 'ignore': '',
+ 'ignore': 'E226',
'complexity': '10',
}
|
ff0bae24be1dfc800dd76940f95cc4580cdc7421 | rest-api/metrics_api.py | rest-api/metrics_api.py | """The API definition for the metrics API.
This defines the APIs and the handlers for the APIs.
"""
import api_util
import metrics
from protorpc import protojson
from flask import request
from flask.ext.restful import Resource
class MetricsApi(Resource):
@api_util.auth_required
def post(self):
resource = re... | """The API definition for the metrics API.
This defines the APIs and the handlers for the APIs.
"""
import api_util
import metrics
import json
from protorpc import protojson
from flask import request
from flask.ext.restful import Resource
class MetricsApi(Resource):
@api_util.auth_required
def post(self):
r... | Return a JSON payload, rather than stringified JSON | Return a JSON payload, rather than stringified JSON
| Python | bsd-3-clause | all-of-us/raw-data-repository,all-of-us/raw-data-repository,all-of-us/raw-data-repository | ---
+++
@@ -5,6 +5,7 @@
import api_util
import metrics
+import json
from protorpc import protojson
from flask import request
@@ -18,4 +19,4 @@
metrics_response = metrics.SERVICE.get_metrics(metrics_request)
- return protojson.encode_message(metrics_response)
+ return json.loads(protojson.encode... |
066d776041b2cae4e0435935d7f9a05173e34563 | script/echo.py | script/echo.py | #!/usr/bin/env python3
# -*- coding: ascii -*-
import sys
import instabot
NICKNAME = 'Echo'
def post_cb(self, msg, meta):
if msg['text'].startswith('!echo '):
return msg['text'][6:]
def main():
parser = instabot.argparse(sys.argv[1:])
url, nickname = None, NICKNAME
for arg in parser:
... | #!/usr/bin/env python3
# -*- coding: ascii -*-
import sys
import instabot
NICKNAME = 'Echo'
def post_cb(self, msg, meta):
if msg['text'].startswith('!echo '):
return msg['text'][6:]
def main():
parser = instabot.argparse(sys.argv[1:])
url, nickname = None, NICKNAME
for arg in parser:
... | Make example bot react to SIGINT better | [Instabot] Make example bot react to SIGINT better
| Python | mit | CylonicRaider/Instant,CylonicRaider/Instant,CylonicRaider/Instant,CylonicRaider/Instant,CylonicRaider/Instant | ---
+++
@@ -29,6 +29,11 @@
url = arg
if url is None: raise SystemExit('ERROR: Too few arguments')
bot = instabot.HookBot(url, nickname, post_cb=post_cb)
- bot.run()
+ try:
+ bot.run()
+ except KeyboardInterrupt:
+ sys.stderr.write('\n')
+ finally:
+ bot.close()
... |
dbba9e403538fb3bfd29763b8741e07dad3db1b1 | src/main/python/cfn_sphere/resolver/file.py | src/main/python/cfn_sphere/resolver/file.py |
class FileResolver(object):
def read(self, path):
with open(path, 'r') as file:
return file.read()
|
class FileResolver(object):
def read(self, path):
try:
with open(path, 'r') as f:
return f.read()
except IOError as e:
raise CfnSphereException("Cannot read file " + path, e)
| Throw CfnSphereException on IOErrors. Fix landmark issue. | Throw CfnSphereException on IOErrors. Fix landmark issue.
| Python | apache-2.0 | cfn-sphere/cfn-sphere,cfn-sphere/cfn-sphere,ImmobilienScout24/cfn-sphere,cfn-sphere/cfn-sphere,marco-hoyer/cfn-sphere | ---
+++
@@ -2,5 +2,8 @@
class FileResolver(object):
def read(self, path):
- with open(path, 'r') as file:
- return file.read()
+ try:
+ with open(path, 'r') as f:
+ return f.read()
+ except IOError as e:
+ raise CfnSphereException("Cannot re... |
9c3d24083be5969ca84c1625dbc0d368acdc51f8 | tg/tests/test_util.py | tg/tests/test_util.py | import tg
from tg.util import *
from nose.tools import eq_
import os
path = None
def setup():
global path
path = os.curdir
os.chdir(os.path.abspath(os.path.dirname(os.path.dirname(tg.__file__))))
def teardown():
global path
os.chdir(path)
# These tests aren't reliable if the package in question h... | import tg
from tg.util import *
from nose.tools import eq_
import os
path = None
def setup():
global path
path = os.curdir
os.chdir(os.path.abspath(os.path.dirname(os.path.dirname(tg.__file__))))
def teardown():
global path
os.chdir(path)
def test_get_partial_dict():
eq_(get_partial_dict('pre... | Add a test_get_partial_dict unit test, which currently fails | Add a test_get_partial_dict unit test, which currently fails
| Python | mit | lucius-feng/tg2,lucius-feng/tg2 | ---
+++
@@ -13,6 +13,10 @@
global path
os.chdir(path)
+def test_get_partial_dict():
+ eq_(get_partial_dict('prefix', {'prefix.xyz':1, 'prefix.zyx':2, 'xy':3}),
+ {'xyz':1,'zyx':2})
+
# These tests aren't reliable if the package in question has
# entry points.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.