commit
stringlengths 40
40
| old_file
stringlengths 4
118
| new_file
stringlengths 4
118
| old_contents
stringlengths 10
2.94k
| new_contents
stringlengths 21
3.18k
| subject
stringlengths 16
444
| message
stringlengths 17
2.63k
| lang
stringclasses 1
value | license
stringclasses 13
values | repos
stringlengths 5
43k
| ndiff
stringlengths 51
3.32k
| instruction
stringlengths 16
444
| content
stringlengths 133
4.32k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
b457eac63690deba408c4b5bdc1db179347f43da | postgres/fields/uuid_field.py | postgres/fields/uuid_field.py | from __future__ import unicode_literals
import uuid
from django.core.exceptions import ValidationError
from django.db import models
from django.utils import six
from django.utils.translation import ugettext_lazy as _
from psycopg2.extras import register_uuid
register_uuid()
class UUIDField(six.with_metaclass(models.SubfieldBase, models.Field)):
"""
We can make use of psycopg2's uuid handling: that means everything
at the database end will be a uuid.
We also make sure that values assigned to this field on a model
will automatically be cast to UUID.
"""
description = "UUID"
default_error_messages = {
'invalid': _("'%(value)s' is not a valid UUID."),
}
def get_internal_type(self):
return 'UUIDField'
def db_type(self, connection):
return 'uuid'
def to_python(self, value):
if isinstance(value, six.string_types):
try:
return uuid.UUID(value)
except ValueError:
raise ValidationError(
self.error_messages['invalid'],
code='invalid',
params={'value': value}
)
return value
| from __future__ import unicode_literals
import uuid
from django.core.exceptions import ValidationError
from django.db import models
from django.utils import six
from django.utils.translation import ugettext_lazy as _
from psycopg2.extras import register_uuid
register_uuid()
class UUIDField(six.with_metaclass(models.SubfieldBase, models.Field)):
"""
We can make use of psycopg2's uuid handling: that means everything
at the database end will be a uuid.
We also make sure that values assigned to this field on a model
will automatically be cast to UUID.
"""
description = "UUID"
default_error_messages = {
'invalid': _("'%(value)s' is not a valid UUID."),
}
def __init__(self, **kwargs):
kwargs['max_length'] = 36
super(UUIDField, self).__init__(**kwargs)
def get_internal_type(self):
return 'UUIDField'
def db_type(self, connection):
return 'uuid'
def to_python(self, value):
if not value:
return None
if isinstance(value, six.string_types):
try:
return uuid.UUID(value)
except ValueError:
raise ValidationError(
self.error_messages['invalid'],
code='invalid',
params={'value': value}
)
return value
| Make UUIDField have a fixed max-length | Make UUIDField have a fixed max-length
| Python | bsd-3-clause | wlanslovenija/django-postgres | from __future__ import unicode_literals
import uuid
from django.core.exceptions import ValidationError
from django.db import models
from django.utils import six
from django.utils.translation import ugettext_lazy as _
from psycopg2.extras import register_uuid
register_uuid()
class UUIDField(six.with_metaclass(models.SubfieldBase, models.Field)):
"""
We can make use of psycopg2's uuid handling: that means everything
at the database end will be a uuid.
We also make sure that values assigned to this field on a model
will automatically be cast to UUID.
"""
description = "UUID"
default_error_messages = {
'invalid': _("'%(value)s' is not a valid UUID."),
}
+ def __init__(self, **kwargs):
+ kwargs['max_length'] = 36
+ super(UUIDField, self).__init__(**kwargs)
+
def get_internal_type(self):
return 'UUIDField'
def db_type(self, connection):
return 'uuid'
def to_python(self, value):
+ if not value:
+ return None
+
if isinstance(value, six.string_types):
try:
return uuid.UUID(value)
except ValueError:
raise ValidationError(
self.error_messages['invalid'],
code='invalid',
params={'value': value}
)
return value
| Make UUIDField have a fixed max-length | ## Code Before:
from __future__ import unicode_literals
import uuid
from django.core.exceptions import ValidationError
from django.db import models
from django.utils import six
from django.utils.translation import ugettext_lazy as _
from psycopg2.extras import register_uuid
register_uuid()
class UUIDField(six.with_metaclass(models.SubfieldBase, models.Field)):
"""
We can make use of psycopg2's uuid handling: that means everything
at the database end will be a uuid.
We also make sure that values assigned to this field on a model
will automatically be cast to UUID.
"""
description = "UUID"
default_error_messages = {
'invalid': _("'%(value)s' is not a valid UUID."),
}
def get_internal_type(self):
return 'UUIDField'
def db_type(self, connection):
return 'uuid'
def to_python(self, value):
if isinstance(value, six.string_types):
try:
return uuid.UUID(value)
except ValueError:
raise ValidationError(
self.error_messages['invalid'],
code='invalid',
params={'value': value}
)
return value
## Instruction:
Make UUIDField have a fixed max-length
## Code After:
from __future__ import unicode_literals
import uuid
from django.core.exceptions import ValidationError
from django.db import models
from django.utils import six
from django.utils.translation import ugettext_lazy as _
from psycopg2.extras import register_uuid
register_uuid()
class UUIDField(six.with_metaclass(models.SubfieldBase, models.Field)):
"""
We can make use of psycopg2's uuid handling: that means everything
at the database end will be a uuid.
We also make sure that values assigned to this field on a model
will automatically be cast to UUID.
"""
description = "UUID"
default_error_messages = {
'invalid': _("'%(value)s' is not a valid UUID."),
}
def __init__(self, **kwargs):
kwargs['max_length'] = 36
super(UUIDField, self).__init__(**kwargs)
def get_internal_type(self):
return 'UUIDField'
def db_type(self, connection):
return 'uuid'
def to_python(self, value):
if not value:
return None
if isinstance(value, six.string_types):
try:
return uuid.UUID(value)
except ValueError:
raise ValidationError(
self.error_messages['invalid'],
code='invalid',
params={'value': value}
)
return value
|
89fe38163426efe02da92974bac369538ab5532f | elmextensions/__init__.py | elmextensions/__init__.py | from .sortedlist import *
from .embeddedterminal import *
from .aboutwindow import *
from .fileselector import *
from .tabbedbox import *
from .StandardButton import *
from .StandardPopup import *
from .SearchableList import *
| from .sortedlist import *
from .embeddedterminal import *
from .aboutwindow import *
from .fileselector import *
from .fontselector import *
from .tabbedbox import *
from .StandardButton import *
from .StandardPopup import *
from .SearchableList import *
__copyright__ = "Copyright 2015-2017 Jeff Hoogland"
__license__ = "BSD-3-clause"
# the version number: major, minor, micro, releaselevel, and serial.
__version__ = "0.2.1rc.2"
version_string = __version__
| Access to module level information | Access to module level information | Python | bsd-3-clause | JeffHoogland/python-elm-extensions | from .sortedlist import *
from .embeddedterminal import *
from .aboutwindow import *
from .fileselector import *
+ from .fontselector import *
from .tabbedbox import *
from .StandardButton import *
from .StandardPopup import *
from .SearchableList import *
+ __copyright__ = "Copyright 2015-2017 Jeff Hoogland"
+ __license__ = "BSD-3-clause"
+
+ # the version number: major, minor, micro, releaselevel, and serial.
+ __version__ = "0.2.1rc.2"
+ version_string = __version__
+ | Access to module level information | ## Code Before:
from .sortedlist import *
from .embeddedterminal import *
from .aboutwindow import *
from .fileselector import *
from .tabbedbox import *
from .StandardButton import *
from .StandardPopup import *
from .SearchableList import *
## Instruction:
Access to module level information
## Code After:
from .sortedlist import *
from .embeddedterminal import *
from .aboutwindow import *
from .fileselector import *
from .fontselector import *
from .tabbedbox import *
from .StandardButton import *
from .StandardPopup import *
from .SearchableList import *
__copyright__ = "Copyright 2015-2017 Jeff Hoogland"
__license__ = "BSD-3-clause"
# the version number: major, minor, micro, releaselevel, and serial.
__version__ = "0.2.1rc.2"
version_string = __version__
|
f517442097b6ae12eb13b16f2fa6ca40a00b9998 | __init__.py | __init__.py | from .features import Giraffe_Feature_Base
from .features import Aligned_Feature
| from .features import Giraffe_Feature_Base
from .features import Aligned_Feature
from .features import Feature_Type_Choices
| Move Feature_Type_Choices to toplevel name sapce | Move Feature_Type_Choices to toplevel name sapce
| Python | mit | benjiec/giraffe-features | from .features import Giraffe_Feature_Base
from .features import Aligned_Feature
+ from .features import Feature_Type_Choices
| Move Feature_Type_Choices to toplevel name sapce | ## Code Before:
from .features import Giraffe_Feature_Base
from .features import Aligned_Feature
## Instruction:
Move Feature_Type_Choices to toplevel name sapce
## Code After:
from .features import Giraffe_Feature_Base
from .features import Aligned_Feature
from .features import Feature_Type_Choices
|
5a8788222d9a5765bf66a2c93eed25ca7879c856 | __init__.py | __init__.py | import inspect
import sys
if sys.version_info[0] == 2:
from .python2 import httplib2
else:
from .python3 import httplib2
globals().update(inspect.getmembers(httplib2))
| import os
import sys
path = os.path.dirname(__file__)+os.path.sep+'python'+str(sys.version_info[0])
sys.path.insert(0, path)
del sys.modules['httplib2']
import httplib2
| Rewrite python version dependent import | Rewrite python version dependent import
The top level of this external includes a __init__.py so that
it may be imported with only 'externals' in sys.path.
However it copies the contents of the python version dependent httplib2
code, resulting in module level variables appearing in two different
namespaces. As a result, regarding bug 66161, the 'httplib2.debuglevel'
modified in pywikibot code is a different variable to the
'httplib2.debuglevel' used by the httplib2 module.
Instead of copying the python version dependent httplib2, re-import the
python version dependent httplib2.
Change-Id: Ic520505545a5f50f669a01375b253426ecad15ed
| Python | mit | jayvdb/httplib2,wikimedia/pywikibot-externals-httplib2,jayvdb/httplib2,wikimedia/pywikibot-externals-httplib2 | - import inspect
+ import os
import sys
- if sys.version_info[0] == 2:
- from .python2 import httplib2
- else:
- from .python3 import httplib2
- globals().update(inspect.getmembers(httplib2))
+ path = os.path.dirname(__file__)+os.path.sep+'python'+str(sys.version_info[0])
+ sys.path.insert(0, path)
+ del sys.modules['httplib2']
+ import httplib2
+ | Rewrite python version dependent import | ## Code Before:
import inspect
import sys
if sys.version_info[0] == 2:
from .python2 import httplib2
else:
from .python3 import httplib2
globals().update(inspect.getmembers(httplib2))
## Instruction:
Rewrite python version dependent import
## Code After:
import os
import sys
path = os.path.dirname(__file__)+os.path.sep+'python'+str(sys.version_info[0])
sys.path.insert(0, path)
del sys.modules['httplib2']
import httplib2
|
01c5b53ba16a95ab77918d30dfa3a63f2ef2707f | var/spack/repos/builtin/packages/libxcb/package.py | var/spack/repos/builtin/packages/libxcb/package.py | from spack import *
class Libxcb(Package):
"""The X protocol C-language Binding (XCB) is a replacement
for Xlib featuring a small footprint, latency hiding, direct
access to the protocol, improved threading support, and
extensibility."""
homepage = "http://xcb.freedesktop.org/"
url = "http://xcb.freedesktop.org/dist/libxcb-1.11.tar.gz"
version('1.11', '1698dd837d7e6e94d029dbe8b3a82deb')
version('1.11.1', '118623c15a96b08622603a71d8789bf3')
depends_on("python")
depends_on("xcb-proto")
def install(self, spec, prefix):
configure("--prefix=%s" % prefix)
make()
make("install")
| from spack import *
class Libxcb(Package):
"""The X protocol C-language Binding (XCB) is a replacement
for Xlib featuring a small footprint, latency hiding, direct
access to the protocol, improved threading support, and
extensibility."""
homepage = "http://xcb.freedesktop.org/"
url = "http://xcb.freedesktop.org/dist/libxcb-1.11.tar.gz"
version('1.11', '1698dd837d7e6e94d029dbe8b3a82deb')
version('1.11.1', '118623c15a96b08622603a71d8789bf3')
depends_on("python")
depends_on("xcb-proto")
def patch(self):
filter_file('typedef struct xcb_auth_info_t {', 'typedef struct {', 'src/xcb.h')
def install(self, spec, prefix):
configure("--prefix=%s" % prefix)
make()
make("install")
| Make libxcb compile with gcc 4.9. | Make libxcb compile with gcc 4.9.
| Python | lgpl-2.1 | krafczyk/spack,krafczyk/spack,mfherbst/spack,skosukhin/spack,tmerrick1/spack,iulian787/spack,EmreAtes/spack,lgarren/spack,EmreAtes/spack,matthiasdiener/spack,lgarren/spack,TheTimmy/spack,LLNL/spack,mfherbst/spack,lgarren/spack,iulian787/spack,skosukhin/spack,LLNL/spack,LLNL/spack,mfherbst/spack,skosukhin/spack,matthiasdiener/spack,lgarren/spack,matthiasdiener/spack,TheTimmy/spack,TheTimmy/spack,TheTimmy/spack,skosukhin/spack,iulian787/spack,mfherbst/spack,LLNL/spack,skosukhin/spack,tmerrick1/spack,krafczyk/spack,EmreAtes/spack,matthiasdiener/spack,EmreAtes/spack,tmerrick1/spack,mfherbst/spack,TheTimmy/spack,tmerrick1/spack,EmreAtes/spack,LLNL/spack,lgarren/spack,krafczyk/spack,matthiasdiener/spack,iulian787/spack,krafczyk/spack,tmerrick1/spack,iulian787/spack | from spack import *
class Libxcb(Package):
- """The X protocol C-language Binding (XCB) is a replacement
+ """The X protocol C-language Binding (XCB) is a replacement
- for Xlib featuring a small footprint, latency hiding, direct
+ for Xlib featuring a small footprint, latency hiding, direct
- access to the protocol, improved threading support, and
+ access to the protocol, improved threading support, and
extensibility."""
homepage = "http://xcb.freedesktop.org/"
url = "http://xcb.freedesktop.org/dist/libxcb-1.11.tar.gz"
version('1.11', '1698dd837d7e6e94d029dbe8b3a82deb')
version('1.11.1', '118623c15a96b08622603a71d8789bf3')
depends_on("python")
depends_on("xcb-proto")
+ def patch(self):
+ filter_file('typedef struct xcb_auth_info_t {', 'typedef struct {', 'src/xcb.h')
+
+
def install(self, spec, prefix):
configure("--prefix=%s" % prefix)
make()
make("install")
| Make libxcb compile with gcc 4.9. | ## Code Before:
from spack import *
class Libxcb(Package):
"""The X protocol C-language Binding (XCB) is a replacement
for Xlib featuring a small footprint, latency hiding, direct
access to the protocol, improved threading support, and
extensibility."""
homepage = "http://xcb.freedesktop.org/"
url = "http://xcb.freedesktop.org/dist/libxcb-1.11.tar.gz"
version('1.11', '1698dd837d7e6e94d029dbe8b3a82deb')
version('1.11.1', '118623c15a96b08622603a71d8789bf3')
depends_on("python")
depends_on("xcb-proto")
def install(self, spec, prefix):
configure("--prefix=%s" % prefix)
make()
make("install")
## Instruction:
Make libxcb compile with gcc 4.9.
## Code After:
from spack import *
class Libxcb(Package):
"""The X protocol C-language Binding (XCB) is a replacement
for Xlib featuring a small footprint, latency hiding, direct
access to the protocol, improved threading support, and
extensibility."""
homepage = "http://xcb.freedesktop.org/"
url = "http://xcb.freedesktop.org/dist/libxcb-1.11.tar.gz"
version('1.11', '1698dd837d7e6e94d029dbe8b3a82deb')
version('1.11.1', '118623c15a96b08622603a71d8789bf3')
depends_on("python")
depends_on("xcb-proto")
def patch(self):
filter_file('typedef struct xcb_auth_info_t {', 'typedef struct {', 'src/xcb.h')
def install(self, spec, prefix):
configure("--prefix=%s" % prefix)
make()
make("install")
|
42f5b2c53474f20fbffbc0b8cdaa4e5b47a4751d | app/wsgi.py | app/wsgi.py | try:
from gevent.monkey import patch_all
patch_all()
except ImportError:
print "unable to apply gevent monkey.patch_all"
import os
from werkzeug.contrib.fixers import ProxyFix
from app import app as application
if os.environ.get('SENTRY_DSN'):
from raven.contrib.flask import Sentry
sentry = Sentry()
sentry.init_app(application)
application.wsgi_app = ProxyFix(application.wsgi_app)
|
import os
from werkzeug.contrib.fixers import ProxyFix
from app import app as application
if os.environ.get('SENTRY_DSN'):
from raven.contrib.flask import Sentry
sentry = Sentry()
sentry.init_app(application)
application.wsgi_app = ProxyFix(application.wsgi_app)
| Comment out gevent until we need it | Comment out gevent until we need it
| Python | mit | spacedogXYZ/email-validator,spacedogXYZ/email-validator,spacedogXYZ/email-validator | - try:
- from gevent.monkey import patch_all
- patch_all()
- except ImportError:
- print "unable to apply gevent monkey.patch_all"
import os
from werkzeug.contrib.fixers import ProxyFix
from app import app as application
if os.environ.get('SENTRY_DSN'):
from raven.contrib.flask import Sentry
sentry = Sentry()
sentry.init_app(application)
application.wsgi_app = ProxyFix(application.wsgi_app)
| Comment out gevent until we need it | ## Code Before:
try:
from gevent.monkey import patch_all
patch_all()
except ImportError:
print "unable to apply gevent monkey.patch_all"
import os
from werkzeug.contrib.fixers import ProxyFix
from app import app as application
if os.environ.get('SENTRY_DSN'):
from raven.contrib.flask import Sentry
sentry = Sentry()
sentry.init_app(application)
application.wsgi_app = ProxyFix(application.wsgi_app)
## Instruction:
Comment out gevent until we need it
## Code After:
import os
from werkzeug.contrib.fixers import ProxyFix
from app import app as application
if os.environ.get('SENTRY_DSN'):
from raven.contrib.flask import Sentry
sentry = Sentry()
sentry.init_app(application)
application.wsgi_app = ProxyFix(application.wsgi_app)
|
785236ca766d832d859c2933389e23fd3d1bea20 | djangocms_table/cms_plugins.py | djangocms_table/cms_plugins.py | from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from models import Table
from djangocms_table.forms import TableForm
from django.utils import simplejson
from djangocms_table.utils import static_url
from django.http import HttpResponseRedirect
class TablePlugin(CMSPluginBase):
model = Table
form = TableForm
name = _("Table")
render_template = "cms/plugins/table.html"
text_enabled = True
fieldsets = (
(None, {
'fields': ('name',)
}),
(_('Headers'), {
'fields': (('headers_top', 'headers_left', 'headers_bottom'),)
}),
(None, {
'fields': ('table_data', 'csv_upload')
})
)
def render(self, context, instance, placeholder):
try:
data = simplejson.loads(instance.table_data)
except:
data = "error"
context.update({
'name': instance.name,
'data': data,
'instance':instance,
})
return context
def icon_src(self, instance):
return static_url("img/table.png")
def response_change(self, request, obj):
response = super(TablePlugin, self).response_change(request, obj)
if 'csv_upload' in request.FILES.keys():
self.object_successfully_changed = False
return response
plugin_pool.register_plugin(TablePlugin)
| import json
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from models import Table
from djangocms_table.forms import TableForm
from djangocms_table.utils import static_url
from django.http import HttpResponseRedirect
class TablePlugin(CMSPluginBase):
model = Table
form = TableForm
name = _("Table")
render_template = "cms/plugins/table.html"
text_enabled = True
fieldsets = (
(None, {
'fields': ('name',)
}),
(_('Headers'), {
'fields': (('headers_top', 'headers_left', 'headers_bottom'),)
}),
(None, {
'fields': ('table_data', 'csv_upload')
})
)
def render(self, context, instance, placeholder):
try:
data = json.loads(instance.table_data)
except:
data = "error"
context.update({
'name': instance.name,
'data': data,
'instance':instance,
})
return context
def icon_src(self, instance):
return static_url("img/table.png")
def response_change(self, request, obj):
response = super(TablePlugin, self).response_change(request, obj)
if 'csv_upload' in request.FILES.keys():
self.object_successfully_changed = False
return response
plugin_pool.register_plugin(TablePlugin)
| Fix another simplejson deprecation warning | Fix another simplejson deprecation warning
| Python | bsd-3-clause | freelancersunion/djangocms-table,freelancersunion/djangocms-table,freelancersunion/djangocms-table,divio/djangocms-table,divio/djangocms-table,divio/djangocms-table | + import json
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from models import Table
from djangocms_table.forms import TableForm
- from django.utils import simplejson
from djangocms_table.utils import static_url
from django.http import HttpResponseRedirect
class TablePlugin(CMSPluginBase):
model = Table
form = TableForm
name = _("Table")
render_template = "cms/plugins/table.html"
text_enabled = True
fieldsets = (
(None, {
'fields': ('name',)
}),
(_('Headers'), {
'fields': (('headers_top', 'headers_left', 'headers_bottom'),)
}),
(None, {
'fields': ('table_data', 'csv_upload')
})
)
def render(self, context, instance, placeholder):
try:
- data = simplejson.loads(instance.table_data)
+ data = json.loads(instance.table_data)
except:
data = "error"
context.update({
'name': instance.name,
'data': data,
'instance':instance,
})
return context
def icon_src(self, instance):
return static_url("img/table.png")
def response_change(self, request, obj):
response = super(TablePlugin, self).response_change(request, obj)
if 'csv_upload' in request.FILES.keys():
self.object_successfully_changed = False
return response
plugin_pool.register_plugin(TablePlugin)
| Fix another simplejson deprecation warning | ## Code Before:
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from models import Table
from djangocms_table.forms import TableForm
from django.utils import simplejson
from djangocms_table.utils import static_url
from django.http import HttpResponseRedirect
class TablePlugin(CMSPluginBase):
model = Table
form = TableForm
name = _("Table")
render_template = "cms/plugins/table.html"
text_enabled = True
fieldsets = (
(None, {
'fields': ('name',)
}),
(_('Headers'), {
'fields': (('headers_top', 'headers_left', 'headers_bottom'),)
}),
(None, {
'fields': ('table_data', 'csv_upload')
})
)
def render(self, context, instance, placeholder):
try:
data = simplejson.loads(instance.table_data)
except:
data = "error"
context.update({
'name': instance.name,
'data': data,
'instance':instance,
})
return context
def icon_src(self, instance):
return static_url("img/table.png")
def response_change(self, request, obj):
response = super(TablePlugin, self).response_change(request, obj)
if 'csv_upload' in request.FILES.keys():
self.object_successfully_changed = False
return response
plugin_pool.register_plugin(TablePlugin)
## Instruction:
Fix another simplejson deprecation warning
## Code After:
import json
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from models import Table
from djangocms_table.forms import TableForm
from djangocms_table.utils import static_url
from django.http import HttpResponseRedirect
class TablePlugin(CMSPluginBase):
model = Table
form = TableForm
name = _("Table")
render_template = "cms/plugins/table.html"
text_enabled = True
fieldsets = (
(None, {
'fields': ('name',)
}),
(_('Headers'), {
'fields': (('headers_top', 'headers_left', 'headers_bottom'),)
}),
(None, {
'fields': ('table_data', 'csv_upload')
})
)
def render(self, context, instance, placeholder):
try:
data = json.loads(instance.table_data)
except:
data = "error"
context.update({
'name': instance.name,
'data': data,
'instance':instance,
})
return context
def icon_src(self, instance):
return static_url("img/table.png")
def response_change(self, request, obj):
response = super(TablePlugin, self).response_change(request, obj)
if 'csv_upload' in request.FILES.keys():
self.object_successfully_changed = False
return response
plugin_pool.register_plugin(TablePlugin)
|
6b3f568a6615e9439fc0df0eac68838b6cbda0d9 | anti-XSS.py | anti-XSS.py |
'''
Copyright (c) 2016 anti-XSS developers
'''
import sys
from lib.core.link import Link
from optparse import OptionParser
from lib.core.engine import getPage
from lib.core.engine import getScript
from lib.core.engine import xssScanner
from lib.generator.report import gnrReport
def main():
parser = OptionParser()
parser.add_option('-u', '--url', dest='startUrl', help='Target URL (e.g. \'http://www.site.com/\')')
parser.add_option('-d', '--depth', dest='depth', help='The depth you want to scan (default: 2)')
(options, args) = parser.parse_args()
if options.startUrl:
rootLink = Link(options.startUrl, options.startUrl)
if options.depth:
getPage(rootLink, int(options.depth))
else:
getPage(rootLink, 2)
getScript()
xssScanner()
pass
if __name__ == '__main__':
main()
|
'''
Copyright (c) 2016 anti-XSS developers
'''
import sys
from lib.core.urlfun import *
from lib.core.link import Link
from optparse import OptionParser
from lib.core.engine import getPage
from lib.core.engine import getScript
from lib.core.engine import xssScanner
from lib.generator.report import gnrReport
def main():
parser = OptionParser()
parser.add_option('-u', '--url', dest='startUrl', help='Target URL (e.g. \'http://www.site.com/\')')
parser.add_option('-d', '--depth', dest='depth', help='The depth you want to scan (default: 2)')
(options, args) = parser.parse_args()
if options.startUrl:
url = initialize(options.startUrl)
rootLink = Link(url, url)
if options.depth:
getPage(rootLink, int(options.depth))
else:
getPage(rootLink, 2)
getScript()
xssScanner()
pass
if __name__ == '__main__':
main()
| Add initialization before get url | Add initialization before get url
| Python | mit | lewangbtcc/anti-XSS,lewangbtcc/anti-XSS |
'''
Copyright (c) 2016 anti-XSS developers
'''
import sys
+
+ from lib.core.urlfun import *
from lib.core.link import Link
from optparse import OptionParser
from lib.core.engine import getPage
from lib.core.engine import getScript
from lib.core.engine import xssScanner
from lib.generator.report import gnrReport
def main():
parser = OptionParser()
parser.add_option('-u', '--url', dest='startUrl', help='Target URL (e.g. \'http://www.site.com/\')')
parser.add_option('-d', '--depth', dest='depth', help='The depth you want to scan (default: 2)')
(options, args) = parser.parse_args()
if options.startUrl:
- rootLink = Link(options.startUrl, options.startUrl)
+ url = initialize(options.startUrl)
+ rootLink = Link(url, url)
if options.depth:
getPage(rootLink, int(options.depth))
else:
getPage(rootLink, 2)
getScript()
xssScanner()
pass
if __name__ == '__main__':
main()
| Add initialization before get url | ## Code Before:
'''
Copyright (c) 2016 anti-XSS developers
'''
import sys
from lib.core.link import Link
from optparse import OptionParser
from lib.core.engine import getPage
from lib.core.engine import getScript
from lib.core.engine import xssScanner
from lib.generator.report import gnrReport
def main():
parser = OptionParser()
parser.add_option('-u', '--url', dest='startUrl', help='Target URL (e.g. \'http://www.site.com/\')')
parser.add_option('-d', '--depth', dest='depth', help='The depth you want to scan (default: 2)')
(options, args) = parser.parse_args()
if options.startUrl:
rootLink = Link(options.startUrl, options.startUrl)
if options.depth:
getPage(rootLink, int(options.depth))
else:
getPage(rootLink, 2)
getScript()
xssScanner()
pass
if __name__ == '__main__':
main()
## Instruction:
Add initialization before get url
## Code After:
'''
Copyright (c) 2016 anti-XSS developers
'''
import sys
from lib.core.urlfun import *
from lib.core.link import Link
from optparse import OptionParser
from lib.core.engine import getPage
from lib.core.engine import getScript
from lib.core.engine import xssScanner
from lib.generator.report import gnrReport
def main():
parser = OptionParser()
parser.add_option('-u', '--url', dest='startUrl', help='Target URL (e.g. \'http://www.site.com/\')')
parser.add_option('-d', '--depth', dest='depth', help='The depth you want to scan (default: 2)')
(options, args) = parser.parse_args()
if options.startUrl:
url = initialize(options.startUrl)
rootLink = Link(url, url)
if options.depth:
getPage(rootLink, int(options.depth))
else:
getPage(rootLink, 2)
getScript()
xssScanner()
pass
if __name__ == '__main__':
main()
|
a3df62c7da4aa29ab9977a0307e0634fd43e37e8 | pywebfaction/exceptions.py | pywebfaction/exceptions.py | import ast
EXCEPTION_TYPE_PREFIX = "<class 'webfaction_api.exceptions."
EXCEPTION_TYPE_SUFFIX = "'>"
def _parse_exc_type(exc_type):
# This is horribly hacky, but there's not a particularly elegant
# way to go from the exception type to a string representing that
# exception.
if not exc_type.startswith(EXCEPTION_TYPE_PREFIX):
return None
if not exc_type.endswith(EXCEPTION_TYPE_SUFFIX):
return None
return exc_type[len(EXCEPTION_TYPE_PREFIX):len(EXCEPTION_TYPE_SUFFIX) * -1]
def _parse_exc_message(exc_message):
if not exc_message:
return None
message = ast.literal_eval(exc_message)
if isinstance(message, list):
if not message:
return None
return message[0]
return message
class WebFactionFault(Exception):
def __init__(self, underlying_fault):
self.underlying_fault = underlying_fault
exc_type, exc_message = underlying_fault.faultString.split(':', 1)
self.exception_type = _parse_exc_type(exc_type)
self.exception_message = _parse_exc_message(exc_message)
| import ast
EXCEPTION_TYPE_PREFIX = "<class 'webfaction_api.exceptions."
EXCEPTION_TYPE_SUFFIX = "'>"
def _parse_exc_type(exc_type):
# This is horribly hacky, but there's not a particularly elegant
# way to go from the exception type to a string representing that
# exception.
if not exc_type.startswith(EXCEPTION_TYPE_PREFIX):
return None
if not exc_type.endswith(EXCEPTION_TYPE_SUFFIX):
return None
return exc_type[len(EXCEPTION_TYPE_PREFIX):len(EXCEPTION_TYPE_SUFFIX) * -1]
def _parse_exc_message(exc_message):
if not exc_message:
return None
message = ast.literal_eval(exc_message)
if isinstance(message, list):
if not message:
return None
return message[0]
return message
class WebFactionFault(Exception):
def __init__(self, underlying):
self.underlying_fault = underlying
try:
exc_type, exc_message = underlying.faultString.split(':', 1)
self.exception_type = _parse_exc_type(exc_type)
self.exception_message = _parse_exc_message(exc_message)
except ValueError:
self.exception_type = None
self.exception_message = None
| Make code immune to bad fault messages | Make code immune to bad fault messages
| Python | bsd-3-clause | dominicrodger/pywebfaction,dominicrodger/pywebfaction | import ast
EXCEPTION_TYPE_PREFIX = "<class 'webfaction_api.exceptions."
EXCEPTION_TYPE_SUFFIX = "'>"
def _parse_exc_type(exc_type):
# This is horribly hacky, but there's not a particularly elegant
# way to go from the exception type to a string representing that
# exception.
if not exc_type.startswith(EXCEPTION_TYPE_PREFIX):
return None
if not exc_type.endswith(EXCEPTION_TYPE_SUFFIX):
return None
return exc_type[len(EXCEPTION_TYPE_PREFIX):len(EXCEPTION_TYPE_SUFFIX) * -1]
def _parse_exc_message(exc_message):
if not exc_message:
return None
message = ast.literal_eval(exc_message)
if isinstance(message, list):
if not message:
return None
return message[0]
return message
class WebFactionFault(Exception):
- def __init__(self, underlying_fault):
+ def __init__(self, underlying):
- self.underlying_fault = underlying_fault
+ self.underlying_fault = underlying
+ try:
- exc_type, exc_message = underlying_fault.faultString.split(':', 1)
+ exc_type, exc_message = underlying.faultString.split(':', 1)
- self.exception_type = _parse_exc_type(exc_type)
+ self.exception_type = _parse_exc_type(exc_type)
- self.exception_message = _parse_exc_message(exc_message)
+ self.exception_message = _parse_exc_message(exc_message)
+ except ValueError:
+ self.exception_type = None
+ self.exception_message = None
| Make code immune to bad fault messages | ## Code Before:
import ast
EXCEPTION_TYPE_PREFIX = "<class 'webfaction_api.exceptions."
EXCEPTION_TYPE_SUFFIX = "'>"
def _parse_exc_type(exc_type):
# This is horribly hacky, but there's not a particularly elegant
# way to go from the exception type to a string representing that
# exception.
if not exc_type.startswith(EXCEPTION_TYPE_PREFIX):
return None
if not exc_type.endswith(EXCEPTION_TYPE_SUFFIX):
return None
return exc_type[len(EXCEPTION_TYPE_PREFIX):len(EXCEPTION_TYPE_SUFFIX) * -1]
def _parse_exc_message(exc_message):
if not exc_message:
return None
message = ast.literal_eval(exc_message)
if isinstance(message, list):
if not message:
return None
return message[0]
return message
class WebFactionFault(Exception):
def __init__(self, underlying_fault):
self.underlying_fault = underlying_fault
exc_type, exc_message = underlying_fault.faultString.split(':', 1)
self.exception_type = _parse_exc_type(exc_type)
self.exception_message = _parse_exc_message(exc_message)
## Instruction:
Make code immune to bad fault messages
## Code After:
import ast
EXCEPTION_TYPE_PREFIX = "<class 'webfaction_api.exceptions."
EXCEPTION_TYPE_SUFFIX = "'>"
def _parse_exc_type(exc_type):
# This is horribly hacky, but there's not a particularly elegant
# way to go from the exception type to a string representing that
# exception.
if not exc_type.startswith(EXCEPTION_TYPE_PREFIX):
return None
if not exc_type.endswith(EXCEPTION_TYPE_SUFFIX):
return None
return exc_type[len(EXCEPTION_TYPE_PREFIX):len(EXCEPTION_TYPE_SUFFIX) * -1]
def _parse_exc_message(exc_message):
if not exc_message:
return None
message = ast.literal_eval(exc_message)
if isinstance(message, list):
if not message:
return None
return message[0]
return message
class WebFactionFault(Exception):
def __init__(self, underlying):
self.underlying_fault = underlying
try:
exc_type, exc_message = underlying.faultString.split(':', 1)
self.exception_type = _parse_exc_type(exc_type)
self.exception_message = _parse_exc_message(exc_message)
except ValueError:
self.exception_type = None
self.exception_message = None
|
e7e21188daba6efe02d44c2cef9c1b48c45c0636 | readthedocs/donate/urls.py | readthedocs/donate/urls.py | from django.conf.urls import url, patterns, include
from . import views
urlpatterns = patterns(
'',
url(r'^$', views.DonateListView.as_view(), name='donate'),
url(r'^contribute/$', views.DonateCreateView.as_view(), name='donate_add'),
url(r'^contribute/thanks$', views.DonateSuccessView.as_view(), name='donate_success'),
)
| from django.conf.urls import url, patterns, include
from .views import DonateCreateView
from .views import DonateListView
from .views import DonateSuccessView
urlpatterns = patterns(
'',
url(r'^$', DonateListView.as_view(), name='donate'),
url(r'^contribute/$', DonateCreateView.as_view(), name='donate_add'),
url(r'^contribute/thanks$', DonateSuccessView.as_view(), name='donate_success'),
)
| Resolve linting messages in readthedocs.donate.* | Resolve linting messages in readthedocs.donate.*
| Python | mit | mhils/readthedocs.org,wijerasa/readthedocs.org,davidfischer/readthedocs.org,atsuyim/readthedocs.org,CedarLogic/readthedocs.org,istresearch/readthedocs.org,wanghaven/readthedocs.org,atsuyim/readthedocs.org,CedarLogic/readthedocs.org,hach-que/readthedocs.org,mhils/readthedocs.org,kenwang76/readthedocs.org,kenwang76/readthedocs.org,gjtorikian/readthedocs.org,soulshake/readthedocs.org,kenshinthebattosai/readthedocs.org,wijerasa/readthedocs.org,istresearch/readthedocs.org,sunnyzwh/readthedocs.org,mhils/readthedocs.org,davidfischer/readthedocs.org,GovReady/readthedocs.org,kdkeyser/readthedocs.org,LukasBoersma/readthedocs.org,safwanrahman/readthedocs.org,wijerasa/readthedocs.org,Tazer/readthedocs.org,fujita-shintaro/readthedocs.org,techtonik/readthedocs.org,mhils/readthedocs.org,safwanrahman/readthedocs.org,Tazer/readthedocs.org,kenwang76/readthedocs.org,attakei/readthedocs-oauth,kenshinthebattosai/readthedocs.org,clarkperkins/readthedocs.org,safwanrahman/readthedocs.org,VishvajitP/readthedocs.org,wanghaven/readthedocs.org,CedarLogic/readthedocs.org,VishvajitP/readthedocs.org,atsuyim/readthedocs.org,michaelmcandrew/readthedocs.org,attakei/readthedocs-oauth,hach-que/readthedocs.org,titiushko/readthedocs.org,laplaceliu/readthedocs.org,sunnyzwh/readthedocs.org,LukasBoersma/readthedocs.org,kdkeyser/readthedocs.org,sid-kap/readthedocs.org,tddv/readthedocs.org,gjtorikian/readthedocs.org,SteveViss/readthedocs.org,stevepiercy/readthedocs.org,espdev/readthedocs.org,emawind84/readthedocs.org,fujita-shintaro/readthedocs.org,titiushko/readthedocs.org,techtonik/readthedocs.org,asampat3090/readthedocs.org,emawind84/readthedocs.org,pombredanne/readthedocs.org,gjtorikian/readthedocs.org,clarkperkins/readthedocs.org,singingwolfboy/readthedocs.org,asampat3090/readthedocs.org,techtonik/readthedocs.org,Tazer/readthedocs.org,asampat3090/readthedocs.org,kenshinthebattosai/readthedocs.org,istresearch/readthedocs.org,VishvajitP/readthedocs.org,fujita-shintaro/readthedocs.org,istresearch/readthedocs.org,sunnyzwh/readthedocs.org,singingwolfboy/readthedocs.org,pombredanne/readthedocs.org,titiushko/readthedocs.org,espdev/readthedocs.org,rtfd/readthedocs.org,sid-kap/readthedocs.org,kdkeyser/readthedocs.org,emawind84/readthedocs.org,LukasBoersma/readthedocs.org,espdev/readthedocs.org,michaelmcandrew/readthedocs.org,singingwolfboy/readthedocs.org,kdkeyser/readthedocs.org,soulshake/readthedocs.org,CedarLogic/readthedocs.org,stevepiercy/readthedocs.org,atsuyim/readthedocs.org,royalwang/readthedocs.org,safwanrahman/readthedocs.org,kenshinthebattosai/readthedocs.org,sunnyzwh/readthedocs.org,tddv/readthedocs.org,emawind84/readthedocs.org,kenwang76/readthedocs.org,SteveViss/readthedocs.org,michaelmcandrew/readthedocs.org,rtfd/readthedocs.org,royalwang/readthedocs.org,GovReady/readthedocs.org,fujita-shintaro/readthedocs.org,singingwolfboy/readthedocs.org,SteveViss/readthedocs.org,royalwang/readthedocs.org,LukasBoersma/readthedocs.org,attakei/readthedocs-oauth,Tazer/readthedocs.org,wanghaven/readthedocs.org,espdev/readthedocs.org,rtfd/readthedocs.org,GovReady/readthedocs.org,stevepiercy/readthedocs.org,laplaceliu/readthedocs.org,gjtorikian/readthedocs.org,hach-que/readthedocs.org,tddv/readthedocs.org,sid-kap/readthedocs.org,laplaceliu/readthedocs.org,clarkperkins/readthedocs.org,clarkperkins/readthedocs.org,techtonik/readthedocs.org,hach-que/readthedocs.org,stevepiercy/readthedocs.org,attakei/readthedocs-oauth,royalwang/readthedocs.org,davidfischer/readthedocs.org,soulshake/readthedocs.org,espdev/readthedocs.org,wijerasa/readthedocs.org,sid-kap/readthedocs.org,SteveViss/readthedocs.org,laplaceliu/readthedocs.org,titiushko/readthedocs.org,soulshake/readthedocs.org,pombredanne/readthedocs.org,wanghaven/readthedocs.org,michaelmcandrew/readthedocs.org,GovReady/readthedocs.org,asampat3090/readthedocs.org,VishvajitP/readthedocs.org,davidfischer/readthedocs.org,rtfd/readthedocs.org | from django.conf.urls import url, patterns, include
- from . import views
+ from .views import DonateCreateView
+ from .views import DonateListView
+ from .views import DonateSuccessView
urlpatterns = patterns(
'',
- url(r'^$', views.DonateListView.as_view(), name='donate'),
+ url(r'^$', DonateListView.as_view(), name='donate'),
- url(r'^contribute/$', views.DonateCreateView.as_view(), name='donate_add'),
+ url(r'^contribute/$', DonateCreateView.as_view(), name='donate_add'),
- url(r'^contribute/thanks$', views.DonateSuccessView.as_view(), name='donate_success'),
+ url(r'^contribute/thanks$', DonateSuccessView.as_view(), name='donate_success'),
)
| Resolve linting messages in readthedocs.donate.* | ## Code Before:
from django.conf.urls import url, patterns, include
from . import views
urlpatterns = patterns(
'',
url(r'^$', views.DonateListView.as_view(), name='donate'),
url(r'^contribute/$', views.DonateCreateView.as_view(), name='donate_add'),
url(r'^contribute/thanks$', views.DonateSuccessView.as_view(), name='donate_success'),
)
## Instruction:
Resolve linting messages in readthedocs.donate.*
## Code After:
from django.conf.urls import url, patterns, include
from .views import DonateCreateView
from .views import DonateListView
from .views import DonateSuccessView
urlpatterns = patterns(
'',
url(r'^$', DonateListView.as_view(), name='donate'),
url(r'^contribute/$', DonateCreateView.as_view(), name='donate_add'),
url(r'^contribute/thanks$', DonateSuccessView.as_view(), name='donate_success'),
)
|
a4eb952cc2e583d3b7786f5dea101d1e013c8159 | services/controllers/utils.py | services/controllers/utils.py | def map_range(x, in_min, in_max, out_min, out_max):
out_delta = out_max - out_min
in_delta = in_max - in_min
return (x - in_min) * out_delta / in_delta + out_min
| def lerp(a, b, t):
return (1.0 - t) * a + t * b
def map_range(x, in_min, in_max, out_min, out_max):
out_delta = out_max - out_min
in_delta = in_max - in_min
return (x - in_min) * out_delta / in_delta + out_min
| Add function for linear interpolation (lerp) | Add function for linear interpolation (lerp)
| Python | bsd-3-clause | gizmo-cda/g2x-submarine-v2,gizmo-cda/g2x-submarine-v2,gizmo-cda/g2x-submarine-v2,gizmo-cda/g2x-submarine-v2 | + def lerp(a, b, t):
+ return (1.0 - t) * a + t * b
+
+
def map_range(x, in_min, in_max, out_min, out_max):
out_delta = out_max - out_min
in_delta = in_max - in_min
return (x - in_min) * out_delta / in_delta + out_min
| Add function for linear interpolation (lerp) | ## Code Before:
def map_range(x, in_min, in_max, out_min, out_max):
out_delta = out_max - out_min
in_delta = in_max - in_min
return (x - in_min) * out_delta / in_delta + out_min
## Instruction:
Add function for linear interpolation (lerp)
## Code After:
def lerp(a, b, t):
return (1.0 - t) * a + t * b
def map_range(x, in_min, in_max, out_min, out_max):
out_delta = out_max - out_min
in_delta = in_max - in_min
return (x - in_min) * out_delta / in_delta + out_min
|
a509cd74d1e49dd9f9585b8e4c43e88aaf2bc19d | tests/stonemason/service/tileserver/test_tileserver.py | tests/stonemason/service/tileserver/test_tileserver.py |
import os
import unittest
from stonemason.service.tileserver import AppBuilder
class TestExample(unittest.TestCase):
def setUp(self):
os.environ['EXAMPLE_APP_ENV'] = 'dev'
app = AppBuilder().build()
self.client = app.test_client()
def test_app(self):
resp = self.client.get('/')
self.assertEqual(b'Hello World!', resp.data)
|
import os
import unittest
from stonemason.service.tileserver import AppBuilder
class TestExample(unittest.TestCase):
def setUp(self):
os.environ['EXAMPLE_APP_MODE'] = 'development'
app = AppBuilder().build(config='settings.py')
self.client = app.test_client()
def test_app(self):
resp = self.client.get('/')
self.assertEqual(b'Hello World!', resp.data)
| Update tests for the test app | TEST: Update tests for the test app
| Python | mit | Kotaimen/stonemason,Kotaimen/stonemason |
import os
import unittest
from stonemason.service.tileserver import AppBuilder
class TestExample(unittest.TestCase):
def setUp(self):
- os.environ['EXAMPLE_APP_ENV'] = 'dev'
+ os.environ['EXAMPLE_APP_MODE'] = 'development'
- app = AppBuilder().build()
+ app = AppBuilder().build(config='settings.py')
self.client = app.test_client()
def test_app(self):
resp = self.client.get('/')
self.assertEqual(b'Hello World!', resp.data)
| Update tests for the test app | ## Code Before:
import os
import unittest
from stonemason.service.tileserver import AppBuilder
class TestExample(unittest.TestCase):
def setUp(self):
os.environ['EXAMPLE_APP_ENV'] = 'dev'
app = AppBuilder().build()
self.client = app.test_client()
def test_app(self):
resp = self.client.get('/')
self.assertEqual(b'Hello World!', resp.data)
## Instruction:
Update tests for the test app
## Code After:
import os
import unittest
from stonemason.service.tileserver import AppBuilder
class TestExample(unittest.TestCase):
def setUp(self):
os.environ['EXAMPLE_APP_MODE'] = 'development'
app = AppBuilder().build(config='settings.py')
self.client = app.test_client()
def test_app(self):
resp = self.client.get('/')
self.assertEqual(b'Hello World!', resp.data)
|
7b66af8bea8e6c25e3c2f88efc22875504e8f87a | openstates/events.py | openstates/events.py | from pupa.scrape import Event
from .base import OpenstatesBaseScraper
import dateutil.parser
dparse = lambda x: dateutil.parser.parse(x) if x else None
class OpenstatesEventScraper(OpenstatesBaseScraper):
def scrape(self):
method = 'events/?state={}&dtstart=1776-07-04'.format(self.state)
self.events = self.api(method)
for event in self.events:
e = Event(name=event['description'],
location=event['location'],
start_time=dparse(event['when']),
end_time=dparse(event['end']),)
for source in event['sources']:
e.add_source(**source)
yield e
| from pupa.scrape import Event
from .base import OpenstatesBaseScraper
import dateutil.parser
dparse = lambda x: dateutil.parser.parse(x) if x else None
class OpenstatesEventScraper(OpenstatesBaseScraper):
def scrape(self):
method = 'events/?state={}&dtstart=1776-07-04'.format(self.state)
self.events = self.api(method)
for event in self.events:
e = Event(name=event.pop('description'),
classification=event.pop('type'),
location=event.pop('location'),
timezone=event.pop('timezone'),
start_time=dparse(event.pop('when')),
end_time=dparse(event.pop('end')),)
for source in event.pop('sources'):
e.add_source(**source)
ignore = ['country', 'level', 'state', 'created_at', 'updated_at',
'session', 'id']
for i in ignore:
if i in event:
event.pop(i)
print(event)
assert event == {}, "Unknown fields: %s" % (
", ".join(event.keys())
)
yield e
| Add more keys in; validation | Add more keys in; validation
| Python | bsd-3-clause | openstates/billy,sunlightlabs/billy,sunlightlabs/billy,openstates/billy,sunlightlabs/billy,openstates/billy | from pupa.scrape import Event
from .base import OpenstatesBaseScraper
import dateutil.parser
dparse = lambda x: dateutil.parser.parse(x) if x else None
class OpenstatesEventScraper(OpenstatesBaseScraper):
def scrape(self):
method = 'events/?state={}&dtstart=1776-07-04'.format(self.state)
self.events = self.api(method)
for event in self.events:
- e = Event(name=event['description'],
+ e = Event(name=event.pop('description'),
+ classification=event.pop('type'),
- location=event['location'],
+ location=event.pop('location'),
+ timezone=event.pop('timezone'),
- start_time=dparse(event['when']),
+ start_time=dparse(event.pop('when')),
- end_time=dparse(event['end']),)
+ end_time=dparse(event.pop('end')),)
+
- for source in event['sources']:
+ for source in event.pop('sources'):
e.add_source(**source)
+
+ ignore = ['country', 'level', 'state', 'created_at', 'updated_at',
+ 'session', 'id']
+
+ for i in ignore:
+ if i in event:
+ event.pop(i)
+
+ print(event)
+
+ assert event == {}, "Unknown fields: %s" % (
+ ", ".join(event.keys())
+ )
yield e
| Add more keys in; validation | ## Code Before:
from pupa.scrape import Event
from .base import OpenstatesBaseScraper
import dateutil.parser
dparse = lambda x: dateutil.parser.parse(x) if x else None
class OpenstatesEventScraper(OpenstatesBaseScraper):
def scrape(self):
method = 'events/?state={}&dtstart=1776-07-04'.format(self.state)
self.events = self.api(method)
for event in self.events:
e = Event(name=event['description'],
location=event['location'],
start_time=dparse(event['when']),
end_time=dparse(event['end']),)
for source in event['sources']:
e.add_source(**source)
yield e
## Instruction:
Add more keys in; validation
## Code After:
from pupa.scrape import Event
from .base import OpenstatesBaseScraper
import dateutil.parser
dparse = lambda x: dateutil.parser.parse(x) if x else None
class OpenstatesEventScraper(OpenstatesBaseScraper):
def scrape(self):
method = 'events/?state={}&dtstart=1776-07-04'.format(self.state)
self.events = self.api(method)
for event in self.events:
e = Event(name=event.pop('description'),
classification=event.pop('type'),
location=event.pop('location'),
timezone=event.pop('timezone'),
start_time=dparse(event.pop('when')),
end_time=dparse(event.pop('end')),)
for source in event.pop('sources'):
e.add_source(**source)
ignore = ['country', 'level', 'state', 'created_at', 'updated_at',
'session', 'id']
for i in ignore:
if i in event:
event.pop(i)
print(event)
assert event == {}, "Unknown fields: %s" % (
", ".join(event.keys())
)
yield e
|
14bd2c0732b5871ac43991a237a8f12a334e982d | sirius/LI_V00/__init__.py | sirius/LI_V00/__init__.py | from . import lattice as _lattice
from . import accelerator as _accelerator
from . import record_names
create_accelerator = accelerator.create_accelerator
# -- default accelerator values for LI_V00 --
energy = _lattice._energy
single_bunch_charge = _lattice._single_bunch_charge
multi_bunch_charge = _lattice._multi_bunch_charge
pulse_duration_interval = _lattice._pulse_duration_interval
default_optics_mode = _lattice._default_optics_mode.label
lattice_version = 'LI_V00'
family_data = _lattice._family_data
emittance = _lattice._emittance
| from . import lattice as _lattice
from . import accelerator as _accelerator
from . import record_names
create_accelerator = accelerator.create_accelerator
# -- default accelerator values for LI_V00 --
energy = _lattice._energy
single_bunch_charge = _lattice._single_bunch_charge
multi_bunch_charge = _lattice._multi_bunch_charge
pulse_duration_interval = _lattice._pulse_duration_interval
default_optics_mode = _lattice._default_optics_mode.label
lattice_version = 'LI_V00'
family_data = _lattice._family_data
emittance = _lattice._emittance
global_coupling = 1.0 # "round" beam
| Add parameters of initial beam distribution at LI | Add parameters of initial beam distribution at LI
| Python | mit | lnls-fac/sirius | from . import lattice as _lattice
from . import accelerator as _accelerator
from . import record_names
create_accelerator = accelerator.create_accelerator
# -- default accelerator values for LI_V00 --
energy = _lattice._energy
single_bunch_charge = _lattice._single_bunch_charge
multi_bunch_charge = _lattice._multi_bunch_charge
pulse_duration_interval = _lattice._pulse_duration_interval
default_optics_mode = _lattice._default_optics_mode.label
lattice_version = 'LI_V00'
family_data = _lattice._family_data
- emittance = _lattice._emittance
+ emittance = _lattice._emittance
+ global_coupling = 1.0 # "round" beam
| Add parameters of initial beam distribution at LI | ## Code Before:
from . import lattice as _lattice
from . import accelerator as _accelerator
from . import record_names
create_accelerator = accelerator.create_accelerator
# -- default accelerator values for LI_V00 --
energy = _lattice._energy
single_bunch_charge = _lattice._single_bunch_charge
multi_bunch_charge = _lattice._multi_bunch_charge
pulse_duration_interval = _lattice._pulse_duration_interval
default_optics_mode = _lattice._default_optics_mode.label
lattice_version = 'LI_V00'
family_data = _lattice._family_data
emittance = _lattice._emittance
## Instruction:
Add parameters of initial beam distribution at LI
## Code After:
from . import lattice as _lattice
from . import accelerator as _accelerator
from . import record_names
create_accelerator = accelerator.create_accelerator
# -- default accelerator values for LI_V00 --
energy = _lattice._energy
single_bunch_charge = _lattice._single_bunch_charge
multi_bunch_charge = _lattice._multi_bunch_charge
pulse_duration_interval = _lattice._pulse_duration_interval
default_optics_mode = _lattice._default_optics_mode.label
lattice_version = 'LI_V00'
family_data = _lattice._family_data
emittance = _lattice._emittance
global_coupling = 1.0 # "round" beam
|
61448043a039543c38c5ca7b9828792cfc8afbb8 | justwatch/justwatchapi.py | justwatch/justwatchapi.py | import requests
from babel import Locale
class JustWatch:
def __init__(self, country='AU', **kwargs):
self.kwargs = kwargs
self.country = country
self.language = Locale.parse('und_{}'.format(self.country)).language
def search_for_item(self, **kwargs):
if kwargs:
self.kwargs = kwargs
null = None
payload = {
"content_types":null,
"presentation_types":null,
"providers":null,
"genres":null,
"languages":null,
"release_year_from":null,
"release_year_until":null,
"monetization_types":null,
"min_price":null,
"max_price":null,
"scoring_filter_types":null,
"cinema_release":null,
"query":null
}
for key, value in self.kwargs.items():
if key in payload.keys():
payload[key] = value
else:
print('{} is not a valid keyword'.format(key))
header = {'User-Agent':'JustWatch Python client (github.com/dawoudt/JustWatchAPI)'}
api_url = 'https://api.justwatch.com/titles/{}_{}/popular'.format(self.language, self.country)
r = requests.post(api_url, json=payload, headers=header)
return r.json()
| import requests
from babel import Locale
class JustWatch:
def __init__(self, country='AU', **kwargs):
self.kwargs = kwargs
self.country = country
self.language = Locale.parse('und_{}'.format(self.country)).language
def search_for_item(self, **kwargs):
if kwargs:
self.kwargs = kwargs
null = None
payload = {
"content_types":null,
"presentation_types":null,
"providers":null,
"genres":null,
"languages":null,
"release_year_from":null,
"release_year_until":null,
"monetization_types":null,
"min_price":null,
"max_price":null,
"scoring_filter_types":null,
"cinema_release":null,
"query":null
}
for key, value in self.kwargs.items():
if key in payload.keys():
payload[key] = value
else:
print('{} is not a valid keyword'.format(key))
header = {'User-Agent':'JustWatch Python client (github.com/dawoudt/JustWatchAPI)'}
api_url = 'https://api.justwatch.com/titles/{}_{}/popular'.format(self.language, self.country)
r = requests.post(api_url, json=payload, headers=header)
# Client should deal with rate-limiting. JustWatch may send a 429 Too Many Requests response.
r.raise_for_status() # Raises requests.exceptions.HTTPError if r.status_code != 200
return r.json()
| Check and raise HTTP errors | Check and raise HTTP errors
| Python | mit | dawoudt/JustWatchAPI | import requests
from babel import Locale
class JustWatch:
def __init__(self, country='AU', **kwargs):
self.kwargs = kwargs
self.country = country
self.language = Locale.parse('und_{}'.format(self.country)).language
def search_for_item(self, **kwargs):
if kwargs:
self.kwargs = kwargs
null = None
payload = {
"content_types":null,
"presentation_types":null,
"providers":null,
"genres":null,
"languages":null,
"release_year_from":null,
"release_year_until":null,
"monetization_types":null,
"min_price":null,
"max_price":null,
"scoring_filter_types":null,
"cinema_release":null,
"query":null
}
for key, value in self.kwargs.items():
if key in payload.keys():
payload[key] = value
else:
print('{} is not a valid keyword'.format(key))
header = {'User-Agent':'JustWatch Python client (github.com/dawoudt/JustWatchAPI)'}
api_url = 'https://api.justwatch.com/titles/{}_{}/popular'.format(self.language, self.country)
r = requests.post(api_url, json=payload, headers=header)
+
+ # Client should deal with rate-limiting. JustWatch may send a 429 Too Many Requests response.
+ r.raise_for_status() # Raises requests.exceptions.HTTPError if r.status_code != 200
+
return r.json()
| Check and raise HTTP errors | ## Code Before:
import requests
from babel import Locale
class JustWatch:
def __init__(self, country='AU', **kwargs):
self.kwargs = kwargs
self.country = country
self.language = Locale.parse('und_{}'.format(self.country)).language
def search_for_item(self, **kwargs):
if kwargs:
self.kwargs = kwargs
null = None
payload = {
"content_types":null,
"presentation_types":null,
"providers":null,
"genres":null,
"languages":null,
"release_year_from":null,
"release_year_until":null,
"monetization_types":null,
"min_price":null,
"max_price":null,
"scoring_filter_types":null,
"cinema_release":null,
"query":null
}
for key, value in self.kwargs.items():
if key in payload.keys():
payload[key] = value
else:
print('{} is not a valid keyword'.format(key))
header = {'User-Agent':'JustWatch Python client (github.com/dawoudt/JustWatchAPI)'}
api_url = 'https://api.justwatch.com/titles/{}_{}/popular'.format(self.language, self.country)
r = requests.post(api_url, json=payload, headers=header)
return r.json()
## Instruction:
Check and raise HTTP errors
## Code After:
import requests
from babel import Locale
class JustWatch:
def __init__(self, country='AU', **kwargs):
self.kwargs = kwargs
self.country = country
self.language = Locale.parse('und_{}'.format(self.country)).language
def search_for_item(self, **kwargs):
if kwargs:
self.kwargs = kwargs
null = None
payload = {
"content_types":null,
"presentation_types":null,
"providers":null,
"genres":null,
"languages":null,
"release_year_from":null,
"release_year_until":null,
"monetization_types":null,
"min_price":null,
"max_price":null,
"scoring_filter_types":null,
"cinema_release":null,
"query":null
}
for key, value in self.kwargs.items():
if key in payload.keys():
payload[key] = value
else:
print('{} is not a valid keyword'.format(key))
header = {'User-Agent':'JustWatch Python client (github.com/dawoudt/JustWatchAPI)'}
api_url = 'https://api.justwatch.com/titles/{}_{}/popular'.format(self.language, self.country)
r = requests.post(api_url, json=payload, headers=header)
# Client should deal with rate-limiting. JustWatch may send a 429 Too Many Requests response.
r.raise_for_status() # Raises requests.exceptions.HTTPError if r.status_code != 200
return r.json()
|
fc70feec85f0b22ebef05b0fa1316214a48a465a | background/config/prod.py | background/config/prod.py | from decouple import config
from .base import BaseCeleryConfig
class CeleryProduction(BaseCeleryConfig):
enable_utc = config('CELERY_ENABLE_UTC', default=True, cast=bool)
broker_url = config('CELERY_BROKER_URL')
result_backend = config('CELERY_RESULT_BACKEND')
| from decouple import config
from .base import BaseCeleryConfig
REDIS_URL = config('REDIS_URL')
class CeleryProduction(BaseCeleryConfig):
enable_utc = config('CELERY_ENABLE_UTC', default=True, cast=bool)
broker_url = config('CELERY_BROKER_URL',
default=REDIS_URL)
result_backend = config('CELERY_RESULT_BACKEND',
default=REDIS_URL)
| Use REDIS_URL by default for Celery | Use REDIS_URL by default for Celery
| Python | mit | RaitoBezarius/ryuzu-fb-bot | from decouple import config
from .base import BaseCeleryConfig
+ REDIS_URL = config('REDIS_URL')
+
class CeleryProduction(BaseCeleryConfig):
enable_utc = config('CELERY_ENABLE_UTC', default=True, cast=bool)
- broker_url = config('CELERY_BROKER_URL')
+ broker_url = config('CELERY_BROKER_URL',
+ default=REDIS_URL)
- result_backend = config('CELERY_RESULT_BACKEND')
+ result_backend = config('CELERY_RESULT_BACKEND',
+ default=REDIS_URL)
| Use REDIS_URL by default for Celery | ## Code Before:
from decouple import config
from .base import BaseCeleryConfig
class CeleryProduction(BaseCeleryConfig):
enable_utc = config('CELERY_ENABLE_UTC', default=True, cast=bool)
broker_url = config('CELERY_BROKER_URL')
result_backend = config('CELERY_RESULT_BACKEND')
## Instruction:
Use REDIS_URL by default for Celery
## Code After:
from decouple import config
from .base import BaseCeleryConfig
REDIS_URL = config('REDIS_URL')
class CeleryProduction(BaseCeleryConfig):
enable_utc = config('CELERY_ENABLE_UTC', default=True, cast=bool)
broker_url = config('CELERY_BROKER_URL',
default=REDIS_URL)
result_backend = config('CELERY_RESULT_BACKEND',
default=REDIS_URL)
|
dd0cef83edbd3849484b7fc0ec5cb6372f99bb3a | batchflow/models/utils.py | batchflow/models/utils.py | """ Auxiliary functions for models """
def unpack_args(args, layer_no, layers_max):
""" Return layer parameters """
new_args = {}
for arg in args:
if isinstance(args[arg], list) and layers_max > 1:
if len(args[arg]) >= layers_max:
arg_value = args[arg][layer_no]
else:
arg_value = args[arg]
else:
arg_value = args[arg]
new_args.update({arg: arg_value})
return new_args
def unpack_fn_from_config(param, config=None):
""" Return params from config """
par = config.get(param)
if par is None:
return None, {}
if isinstance(par, (tuple, list)):
if len(par) == 0:
par_name = None
elif len(par) == 1:
par_name, par_args = par[0], {}
elif len(par) == 2:
par_name, par_args = par
else:
par_name, par_args = par[0], par[1:]
elif isinstance(par, dict):
par = par.copy()
par_name, par_args = par.pop('name', None), par
else:
par_name, par_args = par, {}
return par_name, par_args
| """ Auxiliary functions for models """
def unpack_args(args, layer_no, layers_max):
""" Return layer parameters """
new_args = {}
for arg in args:
if isinstance(args[arg], list):
if len(args[arg]) >= layers_max:
arg_value = args[arg][layer_no]
else:
arg_value = args[arg]
else:
arg_value = args[arg]
new_args.update({arg: arg_value})
return new_args
def unpack_fn_from_config(param, config=None):
""" Return params from config """
par = config.get(param)
if par is None:
return None, {}
if isinstance(par, (tuple, list)):
if len(par) == 0:
par_name = None
elif len(par) == 1:
par_name, par_args = par[0], {}
elif len(par) == 2:
par_name, par_args = par
else:
par_name, par_args = par[0], par[1:]
elif isinstance(par, dict):
par = par.copy()
par_name, par_args = par.pop('name', None), par
else:
par_name, par_args = par, {}
return par_name, par_args
| Allow for 1 arg in a list | Allow for 1 arg in a list
| Python | apache-2.0 | analysiscenter/dataset | """ Auxiliary functions for models """
def unpack_args(args, layer_no, layers_max):
""" Return layer parameters """
new_args = {}
for arg in args:
- if isinstance(args[arg], list) and layers_max > 1:
+ if isinstance(args[arg], list):
if len(args[arg]) >= layers_max:
arg_value = args[arg][layer_no]
else:
arg_value = args[arg]
else:
arg_value = args[arg]
new_args.update({arg: arg_value})
return new_args
def unpack_fn_from_config(param, config=None):
""" Return params from config """
par = config.get(param)
if par is None:
return None, {}
if isinstance(par, (tuple, list)):
if len(par) == 0:
par_name = None
elif len(par) == 1:
par_name, par_args = par[0], {}
elif len(par) == 2:
par_name, par_args = par
else:
par_name, par_args = par[0], par[1:]
elif isinstance(par, dict):
par = par.copy()
par_name, par_args = par.pop('name', None), par
else:
par_name, par_args = par, {}
return par_name, par_args
| Allow for 1 arg in a list | ## Code Before:
""" Auxiliary functions for models """
def unpack_args(args, layer_no, layers_max):
""" Return layer parameters """
new_args = {}
for arg in args:
if isinstance(args[arg], list) and layers_max > 1:
if len(args[arg]) >= layers_max:
arg_value = args[arg][layer_no]
else:
arg_value = args[arg]
else:
arg_value = args[arg]
new_args.update({arg: arg_value})
return new_args
def unpack_fn_from_config(param, config=None):
""" Return params from config """
par = config.get(param)
if par is None:
return None, {}
if isinstance(par, (tuple, list)):
if len(par) == 0:
par_name = None
elif len(par) == 1:
par_name, par_args = par[0], {}
elif len(par) == 2:
par_name, par_args = par
else:
par_name, par_args = par[0], par[1:]
elif isinstance(par, dict):
par = par.copy()
par_name, par_args = par.pop('name', None), par
else:
par_name, par_args = par, {}
return par_name, par_args
## Instruction:
Allow for 1 arg in a list
## Code After:
""" Auxiliary functions for models """
def unpack_args(args, layer_no, layers_max):
""" Return layer parameters """
new_args = {}
for arg in args:
if isinstance(args[arg], list):
if len(args[arg]) >= layers_max:
arg_value = args[arg][layer_no]
else:
arg_value = args[arg]
else:
arg_value = args[arg]
new_args.update({arg: arg_value})
return new_args
def unpack_fn_from_config(param, config=None):
""" Return params from config """
par = config.get(param)
if par is None:
return None, {}
if isinstance(par, (tuple, list)):
if len(par) == 0:
par_name = None
elif len(par) == 1:
par_name, par_args = par[0], {}
elif len(par) == 2:
par_name, par_args = par
else:
par_name, par_args = par[0], par[1:]
elif isinstance(par, dict):
par = par.copy()
par_name, par_args = par.pop('name', None), par
else:
par_name, par_args = par, {}
return par_name, par_args
|
5c3863fdb366f857fb25b88c2e47508f23660cf3 | tests/test_socket.py | tests/test_socket.py | import socket
from unittest import TestCase
try:
from unitetest import mock
except ImportError:
import mock
from routeros_api import api_socket
class TestSocketWrapper(TestCase):
def test_socket(self):
inner = mock.Mock()
wrapper = api_socket.SocketWrapper(inner)
inner.recv.side_effect = [
socket.error(api_socket.EINTR),
'bytes'
]
self.assertEqual(wrapper.receive(5), 'bytes')
class TestGetSocket(TestCase):
@mock.patch('socket.socket.connect')
def test_with_interrupt(self, connect):
connect.side_effect = [
socket.error(api_socket.EINTR),
None
]
api_socket.get_socket('host', 123)
connect.assert_has_calls([mock.call(('host', 123)),
mock.call(('host', 123))])
@mock.patch('socket.socket.connect')
def test_with_other_error(self, connect):
connect.side_effect = [
socket.error(1),
None
]
with self.assertRaises(socket.error):
api_socket.get_socket('host', 123)
connect.assert_has_calls([mock.call(('host', 123))])
| import socket
from unittest import TestCase
try:
from unitetest import mock
except ImportError:
import mock
from routeros_api import api_socket
class TestSocketWrapper(TestCase):
def test_socket(self):
inner = mock.Mock()
wrapper = api_socket.SocketWrapper(inner)
inner.recv.side_effect = [
socket.error(api_socket.EINTR),
'bytes'
]
self.assertEqual(wrapper.receive(5), 'bytes')
class TestGetSocket(TestCase):
@mock.patch('socket.socket.connect')
def test_with_interrupt(self, connect):
connect.side_effect = [
socket.error(api_socket.EINTR),
None
]
api_socket.get_socket('host', 123)
connect.assert_has_calls([mock.call(('host', 123)),
mock.call(('host', 123))])
@mock.patch('socket.socket.connect')
def test_with_other_error(self, connect):
connect.side_effect = [
socket.error(1),
None
]
self.assertRaises(socket.error, api_socket.get_socket, 'host', 123)
connect.assert_has_calls([mock.call(('host', 123))])
| Fix python2.6 compatibility in tests. | Fix python2.6 compatibility in tests.
| Python | mit | kramarz/RouterOS-api,socialwifi/RouterOS-api,pozytywnie/RouterOS-api | import socket
from unittest import TestCase
try:
from unitetest import mock
except ImportError:
import mock
from routeros_api import api_socket
class TestSocketWrapper(TestCase):
def test_socket(self):
inner = mock.Mock()
wrapper = api_socket.SocketWrapper(inner)
inner.recv.side_effect = [
socket.error(api_socket.EINTR),
'bytes'
]
self.assertEqual(wrapper.receive(5), 'bytes')
class TestGetSocket(TestCase):
@mock.patch('socket.socket.connect')
def test_with_interrupt(self, connect):
connect.side_effect = [
socket.error(api_socket.EINTR),
None
]
api_socket.get_socket('host', 123)
connect.assert_has_calls([mock.call(('host', 123)),
mock.call(('host', 123))])
@mock.patch('socket.socket.connect')
def test_with_other_error(self, connect):
connect.side_effect = [
socket.error(1),
None
]
+ self.assertRaises(socket.error, api_socket.get_socket, 'host', 123)
- with self.assertRaises(socket.error):
- api_socket.get_socket('host', 123)
connect.assert_has_calls([mock.call(('host', 123))])
| Fix python2.6 compatibility in tests. | ## Code Before:
import socket
from unittest import TestCase
try:
from unitetest import mock
except ImportError:
import mock
from routeros_api import api_socket
class TestSocketWrapper(TestCase):
def test_socket(self):
inner = mock.Mock()
wrapper = api_socket.SocketWrapper(inner)
inner.recv.side_effect = [
socket.error(api_socket.EINTR),
'bytes'
]
self.assertEqual(wrapper.receive(5), 'bytes')
class TestGetSocket(TestCase):
@mock.patch('socket.socket.connect')
def test_with_interrupt(self, connect):
connect.side_effect = [
socket.error(api_socket.EINTR),
None
]
api_socket.get_socket('host', 123)
connect.assert_has_calls([mock.call(('host', 123)),
mock.call(('host', 123))])
@mock.patch('socket.socket.connect')
def test_with_other_error(self, connect):
connect.side_effect = [
socket.error(1),
None
]
with self.assertRaises(socket.error):
api_socket.get_socket('host', 123)
connect.assert_has_calls([mock.call(('host', 123))])
## Instruction:
Fix python2.6 compatibility in tests.
## Code After:
import socket
from unittest import TestCase
try:
from unitetest import mock
except ImportError:
import mock
from routeros_api import api_socket
class TestSocketWrapper(TestCase):
def test_socket(self):
inner = mock.Mock()
wrapper = api_socket.SocketWrapper(inner)
inner.recv.side_effect = [
socket.error(api_socket.EINTR),
'bytes'
]
self.assertEqual(wrapper.receive(5), 'bytes')
class TestGetSocket(TestCase):
@mock.patch('socket.socket.connect')
def test_with_interrupt(self, connect):
connect.side_effect = [
socket.error(api_socket.EINTR),
None
]
api_socket.get_socket('host', 123)
connect.assert_has_calls([mock.call(('host', 123)),
mock.call(('host', 123))])
@mock.patch('socket.socket.connect')
def test_with_other_error(self, connect):
connect.side_effect = [
socket.error(1),
None
]
self.assertRaises(socket.error, api_socket.get_socket, 'host', 123)
connect.assert_has_calls([mock.call(('host', 123))])
|
889473ba81816aa0ad349823515843c337a6b985 | benchexec/tools/deagle.py | benchexec/tools/deagle.py |
import benchexec.result as result
import benchexec.util as util
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool):
def executable(self):
return util.find_executable("deagle")
def name(self):
return "Deagle"
def version(self, executable):
return self._version_from_tool(executable)
def cmdline(self, executable, options, tasks, propertyfile, rlimits):
options = options + ["--32", "--no-unwinding-assertions", "--closure"]
return [executable] + options + tasks
def determine_result(self, returncode, returnsignal, output, isTimeout):
status = result.RESULT_UNKNOWN
stroutput = str(output)
if isTimeout:
status = "TIMEOUT"
elif "SUCCESSFUL" in stroutput:
status = result.RESULT_TRUE_PROP
elif "FAILED" in stroutput:
status = result.RESULT_FALSE_REACH
elif "UNKNOWN" in stroutput:
status = result.RESULT_UNKNOWN
else:
status = result.RESULT_UNKNOWN
return status
|
import benchexec.result as result
import benchexec.util as util
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool2):
def executable(self, tool_locator):
return tool_locator.find_executable("deagle")
def name(self):
return "Deagle"
def version(self, executable):
return self._version_from_tool(executable)
def get_data_model(self, task):
if isinstance(task.options, dict) and task.options.get("language") == "C":
data_model = task.options.get("data_model")
if data_model == "LP64":
return ["--64"]
return ["--32"] # default
def cmdline(self, executable, options, task, rlimits):
return [executable] + options + self.get_data_model(task) + list(task.input_files_or_identifier)
def determine_result(self, run):
status = result.RESULT_UNKNOWN
output = run.output
stroutput = str(output)
if "SUCCESSFUL" in stroutput:
status = result.RESULT_TRUE_PROP
elif "FAILED" in stroutput:
status = result.RESULT_FALSE_REACH
else:
status = result.RESULT_UNKNOWN
return status
| Move --closure and --no-unwinding-assertions to bench-defs; rewrite choices between --32 and --64 | Move --closure and --no-unwinding-assertions to bench-defs; rewrite choices between --32 and --64
| Python | apache-2.0 | ultimate-pa/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,sosy-lab/benchexec |
import benchexec.result as result
import benchexec.util as util
import benchexec.tools.template
- class Tool(benchexec.tools.template.BaseTool):
+ class Tool(benchexec.tools.template.BaseTool2):
- def executable(self):
+ def executable(self, tool_locator):
- return util.find_executable("deagle")
+ return tool_locator.find_executable("deagle")
def name(self):
return "Deagle"
def version(self, executable):
return self._version_from_tool(executable)
- def cmdline(self, executable, options, tasks, propertyfile, rlimits):
- options = options + ["--32", "--no-unwinding-assertions", "--closure"]
- return [executable] + options + tasks
+ def get_data_model(self, task):
+ if isinstance(task.options, dict) and task.options.get("language") == "C":
+ data_model = task.options.get("data_model")
+ if data_model == "LP64":
+ return ["--64"]
+ return ["--32"] # default
- def determine_result(self, returncode, returnsignal, output, isTimeout):
+ def cmdline(self, executable, options, task, rlimits):
+ return [executable] + options + self.get_data_model(task) + list(task.input_files_or_identifier)
+ def determine_result(self, run):
status = result.RESULT_UNKNOWN
+
+ output = run.output
stroutput = str(output)
- if isTimeout:
- status = "TIMEOUT"
- elif "SUCCESSFUL" in stroutput:
+ if "SUCCESSFUL" in stroutput:
status = result.RESULT_TRUE_PROP
elif "FAILED" in stroutput:
status = result.RESULT_FALSE_REACH
- elif "UNKNOWN" in stroutput:
- status = result.RESULT_UNKNOWN
else:
status = result.RESULT_UNKNOWN
return status
| Move --closure and --no-unwinding-assertions to bench-defs; rewrite choices between --32 and --64 | ## Code Before:
import benchexec.result as result
import benchexec.util as util
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool):
def executable(self):
return util.find_executable("deagle")
def name(self):
return "Deagle"
def version(self, executable):
return self._version_from_tool(executable)
def cmdline(self, executable, options, tasks, propertyfile, rlimits):
options = options + ["--32", "--no-unwinding-assertions", "--closure"]
return [executable] + options + tasks
def determine_result(self, returncode, returnsignal, output, isTimeout):
status = result.RESULT_UNKNOWN
stroutput = str(output)
if isTimeout:
status = "TIMEOUT"
elif "SUCCESSFUL" in stroutput:
status = result.RESULT_TRUE_PROP
elif "FAILED" in stroutput:
status = result.RESULT_FALSE_REACH
elif "UNKNOWN" in stroutput:
status = result.RESULT_UNKNOWN
else:
status = result.RESULT_UNKNOWN
return status
## Instruction:
Move --closure and --no-unwinding-assertions to bench-defs; rewrite choices between --32 and --64
## Code After:
import benchexec.result as result
import benchexec.util as util
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool2):
def executable(self, tool_locator):
return tool_locator.find_executable("deagle")
def name(self):
return "Deagle"
def version(self, executable):
return self._version_from_tool(executable)
def get_data_model(self, task):
if isinstance(task.options, dict) and task.options.get("language") == "C":
data_model = task.options.get("data_model")
if data_model == "LP64":
return ["--64"]
return ["--32"] # default
def cmdline(self, executable, options, task, rlimits):
return [executable] + options + self.get_data_model(task) + list(task.input_files_or_identifier)
def determine_result(self, run):
status = result.RESULT_UNKNOWN
output = run.output
stroutput = str(output)
if "SUCCESSFUL" in stroutput:
status = result.RESULT_TRUE_PROP
elif "FAILED" in stroutput:
status = result.RESULT_FALSE_REACH
else:
status = result.RESULT_UNKNOWN
return status
|
6bc1f6e466fa09dd0bc6a076f9081e1aa03efdc7 | examples/translations/dutch_test_1.py | examples/translations/dutch_test_1.py | from seleniumbase.translate.dutch import Testgeval
class MijnTestklasse(Testgeval):
def test_voorbeeld_1(self):
self.openen("https://nl.wikipedia.org/wiki/Hoofdpagina")
self.controleren_element('a[title*="hoofdpagina gaan"]')
self.controleren_tekst("Welkom op Wikipedia", "td.hp-welkom")
self.typ("#searchInput", "Stroopwafel")
self.klik("#searchButton")
self.controleren_tekst("Stroopwafel", "#firstHeading")
self.controleren_element('img[alt="Stroopwafels"]')
self.typ("#searchInput", "Rijksmuseum Amsterdam")
self.klik("#searchButton")
self.controleren_tekst("Rijksmuseum", "#firstHeading")
self.controleren_element('img[alt="Het Rijksmuseum"]')
self.terug()
self.controleren_ware("Stroopwafel" in self.huidige_url_ophalen())
self.vooruit()
self.controleren_ware("Rijksmuseum" in self.huidige_url_ophalen())
| from seleniumbase.translate.dutch import Testgeval
class MijnTestklasse(Testgeval):
def test_voorbeeld_1(self):
self.openen("https://nl.wikipedia.org/wiki/Hoofdpagina")
self.controleren_element('a[title*="hoofdpagina gaan"]')
self.controleren_tekst("Welkom op Wikipedia", "td.hp-welkom")
self.typ("#searchInput", "Stroopwafel")
self.klik("#searchButton")
self.controleren_tekst("Stroopwafel", "#firstHeading")
self.controleren_element('img[src*="Stroopwafels"]')
self.typ("#searchInput", "Rijksmuseum Amsterdam")
self.klik("#searchButton")
self.controleren_tekst("Rijksmuseum", "#firstHeading")
self.controleren_element('img[src*="Rijksmuseum"]')
self.terug()
self.controleren_ware("Stroopwafel" in self.huidige_url_ophalen())
self.vooruit()
self.controleren_ware("Rijksmuseum" in self.huidige_url_ophalen())
| Update the Dutch example test | Update the Dutch example test
| Python | mit | seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase | from seleniumbase.translate.dutch import Testgeval
class MijnTestklasse(Testgeval):
def test_voorbeeld_1(self):
self.openen("https://nl.wikipedia.org/wiki/Hoofdpagina")
self.controleren_element('a[title*="hoofdpagina gaan"]')
self.controleren_tekst("Welkom op Wikipedia", "td.hp-welkom")
self.typ("#searchInput", "Stroopwafel")
self.klik("#searchButton")
self.controleren_tekst("Stroopwafel", "#firstHeading")
- self.controleren_element('img[alt="Stroopwafels"]')
+ self.controleren_element('img[src*="Stroopwafels"]')
self.typ("#searchInput", "Rijksmuseum Amsterdam")
self.klik("#searchButton")
self.controleren_tekst("Rijksmuseum", "#firstHeading")
- self.controleren_element('img[alt="Het Rijksmuseum"]')
+ self.controleren_element('img[src*="Rijksmuseum"]')
self.terug()
self.controleren_ware("Stroopwafel" in self.huidige_url_ophalen())
self.vooruit()
self.controleren_ware("Rijksmuseum" in self.huidige_url_ophalen())
| Update the Dutch example test | ## Code Before:
from seleniumbase.translate.dutch import Testgeval
class MijnTestklasse(Testgeval):
def test_voorbeeld_1(self):
self.openen("https://nl.wikipedia.org/wiki/Hoofdpagina")
self.controleren_element('a[title*="hoofdpagina gaan"]')
self.controleren_tekst("Welkom op Wikipedia", "td.hp-welkom")
self.typ("#searchInput", "Stroopwafel")
self.klik("#searchButton")
self.controleren_tekst("Stroopwafel", "#firstHeading")
self.controleren_element('img[alt="Stroopwafels"]')
self.typ("#searchInput", "Rijksmuseum Amsterdam")
self.klik("#searchButton")
self.controleren_tekst("Rijksmuseum", "#firstHeading")
self.controleren_element('img[alt="Het Rijksmuseum"]')
self.terug()
self.controleren_ware("Stroopwafel" in self.huidige_url_ophalen())
self.vooruit()
self.controleren_ware("Rijksmuseum" in self.huidige_url_ophalen())
## Instruction:
Update the Dutch example test
## Code After:
from seleniumbase.translate.dutch import Testgeval
class MijnTestklasse(Testgeval):
def test_voorbeeld_1(self):
self.openen("https://nl.wikipedia.org/wiki/Hoofdpagina")
self.controleren_element('a[title*="hoofdpagina gaan"]')
self.controleren_tekst("Welkom op Wikipedia", "td.hp-welkom")
self.typ("#searchInput", "Stroopwafel")
self.klik("#searchButton")
self.controleren_tekst("Stroopwafel", "#firstHeading")
self.controleren_element('img[src*="Stroopwafels"]')
self.typ("#searchInput", "Rijksmuseum Amsterdam")
self.klik("#searchButton")
self.controleren_tekst("Rijksmuseum", "#firstHeading")
self.controleren_element('img[src*="Rijksmuseum"]')
self.terug()
self.controleren_ware("Stroopwafel" in self.huidige_url_ophalen())
self.vooruit()
self.controleren_ware("Rijksmuseum" in self.huidige_url_ophalen())
|
dc2c960bb937cc287dedf95d407ed2e95f3f6724 | sigma_files/serializers.py | sigma_files/serializers.py | from rest_framework import serializers
from sigma.utils import CurrentUserCreateOnlyDefault
from sigma_files.models import Image
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = Image
file = serializers.ImageField(max_length=255)
height = serializers.IntegerField(source='file.height', read_only=True)
width = serializers.IntegerField(source='file.width', read_only=True)
owner = serializers.PrimaryKeyRelatedField(read_only=True, default=CurrentUserCreateOnlyDefault())
| from rest_framework import serializers
from dry_rest_permissions.generics import DRYPermissionsField
from sigma.utils import CurrentUserCreateOnlyDefault
from sigma_files.models import Image
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = Image
file = serializers.ImageField(max_length=255)
height = serializers.IntegerField(source='file.height', read_only=True)
width = serializers.IntegerField(source='file.width', read_only=True)
owner = serializers.PrimaryKeyRelatedField(read_only=True, default=CurrentUserCreateOnlyDefault())
permissions = DRYPermissionsField(actions=['read', 'write'])
| Add permissions field on ImageSerializer | Add permissions field on ImageSerializer
| Python | agpl-3.0 | ProjetSigma/backend,ProjetSigma/backend | from rest_framework import serializers
+ from dry_rest_permissions.generics import DRYPermissionsField
from sigma.utils import CurrentUserCreateOnlyDefault
from sigma_files.models import Image
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = Image
file = serializers.ImageField(max_length=255)
height = serializers.IntegerField(source='file.height', read_only=True)
width = serializers.IntegerField(source='file.width', read_only=True)
owner = serializers.PrimaryKeyRelatedField(read_only=True, default=CurrentUserCreateOnlyDefault())
+ permissions = DRYPermissionsField(actions=['read', 'write'])
| Add permissions field on ImageSerializer | ## Code Before:
from rest_framework import serializers
from sigma.utils import CurrentUserCreateOnlyDefault
from sigma_files.models import Image
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = Image
file = serializers.ImageField(max_length=255)
height = serializers.IntegerField(source='file.height', read_only=True)
width = serializers.IntegerField(source='file.width', read_only=True)
owner = serializers.PrimaryKeyRelatedField(read_only=True, default=CurrentUserCreateOnlyDefault())
## Instruction:
Add permissions field on ImageSerializer
## Code After:
from rest_framework import serializers
from dry_rest_permissions.generics import DRYPermissionsField
from sigma.utils import CurrentUserCreateOnlyDefault
from sigma_files.models import Image
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = Image
file = serializers.ImageField(max_length=255)
height = serializers.IntegerField(source='file.height', read_only=True)
width = serializers.IntegerField(source='file.width', read_only=True)
owner = serializers.PrimaryKeyRelatedField(read_only=True, default=CurrentUserCreateOnlyDefault())
permissions = DRYPermissionsField(actions=['read', 'write'])
|
05c9039c364d87c890cffdb9de7f0c8d1f7f9cb3 | tfx/orchestration/config/kubernetes_component_config.py | tfx/orchestration/config/kubernetes_component_config.py | """Component config for Kubernets Pod execution."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from typing import Any, Dict, Text, Union
from kubernetes import client
from tfx.orchestration.config import base_component_config
class KubernetesComponentConfig(base_component_config.BaseComponentConfig):
"""Component config which holds Kubernetes Pod execution args.
Attributes:
pod: the spec for a Pod. It can either be an instance of client.V1Pod or a
dict of a Pod spec. The spec details are:
https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/V1Pod.md
"""
def __init__(self, pod: Union[client.V1Pod, Dict[Text, Any]]):
if not pod:
raise ValueError('pod must have a value.')
self.pod = pod
| """Component config for Kubernets Pod execution."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from typing import Any, Dict, Text, Union
from kubernetes import client
from tfx.orchestration.config import base_component_config
from tfx.orchestration.launcher import container_common
class KubernetesComponentConfig(base_component_config.BaseComponentConfig):
"""Component config which holds Kubernetes Pod execution args.
Attributes:
pod: the spec for a Pod. It can either be an instance of client.V1Pod or a
dict of a Pod spec. The spec details are:
https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/V1Pod.md
"""
def __init__(self, pod: Union[client.V1Pod, Dict[Text, Any]]):
if not pod:
raise ValueError('pod must have a value.')
self.pod = container_common.to_swagger_dict(pod)
| Convert k8s pod spec into dict structure to make sure that it's json serializable. | Convert k8s pod spec into dict structure to make sure that it's json serializable.
PiperOrigin-RevId: 279162159
| Python | apache-2.0 | tensorflow/tfx,tensorflow/tfx | """Component config for Kubernets Pod execution."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from typing import Any, Dict, Text, Union
from kubernetes import client
from tfx.orchestration.config import base_component_config
+ from tfx.orchestration.launcher import container_common
class KubernetesComponentConfig(base_component_config.BaseComponentConfig):
"""Component config which holds Kubernetes Pod execution args.
Attributes:
pod: the spec for a Pod. It can either be an instance of client.V1Pod or a
dict of a Pod spec. The spec details are:
https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/V1Pod.md
"""
def __init__(self, pod: Union[client.V1Pod, Dict[Text, Any]]):
if not pod:
raise ValueError('pod must have a value.')
- self.pod = pod
+ self.pod = container_common.to_swagger_dict(pod)
| Convert k8s pod spec into dict structure to make sure that it's json serializable. | ## Code Before:
"""Component config for Kubernets Pod execution."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from typing import Any, Dict, Text, Union
from kubernetes import client
from tfx.orchestration.config import base_component_config
class KubernetesComponentConfig(base_component_config.BaseComponentConfig):
"""Component config which holds Kubernetes Pod execution args.
Attributes:
pod: the spec for a Pod. It can either be an instance of client.V1Pod or a
dict of a Pod spec. The spec details are:
https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/V1Pod.md
"""
def __init__(self, pod: Union[client.V1Pod, Dict[Text, Any]]):
if not pod:
raise ValueError('pod must have a value.')
self.pod = pod
## Instruction:
Convert k8s pod spec into dict structure to make sure that it's json serializable.
## Code After:
"""Component config for Kubernets Pod execution."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from typing import Any, Dict, Text, Union
from kubernetes import client
from tfx.orchestration.config import base_component_config
from tfx.orchestration.launcher import container_common
class KubernetesComponentConfig(base_component_config.BaseComponentConfig):
"""Component config which holds Kubernetes Pod execution args.
Attributes:
pod: the spec for a Pod. It can either be an instance of client.V1Pod or a
dict of a Pod spec. The spec details are:
https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/V1Pod.md
"""
def __init__(self, pod: Union[client.V1Pod, Dict[Text, Any]]):
if not pod:
raise ValueError('pod must have a value.')
self.pod = container_common.to_swagger_dict(pod)
|
525e7d5061326c7c815f4ede7757afb7c085ff78 | apartments/models.py | apartments/models.py | from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class Listing(Base):
__tablename__ = 'listings'
id = Column(Integer, primary_key=True)
craigslist_id = Column(String, unique=True)
url = Column(String, unique=True)
engine = create_engine('sqlite:///apartments.db')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
| from sqlalchemy import create_engine, Column, DateTime, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql import func
Base = declarative_base()
class Listing(Base):
__tablename__ = 'listings'
id = Column(Integer, primary_key=True)
timestamp = Column(DateTime, server_default=func.now())
craigslist_id = Column(String, unique=True)
url = Column(String, unique=True)
engine = create_engine('sqlite:///apartments.db')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
| Add timestamp field to Listing | Add timestamp field to Listing
| Python | mit | rlucioni/apartments,rlucioni/craigbot,rlucioni/craigbot | - from sqlalchemy import create_engine, Column, Integer, String
+ from sqlalchemy import create_engine, Column, DateTime, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
+ from sqlalchemy.sql import func
Base = declarative_base()
class Listing(Base):
__tablename__ = 'listings'
id = Column(Integer, primary_key=True)
+ timestamp = Column(DateTime, server_default=func.now())
craigslist_id = Column(String, unique=True)
url = Column(String, unique=True)
engine = create_engine('sqlite:///apartments.db')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
| Add timestamp field to Listing | ## Code Before:
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class Listing(Base):
__tablename__ = 'listings'
id = Column(Integer, primary_key=True)
craigslist_id = Column(String, unique=True)
url = Column(String, unique=True)
engine = create_engine('sqlite:///apartments.db')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
## Instruction:
Add timestamp field to Listing
## Code After:
from sqlalchemy import create_engine, Column, DateTime, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql import func
Base = declarative_base()
class Listing(Base):
__tablename__ = 'listings'
id = Column(Integer, primary_key=True)
timestamp = Column(DateTime, server_default=func.now())
craigslist_id = Column(String, unique=True)
url = Column(String, unique=True)
engine = create_engine('sqlite:///apartments.db')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
|
f67746750bdd2a1d6e662b1fc36d5a6fa13098c5 | scripts/generate.py | scripts/generate.py |
params = [
("dict(dim=250, dim_mlp=250)", "run1"),
("dict(dim=500, dim_mlp=500)", "run2"),
("dict(rank_n_approx=200)", "run3"),
("dict(rank_n_approx=500)", "run4"),
("dict(avg_word=False)", "run5")
]
for options, name in params:
with open("{}.sh".format(name), "w") as script:
log = "{}.log".format(name)
print >>script, template.format(**locals())
|
params = [
("dict(dim=250, dim_mlp=250, prefix='model_run1_')", "run1"),
("dict(dim=500, dim_mlp=500, prefix='model_run2_')", "run2"),
("dict(rank_n_approx=200, prefix='model_run3_')", "run3"),
("dict(rank_n_approx=500, prefix='model_run4_')", "run4"),
("dict(avg_word=False, prefix='model_run5_')", "run5")
]
for options, name in params:
with open("{}.sh".format(name), "w") as script:
log = "{}.log".format(name)
print >>script, template.format(**locals())
| Add different prefixes for the experiments | Add different prefixes for the experiments
| Python | bsd-3-clause | rizar/groundhog-private |
params = [
- ("dict(dim=250, dim_mlp=250)", "run1"),
+ ("dict(dim=250, dim_mlp=250, prefix='model_run1_')", "run1"),
- ("dict(dim=500, dim_mlp=500)", "run2"),
+ ("dict(dim=500, dim_mlp=500, prefix='model_run2_')", "run2"),
- ("dict(rank_n_approx=200)", "run3"),
+ ("dict(rank_n_approx=200, prefix='model_run3_')", "run3"),
- ("dict(rank_n_approx=500)", "run4"),
+ ("dict(rank_n_approx=500, prefix='model_run4_')", "run4"),
- ("dict(avg_word=False)", "run5")
+ ("dict(avg_word=False, prefix='model_run5_')", "run5")
]
for options, name in params:
with open("{}.sh".format(name), "w") as script:
log = "{}.log".format(name)
print >>script, template.format(**locals())
| Add different prefixes for the experiments | ## Code Before:
params = [
("dict(dim=250, dim_mlp=250)", "run1"),
("dict(dim=500, dim_mlp=500)", "run2"),
("dict(rank_n_approx=200)", "run3"),
("dict(rank_n_approx=500)", "run4"),
("dict(avg_word=False)", "run5")
]
for options, name in params:
with open("{}.sh".format(name), "w") as script:
log = "{}.log".format(name)
print >>script, template.format(**locals())
## Instruction:
Add different prefixes for the experiments
## Code After:
params = [
("dict(dim=250, dim_mlp=250, prefix='model_run1_')", "run1"),
("dict(dim=500, dim_mlp=500, prefix='model_run2_')", "run2"),
("dict(rank_n_approx=200, prefix='model_run3_')", "run3"),
("dict(rank_n_approx=500, prefix='model_run4_')", "run4"),
("dict(avg_word=False, prefix='model_run5_')", "run5")
]
for options, name in params:
with open("{}.sh".format(name), "w") as script:
log = "{}.log".format(name)
print >>script, template.format(**locals())
|
1986000f7e3fff1366de245dadf8cd3b6e53f238 | djstripe/contrib/rest_framework/permissions.py | djstripe/contrib/rest_framework/permissions.py | from rest_framework.permissions import BasePermission
from ...settings import subscriber_request_callback
from ...utils import subscriber_has_active_subscription
class DJStripeSubscriptionPermission(BasePermission):
"""
A permission to be used when wanting to permit users with active subscriptions.
"""
def has_permission(self, request, view):
"""
Check if the subscriber has an active subscription.
Returns false if:
* a subscriber isn't passed through the request
See ``utils.subscriber_has_active_subscription`` for more rules.
"""
try:
subscriber_has_active_subscription(subscriber_request_callback(request))
except AttributeError:
return False
| from rest_framework.permissions import BasePermission
from ...settings import subscriber_request_callback
from ...utils import subscriber_has_active_subscription
class DJStripeSubscriptionPermission(BasePermission):
"""
A permission to be used when wanting to permit users with active subscriptions.
"""
def has_permission(self, request, view) -> bool:
"""
Check if the subscriber has an active subscription.
Returns false if:
* a subscriber isn't passed through the request
See ``utils.subscriber_has_active_subscription`` for more rules.
"""
try:
return subscriber_has_active_subscription(
subscriber_request_callback(request)
)
except AttributeError:
return False
| Fix missing return statement in DJStripeSubscriptionPermission | Fix missing return statement in DJStripeSubscriptionPermission
Fixes #1250
| Python | mit | dj-stripe/dj-stripe,dj-stripe/dj-stripe,pydanny/dj-stripe,pydanny/dj-stripe | from rest_framework.permissions import BasePermission
from ...settings import subscriber_request_callback
from ...utils import subscriber_has_active_subscription
class DJStripeSubscriptionPermission(BasePermission):
"""
A permission to be used when wanting to permit users with active subscriptions.
"""
- def has_permission(self, request, view):
+ def has_permission(self, request, view) -> bool:
"""
Check if the subscriber has an active subscription.
Returns false if:
* a subscriber isn't passed through the request
See ``utils.subscriber_has_active_subscription`` for more rules.
"""
try:
- subscriber_has_active_subscription(subscriber_request_callback(request))
+ return subscriber_has_active_subscription(
+ subscriber_request_callback(request)
+ )
except AttributeError:
return False
| Fix missing return statement in DJStripeSubscriptionPermission | ## Code Before:
from rest_framework.permissions import BasePermission
from ...settings import subscriber_request_callback
from ...utils import subscriber_has_active_subscription
class DJStripeSubscriptionPermission(BasePermission):
"""
A permission to be used when wanting to permit users with active subscriptions.
"""
def has_permission(self, request, view):
"""
Check if the subscriber has an active subscription.
Returns false if:
* a subscriber isn't passed through the request
See ``utils.subscriber_has_active_subscription`` for more rules.
"""
try:
subscriber_has_active_subscription(subscriber_request_callback(request))
except AttributeError:
return False
## Instruction:
Fix missing return statement in DJStripeSubscriptionPermission
## Code After:
from rest_framework.permissions import BasePermission
from ...settings import subscriber_request_callback
from ...utils import subscriber_has_active_subscription
class DJStripeSubscriptionPermission(BasePermission):
"""
A permission to be used when wanting to permit users with active subscriptions.
"""
def has_permission(self, request, view) -> bool:
"""
Check if the subscriber has an active subscription.
Returns false if:
* a subscriber isn't passed through the request
See ``utils.subscriber_has_active_subscription`` for more rules.
"""
try:
return subscriber_has_active_subscription(
subscriber_request_callback(request)
)
except AttributeError:
return False
|
94351ce09112c7bd4c9ed58722334ee48fe99883 | datapackage_pipelines_fiscal/processors/upload.py | datapackage_pipelines_fiscal/processors/upload.py | import os
import zipfile
import tempfile
from datapackage_pipelines.wrapper import ingest, spew
import gobble
params, datapackage, res_iter = ingest()
spew(datapackage, res_iter)
user = gobble.user.User()
in_filename = open(params['in-file'], 'rb')
in_file = zipfile.ZipFile(in_filename)
temp_dir = tempfile.mkdtemp()
for name in in_file.namelist():
in_file.extract(name, temp_dir)
in_file.close()
datapackage_json = os.path.join(temp_dir, 'datapackage.json')
package = gobble.fiscal.FiscalDataPackage(datapackage_json, user=user)
package.upload(skip_validation=True, publish=False)
| import os
import zipfile
import tempfile
from datapackage_pipelines.wrapper import ingest, spew
import gobble
params, datapackage, res_iter = ingest()
spew(datapackage, res_iter)
user = gobble.user.User()
in_filename = open(params['in-file'], 'rb')
in_file = zipfile.ZipFile(in_filename)
temp_dir = tempfile.mkdtemp()
for name in in_file.namelist():
in_file.extract(name, temp_dir)
in_file.close()
datapackage_json = os.path.join(temp_dir, 'datapackage.json')
package = gobble.fiscal.FiscalDataPackage(datapackage_json, user=user)
package.upload(skip_validation=True, publish=params.get('publish', False))
| Set the publication with a parameter. | Set the publication with a parameter. | Python | mit | openspending/datapackage-pipelines-fiscal | import os
import zipfile
import tempfile
from datapackage_pipelines.wrapper import ingest, spew
import gobble
params, datapackage, res_iter = ingest()
spew(datapackage, res_iter)
user = gobble.user.User()
in_filename = open(params['in-file'], 'rb')
in_file = zipfile.ZipFile(in_filename)
temp_dir = tempfile.mkdtemp()
for name in in_file.namelist():
in_file.extract(name, temp_dir)
in_file.close()
datapackage_json = os.path.join(temp_dir, 'datapackage.json')
package = gobble.fiscal.FiscalDataPackage(datapackage_json, user=user)
- package.upload(skip_validation=True, publish=False)
+ package.upload(skip_validation=True, publish=params.get('publish', False))
| Set the publication with a parameter. | ## Code Before:
import os
import zipfile
import tempfile
from datapackage_pipelines.wrapper import ingest, spew
import gobble
params, datapackage, res_iter = ingest()
spew(datapackage, res_iter)
user = gobble.user.User()
in_filename = open(params['in-file'], 'rb')
in_file = zipfile.ZipFile(in_filename)
temp_dir = tempfile.mkdtemp()
for name in in_file.namelist():
in_file.extract(name, temp_dir)
in_file.close()
datapackage_json = os.path.join(temp_dir, 'datapackage.json')
package = gobble.fiscal.FiscalDataPackage(datapackage_json, user=user)
package.upload(skip_validation=True, publish=False)
## Instruction:
Set the publication with a parameter.
## Code After:
import os
import zipfile
import tempfile
from datapackage_pipelines.wrapper import ingest, spew
import gobble
params, datapackage, res_iter = ingest()
spew(datapackage, res_iter)
user = gobble.user.User()
in_filename = open(params['in-file'], 'rb')
in_file = zipfile.ZipFile(in_filename)
temp_dir = tempfile.mkdtemp()
for name in in_file.namelist():
in_file.extract(name, temp_dir)
in_file.close()
datapackage_json = os.path.join(temp_dir, 'datapackage.json')
package = gobble.fiscal.FiscalDataPackage(datapackage_json, user=user)
package.upload(skip_validation=True, publish=params.get('publish', False))
|
ec4d84e0b67d26dd9888d1b54adda6fbbcdc67da | packages/blueprints/api.py | packages/blueprints/api.py | from flask import Blueprint, render_template, abort, request, redirect, session, url_for
from flask.ext.login import current_user, login_user
from sqlalchemy import desc
from packages.objects import *
from packages.common import *
from packages.config import _cfg
import os
import zipfile
import urllib
api = Blueprint('api', __name__)
@api.route("/test")
@json_output
def test():
return { 'value': 'Hello world!' }
| from flask import Blueprint, render_template, abort, request, redirect, session, url_for
from flask.ext.login import current_user, login_user
from sqlalchemy import desc
from packages.objects import *
from packages.common import *
from packages.config import _cfg
import os
import zipfile
import urllib
api = Blueprint('api', __name__)
@api.route("/api/v1/login", methods=['POST'])
@json_output
def login():
username = request.form['username']
password = request.form['password']
user = User.query.filter(User.username.ilike(username)).first()
if not user:
return { 'success': False, 'error': 'Your username or password is incorrect.' }
if user.confirmation != '' and user.confirmation != None:
return { 'success': False, 'error': 'Your account is pending. Check your email or contact [email protected]' }
if not bcrypt.checkpw(password, user.password):
return { 'success': False, 'error': 'Your username or password is incorrect.' }
login_user(user)
return { 'success': True }
| Add API endpoint for logging in | Add API endpoint for logging in
| Python | mit | KnightOS/packages.knightos.org,MaxLeiter/packages.knightos.org,MaxLeiter/packages.knightos.org,KnightOS/packages.knightos.org,KnightOS/packages.knightos.org,MaxLeiter/packages.knightos.org | from flask import Blueprint, render_template, abort, request, redirect, session, url_for
from flask.ext.login import current_user, login_user
from sqlalchemy import desc
from packages.objects import *
from packages.common import *
from packages.config import _cfg
import os
import zipfile
import urllib
api = Blueprint('api', __name__)
- @api.route("/test")
+ @api.route("/api/v1/login", methods=['POST'])
@json_output
- def test():
- return { 'value': 'Hello world!' }
+ def login():
+ username = request.form['username']
+ password = request.form['password']
+ user = User.query.filter(User.username.ilike(username)).first()
+ if not user:
+ return { 'success': False, 'error': 'Your username or password is incorrect.' }
+ if user.confirmation != '' and user.confirmation != None:
+ return { 'success': False, 'error': 'Your account is pending. Check your email or contact [email protected]' }
+ if not bcrypt.checkpw(password, user.password):
+ return { 'success': False, 'error': 'Your username or password is incorrect.' }
+ login_user(user)
+ return { 'success': True }
| Add API endpoint for logging in | ## Code Before:
from flask import Blueprint, render_template, abort, request, redirect, session, url_for
from flask.ext.login import current_user, login_user
from sqlalchemy import desc
from packages.objects import *
from packages.common import *
from packages.config import _cfg
import os
import zipfile
import urllib
api = Blueprint('api', __name__)
@api.route("/test")
@json_output
def test():
return { 'value': 'Hello world!' }
## Instruction:
Add API endpoint for logging in
## Code After:
from flask import Blueprint, render_template, abort, request, redirect, session, url_for
from flask.ext.login import current_user, login_user
from sqlalchemy import desc
from packages.objects import *
from packages.common import *
from packages.config import _cfg
import os
import zipfile
import urllib
api = Blueprint('api', __name__)
@api.route("/api/v1/login", methods=['POST'])
@json_output
def login():
username = request.form['username']
password = request.form['password']
user = User.query.filter(User.username.ilike(username)).first()
if not user:
return { 'success': False, 'error': 'Your username or password is incorrect.' }
if user.confirmation != '' and user.confirmation != None:
return { 'success': False, 'error': 'Your account is pending. Check your email or contact [email protected]' }
if not bcrypt.checkpw(password, user.password):
return { 'success': False, 'error': 'Your username or password is incorrect.' }
login_user(user)
return { 'success': True }
|
58c97445c8d55d48e03498c758f7b7c6dee245aa | enabled/_50_admin_add_monitoring_panel.py | enabled/_50_admin_add_monitoring_panel.py | PANEL = 'monitoring'
# The name of the dashboard the PANEL associated with. Required.
PANEL_DASHBOARD = 'overcloud'
# The name of the panel group the PANEL is associated with.
#PANEL_GROUP = 'admin'
# Python panel class of the PANEL to be added.
ADD_PANEL = \
'monitoring.panel.Monitoring'
# A list of applications to be added to INSTALLED_APPS.
ADD_INSTALLED_APPS = ['monitoring']
| PANEL = 'monitoring'
# The name of the dashboard the PANEL associated with. Required.
PANEL_DASHBOARD = 'overcloud'
# The name of the panel group the PANEL is associated with.
#PANEL_GROUP = 'admin'
DEFAULT_PANEL = 'monitoring'
# Python panel class of the PANEL to be added.
ADD_PANEL = \
'monitoring.panel.Monitoring'
# A list of applications to be added to INSTALLED_APPS.
ADD_INSTALLED_APPS = ['monitoring']
# A list of angular modules to be added as dependencies to horizon app.
#ADD_ANGULAR_MODULE = ['monitoringApp']
| Set DEFAULT_PANEL to monitoring panel | Set DEFAULT_PANEL to monitoring panel
| Python | apache-2.0 | stackforge/monasca-ui,openstack/monasca-ui,openstack/monasca-ui,stackforge/monasca-ui,openstack/monasca-ui,openstack/monasca-ui,stackforge/monasca-ui,stackforge/monasca-ui | PANEL = 'monitoring'
# The name of the dashboard the PANEL associated with. Required.
PANEL_DASHBOARD = 'overcloud'
# The name of the panel group the PANEL is associated with.
#PANEL_GROUP = 'admin'
+
+ DEFAULT_PANEL = 'monitoring'
# Python panel class of the PANEL to be added.
ADD_PANEL = \
'monitoring.panel.Monitoring'
# A list of applications to be added to INSTALLED_APPS.
ADD_INSTALLED_APPS = ['monitoring']
+ # A list of angular modules to be added as dependencies to horizon app.
+ #ADD_ANGULAR_MODULE = ['monitoringApp']
+ | Set DEFAULT_PANEL to monitoring panel | ## Code Before:
PANEL = 'monitoring'
# The name of the dashboard the PANEL associated with. Required.
PANEL_DASHBOARD = 'overcloud'
# The name of the panel group the PANEL is associated with.
#PANEL_GROUP = 'admin'
# Python panel class of the PANEL to be added.
ADD_PANEL = \
'monitoring.panel.Monitoring'
# A list of applications to be added to INSTALLED_APPS.
ADD_INSTALLED_APPS = ['monitoring']
## Instruction:
Set DEFAULT_PANEL to monitoring panel
## Code After:
PANEL = 'monitoring'
# The name of the dashboard the PANEL associated with. Required.
PANEL_DASHBOARD = 'overcloud'
# The name of the panel group the PANEL is associated with.
#PANEL_GROUP = 'admin'
DEFAULT_PANEL = 'monitoring'
# Python panel class of the PANEL to be added.
ADD_PANEL = \
'monitoring.panel.Monitoring'
# A list of applications to be added to INSTALLED_APPS.
ADD_INSTALLED_APPS = ['monitoring']
# A list of angular modules to be added as dependencies to horizon app.
#ADD_ANGULAR_MODULE = ['monitoringApp']
|
7cedab4826d5d184e595864f4cf5ca3966a1921e | random_object_id/random_object_id.py | random_object_id/random_object_id.py | import binascii
import os
import time
from optparse import OptionParser
def gen_random_object_id():
timestamp = '{0:x}'.format(int(time.time()))
rest = binascii.b2a_hex(os.urandom(8)).decode('ascii')
return timestamp + rest
if __name__ == '__main__':
parser = OptionParser()
parser.add_option('-l', '--longform',
action="store_true",
dest="long_form",
help="prints the ID surrounded by ObjectId(...)")
(options, args) = parser.parse_args()
object_id = gen_random_object_id()
if options.long_form:
print('ObjectId("{}")'.format(object_id))
else:
print(object_id)
| import binascii
import os
import time
from argparse import ArgumentParser
def gen_random_object_id():
timestamp = '{0:x}'.format(int(time.time()))
rest = binascii.b2a_hex(os.urandom(8)).decode('ascii')
return timestamp + rest
if __name__ == '__main__':
parser = ArgumentParser(description='Generate a random MongoDB ObjectId')
parser.add_argument('-l', '--longform',
action="store_true",
dest="long_form",
help="prints the ID surrounded by ObjectId(...)")
args = parser.parse_args()
object_id = gen_random_object_id()
if args.long_form:
print('ObjectId("{}")'.format(object_id))
else:
print(object_id)
| Use argparse instead of optparse | Use argparse instead of optparse
| Python | mit | mxr/random-object-id | import binascii
import os
import time
- from optparse import OptionParser
+ from argparse import ArgumentParser
def gen_random_object_id():
timestamp = '{0:x}'.format(int(time.time()))
rest = binascii.b2a_hex(os.urandom(8)).decode('ascii')
return timestamp + rest
if __name__ == '__main__':
- parser = OptionParser()
+ parser = ArgumentParser(description='Generate a random MongoDB ObjectId')
- parser.add_option('-l', '--longform',
+ parser.add_argument('-l', '--longform',
- action="store_true",
+ action="store_true",
- dest="long_form",
+ dest="long_form",
- help="prints the ID surrounded by ObjectId(...)")
+ help="prints the ID surrounded by ObjectId(...)")
- (options, args) = parser.parse_args()
+ args = parser.parse_args()
object_id = gen_random_object_id()
- if options.long_form:
+ if args.long_form:
print('ObjectId("{}")'.format(object_id))
else:
print(object_id)
| Use argparse instead of optparse | ## Code Before:
import binascii
import os
import time
from optparse import OptionParser
def gen_random_object_id():
timestamp = '{0:x}'.format(int(time.time()))
rest = binascii.b2a_hex(os.urandom(8)).decode('ascii')
return timestamp + rest
if __name__ == '__main__':
parser = OptionParser()
parser.add_option('-l', '--longform',
action="store_true",
dest="long_form",
help="prints the ID surrounded by ObjectId(...)")
(options, args) = parser.parse_args()
object_id = gen_random_object_id()
if options.long_form:
print('ObjectId("{}")'.format(object_id))
else:
print(object_id)
## Instruction:
Use argparse instead of optparse
## Code After:
import binascii
import os
import time
from argparse import ArgumentParser
def gen_random_object_id():
timestamp = '{0:x}'.format(int(time.time()))
rest = binascii.b2a_hex(os.urandom(8)).decode('ascii')
return timestamp + rest
if __name__ == '__main__':
parser = ArgumentParser(description='Generate a random MongoDB ObjectId')
parser.add_argument('-l', '--longform',
action="store_true",
dest="long_form",
help="prints the ID surrounded by ObjectId(...)")
args = parser.parse_args()
object_id = gen_random_object_id()
if args.long_form:
print('ObjectId("{}")'.format(object_id))
else:
print(object_id)
|
404b9208d98753dfccffb6c87594cfc70faed073 | filer/tests/general.py | filer/tests/general.py | from django.test import TestCase
import filer
class GeneralTestCase(TestCase):
def test_version_is_set(self):
self.assertTrue(len(filer.get_version())>0)
def test_travisci_configuration(self):
self.assertTrue(False) | from django.test import TestCase
import filer
class GeneralTestCase(TestCase):
def test_version_is_set(self):
self.assertTrue(len(filer.get_version())>0) | Revert "travis ci: test if it REALLY works" | Revert "travis ci: test if it REALLY works"
This reverts commit 78d87177c71adea7cc06d968374d2c2197dc5289.
| Python | bsd-3-clause | Flight/django-filer,obigroup/django-filer,DylannCordel/django-filer,vstoykov/django-filer,o-zander/django-filer,mitar/django-filer,stefanfoulis/django-filer,skirsdeda/django-filer,thomasbilk/django-filer,kriwil/django-filer,sbussetti/django-filer,jakob-o/django-filer,lory87/django-filer,rollstudio/django-filer,Flight/django-filer,jrief/django-filer,lory87/django-filer,mitar/django-filer,pbs/django-filer,DylannCordel/django-filer,sopraux/django-filer,fusionbox/django-filer,jakob-o/django-filer,alexandrupirjol/django-filer,belimawr/django-filer,SmithsonianEnterprises/django-filer,nimbis/django-filer,obigroup/django-filer,pbs/django-filer,skirsdeda/django-filer,SmithsonianEnterprises/django-filer,rollstudio/django-filer,samastur/django-filer,mkoistinen/django-filer,20tab/django-filer,skirsdeda/django-filer,stefanfoulis/django-filer,webu/django-filer,jakob-o/django-filer,vechorko/django-filer,dbrgn/django-filer,dereknutile/django-filer,skirsdeda/django-filer,nimbis/django-filer,mbrochh/django-filer,kriwil/django-filer,SmithsonianEnterprises/django-filer,DylannCordel/django-filer,neoascetic/django-filer,lory87/django-filer,pbs/django-filer,mitar/django-filer,stefanfoulis/django-filer-travis-testing,nimbis/django-filer,matthiask/django-filer,rollstudio/django-filer,civicresourcegroup/django-filer,jrief/django-filer,belimawr/django-filer,Flight/django-filer,bogdal/django-filer,DylannCordel/django-filer,divio/django-filer,jakob-o/django-filer,maikelwever/django-filer,bogdal/django-filer,matthiask/django-filer,maykinmedia/django-filer,dereknutile/django-filer,vechorko/django-filer,maykinmedia/django-filer,sbussetti/django-filer,stefanfoulis/django-filer-travis-testing,pbs/django-filer,o-zander/django-filer,maikelwever/django-filer,sopraux/django-filer,civicresourcegroup/django-filer,DylannCordel/django-filer,fusionbox/django-filer,vechorko/django-filer,nephila/django-filer,skirsdeda/django-filer,webu/django-filer,sopraux/django-filer,neoascetic/django-filer,belimawr/django-filer,neoascetic/django-filer,mbrochh/django-filer,BertrandBordage/django-filer,matthiask/django-filer,20tab/django-filer,civicresourcegroup/django-filer,pbs/django-filer,stefanfoulis/django-filer,jakob-o/django-filer,matthiask/django-filer,kriwil/django-filer,kriwil/django-filer,sopraux/django-filer,divio/django-filer,jrief/django-filer,dbrgn/django-filer,vechorko/django-filer,divio/django-filer,writepython/django-filer,nimbis/django-filer,BertrandBordage/django-filer,nephila/django-filer,nephila/django-filer,stefanfoulis/django-filer,writepython/django-filer,mkoistinen/django-filer,mbrochh/django-filer,mkoistinen/django-filer,BertrandBordage/django-filer,thomasbilk/django-filer,writepython/django-filer,jrutila/django-filer,webu/django-filer,stefanfoulis/django-filer-travis-testing,dbrgn/django-filer,maykinmedia/django-filer,Flight/django-filer,alexandrupirjol/django-filer,vstoykov/django-filer,bogdal/django-filer,webu/django-filer,samastur/django-filer,fusionbox/django-filer,stefanfoulis/django-filer,divio/django-filer,SmithsonianEnterprises/django-filer,20tab/django-filer,thomasbilk/django-filer,o-zander/django-filer,jrutila/django-filer,obigroup/django-filer,dubizzle/django-filer,Flight/django-filer,civicresourcegroup/django-filer,lory87/django-filer,jrutila/django-filer,sbussetti/django-filer,alexandrupirjol/django-filer,vstoykov/django-filer,mkoistinen/django-filer,dubizzle/django-filer,o-zander/django-filer,belimawr/django-filer,maikelwever/django-filer,dereknutile/django-filer,dubizzle/django-filer,samastur/django-filer | from django.test import TestCase
import filer
class GeneralTestCase(TestCase):
def test_version_is_set(self):
self.assertTrue(len(filer.get_version())>0)
-
- def test_travisci_configuration(self):
- self.assertTrue(False) | Revert "travis ci: test if it REALLY works" | ## Code Before:
from django.test import TestCase
import filer
class GeneralTestCase(TestCase):
def test_version_is_set(self):
self.assertTrue(len(filer.get_version())>0)
def test_travisci_configuration(self):
self.assertTrue(False)
## Instruction:
Revert "travis ci: test if it REALLY works"
## Code After:
from django.test import TestCase
import filer
class GeneralTestCase(TestCase):
def test_version_is_set(self):
self.assertTrue(len(filer.get_version())>0) |
ffb8f3f0d1fe17e13b349f8f4bae8fd9acbbd146 | linter.py | linter.py |
"""This module exports the RamlCop plugin class."""
from SublimeLinter.lint import NodeLinter
class RamlCop(NodeLinter):
"""Provides an interface to raml-cop."""
syntax = 'raml'
cmd = 'raml-cop --no-color'
version_requirement = '>= 1.0.0'
regex = (
r'^\[.+:(?P<line>\d+):(?P<col>\d+)\] '
r'(?:(?P<warning>WARNING)|(?P<error>ERROR)) '
r'(?P<message>.+)'
)
line_col_base = (0, 0)
|
"""This module exports the RamlCop plugin class."""
from SublimeLinter.lint import NodeLinter
class RamlCop(NodeLinter):
"""Provides an interface to raml-cop."""
syntax = 'raml'
cmd = 'raml-cop --no-color'
version_requirement = '>= 1.0.0'
regex = (
r'^\[.+:(?P<line>\d+):(?P<col>\d+)\] '
r'(?P<message>.+)'
)
line_col_base = (0, 0)
| Update regex to match new parser output | Update regex to match new parser output
| Python | mit | thebinarypenguin/SublimeLinter-contrib-raml-cop |
"""This module exports the RamlCop plugin class."""
from SublimeLinter.lint import NodeLinter
class RamlCop(NodeLinter):
"""Provides an interface to raml-cop."""
syntax = 'raml'
cmd = 'raml-cop --no-color'
version_requirement = '>= 1.0.0'
regex = (
r'^\[.+:(?P<line>\d+):(?P<col>\d+)\] '
- r'(?:(?P<warning>WARNING)|(?P<error>ERROR)) '
r'(?P<message>.+)'
)
line_col_base = (0, 0)
| Update regex to match new parser output | ## Code Before:
"""This module exports the RamlCop plugin class."""
from SublimeLinter.lint import NodeLinter
class RamlCop(NodeLinter):
"""Provides an interface to raml-cop."""
syntax = 'raml'
cmd = 'raml-cop --no-color'
version_requirement = '>= 1.0.0'
regex = (
r'^\[.+:(?P<line>\d+):(?P<col>\d+)\] '
r'(?:(?P<warning>WARNING)|(?P<error>ERROR)) '
r'(?P<message>.+)'
)
line_col_base = (0, 0)
## Instruction:
Update regex to match new parser output
## Code After:
"""This module exports the RamlCop plugin class."""
from SublimeLinter.lint import NodeLinter
class RamlCop(NodeLinter):
"""Provides an interface to raml-cop."""
syntax = 'raml'
cmd = 'raml-cop --no-color'
version_requirement = '>= 1.0.0'
regex = (
r'^\[.+:(?P<line>\d+):(?P<col>\d+)\] '
r'(?P<message>.+)'
)
line_col_base = (0, 0)
|
69c81b16e07b67ba0a0bc8e1f55049e7987c5b8c | openstack_dashboard/dashboards/admin/instances/panel.py | openstack_dashboard/dashboards/admin/instances/panel.py |
from django.utils.translation import ugettext_lazy as _
import horizon
class Instances(horizon.Panel):
name = _("Instances")
slug = 'instances'
permissions = ('openstack.services.compute',)
policy_rules = ((("compute", "context_is_admin"),
("compute", "compute:get_all")),)
|
from django.utils.translation import ugettext_lazy as _
import horizon
class Instances(horizon.Panel):
name = _("Instances")
slug = 'instances'
permissions = ('openstack.services.compute',)
policy_rules = ((("compute", "context_is_admin"),
("compute", "os_compute_api:servers:detail")),)
| Fix an incorrect policy rule in Admin > Instances | Fix an incorrect policy rule in Admin > Instances
Change-Id: I765ae0c36d19c88138fbea9545a2ca4791377ffb
Closes-Bug: #1703066
| Python | apache-2.0 | BiznetGIO/horizon,BiznetGIO/horizon,noironetworks/horizon,ChameleonCloud/horizon,yeming233/horizon,NeCTAR-RC/horizon,yeming233/horizon,BiznetGIO/horizon,yeming233/horizon,openstack/horizon,noironetworks/horizon,NeCTAR-RC/horizon,yeming233/horizon,ChameleonCloud/horizon,NeCTAR-RC/horizon,noironetworks/horizon,openstack/horizon,ChameleonCloud/horizon,openstack/horizon,BiznetGIO/horizon,ChameleonCloud/horizon,openstack/horizon,noironetworks/horizon,NeCTAR-RC/horizon |
from django.utils.translation import ugettext_lazy as _
import horizon
class Instances(horizon.Panel):
name = _("Instances")
slug = 'instances'
permissions = ('openstack.services.compute',)
policy_rules = ((("compute", "context_is_admin"),
- ("compute", "compute:get_all")),)
+ ("compute", "os_compute_api:servers:detail")),)
| Fix an incorrect policy rule in Admin > Instances | ## Code Before:
from django.utils.translation import ugettext_lazy as _
import horizon
class Instances(horizon.Panel):
name = _("Instances")
slug = 'instances'
permissions = ('openstack.services.compute',)
policy_rules = ((("compute", "context_is_admin"),
("compute", "compute:get_all")),)
## Instruction:
Fix an incorrect policy rule in Admin > Instances
## Code After:
from django.utils.translation import ugettext_lazy as _
import horizon
class Instances(horizon.Panel):
name = _("Instances")
slug = 'instances'
permissions = ('openstack.services.compute',)
policy_rules = ((("compute", "context_is_admin"),
("compute", "os_compute_api:servers:detail")),)
|
5516b125bb00b928d85a044d3df777e1b0004d03 | ovp_organizations/migrations/0008_auto_20161207_1941.py | ovp_organizations/migrations/0008_auto_20161207_1941.py | from __future__ import unicode_literals
from django.db import migrations
from ovp_organizations.models import Organization
def add_members(apps, schema_editor):
for organization in Organization.objects.all():
organization.members.add(organization.owner)
def remove_members(apps, schema_editor):
for organization in Organization.objects.all():
organization.members.clear()
class Migration(migrations.Migration):
dependencies = [
('ovp_organizations', '0007_organization_members'),
]
operations = [
migrations.RunPython(add_members, reverse_code=remove_members)
]
| from __future__ import unicode_literals
from django.db import migrations
from ovp_organizations.models import Organization
def add_members(apps, schema_editor):
for organization in Organization.objects.only('pk', 'members').all():
organization.members.add(organization.owner)
def remove_members(apps, schema_editor):
for organization in Organization.objects.only('pk', 'members').all():
organization.members.clear()
class Migration(migrations.Migration):
dependencies = [
('ovp_organizations', '0007_organization_members'),
]
operations = [
migrations.RunPython(add_members, reverse_code=remove_members)
]
| Add ".only" restriction to query on migration 0008 | Add ".only" restriction to query on migration 0008
| Python | agpl-3.0 | OpenVolunteeringPlatform/django-ovp-organizations,OpenVolunteeringPlatform/django-ovp-organizations | from __future__ import unicode_literals
from django.db import migrations
from ovp_organizations.models import Organization
def add_members(apps, schema_editor):
- for organization in Organization.objects.all():
+ for organization in Organization.objects.only('pk', 'members').all():
organization.members.add(organization.owner)
def remove_members(apps, schema_editor):
- for organization in Organization.objects.all():
+ for organization in Organization.objects.only('pk', 'members').all():
organization.members.clear()
class Migration(migrations.Migration):
dependencies = [
('ovp_organizations', '0007_organization_members'),
]
operations = [
migrations.RunPython(add_members, reverse_code=remove_members)
]
| Add ".only" restriction to query on migration 0008 | ## Code Before:
from __future__ import unicode_literals
from django.db import migrations
from ovp_organizations.models import Organization
def add_members(apps, schema_editor):
for organization in Organization.objects.all():
organization.members.add(organization.owner)
def remove_members(apps, schema_editor):
for organization in Organization.objects.all():
organization.members.clear()
class Migration(migrations.Migration):
dependencies = [
('ovp_organizations', '0007_organization_members'),
]
operations = [
migrations.RunPython(add_members, reverse_code=remove_members)
]
## Instruction:
Add ".only" restriction to query on migration 0008
## Code After:
from __future__ import unicode_literals
from django.db import migrations
from ovp_organizations.models import Organization
def add_members(apps, schema_editor):
for organization in Organization.objects.only('pk', 'members').all():
organization.members.add(organization.owner)
def remove_members(apps, schema_editor):
for organization in Organization.objects.only('pk', 'members').all():
organization.members.clear()
class Migration(migrations.Migration):
dependencies = [
('ovp_organizations', '0007_organization_members'),
]
operations = [
migrations.RunPython(add_members, reverse_code=remove_members)
]
|
4ec16018192c1bd8fbe60a9e4c410c6c898149f0 | server/ec2spotmanager/migrations/0007_instance_type_to_list.py | server/ec2spotmanager/migrations/0007_instance_type_to_list.py | from __future__ import unicode_literals
from django.db import migrations, models
def instance_types_to_list(apps, schema_editor):
PoolConfiguration = apps.get_model("ec2spotmanager", "PoolConfiguration")
for pool in PoolConfiguration.objects.all():
pool.ec2_instance_types_list = [pool.ec2_instance_types]
pool.save()
class Migration(migrations.Migration):
dependencies = [
('ec2spotmanager', '0006_auto_20150625_2050'),
]
operations = [
migrations.AlterField(
model_name='poolconfiguration',
name='ec2_instance_type',
field=models.CharField(blank=True, max_length=1023, null=True),
),
migrations.RenameField(
model_name='poolconfiguration',
old_name='ec2_instance_type',
new_name='ec2_instance_types',
),
migrations.RunPython(instance_types_to_list),
]
| from __future__ import print_function, unicode_literals
import json
import sys
from django.db import migrations, models
def instance_type_to_list(apps, schema_editor):
PoolConfiguration = apps.get_model("ec2spotmanager", "PoolConfiguration")
for pool in PoolConfiguration.objects.all():
if pool.ec2_instance_type:
pool.ec2_instance_type = json.dumps([pool.ec2_instance_type])
pool.save()
def instance_type_from_list(apps, schema_editor):
PoolConfiguration = apps.get_model("ec2spotmanager", "PoolConfiguration")
for pool in PoolConfiguration.objects.all():
if pool.ec2_instance_types:
types = json.loads(pool.ec2_instance_types)
if len(types) > 1:
print("pool %d had instance types %r, choosing %s for reverse migration" % (pool.id, types, types[0]),
file=sys.stderr)
pool.ec2_instance_types = types[0]
pool.save()
class Migration(migrations.Migration):
dependencies = [
('ec2spotmanager', '0006_auto_20150625_2050'),
]
operations = [
migrations.AlterField(
model_name='poolconfiguration',
name='ec2_instance_type',
field=models.CharField(blank=True, max_length=1023, null=True),
),
migrations.RunPython(
code=instance_type_to_list,
reverse_code=instance_type_from_list,
),
migrations.RenameField(
model_name='poolconfiguration',
old_name='ec2_instance_type',
new_name='ec2_instance_types',
),
]
| Fix migration. Custom triggers are not run in data migrations. | Fix migration. Custom triggers are not run in data migrations.
| Python | mpl-2.0 | MozillaSecurity/FuzzManager,MozillaSecurity/FuzzManager,MozillaSecurity/FuzzManager,MozillaSecurity/FuzzManager | - from __future__ import unicode_literals
+ from __future__ import print_function, unicode_literals
+ import json
+ import sys
from django.db import migrations, models
- def instance_types_to_list(apps, schema_editor):
+ def instance_type_to_list(apps, schema_editor):
PoolConfiguration = apps.get_model("ec2spotmanager", "PoolConfiguration")
for pool in PoolConfiguration.objects.all():
+ if pool.ec2_instance_type:
- pool.ec2_instance_types_list = [pool.ec2_instance_types]
+ pool.ec2_instance_type = json.dumps([pool.ec2_instance_type])
- pool.save()
+ pool.save()
+
+
+ def instance_type_from_list(apps, schema_editor):
+ PoolConfiguration = apps.get_model("ec2spotmanager", "PoolConfiguration")
+ for pool in PoolConfiguration.objects.all():
+ if pool.ec2_instance_types:
+ types = json.loads(pool.ec2_instance_types)
+ if len(types) > 1:
+ print("pool %d had instance types %r, choosing %s for reverse migration" % (pool.id, types, types[0]),
+ file=sys.stderr)
+ pool.ec2_instance_types = types[0]
+ pool.save()
class Migration(migrations.Migration):
dependencies = [
('ec2spotmanager', '0006_auto_20150625_2050'),
]
operations = [
migrations.AlterField(
model_name='poolconfiguration',
name='ec2_instance_type',
field=models.CharField(blank=True, max_length=1023, null=True),
),
+ migrations.RunPython(
+ code=instance_type_to_list,
+ reverse_code=instance_type_from_list,
+ ),
migrations.RenameField(
model_name='poolconfiguration',
old_name='ec2_instance_type',
new_name='ec2_instance_types',
),
- migrations.RunPython(instance_types_to_list),
]
| Fix migration. Custom triggers are not run in data migrations. | ## Code Before:
from __future__ import unicode_literals
from django.db import migrations, models
def instance_types_to_list(apps, schema_editor):
PoolConfiguration = apps.get_model("ec2spotmanager", "PoolConfiguration")
for pool in PoolConfiguration.objects.all():
pool.ec2_instance_types_list = [pool.ec2_instance_types]
pool.save()
class Migration(migrations.Migration):
dependencies = [
('ec2spotmanager', '0006_auto_20150625_2050'),
]
operations = [
migrations.AlterField(
model_name='poolconfiguration',
name='ec2_instance_type',
field=models.CharField(blank=True, max_length=1023, null=True),
),
migrations.RenameField(
model_name='poolconfiguration',
old_name='ec2_instance_type',
new_name='ec2_instance_types',
),
migrations.RunPython(instance_types_to_list),
]
## Instruction:
Fix migration. Custom triggers are not run in data migrations.
## Code After:
from __future__ import print_function, unicode_literals
import json
import sys
from django.db import migrations, models
def instance_type_to_list(apps, schema_editor):
PoolConfiguration = apps.get_model("ec2spotmanager", "PoolConfiguration")
for pool in PoolConfiguration.objects.all():
if pool.ec2_instance_type:
pool.ec2_instance_type = json.dumps([pool.ec2_instance_type])
pool.save()
def instance_type_from_list(apps, schema_editor):
PoolConfiguration = apps.get_model("ec2spotmanager", "PoolConfiguration")
for pool in PoolConfiguration.objects.all():
if pool.ec2_instance_types:
types = json.loads(pool.ec2_instance_types)
if len(types) > 1:
print("pool %d had instance types %r, choosing %s for reverse migration" % (pool.id, types, types[0]),
file=sys.stderr)
pool.ec2_instance_types = types[0]
pool.save()
class Migration(migrations.Migration):
dependencies = [
('ec2spotmanager', '0006_auto_20150625_2050'),
]
operations = [
migrations.AlterField(
model_name='poolconfiguration',
name='ec2_instance_type',
field=models.CharField(blank=True, max_length=1023, null=True),
),
migrations.RunPython(
code=instance_type_to_list,
reverse_code=instance_type_from_list,
),
migrations.RenameField(
model_name='poolconfiguration',
old_name='ec2_instance_type',
new_name='ec2_instance_types',
),
]
|
19cd85215a7a305e6f253405a88d087aef114811 | candidates/tests/test_constituencies_view.py | candidates/tests/test_constituencies_view.py | import re
from django_webtest import WebTest
class TestConstituencyDetailView(WebTest):
def test_constituencies_page(self):
# Just a smoke test to check that the page loads:
response = self.app.get('/constituencies')
aberdeen_north = response.html.find(
'a', text=re.compile(r'York Outer')
)
self.assertTrue(aberdeen_north)
| import re
from mock import patch
from django_webtest import WebTest
class TestConstituencyDetailView(WebTest):
@patch('candidates.popit.PopIt')
def test_constituencies_page(self, mock_popit):
# Just a smoke test to check that the page loads:
response = self.app.get('/constituencies')
aberdeen_north = response.html.find(
'a', text=re.compile(r'York Outer')
)
self.assertTrue(aberdeen_north)
| Make test_constituencies_page work without PopIt | Make test_constituencies_page work without PopIt
| Python | agpl-3.0 | DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,neavouli/yournextrepresentative,DemocracyClub/yournextrepresentative,YoQuieroSaber/yournextrepresentative,mysociety/yournextrepresentative,YoQuieroSaber/yournextrepresentative,YoQuieroSaber/yournextrepresentative,openstate/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextrepresentative,YoQuieroSaber/yournextrepresentative,mysociety/yournextmp-popit,neavouli/yournextrepresentative,datamade/yournextmp-popit,datamade/yournextmp-popit,datamade/yournextmp-popit,openstate/yournextrepresentative,openstate/yournextrepresentative,openstate/yournextrepresentative,neavouli/yournextrepresentative,mysociety/yournextmp-popit,neavouli/yournextrepresentative,YoQuieroSaber/yournextrepresentative,datamade/yournextmp-popit,DemocracyClub/yournextrepresentative,datamade/yournextmp-popit,mysociety/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,openstate/yournextrepresentative,neavouli/yournextrepresentative | import re
+
+ from mock import patch
from django_webtest import WebTest
class TestConstituencyDetailView(WebTest):
+ @patch('candidates.popit.PopIt')
- def test_constituencies_page(self):
+ def test_constituencies_page(self, mock_popit):
# Just a smoke test to check that the page loads:
response = self.app.get('/constituencies')
aberdeen_north = response.html.find(
'a', text=re.compile(r'York Outer')
)
self.assertTrue(aberdeen_north)
| Make test_constituencies_page work without PopIt | ## Code Before:
import re
from django_webtest import WebTest
class TestConstituencyDetailView(WebTest):
def test_constituencies_page(self):
# Just a smoke test to check that the page loads:
response = self.app.get('/constituencies')
aberdeen_north = response.html.find(
'a', text=re.compile(r'York Outer')
)
self.assertTrue(aberdeen_north)
## Instruction:
Make test_constituencies_page work without PopIt
## Code After:
import re
from mock import patch
from django_webtest import WebTest
class TestConstituencyDetailView(WebTest):
@patch('candidates.popit.PopIt')
def test_constituencies_page(self, mock_popit):
# Just a smoke test to check that the page loads:
response = self.app.get('/constituencies')
aberdeen_north = response.html.find(
'a', text=re.compile(r'York Outer')
)
self.assertTrue(aberdeen_north)
|
723a102d6272e7ba4b9df405b7c1493c34ac5b77 | masters/master.chromium.fyi/master_site_config.py | masters/master.chromium.fyi/master_site_config.py |
"""ActiveMaster definition."""
from config_bootstrap import Master
class ChromiumFYI(Master.Master1):
project_name = 'Chromium FYI'
master_port = 8011
slave_port = 8111
master_port_alt = 8211
buildbot_url = 'http://build.chromium.org/p/chromium.fyi/'
reboot_on_step_timeout = True
pubsub_service_account_file = 'service-account-pubsub.json'
pubsub_topic_url = 'projects/luci-milo/topics/public-buildbot'
name = 'chromium.fyi'
|
"""ActiveMaster definition."""
from config_bootstrap import Master
class ChromiumFYI(Master.Master1):
project_name = 'Chromium FYI'
master_port = 8011
slave_port = 8111
master_port_alt = 8211
buildbot_url = 'http://build.chromium.org/p/chromium.fyi/'
reboot_on_step_timeout = True
| Revert pubsub roll on FYI | Revert pubsub roll on FYI
BUG=
TBR=estaab
Review URL: https://codereview.chromium.org/1688503002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@298680 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | eunchong/build,eunchong/build,eunchong/build,eunchong/build |
"""ActiveMaster definition."""
from config_bootstrap import Master
class ChromiumFYI(Master.Master1):
project_name = 'Chromium FYI'
master_port = 8011
slave_port = 8111
master_port_alt = 8211
buildbot_url = 'http://build.chromium.org/p/chromium.fyi/'
reboot_on_step_timeout = True
- pubsub_service_account_file = 'service-account-pubsub.json'
- pubsub_topic_url = 'projects/luci-milo/topics/public-buildbot'
- name = 'chromium.fyi'
| Revert pubsub roll on FYI | ## Code Before:
"""ActiveMaster definition."""
from config_bootstrap import Master
class ChromiumFYI(Master.Master1):
project_name = 'Chromium FYI'
master_port = 8011
slave_port = 8111
master_port_alt = 8211
buildbot_url = 'http://build.chromium.org/p/chromium.fyi/'
reboot_on_step_timeout = True
pubsub_service_account_file = 'service-account-pubsub.json'
pubsub_topic_url = 'projects/luci-milo/topics/public-buildbot'
name = 'chromium.fyi'
## Instruction:
Revert pubsub roll on FYI
## Code After:
"""ActiveMaster definition."""
from config_bootstrap import Master
class ChromiumFYI(Master.Master1):
project_name = 'Chromium FYI'
master_port = 8011
slave_port = 8111
master_port_alt = 8211
buildbot_url = 'http://build.chromium.org/p/chromium.fyi/'
reboot_on_step_timeout = True
|
39d3f605d240a8abef22107424ec1d6f76161580 | static_precompiler/models.py | static_precompiler/models.py | from django.db import models
class Dependency(models.Model):
source = models.CharField(max_length=255, db_index=True)
depends_on = models.CharField(max_length=255, db_index=True)
class Meta:
unique_together = ("source", "depends_on")
| from __future__ import unicode_literals
from django.db import models
class Dependency(models.Model):
source = models.CharField(max_length=255, db_index=True)
depends_on = models.CharField(max_length=255, db_index=True)
class Meta:
unique_together = ("source", "depends_on")
def __unicode__(self):
return "{0} depends on {1}".format(self.source, self.depends_on)
| Add __unicode__ to Dependency model | Add __unicode__ to Dependency model
| Python | mit | jaheba/django-static-precompiler,jaheba/django-static-precompiler,paera/django-static-precompiler,liumengjun/django-static-precompiler,jaheba/django-static-precompiler,liumengjun/django-static-precompiler,paera/django-static-precompiler,liumengjun/django-static-precompiler,liumengjun/django-static-precompiler,liumengjun/django-static-precompiler,paera/django-static-precompiler,paera/django-static-precompiler,jaheba/django-static-precompiler | + from __future__ import unicode_literals
from django.db import models
class Dependency(models.Model):
source = models.CharField(max_length=255, db_index=True)
depends_on = models.CharField(max_length=255, db_index=True)
class Meta:
unique_together = ("source", "depends_on")
+ def __unicode__(self):
+ return "{0} depends on {1}".format(self.source, self.depends_on)
+ | Add __unicode__ to Dependency model | ## Code Before:
from django.db import models
class Dependency(models.Model):
source = models.CharField(max_length=255, db_index=True)
depends_on = models.CharField(max_length=255, db_index=True)
class Meta:
unique_together = ("source", "depends_on")
## Instruction:
Add __unicode__ to Dependency model
## Code After:
from __future__ import unicode_literals
from django.db import models
class Dependency(models.Model):
source = models.CharField(max_length=255, db_index=True)
depends_on = models.CharField(max_length=255, db_index=True)
class Meta:
unique_together = ("source", "depends_on")
def __unicode__(self):
return "{0} depends on {1}".format(self.source, self.depends_on)
|
d2051073d48873408a711b56676ee099e5ff685a | sunpy/timeseries/__init__.py | sunpy/timeseries/__init__.py | from __future__ import absolute_import
from sunpy.timeseries.metadata import TimeSeriesMetaData
from sunpy.timeseries.timeseries_factory import TimeSeries
from sunpy.timeseries.timeseriesbase import GenericTimeSeries
from sunpy.timeseries.sources.eve import EVESpWxTimeSeries
from sunpy.timeseries.sources.goes import XRSTimeSeries
from sunpy.timeseries.sources.noaa import NOAAIndicesTimeSeries, NOAAPredictIndicesTimeSeries
from sunpy.timeseries.sources.lyra import LYRATimeSeries
from sunpy.timeseries.sources.norh import NoRHTimeSeries
from sunpy.timeseries.sources.rhessi import RHESSISummaryTimeSeries
from sunpy.timeseries.sources.fermi_gbm import GBMSummaryTimeSeries
| from __future__ import absolute_import
from sunpy.timeseries.metadata import TimeSeriesMetaData
from sunpy.timeseries.timeseries_factory import TimeSeries
from sunpy.timeseries.timeseriesbase import GenericTimeSeries
from sunpy.timeseries.sources.eve import EVESpWxTimeSeries
from sunpy.timeseries.sources.goes import XRSTimeSeries
from sunpy.timeseries.sources.noaa import NOAAIndicesTimeSeries, NOAAPredictIndicesTimeSeries
from sunpy.timeseries.sources.lyra import LYRATimeSeries
from sunpy.timeseries.sources.norh import NoRHTimeSeries
from sunpy.timeseries.sources.rhessi import RHESSISummaryTimeSeries
from sunpy.timeseries.sources.fermi_gbm import GBMSummaryTimeSeries
# register pandas datetime converter with matplotlib
# This is to work around the change in pandas-dev/pandas#17710
import pandas.plotting._converter
pandas.plotting._converter.register()
| Fix matplotlib / pandas 0.21 bug in examples | Fix matplotlib / pandas 0.21 bug in examples
Here we manually register the pandas matplotlib converters so people
doing manual plotting with pandas works under pandas 0.21
| Python | bsd-2-clause | dpshelio/sunpy,dpshelio/sunpy,dpshelio/sunpy | from __future__ import absolute_import
from sunpy.timeseries.metadata import TimeSeriesMetaData
from sunpy.timeseries.timeseries_factory import TimeSeries
from sunpy.timeseries.timeseriesbase import GenericTimeSeries
from sunpy.timeseries.sources.eve import EVESpWxTimeSeries
from sunpy.timeseries.sources.goes import XRSTimeSeries
from sunpy.timeseries.sources.noaa import NOAAIndicesTimeSeries, NOAAPredictIndicesTimeSeries
from sunpy.timeseries.sources.lyra import LYRATimeSeries
from sunpy.timeseries.sources.norh import NoRHTimeSeries
from sunpy.timeseries.sources.rhessi import RHESSISummaryTimeSeries
from sunpy.timeseries.sources.fermi_gbm import GBMSummaryTimeSeries
+ # register pandas datetime converter with matplotlib
+ # This is to work around the change in pandas-dev/pandas#17710
+ import pandas.plotting._converter
+ pandas.plotting._converter.register()
+ | Fix matplotlib / pandas 0.21 bug in examples | ## Code Before:
from __future__ import absolute_import
from sunpy.timeseries.metadata import TimeSeriesMetaData
from sunpy.timeseries.timeseries_factory import TimeSeries
from sunpy.timeseries.timeseriesbase import GenericTimeSeries
from sunpy.timeseries.sources.eve import EVESpWxTimeSeries
from sunpy.timeseries.sources.goes import XRSTimeSeries
from sunpy.timeseries.sources.noaa import NOAAIndicesTimeSeries, NOAAPredictIndicesTimeSeries
from sunpy.timeseries.sources.lyra import LYRATimeSeries
from sunpy.timeseries.sources.norh import NoRHTimeSeries
from sunpy.timeseries.sources.rhessi import RHESSISummaryTimeSeries
from sunpy.timeseries.sources.fermi_gbm import GBMSummaryTimeSeries
## Instruction:
Fix matplotlib / pandas 0.21 bug in examples
## Code After:
from __future__ import absolute_import
from sunpy.timeseries.metadata import TimeSeriesMetaData
from sunpy.timeseries.timeseries_factory import TimeSeries
from sunpy.timeseries.timeseriesbase import GenericTimeSeries
from sunpy.timeseries.sources.eve import EVESpWxTimeSeries
from sunpy.timeseries.sources.goes import XRSTimeSeries
from sunpy.timeseries.sources.noaa import NOAAIndicesTimeSeries, NOAAPredictIndicesTimeSeries
from sunpy.timeseries.sources.lyra import LYRATimeSeries
from sunpy.timeseries.sources.norh import NoRHTimeSeries
from sunpy.timeseries.sources.rhessi import RHESSISummaryTimeSeries
from sunpy.timeseries.sources.fermi_gbm import GBMSummaryTimeSeries
# register pandas datetime converter with matplotlib
# This is to work around the change in pandas-dev/pandas#17710
import pandas.plotting._converter
pandas.plotting._converter.register()
|
2de7222ffd3d9f4cc7971ad142aa2542eb7ca117 | yunity/stores/models.py | yunity/stores/models.py | from config import settings
from yunity.base.base_models import BaseModel, LocationModel
from django.db import models
class PickupDate(BaseModel):
date = models.DateTimeField()
collectors = models.ManyToManyField(settings.AUTH_USER_MODEL)
store = models.ForeignKey('stores.store', related_name='pickupdates', on_delete=models.CASCADE)
max_collectors = models.IntegerField(null=True)
class Store(BaseModel, LocationModel):
group = models.ForeignKey('groups.Group', on_delete=models.CASCADE)
name = models.TextField()
description = models.TextField(null=True)
| from config import settings
from yunity.base.base_models import BaseModel, LocationModel
from django.db import models
class PickupDate(BaseModel):
date = models.DateTimeField()
collectors = models.ManyToManyField(settings.AUTH_USER_MODEL)
store = models.ForeignKey('stores.store', related_name='pickupdates', on_delete=models.CASCADE)
max_collectors = models.IntegerField(null=True)
class Store(BaseModel, LocationModel):
group = models.ForeignKey('groups.Group', on_delete=models.CASCADE, related_name='store')
name = models.TextField()
description = models.TextField(null=True)
| Add related name for group of store | Add related name for group of store
| Python | agpl-3.0 | yunity/yunity-core,yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend,yunity/foodsaving-backend | from config import settings
from yunity.base.base_models import BaseModel, LocationModel
from django.db import models
class PickupDate(BaseModel):
date = models.DateTimeField()
collectors = models.ManyToManyField(settings.AUTH_USER_MODEL)
store = models.ForeignKey('stores.store', related_name='pickupdates', on_delete=models.CASCADE)
max_collectors = models.IntegerField(null=True)
class Store(BaseModel, LocationModel):
- group = models.ForeignKey('groups.Group', on_delete=models.CASCADE)
+ group = models.ForeignKey('groups.Group', on_delete=models.CASCADE, related_name='store')
name = models.TextField()
description = models.TextField(null=True)
| Add related name for group of store | ## Code Before:
from config import settings
from yunity.base.base_models import BaseModel, LocationModel
from django.db import models
class PickupDate(BaseModel):
date = models.DateTimeField()
collectors = models.ManyToManyField(settings.AUTH_USER_MODEL)
store = models.ForeignKey('stores.store', related_name='pickupdates', on_delete=models.CASCADE)
max_collectors = models.IntegerField(null=True)
class Store(BaseModel, LocationModel):
group = models.ForeignKey('groups.Group', on_delete=models.CASCADE)
name = models.TextField()
description = models.TextField(null=True)
## Instruction:
Add related name for group of store
## Code After:
from config import settings
from yunity.base.base_models import BaseModel, LocationModel
from django.db import models
class PickupDate(BaseModel):
date = models.DateTimeField()
collectors = models.ManyToManyField(settings.AUTH_USER_MODEL)
store = models.ForeignKey('stores.store', related_name='pickupdates', on_delete=models.CASCADE)
max_collectors = models.IntegerField(null=True)
class Store(BaseModel, LocationModel):
group = models.ForeignKey('groups.Group', on_delete=models.CASCADE, related_name='store')
name = models.TextField()
description = models.TextField(null=True)
|
7ddc4b975910bf9c77b753e8e0aeaebc45949e4e | linkatos.py | linkatos.py | import os
import time
from slackclient import SlackClient
import pyrebase
import linkatos.parser as parser
import linkatos.confirmation as confirmation
import linkatos.printer as printer
import linkatos.utils as utils
import linkatos.firebase as fb
# starterbot environment variables
BOT_ID = os.environ.get("BOT_ID")
SLACK_BOT_TOKEN = os.environ.get("SLACK_BOT_TOKEN")
# instantiate Slack clients
slack_client = SlackClient(SLACK_BOT_TOKEN)
# firebase environment variables
FB_API_KEY = os.environ.get("FB_API_KEY")
FB_USER = os.environ.get("FB_USER")
FB_PASS = os.environ.get("FB_PASS")
# initialise firebase
project_name = 'coses-acbe6'
firebase = fb.initialise(FB_API_KEY, project_name)
# Main
if __name__ == '__main__':
READ_WEBSOCKET_DELAY = 1 # 1 second delay between reading from firehose
# verify linkatos connection
if slack_client.rtm_connect():
expecting_confirmation = False
url = None
while True:
(expecting_confirmation, url) = do.keep_wanted_urls(expecting_confirmation, url)
else:
print("Connection failed. Invalid Slack token or bot ID?")
| import os
import time
from slackclient import SlackClient
import pyrebase
import linkatos.firebase as fb
# starterbot environment variables
BOT_ID = os.environ.get("BOT_ID")
SLACK_BOT_TOKEN = os.environ.get("SLACK_BOT_TOKEN")
# instantiate Slack clients
slack_client = SlackClient(SLACK_BOT_TOKEN)
# firebase environment variables
FB_API_KEY = os.environ.get("FB_API_KEY")
FB_USER = os.environ.get("FB_USER")
FB_PASS = os.environ.get("FB_PASS")
# initialise firebase
project_name = 'coses-acbe6'
firebase = fb.initialise(FB_API_KEY, project_name)
# Main
if __name__ == '__main__':
READ_WEBSOCKET_DELAY = 1 # 1 second delay between reading from firehose
# verify linkatos connection
if slack_client.rtm_connect():
expecting_confirmation = False
url = None
while True:
(expecting_confirmation, url) = do.keep_wanted_urls(expecting_confirmation, url)
else:
print("Connection failed. Invalid Slack token or bot ID?")
| Remove old imports from main | refactor: Remove old imports from main
| Python | mit | iwi/linkatos,iwi/linkatos | import os
import time
from slackclient import SlackClient
import pyrebase
- import linkatos.parser as parser
- import linkatos.confirmation as confirmation
- import linkatos.printer as printer
- import linkatos.utils as utils
import linkatos.firebase as fb
# starterbot environment variables
BOT_ID = os.environ.get("BOT_ID")
SLACK_BOT_TOKEN = os.environ.get("SLACK_BOT_TOKEN")
# instantiate Slack clients
slack_client = SlackClient(SLACK_BOT_TOKEN)
# firebase environment variables
FB_API_KEY = os.environ.get("FB_API_KEY")
FB_USER = os.environ.get("FB_USER")
FB_PASS = os.environ.get("FB_PASS")
# initialise firebase
project_name = 'coses-acbe6'
firebase = fb.initialise(FB_API_KEY, project_name)
# Main
if __name__ == '__main__':
READ_WEBSOCKET_DELAY = 1 # 1 second delay between reading from firehose
# verify linkatos connection
if slack_client.rtm_connect():
expecting_confirmation = False
url = None
while True:
(expecting_confirmation, url) = do.keep_wanted_urls(expecting_confirmation, url)
else:
print("Connection failed. Invalid Slack token or bot ID?")
| Remove old imports from main | ## Code Before:
import os
import time
from slackclient import SlackClient
import pyrebase
import linkatos.parser as parser
import linkatos.confirmation as confirmation
import linkatos.printer as printer
import linkatos.utils as utils
import linkatos.firebase as fb
# starterbot environment variables
BOT_ID = os.environ.get("BOT_ID")
SLACK_BOT_TOKEN = os.environ.get("SLACK_BOT_TOKEN")
# instantiate Slack clients
slack_client = SlackClient(SLACK_BOT_TOKEN)
# firebase environment variables
FB_API_KEY = os.environ.get("FB_API_KEY")
FB_USER = os.environ.get("FB_USER")
FB_PASS = os.environ.get("FB_PASS")
# initialise firebase
project_name = 'coses-acbe6'
firebase = fb.initialise(FB_API_KEY, project_name)
# Main
if __name__ == '__main__':
READ_WEBSOCKET_DELAY = 1 # 1 second delay between reading from firehose
# verify linkatos connection
if slack_client.rtm_connect():
expecting_confirmation = False
url = None
while True:
(expecting_confirmation, url) = do.keep_wanted_urls(expecting_confirmation, url)
else:
print("Connection failed. Invalid Slack token or bot ID?")
## Instruction:
Remove old imports from main
## Code After:
import os
import time
from slackclient import SlackClient
import pyrebase
import linkatos.firebase as fb
# starterbot environment variables
BOT_ID = os.environ.get("BOT_ID")
SLACK_BOT_TOKEN = os.environ.get("SLACK_BOT_TOKEN")
# instantiate Slack clients
slack_client = SlackClient(SLACK_BOT_TOKEN)
# firebase environment variables
FB_API_KEY = os.environ.get("FB_API_KEY")
FB_USER = os.environ.get("FB_USER")
FB_PASS = os.environ.get("FB_PASS")
# initialise firebase
project_name = 'coses-acbe6'
firebase = fb.initialise(FB_API_KEY, project_name)
# Main
if __name__ == '__main__':
READ_WEBSOCKET_DELAY = 1 # 1 second delay between reading from firehose
# verify linkatos connection
if slack_client.rtm_connect():
expecting_confirmation = False
url = None
while True:
(expecting_confirmation, url) = do.keep_wanted_urls(expecting_confirmation, url)
else:
print("Connection failed. Invalid Slack token or bot ID?")
|
d5cd1eddf1ecf0c463a90d0e69413aadd311977a | lots/urls.py | lots/urls.py | from django.conf.urls import patterns, include, url
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'lots_client.views.home', name='home'),
url(r'^status/$', 'lots_client.views.status', name='status'),
url(r'^apply/$', 'lots_client.views.apply', name='apply'),
url(r'^apply-confirm/(?P<tracking_id>\S+)/$', 'lots_client.views.apply_confirm', name='apply_confirm'),
url(r'^faq/$', 'lots_client.views.faq', name='faq'),
url(r'^about/$', 'lots_client.views.about', name='about'),
url(r'^lots-admin/$', 'lots_admin.views.lots_admin', name='lots_admin'),
url(r'^lots-admin-map/$', 'lots_admin.views.lots_admin_map', name='lots_admin_map'),
url(r'^csv-dump/$', 'lots_admin.views.csv_dump', name='csv_dump'),
url(r'^lots-login/$', 'lots_admin.views.lots_login', name='lots_login'),
url(r'^logout/$', 'lots_admin.views.lots_logout', name='logout'),
url(r'^django-admin/', include(admin.site.urls)),
)
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.STATIC_ROOT,
}),)
| from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'lots_client.views.home', name='home'),
url(r'^status/$', 'lots_client.views.status', name='status'),
url(r'^apply/$', 'lots_client.views.apply', name='apply'),
url(r'^apply-confirm/(?P<tracking_id>\S+)/$', 'lots_client.views.apply_confirm', name='apply_confirm'),
url(r'^faq/$', 'lots_client.views.faq', name='faq'),
url(r'^about/$', 'lots_client.views.about', name='about'),
url(r'^lots-admin/$', 'lots_admin.views.lots_admin', name='lots_admin'),
url(r'^lots-admin-map/$', 'lots_admin.views.lots_admin_map', name='lots_admin_map'),
url(r'^csv-dump/$', 'lots_admin.views.csv_dump', name='csv_dump'),
url(r'^lots-login/$', 'lots_admin.views.lots_login', name='lots_login'),
url(r'^logout/$', 'lots_admin.views.lots_logout', name='logout'),
url(r'^django-admin/', include(admin.site.urls)),
)
| Revert "Picture access from admin console" | Revert "Picture access from admin console"
This reverts commit 324fa160fb629f6c4537ca15212c0822e8ac436d.
| Python | mit | opencleveland/large-lots,skorasaurus/large-lots,opencleveland/large-lots,skorasaurus/large-lots,skorasaurus/large-lots,skorasaurus/large-lots,opencleveland/large-lots,opencleveland/large-lots | from django.conf.urls import patterns, include, url
- from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'lots_client.views.home', name='home'),
url(r'^status/$', 'lots_client.views.status', name='status'),
url(r'^apply/$', 'lots_client.views.apply', name='apply'),
url(r'^apply-confirm/(?P<tracking_id>\S+)/$', 'lots_client.views.apply_confirm', name='apply_confirm'),
url(r'^faq/$', 'lots_client.views.faq', name='faq'),
url(r'^about/$', 'lots_client.views.about', name='about'),
url(r'^lots-admin/$', 'lots_admin.views.lots_admin', name='lots_admin'),
url(r'^lots-admin-map/$', 'lots_admin.views.lots_admin_map', name='lots_admin_map'),
url(r'^csv-dump/$', 'lots_admin.views.csv_dump', name='csv_dump'),
url(r'^lots-login/$', 'lots_admin.views.lots_login', name='lots_login'),
url(r'^logout/$', 'lots_admin.views.lots_logout', name='logout'),
+
url(r'^django-admin/', include(admin.site.urls)),
)
- urlpatterns += patterns('',
- url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
- 'document_root': settings.MEDIA_ROOT,
- }),
- url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {
- 'document_root': settings.STATIC_ROOT,
- }),)
- | Revert "Picture access from admin console" | ## Code Before:
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'lots_client.views.home', name='home'),
url(r'^status/$', 'lots_client.views.status', name='status'),
url(r'^apply/$', 'lots_client.views.apply', name='apply'),
url(r'^apply-confirm/(?P<tracking_id>\S+)/$', 'lots_client.views.apply_confirm', name='apply_confirm'),
url(r'^faq/$', 'lots_client.views.faq', name='faq'),
url(r'^about/$', 'lots_client.views.about', name='about'),
url(r'^lots-admin/$', 'lots_admin.views.lots_admin', name='lots_admin'),
url(r'^lots-admin-map/$', 'lots_admin.views.lots_admin_map', name='lots_admin_map'),
url(r'^csv-dump/$', 'lots_admin.views.csv_dump', name='csv_dump'),
url(r'^lots-login/$', 'lots_admin.views.lots_login', name='lots_login'),
url(r'^logout/$', 'lots_admin.views.lots_logout', name='logout'),
url(r'^django-admin/', include(admin.site.urls)),
)
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.STATIC_ROOT,
}),)
## Instruction:
Revert "Picture access from admin console"
## Code After:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'lots_client.views.home', name='home'),
url(r'^status/$', 'lots_client.views.status', name='status'),
url(r'^apply/$', 'lots_client.views.apply', name='apply'),
url(r'^apply-confirm/(?P<tracking_id>\S+)/$', 'lots_client.views.apply_confirm', name='apply_confirm'),
url(r'^faq/$', 'lots_client.views.faq', name='faq'),
url(r'^about/$', 'lots_client.views.about', name='about'),
url(r'^lots-admin/$', 'lots_admin.views.lots_admin', name='lots_admin'),
url(r'^lots-admin-map/$', 'lots_admin.views.lots_admin_map', name='lots_admin_map'),
url(r'^csv-dump/$', 'lots_admin.views.csv_dump', name='csv_dump'),
url(r'^lots-login/$', 'lots_admin.views.lots_login', name='lots_login'),
url(r'^logout/$', 'lots_admin.views.lots_logout', name='logout'),
url(r'^django-admin/', include(admin.site.urls)),
)
|
88a31ebcd7b65f9282bb0d0a19ad299c1ad431ec | spectral_cube/__init__.py | spectral_cube/__init__.py |
# Affiliated packages may add whatever they like to this file, but
# should keep this content at the top.
# ----------------------------------------------------------------------------
from ._astropy_init import *
# ----------------------------------------------------------------------------
if not _ASTROPY_SETUP_:
from .spectral_cube import SpectralCube, VaryingResolutionSpectralCube
from .stokes_spectral_cube import StokesSpectralCube
from .masks import *
|
# Affiliated packages may add whatever they like to this file, but
# should keep this content at the top.
# ----------------------------------------------------------------------------
from ._astropy_init import *
# ----------------------------------------------------------------------------
if not _ASTROPY_SETUP_:
from .spectral_cube import SpectralCube, VaryingResolutionSpectralCube
from .stokes_spectral_cube import StokesSpectralCube
from .masks import *
from .lower_dimensional_structures import Projection
| Make Projection importable from the top level of the package | Make Projection importable from the top level of the package
| Python | bsd-3-clause | e-koch/spectral-cube,jzuhone/spectral-cube,radio-astro-tools/spectral-cube,keflavich/spectral-cube,low-sky/spectral-cube |
# Affiliated packages may add whatever they like to this file, but
# should keep this content at the top.
# ----------------------------------------------------------------------------
from ._astropy_init import *
# ----------------------------------------------------------------------------
if not _ASTROPY_SETUP_:
from .spectral_cube import SpectralCube, VaryingResolutionSpectralCube
from .stokes_spectral_cube import StokesSpectralCube
from .masks import *
+ from .lower_dimensional_structures import Projection
| Make Projection importable from the top level of the package | ## Code Before:
# Affiliated packages may add whatever they like to this file, but
# should keep this content at the top.
# ----------------------------------------------------------------------------
from ._astropy_init import *
# ----------------------------------------------------------------------------
if not _ASTROPY_SETUP_:
from .spectral_cube import SpectralCube, VaryingResolutionSpectralCube
from .stokes_spectral_cube import StokesSpectralCube
from .masks import *
## Instruction:
Make Projection importable from the top level of the package
## Code After:
# Affiliated packages may add whatever they like to this file, but
# should keep this content at the top.
# ----------------------------------------------------------------------------
from ._astropy_init import *
# ----------------------------------------------------------------------------
if not _ASTROPY_SETUP_:
from .spectral_cube import SpectralCube, VaryingResolutionSpectralCube
from .stokes_spectral_cube import StokesSpectralCube
from .masks import *
from .lower_dimensional_structures import Projection
|
6a4046aafe43930c202e2f18a55b1cd8517d95f9 | testanalyzer/javaanalyzer.py | testanalyzer/javaanalyzer.py | import re
from fileanalyzer import FileAnalyzer
class JavaAnalyzer(FileAnalyzer):
def get_class_count(self, content):
return len(
re.findall("[a-zA-Z ]*class +[a-zA-Z0-9_]+ *\n*\{", content))
# TODO: Accept angle brackets and decline "else if"
def get_function_count(self, content):
return len(
re.findall(
"[a-zA-Z ]+ +[a-zA-Z0-9_]+ *\n*\([a-zA-Z0-9_,\[\] \n]*\)[a-zA-Z \n]*\{",
content))
| import re
from fileanalyzer import FileAnalyzer
class JavaAnalyzer(FileAnalyzer):
def get_class_count(self, content):
return len(
re.findall("[a-zA-Z ]*class +[a-zA-Z0-9_<>, ]+\n*\{", content))
def get_function_count(self, content):
matches = re.findall(
"[a-zA-Z <>]+ +[a-zA-Z0-9_]+ *\n*\([a-zA-Z0-9_,\[\]<>\?\. \n]*\)[a-zA-Z \n]*\{",
content)
matches = [
m for m in matches
if "if " not in m.strip() and "if(" not in m.strip()
]
return len(matches)
| Fix regex to match generics | Fix regex to match generics
| Python | mpl-2.0 | CheriPai/TestAnalyzer,CheriPai/TestAnalyzer,CheriPai/TestAnalyzer | import re
from fileanalyzer import FileAnalyzer
class JavaAnalyzer(FileAnalyzer):
def get_class_count(self, content):
return len(
- re.findall("[a-zA-Z ]*class +[a-zA-Z0-9_]+ *\n*\{", content))
+ re.findall("[a-zA-Z ]*class +[a-zA-Z0-9_<>, ]+\n*\{", content))
- # TODO: Accept angle brackets and decline "else if"
def get_function_count(self, content):
- return len(
- re.findall(
+ matches = re.findall(
- "[a-zA-Z ]+ +[a-zA-Z0-9_]+ *\n*\([a-zA-Z0-9_,\[\] \n]*\)[a-zA-Z \n]*\{",
+ "[a-zA-Z <>]+ +[a-zA-Z0-9_]+ *\n*\([a-zA-Z0-9_,\[\]<>\?\. \n]*\)[a-zA-Z \n]*\{",
- content))
+ content)
+ matches = [
+ m for m in matches
+ if "if " not in m.strip() and "if(" not in m.strip()
+ ]
+ return len(matches)
| Fix regex to match generics | ## Code Before:
import re
from fileanalyzer import FileAnalyzer
class JavaAnalyzer(FileAnalyzer):
def get_class_count(self, content):
return len(
re.findall("[a-zA-Z ]*class +[a-zA-Z0-9_]+ *\n*\{", content))
# TODO: Accept angle brackets and decline "else if"
def get_function_count(self, content):
return len(
re.findall(
"[a-zA-Z ]+ +[a-zA-Z0-9_]+ *\n*\([a-zA-Z0-9_,\[\] \n]*\)[a-zA-Z \n]*\{",
content))
## Instruction:
Fix regex to match generics
## Code After:
import re
from fileanalyzer import FileAnalyzer
class JavaAnalyzer(FileAnalyzer):
def get_class_count(self, content):
return len(
re.findall("[a-zA-Z ]*class +[a-zA-Z0-9_<>, ]+\n*\{", content))
def get_function_count(self, content):
matches = re.findall(
"[a-zA-Z <>]+ +[a-zA-Z0-9_]+ *\n*\([a-zA-Z0-9_,\[\]<>\?\. \n]*\)[a-zA-Z \n]*\{",
content)
matches = [
m for m in matches
if "if " not in m.strip() and "if(" not in m.strip()
]
return len(matches)
|
ea1c62ae3f13d47ee820eae31a2e284e3d66b6ab | libPiLite.py | libPiLite.py |
def createBlankGrid(row,column):
blankgrid = [[0 for x in range(column)] for y in range(row)]
return blankgrid
def getHeight(grid):
return len(grid)
def getWidth(grid):
return len(grid[0])
def printGrid(grid):
numRow = len(grid)
for i in range(0,numRow):
row = grid[i]
rowstr = ''
for j in row:
rowstr += str(j)+' '
print(rowstr)
def serializeGrid(grid):
numRow = len(grid)
numCol = len(grid[0])
gridstr = ''
for j in range(0,numCol):
for i in range(0,numRow):
gridstr += str(grid[i][j])
return gridstr
|
def createBlankGrid(row,column):
blankgrid = [[0 for x in range(column)] for y in range(row)]
return blankgrid
def getHeight(grid):
return len(grid)
def getWidth(grid):
return len(grid[0])
def printGrid(grid):
numRow = len(grid)
for i in range(0,numRow):
row = grid[i]
rowstr = ''
for j in row:
rowstr += str(j)+' '
print(rowstr)
def serializeGrid(grid):
numRow = len(grid)
numCol = len(grid[0])
gridstr = ''
for j in range(0,numCol):
for i in range(0,numRow):
gridstr += str(grid[i][j])
return gridstr
def setGrid(grid, setlist, rowoffset, coloffset):
for entry in setlist:
grid[entry[0]+rowoffset][entry[1]+coloffset] = 1
return grid
def resetGrid(grid, setlist, rowoffset, coloffset):
for entry in setlist:
grid[entry[0]+rowoffset][entry[1]+coloffset] = 0
return grid
| Add setGrid and resetGrid functions | Add setGrid and resetGrid functions
| Python | mit | rorasa/RPiClockArray |
def createBlankGrid(row,column):
blankgrid = [[0 for x in range(column)] for y in range(row)]
return blankgrid
def getHeight(grid):
return len(grid)
def getWidth(grid):
return len(grid[0])
def printGrid(grid):
numRow = len(grid)
for i in range(0,numRow):
row = grid[i]
rowstr = ''
for j in row:
rowstr += str(j)+' '
print(rowstr)
def serializeGrid(grid):
numRow = len(grid)
numCol = len(grid[0])
gridstr = ''
for j in range(0,numCol):
for i in range(0,numRow):
gridstr += str(grid[i][j])
return gridstr
-
+ def setGrid(grid, setlist, rowoffset, coloffset):
+ for entry in setlist:
+ grid[entry[0]+rowoffset][entry[1]+coloffset] = 1
+ return grid
+
+ def resetGrid(grid, setlist, rowoffset, coloffset):
+ for entry in setlist:
+ grid[entry[0]+rowoffset][entry[1]+coloffset] = 0
+ return grid
+ | Add setGrid and resetGrid functions | ## Code Before:
def createBlankGrid(row,column):
blankgrid = [[0 for x in range(column)] for y in range(row)]
return blankgrid
def getHeight(grid):
return len(grid)
def getWidth(grid):
return len(grid[0])
def printGrid(grid):
numRow = len(grid)
for i in range(0,numRow):
row = grid[i]
rowstr = ''
for j in row:
rowstr += str(j)+' '
print(rowstr)
def serializeGrid(grid):
numRow = len(grid)
numCol = len(grid[0])
gridstr = ''
for j in range(0,numCol):
for i in range(0,numRow):
gridstr += str(grid[i][j])
return gridstr
## Instruction:
Add setGrid and resetGrid functions
## Code After:
def createBlankGrid(row,column):
blankgrid = [[0 for x in range(column)] for y in range(row)]
return blankgrid
def getHeight(grid):
return len(grid)
def getWidth(grid):
return len(grid[0])
def printGrid(grid):
numRow = len(grid)
for i in range(0,numRow):
row = grid[i]
rowstr = ''
for j in row:
rowstr += str(j)+' '
print(rowstr)
def serializeGrid(grid):
numRow = len(grid)
numCol = len(grid[0])
gridstr = ''
for j in range(0,numCol):
for i in range(0,numRow):
gridstr += str(grid[i][j])
return gridstr
def setGrid(grid, setlist, rowoffset, coloffset):
for entry in setlist:
grid[entry[0]+rowoffset][entry[1]+coloffset] = 1
return grid
def resetGrid(grid, setlist, rowoffset, coloffset):
for entry in setlist:
grid[entry[0]+rowoffset][entry[1]+coloffset] = 0
return grid
|
e0b3b767ccb7fc601eb7b40d336f94d75f8aa43c | 2016/python/aoc_2016_03.py | 2016/python/aoc_2016_03.py | from __future__ import annotations
from typing import List, Tuple
from aoc_common import load_puzzle_input, report_solution
def parse_horizontal(string: str) -> List[Tuple[int, int, int]]:
"""Parse the instruction lines into sorted triples of side lengths."""
sorted_sides = [
sorted(int(x) for x in line.split()) for line in string.splitlines()
]
triples = [(sides[0], sides[1], sides[2]) for sides in sorted_sides]
return triples
def filter_valid_triangles(
triples: List[Tuple[int, int, int]]
) -> List[Tuple[int, int, int]]:
return [triple for triple in triples if triple[0] + triple[1] > triple[2]]
if __name__ == "__main__":
horizontal_triples = parse_horizontal(load_puzzle_input(day=3))
valid_horizontal = filter_valid_triangles(horizontal_triples)
report_solution(
puzzle_title="Day 3: Squares With Three Sides",
part_one_solution=len(valid_horizontal),
)
| from __future__ import annotations
from typing import List, Tuple
from aoc_common import load_puzzle_input, report_solution
def parse_horizontal(string: str) -> List[Tuple[int, int, int]]:
"""Parse the instruction lines into triples of side lengths."""
sides = [[int(x) for x in line.split()] for line in string.splitlines()]
return [(s[0], s[1], s[2]) for s in sides]
def filter_valid_triangles(
triples: List[Tuple[int, int, int]]
) -> List[Tuple[int, int, int]]:
triples = sort_sides(triples)
return [triple for triple in triples if triple[0] + triple[1] > triple[2]]
def sort_sides(triples: List[Tuple[int, int, int]]) -> List[Tuple[int, int, int]]:
return [(t[0], t[1], t[2]) for t in [sorted(sides) for sides in triples]]
if __name__ == "__main__":
horizontal_triples = parse_horizontal(load_puzzle_input(day=3))
valid_horizontal = filter_valid_triangles(horizontal_triples)
report_solution(
puzzle_title="Day 3: Squares With Three Sides",
part_one_solution=len(valid_horizontal),
)
| Sort triples in separate step | 2016-03.py: Sort triples in separate step
| Python | mit | robjwells/adventofcode-solutions,robjwells/adventofcode-solutions,robjwells/adventofcode-solutions,robjwells/adventofcode-solutions,robjwells/adventofcode-solutions,robjwells/adventofcode-solutions | from __future__ import annotations
from typing import List, Tuple
from aoc_common import load_puzzle_input, report_solution
def parse_horizontal(string: str) -> List[Tuple[int, int, int]]:
- """Parse the instruction lines into sorted triples of side lengths."""
+ """Parse the instruction lines into triples of side lengths."""
- sorted_sides = [
- sorted(int(x) for x in line.split()) for line in string.splitlines()
+ sides = [[int(x) for x in line.split()] for line in string.splitlines()]
+ return [(s[0], s[1], s[2]) for s in sides]
- ]
- triples = [(sides[0], sides[1], sides[2]) for sides in sorted_sides]
- return triples
def filter_valid_triangles(
triples: List[Tuple[int, int, int]]
) -> List[Tuple[int, int, int]]:
+ triples = sort_sides(triples)
return [triple for triple in triples if triple[0] + triple[1] > triple[2]]
+
+
+ def sort_sides(triples: List[Tuple[int, int, int]]) -> List[Tuple[int, int, int]]:
+ return [(t[0], t[1], t[2]) for t in [sorted(sides) for sides in triples]]
if __name__ == "__main__":
horizontal_triples = parse_horizontal(load_puzzle_input(day=3))
valid_horizontal = filter_valid_triangles(horizontal_triples)
report_solution(
puzzle_title="Day 3: Squares With Three Sides",
part_one_solution=len(valid_horizontal),
)
| Sort triples in separate step | ## Code Before:
from __future__ import annotations
from typing import List, Tuple
from aoc_common import load_puzzle_input, report_solution
def parse_horizontal(string: str) -> List[Tuple[int, int, int]]:
"""Parse the instruction lines into sorted triples of side lengths."""
sorted_sides = [
sorted(int(x) for x in line.split()) for line in string.splitlines()
]
triples = [(sides[0], sides[1], sides[2]) for sides in sorted_sides]
return triples
def filter_valid_triangles(
triples: List[Tuple[int, int, int]]
) -> List[Tuple[int, int, int]]:
return [triple for triple in triples if triple[0] + triple[1] > triple[2]]
if __name__ == "__main__":
horizontal_triples = parse_horizontal(load_puzzle_input(day=3))
valid_horizontal = filter_valid_triangles(horizontal_triples)
report_solution(
puzzle_title="Day 3: Squares With Three Sides",
part_one_solution=len(valid_horizontal),
)
## Instruction:
Sort triples in separate step
## Code After:
from __future__ import annotations
from typing import List, Tuple
from aoc_common import load_puzzle_input, report_solution
def parse_horizontal(string: str) -> List[Tuple[int, int, int]]:
"""Parse the instruction lines into triples of side lengths."""
sides = [[int(x) for x in line.split()] for line in string.splitlines()]
return [(s[0], s[1], s[2]) for s in sides]
def filter_valid_triangles(
triples: List[Tuple[int, int, int]]
) -> List[Tuple[int, int, int]]:
triples = sort_sides(triples)
return [triple for triple in triples if triple[0] + triple[1] > triple[2]]
def sort_sides(triples: List[Tuple[int, int, int]]) -> List[Tuple[int, int, int]]:
return [(t[0], t[1], t[2]) for t in [sorted(sides) for sides in triples]]
if __name__ == "__main__":
horizontal_triples = parse_horizontal(load_puzzle_input(day=3))
valid_horizontal = filter_valid_triangles(horizontal_triples)
report_solution(
puzzle_title="Day 3: Squares With Three Sides",
part_one_solution=len(valid_horizontal),
)
|
8b5337878172df95400a708b096e012436f8a706 | dags/main_summary.py | dags/main_summary.py | from airflow import DAG
from datetime import datetime, timedelta
from operators.emr_spark_operator import EMRSparkOperator
from airflow.operators import BashOperator
default_args = {
'owner': '[email protected]',
'depends_on_past': False,
'start_date': datetime(2016, 6, 27),
'email': ['[email protected]', '[email protected]'],
'email_on_failure': True,
'email_on_retry': True,
'retries': 2,
'retry_delay': timedelta(minutes=30),
}
dag = DAG('main_summary', default_args=default_args, schedule_interval='@daily')
# Make sure all the data for the given day has arrived before running.
t0 = BashOperator(task_id="delayed_start",
bash_command="sleep 1800",
dag=dag)
t1 = EMRSparkOperator(task_id="main_summary",
job_name="Main Summary View",
execution_timeout=timedelta(hours=10),
instance_count=10,
env = {"date": "{{ ds_nodash }}", "bucket": "{{ task.__class__.private_output_bucket }}"},
uri="https://raw.githubusercontent.com/mozilla/telemetry-airflow/master/jobs/main_summary_view.sh",
dag=dag)
# Wait a little while after midnight to start for a given day.
t1.set_upstream(t0)
| from airflow import DAG
from datetime import datetime, timedelta
from operators.emr_spark_operator import EMRSparkOperator
from airflow.operators import BashOperator
default_args = {
'owner': '[email protected]',
'depends_on_past': False,
'start_date': datetime(2016, 6, 25),
'email': ['[email protected]', '[email protected]'],
'email_on_failure': True,
'email_on_retry': True,
'retries': 2,
'retry_delay': timedelta(minutes=30),
}
dag = DAG('main_summary', default_args=default_args, schedule_interval='@daily', max_active_runs=10)
# Make sure all the data for the given day has arrived before running.
t0 = BashOperator(task_id="delayed_start",
bash_command="sleep 1800",
dag=dag)
t1 = EMRSparkOperator(task_id="main_summary",
job_name="Main Summary View",
execution_timeout=timedelta(hours=10),
instance_count=10,
env={"date": "{{ ds_nodash }}", "bucket": "{{ task.__class__.private_output_bucket }}"},
uri="https://raw.githubusercontent.com/mozilla/telemetry-airflow/master/jobs/main_summary_view.sh",
dag=dag)
# Wait a little while after midnight to start for a given day.
t1.set_upstream(t0)
| Prepare "Main Summary" job for backfill | Prepare "Main Summary" job for backfill
Set the max number of active runs so we don't overwhelm the system,
and rewind the start date by a couple of days to test that the
scheduler does the right thing.
| Python | mpl-2.0 | opentrials/opentrials-airflow,opentrials/opentrials-airflow | from airflow import DAG
from datetime import datetime, timedelta
from operators.emr_spark_operator import EMRSparkOperator
from airflow.operators import BashOperator
default_args = {
'owner': '[email protected]',
'depends_on_past': False,
- 'start_date': datetime(2016, 6, 27),
+ 'start_date': datetime(2016, 6, 25),
'email': ['[email protected]', '[email protected]'],
'email_on_failure': True,
'email_on_retry': True,
'retries': 2,
'retry_delay': timedelta(minutes=30),
}
- dag = DAG('main_summary', default_args=default_args, schedule_interval='@daily')
+ dag = DAG('main_summary', default_args=default_args, schedule_interval='@daily', max_active_runs=10)
# Make sure all the data for the given day has arrived before running.
t0 = BashOperator(task_id="delayed_start",
bash_command="sleep 1800",
dag=dag)
t1 = EMRSparkOperator(task_id="main_summary",
job_name="Main Summary View",
execution_timeout=timedelta(hours=10),
instance_count=10,
- env = {"date": "{{ ds_nodash }}", "bucket": "{{ task.__class__.private_output_bucket }}"},
+ env={"date": "{{ ds_nodash }}", "bucket": "{{ task.__class__.private_output_bucket }}"},
uri="https://raw.githubusercontent.com/mozilla/telemetry-airflow/master/jobs/main_summary_view.sh",
dag=dag)
# Wait a little while after midnight to start for a given day.
t1.set_upstream(t0)
| Prepare "Main Summary" job for backfill | ## Code Before:
from airflow import DAG
from datetime import datetime, timedelta
from operators.emr_spark_operator import EMRSparkOperator
from airflow.operators import BashOperator
default_args = {
'owner': '[email protected]',
'depends_on_past': False,
'start_date': datetime(2016, 6, 27),
'email': ['[email protected]', '[email protected]'],
'email_on_failure': True,
'email_on_retry': True,
'retries': 2,
'retry_delay': timedelta(minutes=30),
}
dag = DAG('main_summary', default_args=default_args, schedule_interval='@daily')
# Make sure all the data for the given day has arrived before running.
t0 = BashOperator(task_id="delayed_start",
bash_command="sleep 1800",
dag=dag)
t1 = EMRSparkOperator(task_id="main_summary",
job_name="Main Summary View",
execution_timeout=timedelta(hours=10),
instance_count=10,
env = {"date": "{{ ds_nodash }}", "bucket": "{{ task.__class__.private_output_bucket }}"},
uri="https://raw.githubusercontent.com/mozilla/telemetry-airflow/master/jobs/main_summary_view.sh",
dag=dag)
# Wait a little while after midnight to start for a given day.
t1.set_upstream(t0)
## Instruction:
Prepare "Main Summary" job for backfill
## Code After:
from airflow import DAG
from datetime import datetime, timedelta
from operators.emr_spark_operator import EMRSparkOperator
from airflow.operators import BashOperator
default_args = {
'owner': '[email protected]',
'depends_on_past': False,
'start_date': datetime(2016, 6, 25),
'email': ['[email protected]', '[email protected]'],
'email_on_failure': True,
'email_on_retry': True,
'retries': 2,
'retry_delay': timedelta(minutes=30),
}
dag = DAG('main_summary', default_args=default_args, schedule_interval='@daily', max_active_runs=10)
# Make sure all the data for the given day has arrived before running.
t0 = BashOperator(task_id="delayed_start",
bash_command="sleep 1800",
dag=dag)
t1 = EMRSparkOperator(task_id="main_summary",
job_name="Main Summary View",
execution_timeout=timedelta(hours=10),
instance_count=10,
env={"date": "{{ ds_nodash }}", "bucket": "{{ task.__class__.private_output_bucket }}"},
uri="https://raw.githubusercontent.com/mozilla/telemetry-airflow/master/jobs/main_summary_view.sh",
dag=dag)
# Wait a little while after midnight to start for a given day.
t1.set_upstream(t0)
|
847375a5cd6cbc160c190c9fb5e9fa2b1f0cdea9 | lustro/db.py | lustro/db.py |
from sqlalchemy import MetaData, create_engine
from sqlalchemy.orm import Session
from sqlalchemy.ext.automap import automap_base
class DB(object):
"""Facade for the low level DB operations"""
def __init__(self, dsn, schema=None):
self.engine = create_engine(dsn)
self.meta = MetaData()
self.meta.reflect(bind=self.engine, schema=schema)
self.base = automap_base(metadata=self.meta)
self.base.prepare()
def get_classes(self):
return self.base.classes
def get_session(self):
return Session(self.engine)
def get_rows(self, session, cls, modified=None):
return session.query(cls).all()
class Mirror(object):
"""API for cli mirroring operations"""
def __init__(self, source, target, source_schema=None, target_schema=None):
self.source = DB(source, source_schema)
self.target = DB(target, target_schema)
def diff(self, tables):
pass
def create(self, tables):
pass
def recreate(self, tables):
pass
def mirror(self, tables):
pass
|
from sqlalchemy import MetaData, create_engine
from sqlalchemy.orm import Session
from sqlalchemy.ext.automap import automap_base
class DB(object):
"""Facade for the low level DB operations"""
def __init__(self, dsn, schema=None):
self.engine = create_engine(dsn)
self.meta = MetaData()
self.meta.reflect(bind=self.engine, schema=schema)
self.base = automap_base(metadata=self.meta)
self.base.prepare()
def get_classes(self):
return self.base.classes
def get_session(self):
return Session(self.engine)
def get_rows(self, session, cls, modified=None):
return session.query(cls).all()
class Mirror(object):
"""API for cli mirroring operations"""
def __init__(self, source, target, source_schema=None, target_schema=None):
self.source = DB(source, source_schema)
self.target = DB(target, target_schema)
def diff(self, tables, modified):
pass
def create(self, tables):
pass
def recreate(self, tables):
pass
def mirror(self, tables):
pass
| Fix arguments to diff method | Fix arguments to diff method
| Python | mit | ashwoods/lustro |
from sqlalchemy import MetaData, create_engine
from sqlalchemy.orm import Session
from sqlalchemy.ext.automap import automap_base
class DB(object):
"""Facade for the low level DB operations"""
def __init__(self, dsn, schema=None):
self.engine = create_engine(dsn)
self.meta = MetaData()
self.meta.reflect(bind=self.engine, schema=schema)
self.base = automap_base(metadata=self.meta)
self.base.prepare()
def get_classes(self):
return self.base.classes
def get_session(self):
return Session(self.engine)
def get_rows(self, session, cls, modified=None):
return session.query(cls).all()
class Mirror(object):
"""API for cli mirroring operations"""
def __init__(self, source, target, source_schema=None, target_schema=None):
self.source = DB(source, source_schema)
self.target = DB(target, target_schema)
- def diff(self, tables):
+ def diff(self, tables, modified):
pass
def create(self, tables):
pass
def recreate(self, tables):
pass
def mirror(self, tables):
pass
| Fix arguments to diff method | ## Code Before:
from sqlalchemy import MetaData, create_engine
from sqlalchemy.orm import Session
from sqlalchemy.ext.automap import automap_base
class DB(object):
"""Facade for the low level DB operations"""
def __init__(self, dsn, schema=None):
self.engine = create_engine(dsn)
self.meta = MetaData()
self.meta.reflect(bind=self.engine, schema=schema)
self.base = automap_base(metadata=self.meta)
self.base.prepare()
def get_classes(self):
return self.base.classes
def get_session(self):
return Session(self.engine)
def get_rows(self, session, cls, modified=None):
return session.query(cls).all()
class Mirror(object):
"""API for cli mirroring operations"""
def __init__(self, source, target, source_schema=None, target_schema=None):
self.source = DB(source, source_schema)
self.target = DB(target, target_schema)
def diff(self, tables):
pass
def create(self, tables):
pass
def recreate(self, tables):
pass
def mirror(self, tables):
pass
## Instruction:
Fix arguments to diff method
## Code After:
from sqlalchemy import MetaData, create_engine
from sqlalchemy.orm import Session
from sqlalchemy.ext.automap import automap_base
class DB(object):
"""Facade for the low level DB operations"""
def __init__(self, dsn, schema=None):
self.engine = create_engine(dsn)
self.meta = MetaData()
self.meta.reflect(bind=self.engine, schema=schema)
self.base = automap_base(metadata=self.meta)
self.base.prepare()
def get_classes(self):
return self.base.classes
def get_session(self):
return Session(self.engine)
def get_rows(self, session, cls, modified=None):
return session.query(cls).all()
class Mirror(object):
"""API for cli mirroring operations"""
def __init__(self, source, target, source_schema=None, target_schema=None):
self.source = DB(source, source_schema)
self.target = DB(target, target_schema)
def diff(self, tables, modified):
pass
def create(self, tables):
pass
def recreate(self, tables):
pass
def mirror(self, tables):
pass
|
3131ea5c8dd41d18192f685e61c1bc8987038193 | vcs_info_panel/tests/test_clients/test_git.py | vcs_info_panel/tests/test_clients/test_git.py | import subprocess
from unittest.mock import patch
from django.test import TestCase
from vcs_info_panel.clients.git import GitClient
class GitClientTestCase(TestCase):
def setUp(self):
self.client = GitClient()
def _test_called_check_output(self, commands):
with patch('subprocess.check_output') as _check_output:
_check_output.assert_called_with(commands)
def test_base_command(self):
self.assertEqual(self.client.base_command, 'git')
def test_is_repository_with_repository(self):
with patch('subprocess.check_output') as _check_output:
_check_output.return_value = b'true'
self.assertEqual(self.client.is_repository(), True)
_check_output.assert_called_once_with(['git', 'rev-parse', '--is-inside-work-tree'])
def _patch_without_repository(self, func):
with patch('subprocess.check_output') as _check_output:
_check_output.side_effect = subprocess.CalledProcessError(128,
['git', 'rev-parse', '--is-inside-work-tree'],
'fatal: Not a git repository (or any of the parent directories): .git')
def test_is_repository_without_repository(self):
def _func(_check_output):
self.assertEqual(self.client.is_repository(), False)
_check_output.assert_called_once_with(['git', 'rev-parse', '--is-inside-work-tree'])
self._patch_without_repository(_func)
| import subprocess
from unittest.mock import patch
from django.test import TestCase
from vcs_info_panel.clients.git import GitClient
def without_git_repository(func):
def inner(*args, **kwargs):
with patch('subprocess.check_output') as _check_output:
_check_output.side_effect = subprocess.CalledProcessError(128,
['git', 'rev-parse', '--is-inside-work-tree'],
'fatal: Not a git repository (or any of the parent directories): .git')
return func(*args, **kwargs)
return inner
class GitClientTestCase(TestCase):
def setUp(self):
self.client = GitClient()
def _test_called_check_output(self, commands):
with patch('subprocess.check_output') as _check_output:
_check_output.assert_called_with(commands)
def test_base_command(self):
self.assertEqual(self.client.base_command, 'git')
def test_is_repository_with_repository(self):
with patch('subprocess.check_output') as _check_output:
_check_output.return_value = b'true'
self.assertEqual(self.client.is_repository(), True)
_check_output.assert_called_once_with(['git', 'rev-parse', '--is-inside-work-tree'])
@without_git_repository
def test_is_repository_without_repository(self):
self.assertEqual(self.client.is_repository(), True)
| Use decorator to patch git repository is not exist | Use decorator to patch git repository is not exist
| Python | mit | giginet/django-debug-toolbar-vcs-info,giginet/django-debug-toolbar-vcs-info | import subprocess
from unittest.mock import patch
from django.test import TestCase
from vcs_info_panel.clients.git import GitClient
+
+
+ def without_git_repository(func):
+ def inner(*args, **kwargs):
+ with patch('subprocess.check_output') as _check_output:
+ _check_output.side_effect = subprocess.CalledProcessError(128,
+ ['git', 'rev-parse', '--is-inside-work-tree'],
+ 'fatal: Not a git repository (or any of the parent directories): .git')
+ return func(*args, **kwargs)
+ return inner
class GitClientTestCase(TestCase):
def setUp(self):
self.client = GitClient()
def _test_called_check_output(self, commands):
with patch('subprocess.check_output') as _check_output:
_check_output.assert_called_with(commands)
def test_base_command(self):
self.assertEqual(self.client.base_command, 'git')
def test_is_repository_with_repository(self):
with patch('subprocess.check_output') as _check_output:
_check_output.return_value = b'true'
self.assertEqual(self.client.is_repository(), True)
_check_output.assert_called_once_with(['git', 'rev-parse', '--is-inside-work-tree'])
+ @without_git_repository
- def _patch_without_repository(self, func):
+ def test_is_repository_without_repository(self):
+ self.assertEqual(self.client.is_repository(), True)
- with patch('subprocess.check_output') as _check_output:
- _check_output.side_effect = subprocess.CalledProcessError(128,
- ['git', 'rev-parse', '--is-inside-work-tree'],
- 'fatal: Not a git repository (or any of the parent directories): .git')
- def test_is_repository_without_repository(self):
- def _func(_check_output):
- self.assertEqual(self.client.is_repository(), False)
- _check_output.assert_called_once_with(['git', 'rev-parse', '--is-inside-work-tree'])
- self._patch_without_repository(_func)
| Use decorator to patch git repository is not exist | ## Code Before:
import subprocess
from unittest.mock import patch
from django.test import TestCase
from vcs_info_panel.clients.git import GitClient
class GitClientTestCase(TestCase):
def setUp(self):
self.client = GitClient()
def _test_called_check_output(self, commands):
with patch('subprocess.check_output') as _check_output:
_check_output.assert_called_with(commands)
def test_base_command(self):
self.assertEqual(self.client.base_command, 'git')
def test_is_repository_with_repository(self):
with patch('subprocess.check_output') as _check_output:
_check_output.return_value = b'true'
self.assertEqual(self.client.is_repository(), True)
_check_output.assert_called_once_with(['git', 'rev-parse', '--is-inside-work-tree'])
def _patch_without_repository(self, func):
with patch('subprocess.check_output') as _check_output:
_check_output.side_effect = subprocess.CalledProcessError(128,
['git', 'rev-parse', '--is-inside-work-tree'],
'fatal: Not a git repository (or any of the parent directories): .git')
def test_is_repository_without_repository(self):
def _func(_check_output):
self.assertEqual(self.client.is_repository(), False)
_check_output.assert_called_once_with(['git', 'rev-parse', '--is-inside-work-tree'])
self._patch_without_repository(_func)
## Instruction:
Use decorator to patch git repository is not exist
## Code After:
import subprocess
from unittest.mock import patch
from django.test import TestCase
from vcs_info_panel.clients.git import GitClient
def without_git_repository(func):
def inner(*args, **kwargs):
with patch('subprocess.check_output') as _check_output:
_check_output.side_effect = subprocess.CalledProcessError(128,
['git', 'rev-parse', '--is-inside-work-tree'],
'fatal: Not a git repository (or any of the parent directories): .git')
return func(*args, **kwargs)
return inner
class GitClientTestCase(TestCase):
def setUp(self):
self.client = GitClient()
def _test_called_check_output(self, commands):
with patch('subprocess.check_output') as _check_output:
_check_output.assert_called_with(commands)
def test_base_command(self):
self.assertEqual(self.client.base_command, 'git')
def test_is_repository_with_repository(self):
with patch('subprocess.check_output') as _check_output:
_check_output.return_value = b'true'
self.assertEqual(self.client.is_repository(), True)
_check_output.assert_called_once_with(['git', 'rev-parse', '--is-inside-work-tree'])
@without_git_repository
def test_is_repository_without_repository(self):
self.assertEqual(self.client.is_repository(), True)
|
f4adce54b573b7776cf3f56230821f982c16b49f | modules/helloworld/helloworld.py | modules/helloworld/helloworld.py | def run(seed):
""" function to run
Args:
seed: The value of each line striped in seed file
Returns:
String, object, list, directory, etc.
"""
name, age = seed.split(',')
return 'Hello World! {}, {}'.format(seed, int(age))
def callback(result):
""" callback function to call
Args:
result: ProcessTask instance pool_task_with_timeout() method returned
result = {
'seed': 'Jone',
'data': 'Hello World! Jone',
'exception': None
}
or
result = {
'seed': 'Jone',
'data': None,
'exception': 'ValueError: invalid literal'
}
Returns:
Anything want to return.
"""
seed = result['seed']
data = result['data']
exception = result['exception']
print('seed: "{}", data: "{}", exception: "{}"'
.format(seed, data, exception))
| import time
def run(seed):
""" function to run
Args:
seed: The value of each line striped in seed file
Returns:
String, object, list, directory, etc.
"""
name, age = seed.split(',')
return 'Hello World! {}, {}'.format(seed, int(age))
def callback(result):
""" callback function to call
Args:
result: ProcessTask instance pool_task_with_timeout() method returned
result = {
'seed': 'Jone',
'data': 'Hello World! Jone',
'exception': None
}
result = {
'seed': 'Jone',
'data': None,
'exception': 'ValueError: invalid literal'
}
Returns:
Anything want to return.
"""
seed = result['seed']
data = result['data']
exception = result['exception']
time.sleep(0.05)
print('seed: "{}", data: "{}", exception: "{}"'
.format(seed, data, exception))
| Add time.sleep(0.05) in test module | Add time.sleep(0.05) in test module
| Python | mit | RickGray/cyberbot | + import time
+
+
def run(seed):
""" function to run
Args:
seed: The value of each line striped in seed file
Returns:
String, object, list, directory, etc.
"""
name, age = seed.split(',')
return 'Hello World! {}, {}'.format(seed, int(age))
def callback(result):
""" callback function to call
-
+
Args:
result: ProcessTask instance pool_task_with_timeout() method returned
result = {
'seed': 'Jone',
'data': 'Hello World! Jone',
'exception': None
}
-
- or
result = {
'seed': 'Jone',
'data': None,
'exception': 'ValueError: invalid literal'
}
Returns:
Anything want to return.
"""
seed = result['seed']
data = result['data']
exception = result['exception']
+ time.sleep(0.05)
print('seed: "{}", data: "{}", exception: "{}"'
.format(seed, data, exception))
| Add time.sleep(0.05) in test module | ## Code Before:
def run(seed):
""" function to run
Args:
seed: The value of each line striped in seed file
Returns:
String, object, list, directory, etc.
"""
name, age = seed.split(',')
return 'Hello World! {}, {}'.format(seed, int(age))
def callback(result):
""" callback function to call
Args:
result: ProcessTask instance pool_task_with_timeout() method returned
result = {
'seed': 'Jone',
'data': 'Hello World! Jone',
'exception': None
}
or
result = {
'seed': 'Jone',
'data': None,
'exception': 'ValueError: invalid literal'
}
Returns:
Anything want to return.
"""
seed = result['seed']
data = result['data']
exception = result['exception']
print('seed: "{}", data: "{}", exception: "{}"'
.format(seed, data, exception))
## Instruction:
Add time.sleep(0.05) in test module
## Code After:
import time
def run(seed):
""" function to run
Args:
seed: The value of each line striped in seed file
Returns:
String, object, list, directory, etc.
"""
name, age = seed.split(',')
return 'Hello World! {}, {}'.format(seed, int(age))
def callback(result):
""" callback function to call
Args:
result: ProcessTask instance pool_task_with_timeout() method returned
result = {
'seed': 'Jone',
'data': 'Hello World! Jone',
'exception': None
}
result = {
'seed': 'Jone',
'data': None,
'exception': 'ValueError: invalid literal'
}
Returns:
Anything want to return.
"""
seed = result['seed']
data = result['data']
exception = result['exception']
time.sleep(0.05)
print('seed: "{}", data: "{}", exception: "{}"'
.format(seed, data, exception))
|
41ba2d55ed00269465d49ba22a1cb07eb899273a | test/test_run.py | test/test_run.py |
from exp_test_helper import run_exp
import pytest
class TestRun():
"""
Run and check return code.
"""
@pytest.mark.fast
def test_run(self):
run_exp('1deg_jra55_ryf')
@pytest.mark.slow
def test_slow_run(self):
run_exp('025deg_jra55_ryf')
|
from exp_test_helper import run_exp
import pytest
class TestRun():
"""
Run and check return code.
"""
@pytest.mark.fast
def test_1deg_jra55_run(self):
run_exp('1deg_jra55_ryf')
@pytest.mark.slow
def test_1deg_core_run(self):
run_exp('1deg_core_nyf')
@pytest.mark.slow
def test_slow_run(self):
run_exp('025deg_jra55_ryf')
| Include the 1deg core experiment in tests. | Include the 1deg core experiment in tests.
| Python | apache-2.0 | CWSL/access-om |
from exp_test_helper import run_exp
import pytest
class TestRun():
"""
Run and check return code.
"""
@pytest.mark.fast
- def test_run(self):
+ def test_1deg_jra55_run(self):
run_exp('1deg_jra55_ryf')
+
+ @pytest.mark.slow
+ def test_1deg_core_run(self):
+ run_exp('1deg_core_nyf')
@pytest.mark.slow
def test_slow_run(self):
run_exp('025deg_jra55_ryf')
| Include the 1deg core experiment in tests. | ## Code Before:
from exp_test_helper import run_exp
import pytest
class TestRun():
"""
Run and check return code.
"""
@pytest.mark.fast
def test_run(self):
run_exp('1deg_jra55_ryf')
@pytest.mark.slow
def test_slow_run(self):
run_exp('025deg_jra55_ryf')
## Instruction:
Include the 1deg core experiment in tests.
## Code After:
from exp_test_helper import run_exp
import pytest
class TestRun():
"""
Run and check return code.
"""
@pytest.mark.fast
def test_1deg_jra55_run(self):
run_exp('1deg_jra55_ryf')
@pytest.mark.slow
def test_1deg_core_run(self):
run_exp('1deg_core_nyf')
@pytest.mark.slow
def test_slow_run(self):
run_exp('025deg_jra55_ryf')
|
cc3d89d4357099ba2df1628e9d91e48c743bd471 | api/common/views.py | api/common/views.py | import subprocess
from django.conf import settings
from django.http import JsonResponse, HttpResponseBadRequest
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from rest_framework.authtoken.models import Token
@csrf_exempt
def deploy(request):
deploy_secret_key = request.POST.get('DEPLOY_SECRET_KEY')
# branch = request.POST.get('BRANCH')
commit = request.POST.get('COMMIT')
if deploy_secret_key != settings.SECRET_KEY:
return HttpResponseBadRequest('Incorrect key.')
subprocess.Popen(['scripts/deploy.sh', commit], stdout=subprocess.PIPE)
return JsonResponse({'result': 'deploy started'})
def social_redirect(request):
token, _ = Token.objects.get_or_create(user=request.user)
return redirect('http://localhost:3000/finish-steam/{}'.format(token.key))
| import subprocess
from django.conf import settings
from django.http import JsonResponse, HttpResponseBadRequest
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from rest_framework.authtoken.models import Token
@csrf_exempt
def deploy(request):
deploy_secret_key = request.POST.get('DEPLOY_SECRET_KEY')
# branch = request.POST.get('BRANCH')
commit = request.POST.get('COMMIT')
if deploy_secret_key != settings.SECRET_KEY:
return HttpResponseBadRequest('Incorrect key.')
subprocess.Popen(['scripts/deploy.sh', commit], stdout=subprocess.PIPE)
return JsonResponse({'result': 'deploy started'})
def social_redirect(request):
token, _ = Token.objects.get_or_create(user=request.user)
return redirect('http://dotateamfinder.com/finish-steam/{}'.format(token.key))
| Fix incorrect social redirect link | Fix incorrect social redirect link
| Python | apache-2.0 | prattl/teamfinder,prattl/teamfinder,prattl/teamfinder,prattl/teamfinder | import subprocess
from django.conf import settings
from django.http import JsonResponse, HttpResponseBadRequest
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from rest_framework.authtoken.models import Token
@csrf_exempt
def deploy(request):
deploy_secret_key = request.POST.get('DEPLOY_SECRET_KEY')
# branch = request.POST.get('BRANCH')
commit = request.POST.get('COMMIT')
if deploy_secret_key != settings.SECRET_KEY:
return HttpResponseBadRequest('Incorrect key.')
subprocess.Popen(['scripts/deploy.sh', commit], stdout=subprocess.PIPE)
return JsonResponse({'result': 'deploy started'})
def social_redirect(request):
token, _ = Token.objects.get_or_create(user=request.user)
- return redirect('http://localhost:3000/finish-steam/{}'.format(token.key))
+ return redirect('http://dotateamfinder.com/finish-steam/{}'.format(token.key))
| Fix incorrect social redirect link | ## Code Before:
import subprocess
from django.conf import settings
from django.http import JsonResponse, HttpResponseBadRequest
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from rest_framework.authtoken.models import Token
@csrf_exempt
def deploy(request):
deploy_secret_key = request.POST.get('DEPLOY_SECRET_KEY')
# branch = request.POST.get('BRANCH')
commit = request.POST.get('COMMIT')
if deploy_secret_key != settings.SECRET_KEY:
return HttpResponseBadRequest('Incorrect key.')
subprocess.Popen(['scripts/deploy.sh', commit], stdout=subprocess.PIPE)
return JsonResponse({'result': 'deploy started'})
def social_redirect(request):
token, _ = Token.objects.get_or_create(user=request.user)
return redirect('http://localhost:3000/finish-steam/{}'.format(token.key))
## Instruction:
Fix incorrect social redirect link
## Code After:
import subprocess
from django.conf import settings
from django.http import JsonResponse, HttpResponseBadRequest
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from rest_framework.authtoken.models import Token
@csrf_exempt
def deploy(request):
deploy_secret_key = request.POST.get('DEPLOY_SECRET_KEY')
# branch = request.POST.get('BRANCH')
commit = request.POST.get('COMMIT')
if deploy_secret_key != settings.SECRET_KEY:
return HttpResponseBadRequest('Incorrect key.')
subprocess.Popen(['scripts/deploy.sh', commit], stdout=subprocess.PIPE)
return JsonResponse({'result': 'deploy started'})
def social_redirect(request):
token, _ = Token.objects.get_or_create(user=request.user)
return redirect('http://dotateamfinder.com/finish-steam/{}'.format(token.key))
|
107b97e952d731f8c55c9ca3208ecd2a41512b8d | tests/integration/modules/sysmod.py | tests/integration/modules/sysmod.py | import integration
class SysModuleTest(integration.ModuleCase):
'''
Validate the sys module
'''
def test_list_functions(self):
'''
sys.list_functions
'''
funcs = self.run_function('sys.list_functions')
self.assertTrue('hosts.list_hosts' in funcs)
self.assertTrue('pkg.install' in funcs)
def test_list_modules(self):
'''
sys.list_moduels
'''
mods = self.run_function('sys.list_modules')
self.assertTrue('hosts' in mods)
self.assertTrue('pkg' in mods)
if __name__ == '__main__':
from integration import run_tests
run_tests(SysModuleTest)
| import integration
class SysModuleTest(integration.ModuleCase):
'''
Validate the sys module
'''
def test_list_functions(self):
'''
sys.list_functions
'''
funcs = self.run_function('sys.list_functions')
self.assertTrue('hosts.list_hosts' in funcs)
self.assertTrue('pkg.install' in funcs)
def test_list_modules(self):
'''
sys.list_moduels
'''
mods = self.run_function('sys.list_modules')
self.assertTrue('hosts' in mods)
self.assertTrue('pkg' in mods)
def test_valid_docs(self):
'''
Make sure no functions are exposed that don't have valid docstrings
'''
docs = self.run_function('sys.doc')
bad = set()
for fun in docs:
if fun.startswith('runtests_helpers'):
continue
if not isinstance(docs[fun], basestring):
bad.add(fun)
elif not 'Example::' in docs[fun]:
if not 'Examples::' in docs[fun]:
bad.add(fun)
if bad:
import pprint
pprint.pprint(sorted(bad))
self.assertFalse(bool(bad))
if __name__ == '__main__':
from integration import run_tests
run_tests(SysModuleTest)
| Add test to verify loader modules | Add test to verify loader modules
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | import integration
class SysModuleTest(integration.ModuleCase):
'''
Validate the sys module
'''
def test_list_functions(self):
'''
sys.list_functions
'''
funcs = self.run_function('sys.list_functions')
self.assertTrue('hosts.list_hosts' in funcs)
self.assertTrue('pkg.install' in funcs)
def test_list_modules(self):
'''
sys.list_moduels
'''
mods = self.run_function('sys.list_modules')
self.assertTrue('hosts' in mods)
self.assertTrue('pkg' in mods)
+ def test_valid_docs(self):
+ '''
+ Make sure no functions are exposed that don't have valid docstrings
+ '''
+ docs = self.run_function('sys.doc')
+ bad = set()
+ for fun in docs:
+ if fun.startswith('runtests_helpers'):
+ continue
+ if not isinstance(docs[fun], basestring):
+ bad.add(fun)
+ elif not 'Example::' in docs[fun]:
+ if not 'Examples::' in docs[fun]:
+ bad.add(fun)
+ if bad:
+ import pprint
+ pprint.pprint(sorted(bad))
+ self.assertFalse(bool(bad))
+
if __name__ == '__main__':
from integration import run_tests
run_tests(SysModuleTest)
| Add test to verify loader modules | ## Code Before:
import integration
class SysModuleTest(integration.ModuleCase):
'''
Validate the sys module
'''
def test_list_functions(self):
'''
sys.list_functions
'''
funcs = self.run_function('sys.list_functions')
self.assertTrue('hosts.list_hosts' in funcs)
self.assertTrue('pkg.install' in funcs)
def test_list_modules(self):
'''
sys.list_moduels
'''
mods = self.run_function('sys.list_modules')
self.assertTrue('hosts' in mods)
self.assertTrue('pkg' in mods)
if __name__ == '__main__':
from integration import run_tests
run_tests(SysModuleTest)
## Instruction:
Add test to verify loader modules
## Code After:
import integration
class SysModuleTest(integration.ModuleCase):
'''
Validate the sys module
'''
def test_list_functions(self):
'''
sys.list_functions
'''
funcs = self.run_function('sys.list_functions')
self.assertTrue('hosts.list_hosts' in funcs)
self.assertTrue('pkg.install' in funcs)
def test_list_modules(self):
'''
sys.list_moduels
'''
mods = self.run_function('sys.list_modules')
self.assertTrue('hosts' in mods)
self.assertTrue('pkg' in mods)
def test_valid_docs(self):
'''
Make sure no functions are exposed that don't have valid docstrings
'''
docs = self.run_function('sys.doc')
bad = set()
for fun in docs:
if fun.startswith('runtests_helpers'):
continue
if not isinstance(docs[fun], basestring):
bad.add(fun)
elif not 'Example::' in docs[fun]:
if not 'Examples::' in docs[fun]:
bad.add(fun)
if bad:
import pprint
pprint.pprint(sorted(bad))
self.assertFalse(bool(bad))
if __name__ == '__main__':
from integration import run_tests
run_tests(SysModuleTest)
|
9058d2ddc9a89913710df0efc8d7c88471592795 | back2back/management/commands/import_entries.py | back2back/management/commands/import_entries.py | import csv
from optparse import make_option
from django.core.management import BaseCommand
from back2back.models import Entry
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option(
'-i', '--input',
action='store',
dest='input_file',
default=None,
),
make_option(
'--reset',
action='store_true',
dest='reset',
default=False,
),
)
def handle(self, *args, **options):
if options['reset']:
Entry.objects.all().delete()
input_file = options['input_file']
with open(input_file) as f:
reader = csv.reader(f)
for row in reader:
Entry.objects.create(category=row[0], name=row[1], first_group_number=row[2])
| import collections
import csv
from optparse import make_option
from django.core.management import BaseCommand
from back2back.models import Entry
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option(
'-i', '--input',
action='store',
dest='input_file',
default=None,
),
make_option(
'--reset',
action='store_true',
dest='reset',
default=False,
),
)
def handle(self, *args, **options):
if options['reset']:
Entry.objects.all().delete()
input_file = options['input_file']
category_group_counts = collections.defaultdict(int)
with open(input_file) as f:
reader = csv.reader(f)
for row in reader:
if not row[1].strip():
continue
Entry.objects.create(
category=row[0],
name=row[1],
first_group_number=row[2],
first_group_index=category_group_counts[(row[0], row[2])],
)
category_group_counts[(row[0], row[2])] += 1
| Save indexes as well when importing entries. | Save indexes as well when importing entries.
| Python | bsd-2-clause | mjtamlyn/back2back,mjtamlyn/back2back,mjtamlyn/back2back,mjtamlyn/back2back | + import collections
import csv
from optparse import make_option
from django.core.management import BaseCommand
from back2back.models import Entry
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option(
'-i', '--input',
action='store',
dest='input_file',
default=None,
),
make_option(
'--reset',
action='store_true',
dest='reset',
default=False,
),
)
def handle(self, *args, **options):
if options['reset']:
Entry.objects.all().delete()
input_file = options['input_file']
+ category_group_counts = collections.defaultdict(int)
with open(input_file) as f:
reader = csv.reader(f)
for row in reader:
- Entry.objects.create(category=row[0], name=row[1], first_group_number=row[2])
+ if not row[1].strip():
+ continue
+ Entry.objects.create(
+ category=row[0],
+ name=row[1],
+ first_group_number=row[2],
+ first_group_index=category_group_counts[(row[0], row[2])],
+ )
+ category_group_counts[(row[0], row[2])] += 1
| Save indexes as well when importing entries. | ## Code Before:
import csv
from optparse import make_option
from django.core.management import BaseCommand
from back2back.models import Entry
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option(
'-i', '--input',
action='store',
dest='input_file',
default=None,
),
make_option(
'--reset',
action='store_true',
dest='reset',
default=False,
),
)
def handle(self, *args, **options):
if options['reset']:
Entry.objects.all().delete()
input_file = options['input_file']
with open(input_file) as f:
reader = csv.reader(f)
for row in reader:
Entry.objects.create(category=row[0], name=row[1], first_group_number=row[2])
## Instruction:
Save indexes as well when importing entries.
## Code After:
import collections
import csv
from optparse import make_option
from django.core.management import BaseCommand
from back2back.models import Entry
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option(
'-i', '--input',
action='store',
dest='input_file',
default=None,
),
make_option(
'--reset',
action='store_true',
dest='reset',
default=False,
),
)
def handle(self, *args, **options):
if options['reset']:
Entry.objects.all().delete()
input_file = options['input_file']
category_group_counts = collections.defaultdict(int)
with open(input_file) as f:
reader = csv.reader(f)
for row in reader:
if not row[1].strip():
continue
Entry.objects.create(
category=row[0],
name=row[1],
first_group_number=row[2],
first_group_index=category_group_counts[(row[0], row[2])],
)
category_group_counts[(row[0], row[2])] += 1
|
47a9271a00fae3f55c79323c93feb4dc2e1fd515 | portal/tests/models/test_profile.py | portal/tests/models/test_profile.py | from django.contrib.auth import get_user_model
from django.test import TestCase
from portal.models import Profile
class TestProfile(TestCase):
"""Profile test suite"""
users = ["john", "jane"]
UserModel = get_user_model()
def setUp(self):
for user in self.users:
self.UserModel.objects.create_user(user, f"{user}@localhost", user)
def test_profile_all(self):
profiles = Profile.objects.all()
self.assertEquals(len(profiles), len(self.users))
def test_profile_get(self):
user = self.UserModel.objects.get(username="john")
profile = Profile.objects.get(user=user)
self.assertIsNotNone(profile)
| from django.contrib.auth import get_user_model
from django.test import TestCase
from portal.models import Profile
class TestProfile(TestCase):
"""Profile test suite"""
users = ["john", "jane"]
UserModel = get_user_model()
def setUp(self):
for user in self.users:
self.UserModel.objects.create_user(user, f"{user}@localhost", user)
def test_profile_all(self):
profiles = Profile.objects.all()
self.assertEquals(len(profiles), len(self.users))
def test_profile_get(self):
user = self.UserModel.objects.get(username="john")
profile = Profile.objects.get(user=user)
self.assertIsNotNone(profile)
def test_profile_exception(self):
self.assertRaises(Profile.DoesNotExist, Profile.objects.get, bio="Bogus")
def test_profile_empty(self):
profiles = Profile.objects.filter(bio__exact="Bogus")
self.assertEquals(len(profiles), 0)
| Add more profile model tests | Add more profile model tests
| Python | mit | huangsam/chowist,huangsam/chowist,huangsam/chowist | from django.contrib.auth import get_user_model
from django.test import TestCase
from portal.models import Profile
class TestProfile(TestCase):
"""Profile test suite"""
users = ["john", "jane"]
UserModel = get_user_model()
def setUp(self):
for user in self.users:
self.UserModel.objects.create_user(user, f"{user}@localhost", user)
def test_profile_all(self):
profiles = Profile.objects.all()
self.assertEquals(len(profiles), len(self.users))
def test_profile_get(self):
user = self.UserModel.objects.get(username="john")
profile = Profile.objects.get(user=user)
self.assertIsNotNone(profile)
+ def test_profile_exception(self):
+ self.assertRaises(Profile.DoesNotExist, Profile.objects.get, bio="Bogus")
+
+ def test_profile_empty(self):
+ profiles = Profile.objects.filter(bio__exact="Bogus")
+ self.assertEquals(len(profiles), 0)
+ | Add more profile model tests | ## Code Before:
from django.contrib.auth import get_user_model
from django.test import TestCase
from portal.models import Profile
class TestProfile(TestCase):
"""Profile test suite"""
users = ["john", "jane"]
UserModel = get_user_model()
def setUp(self):
for user in self.users:
self.UserModel.objects.create_user(user, f"{user}@localhost", user)
def test_profile_all(self):
profiles = Profile.objects.all()
self.assertEquals(len(profiles), len(self.users))
def test_profile_get(self):
user = self.UserModel.objects.get(username="john")
profile = Profile.objects.get(user=user)
self.assertIsNotNone(profile)
## Instruction:
Add more profile model tests
## Code After:
from django.contrib.auth import get_user_model
from django.test import TestCase
from portal.models import Profile
class TestProfile(TestCase):
"""Profile test suite"""
users = ["john", "jane"]
UserModel = get_user_model()
def setUp(self):
for user in self.users:
self.UserModel.objects.create_user(user, f"{user}@localhost", user)
def test_profile_all(self):
profiles = Profile.objects.all()
self.assertEquals(len(profiles), len(self.users))
def test_profile_get(self):
user = self.UserModel.objects.get(username="john")
profile = Profile.objects.get(user=user)
self.assertIsNotNone(profile)
def test_profile_exception(self):
self.assertRaises(Profile.DoesNotExist, Profile.objects.get, bio="Bogus")
def test_profile_empty(self):
profiles = Profile.objects.filter(bio__exact="Bogus")
self.assertEquals(len(profiles), 0)
|
416dea771c5750044b99e8c8bfe0755feeb3ee71 | astropy/vo/samp/constants.py | astropy/vo/samp/constants.py | """Defines constants used in `astropy.vo.samp`."""
import os
DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
__all__ = ['SAMP_STATUS_OK', 'SAMP_STATUS_WARNING', 'SAMP_STATUS_ERROR',
'SAMP_HUB_SINGLE_INSTANCE', 'SAMP_HUB_MULTIPLE_INSTANCE',
'SAFE_MTYPES', 'SAMP_ICON']
__profile_version__ = "1.3"
#: General constant for samp.ok status string
SAMP_STATUS_OK = "samp.ok"
#: General constant for samp.warning status string
SAMP_STATUS_WARNING = "samp.warning"
#: General constant for samp.error status string
SAMP_STATUS_ERROR = "samp.error"
#: General constant to specify single instance Hub running mode
SAMP_HUB_SINGLE_INSTANCE = "single"
#: General constant to specify multiple instance Hub running mode
SAMP_HUB_MULTIPLE_INSTANCE = "multiple"
SAFE_MTYPES = ["samp.app.*", "samp.msg.progress", "table.*", "image.*",
"coord.*", "spectrum.*", "bibcode.*", "voresource.*"]
with open(os.path.join(DATA_DIR, 'astropy_icon.png'), 'rb') as f:
SAMP_ICON = f.read()
try:
import ssl
except ImportError:
SSL_SUPPORT = False
else:
SSL_SUPPORT = True
del ssl | """Defines constants used in `astropy.vo.samp`."""
import os
from ...utils.data import get_pkg_data_filename
__all__ = ['SAMP_STATUS_OK', 'SAMP_STATUS_WARNING', 'SAMP_STATUS_ERROR',
'SAMP_HUB_SINGLE_INSTANCE', 'SAMP_HUB_MULTIPLE_INSTANCE',
'SAFE_MTYPES', 'SAMP_ICON']
__profile_version__ = "1.3"
#: General constant for samp.ok status string
SAMP_STATUS_OK = "samp.ok"
#: General constant for samp.warning status string
SAMP_STATUS_WARNING = "samp.warning"
#: General constant for samp.error status string
SAMP_STATUS_ERROR = "samp.error"
#: General constant to specify single instance Hub running mode
SAMP_HUB_SINGLE_INSTANCE = "single"
#: General constant to specify multiple instance Hub running mode
SAMP_HUB_MULTIPLE_INSTANCE = "multiple"
SAFE_MTYPES = ["samp.app.*", "samp.msg.progress", "table.*", "image.*",
"coord.*", "spectrum.*", "bibcode.*", "voresource.*"]
with open(get_pkg_data_filename('data/astropy_icon.png'), 'rb') as f:
SAMP_ICON = f.read()
try:
import ssl
except ImportError:
SSL_SUPPORT = False
else:
SSL_SUPPORT = True
del ssl | Make use of get_pkg_data_filename for icon | Make use of get_pkg_data_filename for icon
| Python | bsd-3-clause | StuartLittlefair/astropy,StuartLittlefair/astropy,bsipocz/astropy,saimn/astropy,bsipocz/astropy,tbabej/astropy,dhomeier/astropy,aleksandr-bakanov/astropy,AustereCuriosity/astropy,larrybradley/astropy,mhvk/astropy,stargaser/astropy,dhomeier/astropy,pllim/astropy,kelle/astropy,DougBurke/astropy,AustereCuriosity/astropy,dhomeier/astropy,saimn/astropy,tbabej/astropy,DougBurke/astropy,larrybradley/astropy,AustereCuriosity/astropy,mhvk/astropy,kelle/astropy,StuartLittlefair/astropy,MSeifert04/astropy,astropy/astropy,StuartLittlefair/astropy,lpsinger/astropy,DougBurke/astropy,saimn/astropy,mhvk/astropy,pllim/astropy,aleksandr-bakanov/astropy,lpsinger/astropy,joergdietrich/astropy,stargaser/astropy,mhvk/astropy,AustereCuriosity/astropy,MSeifert04/astropy,funbaker/astropy,lpsinger/astropy,bsipocz/astropy,larrybradley/astropy,astropy/astropy,lpsinger/astropy,pllim/astropy,stargaser/astropy,aleksandr-bakanov/astropy,joergdietrich/astropy,tbabej/astropy,mhvk/astropy,tbabej/astropy,larrybradley/astropy,dhomeier/astropy,dhomeier/astropy,AustereCuriosity/astropy,joergdietrich/astropy,saimn/astropy,stargaser/astropy,funbaker/astropy,kelle/astropy,lpsinger/astropy,joergdietrich/astropy,funbaker/astropy,astropy/astropy,tbabej/astropy,StuartLittlefair/astropy,larrybradley/astropy,bsipocz/astropy,MSeifert04/astropy,pllim/astropy,aleksandr-bakanov/astropy,MSeifert04/astropy,funbaker/astropy,saimn/astropy,kelle/astropy,DougBurke/astropy,astropy/astropy,joergdietrich/astropy,astropy/astropy,pllim/astropy,kelle/astropy | """Defines constants used in `astropy.vo.samp`."""
import os
- DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
+ from ...utils.data import get_pkg_data_filename
__all__ = ['SAMP_STATUS_OK', 'SAMP_STATUS_WARNING', 'SAMP_STATUS_ERROR',
'SAMP_HUB_SINGLE_INSTANCE', 'SAMP_HUB_MULTIPLE_INSTANCE',
'SAFE_MTYPES', 'SAMP_ICON']
__profile_version__ = "1.3"
#: General constant for samp.ok status string
SAMP_STATUS_OK = "samp.ok"
#: General constant for samp.warning status string
SAMP_STATUS_WARNING = "samp.warning"
#: General constant for samp.error status string
SAMP_STATUS_ERROR = "samp.error"
#: General constant to specify single instance Hub running mode
SAMP_HUB_SINGLE_INSTANCE = "single"
#: General constant to specify multiple instance Hub running mode
SAMP_HUB_MULTIPLE_INSTANCE = "multiple"
SAFE_MTYPES = ["samp.app.*", "samp.msg.progress", "table.*", "image.*",
"coord.*", "spectrum.*", "bibcode.*", "voresource.*"]
- with open(os.path.join(DATA_DIR, 'astropy_icon.png'), 'rb') as f:
+ with open(get_pkg_data_filename('data/astropy_icon.png'), 'rb') as f:
SAMP_ICON = f.read()
try:
import ssl
except ImportError:
SSL_SUPPORT = False
else:
SSL_SUPPORT = True
del ssl | Make use of get_pkg_data_filename for icon | ## Code Before:
"""Defines constants used in `astropy.vo.samp`."""
import os
DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
__all__ = ['SAMP_STATUS_OK', 'SAMP_STATUS_WARNING', 'SAMP_STATUS_ERROR',
'SAMP_HUB_SINGLE_INSTANCE', 'SAMP_HUB_MULTIPLE_INSTANCE',
'SAFE_MTYPES', 'SAMP_ICON']
__profile_version__ = "1.3"
#: General constant for samp.ok status string
SAMP_STATUS_OK = "samp.ok"
#: General constant for samp.warning status string
SAMP_STATUS_WARNING = "samp.warning"
#: General constant for samp.error status string
SAMP_STATUS_ERROR = "samp.error"
#: General constant to specify single instance Hub running mode
SAMP_HUB_SINGLE_INSTANCE = "single"
#: General constant to specify multiple instance Hub running mode
SAMP_HUB_MULTIPLE_INSTANCE = "multiple"
SAFE_MTYPES = ["samp.app.*", "samp.msg.progress", "table.*", "image.*",
"coord.*", "spectrum.*", "bibcode.*", "voresource.*"]
with open(os.path.join(DATA_DIR, 'astropy_icon.png'), 'rb') as f:
SAMP_ICON = f.read()
try:
import ssl
except ImportError:
SSL_SUPPORT = False
else:
SSL_SUPPORT = True
del ssl
## Instruction:
Make use of get_pkg_data_filename for icon
## Code After:
"""Defines constants used in `astropy.vo.samp`."""
import os
from ...utils.data import get_pkg_data_filename
__all__ = ['SAMP_STATUS_OK', 'SAMP_STATUS_WARNING', 'SAMP_STATUS_ERROR',
'SAMP_HUB_SINGLE_INSTANCE', 'SAMP_HUB_MULTIPLE_INSTANCE',
'SAFE_MTYPES', 'SAMP_ICON']
__profile_version__ = "1.3"
#: General constant for samp.ok status string
SAMP_STATUS_OK = "samp.ok"
#: General constant for samp.warning status string
SAMP_STATUS_WARNING = "samp.warning"
#: General constant for samp.error status string
SAMP_STATUS_ERROR = "samp.error"
#: General constant to specify single instance Hub running mode
SAMP_HUB_SINGLE_INSTANCE = "single"
#: General constant to specify multiple instance Hub running mode
SAMP_HUB_MULTIPLE_INSTANCE = "multiple"
SAFE_MTYPES = ["samp.app.*", "samp.msg.progress", "table.*", "image.*",
"coord.*", "spectrum.*", "bibcode.*", "voresource.*"]
with open(get_pkg_data_filename('data/astropy_icon.png'), 'rb') as f:
SAMP_ICON = f.read()
try:
import ssl
except ImportError:
SSL_SUPPORT = False
else:
SSL_SUPPORT = True
del ssl |
745ec6f3dd227cc00c3db0d100b005fb6fd4d903 | test/on_yubikey/test_cli_openpgp.py | test/on_yubikey/test_cli_openpgp.py | import unittest
from ykman.util import TRANSPORT
from .util import (DestructiveYubikeyTestCase, missing_mode, ykman_cli)
@unittest.skipIf(*missing_mode(TRANSPORT.CCID))
class TestOpenPGP(DestructiveYubikeyTestCase):
def test_openpgp_info(self):
output = ykman_cli('openpgp', 'info')
self.assertIn('OpenPGP version:', output)
def test_openpgp_reset(self):
output = ykman_cli('openpgp', 'reset', '-f')
self.assertIn(
'Success! All data has been cleared and default PINs are set.',
output)
| import unittest
from ykman.util import TRANSPORT
from .util import (DestructiveYubikeyTestCase, missing_mode, ykman_cli)
@unittest.skipIf(*missing_mode(TRANSPORT.CCID))
class TestOpenPGP(DestructiveYubikeyTestCase):
def setUp(self):
ykman_cli('openpgp', 'reset', '-f')
def test_openpgp_info(self):
output = ykman_cli('openpgp', 'info')
self.assertIn('OpenPGP version:', output)
def test_openpgp_reset(self):
output = ykman_cli('openpgp', 'reset', '-f')
self.assertIn(
'Success! All data has been cleared and default PINs are set.',
output)
| Reset OpenPGP applet before each test | Reset OpenPGP applet before each test
| Python | bsd-2-clause | Yubico/yubikey-manager,Yubico/yubikey-manager | import unittest
from ykman.util import TRANSPORT
from .util import (DestructiveYubikeyTestCase, missing_mode, ykman_cli)
@unittest.skipIf(*missing_mode(TRANSPORT.CCID))
class TestOpenPGP(DestructiveYubikeyTestCase):
+
+ def setUp(self):
+ ykman_cli('openpgp', 'reset', '-f')
def test_openpgp_info(self):
output = ykman_cli('openpgp', 'info')
self.assertIn('OpenPGP version:', output)
def test_openpgp_reset(self):
output = ykman_cli('openpgp', 'reset', '-f')
self.assertIn(
'Success! All data has been cleared and default PINs are set.',
output)
| Reset OpenPGP applet before each test | ## Code Before:
import unittest
from ykman.util import TRANSPORT
from .util import (DestructiveYubikeyTestCase, missing_mode, ykman_cli)
@unittest.skipIf(*missing_mode(TRANSPORT.CCID))
class TestOpenPGP(DestructiveYubikeyTestCase):
def test_openpgp_info(self):
output = ykman_cli('openpgp', 'info')
self.assertIn('OpenPGP version:', output)
def test_openpgp_reset(self):
output = ykman_cli('openpgp', 'reset', '-f')
self.assertIn(
'Success! All data has been cleared and default PINs are set.',
output)
## Instruction:
Reset OpenPGP applet before each test
## Code After:
import unittest
from ykman.util import TRANSPORT
from .util import (DestructiveYubikeyTestCase, missing_mode, ykman_cli)
@unittest.skipIf(*missing_mode(TRANSPORT.CCID))
class TestOpenPGP(DestructiveYubikeyTestCase):
def setUp(self):
ykman_cli('openpgp', 'reset', '-f')
def test_openpgp_info(self):
output = ykman_cli('openpgp', 'info')
self.assertIn('OpenPGP version:', output)
def test_openpgp_reset(self):
output = ykman_cli('openpgp', 'reset', '-f')
self.assertIn(
'Success! All data has been cleared and default PINs are set.',
output)
|
2b1e60a9910561de5a71e83d042b845f6be0bc73 | __init__.py | __init__.py | from . import platform_specific, input
from .graphics import screen
from .run_loop import main_run_loop, every
platform_specific.fixup_env()
def run():
main_run_loop.add_wait_callback(input.check_for_quit_event)
main_run_loop.add_after_action_callback(screen.after_loop)
main_run_loop.run()
| from . import platform_specific, input
from .graphics import screen
from .run_loop import main_run_loop, every
platform_specific.fixup_env()
def run(loop=None):
if loop is not None:
every(seconds=1.0/30)(loop)
main_run_loop.add_wait_callback(input.check_for_quit_event)
main_run_loop.add_after_action_callback(screen.after_loop)
main_run_loop.run()
| Allow run argument to avoid @every template | Allow run argument to avoid @every template
| Python | bsd-2-clause | furbrain/tingbot-python | from . import platform_specific, input
from .graphics import screen
from .run_loop import main_run_loop, every
platform_specific.fixup_env()
- def run():
+ def run(loop=None):
+ if loop is not None:
+ every(seconds=1.0/30)(loop)
+
main_run_loop.add_wait_callback(input.check_for_quit_event)
main_run_loop.add_after_action_callback(screen.after_loop)
main_run_loop.run()
| Allow run argument to avoid @every template | ## Code Before:
from . import platform_specific, input
from .graphics import screen
from .run_loop import main_run_loop, every
platform_specific.fixup_env()
def run():
main_run_loop.add_wait_callback(input.check_for_quit_event)
main_run_loop.add_after_action_callback(screen.after_loop)
main_run_loop.run()
## Instruction:
Allow run argument to avoid @every template
## Code After:
from . import platform_specific, input
from .graphics import screen
from .run_loop import main_run_loop, every
platform_specific.fixup_env()
def run(loop=None):
if loop is not None:
every(seconds=1.0/30)(loop)
main_run_loop.add_wait_callback(input.check_for_quit_event)
main_run_loop.add_after_action_callback(screen.after_loop)
main_run_loop.run()
|
0d42aa0158bb4f13098bdb5341bead9b1d7c686a | __init__.py | __init__.py | from django.core.mail import mail_managers
from django.dispatch import dispatcher
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.contrib.comments.signals import comment_was_posted
from kamu.comments.models import KamuComment
import settings
def comment_notification(sender, comment, request, **kwargs):
subject = 'New comment on %s' % str(comment.content_object)
msg = u'Comment from: %s (%s)\n\n' % (comment.user_name, request.META['REMOTE_ADDR'])
msg += u'Comment text:\n\n%s\n' % comment.comment
mail_managers(subject, msg, fail_silently=True)
comment_was_posted.connect(comment_notification, sender=KamuComment)
def user_notification(sender, instance, **kwargs):
user = instance
subject = u"New user '%s' created" % (user.username)
msg = u"Email '%s'\n" % (user.email)
mail_managers(subject, msg, fail_silently=True)
post_save.connect(user_notification, sender=User)
| from django.core.mail import mail_managers
from django.dispatch import dispatcher
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.contrib.comments.signals import comment_was_posted
from kamu.comments.models import KamuComment
import settings
def comment_notification(sender, comment, request, **kwargs):
subject = 'New comment on %s' % str(comment.content_object)
msg = u'Comment from: %s (%s)\n\n' % (comment.user_name, request.META['REMOTE_ADDR'])
msg += u'Comment text:\n\n%s\n' % comment.comment
mail_managers(subject, msg, fail_silently=True)
comment_was_posted.connect(comment_notification, sender=KamuComment)
def user_notification(sender, instance, **kwargs):
if (not 'created' in kwargs) or (not kwargs['created']):
return
user = instance
subject = u"New user '%s' created" % (user.username)
msg = u"Email '%s'\n" % (user.email)
mail_managers(subject, msg, fail_silently=True)
post_save.connect(user_notification, sender=User)
| Make sure to send email only when a new user is created | Make sure to send email only when a new user is created
| Python | agpl-3.0 | kansanmuisti/kamu,kansanmuisti/kamu,kansanmuisti/kamu,kansanmuisti/kamu,kansanmuisti/kamu | from django.core.mail import mail_managers
from django.dispatch import dispatcher
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.contrib.comments.signals import comment_was_posted
from kamu.comments.models import KamuComment
import settings
def comment_notification(sender, comment, request, **kwargs):
subject = 'New comment on %s' % str(comment.content_object)
msg = u'Comment from: %s (%s)\n\n' % (comment.user_name, request.META['REMOTE_ADDR'])
msg += u'Comment text:\n\n%s\n' % comment.comment
mail_managers(subject, msg, fail_silently=True)
comment_was_posted.connect(comment_notification, sender=KamuComment)
def user_notification(sender, instance, **kwargs):
+ if (not 'created' in kwargs) or (not kwargs['created']):
+ return
user = instance
subject = u"New user '%s' created" % (user.username)
msg = u"Email '%s'\n" % (user.email)
mail_managers(subject, msg, fail_silently=True)
post_save.connect(user_notification, sender=User)
| Make sure to send email only when a new user is created | ## Code Before:
from django.core.mail import mail_managers
from django.dispatch import dispatcher
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.contrib.comments.signals import comment_was_posted
from kamu.comments.models import KamuComment
import settings
def comment_notification(sender, comment, request, **kwargs):
subject = 'New comment on %s' % str(comment.content_object)
msg = u'Comment from: %s (%s)\n\n' % (comment.user_name, request.META['REMOTE_ADDR'])
msg += u'Comment text:\n\n%s\n' % comment.comment
mail_managers(subject, msg, fail_silently=True)
comment_was_posted.connect(comment_notification, sender=KamuComment)
def user_notification(sender, instance, **kwargs):
user = instance
subject = u"New user '%s' created" % (user.username)
msg = u"Email '%s'\n" % (user.email)
mail_managers(subject, msg, fail_silently=True)
post_save.connect(user_notification, sender=User)
## Instruction:
Make sure to send email only when a new user is created
## Code After:
from django.core.mail import mail_managers
from django.dispatch import dispatcher
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.contrib.comments.signals import comment_was_posted
from kamu.comments.models import KamuComment
import settings
def comment_notification(sender, comment, request, **kwargs):
subject = 'New comment on %s' % str(comment.content_object)
msg = u'Comment from: %s (%s)\n\n' % (comment.user_name, request.META['REMOTE_ADDR'])
msg += u'Comment text:\n\n%s\n' % comment.comment
mail_managers(subject, msg, fail_silently=True)
comment_was_posted.connect(comment_notification, sender=KamuComment)
def user_notification(sender, instance, **kwargs):
if (not 'created' in kwargs) or (not kwargs['created']):
return
user = instance
subject = u"New user '%s' created" % (user.username)
msg = u"Email '%s'\n" % (user.email)
mail_managers(subject, msg, fail_silently=True)
post_save.connect(user_notification, sender=User)
|
ad7e93fa74054e3d962e34807f5d04acd719df33 | website/search_migration/migrate.py | website/search_migration/migrate.py | '''Migration script for Search-enabled Models.'''
from __future__ import absolute_import
import logging
from modularodm.query.querydialect import DefaultQueryDialect as Q
from website.models import Node
from framework.auth import User
import website.search.search as search
from website.app import init_app
logger = logging.getLogger(__name__)
app = init_app("website.settings", set_backends=True, routes=True)
def migrate_nodes():
nodes = Node.find(Q('is_public', 'eq', True) & Q('is_deleted', 'eq', False))
for i, node in enumerate(nodes):
node.update_search()
return i + 1 # Started counting from 0
def migrate_users():
for i, user in enumerate(User.find()):
if user.is_active:
user.update_search()
return i + 1 # Started counting from 0
def main():
ctx = app.test_request_context()
ctx.push()
search.delete_all()
search.create_index()
logger.info("Nodes migrated: {}".format(migrate_nodes()))
logger.info("Users migrated: {}".format(migrate_users()))
ctx.pop()
if __name__ == '__main__':
main()
| '''Migration script for Search-enabled Models.'''
from __future__ import absolute_import
import logging
from modularodm.query.querydialect import DefaultQueryDialect as Q
from website.models import Node
from framework.auth import User
import website.search.search as search
from website.app import init_app
logger = logging.getLogger(__name__)
app = init_app("website.settings", set_backends=True, routes=True)
def migrate_nodes():
nodes = Node.find(Q('is_public', 'eq', True) & Q('is_deleted', 'eq', False))
for i, node in enumerate(nodes):
node.update_search()
logger.info('Nodes migrated: {}'.format(i + 1))
def migrate_users():
n_iter = 0
for i, user in enumerate(User.find()):
if user.is_active:
user.update_search()
n_iter += 1
logger.info('Users iterated: {0}\nUsers migrated: {1}'.format(i + 1, n_iter))
def main():
ctx = app.test_request_context()
ctx.push()
search.delete_all()
search.create_index()
migrate_nodes()
migrate_users()
ctx.pop()
if __name__ == '__main__':
main()
| Add additional logging for users' | Add additional logging for users'
| Python | apache-2.0 | KAsante95/osf.io,hmoco/osf.io,petermalcolm/osf.io,amyshi188/osf.io,rdhyee/osf.io,samanehsan/osf.io,GaryKriebel/osf.io,mluo613/osf.io,ticklemepierce/osf.io,jnayak1/osf.io,GaryKriebel/osf.io,bdyetton/prettychart,mfraezz/osf.io,GaryKriebel/osf.io,ticklemepierce/osf.io,caneruguz/osf.io,crcresearch/osf.io,abought/osf.io,zachjanicki/osf.io,monikagrabowska/osf.io,caseyrygt/osf.io,baylee-d/osf.io,lyndsysimon/osf.io,billyhunt/osf.io,arpitar/osf.io,felliott/osf.io,GageGaskins/osf.io,jinluyuan/osf.io,reinaH/osf.io,billyhunt/osf.io,MerlinZhang/osf.io,caseyrygt/osf.io,kushG/osf.io,kch8qx/osf.io,kushG/osf.io,lyndsysimon/osf.io,dplorimer/osf,kwierman/osf.io,himanshuo/osf.io,dplorimer/osf,emetsger/osf.io,dplorimer/osf,kwierman/osf.io,barbour-em/osf.io,Nesiehr/osf.io,wearpants/osf.io,sloria/osf.io,chennan47/osf.io,cosenal/osf.io,binoculars/osf.io,cldershem/osf.io,adlius/osf.io,TomHeatwole/osf.io,zkraime/osf.io,caseyrygt/osf.io,laurenrevere/osf.io,leb2dg/osf.io,chrisseto/osf.io,revanthkolli/osf.io,jnayak1/osf.io,laurenrevere/osf.io,HalcyonChimera/osf.io,cldershem/osf.io,KAsante95/osf.io,laurenrevere/osf.io,emetsger/osf.io,Johnetordoff/osf.io,bdyetton/prettychart,doublebits/osf.io,saradbowman/osf.io,DanielSBrown/osf.io,CenterForOpenScience/osf.io,felliott/osf.io,DanielSBrown/osf.io,jeffreyliu3230/osf.io,erinspace/osf.io,hmoco/osf.io,leb2dg/osf.io,alexschiller/osf.io,brandonPurvis/osf.io,jolene-esposito/osf.io,mluke93/osf.io,jeffreyliu3230/osf.io,HarryRybacki/osf.io,hmoco/osf.io,wearpants/osf.io,cwisecarver/osf.io,zachjanicki/osf.io,TomHeatwole/osf.io,icereval/osf.io,caseyrollins/osf.io,arpitar/osf.io,chrisseto/osf.io,Johnetordoff/osf.io,wearpants/osf.io,HarryRybacki/osf.io,amyshi188/osf.io,asanfilippo7/osf.io,Ghalko/osf.io,jmcarp/osf.io,kch8qx/osf.io,leb2dg/osf.io,KAsante95/osf.io,caseyrollins/osf.io,doublebits/osf.io,acshi/osf.io,HarryRybacki/osf.io,njantrania/osf.io,saradbowman/osf.io,lamdnhan/osf.io,acshi/osf.io,arpitar/osf.io,DanielSBrown/osf.io,baylee-d/osf.io,bdyetton/prettychart,jeffreyliu3230/osf.io,sbt9uc/osf.io,adlius/osf.io,alexschiller/osf.io,SSJohns/osf.io,cwisecarver/osf.io,mfraezz/osf.io,ckc6cz/osf.io,mluke93/osf.io,mluo613/osf.io,brianjgeiger/osf.io,jinluyuan/osf.io,sbt9uc/osf.io,kch8qx/osf.io,samchrisinger/osf.io,barbour-em/osf.io,mattclark/osf.io,zamattiac/osf.io,petermalcolm/osf.io,ticklemepierce/osf.io,fabianvf/osf.io,brandonPurvis/osf.io,lamdnhan/osf.io,monikagrabowska/osf.io,binoculars/osf.io,fabianvf/osf.io,fabianvf/osf.io,aaxelb/osf.io,brianjgeiger/osf.io,adlius/osf.io,samchrisinger/osf.io,alexschiller/osf.io,kushG/osf.io,samanehsan/osf.io,Johnetordoff/osf.io,aaxelb/osf.io,crcresearch/osf.io,brandonPurvis/osf.io,GageGaskins/osf.io,ZobairAlijan/osf.io,jmcarp/osf.io,RomanZWang/osf.io,mluke93/osf.io,barbour-em/osf.io,arpitar/osf.io,reinaH/osf.io,ckc6cz/osf.io,SSJohns/osf.io,Nesiehr/osf.io,revanthkolli/osf.io,kushG/osf.io,binoculars/osf.io,kwierman/osf.io,HalcyonChimera/osf.io,HalcyonChimera/osf.io,fabianvf/osf.io,CenterForOpenScience/osf.io,CenterForOpenScience/osf.io,zamattiac/osf.io,CenterForOpenScience/osf.io,caneruguz/osf.io,amyshi188/osf.io,TomBaxter/osf.io,mattclark/osf.io,sbt9uc/osf.io,Ghalko/osf.io,abought/osf.io,felliott/osf.io,doublebits/osf.io,RomanZWang/osf.io,brandonPurvis/osf.io,cslzchen/osf.io,caneruguz/osf.io,sbt9uc/osf.io,cwisecarver/osf.io,aaxelb/osf.io,sloria/osf.io,alexschiller/osf.io,Johnetordoff/osf.io,RomanZWang/osf.io,zkraime/osf.io,billyhunt/osf.io,acshi/osf.io,MerlinZhang/osf.io,monikagrabowska/osf.io,lamdnhan/osf.io,sloria/osf.io,erinspace/osf.io,hmoco/osf.io,ckc6cz/osf.io,baylee-d/osf.io,emetsger/osf.io,jmcarp/osf.io,abought/osf.io,monikagrabowska/osf.io,njantrania/osf.io,cwisecarver/osf.io,asanfilippo7/osf.io,zamattiac/osf.io,ZobairAlijan/osf.io,lyndsysimon/osf.io,Ghalko/osf.io,jeffreyliu3230/osf.io,zkraime/osf.io,ZobairAlijan/osf.io,TomHeatwole/osf.io,mfraezz/osf.io,Nesiehr/osf.io,lamdnhan/osf.io,mluo613/osf.io,pattisdr/osf.io,zachjanicki/osf.io,HarryRybacki/osf.io,zkraime/osf.io,petermalcolm/osf.io,TomBaxter/osf.io,asanfilippo7/osf.io,KAsante95/osf.io,kwierman/osf.io,alexschiller/osf.io,brianjgeiger/osf.io,kch8qx/osf.io,revanthkolli/osf.io,barbour-em/osf.io,haoyuchen1992/osf.io,samchrisinger/osf.io,SSJohns/osf.io,asanfilippo7/osf.io,HalcyonChimera/osf.io,himanshuo/osf.io,rdhyee/osf.io,samchrisinger/osf.io,njantrania/osf.io,jolene-esposito/osf.io,cslzchen/osf.io,jnayak1/osf.io,doublebits/osf.io,jolene-esposito/osf.io,aaxelb/osf.io,njantrania/osf.io,cldershem/osf.io,SSJohns/osf.io,petermalcolm/osf.io,lyndsysimon/osf.io,felliott/osf.io,icereval/osf.io,cosenal/osf.io,revanthkolli/osf.io,adlius/osf.io,ZobairAlijan/osf.io,mluke93/osf.io,danielneis/osf.io,TomHeatwole/osf.io,cslzchen/osf.io,reinaH/osf.io,leb2dg/osf.io,caneruguz/osf.io,MerlinZhang/osf.io,RomanZWang/osf.io,pattisdr/osf.io,emetsger/osf.io,samanehsan/osf.io,cosenal/osf.io,himanshuo/osf.io,billyhunt/osf.io,acshi/osf.io,danielneis/osf.io,rdhyee/osf.io,cosenal/osf.io,billyhunt/osf.io,abought/osf.io,ticklemepierce/osf.io,mfraezz/osf.io,himanshuo/osf.io,kch8qx/osf.io,acshi/osf.io,wearpants/osf.io,brandonPurvis/osf.io,dplorimer/osf,TomBaxter/osf.io,Nesiehr/osf.io,amyshi188/osf.io,haoyuchen1992/osf.io,DanielSBrown/osf.io,chrisseto/osf.io,crcresearch/osf.io,MerlinZhang/osf.io,GaryKriebel/osf.io,caseyrygt/osf.io,jmcarp/osf.io,cslzchen/osf.io,danielneis/osf.io,haoyuchen1992/osf.io,zamattiac/osf.io,chennan47/osf.io,jolene-esposito/osf.io,chennan47/osf.io,jnayak1/osf.io,zachjanicki/osf.io,chrisseto/osf.io,caseyrollins/osf.io,mattclark/osf.io,mluo613/osf.io,doublebits/osf.io,erinspace/osf.io,icereval/osf.io,brianjgeiger/osf.io,bdyetton/prettychart,rdhyee/osf.io,pattisdr/osf.io,mluo613/osf.io,ckc6cz/osf.io,jinluyuan/osf.io,GageGaskins/osf.io,danielneis/osf.io,jinluyuan/osf.io,Ghalko/osf.io,monikagrabowska/osf.io,samanehsan/osf.io,reinaH/osf.io,RomanZWang/osf.io,KAsante95/osf.io,GageGaskins/osf.io,GageGaskins/osf.io,haoyuchen1992/osf.io,cldershem/osf.io | '''Migration script for Search-enabled Models.'''
from __future__ import absolute_import
import logging
from modularodm.query.querydialect import DefaultQueryDialect as Q
from website.models import Node
from framework.auth import User
import website.search.search as search
from website.app import init_app
logger = logging.getLogger(__name__)
app = init_app("website.settings", set_backends=True, routes=True)
def migrate_nodes():
nodes = Node.find(Q('is_public', 'eq', True) & Q('is_deleted', 'eq', False))
for i, node in enumerate(nodes):
node.update_search()
- return i + 1 # Started counting from 0
+ logger.info('Nodes migrated: {}'.format(i + 1))
def migrate_users():
+ n_iter = 0
for i, user in enumerate(User.find()):
if user.is_active:
user.update_search()
+ n_iter += 1
- return i + 1 # Started counting from 0
+ logger.info('Users iterated: {0}\nUsers migrated: {1}'.format(i + 1, n_iter))
def main():
ctx = app.test_request_context()
ctx.push()
search.delete_all()
search.create_index()
- logger.info("Nodes migrated: {}".format(migrate_nodes()))
- logger.info("Users migrated: {}".format(migrate_users()))
+ migrate_nodes()
+ migrate_users()
ctx.pop()
if __name__ == '__main__':
main()
| Add additional logging for users' | ## Code Before:
'''Migration script for Search-enabled Models.'''
from __future__ import absolute_import
import logging
from modularodm.query.querydialect import DefaultQueryDialect as Q
from website.models import Node
from framework.auth import User
import website.search.search as search
from website.app import init_app
logger = logging.getLogger(__name__)
app = init_app("website.settings", set_backends=True, routes=True)
def migrate_nodes():
nodes = Node.find(Q('is_public', 'eq', True) & Q('is_deleted', 'eq', False))
for i, node in enumerate(nodes):
node.update_search()
return i + 1 # Started counting from 0
def migrate_users():
for i, user in enumerate(User.find()):
if user.is_active:
user.update_search()
return i + 1 # Started counting from 0
def main():
ctx = app.test_request_context()
ctx.push()
search.delete_all()
search.create_index()
logger.info("Nodes migrated: {}".format(migrate_nodes()))
logger.info("Users migrated: {}".format(migrate_users()))
ctx.pop()
if __name__ == '__main__':
main()
## Instruction:
Add additional logging for users'
## Code After:
'''Migration script for Search-enabled Models.'''
from __future__ import absolute_import
import logging
from modularodm.query.querydialect import DefaultQueryDialect as Q
from website.models import Node
from framework.auth import User
import website.search.search as search
from website.app import init_app
logger = logging.getLogger(__name__)
app = init_app("website.settings", set_backends=True, routes=True)
def migrate_nodes():
nodes = Node.find(Q('is_public', 'eq', True) & Q('is_deleted', 'eq', False))
for i, node in enumerate(nodes):
node.update_search()
logger.info('Nodes migrated: {}'.format(i + 1))
def migrate_users():
n_iter = 0
for i, user in enumerate(User.find()):
if user.is_active:
user.update_search()
n_iter += 1
logger.info('Users iterated: {0}\nUsers migrated: {1}'.format(i + 1, n_iter))
def main():
ctx = app.test_request_context()
ctx.push()
search.delete_all()
search.create_index()
migrate_nodes()
migrate_users()
ctx.pop()
if __name__ == '__main__':
main()
|
305849d57cc6897c65b4e0996f70a21f1d873d25 | awp/main.py | awp/main.py |
import argparse
import json
import jsonschema
import awp.packager
import awp.validator
# Parse arguments given via command-line interface
def parse_cli_args():
parser = argparse.ArgumentParser()
parser.add_argument(
'--force', '-f', action='store_true',
help='forces the copying of all files and directories')
parser.add_argument(
'--export', '-e', nargs='?', const='', default=None,
help='exports the installed workflow to the local project directory')
parser.add_argument(
'--version', '-v',
help='the new version number to use for the workflow')
return parser.parse_args()
# Locate and parse the configuration for the utility
def get_utility_config():
with open('packager.json', 'r') as config_file:
return json.load(config_file)
def main():
cli_args = parse_cli_args()
config = get_utility_config()
try:
awp.validator.validate_config(config)
awp.packager.package_workflow(
config,
version=cli_args.version,
export_file=cli_args.export,
force=cli_args.force)
except jsonschema.exceptions.ValidationError as error:
print(error.message)
if __name__ == '__main__':
main()
|
import argparse
import json
import jsonschema
import awp.packager
import awp.validator
# Parse arguments given via command-line interface
def parse_cli_args():
parser = argparse.ArgumentParser()
parser.add_argument(
'--force', '-f', action='store_true',
help='forces the copying of all files and directories')
parser.add_argument(
'--export', '-e', nargs='?', const='', default=None,
help='exports the installed workflow to the local project directory')
parser.add_argument(
'--version', '-v',
help='the new version number to use for the workflow')
return parser.parse_args()
# Locate and parse the configuration for the utility
def get_utility_config():
with open('packager.json', 'r') as config_file:
return json.load(config_file)
def main():
cli_args = parse_cli_args()
config = get_utility_config()
try:
awp.validator.validate_config(config)
awp.packager.package_workflow(
config,
version=cli_args.version,
export_file=cli_args.export,
force=cli_args.force)
except jsonschema.exceptions.ValidationError as error:
print('awp (from packager.json): {}'.format(error.message))
if __name__ == '__main__':
main()
| Clarify where packager.json validation error originates | Clarify where packager.json validation error originates
| Python | mit | caleb531/alfred-workflow-packager |
import argparse
import json
import jsonschema
import awp.packager
import awp.validator
# Parse arguments given via command-line interface
def parse_cli_args():
parser = argparse.ArgumentParser()
parser.add_argument(
'--force', '-f', action='store_true',
help='forces the copying of all files and directories')
parser.add_argument(
'--export', '-e', nargs='?', const='', default=None,
help='exports the installed workflow to the local project directory')
parser.add_argument(
'--version', '-v',
help='the new version number to use for the workflow')
return parser.parse_args()
# Locate and parse the configuration for the utility
def get_utility_config():
with open('packager.json', 'r') as config_file:
return json.load(config_file)
def main():
cli_args = parse_cli_args()
config = get_utility_config()
try:
awp.validator.validate_config(config)
awp.packager.package_workflow(
config,
version=cli_args.version,
export_file=cli_args.export,
force=cli_args.force)
except jsonschema.exceptions.ValidationError as error:
- print(error.message)
+ print('awp (from packager.json): {}'.format(error.message))
if __name__ == '__main__':
main()
| Clarify where packager.json validation error originates | ## Code Before:
import argparse
import json
import jsonschema
import awp.packager
import awp.validator
# Parse arguments given via command-line interface
def parse_cli_args():
parser = argparse.ArgumentParser()
parser.add_argument(
'--force', '-f', action='store_true',
help='forces the copying of all files and directories')
parser.add_argument(
'--export', '-e', nargs='?', const='', default=None,
help='exports the installed workflow to the local project directory')
parser.add_argument(
'--version', '-v',
help='the new version number to use for the workflow')
return parser.parse_args()
# Locate and parse the configuration for the utility
def get_utility_config():
with open('packager.json', 'r') as config_file:
return json.load(config_file)
def main():
cli_args = parse_cli_args()
config = get_utility_config()
try:
awp.validator.validate_config(config)
awp.packager.package_workflow(
config,
version=cli_args.version,
export_file=cli_args.export,
force=cli_args.force)
except jsonschema.exceptions.ValidationError as error:
print(error.message)
if __name__ == '__main__':
main()
## Instruction:
Clarify where packager.json validation error originates
## Code After:
import argparse
import json
import jsonschema
import awp.packager
import awp.validator
# Parse arguments given via command-line interface
def parse_cli_args():
parser = argparse.ArgumentParser()
parser.add_argument(
'--force', '-f', action='store_true',
help='forces the copying of all files and directories')
parser.add_argument(
'--export', '-e', nargs='?', const='', default=None,
help='exports the installed workflow to the local project directory')
parser.add_argument(
'--version', '-v',
help='the new version number to use for the workflow')
return parser.parse_args()
# Locate and parse the configuration for the utility
def get_utility_config():
with open('packager.json', 'r') as config_file:
return json.load(config_file)
def main():
cli_args = parse_cli_args()
config = get_utility_config()
try:
awp.validator.validate_config(config)
awp.packager.package_workflow(
config,
version=cli_args.version,
export_file=cli_args.export,
force=cli_args.force)
except jsonschema.exceptions.ValidationError as error:
print('awp (from packager.json): {}'.format(error.message))
if __name__ == '__main__':
main()
|
ad7507f795f465425e72fb6821115e395046b84d | pyshtools/shio/yilm_index_vector.py | pyshtools/shio/yilm_index_vector.py | def YilmIndexVector(i, l, m):
"""
Compute the index of an 1D array of spherical harmonic coefficients
corresponding to i, l, and m.
Usage
-----
index = YilmIndexVector (i, l, m)
Returns
-------
index : integer
Index of an 1D array of spherical harmonic coefficients corresponding
to i, l, and m.
Parameters
----------
i : integer
1 corresponds to the cosine coefficient cilm[0,:,:], and 2 corresponds
to the sine coefficient cilm[1,:,:].
l : integer
The spherical harmonic degree.
m : integer
The angular order.
Notes
-----
YilmIndexVector will calculate the index of a 1D vector of spherical
harmonic coefficients corresponding to degree l, angular order m and i
(1 = cosine, 2 = sine). The index is given by l**2+(i-1)*l+m.
"""
return l**2 + (i - 1) * l + m
| def YilmIndexVector(i, l, m):
"""
Compute the index of a 1D array of spherical harmonic coefficients
corresponding to i, l, and m.
Usage
-----
index = YilmIndexVector (i, l, m)
Returns
-------
index : integer
Index of a 1D array of spherical harmonic coefficients corresponding
to i, l, and m.
Parameters
----------
i : integer
1 corresponds to the cosine coefficient Ylm = cilm[0,:,:], and 2
corresponds to the sine coefficient Yl,-m = cilm[1,:,:].
l : integer
The spherical harmonic degree.
m : integer
The angular order, which must be greater or equal to zero.
Notes
-----
YilmIndexVector will calculate the index of a 1D vector of spherical
harmonic coefficients corresponding to degree l, (positive) angular order
m and i (1 = cosine, 2 = sine). The index is given by l**2+(i-1)*l+m.
"""
if l < 0:
raise ValueError('The spherical harmonic degree must be positive. '
'Input value is {:s}'.format(repr(l)))
if m < 0:
raise ValueError('The angular order must be positive. '
'Input value is {:s}'.format(repr(m)))
if m >= l:
raise ValueError('The angular order must be less than or equal to '
'the spherical harmonic degree. Input degree is {:s}.'
' Input order is {:s}.'.format(repr(l), repr(m)))
return l**2 + (i - 1) * l + m
| Add error checks to YilmIndexVector (and update docs) | Add error checks to YilmIndexVector (and update docs)
| Python | bsd-3-clause | SHTOOLS/SHTOOLS,MarkWieczorek/SHTOOLS,MarkWieczorek/SHTOOLS,SHTOOLS/SHTOOLS | def YilmIndexVector(i, l, m):
"""
- Compute the index of an 1D array of spherical harmonic coefficients
+ Compute the index of a 1D array of spherical harmonic coefficients
corresponding to i, l, and m.
Usage
-----
index = YilmIndexVector (i, l, m)
Returns
-------
index : integer
- Index of an 1D array of spherical harmonic coefficients corresponding
+ Index of a 1D array of spherical harmonic coefficients corresponding
to i, l, and m.
Parameters
----------
i : integer
- 1 corresponds to the cosine coefficient cilm[0,:,:], and 2 corresponds
+ 1 corresponds to the cosine coefficient Ylm = cilm[0,:,:], and 2
- to the sine coefficient cilm[1,:,:].
+ corresponds to the sine coefficient Yl,-m = cilm[1,:,:].
l : integer
The spherical harmonic degree.
m : integer
- The angular order.
+ The angular order, which must be greater or equal to zero.
Notes
-----
YilmIndexVector will calculate the index of a 1D vector of spherical
- harmonic coefficients corresponding to degree l, angular order m and i
+ harmonic coefficients corresponding to degree l, (positive) angular order
- (1 = cosine, 2 = sine). The index is given by l**2+(i-1)*l+m.
+ m and i (1 = cosine, 2 = sine). The index is given by l**2+(i-1)*l+m.
"""
+ if l < 0:
+ raise ValueError('The spherical harmonic degree must be positive. '
+ 'Input value is {:s}'.format(repr(l)))
+ if m < 0:
+ raise ValueError('The angular order must be positive. '
+ 'Input value is {:s}'.format(repr(m)))
+ if m >= l:
+ raise ValueError('The angular order must be less than or equal to '
+ 'the spherical harmonic degree. Input degree is {:s}.'
+ ' Input order is {:s}.'.format(repr(l), repr(m)))
return l**2 + (i - 1) * l + m
| Add error checks to YilmIndexVector (and update docs) | ## Code Before:
def YilmIndexVector(i, l, m):
"""
Compute the index of an 1D array of spherical harmonic coefficients
corresponding to i, l, and m.
Usage
-----
index = YilmIndexVector (i, l, m)
Returns
-------
index : integer
Index of an 1D array of spherical harmonic coefficients corresponding
to i, l, and m.
Parameters
----------
i : integer
1 corresponds to the cosine coefficient cilm[0,:,:], and 2 corresponds
to the sine coefficient cilm[1,:,:].
l : integer
The spherical harmonic degree.
m : integer
The angular order.
Notes
-----
YilmIndexVector will calculate the index of a 1D vector of spherical
harmonic coefficients corresponding to degree l, angular order m and i
(1 = cosine, 2 = sine). The index is given by l**2+(i-1)*l+m.
"""
return l**2 + (i - 1) * l + m
## Instruction:
Add error checks to YilmIndexVector (and update docs)
## Code After:
def YilmIndexVector(i, l, m):
"""
Compute the index of a 1D array of spherical harmonic coefficients
corresponding to i, l, and m.
Usage
-----
index = YilmIndexVector (i, l, m)
Returns
-------
index : integer
Index of a 1D array of spherical harmonic coefficients corresponding
to i, l, and m.
Parameters
----------
i : integer
1 corresponds to the cosine coefficient Ylm = cilm[0,:,:], and 2
corresponds to the sine coefficient Yl,-m = cilm[1,:,:].
l : integer
The spherical harmonic degree.
m : integer
The angular order, which must be greater or equal to zero.
Notes
-----
YilmIndexVector will calculate the index of a 1D vector of spherical
harmonic coefficients corresponding to degree l, (positive) angular order
m and i (1 = cosine, 2 = sine). The index is given by l**2+(i-1)*l+m.
"""
if l < 0:
raise ValueError('The spherical harmonic degree must be positive. '
'Input value is {:s}'.format(repr(l)))
if m < 0:
raise ValueError('The angular order must be positive. '
'Input value is {:s}'.format(repr(m)))
if m >= l:
raise ValueError('The angular order must be less than or equal to '
'the spherical harmonic degree. Input degree is {:s}.'
' Input order is {:s}.'.format(repr(l), repr(m)))
return l**2 + (i - 1) * l + m
|
2c7621143a9d110ebb1ea5dc7884f2c21e2786b5 | microgear/cache.py | microgear/cache.py | import os
import json
import sys
def get_item(key):
try:
return json.loads(open(os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])),key), "rb").read().decode('UTF-8'))["_"]
except (IOError, ValueError):
return None
def set_item(key,value):
open(os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])),key), "wb").write(json.dumps({"_": value}).encode('UTF-8'))
return value
def delete_item(key):
if os.path.isfile(os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])),key)):
os.remove(os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])),key))
| import os
import json
import sys
CURRENT_DIR = os.path.abspath(os.path.dirname(sys.argv[0]))
def get_item(key):
"""Return content in cached file in JSON format"""
CACHED_KEY_FILE = os.path.join(CURRENT_DIR, key)
try:
return json.loads(open(CACHED_KEY_FILE, "rb").read().decode('UTF-8'))["_"]
except (IOError, ValueError):
return None
def set_item(key,value):
"""Write JSON content from value argument to cached file and return"""
CACHED_KEY_FILE = os.path.join(CURRENT_DIR, key)
open(CACHED_KEY_FILE, "wb").write(json.dumps({"_": value}).encode('UTF-8'))
return value
def delete_item(key):
"""Delete cached file if present"""
CACHED_KEY_FILE = os.path.join(CURRENT_DIR, key)
if os.path.isfile(CACHED_KEY_FILE):
os.remove(CACHED_KEY_FILE)
| Add docstring to function and refactor some code for clarification | Add docstring to function and refactor some code for clarification
| Python | isc | netpieio/microgear-python | import os
import json
import sys
+
+ CURRENT_DIR = os.path.abspath(os.path.dirname(sys.argv[0]))
+
+
def get_item(key):
+ """Return content in cached file in JSON format"""
+ CACHED_KEY_FILE = os.path.join(CURRENT_DIR, key)
+
try:
- return json.loads(open(os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])),key), "rb").read().decode('UTF-8'))["_"]
+ return json.loads(open(CACHED_KEY_FILE, "rb").read().decode('UTF-8'))["_"]
except (IOError, ValueError):
return None
+
def set_item(key,value):
- open(os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])),key), "wb").write(json.dumps({"_": value}).encode('UTF-8'))
+ """Write JSON content from value argument to cached file and return"""
+ CACHED_KEY_FILE = os.path.join(CURRENT_DIR, key)
+
+ open(CACHED_KEY_FILE, "wb").write(json.dumps({"_": value}).encode('UTF-8'))
+
return value
+
def delete_item(key):
- if os.path.isfile(os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])),key)):
- os.remove(os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])),key))
+ """Delete cached file if present"""
+ CACHED_KEY_FILE = os.path.join(CURRENT_DIR, key)
+
+ if os.path.isfile(CACHED_KEY_FILE):
+ os.remove(CACHED_KEY_FILE)
+
| Add docstring to function and refactor some code for clarification | ## Code Before:
import os
import json
import sys
def get_item(key):
try:
return json.loads(open(os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])),key), "rb").read().decode('UTF-8'))["_"]
except (IOError, ValueError):
return None
def set_item(key,value):
open(os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])),key), "wb").write(json.dumps({"_": value}).encode('UTF-8'))
return value
def delete_item(key):
if os.path.isfile(os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])),key)):
os.remove(os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])),key))
## Instruction:
Add docstring to function and refactor some code for clarification
## Code After:
import os
import json
import sys
CURRENT_DIR = os.path.abspath(os.path.dirname(sys.argv[0]))
def get_item(key):
"""Return content in cached file in JSON format"""
CACHED_KEY_FILE = os.path.join(CURRENT_DIR, key)
try:
return json.loads(open(CACHED_KEY_FILE, "rb").read().decode('UTF-8'))["_"]
except (IOError, ValueError):
return None
def set_item(key,value):
"""Write JSON content from value argument to cached file and return"""
CACHED_KEY_FILE = os.path.join(CURRENT_DIR, key)
open(CACHED_KEY_FILE, "wb").write(json.dumps({"_": value}).encode('UTF-8'))
return value
def delete_item(key):
"""Delete cached file if present"""
CACHED_KEY_FILE = os.path.join(CURRENT_DIR, key)
if os.path.isfile(CACHED_KEY_FILE):
os.remove(CACHED_KEY_FILE)
|
562fa35a036a43526b55546d97490b3f36001a18 | robotpy_ext/misc/periodic_filter.py | robotpy_ext/misc/periodic_filter.py | import logging
import time
class PeriodicFilter:
"""
Periodic Filter to help keep down clutter in the console.
Simply add this filter to your logger and the logger will
only print periodically.
The logger will always print logging levels of WARNING or higher
"""
def __init__(self, period, bypassLevel=logging.WARN):
'''
:param period: Wait period (in seconds) between logs
:param bypassLevel: Lowest logging level that the filter should ignore
'''
self._period = period
self._loggingLoop = True
self._last_log = -period
self._bypassLevel = bypassLevel
def filter(self, record):
"""Performs filtering action for logger"""
self._refresh_logger()
return self._loggingLoop or record.levelno >= self._bypassLevel
def _refresh_logger(self):
"""Determine if the log wait period has passed"""
now = time.monotonic()
self._loggingLoop = False
if now - self._last_log > self._period:
self._loggingLoop = True
self._last_log = now
| import logging
import time
class PeriodicFilter:
"""
Periodic Filter to help keep down clutter in the console.
Simply add this filter to your logger and the logger will
only print periodically.
The logger will always print logging levels of WARNING or higher,
unless given a different bypass level
Example
class Component1:
def setup(self):
# Set period to 3 seconds, set bypass_level to WARN
self.logger.addFilter(PeriodicFilter(3, bypass_level=logging.WARN))
def execute(self):
# This message will be printed once every three seconds
self.logger.info('Component1 Executing')
# This message will be printed out every loop
self.logger.warn('Uh oh, this shouldn't have happened...')
"""
def __init__(self, period, bypass_level=logging.WARN):
'''
:param period: Wait period (in seconds) between logs
:param bypass_level: Lowest logging level that the filter should ignore
'''
self._period = period
self._loggingLoop = True
self._last_log = -period
self._bypass_level = bypass_level
def filter(self, record):
"""Performs filtering action for logger"""
self._refresh_logger()
return self._loggingLoop or record.levelno >= self._bypass_level
def _refresh_logger(self):
"""Determine if the log wait period has passed"""
now = time.monotonic()
self._loggingLoop = False
if now - self._last_log > self._period:
self._loggingLoop = True
self._last_log = now
| Create example usage. Rename bypass_level | Create example usage. Rename bypass_level
| Python | bsd-3-clause | robotpy/robotpy-wpilib-utilities,Twinters007/robotpy-wpilib-utilities,robotpy/robotpy-wpilib-utilities,Twinters007/robotpy-wpilib-utilities | import logging
import time
class PeriodicFilter:
"""
Periodic Filter to help keep down clutter in the console.
Simply add this filter to your logger and the logger will
only print periodically.
- The logger will always print logging levels of WARNING or higher
+ The logger will always print logging levels of WARNING or higher,
+ unless given a different bypass level
+
+ Example
+
+ class Component1:
+
+ def setup(self):
+ # Set period to 3 seconds, set bypass_level to WARN
+ self.logger.addFilter(PeriodicFilter(3, bypass_level=logging.WARN))
+
+ def execute(self):
+ # This message will be printed once every three seconds
+ self.logger.info('Component1 Executing')
+
+ # This message will be printed out every loop
+ self.logger.warn('Uh oh, this shouldn't have happened...')
+
"""
- def __init__(self, period, bypassLevel=logging.WARN):
+ def __init__(self, period, bypass_level=logging.WARN):
'''
:param period: Wait period (in seconds) between logs
- :param bypassLevel: Lowest logging level that the filter should ignore
+ :param bypass_level: Lowest logging level that the filter should ignore
'''
self._period = period
self._loggingLoop = True
self._last_log = -period
- self._bypassLevel = bypassLevel
+ self._bypass_level = bypass_level
def filter(self, record):
"""Performs filtering action for logger"""
self._refresh_logger()
- return self._loggingLoop or record.levelno >= self._bypassLevel
+ return self._loggingLoop or record.levelno >= self._bypass_level
def _refresh_logger(self):
"""Determine if the log wait period has passed"""
now = time.monotonic()
self._loggingLoop = False
if now - self._last_log > self._period:
self._loggingLoop = True
self._last_log = now
| Create example usage. Rename bypass_level | ## Code Before:
import logging
import time
class PeriodicFilter:
"""
Periodic Filter to help keep down clutter in the console.
Simply add this filter to your logger and the logger will
only print periodically.
The logger will always print logging levels of WARNING or higher
"""
def __init__(self, period, bypassLevel=logging.WARN):
'''
:param period: Wait period (in seconds) between logs
:param bypassLevel: Lowest logging level that the filter should ignore
'''
self._period = period
self._loggingLoop = True
self._last_log = -period
self._bypassLevel = bypassLevel
def filter(self, record):
"""Performs filtering action for logger"""
self._refresh_logger()
return self._loggingLoop or record.levelno >= self._bypassLevel
def _refresh_logger(self):
"""Determine if the log wait period has passed"""
now = time.monotonic()
self._loggingLoop = False
if now - self._last_log > self._period:
self._loggingLoop = True
self._last_log = now
## Instruction:
Create example usage. Rename bypass_level
## Code After:
import logging
import time
class PeriodicFilter:
"""
Periodic Filter to help keep down clutter in the console.
Simply add this filter to your logger and the logger will
only print periodically.
The logger will always print logging levels of WARNING or higher,
unless given a different bypass level
Example
class Component1:
def setup(self):
# Set period to 3 seconds, set bypass_level to WARN
self.logger.addFilter(PeriodicFilter(3, bypass_level=logging.WARN))
def execute(self):
# This message will be printed once every three seconds
self.logger.info('Component1 Executing')
# This message will be printed out every loop
self.logger.warn('Uh oh, this shouldn't have happened...')
"""
def __init__(self, period, bypass_level=logging.WARN):
'''
:param period: Wait period (in seconds) between logs
:param bypass_level: Lowest logging level that the filter should ignore
'''
self._period = period
self._loggingLoop = True
self._last_log = -period
self._bypass_level = bypass_level
def filter(self, record):
"""Performs filtering action for logger"""
self._refresh_logger()
return self._loggingLoop or record.levelno >= self._bypass_level
def _refresh_logger(self):
"""Determine if the log wait period has passed"""
now = time.monotonic()
self._loggingLoop = False
if now - self._last_log > self._period:
self._loggingLoop = True
self._last_log = now
|
ef72be28dc83ff2c73335c6eb13135cab8affe53 | troposphere/sso.py | troposphere/sso.py |
from . import AWSObject
from troposphere import Tags
class Assignment(AWSObject):
resource_type = "AWS::SSO::Assignment"
props = {
'InstanceArn': (basestring, True),
'PermissionSetArn': (basestring, True),
'PrincipalId': (basestring, True),
'PrincipalType': (basestring, True),
'TargetId': (basestring, True),
'TargetType': (basestring, True),
}
class PermissionSet(AWSObject):
resource_type = "AWS::SSO::PermissionSet"
props = {
'Description': (basestring, False),
'InlinePolicy': (basestring, False),
'InstanceArn': (basestring, True),
'ManagedPolicies': ([basestring], False),
'Name': (basestring, True),
'RelayStateType': (basestring, False),
'SessionDuration': (basestring, False),
'Tags': (Tags, False),
}
|
from . import AWSObject
from . import AWSProperty
from troposphere import Tags
class Assignment(AWSObject):
resource_type = "AWS::SSO::Assignment"
props = {
'InstanceArn': (basestring, True),
'PermissionSetArn': (basestring, True),
'PrincipalId': (basestring, True),
'PrincipalType': (basestring, True),
'TargetId': (basestring, True),
'TargetType': (basestring, True),
}
class AccessControlAttributeValueSourceList(AWSProperty):
props = {
'AccessControlAttributeValueSourceList': ([basestring], False),
}
class AccessControlAttributeValue(AWSProperty):
props = {
'Source': (AccessControlAttributeValueSourceList, True),
}
class AccessControlAttribute(AWSProperty):
props = {
'Key': (basestring, True),
'Value': (AccessControlAttributeValue, True),
}
class InstanceAccessControlAttributeConfiguration(AWSObject):
resource_type = "AWS::SSO::InstanceAccessControlAttributeConfiguration"
props = {
'AccessControlAttributes': ([AccessControlAttribute], False),
'InstanceAccessControlAttributeConfiguration': (dict, False),
'InstanceArn': (basestring, True),
}
class PermissionSet(AWSObject):
resource_type = "AWS::SSO::PermissionSet"
props = {
'Description': (basestring, False),
'InlinePolicy': (dict, False),
'InstanceArn': (basestring, True),
'ManagedPolicies': ([basestring], False),
'Name': (basestring, True),
'RelayStateType': (basestring, False),
'SessionDuration': (basestring, False),
'Tags': (Tags, False),
}
| Update SSO per 2020-12-18 changes | Update SSO per 2020-12-18 changes
| Python | bsd-2-clause | cloudtools/troposphere,cloudtools/troposphere |
from . import AWSObject
+ from . import AWSProperty
from troposphere import Tags
class Assignment(AWSObject):
resource_type = "AWS::SSO::Assignment"
props = {
'InstanceArn': (basestring, True),
'PermissionSetArn': (basestring, True),
'PrincipalId': (basestring, True),
'PrincipalType': (basestring, True),
'TargetId': (basestring, True),
'TargetType': (basestring, True),
}
+ class AccessControlAttributeValueSourceList(AWSProperty):
+ props = {
+ 'AccessControlAttributeValueSourceList': ([basestring], False),
+ }
+
+
+ class AccessControlAttributeValue(AWSProperty):
+ props = {
+ 'Source': (AccessControlAttributeValueSourceList, True),
+ }
+
+
+ class AccessControlAttribute(AWSProperty):
+ props = {
+ 'Key': (basestring, True),
+ 'Value': (AccessControlAttributeValue, True),
+ }
+
+
+ class InstanceAccessControlAttributeConfiguration(AWSObject):
+ resource_type = "AWS::SSO::InstanceAccessControlAttributeConfiguration"
+
+ props = {
+ 'AccessControlAttributes': ([AccessControlAttribute], False),
+ 'InstanceAccessControlAttributeConfiguration': (dict, False),
+ 'InstanceArn': (basestring, True),
+ }
+
+
class PermissionSet(AWSObject):
resource_type = "AWS::SSO::PermissionSet"
props = {
'Description': (basestring, False),
- 'InlinePolicy': (basestring, False),
+ 'InlinePolicy': (dict, False),
'InstanceArn': (basestring, True),
'ManagedPolicies': ([basestring], False),
'Name': (basestring, True),
'RelayStateType': (basestring, False),
'SessionDuration': (basestring, False),
'Tags': (Tags, False),
}
| Update SSO per 2020-12-18 changes | ## Code Before:
from . import AWSObject
from troposphere import Tags
class Assignment(AWSObject):
resource_type = "AWS::SSO::Assignment"
props = {
'InstanceArn': (basestring, True),
'PermissionSetArn': (basestring, True),
'PrincipalId': (basestring, True),
'PrincipalType': (basestring, True),
'TargetId': (basestring, True),
'TargetType': (basestring, True),
}
class PermissionSet(AWSObject):
resource_type = "AWS::SSO::PermissionSet"
props = {
'Description': (basestring, False),
'InlinePolicy': (basestring, False),
'InstanceArn': (basestring, True),
'ManagedPolicies': ([basestring], False),
'Name': (basestring, True),
'RelayStateType': (basestring, False),
'SessionDuration': (basestring, False),
'Tags': (Tags, False),
}
## Instruction:
Update SSO per 2020-12-18 changes
## Code After:
from . import AWSObject
from . import AWSProperty
from troposphere import Tags
class Assignment(AWSObject):
resource_type = "AWS::SSO::Assignment"
props = {
'InstanceArn': (basestring, True),
'PermissionSetArn': (basestring, True),
'PrincipalId': (basestring, True),
'PrincipalType': (basestring, True),
'TargetId': (basestring, True),
'TargetType': (basestring, True),
}
class AccessControlAttributeValueSourceList(AWSProperty):
props = {
'AccessControlAttributeValueSourceList': ([basestring], False),
}
class AccessControlAttributeValue(AWSProperty):
props = {
'Source': (AccessControlAttributeValueSourceList, True),
}
class AccessControlAttribute(AWSProperty):
props = {
'Key': (basestring, True),
'Value': (AccessControlAttributeValue, True),
}
class InstanceAccessControlAttributeConfiguration(AWSObject):
resource_type = "AWS::SSO::InstanceAccessControlAttributeConfiguration"
props = {
'AccessControlAttributes': ([AccessControlAttribute], False),
'InstanceAccessControlAttributeConfiguration': (dict, False),
'InstanceArn': (basestring, True),
}
class PermissionSet(AWSObject):
resource_type = "AWS::SSO::PermissionSet"
props = {
'Description': (basestring, False),
'InlinePolicy': (dict, False),
'InstanceArn': (basestring, True),
'ManagedPolicies': ([basestring], False),
'Name': (basestring, True),
'RelayStateType': (basestring, False),
'SessionDuration': (basestring, False),
'Tags': (Tags, False),
}
|
7c3a3283b3da0c01da012bb823d781036d1847b6 | packages/syft/src/syft/core/node/common/node_table/node_route.py | packages/syft/src/syft/core/node/common/node_table/node_route.py | from sqlalchemy import Boolean
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import String
# relative
from . import Base
class NodeRoute(Base):
__tablename__ = "node_route"
id = Column(Integer(), primary_key=True, autoincrement=True)
node_id = Column(Integer, ForeignKey("node.id"))
host_or_ip = Column(String(255))
is_vpn = Column(Boolean(), default=False)
| from sqlalchemy import Boolean
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import String
# relative
from . import Base
class NodeRoute(Base):
__tablename__ = "node_route"
id = Column(Integer(), primary_key=True, autoincrement=True)
node_id = Column(Integer, ForeignKey("node.id"))
host_or_ip = Column(String(255), default="")
is_vpn = Column(Boolean(), default=False)
vpn_endpoint = Column(String(255), default="")
vpn_key = Column(String(255), default="")
| ADD vpn_endpoint and vpn_key columns | ADD vpn_endpoint and vpn_key columns
| Python | apache-2.0 | OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft | from sqlalchemy import Boolean
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import String
# relative
from . import Base
class NodeRoute(Base):
__tablename__ = "node_route"
id = Column(Integer(), primary_key=True, autoincrement=True)
node_id = Column(Integer, ForeignKey("node.id"))
- host_or_ip = Column(String(255))
+ host_or_ip = Column(String(255), default="")
is_vpn = Column(Boolean(), default=False)
+ vpn_endpoint = Column(String(255), default="")
+ vpn_key = Column(String(255), default="")
| ADD vpn_endpoint and vpn_key columns | ## Code Before:
from sqlalchemy import Boolean
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import String
# relative
from . import Base
class NodeRoute(Base):
__tablename__ = "node_route"
id = Column(Integer(), primary_key=True, autoincrement=True)
node_id = Column(Integer, ForeignKey("node.id"))
host_or_ip = Column(String(255))
is_vpn = Column(Boolean(), default=False)
## Instruction:
ADD vpn_endpoint and vpn_key columns
## Code After:
from sqlalchemy import Boolean
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import String
# relative
from . import Base
class NodeRoute(Base):
__tablename__ = "node_route"
id = Column(Integer(), primary_key=True, autoincrement=True)
node_id = Column(Integer, ForeignKey("node.id"))
host_or_ip = Column(String(255), default="")
is_vpn = Column(Boolean(), default=False)
vpn_endpoint = Column(String(255), default="")
vpn_key = Column(String(255), default="")
|
1f697a2c7bcf0f7769a9fc4f81be676ed5ee97c6 | examples/flask/flask_seguro/cart.py | examples/flask/flask_seguro/cart.py | from flask_seguro.products import Products
from flask import current_app as app
class Cart:
def __init__(self, cart_dict={}):
if cart_dict == {}:
self.total = 0
self.subtotal = 0
self.items = []
else:
self.total = cart_dict["total"]
self.subtotal = cart_dict["subtotal"]
self.items = cart_dict["items"]
self.extra_amount = float(app.config['EXTRA_AMOUNT'])
def to_dict(self):
return {"total": self.total,
"subtotal": self.subtotal,
"items": self.items,
"extra_amount": self.extra_amount}
def change_item(self, item_id, operation):
product = Products().get_one(item_id)
if product:
if operation == 'add':
self.items.append(product)
elif operation == 'remove':
cart_product = filter(
lambda x: x['id'] == product['id'], self.items)
self.items.remove(cart_product[0])
self.update()
return True
else:
return False
def update(self):
subtotal = float(0)
total = float(0)
for product in self.items:
subtotal += float(product["price"])
if subtotal > 0:
total = subtotal + self.extra_amount
self.subtotal = subtotal
self.total = total
| from flask_seguro.products import Products
from flask import current_app as app
class Cart:
def __init__(self, cart_dict=None):
cart_dict = cart_dict or {}
if cart_dict == {}:
self.total = 0
self.subtotal = 0
self.items = []
else:
self.total = cart_dict["total"]
self.subtotal = cart_dict["subtotal"]
self.items = cart_dict["items"]
self.extra_amount = float(app.config['EXTRA_AMOUNT'])
def to_dict(self):
return {"total": self.total,
"subtotal": self.subtotal,
"items": self.items,
"extra_amount": self.extra_amount}
def change_item(self, item_id, operation):
product = Products().get_one(item_id)
if product:
if operation == 'add':
self.items.append(product)
elif operation == 'remove':
cart_product = filter(
lambda x: x['id'] == product['id'], self.items)
self.items.remove(cart_product[0])
self.update()
return True
else:
return False
def update(self):
subtotal = float(0)
total = float(0)
for product in self.items:
subtotal += float(product["price"])
if subtotal > 0:
total = subtotal + self.extra_amount
self.subtotal = subtotal
self.total = total
| Fix dangerous default mutable value | Fix dangerous default mutable value | Python | mit | rgcarrasqueira/python-pagseguro,vintasoftware/python-pagseguro,rochacbruno/python-pagseguro | from flask_seguro.products import Products
from flask import current_app as app
class Cart:
- def __init__(self, cart_dict={}):
+ def __init__(self, cart_dict=None):
+ cart_dict = cart_dict or {}
if cart_dict == {}:
self.total = 0
self.subtotal = 0
self.items = []
else:
self.total = cart_dict["total"]
self.subtotal = cart_dict["subtotal"]
self.items = cart_dict["items"]
self.extra_amount = float(app.config['EXTRA_AMOUNT'])
def to_dict(self):
return {"total": self.total,
"subtotal": self.subtotal,
"items": self.items,
"extra_amount": self.extra_amount}
def change_item(self, item_id, operation):
product = Products().get_one(item_id)
if product:
if operation == 'add':
self.items.append(product)
elif operation == 'remove':
cart_product = filter(
lambda x: x['id'] == product['id'], self.items)
self.items.remove(cart_product[0])
self.update()
return True
else:
return False
def update(self):
subtotal = float(0)
total = float(0)
for product in self.items:
subtotal += float(product["price"])
if subtotal > 0:
total = subtotal + self.extra_amount
self.subtotal = subtotal
self.total = total
| Fix dangerous default mutable value | ## Code Before:
from flask_seguro.products import Products
from flask import current_app as app
class Cart:
def __init__(self, cart_dict={}):
if cart_dict == {}:
self.total = 0
self.subtotal = 0
self.items = []
else:
self.total = cart_dict["total"]
self.subtotal = cart_dict["subtotal"]
self.items = cart_dict["items"]
self.extra_amount = float(app.config['EXTRA_AMOUNT'])
def to_dict(self):
return {"total": self.total,
"subtotal": self.subtotal,
"items": self.items,
"extra_amount": self.extra_amount}
def change_item(self, item_id, operation):
product = Products().get_one(item_id)
if product:
if operation == 'add':
self.items.append(product)
elif operation == 'remove':
cart_product = filter(
lambda x: x['id'] == product['id'], self.items)
self.items.remove(cart_product[0])
self.update()
return True
else:
return False
def update(self):
subtotal = float(0)
total = float(0)
for product in self.items:
subtotal += float(product["price"])
if subtotal > 0:
total = subtotal + self.extra_amount
self.subtotal = subtotal
self.total = total
## Instruction:
Fix dangerous default mutable value
## Code After:
from flask_seguro.products import Products
from flask import current_app as app
class Cart:
def __init__(self, cart_dict=None):
cart_dict = cart_dict or {}
if cart_dict == {}:
self.total = 0
self.subtotal = 0
self.items = []
else:
self.total = cart_dict["total"]
self.subtotal = cart_dict["subtotal"]
self.items = cart_dict["items"]
self.extra_amount = float(app.config['EXTRA_AMOUNT'])
def to_dict(self):
return {"total": self.total,
"subtotal": self.subtotal,
"items": self.items,
"extra_amount": self.extra_amount}
def change_item(self, item_id, operation):
product = Products().get_one(item_id)
if product:
if operation == 'add':
self.items.append(product)
elif operation == 'remove':
cart_product = filter(
lambda x: x['id'] == product['id'], self.items)
self.items.remove(cart_product[0])
self.update()
return True
else:
return False
def update(self):
subtotal = float(0)
total = float(0)
for product in self.items:
subtotal += float(product["price"])
if subtotal > 0:
total = subtotal + self.extra_amount
self.subtotal = subtotal
self.total = total
|
45ee803cad9b16351a2d02c7ce9d39a36f8f2480 | stutuz/__init__.py | stutuz/__init__.py |
from __future__ import division
from __future__ import absolute_import
from __future__ import with_statement
from __future__ import print_function
from __future__ import unicode_literals
from logbook import NestedSetup
from flask import Flask, request
from flaskext.babel import Babel, get_locale
from stutuz.extensions import genshi, db
from stutuz.converters import converters
from stutuz.modules import MOUNTS
def create_app(config=None):
app = Flask(__name__)
app.config.from_object('stutuz.configs')
if config is not None:
app.config.from_object(config)
app.config.from_envvar('STUTUZ_CONFIG', silent=True)
handlers = app.config.get('LOGBOOK_HANDLERS')
with NestedSetup(handlers):
for extension in genshi, db:
extension.init_app(app)
babel = Babel(app)
@babel.localeselector
def best_locale():
return request.accept_languages.best_match(
map(str, babel.list_translations()))
@app.context_processor
def locale():
return dict(locale=get_locale())
for middleware in app.config.get('MIDDLEWARES', ()):
app.wsgi_app = middleware(app.wsgi_app)
app.url_map.converters.update(converters)
for url_prefix, module in MOUNTS:
app.register_module(module, url_prefix=url_prefix)
return app
|
from __future__ import division
from __future__ import absolute_import
from __future__ import with_statement
from __future__ import print_function
from __future__ import unicode_literals
from logbook import NestedSetup
from flask import Flask, request
from flaskext.babel import Babel, get_locale
from stutuz.extensions import genshi, db
from stutuz.converters import converters
from stutuz.modules import MOUNTS
def create_app(config=None):
app = Flask(__name__)
app.config.from_object('stutuz.configs')
if config is not None:
app.config.from_object(config)
app.config.from_envvar('STUTUZ_CONFIG', silent=True)
handlers = app.config.get('LOGBOOK_HANDLERS')
with NestedSetup(handlers):
for extension in genshi, db:
extension.init_app(app)
babel = Babel(app)
@babel.localeselector
def best_locale():
if 'locale' in request.args:
return request.args['locale']
return request.accept_languages.best_match(
map(str, babel.list_translations()))
@app.context_processor
def locale():
return dict(locale=get_locale())
for middleware in app.config.get('MIDDLEWARES', ()):
app.wsgi_app = middleware(app.wsgi_app)
app.url_map.converters.update(converters)
for url_prefix, module in MOUNTS:
app.register_module(module, url_prefix=url_prefix)
return app
| Allow setting locale with a query parameter | Allow setting locale with a query parameter
| Python | bsd-2-clause | dag/stutuz |
from __future__ import division
from __future__ import absolute_import
from __future__ import with_statement
from __future__ import print_function
from __future__ import unicode_literals
from logbook import NestedSetup
from flask import Flask, request
from flaskext.babel import Babel, get_locale
from stutuz.extensions import genshi, db
from stutuz.converters import converters
from stutuz.modules import MOUNTS
def create_app(config=None):
app = Flask(__name__)
app.config.from_object('stutuz.configs')
if config is not None:
app.config.from_object(config)
app.config.from_envvar('STUTUZ_CONFIG', silent=True)
handlers = app.config.get('LOGBOOK_HANDLERS')
with NestedSetup(handlers):
for extension in genshi, db:
extension.init_app(app)
babel = Babel(app)
@babel.localeselector
def best_locale():
+ if 'locale' in request.args:
+ return request.args['locale']
return request.accept_languages.best_match(
map(str, babel.list_translations()))
@app.context_processor
def locale():
return dict(locale=get_locale())
for middleware in app.config.get('MIDDLEWARES', ()):
app.wsgi_app = middleware(app.wsgi_app)
app.url_map.converters.update(converters)
for url_prefix, module in MOUNTS:
app.register_module(module, url_prefix=url_prefix)
return app
| Allow setting locale with a query parameter | ## Code Before:
from __future__ import division
from __future__ import absolute_import
from __future__ import with_statement
from __future__ import print_function
from __future__ import unicode_literals
from logbook import NestedSetup
from flask import Flask, request
from flaskext.babel import Babel, get_locale
from stutuz.extensions import genshi, db
from stutuz.converters import converters
from stutuz.modules import MOUNTS
def create_app(config=None):
app = Flask(__name__)
app.config.from_object('stutuz.configs')
if config is not None:
app.config.from_object(config)
app.config.from_envvar('STUTUZ_CONFIG', silent=True)
handlers = app.config.get('LOGBOOK_HANDLERS')
with NestedSetup(handlers):
for extension in genshi, db:
extension.init_app(app)
babel = Babel(app)
@babel.localeselector
def best_locale():
return request.accept_languages.best_match(
map(str, babel.list_translations()))
@app.context_processor
def locale():
return dict(locale=get_locale())
for middleware in app.config.get('MIDDLEWARES', ()):
app.wsgi_app = middleware(app.wsgi_app)
app.url_map.converters.update(converters)
for url_prefix, module in MOUNTS:
app.register_module(module, url_prefix=url_prefix)
return app
## Instruction:
Allow setting locale with a query parameter
## Code After:
from __future__ import division
from __future__ import absolute_import
from __future__ import with_statement
from __future__ import print_function
from __future__ import unicode_literals
from logbook import NestedSetup
from flask import Flask, request
from flaskext.babel import Babel, get_locale
from stutuz.extensions import genshi, db
from stutuz.converters import converters
from stutuz.modules import MOUNTS
def create_app(config=None):
app = Flask(__name__)
app.config.from_object('stutuz.configs')
if config is not None:
app.config.from_object(config)
app.config.from_envvar('STUTUZ_CONFIG', silent=True)
handlers = app.config.get('LOGBOOK_HANDLERS')
with NestedSetup(handlers):
for extension in genshi, db:
extension.init_app(app)
babel = Babel(app)
@babel.localeselector
def best_locale():
if 'locale' in request.args:
return request.args['locale']
return request.accept_languages.best_match(
map(str, babel.list_translations()))
@app.context_processor
def locale():
return dict(locale=get_locale())
for middleware in app.config.get('MIDDLEWARES', ()):
app.wsgi_app = middleware(app.wsgi_app)
app.url_map.converters.update(converters)
for url_prefix, module in MOUNTS:
app.register_module(module, url_prefix=url_prefix)
return app
|
8bfe6e791228ccbc3143f3a8747c68d2e8b0cbb5 | runtests.py | runtests.py |
from django.conf import settings
from django.core.management import execute_from_command_line
import django
import os
import sys
if not settings.configured:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproj.settings")
django.setup()
module_root = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, module_root)
def runtests():
argv = sys.argv[:1] + ['test', 'testproj'] + sys.argv[1:]
execute_from_command_line(argv)
if __name__ == '__main__':
runtests()
|
from django.conf import settings
from django.core.management import execute_from_command_line
import django
import os
import sys
if not settings.configured:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproj.settings")
if django.VERSION >= (1,7):
django.setup()
module_root = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, module_root)
def runtests():
argv = sys.argv[:1] + ['test', 'testproj'] + sys.argv[1:]
execute_from_command_line(argv)
if __name__ == '__main__':
runtests()
| Fix running tests on lower Django versions | Fix running tests on lower Django versions
| Python | apache-2.0 | AdrianLC/django-parler-rest,edoburu/django-parler-rest |
from django.conf import settings
from django.core.management import execute_from_command_line
import django
import os
import sys
if not settings.configured:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproj.settings")
+ if django.VERSION >= (1,7):
- django.setup()
+ django.setup()
module_root = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, module_root)
def runtests():
argv = sys.argv[:1] + ['test', 'testproj'] + sys.argv[1:]
execute_from_command_line(argv)
if __name__ == '__main__':
runtests()
| Fix running tests on lower Django versions | ## Code Before:
from django.conf import settings
from django.core.management import execute_from_command_line
import django
import os
import sys
if not settings.configured:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproj.settings")
django.setup()
module_root = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, module_root)
def runtests():
argv = sys.argv[:1] + ['test', 'testproj'] + sys.argv[1:]
execute_from_command_line(argv)
if __name__ == '__main__':
runtests()
## Instruction:
Fix running tests on lower Django versions
## Code After:
from django.conf import settings
from django.core.management import execute_from_command_line
import django
import os
import sys
if not settings.configured:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproj.settings")
if django.VERSION >= (1,7):
django.setup()
module_root = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, module_root)
def runtests():
argv = sys.argv[:1] + ['test', 'testproj'] + sys.argv[1:]
execute_from_command_line(argv)
if __name__ == '__main__':
runtests()
|
b6836dd7bccd40eec146bc034cc8ac83b4e7f16a | runtests.py | runtests.py | import sys
import os
from coverage import coverage
from optparse import OptionParser
# This envar must be set before importing NoseTestSuiteRunner,
# silence flake8 E402 ("module level import not at top of file").
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_settings")
from django_nose import NoseTestSuiteRunner # noqa: E402
def run_tests(*test_args):
if not test_args:
test_args = ['tests']
# Run tests
test_runner = NoseTestSuiteRunner(verbosity=1)
c = coverage(source=['edx_shopify'], omit=['*migrations*', '*tests*'],
auto_data=True)
c.start()
num_failures = test_runner.run_tests(test_args)
c.stop()
if num_failures > 0:
sys.exit(num_failures)
if __name__ == '__main__':
parser = OptionParser()
(options, args) = parser.parse_args()
run_tests(*args)
| import sys
import os
from coverage import coverage
from optparse import OptionParser
# This envar must be set before importing NoseTestSuiteRunner,
# silence flake8 E402 ("module level import not at top of file").
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_settings")
from django_nose import NoseTestSuiteRunner # noqa: E402
def run_tests(*test_args):
if not test_args:
test_args = ['tests']
# Add Open edX common and LMS Django apps to PYTHONPATH
sys.path.append(os.path.join(os.path.dirname(__file__),
'edx-platform'))
for directory in ['common', 'lms']:
sys.path.append(os.path.join(os.path.dirname(__file__),
'edx-platform',
directory,
'djangoapps'))
for lib in ['xmodule', 'dogstats', 'capa', 'calc', 'chem']:
sys.path.append(os.path.join(os.path.dirname(__file__),
'edx-platform',
'common',
'lib',
lib))
# Run tests
test_runner = NoseTestSuiteRunner(verbosity=1)
c = coverage(source=['edx_shopify'], omit=['*migrations*', '*tests*'],
auto_data=True)
c.start()
num_failures = test_runner.run_tests(test_args)
c.stop()
if num_failures > 0:
sys.exit(num_failures)
if __name__ == '__main__':
parser = OptionParser()
(options, args) = parser.parse_args()
run_tests(*args)
| Extend sys.path with required paths from edx-platform submodule | Extend sys.path with required paths from edx-platform submodule
| Python | agpl-3.0 | hastexo/edx-shopify,fghaas/edx-shopify | import sys
import os
from coverage import coverage
from optparse import OptionParser
# This envar must be set before importing NoseTestSuiteRunner,
# silence flake8 E402 ("module level import not at top of file").
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_settings")
from django_nose import NoseTestSuiteRunner # noqa: E402
def run_tests(*test_args):
if not test_args:
test_args = ['tests']
+
+ # Add Open edX common and LMS Django apps to PYTHONPATH
+ sys.path.append(os.path.join(os.path.dirname(__file__),
+ 'edx-platform'))
+ for directory in ['common', 'lms']:
+ sys.path.append(os.path.join(os.path.dirname(__file__),
+ 'edx-platform',
+ directory,
+ 'djangoapps'))
+ for lib in ['xmodule', 'dogstats', 'capa', 'calc', 'chem']:
+ sys.path.append(os.path.join(os.path.dirname(__file__),
+ 'edx-platform',
+ 'common',
+ 'lib',
+ lib))
# Run tests
test_runner = NoseTestSuiteRunner(verbosity=1)
c = coverage(source=['edx_shopify'], omit=['*migrations*', '*tests*'],
auto_data=True)
c.start()
num_failures = test_runner.run_tests(test_args)
c.stop()
if num_failures > 0:
sys.exit(num_failures)
if __name__ == '__main__':
parser = OptionParser()
(options, args) = parser.parse_args()
run_tests(*args)
| Extend sys.path with required paths from edx-platform submodule | ## Code Before:
import sys
import os
from coverage import coverage
from optparse import OptionParser
# This envar must be set before importing NoseTestSuiteRunner,
# silence flake8 E402 ("module level import not at top of file").
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_settings")
from django_nose import NoseTestSuiteRunner # noqa: E402
def run_tests(*test_args):
if not test_args:
test_args = ['tests']
# Run tests
test_runner = NoseTestSuiteRunner(verbosity=1)
c = coverage(source=['edx_shopify'], omit=['*migrations*', '*tests*'],
auto_data=True)
c.start()
num_failures = test_runner.run_tests(test_args)
c.stop()
if num_failures > 0:
sys.exit(num_failures)
if __name__ == '__main__':
parser = OptionParser()
(options, args) = parser.parse_args()
run_tests(*args)
## Instruction:
Extend sys.path with required paths from edx-platform submodule
## Code After:
import sys
import os
from coverage import coverage
from optparse import OptionParser
# This envar must be set before importing NoseTestSuiteRunner,
# silence flake8 E402 ("module level import not at top of file").
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_settings")
from django_nose import NoseTestSuiteRunner # noqa: E402
def run_tests(*test_args):
if not test_args:
test_args = ['tests']
# Add Open edX common and LMS Django apps to PYTHONPATH
sys.path.append(os.path.join(os.path.dirname(__file__),
'edx-platform'))
for directory in ['common', 'lms']:
sys.path.append(os.path.join(os.path.dirname(__file__),
'edx-platform',
directory,
'djangoapps'))
for lib in ['xmodule', 'dogstats', 'capa', 'calc', 'chem']:
sys.path.append(os.path.join(os.path.dirname(__file__),
'edx-platform',
'common',
'lib',
lib))
# Run tests
test_runner = NoseTestSuiteRunner(verbosity=1)
c = coverage(source=['edx_shopify'], omit=['*migrations*', '*tests*'],
auto_data=True)
c.start()
num_failures = test_runner.run_tests(test_args)
c.stop()
if num_failures > 0:
sys.exit(num_failures)
if __name__ == '__main__':
parser = OptionParser()
(options, args) = parser.parse_args()
run_tests(*args)
|
bde09206bf308167a11bcb012753d10d845dc810 | test_project/blog/models.py | test_project/blog/models.py | from django.db import models
from django.contrib.auth.models import User
class Entry(models.Model):
content = models.TextField()
author = models.ForeignKey(User)
created = models.DateTimeField()
class Comment(models.Model):
post = models.ForeignKey(Entry, related_name='comments')
content = models.TextField()
author = models.ForeignKey(User)
created = models.DateTimeField()
class Actor(models.Model):
name = models.CharField(max_length=32)
class Movie(models.Model):
name = models.CharField(max_length=32)
actors = models.ManyToManyField(Actor, related_name='movies')
score = models.IntegerField(default=0)
| from django.db import models
from django.contrib.auth.models import User
class Entry(models.Model):
content = models.TextField()
author = models.ForeignKey(User)
created = models.DateTimeField()
class Comment(models.Model):
post = models.ForeignKey(Entry, related_name='comments')
content = models.TextField()
author = models.ForeignKey(User)
created = models.DateTimeField()
class SmartTag(models.Model):
entry = models.ForeignKey(Entry, related_name='smart_tags')
name = models.CharField(max_length=32)
class Actor(models.Model):
name = models.CharField(max_length=32)
class Movie(models.Model):
name = models.CharField(max_length=32)
actors = models.ManyToManyField(Actor, related_name='movies')
score = models.IntegerField(default=0)
| Create SmartTag model to demonstrate multi-word resource names. | Create SmartTag model to demonstrate multi-word resource names.
| Python | bsd-3-clause | juanique/django-chocolate,juanique/django-chocolate,juanique/django-chocolate | from django.db import models
from django.contrib.auth.models import User
class Entry(models.Model):
content = models.TextField()
author = models.ForeignKey(User)
created = models.DateTimeField()
class Comment(models.Model):
post = models.ForeignKey(Entry, related_name='comments')
content = models.TextField()
author = models.ForeignKey(User)
created = models.DateTimeField()
+ class SmartTag(models.Model):
+ entry = models.ForeignKey(Entry, related_name='smart_tags')
+ name = models.CharField(max_length=32)
+
+
class Actor(models.Model):
name = models.CharField(max_length=32)
class Movie(models.Model):
name = models.CharField(max_length=32)
actors = models.ManyToManyField(Actor, related_name='movies')
score = models.IntegerField(default=0)
| Create SmartTag model to demonstrate multi-word resource names. | ## Code Before:
from django.db import models
from django.contrib.auth.models import User
class Entry(models.Model):
content = models.TextField()
author = models.ForeignKey(User)
created = models.DateTimeField()
class Comment(models.Model):
post = models.ForeignKey(Entry, related_name='comments')
content = models.TextField()
author = models.ForeignKey(User)
created = models.DateTimeField()
class Actor(models.Model):
name = models.CharField(max_length=32)
class Movie(models.Model):
name = models.CharField(max_length=32)
actors = models.ManyToManyField(Actor, related_name='movies')
score = models.IntegerField(default=0)
## Instruction:
Create SmartTag model to demonstrate multi-word resource names.
## Code After:
from django.db import models
from django.contrib.auth.models import User
class Entry(models.Model):
content = models.TextField()
author = models.ForeignKey(User)
created = models.DateTimeField()
class Comment(models.Model):
post = models.ForeignKey(Entry, related_name='comments')
content = models.TextField()
author = models.ForeignKey(User)
created = models.DateTimeField()
class SmartTag(models.Model):
entry = models.ForeignKey(Entry, related_name='smart_tags')
name = models.CharField(max_length=32)
class Actor(models.Model):
name = models.CharField(max_length=32)
class Movie(models.Model):
name = models.CharField(max_length=32)
actors = models.ManyToManyField(Actor, related_name='movies')
score = models.IntegerField(default=0)
|
f35163ad752a52983d7d5ff9bfd383e98db06f0b | tests/test_pycookiecheat.py | tests/test_pycookiecheat.py |
from pycookiecheat import chrome_cookies
from uuid import uuid4
import pytest
def test_raises_on_empty():
with pytest.raises(TypeError):
broken = chrome_cookies()
def test_no_cookies():
never_been_here = 'http://{}.com'.format(uuid4())
empty_dict = chrome_cookies(never_been_here)
assert empty_dict == dict()
def test_n8henrie_com():
"""Tests a wordpress cookie that I think should be set. NB: Will fail unless you've visited my site in Chrome."""
cookies = chrome_cookies('http://n8henrie.com')
assert cookies['wordpress_test_cookie'] == 'WP+Cookie+check'
|
from pycookiecheat import chrome_cookies
from uuid import uuid4
import pytest
import os
def test_raises_on_empty():
with pytest.raises(TypeError):
broken = chrome_cookies()
def test_no_cookies():
if os.getenv('TRAVIS', False) == 'true':
never_been_here = 'http://{}.com'.format(uuid4())
empty_dict = chrome_cookies(never_been_here)
assert empty_dict == dict()
else:
assert True
def test_n8henrie_com():
"""Tests a wordpress cookie that I think should be set. NB: Will fail
unless you've visited my site in Chrome."""
if os.getenv('TRAVIS', False) == 'true':
cookies = chrome_cookies('http://n8henrie.com')
assert cookies['wordpress_test_cookie'] == 'WP+Cookie+check'
else:
assert True
| Test for travis-CI and skip tests accordingly. | Test for travis-CI and skip tests accordingly.
| Python | mit | fxxkhand/pycookiecheat,n8henrie/pycookiecheat |
from pycookiecheat import chrome_cookies
from uuid import uuid4
import pytest
+ import os
+
def test_raises_on_empty():
with pytest.raises(TypeError):
broken = chrome_cookies()
+
def test_no_cookies():
+ if os.getenv('TRAVIS', False) == 'true':
- never_been_here = 'http://{}.com'.format(uuid4())
+ never_been_here = 'http://{}.com'.format(uuid4())
- empty_dict = chrome_cookies(never_been_here)
+ empty_dict = chrome_cookies(never_been_here)
- assert empty_dict == dict()
+ assert empty_dict == dict()
+ else:
+ assert True
+
def test_n8henrie_com():
- """Tests a wordpress cookie that I think should be set. NB: Will fail unless you've visited my site in Chrome."""
+ """Tests a wordpress cookie that I think should be set. NB: Will fail
+ unless you've visited my site in Chrome."""
+ if os.getenv('TRAVIS', False) == 'true':
- cookies = chrome_cookies('http://n8henrie.com')
+ cookies = chrome_cookies('http://n8henrie.com')
- assert cookies['wordpress_test_cookie'] == 'WP+Cookie+check'
+ assert cookies['wordpress_test_cookie'] == 'WP+Cookie+check'
+ else:
+ assert True
| Test for travis-CI and skip tests accordingly. | ## Code Before:
from pycookiecheat import chrome_cookies
from uuid import uuid4
import pytest
def test_raises_on_empty():
with pytest.raises(TypeError):
broken = chrome_cookies()
def test_no_cookies():
never_been_here = 'http://{}.com'.format(uuid4())
empty_dict = chrome_cookies(never_been_here)
assert empty_dict == dict()
def test_n8henrie_com():
"""Tests a wordpress cookie that I think should be set. NB: Will fail unless you've visited my site in Chrome."""
cookies = chrome_cookies('http://n8henrie.com')
assert cookies['wordpress_test_cookie'] == 'WP+Cookie+check'
## Instruction:
Test for travis-CI and skip tests accordingly.
## Code After:
from pycookiecheat import chrome_cookies
from uuid import uuid4
import pytest
import os
def test_raises_on_empty():
with pytest.raises(TypeError):
broken = chrome_cookies()
def test_no_cookies():
if os.getenv('TRAVIS', False) == 'true':
never_been_here = 'http://{}.com'.format(uuid4())
empty_dict = chrome_cookies(never_been_here)
assert empty_dict == dict()
else:
assert True
def test_n8henrie_com():
"""Tests a wordpress cookie that I think should be set. NB: Will fail
unless you've visited my site in Chrome."""
if os.getenv('TRAVIS', False) == 'true':
cookies = chrome_cookies('http://n8henrie.com')
assert cookies['wordpress_test_cookie'] == 'WP+Cookie+check'
else:
assert True
|
5b282d9322a676b4185fcd253f338a342ec5e5ce | .config/i3/py3status/playerctlbar.py | .config/i3/py3status/playerctlbar.py |
import subprocess
def run(*cmdlist):
return subprocess.run(cmdlist, stdout=subprocess.PIPE).stdout.decode()
def player_args(players):
if not players:
return 'playerctl',
else:
return 'playerctl', '-p', players
def get_status(players):
status = run(*player_args(players), 'status')[:-1]
if status in ('Playing', 'Paused'):
return status
return ''
def get_info(players, fmt):
args = 'metadata', '--format', f'{fmt}'
return run(*player_args(players), *args).strip()
class Py3status:
players = ''
format = '{{ artist }} / {{ title }}'
def spotbar(self):
text_format = "[[ {info} ]]|[ {status} ]"
params = {'status': get_status(self.players)}
if params['status'] == 'Playing':
params['info'] = get_info(self.players, self.format)
if params['info'] == '/ -':
params['info'] = None
return {
'full_text': self.py3.safe_format(text_format, params),
'cached_until': self.py3.time_in(seconds=1)
}
def on_click(self, event):
if event['button'] == 1:
run('playerctl', 'play-pause')
if __name__ == '__main__':
from py3status.module_test import module_test
module_test(Py3status)
|
import subprocess
def run(*cmdlist):
return subprocess.run(
cmdlist,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL).stdout.decode()
def player_args(players):
if not players:
return 'playerctl',
else:
return 'playerctl', '-p', players
def get_status(players):
status = run(*player_args(players), 'status')[:-1]
if status in ('Playing', 'Paused'):
return status
return ''
def get_info(players, fmt):
args = 'metadata', '--format', f'{fmt}'
return run(*player_args(players), *args).strip()
class Py3status:
players = ''
format = '{{ artist }} / {{ title }}'
def spotbar(self):
text_format = "[[ {info} ]]|[ {status} ]"
params = {'status': get_status(self.players)}
if params['status'] == 'Playing':
params['info'] = get_info(self.players, self.format)
if params['info'] == '/ -':
params['info'] = None
return {
'full_text': self.py3.safe_format(text_format, params),
'cached_until': self.py3.time_in(seconds=1)
}
def on_click(self, event):
if event['button'] == 1:
run('playerctl', 'play-pause')
if __name__ == '__main__':
from py3status.module_test import module_test
module_test(Py3status)
| Fix stderr from playerctl bar | Fix stderr from playerctl bar
| Python | unlicense | louisswarren/dotfiles,louisswarren/dotfiles |
import subprocess
def run(*cmdlist):
- return subprocess.run(cmdlist, stdout=subprocess.PIPE).stdout.decode()
+ return subprocess.run(
+ cmdlist,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL).stdout.decode()
def player_args(players):
if not players:
return 'playerctl',
else:
return 'playerctl', '-p', players
def get_status(players):
status = run(*player_args(players), 'status')[:-1]
if status in ('Playing', 'Paused'):
return status
return ''
def get_info(players, fmt):
args = 'metadata', '--format', f'{fmt}'
return run(*player_args(players), *args).strip()
class Py3status:
players = ''
format = '{{ artist }} / {{ title }}'
def spotbar(self):
text_format = "[[ {info} ]]|[ {status} ]"
params = {'status': get_status(self.players)}
if params['status'] == 'Playing':
params['info'] = get_info(self.players, self.format)
if params['info'] == '/ -':
params['info'] = None
return {
'full_text': self.py3.safe_format(text_format, params),
'cached_until': self.py3.time_in(seconds=1)
}
def on_click(self, event):
if event['button'] == 1:
run('playerctl', 'play-pause')
if __name__ == '__main__':
from py3status.module_test import module_test
module_test(Py3status)
| Fix stderr from playerctl bar | ## Code Before:
import subprocess
def run(*cmdlist):
return subprocess.run(cmdlist, stdout=subprocess.PIPE).stdout.decode()
def player_args(players):
if not players:
return 'playerctl',
else:
return 'playerctl', '-p', players
def get_status(players):
status = run(*player_args(players), 'status')[:-1]
if status in ('Playing', 'Paused'):
return status
return ''
def get_info(players, fmt):
args = 'metadata', '--format', f'{fmt}'
return run(*player_args(players), *args).strip()
class Py3status:
players = ''
format = '{{ artist }} / {{ title }}'
def spotbar(self):
text_format = "[[ {info} ]]|[ {status} ]"
params = {'status': get_status(self.players)}
if params['status'] == 'Playing':
params['info'] = get_info(self.players, self.format)
if params['info'] == '/ -':
params['info'] = None
return {
'full_text': self.py3.safe_format(text_format, params),
'cached_until': self.py3.time_in(seconds=1)
}
def on_click(self, event):
if event['button'] == 1:
run('playerctl', 'play-pause')
if __name__ == '__main__':
from py3status.module_test import module_test
module_test(Py3status)
## Instruction:
Fix stderr from playerctl bar
## Code After:
import subprocess
def run(*cmdlist):
return subprocess.run(
cmdlist,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL).stdout.decode()
def player_args(players):
if not players:
return 'playerctl',
else:
return 'playerctl', '-p', players
def get_status(players):
status = run(*player_args(players), 'status')[:-1]
if status in ('Playing', 'Paused'):
return status
return ''
def get_info(players, fmt):
args = 'metadata', '--format', f'{fmt}'
return run(*player_args(players), *args).strip()
class Py3status:
players = ''
format = '{{ artist }} / {{ title }}'
def spotbar(self):
text_format = "[[ {info} ]]|[ {status} ]"
params = {'status': get_status(self.players)}
if params['status'] == 'Playing':
params['info'] = get_info(self.players, self.format)
if params['info'] == '/ -':
params['info'] = None
return {
'full_text': self.py3.safe_format(text_format, params),
'cached_until': self.py3.time_in(seconds=1)
}
def on_click(self, event):
if event['button'] == 1:
run('playerctl', 'play-pause')
if __name__ == '__main__':
from py3status.module_test import module_test
module_test(Py3status)
|
7527ce1b48f769d33eb5ede3d54413e51eb2ac12 | senkumba/models.py | senkumba/models.py | from django.contrib.auth.models import User
def user_new_str(self):
return self.username if self.get_full_name() == "" else self.get_full_name()
# Replace the __str__ method in the User class with our new implementation
User.__str__ = user_new_str | from django.contrib import admin
from django.contrib.auth.models import User
def user_new_str(self):
return self.username if self.get_full_name() == "" else self.get_full_name()
# Replace the __str__ method in the User class with our new implementation
User.__str__ = user_new_str
admin.site.site_header = 'SENKUMBA'
admin.site.site_title = 'SENKUMBA'
admin.site.index_title = 'SENKUMBA' | Change titles for the site | Change titles for the site
| Python | mit | lubegamark/senkumba | + from django.contrib import admin
from django.contrib.auth.models import User
def user_new_str(self):
return self.username if self.get_full_name() == "" else self.get_full_name()
# Replace the __str__ method in the User class with our new implementation
User.__str__ = user_new_str
+
+ admin.site.site_header = 'SENKUMBA'
+ admin.site.site_title = 'SENKUMBA'
+ admin.site.index_title = 'SENKUMBA' | Change titles for the site | ## Code Before:
from django.contrib.auth.models import User
def user_new_str(self):
return self.username if self.get_full_name() == "" else self.get_full_name()
# Replace the __str__ method in the User class with our new implementation
User.__str__ = user_new_str
## Instruction:
Change titles for the site
## Code After:
from django.contrib import admin
from django.contrib.auth.models import User
def user_new_str(self):
return self.username if self.get_full_name() == "" else self.get_full_name()
# Replace the __str__ method in the User class with our new implementation
User.__str__ = user_new_str
admin.site.site_header = 'SENKUMBA'
admin.site.site_title = 'SENKUMBA'
admin.site.index_title = 'SENKUMBA' |
d3a203725d13a7abef091f0070f90826d3225dbc | settings_travis.py | settings_travis.py | import ssl
LDAP_SERVER = 'ldap.rserver.de'
LDAP_PORT = 3389
LDAP_SSL_PORT = 6636
LDAP_REQUIRE_CERT = ssl.CERT_NONE
| import ssl
LDAP_SERVER = 'ldap.rserver.de'
LDAP_PORT = 3389
LDAP_SSL_PORT = 6636
LDAP_REQUIRE_CERT = ssl.CERT_NONE
LDAP_TLS_VERSION = ssl.PROTOCOL_TLSv1
| Fix travis unit test for python 3.3 | Fix travis unit test for python 3.3
| Python | bsd-2-clause | rroemhild/flask-ldapconn | import ssl
LDAP_SERVER = 'ldap.rserver.de'
LDAP_PORT = 3389
LDAP_SSL_PORT = 6636
LDAP_REQUIRE_CERT = ssl.CERT_NONE
+ LDAP_TLS_VERSION = ssl.PROTOCOL_TLSv1
| Fix travis unit test for python 3.3 | ## Code Before:
import ssl
LDAP_SERVER = 'ldap.rserver.de'
LDAP_PORT = 3389
LDAP_SSL_PORT = 6636
LDAP_REQUIRE_CERT = ssl.CERT_NONE
## Instruction:
Fix travis unit test for python 3.3
## Code After:
import ssl
LDAP_SERVER = 'ldap.rserver.de'
LDAP_PORT = 3389
LDAP_SSL_PORT = 6636
LDAP_REQUIRE_CERT = ssl.CERT_NONE
LDAP_TLS_VERSION = ssl.PROTOCOL_TLSv1
|
c84e22824cd5546406656ecc06a7dcd37a013954 | shopit_app/urls.py | shopit_app/urls.py | from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
import authentication_app.views
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'gettingstarted.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^$', authentication_app.views.index, name='index'),
url(r'^db', authentication_app.views.db, name='db'),
url(r'^admin/', include(admin.site.urls)),
)
| from rest_frmaework_nested import routers
from authentication_app.views import AccountViewSet
router = routers.SimpleRouter()
router.register(r'accounts', AccountViewSet)
urlpatterns = patterns('',
# APIendpoints
url(r'^api/v1/', include(router.urls)),
url('^.*$', IndexView.as_view(), name='index'),
)
| Add the API endpoint url for the account view set. | Add the API endpoint url for the account view set.
| Python | mit | mvpgomes/shopit-app,mvpgomes/shopit-app,mvpgomes/shopit-app,mvpgomes/shopit-app | - from django.conf.urls import patterns, include, url
+ from rest_frmaework_nested import routers
+ from authentication_app.views import AccountViewSet
+ router = routers.SimpleRouter()
+ router.register(r'accounts', AccountViewSet)
- from django.contrib import admin
- admin.autodiscover()
-
- import authentication_app.views
urlpatterns = patterns('',
+ # APIendpoints
- # Examples:
- # url(r'^$', 'gettingstarted.views.home', name='home'),
- # url(r'^blog/', include('blog.urls')),
-
- url(r'^$', authentication_app.views.index, name='index'),
- url(r'^db', authentication_app.views.db, name='db'),
- url(r'^admin/', include(admin.site.urls)),
+ url(r'^api/v1/', include(router.urls)),
-
+ url('^.*$', IndexView.as_view(), name='index'),
)
| Add the API endpoint url for the account view set. | ## Code Before:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
import authentication_app.views
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'gettingstarted.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^$', authentication_app.views.index, name='index'),
url(r'^db', authentication_app.views.db, name='db'),
url(r'^admin/', include(admin.site.urls)),
)
## Instruction:
Add the API endpoint url for the account view set.
## Code After:
from rest_frmaework_nested import routers
from authentication_app.views import AccountViewSet
router = routers.SimpleRouter()
router.register(r'accounts', AccountViewSet)
urlpatterns = patterns('',
# APIendpoints
url(r'^api/v1/', include(router.urls)),
url('^.*$', IndexView.as_view(), name='index'),
)
|
a57f7c43bc7749de5acd42b6db95d77074308cef | scaper/__init__.py | scaper/__init__.py | """Top-level module for scaper"""
from .core import *
__version__ = '0.1.0'
| """Top-level module for scaper"""
from .core import *
import jams
from pkg_resources import resource_filename
__version__ = '0.1.0'
# Add sound_event namesapce
namespace_file = resource_filename(__name__, 'namespaces/sound_event.json')
jams.schema.add_namespace(namespace_file)
| Add sound_event namespace to jams during init | Add sound_event namespace to jams during init
| Python | bsd-3-clause | justinsalamon/scaper | """Top-level module for scaper"""
from .core import *
+ import jams
+ from pkg_resources import resource_filename
__version__ = '0.1.0'
+ # Add sound_event namesapce
+ namespace_file = resource_filename(__name__, 'namespaces/sound_event.json')
+ jams.schema.add_namespace(namespace_file)
- | Add sound_event namespace to jams during init | ## Code Before:
"""Top-level module for scaper"""
from .core import *
__version__ = '0.1.0'
## Instruction:
Add sound_event namespace to jams during init
## Code After:
"""Top-level module for scaper"""
from .core import *
import jams
from pkg_resources import resource_filename
__version__ = '0.1.0'
# Add sound_event namesapce
namespace_file = resource_filename(__name__, 'namespaces/sound_event.json')
jams.schema.add_namespace(namespace_file)
|
b62c8c905cdd332a0073ce462be3e5c5b17b282d | api/webview/views.py | api/webview/views.py | from rest_framework import generics
from rest_framework import permissions
from rest_framework.response import Response
from rest_framework.decorators import api_view
from django.views.decorators.clickjacking import xframe_options_exempt
from api.webview.models import Document
from api.webview.serializers import DocumentSerializer
class DocumentList(generics.ListCreateAPIView):
"""
List all documents in the SHARE API
"""
serializer_class = DocumentSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
def perform_create(self, serializer):
serializer.save(source=self.request.user)
def get_queryset(self):
""" Return all documents
"""
return Document.objects.all()
class DocumentsFromSource(generics.ListCreateAPIView):
"""
List all documents from a particular source
"""
serializer_class = DocumentSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
def perform_create(self, serializer):
serializer.save(source=self.request.user)
def get_queryset(self):
""" Return queryset based on source
"""
return Document.objects.filter(source=self.kwargs['source'])
@api_view(['GET'])
@xframe_options_exempt
def document_detail(request, source, docID):
"""
Retrieve one particular document.
"""
try:
all_sources = Document.objects.filter(source=source)
document = all_sources.get(docID=docID)
except Document.DoesNotExist:
return Response(status=404)
serializer = DocumentSerializer(document)
return Response(serializer.data)
| from rest_framework import generics
from rest_framework import permissions
from rest_framework.response import Response
from rest_framework.decorators import api_view
from django.views.decorators.clickjacking import xframe_options_exempt
from api.webview.models import Document
from api.webview.serializers import DocumentSerializer
class DocumentList(generics.ListAPIView):
"""
List all documents in the SHARE API
"""
serializer_class = DocumentSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
def perform_create(self, serializer):
serializer.save(source=self.request.user)
def get_queryset(self):
""" Return all documents
"""
return Document.objects.all()
class DocumentsFromSource(generics.ListAPIView):
"""
List all documents from a particular source
"""
serializer_class = DocumentSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
def perform_create(self, serializer):
serializer.save(source=self.request.user)
def get_queryset(self):
""" Return queryset based on source
"""
return Document.objects.filter(source=self.kwargs['source'])
@api_view(['GET'])
@xframe_options_exempt
def document_detail(request, source, docID):
"""
Retrieve one particular document.
"""
try:
all_sources = Document.objects.filter(source=source)
document = all_sources.get(docID=docID)
except Document.DoesNotExist:
return Response(status=404)
serializer = DocumentSerializer(document)
return Response(serializer.data)
| Make the view List only remove Create | Make the view List only remove Create
| Python | apache-2.0 | erinspace/scrapi,CenterForOpenScience/scrapi,felliott/scrapi,fabianvf/scrapi,erinspace/scrapi,CenterForOpenScience/scrapi,fabianvf/scrapi,felliott/scrapi | from rest_framework import generics
from rest_framework import permissions
from rest_framework.response import Response
from rest_framework.decorators import api_view
from django.views.decorators.clickjacking import xframe_options_exempt
from api.webview.models import Document
from api.webview.serializers import DocumentSerializer
- class DocumentList(generics.ListCreateAPIView):
+ class DocumentList(generics.ListAPIView):
"""
List all documents in the SHARE API
"""
serializer_class = DocumentSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
def perform_create(self, serializer):
serializer.save(source=self.request.user)
def get_queryset(self):
""" Return all documents
"""
return Document.objects.all()
- class DocumentsFromSource(generics.ListCreateAPIView):
+ class DocumentsFromSource(generics.ListAPIView):
"""
List all documents from a particular source
"""
serializer_class = DocumentSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
def perform_create(self, serializer):
serializer.save(source=self.request.user)
def get_queryset(self):
""" Return queryset based on source
"""
return Document.objects.filter(source=self.kwargs['source'])
@api_view(['GET'])
@xframe_options_exempt
def document_detail(request, source, docID):
"""
Retrieve one particular document.
"""
try:
all_sources = Document.objects.filter(source=source)
document = all_sources.get(docID=docID)
except Document.DoesNotExist:
return Response(status=404)
serializer = DocumentSerializer(document)
return Response(serializer.data)
| Make the view List only remove Create | ## Code Before:
from rest_framework import generics
from rest_framework import permissions
from rest_framework.response import Response
from rest_framework.decorators import api_view
from django.views.decorators.clickjacking import xframe_options_exempt
from api.webview.models import Document
from api.webview.serializers import DocumentSerializer
class DocumentList(generics.ListCreateAPIView):
"""
List all documents in the SHARE API
"""
serializer_class = DocumentSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
def perform_create(self, serializer):
serializer.save(source=self.request.user)
def get_queryset(self):
""" Return all documents
"""
return Document.objects.all()
class DocumentsFromSource(generics.ListCreateAPIView):
"""
List all documents from a particular source
"""
serializer_class = DocumentSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
def perform_create(self, serializer):
serializer.save(source=self.request.user)
def get_queryset(self):
""" Return queryset based on source
"""
return Document.objects.filter(source=self.kwargs['source'])
@api_view(['GET'])
@xframe_options_exempt
def document_detail(request, source, docID):
"""
Retrieve one particular document.
"""
try:
all_sources = Document.objects.filter(source=source)
document = all_sources.get(docID=docID)
except Document.DoesNotExist:
return Response(status=404)
serializer = DocumentSerializer(document)
return Response(serializer.data)
## Instruction:
Make the view List only remove Create
## Code After:
from rest_framework import generics
from rest_framework import permissions
from rest_framework.response import Response
from rest_framework.decorators import api_view
from django.views.decorators.clickjacking import xframe_options_exempt
from api.webview.models import Document
from api.webview.serializers import DocumentSerializer
class DocumentList(generics.ListAPIView):
"""
List all documents in the SHARE API
"""
serializer_class = DocumentSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
def perform_create(self, serializer):
serializer.save(source=self.request.user)
def get_queryset(self):
""" Return all documents
"""
return Document.objects.all()
class DocumentsFromSource(generics.ListAPIView):
"""
List all documents from a particular source
"""
serializer_class = DocumentSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
def perform_create(self, serializer):
serializer.save(source=self.request.user)
def get_queryset(self):
""" Return queryset based on source
"""
return Document.objects.filter(source=self.kwargs['source'])
@api_view(['GET'])
@xframe_options_exempt
def document_detail(request, source, docID):
"""
Retrieve one particular document.
"""
try:
all_sources = Document.objects.filter(source=source)
document = all_sources.get(docID=docID)
except Document.DoesNotExist:
return Response(status=404)
serializer = DocumentSerializer(document)
return Response(serializer.data)
|
067b557258a85945635a880ced65454cfa2b61af | supermega/tests/test_session.py | supermega/tests/test_session.py | import unittest
import hashlib
from .. import Session
from .. import models
class TestSession(unittest.TestCase):
def setUp(self):
self.sess = Session()
def test_public_file_download(self):
url = 'https://mega.co.nz/#!2ctGgQAI!AkJMowjRiXVcSrRLn3d-e1vl47ZxZEK0CbrHGIKFY-E'
sha256 = '9431103cb989f2913cbc503767015ca22c0ae40942932186c59ffe6d6a69830d'
hash = hashlib.sha256()
def verify_hash(file, chunks):
for chunk in chunks:
hash.update(chunk)
self.assertEqual(hash.hexdigest(), sha256)
self.sess.download(verify_hash, url)
def test_ephemeral_account(self):
sess = self.sess
user = models.User(sess)
user.ephemeral()
sess.init_datastore() | import unittest
import hashlib
from .. import Session
from .. import models
class TestSession(unittest.TestCase):
def setUp(self):
self.sess = Session()
def test_public_file_download(self):
url = 'https://mega.co.nz/#!2ctGgQAI!AkJMowjRiXVcSrRLn3d-e1vl47ZxZEK0CbrHGIKFY-E'
sha256 = '9431103cb989f2913cbc503767015ca22c0ae40942932186c59ffe6d6a69830d'
hash = hashlib.sha256()
def verify_hash(file, chunks):
for chunk in chunks:
hash.update(chunk)
self.assertEqual(hash.hexdigest(), sha256)
self.sess.download(verify_hash, url)
def test_ephemeral_account(self):
sess = self.sess
user = models.User(sess)
user.ephemeral()
sess.init_datastore()
def test_key_derivation(self):
self.assertEqual(models.User.derive_key("password"), 'd\x039r^n\xbd\x13\xa2_\x00R\x12\x9f|\xb1')
| Add test for key derivation | Add test for key derivation
| Python | bsd-3-clause | lmb/Supermega | import unittest
import hashlib
from .. import Session
from .. import models
class TestSession(unittest.TestCase):
def setUp(self):
self.sess = Session()
def test_public_file_download(self):
url = 'https://mega.co.nz/#!2ctGgQAI!AkJMowjRiXVcSrRLn3d-e1vl47ZxZEK0CbrHGIKFY-E'
sha256 = '9431103cb989f2913cbc503767015ca22c0ae40942932186c59ffe6d6a69830d'
hash = hashlib.sha256()
def verify_hash(file, chunks):
for chunk in chunks:
hash.update(chunk)
self.assertEqual(hash.hexdigest(), sha256)
self.sess.download(verify_hash, url)
def test_ephemeral_account(self):
sess = self.sess
user = models.User(sess)
user.ephemeral()
sess.init_datastore()
+
+ def test_key_derivation(self):
+ self.assertEqual(models.User.derive_key("password"), 'd\x039r^n\xbd\x13\xa2_\x00R\x12\x9f|\xb1')
+ | Add test for key derivation | ## Code Before:
import unittest
import hashlib
from .. import Session
from .. import models
class TestSession(unittest.TestCase):
def setUp(self):
self.sess = Session()
def test_public_file_download(self):
url = 'https://mega.co.nz/#!2ctGgQAI!AkJMowjRiXVcSrRLn3d-e1vl47ZxZEK0CbrHGIKFY-E'
sha256 = '9431103cb989f2913cbc503767015ca22c0ae40942932186c59ffe6d6a69830d'
hash = hashlib.sha256()
def verify_hash(file, chunks):
for chunk in chunks:
hash.update(chunk)
self.assertEqual(hash.hexdigest(), sha256)
self.sess.download(verify_hash, url)
def test_ephemeral_account(self):
sess = self.sess
user = models.User(sess)
user.ephemeral()
sess.init_datastore()
## Instruction:
Add test for key derivation
## Code After:
import unittest
import hashlib
from .. import Session
from .. import models
class TestSession(unittest.TestCase):
def setUp(self):
self.sess = Session()
def test_public_file_download(self):
url = 'https://mega.co.nz/#!2ctGgQAI!AkJMowjRiXVcSrRLn3d-e1vl47ZxZEK0CbrHGIKFY-E'
sha256 = '9431103cb989f2913cbc503767015ca22c0ae40942932186c59ffe6d6a69830d'
hash = hashlib.sha256()
def verify_hash(file, chunks):
for chunk in chunks:
hash.update(chunk)
self.assertEqual(hash.hexdigest(), sha256)
self.sess.download(verify_hash, url)
def test_ephemeral_account(self):
sess = self.sess
user = models.User(sess)
user.ephemeral()
sess.init_datastore()
def test_key_derivation(self):
self.assertEqual(models.User.derive_key("password"), 'd\x039r^n\xbd\x13\xa2_\x00R\x12\x9f|\xb1')
|
bbfe056602075a46b231dc28ddcada7f525ce927 | conftest.py | conftest.py | import pytest
import django_webtest
from django.core.urlresolvers import reverse
from ideasbox.tests.factories import UserFactory
@pytest.fixture()
def user():
return UserFactory(short_name="Hello", password='password')
@pytest.fixture()
def staffuser():
return UserFactory(short_name="Hello", password='password', is_staff=True)
@pytest.fixture()
def app(request):
wtm = django_webtest.WebTestMixin()
wtm._patch_settings()
request.addfinalizer(wtm._unpatch_settings)
return django_webtest.DjangoTestApp()
@pytest.fixture()
def loggedapp(app, user):
"""Return an app with an already logged in user."""
form = app.get(reverse('login')).forms['login']
form['username'] = user.serial
form['password'] = 'password'
form.submit().follow()
setattr(app, 'user', user) # for later use, if needed
return app
@pytest.fixture()
def staffapp(app, staffuser):
"""Return an app with an already logged in staff user."""
form = app.get(reverse('login')).forms['login']
form['username'] = staffuser.serial
form['password'] = 'password'
form.submit().follow()
setattr(app, 'user', user) # for later use, if needed
return app
| import pytest
import django_webtest
from django.core.urlresolvers import reverse
from ideasbox.tests.factories import UserFactory
@pytest.fixture()
def user():
return UserFactory(short_name="Hello", password='password')
@pytest.fixture()
def staffuser():
return UserFactory(short_name="Hello", password='password', is_staff=True)
@pytest.yield_fixture()
def app(request):
wtm = django_webtest.WebTestMixin()
wtm._patch_settings()
yield django_webtest.DjangoTestApp()
wtm._unpatch_settings()
@pytest.fixture()
def loggedapp(app, user):
"""Return an app with an already logged in user."""
form = app.get(reverse('login')).forms['login']
form['username'] = user.serial
form['password'] = 'password'
form.submit().follow()
setattr(app, 'user', user) # for later use, if needed
return app
@pytest.fixture()
def staffapp(app, staffuser):
"""Return an app with an already logged in staff user."""
form = app.get(reverse('login')).forms['login']
form['username'] = staffuser.serial
form['password'] = 'password'
form.submit().follow()
setattr(app, 'user', user) # for later use, if needed
return app
| Use yield_fixture for app fixture | Use yield_fixture for app fixture
| Python | agpl-3.0 | ideascube/ideascube,Lcaracol/ideasbox.lan,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,Lcaracol/ideasbox.lan,Lcaracol/ideasbox.lan | import pytest
import django_webtest
from django.core.urlresolvers import reverse
from ideasbox.tests.factories import UserFactory
@pytest.fixture()
def user():
return UserFactory(short_name="Hello", password='password')
@pytest.fixture()
def staffuser():
return UserFactory(short_name="Hello", password='password', is_staff=True)
- @pytest.fixture()
+ @pytest.yield_fixture()
def app(request):
wtm = django_webtest.WebTestMixin()
wtm._patch_settings()
- request.addfinalizer(wtm._unpatch_settings)
- return django_webtest.DjangoTestApp()
+ yield django_webtest.DjangoTestApp()
+ wtm._unpatch_settings()
@pytest.fixture()
def loggedapp(app, user):
"""Return an app with an already logged in user."""
form = app.get(reverse('login')).forms['login']
form['username'] = user.serial
form['password'] = 'password'
form.submit().follow()
setattr(app, 'user', user) # for later use, if needed
return app
@pytest.fixture()
def staffapp(app, staffuser):
"""Return an app with an already logged in staff user."""
form = app.get(reverse('login')).forms['login']
form['username'] = staffuser.serial
form['password'] = 'password'
form.submit().follow()
setattr(app, 'user', user) # for later use, if needed
return app
| Use yield_fixture for app fixture | ## Code Before:
import pytest
import django_webtest
from django.core.urlresolvers import reverse
from ideasbox.tests.factories import UserFactory
@pytest.fixture()
def user():
return UserFactory(short_name="Hello", password='password')
@pytest.fixture()
def staffuser():
return UserFactory(short_name="Hello", password='password', is_staff=True)
@pytest.fixture()
def app(request):
wtm = django_webtest.WebTestMixin()
wtm._patch_settings()
request.addfinalizer(wtm._unpatch_settings)
return django_webtest.DjangoTestApp()
@pytest.fixture()
def loggedapp(app, user):
"""Return an app with an already logged in user."""
form = app.get(reverse('login')).forms['login']
form['username'] = user.serial
form['password'] = 'password'
form.submit().follow()
setattr(app, 'user', user) # for later use, if needed
return app
@pytest.fixture()
def staffapp(app, staffuser):
"""Return an app with an already logged in staff user."""
form = app.get(reverse('login')).forms['login']
form['username'] = staffuser.serial
form['password'] = 'password'
form.submit().follow()
setattr(app, 'user', user) # for later use, if needed
return app
## Instruction:
Use yield_fixture for app fixture
## Code After:
import pytest
import django_webtest
from django.core.urlresolvers import reverse
from ideasbox.tests.factories import UserFactory
@pytest.fixture()
def user():
return UserFactory(short_name="Hello", password='password')
@pytest.fixture()
def staffuser():
return UserFactory(short_name="Hello", password='password', is_staff=True)
@pytest.yield_fixture()
def app(request):
wtm = django_webtest.WebTestMixin()
wtm._patch_settings()
yield django_webtest.DjangoTestApp()
wtm._unpatch_settings()
@pytest.fixture()
def loggedapp(app, user):
"""Return an app with an already logged in user."""
form = app.get(reverse('login')).forms['login']
form['username'] = user.serial
form['password'] = 'password'
form.submit().follow()
setattr(app, 'user', user) # for later use, if needed
return app
@pytest.fixture()
def staffapp(app, staffuser):
"""Return an app with an already logged in staff user."""
form = app.get(reverse('login')).forms['login']
form['username'] = staffuser.serial
form['password'] = 'password'
form.submit().follow()
setattr(app, 'user', user) # for later use, if needed
return app
|
9e7aed847c2d5fcd6e00bc787d8b3558b590f605 | api/logs/urls.py | api/logs/urls.py | from django.conf.urls import url
from api.logs import views
urlpatterns = [
url(r'^(?P<log_id>\w+)/$', views.NodeLogDetail.as_view(), name=views.NodeLogDetail.view_name),
url(r'^(?P<log_id>\w+)/nodes/$', views.LogNodeList.as_view(), name=views.LogNodeList.view_name),
]
| from django.conf.urls import url
from api.logs import views
urlpatterns = [
url(r'^(?P<log_id>\w+)/$', views.NodeLogDetail.as_view(), name=views.NodeLogDetail.view_name),
url(r'^(?P<log_id>\w+)/nodes/$', views.LogNodeList.as_view(), name=views.LogNodeList.view_name),
url(r'^(?P<log_id>\w+)/added_contributors/$', views.NodeLogAddedContributors.as_view(), name=views.NodeLogAddedContributors.view_name),
]
| Add /v2/logs/log_id/added_contributors/ to list of URL's. | Add /v2/logs/log_id/added_contributors/ to list of URL's.
| Python | apache-2.0 | abought/osf.io,mfraezz/osf.io,TomHeatwole/osf.io,chennan47/osf.io,RomanZWang/osf.io,alexschiller/osf.io,billyhunt/osf.io,crcresearch/osf.io,saradbowman/osf.io,acshi/osf.io,jnayak1/osf.io,RomanZWang/osf.io,emetsger/osf.io,KAsante95/osf.io,zachjanicki/osf.io,mattclark/osf.io,RomanZWang/osf.io,emetsger/osf.io,monikagrabowska/osf.io,laurenrevere/osf.io,TomBaxter/osf.io,samchrisinger/osf.io,emetsger/osf.io,billyhunt/osf.io,RomanZWang/osf.io,GageGaskins/osf.io,brandonPurvis/osf.io,zachjanicki/osf.io,kwierman/osf.io,samchrisinger/osf.io,TomBaxter/osf.io,aaxelb/osf.io,Nesiehr/osf.io,asanfilippo7/osf.io,SSJohns/osf.io,kch8qx/osf.io,asanfilippo7/osf.io,rdhyee/osf.io,cslzchen/osf.io,crcresearch/osf.io,HalcyonChimera/osf.io,mluo613/osf.io,hmoco/osf.io,erinspace/osf.io,doublebits/osf.io,felliott/osf.io,mfraezz/osf.io,cslzchen/osf.io,monikagrabowska/osf.io,zamattiac/osf.io,CenterForOpenScience/osf.io,abought/osf.io,leb2dg/osf.io,adlius/osf.io,Johnetordoff/osf.io,Nesiehr/osf.io,binoculars/osf.io,GageGaskins/osf.io,hmoco/osf.io,GageGaskins/osf.io,kwierman/osf.io,hmoco/osf.io,caneruguz/osf.io,SSJohns/osf.io,billyhunt/osf.io,DanielSBrown/osf.io,baylee-d/osf.io,mluo613/osf.io,rdhyee/osf.io,laurenrevere/osf.io,samchrisinger/osf.io,chennan47/osf.io,icereval/osf.io,rdhyee/osf.io,doublebits/osf.io,adlius/osf.io,caneruguz/osf.io,amyshi188/osf.io,jnayak1/osf.io,mluke93/osf.io,erinspace/osf.io,monikagrabowska/osf.io,KAsante95/osf.io,laurenrevere/osf.io,acshi/osf.io,Johnetordoff/osf.io,acshi/osf.io,crcresearch/osf.io,cwisecarver/osf.io,binoculars/osf.io,brianjgeiger/osf.io,sloria/osf.io,zachjanicki/osf.io,baylee-d/osf.io,KAsante95/osf.io,caseyrollins/osf.io,doublebits/osf.io,brandonPurvis/osf.io,chrisseto/osf.io,mattclark/osf.io,pattisdr/osf.io,baylee-d/osf.io,KAsante95/osf.io,brandonPurvis/osf.io,icereval/osf.io,wearpants/osf.io,aaxelb/osf.io,caseyrollins/osf.io,erinspace/osf.io,alexschiller/osf.io,brandonPurvis/osf.io,mluke93/osf.io,leb2dg/osf.io,Nesiehr/osf.io,amyshi188/osf.io,caneruguz/osf.io,Johnetordoff/osf.io,cslzchen/osf.io,sloria/osf.io,kwierman/osf.io,samchrisinger/osf.io,doublebits/osf.io,SSJohns/osf.io,Johnetordoff/osf.io,mluke93/osf.io,mfraezz/osf.io,saradbowman/osf.io,kch8qx/osf.io,KAsante95/osf.io,cwisecarver/osf.io,leb2dg/osf.io,TomHeatwole/osf.io,alexschiller/osf.io,chrisseto/osf.io,acshi/osf.io,amyshi188/osf.io,chrisseto/osf.io,DanielSBrown/osf.io,mattclark/osf.io,cslzchen/osf.io,Nesiehr/osf.io,wearpants/osf.io,CenterForOpenScience/osf.io,cwisecarver/osf.io,SSJohns/osf.io,DanielSBrown/osf.io,HalcyonChimera/osf.io,HalcyonChimera/osf.io,GageGaskins/osf.io,CenterForOpenScience/osf.io,mluke93/osf.io,acshi/osf.io,cwisecarver/osf.io,kwierman/osf.io,abought/osf.io,leb2dg/osf.io,CenterForOpenScience/osf.io,zachjanicki/osf.io,felliott/osf.io,adlius/osf.io,felliott/osf.io,jnayak1/osf.io,binoculars/osf.io,DanielSBrown/osf.io,zamattiac/osf.io,billyhunt/osf.io,abought/osf.io,mluo613/osf.io,zamattiac/osf.io,GageGaskins/osf.io,mluo613/osf.io,brandonPurvis/osf.io,amyshi188/osf.io,brianjgeiger/osf.io,caneruguz/osf.io,HalcyonChimera/osf.io,brianjgeiger/osf.io,aaxelb/osf.io,brianjgeiger/osf.io,hmoco/osf.io,wearpants/osf.io,TomBaxter/osf.io,aaxelb/osf.io,alexschiller/osf.io,caseyrollins/osf.io,mfraezz/osf.io,doublebits/osf.io,zamattiac/osf.io,sloria/osf.io,pattisdr/osf.io,pattisdr/osf.io,rdhyee/osf.io,asanfilippo7/osf.io,asanfilippo7/osf.io,felliott/osf.io,monikagrabowska/osf.io,wearpants/osf.io,jnayak1/osf.io,monikagrabowska/osf.io,adlius/osf.io,emetsger/osf.io,RomanZWang/osf.io,chrisseto/osf.io,kch8qx/osf.io,billyhunt/osf.io,chennan47/osf.io,kch8qx/osf.io,icereval/osf.io,TomHeatwole/osf.io,mluo613/osf.io,TomHeatwole/osf.io,alexschiller/osf.io,kch8qx/osf.io | from django.conf.urls import url
from api.logs import views
urlpatterns = [
url(r'^(?P<log_id>\w+)/$', views.NodeLogDetail.as_view(), name=views.NodeLogDetail.view_name),
url(r'^(?P<log_id>\w+)/nodes/$', views.LogNodeList.as_view(), name=views.LogNodeList.view_name),
+ url(r'^(?P<log_id>\w+)/added_contributors/$', views.NodeLogAddedContributors.as_view(), name=views.NodeLogAddedContributors.view_name),
]
| Add /v2/logs/log_id/added_contributors/ to list of URL's. | ## Code Before:
from django.conf.urls import url
from api.logs import views
urlpatterns = [
url(r'^(?P<log_id>\w+)/$', views.NodeLogDetail.as_view(), name=views.NodeLogDetail.view_name),
url(r'^(?P<log_id>\w+)/nodes/$', views.LogNodeList.as_view(), name=views.LogNodeList.view_name),
]
## Instruction:
Add /v2/logs/log_id/added_contributors/ to list of URL's.
## Code After:
from django.conf.urls import url
from api.logs import views
urlpatterns = [
url(r'^(?P<log_id>\w+)/$', views.NodeLogDetail.as_view(), name=views.NodeLogDetail.view_name),
url(r'^(?P<log_id>\w+)/nodes/$', views.LogNodeList.as_view(), name=views.LogNodeList.view_name),
url(r'^(?P<log_id>\w+)/added_contributors/$', views.NodeLogAddedContributors.as_view(), name=views.NodeLogAddedContributors.view_name),
]
|
a9c6e045631103fe8508fd1b60d6076c05092fe1 | tests/examples/customnode/nodes.py | tests/examples/customnode/nodes.py | from viewflow.activation import AbstractGateActivation, Activation
from viewflow.flow import base
from viewflow.token import Token
class DynamicSplitActivation(AbstractGateActivation):
def calculate_next(self):
self._split_count = self.flow_task._task_count_callback(self.process)
@Activation.status.super()
def activate_next(self):
if self._split_count:
token_source = Token.split_token_source(self.task.token, self.task.pk)
for _ in range(self._split_count):
self.flow_task._next.activate(prev_activation=self, token=next(token_source))
class DynamicSplit(base.NextNodeMixin, base.DetailsViewMixin, base.Gateway):
"""
Activates several outgoing task instances depends on callback value
Example::
spit_on_decision = flow.DynamicSplit(lambda p: 4) \\
.Next(this.make_decision)
make_decision = flow.View(MyView) \\
.Next(this.join_on_decision)
join_on_decision = flow.Join() \\
.Next(this.end)
"""
task_type = 'SPLIT'
activation_cls = DynamicSplitActivation
def __init__(self, callback):
super(DynamicSplit, self).__init__()
self._task_count_callback = callback
| from viewflow.activation import AbstractGateActivation
from viewflow.flow import base
from viewflow.token import Token
class DynamicSplitActivation(AbstractGateActivation):
def calculate_next(self):
self._split_count = self.flow_task._task_count_callback(self.process)
def activate_next(self):
if self._split_count:
token_source = Token.split_token_source(self.task.token, self.task.pk)
for _ in range(self._split_count):
self.flow_task._next.activate(prev_activation=self, token=next(token_source))
class DynamicSplit(base.NextNodeMixin,
base.UndoViewMixin,
base.CancelViewMixin,
base.PerformViewMixin,
base.DetailsViewMixin,
base.Gateway):
"""
Activates several outgoing task instances depends on callback value
Example::
spit_on_decision = flow.DynamicSplit(lambda p: 4) \\
.Next(this.make_decision)
make_decision = flow.View(MyView) \\
.Next(this.join_on_decision)
join_on_decision = flow.Join() \\
.Next(this.end)
"""
task_type = 'SPLIT'
activation_cls = DynamicSplitActivation
def __init__(self, callback):
super(DynamicSplit, self).__init__()
self._task_count_callback = callback
| Add undo to custom node sample | Add undo to custom node sample
| Python | agpl-3.0 | ribeiro-ucl/viewflow,codingjoe/viewflow,pombredanne/viewflow,pombredanne/viewflow,codingjoe/viewflow,codingjoe/viewflow,viewflow/viewflow,viewflow/viewflow,ribeiro-ucl/viewflow,viewflow/viewflow,ribeiro-ucl/viewflow | - from viewflow.activation import AbstractGateActivation, Activation
+ from viewflow.activation import AbstractGateActivation
from viewflow.flow import base
from viewflow.token import Token
class DynamicSplitActivation(AbstractGateActivation):
def calculate_next(self):
self._split_count = self.flow_task._task_count_callback(self.process)
- @Activation.status.super()
def activate_next(self):
if self._split_count:
token_source = Token.split_token_source(self.task.token, self.task.pk)
for _ in range(self._split_count):
self.flow_task._next.activate(prev_activation=self, token=next(token_source))
- class DynamicSplit(base.NextNodeMixin, base.DetailsViewMixin, base.Gateway):
+ class DynamicSplit(base.NextNodeMixin,
+ base.UndoViewMixin,
+ base.CancelViewMixin,
+ base.PerformViewMixin,
+ base.DetailsViewMixin,
+ base.Gateway):
"""
Activates several outgoing task instances depends on callback value
Example::
spit_on_decision = flow.DynamicSplit(lambda p: 4) \\
.Next(this.make_decision)
make_decision = flow.View(MyView) \\
.Next(this.join_on_decision)
join_on_decision = flow.Join() \\
.Next(this.end)
"""
task_type = 'SPLIT'
activation_cls = DynamicSplitActivation
def __init__(self, callback):
super(DynamicSplit, self).__init__()
self._task_count_callback = callback
| Add undo to custom node sample | ## Code Before:
from viewflow.activation import AbstractGateActivation, Activation
from viewflow.flow import base
from viewflow.token import Token
class DynamicSplitActivation(AbstractGateActivation):
def calculate_next(self):
self._split_count = self.flow_task._task_count_callback(self.process)
@Activation.status.super()
def activate_next(self):
if self._split_count:
token_source = Token.split_token_source(self.task.token, self.task.pk)
for _ in range(self._split_count):
self.flow_task._next.activate(prev_activation=self, token=next(token_source))
class DynamicSplit(base.NextNodeMixin, base.DetailsViewMixin, base.Gateway):
"""
Activates several outgoing task instances depends on callback value
Example::
spit_on_decision = flow.DynamicSplit(lambda p: 4) \\
.Next(this.make_decision)
make_decision = flow.View(MyView) \\
.Next(this.join_on_decision)
join_on_decision = flow.Join() \\
.Next(this.end)
"""
task_type = 'SPLIT'
activation_cls = DynamicSplitActivation
def __init__(self, callback):
super(DynamicSplit, self).__init__()
self._task_count_callback = callback
## Instruction:
Add undo to custom node sample
## Code After:
from viewflow.activation import AbstractGateActivation
from viewflow.flow import base
from viewflow.token import Token
class DynamicSplitActivation(AbstractGateActivation):
def calculate_next(self):
self._split_count = self.flow_task._task_count_callback(self.process)
def activate_next(self):
if self._split_count:
token_source = Token.split_token_source(self.task.token, self.task.pk)
for _ in range(self._split_count):
self.flow_task._next.activate(prev_activation=self, token=next(token_source))
class DynamicSplit(base.NextNodeMixin,
base.UndoViewMixin,
base.CancelViewMixin,
base.PerformViewMixin,
base.DetailsViewMixin,
base.Gateway):
"""
Activates several outgoing task instances depends on callback value
Example::
spit_on_decision = flow.DynamicSplit(lambda p: 4) \\
.Next(this.make_decision)
make_decision = flow.View(MyView) \\
.Next(this.join_on_decision)
join_on_decision = flow.Join() \\
.Next(this.end)
"""
task_type = 'SPLIT'
activation_cls = DynamicSplitActivation
def __init__(self, callback):
super(DynamicSplit, self).__init__()
self._task_count_callback = callback
|
fffca3d2198f7c65b2e4fa2b805efa54f4c9fdb9 | tests/zeus/artifacts/test_xunit.py | tests/zeus/artifacts/test_xunit.py | from io import BytesIO
from zeus.artifacts.xunit import XunitHandler
from zeus.constants import Result
from zeus.models import Job
from zeus.utils.testresult import TestResult as ZeusTestResult
def test_result_generation(sample_xunit):
job = Job()
fp = BytesIO(sample_xunit.encode("utf8"))
handler = XunitHandler(job)
results = handler.get_tests(fp)
assert len(results) == 2
r1 = results[0]
assert type(r1) == ZeusTestResult
assert r1.job == job
assert r1.name == "tests.test_report"
assert r1.duration == 0.0
assert r1.result == Result.failed
assert (
r1.message
== """tests/test_report.py:1: in <module>
> import mock
E ImportError: No module named mock"""
)
r2 = results[1]
assert type(r2) == ZeusTestResult
assert r2.job == job
assert r2.name == "tests.test_report.ParseTestResultsTest.test_simple"
assert r2.duration == 1.65796279907
assert r2.result == Result.passed
assert r2.message == ""
| from io import BytesIO
from zeus.artifacts.xunit import XunitHandler
from zeus.constants import Result
from zeus.models import Job
from zeus.utils.testresult import TestResult as ZeusTestResult
def test_result_generation(sample_xunit):
job = Job()
fp = BytesIO(sample_xunit.encode("utf8"))
handler = XunitHandler(job)
results = handler.get_tests(fp)
assert len(results) == 2
r1 = results[0]
assert type(r1) == ZeusTestResult
assert r1.job == job
assert r1.name == "tests.test_report"
assert r1.duration == 0
assert r1.result == Result.failed
assert (
r1.message
== """tests/test_report.py:1: in <module>
> import mock
E ImportError: No module named mock"""
)
r2 = results[1]
assert type(r2) == ZeusTestResult
assert r2.job == job
assert r2.name == "tests.test_report.ParseTestResultsTest.test_simple"
assert r2.duration == 1
assert r2.result == Result.passed
assert r2.message == ""
| Fix test case being integers | test: Fix test case being integers
| Python | apache-2.0 | getsentry/zeus,getsentry/zeus,getsentry/zeus,getsentry/zeus | from io import BytesIO
from zeus.artifacts.xunit import XunitHandler
from zeus.constants import Result
from zeus.models import Job
from zeus.utils.testresult import TestResult as ZeusTestResult
def test_result_generation(sample_xunit):
job = Job()
fp = BytesIO(sample_xunit.encode("utf8"))
handler = XunitHandler(job)
results = handler.get_tests(fp)
assert len(results) == 2
r1 = results[0]
assert type(r1) == ZeusTestResult
assert r1.job == job
assert r1.name == "tests.test_report"
- assert r1.duration == 0.0
+ assert r1.duration == 0
assert r1.result == Result.failed
assert (
r1.message
== """tests/test_report.py:1: in <module>
> import mock
E ImportError: No module named mock"""
)
r2 = results[1]
assert type(r2) == ZeusTestResult
assert r2.job == job
assert r2.name == "tests.test_report.ParseTestResultsTest.test_simple"
- assert r2.duration == 1.65796279907
+ assert r2.duration == 1
assert r2.result == Result.passed
assert r2.message == ""
| Fix test case being integers | ## Code Before:
from io import BytesIO
from zeus.artifacts.xunit import XunitHandler
from zeus.constants import Result
from zeus.models import Job
from zeus.utils.testresult import TestResult as ZeusTestResult
def test_result_generation(sample_xunit):
job = Job()
fp = BytesIO(sample_xunit.encode("utf8"))
handler = XunitHandler(job)
results = handler.get_tests(fp)
assert len(results) == 2
r1 = results[0]
assert type(r1) == ZeusTestResult
assert r1.job == job
assert r1.name == "tests.test_report"
assert r1.duration == 0.0
assert r1.result == Result.failed
assert (
r1.message
== """tests/test_report.py:1: in <module>
> import mock
E ImportError: No module named mock"""
)
r2 = results[1]
assert type(r2) == ZeusTestResult
assert r2.job == job
assert r2.name == "tests.test_report.ParseTestResultsTest.test_simple"
assert r2.duration == 1.65796279907
assert r2.result == Result.passed
assert r2.message == ""
## Instruction:
Fix test case being integers
## Code After:
from io import BytesIO
from zeus.artifacts.xunit import XunitHandler
from zeus.constants import Result
from zeus.models import Job
from zeus.utils.testresult import TestResult as ZeusTestResult
def test_result_generation(sample_xunit):
job = Job()
fp = BytesIO(sample_xunit.encode("utf8"))
handler = XunitHandler(job)
results = handler.get_tests(fp)
assert len(results) == 2
r1 = results[0]
assert type(r1) == ZeusTestResult
assert r1.job == job
assert r1.name == "tests.test_report"
assert r1.duration == 0
assert r1.result == Result.failed
assert (
r1.message
== """tests/test_report.py:1: in <module>
> import mock
E ImportError: No module named mock"""
)
r2 = results[1]
assert type(r2) == ZeusTestResult
assert r2.job == job
assert r2.name == "tests.test_report.ParseTestResultsTest.test_simple"
assert r2.duration == 1
assert r2.result == Result.passed
assert r2.message == ""
|
cfde8a339c52c1875cb3b863ace3cad6174eb54c | account_cost_spread/models/account_invoice.py | account_cost_spread/models/account_invoice.py |
from odoo import api, models
class AccountInvoice(models.Model):
_inherit = 'account.invoice'
@api.multi
def action_move_create(self):
"""Override, button Validate on invoices."""
res = super(AccountInvoice, self).action_move_create()
for rec in self:
rec.invoice_line_ids.compute_spread_board()
return res
@api.multi
def invoice_line_move_line_get(self):
res = super(AccountInvoice, self).invoice_line_move_line_get()
for line in res:
invl_id = line.get('invl_id')
invl = self.env['account.invoice.line'].browse(invl_id)
if invl.spread_account_id:
line['account_id'] = invl.spread_account_id.id
return res
@api.multi
def action_invoice_cancel(self):
res = self.action_cancel()
for invoice in self:
for invoice_line in invoice.invoice_line_ids:
for spread_line in invoice_line.spread_line_ids:
if spread_line.move_id:
spread_line.move_id.button_cancel()
spread_line.move_id.unlink()
spread_line.unlink()
return res
|
from odoo import api, models
class AccountInvoice(models.Model):
_inherit = 'account.invoice'
@api.multi
def action_move_create(self):
"""Invoked when validating the invoices."""
res = super(AccountInvoice, self).action_move_create()
for rec in self:
rec.invoice_line_ids.compute_spread_board()
return res
@api.multi
def invoice_line_move_line_get(self):
res = super(AccountInvoice, self).invoice_line_move_line_get()
for line in res:
invl_id = line.get('invl_id')
invl = self.env['account.invoice.line'].browse(invl_id)
if invl.spread_account_id:
line['account_id'] = invl.spread_account_id.id
return res
@api.multi
def action_invoice_cancel(self):
res = self.action_cancel()
for invoice in self:
for invoice_line in invoice.invoice_line_ids:
for spread_line in invoice_line.spread_line_ids:
if spread_line.move_id:
spread_line.move_id.button_cancel()
spread_line.move_id.unlink()
spread_line.unlink()
return res
| Fix method description in account_cost_spread | Fix method description in account_cost_spread
| Python | agpl-3.0 | onesteinbv/addons-onestein,onesteinbv/addons-onestein,onesteinbv/addons-onestein |
from odoo import api, models
class AccountInvoice(models.Model):
_inherit = 'account.invoice'
@api.multi
def action_move_create(self):
- """Override, button Validate on invoices."""
+ """Invoked when validating the invoices."""
res = super(AccountInvoice, self).action_move_create()
for rec in self:
rec.invoice_line_ids.compute_spread_board()
return res
@api.multi
def invoice_line_move_line_get(self):
res = super(AccountInvoice, self).invoice_line_move_line_get()
for line in res:
invl_id = line.get('invl_id')
invl = self.env['account.invoice.line'].browse(invl_id)
if invl.spread_account_id:
line['account_id'] = invl.spread_account_id.id
return res
@api.multi
def action_invoice_cancel(self):
res = self.action_cancel()
for invoice in self:
for invoice_line in invoice.invoice_line_ids:
for spread_line in invoice_line.spread_line_ids:
if spread_line.move_id:
spread_line.move_id.button_cancel()
spread_line.move_id.unlink()
spread_line.unlink()
return res
| Fix method description in account_cost_spread | ## Code Before:
from odoo import api, models
class AccountInvoice(models.Model):
_inherit = 'account.invoice'
@api.multi
def action_move_create(self):
"""Override, button Validate on invoices."""
res = super(AccountInvoice, self).action_move_create()
for rec in self:
rec.invoice_line_ids.compute_spread_board()
return res
@api.multi
def invoice_line_move_line_get(self):
res = super(AccountInvoice, self).invoice_line_move_line_get()
for line in res:
invl_id = line.get('invl_id')
invl = self.env['account.invoice.line'].browse(invl_id)
if invl.spread_account_id:
line['account_id'] = invl.spread_account_id.id
return res
@api.multi
def action_invoice_cancel(self):
res = self.action_cancel()
for invoice in self:
for invoice_line in invoice.invoice_line_ids:
for spread_line in invoice_line.spread_line_ids:
if spread_line.move_id:
spread_line.move_id.button_cancel()
spread_line.move_id.unlink()
spread_line.unlink()
return res
## Instruction:
Fix method description in account_cost_spread
## Code After:
from odoo import api, models
class AccountInvoice(models.Model):
_inherit = 'account.invoice'
@api.multi
def action_move_create(self):
"""Invoked when validating the invoices."""
res = super(AccountInvoice, self).action_move_create()
for rec in self:
rec.invoice_line_ids.compute_spread_board()
return res
@api.multi
def invoice_line_move_line_get(self):
res = super(AccountInvoice, self).invoice_line_move_line_get()
for line in res:
invl_id = line.get('invl_id')
invl = self.env['account.invoice.line'].browse(invl_id)
if invl.spread_account_id:
line['account_id'] = invl.spread_account_id.id
return res
@api.multi
def action_invoice_cancel(self):
res = self.action_cancel()
for invoice in self:
for invoice_line in invoice.invoice_line_ids:
for spread_line in invoice_line.spread_line_ids:
if spread_line.move_id:
spread_line.move_id.button_cancel()
spread_line.move_id.unlink()
spread_line.unlink()
return res
|
08f633cdf0f5dcd1940da46e91c175e81b39ad3f | setup.py | setup.py |
from distutils.core import setup
from distutils.extension import Extension
try:
from Cython.Build import build_ext, cythonize
BUILD_EXTENSION = {'build_ext': build_ext}
EXT_MODULES = cythonize([Extension("dtrace", ["dtrace_cython/dtrace_h.pxd",
"dtrace_cython/consumer.pyx"],
libraries=["dtrace"])],
language_level=2)
except ImportError:
BUILD_EXTENSION = {}
EXT_MODULES = None
print('WARNING: Cython seems not to be present. Currently you will only'
' be able to use the ctypes wrapper. Or you can install cython and'
' try again.')
setup(name='python-dtrace',
version='0.0.10',
description='DTrace consumer for Python based on libdtrace. Use Python'
+ ' as DTrace Consumer and Provider! See the homepage for'
+ ' more information.',
license='MIT',
keywords='DTrace',
url='http://tmetsch.github.com/python-dtrace/',
packages=['dtrace_ctypes'],
cmdclass=BUILD_EXTENSION,
ext_modules=EXT_MODULES,
classifiers=["Development Status :: 2 - Pre-Alpha",
"Operating System :: OS Independent",
"Programming Language :: Python"
])
|
from distutils.core import setup
from distutils.extension import Extension
import sys
try:
from Cython.Build import build_ext, cythonize
BUILD_EXTENSION = {'build_ext': build_ext}
EXT_MODULES = cythonize([Extension("dtrace", ["dtrace_cython/dtrace_h.pxd",
"dtrace_cython/consumer.pyx"],
libraries=["dtrace"])],
language_level=sys.version_info.major)
except ImportError:
BUILD_EXTENSION = {}
EXT_MODULES = None
print('WARNING: Cython seems not to be present. Currently you will only'
' be able to use the ctypes wrapper. Or you can install cython and'
' try again.')
setup(name='python-dtrace',
version='0.0.10',
description='DTrace consumer for Python based on libdtrace. Use Python'
+ ' as DTrace Consumer and Provider! See the homepage for'
+ ' more information.',
license='MIT',
keywords='DTrace',
url='http://tmetsch.github.com/python-dtrace/',
packages=['dtrace_ctypes'],
cmdclass=BUILD_EXTENSION,
ext_modules=EXT_MODULES,
classifiers=["Development Status :: 2 - Pre-Alpha",
"Operating System :: OS Independent",
"Programming Language :: Python"
])
| Set Cython language_level to 3 when compiling for python3 | Set Cython language_level to 3 when compiling for python3
| Python | mit | tmetsch/python-dtrace,tmetsch/python-dtrace |
from distutils.core import setup
from distutils.extension import Extension
+ import sys
try:
from Cython.Build import build_ext, cythonize
BUILD_EXTENSION = {'build_ext': build_ext}
EXT_MODULES = cythonize([Extension("dtrace", ["dtrace_cython/dtrace_h.pxd",
"dtrace_cython/consumer.pyx"],
libraries=["dtrace"])],
- language_level=2)
+ language_level=sys.version_info.major)
except ImportError:
BUILD_EXTENSION = {}
EXT_MODULES = None
print('WARNING: Cython seems not to be present. Currently you will only'
' be able to use the ctypes wrapper. Or you can install cython and'
' try again.')
setup(name='python-dtrace',
version='0.0.10',
description='DTrace consumer for Python based on libdtrace. Use Python'
+ ' as DTrace Consumer and Provider! See the homepage for'
+ ' more information.',
license='MIT',
keywords='DTrace',
url='http://tmetsch.github.com/python-dtrace/',
packages=['dtrace_ctypes'],
cmdclass=BUILD_EXTENSION,
ext_modules=EXT_MODULES,
classifiers=["Development Status :: 2 - Pre-Alpha",
"Operating System :: OS Independent",
"Programming Language :: Python"
])
| Set Cython language_level to 3 when compiling for python3 | ## Code Before:
from distutils.core import setup
from distutils.extension import Extension
try:
from Cython.Build import build_ext, cythonize
BUILD_EXTENSION = {'build_ext': build_ext}
EXT_MODULES = cythonize([Extension("dtrace", ["dtrace_cython/dtrace_h.pxd",
"dtrace_cython/consumer.pyx"],
libraries=["dtrace"])],
language_level=2)
except ImportError:
BUILD_EXTENSION = {}
EXT_MODULES = None
print('WARNING: Cython seems not to be present. Currently you will only'
' be able to use the ctypes wrapper. Or you can install cython and'
' try again.')
setup(name='python-dtrace',
version='0.0.10',
description='DTrace consumer for Python based on libdtrace. Use Python'
+ ' as DTrace Consumer and Provider! See the homepage for'
+ ' more information.',
license='MIT',
keywords='DTrace',
url='http://tmetsch.github.com/python-dtrace/',
packages=['dtrace_ctypes'],
cmdclass=BUILD_EXTENSION,
ext_modules=EXT_MODULES,
classifiers=["Development Status :: 2 - Pre-Alpha",
"Operating System :: OS Independent",
"Programming Language :: Python"
])
## Instruction:
Set Cython language_level to 3 when compiling for python3
## Code After:
from distutils.core import setup
from distutils.extension import Extension
import sys
try:
from Cython.Build import build_ext, cythonize
BUILD_EXTENSION = {'build_ext': build_ext}
EXT_MODULES = cythonize([Extension("dtrace", ["dtrace_cython/dtrace_h.pxd",
"dtrace_cython/consumer.pyx"],
libraries=["dtrace"])],
language_level=sys.version_info.major)
except ImportError:
BUILD_EXTENSION = {}
EXT_MODULES = None
print('WARNING: Cython seems not to be present. Currently you will only'
' be able to use the ctypes wrapper. Or you can install cython and'
' try again.')
setup(name='python-dtrace',
version='0.0.10',
description='DTrace consumer for Python based on libdtrace. Use Python'
+ ' as DTrace Consumer and Provider! See the homepage for'
+ ' more information.',
license='MIT',
keywords='DTrace',
url='http://tmetsch.github.com/python-dtrace/',
packages=['dtrace_ctypes'],
cmdclass=BUILD_EXTENSION,
ext_modules=EXT_MODULES,
classifiers=["Development Status :: 2 - Pre-Alpha",
"Operating System :: OS Independent",
"Programming Language :: Python"
])
|
6a5c9ccf0bd2582cf42577712309b8fd6e912966 | blo/__init__.py | blo/__init__.py | import configparser
from blo.BloArticle import BloArticle
from blo.DBControl import DBControl
class Blo:
def __init__(self, config_file_path):
config = configparser.ConfigParser()
config.read(config_file_path)
self._db_file_path = config['DB']['DB_PATH']
self._template_dir = config['TEMPLATE']['TEMPLATE_DIR']
self._default_template_file = config['TEMPLATE']['DEFAULT_TEMPLATE_FILE']
# create tables
self._db_control = DBControl(self._db_file_path)
self._db_control.create_tables()
self._db_control.close_connect()
def insert_article(self, file_path):
self._db_control = DBControl(self._db_file_path)
article = BloArticle(self._template_dir)
article.load_from_file(file_path)
self._db_control.insert_article(article, self._default_template_file)
self._db_control.close_connect()
| import configparser
from blo.BloArticle import BloArticle
from blo.DBControl import DBControl
class Blo:
def __init__(self, config_file_path):
config = configparser.ConfigParser()
config.read(config_file_path)
self._db_file_path = config['DB']['DB_PATH'].replace('"', '')
self._template_dir = config['TEMPLATE']['TEMPLATE_DIR'].replace('"', '')
self._default_template_file = config['TEMPLATE']['DEFAULT_TEMPLATE_FILE'].replace('"', '')
# create tables
self._db_control = DBControl(self._db_file_path)
self._db_control.create_tables()
self._db_control.close_connect()
def insert_article(self, file_path):
self._db_control = DBControl(self._db_file_path)
article = BloArticle(self._template_dir)
article.load_from_file(file_path)
self._db_control.insert_article(article, self._default_template_file)
self._db_control.close_connect()
| Add replace double quotation mark from configuration file parameters. | Add replace double quotation mark from configuration file parameters.
| Python | mit | 10nin/blo,10nin/blo | import configparser
from blo.BloArticle import BloArticle
from blo.DBControl import DBControl
class Blo:
def __init__(self, config_file_path):
config = configparser.ConfigParser()
config.read(config_file_path)
- self._db_file_path = config['DB']['DB_PATH']
+ self._db_file_path = config['DB']['DB_PATH'].replace('"', '')
- self._template_dir = config['TEMPLATE']['TEMPLATE_DIR']
+ self._template_dir = config['TEMPLATE']['TEMPLATE_DIR'].replace('"', '')
- self._default_template_file = config['TEMPLATE']['DEFAULT_TEMPLATE_FILE']
+ self._default_template_file = config['TEMPLATE']['DEFAULT_TEMPLATE_FILE'].replace('"', '')
# create tables
self._db_control = DBControl(self._db_file_path)
self._db_control.create_tables()
self._db_control.close_connect()
def insert_article(self, file_path):
self._db_control = DBControl(self._db_file_path)
article = BloArticle(self._template_dir)
article.load_from_file(file_path)
self._db_control.insert_article(article, self._default_template_file)
self._db_control.close_connect()
| Add replace double quotation mark from configuration file parameters. | ## Code Before:
import configparser
from blo.BloArticle import BloArticle
from blo.DBControl import DBControl
class Blo:
def __init__(self, config_file_path):
config = configparser.ConfigParser()
config.read(config_file_path)
self._db_file_path = config['DB']['DB_PATH']
self._template_dir = config['TEMPLATE']['TEMPLATE_DIR']
self._default_template_file = config['TEMPLATE']['DEFAULT_TEMPLATE_FILE']
# create tables
self._db_control = DBControl(self._db_file_path)
self._db_control.create_tables()
self._db_control.close_connect()
def insert_article(self, file_path):
self._db_control = DBControl(self._db_file_path)
article = BloArticle(self._template_dir)
article.load_from_file(file_path)
self._db_control.insert_article(article, self._default_template_file)
self._db_control.close_connect()
## Instruction:
Add replace double quotation mark from configuration file parameters.
## Code After:
import configparser
from blo.BloArticle import BloArticle
from blo.DBControl import DBControl
class Blo:
def __init__(self, config_file_path):
config = configparser.ConfigParser()
config.read(config_file_path)
self._db_file_path = config['DB']['DB_PATH'].replace('"', '')
self._template_dir = config['TEMPLATE']['TEMPLATE_DIR'].replace('"', '')
self._default_template_file = config['TEMPLATE']['DEFAULT_TEMPLATE_FILE'].replace('"', '')
# create tables
self._db_control = DBControl(self._db_file_path)
self._db_control.create_tables()
self._db_control.close_connect()
def insert_article(self, file_path):
self._db_control = DBControl(self._db_file_path)
article = BloArticle(self._template_dir)
article.load_from_file(file_path)
self._db_control.insert_article(article, self._default_template_file)
self._db_control.close_connect()
|
1fffdb60aa4eb875bfbd961773d0cf5066dc38e2 | django_website/views.py | django_website/views.py | from __future__ import absolute_import
from django.contrib.comments.models import Comment
from django.contrib.sitemaps import views as sitemap_views
from django.shortcuts import render
from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import requires_csrf_token
from django.views.generic import list_detail
from .sitemaps import FlatPageSitemap, WeblogSitemap
@cache_page(60*60*6)
def sitemap(request):
return sitemap_views.sitemap(request, sitemaps={
'weblog': WeblogSitemap,
'flatpages': FlatPageSitemap,
})
def comments(request):
return list_detail.object_list(
request,
queryset = Comment.objects.filter(is_public=True).order_by('-submit_date'),
paginate_by = 30,
)
@requires_csrf_token
def server_error(request, template_name='500.html'):
"""
Custom 500 error handler for static stuff.
"""
return render(request, template_name)
| from django.shortcuts import render
from django.views.decorators.csrf import requires_csrf_token
@requires_csrf_token
def server_error(request, template_name='500.html'):
"""
Custom 500 error handler for static stuff.
"""
return render(request, template_name)
| Remove dead code. This isn't wired in any URLconf. | Remove dead code. This isn't wired in any URLconf.
| Python | bsd-3-clause | nanuxbe/django,xavierdutreilh/djangoproject.com,vxvinh1511/djangoproject.com,rmoorman/djangoproject.com,gnarf/djangoproject.com,django/djangoproject.com,rmoorman/djangoproject.com,relekang/djangoproject.com,hassanabidpk/djangoproject.com,alawnchen/djangoproject.com,alawnchen/djangoproject.com,khkaminska/djangoproject.com,nanuxbe/django,nanuxbe/django,nanuxbe/django,hassanabidpk/djangoproject.com,gnarf/djangoproject.com,alawnchen/djangoproject.com,khkaminska/djangoproject.com,relekang/djangoproject.com,django/djangoproject.com,xavierdutreilh/djangoproject.com,relekang/djangoproject.com,relekang/djangoproject.com,django/djangoproject.com,rmoorman/djangoproject.com,gnarf/djangoproject.com,alawnchen/djangoproject.com,xavierdutreilh/djangoproject.com,django/djangoproject.com,vxvinh1511/djangoproject.com,xavierdutreilh/djangoproject.com,khkaminska/djangoproject.com,django/djangoproject.com,hassanabidpk/djangoproject.com,khkaminska/djangoproject.com,gnarf/djangoproject.com,rmoorman/djangoproject.com,vxvinh1511/djangoproject.com,vxvinh1511/djangoproject.com,hassanabidpk/djangoproject.com,django/djangoproject.com | - from __future__ import absolute_import
-
- from django.contrib.comments.models import Comment
- from django.contrib.sitemaps import views as sitemap_views
from django.shortcuts import render
- from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import requires_csrf_token
- from django.views.generic import list_detail
-
- from .sitemaps import FlatPageSitemap, WeblogSitemap
-
- @cache_page(60*60*6)
- def sitemap(request):
- return sitemap_views.sitemap(request, sitemaps={
- 'weblog': WeblogSitemap,
- 'flatpages': FlatPageSitemap,
- })
-
- def comments(request):
- return list_detail.object_list(
- request,
- queryset = Comment.objects.filter(is_public=True).order_by('-submit_date'),
- paginate_by = 30,
- )
@requires_csrf_token
def server_error(request, template_name='500.html'):
"""
Custom 500 error handler for static stuff.
"""
return render(request, template_name)
| Remove dead code. This isn't wired in any URLconf. | ## Code Before:
from __future__ import absolute_import
from django.contrib.comments.models import Comment
from django.contrib.sitemaps import views as sitemap_views
from django.shortcuts import render
from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import requires_csrf_token
from django.views.generic import list_detail
from .sitemaps import FlatPageSitemap, WeblogSitemap
@cache_page(60*60*6)
def sitemap(request):
return sitemap_views.sitemap(request, sitemaps={
'weblog': WeblogSitemap,
'flatpages': FlatPageSitemap,
})
def comments(request):
return list_detail.object_list(
request,
queryset = Comment.objects.filter(is_public=True).order_by('-submit_date'),
paginate_by = 30,
)
@requires_csrf_token
def server_error(request, template_name='500.html'):
"""
Custom 500 error handler for static stuff.
"""
return render(request, template_name)
## Instruction:
Remove dead code. This isn't wired in any URLconf.
## Code After:
from django.shortcuts import render
from django.views.decorators.csrf import requires_csrf_token
@requires_csrf_token
def server_error(request, template_name='500.html'):
"""
Custom 500 error handler for static stuff.
"""
return render(request, template_name)
|
27a0226ec444523034d739a00a999b089ce116ba | enthought/chaco/tools/api.py | enthought/chaco/tools/api.py | from better_zoom import BetterZoom
from better_selecting_zoom import BetterSelectingZoom
from broadcaster import BroadcasterTool
from dataprinter import DataPrinter
from data_label_tool import DataLabelTool
from drag_zoom import DragZoom
from enthought.enable.tools.drag_tool import DragTool
from draw_points_tool import DrawPointsTool
from highlight_tool import HighlightTool
from image_inspector_tool import ImageInspectorTool, ImageInspectorOverlay
from lasso_selection import LassoSelection
from legend_tool import LegendTool
from legend_highlighter import LegendHighlighter
from line_inspector import LineInspector
from line_segment_tool import LineSegmentTool
from move_tool import MoveTool
from pan_tool import PanTool
from point_marker import PointMarker
from range_selection import RangeSelection
from range_selection_2d import RangeSelection2D
from range_selection_overlay import RangeSelectionOverlay
from regression_lasso import RegressionLasso, RegressionOverlay
from save_tool import SaveTool
from scatter_inspector import ScatterInspector
from select_tool import SelectTool
from simple_inspector import SimpleInspectorTool
from tracking_pan_tool import TrackingPanTool
from tracking_zoom import TrackingZoom
from traits_tool import TraitsTool
from zoom_tool import ZoomTool
# EOF
| from better_zoom import BetterZoom
from better_selecting_zoom import BetterSelectingZoom
from broadcaster import BroadcasterTool
from dataprinter import DataPrinter
from data_label_tool import DataLabelTool
from enthought.enable.tools.drag_tool import DragTool
from draw_points_tool import DrawPointsTool
from highlight_tool import HighlightTool
from image_inspector_tool import ImageInspectorTool, ImageInspectorOverlay
from lasso_selection import LassoSelection
from legend_tool import LegendTool
from legend_highlighter import LegendHighlighter
from line_inspector import LineInspector
from line_segment_tool import LineSegmentTool
from move_tool import MoveTool
from pan_tool import PanTool
from point_marker import PointMarker
from range_selection import RangeSelection
from range_selection_2d import RangeSelection2D
from range_selection_overlay import RangeSelectionOverlay
from regression_lasso import RegressionLasso, RegressionOverlay
from save_tool import SaveTool
from scatter_inspector import ScatterInspector
from select_tool import SelectTool
from simple_inspector import SimpleInspectorTool
from tracking_pan_tool import TrackingPanTool
from tracking_zoom import TrackingZoom
from traits_tool import TraitsTool
from zoom_tool import ZoomTool
# EOF
| Remove deprecated DragZoom from Chaco tools API to eliminate irrelevant BaseZoomTool deprecation warning. DragZoom is still used in 4 Chaco examples | [Chaco] Remove deprecated DragZoom from Chaco tools API to eliminate irrelevant BaseZoomTool deprecation warning. DragZoom is still used in 4 Chaco examples
| Python | bsd-3-clause | ContinuumIO/chaco,tommy-u/chaco,tommy-u/chaco,ContinuumIO/chaco,tommy-u/chaco,ContinuumIO/chaco,burnpanck/chaco,burnpanck/chaco,ContinuumIO/chaco,burnpanck/chaco | from better_zoom import BetterZoom
from better_selecting_zoom import BetterSelectingZoom
from broadcaster import BroadcasterTool
from dataprinter import DataPrinter
from data_label_tool import DataLabelTool
- from drag_zoom import DragZoom
from enthought.enable.tools.drag_tool import DragTool
from draw_points_tool import DrawPointsTool
from highlight_tool import HighlightTool
from image_inspector_tool import ImageInspectorTool, ImageInspectorOverlay
from lasso_selection import LassoSelection
from legend_tool import LegendTool
from legend_highlighter import LegendHighlighter
from line_inspector import LineInspector
from line_segment_tool import LineSegmentTool
from move_tool import MoveTool
from pan_tool import PanTool
from point_marker import PointMarker
from range_selection import RangeSelection
from range_selection_2d import RangeSelection2D
from range_selection_overlay import RangeSelectionOverlay
from regression_lasso import RegressionLasso, RegressionOverlay
from save_tool import SaveTool
from scatter_inspector import ScatterInspector
from select_tool import SelectTool
from simple_inspector import SimpleInspectorTool
from tracking_pan_tool import TrackingPanTool
from tracking_zoom import TrackingZoom
from traits_tool import TraitsTool
from zoom_tool import ZoomTool
# EOF
| Remove deprecated DragZoom from Chaco tools API to eliminate irrelevant BaseZoomTool deprecation warning. DragZoom is still used in 4 Chaco examples | ## Code Before:
from better_zoom import BetterZoom
from better_selecting_zoom import BetterSelectingZoom
from broadcaster import BroadcasterTool
from dataprinter import DataPrinter
from data_label_tool import DataLabelTool
from drag_zoom import DragZoom
from enthought.enable.tools.drag_tool import DragTool
from draw_points_tool import DrawPointsTool
from highlight_tool import HighlightTool
from image_inspector_tool import ImageInspectorTool, ImageInspectorOverlay
from lasso_selection import LassoSelection
from legend_tool import LegendTool
from legend_highlighter import LegendHighlighter
from line_inspector import LineInspector
from line_segment_tool import LineSegmentTool
from move_tool import MoveTool
from pan_tool import PanTool
from point_marker import PointMarker
from range_selection import RangeSelection
from range_selection_2d import RangeSelection2D
from range_selection_overlay import RangeSelectionOverlay
from regression_lasso import RegressionLasso, RegressionOverlay
from save_tool import SaveTool
from scatter_inspector import ScatterInspector
from select_tool import SelectTool
from simple_inspector import SimpleInspectorTool
from tracking_pan_tool import TrackingPanTool
from tracking_zoom import TrackingZoom
from traits_tool import TraitsTool
from zoom_tool import ZoomTool
# EOF
## Instruction:
Remove deprecated DragZoom from Chaco tools API to eliminate irrelevant BaseZoomTool deprecation warning. DragZoom is still used in 4 Chaco examples
## Code After:
from better_zoom import BetterZoom
from better_selecting_zoom import BetterSelectingZoom
from broadcaster import BroadcasterTool
from dataprinter import DataPrinter
from data_label_tool import DataLabelTool
from enthought.enable.tools.drag_tool import DragTool
from draw_points_tool import DrawPointsTool
from highlight_tool import HighlightTool
from image_inspector_tool import ImageInspectorTool, ImageInspectorOverlay
from lasso_selection import LassoSelection
from legend_tool import LegendTool
from legend_highlighter import LegendHighlighter
from line_inspector import LineInspector
from line_segment_tool import LineSegmentTool
from move_tool import MoveTool
from pan_tool import PanTool
from point_marker import PointMarker
from range_selection import RangeSelection
from range_selection_2d import RangeSelection2D
from range_selection_overlay import RangeSelectionOverlay
from regression_lasso import RegressionLasso, RegressionOverlay
from save_tool import SaveTool
from scatter_inspector import ScatterInspector
from select_tool import SelectTool
from simple_inspector import SimpleInspectorTool
from tracking_pan_tool import TrackingPanTool
from tracking_zoom import TrackingZoom
from traits_tool import TraitsTool
from zoom_tool import ZoomTool
# EOF
|
0df76d66fb6a2425c6ccc8a3a75d41599b2545c6 | auth0/v2/authentication/delegated.py | auth0/v2/authentication/delegated.py | from .base import AuthenticationBase
class Delegated(AuthenticationBase):
def __init__(self, domain):
self.domain = domain
def get_token(self, client_id, target, api_type, grant_type,
id_token=None, refresh_token=None):
if id_token and refresh_token:
raise ValueError('Only one of id_token or refresh_token '
'can be None')
data = {
'client_id': client_id,
'grant_type': grant_type,
'target': target,
'scope': 'openid',
'api_type': api_type,
}
if id_token:
data.update({'id_token': id_token})
elif refresh_token:
data.update({'refresh_token': refresh_token})
else:
raise ValueError('Either id_token or refresh_token must '
'have a value')
return self.post(
'https://%s/delegation' % self.domain,
headers={'Content-Type': 'application/json'},
data=data
)
| from .base import AuthenticationBase
class Delegated(AuthenticationBase):
"""Delegated authentication endpoints.
Args:
domain (str): Your auth0 domain (e.g: username.auth0.com)
"""
def __init__(self, domain):
self.domain = domain
def get_token(self, client_id, target, api_type, grant_type,
id_token=None, refresh_token=None):
"""Obtain a delegation token.
"""
if id_token and refresh_token:
raise ValueError('Only one of id_token or refresh_token '
'can be None')
data = {
'client_id': client_id,
'grant_type': grant_type,
'target': target,
'scope': 'openid',
'api_type': api_type,
}
if id_token:
data.update({'id_token': id_token})
elif refresh_token:
data.update({'refresh_token': refresh_token})
else:
raise ValueError('Either id_token or refresh_token must '
'have a value')
return self.post(
'https://%s/delegation' % self.domain,
headers={'Content-Type': 'application/json'},
data=data
)
| Add docstrings in Delegated class | Add docstrings in Delegated class
| Python | mit | auth0/auth0-python,auth0/auth0-python | from .base import AuthenticationBase
class Delegated(AuthenticationBase):
+
+ """Delegated authentication endpoints.
+
+ Args:
+ domain (str): Your auth0 domain (e.g: username.auth0.com)
+ """
def __init__(self, domain):
self.domain = domain
def get_token(self, client_id, target, api_type, grant_type,
id_token=None, refresh_token=None):
+
+ """Obtain a delegation token.
+ """
if id_token and refresh_token:
raise ValueError('Only one of id_token or refresh_token '
'can be None')
data = {
'client_id': client_id,
'grant_type': grant_type,
'target': target,
'scope': 'openid',
'api_type': api_type,
}
if id_token:
data.update({'id_token': id_token})
elif refresh_token:
data.update({'refresh_token': refresh_token})
else:
raise ValueError('Either id_token or refresh_token must '
'have a value')
return self.post(
'https://%s/delegation' % self.domain,
headers={'Content-Type': 'application/json'},
data=data
)
| Add docstrings in Delegated class | ## Code Before:
from .base import AuthenticationBase
class Delegated(AuthenticationBase):
def __init__(self, domain):
self.domain = domain
def get_token(self, client_id, target, api_type, grant_type,
id_token=None, refresh_token=None):
if id_token and refresh_token:
raise ValueError('Only one of id_token or refresh_token '
'can be None')
data = {
'client_id': client_id,
'grant_type': grant_type,
'target': target,
'scope': 'openid',
'api_type': api_type,
}
if id_token:
data.update({'id_token': id_token})
elif refresh_token:
data.update({'refresh_token': refresh_token})
else:
raise ValueError('Either id_token or refresh_token must '
'have a value')
return self.post(
'https://%s/delegation' % self.domain,
headers={'Content-Type': 'application/json'},
data=data
)
## Instruction:
Add docstrings in Delegated class
## Code After:
from .base import AuthenticationBase
class Delegated(AuthenticationBase):
"""Delegated authentication endpoints.
Args:
domain (str): Your auth0 domain (e.g: username.auth0.com)
"""
def __init__(self, domain):
self.domain = domain
def get_token(self, client_id, target, api_type, grant_type,
id_token=None, refresh_token=None):
"""Obtain a delegation token.
"""
if id_token and refresh_token:
raise ValueError('Only one of id_token or refresh_token '
'can be None')
data = {
'client_id': client_id,
'grant_type': grant_type,
'target': target,
'scope': 'openid',
'api_type': api_type,
}
if id_token:
data.update({'id_token': id_token})
elif refresh_token:
data.update({'refresh_token': refresh_token})
else:
raise ValueError('Either id_token or refresh_token must '
'have a value')
return self.post(
'https://%s/delegation' % self.domain,
headers={'Content-Type': 'application/json'},
data=data
)
|
305969cedb966d1e5cd340d531727bb984ac35a8 | whitenoise/generators/sqlalchemy.py | whitenoise/generators/sqlalchemy.py | import random
from whitenoise.generators import BaseGenerator
class SelectGenerator(BaseGenerator):
'''
Creates a value by selecting from another SQLAlchemy table
Depends on SQLAlchemy, and receiving a session object from the Fixture runner
the SQLAlchemy fixture runner handles this for us
Receives the name of another class to lookup. If the
query returns more than one option, either random or the 1st is selected
(default is random)
'''
def __init__(self, model, random=True, *args, **kwargs):
super().__init__(*args, **kwargs)
self.session = None
self.model = model
self.random = random
def generate(self):
if(self.session is None):
raise ValueError('You must set the session property before using this generator')
_query = self.session.query(self.model).all()
if self.random:
return random.SystemRandom().choice(_query)
else:
return _query[0]
| import random
from whitenoise.generators import BaseGenerator
class SelectGenerator(BaseGenerator):
'''
Creates a value by selecting from another SQLAlchemy table
Depends on SQLAlchemy, and receiving a session object from the Fixture runner
the SQLAlchemy fixture runner handles this for us
Receives the name of another class to lookup. If the
query returns more than one option, either random or the 1st is selected
(default is random)
'''
def __init__(self, model, random=True, *args, **kwargs):
super().__init__(*args, **kwargs)
self.session = None
self.model = model
self.random = random
def generate(self):
if(self.session is None):
raise ValueError('You must set the session property before using this generator')
_query = self.session.query(self.model).all()
if self.random:
return random.SystemRandom().choice(_query)
else:
return _query[0]
class LinkGenerator(BaseGenerator):
'''
Creates a list for secondary relationships using link tables by selecting from another SQLAlchemy table
Depends on SQLAlchemy, and receiving a session object from the Fixture runner
the SQLAlchemy fixture runner handles this for us
Receives the name of another class to lookup. If the
query returns more than one option, either random or the 1st is selected
(default is random)
'''
def __init__(self, model, max_map, random=True, *args, **kwargs):
super().__init__(*args, **kwargs)
self.session = None
self.model = model
self.random = random
self.max_map = max_map
def generate(self):
if(self.session is None):
raise ValueError('You must set the session property before using this generator')
_query = self.session.query(self.model).all()
if self.random:
return random.SystemRandom().sample(_query,random.randint(1, max_map))
else:
return [_query[0]] | Add a generator for association tables | Add a generator for association tables
| Python | mit | James1345/white-noise | import random
from whitenoise.generators import BaseGenerator
class SelectGenerator(BaseGenerator):
'''
Creates a value by selecting from another SQLAlchemy table
Depends on SQLAlchemy, and receiving a session object from the Fixture runner
the SQLAlchemy fixture runner handles this for us
Receives the name of another class to lookup. If the
query returns more than one option, either random or the 1st is selected
(default is random)
'''
def __init__(self, model, random=True, *args, **kwargs):
super().__init__(*args, **kwargs)
self.session = None
self.model = model
self.random = random
def generate(self):
if(self.session is None):
raise ValueError('You must set the session property before using this generator')
_query = self.session.query(self.model).all()
if self.random:
return random.SystemRandom().choice(_query)
else:
return _query[0]
+ class LinkGenerator(BaseGenerator):
+ '''
+ Creates a list for secondary relationships using link tables by selecting from another SQLAlchemy table
+ Depends on SQLAlchemy, and receiving a session object from the Fixture runner
+ the SQLAlchemy fixture runner handles this for us
+ Receives the name of another class to lookup. If the
+ query returns more than one option, either random or the 1st is selected
+ (default is random)
+ '''
+ def __init__(self, model, max_map, random=True, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.session = None
+ self.model = model
+ self.random = random
+ self.max_map = max_map
+
+ def generate(self):
+ if(self.session is None):
+ raise ValueError('You must set the session property before using this generator')
+ _query = self.session.query(self.model).all()
+ if self.random:
+ return random.SystemRandom().sample(_query,random.randint(1, max_map))
+ else:
+ return [_query[0]] | Add a generator for association tables | ## Code Before:
import random
from whitenoise.generators import BaseGenerator
class SelectGenerator(BaseGenerator):
'''
Creates a value by selecting from another SQLAlchemy table
Depends on SQLAlchemy, and receiving a session object from the Fixture runner
the SQLAlchemy fixture runner handles this for us
Receives the name of another class to lookup. If the
query returns more than one option, either random or the 1st is selected
(default is random)
'''
def __init__(self, model, random=True, *args, **kwargs):
super().__init__(*args, **kwargs)
self.session = None
self.model = model
self.random = random
def generate(self):
if(self.session is None):
raise ValueError('You must set the session property before using this generator')
_query = self.session.query(self.model).all()
if self.random:
return random.SystemRandom().choice(_query)
else:
return _query[0]
## Instruction:
Add a generator for association tables
## Code After:
import random
from whitenoise.generators import BaseGenerator
class SelectGenerator(BaseGenerator):
'''
Creates a value by selecting from another SQLAlchemy table
Depends on SQLAlchemy, and receiving a session object from the Fixture runner
the SQLAlchemy fixture runner handles this for us
Receives the name of another class to lookup. If the
query returns more than one option, either random or the 1st is selected
(default is random)
'''
def __init__(self, model, random=True, *args, **kwargs):
super().__init__(*args, **kwargs)
self.session = None
self.model = model
self.random = random
def generate(self):
if(self.session is None):
raise ValueError('You must set the session property before using this generator')
_query = self.session.query(self.model).all()
if self.random:
return random.SystemRandom().choice(_query)
else:
return _query[0]
class LinkGenerator(BaseGenerator):
'''
Creates a list for secondary relationships using link tables by selecting from another SQLAlchemy table
Depends on SQLAlchemy, and receiving a session object from the Fixture runner
the SQLAlchemy fixture runner handles this for us
Receives the name of another class to lookup. If the
query returns more than one option, either random or the 1st is selected
(default is random)
'''
def __init__(self, model, max_map, random=True, *args, **kwargs):
super().__init__(*args, **kwargs)
self.session = None
self.model = model
self.random = random
self.max_map = max_map
def generate(self):
if(self.session is None):
raise ValueError('You must set the session property before using this generator')
_query = self.session.query(self.model).all()
if self.random:
return random.SystemRandom().sample(_query,random.randint(1, max_map))
else:
return [_query[0]] |
ee5ab61090cef682f37631a8c3f5764bdda63772 | xpserver_web/tests/unit/test_web.py | xpserver_web/tests/unit/test_web.py | from django.core.urlresolvers import resolve
from xpserver_web.views import main
def test_root_resolves_to_hello_world():
found = resolve('/')
assert found.func == main
| from django.core.urlresolvers import resolve
from xpserver_web.views import main, register
def test_root_resolves_to_main():
found = resolve('/')
assert found.func == main
def test_register_resolves_to_main():
found = resolve('/register/')
assert found.func == register
| Add unit test for register | Add unit test for register
| Python | mit | xp2017-hackergarden/server,xp2017-hackergarden/server,xp2017-hackergarden/server,xp2017-hackergarden/server | from django.core.urlresolvers import resolve
- from xpserver_web.views import main
+ from xpserver_web.views import main, register
- def test_root_resolves_to_hello_world():
+ def test_root_resolves_to_main():
found = resolve('/')
assert found.func == main
+ def test_register_resolves_to_main():
+ found = resolve('/register/')
+ assert found.func == register
+ | Add unit test for register | ## Code Before:
from django.core.urlresolvers import resolve
from xpserver_web.views import main
def test_root_resolves_to_hello_world():
found = resolve('/')
assert found.func == main
## Instruction:
Add unit test for register
## Code After:
from django.core.urlresolvers import resolve
from xpserver_web.views import main, register
def test_root_resolves_to_main():
found = resolve('/')
assert found.func == main
def test_register_resolves_to_main():
found = resolve('/register/')
assert found.func == register
|
e120858d5cb123e9f3422ddb15ce79bde8d05d64 | statsd/__init__.py | statsd/__init__.py | import socket
try:
from django.conf import settings
except ImportError:
settings = None
from client import StatsClient
__all__ = ['StatsClient', 'statsd']
VERSION = (0, 4, 0)
__version__ = '.'.join(map(str, VERSION))
if settings:
try:
host = getattr(settings, 'STATSD_HOST', 'localhost')
port = getattr(settings, 'STATSD_PORT', 8125)
prefix = getattr(settings, 'STATSD_PREFIX', None)
statsd = StatsClient(host, port, prefix)
except (socket.error, socket.gaierror, ImportError):
statsd = None
| import socket
import os
try:
from django.conf import settings
except ImportError:
settings = None
from client import StatsClient
__all__ = ['StatsClient', 'statsd']
VERSION = (0, 4, 0)
__version__ = '.'.join(map(str, VERSION))
if settings:
try:
host = getattr(settings, 'STATSD_HOST', 'localhost')
port = getattr(settings, 'STATSD_PORT', 8125)
prefix = getattr(settings, 'STATSD_PREFIX', None)
statsd = StatsClient(host, port, prefix)
except (socket.error, socket.gaierror, ImportError):
try:
host = os.environ['STATSD_HOST']
port = os.environ['STATSD_PORT']
prefix = os.environ.get('STATSD_PREFIX')
statsd = StatsClient(host, port, prefix)
except (socket.error, socket.gaierror, KeyError):
statsd = None
| Read settings from environment, if available | Read settings from environment, if available
| Python | mit | lyft/pystatsd,jsocol/pystatsd,deathowl/pystatsd,Khan/pystatsd,Khan/pystatsd,smarkets/pystatsd,wujuguang/pystatsd,lyft/pystatsd | import socket
+ import os
try:
from django.conf import settings
except ImportError:
settings = None
from client import StatsClient
__all__ = ['StatsClient', 'statsd']
VERSION = (0, 4, 0)
__version__ = '.'.join(map(str, VERSION))
if settings:
try:
host = getattr(settings, 'STATSD_HOST', 'localhost')
port = getattr(settings, 'STATSD_PORT', 8125)
prefix = getattr(settings, 'STATSD_PREFIX', None)
statsd = StatsClient(host, port, prefix)
except (socket.error, socket.gaierror, ImportError):
+ try:
+ host = os.environ['STATSD_HOST']
+ port = os.environ['STATSD_PORT']
+ prefix = os.environ.get('STATSD_PREFIX')
+ statsd = StatsClient(host, port, prefix)
+ except (socket.error, socket.gaierror, KeyError):
- statsd = None
+ statsd = None
+ | Read settings from environment, if available | ## Code Before:
import socket
try:
from django.conf import settings
except ImportError:
settings = None
from client import StatsClient
__all__ = ['StatsClient', 'statsd']
VERSION = (0, 4, 0)
__version__ = '.'.join(map(str, VERSION))
if settings:
try:
host = getattr(settings, 'STATSD_HOST', 'localhost')
port = getattr(settings, 'STATSD_PORT', 8125)
prefix = getattr(settings, 'STATSD_PREFIX', None)
statsd = StatsClient(host, port, prefix)
except (socket.error, socket.gaierror, ImportError):
statsd = None
## Instruction:
Read settings from environment, if available
## Code After:
import socket
import os
try:
from django.conf import settings
except ImportError:
settings = None
from client import StatsClient
__all__ = ['StatsClient', 'statsd']
VERSION = (0, 4, 0)
__version__ = '.'.join(map(str, VERSION))
if settings:
try:
host = getattr(settings, 'STATSD_HOST', 'localhost')
port = getattr(settings, 'STATSD_PORT', 8125)
prefix = getattr(settings, 'STATSD_PREFIX', None)
statsd = StatsClient(host, port, prefix)
except (socket.error, socket.gaierror, ImportError):
try:
host = os.environ['STATSD_HOST']
port = os.environ['STATSD_PORT']
prefix = os.environ.get('STATSD_PREFIX')
statsd = StatsClient(host, port, prefix)
except (socket.error, socket.gaierror, KeyError):
statsd = None
|
7d3ffe4582a5b4032f9a59a3ea8edfded57a7a1f | src/nodeconductor_openstack/openstack/migrations/0031_tenant_backup_storage.py | src/nodeconductor_openstack/openstack/migrations/0031_tenant_backup_storage.py | from __future__ import unicode_literals
from django.contrib.contenttypes.models import ContentType
from django.db import migrations
from nodeconductor.quotas import models as quotas_models
from .. import models
def cleanup_tenant_quotas(apps, schema_editor):
for obj in models.Tenant.objects.all():
quotas_names = models.Tenant.QUOTAS_NAMES + [f.name for f in models.Tenant.get_quotas_fields()]
obj.quotas.exclude(name__in=quotas_names).delete()
class Migration(migrations.Migration):
dependencies = [
('openstack', '0030_subnet_dns_nameservers'),
]
operations = [
migrations.RunPython(cleanup_tenant_quotas),
]
| from __future__ import unicode_literals
from django.db import migrations
from .. import models
def cleanup_tenant_quotas(apps, schema_editor):
quota_names = models.Tenant.get_quotas_names()
for obj in models.Tenant.objects.all():
obj.quotas.exclude(name__in=quota_names).delete()
class Migration(migrations.Migration):
dependencies = [
('openstack', '0030_subnet_dns_nameservers'),
]
operations = [
migrations.RunPython(cleanup_tenant_quotas),
]
| Clean up quota cleanup migration | Clean up quota cleanup migration [WAL-433]
| Python | mit | opennode/nodeconductor-openstack | from __future__ import unicode_literals
- from django.contrib.contenttypes.models import ContentType
from django.db import migrations
-
- from nodeconductor.quotas import models as quotas_models
from .. import models
def cleanup_tenant_quotas(apps, schema_editor):
+ quota_names = models.Tenant.get_quotas_names()
for obj in models.Tenant.objects.all():
- quotas_names = models.Tenant.QUOTAS_NAMES + [f.name for f in models.Tenant.get_quotas_fields()]
- obj.quotas.exclude(name__in=quotas_names).delete()
+ obj.quotas.exclude(name__in=quota_names).delete()
class Migration(migrations.Migration):
dependencies = [
('openstack', '0030_subnet_dns_nameservers'),
]
operations = [
migrations.RunPython(cleanup_tenant_quotas),
]
| Clean up quota cleanup migration | ## Code Before:
from __future__ import unicode_literals
from django.contrib.contenttypes.models import ContentType
from django.db import migrations
from nodeconductor.quotas import models as quotas_models
from .. import models
def cleanup_tenant_quotas(apps, schema_editor):
for obj in models.Tenant.objects.all():
quotas_names = models.Tenant.QUOTAS_NAMES + [f.name for f in models.Tenant.get_quotas_fields()]
obj.quotas.exclude(name__in=quotas_names).delete()
class Migration(migrations.Migration):
dependencies = [
('openstack', '0030_subnet_dns_nameservers'),
]
operations = [
migrations.RunPython(cleanup_tenant_quotas),
]
## Instruction:
Clean up quota cleanup migration
## Code After:
from __future__ import unicode_literals
from django.db import migrations
from .. import models
def cleanup_tenant_quotas(apps, schema_editor):
quota_names = models.Tenant.get_quotas_names()
for obj in models.Tenant.objects.all():
obj.quotas.exclude(name__in=quota_names).delete()
class Migration(migrations.Migration):
dependencies = [
('openstack', '0030_subnet_dns_nameservers'),
]
operations = [
migrations.RunPython(cleanup_tenant_quotas),
]
|
e45fff968f37f558a49cf82b582d1f514a97b5af | tests/test_pool.py | tests/test_pool.py | import random
import unittest
from aioes.pool import RandomSelector, RoundRobinSelector
class TestRandomSelector(unittest.TestCase):
def setUp(self):
random.seed(123456)
def tearDown(self):
random.seed(None)
def test_select(self):
s = RandomSelector()
r = s.select([1, 2, 3])
self.assertEqual(2, r)
class TestRoundRobinSelector(unittest.TestCase):
def test_select(self):
s = RoundRobinSelector()
r = s.select([1, 2, 3])
self.assertEqual(2, r)
r = s.select([1, 2, 3])
self.assertEqual(3, r)
r = s.select([1, 2, 3])
self.assertEqual(1, r)
r = s.select([1, 2, 3])
self.assertEqual(2, r)
| import asyncio
import random
import unittest
from aioes.pool import RandomSelector, RoundRobinSelector, ConnectionPool
from aioes.transport import Endpoint
from aioes.connection import Connection
class TestRandomSelector(unittest.TestCase):
def setUp(self):
random.seed(123456)
def tearDown(self):
random.seed(None)
def test_select(self):
s = RandomSelector()
r = s.select([1, 2, 3])
self.assertEqual(2, r)
class TestRoundRobinSelector(unittest.TestCase):
def test_select(self):
s = RoundRobinSelector()
r = s.select([1, 2, 3])
self.assertEqual(2, r)
r = s.select([1, 2, 3])
self.assertEqual(3, r)
r = s.select([1, 2, 3])
self.assertEqual(1, r)
r = s.select([1, 2, 3])
self.assertEqual(2, r)
class TestConnectionPool(unittest.TestCase):
def setUp(self):
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(None)
def tearDown(self):
self.loop.close()
def make_pool(self):
conn = Connection(Endpoint('localhost', 9200), loop=self.loop)
pool = ConnectionPool([conn], loop=self.loop)
self.addCleanup(pool.close)
return pool
def test_ctor(self):
pool = self.make_pool()
self.assertAlmostEqual(60, pool.dead_timeout)
self.assertAlmostEqual(5, pool.timeout_cutoff)
| Add more tests for pool | Add more tests for pool
| Python | apache-2.0 | aio-libs/aioes | + import asyncio
import random
import unittest
- from aioes.pool import RandomSelector, RoundRobinSelector
+ from aioes.pool import RandomSelector, RoundRobinSelector, ConnectionPool
+ from aioes.transport import Endpoint
+ from aioes.connection import Connection
class TestRandomSelector(unittest.TestCase):
def setUp(self):
random.seed(123456)
def tearDown(self):
random.seed(None)
def test_select(self):
s = RandomSelector()
r = s.select([1, 2, 3])
self.assertEqual(2, r)
class TestRoundRobinSelector(unittest.TestCase):
def test_select(self):
s = RoundRobinSelector()
r = s.select([1, 2, 3])
self.assertEqual(2, r)
r = s.select([1, 2, 3])
self.assertEqual(3, r)
r = s.select([1, 2, 3])
self.assertEqual(1, r)
r = s.select([1, 2, 3])
self.assertEqual(2, r)
+
+ class TestConnectionPool(unittest.TestCase):
+
+ def setUp(self):
+ self.loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(None)
+
+ def tearDown(self):
+ self.loop.close()
+
+ def make_pool(self):
+ conn = Connection(Endpoint('localhost', 9200), loop=self.loop)
+ pool = ConnectionPool([conn], loop=self.loop)
+ self.addCleanup(pool.close)
+ return pool
+
+ def test_ctor(self):
+ pool = self.make_pool()
+ self.assertAlmostEqual(60, pool.dead_timeout)
+ self.assertAlmostEqual(5, pool.timeout_cutoff)
+ | Add more tests for pool | ## Code Before:
import random
import unittest
from aioes.pool import RandomSelector, RoundRobinSelector
class TestRandomSelector(unittest.TestCase):
def setUp(self):
random.seed(123456)
def tearDown(self):
random.seed(None)
def test_select(self):
s = RandomSelector()
r = s.select([1, 2, 3])
self.assertEqual(2, r)
class TestRoundRobinSelector(unittest.TestCase):
def test_select(self):
s = RoundRobinSelector()
r = s.select([1, 2, 3])
self.assertEqual(2, r)
r = s.select([1, 2, 3])
self.assertEqual(3, r)
r = s.select([1, 2, 3])
self.assertEqual(1, r)
r = s.select([1, 2, 3])
self.assertEqual(2, r)
## Instruction:
Add more tests for pool
## Code After:
import asyncio
import random
import unittest
from aioes.pool import RandomSelector, RoundRobinSelector, ConnectionPool
from aioes.transport import Endpoint
from aioes.connection import Connection
class TestRandomSelector(unittest.TestCase):
def setUp(self):
random.seed(123456)
def tearDown(self):
random.seed(None)
def test_select(self):
s = RandomSelector()
r = s.select([1, 2, 3])
self.assertEqual(2, r)
class TestRoundRobinSelector(unittest.TestCase):
def test_select(self):
s = RoundRobinSelector()
r = s.select([1, 2, 3])
self.assertEqual(2, r)
r = s.select([1, 2, 3])
self.assertEqual(3, r)
r = s.select([1, 2, 3])
self.assertEqual(1, r)
r = s.select([1, 2, 3])
self.assertEqual(2, r)
class TestConnectionPool(unittest.TestCase):
def setUp(self):
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(None)
def tearDown(self):
self.loop.close()
def make_pool(self):
conn = Connection(Endpoint('localhost', 9200), loop=self.loop)
pool = ConnectionPool([conn], loop=self.loop)
self.addCleanup(pool.close)
return pool
def test_ctor(self):
pool = self.make_pool()
self.assertAlmostEqual(60, pool.dead_timeout)
self.assertAlmostEqual(5, pool.timeout_cutoff)
|
aa8820bd7b78ba5729e0a7a17e43b87bfd033980 | tests/runtests.py | tests/runtests.py |
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import unittest
import util_tests
import jsonpickle_test
import thirdparty_tests
def suite():
suite = unittest.TestSuite()
suite.addTest(util_tests.suite())
suite.addTest(jsonpickle_test.suite())
suite.addTest(thirdparty_tests.suite())
return suite
def main():
#unittest.main(defaultTest='suite')
unittest.TextTestRunner(verbosity=2).run(suite())
if __name__ == '__main__':
main()
|
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import unittest
import util_tests
import jsonpickle_test
import thirdparty_tests
def suite():
suite = unittest.TestSuite()
suite.addTest(util_tests.suite())
suite.addTest(jsonpickle_test.suite())
suite.addTest(thirdparty_tests.suite())
return suite
def main():
#unittest.main(defaultTest='suite')
return unittest.TextTestRunner(verbosity=2).run(suite())
if __name__ == '__main__':
sys.exit(not main().wasSuccessful())
| Return correct status code to shell when tests fail. | Return correct status code to shell when tests fail.
When tests fail (due to e.g. missing feedparser), then the exit code of tests/runtests.py is 0, which is treated by shell as
success. Patch by Arfrever Frehtes Taifersar Arahesis.
| Python | bsd-3-clause | mandx/jsonpickle,dongguangming/jsonpickle,dongguangming/jsonpickle,mandx/jsonpickle,mandx/jsonpickle,dongguangming/jsonpickle,mandx/jsonpickle,dongguangming/jsonpickle |
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import unittest
import util_tests
import jsonpickle_test
import thirdparty_tests
def suite():
suite = unittest.TestSuite()
suite.addTest(util_tests.suite())
suite.addTest(jsonpickle_test.suite())
suite.addTest(thirdparty_tests.suite())
return suite
def main():
#unittest.main(defaultTest='suite')
- unittest.TextTestRunner(verbosity=2).run(suite())
+ return unittest.TextTestRunner(verbosity=2).run(suite())
if __name__ == '__main__':
- main()
+ sys.exit(not main().wasSuccessful())
| Return correct status code to shell when tests fail. | ## Code Before:
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import unittest
import util_tests
import jsonpickle_test
import thirdparty_tests
def suite():
suite = unittest.TestSuite()
suite.addTest(util_tests.suite())
suite.addTest(jsonpickle_test.suite())
suite.addTest(thirdparty_tests.suite())
return suite
def main():
#unittest.main(defaultTest='suite')
unittest.TextTestRunner(verbosity=2).run(suite())
if __name__ == '__main__':
main()
## Instruction:
Return correct status code to shell when tests fail.
## Code After:
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import unittest
import util_tests
import jsonpickle_test
import thirdparty_tests
def suite():
suite = unittest.TestSuite()
suite.addTest(util_tests.suite())
suite.addTest(jsonpickle_test.suite())
suite.addTest(thirdparty_tests.suite())
return suite
def main():
#unittest.main(defaultTest='suite')
return unittest.TextTestRunner(verbosity=2).run(suite())
if __name__ == '__main__':
sys.exit(not main().wasSuccessful())
|
4bac0cfeb2d8def6183b4249f0ea93329b282cb4 | botbot/envchecks.py | botbot/envchecks.py | """Tools for checking environment variables"""
import os
from configparser import NoOptionError
from .config import CONFIG
def path_sufficient():
"""
Checks whether all of the given paths are in the PATH environment
variable
"""
paths = CONFIG.get('important', 'pathitems').split(':')
for path in paths:
if path not in os.environ['PATH']:
return ('PROB_PATH_NOT_COMPLETE', path)
| """Tools for checking environment variables"""
import os
from configparser import NoOptionError
from .config import CONFIG
def path_sufficient():
"""
Checks whether all of the given paths are in the PATH environment
variable
"""
paths = CONFIG.get('important', 'pathitems').split(':')
for path in paths:
if path not in os.environ['PATH']:
return ('PROB_PATH_NOT_COMPLETE', path)
def ld_lib_path_sufficient():
"""
Checks whether all of the given paths are in the LD_LIBRARY_PATH
einvironment variable
"""
paths = CONFIG.get('important', 'ldlibitems').split(':')
for path in paths:
if path not in os.environ['LD_LIBRARY_PATH']:
return ('PROB_LD_PATH_NOT_COMPLETE', path)
| Add checker for LD_LIBRARY_PATH env variable | Add checker for LD_LIBRARY_PATH env variable
| Python | mit | jackstanek/BotBot,jackstanek/BotBot | """Tools for checking environment variables"""
import os
from configparser import NoOptionError
from .config import CONFIG
def path_sufficient():
"""
Checks whether all of the given paths are in the PATH environment
variable
"""
paths = CONFIG.get('important', 'pathitems').split(':')
for path in paths:
if path not in os.environ['PATH']:
return ('PROB_PATH_NOT_COMPLETE', path)
+ def ld_lib_path_sufficient():
+ """
+ Checks whether all of the given paths are in the LD_LIBRARY_PATH
+ einvironment variable
+ """
+ paths = CONFIG.get('important', 'ldlibitems').split(':')
+ for path in paths:
+ if path not in os.environ['LD_LIBRARY_PATH']:
+ return ('PROB_LD_PATH_NOT_COMPLETE', path)
+ | Add checker for LD_LIBRARY_PATH env variable | ## Code Before:
"""Tools for checking environment variables"""
import os
from configparser import NoOptionError
from .config import CONFIG
def path_sufficient():
"""
Checks whether all of the given paths are in the PATH environment
variable
"""
paths = CONFIG.get('important', 'pathitems').split(':')
for path in paths:
if path not in os.environ['PATH']:
return ('PROB_PATH_NOT_COMPLETE', path)
## Instruction:
Add checker for LD_LIBRARY_PATH env variable
## Code After:
"""Tools for checking environment variables"""
import os
from configparser import NoOptionError
from .config import CONFIG
def path_sufficient():
"""
Checks whether all of the given paths are in the PATH environment
variable
"""
paths = CONFIG.get('important', 'pathitems').split(':')
for path in paths:
if path not in os.environ['PATH']:
return ('PROB_PATH_NOT_COMPLETE', path)
def ld_lib_path_sufficient():
"""
Checks whether all of the given paths are in the LD_LIBRARY_PATH
einvironment variable
"""
paths = CONFIG.get('important', 'ldlibitems').split(':')
for path in paths:
if path not in os.environ['LD_LIBRARY_PATH']:
return ('PROB_LD_PATH_NOT_COMPLETE', path)
|
805e67ad540e3072929dea30b8894af87fc622ef | uiharu/__init__.py | uiharu/__init__.py | import logging
from flask import Flask
log = logging.getLogger(__name__)
def create_app(config_dict):
app = Flask(__name__, static_folder=None)
app.config.update(**config_dict)
from uiharu.api.views import api as api_blueprint
from uiharu.weather.views import weather as weather_blueprint
app.register_blueprint(api_blueprint, url_prefix='/api/v1')
app.register_blueprint(weather_blueprint)
log.info(app.url_map)
return app
| import logging
log = logging.getLogger(__name__)
| Remove flask usage in init | Remove flask usage in init
| Python | mit | kennydo/uiharu | import logging
-
- from flask import Flask
log = logging.getLogger(__name__)
- def create_app(config_dict):
- app = Flask(__name__, static_folder=None)
- app.config.update(**config_dict)
-
- from uiharu.api.views import api as api_blueprint
- from uiharu.weather.views import weather as weather_blueprint
-
- app.register_blueprint(api_blueprint, url_prefix='/api/v1')
- app.register_blueprint(weather_blueprint)
-
- log.info(app.url_map)
-
- return app
- | Remove flask usage in init | ## Code Before:
import logging
from flask import Flask
log = logging.getLogger(__name__)
def create_app(config_dict):
app = Flask(__name__, static_folder=None)
app.config.update(**config_dict)
from uiharu.api.views import api as api_blueprint
from uiharu.weather.views import weather as weather_blueprint
app.register_blueprint(api_blueprint, url_prefix='/api/v1')
app.register_blueprint(weather_blueprint)
log.info(app.url_map)
return app
## Instruction:
Remove flask usage in init
## Code After:
import logging
log = logging.getLogger(__name__)
|
b047685088b9179e0c784114ff4a41509dbfdf7d | tests/test_utils.py | tests/test_utils.py | from django_logutils.utils import add_items_to_message
def test_add_items_to_message():
msg = "log message"
items = {'user': 'benny', 'email': '[email protected]'}
msg = add_items_to_message(msg, items)
assert msg == 'log message user=benny [email protected]'
| from django_logutils.utils import add_items_to_message
def test_add_items_to_message():
msg = "log message"
items = {'user': 'benny', 'email': '[email protected]'}
msg = add_items_to_message(msg, items)
assert msg.startswith('log message')
assert 'user=benny' in msg
assert '[email protected]' in msg
def test_add_items_to_message_with_empty_items():
msg = "log message"
items = {}
msg = add_items_to_message(msg, items)
assert msg == 'log message'
| Fix utils test and add an extra test. | Fix utils test and add an extra test.
| Python | bsd-3-clause | jsmits/django-logutils,jsmits/django-logutils | from django_logutils.utils import add_items_to_message
def test_add_items_to_message():
msg = "log message"
items = {'user': 'benny', 'email': '[email protected]'}
msg = add_items_to_message(msg, items)
- assert msg == 'log message user=benny [email protected]'
+ assert msg.startswith('log message')
+ assert 'user=benny' in msg
+ assert '[email protected]' in msg
+
+ def test_add_items_to_message_with_empty_items():
+ msg = "log message"
+ items = {}
+ msg = add_items_to_message(msg, items)
+ assert msg == 'log message'
+ | Fix utils test and add an extra test. | ## Code Before:
from django_logutils.utils import add_items_to_message
def test_add_items_to_message():
msg = "log message"
items = {'user': 'benny', 'email': '[email protected]'}
msg = add_items_to_message(msg, items)
assert msg == 'log message user=benny [email protected]'
## Instruction:
Fix utils test and add an extra test.
## Code After:
from django_logutils.utils import add_items_to_message
def test_add_items_to_message():
msg = "log message"
items = {'user': 'benny', 'email': '[email protected]'}
msg = add_items_to_message(msg, items)
assert msg.startswith('log message')
assert 'user=benny' in msg
assert '[email protected]' in msg
def test_add_items_to_message_with_empty_items():
msg = "log message"
items = {}
msg = add_items_to_message(msg, items)
assert msg == 'log message'
|
34db760c5b763ad2df02398d58ea417b47b785e7 | geotrek/zoning/views.py | geotrek/zoning/views.py | from django.shortcuts import get_object_or_404
from django.views.decorators.cache import cache_page
from django.conf import settings
from django.utils.decorators import method_decorator
from djgeojson.views import GeoJSONLayerView
from .models import City, RestrictedArea, RestrictedAreaType, District
class LandLayerMixin(object):
srid = settings.API_SRID
precision = settings.LAYER_PRECISION_LAND
simplify = settings.LAYER_SIMPLIFY_LAND
@method_decorator(cache_page(settings.CACHE_TIMEOUT_LAND_LAYERS, cache="fat"))
def dispatch(self, request, *args, **kwargs):
return super(LandLayerMixin, self).dispatch(request, *args, **kwargs)
class CityGeoJSONLayer(LandLayerMixin, GeoJSONLayerView):
model = City
class RestrictedAreaGeoJSONLayer(LandLayerMixin, GeoJSONLayerView):
model = RestrictedArea
class RestrictedAreaTypeGeoJSONLayer(LandLayerMixin, GeoJSONLayerView):
model = RestrictedArea
def get_queryset(self):
type_pk = self.kwargs['type_pk']
qs = super(RestrictedAreaTypeGeoJSONLayer, self).get_queryset()
get_object_or_404(RestrictedAreaType, pk=type_pk)
return qs.filter(area_type=type_pk)
class DistrictGeoJSONLayer(LandLayerMixin, GeoJSONLayerView):
model = District
properties = ['name']
| from django.shortcuts import get_object_or_404
from django.views.decorators.cache import cache_page
from django.conf import settings
from django.utils.decorators import method_decorator
from djgeojson.views import GeoJSONLayerView
from .models import City, RestrictedArea, RestrictedAreaType, District
class LandLayerMixin(object):
srid = settings.API_SRID
precision = settings.LAYER_PRECISION_LAND
simplify = settings.LAYER_SIMPLIFY_LAND
@method_decorator(cache_page(settings.CACHE_TIMEOUT_LAND_LAYERS,
cache=settings.MAPENTITY_CONFIG['GEOJSON_LAYERS_CACHE_BACKEND']))
def dispatch(self, request, *args, **kwargs):
return super(LandLayerMixin, self).dispatch(request, *args, **kwargs)
class CityGeoJSONLayer(LandLayerMixin, GeoJSONLayerView):
model = City
class RestrictedAreaGeoJSONLayer(LandLayerMixin, GeoJSONLayerView):
model = RestrictedArea
class RestrictedAreaTypeGeoJSONLayer(LandLayerMixin, GeoJSONLayerView):
model = RestrictedArea
def get_queryset(self):
type_pk = self.kwargs['type_pk']
qs = super(RestrictedAreaTypeGeoJSONLayer, self).get_queryset()
get_object_or_404(RestrictedAreaType, pk=type_pk)
return qs.filter(area_type=type_pk)
class DistrictGeoJSONLayer(LandLayerMixin, GeoJSONLayerView):
model = District
properties = ['name']
| Change cache land, use settings mapentity | Change cache land, use settings mapentity
| Python | bsd-2-clause | GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek | from django.shortcuts import get_object_or_404
from django.views.decorators.cache import cache_page
from django.conf import settings
from django.utils.decorators import method_decorator
from djgeojson.views import GeoJSONLayerView
from .models import City, RestrictedArea, RestrictedAreaType, District
class LandLayerMixin(object):
srid = settings.API_SRID
precision = settings.LAYER_PRECISION_LAND
simplify = settings.LAYER_SIMPLIFY_LAND
- @method_decorator(cache_page(settings.CACHE_TIMEOUT_LAND_LAYERS, cache="fat"))
+ @method_decorator(cache_page(settings.CACHE_TIMEOUT_LAND_LAYERS,
+ cache=settings.MAPENTITY_CONFIG['GEOJSON_LAYERS_CACHE_BACKEND']))
def dispatch(self, request, *args, **kwargs):
return super(LandLayerMixin, self).dispatch(request, *args, **kwargs)
class CityGeoJSONLayer(LandLayerMixin, GeoJSONLayerView):
model = City
class RestrictedAreaGeoJSONLayer(LandLayerMixin, GeoJSONLayerView):
model = RestrictedArea
class RestrictedAreaTypeGeoJSONLayer(LandLayerMixin, GeoJSONLayerView):
model = RestrictedArea
def get_queryset(self):
type_pk = self.kwargs['type_pk']
qs = super(RestrictedAreaTypeGeoJSONLayer, self).get_queryset()
get_object_or_404(RestrictedAreaType, pk=type_pk)
return qs.filter(area_type=type_pk)
class DistrictGeoJSONLayer(LandLayerMixin, GeoJSONLayerView):
model = District
properties = ['name']
| Change cache land, use settings mapentity | ## Code Before:
from django.shortcuts import get_object_or_404
from django.views.decorators.cache import cache_page
from django.conf import settings
from django.utils.decorators import method_decorator
from djgeojson.views import GeoJSONLayerView
from .models import City, RestrictedArea, RestrictedAreaType, District
class LandLayerMixin(object):
srid = settings.API_SRID
precision = settings.LAYER_PRECISION_LAND
simplify = settings.LAYER_SIMPLIFY_LAND
@method_decorator(cache_page(settings.CACHE_TIMEOUT_LAND_LAYERS, cache="fat"))
def dispatch(self, request, *args, **kwargs):
return super(LandLayerMixin, self).dispatch(request, *args, **kwargs)
class CityGeoJSONLayer(LandLayerMixin, GeoJSONLayerView):
model = City
class RestrictedAreaGeoJSONLayer(LandLayerMixin, GeoJSONLayerView):
model = RestrictedArea
class RestrictedAreaTypeGeoJSONLayer(LandLayerMixin, GeoJSONLayerView):
model = RestrictedArea
def get_queryset(self):
type_pk = self.kwargs['type_pk']
qs = super(RestrictedAreaTypeGeoJSONLayer, self).get_queryset()
get_object_or_404(RestrictedAreaType, pk=type_pk)
return qs.filter(area_type=type_pk)
class DistrictGeoJSONLayer(LandLayerMixin, GeoJSONLayerView):
model = District
properties = ['name']
## Instruction:
Change cache land, use settings mapentity
## Code After:
from django.shortcuts import get_object_or_404
from django.views.decorators.cache import cache_page
from django.conf import settings
from django.utils.decorators import method_decorator
from djgeojson.views import GeoJSONLayerView
from .models import City, RestrictedArea, RestrictedAreaType, District
class LandLayerMixin(object):
srid = settings.API_SRID
precision = settings.LAYER_PRECISION_LAND
simplify = settings.LAYER_SIMPLIFY_LAND
@method_decorator(cache_page(settings.CACHE_TIMEOUT_LAND_LAYERS,
cache=settings.MAPENTITY_CONFIG['GEOJSON_LAYERS_CACHE_BACKEND']))
def dispatch(self, request, *args, **kwargs):
return super(LandLayerMixin, self).dispatch(request, *args, **kwargs)
class CityGeoJSONLayer(LandLayerMixin, GeoJSONLayerView):
model = City
class RestrictedAreaGeoJSONLayer(LandLayerMixin, GeoJSONLayerView):
model = RestrictedArea
class RestrictedAreaTypeGeoJSONLayer(LandLayerMixin, GeoJSONLayerView):
model = RestrictedArea
def get_queryset(self):
type_pk = self.kwargs['type_pk']
qs = super(RestrictedAreaTypeGeoJSONLayer, self).get_queryset()
get_object_or_404(RestrictedAreaType, pk=type_pk)
return qs.filter(area_type=type_pk)
class DistrictGeoJSONLayer(LandLayerMixin, GeoJSONLayerView):
model = District
properties = ['name']
|
3875b1ec7d056d337cc1c02d9567cd7ff1ae9748 | utils/sub8_ros_tools/sub8_ros_tools/init_helpers.py | utils/sub8_ros_tools/sub8_ros_tools/init_helpers.py | import rospy
from time import time
def wait_for_param(param_name, timeout=None, poll_rate=0.1):
'''Blocking wait for a parameter named $parameter_name to exist
Poll at frequency $poll_rate
Once the parameter exists, return get and return it.
This function intentionally leaves failure logging duties to the developer
'''
start_time = time()
rate = rospy.Rate(poll_rate)
while not rospy.is_shutdown():
# Check if the parameter now exists
if rospy.has_param(param_name):
return rospy.get_param(param_name)
# If we exceed a defined timeout, return None
if timeout is not None:
if time() - start_time > timeout:
return None
# Continue to poll at poll_rate
rate.sleep() | import rospy
import rostest
import time
def wait_for_param(param_name, timeout=None, poll_rate=0.1):
'''Blocking wait for a parameter named $parameter_name to exist
Poll at frequency $poll_rate
Once the parameter exists, return get and return it.
This function intentionally leaves failure logging duties to the developer
'''
start_time = time.time()
rate = rospy.Rate(poll_rate)
while not rospy.is_shutdown():
# Check if the parameter now exists
if rospy.has_param(param_name):
return rospy.get_param(param_name)
# If we exceed a defined timeout, return None
if timeout is not None:
if time.time() - start_time > timeout:
return None
# Continue to poll at poll_rate
rate.sleep()
def wait_for_subscriber(node_name, topic, timeout=5.0):
'''Blocks until $node_name subscribes to $topic
Useful mostly in integration tests --
I would counsel against use elsewhere
'''
end_time = time.time() + timeout
resolved_topic = rospy.resolve_name(topic)
resolved_node = rospy.resolve_name(node_name)
# Wait for time-out or ros-shutdown
while (time.time() < end_time) and (not rospy.is_shutdown()):
subscribed = rostest.is_subscriber(
rospy.resolve_name(topic),
rospy.resolve_name(node_name)
)
# Success scenario: node subscribes
if subscribed:
break
time.sleep(0.1)
# Could do this with a while/else
# But chose to explicitly check
success = rostest.is_subscriber(
rospy.resolve_name(topic),
rospy.resolve_name(node_name)
)
return success | Add init-helper 'wait for subscriber' | UTILS: Add init-helper 'wait for subscriber'
For integration-testing purposes it is often useful to wait until a
particular node subscribes to you
| Python | mit | pemami4911/Sub8,pemami4911/Sub8,pemami4911/Sub8 | import rospy
- from time import time
+ import rostest
+ import time
def wait_for_param(param_name, timeout=None, poll_rate=0.1):
'''Blocking wait for a parameter named $parameter_name to exist
Poll at frequency $poll_rate
Once the parameter exists, return get and return it.
This function intentionally leaves failure logging duties to the developer
'''
- start_time = time()
+ start_time = time.time()
rate = rospy.Rate(poll_rate)
while not rospy.is_shutdown():
# Check if the parameter now exists
if rospy.has_param(param_name):
return rospy.get_param(param_name)
# If we exceed a defined timeout, return None
if timeout is not None:
- if time() - start_time > timeout:
+ if time.time() - start_time > timeout:
return None
# Continue to poll at poll_rate
rate.sleep()
+
+
+ def wait_for_subscriber(node_name, topic, timeout=5.0):
+ '''Blocks until $node_name subscribes to $topic
+ Useful mostly in integration tests --
+ I would counsel against use elsewhere
+ '''
+ end_time = time.time() + timeout
+
+ resolved_topic = rospy.resolve_name(topic)
+ resolved_node = rospy.resolve_name(node_name)
+
+ # Wait for time-out or ros-shutdown
+ while (time.time() < end_time) and (not rospy.is_shutdown()):
+ subscribed = rostest.is_subscriber(
+ rospy.resolve_name(topic),
+ rospy.resolve_name(node_name)
+ )
+ # Success scenario: node subscribes
+ if subscribed:
+ break
+ time.sleep(0.1)
+
+ # Could do this with a while/else
+ # But chose to explicitly check
+ success = rostest.is_subscriber(
+ rospy.resolve_name(topic),
+ rospy.resolve_name(node_name)
+ )
+ return success | Add init-helper 'wait for subscriber' | ## Code Before:
import rospy
from time import time
def wait_for_param(param_name, timeout=None, poll_rate=0.1):
'''Blocking wait for a parameter named $parameter_name to exist
Poll at frequency $poll_rate
Once the parameter exists, return get and return it.
This function intentionally leaves failure logging duties to the developer
'''
start_time = time()
rate = rospy.Rate(poll_rate)
while not rospy.is_shutdown():
# Check if the parameter now exists
if rospy.has_param(param_name):
return rospy.get_param(param_name)
# If we exceed a defined timeout, return None
if timeout is not None:
if time() - start_time > timeout:
return None
# Continue to poll at poll_rate
rate.sleep()
## Instruction:
Add init-helper 'wait for subscriber'
## Code After:
import rospy
import rostest
import time
def wait_for_param(param_name, timeout=None, poll_rate=0.1):
'''Blocking wait for a parameter named $parameter_name to exist
Poll at frequency $poll_rate
Once the parameter exists, return get and return it.
This function intentionally leaves failure logging duties to the developer
'''
start_time = time.time()
rate = rospy.Rate(poll_rate)
while not rospy.is_shutdown():
# Check if the parameter now exists
if rospy.has_param(param_name):
return rospy.get_param(param_name)
# If we exceed a defined timeout, return None
if timeout is not None:
if time.time() - start_time > timeout:
return None
# Continue to poll at poll_rate
rate.sleep()
def wait_for_subscriber(node_name, topic, timeout=5.0):
'''Blocks until $node_name subscribes to $topic
Useful mostly in integration tests --
I would counsel against use elsewhere
'''
end_time = time.time() + timeout
resolved_topic = rospy.resolve_name(topic)
resolved_node = rospy.resolve_name(node_name)
# Wait for time-out or ros-shutdown
while (time.time() < end_time) and (not rospy.is_shutdown()):
subscribed = rostest.is_subscriber(
rospy.resolve_name(topic),
rospy.resolve_name(node_name)
)
# Success scenario: node subscribes
if subscribed:
break
time.sleep(0.1)
# Could do this with a while/else
# But chose to explicitly check
success = rostest.is_subscriber(
rospy.resolve_name(topic),
rospy.resolve_name(node_name)
)
return success |
7376a29d69ac78cabc5d392cb748f708ffa0e68c | tests/pretty_format_json_test.py | tests/pretty_format_json_test.py | import tempfile
import pytest
from pre_commit_hooks.pretty_format_json import pretty_format_json
from testing.util import get_resource_path
@pytest.mark.parametrize(('filename', 'expected_retval'), (
('not_pretty_formatted_json.json', 1),
('pretty_formatted_json.json', 0),
))
def test_pretty_format_json(filename, expected_retval):
ret = pretty_format_json([get_resource_path(filename)])
assert ret == expected_retval
def test_autofix_pretty_format_json():
toformat_file = tempfile.NamedTemporaryFile(delete=False, mode='w+')
# copy our file to format there
model_file = open(get_resource_path('not_pretty_formatted_json.json'), 'r')
model_contents = model_file.read()
model_file.close()
toformat_file.write(model_contents)
toformat_file.close()
# now launch the autofix on that file
ret = pretty_format_json(['--autofix', toformat_file.name])
# it should have formatted it
assert ret == 1
# file already good
ret = pretty_format_json([toformat_file.name])
assert ret == 0
def test_badfile_pretty_format_json():
ret = pretty_format_json([get_resource_path('ok_yaml.yaml')])
assert ret == 1
| import io
import pytest
from pre_commit_hooks.pretty_format_json import pretty_format_json
from testing.util import get_resource_path
@pytest.mark.parametrize(('filename', 'expected_retval'), (
('not_pretty_formatted_json.json', 1),
('pretty_formatted_json.json', 0),
))
def test_pretty_format_json(filename, expected_retval):
ret = pretty_format_json([get_resource_path(filename)])
assert ret == expected_retval
def test_autofix_pretty_format_json(tmpdir):
srcfile = tmpdir.join('to_be_json_formatted.json')
with io.open(get_resource_path('not_pretty_formatted_json.json')) as f:
srcfile.write_text(f.read(), 'UTF-8')
# now launch the autofix on that file
ret = pretty_format_json(['--autofix', srcfile.strpath])
# it should have formatted it
assert ret == 1
# file was formatted (shouldn't trigger linter again)
ret = pretty_format_json([srcfile.strpath])
assert ret == 0
def test_badfile_pretty_format_json():
ret = pretty_format_json([get_resource_path('ok_yaml.yaml')])
assert ret == 1
| Write to temp directories in such a way that files get cleaned up | Write to temp directories in such a way that files get cleaned up
| Python | mit | Coverfox/pre-commit-hooks,Harwood/pre-commit-hooks,pre-commit/pre-commit-hooks | - import tempfile
+ import io
import pytest
from pre_commit_hooks.pretty_format_json import pretty_format_json
from testing.util import get_resource_path
@pytest.mark.parametrize(('filename', 'expected_retval'), (
('not_pretty_formatted_json.json', 1),
('pretty_formatted_json.json', 0),
))
def test_pretty_format_json(filename, expected_retval):
ret = pretty_format_json([get_resource_path(filename)])
assert ret == expected_retval
- def test_autofix_pretty_format_json():
+ def test_autofix_pretty_format_json(tmpdir):
+ srcfile = tmpdir.join('to_be_json_formatted.json')
- toformat_file = tempfile.NamedTemporaryFile(delete=False, mode='w+')
-
- # copy our file to format there
- model_file = open(get_resource_path('not_pretty_formatted_json.json'), 'r')
+ with io.open(get_resource_path('not_pretty_formatted_json.json')) as f:
+ srcfile.write_text(f.read(), 'UTF-8')
- model_contents = model_file.read()
- model_file.close()
-
- toformat_file.write(model_contents)
- toformat_file.close()
# now launch the autofix on that file
- ret = pretty_format_json(['--autofix', toformat_file.name])
+ ret = pretty_format_json(['--autofix', srcfile.strpath])
# it should have formatted it
assert ret == 1
- # file already good
+ # file was formatted (shouldn't trigger linter again)
- ret = pretty_format_json([toformat_file.name])
+ ret = pretty_format_json([srcfile.strpath])
assert ret == 0
def test_badfile_pretty_format_json():
ret = pretty_format_json([get_resource_path('ok_yaml.yaml')])
assert ret == 1
| Write to temp directories in such a way that files get cleaned up | ## Code Before:
import tempfile
import pytest
from pre_commit_hooks.pretty_format_json import pretty_format_json
from testing.util import get_resource_path
@pytest.mark.parametrize(('filename', 'expected_retval'), (
('not_pretty_formatted_json.json', 1),
('pretty_formatted_json.json', 0),
))
def test_pretty_format_json(filename, expected_retval):
ret = pretty_format_json([get_resource_path(filename)])
assert ret == expected_retval
def test_autofix_pretty_format_json():
toformat_file = tempfile.NamedTemporaryFile(delete=False, mode='w+')
# copy our file to format there
model_file = open(get_resource_path('not_pretty_formatted_json.json'), 'r')
model_contents = model_file.read()
model_file.close()
toformat_file.write(model_contents)
toformat_file.close()
# now launch the autofix on that file
ret = pretty_format_json(['--autofix', toformat_file.name])
# it should have formatted it
assert ret == 1
# file already good
ret = pretty_format_json([toformat_file.name])
assert ret == 0
def test_badfile_pretty_format_json():
ret = pretty_format_json([get_resource_path('ok_yaml.yaml')])
assert ret == 1
## Instruction:
Write to temp directories in such a way that files get cleaned up
## Code After:
import io
import pytest
from pre_commit_hooks.pretty_format_json import pretty_format_json
from testing.util import get_resource_path
@pytest.mark.parametrize(('filename', 'expected_retval'), (
('not_pretty_formatted_json.json', 1),
('pretty_formatted_json.json', 0),
))
def test_pretty_format_json(filename, expected_retval):
ret = pretty_format_json([get_resource_path(filename)])
assert ret == expected_retval
def test_autofix_pretty_format_json(tmpdir):
srcfile = tmpdir.join('to_be_json_formatted.json')
with io.open(get_resource_path('not_pretty_formatted_json.json')) as f:
srcfile.write_text(f.read(), 'UTF-8')
# now launch the autofix on that file
ret = pretty_format_json(['--autofix', srcfile.strpath])
# it should have formatted it
assert ret == 1
# file was formatted (shouldn't trigger linter again)
ret = pretty_format_json([srcfile.strpath])
assert ret == 0
def test_badfile_pretty_format_json():
ret = pretty_format_json([get_resource_path('ok_yaml.yaml')])
assert ret == 1
|
Subsets and Splits