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 |
|---|---|---|---|---|---|---|---|---|---|---|
bfcce626990c53aef7fbe534f1f6ff1092945597 | docs/settings.py | docs/settings.py | DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'test.db',
}
}
USE_TZ = False
SITE_ID = 1
STATIC_URL = '/static/'
SECRET_KEY = 'NOT_SO_SECRET'
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.c... | DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'test.db',
}
}
USE_TZ = False
SITE_ID = 1
STATIC_URL = '/static/'
SECRET_KEY = 'NOT_SO_SECRET'
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.c... | Fix read the docs failure | Fix read the docs failure
| Python | bsd-3-clause | consbio/tablo | ---
+++
@@ -22,5 +22,5 @@
'django.contrib.staticfiles',
'tastypie',
'tablo',
- 'django_extensions'
+ # 'django_extensions'
) |
7f0ab829f677a5d91d5b24dc6181a2519e25a934 | notes/managers.py | notes/managers.py | #
# Copyright (c) 2009 Brad Taylor <brad@getcoded.net>
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This... | #
# Copyright (c) 2009 Brad Taylor <brad@getcoded.net>
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This... | Support hiding note and notebook template notes | Support hiding note and notebook template notes
| Python | agpl-3.0 | syskill/snowy,NoUsername/PrivateNotesExperimental,GNOME/snowy,jaredjennings/snowy,jaredjennings/snowy,sandyarmstrong/snowy,jaredjennings/snowy,NoUsername/PrivateNotesExperimental,widox/snowy,syskill/snowy,leonhandreke/snowy,leonhandreke/snowy,jaredjennings/snowy,widox/snowy,GNOME/snowy,sandyarmstrong/snowy | ---
+++
@@ -18,9 +18,11 @@
from django.db import models
class NoteManager(models.Manager):
- def user_viewable(self, request_user, author):
+ def user_viewable(self, request_user, author, templates=False):
notes = self.filter(author=author)
if request_user != author:
# Public ... |
cd5c56583c84b2b0fd05d743578193b7b681151c | nn/embedding/embeddings.py | nn/embedding/embeddings.py | import tensorflow as tf
from ..flags import FLAGS
from ..variable import variable
def embeddings(*, id_space_size, embedding_size, name=None):
return variable([id_space_size, embedding_size], name=name)
def word_embeddings(name="word_embeddings"):
if FLAGS.word_embeddings is None:
return embeddings(id_spa... | import tensorflow as tf
from ..flags import FLAGS
from ..variable import variable
from ..util import func_scope
@func_scope()
def embeddings(*, id_space_size, embedding_size, name=None):
return variable([id_space_size, embedding_size], name=name)
@func_scope()
def word_embeddings(name="word_embeddings"):
if F... | Add func_scope to embedding functions | Add func_scope to embedding functions
| Python | unlicense | raviqqe/tensorflow-extenteten,raviqqe/tensorflow-extenteten | ---
+++
@@ -2,13 +2,16 @@
from ..flags import FLAGS
from ..variable import variable
+from ..util import func_scope
+@func_scope()
def embeddings(*, id_space_size, embedding_size, name=None):
return variable([id_space_size, embedding_size], name=name)
+@func_scope()
def word_embeddings(name="word_em... |
fa418ed5a6769a369d4b5cddfc6e215f551c57cf | events/cms_app.py | events/cms_app.py | from cms.app_base import CMSApp
from cms.apphook_pool import apphook_pool
from django.utils.translation import ugettext_lazy as _
class EventsApphook(CMSApp):
name = _("Events Apphook")
urls = ["events.urls"]
app_name = "events"
apphook_pool.register(EventsApphook)
| from cms.app_base import CMSApp
from cms.apphook_pool import apphook_pool
from django.utils.translation import ugettext_lazy as _
class EventsApphook(CMSApp):
name = _("Events Apphook")
urls = ["events.urls"]
app_name = "events"
namespace = "events"
apphook_pool.register(EventsApphook)
| Add namespace to support djangoCMS v3 | Add namespace to support djangoCMS v3
| Python | bsd-3-clause | theherk/django-theherk-events | ---
+++
@@ -7,5 +7,6 @@
name = _("Events Apphook")
urls = ["events.urls"]
app_name = "events"
+ namespace = "events"
apphook_pool.register(EventsApphook) |
2c742cd00e21412d034bb0cffed0bafca2e6c1ae | inspector/inspector/urls.py | inspector/inspector/urls.py | from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic import TemplateView
from cbv.views import KlassDetailView
# Uncomment the next two lines to enab... | from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic import TemplateView
from cbv.views import KlassDetailView
# Uncomment the next two lines to enab... | Allow dots in module names. | Allow dots in module names.
| Python | bsd-2-clause | refreshoxford/django-cbv-inspector,refreshoxford/django-cbv-inspector,refreshoxford/django-cbv-inspector,abhijo89/django-cbv-inspector,refreshoxford/django-cbv-inspector,abhijo89/django-cbv-inspector,abhijo89/django-cbv-inspector,abhijo89/django-cbv-inspector | ---
+++
@@ -13,7 +13,7 @@
urlpatterns = patterns('',
url(r'^$', TemplateView.as_view(template_name='base.html'), name='home'),
url(r'^admin/', include(admin.site.urls)),
- url(r'class/(?P<package>[a-zA-Z_-]+)/(?P<version>[^/]+)/(?P<module>[A-Za-z_-]+)/(?P<klass>[A-Za-z_-]*)', KlassDetailView.as_view()),
+ ... |
c0b3a482b8ef5284070da1398350acf936e50121 | rplugin/python3/deoplete/sources/LanguageClientSource.py | rplugin/python3/deoplete/sources/LanguageClientSource.py | import re
from .base import Base
CompleteResults = "g:LanguageClient_completeResults"
def simplify_snippet(snip: str) -> str:
return re.sub(r'(?<!\\)\$\d+', '', snip)
class Source(Base):
def __init__(self, vim):
super().__init__(vim)
self.name = "LanguageClient"
self.mark = "[LC]"... | import re
from .base import Base
CompleteResults = "g:LanguageClient_completeResults"
def simplify_snippet(snip: str) -> str:
snip = re.sub(r'(?<!\\)\$(?P<num>\d+)', '<`\g<num>`>', snip)
return re.sub(r'(?<!\\)\${(?P<num>\d+):(?P<desc>.+?)}',
'<`\g<num>:\g<desc>`>', snip)
class Source(Ba... | Replace placeholders in completion text | Replace placeholders in completion text
In deoplete source, replace the placeholders with the neosnippet format.
| Python | mit | autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/L... | ---
+++
@@ -6,7 +6,9 @@
def simplify_snippet(snip: str) -> str:
- return re.sub(r'(?<!\\)\$\d+', '', snip)
+ snip = re.sub(r'(?<!\\)\$(?P<num>\d+)', '<`\g<num>`>', snip)
+ return re.sub(r'(?<!\\)\${(?P<num>\d+):(?P<desc>.+?)}',
+ '<`\g<num>:\g<desc>`>', snip)
class Source(Base): |
5b3d38821517f10f9b9da31f28af19e7302de954 | dimod/reference/composites/structure.py | dimod/reference/composites/structure.py | from dimod.core.sampler import Sampler
from dimod.core.composite import Composite
from dimod.core.structured import Structured
from dimod.decorators import bqm_structured
class StructureComposite(Sampler, Composite, Structured):
"""Creates a structured composed sampler from an unstructured sampler.
todo
... | from dimod.core.sampler import Sampler
from dimod.core.composite import Composite
from dimod.core.structured import Structured
from dimod.decorators import bqm_structured
class StructureComposite(Sampler, Composite, Structured):
"""Creates a structured composed sampler from an unstructured sampler.
"""
# ... | Update Structure composite to use the new abc | Update Structure composite to use the new abc
| Python | apache-2.0 | oneklc/dimod,oneklc/dimod | ---
+++
@@ -6,13 +6,25 @@
class StructureComposite(Sampler, Composite, Structured):
"""Creates a structured composed sampler from an unstructured sampler.
+ """
+ # we will override these in the __init__, but because they are abstract properties we need to
+ # signal that we are overriding them
+ ... |
1a00b905b02d47ef8778a4744d9ef67de5149017 | web/premises/constants.py | web/premises/constants.py | FEATURED_CONTENT_COUNT = 30
NEWS_CONTENT_COUNT = 30
UPDATED_CONTENT_COUNT = 30
MAX_PREMISE_CONTENT_LENGTH = 300 | FEATURED_CONTENT_COUNT = 50
NEWS_CONTENT_COUNT = 50
UPDATED_CONTENT_COUNT = 50
MAX_PREMISE_CONTENT_LENGTH = 300 | Change contention counts on front-page | Change contention counts on front-page
| Python | mit | taiansu/arguman.org,beratdogan/arguman.org,bahattincinic/arguman.org,arguman/arguman.org,Arthur2e5/arguman.org,taiansu/arguman.org,donkawechico/arguman.org,bahattincinic/arguman.org,Arthur2e5/arguman.org,arguman/arguman.org,Arthur2e5/arguman.org,Arthur2e5/arguman.org,donkawechico/arguman.org,bahattincinic/arguman.org,a... | ---
+++
@@ -1,5 +1,5 @@
-FEATURED_CONTENT_COUNT = 30
-NEWS_CONTENT_COUNT = 30
-UPDATED_CONTENT_COUNT = 30
+FEATURED_CONTENT_COUNT = 50
+NEWS_CONTENT_COUNT = 50
+UPDATED_CONTENT_COUNT = 50
MAX_PREMISE_CONTENT_LENGTH = 300 |
9d7beff62a3555aa4be51cefb2f54681070d1305 | ircstat/plugins/__init__.py | ircstat/plugins/__init__.py | # Copyright 2013 John Reese
# Licensed under the MIT license
import importlib
import os
from functools import lru_cache
from os import path
from .base import Plugin
@lru_cache()
def load_plugins(config):
"""Import all the plugins, and return a set of plugin instances, filtering
out any plugin whose name app... | # Copyright 2013 John Reese
# Licensed under the MIT license
import importlib
import os
from functools import lru_cache
from os import path
from .base import Plugin
@lru_cache()
def load_plugins(config):
"""Import all the plugins, and return a set of plugin instances, filtering
out any plugin whose name app... | Make sure plugins' .name property gets set | Make sure plugins' .name property gets set
| Python | mit | jreese/ircstat,jreese/ircstat | ---
+++
@@ -14,22 +14,29 @@
"""Import all the plugins, and return a set of plugin instances, filtering
out any plugin whose name appears in the configurable blacklist."""
- cwd = path.abspath(path.dirname(__file__))
- files = os.listdir(cwd)
-
- for filename in files:
- name, ext = path.sp... |
ad8f54f7a2532b0ad643790d061b4e488ac7849d | patchboard/tests/functional/trivial_example_test.py | patchboard/tests/functional/trivial_example_test.py | # trivial_example.py
#
# Copyright 2014 BitVault.
#
# Reproduces the tests in trivial_example.rb
from __future__ import print_function
import pytest
from random import randint
from patchboard.tests.fixtures import (trivial_net_pb,
trivial_net_resources,
... | # trivial_example.py
#
# Copyright 2014 BitVault.
#
# Reproduces the tests in trivial_example.rb
from __future__ import print_function
import pytest
from random import randint
from patchboard.tests.fixtures import (trivial_net_pb,
trivial_net_resources,
... | Remove xfail from working test | Remove xfail from working test
| Python | mit | patchboard/patchboard-py | ---
+++
@@ -19,7 +19,6 @@
trivial_net_users)
-@pytest.mark.xfail
def test_users_create(trivial_net_users):
login = "foo-{0}".format(randint(1, 100000))
user = trivial_net_users.create({u'login': login}) |
1e79cc27ae0025d9ba51eff2828cc25247c08d3c | ssbench/worker.py | ssbench/worker.py | import yaml
from ssbench.constants import *
class Worker:
def __init__(self, queue):
queue.use(STATS_TUBE)
self.queue = queue
def go(self):
job = self.queue.reserve()
while job:
job.delete() # avoid any job-timeout nonsense
self.handle_job(job)
... | import yaml
from ssbench.constants import *
class Worker:
def __init__(self, queue):
queue.use(STATS_TUBE)
self.queue = queue
def go(self):
job = self.queue.reserve()
while job:
job.delete() # avoid any job-timeout nonsense
self.handle_job(job)
... | Raise error on unknown job type | Raise error on unknown job type
| Python | apache-2.0 | charz/ssbench,swiftstack/ssbench,charz/ssbench,swiftstack/ssbench | ---
+++
@@ -20,5 +20,5 @@
if job_data['type'] == UPLOAD_OBJECT:
print "WOO" # magic goes here
else:
- print "BOO"
-
+ raise NameError("Unknown job type %r" % (job_data['type'],))
+ |
168dab45955499aac320c859ff63a43cb20d9145 | fitz/__init__.py | fitz/__init__.py | from frontend import *
import tools
version = "0.0.1.dev"
__version__ = version
| from frontend import *
import tools
version = "0.0.1-dev"
__version__ = version
| Switch version label to comply with semver | Switch version label to comply with semver | Python | bsd-3-clause | kastman/fitz | ---
+++
@@ -1,5 +1,5 @@
from frontend import *
import tools
-version = "0.0.1.dev"
+version = "0.0.1-dev"
__version__ = version |
0be21659f1190e41db9b9818dd694015d94f78cc | zerodb/models/__init__.py | zerodb/models/__init__.py | import persistent
import indexable
import exceptions
class Model(persistent.Persistent):
"""
Data model to easily create indexable persistent objects.
If an object declares a property from indexable, this property is indexed.
*All* other properties are stored but unindexed
Example:
>>> cl... | import persistent
import indexable
import exceptions
class Model(persistent.Persistent):
"""
Data model to easily create indexable persistent objects.
If an object declares a property from indexable, this property is indexed.
*All* other properties are stored but unindexed
Example:
>>> cl... | Set model instance attributes based on fields | Set model instance attributes based on fields
| Python | agpl-3.0 | zerodb/zerodb,zero-db/zerodb,zero-db/zerodb,zerodb/zerodb | ---
+++
@@ -18,13 +18,24 @@
"""
def __init__(self, **kw):
+ # This set will go to metaclass
indexed_fields = set(filter(lambda key:
not key.startswith("_") and
isinstance(getattr(self.__class__, key), indexable.Indexable),
self.__class__.__dic... |
b378102284bbbcc9ad909a7393dfffa24377ce27 | ginga/__init__.py | ginga/__init__.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""See LONG_DESC.txt"""
# Set up the version
from pkg_resources import get_distribution, DistributionNotFound
try:
__version__ = get_distribution(__name__).version
except DistributionNotFound:
# package is not installed
__version__ = 'unknown... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""See LONG_DESC.txt"""
# Packages may add whatever they like to this file, but
# should keep this content at the top.
# ----------------------------------------------------------------------------
from ._astropy_init import * # noqa
# ------------------... | Fix version import and test runner | BUG: Fix version import and test runner
| Python | bsd-3-clause | pllim/ginga,pllim/ginga,ejeschke/ginga,naojsoft/ginga,ejeschke/ginga,ejeschke/ginga,pllim/ginga,naojsoft/ginga,naojsoft/ginga | ---
+++
@@ -1,14 +1,11 @@
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""See LONG_DESC.txt"""
-# Set up the version
-from pkg_resources import get_distribution, DistributionNotFound
-
-try:
- __version__ = get_distribution(__name__).version
-except DistributionNotFound:
- # package is no... |
5bc8ad66b59312d7459ec9c4d58d89bee0038a48 | conference_scheduler/scheduler.py | conference_scheduler/scheduler.py | import pulp
from typing import Sequence
import conference_scheduler.parameters as params
def is_valid_schedule(schedule):
"""Validate an existing schedule against a problem
Parameters
---------
schedule : iterable
of resources.ScheduledItem
Returns
-------
bool
True if sc... | import pulp
from typing import Sequence
import conference_scheduler.parameters as params
def is_valid_schedule(schedule):
"""Validate an existing schedule against a problem
Parameters
---------
schedule : iterable
of resources.ScheduledItem
Returns
-------
bool
True if sc... | Correct order of constraint assignment and problem solution | Correct order of constraint assignment and problem solution
| Python | mit | PyconUK/ConferenceScheduler | ---
+++
@@ -49,9 +49,9 @@
"""
problem = pulp.LpProblem()
variables = params.variables(events, rooms, slots)
- problem.solve()
for constraint in params.constraints(variables, events, rooms, slots):
problem += constraint
+ problem.solve()
return [
scheduled_item for sche... |
6d7e6d649302523ccbe0373b172b4a4fa8990a45 | dimod/__init__.py | dimod/__init__.py | from __future__ import absolute_import
import sys
__version__ = '0.3.1'
__author__ = 'D-Wave Systems Inc.'
__authoremail__ = 'acondello@dwavesys.com'
__description__ = 'A shared API for binary quadratic model samplers.'
_PY2 = sys.version_info[0] == 2
from dimod.template_sampler import *
from dimod.samplers import ... | from __future__ import absolute_import
import sys
__version__ = '0.4.0'
__author__ = 'D-Wave Systems Inc.'
__authoremail__ = 'acondello@dwavesys.com'
__description__ = 'A shared API for binary quadratic model samplers.'
_PY2 = sys.version_info[0] == 2
from dimod.template_sampler import *
from dimod.samplers import ... | Increment version 0.3.1 -> 0.4.0 | Increment version 0.3.1 -> 0.4.0 | Python | apache-2.0 | oneklc/dimod,oneklc/dimod | ---
+++
@@ -2,7 +2,7 @@
import sys
-__version__ = '0.3.1'
+__version__ = '0.4.0'
__author__ = 'D-Wave Systems Inc.'
__authoremail__ = 'acondello@dwavesys.com'
__description__ = 'A shared API for binary quadratic model samplers.' |
58b46dbc62c98372ed300eeb20b5ecb80a11ddb3 | test/test-mime.py | test/test-mime.py | from xdg import Mime
import unittest
import os.path
import tempfile, shutil
import resources
class MimeTest(unittest.TestCase):
def test_get_type_by_name(self):
appzip = Mime.get_type_by_name("foo.zip")
self.assertEqual(appzip.media, "application")
self.assertEqual(appzip.subtype, "zip")
... | from xdg import Mime
import unittest
import os.path
import tempfile, shutil
import resources
class MimeTest(unittest.TestCase):
def test_get_type_by_name(self):
appzip = Mime.get_type_by_name("foo.zip")
self.assertEqual(appzip.media, "application")
self.assertEqual(appzip.subtype, "zip")
... | Test getting comment for Mime type | Test getting comment for Mime type
| Python | lgpl-2.1 | 0312birdzhang/pyxdg | ---
+++
@@ -36,3 +36,5 @@
self.assertEqual(pdf1, pdf2)
self.assertEqual(pdf1.media, "application")
self.assertEqual(pdf1.subtype, "pdf")
+
+ pdf1.get_comment() |
f61c0a33a79fa4670874f4469e7ceb76c644bf4b | lambda_local/environment_variables.py | lambda_local/environment_variables.py | import json
import os
def set_environment_variables(json_file_path):
"""
Read and set environment variables from a flat json file.
Bear in mind that env vars set this way and later on read using
`os.getenv` function will be strings since after all env vars are just
that - plain strings.
Json... | import json
import os
def export_variables(environment_variables):
for env_name, env_value in environment_variables.items():
os.environ[str(env_name)] = str(env_value)
def set_environment_variables(json_file_path):
"""
Read and set environment variables from a flat json file.
Bear in mind t... | Split the parsing of input and the exporting of the variables for reuse | Split the parsing of input and the exporting of the variables for
reuse
| Python | mit | HDE/python-lambda-local,HDE/python-lambda-local | ---
+++
@@ -1,5 +1,10 @@
import json
import os
+
+
+def export_variables(environment_variables):
+ for env_name, env_value in environment_variables.items():
+ os.environ[str(env_name)] = str(env_value)
def set_environment_variables(json_file_path):
@@ -25,5 +30,4 @@
with open(json_file_path)... |
3598b974ecc078f34e54a32b06e16af8ccaf839b | opps/core/admin/__init__.py | opps/core/admin/__init__.py | # -*- coding: utf-8 -*-
from opps.core.admin.channel import *
from opps.core.admin.profile import *
| # -*- coding: utf-8 -*-
from opps.core.admin.channel import *
from opps.core.admin.profile import *
from opps.core.admin.source import *
| Add source admin in Admin Opps Core | Add source admin in Admin Opps Core
| Python | mit | opps/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,williamroot/opps,jeanmask/opps,opps/opps,YACOWS/opps,williamroot/opps,opps/opps,YACOWS/opps,jeanmask/opps,williamroot/opps,opps/opps | ---
+++
@@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
from opps.core.admin.channel import *
from opps.core.admin.profile import *
+from opps.core.admin.source import * |
83406db629abd389da85666dc79925f8e03a22f4 | lms/djangoapps/courseware/__init__.py | lms/djangoapps/courseware/__init__.py | #pylint: disable=missing-docstring
from __future__ import absolute_import
import warnings
if __name__ == 'courseware':
warnings.warn("Importing 'lms.djangoapps.courseware' as 'courseware' is no longer supported", DeprecationWarning)
| #pylint: disable=missing-docstring
from __future__ import absolute_import
import inspect
import warnings
if __name__ == 'courseware':
# pylint: disable=unicode-format-string
# Show the call stack that imported us wrong.
stack = "\n".join("%30s : %s:%d" % (t[3], t[1], t[2]) for t in inspect.stack()[:0:-1])... | Add more diagnostics to the courseware import warning | Add more diagnostics to the courseware import warning
| Python | agpl-3.0 | angelapper/edx-platform,angelapper/edx-platform,cpennington/edx-platform,edx-solutions/edx-platform,mitocw/edx-platform,edx/edx-platform,cpennington/edx-platform,angelapper/edx-platform,arbrandes/edx-platform,edx/edx-platform,EDUlib/edx-platform,arbrandes/edx-platform,edx-solutions/edx-platform,stvstnfrd/edx-platform,a... | ---
+++
@@ -1,7 +1,12 @@
#pylint: disable=missing-docstring
from __future__ import absolute_import
+import inspect
import warnings
if __name__ == 'courseware':
- warnings.warn("Importing 'lms.djangoapps.courseware' as 'courseware' is no longer supported", DeprecationWarning)
+ # pylint: disable=unicode-... |
3beea9e3800f5c1e68f869d46d137162016a5276 | zc-list.py | zc-list.py | #!/usr/bin/env python
import sys
import client_wrap
def get_keys(client):
key_str = client.GetKeys()
keys = key_str.split (';')
del keys[-1]
if len(keys) == 0:
sys.exit()
return keys
def print_keys(client, keys):
for key in keys:
value = client.ReadLong(key)
print "%... | #!/usr/bin/env python
import sys
import argparse
import client_wrap
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("-t", "--type", help="type of the cached data", default="double")
parser.add_argument("-c", "--connection", help="connection string", default="ipc:///var/run/zero-ca... | Add the parsing arguments function | Add the parsing arguments function
| Python | agpl-3.0 | ellysh/zero-cache-utils,ellysh/zero-cache-utils | ---
+++
@@ -1,7 +1,16 @@
#!/usr/bin/env python
import sys
+import argparse
import client_wrap
+
+def parse_args():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("-t", "--type", help="type of the cached data", default="double")
+ parser.add_argument("-c", "--connection", help="connection str... |
cdb7e9fd80b6b5dc31b0096beb7283b373709b8a | tekka/lib/spell_entry.py | tekka/lib/spell_entry.py |
try:
from sexy import SpellEntry as _SpellEntry
except ImportError:
from gtk import Entry as _SpellEntry
class SpellEntry(_SpellEntry):
__gtype_name__ = "SpellEntry"
pass
| import gtk
from ..helper import color
from gettext import gettext as _
try:
from sexy import SpellEntry as _SpellEntry
except ImportError:
from gtk import Entry as _SpellEntry
class SpellEntry(_SpellEntry):
__gtype_name__ = "SpellEntry"
def __init__(self, *args, **kwargs):
super(SpellEntry, self).__init__(*a... | Add dummy foreground/background color menu | Add dummy foreground/background color menu
| Python | bsd-2-clause | sushi-irc/tekka | ---
+++
@@ -1,3 +1,6 @@
+import gtk
+from ..helper import color
+from gettext import gettext as _
try:
from sexy import SpellEntry as _SpellEntry
@@ -8,4 +11,61 @@
__gtype_name__ = "SpellEntry"
- pass
+ def __init__(self, *args, **kwargs):
+ super(SpellEntry, self).__init__(*args, **kwargs)
+
+ self._ra... |
cab4ec885d3101775ac16532d46f6f47700d1134 | IATISimpleTester/views/uploader.py | IATISimpleTester/views/uploader.py | import os.path
from flask import request, jsonify, redirect, url_for
from IATISimpleTester import app, db
from IATISimpleTester.models import SuppliedData
@app.route('/upload', methods=['GET', 'POST'])
def upload():
resp = {}
source_url = request.args.get('source_url')
file = request.files.get('file')
... | import os.path
from flask import abort, request, jsonify, redirect, url_for
from IATISimpleTester import app, db
from IATISimpleTester.models import SuppliedData
@app.route('/upload', methods=['GET', 'POST'])
def upload():
source_url = request.args.get('source_url')
file = request.files.get('file')
raw_... | Tidy up upload response a bit | Tidy up upload response a bit
| Python | mit | pwyf/data-quality-tester,pwyf/data-quality-tester,pwyf/data-quality-tester,pwyf/data-quality-tester | ---
+++
@@ -1,6 +1,6 @@
import os.path
-from flask import request, jsonify, redirect, url_for
+from flask import abort, request, jsonify, redirect, url_for
from IATISimpleTester import app, db
from IATISimpleTester.models import SuppliedData
@@ -8,7 +8,6 @@
@app.route('/upload', methods=['GET', 'POST'])
de... |
b5fecb2dd0d85d97716b21aa34a8c41d06bc476f | {{cookiecutter.repo_name}}/tests/test_extension.py | {{cookiecutter.repo_name}}/tests/test_extension.py | import unittest
from mopidy_scrobbler import Extension, frontend as frontend_lib
class ExtensionTest(unittest.TestCase):
def test_get_default_config(self):
ext = Extension()
config = ext.get_default_config()
self.assertIn('[{{ cookiecutter.ext_name }}]', config)
self.assertIn('... | import unittest
from mopidy_{{ cookiecutter.ext_name }} import Extension, frontend as frontend_lib
class ExtensionTest(unittest.TestCase):
def test_get_default_config(self):
ext = Extension()
config = ext.get_default_config()
self.assertIn('[{{ cookiecutter.ext_name }}]', config)
... | Remove reference to scrobbler extension | Remove reference to scrobbler extension
| Python | apache-2.0 | mopidy/cookiecutter-mopidy-ext | ---
+++
@@ -1,6 +1,6 @@
import unittest
-from mopidy_scrobbler import Extension, frontend as frontend_lib
+from mopidy_{{ cookiecutter.ext_name }} import Extension, frontend as frontend_lib
class ExtensionTest(unittest.TestCase): |
2aab542cc74fdc0cf060518241f01fd74d91ecb5 | byceps/services/user/transfer/models.py | byceps/services/user/transfer/models.py | """
byceps.services.user.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from attr import attrs
from ....typing import UserID
@attrs(auto_attribs=True, frozen=True, slots=True)
class User:
id: UserID
screen... | """
byceps.services.user.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from typing import Optional
from attr import attrs
from ....typing import UserID
@attrs(auto_attribs=True, frozen=True, slots=True)
class Us... | Fix type hint for avatar URL in user DTO | Fix type hint for avatar URL in user DTO
| Python | bsd-3-clause | m-ober/byceps,homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps | ---
+++
@@ -5,6 +5,8 @@
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
+
+from typing import Optional
from attr import attrs
@@ -17,5 +19,5 @@
screen_name: str
suspended: bool
deleted: bool
- avatar_url: str
+ avatar_url: Optional[str]
... |
1c4e75c243205ad47cd2e47a3d836c6c9e516db4 | pika/amqp_object.py | pika/amqp_object.py | """Base classes that are extended by low level AMQP frames and higher level
AMQP classes and methods.
"""
class AMQPObject(object):
"""Base object that is extended by AMQP low level frames and AMQP classes
and methods.
"""
NAME = 'AMQPObject'
def __repr__(self):
items = list()
fo... | """Base classes that are extended by low level AMQP frames and higher level
AMQP classes and methods.
"""
class AMQPObject(object):
"""Base object that is extended by AMQP low level frames and AMQP classes
and methods.
"""
NAME = 'AMQPObject'
INDEX = None
def __repr__(self):
items = ... | Add a few base attributes | Add a few base attributes
| Python | bsd-3-clause | reddec/pika,shinji-s/pika,fkarb/pika-python3,renshawbay/pika-python3,zixiliuyue/pika,skftn/pika,vitaly-krugl/pika,vrtsystems/pika,hugoxia/pika,knowsis/pika,Tarsbot/pika,Zephor5/pika,jstnlef/pika,benjamin9999/pika,pika/pika | ---
+++
@@ -9,6 +9,7 @@
"""
NAME = 'AMQPObject'
+ INDEX = None
def __repr__(self):
items = list()
@@ -28,6 +29,7 @@
class Method(AMQPObject):
"""Is extended by AMQP methods"""
NAME = 'Unextended Method'
+ synchronous = False
def _set_content(self, properties, body):... |
5830f5590ed185116dd4807f6351ad3afeb0dd5d | plugins/postgres/dbt/adapters/postgres/relation.py | plugins/postgres/dbt/adapters/postgres/relation.py | from dbt.adapters.base import Column
from dataclasses import dataclass
from dbt.adapters.base.relation import BaseRelation
from dbt.exceptions import RuntimeException
@dataclass(frozen=True, eq=False, repr=False)
class PostgresRelation(BaseRelation):
def __post_init__(self):
# Check for length of Postgres... | from dbt.adapters.base import Column
from dataclasses import dataclass
from dbt.adapters.base.relation import BaseRelation
from dbt.exceptions import RuntimeException
@dataclass(frozen=True, eq=False, repr=False)
class PostgresRelation(BaseRelation):
def __post_init__(self):
# Check for length of Postgres... | Tweak error message, reformat for flake8 | Tweak error message, reformat for flake8
| Python | apache-2.0 | analyst-collective/dbt,analyst-collective/dbt | ---
+++
@@ -9,14 +9,11 @@
def __post_init__(self):
# Check for length of Postgres table/view names.
# Check self.type to exclude test relation identifiers
- if (
- self.identifier is not None
- and self.type is not None
- and len(self.identifier) > self.r... |
d0861d4c072e81c94c06b093469224c076c6c362 | armstrong/core/arm_sections/tests/_utils.py | armstrong/core/arm_sections/tests/_utils.py | from datetime import datetime
from django.core.files import File
from django.conf import settings
from armstrong.dev.tests.utils import ArmstrongTestCase
from armstrong.dev.tests.utils.backports import *
from armstrong.dev.tests.utils.concrete import *
from armstrong.dev.tests.utils.users import *
from ..models impor... | from datetime import datetime
from django.core.files import File
from django.conf import settings
from armstrong.dev.tests.utils import ArmstrongTestCase
from armstrong.dev.tests.utils.backports import *
from armstrong.dev.tests.utils.concrete import *
from armstrong.dev.tests.utils.users import *
from ..models impor... | Adjust in a BC way to introduce TestCase | Adjust in a BC way to introduce TestCase
| Python | apache-2.0 | texastribune/armstrong.core.tt_sections,texastribune/armstrong.core.tt_sections,armstrong/armstrong.core.arm_sections,texastribune/armstrong.core.tt_sections,armstrong/armstrong.core.arm_sections | ---
+++
@@ -12,7 +12,7 @@
import fudge
-class ArmSectionsTestCase(ArmstrongTestCase):
+class TestCase(ArmstrongTestCase):
def setUp(self):
super(ArmSectionsTestCase, self).setUp()
self.sections = []
@@ -33,3 +33,7 @@
summary=summary,
parent=parent,... |
1007ee608ac448941e9bb8958c6b2308abeb63ef | github-listener/listener.py | github-listener/listener.py | import flask
import registry
app = flask.Flask(__name__)
def get_registry():
r = getattr(flask.g, '_registry', None)
if r is None:
r = flask.g._registry = registry.Registry("hooks.json")
return r
@app.route("/hook/<repo>", methods=['POST'])
def hook(repo):
branch = flask.request.json["ref"]... | import flask
import registry
app = flask.Flask(__name__)
def get_registry():
r = getattr(flask.g, '_registry', None)
if r is None:
r = flask.g._registry = registry.Registry("hooks.json")
return r
@app.route("/hook/<repo>", methods=['POST'])
def hook(repo):
if flask.request.headers['X-GitHub... | Add support for github ping event | Add support for github ping event
| Python | mit | Storj/lunchbox,Storj/lunchbox | ---
+++
@@ -13,12 +13,16 @@
@app.route("/hook/<repo>", methods=['POST'])
def hook(repo):
- branch = flask.request.json["ref"].split("/")[-1]
- sha = flask.request.json["head"]
+ if flask.request.headers['X-GitHub-Event'] == 'ping':
+ return flask.jsonify(zen_level="super")
- get_registry()... |
82155f3caad1220eeb2ee718142c5aace8600f87 | django-jquery-file-upload/urls.py | django-jquery-file-upload/urls.py | from django.conf.urls import patterns, include, url
from django.http import HttpResponseRedirect
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'upload.views.home', name='home'),
url(r'^$', lamb... | from django.conf.urls import patterns, include, url
from django.http import HttpResponseRedirect
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'upload.views.home', name='home'),
url(r'^$', lamb... | Fix serve media files path | Fix serve media files path
| Python | mit | minhlongdo/django-jquery-file-upload,Imaginashion/cloud-vision,vaniakov/django-jquery-file-upload,indrajithi/mgc-django,sigurdga/django-jquery-file-upload,Imaginashion/cloud-vision,minhlongdo/django-jquery-file-upload,Imaginashion/cloud-vision,vaniakov/django-jquery-file-upload,Imaginashion/cloud-vision,sigurdga/django... | ---
+++
@@ -19,7 +19,7 @@
url(r'^admin/', include(admin.site.urls)),
)
-import os
+from os.path import join, abspath, dirname
urlpatterns += patterns('',
- (r'^media/(.*)$', 'django.views.static.serve', {'document_root': os.path.join(os.path.abspath(os.path.dirname(__file__)), 'media')}),
+ (r'^media/(... |
67ab4b7374d739719700f84f0f5726f1b0c476d8 | cybox/test/objects/mutex_test.py | cybox/test/objects/mutex_test.py | import unittest
import cybox.bindings.cybox_common_types_1_0 as common_types_binding
import cybox.bindings.mutex_object_1_3 as mutex_binding
from cybox.objects.mutex_object import Mutex
class MutexTest(unittest.TestCase):
def setUp(self):
self.test_dict = {'named': True, 'name': {'value': 'test_name'}}
... | import unittest
import cybox.bindings.cybox_common_types_1_0 as common_types_binding
import cybox.bindings.mutex_object_1_3 as mutex_binding
from cybox.objects.mutex_object import Mutex
class MutexTest(unittest.TestCase):
def setUp(self):
self.test_dict = {'named': True, 'name': {'value': 'test_name'}}
... | Fix some more unittest assert methods for Python 2.6 | Fix some more unittest assert methods for Python 2.6
| Python | bsd-3-clause | CybOXProject/python-cybox | ---
+++
@@ -12,17 +12,18 @@
def test_obj_from_dict(self):
#Make sure it's an instance of the right class
- self.assertIsInstance(self.mutex_obj, mutex_binding.MutexObjectType)
+ self.assertTrue(isinstance(self.mutex_obj,
+ mutex_binding.MutexObjectType))... |
02937272206a526ff62b164fc54a14c385eb6970 | common/lib/xmodule/xmodule/hidden_module.py | common/lib/xmodule/xmodule/hidden_module.py | from xmodule.x_module import XModule
from xmodule.raw_module import RawDescriptor
class HiddenModule(XModule):
def get_html(self):
if self.system.user_is_staff:
return "ERROR: This module is unknown--students will not see it at all"
else:
return ""
class HiddenDescriptor(... | from xmodule.x_module import XModule
from xmodule.raw_module import RawDescriptor
class HiddenModule(XModule):
def get_html(self):
if self.system.user_is_staff:
return u"ERROR: This module is unknown--students will not see it at all"
else:
return u""
class HiddenDescripto... | Return unicode string to pass assertion | hidden-module-unicode: Return unicode string to pass assertion
XBlock Fragments expect unicode strings, and fail on an assertion when
it isn't:
```
2013-11-14 07:55:50,774 ERROR 3788 [django.request] base.py:215 - Internal Server Error: /courses/TestU/TST101/now/courseware/41d55c576a574fde99319420228f7f88/5fef5794e34... | Python | agpl-3.0 | louyihua/edx-platform,Endika/edx-platform,mushtaqak/edx-platform,shubhdev/openedx,valtech-mooc/edx-platform,a-parhom/edx-platform,Livit/Livit.Learn.EdX,longmen21/edx-platform,knehez/edx-platform,shurihell/testasia,mbareta/edx-platform-ft,hkawasaki/kawasaki-aio8-1,Softmotions/edx-platform,kursitet/edx-platform,dsajkl/re... | ---
+++
@@ -5,9 +5,9 @@
class HiddenModule(XModule):
def get_html(self):
if self.system.user_is_staff:
- return "ERROR: This module is unknown--students will not see it at all"
+ return u"ERROR: This module is unknown--students will not see it at all"
else:
- r... |
578fe6f7403de0f93b3ca2776092e5dfe8dbfa73 | twisted/plugins/docker_xylem_plugin.py | twisted/plugins/docker_xylem_plugin.py | import yaml
from zope.interface import implements
from twisted.python import usage
from twisted.plugin import IPlugin
from twisted.application.service import IServiceMaker
from twisted.application import internet
from twisted.web import server
from docker_xylem import service
class Options(usage.Options):
optP... | import yaml
from zope.interface import implements
from twisted.python import filepath, usage
from twisted.plugin import IPlugin
from twisted.application.service import IServiceMaker
from twisted.application import internet
from twisted.web import server
from docker_xylem import service
class Options(usage.Options)... | Create /run/docker/plugins before using it. (@bearnard) | Create /run/docker/plugins before using it. (@bearnard)
| Python | mit | praekeltfoundation/docker-xylem,praekeltfoundation/docker-xylem | ---
+++
@@ -2,7 +2,7 @@
from zope.interface import implements
-from twisted.python import usage
+from twisted.python import filepath, usage
from twisted.plugin import IPlugin
from twisted.application.service import IServiceMaker
from twisted.application import internet
@@ -25,9 +25,12 @@
def makeServic... |
45ead09898275154919ab9589abb610d42049782 | website/apps/ts_om/views/ScenarioValidationView.py | website/apps/ts_om/views/ScenarioValidationView.py | import requests
from django.conf import settings
from django.http import HttpResponse
from django.views.generic.base import View
from website.apps.ts_om.check import check_url
def rest_validate(f):
validate_url = check_url(getattr(settings, "TS_OM_VALIDATE_URL", None), "validate")
response = requests.post(... | import requests
from django.conf import settings
from django.http import HttpResponse
from django.views.generic.base import View
from website.apps.ts_om.check import check_url
def rest_validate(f):
validate_url = check_url(getattr(settings, "TS_OM_VALIDATE_URL", None), "validate")
response = requests.post(... | Remove invalid staticmethod decorator from post method. | Fix: Remove invalid staticmethod decorator from post method.
| Python | mpl-2.0 | vecnet/om,vecnet/om,vecnet/om,vecnet/om,vecnet/om | ---
+++
@@ -16,7 +16,6 @@
class ScenarioValidationView(View):
- @staticmethod
def post(self, request):
json_str = rest_validate(request.read())
|
861f2ea86e26fe27ba3f2f283c32ed0a9931c5fb | ce/analysis/core.py | ce/analysis/core.py | #!/usr/bin/env python
# vim: set fileencoding=UTF-8 :
from ..common import DynamicMethods
from ..expr import Expr, ExprTreeTransformer
from ..semantics import cast_error
class Analysis(DynamicMethods):
def __init__(self, e, **kwargs):
super(Analysis, self).__init__()
self.e = e
self.s =... | #!/usr/bin/env python
# vim: set fileencoding=UTF-8 :
from ..common import DynamicMethods
from ..expr import Expr, ExprTreeTransformer
from ..semantics import cast_error
class Analysis(DynamicMethods):
def __init__(self, e, **kwargs):
super(Analysis, self).__init__()
self.e = e
self.s =... | Add preliminary ErrorAnalysis test case | Add preliminary ErrorAnalysis test case
| Python | mit | admk/soap | ---
+++
@@ -30,3 +30,8 @@
def error_analysis(self, t):
return t.error(self.v)
+
+
+if __name__ == '__main__':
+ e = '((a + 2) * (a + 3))'
+ ErrorAnalysis(e, {'a': cast_error('0.1', '0.2')}) |
80d02cffe20cfa6d370bd33856db480bf0ce5fea | backend/unichat/helpers.py | backend/unichat/helpers.py | from .models import School, User
import re
def get_school_list():
schools = School.objects.all()
school_list = []
for s in schools:
school = {}
school['id'] = s.id
school['name'] = s.name
school['site'] = s.site
school['university'] = s.university.name
schoo... | from .models import School, User
import re
import string
import random
def get_school_list():
schools = School.objects.all()
school_list = []
for s in schools:
school = {}
school['id'] = s.id
school['name'] = s.name
school['site'] = s.site
school['university'] = s.u... | Create random auth token on user signup | Create random auth token on user signup
| Python | mit | dimkarakostas/unimeet,dimkarakostas/unimeet,dimkarakostas/unimeet,dimkarakostas/unimeet | ---
+++
@@ -1,5 +1,7 @@
from .models import School, User
import re
+import string
+import random
def get_school_list():
@@ -26,7 +28,9 @@
def create_user(email, school):
password = User.objects.make_random_password()
- user_obj = User.objects.create_user(email=email, school=school, password=password... |
c4ea358c7cdcd76dc9bf35b54e22cc9be05dc62a | setuptools/command/sdist3.py | setuptools/command/sdist3.py | from distutils import log
from sdist import sdist
from lib2to3.refactor import RefactoringTool, get_fixers_from_package
class _RefactoringTool(RefactoringTool):
def log_error(self, msg, *args, **kw):
log.error(msg, *args)
def log_message(self, msg, *args):
log.info(msg, *args)
de... | import os
from distutils import log
from sdist import sdist
from lib2to3.refactor import RefactoringTool, get_fixers_from_package
class _RefactoringTool(RefactoringTool):
def log_error(self, msg, *args, **kw):
log.error(msg, *args)
def log_message(self, msg, *args):
log.info(msg, *arg... | Correct path names for fixed files. | Correct path names for fixed files.
--HG--
branch : distribute
extra : rebase_source : d5bd9c6fdb8cf2208eca9e0e5f37cb7fea1d14a5
| Python | mit | pypa/setuptools,pypa/setuptools,pypa/setuptools | ---
+++
@@ -1,3 +1,4 @@
+import os
from distutils import log
from sdist import sdist
from lib2to3.refactor import RefactoringTool, get_fixers_from_package
@@ -31,4 +32,4 @@
if fixer_names is None:
fixer_names = get_fixers_from_package('lib2to3.fixes')
r = _RefactoringTool(fixer_names... |
e4345634ea6a4c43db20ea1d3d33134b6ee6204d | alembic/versions/151b2f642877_text_to_json.py | alembic/versions/151b2f642877_text_to_json.py | """text to JSON
Revision ID: 151b2f642877
Revises: aee7291c81
Create Date: 2015-06-12 14:40:56.956657
"""
# revision identifiers, used by Alembic.
revision = '151b2f642877'
down_revision = 'aee7291c81'
from alembic import op
import sqlalchemy as sa
def upgrade():
query = 'ALTER TABLE project ALTER COLUMN info... | """text to JSON
Revision ID: 151b2f642877
Revises: ac115763654
Create Date: 2015-06-12 14:40:56.956657
"""
# revision identifiers, used by Alembic.
revision = '151b2f642877'
down_revision = 'ac115763654'
from alembic import op
import sqlalchemy as sa
def upgrade():
query = 'ALTER TABLE project ALTER COLUMN in... | Fix alembic revision after merge master | Fix alembic revision after merge master
| Python | agpl-3.0 | OpenNewsLabs/pybossa,PyBossa/pybossa,PyBossa/pybossa,Scifabric/pybossa,jean/pybossa,geotagx/pybossa,OpenNewsLabs/pybossa,jean/pybossa,Scifabric/pybossa,geotagx/pybossa | ---
+++
@@ -1,14 +1,14 @@
"""text to JSON
Revision ID: 151b2f642877
-Revises: aee7291c81
+Revises: ac115763654
Create Date: 2015-06-12 14:40:56.956657
"""
# revision identifiers, used by Alembic.
revision = '151b2f642877'
-down_revision = 'aee7291c81'
+down_revision = 'ac115763654'
from alembic import ... |
780ba3b8f1271dd0a4b78c7a3bb00f5f4fabf2eb | external_ip.py | external_ip.py | # -*- coding: utf-8 -*-
'''
:codeauthor: David Boucha
:copyright: © 2013 by the SaltStack Team, see AUTHORS for more details.
:license: Apache 2.0, see LICENSE for more details.
salt.grains.external_ip
~~~~~~~~~~~~~~~~~~~~~~~
Return the external IP address reported by boucha.saltstack.com
'''... | # -*- coding: utf-8 -*-
'''
:codeauthor: David Boucha
:copyright: © 2013 by the SaltStack Team, see AUTHORS for more details.
:license: Apache 2.0, see LICENSE for more details.
salt.grains.external_ip
~~~~~~~~~~~~~~~~~~~~~~~
Return the external IP address reported by an IP reporting service.... | Add requirement for opt in | Add requirement for opt in
| Python | apache-2.0 | UtahDave/external_ip | ---
+++
@@ -8,13 +8,21 @@
salt.grains.external_ip
~~~~~~~~~~~~~~~~~~~~~~~
- Return the external IP address reported by boucha.saltstack.com
+ Return the external IP address reported by an IP reporting service.
+ SaltStack provides this at http://boucha.saltstack.com:8080
+
+ The following conf... |
7e47ce789c9eb363f941ead2b3b199152dffff1c | pushmanager/tests/test_bookmarklet.py | pushmanager/tests/test_bookmarklet.py | import contextlib
import mock
import testify as T
from pushmanager.handlers import CheckSitesBookmarkletHandler
from pushmanager.handlers import CreateRequestBookmarkletHandler
from pushmanager.testing.testservlet import AsyncTestCase
class BookmarkletTest(T.TestCase, AsyncTestCase):
def get_handlers(self):
... | import contextlib
import mock
import testify as T
from pushmanager.handlers import CheckSitesBookmarkletHandler
from pushmanager.handlers import CreateRequestBookmarkletHandler
from pushmanager.testing.testservlet import AsyncTestCase
class BookmarkletTest(T.TestCase, AsyncTestCase):
def get_handlers(self):
... | Test added for the ticket tracker url. | Test added for the ticket tracker url.
The automatic test now checks also the ticket tracker url (just tests that
the javascript contains the word %TICKET%).
| Python | apache-2.0 | Yelp/pushmanager,YelpArchive/pushmanager,Yelp/pushmanager,Yelp/pushmanager,YelpArchive/pushmanager,YelpArchive/pushmanager,YelpArchive/pushmanager,Yelp/pushmanager | ---
+++
@@ -30,6 +30,7 @@
T.assert_equal(response.error, None)
T.assert_in("ticketNumberToURL", response.body)
T.assert_in("codeReview", response.body)
+ T.assert_in("%TICKET%", response.body)
def test_check_sites_bookmarklet(self): |
e5bec10f3788e435af63970158e35cb3f2ad4f2a | simple_faq/views.py | simple_faq/views.py | from django.views.generic import TemplateView
from simple_faq.models import Topic
class Topics(TemplateView):
template_name = "topics.html"
context_object_name = "topics"
model = Topic | from django.views.generic import ListView
from simple_faq.models import Topic
class Topics(ListView):
template_name = "topics.html"
context_object_name = "topics"
model = Topic | Fix father class of topics view | Fix father class of topics view
@15m
| Python | mit | devartis/django-simple-faq,devartis/django-simple-faq | ---
+++
@@ -1,8 +1,8 @@
-from django.views.generic import TemplateView
+from django.views.generic import ListView
from simple_faq.models import Topic
-class Topics(TemplateView):
+class Topics(ListView):
template_name = "topics.html"
context_object_name = "topics"
model = Topic |
3fcdb9e64ef955fd0a7e5b2fda481d351dfb4d18 | spotify/__init__.py | spotify/__init__.py | from __future__ import unicode_literals
import os
import weakref
import cffi
__version__ = '2.0.0a1'
_header_file = os.path.join(os.path.dirname(__file__), 'api.processed.h')
_header = open(_header_file).read()
_header += '#define SPOTIFY_API_VERSION ...\n'
ffi = cffi.FFI()
ffi.cdef(_header)
lib = ffi.verify('#in... | from __future__ import unicode_literals
import logging
import os
import weakref
import cffi
__version__ = '2.0.0a1'
# Log to nowhere by default. For details, see:
# http://docs.python.org/2/howto/logging.html#library-config
logging.getLogger('spotify').addHandler(logging.NullHandler())
_header_file = os.path.jo... | Add NullHandler to the 'spotify' logger | Add NullHandler to the 'spotify' logger
| Python | apache-2.0 | jodal/pyspotify,mopidy/pyspotify,kotamat/pyspotify,jodal/pyspotify,kotamat/pyspotify,felix1m/pyspotify,mopidy/pyspotify,kotamat/pyspotify,felix1m/pyspotify,felix1m/pyspotify,jodal/pyspotify | ---
+++
@@ -1,5 +1,6 @@
from __future__ import unicode_literals
+import logging
import os
import weakref
@@ -7,6 +8,11 @@
__version__ = '2.0.0a1'
+
+
+# Log to nowhere by default. For details, see:
+# http://docs.python.org/2/howto/logging.html#library-config
+logging.getLogger('spotify').addHandler(loggi... |
65655186f22f1cdc4699cfbddb8b11ccf3ad292a | apps/challenge/forms.py | apps/challenge/forms.py | from django import forms
from django.contrib.admin import widgets
# Smrtr
from network.models import Network
from challenge.models import Challenge
# External
from haystack.forms import SearchForm
class ChallengeForm(forms.ModelForm):
class Meta:
model = Challenge
... | from django import forms
from django.contrib.admin import widgets
# Smrtr
from network.models import Network
from challenge.models import Challenge
# External
from haystack.forms import SearchForm
class ChallengeForm(forms.ModelForm):
class Meta:
model = Challenge
... | Improve search ordering in challenges (+packages) | Improve search ordering in challenges (+packages)
| Python | bsd-3-clause | mfitzp/smrtr,mfitzp/smrtr | ---
+++
@@ -21,5 +21,10 @@
class ChallengeSearchForm(SearchForm):
+ def search(self):
+ sqs = super(ChallengeSearchForm, self).search()
+ sqs = sqs.order_by('-total_members','-type','score')
+ return sqs
+
def __init__(self, *args, **kwargs):
super(ChallengeSearchFor... |
95bd5b96fcbc62133aac4045a77ed7b7e7d342a5 | pyhprof/__init__.py | pyhprof/__init__.py | from pyhprof import *
from pyhprof import __doc__
from pyhprof import __all__
| '''Library for parsing and analyzing Java hprof files
'''
from .parsers import HProfParser, HeapDumpParser | Include parsers in top level module | Include parsers in top level module
| Python | apache-2.0 | matthagy/pyhprof | ---
+++
@@ -1,3 +1,4 @@
-from pyhprof import *
-from pyhprof import __doc__
-from pyhprof import __all__
+'''Library for parsing and analyzing Java hprof files
+'''
+
+from .parsers import HProfParser, HeapDumpParser |
761ba162338b86bc16aa4b642cc51a297d5491d6 | games/notifier.py | games/notifier.py | from games import models
def get_unpublished_installers(count=10):
return models.Installer.objects.filter(published=False).order_by('?')[:count]
def get_unpublished_screenshots(count=10):
return models.Screenshot.objects.filter(published=False).order_by('?')[:count]
def get_unreviewed_game_submissions(cou... | from games import models
DEFAULT_COUNT = 12
def get_unpublished_installers(count=DEFAULT_COUNT):
return models.Installer.objects.filter(published=False).order_by('?')[:count]
def get_unpublished_screenshots(count=DEFAULT_COUNT):
return models.Screenshot.objects.filter(published=False).order_by('?')[:count]... | Set the default number of items to 12 because it fits more nicely on the email | Set the default number of items to 12 because it fits more nicely on the email
| Python | agpl-3.0 | lutris/website,Turupawn/website,lutris/website,lutris/website,Turupawn/website,Turupawn/website,Turupawn/website,lutris/website | ---
+++
@@ -1,19 +1,21 @@
from games import models
+DEFAULT_COUNT = 12
-def get_unpublished_installers(count=10):
+
+def get_unpublished_installers(count=DEFAULT_COUNT):
return models.Installer.objects.filter(published=False).order_by('?')[:count]
-def get_unpublished_screenshots(count=10):
+def get_unp... |
1fc452c7b0a8c55eee40e496de4750045ef725a4 | overspill/settings/local.py | overspill/settings/local.py | from __future__ import absolute_import
from djcelery import setup_loader
from .base import *
DEBUG = True
ALLOWED_HOSTS = ['*']
STATIC_URL = '/static/'
CELERY_REDIRECT_STDOUTS = False
CELERY_ALWAYS_EAGER = True
CELERY_EAGER_PROPAGATES_EXCEPTIONS = True
setup_loader()
| from __future__ import absolute_import
import os
from djcelery import setup_loader
from .base import *
DEBUG = True
ALLOWED_HOSTS = ['*']
STATIC_ROOT = os.getenv('STATIC_ROOT')
MEDIA_ROOT = os.getenv('STATIC_ROOT')
STATIC_URL = '/static/'
CELERY_REDIRECT_STDOUTS = False
CELERY_ALWAYS_EAGER = True
CELERY_EAGER_PROPAGA... | Set MEDIA_ROOT and STATIC_ROOT settings | Set MEDIA_ROOT and STATIC_ROOT settings
| Python | apache-2.0 | iamsteadman/overspill,iamsteadman/overspill | ---
+++
@@ -1,9 +1,12 @@
from __future__ import absolute_import
+import os
from djcelery import setup_loader
from .base import *
DEBUG = True
ALLOWED_HOSTS = ['*']
+STATIC_ROOT = os.getenv('STATIC_ROOT')
+MEDIA_ROOT = os.getenv('STATIC_ROOT')
STATIC_URL = '/static/'
CELERY_REDIRECT_STDOUTS = False |
1d6ddc15fd6b195f3331e8c4022f0760da0fe9ef | cibopath/cli.py | cibopath/cli.py | # -*- coding: utf-8 -*-
import click
from cibopath import __version__
@click.group()
@click.version_option(__version__, u'-V', u'--version', prog_name='Cibopath')
def cli():
"""Cibopath - Search Cookiecutters on GitHub."""
@cli.command('update')
def update_cmd():
print('update')
main = cli
| # -*- coding: utf-8 -*-
import click
from cibopath import __version__
@click.group()
@click.version_option(__version__, u'-V', u'--version', prog_name='Cibopath')
def cli():
"""Cibopath - Search Cookiecutters on GitHub."""
@cli.command('update')
def update_cmd():
print('update')
main = cli
| Remove unwanted whitespace from doc str | Remove unwanted whitespace from doc str
| Python | bsd-3-clause | hackebrot/cibopath | ---
+++
@@ -8,7 +8,7 @@
@click.group()
@click.version_option(__version__, u'-V', u'--version', prog_name='Cibopath')
def cli():
- """Cibopath - Search Cookiecutters on GitHub."""
+ """Cibopath - Search Cookiecutters on GitHub."""
@cli.command('update') |
0825919e14ae34abbafaf982533c6936a9958bc4 | shopify_python/__init__.py | shopify_python/__init__.py | # Copyright (c) 2017 "Shopify inc." All rights reserved.
# Use of this source code is governed by a MIT-style license that can be found in the LICENSE file.
from __future__ import unicode_literals
from pylint import lint
from shopify_python import google_styleguide
from shopify_python import shopify_styleguide
__ver... | # Copyright (c) 2017 "Shopify inc." All rights reserved.
# Use of this source code is governed by a MIT-style license that can be found in the LICENSE file.
from __future__ import unicode_literals
from pylint import lint
from shopify_python import google_styleguide
from shopify_python import shopify_styleguide
__ver... | Increase version number to 0.4.1 | Increase version number to 0.4.1
| Python | mit | Shopify/shopify_python | ---
+++
@@ -7,7 +7,7 @@
from shopify_python import shopify_styleguide
-__version__ = '0.4.0'
+__version__ = '0.4.1'
def register(linter): # type: (lint.PyLinter) -> None |
efb14d75d04d0200b37af1c4c3bb50b61f0b2a7e | km3pipe/__init__.py | km3pipe/__init__.py | # coding=utf-8
# Filename: __init__.py
"""
The extemporary KM3NeT analysis framework.
"""
from __future__ import division, absolute_import, print_function
try:
__KM3PIPE_SETUP__
except NameError:
__KM3PIPE_SETUP__ = False
from .__version__ import version, version_info # noqa
if not __KM3PIPE_SETUP__:
... | # coding=utf-8
# Filename: __init__.py
"""
The extemporary KM3NeT analysis framework.
"""
from __future__ import division, absolute_import, print_function
try:
__KM3PIPE_SETUP__
except NameError:
__KM3PIPE_SETUP__ = False
from .__version__ import version, version_info # noqa
if not __KM3PIPE_SETUP__:
... | FIX also drop genericpump/h5pump from init | FIX also drop genericpump/h5pump from init
| Python | mit | tamasgal/km3pipe,tamasgal/km3pipe | ---
+++
@@ -17,7 +17,6 @@
if not __KM3PIPE_SETUP__:
from .core import (Pipeline, Module, Pump, Blob, Run, # noqa
Geometry, AanetGeometry)
- from .io import GenericPump # noqa
__author__ = "Tamas Gal and Moritz Lotze" |
46bcad1e20e57f66498e7a70b8f3be929115bde6 | incunafein/module/page/extensions/prepared_date.py | incunafein/module/page/extensions/prepared_date.py | from django.db import models
def get_prepared_date(cls):
return cls.prepared_date or cls.parent.prepared_date
def register(cls, admin_cls):
cls.add_to_class('prepared_date', models.TextField('Date of Preparation', blank=True, null=True))
cls.add_to_class('get_prepared_date', get_prepared_date)
| from django.db import models
def register(cls, admin_cls):
cls.add_to_class('_prepared_date', models.TextField('Date of Preparation', blank=True, null=True))
def getter():
if not cls._prepared_date:
try:
return cls.get_ancestors(ascending=True).filter(_prepared_date__isnull... | Return parent date if there isn't one on the current object | Return parent date if there isn't one on the current object
Look for a prepared date in the ancestors of the current object and use
that if it exists
| Python | bsd-2-clause | incuna/incuna-feincms,incuna/incuna-feincms,incuna/incuna-feincms | ---
+++
@@ -1,9 +1,21 @@
from django.db import models
-def get_prepared_date(cls):
- return cls.prepared_date or cls.parent.prepared_date
+def register(cls, admin_cls):
+ cls.add_to_class('_prepared_date', models.TextField('Date of Preparation', blank=True, null=True))
-def register(cls, admin_cls):
- c... |
83bf2da38eb67abab9005495289eb97b58c3856a | ec2_instance_change_type.py | ec2_instance_change_type.py | #!/usr/bin/env python
import sys
import click
from aws_util import Ec2Util
@click.command()
@click.option('-p', '--profile', default='default', help='Profile name to use.')
@click.argument('id_or_tag', required=True)
@click.argument('new_instance_type', required=True)
def cli(profile, id_or_tag, new_instance_type):
... | #!/usr/bin/env python
import sys
import click
from aws_util import Ec2Util
@click.command()
@click.option('-p', '--profile', default='default', help='Profile name to use.')
@click.argument('id_or_tag', required=True)
@click.argument('new_instance_type', required=True)
def cli(profile, id_or_tag, new_instance_type):
... | Change message that detects instance type | Change message that detects instance type
| Python | mit | thinhpham/aws-tools | ---
+++
@@ -19,7 +19,9 @@
if new_instance_type != instance.instance_type:
ec2.change_instance_type(id_or_tag, new_instance_type)
instance.reload()
- print('Instance type changed to %s successfully' % instance.instance_type)
+ print('Instance type changed to %s succ... |
e867722e4369fca2df9a4e07218815c7611f35be | examples/timeflies/timeflies_tkinter.py | examples/timeflies/timeflies_tkinter.py | from tkinter import Tk, Label, Frame
from rx import from_
from rx import operators as _
from rx.subjects import Subject
from rx.concurrency import TkinterScheduler
def main():
root = Tk()
root.title("Rx for Python rocks")
scheduler = TkinterScheduler(root)
mousemove = Subject()
frame = Frame(ro... | from tkinter import Tk, Label, Frame
import rx
from rx import operators as ops
from rx.subjects import Subject
from rx.concurrency import TkinterScheduler
def main():
root = Tk()
root.title("Rx for Python rocks")
scheduler = TkinterScheduler(root)
mousemove = Subject()
frame = Frame(root, width... | Use ops instead of _ | Use ops instead of _
| Python | mit | ReactiveX/RxPY,ReactiveX/RxPY | ---
+++
@@ -1,7 +1,7 @@
from tkinter import Tk, Label, Frame
-from rx import from_
-from rx import operators as _
+import rx
+from rx import operators as ops
from rx.subjects import Subject
from rx.concurrency import TkinterScheduler
@@ -26,18 +26,18 @@
def handle_label(label, i):
label.config(di... |
2181d63c279965e4e694cae508a236f51d66d49b | data_structures/bitorrent/server/announce/torrent.py | data_structures/bitorrent/server/announce/torrent.py | import struct
import socket
import time
from trackpy.vendors.redis import redis
class Torrent(object):
def __init__(self, info_hash):
self.info = redis.hgetall(info_hash)
self.info_hash = info_hash
def can_announce(self, peer_id):
timestamp = int(redis.get("%s_%s" % (self.info_hash, peer_id)) or 0)
... | import struct
import socket
import time
from trackpy.vendors.redis import redis
class Torrent(object):
def __init__(self, info_hash):
self.info = redis.hgetall(info_hash)
self.info_hash = info_hash
def can_announce(self, peer_id):
timestamp = int(redis.get("%s_%s" % (self.info_hash, peer_id)) or 0)
... | Implement binary representation of peers | Implement binary representation of peers
| Python | apache-2.0 | vtemian/university_projects,vtemian/university_projects,vtemian/university_projects | ---
+++
@@ -32,8 +32,19 @@
@property
def seeders(self):
- return self.info['seeders'] if 'seeders' in self.info else []
+ return self.info['seeders'] if 'seeders' in self.info else 0
@property
def leechers(self):
- return self.info['leecher'] if 'leechers' in self.info else []
+ return sel... |
f52c1f6b91bf9d1748d4254b33634394ec07df3f | markups/common.py | markups/common.py | # This file is part of python-markups module
# License: BSD
# Copyright: (C) Dmitry Shachnev, 2012-2017
import os.path
# Some common constants and functions
(LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3)
CONFIGURATION_DIR = (os.getenv('XDG_CONFIG_HOME') or os.getenv('APPDATA') or
os.path.exp... | # This file is part of python-markups module
# License: BSD
# Copyright: (C) Dmitry Shachnev, 2012-2017
import os.path
# Some common constants and functions
(LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3)
CONFIGURATION_DIR = (os.getenv('XDG_CONFIG_HOME') or os.getenv('APPDATA') or
os.path.exp... | Update MathJax URL to 2.7.4 | Update MathJax URL to 2.7.4
| Python | bsd-3-clause | mitya57/pymarkups,retext-project/pymarkups | ---
+++
@@ -9,7 +9,7 @@
CONFIGURATION_DIR = (os.getenv('XDG_CONFIG_HOME') or os.getenv('APPDATA') or
os.path.expanduser('~/.config'))
MATHJAX_LOCAL_URL = 'file:///usr/share/javascript/mathjax/MathJax.js'
-MATHJAX_WEB_URL = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js'
+MATHJAX_WEB_URL = 'https... |
be958ec64ec82b2687376058c90ce2465bfbc84a | twitter_explorer/__init__.py | twitter_explorer/__init__.py | from application import app, db, bcrypt, login_manager
from utils import render_template, user_loader
from twitter_explorer.handlers import login, index, config
login_manager.login_view = 'login'
login_manager.user_loader(user_loader)
# Routes.
app.add_url_rule('/login', 'login', login.login, methods=['GET', 'POST... | from application import app, db, bcrypt, login_manager
from utils import render_template, user_loader
from twitter_explorer.handlers import login, index, config
login_manager.login_view = 'login'
login_manager.user_loader(user_loader)
# Routes.
app.add_url_rule('/login', 'login', login.login, methods=['GET', 'POST... | Index endpoint now accepts POST | Index endpoint now accepts POST
| Python | mit | ysenko/python-from-zero-to-hero,ysenko/python-from-zero-to-hero | ---
+++
@@ -13,7 +13,7 @@
app.add_url_rule('/signup', 'signup', login.register, methods=['GET', 'POST'])
app.add_url_rule('/logout', 'logout', login.logout, methods=['GET'])
app.add_url_rule('/config', 'config', config.config, methods=['GET', 'POST'])
-app.add_url_rule('/', 'index', index.index, methods=['GET'])
+... |
8b3ad1ea09c1fd8f2d433e79497eb51d9f32f4c7 | osversion.py | osversion.py | #!/usr/bin/env python3
# file: osversion.py
# vim:fileencoding=utf-8:fdm=marker:ft=python
#
# Author: R.F. Smith <rsmith@xs4all.nl>
# Created: 2018-04-06 22:34:00 +0200
# Last modified: 2018-07-06T22:54:44+0200
from ctypes import CDLL
with open('/usr/include/osreldate.h') as h:
lines = h.readlines()
line = [ln fo... | #!/usr/bin/env python3
# file: osversion.py
# vim:fileencoding=utf-8:fdm=marker:ft=python
#
# Author: R.F. Smith <rsmith@xs4all.nl>
# Created: 2018-04-06 22:34:00 +0200
# Last modified: 2018-08-19T14:18:16+0200
"""Print the __FreeBSD_version. This is also called OSVERSION in scripts."""
from ctypes import CDLL
import ... | Print a warning and exit when not run on FreeBSD. | Print a warning and exit when not run on FreeBSD.
| Python | mit | rsmith-nl/scripts,rsmith-nl/scripts | ---
+++
@@ -4,9 +4,15 @@
#
# Author: R.F. Smith <rsmith@xs4all.nl>
# Created: 2018-04-06 22:34:00 +0200
-# Last modified: 2018-07-06T22:54:44+0200
+# Last modified: 2018-08-19T14:18:16+0200
+"""Print the __FreeBSD_version. This is also called OSVERSION in scripts."""
from ctypes import CDLL
+import sys
+
+if 'f... |
d17f14b693d770618de559bd71a277c3771ccc8e | src/events/views.py | src/events/views.py | from django.http import Http404
from django.views.generic import DetailView, ListView, RedirectView
from proposals.models import TalkProposal
from .models import SponsoredEvent
class AcceptedTalkMixin:
queryset = (
TalkProposal.objects
.filter(accepted=True)
.select_related('submitter')
... | from django.http import Http404
from django.views.generic import DetailView, ListView, RedirectView
from proposals.models import TalkProposal
from .models import SponsoredEvent
class AcceptedTalkMixin:
queryset = (
TalkProposal.objects
.filter(accepted=True)
.select_related('submitter')
... | Make sponsored event redirect permanent (HTTP 301) | Make sponsored event redirect permanent (HTTP 301)
| Python | mit | pycontw/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016 | ---
+++
@@ -36,6 +36,9 @@
class SponsoredEventRedirectView(RedirectView):
+
+ permanent = True
+
def get_redirect_url(self, pk):
try:
event = SponsoredEvent.objects.get(pk=pk) |
8cbac87d73f361bd6d623cbe58d188dd9cc518ce | ext_pylib/input/__init__.py | ext_pylib/input/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
ext_pylib.input
~~~~~~~~~~~~~~~~
Functions for displaying and handling input on the terminal.
"""
from __future__ import absolute_import
# Use Python 3 input if possible
try:
INPUT = input
except NameError:
INPUT = raw_input
# pylint: disable=wrong-import-p... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
ext_pylib.input
~~~~~~~~~~~~~~~~
Functions for displaying and handling input on the terminal.
"""
from __future__ import absolute_import
# Use Python 2 input unless raw_input doesn't exist
try:
INPUT = raw_input
except NameError:
INPUT = input
# pylint: dis... | Use raw_input [py2] first, then resort to input [py3]. | BUGFIX: Use raw_input [py2] first, then resort to input [py3].
| Python | mit | hbradleyiii/ext_pylib | ---
+++
@@ -10,11 +10,11 @@
from __future__ import absolute_import
-# Use Python 3 input if possible
+# Use Python 2 input unless raw_input doesn't exist
try:
+ INPUT = raw_input
+except NameError:
INPUT = input
-except NameError:
- INPUT = raw_input
# pylint: disable=wrong-import-position
# this... |
99354752661828451732fdf317c5f2742a86733e | api/base/exceptions.py | api/base/exceptions.py |
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.view... |
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.view... | Change source to point to which part of the request caused the error, and add the specific reason to detail | Change source to point to which part of the request caused the error, and add the specific reason to detail
| Python | apache-2.0 | aaxelb/osf.io,brianjgeiger/osf.io,felliott/osf.io,chennan47/osf.io,mluo613/osf.io,crcresearch/osf.io,billyhunt/osf.io,asanfilippo7/osf.io,ticklemepierce/osf.io,kwierman/osf.io,samchrisinger/osf.io,brianjgeiger/osf.io,icereval/osf.io,RomanZWang/osf.io,Johnetordoff/osf.io,erinspace/osf.io,arpitar/osf.io,arpitar/osf.io,ab... | ---
+++
@@ -23,9 +23,9 @@
else:
if isinstance(value, list):
for reason in value:
- errors.append({'source': {key: reason}})
+ errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': ... |
0667b4b1c8660feb2c1bdf09562fe51700db620b | app/models/__init__.py | app/models/__init__.py | # Copyright (C) 2014 Linaro Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distribute... | # Copyright (C) 2014 Linaro Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distribute... | Add new status (unknown), and necessary build files. | Add new status (unknown), and necessary build files.
| Python | lgpl-2.1 | kernelci/kernelci-backend,joyxu/kernelci-backend,joyxu/kernelci-backend,kernelci/kernelci-backend,joyxu/kernelci-backend | ---
+++
@@ -24,3 +24,10 @@
DONE_STATUS = 'DONE'
FAILED_STATUS = 'FAILED'
SUCCESS_STATUS = 'SUCCESS'
+UNKNOWN_STATUS = 'UNKNOWN'
+
+# Build file names.
+DONE_FILE = '.done'
+BUILD_META_FILE = 'build.meta'
+BUILD_FAIL_FILE = 'build.FAIL'
+BUILD_PASS_FILE = 'build.PASS' |
624ded5833e25d6a51671255fd32208ff947b22f | sconsole/manager.py | sconsole/manager.py | # Import third party libs
import urwid
# Import sconsole libs
import sconsole.cmdbar
import sconsole.static
FOOTER = [
('title', 'Salt Console'), ' ',
('key', 'UP'), ' ',
('key', 'DOWN'), ' ']
class Manager(object):
def __init__(self, opts):
self.opts = opts
self.cmdba... | # Import third party libs
import urwid
# Import sconsole libs
import sconsole.cmdbar
import sconsole.static
FOOTER = [
('title', 'Salt Console'), ' ',
('key', 'UP'), ' ',
('key', 'DOWN'), ' ']
class Manager(object):
def __init__(self, opts):
self.opts = opts
self.cmdba... | Fix refs to body of sconsole | Fix refs to body of sconsole
| Python | apache-2.0 | saltstack/salt-console | ---
+++
@@ -16,10 +16,10 @@
self.opts = opts
self.cmdbar = sconsole.cmdbar.CommandBar(self.opts)
self.header = urwid.LineBox(urwid.Text(('banner', 'Salt Console'), align='center'))
- self.body = self.body()
+ self.body_frame = self.body()
self.footer = urwid.AttrMap(u... |
5b0e750c70759f79e6ea5dce051f1c29726ac71c | scoreboard/tests.py | scoreboard/tests.py | from django.test import TestCase
from django.utils import timezone as tz
from scoreboard.models import *
class GameUnitTests(TestCase):
@classmethod
def setUpClass(cls):
super(GameUnitTests, cls).setUpClass()
cls.home_team = Team.objects.create(name='Home')
cls.visiting_team = Team.ob... | from django.test import TestCase
from django.utils import timezone as tz
from scoreboard.models import *
class GameUnitTests(TestCase):
@classmethod
def setUpClass(cls):
super(GameUnitTests, cls).setUpClass()
cls.home_team = Team.objects.create(name='Home')
cls.visiting_team = Team.ob... | Fix failing test and add 2 more | Fix failing test and add 2 more
| Python | mit | jspitzen/lacrosse_scoreboard,jspitzen/lacrosse_scoreboard | ---
+++
@@ -16,4 +16,25 @@
self.assertEqual(0, self.game.home_score())
def test_away_score_zero(self):
+ self.assertEqual(0, self.game.visiting_score())
+
+ def test_home_score_one(self):
+ Goal.objects.create(game=self.game,
+ game_time_minutes=1,
+ ... |
a72b75f67753985a4559d4675393042d9d363a02 | media/sites/lapinkansa.py | media/sites/lapinkansa.py | import requests
from bs4 import BeautifulSoup
def nouda( url , out ):
r = requests.get( url )
r.encoding = 'UTF-8'
soup = BeautifulSoup( r.text )
teksti = soup.find_all( class_ ='Teksti' )
for string in teksti[0].stripped_strings:
out.write( string.encode('utf8') + ' ' )
if __name__ == '__main__':
... | import requests
from bs4 import BeautifulSoup
def nouda( url , out ):
r = requests.get( url )
r.encoding = 'UTF-8'
soup = BeautifulSoup( r.text )
teksti = soup.find_all( class_ ='post-meta' )
for string in teksti[0].stripped_strings:
out.write( string.encode('utf8') + ' ' )
if __name__ == '__main__'... | Fix to new page layout | Fix to new page layout
| Python | mit | HIIT/digivaalit-2015,HIIT/digivaalit-2015,HIIT/digivaalit-2015 | ---
+++
@@ -8,7 +8,7 @@
r.encoding = 'UTF-8'
soup = BeautifulSoup( r.text )
- teksti = soup.find_all( class_ ='Teksti' )
+ teksti = soup.find_all( class_ ='post-meta' )
for string in teksti[0].stripped_strings:
out.write( string.encode('utf8') + ' ' ) |
9387dfd4cc39fa6fbbf66147ced880dffa6408bd | keystone/server/flask/__init__.py | keystone/server/flask/__init__.py | # 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, software
# d... | # 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, software
# d... | Make keystone.server.flask more interesting for importing | Make keystone.server.flask more interesting for importing
Importing keystone.server.flask now exposes all the relevant bits
from the sub modules to develop APIs without needing to understand
all the underlying modules. __all__ has also be setup in a meaningful
way to allow for `from keystone.server.flask import *` and... | Python | apache-2.0 | openstack/keystone,openstack/keystone,mahak/keystone,openstack/keystone,mahak/keystone,mahak/keystone | ---
+++
@@ -10,11 +10,27 @@
# License for the specific language governing permissions and limitations
# under the License.
+# NOTE(morgan): Import relevant stuff so importing individual under-pinnings
+# isn't needed, keystone.server.flask exposes all the interesting bits
+# needed to develop restful APIs f... |
db374d1cc7188b4102ff727d5edfe458b6533584 | markdown_for_squirrel/__init__.py | markdown_for_squirrel/__init__.py | import markdown
def markdownify_content(context):
for article in context["articles"]:
article["content"] = markdown.markdown(article["content"])
return context
def inject_middlewares(middlewares):
middlewares.add("markdownify_content", markdownify_content)
return middlewares
| import markdown
import helpers
logger = helpers.get_logger(__name__)
def markdownify_content(context):
if context["is_called_from_cli"]:
arg_parser = context["arg_parser"]
args = arg_parser.parse_args()
if args.action == "generate":
for article in context["articles"]:
... | Fix markdown plugin so it's run only when needed | Fix markdown plugin so it's run only when needed
| Python | mit | daGrevis/squirrel | ---
+++
@@ -1,9 +1,25 @@
import markdown
+
+import helpers
+
+
+logger = helpers.get_logger(__name__)
def markdownify_content(context):
- for article in context["articles"]:
- article["content"] = markdown.markdown(article["content"])
+ if context["is_called_from_cli"]:
+
+ arg_parser = cont... |
0245952bacb6a2c7cd20fb7758d90301776c4ab4 | armstrong/apps/embedded_video/models.py | armstrong/apps/embedded_video/models.py | from armstrong.apps.content.models import Content
from armstrong.core.arm_content.mixins import AuthorsMixin
from armstrong.core.arm_content.mixins import EmbeddedVideoMixin
from armstrong.core.arm_content.fields import EmbeddedVideoField
from django.contrib.sites.models import Site
from django.db import models
from ... | from armstrong.apps.content.models import Content
from armstrong.core.arm_content.mixins import AuthorsMixin
from armstrong.core.arm_content.mixins import EmbeddedVideoMixin
from armstrong.core.arm_content.fields import EmbeddedVideoField
from django.db import models
from . import settings
class EmbeddedVideoBase(C... | Remove sites from explicitly being defined (thanks @niran for pointing it out) | Remove sites from explicitly being defined (thanks @niran for pointing it out)
| Python | apache-2.0 | armstrong/armstrong.apps.embedded_video | ---
+++
@@ -3,7 +3,6 @@
from armstrong.core.arm_content.mixins import EmbeddedVideoMixin
from armstrong.core.arm_content.fields import EmbeddedVideoField
-from django.contrib.sites.models import Site
from django.db import models
from . import settings
@@ -16,7 +15,6 @@
# TODO: screen cap thumbnail
... |
31ea614e783273ef14919d1628a7ada11e8850fd | apps/users/adapters.py | apps/users/adapters.py | import re
from allauth.account.adapter import DefaultAccountAdapter
from django.conf import settings
from apps.contrib.emails import Email
from apps.users import USERNAME_INVALID_MESSAGE
from apps.users import USERNAME_REGEX
class UserAccountEmail(Email):
def get_receivers(self):
return [self.object]
... | import re
from allauth.account.adapter import DefaultAccountAdapter
from django.conf import settings
from adhocracy4.emails.mixins import SyncEmailMixin
from apps.contrib.emails import Email
from apps.users import USERNAME_INVALID_MESSAGE
from apps.users import USERNAME_REGEX
class UserAccountEmail(Email, SyncEmail... | Use SyncEmailMixin for account mails | Use SyncEmailMixin for account mails
| Python | agpl-3.0 | liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin | ---
+++
@@ -3,12 +3,13 @@
from allauth.account.adapter import DefaultAccountAdapter
from django.conf import settings
+from adhocracy4.emails.mixins import SyncEmailMixin
from apps.contrib.emails import Email
from apps.users import USERNAME_INVALID_MESSAGE
from apps.users import USERNAME_REGEX
-class UserAc... |
f22476a36f2096628dc336f9adf0caa9a827dc11 | jfr_playoff/db.py | jfr_playoff/db.py | import sys
class PlayoffDB(object):
db_cursor = None
DATABASE_NOT_CONFIGURED_WARNING = 'WARNING: database not configured'
def __init__(self, settings):
reload(sys)
sys.setdefaultencoding("latin1")
import mysql.connector
self.database = mysql.connector.connect(
... | import sys
class PlayoffDB(object):
db_cursor = None
DATABASE_NOT_CONFIGURED_WARNING = 'WARNING: database not configured'
def __init__(self, settings):
reload(sys)
sys.setdefaultencoding("latin1")
import mysql.connector
self.database = mysql.connector.connect(
... | Fix for rethrowing mysql.connector.Error as IOError | Fix for rethrowing mysql.connector.Error as IOError
| Python | bsd-2-clause | emkael/jfrteamy-playoff,emkael/jfrteamy-playoff | ---
+++
@@ -29,9 +29,7 @@
row = self.db_cursor.fetchone()
return row
except mysql.connector.Error as e:
- raise IOError(
- message=str(e), filename=db_name,
- errno=e.errno, strerror=str(e))
+ raise IOError(e.errno, str(e), db_name... |
4b719f5c1f5e2e8923ce9d0fca4ffe849bf9ea79 | opps/article/urls.py | opps/article/urls.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
from django.conf.urls.defaults import patterns, url
from django.conf.urls import include
from opps.article.views import OppsDetail
urlpatterns = patterns('',
url(r'^redactor/', include('redactor.urls')),
url(r'^(?P<channel__slug_name>[0-9A-Za-z-_.//]+)... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
from django.conf.urls.defaults import patterns, url
from django.conf.urls import include
from opps.article.views import OppsDetail
urlpatterns = patterns('',
url(r'^redactor/', include('redactor.urls')),
url(r'(?P<channel__slug_name>[0-9A-Za-z-_.//]+)/... | Fix article url open new | Fix article url open new
| Python | mit | opps/opps,YACOWS/opps,opps/opps,williamroot/opps,opps/opps,YACOWS/opps,opps/opps,williamroot/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,williamroot/opps,jeanmask/opps,jeanmask/opps | ---
+++
@@ -10,6 +10,6 @@
urlpatterns = patterns('',
url(r'^redactor/', include('redactor.urls')),
- url(r'^(?P<channel__slug_name>[0-9A-Za-z-_.//]+)/(?P<slug>[\w-]+)$',
+ url(r'(?P<channel__slug_name>[0-9A-Za-z-_.//]+)/(?P<slug>[\w-]+)$',
OppsDetail.as_view(), name='home'),
) |
e3b0ccb529dca19bb3882f9caad82dbd965c9ae0 | onnx/__init__.py | onnx/__init__.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from .onnx_pb2 import *
import sys
def load(obj):
'''
Loads a binary protobuf that stores onnx graph
@params
Takes a file-like object (has to implement... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from .onnx_pb2 import *
import sys
def load(obj):
'''
Loads a binary protobuf that stores onnx graph
@params
Takes a file-like object (has "read" funct... | Fix string/file-like object detection in onnx.load | Fix string/file-like object detection in onnx.load
| Python | apache-2.0 | onnx/onnx,onnx/onnx,onnx/onnx,onnx/onnx | ---
+++
@@ -12,15 +12,14 @@
Loads a binary protobuf that stores onnx graph
@params
- Takes a file-like object (has to implement fileno that returns a file descriptor)
+ Takes a file-like object (has "read" function)
or a string containing a file name
@return ONNX ModelProto object
'''... |
c22528df06e821936590431db5ba1a424e16f6a0 | debug_toolbar/management/commands/debugsqlshell.py | debug_toolbar/management/commands/debugsqlshell.py | from datetime import datetime
from django.db.backends import util
import sqlparse
from debug_toolbar.utils import ms_from_timedelta
class PrintQueryWrapper(util.CursorDebugWrapper):
def execute(self, sql, params=()):
starttime = datetime.now()
try:
return self.cursor.execute(sql, pa... | from __future__ import print_function
from datetime import datetime
from django.db.backends import util
import sqlparse
from debug_toolbar.utils import ms_from_timedelta
class PrintQueryWrapper(util.CursorDebugWrapper):
def execute(self, sql, params=()):
starttime = datetime.now()
try:
... | Replace print statement by print function. | Replace print statement by print function.
| Python | bsd-3-clause | seperman/django-debug-toolbar,guilhermetavares/django-debug-toolbar,stored/django-debug-toolbar,sidja/django-debug-toolbar,Endika/django-debug-toolbar,guilhermetavares/django-debug-toolbar,megcunningham/django-debug-toolbar,pevzi/django-debug-toolbar,peap/django-debug-toolbar,django-debug-toolbar/django-debug-toolbar,C... | ---
+++
@@ -1,3 +1,5 @@
+from __future__ import print_function
+
from datetime import datetime
from django.db.backends import util
@@ -14,9 +16,9 @@
return self.cursor.execute(sql, params)
finally:
raw_sql = self.db.ops.last_executed_query(self.cursor, sql, params)
- ... |
371be140dfbecff72d72cda580cd299badc6bc15 | aws_list_all/client.py | aws_list_all/client.py | import boto3
_CLIENTS = {}
def get_regions_for_service(service, regions=()):
"""Given a service name, return a list of region names where this service can have resources,
restricted by a possible set of regions."""
if service == "s3":
return ['us-east-1'] # s3 ListBuckets is a global request, so... | import boto3
_CLIENTS = {}
def get_regions_for_service(service, regions=()):
"""Given a service name, return a list of region names where this service can have resources,
restricted by a possible set of regions."""
if service == "s3":
return ['us-east-1'] # s3 ListBuckets is a global request, so... | Use us-east-1 to query route53 | Use us-east-1 to query route53
Route53 is a global service so doesn't belong to a region, but the API endpoint is in us-east-1.
This makes various listings now work, but not record sets.
Updates #4.
| Python | mit | JohannesEbke/aws_list_all | ---
+++
@@ -8,6 +8,8 @@
restricted by a possible set of regions."""
if service == "s3":
return ['us-east-1'] # s3 ListBuckets is a global request, so no region required.
+ if service == "route53":
+ return ['us-east-1'] # route53 is a global service, but the endpoint is in us-east-1.
... |
945aba9548b92f57fc25f9996bfa9c3811e64deb | server/resources.py | server/resources.py | from flask import request
from flask_restful import Resource, Api, abort, reqparse
from .models import db, Comment, Lecture
api = Api()
class CommentListResource(Resource):
def get(self, lecture_id):
db_lecture = Lecture.query.filter(Lecture.id == lecture_id).first()
if not db_lecture:
... | from flask import request
from flask_restful import Resource, Api, abort, reqparse
from .models import db, Comment, Lecture
api = Api()
class CommentListResource(Resource):
def get(self, lecture_id):
db_lecture = Lecture.query.filter(Lecture.id == lecture_id).first()
if not db_lecture:
... | Change single Lecture query to use first() in stead of all() | Change single Lecture query to use first() in stead of all()
| Python | mit | MACSIFS/IFS,MACSIFS/IFS,MACSIFS/IFS,MACSIFS/IFS | ---
+++
@@ -24,9 +24,9 @@
}
def post(self, lecture_id):
- db_lectures = Lecture.query.filter(Lecture.id == lecture_id).all()
+ lecture = Lecture.query.filter(Lecture.id == lecture_id).first()
- if not db_lectures:
+ if not lecture:
abort(404, message="Lecture... |
8fb6f506bae11377ca3e3d040ce31d81eaa81d3e | localore/people/wagtail_hooks.py | localore/people/wagtail_hooks.py | from wagtailmodeladmin.options import ModelAdmin, wagtailmodeladmin_register
from .models import Person
class PeopleAdmin(ModelAdmin):
model = Person
menu_icon = 'group'
menu_label = 'Team'
menu_order = 300
list_display = ('full_name', 'production', 'role')
list_filter = ('role', 'production')... | from django.utils.html import format_html
from wagtailmodeladmin.options import ModelAdmin, wagtailmodeladmin_register
from .models import Person
class PeopleAdmin(ModelAdmin):
model = Person
menu_icon = 'group'
menu_label = 'Team'
menu_order = 300
list_display = ('profile_photo', 'full_name', '... | Add profile photos to list of people. | Add profile photos to list of people.
| Python | mpl-2.0 | ghostwords/localore,ghostwords/localore,ghostwords/localore | ---
+++
@@ -1,4 +1,7 @@
+from django.utils.html import format_html
+
from wagtailmodeladmin.options import ModelAdmin, wagtailmodeladmin_register
+
from .models import Person
@@ -7,13 +10,12 @@
menu_icon = 'group'
menu_label = 'Team'
menu_order = 300
- list_display = ('full_name', 'production'... |
1492d79dc422cb37ddf2dd66558bd954a0e08bfb | download-records-s3.py | download-records-s3.py | #!/usr/bin/python
import sys
import gzip
import datetime
import tempfile
import boto3
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
ch = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter('[%(levelname)s] %(asctime)s - %(message)s')
ch.setFormatter(formatter)
logger.addHandler... | #!/usr/bin/python
import sys
import gzip
import datetime
import tempfile
import boto3
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
ch = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter('[%(levelname)s] %(asctime)s - %(message)s')
ch.setFormatter(formatter)
logger.addHandler... | Fix string format for week numbers < 10 | Fix string format for week numbers < 10
| Python | mit | gertvv/ictrp-retrieval,gertvv/ictrp-retrieval | ---
+++
@@ -18,7 +18,7 @@
import download
def main():
- dataset = 'ictrp-raw-{}-w{}.xml.gz'.format(*datetime.datetime.today().isocalendar())
+ dataset = 'ictrp-raw-{}-w{:02d}.xml.gz'.format(*datetime.datetime.today().isocalendar())
idlist = listRecords.allList()
with tempfile.TemporaryFile() as tm... |
116735d900b9ad92ae8ad265e5478f232e1474be | cartesius/colors.py | cartesius/colors.py | # -*- coding: utf-8 -*-
""" Utility functions folr colors """
def get_color(color):
""" Can convert from integer to (r, g, b) """
if not color:
return None
if isinstance(color, int):
temp = color
blue = temp % 256
temp = temp / 256
green = temp % 256
temp... | # -*- coding: utf-8 -*-
""" Utility functions folr colors """
def get_color(color):
""" Can convert from integer to (r, g, b) """
if not color:
return None
if isinstance(color, int):
temp = color
blue = temp % 256
temp = int(temp / 256)
green = temp % 256
... | Fix for integer division error: | Fix for integer division error:
$ python3 create_images_and_readme.py
Processing <function test_circles at 0x10cda6400>
written: graph-0-0.png
written: graph-0-1.png
Processing <function test_piechart_1 at 0x10d1d4a60>
written: graph-1-0.png
written: graph-1-1.png
Processing <function test_piechart_2 at 0x10d1ed1e0>
w... | Python | apache-2.0 | tkrajina/cartesius,tkrajina/cartesius | ---
+++
@@ -11,10 +11,10 @@
temp = color
blue = temp % 256
- temp = temp / 256
+ temp = int(temp / 256)
green = temp % 256
- temp = temp / 256
+ temp = int(temp / 256)
red = temp % 256
return (red, green, blue) |
06d6f8d70d09214dbdcff2af2637deeb025cd22e | radar/radar/validation/family_histories.py | radar/radar/validation/family_histories.py | from radar.validation.groups import CohortGroupValidationMixin
from radar.validation.core import Field, Validation
from radar.validation.meta import MetaValidationMixin
from radar.validation.patients import PatientValidationMixin
from radar.validation.validators import required, none_if_blank, optional, max_length, in_... | from radar.validation.groups import CohortGroupValidationMixin
from radar.validation.core import Field, Validation
from radar.validation.meta import MetaValidationMixin
from radar.validation.patients import PatientValidationMixin
from radar.validation.validators import required, none_if_blank, optional, max_length, in_... | Clear relatives if no family history | Clear relatives if no family history
| Python | agpl-3.0 | renalreg/radar,renalreg/radar,renalreg/radar,renalreg/radar | ---
+++
@@ -17,3 +17,9 @@
family_history = Field([required()])
other_family_history = Field([none_if_blank(), optional(), max_length(10000)])
relatives = ListField(FamilyHistoryRelativeValidation())
+
+ def pre_validate(self, obj):
+ if not obj.family_history:
+ obj.relatives = []
... |
e94b3ad6c393d6758d6bc5c5ca2b7e59febf710c | solidity/python/constants/PrintExpScalingFactors.py | solidity/python/constants/PrintExpScalingFactors.py | from common import exp
MIN_PRECISION = 32
for n in [0.5,1.0,2.0,3.0]:
print ' uint256 constant SCALED_EXP_{} = 0x{:x};'.format(n,int(exp(n)*(1<<MIN_PRECISION))).replace('.','P')
print ' uint256 constant SCALED_VAL_{} = 0x{:x};'.format(n,int( (n)*(1<<MIN_PRECISION))).replace('.','P')
| from math import exp
MIN_PRECISION = 32
for n in [0.5,1.0,2.0,3.0]:
print ' uint256 constant SCALED_EXP_{} = 0x{:x};'.format(n,int(exp(n)*(1<<MIN_PRECISION))).replace('.','P')
print ' uint256 constant SCALED_VAL_{} = 0x{:x};'.format(n,int( (n)*(1<<MIN_PRECISION))).replace('.','P')
| Revert previous commit on this specific file (mistake). | Revert previous commit on this specific file (mistake).
| Python | apache-2.0 | enjin/contracts | ---
+++
@@ -1,4 +1,4 @@
-from common import exp
+from math import exp
MIN_PRECISION = 32 |
dbe5e67d2685083769e7d154926e6a1a234fa3c4 | src/livestreamer/stream.py | src/livestreamer/stream.py | from livestreamer.utils import urlopen
import pbs
class StreamError(Exception):
pass
class Stream(object):
def open(self):
raise NotImplementedError
class RTMPStream(Stream):
def __init__(self, params):
self.params = params or {}
def open(self):
try:
rtmpdump = pb... | from livestreamer.utils import urlopen
import os
import pbs
class StreamError(Exception):
pass
class Stream(object):
def open(self):
raise NotImplementedError
class RTMPStream(Stream):
def __init__(self, params):
self.params = params or {}
def open(self):
try:
rtm... | Fix rtmpdump locking up when stderr buffer is filled. | Fix rtmpdump locking up when stderr buffer is filled.
| Python | bsd-2-clause | charmander/livestreamer,sbstp/streamlink,wolftankk/livestreamer,bastimeyer/streamlink,caorong/livestreamer,breunigs/livestreamer,lyhiving/livestreamer,breunigs/livestreamer,okaywit/livestreamer,derrod/livestreamer,fishscene/streamlink,back-to/streamlink,streamlink/streamlink,wlerin/streamlink,melmorabity/streamlink,sbs... | ---
+++
@@ -1,5 +1,6 @@
from livestreamer.utils import urlopen
+import os
import pbs
class StreamError(Exception):
@@ -21,6 +22,7 @@
self.params["flv"] = "-"
self.params["_bg"] = True
+ self.params["_err"] = open(os.devnull, "w")
stream = rtmpdump(**self.params)
|
cf22defd6a705cab79bc24b82377e23b9d798dbf | nopassword/backends/base.py | nopassword/backends/base.py | # -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from nopassword.models import LoginCode
class NoPasswordBackend(ModelBackend):
def authenticate(self, request, u... | # -*- coding: utf-8 -*-
from datetime import timedelta
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from django.utils import timezone
from nopassword.models import LoginCode
class NoPasswordBackend(ModelBackend):
def authe... | Use timezone.now() instead of datetime.now() | fix: Use timezone.now() instead of datetime.now()
| Python | mit | relekang/django-nopassword,relekang/django-nopassword | ---
+++
@@ -1,9 +1,10 @@
# -*- coding: utf-8 -*-
-from datetime import datetime, timedelta
+from datetime import timedelta
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
+from django.utils import timezone
from nopassword.m... |
a5befe542e857ec36717f7f8da53ff9f2c2af7e6 | natasha/__init__.py | natasha/__init__.py | from copy import copy
from collections import deque
from yargy import FactParser
from natasha.grammars import Person, Geo
class Combinator(object):
DEFAULT_GRAMMARS = [
Person,
Geo,
]
def __init__(self, grammars=None, cache_size=50000):
self.grammars = grammars or self.DEFAULT_... | from copy import copy
from collections import deque
from yargy import FactParser
from natasha.grammars import Person, Geo, Money, Date
class Combinator(object):
DEFAULT_GRAMMARS = [
Money,
Person,
Geo,
Date,
]
def __init__(self, grammars=None, cache_size=50000):
... | Add new grammars to Combinator.DEFAULT_GRAMMARS | Add new grammars to Combinator.DEFAULT_GRAMMARS
| Python | mit | natasha/natasha | ---
+++
@@ -3,14 +3,16 @@
from yargy import FactParser
-from natasha.grammars import Person, Geo
+from natasha.grammars import Person, Geo, Money, Date
class Combinator(object):
DEFAULT_GRAMMARS = [
+ Money,
Person,
Geo,
+ Date,
]
def __init__(self, grammar... |
e382566a5a74a0eb2545456eb966cac569d5ebb4 | pylatex/numpy.py | pylatex/numpy.py | # -*- coding: utf-8 -*-
"""
pylatex.numpy
~~~~~~~~~~~~~
This module implements the classes that deals with numpy objects.
:copyright: (c) 2014 by Jelte Fennema.
:license: MIT, see License for more details.
"""
import numpy as np
from pylatex.base_classes import BaseLaTeXClass
from pylatex.package... | # -*- coding: utf-8 -*-
"""
pylatex.numpy
~~~~~~~~~~~~~
This module implements the classes that deals with numpy objects.
:copyright: (c) 2014 by Jelte Fennema.
:license: MIT, see License for more details.
"""
import numpy as np
from pylatex.base_classes import BaseLaTeXClass
from pylatex.package... | Fix bug in VectorName, caused by new Command arguments | Fix bug in VectorName, caused by new Command arguments
| Python | mit | JelteF/PyLaTeX,ovaskevich/PyLaTeX,bjodah/PyLaTeX,sebastianhaas/PyLaTeX,JelteF/PyLaTeX,votti/PyLaTeX,bjodah/PyLaTeX,jendas1/PyLaTeX,jendas1/PyLaTeX,sebastianhaas/PyLaTeX,votti/PyLaTeX,ovaskevich/PyLaTeX | ---
+++
@@ -17,7 +17,7 @@
class VectorName(Command):
def __init__(self, name):
- super().__init__('mathbf', argument=name)
+ super().__init__('mathbf', arguments=name)
class Matrix(BaseLaTeXClass): |
95bac0b68e271d7ad5a4f8fa22c441d18a65390c | client/serial_datagrams.py | client/serial_datagrams.py | import struct
from zlib import crc32
class CRCMismatchError(RuntimeError):
"""
Error raised when a datagram has an invalid CRC.
"""
pass
class FrameError(RuntimeError):
"""
Error raised when a datagram is too short to be valid.
"""
END = b'\xC0'
ESC = b'\xDB'
ESC_END = b'\xDC'
ESC_ESC = b... | import struct
from zlib import crc32
class CRCMismatchError(RuntimeError):
"""
Error raised when a datagram has an invalid CRC.
"""
pass
class FrameError(RuntimeError):
"""
Error raised when a datagram is too short to be valid.
"""
END = b'\xC0'
ESC = b'\xDB'
ESC_END = b'\xDC'
ESC_ESC = b... | Correct crc32 behaviour for all python versions. | Correct crc32 behaviour for all python versions.
This fixes signedness issue with crc32 from different python versions.
Was suggested in the documentation: https://docs.python.org/3.4/library/zlib.html
| Python | bsd-2-clause | cvra/can-bootloader,cvra/can-bootloader,cvra/can-bootloader,cvra/can-bootloader | ---
+++
@@ -22,7 +22,9 @@
Encodes the given datagram (bytes object) by adding a CRC at the end then an end marker.
It also escapes the end marker correctly.
"""
- data = data + struct.pack('>I', crc32(data))
+ # to generate same numeric value for all python versions
+ crc = crc32(data) & 0xfff... |
31c0863d088488da5dd85e2cbe3c01c6b01aa4a2 | system_tests/test_default.py | system_tests/test_default.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,... | Fix system tests when running on GCE | Fix system tests when running on GCE
The new project ID logic for Cloud SDK invokes Cloud SDK directly. Cloud SDK helpfully falls back to the GCE project ID if the project ID is unset in the configuration. This breaks one of our previous expectations.
| Python | apache-2.0 | googleapis/google-auth-library-python,googleapis/google-auth-library-python | ---
+++
@@ -24,7 +24,5 @@
if EXPECT_PROJECT_ID is not None:
assert project_id is not None
- else:
- assert project_id is None
verify_refresh(credentials) |
f042f6c9799d70edb41ae9495adf8bb78ed23e13 | elections/ar_elections_2015/settings.py | elections/ar_elections_2015/settings.py | # -*- coding: utf-8 -*-
ELECTION_RE = '(?P<election>diputados-argentina-paso-2015|gobernadores-argentina-paso-2015|senadores-argentina-paso-2015|presidentes-argentina-paso-2015)'
MAPIT_BASE_URL = 'http://argentina.mapit.staging.mysociety.org/'
SITE_OWNER = 'YoQuieroSaber'
COPYRIGHT_HOLDER = 'YoQuieroSaber'
| # -*- coding: utf-8 -*-
ELECTION_RE = '(?P<election>diputados-argentina-paso-2015|gobernadores-argentina-paso-2015|senadores-argentina-paso-2015|presidentes-argentina-paso-2015|parlamentarios-mercosur-regional-paso-2015|parlamentarios-mercosur-unico-paso-2015)'
MAPIT_BASE_URL = 'http://argentina.mapit.staging.mysociet... | Add some missing election slugs to Argentina's ELECTION_RE | AR: Add some missing election slugs to Argentina's ELECTION_RE
| Python | agpl-3.0 | mysociety/yournextmp-popit,DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,neavouli/yournextrepresentative,neavouli/yournextrepresentative,neavouli/yournextrepresentative,DemocracyClub/yournextrepresentative,mysociety/yournextmp-popit,datamade/yournextmp-popit,neavouli/y... | ---
+++
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
-ELECTION_RE = '(?P<election>diputados-argentina-paso-2015|gobernadores-argentina-paso-2015|senadores-argentina-paso-2015|presidentes-argentina-paso-2015)'
+ELECTION_RE = '(?P<election>diputados-argentina-paso-2015|gobernadores-argentina-paso-2015|senadores-argentina... |
cf6c18925c05a6f009573c204631a09ed1957227 | mama_cas/utils.py | mama_cas/utils.py | import urllib
import urlparse
def add_query_params(url, params):
"""
Inject additional query parameters into an existing URL. If
existing parameters already exist with the same name, they
will be overwritten.
Return the modified URL as a string.
"""
# If any of the additional parameters h... | import urllib
import urlparse
def add_query_params(url, params):
"""
Inject additional query parameters into an existing URL. If
parameters already exist with the same name, they will be
overwritten. Return the modified URL as a string.
"""
# If any of the additional parameters have empty valu... | Tweak comment text for clarity | Tweak comment text for clarity
| Python | bsd-3-clause | harlov/django-mama-cas,harlov/django-mama-cas,jbittel/django-mama-cas,orbitvu/django-mama-cas,jbittel/django-mama-cas,orbitvu/django-mama-cas,forcityplatform/django-mama-cas,forcityplatform/django-mama-cas | ---
+++
@@ -5,10 +5,8 @@
def add_query_params(url, params):
"""
Inject additional query parameters into an existing URL. If
- existing parameters already exist with the same name, they
- will be overwritten.
-
- Return the modified URL as a string.
+ parameters already exist with the same name,... |
65504fbb13a61e36f1fe0ea9fcc790efdf7d8fd6 | resolwe/__about__.py | resolwe/__about__.py | """Central place for package metadata."""
# NOTE: We use __title__ instead of simply __name__ since the latter would
# interfere with a global variable __name__ denoting object's name.
__title__ = 'resolwe'
__summary__ = 'Open source enterprise dataflow engine in Django'
__url__ = 'https://github.com/genialis/re... | """Central place for package metadata."""
# NOTE: We use __title__ instead of simply __name__ since the latter would
# interfere with a global variable __name__ denoting object's name.
__title__ = 'resolwe'
__summary__ = 'Open source enterprise dataflow engine in Django'
__url__ = 'https://github.com/genialis/re... | Change author in about file | Change author in about file
| Python | apache-2.0 | genialis/resolwe,jberci/resolwe,jberci/resolwe,genialis/resolwe | ---
+++
@@ -10,7 +10,7 @@
# https://packaging.python.org/en/latest/distributing/#semantic-versioning-preferred
__version__ = '10.2.0a2'
-__author__ = 'Genialis d.o.o.'
+__author__ = 'Genialis, Inc.'
__email__ = 'dev-team@genialis.com'
__license__ = 'Apache License (2.0)' |
81235c83c094e3dbca62f19d13c83a002d01da99 | bokeh/mixins.py | bokeh/mixins.py | """Classes that can be mixed-in to HasProps classes to get them the corresponding attributes. """
from .properties import HasProps, ColorSpec, DataSpec, Enum, DashPattern, Int, String
from .enums import LineJoin, LineCap, FontStyle, TextAlign, TextBaseline
class FillProps(HasProps):
""" Mirrors the BokehJS proper... | """Classes that can be mixed-in to HasProps classes to get them the corresponding attributes. """
from .properties import HasProps, ColorSpec, DataSpec, Enum, DashPattern, Int, String
from .enums import LineJoin, LineCap, FontStyle, TextAlign, TextBaseline
class FillProps(HasProps):
""" Mirrors the BokehJS proper... | Unify bokeh's text properties' values with bokehjs | Unify bokeh's text properties' values with bokehjs
| Python | bsd-3-clause | eteq/bokeh,jakirkham/bokeh,Karel-van-de-Plassche/bokeh,caseyclements/bokeh,bokeh/bokeh,xguse/bokeh,timothydmorton/bokeh,azjps/bokeh,ptitjano/bokeh,timothydmorton/bokeh,canavandl/bokeh,alan-unravel/bokeh,ahmadia/bokeh,eteq/bokeh,stuart-knock/bokeh,CrazyGuo/bokeh,ChristosChristofidis/bokeh,percyfal/bokeh,aavanian/bokeh,l... | ---
+++
@@ -21,9 +21,9 @@
class TextProps(HasProps):
""" Mirrors the BokehJS properties.text_properties class """
text_font = String("Helvetica")
- text_font_size = String("10pt")
+ text_font_size = String("12pt")
text_font_style = Enum(FontStyle)
- text_color = ColorSpec("black")
+ text_c... |
e081646028e4f3283fb9c7278fed89c3e42cc4d3 | server/tests/api/test_user_api.py | server/tests/api/test_user_api.py | import json
from tests.helpers import FlaskTestCase, fixtures
class TestUserAPI(FlaskTestCase):
@fixtures('base.json')
def test_get_empty_users(self):
"""Test GET /api/users endpoint with no data"""
response = self.test_client.get('/api/users')
assert response.status_code is 200
... | import json
from tests.helpers import FlaskTestCase, fixtures
class TestUserAPI(FlaskTestCase):
@fixtures('base.json')
def test_get_empty_users(self):
"""Test GET /api/users endpoint with no data"""
response, data = self.api_request('get', '/api/users')
assert data['num_results'] is 0... | Implement tests for getting empty users list and single user list | Implement tests for getting empty users list and single user list
| Python | mit | ganemone/ontheside,ganemone/ontheside,ganemone/ontheside | ---
+++
@@ -7,18 +7,26 @@
@fixtures('base.json')
def test_get_empty_users(self):
"""Test GET /api/users endpoint with no data"""
- response = self.test_client.get('/api/users')
+ response, data = self.api_request('get', '/api/users')
+ assert data['num_results'] is 0
a... |
962f26299a7038879eb1efeb8f16b0801fd9a04a | glitter/assets/apps.py | glitter/assets/apps.py | # -*- coding: utf-8 -*-
from django.apps import AppConfig
class GlitterBasicAssetsConfig(AppConfig):
name = 'glitter.assets'
label = 'glitter_assets'
def ready(self):
super(GlitterBasicAssetsConfig, self).ready()
from . import listeners # noqa
| # -*- coding: utf-8 -*-
from django.apps import AppConfig
class GlitterBasicAssetsConfig(AppConfig):
name = 'glitter.assets'
label = 'glitter_assets'
verbose_name = 'Assets'
def ready(self):
super(GlitterBasicAssetsConfig, self).ready()
from . import listeners # noqa
| Improve verbose name for assets | Improve verbose name for assets
| Python | bsd-3-clause | blancltd/django-glitter,blancltd/django-glitter,developersociety/django-glitter,blancltd/django-glitter,developersociety/django-glitter,developersociety/django-glitter | ---
+++
@@ -6,6 +6,7 @@
class GlitterBasicAssetsConfig(AppConfig):
name = 'glitter.assets'
label = 'glitter_assets'
+ verbose_name = 'Assets'
def ready(self):
super(GlitterBasicAssetsConfig, self).ready() |
5dfc8a9b759e2106cfa33d13f736b27fddee9079 | influxdb_metrics/loader.py | influxdb_metrics/loader.py | """Loads celery or non-celery version."""
from django.conf import settings
try:
from .tasks import write_points as write_points_celery
except Exception:
write_points_celery = None
from .utils import write_points as write_points_normal
write_points = None
if getattr(settings, 'INFLUXDB_USE_CELERY', False):
... | """Loads celery or non-celery version."""
from django.conf import settings
try:
from .tasks import write_points as write_points_celery
except ImportError:
write_points_celery = None
from .utils import write_points as write_points_normal
write_points = None
if getattr(settings, 'INFLUXDB_USE_CELERY', False):
... | Fix to not silently swallow all Exceptions. | Fix to not silently swallow all Exceptions.
Great lib, thanks! | Python | mit | bitmazk/django-influxdb-metrics,bitlabstudio/django-influxdb-metrics,bitlabstudio/django-influxdb-metrics,bitmazk/django-influxdb-metrics | ---
+++
@@ -3,7 +3,7 @@
try:
from .tasks import write_points as write_points_celery
-except Exception:
+except ImportError:
write_points_celery = None
from .utils import write_points as write_points_normal |
28f504dccd02046604761e997f929015a285dffd | pyQuantuccia/tests/test_get_holiday_date.py | pyQuantuccia/tests/test_get_holiday_date.py | from datetime import date
import calendar
print(calendar.__dir__())
print(calendar.__dict__)
def test_united_kingdom_is_business_day():
""" Check a single day to see that we
can identify holidays.
"""
assert(calendar.united_kingdom_is_business_day(date(2017, 4, 17)) is False)
| from datetime import date
import calendar
def test_foo():
assert(calendar.__dir__() == "")
def test_dummy():
assert(calendar.__dict__ == "")
def test_united_kingdom_is_business_day():
""" Check a single day to see that we
can identify holidays.
"""
assert(calendar.united_kingdom_is_busine... | Add some bogus tests to try and get this info. | Add some bogus tests to try and get this info.
| Python | bsd-3-clause | jwg4/pyQuantuccia,jwg4/pyQuantuccia | ---
+++
@@ -2,8 +2,13 @@
import calendar
-print(calendar.__dir__())
-print(calendar.__dict__)
+
+def test_foo():
+ assert(calendar.__dir__() == "")
+
+
+def test_dummy():
+ assert(calendar.__dict__ == "")
def test_united_kingdom_is_business_day(): |
fea4f04abc18b8dcf4970a1f338a8d610f04260d | src/pytz/tests/test_docs.py | src/pytz/tests/test_docs.py | #!/usr/bin/env python
# -*- coding: ascii -*-
import unittest, os, os.path, sys
from doctest import DocFileSuite
sys.path.insert(0, os.path.join(os.pardir, os.pardir))
locs = [
'README.txt',
os.path.join(os.pardir, 'README.txt'),
os.path.join(os.pardir, os.pardir, 'README.txt'),
]
README = None
for lo... | #!/usr/bin/env python
# -*- coding: ascii -*-
import unittest, os, os.path, sys
from doctest import DocFileSuite
sys.path.insert(0, os.path.join(os.pardir, os.pardir))
locs = [
'README.txt',
os.path.join(os.pardir, 'README.txt'),
os.path.join(os.pardir, os.pardir, 'README.txt'),
]
README = None
for lo... | Add a test_suite method as used by the Zope3 test runner | Add a test_suite method as used by the Zope3 test runner | Python | mit | stub42/pytz,stub42/pytz,stub42/pytz,stub42/pytz | ---
+++
@@ -18,6 +18,9 @@
if README is None:
raise RuntimeError("Can't locate README.txt")
+def test_suite():
+ return README
+
if __name__ == '__main__':
unittest.main(defaultTest='README')
|
c3c0bf614e046f4640d123f801739fc7ea0d7cac | salt/states/salt_proxy.py | salt/states/salt_proxy.py | # -*- coding: utf-8 -*-
'''
Salt proxy state
.. versionadded:: 2015.8.2
State to deploy and run salt-proxy processes
on a minion.
Set up pillar data for your proxies per the documentation.
Run the state as below
..code-block:: yaml
salt-proxy-configure:
salt_proxy.c... | # -*- coding: utf-8 -*-
'''
Salt proxy state
.. versionadded:: 2015.8.2
State to deploy and run salt-proxy processes
on a minion.
Set up pillar data for your proxies per the documentation.
Run the state as below
..code-block:: yaml
salt-proxy-configure:
salt_proxy.c... | Add example to function docstring | Add example to function docstring
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -42,6 +42,16 @@
Name to be used for this proxy (should match entries in pillar)
start:
Boolean indicating if the process should be started
+
+ Example:
+
+ ..code-block:: yaml
+
+ salt-proxy-configure:
+ salt_proxy.configure_proxy:
+ ... |
dd63ef92e14a3111fd0914e9994aaea9ebd4e668 | hcalendar/hcalendar.py | hcalendar/hcalendar.py | import bs4
from vcalendar import vCalendar
class hCalendar(object):
def __init__(self, markup, value=None, key='id'):
self._soup = bs4.BeautifulSoup(markup)
if value:
self._soup = self._soup.find(**{key: value})
self._cals = self._soup.findAll(attrs='vcalendar')
... | from vcalendar import vCalendar
from bs4 import BeautifulSoup
class hCalendar(object):
def __init__(self, markup, value=None, key='id'):
if isinstance(markup, BeautifulSoup):
self._soup = markup
else:
self._soup = BeautifulSoup(markup)
if value:
... | Allow BeautifulSoup object being passed into hCalendar | Allow BeautifulSoup object being passed into hCalendar
| Python | mit | mback2k/python-hcalendar | ---
+++
@@ -1,9 +1,12 @@
-import bs4
from vcalendar import vCalendar
+from bs4 import BeautifulSoup
class hCalendar(object):
def __init__(self, markup, value=None, key='id'):
- self._soup = bs4.BeautifulSoup(markup)
+ if isinstance(markup, BeautifulSoup):
+ self._soup = markup
+ ... |
a773b1aa98a96b6335b76fc587ea714e5cca7545 | cle/relocations/mips.py | cle/relocations/mips.py | from . import generic
arch = 'MIPS32'
R_MIPS_32 = generic.GenericAbsoluteAddendReloc
R_MIPS_REL32 = generic.GenericRelativeReloc
R_MIPS_TLS_DTPMOD32 = generic.GenericTLSModIdReloc
R_MIPS_TLS_TPREL32 = generic.GenericTLSOffsetReloc
R_MIPS_TLS_DTPREL32 = generic.GenericTLSDoffsetReloc
| from . import generic
arch = 'MIPS32'
R_MIPS_32 = generic.GenericAbsoluteAddendReloc
R_MIPS_REL32 = generic.GenericRelativeReloc
R_MIPS_TLS_DTPMOD32 = generic.GenericTLSModIdReloc
R_MIPS_TLS_TPREL32 = generic.GenericTLSOffsetReloc
R_MIPS_TLS_DTPREL32 = generic.GenericTLSDoffsetReloc
R_MIPS_JUMP_SLOT = generic.Generic... | Add R_MIPS_JUMP_SLOT and R_MIPS_GLOB_DAT relocations | Add R_MIPS_JUMP_SLOT and R_MIPS_GLOB_DAT relocations
| Python | bsd-2-clause | chubbymaggie/cle,angr/cle | ---
+++
@@ -7,3 +7,5 @@
R_MIPS_TLS_DTPMOD32 = generic.GenericTLSModIdReloc
R_MIPS_TLS_TPREL32 = generic.GenericTLSOffsetReloc
R_MIPS_TLS_DTPREL32 = generic.GenericTLSDoffsetReloc
+R_MIPS_JUMP_SLOT = generic.GenericAbsoluteReloc
+R_MIPS_GLOB_DAT = generic.GenericAbsoluteReloc |
5863cbf81156074df4e0a9abb7a823a7701933da | tlsenum/__init__.py | tlsenum/__init__.py | import click
CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"])
@click.command(context_settings=CONTEXT_SETTINGS)
@click.argument("host", type=click.STRING)
@click.argument("port", type=click.INT)
@click.option("--verify-cert", is_flag=True)
def cli(host, port, verify_cert):
"""
A command line tool... | import socket
import click
from construct import UBInt16
from tlsenum.parse_hello import (
ClientHello, Extensions, HandshakeFailure, ServerHello
)
from tlsenum.mappings import CipherSuites, ECCurves, ECPointFormat
CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"])
def send_client_hello(host, port, d... | Add very basic logic to figure out supported cipher suites. | Add very basic logic to figure out supported cipher suites.
| Python | mit | Ayrx/tlsenum,Ayrx/tlsenum | ---
+++
@@ -1,7 +1,32 @@
+import socket
+
import click
+from construct import UBInt16
+
+from tlsenum.parse_hello import (
+ ClientHello, Extensions, HandshakeFailure, ServerHello
+)
+from tlsenum.mappings import CipherSuites, ECCurves, ECPointFormat
CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"]... |
f6d54387a620020e3766ca9f2528b5b4af41e9c1 | tests/unit/tornado_tests.py | tests/unit/tornado_tests.py | """
Tests for pika.adapters.tornado_connection
"""
import unittest
import mock
from pika.adapters import tornado_connection
class TornadoConnectionTests(unittest.TestCase):
@mock.patch('pika.adapters.base_connection.BaseConnection.__init__')
def test_tornado_connection_call_parent(self, mock_init):
... | """
Tests for pika.adapters.tornado_connection
"""
import unittest
import mock
from pika.adapters import tornado_connection
class TornadoConnectionTests(unittest.TestCase):
@mock.patch('pika.adapters.base_connection.BaseConnection.__init__')
def test_tornado_connection_call_parent(self, mock_init):
... | Revert "Fixed check in test_tornado_connection_call_parent." accidentally committed to wrong branch | Revert "Fixed check in test_tornado_connection_call_parent." accidentally committed to wrong branch
This reverts commit 3ca1365eafa63712e6d0dca7f5d6aa134f05d580.
| Python | bsd-3-clause | pika/pika,vitaly-krugl/pika | ---
+++
@@ -15,4 +15,4 @@
obj = tornado_connection.TornadoConnection()
mock_init.assert_called_once_with(
None, None, None, None,
- tornado_connection.ioloop.IOLoop.instance())
+ tornado_connection.ioloop.IOLoop.instance(), False) |
157d427646ccee414503089e7080b92335848803 | floq/helpers.py | floq/helpers.py | def n_to_i(num, n):
"""
Translate num, ranging from
-(n-1)/2 through (n-1)/2
into an index i from 0 to n-1
If num > (n-1)/2, map it into the interval
This is necessary to translate from a physical
Fourier mode number to an index in an array.
"""
cutoff = (n-1)/2
if num > cutoff... | def n_to_i(num, n):
"""
Translate num, ranging from
-(n-1)/2 through (n-1)/2
into an index i from 0 to n-1
If num > (n-1)/2, map it into the interval
This is necessary to translate from a physical
Fourier mode number to an index in an array.
"""
cutoff = (n-1)/2
return (num+cut... | Implement rollover correctly and a lot more concisely | Implement rollover correctly and a lot more concisely
| Python | mit | sirmarcel/floq | ---
+++
@@ -10,12 +10,7 @@
Fourier mode number to an index in an array.
"""
cutoff = (n-1)/2
- if num > cutoff:
- return (num % n)-n+cutoff
- if num < -cutoff:
- return -(-num % n)+n+cutoff
- else:
- return num+cutoff
+ return (num+cutoff) % n
def i_to_n(i, n): |
610ada5f26d7421c2b0dd16a8a14ac9c95e4ed8c | config/test/__init__.py | config/test/__init__.py | from SCons.Script import *
def run_tests(env):
import shlex
import subprocess
import sys
sys.exit(subprocess.call(shlex.split(env.get('TEST_COMMAND'))))
def generate(env):
import os
import distutils.spawn
python = distutils.spawn.find_executable('python3')
if not python: python = d... | from SCons.Script import *
def run_tests(env):
import shlex
import subprocess
import sys
cmd = shlex.split(env.get('TEST_COMMAND'))
print('Executing:', cmd)
sys.exit(subprocess.call(cmd))
def generate(env):
import os
import distutils.spawn
python = distutils.spawn.find_executab... | Fix "test" target in Windows | Fix "test" target in Windows
| Python | lgpl-2.1 | CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang | ---
+++
@@ -6,7 +6,9 @@
import subprocess
import sys
- sys.exit(subprocess.call(shlex.split(env.get('TEST_COMMAND'))))
+ cmd = shlex.split(env.get('TEST_COMMAND'))
+ print('Executing:', cmd)
+ sys.exit(subprocess.call(cmd))
def generate(env):
@@ -16,6 +18,8 @@
python = distutils.spaw... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.