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 |
|---|---|---|---|---|---|---|---|---|---|---|
b1c67f1846d03f20bf813b9a9940c07a0806a3ee | threaded_messages/search_indexes.py | threaded_messages/search_indexes.py | from haystack import indexes
from .models import Thread
class ThreadIndex(indexes.RealTimeSearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
participants = indexes.MultiValueField()
last_message = indexes.DateTimeField(model_attr='latest_msg__sent_at')
def inde... | from haystack import indexes
from .models import Thread
class ThreadIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
participants = indexes.MultiValueField()
last_message = indexes.DateTimeField(model_attr='latest_msg__sent_at')
def index_querys... | Remove RealTimeSearchIndex, gone in Haystack 2.something | Remove RealTimeSearchIndex, gone in Haystack 2.something
| Python | mit | siovene/django-threaded-messages,siovene/django-threaded-messages,siovene/django-threaded-messages | ---
+++
@@ -1,7 +1,7 @@
from haystack import indexes
from .models import Thread
-class ThreadIndex(indexes.RealTimeSearchIndex, indexes.Indexable):
+class ThreadIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
participants = indexes.MultiValueFiel... |
c0daf6e2c549e2857f8acfc69ae97635705a5342 | docs/conf.py | docs/conf.py | import pymanopt
# Package information
project = "Pymanopt"
author = "Jamie Townsend, Niklas Koep, Sebastian Weichwald"
copyright = "2016-2021, {:s}".format(author)
release = version = pymanopt.__version__
# Build settings
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.coverage",
"sphinx.ext.mathjax",
... | import datetime
import pymanopt
# Package information
project = "Pymanopt"
author = "Jamie Townsend, Niklas Koep, Sebastian Weichwald"
copyright = f"2016-{datetime.date.today().year}, {author}"
release = version = pymanopt.__version__
# Build settings
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.coverag... | Define date in docs dynamically | Define date in docs dynamically
Signed-off-by: Niklas Koep <342d5290239d9c5264c8f98185afedb99596601a@gmail.com>
| Python | bsd-3-clause | pymanopt/pymanopt,pymanopt/pymanopt | ---
+++
@@ -1,10 +1,12 @@
+import datetime
+
import pymanopt
# Package information
project = "Pymanopt"
author = "Jamie Townsend, Niklas Koep, Sebastian Weichwald"
-copyright = "2016-2021, {:s}".format(author)
+copyright = f"2016-{datetime.date.today().year}, {author}"
release = version = pymanopt.__version_... |
9616afb9e8c7a5a599096b588cd71a714e001e2b | dduplicated/fileManager.py | dduplicated/fileManager.py | import os
from threading import Thread
def _delete(path):
os.remove(path)
def _link(src, path):
os.symlink(src, path)
def manager_files(paths, link):
# The first file is preserved to not delete all files in directories.
first = True
src = ""
deleted_files = []
linked_files = []
errors = []
for path in pat... | import os
from threading import Thread
def _delete(path: str, src: str, link: bool):
os.remove(path)
if link:
os.symlink(src, path)
def manager_files(paths, link):
# The first file is preserved to not delete all files in directories.
first = True
src = ""
deleted_files = []
linked_files = []
errors = []
... | Fix in link action. Remove the `_link` method and add action to `_delete`, this fix concurrency problems. | Fix in link action. Remove the `_link` method and add action to `_delete`, this fix concurrency problems.
Signed-off-by: messiasthi <8562fc1efba9a3c99753c749fdfb1b6932b70fbf@gmail.com>
| Python | mit | messiasthi/dduplicated-cli | ---
+++
@@ -1,11 +1,10 @@
import os
from threading import Thread
-def _delete(path):
+def _delete(path: str, src: str, link: bool):
os.remove(path)
-
-def _link(src, path):
- os.symlink(src, path)
+ if link:
+ os.symlink(src, path)
def manager_files(paths, link):
# The first file is preserved to not delet... |
64147133f2140777c5b3aafcdf7510d816dd6462 | core/data/DataTransformer.py | core/data/DataTransformer.py | """
DataTransformer
:Authors:
Berend Klein Haneveld
"""
from vtk import vtkImageReslice
class DataTransformer(object):
"""DataTransformer is a class that can transform a given dataset"""
def __init__(self):
super(DataTransformer, self).__init__()
def TransformImageData(self, imageData, transform):
"""
:t... | """
DataTransformer
:Authors:
Berend Klein Haneveld
"""
from vtk import vtkImageReslice
class DataTransformer(object):
"""DataTransformer is a class that can transform a given dataset"""
def __init__(self):
super(DataTransformer, self).__init__()
def TransformImageData(self, imageData, transform):
"""
:t... | Fix for data transformer giving no output. | Fix for data transformer giving no output.
| Python | mit | berendkleinhaneveld/Registrationshop,berendkleinhaneveld/Registrationshop | ---
+++
@@ -20,9 +20,10 @@
"""
reslicer = vtkImageReslice()
reslicer.SetInterpolationModeToCubic()
- reslicer.SetAutoCropOutput(1) # Not sure if this is what we want
+ # reslicer.SetAutoCropOutput(1) # Not sure if this is what we want
reslicer.SetInputData(imageData)
reslicer.SetResliceTransform(... |
d708fa46b135fb1104d827ec4e64412f0028d94e | pyleus/compat.py | pyleus/compat.py | import sys
if sys.version_info[0] < 3:
from cStringIO import StringIO
BytesIO = StringIO
else:
from io import BytesIO
from io import StringIO
_ = BytesIO
_ = StringIO
| import sys
if sys.version_info[0] < 3:
from cStringIO import StringIO
BytesIO = StringIO
else:
from io import BytesIO
from io import StringIO
_ = BytesIO # pyflakes
_ = StringIO # pyflakes
| Add comments about pyflakes appeasement | Add comments about pyflakes appeasement
| Python | apache-2.0 | poros/pyleus,patricklucas/pyleus,mzbyszynski/pyleus,Yelp/pyleus,imcom/pyleus,dapuck/pyleus,stallman-cui/pyleus,stallman-cui/pyleus,mzbyszynski/pyleus,imcom/pyleus,poros/pyleus,ecanzonieri/pyleus,Yelp/pyleus,imcom/pyleus,jirafe/pyleus,jirafe/pyleus,ecanzonieri/pyleus,patricklucas/pyleus,dapuck/pyleus | ---
+++
@@ -7,5 +7,5 @@
from io import BytesIO
from io import StringIO
-_ = BytesIO
-_ = StringIO
+_ = BytesIO # pyflakes
+_ = StringIO # pyflakes |
f21ebbaabb5ce38432961b7786b78ad4d23f3259 | django_mercadopago/urls.py | django_mercadopago/urls.py | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^notifications$', views.create_notification),
]
| from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^notifications$', views.create_notification, name='notifications'),
]
| Add a view to the notifications name (for reversing) | Add a view to the notifications name (for reversing)
| Python | isc | asermax/django-mercadopago | ---
+++
@@ -3,5 +3,5 @@
from . import views
urlpatterns = [
- url(r'^notifications$', views.create_notification),
+ url(r'^notifications$', views.create_notification, name='notifications'),
] |
748e713fdb2f3126f463651562e1f938a7ce1511 | src/dcm/agent/scripts/common-linux/general_cleanup.py | src/dcm/agent/scripts/common-linux/general_cleanup.py | import os
import sys
import logging
_g_logger = logging.getLogger(__name__)
def main(bin_path, dcm_basedir, dbfile):
dirs_to_clean = [os.path.join(dcm_basedir, 'logs'),
os.path.join(dcm_basedir, 'secure')]
for clean_dir in dirs_to_clean:
for (dirpath, dirname, filenames) in os.w... | import os
import sys
import logging
_g_logger = logging.getLogger(__name__)
def main(bin_path, dcm_basedir, dbfile):
dirs_to_clean = [os.path.join(dcm_basedir, 'logs'),
os.path.join(dcm_basedir, 'secure')]
for clean_dir in dirs_to_clean:
for (dirpath, dirname, filenames) in os.w... | Clean Azure images before snapshot | Clean Azure images before snapshot
For waagent to provision the following file must not exist:
/var/lib/waagent/provisioned
| Python | apache-2.0 | buzztroll/unix-agent,JPWKU/unix-agent,buzztroll/unix-agent,buzztroll/unix-agent,buzztroll/unix-agent,JPWKU/unix-agent,enStratus/unix-agent,enStratus/unix-agent,JPWKU/unix-agent,enStratus/unix-agent,JPWKU/unix-agent,enStratus/unix-agent | ---
+++
@@ -18,6 +18,15 @@
os.path.join(dirpath, file))
os.system(cmd)
+ files_to_clean = ["/var/lib/waagent/provisioned"]
+ for f in files_to_clean:
+ try:
+ os.remove(f)
+ except OSError as osEx:
+ # in many cases the file wi... |
25cd9c428a467fce92dae98476515e43806bc20c | iati/core/codelists.py | iati/core/codelists.py | from lxml import etree
import iati.core.resources
class Codelist(object):
"""Representation of a Codelist as defined within the IATI SSOT"""
def __init__(self, name=None, path=None, xml=None):
def parse_from_xml(xml):
"""Parse a Codelist from the XML that defines it"""
tree = ... | from lxml import etree
import iati.core.resources
class Codelist(object):
"""Representation of a Codelist as defined within the IATI SSOT"""
def __init__(self, name=None, path=None, xml=None):
def parse_from_xml(xml):
"""Parse a Codelist from the XML that defines it
TODO: Def... | Add codelist xml parsing TODO | Add codelist xml parsing TODO
| Python | mit | IATI/iati.core,IATI/iati.core | ---
+++
@@ -7,7 +7,10 @@
def __init__(self, name=None, path=None, xml=None):
def parse_from_xml(xml):
- """Parse a Codelist from the XML that defines it"""
+ """Parse a Codelist from the XML that defines it
+
+ TODO: Define relevant tests and add error handling
+ ... |
67bcacb60a9e24970345d5f6daf3ba3649677b5c | froide/campaign/listeners.py | froide/campaign/listeners.py | from .utils import connect_foirequest
def connect_campaign(sender, **kwargs):
reference = kwargs.get('reference')
if not reference:
return
parts = reference.split(':', 1)
if len(parts) != 2:
return
namespace = parts[0]
connect_foirequest(sender, namespace)
| from .utils import connect_foirequest
def connect_campaign(sender, **kwargs):
reference = kwargs.get('reference')
if not reference:
return
if '@' in reference:
parts = reference.split('@', 1)
else:
parts = reference.split(':', 1)
if len(parts) != 2:
return
names... | Allow connecting froide_campaigns to campaign app | Allow connecting froide_campaigns to campaign app | Python | mit | fin/froide,fin/froide,fin/froide,fin/froide | ---
+++
@@ -5,7 +5,10 @@
reference = kwargs.get('reference')
if not reference:
return
- parts = reference.split(':', 1)
+ if '@' in reference:
+ parts = reference.split('@', 1)
+ else:
+ parts = reference.split(':', 1)
if len(parts) != 2:
return
namespace =... |
ffd917c5ace8e815b185495aec17cf47b0a7648a | storage_service/administration/tests/test_languages.py | storage_service/administration/tests/test_languages.py | from django.contrib.auth.models import User
from django.test import TestCase, override_settings
class TestLanguageSwitching(TestCase):
@classmethod
def setUpClass(cls):
User.objects.create_user(
username="admin", password="admin", email="admin@example.com"
)
super(TestLangu... | from django.contrib.auth.models import User
from django.test import TestCase, override_settings
class TestLanguageSwitching(TestCase):
@classmethod
def setUpClass(cls):
super(TestLanguageSwitching, cls).setUpClass()
User.objects.create_user(
username="admin", password="admin", emai... | Fix integrity error reusing db in tests | Fix integrity error reusing db in tests
Base `setUpClass` needs to be called first so the transaction is initialized
before we mutate the data.
This solves a conflic raised when using `--reuse-db`.
| Python | agpl-3.0 | artefactual/archivematica-storage-service,artefactual/archivematica-storage-service,artefactual/archivematica-storage-service,artefactual/archivematica-storage-service | ---
+++
@@ -5,10 +5,10 @@
class TestLanguageSwitching(TestCase):
@classmethod
def setUpClass(cls):
+ super(TestLanguageSwitching, cls).setUpClass()
User.objects.create_user(
username="admin", password="admin", email="admin@example.com"
)
- super(TestLanguageSwit... |
cc86cb09854cc5656a99e209b27a4c9d9a407bb1 | turbinia/config/turbinia_config.py | turbinia/config/turbinia_config.py | # Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | # Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | Make turbinia-psq the default pubsub queue name | Make turbinia-psq the default pubsub queue name
| Python | apache-2.0 | google/turbinia,google/turbinia,google/turbinia,google/turbinia,google/turbinia | ---
+++
@@ -15,7 +15,7 @@
# Turbinia Config
# Valid values are 'PSQ' or 'Celery'
-TASK_MANAGER = 'PSQ'
+TASK_MANAGER = u'PSQ'
# Time between heartbeats in seconds
WORKER_HEARTBEAT = 600
# Timeout between heartbeats for Workers to be considered inactive
@@ -28,7 +28,7 @@
DEVICE_NAME = None
SCRATCH_PATH = None... |
138fd41960013b11ae1c49d46140b69c24b27abd | tests/stonemason/service/tileserver/test_tileserver.py | tests/stonemason/service/tileserver/test_tileserver.py | # -*- encoding: utf-8 -*-
import os
import unittest
from stonemason.service.tileserver import AppBuilder
class TestExample(unittest.TestCase):
def setUp(self):
os.environ['EXAMPLE_APP_ENV'] = 'dev'
app = AppBuilder().build()
self.client = app.test_client()
def test_app(self):
... | # -*- encoding: utf-8 -*-
import os
import unittest
from stonemason.service.tileserver import AppBuilder
class TestExample(unittest.TestCase):
def setUp(self):
os.environ['EXAMPLE_APP_ENV'] = 'dev'
app = AppBuilder().build()
self.client = app.test_client()
def test_app(self):
... | Fix a compatible bug. Response data is binary in Python 3. | Fix: Fix a compatible bug. Response data is binary in Python 3.
| Python | mit | Kotaimen/stonemason,Kotaimen/stonemason | ---
+++
@@ -14,4 +14,4 @@
def test_app(self):
resp = self.client.get('/')
- self.assertEqual('Hello World!', resp.data)
+ self.assertEqual(b'Hello World!', resp.data) |
a0444025e6d861dfef29d307435fa74f10362890 | src/hireme/server.py | src/hireme/server.py | # -*- coding: utf-8 -*-
import flask
from . import rendering
from . import task1, task2
def app_factory():
"""Create a new Flask instance and configure the URL map."""
app = flask.Flask(import_name=__package__)
app.add_url_rule('/', 'index', rendering.render_index)
app.add_url_rule('/task1', 'task1'... | # -*- coding: utf-8 -*-
import flask
from . import rendering
from . import task1, task2
def app_factory(*args, **kwargs):
"""Create a new Flask instance and configure the URL map."""
app = flask.Flask(import_name=__package__)
app.add_url_rule('/', 'index', rendering.render_index)
app.add_url_rule('/... | Allow arbitrary parameters to be passed | Allow arbitrary parameters to be passed
| Python | bsd-2-clause | cutoffthetop/hireme | ---
+++
@@ -6,7 +6,7 @@
from . import task1, task2
-def app_factory():
+def app_factory(*args, **kwargs):
"""Create a new Flask instance and configure the URL map."""
app = flask.Flask(import_name=__package__)
app.add_url_rule('/', 'index', rendering.render_index) |
be127957f35a4673c95a81884adf3484943af079 | future/tests/test_imports_urllib.py | future/tests/test_imports_urllib.py | import unittest
import sys
print([m for m in sys.modules if m.startswith('urllib')])
class MyTest(unittest.TestCase):
def test_urllib(self):
import urllib
print(urllib.__file__)
from future import standard_library
with standard_library.hooks():
import urllib.response
... | from __future__ import absolute_import, print_function
import unittest
import sys
print([m for m in sys.modules if m.startswith('urllib')])
class MyTest(unittest.TestCase):
def test_urllib(self):
import urllib
print(urllib.__file__)
from future import standard_library
with standard... | Tweak to a noisy test module | Tweak to a noisy test module
| Python | mit | krischer/python-future,michaelpacer/python-future,krischer/python-future,michaelpacer/python-future,QuLogic/python-future,QuLogic/python-future,PythonCharmers/python-future,PythonCharmers/python-future | ---
+++
@@ -1,3 +1,5 @@
+from __future__ import absolute_import, print_function
+
import unittest
import sys
print([m for m in sys.modules if m.startswith('urllib')]) |
cad499437969e6b1b23ab7d2639003d4ec6a86b1 | datasets/ccgois/transform.py | datasets/ccgois/transform.py | import datetime
import json
import sys
import ffs
import re
from publish.lib.helpers import filename_for_resource, download_file
from publish.lib.upload import Uploader
def main(workspace):
DATA_DIR = ffs.Path(workspace)
datasets = json.load(open(DATA_DIR / 'ccgois_indicators.json'))
u = Uploader("ccgo... | import datetime
import json
import sys
import ffs
import re
from publish.lib.helpers import filename_for_resource, download_file
from publish.lib.upload import Uploader
def main(workspace):
DATA_DIR = ffs.Path(workspace)
datasets = json.load(open(DATA_DIR / 'ccgois_indicators.json'))
u = Uploader("ccgo... | Fix the naming of the newly created resources | Fix the naming of the newly created resources
| Python | mit | nhsengland/publish-o-matic | ---
+++
@@ -18,7 +18,7 @@
resources = []
for resource in dataset['sources']:
resource['format'] = resource['filetype']
- resource['name'] = resource['url'].split('/')[-1],
+ resource['name'] = resource['url'].split('/')[-1]
filename = filename_for_re... |
3128c2be4cd44977638c81e22a24c956a273153a | allaccess/__init__.py | allaccess/__init__.py | """
django-all-access is a reusable application for user registration and authentication
from OAuth 1.0 and OAuth 2.0 providers such as Twitter and Facebook.
"""
__version__ = '0.5.1'
import logging
class NullHandler(logging.Handler):
"No-op logging handler."
def emit(self, record):
pass
# Confi... | """
django-all-access is a reusable application for user registration and authentication
from OAuth 1.0 and OAuth 2.0 providers such as Twitter and Facebook.
"""
__version__ = '0.6.0dev'
import logging
class NullHandler(logging.Handler):
"No-op logging handler."
def emit(self, record):
pass
# Co... | Update master version to reflect dev status. | Update master version to reflect dev status.
| Python | bsd-2-clause | iXioN/django-all-access,vyscond/django-all-access,mlavin/django-all-access,iXioN/django-all-access,dpoirier/django-all-access,mlavin/django-all-access,dpoirier/django-all-access,vyscond/django-all-access | ---
+++
@@ -4,7 +4,7 @@
"""
-__version__ = '0.5.1'
+__version__ = '0.6.0dev'
import logging |
3842fef4a2f291b64d83a3977946b07c86ac46d6 | build/identfilter.py | build/identfilter.py | #!/usr/bin/env python
import sys
import re
NUMBER_REGEX = re.compile(r'([0-9])([a-z])')
def to_camel_case(text):
# We only care about types that end with '_t'
if not text.endswith('_t'):
return text
res = []
for token in text[:-2].split('_'):
uc_token = token.title()
# We need to do this f... | #!/usr/bin/env python
import sys
import re
NUMBER_REGEX = re.compile(r'([0-9])([a-z])')
def to_camel_case(text):
# We only care about types that end with '_t'
if not text.endswith('_t'):
return text
res = []
for token in text[:-2].split('_'):
uc_token = token.title()
# We need to d... | Fix spacing in the filter script | Fix spacing in the filter script
Conflicting file loading directives in Vim screwed up the tab stops.
| Python | mit | criptych/graphene,criptych/graphene,ebassi/graphene,criptych/graphene,criptych/graphene,ebassi/graphene | ---
+++
@@ -6,16 +6,16 @@
NUMBER_REGEX = re.compile(r'([0-9])([a-z])')
def to_camel_case(text):
- # We only care about types that end with '_t'
+ # We only care about types that end with '_t'
if not text.endswith('_t'):
- return text
+ return text
res = []
for token in text[:-2].split(... |
f4cb832d61437ad6e871a1596393adc06ceafab9 | cookiecutter/utils.py | cookiecutter/utils.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
cookiecutter.utils
------------------
Helper functions used throughout Cookiecutter.
"""
import errno
import os
import sys
import contextlib
PY3 = sys.version > '3'
if PY3:
pass
else:
import codecs
def make_sure_path_exists(path):
"""
Ensures that... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
cookiecutter.utils
------------------
Helper functions used throughout Cookiecutter.
"""
import errno
import os
import sys
import contextlib
PY3 = sys.version > '3'
if PY3:
pass
else:
import codecs
def make_sure_path_exists(path):
"""
Ensures that... | Add docstring. 4 spaces for consistency. | Add docstring. 4 spaces for consistency.
| Python | bsd-3-clause | lgp171188/cookiecutter,janusnic/cookiecutter,dajose/cookiecutter,agconti/cookiecutter,willingc/cookiecutter,letolab/cookiecutter,christabor/cookiecutter,cichm/cookiecutter,vincentbernat/cookiecutter,terryjbates/cookiecutter,atlassian/cookiecutter,foodszhang/cookiecutter,michaeljoseph/cookiecutter,cguardia/cookiecutter,... | ---
+++
@@ -47,10 +47,14 @@
@contextlib.contextmanager
def work_in(dirname=None):
- curdir = os.getcwd()
- try:
- if dirname is not None:
- os.chdir(dirname)
- yield
- finally:
- os.chdir(curdir)
+ """
+ Context manager version of os.chdir. When exited, returns to the working
+ directory... |
20d02eef92d458dac890f1ab814ca146f2bd1853 | s3direct/urls.py | s3direct/urls.py | from django.conf.urls import patterns, url
from s3direct.views import get_upload_params
urlpatterns = patterns('',
url('^get_upload_params/',
get_upload_params, name='s3direct'),
)
| from django.conf.urls import url
from s3direct.views import get_upload_params
urlpatterns = [
url('^get_upload_params/', get_upload_params, name='s3direct')
]
| Update urlpatterns to use list of url() | Update urlpatterns to use list of url()
| Python | mit | AlexRiina/django-s3direct,yunojuno/django-s3-upload,yunojuno/django-s3-upload,bradleyg/django-s3direct,yunojuno/django-s3-upload,Artory/django-s3direct,Artory/django-s3direct,bradleyg/django-s3direct,Artory/django-s3direct,AlexRiina/django-s3direct,AlexRiina/django-s3direct,bradleyg/django-s3direct | ---
+++
@@ -1,7 +1,6 @@
-from django.conf.urls import patterns, url
+from django.conf.urls import url
from s3direct.views import get_upload_params
-urlpatterns = patterns('',
- url('^get_upload_params/',
- get_upload_params, name='s3direct'),
- ... |
cff73bbff666745a72a8ffc6750c33aebb80fa4b | feature_extraction.py | feature_extraction.py | from PIL import Image
import glob
def _get_masks():
TRAIN_MASKS = './data/train/*_mask.tif'
return [Image.open(file_name) for file_name in glob.glob(TRAIN_MASKS)]
def _get_mask_labels():
mask_labels = []
for image in _get_masks():
mask_labels.append((image.filename, 255 in image.getdata(... | import re
import glob
from PIL import Image
from tqdm import tqdm
def _get_file_root_name(file_path):
file_root_name_expression = re.compile(r'/[^/]*\.', re.IGNORECASE)
return file_root_name_expression.search(file_path).group(0)[1:-1]
def _get_feature_label_images():
TRAIN_FILES = './data/train/*.tif'
... | Return all data instead of just mask data | Return all data instead of just mask data
| Python | mit | Brok-Bucholtz/Ultrasound-Nerve-Segmentation | ---
+++
@@ -1,19 +1,49 @@
-from PIL import Image
+import re
import glob
-
-def _get_masks():
- TRAIN_MASKS = './data/train/*_mask.tif'
- return [Image.open(file_name) for file_name in glob.glob(TRAIN_MASKS)]
+from PIL import Image
+from tqdm import tqdm
+def _get_file_root_name(file_path):
+ file_root... |
0cf60c650b81d2d396d673e4256be19a5193774e | app/main/helpers/s3.py | app/main/helpers/s3.py | import os
import boto
import datetime
class S3(object):
def __init__(self, bucket_name=None, host='s3-eu-west-1.amazonaws.com'):
conn = boto.connect_s3(host=host)
self.bucket_name = bucket_name
self.bucket = conn.get_bucket(bucket_name)
def save(self, path, name, file, acl='public-re... | import os
import boto
import datetime
import mimetypes
class S3(object):
def __init__(self, bucket_name=None, host='s3-eu-west-1.amazonaws.com'):
conn = boto.connect_s3(host=host)
self.bucket_name = bucket_name
self.bucket = conn.get_bucket(bucket_name)
def save(self, path, name, fil... | Set Content-Type header for S3 uploads | Set Content-Type header for S3 uploads
Current document updates do not preserve the content type - it is reset to "application/octet-stream"
We should set the correct content type so that browsers know what to do when users access the documents.
| Python | mit | alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace... | ---
+++
@@ -1,6 +1,7 @@
import os
import boto
import datetime
+import mimetypes
class S3(object):
@@ -23,5 +24,6 @@
)
key = self.bucket.new_key(full_path)
- key.set_contents_from_file(file)
+ mimetype, _ = mimetypes.guess_type(key.name)
+ key.set_contents_from_file... |
8c5aca4b9957e883a9dab8c95933de7285ab335b | login/middleware.py | login/middleware.py | from django.conf import settings
from django.http import HttpResponseRedirect
DETACH_PATH = '/user/detach'
ACTIVATE_PATH = '/user/activate'
class DetachMiddleware(object):
def process_request(self, request):
if not request.path == '/login/' \
and not request.path.startswith('/api') \
... | from django.conf import settings
from django.http import HttpResponseRedirect
DETACH_PATH = '/user/detach'
ACTIVATE_PATH = '/user/activate'
class DetachMiddleware(object):
def process_request(self, request):
if not request.path == '/login/' \
and not request.path.startswith('/api') \
... | Revert trying to fix activation redirection bug | Revert trying to fix activation redirection bug
This reverts commit c2d63335062abea4cece32bd01132bcf8dce44f2.
It seems like the commit doesn't actually do anything to alleviate the
bug. Since it's also more lenient with its checks, I'll rather revert
it.
| Python | agpl-3.0 | openego/oeplatform,openego/oeplatform,openego/oeplatform,openego/oeplatform | ---
+++
@@ -15,6 +15,6 @@
or request.path.startswith('/logout')):
return HttpResponseRedirect(DETACH_PATH)
elif not request.user.is_mail_verified \
- and not (ACTIVATE_PATH in request.path
+ and not (request.path.startswi... |
7d862be1aba5a062eeaf54ada9587278e7e93f5b | apps/provider/urls.py | apps/provider/urls.py | from __future__ import absolute_import
from __future__ import unicode_literals
from django.conf.urls import patterns, include, url
from .views import *
urlpatterns = patterns('',
url(r'^pjson/push$', pjson_provider_push, name="pjson_provider_push"),
url(r'^fhir/push$', fhir_practitioner_push, name="fhir_p... | from __future__ import absolute_import
from __future__ import unicode_literals
from django.conf.urls import patterns, include, url
from .views import *
urlpatterns = patterns('',
url(r'^pjson/push$', pjson_provider_push, name="pjson_provider_push"),
url(r'^fhir/practioner/push$', fhir_practitioner_push, n... | Change fhir practitioner url and add organization url | Change fhir practitioner url and add organization url
| Python | apache-2.0 | TransparentHealth/hhs_oauth_client,TransparentHealth/hhs_oauth_client,TransparentHealth/hhs_oauth_client,TransparentHealth/hhs_oauth_client | ---
+++
@@ -8,6 +8,7 @@
urlpatterns = patterns('',
url(r'^pjson/push$', pjson_provider_push, name="pjson_provider_push"),
- url(r'^fhir/push$', fhir_practitioner_push, name="fhir_practitioner_push"),
+ url(r'^fhir/practioner/push$', fhir_practitioner_push, name="fhir_practitioner_push"),
+ url(r'^... |
9771428d7b0c4a2c0fe057e1030024b13344ccc7 | moa/device/__init__.py | moa/device/__init__.py |
from moa.threading import CallbackQueue
from moa.base import MoaBase
from kivy.properties import BooleanProperty
from kivy.clock import Clock
try:
from Queue import Queue
except ImportError:
from queue import Queue
class Device(MoaBase):
''' By default, the device does not support multi-threading.
''... |
from moa.base import MoaBase
class Device(MoaBase):
''' By default, the device does not support multi-threading.
'''
def activate(self, **kwargs):
pass
def recover(self, **kwargs):
pass
def deactivate(self, **kwargs):
pass
| Clean the base device class. | Clean the base device class.
| Python | mit | matham/moa | ---
+++
@@ -1,54 +1,16 @@
-from moa.threading import CallbackQueue
from moa.base import MoaBase
-from kivy.properties import BooleanProperty
-from kivy.clock import Clock
-try:
- from Queue import Queue
-except ImportError:
- from queue import Queue
class Device(MoaBase):
''' By default, the device... |
ff19efc1b5a51bc4b29c82d32bfe066661dbadca | sonnet/src/conformance/api_test.py | sonnet/src/conformance/api_test.py | # Copyright 2019 The Sonnet Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | # Copyright 2019 The Sonnet Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | Use six.moves to reference `reload`. | Use six.moves to reference `reload`.
PiperOrigin-RevId: 253199825
Change-Id: Ifb9bf182572900a813ea1b0dbbda60f82495eac1
| Python | apache-2.0 | deepmind/sonnet,deepmind/sonnet | ---
+++
@@ -19,9 +19,7 @@
from __future__ import division
from __future__ import print_function
-import importlib
-
-import six
+from six.moves import reload_module as reload
import sonnet as snt
from sonnet.src import test_utils
import tensorflow as tf
@@ -35,10 +33,7 @@
def test_supports_reload(self):
... |
06907e310169db7084f9e40f93e60182ba6e6423 | python/animationBase.py | python/animationBase.py | #!/usr/bin/env python
from rgbmatrix import RGBMatrix
import sys, time
from ball import Ball
rows = 16
chains = 1
parallel = 1
ledMatrix = RGBMatrix(rows, chains, parallel)
numRows = 16
height = ledMatrix.height
width = ledMatrix.width
ball = Ball(5, 9, 4)
try:
print "Press Ctrl + C to stop executing"
while True:
... | #!/usr/bin/env python
from rgbmatrix import RGBMatrix
import sys, time
from ball import Ball
rows = 16
chains = 1
parallel = 1
ledMatrix = RGBMatrix(rows, chains, parallel)
numRows = 16
height = ledMatrix.height
width = ledMatrix.width
red = Ball(5, 9, 4)
blue = Ball(6, 9, 2, 2, 0, 0, 255)
try:
print "Press Ctrl + ... | Add two balls to animation | Add two balls to animation
| Python | mit | DarkAce65/rpi-led-matrix,DarkAce65/rpi-led-matrix | ---
+++
@@ -11,14 +11,17 @@
numRows = 16
height = ledMatrix.height
width = ledMatrix.width
-ball = Ball(5, 9, 4)
+red = Ball(5, 9, 4)
+blue = Ball(6, 9, 2, 2, 0, 0, 255)
try:
print "Press Ctrl + C to stop executing"
while True:
nextFrame = ledMatrix.CreateFrameCanvas()
- ball.updateValues(1 / 60.0)
- b... |
1adc660916eafe5937b96f1b5bc480185efc96ad | aospy_user/__init__.py | aospy_user/__init__.py | """aospy_user: Library of user-defined aospy objects."""
from . import regions
from . import units
from . import calcs
from . import variables
from . import runs
from . import models
from . import projs
from . import obj_from_name
from .obj_from_name import (to_proj, to_model, to_run, to_var, to_region,
... | """aospy_user: Library of user-defined aospy objects."""
from aospy import (LAT_STR, LON_STR, PHALF_STR, PFULL_STR, PLEVEL_STR,
TIME_STR, TIME_STR_IDEALIZED)
from . import regions
from . import units
from . import calcs
from . import variables
from . import runs
from . import models
from . import pr... | Use aospy coord label constants | Use aospy coord label constants
| Python | apache-2.0 | spencerahill/aospy-obj-lib | ---
+++
@@ -1,4 +1,7 @@
"""aospy_user: Library of user-defined aospy objects."""
+from aospy import (LAT_STR, LON_STR, PHALF_STR, PFULL_STR, PLEVEL_STR,
+ TIME_STR, TIME_STR_IDEALIZED)
+
from . import regions
from . import units
from . import calcs |
d739767df47d5fc7424ab40485cba18ab5e137b2 | integration_tests/tests/__init__.py | integration_tests/tests/__init__.py | import logging
import os
import colorlog
import extensions
if os.getenv("CLICOLOR_FORCE") == "1":
print "Forcing colors"
import colorama
colorama.deinit()
def _setup_log():
logging.basicConfig()
root_logger = logging.getLogger()
handler = colorlog.StreamHandler()
form... | import logging
import os
import colorlog
import extensions
if os.getenv("CLICOLOR_FORCE") == "1":
print "Forcing colors"
import colorama
colorama.deinit()
def _setup_log():
root_logger = logging.getLogger()
handler = colorlog.StreamHandler()
formatter = colorlog.ColoredFor... | Remove unnecessary logger configuration from integration tests. | [antenna] Remove unnecessary logger configuration from integration tests.
| Python | agpl-3.0 | PW-Sat2/PWSat2OBC,PW-Sat2/PWSat2OBC,PW-Sat2/PWSat2OBC,PW-Sat2/PWSat2OBC | ---
+++
@@ -11,7 +11,6 @@
def _setup_log():
- logging.basicConfig()
root_logger = logging.getLogger()
handler = colorlog.StreamHandler() |
75a9c9b870102b7864e160988e011b01bb231ed9 | randterrainpy/terraindisplay.py | randterrainpy/terraindisplay.py | """Module for displaying Terrain, both in 2D and 3D.
(Not accessible outside of package; use display methods of Terrain instead.)
"""
from Tkinter import Tk, Frame, BOTH
class Terrain2D(Frame):
"""2D graphical representation of a Terrain object.
Consists of a 2D top-down image of terrain as a grid of grey... | """Module for displaying Terrain, both in 2D and 3D.
(Not accessible outside of package; use display methods of Terrain instead.)
"""
from Tkinter import Tk, Canvas, Frame, BOTH
class Terrain2D(Frame):
"""2D graphical representation of a Terrain object.
Consists of a 2D top-down image of terrain as a grid... | Add empty draw_heights method and docstrings to Terrain2D | Add empty draw_heights method and docstrings to Terrain2D
| Python | mit | jackromo/RandTerrainPy | ---
+++
@@ -4,7 +4,7 @@
"""
-from Tkinter import Tk, Frame, BOTH
+from Tkinter import Tk, Canvas, Frame, BOTH
class Terrain2D(Frame):
@@ -20,17 +20,42 @@
@classmethod
def display_terrain(cls, terrain):
+ """Display a Terrain in 2D.
+
+ Args:
+ terrain (Terrain): Terrain ... |
721f837cbfa0de8804def607908a9744b0d099a8 | asl/vendor/__init__.py | asl/vendor/__init__.py | import sys
import os
_vendor_initialized = False
def append_paths(path, vendor_modules):
new_path = []
for v in vendor_modules:
new_path.append(path + os.sep + v)
sys.path = new_path + sys.path
def do_init():
global _vendor_initialized
if _vendor_initialized:
return
_vendor_i... | import sys
import os
_vendor_initialized = False
def append_paths(path, vendor_modules):
new_path = []
for v in vendor_modules:
new_path.append(path + os.sep + v)
sys.path = new_path + sys.path
def do_init():
global _vendor_initialized
if _vendor_initialized:
return
_vendor_i... | Fix of vendor directory search. | Fix of vendor directory search.
| Python | mit | AtteqCom/zsl,AtteqCom/zsl | ---
+++
@@ -16,18 +16,7 @@
_vendor_initialized = True
- path = "."
- if os.path.exists('./asl/asl/vendor'):
- path = os.path.abspath('./asl/asl/vendor')
- else:
- for p in sys.path:
- if os.path.exists(p + '/vendor/'):
- path = os.path.abspath(p + '/vendor/')
... |
75ce7463218609129151ea96fae4590763165961 | array/quick-sort.py | array/quick-sort.py | # Sort list using recursion
def quick_sort(lst):
if len(lst) == 0:
print []
left = []
right = []
pivot = lst[0]
# compare first element in list to the rest
for i in range(1, len(lst)):
if lst[i] < pivot:
left.append(lst[i])
else:
right.append(lst[i])
# recursion
print quick_sort(left) + pivot + ... | # Sort list using recursion
def quick_sort(lst):
if len(lst) <= 1:
return lst
left = []
right = []
# compare first element in list to the rest
for i in lst[1:]:
if lst[i] < lst[0]:
left.append(i)
else:
right.append(i)
# recursion
return quick_sort(left) + lst[0:1] + quick_sort(right)
# test cas... | Debug and add test case | Debug and add test case
| Python | mit | derekmpham/interview-prep,derekmpham/interview-prep | ---
+++
@@ -1,19 +1,22 @@
# Sort list using recursion
def quick_sort(lst):
- if len(lst) == 0:
- print []
+ if len(lst) <= 1:
+ return lst
left = []
right = []
- pivot = lst[0]
# compare first element in list to the rest
- for i in range(1, len(lst)):
- if lst[i] < pivot:
- left.append(lst[i])
+ fo... |
d7219365197ff22aec44836e37af19f62420f996 | paystackapi/tests/test_tcontrol.py | paystackapi/tests/test_tcontrol.py | import httpretty
from paystackapi.tests.base_test_case import BaseTestCase
from paystackapi.tcontrol import TransferControl
class TestTransfer(BaseTestCase):
@httpretty.activate
def test_check_balance(self):
"""Method defined to test check_balance."""
httpretty.register_uri(
http... | import httpretty
from paystackapi.tests.base_test_case import BaseTestCase
from paystackapi.tcontrol import TransferControl
class TestTransfer(BaseTestCase):
@httpretty.activate
def test_check_balance(self):
"""Method defined to test check_balance."""
httpretty.register_uri(
http... | Add test for transfer control resend otp | Add test for transfer control resend otp
| Python | mit | andela-sjames/paystack-python | ---
+++
@@ -19,3 +19,21 @@
response = TransferControl.check_balance()
self.assertTrue(response['status'])
+
+ @httpretty.activate
+ def test_resend_otp(self):
+ """Method defined to test resend_otp."""
+ httpretty.register_uri(
+ httpretty.POST,
+ self.end... |
b682addf7d65dbb48ad5c0a3506987103ea43835 | miura/morph.py | miura/morph.py | import MeCab
class MeCabParser(object):
def __init__(self, arg=''):
self.model = MeCab.Model_create(arg)
def parse(self, s):
tagger = self.model.createTagger()
lattice = self.model.createLattice()
lattice.set_sentence(s)
tagger.parse(lattice)
node = latt... | import MeCab
class MeCabParser(object):
def __init__(self, arg=''):
self.model = MeCab.Model_create(arg)
def parse(self, s):
tagger = self.model.createTagger()
lattice = self.model.createLattice()
lattice.set_sentence(s)
tagger.parse(lattice)
node = latt... | Use find instead of split | Use find instead of split
| Python | mit | unnonouno/mrep | ---
+++
@@ -16,7 +16,7 @@
feature = node.feature
morphs.append({
'surface': node.surface,
- 'pos': feature.split(',')[0],
+ 'pos': feature[0:feature.find(',')],
'feature': feature,
})
... |
fce1a7e5c1466ef79c5387f4b9f0c231e745f380 | basics/candidate.py | basics/candidate.py |
import numpy as np
class Bubble2D(object):
"""
Class for candidate bubble portions from 2D planes.
"""
def __init__(self, props):
super(Bubble2D, self).__init__()
self._y = props[0]
self._x = props[1]
self._major = props[2]
self._minor = props[3]
self.... |
import numpy as np
class Bubble2D(object):
"""
Class for candidate bubble portions from 2D planes.
"""
def __init__(self, props):
super(Bubble2D, self).__init__()
self._y = props[0]
self._x = props[1]
self._major = props[2]
self._minor = props[3]
self.... | Return as array; start of finding shell fraction | Return as array; start of finding shell fraction
| Python | mit | e-koch/BaSiCs | ---
+++
@@ -17,8 +17,8 @@
@property
def params(self):
- return [self._y, self._x, self._major,
- self._minor, self._pa]
+ return np.array([self._y, self._x, self._major,
+ self._minor, self._pa])
@property
def area(self):
@@ -36,7 +36,7 @@
... |
bfa446d5fc399b685419ad00c376bcd9a13a8605 | mediacrush/decorators.py | mediacrush/decorators.py | from flask import jsonify, request
from functools import wraps
import json
def json_output(f):
@wraps(f)
def wrapper(*args, **kwargs):
def jsonify_wrap(obj):
callback = request.args.get('callback', False)
jsonification = jsonify(obj)
if callback:
jso... | from flask import jsonify, request
from functools import wraps
import json
jsonp_notice = """
// MediaCrush supports Cross Origin Resource Sharing requests.
// There is no reason to use JSONP; please use CORS instead.
// For more information, see https://mediacru.sh/docs/api"""
def json_output(f):
@wraps(f)
d... | Add JSONP notice to API | Add JSONP notice to API | Python | mit | nerdzeu/NERDZCrush,MediaCrush/MediaCrush,roderickm/MediaCrush,roderickm/MediaCrush,nerdzeu/NERDZCrush,MediaCrush/MediaCrush,nerdzeu/NERDZCrush,roderickm/MediaCrush | ---
+++
@@ -1,6 +1,11 @@
from flask import jsonify, request
from functools import wraps
import json
+
+jsonp_notice = """
+// MediaCrush supports Cross Origin Resource Sharing requests.
+// There is no reason to use JSONP; please use CORS instead.
+// For more information, see https://mediacru.sh/docs/api"""
de... |
a45f729d803d32cedd1b511c55c11ba53940c698 | server/lib/stl_tools.py | server/lib/stl_tools.py | import subprocess
import re
import os
from lib.utils import loadYaml
config = loadYaml('../config.yml')
dimensionsRegex = r'{type} = +(\-?\d+\.\d+)'
types = {
'x': ['Min X', 'Max X'],
'y': ['Min Y', 'Max Y'],
'z': ['Min Z', 'Max Z'],
}
def analyzeSTL(path, fileName):
command = subprocess.Popen('{ADMeshExecut... | import subprocess
import re
import os
from lib.utils import loadYaml
config = loadYaml('../config.yml')
dimensionsRegex = r'{type} = +(\-?\d+\.\d+)'
types = {
'x': ['Min X', 'Max X'],
'y': ['Min Y', 'Max Y'],
'z': ['Min Z', 'Max Z'],
}
def analyzeSTL(path, fileName):
command = subprocess.Popen('{ADMeshExecut... | Fix calculation of model size | Fix calculation of model size
| Python | agpl-3.0 | MakersLab/custom-print | ---
+++
@@ -24,7 +24,7 @@
try:
firstVal = re.findall(dimensionsRegex.format(type=types[type][0]), output)[0]
secondVal = re.findall(dimensionsRegex.format(type=types[type][1]), output)[0]
- dimensions[type] = abs(float(firstVal)) + abs(float(secondVal))
+ dimensions[type] = abs(float(firs... |
b5db32721780c168cd7e2f5915dd4256fb9f9018 | board/pagination.py | board/pagination.py | from django.core.paginator import Paginator
class HCPaginator(Paginator):
adjacent_pages = 5
def page(self, number):
self.page_num = number
return super().page(number)
@property
def page_range(self):
start = max(1, self.page_num - self.adjacent_pages)
end = min(self.n... | from django.core.paginator import Paginator
class HCPaginator(Paginator):
adjacent_pages = 5
def page(self, number):
self.page_num = number
return super().page(number)
@property
def page_range(self):
start = max(1, self.page_num - self.adjacent_pages)
end = min(self.n... | Return iterator instead of list in paginator | Return iterator instead of list in paginator
| Python | mit | devunt/hydrocarbon,devunt/hydrocarbon,devunt/hydrocarbon | ---
+++
@@ -17,4 +17,4 @@
end += self.adjacent_pages - (self.page_num - start)
if end == self.num_pages:
start -= self.adjacent_pages - (end - self.page_num)
- return list(range(start, end + 1))
+ return range(start, end + 1) |
30dd3c8436ebe69aff2956322312072e8ab581f0 | example/tests/test_fields.py | example/tests/test_fields.py | # -*- coding: utf-8
from __future__ import unicode_literals
from django.test import TestCase
from shop.models.cart import BaseCartItem
class JSONFieldTest(TestCase):
"""JSONField Wrapper Tests"""
def test_json_field_create(self):
"""Test saving a JSON object in our JSONField"""
json_obj = {... | # -*- coding: utf-8
from __future__ import unicode_literals
from django.test import TestCase
from shop.models.defaults.customer import Customer
class JSONFieldTest(TestCase):
"""JSONField Wrapper Tests"""
def test_json_field_create(self):
"""Test saving a JSON object in our JSONField"""
jso... | Update model used to test | Update model used to test
| Python | bsd-3-clause | jrief/django-shop,khchine5/django-shop,khchine5/django-shop,awesto/django-shop,divio/django-shop,khchine5/django-shop,nimbis/django-shop,jrief/django-shop,khchine5/django-shop,nimbis/django-shop,divio/django-shop,jrief/django-shop,nimbis/django-shop,nimbis/django-shop,awesto/django-shop,awesto/django-shop,jrief/django-... | ---
+++
@@ -3,7 +3,7 @@
from django.test import TestCase
-from shop.models.cart import BaseCartItem
+from shop.models.defaults.customer import Customer
class JSONFieldTest(TestCase):
@@ -15,7 +15,7 @@
"item_1": "this is a json blah",
"blergh": "hey, hey, hey"}
- obj = Base... |
b0a94dc2f696464db999e652b4a9dbdaf96f8532 | backend/talks/forms.py | backend/talks/forms.py | from django import forms
from django.utils.translation import ugettext_lazy as _
from api.forms import GrapheneModelForm
from languages.models import Language
from conferences.models import Conference
from .models import Talk
class ProposeTalkForm(GrapheneModelForm):
conference = forms.ModelChoiceField(queryse... | from django import forms
from django.utils.translation import ugettext_lazy as _
from api.forms import GrapheneModelForm
from languages.models import Language
from conferences.models import Conference
from .models import Talk
class ProposeTalkForm(GrapheneModelForm):
conference = forms.ModelChoiceField(queryse... | Mark conference and language as required | Mark conference and language as required
| Python | mit | patrick91/pycon,patrick91/pycon | ---
+++
@@ -10,14 +10,14 @@
class ProposeTalkForm(GrapheneModelForm):
- conference = forms.ModelChoiceField(queryset=Conference.objects.all(), to_field_name='code')
- language = forms.ModelChoiceField(queryset=Language.objects.all(), to_field_name='code')
+ conference = forms.ModelChoiceField(queryset=C... |
fb14ac15bcb1db14f756e8943f551ba428de4c7f | dusty/systems/known_hosts/__init__.py | dusty/systems/known_hosts/__init__.py | import os
import logging
from ...subprocess import check_output
def _get_known_hosts_path():
ssh_dir = os.path.expanduser('~root/.ssh')
if not os.path.isdir(ssh_dir):
os.makedirs(ssh_dir)
return os.path.join(ssh_dir, 'known_hosts')
def ensure_known_hosts(hosts):
known_hosts_path = _get_known_... | import os
import logging
from ...subprocess import check_output
def _get_known_hosts_path():
ssh_dir = os.path.expanduser('~root/.ssh')
if not os.path.isdir(ssh_dir):
os.makedirs(ssh_dir)
return os.path.join(ssh_dir, 'known_hosts')
def ensure_known_hosts(hosts):
known_hosts_path = _get_known_... | Create required known_hosts file if it does not exists | Create required known_hosts file if it does not exists
| Python | mit | gamechanger/dusty,gamechanger/dusty,gamechanger/dusty,gamechanger/dusty,gamechanger/dusty | ---
+++
@@ -11,6 +11,8 @@
def ensure_known_hosts(hosts):
known_hosts_path = _get_known_hosts_path()
+ if not os.path.exists(known_hosts_path):
+ open(known_hosts_path, 'a+').close()
modified = False
with open(known_hosts_path, 'r+') as f:
contents = f.read() |
4cb455890b7afa4f44da9d96a5c9820598731b36 | sedlex/AddGitHubIssueVisitor.py | sedlex/AddGitHubIssueVisitor.py | # -*- coding: utf-8 -*-
from AbstractVisitor import AbstractVisitor
from duralex.alinea_parser import *
from github import Github
class AddGitHubIssueVisitor(AbstractVisitor):
def __init__(self, args):
self.github = Github(args.github_token)
self.repo = self.github.get_repo(args.github_repositor... | # -*- coding: utf-8 -*-
from AbstractVisitor import AbstractVisitor
from duralex.alinea_parser import *
from github import Github
class AddGitHubIssueVisitor(AbstractVisitor):
def __init__(self, args):
self.github = Github(args.github_token)
self.repo = self.github.get_repo(args.github_repositor... | Fix missing githubIssue field when the corresponding issue already existed. | Fix missing githubIssue field when the corresponding issue already existed.
| Python | agpl-3.0 | Legilibre/SedLex | ---
+++
@@ -39,6 +39,7 @@
issue.edit(title=title, body=body)
if not found:
issue = self.repo.create_issue(title=title, body=body)
+ node['githubIssue'] = issue.html_url
self.current_issue = issue.number
super(AddGitHubIs... |
7503ebff7ded94a52ed5bb6e0a72935071576e20 | tests/test_default.py | tests/test_default.py | def test_confluence_user(User):
user = User("confluence")
assert user.exists
assert user.group == "confluence"
| def test_confluence_user(User):
user = User("confluence")
assert user.exists
assert user.group == "confluence"
def test_confluence_group(Group):
group = Group("confluence")
assert group.exists
| Add a testinfra group example | Add a testinfra group example
| Python | apache-2.0 | telstra-digital/ansible-role-confluence,telstra-digital/ansible-role-confluence | ---
+++
@@ -3,3 +3,9 @@
assert user.exists
assert user.group == "confluence"
+
+
+def test_confluence_group(Group):
+ group = Group("confluence")
+
+ assert group.exists |
843601dbd89d7ac99b128684bb19e9363e867b8a | tests/test_stumpff.py | tests/test_stumpff.py | from numpy import cos, cosh, sin, sinh
from numpy.testing import assert_allclose, assert_equal
from poliastro._math.special import stumpff_c2 as c2, stumpff_c3 as c3
def test_stumpff_functions_near_zero():
psi = 0.5
expected_c2 = (1 - cos(psi**0.5)) / psi
expected_c3 = (psi**0.5 - sin(psi**0.5)) / psi**1... | from numpy import cos, cosh, sin, sinh
from numpy.testing import assert_allclose
from poliastro._math.special import stumpff_c2 as c2, stumpff_c3 as c3
def test_stumpff_functions_near_zero():
psi = 0.5
expected_c2 = (1 - cos(psi**0.5)) / psi
expected_c3 = (psi**0.5 - sin(psi**0.5)) / psi**1.5
assert... | Use numpy.testing.assert_allclose with small relative tolerance | test: Use numpy.testing.assert_allclose with small relative tolerance
To avoid having numpy.testing.assert_equal fail in some cases at the
level of machine precision, use numpy.testing.assert_allclose instead
with a relative tolerance set small, 1e-10, to still be restrictive in
the level of equality accepted.
| Python | mit | poliastro/poliastro | ---
+++
@@ -1,5 +1,5 @@
from numpy import cos, cosh, sin, sinh
-from numpy.testing import assert_allclose, assert_equal
+from numpy.testing import assert_allclose
from poliastro._math.special import stumpff_c2 as c2, stumpff_c3 as c3
@@ -18,8 +18,8 @@
expected_c2 = (1 - cos(psi**0.5)) / psi
expected_c... |
62f6e116306901aedaa738236075c4faa00db74d | tests/config_test.py | tests/config_test.py | #!/usr/bin/python
#
# Copyright 2014 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | #!/usr/bin/python
#
# Copyright 2014 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | Fix module path (config -> config_yaml) to unbreak test. | Fix module path (config -> config_yaml) to unbreak test.
| Python | apache-2.0 | mbrukman/cloud-launcher,mbrukman/cloud-launcher,mbrukman/cloud-launcher,mbrukman/cloud-launcher | ---
+++
@@ -24,7 +24,7 @@
import unittest
# Local imports
-import config
+import config_yaml
class ConfigExpanderTest(unittest.TestCase):
@@ -36,7 +36,7 @@
with open(expected) as expected_in:
expected_json = json.loads(expected_in.read(), encoding='utf-8')
- expander = config.ConfigExp... |
c47b2d88fce9f890e7356288faf097cf4a97f0b8 | simplesqlite/_logger/_logger.py | simplesqlite/_logger/_logger.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
import sqliteschema
import tabledata
from ._null_logger import NullLogger
MODULE_NAME = "simplesqlite"
try:
from loguru import logger
logger.disable(MODULE_... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
import sqliteschema
import tabledata
from ._null_logger import NullLogger
MODULE_NAME = "simplesqlite"
_is_enable = False
try:
from loguru import logger
log... | Add check for logging state | Add check for logging state
| Python | mit | thombashi/SimpleSQLite,thombashi/SimpleSQLite | ---
+++
@@ -13,6 +13,7 @@
MODULE_NAME = "simplesqlite"
+_is_enable = False
try:
@@ -24,6 +25,11 @@
def set_logger(is_enable):
+ global _is_enable
+
+ if is_enable == _is_enable:
+ return
+
if is_enable:
logger.enable(MODULE_NAME)
else: |
c784fb30beac7abe958867345161f74876ca940d | causalinfo/__init__.py | causalinfo/__init__.py | from .probability import (
vs,
Variable,
make_variables,
UniformDist,
JointDist,
JointDistByState
)
from .network import CausalGraph, Equation
from .measure import MeasureCause, MeasureSuccess
from .payoff import PayoffMatrix
import equations
__version__ = "0.1.0"
__title__ = "causalinfo"
... | from .probability import (
vs,
Variable,
make_variables,
UniformDist,
JointDist,
JointDistByState
)
from .network import CausalGraph, Equation
from .measure import MeasureCause, MeasureSuccess
from .payoff import PayoffMatrix
import equations
__version__ = "0.1.0"
__title__ = "causalinfo"
... | Fix silly boiler plate copy issue. | Fix silly boiler plate copy issue.
| Python | mit | brettc/causalinfo | ---
+++
@@ -18,7 +18,7 @@
__version__ = "0.1.0"
__title__ = "causalinfo"
-__description__ = "Attributes without boilerplate."
+__description__ = "Information Measures on Causal Graphs."
__uri__ = "http://github/brettc/causalinfo/"
__author__ = "Brett Calcott" |
8c203bfb28e027e4fdd490096296f712c3afd28e | consulrest/keyvalue.py | consulrest/keyvalue.py | import json
import re
import requests
class KeyValue(object):
def __init__(self, url):
self._url = "%s/kv" % url
def _get(self, key, recurse=None, keys=None):
url = self._url + '/' + key
params = dict()
if recurse is not None:
params['recurse'] = True
if k... | import json
import re
import requests
class KeyValue(object):
def __init__(self, url):
self._url = "%s/kv" % url
def _get(self, key, recurse=None, keys=None):
url = self._url + '/' + key
params = dict()
if recurse is not None:
params['recurse'] = True
if k... | Return None if key is not found | Return None if key is not found
| Python | mit | vcoque/consul-ri | ---
+++
@@ -20,13 +20,15 @@
if r.ok:
return json.loads(r.text)
+ elif r.status_code == 404:
+ return None
else:
r.raise_for_status()
def get(self, key, recurse=None):
return self._get(key, recurse=recurse)
- def list(self, key=''):
+... |
a013927ee9772e05ae4255cff98ecfe4819f205c | flask_app/__init__.py | flask_app/__init__.py | """
The flask application package.
"""
from flask import Flask
from flask.ext import login
import models
app = Flask(__name__)
# Flask-Login initialization
login_manager = login.LoginManager()
login_manager.init_app(app)
@login_manager.user_loader
def load_user(user_id):
return models.User.get(user_id)
# See co... | """
The flask application package.
"""
from flask import Flask
from flask.ext import login
import models
app = Flask(__name__)
# Flask-Login initialization
login_manager = login.LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
@login_manager.user_loader
def load_user(user_id):
return... | Set login view for login_required | Set login view for login_required
| Python | mit | szeestraten/kidsakoder-minecraft,szeestraten/kidsakoder-minecraft,szeestraten/kidsakoder-minecraft,szeestraten/kidsakoder-minecraft | ---
+++
@@ -11,6 +11,7 @@
# Flask-Login initialization
login_manager = login.LoginManager()
login_manager.init_app(app)
+login_manager.login_view = 'login'
@login_manager.user_loader
def load_user(user_id):
return models.User.get(user_id) |
9698e531ffd528b6b56e285f5cf8087aa06d4a02 | test/conftest.py | test/conftest.py | import pytest
@pytest.fixture
def namespaces():
import class_namespaces
return class_namespaces
@pytest.fixture
def compat():
import class_namespaces.compat
return class_namespaces.compat
@pytest.fixture
def abc():
import class_namespaces.compat.abc
return class_namespaces.compat.abc
| import pytest
@pytest.fixture
def namespaces():
import class_namespaces
return class_namespaces
@pytest.fixture
def namespace(namespaces):
return namespaces.Namespace
@pytest.fixture
def compat():
import class_namespaces.compat
return class_namespaces.compat
@pytest.fixture
def abc():
im... | Add fixture for Namespace specifically. | Add fixture for Namespace specifically.
| Python | mit | mwchase/class-namespaces,mwchase/class-namespaces | ---
+++
@@ -5,6 +5,11 @@
def namespaces():
import class_namespaces
return class_namespaces
+
+
+@pytest.fixture
+def namespace(namespaces):
+ return namespaces.Namespace
@pytest.fixture |
a9fd1154c99d1377e0da5127762d6248f3c9f81f | github3/gists/file.py | github3/gists/file.py | # -*- coding: utf-8 -*-
"""
github3.gists.file
------------------
Module containing the logic for the GistFile object.
"""
from __future__ import unicode_literals
import requests
from ..models import GitHubObject
class GistFile(GitHubObject):
"""This represents the file object returned by interacting with gis... | # -*- coding: utf-8 -*-
"""
github3.gists.file
------------------
Module containing the logic for the GistFile object.
"""
from __future__ import unicode_literals
from ..models import GitHubCore
class GistFile(GitHubCore):
"""This represents the file object returned by interacting with gists.
It stores th... | Load content from raw_url if empty | Load content from raw_url if empty
| Python | bsd-3-clause | balloob/github3.py,christophelec/github3.py,sigmavirus24/github3.py | ---
+++
@@ -7,12 +7,10 @@
"""
from __future__ import unicode_literals
-import requests
-
-from ..models import GitHubObject
+from ..models import GitHubCore
-class GistFile(GitHubObject):
+class GistFile(GitHubCore):
"""This represents the file object returned by interacting with gists.
@@ -33,8 +31,... |
b26614d3f29824e9c5ec0663f09855074f754ddf | globus_sdk/version.py | globus_sdk/version.py | # single source of truth for package version,
# see https://packaging.python.org/en/latest/single_source_version/
__version__ = "1.6.0"
| # single source of truth for package version,
# see https://packaging.python.org/en/latest/single_source_version/
__version__ = "1.6.1"
| Update to v1.6.1 for release | Update to v1.6.1 for release
- Replace egg distribution format with wheels (#314)
- Internal maintenance
| Python | apache-2.0 | sirosen/globus-sdk-python,globusonline/globus-sdk-python,globus/globus-sdk-python,globus/globus-sdk-python | ---
+++
@@ -1,3 +1,3 @@
# single source of truth for package version,
# see https://packaging.python.org/en/latest/single_source_version/
-__version__ = "1.6.0"
+__version__ = "1.6.1" |
d6f13599f47ff4b4926d07d79962d3fff36ab6c4 | gradebook/__init__.py | gradebook/__init__.py | from collections import OrderedDict
import os
import sys
import json
try:
gb_home = os.environ["GB_HOME"]
except KeyError:
raise RuntimeError("Please set the environment variable GB_HOME")
repo_dir = os.path.join(gb_home, 'repos')
data_dir = os.path.join(gb_home, 'data')
log_dir = os.path.join(gb_home, 'log')
... | from collections import OrderedDict
import os
import sys
import json
try:
gb_home = os.environ["GB_HOME"]
except KeyError:
raise RuntimeError("Please set the environment variable GB_HOME")
repo_dir = os.path.join(gb_home, 'repos')
data_dir = os.path.join(gb_home, 'data')
log_dir = os.path.join(gb_home, 'log')
... | Add placeholder for CSV file | Add placeholder for CSV file
| Python | bsd-2-clause | jarrodmillman/gradebook | ---
+++
@@ -19,6 +19,7 @@
student_grades = grade_file
class_grades = os.path.join(data_dir, grade_file)
config_file = os.path.join(data_dir, 'config.json')
+csv_file = os.path.join(data_home, 'grades.csv')
class_log = os.path.join(log_dir, 'grade.log')
|
465a13cad35b62a0fc64768ec6b2aed0573566da | ubersmith/__init__.py | ubersmith/__init__.py |
__all__ = [
'api',
'calls',
'entities',
]
|
__all__ = [
'api',
'calls',
'entities',
'exceptions',
'utils',
]
| Add new modules to package init. | Add new modules to package init.
| Python | mit | jasonkeene/python-ubersmith,jasonkeene/python-ubersmith,hivelocity/python-ubersmith,hivelocity/python-ubersmith | ---
+++
@@ -3,4 +3,6 @@
'api',
'calls',
'entities',
+ 'exceptions',
+ 'utils',
] |
cf5fb07651099e38e6487eae641da07feda40b05 | numba/tests/test_api.py | numba/tests/test_api.py | import numba
from numba.tests.support import TestCase
import unittest
class TestNumbaModule(TestCase):
"""
Test the APIs exposed by the top-level `numba` module.
"""
def check_member(self, name):
self.assertTrue(hasattr(numba, name), name)
self.assertIn(name, numba.__all__)
def ... | import numba
from numba import jit, njit
from numba.tests.support import TestCase
import unittest
class TestNumbaModule(TestCase):
"""
Test the APIs exposed by the top-level `numba` module.
"""
def check_member(self, name):
self.assertTrue(hasattr(numba, name), name)
self.assertIn(na... | Add testcases for jit and njit with forceobj and nopython | Add testcases for jit and njit with forceobj and nopython
| Python | bsd-2-clause | numba/numba,cpcloud/numba,seibert/numba,stuartarchibald/numba,sklam/numba,seibert/numba,stonebig/numba,IntelLabs/numba,cpcloud/numba,stuartarchibald/numba,IntelLabs/numba,IntelLabs/numba,numba/numba,stonebig/numba,stonebig/numba,IntelLabs/numba,seibert/numba,stonebig/numba,gmarkall/numba,numba/numba,sklam/numba,IntelLa... | ---
+++
@@ -1,4 +1,5 @@
import numba
+from numba import jit, njit
from numba.tests.support import TestCase
import unittest
@@ -28,5 +29,45 @@
numba.__version__ # not in __all__
+class TestJitDecorator(TestCase):
+ """
+ Test the jit and njit decorators
+ """
+ def test_jit_nopython_forc... |
95245bb7fab6efe5a72cb8abbf4380a26b72a720 | corehq/apps/hqwebapp/middleware.py | corehq/apps/hqwebapp/middleware.py | import logging
from django.middleware.csrf import CsrfViewMiddleware, REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN
from django.conf import settings
logger = logging.getLogger('')
class HQCsrfViewMiddleWare(CsrfViewMiddleware):
def _reject(self, request, reason):
if settings.CSRF_ALWAYS_OFF and reason in [R... | from django.middleware.csrf import CsrfViewMiddleware, REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN
from corehq.util.soft_assert import soft_assert
from django.conf import settings
class HQCsrfViewMiddleWare(CsrfViewMiddleware):
def _reject(self, request, reason):
if settings.CSRF_ALWAYS_OFF and reason in [R... | Revert "log to file, don't email" | Revert "log to file, don't email"
This reverts commit a132890ef32c99b938021717b67c3e58c13952b0.
| Python | bsd-3-clause | qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq | ---
+++
@@ -1,10 +1,7 @@
-import logging
+from django.middleware.csrf import CsrfViewMiddleware, REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN
-from django.middleware.csrf import CsrfViewMiddleware, REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN
+from corehq.util.soft_assert import soft_assert
from django.conf import settings
... |
ab4e279a6866d432cd1f58a07879e219360b4911 | src/tenyksscripts/scripts/8ball.py | src/tenyksscripts/scripts/8ball.py | import random
ateball = [
"It is certain.",
"It is decidedly so.",
"Without a doubt.",
"Yes, definitely.",
"You may rely on it.",
"As I see it, yes.",
"Most likely.",
"Outlook good.",
"Yes.",
"Signs point to yes.",
"Reply hazy, try... | import random
ateball = [
"It is certain",
"It is decidedly so",
"Without a doubt",
"Yes definitely",
"You may rely on it",
"As I see it yes",
"Most likely",
"Outlook good",
"Yes",
"Signs point to yes",
"Reply hazy try again",
... | Revert "Added nickname and punct, removed parens" | Revert "Added nickname and punct, removed parens"
This reverts commit 061de1a57a95cd2911c06bb58c29a8e488b7387e.
| Python | mit | colby/tenyks-contrib,cblgh/tenyks-contrib,kyleterry/tenyks-contrib | ---
+++
@@ -1,30 +1,28 @@
import random
ateball = [
- "It is certain.",
- "It is decidedly so.",
- "Without a doubt.",
- "Yes, definitely.",
- "You may rely on it.",
- "As I see it, yes.",
- "Most likely.",
- "Outlook good.",
- "Yes.",
- "Signs... |
6cf3baed6e5f707e5c307388018f4bb3121327f9 | nanoservice/config.py | nanoservice/config.py | """ Read configuration for a service from a json file """
import io
import json
from .client import Client
from .error import ConfigError
def load(filepath=None, filecontent=None, clients=True):
""" Read the json file located at `filepath`
If `filecontent` is specified, its content will be json decoded
... | """ Read configuration for a service from a json file """
import io
import json
from .client import Client
from .error import ConfigError
class DotDict(dict):
""" Access a dictionary like an object """
def __getattr__(self, key):
return self[key]
def __setattr__(self, key, value):
self... | Access the conf like a object | Access the conf like a object
| Python | mit | walkr/nanoservice | ---
+++
@@ -5,6 +5,16 @@
from .client import Client
from .error import ConfigError
+
+
+class DotDict(dict):
+ """ Access a dictionary like an object """
+
+ def __getattr__(self, key):
+ return self[key]
+
+ def __setattr__(self, key, value):
+ self[key] = value
def load(filepath=None... |
1fb34b960f10d362fbc436c47fafc127be59584e | template_utils/templatetags/generic_markup.py | template_utils/templatetags/generic_markup.py | """
Filters for converting plain text to HTML and enhancing the
typographic appeal of text on the Web.
"""
from django.conf import settings
from django.template import Library
from template_utils.markup import formatter
def apply_markup(value, arg=None):
"""
Applies text-to-HTML conversion.
Takes an... | """
Filters for converting plain text to HTML and enhancing the
typographic appeal of text on the Web.
"""
from django.conf import settings
from django.template import Library
from template_utils.markup import formatter
def apply_markup(value, arg=None):
"""
Applies text-to-HTML conversion.
Takes an... | Enable the SmartyPants filter; need to document it later | Enable the SmartyPants filter; need to document it later
git-svn-id: 4b29f3e8959dfd6aa2f99bd14fd314e33970d95d@74 d6b9e1ad-042d-0410-a639-15a354c1509c
| Python | bsd-3-clause | clones/django-template-utils | ---
+++
@@ -39,3 +39,4 @@
register = Library()
register.filter(apply_markup)
+register.filter(smartypants) |
2b05a59b09e72f263761dae2feac360f5abd1f82 | promgen/__init__.py | promgen/__init__.py | default_app_config = 'promgen.apps.PromgenConfig'
import logging
logging.basicConfig(level=logging.DEBUG)
| default_app_config = 'promgen.apps.PromgenConfig'
| Remove some debug logging config | Remove some debug logging config
| Python | mit | kfdm/promgen,kfdm/promgen,kfdm/promgen,kfdm/promgen | ---
+++
@@ -1,3 +1 @@
default_app_config = 'promgen.apps.PromgenConfig'
-import logging
-logging.basicConfig(level=logging.DEBUG) |
30a836c9603ebb9289887a766e3c053a14c23c9f | archlinux/archpack_settings.py | archlinux/archpack_settings.py | #
# Biicode Arch Linux package settings.
#
# Check PKGBUILD_template docs for those settings and
# what they mean.
#
def settings():
return { "version": "2.6.1",
"release_number": "1",
"arch_deps": ["cmake>=3.0.2",
"zlib",
"glibc",
"sqlite",
... | #
# Biicode Arch Linux package settings.
#
# Check PKGBUILD_template docs for those settings and
# what they mean.
#
def settings():
return { "version": "2.7",
"release_number": "1",
"arch_deps": ["cmake>=3.0.2",
"zlib",
"glibc",
"sqlite",
... | Update Arch package to 2.7 | Update Arch package to 2.7
| Python | bsd-2-clause | biicode/packages,bowlofstew/packages,bowlofstew/packages,biicode/packages | ---
+++
@@ -6,7 +6,7 @@
#
def settings():
- return { "version": "2.6.1",
+ return { "version": "2.7",
"release_number": "1",
"arch_deps": ["cmake>=3.0.2",
"zlib", |
d4274336756ed6d6c36f94cbaae7e8328ac50f9a | djedi/auth/__init__.py | djedi/auth/__init__.py | def has_permission(request):
user = request.user
if user:
if user.is_superuser:
return True
if user.is_staff and user.groups.filter(name__iexact='djedi').exists():
return True
return False
def get_username(request):
user = request.user
if hasattr(user, 'ge... | import logging
_log = logging.getLogger(__name__)
def has_permission(request):
user = getattr(request, 'user', None)
if user:
if user.is_superuser:
return True
if user.is_staff and user.groups.filter(name__iexact='djedi').exists():
return True
else:
_log.w... | Handle wrong order of middleware. | Handle wrong order of middleware.
| Python | bsd-3-clause | andreif/djedi-cms,andreif/djedi-cms,andreif/djedi-cms,5monkeys/djedi-cms,5monkeys/djedi-cms,5monkeys/djedi-cms | ---
+++
@@ -1,11 +1,19 @@
+import logging
+
+_log = logging.getLogger(__name__)
+
+
def has_permission(request):
- user = request.user
+ user = getattr(request, 'user', None)
if user:
if user.is_superuser:
return True
if user.is_staff and user.groups.filter(name__iexact='d... |
2dfc3817881d9e90456dc3ea94b1fd0ec308fb5e | beavy/common/morphing_field.py | beavy/common/morphing_field.py | from marshmallow.fields import Field
class MorphingField(Field):
# registry = {
# }
def __init__(self, many=False, fallback=None, overwrite=None, **metadata):
self.many = False
self.fallback = fallback or self.FALLBACK
self.overwrite = overwrite
# Common alternative:
# d... | from marshmallow.fields import Field
class MorphingField(Field):
# registry = {
# }
def __init__(self, many=False, fallback=None, overwrite=None, **metadata):
self.many = False
self.fallback = fallback or self.FALLBACK
self.overwrite = overwrite
# Common alternative:
# d... | Fix MorphingField: polymorphic_identy is already the string we want | Fix MorphingField: polymorphic_identy is already the string we want
| Python | mpl-2.0 | beavyHQ/beavy,beavyHQ/beavy,beavyHQ/beavy,beavyHQ/beavy | ---
+++
@@ -16,7 +16,7 @@
# return obj.__class__.__name__
def _obj_to_name(self, obj):
- return obj.__mapper__.polymorphic_identity and obj.__mapper__.polymorphic_identity.__class__.__name__
+ return obj.__mapper__.polymorphic_identity
def _serialize(self, value, attr, obj):
... |
56b469eb2836d1fb6c2a7702b4693978512ecb51 | common/migrations/admin_unit_codes.py | common/migrations/admin_unit_codes.py | # -*- coding: utf-8 -*-
from django.db import models, migrations
from facilities.models import Facility
def set_min_code_value(apps, schema_editor):
from django.db import connection
cursor = connection.cursor()
sql = """
ALTER SEQUENCE common_constituency_code_seq restart 1000 start 1000 minvalue... | # -*- coding: utf-8 -*-
from django.db import models, migrations
from facilities.models import Facility
def set_min_code_value(apps, schema_editor):
from django.db import connection
cursor = connection.cursor()
sql = """
ALTER SEQUENCE common_constituency_code_seq restart 1000 start 1000 minvalue... | Fix wards code sequences restart | Fix wards code sequences restart
| Python | mit | MasterFacilityList/mfl_api,MasterFacilityList/mfl_api,MasterFacilityList/mfl_api,MasterFacilityList/mfl_api,MasterFacilityList/mfl_api | ---
+++
@@ -9,7 +9,7 @@
ALTER SEQUENCE common_constituency_code_seq restart 1000 start 1000 minvalue 1000;
ALTER SEQUENCE common_county_code_seq restart 1000 start 1000 minvalue 1000;
ALTER SEQUENCE common_subcounty_code_seq restart 1000 start 1000 minvalue 1000;
- ALTER SEQU... |
287c2da6d72155a4988665ac3c4031032dd835e3 | admin_tests/common_auth/test_logs.py | admin_tests/common_auth/test_logs.py | from nose import tools as nt
from tests.base import AdminTestCase
from osf.models.admin_log_entry import AdminLogEntry, update_admin_log
class TestUpdateAdminLog(AdminTestCase):
def test_add_log(self):
update_admin_log('123', 'dfqc2', 'This', 'log_added')
nt.assert_equal(AdminLogEntry.objects.co... | from nose import tools as nt
from tests.base import AdminTestCase
from osf_tests.factories import UserFactory
from osf.models.admin_log_entry import AdminLogEntry, update_admin_log
class TestUpdateAdminLog(AdminTestCase):
def test_add_log(self):
user = UserFactory()
update_admin_log(user.id, 'df... | Fix log test to use real user and id | Fix log test to use real user and id
| Python | apache-2.0 | sloria/osf.io,cwisecarver/osf.io,mattclark/osf.io,CenterForOpenScience/osf.io,pattisdr/osf.io,laurenrevere/osf.io,aaxelb/osf.io,TomBaxter/osf.io,binoculars/osf.io,chrisseto/osf.io,cslzchen/osf.io,adlius/osf.io,baylee-d/osf.io,caneruguz/osf.io,mfraezz/osf.io,brianjgeiger/osf.io,CenterForOpenScience/osf.io,caseyrollins/o... | ---
+++
@@ -2,12 +2,14 @@
from tests.base import AdminTestCase
+from osf_tests.factories import UserFactory
from osf.models.admin_log_entry import AdminLogEntry, update_admin_log
class TestUpdateAdminLog(AdminTestCase):
def test_add_log(self):
- update_admin_log('123', 'dfqc2', 'This', 'log_add... |
07fabcc0fa08d95ec5f17f5cbfcd0c14b645f31c | child_compassion/migrations/11.0.1.0.0/post-migration.py | child_compassion/migrations/11.0.1.0.0/post-migration.py | ##############################################################################
#
# Copyright (C) 2018 Compassion CH (http://www.compassion.ch)
# @author: Nathan Flückiger <nathan.fluckiger@hotmail.ch>
#
# The licence is in the file __manifest__.py
#
#############################################################... | ##############################################################################
#
# Copyright (C) 2018 Compassion CH (http://www.compassion.ch)
# @author: Nathan Flückiger <nathan.fluckiger@hotmail.ch>
#
# The licence is in the file __manifest__.py
#
#############################################################... | Add migration for assigning security groups | Add migration for assigning security groups
| Python | agpl-3.0 | CompassionCH/compassion-modules,CompassionCH/compassion-modules,CompassionCH/compassion-modules,CompassionCH/compassion-modules | ---
+++
@@ -17,3 +17,20 @@
return
load_mappings(env.cr, env)
+
+ # Add sponsorship group to everyone
+ sponsorship_group = env.ref('child_compassion.group_sponsorship')
+ env['res.users'].search([
+ ('internal', '=', True),
+ ('email', 'ilike', 'compassion.ch')
+ ]).write({
+... |
ffd8bb1e85fe7ed80d85062e4d5932f28065b84c | auditlog/apps.py | auditlog/apps.py | from django.apps import AppConfig
class AuditlogConfig(AppConfig):
name = "auditlog"
verbose_name = "Audit log"
| from django.apps import AppConfig
class AuditlogConfig(AppConfig):
name = "auditlog"
verbose_name = "Audit log"
default_auto_field = 'django.db.models.AutoField'
| Apply default_auto_field to app config. | Apply default_auto_field to app config.
| Python | mit | jjkester/django-auditlog | ---
+++
@@ -4,3 +4,4 @@
class AuditlogConfig(AppConfig):
name = "auditlog"
verbose_name = "Audit log"
+ default_auto_field = 'django.db.models.AutoField' |
f6072411bf097ae3d493f5c95d05f4711fdc5195 | Discord/cogs/python.py | Discord/cogs/python.py |
from discord.ext import commands
from utilities import checks
def setup(bot):
bot.add_cog(Python())
class Python(commands.Cog):
async def cog_check(self, ctx):
return await checks.not_forbidden().predicate(ctx)
@commands.command()
async def pep(self, ctx, number: int):
'''Generate Python Enhancement Pro... |
from discord.ext import commands
from utilities import checks
def setup(bot):
bot.add_cog(Python())
class Python(commands.Cog):
async def cog_check(self, ctx):
return await checks.not_forbidden().predicate(ctx)
@commands.command()
async def pep(self, ctx, number: int):
'''Generate Python Enhancement Pro... | Handle package not found in pypi command | [Discord] Handle package not found in pypi command
| Python | mit | Harmon758/Harmonbot,Harmon758/Harmonbot | ---
+++
@@ -21,6 +21,8 @@
'''Information about a package on PyPI'''
url = f"https://pypi.python.org/pypi/{package}/json"
async with ctx.bot.aiohttp_session.get(url) as resp:
+ if resp.status == 404:
+ return await ctx.embed_reply(f"{ctx.bot.error_emoji} Package not found")
data = await resp.json()
... |
2032de8bcf6ae6ed84a09ce3e294bae8fd86962a | dog/core/ext/health.py | dog/core/ext/health.py | """
Commands used to check the health of the bot.
"""
import datetime
from time import monotonic
from dog import Cog
from discord.ext import commands
class Health(Cog):
@commands.command()
async def ping(self, ctx):
""" Pong! """
# measure gateway delay
before = monotonic()
... | """
Commands used to check the health of the bot.
"""
import datetime
from time import monotonic
from dog import Cog
from discord.ext import commands
class Health(Cog):
@commands.command()
async def ping(self, ctx):
""" Pong! """
# measure gateway delay
before = monotonic()
... | Fix gateway lag being negative in d?ping | Fix gateway lag being negative in d?ping
| Python | mit | sliceofcode/dogbot,slice/dogbot,slice/dogbot,slice/dogbot,sliceofcode/dogbot | ---
+++
@@ -21,7 +21,7 @@
pong_ws = round(ctx.bot.latency * 1000, 2)
pong_rest = round((after - before) * 1000, 2)
- pong_gateway_lag = round((msg.created_at - datetime.datetime.utcnow()).total_seconds() * 1000, 2)
+ pong_gateway_lag = round((datetime.datetime.utcnow() - msg.created_... |
a0585269f05189fb9ae4f5abe98cd36731ad8a53 | babel_util/scripts/json_to_pajek.py | babel_util/scripts/json_to_pajek.py | #!/usr/bin/env python3
from util.misc import open_file, Benchmark
from util.PajekFactory import PajekFactory
import ujson
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Creates Pajek (.net) files from JSON")
parser.add_argument('outfile')
parser.add_argument('... | #!/usr/bin/env python3
from util.misc import open_file, Benchmark
from util.PajekFactory import PajekFactory
import ujson
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Creates Pajek (.net) files from JSON")
parser.add_argument('outfile')
parser.add_argument('... | Support for multiple subjects and filtering out non-wos ids | Support for multiple subjects and filtering out non-wos ids
| Python | agpl-3.0 | jevinw/rec_utilities,jevinw/rec_utilities | ---
+++
@@ -9,12 +9,17 @@
parser = argparse.ArgumentParser(description="Creates Pajek (.net) files from JSON")
parser.add_argument('outfile')
parser.add_argument('--temp-dir', help="Directory to store temporary files in", default=None)
- parser.add_argument('--subject', '-s', help="For WoS, subject ... |
5f001d818459a2bd5e9f6a89e8ed097d379a26d2 | runtime/__init__.py | runtime/__init__.py | import builtins
import operator
import functools
from ..compile import varary
builtins.__dict__.update({
# Runtime counterparts of some stuff in `Compiler.builtins`.
'$': lambda f, *xs: f(*xs)
, ':': lambda f, *xs: f(*xs)
, ',': lambda a, *xs: (a,) + xs
, '<': operator.lt
, '<=': operator.le
, '=... | import builtins
import operator
import functools
import importlib
from ..compile import varary
builtins.__dict__.update({
# Runtime counterparts of some stuff in `Compiler.builtins`.
'$': lambda f, *xs: f(*xs)
, ':': lambda f, *xs: f(*xs)
, ',': lambda a, *xs: (a,) + xs
, '<': operator.lt
, '<=': o... | Use importlib.import_module instead of __import__. | Use importlib.import_module instead of __import__.
| Python | mit | pyos/dg | ---
+++
@@ -1,6 +1,7 @@
import builtins
import operator
import functools
+import importlib
from ..compile import varary
@@ -37,7 +38,7 @@
, '>>': operator.rshift
# Useful stuff.
- , 'import': __import__
+ , 'import': importlib.import_module
, 'foldl': functools.reduce
, '~:': functools.parti... |
9a0ababb3b8b4b23184ab7005d995c17edef2a2b | src/test/test_imagesaveblock.py | src/test/test_imagesaveblock.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import unittest
import cv
import os, sys
cmd_folder, f = os.path.split(os.path.dirname(os.path.abspath(__file__)))
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)
import ipf.ipfblock.imagesave
class TestImageSaveBlock(unittest.TestCase):
def setUp(sel... | #!/usr/bin/python
# -*- coding: utf-8 -*-
import unittest
import cv
import os, sys
cmd_folder, f = os.path.split(os.path.dirname(os.path.abspath(__file__)))
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)
import ipf.ipfblock.imagesave
class TestImageSaveBlock(unittest.TestCase):
def setUp(sel... | Remove saved file in TestImageSaveBlock test case | Remove saved file in TestImageSaveBlock test case
| Python | lgpl-2.1 | anton-golubkov/Garland,anton-golubkov/Garland | ---
+++
@@ -27,6 +27,9 @@
self.block.process()
saved_image = cv.LoadImage("test_saved.png")
self.assertEqual(saved_image.tostring(), image.tostring())
+
+ def tearDown(self):
+ os.remove("test_saved.png")
if __name__ == '__main__': |
67a20401caaa63852e95fcaf8bafb6ed85ecd1f2 | test/selenium/src/lib/page/modal/__init__.py | test/selenium/src/lib/page/modal/__init__.py | # Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
from lib.page.modal import (
create_new_object, # flake8: noqa
edit_object, # flake8: noqa
delete_object # flake8: noqa
)
| # Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
from lib.page.modal import (
create_new_object, # flake8: noqa
edit_object, # flake8: noqa
delete_object, # flake8: noqa
update_object # flake8: noqa
)
| Add a sort of hierarchy of modules for package | Add a sort of hierarchy of modules for package
| Python | apache-2.0 | AleksNeStu/ggrc-core,VinnieJohns/ggrc-core,plamut/ggrc-core,plamut/ggrc-core,AleksNeStu/ggrc-core,VinnieJohns/ggrc-core,plamut/ggrc-core,VinnieJohns/ggrc-core,AleksNeStu/ggrc-core,plamut/ggrc-core,VinnieJohns/ggrc-core,AleksNeStu/ggrc-core | ---
+++
@@ -1,8 +1,10 @@
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
+
from lib.page.modal import (
create_new_object, # flake8: noqa
edit_object, # flake8: noqa
- delete_object # flake8: noqa
+ delete_object, # flake8: noqa
+... |
29d895b23e8a4656a82a9a39489c354b67b2b067 | bioagents/databases/chebi_client.py | bioagents/databases/chebi_client.py | import suds
import re
import logging
logger = logging.getLogger('suds')
logger.setLevel(logging.ERROR)
chebi_wsdl = 'http://www.ebi.ac.uk/webservices/chebi/2.0/webservice?wsdl'
chebi_client = suds.client.Client(chebi_wsdl)
def get_id(name, max_results=1):
# TODO: reimplement to get result from actual returned ob... | import suds
import re
import logging
logger = logging.getLogger('suds')
logger.setLevel(logging.ERROR)
chebi_wsdl = 'http://www.ebi.ac.uk/webservices/chebi/2.0/webservice?wsdl'
try:
chebi_client = suds.client.Client(chebi_wsdl)
except Exception as e:
logger.error('ChEBI web service is unavailable.')
chebi... | Handle webservice problems in ChEBI client | Handle webservice problems in ChEBI client
| Python | bsd-2-clause | bgyori/bioagents,sorgerlab/bioagents | ---
+++
@@ -6,11 +6,17 @@
logger.setLevel(logging.ERROR)
chebi_wsdl = 'http://www.ebi.ac.uk/webservices/chebi/2.0/webservice?wsdl'
-chebi_client = suds.client.Client(chebi_wsdl)
+try:
+ chebi_client = suds.client.Client(chebi_wsdl)
+except Exception as e:
+ logger.error('ChEBI web service is unavailable.')
... |
be0a9da80d46630d8958aa95838c5c7c67dda375 | blanc_basic_podcast/podcast/views.py | blanc_basic_podcast/podcast/views.py | from django.views.generic import ListView, DateDetailView
from .models import PodcastFile
class PodcastFileListView(ListView):
queryset = PodcastFile.objects.filter(published=True)
class PodcastFileDetailView(DateDetailView):
queryset = PodcastFile.objects.filter(published=True)
month_format = '%m'
... | from django.views.generic import ListView, DateDetailView
from django.utils import timezone
from django.conf import settings
from .models import PodcastFile
class PodcastFileListView(ListView):
paginate_by = getattr(settings, 'PODCAST_PER_PAGE', 10)
def get_queryset(self):
return PodcastFile.objects.... | Fix the list view for podcast files, and allow custom per page number in settings | Fix the list view for podcast files, and allow custom per page number in settings
| Python | bsd-2-clause | blancltd/blanc-basic-podcast | ---
+++
@@ -1,9 +1,15 @@
from django.views.generic import ListView, DateDetailView
+from django.utils import timezone
+from django.conf import settings
from .models import PodcastFile
class PodcastFileListView(ListView):
- queryset = PodcastFile.objects.filter(published=True)
+ paginate_by = getattr(sett... |
9334e8059cd74086278133345566c4b4591c81a4 | amgut/__init__.py | amgut/__init__.py | #!/usr/bin/env python
from __future__ import division
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The American Gut Project Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed ... | #!/usr/bin/env python
from __future__ import division
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The American Gut Project Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed ... | Add DB connection to amgut init module | Add DB connection to amgut init module
| Python | bsd-3-clause | biocore/american-gut-web,ElDeveloper/american-gut-web,PersonalGenomesOrg/american-gut-web,josenavas/american-gut-web,josenavas/american-gut-web,wasade/american-gut-web,mortonjt/american-gut-web,adamrp/american-gut-web,biocore/american-gut-web,adamrp/american-gut-web,mortonjt/american-gut-web,mortonjt/american-gut-web,s... | ---
+++
@@ -14,10 +14,13 @@
from amgut.lib.config_manager import AMGUT_CONFIG
from amgut.lib.locale_data import media_locale
from redis import Redis
+from amgut.lib.data_access.sql_connection import SQLConnectionHandler
r_server = Redis(host=AMGUT_CONFIG.redis_host,
port=AMGUT_CONFIG.redis_por... |
d28e884d832b63bef1434476a378de9b7e333264 | samples/WavGenerator.py | samples/WavGenerator.py | #############
# ECE 612 Spring 2017
# Joe Parrish
#
# Use the same logic from SpectrumTester.py to generate multiple sine waves
# but write that output to a .wav file for file based testing of the project code
#############
import wave
import numpy as np
def generate_sample_file(test_freqs, test_amps, chunk=4096, sa... | #############
# ECE 612 Spring 2017
# Joe Parrish
#
# Use the same logic from SpectrumTester.py to generate multiple sine waves
# but write that output to a .wav file for file based testing of the project code
#############
import wave
import argparse
import numpy as np
def generate_sample_file(test_freqs, test_amps... | Add a main function with command line arguments | Add a main function with command line arguments
Now able to generate wave files from command line | Python | mit | parrisha/raspi-visualizer | ---
+++
@@ -7,16 +7,17 @@
#############
import wave
+import argparse
import numpy as np
def generate_sample_file(test_freqs, test_amps, chunk=4096, samplerate=44100):
-
- filename = 'Sample_'
+
+ filename = 'Sample'
x = np.arange(chunk)
y = np.zeros(chunk)
for test_freq,test_amp in zip(te... |
ee6ad550ebeeaebf7c0959932ec60cbd923d480e | plowshare/__init__.py | plowshare/__init__.py | from .plowshare import *
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
# The MIT License (MIT)
#
# Copyright (c) 2014 Storj Labs
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including witho... | Add proper header and fix import. | Add proper header and fix import.
| Python | mit | Storj/plowshare-wrapper | ---
+++
@@ -1 +1,26 @@
-from .plowshare import *
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+# The MIT License (MIT)
+#
+# Copyright (c) 2014 Storj Labs
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to... |
643c8896b23cc1d008ce1e2a278d4379fb3b9b08 | byceps/services/language/dbmodels.py | byceps/services/language/dbmodels.py | """
byceps.services.language.dbmodels
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2014-2022 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from ...database import db
class Language(db.Model):
"""A language.
The code can be just `en` or `de`, but also `en-gb` or `de-de`.
... | """
byceps.services.language.dbmodels
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2014-2022 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from ...database import db
class Language(db.Model):
"""A language.
The code can be just `en` or `de`, but also `en-gb` or `de-de`.
... | Fix name of languages table | Fix name of languages table
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps | ---
+++
@@ -15,7 +15,7 @@
The code can be just `en` or `de`, but also `en-gb` or `de-de`.
"""
- __tablename__ = 'locales'
+ __tablename__ = 'languages'
code = db.Column(db.UnicodeText, primary_key=True)
|
c5e5b3d6c3d8cad75b1d2eac16179872dd415eb9 | scripts/asgard-deploy.py | scripts/asgard-deploy.py | #!/usr/bin/env python
import sys
import logging
import click
import tubular.asgard as asgard
logging.basicConfig(stream=sys.stdout, level=logging.ERROR)
@click.command()
@click.option('--ami_id', help='The ami-id to deploy', required=True)
def deploy(ami_id):
try:
asgard.deploy(ami_id)
except Exceptio... | #!/usr/bin/env python
import sys
import logging
import click
import tubular.asgard as asgard
logging.basicConfig(stream=sys.stdout, level=logging.ERROR)
@click.command()
@click.option('--ami_id', envvar='AMI_ID', help='The ami-id to deploy', required=True)
def deploy(ami_id):
try:
asgard.deploy(ami_id)
... | Use environment var for AMI_ID. | Use environment var for AMI_ID.
| Python | agpl-3.0 | eltoncarr/tubular,eltoncarr/tubular | ---
+++
@@ -7,7 +7,7 @@
logging.basicConfig(stream=sys.stdout, level=logging.ERROR)
@click.command()
-@click.option('--ami_id', help='The ami-id to deploy', required=True)
+@click.option('--ami_id', envvar='AMI_ID', help='The ami-id to deploy', required=True)
def deploy(ami_id):
try:
asgard.deploy(... |
51a126c0ada7c00a99416b241bb1c11888e82836 | esmgrids/jra55_grid.py | esmgrids/jra55_grid.py |
import numpy as np
import netCDF4 as nc
from .base_grid import BaseGrid
class Jra55Grid(BaseGrid):
def __init__(self, h_grid_def, description='JRA55 regular grid'):
self.type = 'Arakawa A'
self.full_name = 'JRA55'
with nc.Dataset(h_grid_def) as f:
x_t = f.variables['lon'][:]... |
import numpy as np
import netCDF4 as nc
from .base_grid import BaseGrid
class Jra55Grid(BaseGrid):
def __init__(self, h_grid_def, description='JRA55 regular grid'):
self.type = 'Arakawa A'
self.full_name = 'JRA55'
with nc.Dataset(h_grid_def) as f:
lon_bnds = f.variables['lon... | Use bounds to determing jra55 grid cell locations. | Use bounds to determing jra55 grid cell locations.
| Python | apache-2.0 | DoublePrecision/esmgrids | ---
+++
@@ -11,8 +11,12 @@
self.full_name = 'JRA55'
with nc.Dataset(h_grid_def) as f:
- x_t = f.variables['lon'][:]
- y_t = f.variables['lat'][1:-1]
+ lon_bnds = f.variables['lon_bnds'][:]
+ lat_bnds = f.variables['lat_bnds'][:]
+ dx_t = lon_... |
6251bffd124e3ab960f6150ef66585a3653ef4cf | argus/backends/base.py | argus/backends/base.py | import abc
import six
@six.add_metaclass(abc.ABCMeta)
class BaseBackend(object):
@abc.abstractmethod
def setup_instance(self):
"""Called by setUpClass to setup an instance"""
@abc.abstractmethod
def cleanup(self):
"""Needs to cleanup the resources created in ``setup_instance``"""
| # Copyright 2015 Cloudbase Solutions Srl
# 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 r... | Add the license header where it's missing. | Add the license header where it's missing.
| Python | apache-2.0 | micumatei/cloudbase-init-ci,stefan-caraiman/cloudbase-init-ci,AlexandruTudose/cloudbase-init-ci,PCManticore/argus-ci,cloudbase/cloudbase-init-ci,cmin764/argus-ci | ---
+++
@@ -1,3 +1,18 @@
+# Copyright 2015 Cloudbase Solutions Srl
+# 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/l... |
32432291eea4b3b6d6ac3cf597102740ae83df28 | d_parser/helpers/re_set.py | d_parser/helpers/re_set.py | # re_set.py
# Module for generating regex rules
# r1
import re
class Ree:
float = None
number = None
page_number = None
extract_int = None
@staticmethod
def init():
Ree.is_float()
Ree.is_number()
Ree.is_page_number('')
Ree.extract_int_compile()
@staticme... | # re_set.py
# Module for generating regex rules
# r1
import re
class Ree:
float = None
number = None
page_number = None
extract_int = None
@staticmethod
def init():
Ree.is_float()
Ree.is_number()
Ree.is_page_number('')
Ree.extract_int_compile()
@staticme... | Fix int extractor (greedy > lazy) | Fix int extractor (greedy > lazy)
| Python | mit | Holovin/D_GrabDemo | ---
+++
@@ -33,4 +33,4 @@
@staticmethod
def extract_int_compile():
- Ree.extract_int = re.compile('^.+(?P<int>\d+).+$')
+ Ree.extract_int = re.compile('^.*?(?P<int>\d+).+$') |
3ce0db9cccea34998674e340c1dcc7f49b487e9a | TweetPoster/twitter.py | TweetPoster/twitter.py | from requests_oauthlib import OAuth1
from TweetPoster import User, config
class Twitter(User):
def __init__(self, *a, **kw):
super(Twitter, self).__init__(*a, **kw)
self.session.auth = OAuth1(
config['twitter']['consumer_key'],
config['twitter']['consumer_secret'],
... | from datetime import datetime
from requests_oauthlib import OAuth1
from TweetPoster import User, config
class Twitter(User):
def __init__(self, *a, **kw):
super(Twitter, self).__init__(*a, **kw)
self.session.auth = OAuth1(
config['twitter']['consumer_key'],
config['twit... | Convert JSON into Tweet and TwitterUser objects | Convert JSON into Tweet and TwitterUser objects
| Python | mit | joealcorn/TweetPoster,tytek2012/TweetPoster,r3m0t/TweetPoster,aperson/TweetPoster | ---
+++
@@ -1,3 +1,5 @@
+from datetime import datetime
+
from requests_oauthlib import OAuth1
from TweetPoster import User, config
@@ -26,4 +28,24 @@
r = self.get(url, params=params)
assert r.status_code == 200, r.status_code
- return r.json()
+ return Tweet(r.json())
+
+
+class ... |
cb29f8522c4e90b7db82bac408bc16bd2f1d53da | cs251tk/common/run.py | cs251tk/common/run.py | import shlex
import copy
import os
from subprocess import STDOUT, run as _run, CalledProcessError, TimeoutExpired
# This env stuff is to catch glibc errors, because
# it apparently prints to /dev/tty instead of stderr.
# (see http://stackoverflow.com/a/27797579)
ENV = copy.copy(os.environ)
ENV["LIBC_FATAL_STDERR_"] =... | import copy
import os
from subprocess import STDOUT, run as _run, CalledProcessError, TimeoutExpired
# This env stuff is to catch glibc errors, because
# it apparently prints to /dev/tty instead of stderr.
# (see http://stackoverflow.com/a/27797579)
ENV = copy.copy(os.environ)
ENV["LIBC_FATAL_STDERR_"] = "1"
def ru... | Revert "revert part of 27cd680" | Revert "revert part of 27cd680"
c491bbc2302ac7c95c180d31845c643804fa30d3
| Python | mit | StoDevX/cs251-toolkit,StoDevX/cs251-toolkit,StoDevX/cs251-toolkit,StoDevX/cs251-toolkit | ---
+++
@@ -1,4 +1,3 @@
-import shlex
import copy
import os
from subprocess import STDOUT, run as _run, CalledProcessError, TimeoutExpired
@@ -12,11 +11,6 @@
def run(cmd, input_data=None, timeout=None):
- # Stringified commands are passed in from the spec files.
- # Otherwise, it needs to be an array.
-... |
b836a7347d66e6fb8df2f97c011b875e24c91e17 | dashboard/consumers.py | dashboard/consumers.py | from channels.auth import channel_session_user, channel_session_user_from_http
@channel_session_user_from_http
def ws_connect(message):
message.reply_channel.send({
'accept': True
})
| from channels import Group
from channels.auth import channel_session_user, channel_session_user_from_http
@channel_session_user_from_http
def ws_connect(message):
Group('btc-price').add(message.reply_channel)
message.reply_channel.send({
'accept': True
})
| Add user to the group when he first connects | Add user to the group when he first connects
| Python | mit | alessandroHenrique/coinpricemonitor,alessandroHenrique/coinpricemonitor,alessandroHenrique/coinpricemonitor | ---
+++
@@ -1,8 +1,12 @@
+from channels import Group
from channels.auth import channel_session_user, channel_session_user_from_http
@channel_session_user_from_http
def ws_connect(message):
+
+ Group('btc-price').add(message.reply_channel)
+
message.reply_channel.send({
'accept': True
}) |
aeaf802100cd6869178dd9f412d35e452916a63d | common/commands/view_manipulation.py | common/commands/view_manipulation.py | from sublime_plugin import TextCommand
from ...core.git_command import GitCommand
__all__ = (
"gs_handle_vintageous",
"gs_handle_arrow_keys"
)
class gs_handle_vintageous(TextCommand, GitCommand):
"""
Set the vintageous_friendly view setting if needed.
Enter insert mode if vintageous_enter_inser... | from sublime_plugin import TextCommand
from ...core.git_command import GitCommand
__all__ = (
"gs_handle_vintageous",
"gs_handle_arrow_keys"
)
class gs_handle_vintageous(TextCommand, GitCommand):
"""
Set the vintageous_friendly view setting if needed.
Enter insert mode if vintageous_enter_inser... | Fix `vintageous_enter_insert_mode` for NeoVintageous 1.22.0 | Fix `vintageous_enter_insert_mode` for NeoVintageous 1.22.0
Fixes #1395
In NeoVintageous/NeoVintageous#749, pushed as 1.22.0 (Oct 2020), the
relevant commands were renamed.
We follow the new names, but for now also call the old ones.
| Python | mit | divmain/GitSavvy,divmain/GitSavvy,divmain/GitSavvy | ---
+++
@@ -20,7 +20,10 @@
self.view.settings().set("git_savvy.vintageous_friendly", True)
if self.savvy_settings.get("vintageous_enter_insert_mode"):
self.view.settings().set("vintageous_reset_mode_when_switching_tabs", False)
+ # NeoVintageous renamed the co... |
a55b96a7d64643af6d2adcd6a15fe3348c5d1c41 | dbaas/workflow/settings.py | dbaas/workflow/settings.py | DEPLOY_MYSQL_WORKFLOW = (
'util.gen_names',
'util.gen_dbinfra',
'dbaas_cloudstack.create_vm'
)
DEPLOY_VIRTUALMACHINE = (
'workflow.steps.build_databaseinfra.BuildDatabaseInfra',
'workflow.steps.create_virtualmachines.CreateVirtualMachine',
)
DEPLOY_MONGO_WORKFLOW = (
'util.gen_names... | DEPLOY_MYSQL_WORKFLOW = (
'util.gen_names',
'util.gen_dbinfra',
'dbaas_cloudstack.create_vm'
)
DEPLOY_VIRTUALMACHINE = (
'workflow.steps.build_databaseinfra.BuildDatabaseInfra',
'workflow.steps.create_virtualmachines.CreateVirtualMachine',
'workflow.steps.create_dns.CreateDns'
... | Add create dns on main workflow | Add create dns on main workflow
| Python | bsd-3-clause | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service | ---
+++
@@ -7,6 +7,7 @@
DEPLOY_VIRTUALMACHINE = (
'workflow.steps.build_databaseinfra.BuildDatabaseInfra',
'workflow.steps.create_virtualmachines.CreateVirtualMachine',
+ 'workflow.steps.create_dns.CreateDns'
) |
6e9a19d362005125036f5c0ecdbe88fc1c4f01aa | product_computed_list_price/__init__.py | product_computed_list_price/__init__.py | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from . import product | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from . import product
from . import pricelist
| FIX price type 'list_price' inactivation | FIX price type 'list_price' inactivation
| Python | agpl-3.0 | ingadhoc/product,ingadhoc/product | ---
+++
@@ -4,3 +4,4 @@
# directory
##############################################################################
from . import product
+from . import pricelist |
f2ea241e9bb6e5e927a90c56438bf7883ae3744f | siemstress/__init__.py | siemstress/__init__.py | __version__ = '0.2'
__author__ = 'Dan Persons <dpersonsdev@gmail.com>'
__license__ = 'MIT License'
__github__ = 'https://github.com/dogoncouch/siemstress'
__all__ = ['core', 'querycore', 'query']
import siemstress.query
| __version__ = '0.2'
__author__ = 'Dan Persons <dpersonsdev@gmail.com>'
__license__ = 'MIT License'
__github__ = 'https://github.com/dogoncouch/siemstress'
__all__ = ['core', 'querycore', 'query']
import siemstress.query
import siemstress.trigger
| Add trigger to module import | Add trigger to module import
| Python | mit | dogoncouch/siemstress | ---
+++
@@ -5,3 +5,4 @@
__all__ = ['core', 'querycore', 'query']
import siemstress.query
+import siemstress.trigger |
3b0608e11da620f1e12aeb270dbaf2f255a35cec | Cura/Qt/Bindings/ControllerProxy.py | Cura/Qt/Bindings/ControllerProxy.py | from PyQt5.QtCore import QObject, QCoreApplication, pyqtSlot, QUrl
from Cura.Application import Application
from Cura.Scene.SceneNode import SceneNode
class ControllerProxy(QObject):
def __init__(self, parent = None):
super().__init__(parent)
self._controller = Application.getInstance().getControl... | from PyQt5.QtCore import QObject, QCoreApplication, pyqtSlot, QUrl
from Cura.Application import Application
from Cura.Scene.SceneNode import SceneNode
from Cura.Scene.BoxRenderer import BoxRenderer
class ControllerProxy(QObject):
def __init__(self, parent = None):
super().__init__(parent)
self._co... | Add a (temporary) bounding box around an added mesh | Add a (temporary) bounding box around an added mesh
| Python | agpl-3.0 | onitake/Uranium,onitake/Uranium | ---
+++
@@ -2,6 +2,7 @@
from Cura.Application import Application
from Cura.Scene.SceneNode import SceneNode
+from Cura.Scene.BoxRenderer import BoxRenderer
class ControllerProxy(QObject):
def __init__(self, parent = None):
@@ -24,3 +25,4 @@
mesh = SceneNode(self._controller.getScene().getRoot())
... |
e82ab299a6c68f682a9f9b769e79cf2054684e3b | reviewboard/attachments/evolutions/file_attachment_uuid.py | reviewboard/attachments/evolutions/file_attachment_uuid.py | from __future__ import unicode_literals
from django_evolution.mutations import AddField
from django.db import models
MUTATIONS = [
AddField('FileAttachment', 'uuid', models.CharField, max_length=255,
initial=None, null=True),
]
| from __future__ import unicode_literals
from django_evolution.mutations import AddField
from django.db import models
MUTATIONS = [
AddField('FileAttachment', 'uuid', models.CharField, max_length=255,
initial=''),
]
| Fix the FileAttachment.uuid evolution to match the model field. | Fix the FileAttachment.uuid evolution to match the model field.
The evolution that was included in the existing code didn't match the
definition of the field. This is a very simple fix.
Testing done:
Ran evolutions.
Reviewed at https://reviews.reviewboard.org/r/8141/
| Python | mit | davidt/reviewboard,davidt/reviewboard,reviewboard/reviewboard,chipx86/reviewboard,sgallagher/reviewboard,brennie/reviewboard,reviewboard/reviewboard,brennie/reviewboard,sgallagher/reviewboard,chipx86/reviewboard,brennie/reviewboard,chipx86/reviewboard,reviewboard/reviewboard,davidt/reviewboard,chipx86/reviewboard,sgall... | ---
+++
@@ -6,5 +6,5 @@
MUTATIONS = [
AddField('FileAttachment', 'uuid', models.CharField, max_length=255,
- initial=None, null=True),
+ initial=''),
] |
3e33849ded2c69760ce93b4b1e9ab8094904040f | space-age/space_age.py | space-age/space_age.py | class SpaceAge(object):
def __init__(self, seconds):
self.seconds = seconds
@property
def years(self):
return self.seconds/31557600
def on_earth(self):
return round(self.years, 2)
def on_mercury(self):
return round(self.years/0.2408467, 2)
def on_venus(self):
... | class SpaceAge(object):
YEARS = {"on_earth": 1,
"on_mercury": 0.2408467,
"on_venus": 0.61519726,
"on_mars": 1.8808158,
"on_jupiter": 11.862615,
"on_saturn": 29.447498,
"on_uranus": 84.016846,
"on_neptune": 164.79132}
def... | Implement __getattr__ to reduce code | Implement __getattr__ to reduce code
| Python | agpl-3.0 | CubicComet/exercism-python-solutions | ---
+++
@@ -1,4 +1,13 @@
class SpaceAge(object):
+ YEARS = {"on_earth": 1,
+ "on_mercury": 0.2408467,
+ "on_venus": 0.61519726,
+ "on_mars": 1.8808158,
+ "on_jupiter": 11.862615,
+ "on_saturn": 29.447498,
+ "on_uranus": 84.016846,
+ ... |
486d3ab08858c2a872732f0efd82fe2fb0054366 | relay_api/api/main.py | relay_api/api/main.py | from flask import Flask
import relay_api.api.backend as backend
server = Flask(__name__)
backend.init_relays()
@server.route("/relay-api/relays/", methods=["GET"])
def get_all_relays():
js = backend.get_all_relays()
return js, 200
@server.route("/relay-api/relays/<relay_name>", methods=["GET"])
def get_r... | from flask import Flask
import relay_api.api.backend as backend
server = Flask(__name__)
backend.init_relays()
@server.route("/relay-api/relays/", methods=["GET"])
def get_all_relays():
js = backend.get_all_relays()
return js, 200
@server.route("/relay-api/relays/<relay_name>", methods=["GET"])
def get_r... | Change the new endpoint function name | Change the new endpoint function name
| Python | mit | pahumadad/raspi-relay-api | ---
+++
@@ -22,7 +22,7 @@
@server.route("/relay-api/relays/<relay_name>/on", methods=["PUT"])
-def get_relay(relay_name):
+def set_relay_on(relay_name):
js = backend.set_relay_on(relay_name)
if not js:
return "", 404 |
15a5e6c1aca706330147475984848dfc33fd1a9d | common/djangoapps/mitxmako/tests.py | common/djangoapps/mitxmako/tests.py | from django.test import TestCase
from django.test.utils import override_settings
from django.core.urlresolvers import reverse
from django.conf import settings
from mitxmako.shortcuts import marketing_link
from mock import patch
class ShortcutsTests(TestCase):
"""
Test the mitxmako shortcuts file
"""
... | from django.test import TestCase
from django.test.utils import override_settings
from django.core.urlresolvers import reverse
from django.conf import settings
from mitxmako.shortcuts import marketing_link
from mock import patch
class ShortcutsTests(TestCase):
"""
Test the mitxmako shortcuts file
"""
... | Fix test so that it works with both CMS and LMS settings | Fix test so that it works with both CMS and LMS settings
| Python | agpl-3.0 | nanolearningllc/edx-platform-cypress,jjmiranda/edx-platform,SivilTaram/edx-platform,olexiim/edx-platform,eduNEXT/edx-platform,bdero/edx-platform,olexiim/edx-platform,nanolearningllc/edx-platform-cypress-2,cyanna/edx-platform,rismalrv/edx-platform,don-github/edx-platform,unicri/edx-platform,xuxiao19910803/edx-platform,U... | ---
+++
@@ -12,7 +12,7 @@
"""
@override_settings(MKTG_URLS={'ROOT': 'dummy-root', 'ABOUT': '/about-us'})
- @override_settings(MKTG_URL_LINK_MAP={'ABOUT': 'about_edx'})
+ @override_settings(MKTG_URL_LINK_MAP={'ABOUT': 'login'})
def test_marketing_link(self):
# test marketing site on
... |
0c24bb0a422a816b4e6909e458bb1bbbfed61720 | fluent_contents/plugins/oembeditem/__init__.py | fluent_contents/plugins/oembeditem/__init__.py | VERSION = (0, 1, 0)
# Do some version checking
try:
import micawber
except ImportError:
raise ImportError("The 'micawber' package is required to use the 'oembeditem' plugin.")
| Add check for `micawber` existance in `oembeditem` plugin. | Add check for `micawber` existance in `oembeditem` plugin.
| Python | apache-2.0 | edoburu/django-fluent-contents,ixc/django-fluent-contents,django-fluent/django-fluent-contents,pombredanne/django-fluent-contents,django-fluent/django-fluent-contents,jpotterm/django-fluent-contents,edoburu/django-fluent-contents,pombredanne/django-fluent-contents,edoburu/django-fluent-contents,django-fluent/django-flu... | ---
+++
@@ -0,0 +1,7 @@
+VERSION = (0, 1, 0)
+
+# Do some version checking
+try:
+ import micawber
+except ImportError:
+ raise ImportError("The 'micawber' package is required to use the 'oembeditem' plugin.") | |
6690479e46c9138c6f57ce9415b0429175545e96 | stock_transfer_restrict_lot/models/stock_production_lot.py | stock_transfer_restrict_lot/models/stock_production_lot.py | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from openerp import models, fields, api
class St... | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from openerp import models, fields, api
class St... | FIX in lot name_get to show location with the stock | FIX in lot name_get to show location with the stock
| Python | agpl-3.0 | ingadhoc/stock | ---
+++
@@ -27,6 +27,11 @@
def name_get(self):
result = []
for rec in self:
- name = '%s (%s u)' % (rec.name, rec.qty_available_not_res or 0.0)
+ read = rec.quant_ids.read_group(
+ [('lot_id', '=', rec.id)],
+ ['location_id', 'qty'], 'location... |
a02791231dcc5ecd5bebbb698719e47bd01c68ed | src/__init__.py | src/__init__.py | # -*- coding: utf-8 -*-
# Copyright (c) 2015-2016 MIT Probabilistic Computing Project
# 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
# Unles... | # -*- coding: utf-8 -*-
# Copyright (c) 2015-2016 MIT Probabilistic Computing Project
# 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
# Unles... | Revert "Expose __version__ from the top level cgpm module." | Revert "Expose __version__ from the top level cgpm module."
This reverts commit 3b94d4111ea00ff15cf0566392861124fc31b430.
Shouldn't've jumped the gun like that, I guess. Apparently this
doesn't work and it's not clear to me why.
| Python | apache-2.0 | probcomp/cgpm,probcomp/cgpm | ---
+++
@@ -13,5 +13,3 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-
-from cgpm.version import __version__ |
8207d86b7b2a6e1f81454eefea4784d89c8674a8 | resolver_test/django_test.py | resolver_test/django_test.py | # Copyright (c) 2011 Resolver Systems Ltd.
# All Rights Reserved
#
from urlparse import urljoin
from mock import Mock
from resolver_test import ResolverTestMixins
import django
from django.conf import settings
from django.contrib.auth.models import AnonymousUser, User
from django.http import HttpRequest
class R... | # Copyright (c) 2017 PythonAnywhere LLP.
# All Rights Reserved
#
from urlparse import urljoin
from mock import Mock
from resolver_test import ResolverTestMixins
import django
from django.conf import settings
from django.contrib.auth.models import AnonymousUser, User
from django.http import HttpRequest
class Res... | Use different usernames for each test. by: Glenn, Giles | Use different usernames for each test. by: Glenn, Giles
| Python | mit | pythonanywhere/resolver_test | ---
+++
@@ -1,4 +1,4 @@
-# Copyright (c) 2011 Resolver Systems Ltd.
+# Copyright (c) 2017 PythonAnywhere LLP.
# All Rights Reserved
#
@@ -20,11 +20,15 @@
maxDiff = None
+
+usernumber = 0
+
class ResolverViewTestCase(ResolverDjangoTestCase):
def setUp(self):
- self.user = User(username='che... |
50cc2ba3353cdd27513999465e854d01823605a4 | angr/knowledge_base.py | angr/knowledge_base.py | """Representing the artifacts of a project."""
from .knowledge_plugins.plugin import default_plugins
class KnowledgeBase(object):
"""Represents a "model" of knowledge about an artifact.
Contains things like a CFG, data references, etc.
"""
def __init__(self, project, obj):
self._project = pr... | """Representing the artifacts of a project."""
from .knowledge_plugins.plugin import default_plugins
class KnowledgeBase(object):
"""Represents a "model" of knowledge about an artifact.
Contains things like a CFG, data references, etc.
"""
def __init__(self, project, obj):
self._project = pr... | Fix the recursion bug in KnowledgeBase after the previous refactor. | Fix the recursion bug in KnowledgeBase after the previous refactor.
| Python | bsd-2-clause | f-prettyland/angr,axt/angr,tyb0807/angr,iamahuman/angr,angr/angr,angr/angr,axt/angr,angr/angr,chubbymaggie/angr,schieb/angr,chubbymaggie/angr,f-prettyland/angr,iamahuman/angr,f-prettyland/angr,tyb0807/angr,iamahuman/angr,axt/angr,schieb/angr,chubbymaggie/angr,schieb/angr,tyb0807/angr | ---
+++
@@ -24,6 +24,19 @@
@property
def resolved_indirect_jumps(self):
return self.indirect_jumps.resolved
+
+ def __setstate__(self, state):
+ self._project = state['project']
+ self.obj = state['obj']
+ self._plugins = state['plugins']
+
+ def __getstate__(self):
+ ... |
22eda7c2b844c9dccb31ad9cce882cc13d1adf75 | apel_rest/urls.py | apel_rest/urls.py | """This file maps url patterns to classes."""
from django.conf.urls import patterns, include, url
from django.contrib import admin
from api.views.CloudRecordSummaryView import CloudRecordSummaryView
from api.views.CloudRecordView import CloudRecordView
admin.autodiscover()
urlpatterns = patterns('',
... | """This file maps url patterns to classes."""
from django.conf.urls import patterns, include, url
from django.contrib import admin
from api.views.CloudRecordSummaryView import CloudRecordSummaryView
from api.views.CloudRecordView import CloudRecordView
admin.autodiscover()
urlpatterns = patterns('',
... | Add name to patterns in urlpatterns | Add name to patterns in urlpatterns
- so tests can use reverse()
| Python | apache-2.0 | apel/rest,apel/rest | ---
+++
@@ -13,8 +13,12 @@
# url(r'^blog/', include('blog.urls')),
url(r'^admin/',
- include(admin.site.urls)),
+ include(admin.site.urls,)),
+
url(r'^api/v1/cloud/record$',
- ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.