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
52
3.32k
instruction
stringlengths
16
444
content
stringlengths
133
4.32k
fuzzy_diff
stringlengths
16
3.18k
42755823774f4a57849c54d5812e885dfbeee34c
camelot/roundtable/migrations/0002_add_knight_data.py
camelot/roundtable/migrations/0002_add_knight_data.py
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('roundtable', '0001_initial'), ] operations = [ ]
from __future__ import unicode_literals from django.db import models, migrations def add_knight_data(apps, schema_editor): pass def remove_knight_data(apps, schema_editor): pass class Migration(migrations.Migration): dependencies = [ ('roundtable', '0001_initial'), ] operations = [ migrations.RunPython( add_knight_data, reverse_code=remove_knight_data), ]
Use RunPython operation to perform data migration.
Use RunPython operation to perform data migration.
Python
bsd-2-clause
jambonrose/djangocon2014-updj17
from __future__ import unicode_literals + from django.db import models, migrations - from django.db import models, migrations + + def add_knight_data(apps, schema_editor): + pass + + + def remove_knight_data(apps, schema_editor): + pass class Migration(migrations.Migration): dependencies = [ ('roundtable', '0001_initial'), ] operations = [ + migrations.RunPython( + add_knight_data, + reverse_code=remove_knight_data), ]
Use RunPython operation to perform data migration.
## Code Before: from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('roundtable', '0001_initial'), ] operations = [ ] ## Instruction: Use RunPython operation to perform data migration. ## Code After: from __future__ import unicode_literals from django.db import models, migrations def add_knight_data(apps, schema_editor): pass def remove_knight_data(apps, schema_editor): pass class Migration(migrations.Migration): dependencies = [ ('roundtable', '0001_initial'), ] operations = [ migrations.RunPython( add_knight_data, reverse_code=remove_knight_data), ]
# ... existing code ... from __future__ import unicode_literals from django.db import models, migrations def add_knight_data(apps, schema_editor): pass def remove_knight_data(apps, schema_editor): pass # ... modified code ... operations = [ migrations.RunPython( add_knight_data, reverse_code=remove_knight_data), ] # ... rest of the code ...
a94aa2d9aa58a7c2df289588eb4f16d83725ce8f
numba/exttypes/tests/test_vtables.py
numba/exttypes/tests/test_vtables.py
__author__ = 'mark'
from __future__ import print_function, division, absolute_import import numba as nb from numba import * from numba.minivect.minitypes import FunctionType from numba.exttypes import virtual from numba.exttypes import ordering from numba.exttypes import methodtable from numba.exttypes.signatures import Method from numba.testing.test_support import parametrize, main class py_class(object): pass def myfunc1(a): pass def myfunc2(a, b): pass def myfunc3(a, b, c): pass types = list(nb.numeric) + [object_] array_types = [t[:] for t in types] array_types += [t[:, :] for t in types] array_types += [t[:, :, :] for t in types] all_types = types + array_types def method(func, name, sig): return Method(func, name, sig, False, False) make_methods1 = lambda: [ method(myfunc1, 'method', FunctionType(argtype, [argtype])) for argtype in all_types] make_methods2 = lambda: [ method(myfunc2, 'method', FunctionType(argtype1, [argtype1, argtype2])) for argtype1 in all_types for argtype2 in all_types] def make_table(methods): table = methodtable.VTabType(py_class, []) table.create_method_ordering() for i, method in enumerate(make_methods1()): key = method.name, method.signature.args method.lfunc_pointer = i table.specialized_methods[key] = method assert len(methods) == len(table.specialized_methods) return table def make_hashtable(methods): table = make_table(methods) hashtable = virtual.build_hashing_vtab(table) return hashtable #------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------ @parametrize(make_methods1()) def test_specializations(methods): hashtable = make_hashtable(methods) print(hashtable) for i, method in enumerate(methods): key = virtual.sep201_signature_string(method.signature, method.name) assert hashtable.find_method(key), (i, method, key) if __name__ == '__main__': main()
Add test for hash-based vtable creation
Add test for hash-based vtable creation
Python
bsd-2-clause
cpcloud/numba,ssarangi/numba,jriehl/numba,stuartarchibald/numba,pombredanne/numba,stefanseefeld/numba,stuartarchibald/numba,pitrou/numba,seibert/numba,cpcloud/numba,ssarangi/numba,IntelLabs/numba,IntelLabs/numba,sklam/numba,cpcloud/numba,seibert/numba,GaZ3ll3/numba,stonebig/numba,GaZ3ll3/numba,stonebig/numba,cpcloud/numba,IntelLabs/numba,stefanseefeld/numba,stefanseefeld/numba,gmarkall/numba,pombredanne/numba,stonebig/numba,shiquanwang/numba,pombredanne/numba,pitrou/numba,numba/numba,pitrou/numba,sklam/numba,IntelLabs/numba,gdementen/numba,gdementen/numba,numba/numba,gdementen/numba,stonebig/numba,stefanseefeld/numba,pitrou/numba,numba/numba,stonebig/numba,IntelLabs/numba,pitrou/numba,gmarkall/numba,gmarkall/numba,gdementen/numba,GaZ3ll3/numba,numba/numba,GaZ3ll3/numba,ssarangi/numba,pombredanne/numba,jriehl/numba,jriehl/numba,shiquanwang/numba,stuartarchibald/numba,gmarkall/numba,seibert/numba,stuartarchibald/numba,jriehl/numba,shiquanwang/numba,numba/numba,stefanseefeld/numba,jriehl/numba,sklam/numba,seibert/numba,seibert/numba,GaZ3ll3/numba,stuartarchibald/numba,cpcloud/numba,sklam/numba,pombredanne/numba,ssarangi/numba,gmarkall/numba,gdementen/numba,sklam/numba,ssarangi/numba
- __author__ = 'mark' + from __future__ import print_function, division, absolute_import + import numba as nb + from numba import * + from numba.minivect.minitypes import FunctionType + from numba.exttypes import virtual + from numba.exttypes import ordering + from numba.exttypes import methodtable + from numba.exttypes.signatures import Method + from numba.testing.test_support import parametrize, main + + class py_class(object): + pass + + def myfunc1(a): + pass + + def myfunc2(a, b): + pass + + def myfunc3(a, b, c): + pass + + types = list(nb.numeric) + [object_] + + array_types = [t[:] for t in types] + array_types += [t[:, :] for t in types] + array_types += [t[:, :, :] for t in types] + + all_types = types + array_types + + def method(func, name, sig): + return Method(func, name, sig, False, False) + + make_methods1 = lambda: [ + method(myfunc1, 'method', FunctionType(argtype, [argtype])) + for argtype in all_types] + + make_methods2 = lambda: [ + method(myfunc2, 'method', FunctionType(argtype1, [argtype1, argtype2])) + for argtype1 in all_types + for argtype2 in all_types] + + + def make_table(methods): + table = methodtable.VTabType(py_class, []) + table.create_method_ordering() + + for i, method in enumerate(make_methods1()): + key = method.name, method.signature.args + method.lfunc_pointer = i + table.specialized_methods[key] = method + + assert len(methods) == len(table.specialized_methods) + + return table + + def make_hashtable(methods): + table = make_table(methods) + hashtable = virtual.build_hashing_vtab(table) + return hashtable + + #------------------------------------------------------------------------ + # Tests + #------------------------------------------------------------------------ + + @parametrize(make_methods1()) + def test_specializations(methods): + hashtable = make_hashtable(methods) + print(hashtable) + + for i, method in enumerate(methods): + key = virtual.sep201_signature_string(method.signature, method.name) + assert hashtable.find_method(key), (i, method, key) + + if __name__ == '__main__': + main() +
Add test for hash-based vtable creation
## Code Before: __author__ = 'mark' ## Instruction: Add test for hash-based vtable creation ## Code After: from __future__ import print_function, division, absolute_import import numba as nb from numba import * from numba.minivect.minitypes import FunctionType from numba.exttypes import virtual from numba.exttypes import ordering from numba.exttypes import methodtable from numba.exttypes.signatures import Method from numba.testing.test_support import parametrize, main class py_class(object): pass def myfunc1(a): pass def myfunc2(a, b): pass def myfunc3(a, b, c): pass types = list(nb.numeric) + [object_] array_types = [t[:] for t in types] array_types += [t[:, :] for t in types] array_types += [t[:, :, :] for t in types] all_types = types + array_types def method(func, name, sig): return Method(func, name, sig, False, False) make_methods1 = lambda: [ method(myfunc1, 'method', FunctionType(argtype, [argtype])) for argtype in all_types] make_methods2 = lambda: [ method(myfunc2, 'method', FunctionType(argtype1, [argtype1, argtype2])) for argtype1 in all_types for argtype2 in all_types] def make_table(methods): table = methodtable.VTabType(py_class, []) table.create_method_ordering() for i, method in enumerate(make_methods1()): key = method.name, method.signature.args method.lfunc_pointer = i table.specialized_methods[key] = method assert len(methods) == len(table.specialized_methods) return table def make_hashtable(methods): table = make_table(methods) hashtable = virtual.build_hashing_vtab(table) return hashtable #------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------ @parametrize(make_methods1()) def test_specializations(methods): hashtable = make_hashtable(methods) print(hashtable) for i, method in enumerate(methods): key = virtual.sep201_signature_string(method.signature, method.name) assert hashtable.find_method(key), (i, method, key) if __name__ == '__main__': main()
// ... existing code ... from __future__ import print_function, division, absolute_import import numba as nb from numba import * from numba.minivect.minitypes import FunctionType from numba.exttypes import virtual from numba.exttypes import ordering from numba.exttypes import methodtable from numba.exttypes.signatures import Method from numba.testing.test_support import parametrize, main class py_class(object): pass def myfunc1(a): pass def myfunc2(a, b): pass def myfunc3(a, b, c): pass types = list(nb.numeric) + [object_] array_types = [t[:] for t in types] array_types += [t[:, :] for t in types] array_types += [t[:, :, :] for t in types] all_types = types + array_types def method(func, name, sig): return Method(func, name, sig, False, False) make_methods1 = lambda: [ method(myfunc1, 'method', FunctionType(argtype, [argtype])) for argtype in all_types] make_methods2 = lambda: [ method(myfunc2, 'method', FunctionType(argtype1, [argtype1, argtype2])) for argtype1 in all_types for argtype2 in all_types] def make_table(methods): table = methodtable.VTabType(py_class, []) table.create_method_ordering() for i, method in enumerate(make_methods1()): key = method.name, method.signature.args method.lfunc_pointer = i table.specialized_methods[key] = method assert len(methods) == len(table.specialized_methods) return table def make_hashtable(methods): table = make_table(methods) hashtable = virtual.build_hashing_vtab(table) return hashtable #------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------ @parametrize(make_methods1()) def test_specializations(methods): hashtable = make_hashtable(methods) print(hashtable) for i, method in enumerate(methods): key = virtual.sep201_signature_string(method.signature, method.name) assert hashtable.find_method(key), (i, method, key) if __name__ == '__main__': main() // ... rest of the code ...
c694ac630f36c53c130a63908c6c3576f220a6bd
django-openstack/django_openstack/auth/__init__.py
django-openstack/django_openstack/auth/__init__.py
import django_openstack.urls class Roles: USER = 'user' PROJECT_ADMIN = 'projadmin' SOFTWARE_ADMIN = 'softadmin' HARDWARE_ADMIN = 'hardadmin' ALL_ROLES = (HARDWARE_ADMIN, SOFTWARE_ADMIN, PROJECT_ADMIN, USER) @staticmethod def get_max_role(roles): if not roles: return Roles.USER for role in Roles.ALL_ROLES: if role in roles: if role in django_openstack.urls.topbars: return role else: return Roles.USER @staticmethod def needs_tenant(roles): return not (Roles.HARDWARE_ADMIN in roles) and not (Roles.SOFTWARE_ADMIN in roles)
import django_openstack.urls class Roles: USER = 'user' PROJECT_ADMIN = 'projadmin' SOFTWARE_ADMIN = 'softadmin' HARDWARE_ADMIN = 'hardadmin' ALL_ROLES = (HARDWARE_ADMIN, SOFTWARE_ADMIN, PROJECT_ADMIN, USER) @staticmethod def get_max_role(roles): if not roles: return Roles.USER for role in Roles.ALL_ROLES: if role in roles: if role in django_openstack.urls.topbars: return role return Roles.USER @staticmethod def needs_tenant(roles): return not (Roles.HARDWARE_ADMIN in roles) and not (Roles.SOFTWARE_ADMIN in roles)
Return 'user' role as default value
Return 'user' role as default value
Python
apache-2.0
griddynamics/osc-robot-openstack-dashboard,griddynamics/osc-robot-openstack-dashboard,griddynamics/osc-robot-openstack-dashboard
import django_openstack.urls class Roles: USER = 'user' PROJECT_ADMIN = 'projadmin' SOFTWARE_ADMIN = 'softadmin' HARDWARE_ADMIN = 'hardadmin' ALL_ROLES = (HARDWARE_ADMIN, SOFTWARE_ADMIN, PROJECT_ADMIN, USER) @staticmethod def get_max_role(roles): if not roles: return Roles.USER for role in Roles.ALL_ROLES: if role in roles: if role in django_openstack.urls.topbars: return role - else: - return Roles.USER + return Roles.USER @staticmethod def needs_tenant(roles): return not (Roles.HARDWARE_ADMIN in roles) and not (Roles.SOFTWARE_ADMIN in roles)
Return 'user' role as default value
## Code Before: import django_openstack.urls class Roles: USER = 'user' PROJECT_ADMIN = 'projadmin' SOFTWARE_ADMIN = 'softadmin' HARDWARE_ADMIN = 'hardadmin' ALL_ROLES = (HARDWARE_ADMIN, SOFTWARE_ADMIN, PROJECT_ADMIN, USER) @staticmethod def get_max_role(roles): if not roles: return Roles.USER for role in Roles.ALL_ROLES: if role in roles: if role in django_openstack.urls.topbars: return role else: return Roles.USER @staticmethod def needs_tenant(roles): return not (Roles.HARDWARE_ADMIN in roles) and not (Roles.SOFTWARE_ADMIN in roles) ## Instruction: Return 'user' role as default value ## Code After: import django_openstack.urls class Roles: USER = 'user' PROJECT_ADMIN = 'projadmin' SOFTWARE_ADMIN = 'softadmin' HARDWARE_ADMIN = 'hardadmin' ALL_ROLES = (HARDWARE_ADMIN, SOFTWARE_ADMIN, PROJECT_ADMIN, USER) @staticmethod def get_max_role(roles): if not roles: return Roles.USER for role in Roles.ALL_ROLES: if role in roles: if role in django_openstack.urls.topbars: return role return Roles.USER @staticmethod def needs_tenant(roles): return not (Roles.HARDWARE_ADMIN in roles) and not (Roles.SOFTWARE_ADMIN in roles)
... return role return Roles.USER ...
85d71d8a5d7cdf34c12791b84c9f1bdec4ad1ed1
partner_compassion/wizards/portal_wizard.py
partner_compassion/wizards/portal_wizard.py
from odoo import api, models from odoo.tools import email_split class PortalWizard(models.TransientModel): _inherit = 'portal.wizard' class PortalUser(models.TransientModel): _inherit = 'portal.wizard.user' @api.multi def _create_user(self): """ Override portal user creation to prevent sending e-mail to new user. """ res_users = self.env['res.users'].with_context( noshortcut=True, no_reset_password=True) email = email_split(self.email) if email: email = email[0] else: email = self.partner_id.lastname.lower() + '@cs.local' values = { 'email': email, 'login': email, 'partner_id': self.partner_id.id, 'groups_id': [(6, 0, [])], 'notify_email': 'none', } return res_users.create(values) @api.multi def _send_email(self): """ Never send invitation e-mails. """ return True
from odoo import api, models from odoo.tools import email_split class PortalWizard(models.TransientModel): _inherit = 'portal.wizard' class PortalUser(models.TransientModel): _inherit = 'portal.wizard.user' @api.multi def _create_user(self): """ Override portal user creation to prevent sending e-mail to new user. """ res_users = self.env['res.users'].with_context( noshortcut=True, no_reset_password=True) email = email_split(self.email) if email: email = email[0] else: email = self.partner_id.lastname.lower() + '@cs.local' values = { 'email': email, 'login': email, 'partner_id': self.partner_id.id, 'groups_id': [(6, 0, [])], 'notify_email': 'none', } res = res_users.create(values) res.notify_email = 'always' return res @api.multi def _send_email(self): """ Never send invitation e-mails. """ return True
Fix bug, set notify_email to always after create portal user
Fix bug, set notify_email to always after create portal user
Python
agpl-3.0
ecino/compassion-switzerland,CompassionCH/compassion-switzerland,ecino/compassion-switzerland,CompassionCH/compassion-switzerland,CompassionCH/compassion-switzerland,eicher31/compassion-switzerland,eicher31/compassion-switzerland,eicher31/compassion-switzerland,ecino/compassion-switzerland
from odoo import api, models from odoo.tools import email_split class PortalWizard(models.TransientModel): _inherit = 'portal.wizard' class PortalUser(models.TransientModel): _inherit = 'portal.wizard.user' @api.multi def _create_user(self): """ Override portal user creation to prevent sending e-mail to new user. """ res_users = self.env['res.users'].with_context( noshortcut=True, no_reset_password=True) email = email_split(self.email) if email: email = email[0] else: email = self.partner_id.lastname.lower() + '@cs.local' values = { 'email': email, 'login': email, 'partner_id': self.partner_id.id, 'groups_id': [(6, 0, [])], 'notify_email': 'none', } - return res_users.create(values) + res = res_users.create(values) + res.notify_email = 'always' + return res @api.multi def _send_email(self): """ Never send invitation e-mails. """ return True
Fix bug, set notify_email to always after create portal user
## Code Before: from odoo import api, models from odoo.tools import email_split class PortalWizard(models.TransientModel): _inherit = 'portal.wizard' class PortalUser(models.TransientModel): _inherit = 'portal.wizard.user' @api.multi def _create_user(self): """ Override portal user creation to prevent sending e-mail to new user. """ res_users = self.env['res.users'].with_context( noshortcut=True, no_reset_password=True) email = email_split(self.email) if email: email = email[0] else: email = self.partner_id.lastname.lower() + '@cs.local' values = { 'email': email, 'login': email, 'partner_id': self.partner_id.id, 'groups_id': [(6, 0, [])], 'notify_email': 'none', } return res_users.create(values) @api.multi def _send_email(self): """ Never send invitation e-mails. """ return True ## Instruction: Fix bug, set notify_email to always after create portal user ## Code After: from odoo import api, models from odoo.tools import email_split class PortalWizard(models.TransientModel): _inherit = 'portal.wizard' class PortalUser(models.TransientModel): _inherit = 'portal.wizard.user' @api.multi def _create_user(self): """ Override portal user creation to prevent sending e-mail to new user. """ res_users = self.env['res.users'].with_context( noshortcut=True, no_reset_password=True) email = email_split(self.email) if email: email = email[0] else: email = self.partner_id.lastname.lower() + '@cs.local' values = { 'email': email, 'login': email, 'partner_id': self.partner_id.id, 'groups_id': [(6, 0, [])], 'notify_email': 'none', } res = res_users.create(values) res.notify_email = 'always' return res @api.multi def _send_email(self): """ Never send invitation e-mails. """ return True
// ... existing code ... } res = res_users.create(values) res.notify_email = 'always' return res // ... rest of the code ...
d732eb43013eedd700ebb00630a26ae97ecdd0b9
onetime/views.py
onetime/views.py
from datetime import datetime from django.http import HttpResponse, HttpResponseRedirect, HttpResponseGone from django.contrib import auth from django.conf import settings from onetime import utils from onetime.models import Key def cleanup(request): utils.cleanup() return HttpResponse('ok', content_type='text/plain') def login(request, key, login_url=None): next = request.GET.get('next', None) if next is None: next = settings.LOGIN_REDIRECT_URL user = auth.authenticate(key=key) if user is None: url = settings.LOGIN_URL if next is not None: url = '%s?next=%s' % (url, next) return HttpResponseRedirect(url) auth.login(request, user) data = Key.objects.get(key=key) data.update_usage() if data.next is not None: next = data.next return HttpResponseRedirect(next)
from datetime import datetime from django.http import HttpResponse, HttpResponseRedirect, HttpResponseGone from django.contrib import auth from django.conf import settings from onetime import utils from onetime.models import Key def cleanup(request): utils.cleanup() return HttpResponse('ok', content_type='text/plain') def login(request, key): next = request.GET.get('next', None) if next is None: next = settings.LOGIN_REDIRECT_URL user = auth.authenticate(key=key) if user is None: url = settings.LOGIN_URL if next is not None: url = '%s?next=%s' % (url, next) return HttpResponseRedirect(url) auth.login(request, user) data = Key.objects.get(key=key) data.update_usage() if data.next is not None: next = data.next return HttpResponseRedirect(next)
Remove a don't-know-why-it's-still-there parameter: login_url
Remove a don't-know-why-it's-still-there parameter: login_url
Python
agpl-3.0
ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,uploadcare/django-loginurl,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,fajran/django-loginurl,ISIFoundation/influenzanet-website,vanschelven/cmsplugin-journal
from datetime import datetime from django.http import HttpResponse, HttpResponseRedirect, HttpResponseGone from django.contrib import auth from django.conf import settings from onetime import utils from onetime.models import Key def cleanup(request): utils.cleanup() return HttpResponse('ok', content_type='text/plain') - def login(request, key, login_url=None): + def login(request, key): next = request.GET.get('next', None) if next is None: next = settings.LOGIN_REDIRECT_URL user = auth.authenticate(key=key) if user is None: url = settings.LOGIN_URL if next is not None: url = '%s?next=%s' % (url, next) return HttpResponseRedirect(url) auth.login(request, user) data = Key.objects.get(key=key) data.update_usage() if data.next is not None: next = data.next return HttpResponseRedirect(next)
Remove a don't-know-why-it's-still-there parameter: login_url
## Code Before: from datetime import datetime from django.http import HttpResponse, HttpResponseRedirect, HttpResponseGone from django.contrib import auth from django.conf import settings from onetime import utils from onetime.models import Key def cleanup(request): utils.cleanup() return HttpResponse('ok', content_type='text/plain') def login(request, key, login_url=None): next = request.GET.get('next', None) if next is None: next = settings.LOGIN_REDIRECT_URL user = auth.authenticate(key=key) if user is None: url = settings.LOGIN_URL if next is not None: url = '%s?next=%s' % (url, next) return HttpResponseRedirect(url) auth.login(request, user) data = Key.objects.get(key=key) data.update_usage() if data.next is not None: next = data.next return HttpResponseRedirect(next) ## Instruction: Remove a don't-know-why-it's-still-there parameter: login_url ## Code After: from datetime import datetime from django.http import HttpResponse, HttpResponseRedirect, HttpResponseGone from django.contrib import auth from django.conf import settings from onetime import utils from onetime.models import Key def cleanup(request): utils.cleanup() return HttpResponse('ok', content_type='text/plain') def login(request, key): next = request.GET.get('next', None) if next is None: next = settings.LOGIN_REDIRECT_URL user = auth.authenticate(key=key) if user is None: url = settings.LOGIN_URL if next is not None: url = '%s?next=%s' % (url, next) return HttpResponseRedirect(url) auth.login(request, user) data = Key.objects.get(key=key) data.update_usage() if data.next is not None: next = data.next return HttpResponseRedirect(next)
// ... existing code ... def login(request, key): next = request.GET.get('next', None) // ... rest of the code ...
7a00293d602c1997777fb90331fcbf7cde1b0838
tweet.py
tweet.py
from twython import Twython from credentials import * from os import urandom def random_tweet(account): # https://docs.python.org/2/library/codecs.html#python-specific-encodings status = urandom(140).decode('utf-8', errors='ignore') tweet = account.update_status(status=status) # Gotta like this tweet, after all, we wrote it account.create_favorite(id=tweet['id']) if __name__ == '__main__': account = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) random_tweet(account)
from twython import Twython from credentials import * from os import urandom def random_tweet(account): # https://docs.python.org/2/library/codecs.html status = urandom(400).decode('utf-8', errors='ignore') status = status[0:140] tweet = account.update_status(status=status) # Gotta like this tweet, after all, we wrote it account.create_favorite(id=tweet['id']) if __name__ == '__main__': account = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) random_tweet(account)
Make sure we fill all 140 possible characters.
Make sure we fill all 140 possible characters.
Python
mit
chrisma/dev-urandom,chrisma/dev-urandom
from twython import Twython from credentials import * from os import urandom def random_tweet(account): - # https://docs.python.org/2/library/codecs.html#python-specific-encodings + # https://docs.python.org/2/library/codecs.html - status = urandom(140).decode('utf-8', errors='ignore') + status = urandom(400).decode('utf-8', errors='ignore') + status = status[0:140] tweet = account.update_status(status=status) # Gotta like this tweet, after all, we wrote it account.create_favorite(id=tweet['id']) if __name__ == '__main__': account = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) random_tweet(account)
Make sure we fill all 140 possible characters.
## Code Before: from twython import Twython from credentials import * from os import urandom def random_tweet(account): # https://docs.python.org/2/library/codecs.html#python-specific-encodings status = urandom(140).decode('utf-8', errors='ignore') tweet = account.update_status(status=status) # Gotta like this tweet, after all, we wrote it account.create_favorite(id=tweet['id']) if __name__ == '__main__': account = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) random_tweet(account) ## Instruction: Make sure we fill all 140 possible characters. ## Code After: from twython import Twython from credentials import * from os import urandom def random_tweet(account): # https://docs.python.org/2/library/codecs.html status = urandom(400).decode('utf-8', errors='ignore') status = status[0:140] tweet = account.update_status(status=status) # Gotta like this tweet, after all, we wrote it account.create_favorite(id=tweet['id']) if __name__ == '__main__': account = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) random_tweet(account)
# ... existing code ... def random_tweet(account): # https://docs.python.org/2/library/codecs.html status = urandom(400).decode('utf-8', errors='ignore') status = status[0:140] tweet = account.update_status(status=status) # ... rest of the code ...
42c6d252084fa9336cf5c5d1766de29bc31bf082
dbaas/workflow/steps/util/resize/start_database.py
dbaas/workflow/steps/util/resize/start_database.py
import logging from util import full_stack from workflow.steps.util.base import BaseStep from workflow.exceptions.error_codes import DBAAS_0022 from workflow.steps.util.restore_snapshot import use_database_initialization_script LOG = logging.getLogger(__name__) class StartDatabase(BaseStep): def __unicode__(self): return "Starting database..." def do(self, workflow_dict): try: databaseinfra = workflow_dict['databaseinfra'] instance = workflow_dict['instance'] if databaseinfra.plan.is_ha: driver = databaseinfra.get_driver() driver.start_slave(instance=instance) return True except Exception: traceback = full_stack() workflow_dict['exceptions']['error_codes'].append(DBAAS_0022) workflow_dict['exceptions']['traceback'].append(traceback) return False def undo(self, workflow_dict): LOG.info("Running undo...") try: databaseinfra = workflow_dict['databaseinfra'] host = workflow_dict['host'] return_code, output = use_database_initialization_script(databaseinfra=databaseinfra, host=host, option='stop') if return_code != 0: raise Exception(str(output)) return True except Exception: traceback = full_stack() workflow_dict['exceptions']['error_codes'].append(DBAAS_0022) workflow_dict['exceptions']['traceback'].append(traceback) return False
import logging from util import full_stack from workflow.steps.util.base import BaseStep from workflow.exceptions.error_codes import DBAAS_0022 from workflow.steps.util.restore_snapshot import use_database_initialization_script from time import sleep LOG = logging.getLogger(__name__) class StartDatabase(BaseStep): def __unicode__(self): return "Starting database..." def do(self, workflow_dict): try: databaseinfra = workflow_dict['databaseinfra'] instance = workflow_dict['instance'] if databaseinfra.plan.is_ha: sleep(60) driver = databaseinfra.get_driver() driver.start_slave(instance=instance) return True except Exception: traceback = full_stack() workflow_dict['exceptions']['error_codes'].append(DBAAS_0022) workflow_dict['exceptions']['traceback'].append(traceback) return False def undo(self, workflow_dict): LOG.info("Running undo...") try: databaseinfra = workflow_dict['databaseinfra'] host = workflow_dict['host'] return_code, output = use_database_initialization_script(databaseinfra=databaseinfra, host=host, option='stop') if return_code != 0: raise Exception(str(output)) return True except Exception: traceback = full_stack() workflow_dict['exceptions']['error_codes'].append(DBAAS_0022) workflow_dict['exceptions']['traceback'].append(traceback) return False
Add sleep on start database
Add sleep on start database
Python
bsd-3-clause
globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service
import logging from util import full_stack from workflow.steps.util.base import BaseStep from workflow.exceptions.error_codes import DBAAS_0022 from workflow.steps.util.restore_snapshot import use_database_initialization_script + from time import sleep LOG = logging.getLogger(__name__) class StartDatabase(BaseStep): def __unicode__(self): return "Starting database..." def do(self, workflow_dict): try: databaseinfra = workflow_dict['databaseinfra'] instance = workflow_dict['instance'] if databaseinfra.plan.is_ha: + sleep(60) driver = databaseinfra.get_driver() driver.start_slave(instance=instance) return True except Exception: traceback = full_stack() workflow_dict['exceptions']['error_codes'].append(DBAAS_0022) workflow_dict['exceptions']['traceback'].append(traceback) return False def undo(self, workflow_dict): LOG.info("Running undo...") try: databaseinfra = workflow_dict['databaseinfra'] host = workflow_dict['host'] return_code, output = use_database_initialization_script(databaseinfra=databaseinfra, host=host, option='stop') if return_code != 0: raise Exception(str(output)) return True except Exception: traceback = full_stack() workflow_dict['exceptions']['error_codes'].append(DBAAS_0022) workflow_dict['exceptions']['traceback'].append(traceback) return False
Add sleep on start database
## Code Before: import logging from util import full_stack from workflow.steps.util.base import BaseStep from workflow.exceptions.error_codes import DBAAS_0022 from workflow.steps.util.restore_snapshot import use_database_initialization_script LOG = logging.getLogger(__name__) class StartDatabase(BaseStep): def __unicode__(self): return "Starting database..." def do(self, workflow_dict): try: databaseinfra = workflow_dict['databaseinfra'] instance = workflow_dict['instance'] if databaseinfra.plan.is_ha: driver = databaseinfra.get_driver() driver.start_slave(instance=instance) return True except Exception: traceback = full_stack() workflow_dict['exceptions']['error_codes'].append(DBAAS_0022) workflow_dict['exceptions']['traceback'].append(traceback) return False def undo(self, workflow_dict): LOG.info("Running undo...") try: databaseinfra = workflow_dict['databaseinfra'] host = workflow_dict['host'] return_code, output = use_database_initialization_script(databaseinfra=databaseinfra, host=host, option='stop') if return_code != 0: raise Exception(str(output)) return True except Exception: traceback = full_stack() workflow_dict['exceptions']['error_codes'].append(DBAAS_0022) workflow_dict['exceptions']['traceback'].append(traceback) return False ## Instruction: Add sleep on start database ## Code After: import logging from util import full_stack from workflow.steps.util.base import BaseStep from workflow.exceptions.error_codes import DBAAS_0022 from workflow.steps.util.restore_snapshot import use_database_initialization_script from time import sleep LOG = logging.getLogger(__name__) class StartDatabase(BaseStep): def __unicode__(self): return "Starting database..." def do(self, workflow_dict): try: databaseinfra = workflow_dict['databaseinfra'] instance = workflow_dict['instance'] if databaseinfra.plan.is_ha: sleep(60) driver = databaseinfra.get_driver() driver.start_slave(instance=instance) return True except Exception: traceback = full_stack() workflow_dict['exceptions']['error_codes'].append(DBAAS_0022) workflow_dict['exceptions']['traceback'].append(traceback) return False def undo(self, workflow_dict): LOG.info("Running undo...") try: databaseinfra = workflow_dict['databaseinfra'] host = workflow_dict['host'] return_code, output = use_database_initialization_script(databaseinfra=databaseinfra, host=host, option='stop') if return_code != 0: raise Exception(str(output)) return True except Exception: traceback = full_stack() workflow_dict['exceptions']['error_codes'].append(DBAAS_0022) workflow_dict['exceptions']['traceback'].append(traceback) return False
// ... existing code ... from workflow.steps.util.restore_snapshot import use_database_initialization_script from time import sleep // ... modified code ... if databaseinfra.plan.is_ha: sleep(60) driver = databaseinfra.get_driver() // ... rest of the code ...
aae29a385129e6a1573fac2c631eff8db8ea3079
stackdio/stackdio/__init__.py
stackdio/stackdio/__init__.py
from __future__ import absolute_import import sys from .version import __version__, __version_info__ # NOQA # This will make sure the app is always imported when # Django starts so that shared_task will use this app. try: from .celery import app as celery_app except ImportError: sys.stderr.write('Not importing celery... Ignore if this is running setup.py.\n') __copyright__ = "Copyright 2014, Digital Reasoning" __license__ = "Apache License Version 2.0, January 2004" __maintainer__ = "https://github.com/stackdio/stackdio"
from __future__ import absolute_import import sys from .version import __version__, __version_info__ # NOQA # This will make sure the app is always imported when # Django starts so that shared_task will use this app. try: from .celery import app as celery_app except ImportError: sys.stderr.write("Not importing celery... " "Ignore if this if you're currently running setup.py.\n") __copyright__ = "Copyright 2014, Digital Reasoning" __license__ = "Apache License Version 2.0, January 2004" __maintainer__ = "https://github.com/stackdio/stackdio"
Print a more useful warning message
Print a more useful warning message
Python
apache-2.0
stackdio/stackdio,clarkperkins/stackdio,stackdio/stackdio,clarkperkins/stackdio,clarkperkins/stackdio,clarkperkins/stackdio,stackdio/stackdio,stackdio/stackdio
from __future__ import absolute_import import sys from .version import __version__, __version_info__ # NOQA # This will make sure the app is always imported when # Django starts so that shared_task will use this app. try: from .celery import app as celery_app except ImportError: - sys.stderr.write('Not importing celery... Ignore if this is running setup.py.\n') + sys.stderr.write("Not importing celery... " + "Ignore if this if you're currently running setup.py.\n") __copyright__ = "Copyright 2014, Digital Reasoning" __license__ = "Apache License Version 2.0, January 2004" __maintainer__ = "https://github.com/stackdio/stackdio"
Print a more useful warning message
## Code Before: from __future__ import absolute_import import sys from .version import __version__, __version_info__ # NOQA # This will make sure the app is always imported when # Django starts so that shared_task will use this app. try: from .celery import app as celery_app except ImportError: sys.stderr.write('Not importing celery... Ignore if this is running setup.py.\n') __copyright__ = "Copyright 2014, Digital Reasoning" __license__ = "Apache License Version 2.0, January 2004" __maintainer__ = "https://github.com/stackdio/stackdio" ## Instruction: Print a more useful warning message ## Code After: from __future__ import absolute_import import sys from .version import __version__, __version_info__ # NOQA # This will make sure the app is always imported when # Django starts so that shared_task will use this app. try: from .celery import app as celery_app except ImportError: sys.stderr.write("Not importing celery... " "Ignore if this if you're currently running setup.py.\n") __copyright__ = "Copyright 2014, Digital Reasoning" __license__ = "Apache License Version 2.0, January 2004" __maintainer__ = "https://github.com/stackdio/stackdio"
// ... existing code ... except ImportError: sys.stderr.write("Not importing celery... " "Ignore if this if you're currently running setup.py.\n") // ... rest of the code ...
dced68096d5c84c831866cf92e7430df6cf5f477
src/nodeconductor_saltstack/sharepoint/cost_tracking.py
src/nodeconductor_saltstack/sharepoint/cost_tracking.py
from django.contrib.contenttypes.models import ContentType from nodeconductor.cost_tracking import CostTrackingBackend from nodeconductor.cost_tracking.models import DefaultPriceListItem from .models import SharepointTenant class Type(object): USAGE = 'usage' STORAGE = 'storage' STORAGE_KEY = '1 MB' USAGE_KEY = 'basic' CHOICES = { USAGE: USAGE_KEY, STORAGE: STORAGE_KEY, } class SaltStackCostTrackingBackend(CostTrackingBackend): NUMERICAL = [Type.STORAGE] @classmethod def get_default_price_list_items(cls): content_type = ContentType.objects.get_for_model(SharepointTenant) for item, key in Type.CHOICES.iteritems(): yield DefaultPriceListItem(item_type=item, key=key, resource_content_type=content_type) @classmethod def get_used_items(cls, resource): backend = resource.get_backend() storage = sum(s.usage for s in backend.site_collections.list()) return [ (Type.USAGE, Type.CHOICES[Type.USAGE], 1), (Type.STORAGE, Type.CHOICES[Type.STORAGE], storage), ]
from django.contrib.contenttypes.models import ContentType from nodeconductor.cost_tracking import CostTrackingBackend from nodeconductor.cost_tracking.models import DefaultPriceListItem from .models import SharepointTenant class Type(object): USAGE = 'usage' STORAGE = 'storage' STORAGE_KEY = '1 MB' USAGE_KEY = 'basic' CHOICES = { USAGE: USAGE_KEY, STORAGE: STORAGE_KEY, } class SaltStackCostTrackingBackend(CostTrackingBackend): NUMERICAL = [Type.STORAGE] @classmethod def get_default_price_list_items(cls): content_type = ContentType.objects.get_for_model(SharepointTenant) for item, key in Type.CHOICES.iteritems(): yield DefaultPriceListItem(item_type=item, key=key, resource_content_type=content_type) @classmethod def get_used_items(cls, resource): tenant = resource storage = tenant.quotas.get(name=SharepointTenant.Quotas.storage).usage return [ (Type.USAGE, Type.CHOICES[Type.USAGE], 1), (Type.STORAGE, Type.CHOICES[Type.STORAGE], storage), ]
Fix sharepoint tenant cost tracking
Fix sharepoint tenant cost tracking - itacloud-6123
Python
mit
opennode/nodeconductor-saltstack
from django.contrib.contenttypes.models import ContentType from nodeconductor.cost_tracking import CostTrackingBackend from nodeconductor.cost_tracking.models import DefaultPriceListItem from .models import SharepointTenant class Type(object): USAGE = 'usage' STORAGE = 'storage' STORAGE_KEY = '1 MB' USAGE_KEY = 'basic' CHOICES = { USAGE: USAGE_KEY, STORAGE: STORAGE_KEY, } class SaltStackCostTrackingBackend(CostTrackingBackend): NUMERICAL = [Type.STORAGE] @classmethod def get_default_price_list_items(cls): content_type = ContentType.objects.get_for_model(SharepointTenant) for item, key in Type.CHOICES.iteritems(): yield DefaultPriceListItem(item_type=item, key=key, resource_content_type=content_type) @classmethod def get_used_items(cls, resource): - backend = resource.get_backend() - storage = sum(s.usage for s in backend.site_collections.list()) + tenant = resource + storage = tenant.quotas.get(name=SharepointTenant.Quotas.storage).usage return [ (Type.USAGE, Type.CHOICES[Type.USAGE], 1), (Type.STORAGE, Type.CHOICES[Type.STORAGE], storage), ]
Fix sharepoint tenant cost tracking
## Code Before: from django.contrib.contenttypes.models import ContentType from nodeconductor.cost_tracking import CostTrackingBackend from nodeconductor.cost_tracking.models import DefaultPriceListItem from .models import SharepointTenant class Type(object): USAGE = 'usage' STORAGE = 'storage' STORAGE_KEY = '1 MB' USAGE_KEY = 'basic' CHOICES = { USAGE: USAGE_KEY, STORAGE: STORAGE_KEY, } class SaltStackCostTrackingBackend(CostTrackingBackend): NUMERICAL = [Type.STORAGE] @classmethod def get_default_price_list_items(cls): content_type = ContentType.objects.get_for_model(SharepointTenant) for item, key in Type.CHOICES.iteritems(): yield DefaultPriceListItem(item_type=item, key=key, resource_content_type=content_type) @classmethod def get_used_items(cls, resource): backend = resource.get_backend() storage = sum(s.usage for s in backend.site_collections.list()) return [ (Type.USAGE, Type.CHOICES[Type.USAGE], 1), (Type.STORAGE, Type.CHOICES[Type.STORAGE], storage), ] ## Instruction: Fix sharepoint tenant cost tracking ## Code After: from django.contrib.contenttypes.models import ContentType from nodeconductor.cost_tracking import CostTrackingBackend from nodeconductor.cost_tracking.models import DefaultPriceListItem from .models import SharepointTenant class Type(object): USAGE = 'usage' STORAGE = 'storage' STORAGE_KEY = '1 MB' USAGE_KEY = 'basic' CHOICES = { USAGE: USAGE_KEY, STORAGE: STORAGE_KEY, } class SaltStackCostTrackingBackend(CostTrackingBackend): NUMERICAL = [Type.STORAGE] @classmethod def get_default_price_list_items(cls): content_type = ContentType.objects.get_for_model(SharepointTenant) for item, key in Type.CHOICES.iteritems(): yield DefaultPriceListItem(item_type=item, key=key, resource_content_type=content_type) @classmethod def get_used_items(cls, resource): tenant = resource storage = tenant.quotas.get(name=SharepointTenant.Quotas.storage).usage return [ (Type.USAGE, Type.CHOICES[Type.USAGE], 1), (Type.STORAGE, Type.CHOICES[Type.STORAGE], storage), ]
// ... existing code ... def get_used_items(cls, resource): tenant = resource storage = tenant.quotas.get(name=SharepointTenant.Quotas.storage).usage return [ // ... rest of the code ...
810961f65c37d27c5e2d99cf102064d0b4e300f3
project/apiv2/views.py
project/apiv2/views.py
from django.db.models import Q from django.shortcuts import render from rest_framework.filters import OrderingFilter, SearchFilter from rest_framework.generics import ListAPIView from rest_framework_json_api.renderers import JSONRenderer from rest_framework.generics import RetrieveUpdateDestroyAPIView from bookmarks.models import Bookmark from bookmarks.serializers import BookmarkSerializer class BookmarkListCreateAPIView(ListAPIView): queryset = Bookmark.objects.all() serializer_class = BookmarkSerializer resource_name = 'bookmark' action = 'list' renderer_classes = (JSONRenderer,) filter_backends = (SearchFilter, OrderingFilter) search_fields = ('url', 'title') ordering_fields = ('id', 'url', 'title', 'bookmarked_at') class BookmarkRetrieveUpdateDestroyAPIView(RetrieveUpdateDestroyAPIView): queryset = Bookmark.objects.all() serializer_class = BookmarkSerializer lookup_field = 'bookmark_id'
from django.db.models import Q from django.shortcuts import render from rest_framework.filters import OrderingFilter, SearchFilter from rest_framework_json_api.renderers import JSONRenderer from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView from bookmarks.models import Bookmark from bookmarks.serializers import BookmarkSerializer class BookmarkListCreateAPIView(ListCreateAPIView): queryset = Bookmark.objects.all() serializer_class = BookmarkSerializer resource_name = 'bookmark' action = 'list' renderer_classes = (JSONRenderer,) filter_backends = (SearchFilter, OrderingFilter) search_fields = ('url', 'title') ordering_fields = ('id', 'url', 'title', 'bookmarked_at') class BookmarkRetrieveUpdateDestroyAPIView(RetrieveUpdateDestroyAPIView): queryset = Bookmark.objects.all() serializer_class = BookmarkSerializer lookup_field = 'bookmark_id'
Use ListCreateAPIView as base class to support bookmark creation
Use ListCreateAPIView as base class to support bookmark creation
Python
mit
hnakamur/django-bootstrap-table-example,hnakamur/django-bootstrap-table-example,hnakamur/django-bootstrap-table-example
from django.db.models import Q from django.shortcuts import render from rest_framework.filters import OrderingFilter, SearchFilter - from rest_framework.generics import ListAPIView from rest_framework_json_api.renderers import JSONRenderer - from rest_framework.generics import RetrieveUpdateDestroyAPIView + from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView from bookmarks.models import Bookmark from bookmarks.serializers import BookmarkSerializer - class BookmarkListCreateAPIView(ListAPIView): + class BookmarkListCreateAPIView(ListCreateAPIView): queryset = Bookmark.objects.all() serializer_class = BookmarkSerializer resource_name = 'bookmark' action = 'list' renderer_classes = (JSONRenderer,) filter_backends = (SearchFilter, OrderingFilter) search_fields = ('url', 'title') ordering_fields = ('id', 'url', 'title', 'bookmarked_at') class BookmarkRetrieveUpdateDestroyAPIView(RetrieveUpdateDestroyAPIView): queryset = Bookmark.objects.all() serializer_class = BookmarkSerializer lookup_field = 'bookmark_id'
Use ListCreateAPIView as base class to support bookmark creation
## Code Before: from django.db.models import Q from django.shortcuts import render from rest_framework.filters import OrderingFilter, SearchFilter from rest_framework.generics import ListAPIView from rest_framework_json_api.renderers import JSONRenderer from rest_framework.generics import RetrieveUpdateDestroyAPIView from bookmarks.models import Bookmark from bookmarks.serializers import BookmarkSerializer class BookmarkListCreateAPIView(ListAPIView): queryset = Bookmark.objects.all() serializer_class = BookmarkSerializer resource_name = 'bookmark' action = 'list' renderer_classes = (JSONRenderer,) filter_backends = (SearchFilter, OrderingFilter) search_fields = ('url', 'title') ordering_fields = ('id', 'url', 'title', 'bookmarked_at') class BookmarkRetrieveUpdateDestroyAPIView(RetrieveUpdateDestroyAPIView): queryset = Bookmark.objects.all() serializer_class = BookmarkSerializer lookup_field = 'bookmark_id' ## Instruction: Use ListCreateAPIView as base class to support bookmark creation ## Code After: from django.db.models import Q from django.shortcuts import render from rest_framework.filters import OrderingFilter, SearchFilter from rest_framework_json_api.renderers import JSONRenderer from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView from bookmarks.models import Bookmark from bookmarks.serializers import BookmarkSerializer class BookmarkListCreateAPIView(ListCreateAPIView): queryset = Bookmark.objects.all() serializer_class = BookmarkSerializer resource_name = 'bookmark' action = 'list' renderer_classes = (JSONRenderer,) filter_backends = (SearchFilter, OrderingFilter) search_fields = ('url', 'title') ordering_fields = ('id', 'url', 'title', 'bookmarked_at') class BookmarkRetrieveUpdateDestroyAPIView(RetrieveUpdateDestroyAPIView): queryset = Bookmark.objects.all() serializer_class = BookmarkSerializer lookup_field = 'bookmark_id'
... from rest_framework.filters import OrderingFilter, SearchFilter from rest_framework_json_api.renderers import JSONRenderer from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView ... class BookmarkListCreateAPIView(ListCreateAPIView): queryset = Bookmark.objects.all() ...
27aad0e3ed95cb43b28eb3c02fa96b3a9b74de5b
tests/test_container.py
tests/test_container.py
from .common import * class TestContainers(TestCase): def test_unicode_filename(self): container = av.open(self.sandboxed(u'¢∞§¶•ªº.mov'), 'w')
import os import sys import unittest from .common import * # On Windows, Python 3.0 - 3.5 have issues handling unicode filenames. # Starting with Python 3.6 the situation is saner thanks to PEP 529: # # https://www.python.org/dev/peps/pep-0529/ broken_unicode = ( os.name == 'nt' and sys.version_info >= (3, 0) and sys.version_info < (3, 6)) class TestContainers(TestCase): @unittest.skipIf(broken_unicode, 'Unicode filename handling is broken') def test_unicode_filename(self): container = av.open(self.sandboxed(u'¢∞§¶•ªº.mov'), 'w')
Disable unicode filename test on Windows with Python 3.0 - 3.5
Disable unicode filename test on Windows with Python 3.0 - 3.5 Before PEP 529 landed in Python 3.6, unicode filename handling on Windows is hit-and-miss, so don't break CI.
Python
bsd-3-clause
PyAV-Org/PyAV,mikeboers/PyAV,PyAV-Org/PyAV,mikeboers/PyAV
+ + import os + import sys + import unittest from .common import * + + # On Windows, Python 3.0 - 3.5 have issues handling unicode filenames. + # Starting with Python 3.6 the situation is saner thanks to PEP 529: + # + # https://www.python.org/dev/peps/pep-0529/ + + broken_unicode = ( + os.name == 'nt' and + sys.version_info >= (3, 0) and + sys.version_info < (3, 6)) class TestContainers(TestCase): + @unittest.skipIf(broken_unicode, 'Unicode filename handling is broken') def test_unicode_filename(self): container = av.open(self.sandboxed(u'¢∞§¶•ªº.mov'), 'w')
Disable unicode filename test on Windows with Python 3.0 - 3.5
## Code Before: from .common import * class TestContainers(TestCase): def test_unicode_filename(self): container = av.open(self.sandboxed(u'¢∞§¶•ªº.mov'), 'w') ## Instruction: Disable unicode filename test on Windows with Python 3.0 - 3.5 ## Code After: import os import sys import unittest from .common import * # On Windows, Python 3.0 - 3.5 have issues handling unicode filenames. # Starting with Python 3.6 the situation is saner thanks to PEP 529: # # https://www.python.org/dev/peps/pep-0529/ broken_unicode = ( os.name == 'nt' and sys.version_info >= (3, 0) and sys.version_info < (3, 6)) class TestContainers(TestCase): @unittest.skipIf(broken_unicode, 'Unicode filename handling is broken') def test_unicode_filename(self): container = av.open(self.sandboxed(u'¢∞§¶•ªº.mov'), 'w')
# ... existing code ... import os import sys import unittest # ... modified code ... from .common import * # On Windows, Python 3.0 - 3.5 have issues handling unicode filenames. # Starting with Python 3.6 the situation is saner thanks to PEP 529: # # https://www.python.org/dev/peps/pep-0529/ broken_unicode = ( os.name == 'nt' and sys.version_info >= (3, 0) and sys.version_info < (3, 6)) ... @unittest.skipIf(broken_unicode, 'Unicode filename handling is broken') def test_unicode_filename(self): # ... rest of the code ...
8e58b413801a0dbbcd3e48a5ef94201a24af7e8e
are_there_spiders/are_there_spiders/custom_storages.py
are_there_spiders/are_there_spiders/custom_storages.py
from django.contrib.staticfiles.storage import CachedFilesMixin from pipeline.storage import PipelineMixin from storages.backends.s3boto import S3BotoStorage class S3PipelineStorage(PipelineMixin, CachedFilesMixin, S3BotoStorage): pass
import urllib import urlparse from django.contrib.staticfiles.storage import CachedFilesMixin from pipeline.storage import PipelineMixin from storages.backends.s3boto import S3BotoStorage # CachedFilesMixin doesn't play well with Boto and S3. It over-quotes things, # causing erratic failures. So we subclass. # (See http://stackoverflow.com/questions/11820566/inconsistent- # signaturedoesnotmatch-amazon-s3-with-django-pipeline-s3boto-and-st) class PatchedCachedFilesMixin(CachedFilesMixin): def url(self, *a, **kw): s = super(PatchedCachedFilesMixin, self).url(*a, **kw) if isinstance(s, unicode): s = s.encode('utf-8', 'ignore') scheme, netloc, path, qs, anchor = urlparse.urlsplit(s) path = urllib.quote(path, '/%') qs = urllib.quote_plus(qs, ':&=') return urlparse.urlunsplit((scheme, netloc, path, qs, anchor)) class S3PipelineStorage(PipelineMixin, PatchedCachedFilesMixin, S3BotoStorage): pass
Revert "Improvement to custom storage."
Revert "Improvement to custom storage." This reverts commit 6f185ac7398f30653dff9403d5ebf5539d222f4c.
Python
mit
wlonk/are_there_spiders,wlonk/are_there_spiders,wlonk/are_there_spiders
+ import urllib + import urlparse + from django.contrib.staticfiles.storage import CachedFilesMixin from pipeline.storage import PipelineMixin from storages.backends.s3boto import S3BotoStorage + # CachedFilesMixin doesn't play well with Boto and S3. It over-quotes things, + # causing erratic failures. So we subclass. + # (See http://stackoverflow.com/questions/11820566/inconsistent- + # signaturedoesnotmatch-amazon-s3-with-django-pipeline-s3boto-and-st) + class PatchedCachedFilesMixin(CachedFilesMixin): + def url(self, *a, **kw): + s = super(PatchedCachedFilesMixin, self).url(*a, **kw) + if isinstance(s, unicode): + s = s.encode('utf-8', 'ignore') + scheme, netloc, path, qs, anchor = urlparse.urlsplit(s) + path = urllib.quote(path, '/%') + qs = urllib.quote_plus(qs, ':&=') + return urlparse.urlunsplit((scheme, netloc, path, qs, anchor)) + + - class S3PipelineStorage(PipelineMixin, CachedFilesMixin, S3BotoStorage): + class S3PipelineStorage(PipelineMixin, PatchedCachedFilesMixin, S3BotoStorage): pass
Revert "Improvement to custom storage."
## Code Before: from django.contrib.staticfiles.storage import CachedFilesMixin from pipeline.storage import PipelineMixin from storages.backends.s3boto import S3BotoStorage class S3PipelineStorage(PipelineMixin, CachedFilesMixin, S3BotoStorage): pass ## Instruction: Revert "Improvement to custom storage." ## Code After: import urllib import urlparse from django.contrib.staticfiles.storage import CachedFilesMixin from pipeline.storage import PipelineMixin from storages.backends.s3boto import S3BotoStorage # CachedFilesMixin doesn't play well with Boto and S3. It over-quotes things, # causing erratic failures. So we subclass. # (See http://stackoverflow.com/questions/11820566/inconsistent- # signaturedoesnotmatch-amazon-s3-with-django-pipeline-s3boto-and-st) class PatchedCachedFilesMixin(CachedFilesMixin): def url(self, *a, **kw): s = super(PatchedCachedFilesMixin, self).url(*a, **kw) if isinstance(s, unicode): s = s.encode('utf-8', 'ignore') scheme, netloc, path, qs, anchor = urlparse.urlsplit(s) path = urllib.quote(path, '/%') qs = urllib.quote_plus(qs, ':&=') return urlparse.urlunsplit((scheme, netloc, path, qs, anchor)) class S3PipelineStorage(PipelineMixin, PatchedCachedFilesMixin, S3BotoStorage): pass
// ... existing code ... import urllib import urlparse from django.contrib.staticfiles.storage import CachedFilesMixin // ... modified code ... # CachedFilesMixin doesn't play well with Boto and S3. It over-quotes things, # causing erratic failures. So we subclass. # (See http://stackoverflow.com/questions/11820566/inconsistent- # signaturedoesnotmatch-amazon-s3-with-django-pipeline-s3boto-and-st) class PatchedCachedFilesMixin(CachedFilesMixin): def url(self, *a, **kw): s = super(PatchedCachedFilesMixin, self).url(*a, **kw) if isinstance(s, unicode): s = s.encode('utf-8', 'ignore') scheme, netloc, path, qs, anchor = urlparse.urlsplit(s) path = urllib.quote(path, '/%') qs = urllib.quote_plus(qs, ':&=') return urlparse.urlunsplit((scheme, netloc, path, qs, anchor)) class S3PipelineStorage(PipelineMixin, PatchedCachedFilesMixin, S3BotoStorage): pass // ... rest of the code ...
788cc159e4d734b972e22ccf06dbcd8ed8f94885
distutils/_collections.py
distutils/_collections.py
import collections import itertools # from jaraco.collections 3.5 class DictStack(list, collections.abc.Mapping): """ A stack of dictionaries that behaves as a view on those dictionaries, giving preference to the last. >>> stack = DictStack([dict(a=1, c=2), dict(b=2, a=2)]) >>> stack['a'] 2 >>> stack['b'] 2 >>> stack['c'] 2 >>> stack.push(dict(a=3)) >>> stack['a'] 3 >>> set(stack.keys()) == set(['a', 'b', 'c']) True >>> set(stack.items()) == set([('a', 3), ('b', 2), ('c', 2)]) True >>> dict(**stack) == dict(stack) == dict(a=3, c=2, b=2) True >>> d = stack.pop() >>> stack['a'] 2 >>> d = stack.pop() >>> stack['a'] 1 >>> stack.get('b', None) >>> 'c' in stack True """ def __iter__(self): dicts = list.__iter__(self) return iter(set(itertools.chain.from_iterable(c.keys() for c in dicts))) def __getitem__(self, key): for scope in reversed(self): if key in scope: return scope[key] raise KeyError(key) push = list.append def __contains__(self, other): return collections.abc.Mapping.__contains__(self, other)
import collections import itertools # from jaraco.collections 3.5.1 class DictStack(list, collections.abc.Mapping): """ A stack of dictionaries that behaves as a view on those dictionaries, giving preference to the last. >>> stack = DictStack([dict(a=1, c=2), dict(b=2, a=2)]) >>> stack['a'] 2 >>> stack['b'] 2 >>> stack['c'] 2 >>> len(stack) 3 >>> stack.push(dict(a=3)) >>> stack['a'] 3 >>> set(stack.keys()) == set(['a', 'b', 'c']) True >>> set(stack.items()) == set([('a', 3), ('b', 2), ('c', 2)]) True >>> dict(**stack) == dict(stack) == dict(a=3, c=2, b=2) True >>> d = stack.pop() >>> stack['a'] 2 >>> d = stack.pop() >>> stack['a'] 1 >>> stack.get('b', None) >>> 'c' in stack True """ def __iter__(self): dicts = list.__iter__(self) return iter(set(itertools.chain.from_iterable(c.keys() for c in dicts))) def __getitem__(self, key): for scope in reversed(tuple(list.__iter__(self))): if key in scope: return scope[key] raise KeyError(key) push = list.append def __contains__(self, other): return collections.abc.Mapping.__contains__(self, other) def __len__(self): return len(list(iter(self)))
Update DictStack implementation from jaraco.collections 3.5.1
Update DictStack implementation from jaraco.collections 3.5.1
Python
mit
pypa/setuptools,pypa/setuptools,pypa/setuptools
import collections import itertools - # from jaraco.collections 3.5 + # from jaraco.collections 3.5.1 class DictStack(list, collections.abc.Mapping): """ A stack of dictionaries that behaves as a view on those dictionaries, giving preference to the last. >>> stack = DictStack([dict(a=1, c=2), dict(b=2, a=2)]) >>> stack['a'] 2 >>> stack['b'] 2 >>> stack['c'] 2 + >>> len(stack) + 3 >>> stack.push(dict(a=3)) >>> stack['a'] 3 >>> set(stack.keys()) == set(['a', 'b', 'c']) True >>> set(stack.items()) == set([('a', 3), ('b', 2), ('c', 2)]) True >>> dict(**stack) == dict(stack) == dict(a=3, c=2, b=2) True >>> d = stack.pop() >>> stack['a'] 2 >>> d = stack.pop() >>> stack['a'] 1 >>> stack.get('b', None) >>> 'c' in stack True """ def __iter__(self): dicts = list.__iter__(self) return iter(set(itertools.chain.from_iterable(c.keys() for c in dicts))) def __getitem__(self, key): - for scope in reversed(self): + for scope in reversed(tuple(list.__iter__(self))): if key in scope: return scope[key] raise KeyError(key) push = list.append def __contains__(self, other): return collections.abc.Mapping.__contains__(self, other) + def __len__(self): + return len(list(iter(self))) +
Update DictStack implementation from jaraco.collections 3.5.1
## Code Before: import collections import itertools # from jaraco.collections 3.5 class DictStack(list, collections.abc.Mapping): """ A stack of dictionaries that behaves as a view on those dictionaries, giving preference to the last. >>> stack = DictStack([dict(a=1, c=2), dict(b=2, a=2)]) >>> stack['a'] 2 >>> stack['b'] 2 >>> stack['c'] 2 >>> stack.push(dict(a=3)) >>> stack['a'] 3 >>> set(stack.keys()) == set(['a', 'b', 'c']) True >>> set(stack.items()) == set([('a', 3), ('b', 2), ('c', 2)]) True >>> dict(**stack) == dict(stack) == dict(a=3, c=2, b=2) True >>> d = stack.pop() >>> stack['a'] 2 >>> d = stack.pop() >>> stack['a'] 1 >>> stack.get('b', None) >>> 'c' in stack True """ def __iter__(self): dicts = list.__iter__(self) return iter(set(itertools.chain.from_iterable(c.keys() for c in dicts))) def __getitem__(self, key): for scope in reversed(self): if key in scope: return scope[key] raise KeyError(key) push = list.append def __contains__(self, other): return collections.abc.Mapping.__contains__(self, other) ## Instruction: Update DictStack implementation from jaraco.collections 3.5.1 ## Code After: import collections import itertools # from jaraco.collections 3.5.1 class DictStack(list, collections.abc.Mapping): """ A stack of dictionaries that behaves as a view on those dictionaries, giving preference to the last. >>> stack = DictStack([dict(a=1, c=2), dict(b=2, a=2)]) >>> stack['a'] 2 >>> stack['b'] 2 >>> stack['c'] 2 >>> len(stack) 3 >>> stack.push(dict(a=3)) >>> stack['a'] 3 >>> set(stack.keys()) == set(['a', 'b', 'c']) True >>> set(stack.items()) == set([('a', 3), ('b', 2), ('c', 2)]) True >>> dict(**stack) == dict(stack) == dict(a=3, c=2, b=2) True >>> d = stack.pop() >>> stack['a'] 2 >>> d = stack.pop() >>> stack['a'] 1 >>> stack.get('b', None) >>> 'c' in stack True """ def __iter__(self): dicts = list.__iter__(self) return iter(set(itertools.chain.from_iterable(c.keys() for c in dicts))) def __getitem__(self, key): for scope in reversed(tuple(list.__iter__(self))): if key in scope: return scope[key] raise KeyError(key) push = list.append def __contains__(self, other): return collections.abc.Mapping.__contains__(self, other) def __len__(self): return len(list(iter(self)))
... # from jaraco.collections 3.5.1 class DictStack(list, collections.abc.Mapping): ... 2 >>> len(stack) 3 >>> stack.push(dict(a=3)) ... def __getitem__(self, key): for scope in reversed(tuple(list.__iter__(self))): if key in scope: ... return collections.abc.Mapping.__contains__(self, other) def __len__(self): return len(list(iter(self))) ...
19a7a44449b4e08253ca9379dd23db50f27d6488
markdown_wrapper.py
markdown_wrapper.py
from __future__ import absolute_import import sublime import traceback ST3 = int(sublime.version()) >= 3000 if ST3: from markdown import Markdown, util from markdown.extensions import Extension import importlib else: from markdown import Markdown, util from markdown.extensions import Extension class StMarkdown(Markdown): def __init__(self, *args, **kwargs): Markdown.__init__(self, *args, **kwargs) self.Meta = {} def registerExtensions(self, extensions, configs): """ Register extensions with this instance of Markdown. Keyword arguments: * extensions: A list of extensions, which can either be strings or objects. See the docstring on Markdown. * configs: A dictionary mapping module names to config options. """ for ext in extensions: try: if isinstance(ext, util.string_type): ext = self.build_extension(ext, configs.get(ext, [])) if isinstance(ext, Extension): ext.extendMarkdown(self, globals()) elif ext is not None: raise TypeError( 'Extension "%s.%s" must be of type: "markdown.Extension"' % (ext.__class__.__module__, ext.__class__.__name__)) except: print(str(traceback.format_exc())) continue return self
from __future__ import absolute_import import sublime import traceback from markdown import Markdown, util from markdown.extensions import Extension import importlib class StMarkdown(Markdown): def __init__(self, *args, **kwargs): Markdown.__init__(self, *args, **kwargs) self.Meta = {} def registerExtensions(self, extensions, configs): """ Register extensions with this instance of Markdown. Keyword arguments: * extensions: A list of extensions, which can either be strings or objects. See the docstring on Markdown. * configs: A dictionary mapping module names to config options. """ for ext in extensions: try: if isinstance(ext, util.string_type): ext = self.build_extension(ext, configs.get(ext, [])) if isinstance(ext, Extension): ext.extendMarkdown(self, globals()) elif ext is not None: raise TypeError( 'Extension "%s.%s" must be of type: "markdown.Extension"' % (ext.__class__.__module__, ext.__class__.__name__)) except: print(str(traceback.format_exc())) continue return self
Remove some more ST2 specific code
Remove some more ST2 specific code
Python
mit
revolunet/sublimetext-markdown-preview,revolunet/sublimetext-markdown-preview
from __future__ import absolute_import import sublime import traceback - ST3 = int(sublime.version()) >= 3000 - - if ST3: - from markdown import Markdown, util + from markdown import Markdown, util - from markdown.extensions import Extension + from markdown.extensions import Extension - import importlib + import importlib - else: - from markdown import Markdown, util - from markdown.extensions import Extension class StMarkdown(Markdown): def __init__(self, *args, **kwargs): Markdown.__init__(self, *args, **kwargs) self.Meta = {} def registerExtensions(self, extensions, configs): """ Register extensions with this instance of Markdown. Keyword arguments: * extensions: A list of extensions, which can either be strings or objects. See the docstring on Markdown. * configs: A dictionary mapping module names to config options. """ for ext in extensions: try: if isinstance(ext, util.string_type): ext = self.build_extension(ext, configs.get(ext, [])) if isinstance(ext, Extension): ext.extendMarkdown(self, globals()) elif ext is not None: raise TypeError( 'Extension "%s.%s" must be of type: "markdown.Extension"' % (ext.__class__.__module__, ext.__class__.__name__)) except: print(str(traceback.format_exc())) continue return self
Remove some more ST2 specific code
## Code Before: from __future__ import absolute_import import sublime import traceback ST3 = int(sublime.version()) >= 3000 if ST3: from markdown import Markdown, util from markdown.extensions import Extension import importlib else: from markdown import Markdown, util from markdown.extensions import Extension class StMarkdown(Markdown): def __init__(self, *args, **kwargs): Markdown.__init__(self, *args, **kwargs) self.Meta = {} def registerExtensions(self, extensions, configs): """ Register extensions with this instance of Markdown. Keyword arguments: * extensions: A list of extensions, which can either be strings or objects. See the docstring on Markdown. * configs: A dictionary mapping module names to config options. """ for ext in extensions: try: if isinstance(ext, util.string_type): ext = self.build_extension(ext, configs.get(ext, [])) if isinstance(ext, Extension): ext.extendMarkdown(self, globals()) elif ext is not None: raise TypeError( 'Extension "%s.%s" must be of type: "markdown.Extension"' % (ext.__class__.__module__, ext.__class__.__name__)) except: print(str(traceback.format_exc())) continue return self ## Instruction: Remove some more ST2 specific code ## Code After: from __future__ import absolute_import import sublime import traceback from markdown import Markdown, util from markdown.extensions import Extension import importlib class StMarkdown(Markdown): def __init__(self, *args, **kwargs): Markdown.__init__(self, *args, **kwargs) self.Meta = {} def registerExtensions(self, extensions, configs): """ Register extensions with this instance of Markdown. Keyword arguments: * extensions: A list of extensions, which can either be strings or objects. See the docstring on Markdown. * configs: A dictionary mapping module names to config options. """ for ext in extensions: try: if isinstance(ext, util.string_type): ext = self.build_extension(ext, configs.get(ext, [])) if isinstance(ext, Extension): ext.extendMarkdown(self, globals()) elif ext is not None: raise TypeError( 'Extension "%s.%s" must be of type: "markdown.Extension"' % (ext.__class__.__module__, ext.__class__.__name__)) except: print(str(traceback.format_exc())) continue return self
... from markdown import Markdown, util from markdown.extensions import Extension import importlib ...
e2f2fbc0df695102c4d51bdf0e633798c3ae8417
yawf/messages/submessage.py
yawf/messages/submessage.py
from . import Message class Submessage(object): need_lock_object = True def __init__(self, obj, message_id, sender, raw_params, need_lock_object=True): self.obj = obj self.sender = sender self.message_id = message_id self.raw_params = raw_params self.need_lock_object = need_lock_object super(Submessage, self).__init__() def as_message(self, parent): return Message(self.sender, self.message_id, self.raw_params, parent_message_id=parent.unique_id, message_group=parent.message_group, ) def dispatch(self, parent_obj, parent_message): from yawf.dispatch import dispatch_message message = self.as_message(parent_message) return dispatch_message( self.obj, message=message, defer_side_effect=True, need_lock_object=self.need_lock_object) class RecursiveSubmessage(Submessage): def __init__(self, message_id, sender, raw_params): super(RecursiveSubmessage, self).__init__( obj=None, sender=sender, message_id=message_id, raw_params=raw_params) def dispatch(self, parent_obj, parent_message): from yawf.dispatch import dispatch_message message = self.as_message(parent_message) return dispatch_message( parent_obj, message=message, defer_side_effect=True, need_lock_object=False)
from . import Message class Submessage(object): need_lock_object = True def __init__(self, obj, message_id, sender, raw_params=None, need_lock_object=True): self.obj = obj self.sender = sender self.message_id = message_id self.raw_params = raw_params self.need_lock_object = need_lock_object super(Submessage, self).__init__() def as_message(self, parent): return Message(self.sender, self.message_id, self.raw_params, parent_message_id=parent.unique_id, message_group=parent.message_group, ) def dispatch(self, parent_obj, parent_message): from yawf.dispatch import dispatch_message message = self.as_message(parent_message) return dispatch_message( self.obj, message=message, defer_side_effect=True, need_lock_object=self.need_lock_object) class RecursiveSubmessage(Submessage): def __init__(self, message_id, sender, raw_params=None): super(RecursiveSubmessage, self).__init__( obj=None, sender=sender, message_id=message_id, raw_params=raw_params) def dispatch(self, parent_obj, parent_message): from yawf.dispatch import dispatch_message message = self.as_message(parent_message) return dispatch_message( parent_obj, message=message, defer_side_effect=True, need_lock_object=False)
Make raw_params an optional argument in Submessage
Make raw_params an optional argument in Submessage
Python
mit
freevoid/yawf
from . import Message class Submessage(object): need_lock_object = True - def __init__(self, obj, message_id, sender, raw_params, need_lock_object=True): + def __init__(self, obj, message_id, sender, raw_params=None, need_lock_object=True): self.obj = obj self.sender = sender self.message_id = message_id self.raw_params = raw_params self.need_lock_object = need_lock_object super(Submessage, self).__init__() def as_message(self, parent): return Message(self.sender, self.message_id, self.raw_params, parent_message_id=parent.unique_id, message_group=parent.message_group, ) def dispatch(self, parent_obj, parent_message): from yawf.dispatch import dispatch_message message = self.as_message(parent_message) return dispatch_message( self.obj, message=message, defer_side_effect=True, need_lock_object=self.need_lock_object) class RecursiveSubmessage(Submessage): - def __init__(self, message_id, sender, raw_params): + def __init__(self, message_id, sender, raw_params=None): super(RecursiveSubmessage, self).__init__( obj=None, sender=sender, message_id=message_id, raw_params=raw_params) def dispatch(self, parent_obj, parent_message): from yawf.dispatch import dispatch_message message = self.as_message(parent_message) return dispatch_message( parent_obj, message=message, defer_side_effect=True, need_lock_object=False)
Make raw_params an optional argument in Submessage
## Code Before: from . import Message class Submessage(object): need_lock_object = True def __init__(self, obj, message_id, sender, raw_params, need_lock_object=True): self.obj = obj self.sender = sender self.message_id = message_id self.raw_params = raw_params self.need_lock_object = need_lock_object super(Submessage, self).__init__() def as_message(self, parent): return Message(self.sender, self.message_id, self.raw_params, parent_message_id=parent.unique_id, message_group=parent.message_group, ) def dispatch(self, parent_obj, parent_message): from yawf.dispatch import dispatch_message message = self.as_message(parent_message) return dispatch_message( self.obj, message=message, defer_side_effect=True, need_lock_object=self.need_lock_object) class RecursiveSubmessage(Submessage): def __init__(self, message_id, sender, raw_params): super(RecursiveSubmessage, self).__init__( obj=None, sender=sender, message_id=message_id, raw_params=raw_params) def dispatch(self, parent_obj, parent_message): from yawf.dispatch import dispatch_message message = self.as_message(parent_message) return dispatch_message( parent_obj, message=message, defer_side_effect=True, need_lock_object=False) ## Instruction: Make raw_params an optional argument in Submessage ## Code After: from . import Message class Submessage(object): need_lock_object = True def __init__(self, obj, message_id, sender, raw_params=None, need_lock_object=True): self.obj = obj self.sender = sender self.message_id = message_id self.raw_params = raw_params self.need_lock_object = need_lock_object super(Submessage, self).__init__() def as_message(self, parent): return Message(self.sender, self.message_id, self.raw_params, parent_message_id=parent.unique_id, message_group=parent.message_group, ) def dispatch(self, parent_obj, parent_message): from yawf.dispatch import dispatch_message message = self.as_message(parent_message) return dispatch_message( self.obj, message=message, defer_side_effect=True, need_lock_object=self.need_lock_object) class RecursiveSubmessage(Submessage): def __init__(self, message_id, sender, raw_params=None): super(RecursiveSubmessage, self).__init__( obj=None, sender=sender, message_id=message_id, raw_params=raw_params) def dispatch(self, parent_obj, parent_message): from yawf.dispatch import dispatch_message message = self.as_message(parent_message) return dispatch_message( parent_obj, message=message, defer_side_effect=True, need_lock_object=False)
... def __init__(self, obj, message_id, sender, raw_params=None, need_lock_object=True): self.obj = obj ... def __init__(self, message_id, sender, raw_params=None): super(RecursiveSubmessage, self).__init__( ...
d187a8434c9d64171f76efa3055bdc06afbc8981
scripts/pystart.py
scripts/pystart.py
import os,sys,re from time import sleep from pprint import pprint home = os.path.expanduser('~') from math import log,ceil def clog2(num): return int(ceil(log(num,2))) if (sys.version_info > (3, 0)): # Python 3 code in this block exec(open(home+'/homedir/scripts/hexecho.py').read()) else: # Python 2 code in this block execfile(home+'/homedir/scripts/hexecho.py') hexoff print ("Imported os,sys,re,sleep,pprint. Defined clog2,hexon/hexoff")
import os,sys,re from time import sleep from pprint import pprint home = os.path.expanduser('~') from math import log,ceil sys.ps1 = '\001\033[96m\002>>> \001\033[0m\002' sys.ps2 = '\001\033[96m\002... \001\033[0m\002' def clog2(num): return int(ceil(log(num,2))) if (sys.version_info > (3, 0)): # Python 3 code in this block exec(open(home+'/homedir/scripts/hexecho.py').read()) else: # Python 2 code in this block execfile(home+'/homedir/scripts/hexecho.py') hexoff print ("Imported os,sys,re,sleep,pprint. Defined clog2,hexon/hexoff")
Add color to python prompt
Add color to python prompt
Python
mit
jdanders/homedir,jdanders/homedir,jdanders/homedir,jdanders/homedir
import os,sys,re from time import sleep from pprint import pprint home = os.path.expanduser('~') from math import log,ceil + sys.ps1 = '\001\033[96m\002>>> \001\033[0m\002' + sys.ps2 = '\001\033[96m\002... \001\033[0m\002' def clog2(num): return int(ceil(log(num,2))) if (sys.version_info > (3, 0)): # Python 3 code in this block exec(open(home+'/homedir/scripts/hexecho.py').read()) else: # Python 2 code in this block execfile(home+'/homedir/scripts/hexecho.py') hexoff print ("Imported os,sys,re,sleep,pprint. Defined clog2,hexon/hexoff")
Add color to python prompt
## Code Before: import os,sys,re from time import sleep from pprint import pprint home = os.path.expanduser('~') from math import log,ceil def clog2(num): return int(ceil(log(num,2))) if (sys.version_info > (3, 0)): # Python 3 code in this block exec(open(home+'/homedir/scripts/hexecho.py').read()) else: # Python 2 code in this block execfile(home+'/homedir/scripts/hexecho.py') hexoff print ("Imported os,sys,re,sleep,pprint. Defined clog2,hexon/hexoff") ## Instruction: Add color to python prompt ## Code After: import os,sys,re from time import sleep from pprint import pprint home = os.path.expanduser('~') from math import log,ceil sys.ps1 = '\001\033[96m\002>>> \001\033[0m\002' sys.ps2 = '\001\033[96m\002... \001\033[0m\002' def clog2(num): return int(ceil(log(num,2))) if (sys.version_info > (3, 0)): # Python 3 code in this block exec(open(home+'/homedir/scripts/hexecho.py').read()) else: # Python 2 code in this block execfile(home+'/homedir/scripts/hexecho.py') hexoff print ("Imported os,sys,re,sleep,pprint. Defined clog2,hexon/hexoff")
// ... existing code ... from math import log,ceil sys.ps1 = '\001\033[96m\002>>> \001\033[0m\002' sys.ps2 = '\001\033[96m\002... \001\033[0m\002' def clog2(num): // ... rest of the code ...
4e4112b548cc263da2a455c2db9a2c82a3f84e45
ecommerce/theming/models.py
ecommerce/theming/models.py
import logging from django.conf import settings from django.contrib.sites.models import Site from django.db import models logger = logging.getLogger(__name__) class SiteTheme(models.Model): """ This is where the information about the site's theme gets stored to the db. Fields: site (ForeignKey): Foreign Key field pointing to django Site model theme_dir_name (CharField): Contains directory name for any site's theme (e.g. 'red-theme') """ site = models.ForeignKey(Site, related_name='themes', on_delete=models.CASCADE) theme_dir_name = models.CharField(max_length=255) @staticmethod def get_theme(site): """ Get SiteTheme object for given site, returns default site theme if it can not find a theme for the given site and `DEFAULT_SITE_THEME` setting has a proper value. Args: site (django.contrib.sites.models.Site): site object related to the current site. Returns: SiteTheme object for given site or a default site set by `DEFAULT_SITE_THEME` """ if not site: logger.warning('A site must be specified when retrieving a theme.') return None logger.info('Retrieving theme for site [%d]...', site.id) theme = site.themes.first() if theme: logger.info( 'Setting theme for site [%d] to theme [%d] with assets in [%s]', site.id, theme.id, theme.theme_dir_name ) else: default_theme_dir = settings.DEFAULT_SITE_THEME if default_theme_dir: logger.info('No theme found for site [%d]. Using default assets in [%s]', site.id, default_theme_dir) theme = SiteTheme(site=site, theme_dir_name=settings.DEFAULT_SITE_THEME) else: logger.error('No default theme has been defined!') return theme
from django.conf import settings from django.contrib.sites.models import Site from django.db import models class SiteTheme(models.Model): """ This is where the information about the site's theme gets stored to the db. Fields: site (ForeignKey): Foreign Key field pointing to django Site model theme_dir_name (CharField): Contains directory name for any site's theme (e.g. 'red-theme') """ site = models.ForeignKey(Site, related_name='themes', on_delete=models.CASCADE) theme_dir_name = models.CharField(max_length=255) @staticmethod def get_theme(site): """ Get SiteTheme object for given site, returns default site theme if it can not find a theme for the given site and `DEFAULT_SITE_THEME` setting has a proper value. Args: site (django.contrib.sites.models.Site): site object related to the current site. Returns: SiteTheme object for given site or a default site set by `DEFAULT_SITE_THEME` """ if not site: return None theme = site.themes.first() if (not theme) and settings.DEFAULT_SITE_THEME: theme = SiteTheme(site=site, theme_dir_name=settings.DEFAULT_SITE_THEME) return theme
Revert "Added logging to SiteTheme.get_theme"
Revert "Added logging to SiteTheme.get_theme" This reverts commit f1436a255bb22ecd7b9ddca803240262bf484981.
Python
agpl-3.0
edx/ecommerce,eduNEXT/edunext-ecommerce,eduNEXT/edunext-ecommerce,edx/ecommerce,edx/ecommerce,edx/ecommerce,eduNEXT/edunext-ecommerce,eduNEXT/edunext-ecommerce
- import logging - from django.conf import settings from django.contrib.sites.models import Site from django.db import models - - logger = logging.getLogger(__name__) class SiteTheme(models.Model): """ This is where the information about the site's theme gets stored to the db. Fields: site (ForeignKey): Foreign Key field pointing to django Site model theme_dir_name (CharField): Contains directory name for any site's theme (e.g. 'red-theme') """ site = models.ForeignKey(Site, related_name='themes', on_delete=models.CASCADE) theme_dir_name = models.CharField(max_length=255) @staticmethod def get_theme(site): """ Get SiteTheme object for given site, returns default site theme if it can not find a theme for the given site and `DEFAULT_SITE_THEME` setting has a proper value. Args: site (django.contrib.sites.models.Site): site object related to the current site. Returns: SiteTheme object for given site or a default site set by `DEFAULT_SITE_THEME` """ if not site: - logger.warning('A site must be specified when retrieving a theme.') return None - logger.info('Retrieving theme for site [%d]...', site.id) theme = site.themes.first() - if theme: - logger.info( - 'Setting theme for site [%d] to theme [%d] with assets in [%s]', - site.id, theme.id, theme.theme_dir_name - ) - - else: - default_theme_dir = settings.DEFAULT_SITE_THEME + if (not theme) and settings.DEFAULT_SITE_THEME: - if default_theme_dir: - logger.info('No theme found for site [%d]. Using default assets in [%s]', site.id, default_theme_dir) - theme = SiteTheme(site=site, theme_dir_name=settings.DEFAULT_SITE_THEME) + theme = SiteTheme(site=site, theme_dir_name=settings.DEFAULT_SITE_THEME) - else: - logger.error('No default theme has been defined!') return theme
Revert "Added logging to SiteTheme.get_theme"
## Code Before: import logging from django.conf import settings from django.contrib.sites.models import Site from django.db import models logger = logging.getLogger(__name__) class SiteTheme(models.Model): """ This is where the information about the site's theme gets stored to the db. Fields: site (ForeignKey): Foreign Key field pointing to django Site model theme_dir_name (CharField): Contains directory name for any site's theme (e.g. 'red-theme') """ site = models.ForeignKey(Site, related_name='themes', on_delete=models.CASCADE) theme_dir_name = models.CharField(max_length=255) @staticmethod def get_theme(site): """ Get SiteTheme object for given site, returns default site theme if it can not find a theme for the given site and `DEFAULT_SITE_THEME` setting has a proper value. Args: site (django.contrib.sites.models.Site): site object related to the current site. Returns: SiteTheme object for given site or a default site set by `DEFAULT_SITE_THEME` """ if not site: logger.warning('A site must be specified when retrieving a theme.') return None logger.info('Retrieving theme for site [%d]...', site.id) theme = site.themes.first() if theme: logger.info( 'Setting theme for site [%d] to theme [%d] with assets in [%s]', site.id, theme.id, theme.theme_dir_name ) else: default_theme_dir = settings.DEFAULT_SITE_THEME if default_theme_dir: logger.info('No theme found for site [%d]. Using default assets in [%s]', site.id, default_theme_dir) theme = SiteTheme(site=site, theme_dir_name=settings.DEFAULT_SITE_THEME) else: logger.error('No default theme has been defined!') return theme ## Instruction: Revert "Added logging to SiteTheme.get_theme" ## Code After: from django.conf import settings from django.contrib.sites.models import Site from django.db import models class SiteTheme(models.Model): """ This is where the information about the site's theme gets stored to the db. Fields: site (ForeignKey): Foreign Key field pointing to django Site model theme_dir_name (CharField): Contains directory name for any site's theme (e.g. 'red-theme') """ site = models.ForeignKey(Site, related_name='themes', on_delete=models.CASCADE) theme_dir_name = models.CharField(max_length=255) @staticmethod def get_theme(site): """ Get SiteTheme object for given site, returns default site theme if it can not find a theme for the given site and `DEFAULT_SITE_THEME` setting has a proper value. Args: site (django.contrib.sites.models.Site): site object related to the current site. Returns: SiteTheme object for given site or a default site set by `DEFAULT_SITE_THEME` """ if not site: return None theme = site.themes.first() if (not theme) and settings.DEFAULT_SITE_THEME: theme = SiteTheme(site=site, theme_dir_name=settings.DEFAULT_SITE_THEME) return theme
... from django.conf import settings ... from django.db import models ... if not site: return None ... theme = site.themes.first() ... if (not theme) and settings.DEFAULT_SITE_THEME: theme = SiteTheme(site=site, theme_dir_name=settings.DEFAULT_SITE_THEME) ...
62845279b46d6f4394e05e666fe459a427bdd358
enthought/qt/QtCore.py
enthought/qt/QtCore.py
import os qt_api = os.environ.get('QT_API', 'pyqt') if qt_api == 'pyqt': from PyQt4.QtCore import * from PyQt4.QtCore import pyqtSignal as Signal from PyQt4.Qt import QCoreApplication from PyQt4.Qt import Qt else: from PySide.QtCore import *
import os qt_api = os.environ.get('QT_API', 'pyqt') if qt_api == 'pyqt': from PyQt4.QtCore import * from PyQt4.QtCore import pyqtSignal as Signal from PyQt4.Qt import QCoreApplication from PyQt4.Qt import Qt # Emulate PySide version metadata. __version__ = QT_VERSION_STR __version_info__ = tuple(map(int, QT_VERSION_STR.split('.'))) else: from PySide.QtCore import *
Add PySide-style version metadata when PyQt4 is present.
Add PySide-style version metadata when PyQt4 is present.
Python
bsd-3-clause
burnpanck/traits,burnpanck/traits
import os qt_api = os.environ.get('QT_API', 'pyqt') if qt_api == 'pyqt': from PyQt4.QtCore import * from PyQt4.QtCore import pyqtSignal as Signal from PyQt4.Qt import QCoreApplication from PyQt4.Qt import Qt + # Emulate PySide version metadata. + __version__ = QT_VERSION_STR + __version_info__ = tuple(map(int, QT_VERSION_STR.split('.'))) + else: from PySide.QtCore import *
Add PySide-style version metadata when PyQt4 is present.
## Code Before: import os qt_api = os.environ.get('QT_API', 'pyqt') if qt_api == 'pyqt': from PyQt4.QtCore import * from PyQt4.QtCore import pyqtSignal as Signal from PyQt4.Qt import QCoreApplication from PyQt4.Qt import Qt else: from PySide.QtCore import * ## Instruction: Add PySide-style version metadata when PyQt4 is present. ## Code After: import os qt_api = os.environ.get('QT_API', 'pyqt') if qt_api == 'pyqt': from PyQt4.QtCore import * from PyQt4.QtCore import pyqtSignal as Signal from PyQt4.Qt import QCoreApplication from PyQt4.Qt import Qt # Emulate PySide version metadata. __version__ = QT_VERSION_STR __version_info__ = tuple(map(int, QT_VERSION_STR.split('.'))) else: from PySide.QtCore import *
# ... existing code ... # Emulate PySide version metadata. __version__ = QT_VERSION_STR __version_info__ = tuple(map(int, QT_VERSION_STR.split('.'))) else: # ... rest of the code ...
8842bbf45ffe2a76832075e053dce90a95964bcd
Bookie/bookie/tests/__init__.py
Bookie/bookie/tests/__init__.py
import ConfigParser import os import unittest from pyramid.config import Configurator from pyramid import testing global_config = {} ini = ConfigParser.ConfigParser() ini.read('test.ini') settings = dict(ini.items('app:bookie')) def setup_db(settings): """ We need to create the test sqlite database to run our tests against If the db exists, remove it We're using the SA-Migrations API to create the db and catch it up to the latest migration level for testing In theory, we could use this API to do version specific testing as well if we needed to. If we want to run any tests with a fresh db we can call this function """ from migrate.versioning import api as mig sa_url = settings['sqlalchemy.url'] migrate_repository = 'migrations' # we're hackish here since we're going to assume the test db is whatever is # after the last slash of the SA url sqlite:///somedb.db db_name = sa_url[sa_url.rindex('/') + 1:] try: os.remove(db_name) except: pass open(db_name, 'w').close() mig.version_control(sa_url, migrate_repository) mig.upgrade(sa_url, migrate_repository) setup_db(settings)
import ConfigParser import os import unittest from pyramid.config import Configurator from pyramid import testing global_config = {} ini = ConfigParser.ConfigParser() # we need to pull the right ini for the test we want to run # by default pullup test.ini, but we might want to test mysql, pgsql, etc test_ini = os.environ.get('BOOKIE_TEST_INI', None) if test_ini: ini.read(test_ini) else: ini.read('test.ini') settings = dict(ini.items('app:bookie')) def setup_db(settings): """ We need to create the test sqlite database to run our tests against If the db exists, remove it We're using the SA-Migrations API to create the db and catch it up to the latest migration level for testing In theory, we could use this API to do version specific testing as well if we needed to. If we want to run any tests with a fresh db we can call this function """ from migrate.versioning import api as mig sa_url = settings['sqlalchemy.url'] migrate_repository = 'migrations' # we're hackish here since we're going to assume the test db is whatever is # after the last slash of the SA url sqlite:///somedb.db db_name = sa_url[sa_url.rindex('/') + 1:] try: os.remove(db_name) except: pass open(db_name, 'w').close() mig.version_control(sa_url, migrate_repository) mig.upgrade(sa_url, migrate_repository) setup_db(settings)
Add ability to set test ini via env variable
Add ability to set test ini via env variable
Python
agpl-3.0
charany1/Bookie,teodesson/Bookie,skmezanul/Bookie,teodesson/Bookie,skmezanul/Bookie,adamlincoln/Bookie,adamlincoln/Bookie,adamlincoln/Bookie,GreenLunar/Bookie,bookieio/Bookie,pombredanne/Bookie,wangjun/Bookie,adamlincoln/Bookie,pombredanne/Bookie,pombredanne/Bookie,skmezanul/Bookie,bookieio/Bookie,charany1/Bookie,GreenLunar/Bookie,wangjun/Bookie,bookieio/Bookie,bookieio/Bookie,GreenLunar/Bookie,charany1/Bookie,skmezanul/Bookie,GreenLunar/Bookie,teodesson/Bookie,wangjun/Bookie,wangjun/Bookie,teodesson/Bookie
import ConfigParser import os import unittest from pyramid.config import Configurator from pyramid import testing global_config = {} ini = ConfigParser.ConfigParser() + + # we need to pull the right ini for the test we want to run + # by default pullup test.ini, but we might want to test mysql, pgsql, etc + test_ini = os.environ.get('BOOKIE_TEST_INI', None) + if test_ini: + ini.read(test_ini) + else: - ini.read('test.ini') + ini.read('test.ini') + settings = dict(ini.items('app:bookie')) def setup_db(settings): """ We need to create the test sqlite database to run our tests against If the db exists, remove it We're using the SA-Migrations API to create the db and catch it up to the latest migration level for testing In theory, we could use this API to do version specific testing as well if we needed to. If we want to run any tests with a fresh db we can call this function """ from migrate.versioning import api as mig sa_url = settings['sqlalchemy.url'] migrate_repository = 'migrations' # we're hackish here since we're going to assume the test db is whatever is # after the last slash of the SA url sqlite:///somedb.db db_name = sa_url[sa_url.rindex('/') + 1:] try: os.remove(db_name) except: pass open(db_name, 'w').close() mig.version_control(sa_url, migrate_repository) mig.upgrade(sa_url, migrate_repository) setup_db(settings)
Add ability to set test ini via env variable
## Code Before: import ConfigParser import os import unittest from pyramid.config import Configurator from pyramid import testing global_config = {} ini = ConfigParser.ConfigParser() ini.read('test.ini') settings = dict(ini.items('app:bookie')) def setup_db(settings): """ We need to create the test sqlite database to run our tests against If the db exists, remove it We're using the SA-Migrations API to create the db and catch it up to the latest migration level for testing In theory, we could use this API to do version specific testing as well if we needed to. If we want to run any tests with a fresh db we can call this function """ from migrate.versioning import api as mig sa_url = settings['sqlalchemy.url'] migrate_repository = 'migrations' # we're hackish here since we're going to assume the test db is whatever is # after the last slash of the SA url sqlite:///somedb.db db_name = sa_url[sa_url.rindex('/') + 1:] try: os.remove(db_name) except: pass open(db_name, 'w').close() mig.version_control(sa_url, migrate_repository) mig.upgrade(sa_url, migrate_repository) setup_db(settings) ## Instruction: Add ability to set test ini via env variable ## Code After: import ConfigParser import os import unittest from pyramid.config import Configurator from pyramid import testing global_config = {} ini = ConfigParser.ConfigParser() # we need to pull the right ini for the test we want to run # by default pullup test.ini, but we might want to test mysql, pgsql, etc test_ini = os.environ.get('BOOKIE_TEST_INI', None) if test_ini: ini.read(test_ini) else: ini.read('test.ini') settings = dict(ini.items('app:bookie')) def setup_db(settings): """ We need to create the test sqlite database to run our tests against If the db exists, remove it We're using the SA-Migrations API to create the db and catch it up to the latest migration level for testing In theory, we could use this API to do version specific testing as well if we needed to. If we want to run any tests with a fresh db we can call this function """ from migrate.versioning import api as mig sa_url = settings['sqlalchemy.url'] migrate_repository = 'migrations' # we're hackish here since we're going to assume the test db is whatever is # after the last slash of the SA url sqlite:///somedb.db db_name = sa_url[sa_url.rindex('/') + 1:] try: os.remove(db_name) except: pass open(db_name, 'w').close() mig.version_control(sa_url, migrate_repository) mig.upgrade(sa_url, migrate_repository) setup_db(settings)
# ... existing code ... ini = ConfigParser.ConfigParser() # we need to pull the right ini for the test we want to run # by default pullup test.ini, but we might want to test mysql, pgsql, etc test_ini = os.environ.get('BOOKIE_TEST_INI', None) if test_ini: ini.read(test_ini) else: ini.read('test.ini') settings = dict(ini.items('app:bookie')) # ... rest of the code ...
0b28fe44514969470db926c6f38615a8a5478bf6
smoke_signal/__init__.py
smoke_signal/__init__.py
from flask import Flask, g from .main.views import main from .nojs.views import nojs from sqlalchemy import create_engine from smoke_signal.database.models import Base from sqlalchemy.orm import sessionmaker app = Flask(__name__, instance_relative_config=True) app.config.from_object("config") app.config.from_pyfile("config.py") app.register_blueprint(main) app.register_blueprint(nojs) @app.before_request def init_db(): engine = create_engine(app.config["DATABASE_PATH"]) if not engine.dialect.has_table(engine.connect(), "feed"): Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) g.db = Session() @app.teardown_appcontext def shutdown_session(exception=None): db = getattr(g, 'db', None) if db is not None: g.db.close()
from flask import Flask, g from .main.views import main from sqlalchemy import create_engine from smoke_signal.database.models import Base from sqlalchemy.orm import sessionmaker app = Flask(__name__, instance_relative_config=True) app.config.from_object("config") app.config.from_pyfile("config.py") app.register_blueprint(main) @app.before_request def init_db(): engine = create_engine(app.config["DATABASE_PATH"]) if not engine.dialect.has_table(engine.connect(), "feed"): Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) g.db = Session() @app.teardown_appcontext def shutdown_session(exception=None): db = getattr(g, 'db', None) if db is not None: g.db.close()
Remove the no-JS version from the app
Remove the no-JS version from the app I haven't looked into it for a long while.
Python
mit
flacerdk/smoke-signal,flacerdk/smoke-signal,flacerdk/smoke-signal
from flask import Flask, g from .main.views import main - from .nojs.views import nojs from sqlalchemy import create_engine from smoke_signal.database.models import Base from sqlalchemy.orm import sessionmaker app = Flask(__name__, instance_relative_config=True) app.config.from_object("config") app.config.from_pyfile("config.py") app.register_blueprint(main) - app.register_blueprint(nojs) @app.before_request def init_db(): engine = create_engine(app.config["DATABASE_PATH"]) if not engine.dialect.has_table(engine.connect(), "feed"): Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) g.db = Session() @app.teardown_appcontext def shutdown_session(exception=None): db = getattr(g, 'db', None) if db is not None: g.db.close()
Remove the no-JS version from the app
## Code Before: from flask import Flask, g from .main.views import main from .nojs.views import nojs from sqlalchemy import create_engine from smoke_signal.database.models import Base from sqlalchemy.orm import sessionmaker app = Flask(__name__, instance_relative_config=True) app.config.from_object("config") app.config.from_pyfile("config.py") app.register_blueprint(main) app.register_blueprint(nojs) @app.before_request def init_db(): engine = create_engine(app.config["DATABASE_PATH"]) if not engine.dialect.has_table(engine.connect(), "feed"): Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) g.db = Session() @app.teardown_appcontext def shutdown_session(exception=None): db = getattr(g, 'db', None) if db is not None: g.db.close() ## Instruction: Remove the no-JS version from the app ## Code After: from flask import Flask, g from .main.views import main from sqlalchemy import create_engine from smoke_signal.database.models import Base from sqlalchemy.orm import sessionmaker app = Flask(__name__, instance_relative_config=True) app.config.from_object("config") app.config.from_pyfile("config.py") app.register_blueprint(main) @app.before_request def init_db(): engine = create_engine(app.config["DATABASE_PATH"]) if not engine.dialect.has_table(engine.connect(), "feed"): Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) g.db = Session() @app.teardown_appcontext def shutdown_session(exception=None): db = getattr(g, 'db', None) if db is not None: g.db.close()
# ... existing code ... from .main.views import main from sqlalchemy import create_engine # ... modified code ... app.register_blueprint(main) # ... rest of the code ...
c1a1c976642fa1d8f17f89732f6c4fe5bd76d0de
devito/dimension.py
devito/dimension.py
import cgen from sympy import Symbol __all__ = ['Dimension', 'x', 'y', 'z', 't', 'p'] class Dimension(Symbol): """Index object that represents a problem dimension and thus defines a potential iteration space. :param size: Optional, size of the array dimension. :param buffered: Optional, boolean flag indicating whether to buffer variables when iterating this dimension. """ def __new__(cls, name, **kwargs): newobj = Symbol.__new__(cls, name) newobj.size = kwargs.get('size', None) newobj.buffered = kwargs.get('buffered', None) newobj._count = 0 return newobj def __str__(self): return self.name def get_varname(self): """Generates a new variables name based on an internal counter""" name = "%s%d" % (self.name, self._count) self._count += 1 return name @property def ccode(self): """C-level variable name of this dimension""" return "%s_size" % self.name if self.size is None else "%d" % self.size @property def decl(self): """Variable declaration for C-level kernel headers""" return cgen.Value("const int", self.ccode) # Set of default dimensions for space and time x = Dimension('x') y = Dimension('y') z = Dimension('z') t = Dimension('t') p = Dimension('p')
import cgen import numpy as np from sympy import Symbol __all__ = ['Dimension', 'x', 'y', 'z', 't', 'p'] class Dimension(Symbol): """Index object that represents a problem dimension and thus defines a potential iteration space. :param size: Optional, size of the array dimension. :param buffered: Optional, boolean flag indicating whether to buffer variables when iterating this dimension. """ def __new__(cls, name, **kwargs): newobj = Symbol.__new__(cls, name) newobj.size = kwargs.get('size', None) newobj.buffered = kwargs.get('buffered', None) newobj._count = 0 return newobj def __str__(self): return self.name def get_varname(self): """Generates a new variables name based on an internal counter""" name = "%s%d" % (self.name, self._count) self._count += 1 return name @property def ccode(self): """C-level variable name of this dimension""" return "%s_size" % self.name if self.size is None else "%d" % self.size @property def decl(self): """Variable declaration for C-level kernel headers""" return cgen.Value("const int", self.ccode) @property def dtype(self): """The data type of the iteration variable""" return np.int32 # Set of default dimensions for space and time x = Dimension('x') y = Dimension('y') z = Dimension('z') t = Dimension('t') p = Dimension('p')
Add dtype of iteration variable
Dimension: Add dtype of iteration variable
Python
mit
opesci/devito,opesci/devito
import cgen + + import numpy as np from sympy import Symbol + __all__ = ['Dimension', 'x', 'y', 'z', 't', 'p'] class Dimension(Symbol): """Index object that represents a problem dimension and thus defines a potential iteration space. :param size: Optional, size of the array dimension. :param buffered: Optional, boolean flag indicating whether to buffer variables when iterating this dimension. """ def __new__(cls, name, **kwargs): newobj = Symbol.__new__(cls, name) newobj.size = kwargs.get('size', None) newobj.buffered = kwargs.get('buffered', None) newobj._count = 0 return newobj def __str__(self): return self.name def get_varname(self): """Generates a new variables name based on an internal counter""" name = "%s%d" % (self.name, self._count) self._count += 1 return name @property def ccode(self): """C-level variable name of this dimension""" return "%s_size" % self.name if self.size is None else "%d" % self.size @property def decl(self): """Variable declaration for C-level kernel headers""" return cgen.Value("const int", self.ccode) + @property + def dtype(self): + """The data type of the iteration variable""" + return np.int32 + # Set of default dimensions for space and time x = Dimension('x') y = Dimension('y') z = Dimension('z') t = Dimension('t') p = Dimension('p')
Add dtype of iteration variable
## Code Before: import cgen from sympy import Symbol __all__ = ['Dimension', 'x', 'y', 'z', 't', 'p'] class Dimension(Symbol): """Index object that represents a problem dimension and thus defines a potential iteration space. :param size: Optional, size of the array dimension. :param buffered: Optional, boolean flag indicating whether to buffer variables when iterating this dimension. """ def __new__(cls, name, **kwargs): newobj = Symbol.__new__(cls, name) newobj.size = kwargs.get('size', None) newobj.buffered = kwargs.get('buffered', None) newobj._count = 0 return newobj def __str__(self): return self.name def get_varname(self): """Generates a new variables name based on an internal counter""" name = "%s%d" % (self.name, self._count) self._count += 1 return name @property def ccode(self): """C-level variable name of this dimension""" return "%s_size" % self.name if self.size is None else "%d" % self.size @property def decl(self): """Variable declaration for C-level kernel headers""" return cgen.Value("const int", self.ccode) # Set of default dimensions for space and time x = Dimension('x') y = Dimension('y') z = Dimension('z') t = Dimension('t') p = Dimension('p') ## Instruction: Add dtype of iteration variable ## Code After: import cgen import numpy as np from sympy import Symbol __all__ = ['Dimension', 'x', 'y', 'z', 't', 'p'] class Dimension(Symbol): """Index object that represents a problem dimension and thus defines a potential iteration space. :param size: Optional, size of the array dimension. :param buffered: Optional, boolean flag indicating whether to buffer variables when iterating this dimension. """ def __new__(cls, name, **kwargs): newobj = Symbol.__new__(cls, name) newobj.size = kwargs.get('size', None) newobj.buffered = kwargs.get('buffered', None) newobj._count = 0 return newobj def __str__(self): return self.name def get_varname(self): """Generates a new variables name based on an internal counter""" name = "%s%d" % (self.name, self._count) self._count += 1 return name @property def ccode(self): """C-level variable name of this dimension""" return "%s_size" % self.name if self.size is None else "%d" % self.size @property def decl(self): """Variable declaration for C-level kernel headers""" return cgen.Value("const int", self.ccode) @property def dtype(self): """The data type of the iteration variable""" return np.int32 # Set of default dimensions for space and time x = Dimension('x') y = Dimension('y') z = Dimension('z') t = Dimension('t') p = Dimension('p')
... import cgen import numpy as np from sympy import Symbol ... @property def dtype(self): """The data type of the iteration variable""" return np.int32 ...
ccc76f356a0480767eceff83d2b573aa922896f5
package/management/commands/repo_updater.py
package/management/commands/repo_updater.py
import logging import logging.config from django.core.management.base import NoArgsCommand from django.utils import timezone from package.models import Package logger = logging.getLogger(__name__) class Command(NoArgsCommand): help = "Updates all the packages in the system focusing on repo data" def handle(self, *args, **options): yesterday = timezone.now() - timezone.timedelta(1) for package in Package.objects.filter().iterator(): # keep this here because for now we only have one last_fetched field. package.repo.fetch_metadata(package, fetch_pypi=False) if package.last_fetched <= yesterday: continue package.repo.fetch_commits(package) # if package.repo.title == "Github": # msg = "{}. {}. {}".format(count, package.repo.github.ratelimit_remaining, package) # else: # msg = "{}. {}".format(count, package) # logger.info(msg)
import logging import logging.config from django.core.management.base import NoArgsCommand from django.utils import timezone from package.models import Package logger = logging.getLogger(__name__) class Command(NoArgsCommand): help = "Updates all the packages in the system focusing on repo data" def handle(self, *args, **options): yesterday = timezone.now() - timezone.timedelta(1) for package in Package.objects.filter().iterator(): # keep this here because for now we only have one last_fetched field. package.repo.fetch_metadata(package) if package.last_fetched <= yesterday: continue package.repo.fetch_commits(package) package.last_fetched = timezone.now() package.save() # if package.repo.title == "Github": # msg = "{}. {}. {}".format(count, package.repo.github.ratelimit_remaining, package) # else: # msg = "{}. {}".format(count, package) # logger.info(msg)
Fix the last_fetched and repo commands
Fix the last_fetched and repo commands
Python
mit
QLGu/djangopackages,QLGu/djangopackages,nanuxbe/djangopackages,nanuxbe/djangopackages,pydanny/djangopackages,nanuxbe/djangopackages,pydanny/djangopackages,pydanny/djangopackages,QLGu/djangopackages
import logging import logging.config from django.core.management.base import NoArgsCommand from django.utils import timezone from package.models import Package logger = logging.getLogger(__name__) class Command(NoArgsCommand): help = "Updates all the packages in the system focusing on repo data" def handle(self, *args, **options): yesterday = timezone.now() - timezone.timedelta(1) for package in Package.objects.filter().iterator(): # keep this here because for now we only have one last_fetched field. - package.repo.fetch_metadata(package, fetch_pypi=False) + package.repo.fetch_metadata(package) if package.last_fetched <= yesterday: continue package.repo.fetch_commits(package) + package.last_fetched = timezone.now() + package.save() # if package.repo.title == "Github": # msg = "{}. {}. {}".format(count, package.repo.github.ratelimit_remaining, package) # else: # msg = "{}. {}".format(count, package) # logger.info(msg)
Fix the last_fetched and repo commands
## Code Before: import logging import logging.config from django.core.management.base import NoArgsCommand from django.utils import timezone from package.models import Package logger = logging.getLogger(__name__) class Command(NoArgsCommand): help = "Updates all the packages in the system focusing on repo data" def handle(self, *args, **options): yesterday = timezone.now() - timezone.timedelta(1) for package in Package.objects.filter().iterator(): # keep this here because for now we only have one last_fetched field. package.repo.fetch_metadata(package, fetch_pypi=False) if package.last_fetched <= yesterday: continue package.repo.fetch_commits(package) # if package.repo.title == "Github": # msg = "{}. {}. {}".format(count, package.repo.github.ratelimit_remaining, package) # else: # msg = "{}. {}".format(count, package) # logger.info(msg) ## Instruction: Fix the last_fetched and repo commands ## Code After: import logging import logging.config from django.core.management.base import NoArgsCommand from django.utils import timezone from package.models import Package logger = logging.getLogger(__name__) class Command(NoArgsCommand): help = "Updates all the packages in the system focusing on repo data" def handle(self, *args, **options): yesterday = timezone.now() - timezone.timedelta(1) for package in Package.objects.filter().iterator(): # keep this here because for now we only have one last_fetched field. package.repo.fetch_metadata(package) if package.last_fetched <= yesterday: continue package.repo.fetch_commits(package) package.last_fetched = timezone.now() package.save() # if package.repo.title == "Github": # msg = "{}. {}. {}".format(count, package.repo.github.ratelimit_remaining, package) # else: # msg = "{}. {}".format(count, package) # logger.info(msg)
... # keep this here because for now we only have one last_fetched field. package.repo.fetch_metadata(package) if package.last_fetched <= yesterday: ... package.repo.fetch_commits(package) package.last_fetched = timezone.now() package.save() # if package.repo.title == "Github": ...
0ce7a7b396dd62c7e52e355108f8f037335bc5ca
src/sentry/api/endpoints/project_environments.py
src/sentry/api/endpoints/project_environments.py
from __future__ import absolute_import from rest_framework.response import Response from sentry.api.bases.project import ProjectEndpoint from sentry.api.serializers import serialize from sentry.models import EnvironmentProject environment_visibility_filter_options = { 'all': lambda queryset: queryset, 'hidden': lambda queryset: queryset.filter(is_hidden=True), 'visible': lambda queryset: queryset.exclude(is_hidden=True), } class ProjectEnvironmentsEndpoint(ProjectEndpoint): def get(self, request, project): queryset = EnvironmentProject.objects.filter( project=project, ).select_related('environment').order_by('environment__name') visibility = request.GET.get('visibility', 'visible') if visibility not in environment_visibility_filter_options: return Response({ 'detail': 'Invalid value for \'visibility\', valid values are: {!r}'.format( environment_visibility_filter_options.keys(), ), }, status=400) add_visibility_filters = environment_visibility_filter_options[visibility] queryset = add_visibility_filters(queryset) return Response(serialize(list(queryset), request.user))
from __future__ import absolute_import from rest_framework.response import Response from sentry.api.bases.project import ProjectEndpoint from sentry.api.serializers import serialize from sentry.models import EnvironmentProject environment_visibility_filter_options = { 'all': lambda queryset: queryset, 'hidden': lambda queryset: queryset.filter(is_hidden=True), 'visible': lambda queryset: queryset.exclude(is_hidden=True), } class ProjectEnvironmentsEndpoint(ProjectEndpoint): def get(self, request, project): queryset = EnvironmentProject.objects.filter( project=project, ).exclude( # HACK(mattrobenolt): We don't want to surface the # "No Environment" environment to the UI since it # doesn't really exist. This might very likely change # with new tagstore backend in the future, but until # then, we're hiding it since it causes more problems # than it's worth. environment__name='', ).select_related('environment').order_by('environment__name') visibility = request.GET.get('visibility', 'visible') if visibility not in environment_visibility_filter_options: return Response({ 'detail': 'Invalid value for \'visibility\', valid values are: {!r}'.format( environment_visibility_filter_options.keys(), ), }, status=400) add_visibility_filters = environment_visibility_filter_options[visibility] queryset = add_visibility_filters(queryset) return Response(serialize(list(queryset), request.user))
Hide "No Environment" environment from project environments
api: Hide "No Environment" environment from project environments
Python
bsd-3-clause
beeftornado/sentry,beeftornado/sentry,mvaled/sentry,ifduyue/sentry,ifduyue/sentry,mvaled/sentry,mvaled/sentry,beeftornado/sentry,mvaled/sentry,looker/sentry,looker/sentry,looker/sentry,ifduyue/sentry,ifduyue/sentry,mvaled/sentry,looker/sentry,mvaled/sentry,ifduyue/sentry,looker/sentry
from __future__ import absolute_import from rest_framework.response import Response from sentry.api.bases.project import ProjectEndpoint from sentry.api.serializers import serialize from sentry.models import EnvironmentProject environment_visibility_filter_options = { 'all': lambda queryset: queryset, 'hidden': lambda queryset: queryset.filter(is_hidden=True), 'visible': lambda queryset: queryset.exclude(is_hidden=True), } class ProjectEnvironmentsEndpoint(ProjectEndpoint): def get(self, request, project): queryset = EnvironmentProject.objects.filter( project=project, + ).exclude( + # HACK(mattrobenolt): We don't want to surface the + # "No Environment" environment to the UI since it + # doesn't really exist. This might very likely change + # with new tagstore backend in the future, but until + # then, we're hiding it since it causes more problems + # than it's worth. + environment__name='', ).select_related('environment').order_by('environment__name') visibility = request.GET.get('visibility', 'visible') if visibility not in environment_visibility_filter_options: return Response({ 'detail': 'Invalid value for \'visibility\', valid values are: {!r}'.format( environment_visibility_filter_options.keys(), ), }, status=400) add_visibility_filters = environment_visibility_filter_options[visibility] queryset = add_visibility_filters(queryset) return Response(serialize(list(queryset), request.user))
Hide "No Environment" environment from project environments
## Code Before: from __future__ import absolute_import from rest_framework.response import Response from sentry.api.bases.project import ProjectEndpoint from sentry.api.serializers import serialize from sentry.models import EnvironmentProject environment_visibility_filter_options = { 'all': lambda queryset: queryset, 'hidden': lambda queryset: queryset.filter(is_hidden=True), 'visible': lambda queryset: queryset.exclude(is_hidden=True), } class ProjectEnvironmentsEndpoint(ProjectEndpoint): def get(self, request, project): queryset = EnvironmentProject.objects.filter( project=project, ).select_related('environment').order_by('environment__name') visibility = request.GET.get('visibility', 'visible') if visibility not in environment_visibility_filter_options: return Response({ 'detail': 'Invalid value for \'visibility\', valid values are: {!r}'.format( environment_visibility_filter_options.keys(), ), }, status=400) add_visibility_filters = environment_visibility_filter_options[visibility] queryset = add_visibility_filters(queryset) return Response(serialize(list(queryset), request.user)) ## Instruction: Hide "No Environment" environment from project environments ## Code After: from __future__ import absolute_import from rest_framework.response import Response from sentry.api.bases.project import ProjectEndpoint from sentry.api.serializers import serialize from sentry.models import EnvironmentProject environment_visibility_filter_options = { 'all': lambda queryset: queryset, 'hidden': lambda queryset: queryset.filter(is_hidden=True), 'visible': lambda queryset: queryset.exclude(is_hidden=True), } class ProjectEnvironmentsEndpoint(ProjectEndpoint): def get(self, request, project): queryset = EnvironmentProject.objects.filter( project=project, ).exclude( # HACK(mattrobenolt): We don't want to surface the # "No Environment" environment to the UI since it # doesn't really exist. This might very likely change # with new tagstore backend in the future, but until # then, we're hiding it since it causes more problems # than it's worth. environment__name='', ).select_related('environment').order_by('environment__name') visibility = request.GET.get('visibility', 'visible') if visibility not in environment_visibility_filter_options: return Response({ 'detail': 'Invalid value for \'visibility\', valid values are: {!r}'.format( environment_visibility_filter_options.keys(), ), }, status=400) add_visibility_filters = environment_visibility_filter_options[visibility] queryset = add_visibility_filters(queryset) return Response(serialize(list(queryset), request.user))
... project=project, ).exclude( # HACK(mattrobenolt): We don't want to surface the # "No Environment" environment to the UI since it # doesn't really exist. This might very likely change # with new tagstore backend in the future, but until # then, we're hiding it since it causes more problems # than it's worth. environment__name='', ).select_related('environment').order_by('environment__name') ...
3f1aeba98cd4bc2f326f9c18c34e66c396be99cf
scikits/statsmodels/tools/tests/test_data.py
scikits/statsmodels/tools/tests/test_data.py
import pandas import numpy as np from scikits.statsmodels.tools import data def test_missing_data_pandas(): """ Fixes GH: #144 """ X = np.random.random((10,5)) X[1,2] = np.nan df = pandas.DataFrame(X) vals, cnames, rnames = data.interpret_data(df) np.testing.assert_equal(rnames, [0,2,3,4,5,6,7,8,9])
import pandas import numpy as np from scikits.statsmodels.tools import data def test_missing_data_pandas(): """ Fixes GH: #144 """ X = np.random.random((10,5)) X[1,2] = np.nan df = pandas.DataFrame(X) vals, cnames, rnames = data.interpret_data(df) np.testing.assert_equal(rnames, [0,2,3,4,5,6,7,8,9]) def test_structarray(): X = np.random.random((10,)).astype([('var1', 'f8'), ('var2', 'f8'), ('var3', 'f8')]) vals, cnames, rnames = data.interpret_data(X) np.testing.assert_equal(cnames, X.dtype.names) np.testing.assert_equal(vals, X.view((float,3))) np.testing.assert_equal(rnames, None) def test_recarray(): X = np.random.random((10,)).astype([('var1', 'f8'), ('var2', 'f8'), ('var3', 'f8')]) vals, cnames, rnames = data.interpret_data(X.view(np.recarray)) np.testing.assert_equal(cnames, X.dtype.names) np.testing.assert_equal(vals, X.view((float,3))) np.testing.assert_equal(rnames, None) def test_dataframe(): X = np.random.random((10,5)) df = pandas.DataFrame(X) vals, cnames, rnames = data.interpret_data(df) np.testing.assert_equal(vals, df.values) np.testing.assert_equal(rnames, df.index) np.testing.assert_equal(cnames, df.columns)
Add some tests for unused function
TST: Add some tests for unused function
Python
bsd-3-clause
Averroes/statsmodels,saketkc/statsmodels,wwf5067/statsmodels,phobson/statsmodels,musically-ut/statsmodels,hlin117/statsmodels,cbmoore/statsmodels,ChadFulton/statsmodels,pprett/statsmodels,statsmodels/statsmodels,gef756/statsmodels,rgommers/statsmodels,alekz112/statsmodels,jstoxrocky/statsmodels,kiyoto/statsmodels,musically-ut/statsmodels,Averroes/statsmodels,jstoxrocky/statsmodels,gef756/statsmodels,phobson/statsmodels,edhuckle/statsmodels,kiyoto/statsmodels,josef-pkt/statsmodels,Averroes/statsmodels,yl565/statsmodels,bert9bert/statsmodels,huongttlan/statsmodels,jstoxrocky/statsmodels,alekz112/statsmodels,alekz112/statsmodels,wzbozon/statsmodels,wzbozon/statsmodels,wkfwkf/statsmodels,wwf5067/statsmodels,Averroes/statsmodels,wwf5067/statsmodels,yl565/statsmodels,rgommers/statsmodels,bavardage/statsmodels,hlin117/statsmodels,cbmoore/statsmodels,adammenges/statsmodels,ChadFulton/statsmodels,adammenges/statsmodels,statsmodels/statsmodels,phobson/statsmodels,yarikoptic/pystatsmodels,bsipocz/statsmodels,edhuckle/statsmodels,astocko/statsmodels,yarikoptic/pystatsmodels,DonBeo/statsmodels,alekz112/statsmodels,YihaoLu/statsmodels,nvoron23/statsmodels,cbmoore/statsmodels,bsipocz/statsmodels,DonBeo/statsmodels,waynenilsen/statsmodels,kiyoto/statsmodels,nvoron23/statsmodels,waynenilsen/statsmodels,jseabold/statsmodels,detrout/debian-statsmodels,wkfwkf/statsmodels,rgommers/statsmodels,josef-pkt/statsmodels,astocko/statsmodels,bzero/statsmodels,jseabold/statsmodels,bavardage/statsmodels,pprett/statsmodels,bzero/statsmodels,YihaoLu/statsmodels,bashtage/statsmodels,bashtage/statsmodels,bert9bert/statsmodels,detrout/debian-statsmodels,wdurhamh/statsmodels,kiyoto/statsmodels,rgommers/statsmodels,yl565/statsmodels,nguyentu1602/statsmodels,wzbozon/statsmodels,DonBeo/statsmodels,ChadFulton/statsmodels,pprett/statsmodels,hainm/statsmodels,bashtage/statsmodels,wdurhamh/statsmodels,saketkc/statsmodels,bert9bert/statsmodels,wdurhamh/statsmodels,statsmodels/statsmodels,gef756/statsmodels,hainm/statsmodels,rgommers/statsmodels,bashtage/statsmodels,YihaoLu/statsmodels,statsmodels/statsmodels,cbmoore/statsmodels,wdurhamh/statsmodels,musically-ut/statsmodels,phobson/statsmodels,kiyoto/statsmodels,wkfwkf/statsmodels,wdurhamh/statsmodels,YihaoLu/statsmodels,huongttlan/statsmodels,bert9bert/statsmodels,josef-pkt/statsmodels,detrout/debian-statsmodels,waynenilsen/statsmodels,bashtage/statsmodels,hainm/statsmodels,bsipocz/statsmodels,edhuckle/statsmodels,bavardage/statsmodels,DonBeo/statsmodels,bzero/statsmodels,jseabold/statsmodels,bashtage/statsmodels,statsmodels/statsmodels,gef756/statsmodels,hlin117/statsmodels,waynenilsen/statsmodels,jseabold/statsmodels,astocko/statsmodels,bavardage/statsmodels,jseabold/statsmodels,wkfwkf/statsmodels,pprett/statsmodels,yarikoptic/pystatsmodels,wkfwkf/statsmodels,nvoron23/statsmodels,ChadFulton/statsmodels,saketkc/statsmodels,nguyentu1602/statsmodels,musically-ut/statsmodels,cbmoore/statsmodels,bsipocz/statsmodels,saketkc/statsmodels,gef756/statsmodels,nguyentu1602/statsmodels,astocko/statsmodels,bzero/statsmodels,bzero/statsmodels,nvoron23/statsmodels,nvoron23/statsmodels,ChadFulton/statsmodels,josef-pkt/statsmodels,statsmodels/statsmodels,jstoxrocky/statsmodels,phobson/statsmodels,adammenges/statsmodels,wwf5067/statsmodels,ChadFulton/statsmodels,edhuckle/statsmodels,huongttlan/statsmodels,bert9bert/statsmodels,hainm/statsmodels,bavardage/statsmodels,YihaoLu/statsmodels,DonBeo/statsmodels,detrout/debian-statsmodels,josef-pkt/statsmodels,adammenges/statsmodels,huongttlan/statsmodels,josef-pkt/statsmodels,wzbozon/statsmodels,hlin117/statsmodels,yl565/statsmodels,wzbozon/statsmodels,saketkc/statsmodels,nguyentu1602/statsmodels,edhuckle/statsmodels,yl565/statsmodels
import pandas import numpy as np from scikits.statsmodels.tools import data def test_missing_data_pandas(): """ Fixes GH: #144 """ X = np.random.random((10,5)) X[1,2] = np.nan df = pandas.DataFrame(X) vals, cnames, rnames = data.interpret_data(df) np.testing.assert_equal(rnames, [0,2,3,4,5,6,7,8,9]) + def test_structarray(): + X = np.random.random((10,)).astype([('var1', 'f8'), + ('var2', 'f8'), + ('var3', 'f8')]) + vals, cnames, rnames = data.interpret_data(X) + np.testing.assert_equal(cnames, X.dtype.names) + np.testing.assert_equal(vals, X.view((float,3))) + np.testing.assert_equal(rnames, None) + + def test_recarray(): + X = np.random.random((10,)).astype([('var1', 'f8'), + ('var2', 'f8'), + ('var3', 'f8')]) + vals, cnames, rnames = data.interpret_data(X.view(np.recarray)) + np.testing.assert_equal(cnames, X.dtype.names) + np.testing.assert_equal(vals, X.view((float,3))) + np.testing.assert_equal(rnames, None) + + + def test_dataframe(): + X = np.random.random((10,5)) + df = pandas.DataFrame(X) + vals, cnames, rnames = data.interpret_data(df) + np.testing.assert_equal(vals, df.values) + np.testing.assert_equal(rnames, df.index) + np.testing.assert_equal(cnames, df.columns) +
Add some tests for unused function
## Code Before: import pandas import numpy as np from scikits.statsmodels.tools import data def test_missing_data_pandas(): """ Fixes GH: #144 """ X = np.random.random((10,5)) X[1,2] = np.nan df = pandas.DataFrame(X) vals, cnames, rnames = data.interpret_data(df) np.testing.assert_equal(rnames, [0,2,3,4,5,6,7,8,9]) ## Instruction: Add some tests for unused function ## Code After: import pandas import numpy as np from scikits.statsmodels.tools import data def test_missing_data_pandas(): """ Fixes GH: #144 """ X = np.random.random((10,5)) X[1,2] = np.nan df = pandas.DataFrame(X) vals, cnames, rnames = data.interpret_data(df) np.testing.assert_equal(rnames, [0,2,3,4,5,6,7,8,9]) def test_structarray(): X = np.random.random((10,)).astype([('var1', 'f8'), ('var2', 'f8'), ('var3', 'f8')]) vals, cnames, rnames = data.interpret_data(X) np.testing.assert_equal(cnames, X.dtype.names) np.testing.assert_equal(vals, X.view((float,3))) np.testing.assert_equal(rnames, None) def test_recarray(): X = np.random.random((10,)).astype([('var1', 'f8'), ('var2', 'f8'), ('var3', 'f8')]) vals, cnames, rnames = data.interpret_data(X.view(np.recarray)) np.testing.assert_equal(cnames, X.dtype.names) np.testing.assert_equal(vals, X.view((float,3))) np.testing.assert_equal(rnames, None) def test_dataframe(): X = np.random.random((10,5)) df = pandas.DataFrame(X) vals, cnames, rnames = data.interpret_data(df) np.testing.assert_equal(vals, df.values) np.testing.assert_equal(rnames, df.index) np.testing.assert_equal(cnames, df.columns)
... np.testing.assert_equal(rnames, [0,2,3,4,5,6,7,8,9]) def test_structarray(): X = np.random.random((10,)).astype([('var1', 'f8'), ('var2', 'f8'), ('var3', 'f8')]) vals, cnames, rnames = data.interpret_data(X) np.testing.assert_equal(cnames, X.dtype.names) np.testing.assert_equal(vals, X.view((float,3))) np.testing.assert_equal(rnames, None) def test_recarray(): X = np.random.random((10,)).astype([('var1', 'f8'), ('var2', 'f8'), ('var3', 'f8')]) vals, cnames, rnames = data.interpret_data(X.view(np.recarray)) np.testing.assert_equal(cnames, X.dtype.names) np.testing.assert_equal(vals, X.view((float,3))) np.testing.assert_equal(rnames, None) def test_dataframe(): X = np.random.random((10,5)) df = pandas.DataFrame(X) vals, cnames, rnames = data.interpret_data(df) np.testing.assert_equal(vals, df.values) np.testing.assert_equal(rnames, df.index) np.testing.assert_equal(cnames, df.columns) ...
5aff8defb8baf83176ea861b03de04a9d6ac8a31
bundles/views.py
bundles/views.py
from django.views.generic import DetailView, ListView from rest_framework import filters, generics, permissions from rest_framework.response import Response from . import models, serializers class BundleList(ListView): model = models.Bundle context_object_name = 'bundles' paginate_by = 25 class BundleDetail(DetailView): model = models.Bundle context_object_name = 'bundle' class BundleView(generics.RetrieveAPIView): serializer_class = serializers.BundleSerializer permission_classes = [permissions.IsAuthenticated] def get(self, request, slug): try: bundle = models.Bundle.objects.get(slug=slug) except models.Bundle.DoesNotExist: return Response(status=404) serializer = serializers.BundleSerializer(bundle) return Response(serializer.data)
from django.views.generic import DetailView, ListView from rest_framework import filters, generics, permissions from rest_framework.response import Response from . import models, serializers class BundleList(ListView): model = models.Bundle context_object_name = 'bundles' paginate_by = 25 class BundleDetail(DetailView): model = models.Bundle context_object_name = 'bundle' class BundleView(generics.RetrieveAPIView): serializer_class = serializers.BundleSerializer def get(self, request, slug): try: bundle = models.Bundle.objects.get(slug=slug) except models.Bundle.DoesNotExist: return Response(status=404) serializer = serializers.BundleSerializer(bundle) return Response(serializer.data)
Make bundle view accessible to anyone
Make bundle view accessible to anyone
Python
agpl-3.0
lutris/website,lutris/website,lutris/website,lutris/website
from django.views.generic import DetailView, ListView from rest_framework import filters, generics, permissions from rest_framework.response import Response from . import models, serializers class BundleList(ListView): model = models.Bundle context_object_name = 'bundles' paginate_by = 25 class BundleDetail(DetailView): model = models.Bundle context_object_name = 'bundle' class BundleView(generics.RetrieveAPIView): serializer_class = serializers.BundleSerializer - permission_classes = [permissions.IsAuthenticated] def get(self, request, slug): try: bundle = models.Bundle.objects.get(slug=slug) except models.Bundle.DoesNotExist: return Response(status=404) serializer = serializers.BundleSerializer(bundle) return Response(serializer.data)
Make bundle view accessible to anyone
## Code Before: from django.views.generic import DetailView, ListView from rest_framework import filters, generics, permissions from rest_framework.response import Response from . import models, serializers class BundleList(ListView): model = models.Bundle context_object_name = 'bundles' paginate_by = 25 class BundleDetail(DetailView): model = models.Bundle context_object_name = 'bundle' class BundleView(generics.RetrieveAPIView): serializer_class = serializers.BundleSerializer permission_classes = [permissions.IsAuthenticated] def get(self, request, slug): try: bundle = models.Bundle.objects.get(slug=slug) except models.Bundle.DoesNotExist: return Response(status=404) serializer = serializers.BundleSerializer(bundle) return Response(serializer.data) ## Instruction: Make bundle view accessible to anyone ## Code After: from django.views.generic import DetailView, ListView from rest_framework import filters, generics, permissions from rest_framework.response import Response from . import models, serializers class BundleList(ListView): model = models.Bundle context_object_name = 'bundles' paginate_by = 25 class BundleDetail(DetailView): model = models.Bundle context_object_name = 'bundle' class BundleView(generics.RetrieveAPIView): serializer_class = serializers.BundleSerializer def get(self, request, slug): try: bundle = models.Bundle.objects.get(slug=slug) except models.Bundle.DoesNotExist: return Response(status=404) serializer = serializers.BundleSerializer(bundle) return Response(serializer.data)
// ... existing code ... serializer_class = serializers.BundleSerializer // ... rest of the code ...
fdf33278f66028a932dbecb999f66445ab0a3cd1
shuup/admin/modules/product_types/views/edit.py
shuup/admin/modules/product_types/views/edit.py
from __future__ import unicode_literals from django import forms from shuup.admin.utils.views import CreateOrUpdateView from shuup.core.models import ProductType from shuup.utils.multilanguage_model_form import MultiLanguageModelForm class ProductTypeForm(MultiLanguageModelForm): class Meta: model = ProductType exclude = () # All the fields! widgets = { "attributes": forms.CheckboxSelectMultiple } class ProductTypeEditView(CreateOrUpdateView): model = ProductType form_class = ProductTypeForm template_name = "shuup/admin/product_types/edit.jinja" context_object_name = "product_type"
from __future__ import unicode_literals from shuup.admin.forms.fields import Select2MultipleField from shuup.admin.utils.views import CreateOrUpdateView from shuup.core.models import Attribute, ProductType from shuup.utils.multilanguage_model_form import MultiLanguageModelForm class ProductTypeForm(MultiLanguageModelForm): attributes = Select2MultipleField(model=Attribute, required=False) class Meta: model = ProductType exclude = () def __init__(self, **kwargs): super(ProductTypeForm, self).__init__(**kwargs) if self.instance.pk: choices = [(a.pk, a.name) for a in self.instance.attributes.all()] self.fields["attributes"].widget.choices = choices self.fields["attributes"].initial = [pk for pk, name in choices] def clean_attributes(self): attributes = [int(a_id) for a_id in self.cleaned_data.get("attributes", [])] return Attribute.objects.filter(pk__in=attributes).all() def save(self, commit=True): obj = super(ProductTypeForm, self).save(commit=commit) obj.attributes.clear() obj.attributes = self.cleaned_data["attributes"] return self.instance class ProductTypeEditView(CreateOrUpdateView): model = ProductType form_class = ProductTypeForm template_name = "shuup/admin/product_types/edit.jinja" context_object_name = "product_type"
Use Select2 in attribute selection
Use Select2 in attribute selection With large amounts of attributes product type creation was really slow Refs SH-73
Python
agpl-3.0
shawnadelic/shuup,suutari-ai/shoop,shoopio/shoop,suutari-ai/shoop,shawnadelic/shuup,hrayr-artunyan/shuup,suutari/shoop,suutari/shoop,hrayr-artunyan/shuup,suutari/shoop,suutari-ai/shoop,hrayr-artunyan/shuup,shoopio/shoop,shawnadelic/shuup,shoopio/shoop
from __future__ import unicode_literals + from shuup.admin.forms.fields import Select2MultipleField - from django import forms - from shuup.admin.utils.views import CreateOrUpdateView - from shuup.core.models import ProductType + from shuup.core.models import Attribute, ProductType from shuup.utils.multilanguage_model_form import MultiLanguageModelForm class ProductTypeForm(MultiLanguageModelForm): + attributes = Select2MultipleField(model=Attribute, required=False) + class Meta: model = ProductType - exclude = () # All the fields! - widgets = { - "attributes": forms.CheckboxSelectMultiple - } + exclude = () + + def __init__(self, **kwargs): + super(ProductTypeForm, self).__init__(**kwargs) + if self.instance.pk: + choices = [(a.pk, a.name) for a in self.instance.attributes.all()] + self.fields["attributes"].widget.choices = choices + self.fields["attributes"].initial = [pk for pk, name in choices] + + def clean_attributes(self): + attributes = [int(a_id) for a_id in self.cleaned_data.get("attributes", [])] + return Attribute.objects.filter(pk__in=attributes).all() + + def save(self, commit=True): + obj = super(ProductTypeForm, self).save(commit=commit) + obj.attributes.clear() + obj.attributes = self.cleaned_data["attributes"] + return self.instance class ProductTypeEditView(CreateOrUpdateView): model = ProductType form_class = ProductTypeForm template_name = "shuup/admin/product_types/edit.jinja" context_object_name = "product_type"
Use Select2 in attribute selection
## Code Before: from __future__ import unicode_literals from django import forms from shuup.admin.utils.views import CreateOrUpdateView from shuup.core.models import ProductType from shuup.utils.multilanguage_model_form import MultiLanguageModelForm class ProductTypeForm(MultiLanguageModelForm): class Meta: model = ProductType exclude = () # All the fields! widgets = { "attributes": forms.CheckboxSelectMultiple } class ProductTypeEditView(CreateOrUpdateView): model = ProductType form_class = ProductTypeForm template_name = "shuup/admin/product_types/edit.jinja" context_object_name = "product_type" ## Instruction: Use Select2 in attribute selection ## Code After: from __future__ import unicode_literals from shuup.admin.forms.fields import Select2MultipleField from shuup.admin.utils.views import CreateOrUpdateView from shuup.core.models import Attribute, ProductType from shuup.utils.multilanguage_model_form import MultiLanguageModelForm class ProductTypeForm(MultiLanguageModelForm): attributes = Select2MultipleField(model=Attribute, required=False) class Meta: model = ProductType exclude = () def __init__(self, **kwargs): super(ProductTypeForm, self).__init__(**kwargs) if self.instance.pk: choices = [(a.pk, a.name) for a in self.instance.attributes.all()] self.fields["attributes"].widget.choices = choices self.fields["attributes"].initial = [pk for pk, name in choices] def clean_attributes(self): attributes = [int(a_id) for a_id in self.cleaned_data.get("attributes", [])] return Attribute.objects.filter(pk__in=attributes).all() def save(self, commit=True): obj = super(ProductTypeForm, self).save(commit=commit) obj.attributes.clear() obj.attributes = self.cleaned_data["attributes"] return self.instance class ProductTypeEditView(CreateOrUpdateView): model = ProductType form_class = ProductTypeForm template_name = "shuup/admin/product_types/edit.jinja" context_object_name = "product_type"
// ... existing code ... from shuup.admin.forms.fields import Select2MultipleField from shuup.admin.utils.views import CreateOrUpdateView from shuup.core.models import Attribute, ProductType from shuup.utils.multilanguage_model_form import MultiLanguageModelForm // ... modified code ... class ProductTypeForm(MultiLanguageModelForm): attributes = Select2MultipleField(model=Attribute, required=False) class Meta: ... model = ProductType exclude = () def __init__(self, **kwargs): super(ProductTypeForm, self).__init__(**kwargs) if self.instance.pk: choices = [(a.pk, a.name) for a in self.instance.attributes.all()] self.fields["attributes"].widget.choices = choices self.fields["attributes"].initial = [pk for pk, name in choices] def clean_attributes(self): attributes = [int(a_id) for a_id in self.cleaned_data.get("attributes", [])] return Attribute.objects.filter(pk__in=attributes).all() def save(self, commit=True): obj = super(ProductTypeForm, self).save(commit=commit) obj.attributes.clear() obj.attributes = self.cleaned_data["attributes"] return self.instance // ... rest of the code ...
72302898ba5a6fc74dcedfc6f2049f4a0c1299ac
src/conftest.py
src/conftest.py
import pytest def pytest_addoption(parser): parser.addoption("--filter-project-name", action="store", default=None, help="pass a project name to filter a test file to run only tests related to it") @pytest.fixture def filter_project_name(request): return request.config.getoption('--filter-project-name')
import logging import pytest import buildercore.config LOG = logging.getLogger("conftest") def pytest_addoption(parser): parser.addoption("--filter-project-name", action="store", default=None, help="pass a project name to filter a test file to run only tests related to it") @pytest.fixture def filter_project_name(request): return request.config.getoption('--filter-project-name') def pytest_runtest_setup(item): LOG.info("Setting up %s::%s", item.cls, item.name) def pytest_runtest_teardown(item, nextitem): LOG.info("Tearing down up %s::%s", item.cls, item.name)
Add logs for test start and end
Add logs for test start and end
Python
mit
elifesciences/builder,elifesciences/builder
+ import logging import pytest + import buildercore.config + + LOG = logging.getLogger("conftest") def pytest_addoption(parser): parser.addoption("--filter-project-name", action="store", default=None, help="pass a project name to filter a test file to run only tests related to it") @pytest.fixture def filter_project_name(request): return request.config.getoption('--filter-project-name') + def pytest_runtest_setup(item): + LOG.info("Setting up %s::%s", item.cls, item.name) + + def pytest_runtest_teardown(item, nextitem): + LOG.info("Tearing down up %s::%s", item.cls, item.name) +
Add logs for test start and end
## Code Before: import pytest def pytest_addoption(parser): parser.addoption("--filter-project-name", action="store", default=None, help="pass a project name to filter a test file to run only tests related to it") @pytest.fixture def filter_project_name(request): return request.config.getoption('--filter-project-name') ## Instruction: Add logs for test start and end ## Code After: import logging import pytest import buildercore.config LOG = logging.getLogger("conftest") def pytest_addoption(parser): parser.addoption("--filter-project-name", action="store", default=None, help="pass a project name to filter a test file to run only tests related to it") @pytest.fixture def filter_project_name(request): return request.config.getoption('--filter-project-name') def pytest_runtest_setup(item): LOG.info("Setting up %s::%s", item.cls, item.name) def pytest_runtest_teardown(item, nextitem): LOG.info("Tearing down up %s::%s", item.cls, item.name)
... import logging import pytest import buildercore.config LOG = logging.getLogger("conftest") ... return request.config.getoption('--filter-project-name') def pytest_runtest_setup(item): LOG.info("Setting up %s::%s", item.cls, item.name) def pytest_runtest_teardown(item, nextitem): LOG.info("Tearing down up %s::%s", item.cls, item.name) ...
5510f0990712381391dbffc38ae1bc796e2babf0
txircd/modules/umode_i.py
txircd/modules/umode_i.py
from txircd.modbase import Mode class InvisibleMode(Mode): def namesListEntry(self, recipient, channel, user, representation): if channel.name not in recipient.channels and "i" in user.mode: return "" return representation def checkWhoVisible(self, user, targetUser, filters, fields, channel, udata): destination = udata["dest"] if destination[0] == "#": if destination not in user.channels and "i" in targetUser.mode: return {} if "i" in targetUser.mode: share_channel = False for chan in user.channels: if chan in targetUser.channels: share_channel = True break if not share_channel: return {} return udata class Spawner(object): def __init__(self, ircd): self.ircd = ircd self.invisible_mode = None def spawn(self): self.invisible_mode = InvisibleMode() return { "modes": { "uni": self.invisible_mode }, "actions": { "wholinemodify": [self.invisible_mode.checkWhoVisible] } } def cleanup(self): self.ircd.removeMode("uni") self.ircd.actions["wholinemodify"].remove(self.invisible_mode.checkWhoVisible)
from txircd.modbase import Mode class InvisibleMode(Mode): def namesListEntry(self, recipient, channel, user, representation): if channel.name not in recipient.channels and "i" in user.mode: return "" return representation def checkWhoVisible(self, user, targetUser, filters, fields, channel, udata): if channel: if channel.name not in user.channels and "i" in targetUser.mode: return {} if "i" in targetUser.mode: share_channel = False for chan in user.channels: if chan in targetUser.channels: share_channel = True break if not share_channel: return {} return udata class Spawner(object): def __init__(self, ircd): self.ircd = ircd self.invisible_mode = None def spawn(self): self.invisible_mode = InvisibleMode() return { "modes": { "uni": self.invisible_mode }, "actions": { "wholinemodify": [self.invisible_mode.checkWhoVisible] } } def cleanup(self): self.ircd.removeMode("uni") self.ircd.actions["wholinemodify"].remove(self.invisible_mode.checkWhoVisible)
Make the usermode +i check for WHO slightly neater.
Make the usermode +i check for WHO slightly neater.
Python
bsd-3-clause
Heufneutje/txircd,ElementalAlchemist/txircd,DesertBus/txircd
from txircd.modbase import Mode class InvisibleMode(Mode): def namesListEntry(self, recipient, channel, user, representation): if channel.name not in recipient.channels and "i" in user.mode: return "" return representation def checkWhoVisible(self, user, targetUser, filters, fields, channel, udata): + if channel: - destination = udata["dest"] - if destination[0] == "#": - if destination not in user.channels and "i" in targetUser.mode: + if channel.name not in user.channels and "i" in targetUser.mode: return {} if "i" in targetUser.mode: share_channel = False for chan in user.channels: if chan in targetUser.channels: share_channel = True break if not share_channel: return {} return udata class Spawner(object): def __init__(self, ircd): self.ircd = ircd self.invisible_mode = None def spawn(self): self.invisible_mode = InvisibleMode() return { "modes": { "uni": self.invisible_mode }, "actions": { "wholinemodify": [self.invisible_mode.checkWhoVisible] } } def cleanup(self): self.ircd.removeMode("uni") self.ircd.actions["wholinemodify"].remove(self.invisible_mode.checkWhoVisible)
Make the usermode +i check for WHO slightly neater.
## Code Before: from txircd.modbase import Mode class InvisibleMode(Mode): def namesListEntry(self, recipient, channel, user, representation): if channel.name not in recipient.channels and "i" in user.mode: return "" return representation def checkWhoVisible(self, user, targetUser, filters, fields, channel, udata): destination = udata["dest"] if destination[0] == "#": if destination not in user.channels and "i" in targetUser.mode: return {} if "i" in targetUser.mode: share_channel = False for chan in user.channels: if chan in targetUser.channels: share_channel = True break if not share_channel: return {} return udata class Spawner(object): def __init__(self, ircd): self.ircd = ircd self.invisible_mode = None def spawn(self): self.invisible_mode = InvisibleMode() return { "modes": { "uni": self.invisible_mode }, "actions": { "wholinemodify": [self.invisible_mode.checkWhoVisible] } } def cleanup(self): self.ircd.removeMode("uni") self.ircd.actions["wholinemodify"].remove(self.invisible_mode.checkWhoVisible) ## Instruction: Make the usermode +i check for WHO slightly neater. ## Code After: from txircd.modbase import Mode class InvisibleMode(Mode): def namesListEntry(self, recipient, channel, user, representation): if channel.name not in recipient.channels and "i" in user.mode: return "" return representation def checkWhoVisible(self, user, targetUser, filters, fields, channel, udata): if channel: if channel.name not in user.channels and "i" in targetUser.mode: return {} if "i" in targetUser.mode: share_channel = False for chan in user.channels: if chan in targetUser.channels: share_channel = True break if not share_channel: return {} return udata class Spawner(object): def __init__(self, ircd): self.ircd = ircd self.invisible_mode = None def spawn(self): self.invisible_mode = InvisibleMode() return { "modes": { "uni": self.invisible_mode }, "actions": { "wholinemodify": [self.invisible_mode.checkWhoVisible] } } def cleanup(self): self.ircd.removeMode("uni") self.ircd.actions["wholinemodify"].remove(self.invisible_mode.checkWhoVisible)
... def checkWhoVisible(self, user, targetUser, filters, fields, channel, udata): if channel: if channel.name not in user.channels and "i" in targetUser.mode: return {} ...
5a8f107f987198740a0f0b9f1ee1f79d90662109
txircd/modules/rfc/cmode_n.py
txircd/modules/rfc/cmode_n.py
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.module_interface import IMode, IModuleData, Mode, ModuleData from txircd.utils import ModeType from zope.interface import implements class NoExtMsgMode(ModuleData, Mode): implements(IPlugin, IModuleData, IMode) name = "NoExtMsgMode" core = True affectedActions = [ "commandmodify-PRIVMSG", "commandmodify-NOTICE" ] def hookIRCd(self, ircd): self.ircd = ircd def channelModes(self): return [ ("n", ModeType.NoParam, self) ] def actions(self): return [ ("modeactioncheck-channel-n-commandpermission-PRIVMSG", 1, self.channelHasMode), ("modeactioncheck-channel-n-commandpermission-NOTICE", 1, self.channelHasMode) ] def apply(self, actionType, channel, param, user, command, data): if user not in channel.users and channel in data["targetchans"]: del data["targetchans"][channel] user.sendMessage(irc.ERR_CANNOTSENDTOCHAN, channel.name, ":Cannot send to channel (no external messages)") def channelHasMode(self, channel, user, command, data): if "n" in channel.modes: return "" return None noExtMsgMode = NoExtMsgMode()
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.module_interface import IMode, IModuleData, Mode, ModuleData from txircd.utils import ModeType from zope.interface import implements class NoExtMsgMode(ModuleData, Mode): implements(IPlugin, IModuleData, IMode) name = "NoExtMsgMode" core = True affectedActions = [ "commandmodify-PRIVMSG", "commandmodify-NOTICE" ] def hookIRCd(self, ircd): self.ircd = ircd def channelModes(self): return [ ("n", ModeType.NoParam, self) ] def actions(self): return [ ("modeactioncheck-channel-n-commandmodify-PRIVMSG", 1, self.channelHasMode), ("modeactioncheck-channel-n-commandmodify-NOTICE", 1, self.channelHasMode) ] def apply(self, actionType, channel, param, user, command, data): if user not in channel.users and channel in data["targetchans"]: del data["targetchans"][channel] user.sendMessage(irc.ERR_CANNOTSENDTOCHAN, channel.name, ":Cannot send to channel (no external messages)") def channelHasMode(self, channel, user, command, data): if "n" in channel.modes: return "" return None noExtMsgMode = NoExtMsgMode()
Fix mode +n specification so that it actually fires ever
Fix mode +n specification so that it actually fires ever
Python
bsd-3-clause
Heufneutje/txircd,ElementalAlchemist/txircd
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.module_interface import IMode, IModuleData, Mode, ModuleData from txircd.utils import ModeType from zope.interface import implements class NoExtMsgMode(ModuleData, Mode): implements(IPlugin, IModuleData, IMode) name = "NoExtMsgMode" core = True affectedActions = [ "commandmodify-PRIVMSG", "commandmodify-NOTICE" ] def hookIRCd(self, ircd): self.ircd = ircd def channelModes(self): return [ ("n", ModeType.NoParam, self) ] def actions(self): - return [ ("modeactioncheck-channel-n-commandpermission-PRIVMSG", 1, self.channelHasMode), + return [ ("modeactioncheck-channel-n-commandmodify-PRIVMSG", 1, self.channelHasMode), - ("modeactioncheck-channel-n-commandpermission-NOTICE", 1, self.channelHasMode) ] + ("modeactioncheck-channel-n-commandmodify-NOTICE", 1, self.channelHasMode) ] def apply(self, actionType, channel, param, user, command, data): if user not in channel.users and channel in data["targetchans"]: del data["targetchans"][channel] user.sendMessage(irc.ERR_CANNOTSENDTOCHAN, channel.name, ":Cannot send to channel (no external messages)") def channelHasMode(self, channel, user, command, data): if "n" in channel.modes: return "" return None noExtMsgMode = NoExtMsgMode()
Fix mode +n specification so that it actually fires ever
## Code Before: from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.module_interface import IMode, IModuleData, Mode, ModuleData from txircd.utils import ModeType from zope.interface import implements class NoExtMsgMode(ModuleData, Mode): implements(IPlugin, IModuleData, IMode) name = "NoExtMsgMode" core = True affectedActions = [ "commandmodify-PRIVMSG", "commandmodify-NOTICE" ] def hookIRCd(self, ircd): self.ircd = ircd def channelModes(self): return [ ("n", ModeType.NoParam, self) ] def actions(self): return [ ("modeactioncheck-channel-n-commandpermission-PRIVMSG", 1, self.channelHasMode), ("modeactioncheck-channel-n-commandpermission-NOTICE", 1, self.channelHasMode) ] def apply(self, actionType, channel, param, user, command, data): if user not in channel.users and channel in data["targetchans"]: del data["targetchans"][channel] user.sendMessage(irc.ERR_CANNOTSENDTOCHAN, channel.name, ":Cannot send to channel (no external messages)") def channelHasMode(self, channel, user, command, data): if "n" in channel.modes: return "" return None noExtMsgMode = NoExtMsgMode() ## Instruction: Fix mode +n specification so that it actually fires ever ## Code After: from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.module_interface import IMode, IModuleData, Mode, ModuleData from txircd.utils import ModeType from zope.interface import implements class NoExtMsgMode(ModuleData, Mode): implements(IPlugin, IModuleData, IMode) name = "NoExtMsgMode" core = True affectedActions = [ "commandmodify-PRIVMSG", "commandmodify-NOTICE" ] def hookIRCd(self, ircd): self.ircd = ircd def channelModes(self): return [ ("n", ModeType.NoParam, self) ] def actions(self): return [ ("modeactioncheck-channel-n-commandmodify-PRIVMSG", 1, self.channelHasMode), ("modeactioncheck-channel-n-commandmodify-NOTICE", 1, self.channelHasMode) ] def apply(self, actionType, channel, param, user, command, data): if user not in channel.users and channel in data["targetchans"]: del data["targetchans"][channel] user.sendMessage(irc.ERR_CANNOTSENDTOCHAN, channel.name, ":Cannot send to channel (no external messages)") def channelHasMode(self, channel, user, command, data): if "n" in channel.modes: return "" return None noExtMsgMode = NoExtMsgMode()
# ... existing code ... def actions(self): return [ ("modeactioncheck-channel-n-commandmodify-PRIVMSG", 1, self.channelHasMode), ("modeactioncheck-channel-n-commandmodify-NOTICE", 1, self.channelHasMode) ] # ... rest of the code ...
f44630714ce1c20c88919a1ce8d9e4ad49ec9fde
nodeconductor/cloud/perms.py
nodeconductor/cloud/perms.py
from __future__ import unicode_literals from django.contrib.auth import get_user_model from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic from nodeconductor.structure.models import CustomerRole User = get_user_model() PERMISSION_LOGICS = ( ('cloud.Cloud', FilteredCollaboratorsPermissionLogic( collaborators_query='customer__roles__permission_group__user', collaborators_filter={ 'roles__role_type': CustomerRole.OWNER, }, any_permission=True, )), )
from __future__ import unicode_literals from django.contrib.auth import get_user_model from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic from nodeconductor.structure.models import CustomerRole User = get_user_model() PERMISSION_LOGICS = ( ('cloud.Cloud', FilteredCollaboratorsPermissionLogic( collaborators_query='customer__roles__permission_group__user', collaborators_filter={ 'customer__roles__role_type': CustomerRole.OWNER, }, any_permission=True, )), )
Fix permission path for customer role lookup
Fix permission path for customer role lookup
Python
mit
opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor
from __future__ import unicode_literals from django.contrib.auth import get_user_model from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic from nodeconductor.structure.models import CustomerRole User = get_user_model() PERMISSION_LOGICS = ( ('cloud.Cloud', FilteredCollaboratorsPermissionLogic( collaborators_query='customer__roles__permission_group__user', collaborators_filter={ - 'roles__role_type': CustomerRole.OWNER, + 'customer__roles__role_type': CustomerRole.OWNER, }, any_permission=True, )), )
Fix permission path for customer role lookup
## Code Before: from __future__ import unicode_literals from django.contrib.auth import get_user_model from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic from nodeconductor.structure.models import CustomerRole User = get_user_model() PERMISSION_LOGICS = ( ('cloud.Cloud', FilteredCollaboratorsPermissionLogic( collaborators_query='customer__roles__permission_group__user', collaborators_filter={ 'roles__role_type': CustomerRole.OWNER, }, any_permission=True, )), ) ## Instruction: Fix permission path for customer role lookup ## Code After: from __future__ import unicode_literals from django.contrib.auth import get_user_model from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic from nodeconductor.structure.models import CustomerRole User = get_user_model() PERMISSION_LOGICS = ( ('cloud.Cloud', FilteredCollaboratorsPermissionLogic( collaborators_query='customer__roles__permission_group__user', collaborators_filter={ 'customer__roles__role_type': CustomerRole.OWNER, }, any_permission=True, )), )
... collaborators_filter={ 'customer__roles__role_type': CustomerRole.OWNER, }, ...
ac0f0780beb61cab95809b2e0d02e5dab481e225
py/valid-parenthesis-string.py
py/valid-parenthesis-string.py
from collections import Counter class Solution(object): def dfs(self, s, pos, stack): if stack + self.min_possible_opening[-1] - self.min_possible_opening[pos] > self.max_possible_closing[-1] - self.max_possible_closing[pos]: return False if stack + self.max_possible_opening[-1] - self.max_possible_opening[pos] < self.min_possible_closing[-1] - self.min_possible_closing[pos]: return False if pos == len(s): return not stack if s[pos] == '(': stack += 1 if self.dfs(s, pos + 1, stack): return True stack -= 1 elif s[pos] == ')': if not stack: return False else: stack -= 1 if self.dfs(s, pos + 1, stack): return True stack += 1 else: if stack: # treat as ')' stack -= 1 if self.dfs(s, pos + 1, stack): return True stack += 1 # treat as '(' stack += 1 if self.dfs(s, pos + 1, stack): return True stack -= 1 # treat as '' if self.dfs(s, pos + 1, stack): return True return False def checkValidString(self, s): """ :type s: str :rtype: bool """ c = Counter(s) mpo, mpc = c['('] + c['*'], c[')'] + c['*'] self.max_possible_opening = [0] self.min_possible_opening = [0] self.max_possible_closing = [0] self.min_possible_closing = [0] for c in s: self.min_possible_opening.append(self.min_possible_opening[-1] + (c == '(')) self.max_possible_opening.append(self.max_possible_opening[-1] + (c != ')')) self.min_possible_closing.append(self.min_possible_closing[-1] + (c == ')')) self.max_possible_closing.append(self.max_possible_closing[-1] + (c != '(')) return self.dfs(s, 0, 0)
class Solution(object): def checkValidString(self, s): """ :type s: str :rtype: bool """ lowest, highest = 0, 0 for c in s: if c == '(': lowest += 1 highest += 1 elif c == ')': if lowest > 0: lowest -= 1 highest -= 1 if highest < 0: return False else: if lowest > 0: lowest -= 1 highest += 1 return lowest == 0
Add py solution for 678. Valid Parenthesis String
Add py solution for 678. Valid Parenthesis String 678. Valid Parenthesis String: https://leetcode.com/problems/valid-parenthesis-string/ Approach2: Maintain the lowest/highest possible stack size and check if one of them is invalid O(n) time, O(1) size
Python
apache-2.0
ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode
- from collections import Counter class Solution(object): - def dfs(self, s, pos, stack): - if stack + self.min_possible_opening[-1] - self.min_possible_opening[pos] > self.max_possible_closing[-1] - self.max_possible_closing[pos]: - return False - if stack + self.max_possible_opening[-1] - self.max_possible_opening[pos] < self.min_possible_closing[-1] - self.min_possible_closing[pos]: - return False - if pos == len(s): - return not stack - if s[pos] == '(': - stack += 1 - if self.dfs(s, pos + 1, stack): - return True - stack -= 1 - elif s[pos] == ')': - if not stack: - return False - else: - stack -= 1 - if self.dfs(s, pos + 1, stack): - return True - stack += 1 - else: - if stack: # treat as ')' - stack -= 1 - if self.dfs(s, pos + 1, stack): - return True - stack += 1 - # treat as '(' - stack += 1 - if self.dfs(s, pos + 1, stack): - return True - stack -= 1 - - # treat as '' - if self.dfs(s, pos + 1, stack): - return True - return False def checkValidString(self, s): """ :type s: str :rtype: bool """ - c = Counter(s) - mpo, mpc = c['('] + c['*'], c[')'] + c['*'] + lowest, highest = 0, 0 + for c in s: + if c == '(': + lowest += 1 + highest += 1 + elif c == ')': + if lowest > 0: + lowest -= 1 + highest -= 1 + if highest < 0: + return False + else: + if lowest > 0: + lowest -= 1 + highest += 1 + return lowest == 0 - self.max_possible_opening = [0] - self.min_possible_opening = [0] - self.max_possible_closing = [0] - self.min_possible_closing = [0] - for c in s: - self.min_possible_opening.append(self.min_possible_opening[-1] + (c == '(')) - self.max_possible_opening.append(self.max_possible_opening[-1] + (c != ')')) - self.min_possible_closing.append(self.min_possible_closing[-1] + (c == ')')) - self.max_possible_closing.append(self.max_possible_closing[-1] + (c != '(')) - - return self.dfs(s, 0, 0) -
Add py solution for 678. Valid Parenthesis String
## Code Before: from collections import Counter class Solution(object): def dfs(self, s, pos, stack): if stack + self.min_possible_opening[-1] - self.min_possible_opening[pos] > self.max_possible_closing[-1] - self.max_possible_closing[pos]: return False if stack + self.max_possible_opening[-1] - self.max_possible_opening[pos] < self.min_possible_closing[-1] - self.min_possible_closing[pos]: return False if pos == len(s): return not stack if s[pos] == '(': stack += 1 if self.dfs(s, pos + 1, stack): return True stack -= 1 elif s[pos] == ')': if not stack: return False else: stack -= 1 if self.dfs(s, pos + 1, stack): return True stack += 1 else: if stack: # treat as ')' stack -= 1 if self.dfs(s, pos + 1, stack): return True stack += 1 # treat as '(' stack += 1 if self.dfs(s, pos + 1, stack): return True stack -= 1 # treat as '' if self.dfs(s, pos + 1, stack): return True return False def checkValidString(self, s): """ :type s: str :rtype: bool """ c = Counter(s) mpo, mpc = c['('] + c['*'], c[')'] + c['*'] self.max_possible_opening = [0] self.min_possible_opening = [0] self.max_possible_closing = [0] self.min_possible_closing = [0] for c in s: self.min_possible_opening.append(self.min_possible_opening[-1] + (c == '(')) self.max_possible_opening.append(self.max_possible_opening[-1] + (c != ')')) self.min_possible_closing.append(self.min_possible_closing[-1] + (c == ')')) self.max_possible_closing.append(self.max_possible_closing[-1] + (c != '(')) return self.dfs(s, 0, 0) ## Instruction: Add py solution for 678. Valid Parenthesis String ## Code After: class Solution(object): def checkValidString(self, s): """ :type s: str :rtype: bool """ lowest, highest = 0, 0 for c in s: if c == '(': lowest += 1 highest += 1 elif c == ')': if lowest > 0: lowest -= 1 highest -= 1 if highest < 0: return False else: if lowest > 0: lowest -= 1 highest += 1 return lowest == 0
... class Solution(object): ... """ lowest, highest = 0, 0 for c in s: if c == '(': lowest += 1 highest += 1 elif c == ')': if lowest > 0: lowest -= 1 highest -= 1 if highest < 0: return False else: if lowest > 0: lowest -= 1 highest += 1 return lowest == 0 ...
5cdc5755b1a687c9b34bfd575163ac367816f12a
migrations/versions/3961ccb5d884_increase_artifact_name_length.py
migrations/versions/3961ccb5d884_increase_artifact_name_length.py
# revision identifiers, used by Alembic. revision = '3961ccb5d884' down_revision = '1b229c83511d' from alembic import op import sqlalchemy as sa def upgrade(): op.alter_column('artifact', 'name', sa.VARCHAR(1024)) def downgrade(): op.alter_column('artifact', 'name', sa.VARCHAR(128))
# revision identifiers, used by Alembic. revision = '3961ccb5d884' down_revision = '1b229c83511d' from alembic import op import sqlalchemy as sa def upgrade(): op.alter_column('artifact', 'name', type_=sa.VARCHAR(1024)) def downgrade(): op.alter_column('artifact', 'name', type_=sa.VARCHAR(128))
Fix extend artifact name migration script.
Fix extend artifact name migration script. Test Plan: ran migration locally and checked table schema Reviewers: anupc, kylec Reviewed By: kylec Subscribers: changesbot Differential Revision: https://tails.corp.dropbox.com/D151824
Python
apache-2.0
dropbox/changes,dropbox/changes,dropbox/changes,dropbox/changes
# revision identifiers, used by Alembic. revision = '3961ccb5d884' down_revision = '1b229c83511d' from alembic import op import sqlalchemy as sa def upgrade(): - op.alter_column('artifact', 'name', sa.VARCHAR(1024)) + op.alter_column('artifact', 'name', type_=sa.VARCHAR(1024)) def downgrade(): - op.alter_column('artifact', 'name', sa.VARCHAR(128)) + op.alter_column('artifact', 'name', type_=sa.VARCHAR(128))
Fix extend artifact name migration script.
## Code Before: # revision identifiers, used by Alembic. revision = '3961ccb5d884' down_revision = '1b229c83511d' from alembic import op import sqlalchemy as sa def upgrade(): op.alter_column('artifact', 'name', sa.VARCHAR(1024)) def downgrade(): op.alter_column('artifact', 'name', sa.VARCHAR(128)) ## Instruction: Fix extend artifact name migration script. ## Code After: # revision identifiers, used by Alembic. revision = '3961ccb5d884' down_revision = '1b229c83511d' from alembic import op import sqlalchemy as sa def upgrade(): op.alter_column('artifact', 'name', type_=sa.VARCHAR(1024)) def downgrade(): op.alter_column('artifact', 'name', type_=sa.VARCHAR(128))
// ... existing code ... def upgrade(): op.alter_column('artifact', 'name', type_=sa.VARCHAR(1024)) // ... modified code ... def downgrade(): op.alter_column('artifact', 'name', type_=sa.VARCHAR(128)) // ... rest of the code ...
bdc51bb7a71dba4a25fcded0d2758a9af5e15679
pythran/tests/test_doc.py
pythran/tests/test_doc.py
import unittest import doctest class TestDoctest(unittest.TestCase): modules = ('passes',) def test_package(self): import pythran failed, _ = doctest.testmod(pythran) self.assertEqual(failed, 0) def test_passes(self): from pythran import passes failed, _ = doctest.testmod(passes) self.assertEqual(failed, 0) def test_optimizations(self): from pythran import optimizations failed, _ = doctest.testmod(optimizations) self.assertEqual(failed, 0) def test_backend(self): from pythran import backend failed, _ = doctest.testmod(backend) self.assertEqual(failed, 0) def test_cxxtypes(self): from pythran import cxxtypes failed, _ = doctest.testmod(cxxtypes) self.assertEqual(failed, 0) def test_openmp(self): from pythran import openmp failed, _ = doctest.testmod(openmp) self.assertEqual(failed, 0) #def test_typing(self): # from pythran import typing # failed, _ = doctest.testmod(typing) # self.assertEqual(failed, 0) if __name__ == '__main__': unittest.main()
import unittest import doctest import pythran import inspect class TestDoctest(unittest.TestCase): ''' Enable automatic doctest integration to unittest Every module in the pythran package is scanned for doctests and one test per module is created ''' pass def generic_test_package(self, mod): failed, _ = doctest.testmod(mod) self.assertEqual(failed, 0) def add_module_doctest(module_name): module = getattr(pythran, module_name) if inspect.ismodule(module): setattr(TestDoctest, 'test_' + module_name, lambda self: generic_test_package(self, module)) map(add_module_doctest, dir(pythran)) if __name__ == '__main__': unittest.main()
Make doctest integration in unittest generic.
Make doctest integration in unittest generic. Rely on introspection rather than redundant typing.
Python
bsd-3-clause
pbrunet/pythran,artas360/pythran,pbrunet/pythran,pbrunet/pythran,serge-sans-paille/pythran,artas360/pythran,hainm/pythran,serge-sans-paille/pythran,hainm/pythran,pombredanne/pythran,pombredanne/pythran,pombredanne/pythran,hainm/pythran,artas360/pythran
import unittest import doctest + import pythran + import inspect class TestDoctest(unittest.TestCase): + ''' + Enable automatic doctest integration to unittest - modules = ('passes',) + Every module in the pythran package is scanned for doctests + and one test per module is created + ''' + pass + def generic_test_package(self, mod): - def test_package(self): - import pythran - failed, _ = doctest.testmod(pythran) + failed, _ = doctest.testmod(mod) - self.assertEqual(failed, 0) + self.assertEqual(failed, 0) - def test_passes(self): - from pythran import passes - failed, _ = doctest.testmod(passes) - self.assertEqual(failed, 0) + def add_module_doctest(module_name): + module = getattr(pythran, module_name) + if inspect.ismodule(module): + setattr(TestDoctest, 'test_' + module_name, + lambda self: generic_test_package(self, module)) + map(add_module_doctest, dir(pythran)) - def test_optimizations(self): - from pythran import optimizations - failed, _ = doctest.testmod(optimizations) - self.assertEqual(failed, 0) - - def test_backend(self): - from pythran import backend - failed, _ = doctest.testmod(backend) - self.assertEqual(failed, 0) - - def test_cxxtypes(self): - from pythran import cxxtypes - failed, _ = doctest.testmod(cxxtypes) - self.assertEqual(failed, 0) - - def test_openmp(self): - from pythran import openmp - failed, _ = doctest.testmod(openmp) - self.assertEqual(failed, 0) - - #def test_typing(self): - # from pythran import typing - # failed, _ = doctest.testmod(typing) - # self.assertEqual(failed, 0) - if __name__ == '__main__': unittest.main()
Make doctest integration in unittest generic.
## Code Before: import unittest import doctest class TestDoctest(unittest.TestCase): modules = ('passes',) def test_package(self): import pythran failed, _ = doctest.testmod(pythran) self.assertEqual(failed, 0) def test_passes(self): from pythran import passes failed, _ = doctest.testmod(passes) self.assertEqual(failed, 0) def test_optimizations(self): from pythran import optimizations failed, _ = doctest.testmod(optimizations) self.assertEqual(failed, 0) def test_backend(self): from pythran import backend failed, _ = doctest.testmod(backend) self.assertEqual(failed, 0) def test_cxxtypes(self): from pythran import cxxtypes failed, _ = doctest.testmod(cxxtypes) self.assertEqual(failed, 0) def test_openmp(self): from pythran import openmp failed, _ = doctest.testmod(openmp) self.assertEqual(failed, 0) #def test_typing(self): # from pythran import typing # failed, _ = doctest.testmod(typing) # self.assertEqual(failed, 0) if __name__ == '__main__': unittest.main() ## Instruction: Make doctest integration in unittest generic. ## Code After: import unittest import doctest import pythran import inspect class TestDoctest(unittest.TestCase): ''' Enable automatic doctest integration to unittest Every module in the pythran package is scanned for doctests and one test per module is created ''' pass def generic_test_package(self, mod): failed, _ = doctest.testmod(mod) self.assertEqual(failed, 0) def add_module_doctest(module_name): module = getattr(pythran, module_name) if inspect.ismodule(module): setattr(TestDoctest, 'test_' + module_name, lambda self: generic_test_package(self, module)) map(add_module_doctest, dir(pythran)) if __name__ == '__main__': unittest.main()
... import doctest import pythran import inspect ... class TestDoctest(unittest.TestCase): ''' Enable automatic doctest integration to unittest Every module in the pythran package is scanned for doctests and one test per module is created ''' pass def generic_test_package(self, mod): failed, _ = doctest.testmod(mod) self.assertEqual(failed, 0) def add_module_doctest(module_name): module = getattr(pythran, module_name) if inspect.ismodule(module): setattr(TestDoctest, 'test_' + module_name, lambda self: generic_test_package(self, module)) map(add_module_doctest, dir(pythran)) ...
c734fbbcb8680f704cfcc5b8ee605c4d0557526d
Brownian/view/utils/plugins.py
Brownian/view/utils/plugins.py
import subprocess import string class Plugin: def __init__(self, command, allowedChars): # We replace the characters we do allow with empty strings, to get a string of all the characters we don't allow. self.notAllowedCharMap = string.maketrans(allowedChars, " "*len(allowedChars)) self.command = command def run(self, values): sanitizedValues = [] for value in values: sanitizedValues.append(str(value).translate(None, self.notAllowedCharMap)) result = subprocess.Popen([self.command] + sanitizedValues, stdout=subprocess.PIPE) stdout, stderr = result.communicate() return stdout.replace("\n", "<br>") whois = {"displayName": "Whois Lookup", "plugin": Plugin("whois", string.letters + string.digits + ".:-_")} dns_lookup = {"displayName": "DNS Lookup", "plugin": Plugin("host", string.letters + string.digits + ".:-_")} mapping = {"addr": [whois, dns_lookup], "string": [dns_lookup]}
import subprocess import string import shlex class Plugin: def __init__(self, command, allowedChars, insertInitialNewline=False): # We replace the characters we do allow with empty strings, to get a string of all the characters we don't allow. self.notAllowedCharMap = str(string.maketrans(allowedChars, " "*len(allowedChars))) self.command = shlex.split(command) self.insertInitialNewline = insertInitialNewline def run(self, values): sanitizedValues = [] for value in values: sanitizedValues.append(str(value).translate(None, self.notAllowedCharMap)) result = subprocess.Popen(self.command + sanitizedValues, stdout=subprocess.PIPE) stdout, stderr = result.communicate() if self.insertInitialNewline: stdout = "\n" + stdout return stdout.replace("\n", "<br>") whois = {"displayName": "Whois Lookup", "plugin": Plugin("whois -h whois.cymru.com \" -p -u\"", string.letters + string.digits + ".:-_", insertInitialNewline=True)} dns_lookup = {"displayName": "DNS Lookup", "plugin": Plugin("host", string.letters + string.digits + ".:-_")} mapping = {"addr": [whois, dns_lookup], "string": [dns_lookup]}
Use the Team Cymru whois server by default, make it easier to use complex commands, and optionally insert a new line before the output.
Use the Team Cymru whois server by default, make it easier to use complex commands, and optionally insert a new line before the output.
Python
bsd-2-clause
jpressnell/Brownian,grigorescu/Brownian,ruslux/Brownian,grigorescu/Brownian,grigorescu/Brownian,jpressnell/Brownian,jpressnell/Brownian,ruslux/Brownian,ruslux/Brownian
import subprocess import string + import shlex class Plugin: - def __init__(self, command, allowedChars): + def __init__(self, command, allowedChars, insertInitialNewline=False): # We replace the characters we do allow with empty strings, to get a string of all the characters we don't allow. - self.notAllowedCharMap = string.maketrans(allowedChars, " "*len(allowedChars)) + self.notAllowedCharMap = str(string.maketrans(allowedChars, " "*len(allowedChars))) - self.command = command + self.command = shlex.split(command) + self.insertInitialNewline = insertInitialNewline def run(self, values): sanitizedValues = [] for value in values: sanitizedValues.append(str(value).translate(None, self.notAllowedCharMap)) - result = subprocess.Popen([self.command] + sanitizedValues, stdout=subprocess.PIPE) + result = subprocess.Popen(self.command + sanitizedValues, stdout=subprocess.PIPE) stdout, stderr = result.communicate() + if self.insertInitialNewline: + stdout = "\n" + stdout return stdout.replace("\n", "<br>") whois = {"displayName": "Whois Lookup", - "plugin": Plugin("whois", string.letters + string.digits + ".:-_")} + "plugin": Plugin("whois -h whois.cymru.com \" -p -u\"", string.letters + string.digits + ".:-_", insertInitialNewline=True)} dns_lookup = {"displayName": "DNS Lookup", "plugin": Plugin("host", string.letters + string.digits + ".:-_")} mapping = {"addr": [whois, dns_lookup], "string": [dns_lookup]}
Use the Team Cymru whois server by default, make it easier to use complex commands, and optionally insert a new line before the output.
## Code Before: import subprocess import string class Plugin: def __init__(self, command, allowedChars): # We replace the characters we do allow with empty strings, to get a string of all the characters we don't allow. self.notAllowedCharMap = string.maketrans(allowedChars, " "*len(allowedChars)) self.command = command def run(self, values): sanitizedValues = [] for value in values: sanitizedValues.append(str(value).translate(None, self.notAllowedCharMap)) result = subprocess.Popen([self.command] + sanitizedValues, stdout=subprocess.PIPE) stdout, stderr = result.communicate() return stdout.replace("\n", "<br>") whois = {"displayName": "Whois Lookup", "plugin": Plugin("whois", string.letters + string.digits + ".:-_")} dns_lookup = {"displayName": "DNS Lookup", "plugin": Plugin("host", string.letters + string.digits + ".:-_")} mapping = {"addr": [whois, dns_lookup], "string": [dns_lookup]} ## Instruction: Use the Team Cymru whois server by default, make it easier to use complex commands, and optionally insert a new line before the output. ## Code After: import subprocess import string import shlex class Plugin: def __init__(self, command, allowedChars, insertInitialNewline=False): # We replace the characters we do allow with empty strings, to get a string of all the characters we don't allow. self.notAllowedCharMap = str(string.maketrans(allowedChars, " "*len(allowedChars))) self.command = shlex.split(command) self.insertInitialNewline = insertInitialNewline def run(self, values): sanitizedValues = [] for value in values: sanitizedValues.append(str(value).translate(None, self.notAllowedCharMap)) result = subprocess.Popen(self.command + sanitizedValues, stdout=subprocess.PIPE) stdout, stderr = result.communicate() if self.insertInitialNewline: stdout = "\n" + stdout return stdout.replace("\n", "<br>") whois = {"displayName": "Whois Lookup", "plugin": Plugin("whois -h whois.cymru.com \" -p -u\"", string.letters + string.digits + ".:-_", insertInitialNewline=True)} dns_lookup = {"displayName": "DNS Lookup", "plugin": Plugin("host", string.letters + string.digits + ".:-_")} mapping = {"addr": [whois, dns_lookup], "string": [dns_lookup]}
// ... existing code ... import string import shlex // ... modified code ... class Plugin: def __init__(self, command, allowedChars, insertInitialNewline=False): # We replace the characters we do allow with empty strings, to get a string of all the characters we don't allow. self.notAllowedCharMap = str(string.maketrans(allowedChars, " "*len(allowedChars))) self.command = shlex.split(command) self.insertInitialNewline = insertInitialNewline ... sanitizedValues.append(str(value).translate(None, self.notAllowedCharMap)) result = subprocess.Popen(self.command + sanitizedValues, stdout=subprocess.PIPE) stdout, stderr = result.communicate() if self.insertInitialNewline: stdout = "\n" + stdout return stdout.replace("\n", "<br>") ... whois = {"displayName": "Whois Lookup", "plugin": Plugin("whois -h whois.cymru.com \" -p -u\"", string.letters + string.digits + ".:-_", insertInitialNewline=True)} // ... rest of the code ...
1fa3c49f692e311e67db4f128928ac93e51830ff
babybuddy/tests/tests_commands.py
babybuddy/tests/tests_commands.py
from __future__ import unicode_literals from django.test import TestCase from django.contrib.auth.models import User from django.core.management import call_command from core.models import Child class CommandsTestCase(TestCase): def test_migrate(self): call_command('migrate', verbosity=0) self.assertIsInstance(User.objects.get(username='admin'), User) def test_fake(self): call_command('migrate', verbosity=0) call_command('fake', children=1, days=7, verbosity=0) self.assertEqual(Child.objects.count(), 1) call_command('fake', children=2, days=7, verbosity=0) self.assertEqual(Child.objects.count(), 3) """def test_reset(self): call_command('reset', verbosity=0, interactive=False) self.assertIsInstance(User.objects.get(username='admin'), User) self.assertEqual(Child.objects.count(), 1)"""
from __future__ import unicode_literals from django.test import TransactionTestCase from django.contrib.auth.models import User from django.core.management import call_command from core.models import Child class CommandsTestCase(TransactionTestCase): def test_migrate(self): call_command('migrate', verbosity=0) self.assertIsInstance(User.objects.get(username='admin'), User) def test_fake(self): call_command('migrate', verbosity=0) call_command('fake', children=1, days=7, verbosity=0) self.assertEqual(Child.objects.count(), 1) call_command('fake', children=2, days=7, verbosity=0) self.assertEqual(Child.objects.count(), 3) def test_reset(self): call_command('reset', verbosity=0, interactive=False) self.assertIsInstance(User.objects.get(username='admin'), User) self.assertEqual(Child.objects.count(), 1)
Fix and re-enable the reset management command test.
Fix and re-enable the reset management command test. Not 100% sure of why this fixes the issue - it appears that changes to django.test.TestCase in Django 2.0 led to the test failing.
Python
bsd-2-clause
cdubz/babybuddy,cdubz/babybuddy,cdubz/babybuddy
from __future__ import unicode_literals - from django.test import TestCase + from django.test import TransactionTestCase from django.contrib.auth.models import User from django.core.management import call_command from core.models import Child - class CommandsTestCase(TestCase): + class CommandsTestCase(TransactionTestCase): def test_migrate(self): call_command('migrate', verbosity=0) self.assertIsInstance(User.objects.get(username='admin'), User) def test_fake(self): call_command('migrate', verbosity=0) call_command('fake', children=1, days=7, verbosity=0) self.assertEqual(Child.objects.count(), 1) call_command('fake', children=2, days=7, verbosity=0) self.assertEqual(Child.objects.count(), 3) - """def test_reset(self): + def test_reset(self): call_command('reset', verbosity=0, interactive=False) self.assertIsInstance(User.objects.get(username='admin'), User) - self.assertEqual(Child.objects.count(), 1)""" + self.assertEqual(Child.objects.count(), 1)
Fix and re-enable the reset management command test.
## Code Before: from __future__ import unicode_literals from django.test import TestCase from django.contrib.auth.models import User from django.core.management import call_command from core.models import Child class CommandsTestCase(TestCase): def test_migrate(self): call_command('migrate', verbosity=0) self.assertIsInstance(User.objects.get(username='admin'), User) def test_fake(self): call_command('migrate', verbosity=0) call_command('fake', children=1, days=7, verbosity=0) self.assertEqual(Child.objects.count(), 1) call_command('fake', children=2, days=7, verbosity=0) self.assertEqual(Child.objects.count(), 3) """def test_reset(self): call_command('reset', verbosity=0, interactive=False) self.assertIsInstance(User.objects.get(username='admin'), User) self.assertEqual(Child.objects.count(), 1)""" ## Instruction: Fix and re-enable the reset management command test. ## Code After: from __future__ import unicode_literals from django.test import TransactionTestCase from django.contrib.auth.models import User from django.core.management import call_command from core.models import Child class CommandsTestCase(TransactionTestCase): def test_migrate(self): call_command('migrate', verbosity=0) self.assertIsInstance(User.objects.get(username='admin'), User) def test_fake(self): call_command('migrate', verbosity=0) call_command('fake', children=1, days=7, verbosity=0) self.assertEqual(Child.objects.count(), 1) call_command('fake', children=2, days=7, verbosity=0) self.assertEqual(Child.objects.count(), 3) def test_reset(self): call_command('reset', verbosity=0, interactive=False) self.assertIsInstance(User.objects.get(username='admin'), User) self.assertEqual(Child.objects.count(), 1)
# ... existing code ... from django.test import TransactionTestCase from django.contrib.auth.models import User # ... modified code ... class CommandsTestCase(TransactionTestCase): def test_migrate(self): ... def test_reset(self): call_command('reset', verbosity=0, interactive=False) ... self.assertIsInstance(User.objects.get(username='admin'), User) self.assertEqual(Child.objects.count(), 1) # ... rest of the code ...
4a509970cb48b64046f88193efc141344437b151
tests/test_list_struct.py
tests/test_list_struct.py
import pytest from hypothesis import given from hypothesis.strategies import lists, integers, floats, one_of, composite from datatyping.datatyping import validate def test_empty(): assert validate([], []) is None @given(li=lists(integers())) def test_plain(li): assert validate([int], li) is None @given(lst=lists(floats(), min_size=1)) def test_plain_type_error(lst): with pytest.raises(TypeError): validate([int], lst) @given(lst=one_of(lists(integers(), min_size=5), lists(integers(), max_size=3))) def test_list_lengths(lst): with pytest.raises(ValueError): validate([int, int, int, str], lst) @given(lst=lists(lists(integers()))) def test_nested(lst): assert validate([[int]], lst) with pytest.raises(TypeError): validate([int], lst) @composite def heavy_nested_data(draw): return [draw(lists(integers)), draw(floats()), lists(lists(floats()))] @given(lst=heavy_nested_data()) def test_heavy_nested(lst): assert validate([[int], float, [[float]]], lst) is None with pytest.raises(TypeError): assert validate([[str], int, int], lst) with pytest.raises(ValueError): validate([[[float]]], lst)
import pytest from hypothesis import given from hypothesis.strategies import lists, integers, floats, one_of, composite from datatyping.datatyping import validate def test_empty(): assert validate([], []) is None @given(li=lists(integers())) def test_plain(li): assert validate([int], li) is None @given(lst=lists(floats(), min_size=1)) def test_plain_type_error(lst): with pytest.raises(TypeError): validate([int], lst) @given(lst=one_of(lists(integers(), min_size=5), lists(integers(), max_size=3))) def test_list_lengths(lst): with pytest.raises(ValueError): validate([int, int, int, str], lst) @given(lst=lists(lists(integers(), min_size=1), min_size=1)) def test_nested(lst): assert validate([[int]], lst) is None with pytest.raises(TypeError): validate([int], lst) @composite def heavy_nested_data(draw): return [draw(lists(integers(), min_size=1, max_size=3)), draw(floats()), draw(lists(lists(floats(), min_size=1, max_size=3), min_size=1, max_size=3))] @given(lst=heavy_nested_data()) def test_heavy_nested(lst): assert validate([[int], float, [[float]]], lst) is None with pytest.raises(TypeError): validate([[str], int, int], lst) with pytest.raises(TypeError): validate([[[float]]], lst)
Fix up mistakes in tests
Fix up mistakes in tests
Python
mit
Zaab1t/datatyping
import pytest from hypothesis import given from hypothesis.strategies import lists, integers, floats, one_of, composite from datatyping.datatyping import validate def test_empty(): assert validate([], []) is None @given(li=lists(integers())) def test_plain(li): assert validate([int], li) is None @given(lst=lists(floats(), min_size=1)) def test_plain_type_error(lst): with pytest.raises(TypeError): validate([int], lst) @given(lst=one_of(lists(integers(), min_size=5), lists(integers(), max_size=3))) def test_list_lengths(lst): with pytest.raises(ValueError): validate([int, int, int, str], lst) - @given(lst=lists(lists(integers()))) + @given(lst=lists(lists(integers(), min_size=1), min_size=1)) def test_nested(lst): - assert validate([[int]], lst) + assert validate([[int]], lst) is None with pytest.raises(TypeError): validate([int], lst) @composite def heavy_nested_data(draw): - return [draw(lists(integers)), draw(floats()), lists(lists(floats()))] + return [draw(lists(integers(), min_size=1, max_size=3)), + draw(floats()), + draw(lists(lists(floats(), min_size=1, max_size=3), min_size=1, max_size=3))] @given(lst=heavy_nested_data()) def test_heavy_nested(lst): assert validate([[int], float, [[float]]], lst) is None with pytest.raises(TypeError): - assert validate([[str], int, int], lst) + validate([[str], int, int], lst) - with pytest.raises(ValueError): + with pytest.raises(TypeError): validate([[[float]]], lst)
Fix up mistakes in tests
## Code Before: import pytest from hypothesis import given from hypothesis.strategies import lists, integers, floats, one_of, composite from datatyping.datatyping import validate def test_empty(): assert validate([], []) is None @given(li=lists(integers())) def test_plain(li): assert validate([int], li) is None @given(lst=lists(floats(), min_size=1)) def test_plain_type_error(lst): with pytest.raises(TypeError): validate([int], lst) @given(lst=one_of(lists(integers(), min_size=5), lists(integers(), max_size=3))) def test_list_lengths(lst): with pytest.raises(ValueError): validate([int, int, int, str], lst) @given(lst=lists(lists(integers()))) def test_nested(lst): assert validate([[int]], lst) with pytest.raises(TypeError): validate([int], lst) @composite def heavy_nested_data(draw): return [draw(lists(integers)), draw(floats()), lists(lists(floats()))] @given(lst=heavy_nested_data()) def test_heavy_nested(lst): assert validate([[int], float, [[float]]], lst) is None with pytest.raises(TypeError): assert validate([[str], int, int], lst) with pytest.raises(ValueError): validate([[[float]]], lst) ## Instruction: Fix up mistakes in tests ## Code After: import pytest from hypothesis import given from hypothesis.strategies import lists, integers, floats, one_of, composite from datatyping.datatyping import validate def test_empty(): assert validate([], []) is None @given(li=lists(integers())) def test_plain(li): assert validate([int], li) is None @given(lst=lists(floats(), min_size=1)) def test_plain_type_error(lst): with pytest.raises(TypeError): validate([int], lst) @given(lst=one_of(lists(integers(), min_size=5), lists(integers(), max_size=3))) def test_list_lengths(lst): with pytest.raises(ValueError): validate([int, int, int, str], lst) @given(lst=lists(lists(integers(), min_size=1), min_size=1)) def test_nested(lst): assert validate([[int]], lst) is None with pytest.raises(TypeError): validate([int], lst) @composite def heavy_nested_data(draw): return [draw(lists(integers(), min_size=1, max_size=3)), draw(floats()), draw(lists(lists(floats(), min_size=1, max_size=3), min_size=1, max_size=3))] @given(lst=heavy_nested_data()) def test_heavy_nested(lst): assert validate([[int], float, [[float]]], lst) is None with pytest.raises(TypeError): validate([[str], int, int], lst) with pytest.raises(TypeError): validate([[[float]]], lst)
// ... existing code ... @given(lst=lists(lists(integers(), min_size=1), min_size=1)) def test_nested(lst): assert validate([[int]], lst) is None // ... modified code ... def heavy_nested_data(draw): return [draw(lists(integers(), min_size=1, max_size=3)), draw(floats()), draw(lists(lists(floats(), min_size=1, max_size=3), min_size=1, max_size=3))] ... with pytest.raises(TypeError): validate([[str], int, int], lst) with pytest.raises(TypeError): validate([[[float]]], lst) // ... rest of the code ...
d986f68c2490d276bec7f9511c567e591c70d2d3
corehq/ex-submodules/pillow_retry/management/commands/send_pillow_retry_queue_through_pillows.py
corehq/ex-submodules/pillow_retry/management/commands/send_pillow_retry_queue_through_pillows.py
from __future__ import absolute_import from django.core.management.base import BaseCommand from pillow_retry.models import PillowError from corehq.apps.change_feed.producer import producer class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('pillow') def handle(self, pillow, **options): self.pillow = pillow for errors in self.get_next_errors(): for error in errors: if error.change_object.metadata: producer.send_change( error.change_object.metadata.data_source_type, error.change_object.metadata ) def get_next_errors(self): num_retrieved = 1 while num_retrieved > 0: pillow_errors = ( PillowError.objects .filter(pillow=self.pillow) .order_by('date_created') )[:1000] num_retrieved = len(pillow_errors) yield pillow_errors doc_ids = [error.doc_id for error in pillow_errors] PillowError.objects(doc_id__in=doc_ids).delete()
from __future__ import absolute_import from datetime import datetime from django.core.management.base import BaseCommand from pillow_retry.models import PillowError from corehq.apps.change_feed.producer import producer class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('pillow') def handle(self, pillow, **options): self.pillow = pillow for errors in self.get_next_errors(): for error in errors: if error.change_object.metadata: producer.send_change( error.change_object.metadata.data_source_type, error.change_object.metadata ) def get_next_errors(self): num_retrieved = 1 count = 0 while num_retrieved > 0: pillow_errors = ( PillowError.objects .filter(pillow=self.pillow) .order_by('date_created') )[:1000] num_retrieved = len(pillow_errors) yield pillow_errors print("deleting") doc_ids = [error.doc_id for error in pillow_errors] PillowError.objects.filter(doc_id__in=doc_ids).delete() count += num_retrieved print(count) print(datetime.utcnow())
Add some print statements for debugging.
Add some print statements for debugging.
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
from __future__ import absolute_import + from datetime import datetime + from django.core.management.base import BaseCommand from pillow_retry.models import PillowError from corehq.apps.change_feed.producer import producer class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('pillow') def handle(self, pillow, **options): self.pillow = pillow for errors in self.get_next_errors(): for error in errors: if error.change_object.metadata: producer.send_change( error.change_object.metadata.data_source_type, error.change_object.metadata ) def get_next_errors(self): num_retrieved = 1 + count = 0 while num_retrieved > 0: pillow_errors = ( PillowError.objects .filter(pillow=self.pillow) .order_by('date_created') )[:1000] num_retrieved = len(pillow_errors) yield pillow_errors + print("deleting") doc_ids = [error.doc_id for error in pillow_errors] - PillowError.objects(doc_id__in=doc_ids).delete() + PillowError.objects.filter(doc_id__in=doc_ids).delete() + count += num_retrieved + print(count) + print(datetime.utcnow())
Add some print statements for debugging.
## Code Before: from __future__ import absolute_import from django.core.management.base import BaseCommand from pillow_retry.models import PillowError from corehq.apps.change_feed.producer import producer class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('pillow') def handle(self, pillow, **options): self.pillow = pillow for errors in self.get_next_errors(): for error in errors: if error.change_object.metadata: producer.send_change( error.change_object.metadata.data_source_type, error.change_object.metadata ) def get_next_errors(self): num_retrieved = 1 while num_retrieved > 0: pillow_errors = ( PillowError.objects .filter(pillow=self.pillow) .order_by('date_created') )[:1000] num_retrieved = len(pillow_errors) yield pillow_errors doc_ids = [error.doc_id for error in pillow_errors] PillowError.objects(doc_id__in=doc_ids).delete() ## Instruction: Add some print statements for debugging. ## Code After: from __future__ import absolute_import from datetime import datetime from django.core.management.base import BaseCommand from pillow_retry.models import PillowError from corehq.apps.change_feed.producer import producer class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('pillow') def handle(self, pillow, **options): self.pillow = pillow for errors in self.get_next_errors(): for error in errors: if error.change_object.metadata: producer.send_change( error.change_object.metadata.data_source_type, error.change_object.metadata ) def get_next_errors(self): num_retrieved = 1 count = 0 while num_retrieved > 0: pillow_errors = ( PillowError.objects .filter(pillow=self.pillow) .order_by('date_created') )[:1000] num_retrieved = len(pillow_errors) yield pillow_errors print("deleting") doc_ids = [error.doc_id for error in pillow_errors] PillowError.objects.filter(doc_id__in=doc_ids).delete() count += num_retrieved print(count) print(datetime.utcnow())
... from __future__ import absolute_import from datetime import datetime from django.core.management.base import BaseCommand ... num_retrieved = 1 count = 0 ... print("deleting") doc_ids = [error.doc_id for error in pillow_errors] PillowError.objects.filter(doc_id__in=doc_ids).delete() count += num_retrieved print(count) print(datetime.utcnow()) ...
658f0f6825b4f4a226349fcee63a0c5fbbd5ba9e
webapp/cached.py
webapp/cached.py
from datetime import datetime, timedelta import os class cached(object): def __init__(self, *args, **kwargs): self.cached_function_responses = {} self.default_max_age = kwargs.get("default_cache_max_age", timedelta(seconds=int(os.environ['CACHE_AGE']))) def __call__(self, func): def inner(*args, **kwargs): param = args[0] if len(args) > 1: param = args[1] max_age = kwargs.get('max_age', self.default_max_age) if func not in self.cached_function_responses: self.cached_function_responses[func] = {} if not max_age or param not in self.cached_function_responses[func] or (datetime.now() - self.cached_function_responses[func][param]['fetch_time'] > max_age): if 'max_age' in kwargs: del kwargs['max_age'] res = func(*args, **kwargs) self.cached_function_responses[func][param] = {'data': res, 'fetch_time': datetime.now()} return self.cached_function_responses[func][param]['data'] return inner
from datetime import datetime, timedelta import os class cached(object): def __init__(self, *args, **kwargs): self.cached_function_responses = {} self.default_max_age = kwargs.get("default_cache_max_age", timedelta(seconds=int(os.environ['CACHE_AGE']))) def __call__(self, func): def inner(*args, **kwargs): param = args[1] if len(args) > 1 else args[0] max_age = kwargs.get('max_age', self.default_max_age) if func not in self.cached_function_responses: self.cached_function_responses[func] = {} if not max_age or param not in self.cached_function_responses[func] or (datetime.now() - self.cached_function_responses[func][param]['fetch_time'] > max_age): if 'max_age' in kwargs: del kwargs['max_age'] res = func(*args, **kwargs) self.cached_function_responses[func][param] = {'data': res, 'fetch_time': datetime.now()} return self.cached_function_responses[func][param]['data'] return inner
Use ternary operator for arg selection.
Use ternary operator for arg selection.
Python
mit
cheddartv/stockstream.live,cheddartv/stockstream.live
from datetime import datetime, timedelta import os class cached(object): def __init__(self, *args, **kwargs): self.cached_function_responses = {} self.default_max_age = kwargs.get("default_cache_max_age", timedelta(seconds=int(os.environ['CACHE_AGE']))) def __call__(self, func): def inner(*args, **kwargs): + param = args[1] if len(args) > 1 else args[0] - param = args[0] - if len(args) > 1: - param = args[1] max_age = kwargs.get('max_age', self.default_max_age) if func not in self.cached_function_responses: self.cached_function_responses[func] = {} if not max_age or param not in self.cached_function_responses[func] or (datetime.now() - self.cached_function_responses[func][param]['fetch_time'] > max_age): if 'max_age' in kwargs: del kwargs['max_age'] res = func(*args, **kwargs) self.cached_function_responses[func][param] = {'data': res, 'fetch_time': datetime.now()} return self.cached_function_responses[func][param]['data'] return inner
Use ternary operator for arg selection.
## Code Before: from datetime import datetime, timedelta import os class cached(object): def __init__(self, *args, **kwargs): self.cached_function_responses = {} self.default_max_age = kwargs.get("default_cache_max_age", timedelta(seconds=int(os.environ['CACHE_AGE']))) def __call__(self, func): def inner(*args, **kwargs): param = args[0] if len(args) > 1: param = args[1] max_age = kwargs.get('max_age', self.default_max_age) if func not in self.cached_function_responses: self.cached_function_responses[func] = {} if not max_age or param not in self.cached_function_responses[func] or (datetime.now() - self.cached_function_responses[func][param]['fetch_time'] > max_age): if 'max_age' in kwargs: del kwargs['max_age'] res = func(*args, **kwargs) self.cached_function_responses[func][param] = {'data': res, 'fetch_time': datetime.now()} return self.cached_function_responses[func][param]['data'] return inner ## Instruction: Use ternary operator for arg selection. ## Code After: from datetime import datetime, timedelta import os class cached(object): def __init__(self, *args, **kwargs): self.cached_function_responses = {} self.default_max_age = kwargs.get("default_cache_max_age", timedelta(seconds=int(os.environ['CACHE_AGE']))) def __call__(self, func): def inner(*args, **kwargs): param = args[1] if len(args) > 1 else args[0] max_age = kwargs.get('max_age', self.default_max_age) if func not in self.cached_function_responses: self.cached_function_responses[func] = {} if not max_age or param not in self.cached_function_responses[func] or (datetime.now() - self.cached_function_responses[func][param]['fetch_time'] > max_age): if 'max_age' in kwargs: del kwargs['max_age'] res = func(*args, **kwargs) self.cached_function_responses[func][param] = {'data': res, 'fetch_time': datetime.now()} return self.cached_function_responses[func][param]['data'] return inner
# ... existing code ... def inner(*args, **kwargs): param = args[1] if len(args) > 1 else args[0] max_age = kwargs.get('max_age', self.default_max_age) # ... rest of the code ...
7d9265cd3cb29606e37b296dde5af07099098228
axes/tests/test_checks.py
axes/tests/test_checks.py
from django.core.checks import run_checks, Error from django.test import override_settings from axes.checks import Messages, Hints, Codes from axes.conf import settings from axes.tests.base import AxesTestCase @override_settings(AXES_HANDLER='axes.handlers.cache.AxesCacheHandler') class CacheCheckTestCase(AxesTestCase): @override_settings(CACHES={'default': {'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache'}}) def test_cache_check(self): errors = run_checks() self.assertEqual([], errors) @override_settings(CACHES={'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}) def test_cache_check_errors(self): errors = run_checks() error = Error( msg=Messages.CACHE_INVALID, hint=Hints.CACHE_INVALID, obj=settings.CACHES, id=Codes.CACHE_INVALID, ) self.assertEqual([error], errors)
from django.core.checks import run_checks, Error from django.test import override_settings from axes.checks import Messages, Hints, Codes from axes.conf import settings from axes.tests.base import AxesTestCase class CacheCheckTestCase(AxesTestCase): @override_settings( AXES_HANDLER='axes.handlers.cache.AxesCacheHandler', CACHES={'default': {'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache'}}, ) def test_cache_check(self): errors = run_checks() self.assertEqual([], errors) @override_settings( AXES_HANDLER='axes.handlers.cache.AxesCacheHandler', CACHES={'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}, ) def test_cache_check_errors(self): errors = run_checks() error = Error( msg=Messages.CACHE_INVALID, hint=Hints.CACHE_INVALID, obj=settings.CACHES, id=Codes.CACHE_INVALID, ) self.assertEqual([error], errors) @override_settings( AXES_HANDLER='axes.handlers.database.AxesDatabaseHandler', CACHES={'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}, ) def test_cache_check_does_not_produce_check_errors_with_database_handler(self): errors = run_checks() self.assertEqual([], errors)
Add check test for missing case branch
Add check test for missing case branch Signed-off-by: Aleksi Häkli <[email protected]>
Python
mit
jazzband/django-axes,django-pci/django-axes
from django.core.checks import run_checks, Error from django.test import override_settings from axes.checks import Messages, Hints, Codes from axes.conf import settings from axes.tests.base import AxesTestCase - @override_settings(AXES_HANDLER='axes.handlers.cache.AxesCacheHandler') class CacheCheckTestCase(AxesTestCase): + @override_settings( + AXES_HANDLER='axes.handlers.cache.AxesCacheHandler', - @override_settings(CACHES={'default': {'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache'}}) + CACHES={'default': {'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache'}}, + ) def test_cache_check(self): errors = run_checks() self.assertEqual([], errors) + @override_settings( + AXES_HANDLER='axes.handlers.cache.AxesCacheHandler', - @override_settings(CACHES={'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}) + CACHES={'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}, + ) def test_cache_check_errors(self): errors = run_checks() error = Error( msg=Messages.CACHE_INVALID, hint=Hints.CACHE_INVALID, obj=settings.CACHES, id=Codes.CACHE_INVALID, ) self.assertEqual([error], errors) + @override_settings( + AXES_HANDLER='axes.handlers.database.AxesDatabaseHandler', + CACHES={'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}, + ) + def test_cache_check_does_not_produce_check_errors_with_database_handler(self): + errors = run_checks() + self.assertEqual([], errors) +
Add check test for missing case branch
## Code Before: from django.core.checks import run_checks, Error from django.test import override_settings from axes.checks import Messages, Hints, Codes from axes.conf import settings from axes.tests.base import AxesTestCase @override_settings(AXES_HANDLER='axes.handlers.cache.AxesCacheHandler') class CacheCheckTestCase(AxesTestCase): @override_settings(CACHES={'default': {'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache'}}) def test_cache_check(self): errors = run_checks() self.assertEqual([], errors) @override_settings(CACHES={'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}) def test_cache_check_errors(self): errors = run_checks() error = Error( msg=Messages.CACHE_INVALID, hint=Hints.CACHE_INVALID, obj=settings.CACHES, id=Codes.CACHE_INVALID, ) self.assertEqual([error], errors) ## Instruction: Add check test for missing case branch ## Code After: from django.core.checks import run_checks, Error from django.test import override_settings from axes.checks import Messages, Hints, Codes from axes.conf import settings from axes.tests.base import AxesTestCase class CacheCheckTestCase(AxesTestCase): @override_settings( AXES_HANDLER='axes.handlers.cache.AxesCacheHandler', CACHES={'default': {'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache'}}, ) def test_cache_check(self): errors = run_checks() self.assertEqual([], errors) @override_settings( AXES_HANDLER='axes.handlers.cache.AxesCacheHandler', CACHES={'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}, ) def test_cache_check_errors(self): errors = run_checks() error = Error( msg=Messages.CACHE_INVALID, hint=Hints.CACHE_INVALID, obj=settings.CACHES, id=Codes.CACHE_INVALID, ) self.assertEqual([error], errors) @override_settings( AXES_HANDLER='axes.handlers.database.AxesDatabaseHandler', CACHES={'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}, ) def test_cache_check_does_not_produce_check_errors_with_database_handler(self): errors = run_checks() self.assertEqual([], errors)
# ... existing code ... class CacheCheckTestCase(AxesTestCase): @override_settings( AXES_HANDLER='axes.handlers.cache.AxesCacheHandler', CACHES={'default': {'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache'}}, ) def test_cache_check(self): # ... modified code ... @override_settings( AXES_HANDLER='axes.handlers.cache.AxesCacheHandler', CACHES={'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}, ) def test_cache_check_errors(self): ... self.assertEqual([error], errors) @override_settings( AXES_HANDLER='axes.handlers.database.AxesDatabaseHandler', CACHES={'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}, ) def test_cache_check_does_not_produce_check_errors_with_database_handler(self): errors = run_checks() self.assertEqual([], errors) # ... rest of the code ...
2e9472e4989985ebdb770c193856a02616a3d8e4
plugoo/assets.py
plugoo/assets.py
class Asset: """ This is an ooni-probe asset. It is a python iterator object, allowing it to be efficiently looped. To create your own custom asset your should subclass this and override the next_asset method and the len method for computing the length of the asset. """ def __init__(self, file=None, *args, **argv): self.fh = None if file: self.name = file self.fh = open(file, 'r') self.eof = False def __iter__(self): return self def len(self): """ Returns the length of the asset """ for i, l in enumerate(self.fh): pass # rewind the file self.fh.seek(0) return i + 1 def next_asset(self): """ Return the next asset. """ # XXX this is really written with my feet. # clean me up please... line = self.fh.readline() if line: return line.replace('\n','') else: self.fh.seek(0) raise StopIteration def next(self): try: return self.next_asset() except: raise StopIteration
class Asset: """ This is an ooni-probe asset. It is a python iterator object, allowing it to be efficiently looped. To create your own custom asset your should subclass this and override the next_asset method and the len method for computing the length of the asset. """ def __init__(self, file=None, *args, **argv): self.fh = None if file: self.name = file self.fh = open(file, 'r') self.eof = False def __iter__(self): return self def len(self): """ Returns the length of the asset """ for i, l in enumerate(self.fh): pass # rewind the file self.fh.seek(0) return i + 1 def parse_line(self, line): """ Override this method if you need line by line parsing of an Asset. """ return line.replace('\n','') def next_asset(self): """ Return the next asset. """ # XXX this is really written with my feet. # clean me up please... line = self.fh.readline() if line: parsed_line = self.parse_line(line) if parsed_line: return parsed_line else: self.fh.seek(0) raise StopIteration def next(self): try: return self.next_asset() except: raise StopIteration
Add a method for line by line asset parsing
Add a method for line by line asset parsing
Python
bsd-2-clause
0xPoly/ooni-probe,juga0/ooni-probe,kdmurray91/ooni-probe,hackerberry/ooni-probe,lordappsec/ooni-probe,0xPoly/ooni-probe,Karthikeyan-kkk/ooni-probe,kdmurray91/ooni-probe,juga0/ooni-probe,juga0/ooni-probe,lordappsec/ooni-probe,juga0/ooni-probe,0xPoly/ooni-probe,0xPoly/ooni-probe,Karthikeyan-kkk/ooni-probe,lordappsec/ooni-probe,Karthikeyan-kkk/ooni-probe,kdmurray91/ooni-probe,lordappsec/ooni-probe,hackerberry/ooni-probe,kdmurray91/ooni-probe,Karthikeyan-kkk/ooni-probe
class Asset: """ This is an ooni-probe asset. It is a python iterator object, allowing it to be efficiently looped. To create your own custom asset your should subclass this and override the next_asset method and the len method for computing the length of the asset. """ def __init__(self, file=None, *args, **argv): self.fh = None if file: self.name = file self.fh = open(file, 'r') self.eof = False def __iter__(self): return self def len(self): """ Returns the length of the asset """ for i, l in enumerate(self.fh): pass # rewind the file self.fh.seek(0) return i + 1 + def parse_line(self, line): + """ + Override this method if you need line + by line parsing of an Asset. + """ + return line.replace('\n','') + def next_asset(self): """ Return the next asset. """ # XXX this is really written with my feet. # clean me up please... line = self.fh.readline() if line: - return line.replace('\n','') + parsed_line = self.parse_line(line) + if parsed_line: + return parsed_line else: self.fh.seek(0) raise StopIteration def next(self): try: return self.next_asset() except: raise StopIteration
Add a method for line by line asset parsing
## Code Before: class Asset: """ This is an ooni-probe asset. It is a python iterator object, allowing it to be efficiently looped. To create your own custom asset your should subclass this and override the next_asset method and the len method for computing the length of the asset. """ def __init__(self, file=None, *args, **argv): self.fh = None if file: self.name = file self.fh = open(file, 'r') self.eof = False def __iter__(self): return self def len(self): """ Returns the length of the asset """ for i, l in enumerate(self.fh): pass # rewind the file self.fh.seek(0) return i + 1 def next_asset(self): """ Return the next asset. """ # XXX this is really written with my feet. # clean me up please... line = self.fh.readline() if line: return line.replace('\n','') else: self.fh.seek(0) raise StopIteration def next(self): try: return self.next_asset() except: raise StopIteration ## Instruction: Add a method for line by line asset parsing ## Code After: class Asset: """ This is an ooni-probe asset. It is a python iterator object, allowing it to be efficiently looped. To create your own custom asset your should subclass this and override the next_asset method and the len method for computing the length of the asset. """ def __init__(self, file=None, *args, **argv): self.fh = None if file: self.name = file self.fh = open(file, 'r') self.eof = False def __iter__(self): return self def len(self): """ Returns the length of the asset """ for i, l in enumerate(self.fh): pass # rewind the file self.fh.seek(0) return i + 1 def parse_line(self, line): """ Override this method if you need line by line parsing of an Asset. """ return line.replace('\n','') def next_asset(self): """ Return the next asset. """ # XXX this is really written with my feet. # clean me up please... line = self.fh.readline() if line: parsed_line = self.parse_line(line) if parsed_line: return parsed_line else: self.fh.seek(0) raise StopIteration def next(self): try: return self.next_asset() except: raise StopIteration
# ... existing code ... def parse_line(self, line): """ Override this method if you need line by line parsing of an Asset. """ return line.replace('\n','') def next_asset(self): # ... modified code ... if line: parsed_line = self.parse_line(line) if parsed_line: return parsed_line else: # ... rest of the code ...
d9844f5bcf6d48bde1a60d32998ccdaa87e99676
cloud_browser/__init__.py
cloud_browser/__init__.py
VERSION = (0, 2, 1) __version__ = ".".join(str(v) for v in VERSION) __version_full__ = __version__ + "".join(str(v) for v in VERSION)
VERSION = (0, 2, 1) __version__ = ".".join(str(v) for v in VERSION) __version_full__ = __version__
Fix __version_full__ for new scheme.
Version: Fix __version_full__ for new scheme.
Python
mit
ryan-roemer/django-cloud-browser,UrbanDaddy/django-cloud-browser,UrbanDaddy/django-cloud-browser,ryan-roemer/django-cloud-browser,ryan-roemer/django-cloud-browser
VERSION = (0, 2, 1) __version__ = ".".join(str(v) for v in VERSION) - __version_full__ = __version__ + "".join(str(v) for v in VERSION) + __version_full__ = __version__
Fix __version_full__ for new scheme.
## Code Before: VERSION = (0, 2, 1) __version__ = ".".join(str(v) for v in VERSION) __version_full__ = __version__ + "".join(str(v) for v in VERSION) ## Instruction: Fix __version_full__ for new scheme. ## Code After: VERSION = (0, 2, 1) __version__ = ".".join(str(v) for v in VERSION) __version_full__ = __version__
# ... existing code ... __version__ = ".".join(str(v) for v in VERSION) __version_full__ = __version__ # ... rest of the code ...
bd5844aa6c59c8d34df12e358e5e06eefcb55f9d
qiita_pet/handlers/download.py
qiita_pet/handlers/download.py
from tornado.web import authenticated from os.path import split from .base_handlers import BaseHandler from qiita_pet.exceptions import QiitaPetAuthorizationError from qiita_db.util import filepath_id_to_rel_path from qiita_db.meta_util import get_accessible_filepath_ids class DownloadHandler(BaseHandler): @authenticated def get(self, filepath_id): filepath_id = int(filepath_id) # Check access to file accessible_filepaths = get_accessible_filepath_ids(self.current_user) if filepath_id not in accessible_filepaths: raise QiitaPetAuthorizationError( self.current_user, 'filepath id %d' % filepath_id) relpath = filepath_id_to_rel_path(filepath_id) fname = split(relpath)[-1] self.set_header('Content-Description', 'File Transfer') self.set_header('Content-Type', 'application/octet-stream') self.set_header('Content-Transfer-Encoding', 'binary') self.set_header('Expires', '0') self.set_header('X-Accel-Redirect', '/protected/' + relpath) self.set_header('Content-Disposition', 'attachment; filename=%s' % fname) self.finish()
from tornado.web import authenticated from os.path import basename from .base_handlers import BaseHandler from qiita_pet.exceptions import QiitaPetAuthorizationError from qiita_db.util import filepath_id_to_rel_path from qiita_db.meta_util import get_accessible_filepath_ids class DownloadHandler(BaseHandler): @authenticated def get(self, filepath_id): filepath_id = int(filepath_id) # Check access to file accessible_filepaths = get_accessible_filepath_ids(self.current_user) if filepath_id not in accessible_filepaths: raise QiitaPetAuthorizationError( self.current_user, 'filepath id %d' % filepath_id) relpath = filepath_id_to_rel_path(filepath_id) fname = basename(relpath) self.set_header('Content-Description', 'File Transfer') self.set_header('Content-Type', 'application/octet-stream') self.set_header('Content-Transfer-Encoding', 'binary') self.set_header('Expires', '0') self.set_header('X-Accel-Redirect', '/protected/' + relpath) self.set_header('Content-Disposition', 'attachment; filename=%s' % fname) self.finish()
Use basename instead of os.path.split(...)[-1]
Use basename instead of os.path.split(...)[-1]
Python
bsd-3-clause
ElDeveloper/qiita,josenavas/QiiTa,RNAer/qiita,squirrelo/qiita,RNAer/qiita,ElDeveloper/qiita,antgonza/qiita,adamrp/qiita,wasade/qiita,antgonza/qiita,squirrelo/qiita,biocore/qiita,adamrp/qiita,josenavas/QiiTa,biocore/qiita,ElDeveloper/qiita,adamrp/qiita,antgonza/qiita,RNAer/qiita,squirrelo/qiita,ElDeveloper/qiita,wasade/qiita,josenavas/QiiTa,wasade/qiita,antgonza/qiita,biocore/qiita,josenavas/QiiTa,biocore/qiita,squirrelo/qiita,RNAer/qiita,adamrp/qiita
from tornado.web import authenticated - from os.path import split + from os.path import basename from .base_handlers import BaseHandler from qiita_pet.exceptions import QiitaPetAuthorizationError from qiita_db.util import filepath_id_to_rel_path from qiita_db.meta_util import get_accessible_filepath_ids class DownloadHandler(BaseHandler): @authenticated def get(self, filepath_id): filepath_id = int(filepath_id) # Check access to file accessible_filepaths = get_accessible_filepath_ids(self.current_user) if filepath_id not in accessible_filepaths: raise QiitaPetAuthorizationError( self.current_user, 'filepath id %d' % filepath_id) relpath = filepath_id_to_rel_path(filepath_id) - fname = split(relpath)[-1] + fname = basename(relpath) self.set_header('Content-Description', 'File Transfer') self.set_header('Content-Type', 'application/octet-stream') self.set_header('Content-Transfer-Encoding', 'binary') self.set_header('Expires', '0') self.set_header('X-Accel-Redirect', '/protected/' + relpath) self.set_header('Content-Disposition', 'attachment; filename=%s' % fname) self.finish()
Use basename instead of os.path.split(...)[-1]
## Code Before: from tornado.web import authenticated from os.path import split from .base_handlers import BaseHandler from qiita_pet.exceptions import QiitaPetAuthorizationError from qiita_db.util import filepath_id_to_rel_path from qiita_db.meta_util import get_accessible_filepath_ids class DownloadHandler(BaseHandler): @authenticated def get(self, filepath_id): filepath_id = int(filepath_id) # Check access to file accessible_filepaths = get_accessible_filepath_ids(self.current_user) if filepath_id not in accessible_filepaths: raise QiitaPetAuthorizationError( self.current_user, 'filepath id %d' % filepath_id) relpath = filepath_id_to_rel_path(filepath_id) fname = split(relpath)[-1] self.set_header('Content-Description', 'File Transfer') self.set_header('Content-Type', 'application/octet-stream') self.set_header('Content-Transfer-Encoding', 'binary') self.set_header('Expires', '0') self.set_header('X-Accel-Redirect', '/protected/' + relpath) self.set_header('Content-Disposition', 'attachment; filename=%s' % fname) self.finish() ## Instruction: Use basename instead of os.path.split(...)[-1] ## Code After: from tornado.web import authenticated from os.path import basename from .base_handlers import BaseHandler from qiita_pet.exceptions import QiitaPetAuthorizationError from qiita_db.util import filepath_id_to_rel_path from qiita_db.meta_util import get_accessible_filepath_ids class DownloadHandler(BaseHandler): @authenticated def get(self, filepath_id): filepath_id = int(filepath_id) # Check access to file accessible_filepaths = get_accessible_filepath_ids(self.current_user) if filepath_id not in accessible_filepaths: raise QiitaPetAuthorizationError( self.current_user, 'filepath id %d' % filepath_id) relpath = filepath_id_to_rel_path(filepath_id) fname = basename(relpath) self.set_header('Content-Description', 'File Transfer') self.set_header('Content-Type', 'application/octet-stream') self.set_header('Content-Transfer-Encoding', 'binary') self.set_header('Expires', '0') self.set_header('X-Accel-Redirect', '/protected/' + relpath) self.set_header('Content-Disposition', 'attachment; filename=%s' % fname) self.finish()
... from os.path import basename ... relpath = filepath_id_to_rel_path(filepath_id) fname = basename(relpath) ...
659614a6b845a95ce7188e86adae4bdc2c5416e7
examples/benchmark/__init__.py
examples/benchmark/__init__.py
import benchmark_twisted_names __all__ = ['benchmark_fibonacci', 'benchmark_twisted_names']
import benchmark_fibonacci import benchmark_twisted_names __all__ = ['benchmark_fibonacci', 'benchmark_twisted_names']
Add back commented out Fibonacci benchmark.
Add back commented out Fibonacci benchmark.
Python
mit
AlekSi/benchmarking-py
+ import benchmark_fibonacci import benchmark_twisted_names __all__ = ['benchmark_fibonacci', 'benchmark_twisted_names']
Add back commented out Fibonacci benchmark.
## Code Before: import benchmark_twisted_names __all__ = ['benchmark_fibonacci', 'benchmark_twisted_names'] ## Instruction: Add back commented out Fibonacci benchmark. ## Code After: import benchmark_fibonacci import benchmark_twisted_names __all__ = ['benchmark_fibonacci', 'benchmark_twisted_names']
# ... existing code ... import benchmark_fibonacci import benchmark_twisted_names # ... rest of the code ...
ee7147e6d781a92d0ded0e094cc01a187fcb64ae
openstates/people.py
openstates/people.py
from pupa.scrape import Legislator from .base import OpenstatesBaseScraper class OpenstatesPersonScraper(OpenstatesBaseScraper): def scrape_legislator(self, legislator_id): old = self.api('legislators/' + legislator_id + '?') old.pop('country', None) old.pop('level', None) new = Legislator(name=old['full_name'], image=old['photo_url']) return new def scrape(self, apikey=None): if apikey: self.apikey = apikey if not self.apikey: print('apikey not set') return # TODO: change this to just get ids, then scrape legislator can take an id # and get the data it it leaving behind here method = 'legislators/?state={}&fields=id'.format(self.state) for result in self.api(method): yield self.scrape_legislator(result['id'])
from pupa.scrape import Legislator from .base import OpenstatesBaseScraper class OpenstatesPersonScraper(OpenstatesBaseScraper): def scrape_legislator(self, legislator_id): old = self.api('legislators/' + legislator_id + '?') old.pop('country', None) old.pop('level', None) new = Legislator(name=old['full_name'], image=old['photo_url']) return new def scrape(self): method = 'legislators/?state={}&fields=id'.format(self.state) for result in self.api(method): yield self.scrape_legislator(result['id'])
Move the APIKey bits out to the init
Move the APIKey bits out to the init
Python
bsd-3-clause
openstates/billy,openstates/billy,sunlightlabs/billy,openstates/billy,sunlightlabs/billy,sunlightlabs/billy
from pupa.scrape import Legislator from .base import OpenstatesBaseScraper class OpenstatesPersonScraper(OpenstatesBaseScraper): def scrape_legislator(self, legislator_id): old = self.api('legislators/' + legislator_id + '?') old.pop('country', None) old.pop('level', None) new = Legislator(name=old['full_name'], image=old['photo_url']) return new - def scrape(self, apikey=None): + def scrape(self): - if apikey: - self.apikey = apikey - if not self.apikey: - print('apikey not set') - return - - # TODO: change this to just get ids, then scrape legislator can take an id - # and get the data it it leaving behind here method = 'legislators/?state={}&fields=id'.format(self.state) for result in self.api(method): yield self.scrape_legislator(result['id'])
Move the APIKey bits out to the init
## Code Before: from pupa.scrape import Legislator from .base import OpenstatesBaseScraper class OpenstatesPersonScraper(OpenstatesBaseScraper): def scrape_legislator(self, legislator_id): old = self.api('legislators/' + legislator_id + '?') old.pop('country', None) old.pop('level', None) new = Legislator(name=old['full_name'], image=old['photo_url']) return new def scrape(self, apikey=None): if apikey: self.apikey = apikey if not self.apikey: print('apikey not set') return # TODO: change this to just get ids, then scrape legislator can take an id # and get the data it it leaving behind here method = 'legislators/?state={}&fields=id'.format(self.state) for result in self.api(method): yield self.scrape_legislator(result['id']) ## Instruction: Move the APIKey bits out to the init ## Code After: from pupa.scrape import Legislator from .base import OpenstatesBaseScraper class OpenstatesPersonScraper(OpenstatesBaseScraper): def scrape_legislator(self, legislator_id): old = self.api('legislators/' + legislator_id + '?') old.pop('country', None) old.pop('level', None) new = Legislator(name=old['full_name'], image=old['photo_url']) return new def scrape(self): method = 'legislators/?state={}&fields=id'.format(self.state) for result in self.api(method): yield self.scrape_legislator(result['id'])
# ... existing code ... def scrape(self): method = 'legislators/?state={}&fields=id'.format(self.state) # ... rest of the code ...
dac3cedaee583db4cc3c05a9cb2c4f15a707123e
pylib/mapit/middleware.py
pylib/mapit/middleware.py
import re class JSONPMiddleware(object): def process_response(self, request, response): if request.GET.get('callback') and re.match('[a-zA-Z0-9_]+$', request.GET.get('callback')): response.content = request.GET.get('callback') + '(' + response.content + ')' return response
import re class JSONPMiddleware(object): def process_response(self, request, response): if request.GET.get('callback') and re.match('[a-zA-Z0-9_]+$', request.GET.get('callback')): response.content = request.GET.get('callback') + '(' + response.content + ')' response.status_code = 200 # Must return OK for JSONP to be processed return response
Set up JSONP requests to always return 200.
Set up JSONP requests to always return 200.
Python
agpl-3.0
Sinar/mapit,Code4SA/mapit,New-Bamboo/mapit,opencorato/mapit,Sinar/mapit,opencorato/mapit,opencorato/mapit,chris48s/mapit,chris48s/mapit,Code4SA/mapit,chris48s/mapit,New-Bamboo/mapit,Code4SA/mapit
import re class JSONPMiddleware(object): def process_response(self, request, response): if request.GET.get('callback') and re.match('[a-zA-Z0-9_]+$', request.GET.get('callback')): response.content = request.GET.get('callback') + '(' + response.content + ')' + response.status_code = 200 # Must return OK for JSONP to be processed return response
Set up JSONP requests to always return 200.
## Code Before: import re class JSONPMiddleware(object): def process_response(self, request, response): if request.GET.get('callback') and re.match('[a-zA-Z0-9_]+$', request.GET.get('callback')): response.content = request.GET.get('callback') + '(' + response.content + ')' return response ## Instruction: Set up JSONP requests to always return 200. ## Code After: import re class JSONPMiddleware(object): def process_response(self, request, response): if request.GET.get('callback') and re.match('[a-zA-Z0-9_]+$', request.GET.get('callback')): response.content = request.GET.get('callback') + '(' + response.content + ')' response.status_code = 200 # Must return OK for JSONP to be processed return response
// ... existing code ... response.content = request.GET.get('callback') + '(' + response.content + ')' response.status_code = 200 # Must return OK for JSONP to be processed return response // ... rest of the code ...
dfa752590c944fc07253c01c3d99b640a46dae1d
jinja2_time/jinja2_time.py
jinja2_time/jinja2_time.py
import arrow from jinja2 import nodes from jinja2.ext import Extension class TimeExtension(Extension): tags = set(['now']) def __init__(self, environment): super(TimeExtension, self).__init__(environment) # add the defaults to the environment environment.extend( datetime_format='%Y-%m-%d', ) def _now(self, timezone, datetime_format): datetime_format = datetime_format or self.environment.datetime_format return arrow.now(timezone).strftime(datetime_format) def parse(self, parser): lineno = next(parser.stream).lineno args = [parser.parse_expression()] if parser.stream.skip_if('comma'): args.append(parser.parse_expression()) else: args.append(nodes.Const(None)) call = self.call_method('_now', args, lineno=lineno) return nodes.Output([call], lineno=lineno)
import arrow from jinja2 import nodes from jinja2.ext import Extension class TimeExtension(Extension): tags = set(['now']) def __init__(self, environment): super(TimeExtension, self).__init__(environment) # add the defaults to the environment environment.extend(datetime_format='%Y-%m-%d') def _datetime(self, timezone, operator, offset, datetime_format): d = arrow.now(timezone) # Parse replace kwargs from offset and include operator replace_params = {} for param in offset.split(','): interval, value = param.split('=') replace_params[interval] = float(operator + value) d = d.replace(**replace_params) if datetime_format is None: datetime_format = self.environment.datetime_format return d.strftime(datetime_format) def _now(self, timezone, datetime_format): if datetime_format is None: datetime_format = self.environment.datetime_format return arrow.now(timezone).strftime(datetime_format) def parse(self, parser): lineno = next(parser.stream).lineno node = parser.parse_expression() if parser.stream.skip_if('comma'): datetime_format = parser.parse_expression() else: datetime_format = nodes.Const(None) if isinstance(node, nodes.Add): call_method = self.call_method( '_datetime', [node.left, nodes.Const('+'), node.right, datetime_format], lineno=lineno, ) elif isinstance(node, nodes.Sub): call_method = self.call_method( '_datetime', [node.left, nodes.Const('-'), node.right, datetime_format], lineno=lineno, ) else: call_method = self.call_method( '_now', [node, datetime_format], lineno=lineno, ) return nodes.Output([call_method], lineno=lineno)
Implement parser method for optional offset
Implement parser method for optional offset
Python
mit
hackebrot/jinja2-time
import arrow from jinja2 import nodes from jinja2.ext import Extension class TimeExtension(Extension): tags = set(['now']) def __init__(self, environment): super(TimeExtension, self).__init__(environment) # add the defaults to the environment - environment.extend( - datetime_format='%Y-%m-%d', - ) + environment.extend(datetime_format='%Y-%m-%d') + + def _datetime(self, timezone, operator, offset, datetime_format): + d = arrow.now(timezone) + + # Parse replace kwargs from offset and include operator + replace_params = {} + for param in offset.split(','): + interval, value = param.split('=') + replace_params[interval] = float(operator + value) + d = d.replace(**replace_params) + + if datetime_format is None: + datetime_format = self.environment.datetime_format + return d.strftime(datetime_format) def _now(self, timezone, datetime_format): + if datetime_format is None: - datetime_format = datetime_format or self.environment.datetime_format + datetime_format = self.environment.datetime_format return arrow.now(timezone).strftime(datetime_format) def parse(self, parser): lineno = next(parser.stream).lineno - args = [parser.parse_expression()] + node = parser.parse_expression() if parser.stream.skip_if('comma'): - args.append(parser.parse_expression()) + datetime_format = parser.parse_expression() else: - args.append(nodes.Const(None)) + datetime_format = nodes.Const(None) - call = self.call_method('_now', args, lineno=lineno) + if isinstance(node, nodes.Add): + call_method = self.call_method( + '_datetime', + [node.left, nodes.Const('+'), node.right, datetime_format], + lineno=lineno, + ) + elif isinstance(node, nodes.Sub): + call_method = self.call_method( + '_datetime', + [node.left, nodes.Const('-'), node.right, datetime_format], + lineno=lineno, + ) + else: + call_method = self.call_method( + '_now', + [node, datetime_format], + lineno=lineno, + ) + return nodes.Output([call_method], lineno=lineno) - return nodes.Output([call], lineno=lineno) -
Implement parser method for optional offset
## Code Before: import arrow from jinja2 import nodes from jinja2.ext import Extension class TimeExtension(Extension): tags = set(['now']) def __init__(self, environment): super(TimeExtension, self).__init__(environment) # add the defaults to the environment environment.extend( datetime_format='%Y-%m-%d', ) def _now(self, timezone, datetime_format): datetime_format = datetime_format or self.environment.datetime_format return arrow.now(timezone).strftime(datetime_format) def parse(self, parser): lineno = next(parser.stream).lineno args = [parser.parse_expression()] if parser.stream.skip_if('comma'): args.append(parser.parse_expression()) else: args.append(nodes.Const(None)) call = self.call_method('_now', args, lineno=lineno) return nodes.Output([call], lineno=lineno) ## Instruction: Implement parser method for optional offset ## Code After: import arrow from jinja2 import nodes from jinja2.ext import Extension class TimeExtension(Extension): tags = set(['now']) def __init__(self, environment): super(TimeExtension, self).__init__(environment) # add the defaults to the environment environment.extend(datetime_format='%Y-%m-%d') def _datetime(self, timezone, operator, offset, datetime_format): d = arrow.now(timezone) # Parse replace kwargs from offset and include operator replace_params = {} for param in offset.split(','): interval, value = param.split('=') replace_params[interval] = float(operator + value) d = d.replace(**replace_params) if datetime_format is None: datetime_format = self.environment.datetime_format return d.strftime(datetime_format) def _now(self, timezone, datetime_format): if datetime_format is None: datetime_format = self.environment.datetime_format return arrow.now(timezone).strftime(datetime_format) def parse(self, parser): lineno = next(parser.stream).lineno node = parser.parse_expression() if parser.stream.skip_if('comma'): datetime_format = parser.parse_expression() else: datetime_format = nodes.Const(None) if isinstance(node, nodes.Add): call_method = self.call_method( '_datetime', [node.left, nodes.Const('+'), node.right, datetime_format], lineno=lineno, ) elif isinstance(node, nodes.Sub): call_method = self.call_method( '_datetime', [node.left, nodes.Const('-'), node.right, datetime_format], lineno=lineno, ) else: call_method = self.call_method( '_now', [node, datetime_format], lineno=lineno, ) return nodes.Output([call_method], lineno=lineno)
... # add the defaults to the environment environment.extend(datetime_format='%Y-%m-%d') def _datetime(self, timezone, operator, offset, datetime_format): d = arrow.now(timezone) # Parse replace kwargs from offset and include operator replace_params = {} for param in offset.split(','): interval, value = param.split('=') replace_params[interval] = float(operator + value) d = d.replace(**replace_params) if datetime_format is None: datetime_format = self.environment.datetime_format return d.strftime(datetime_format) ... def _now(self, timezone, datetime_format): if datetime_format is None: datetime_format = self.environment.datetime_format return arrow.now(timezone).strftime(datetime_format) ... node = parser.parse_expression() ... if parser.stream.skip_if('comma'): datetime_format = parser.parse_expression() else: datetime_format = nodes.Const(None) if isinstance(node, nodes.Add): call_method = self.call_method( '_datetime', [node.left, nodes.Const('+'), node.right, datetime_format], lineno=lineno, ) elif isinstance(node, nodes.Sub): call_method = self.call_method( '_datetime', [node.left, nodes.Const('-'), node.right, datetime_format], lineno=lineno, ) else: call_method = self.call_method( '_now', [node, datetime_format], lineno=lineno, ) return nodes.Output([call_method], lineno=lineno) ...
4c3a2a61c6a8cb5e0ece14bced4ec8b33df45400
tests/simple/_util.py
tests/simple/_util.py
import arrayfire as af def display_func(verbose): if (verbose): return af.display else: def eval_func(foo): res = foo return eval_func def print_func(verbose): def print_func_impl(*args): if (verbose): print(args) else: res = [args] return print_func_impl class _simple_test_dict(dict): def __init__(self): self.print_str = "Simple %16s: %s" super(_simple_test_dict, self).__init__() def run(self, name_list=None, verbose=False): test_list = name_list if name_list is not None else self.keys() for key in test_list: try: test = self[key] except: print(self.print_str % (key, "NOTFOUND")) continue try: test(verbose) print(self.print_str % (key, "PASSED")) except: print(self.print_str % (key, "FAILED")) tests = _simple_test_dict()
import traceback import logging import arrayfire as af def display_func(verbose): if (verbose): return af.display else: def eval_func(foo): res = foo return eval_func def print_func(verbose): def print_func_impl(*args): if (verbose): print(args) else: res = [args] return print_func_impl class _simple_test_dict(dict): def __init__(self): self.print_str = "Simple %16s: %s" super(_simple_test_dict, self).__init__() def run(self, name_list=None, verbose=False): test_list = name_list if name_list is not None else self.keys() for key in test_list: try: test = self[key] except: print(self.print_str % (key, "NOTFOUND")) continue try: test(verbose) print(self.print_str % (key, "PASSED")) except Exception as e: print(self.print_str % (key, "FAILED")) if (verbose): logging.error(traceback.format_exc()) tests = _simple_test_dict()
Add proper logging to tests when in verbose mode
Add proper logging to tests when in verbose mode
Python
bsd-3-clause
arrayfire/arrayfire_python,pavanky/arrayfire-python,arrayfire/arrayfire-python
+ import traceback + import logging import arrayfire as af def display_func(verbose): if (verbose): return af.display else: def eval_func(foo): res = foo return eval_func def print_func(verbose): def print_func_impl(*args): if (verbose): print(args) else: res = [args] return print_func_impl class _simple_test_dict(dict): def __init__(self): self.print_str = "Simple %16s: %s" super(_simple_test_dict, self).__init__() def run(self, name_list=None, verbose=False): test_list = name_list if name_list is not None else self.keys() for key in test_list: - try: test = self[key] except: print(self.print_str % (key, "NOTFOUND")) continue try: test(verbose) print(self.print_str % (key, "PASSED")) - except: + except Exception as e: print(self.print_str % (key, "FAILED")) + if (verbose): + logging.error(traceback.format_exc()) + tests = _simple_test_dict()
Add proper logging to tests when in verbose mode
## Code Before: import arrayfire as af def display_func(verbose): if (verbose): return af.display else: def eval_func(foo): res = foo return eval_func def print_func(verbose): def print_func_impl(*args): if (verbose): print(args) else: res = [args] return print_func_impl class _simple_test_dict(dict): def __init__(self): self.print_str = "Simple %16s: %s" super(_simple_test_dict, self).__init__() def run(self, name_list=None, verbose=False): test_list = name_list if name_list is not None else self.keys() for key in test_list: try: test = self[key] except: print(self.print_str % (key, "NOTFOUND")) continue try: test(verbose) print(self.print_str % (key, "PASSED")) except: print(self.print_str % (key, "FAILED")) tests = _simple_test_dict() ## Instruction: Add proper logging to tests when in verbose mode ## Code After: import traceback import logging import arrayfire as af def display_func(verbose): if (verbose): return af.display else: def eval_func(foo): res = foo return eval_func def print_func(verbose): def print_func_impl(*args): if (verbose): print(args) else: res = [args] return print_func_impl class _simple_test_dict(dict): def __init__(self): self.print_str = "Simple %16s: %s" super(_simple_test_dict, self).__init__() def run(self, name_list=None, verbose=False): test_list = name_list if name_list is not None else self.keys() for key in test_list: try: test = self[key] except: print(self.print_str % (key, "NOTFOUND")) continue try: test(verbose) print(self.print_str % (key, "PASSED")) except Exception as e: print(self.print_str % (key, "FAILED")) if (verbose): logging.error(traceback.format_exc()) tests = _simple_test_dict()
// ... existing code ... import traceback import logging import arrayfire as af // ... modified code ... for key in test_list: try: ... print(self.print_str % (key, "PASSED")) except Exception as e: print(self.print_str % (key, "FAILED")) if (verbose): logging.error(traceback.format_exc()) // ... rest of the code ...
633f84411e26201233e3c68c584b236363f79f62
server/conf/vhosts/available/token.py
server/conf/vhosts/available/token.py
import core.provider.authentication as authentication import core.notify.dispatcher as notify import core.notify.plugins.available.changes as changes import core.provider.storage as storage import core.resource.base as resource import conf.vhosts.available.default as default class VHost(default.VHost): host = ['localhost'] port = '8888' def build(self): """ Build the resource tree """ default.VHost.build(self) # [Change the notifiers] # self.root.notifier = notify.Manual([changes.Plugin()]) # plain propfind xslt replaces the other one xsltResource = resource.StaticResource( storage.FileStorageProvider(self.config['basePath']+'/static/public/propfind-plain.xslt'), expirationDays = 2 ) xsltResource.isLeaf = True self.root.children['~static'].putChild('propfind.xslt', xsltResource) tree = resource.TokenAccessResourceDecorator(self.root) self.root = resource.TokenResource( authProvider=authentication.TokenAuthProvider(secret=self.config['share']['secret'], userProvider=self.user ), tree=tree)
import core.provider.authentication as authentication import core.notify.dispatcher as notify import core.notify.plugins.available.changes as changes import core.provider.storage as storage import core.resource.base as resource import conf.vhosts.available.default as default class VHost(default.VHost): host = ['localhost'] port = '8888' def build(self): """ Build the resource tree """ default.VHost.build(self) # [Change the notifiers] # self.root.notifier = notify.Manual([changes.Plugin()]) # plain propfind xslt replaces the other one xsltResource = resource.StaticResource( storage.FileStorageProvider(self.config['basePath']+'/static/public/propfind-plain.xslt'), expirationDays = 2 ) xsltResource.isLeaf = True self.root.children['~static'].putChild('propfind.xslt', xsltResource) leaves = {} for path, child in self.root.children.items(): if child.isLeaf == True: leaves[path] = child tree = resource.TokenAccessResourceDecorator(self.root) self.root = resource.TokenResource( authProvider=authentication.TokenAuthProvider(secret=self.config['share']['secret'], userProvider=self.user ), tree=tree) for path, child in leaves.items(): self.root.putChild(path, child)
Allow access to root leaves.
Allow access to root leaves.
Python
mit
slaff/attachix,slaff/attachix,slaff/attachix
import core.provider.authentication as authentication import core.notify.dispatcher as notify import core.notify.plugins.available.changes as changes import core.provider.storage as storage import core.resource.base as resource import conf.vhosts.available.default as default class VHost(default.VHost): host = ['localhost'] port = '8888' def build(self): """ Build the resource tree """ default.VHost.build(self) # [Change the notifiers] # self.root.notifier = notify.Manual([changes.Plugin()]) # plain propfind xslt replaces the other one xsltResource = resource.StaticResource( storage.FileStorageProvider(self.config['basePath']+'/static/public/propfind-plain.xslt'), expirationDays = 2 ) xsltResource.isLeaf = True self.root.children['~static'].putChild('propfind.xslt', xsltResource) + leaves = {} + for path, child in self.root.children.items(): + if child.isLeaf == True: + leaves[path] = child + tree = resource.TokenAccessResourceDecorator(self.root) self.root = resource.TokenResource( authProvider=authentication.TokenAuthProvider(secret=self.config['share']['secret'], userProvider=self.user ), tree=tree) + + for path, child in leaves.items(): + self.root.putChild(path, child)
Allow access to root leaves.
## Code Before: import core.provider.authentication as authentication import core.notify.dispatcher as notify import core.notify.plugins.available.changes as changes import core.provider.storage as storage import core.resource.base as resource import conf.vhosts.available.default as default class VHost(default.VHost): host = ['localhost'] port = '8888' def build(self): """ Build the resource tree """ default.VHost.build(self) # [Change the notifiers] # self.root.notifier = notify.Manual([changes.Plugin()]) # plain propfind xslt replaces the other one xsltResource = resource.StaticResource( storage.FileStorageProvider(self.config['basePath']+'/static/public/propfind-plain.xslt'), expirationDays = 2 ) xsltResource.isLeaf = True self.root.children['~static'].putChild('propfind.xslt', xsltResource) tree = resource.TokenAccessResourceDecorator(self.root) self.root = resource.TokenResource( authProvider=authentication.TokenAuthProvider(secret=self.config['share']['secret'], userProvider=self.user ), tree=tree) ## Instruction: Allow access to root leaves. ## Code After: import core.provider.authentication as authentication import core.notify.dispatcher as notify import core.notify.plugins.available.changes as changes import core.provider.storage as storage import core.resource.base as resource import conf.vhosts.available.default as default class VHost(default.VHost): host = ['localhost'] port = '8888' def build(self): """ Build the resource tree """ default.VHost.build(self) # [Change the notifiers] # self.root.notifier = notify.Manual([changes.Plugin()]) # plain propfind xslt replaces the other one xsltResource = resource.StaticResource( storage.FileStorageProvider(self.config['basePath']+'/static/public/propfind-plain.xslt'), expirationDays = 2 ) xsltResource.isLeaf = True self.root.children['~static'].putChild('propfind.xslt', xsltResource) leaves = {} for path, child in self.root.children.items(): if child.isLeaf == True: leaves[path] = child tree = resource.TokenAccessResourceDecorator(self.root) self.root = resource.TokenResource( authProvider=authentication.TokenAuthProvider(secret=self.config['share']['secret'], userProvider=self.user ), tree=tree) for path, child in leaves.items(): self.root.putChild(path, child)
# ... existing code ... leaves = {} for path, child in self.root.children.items(): if child.isLeaf == True: leaves[path] = child tree = resource.TokenAccessResourceDecorator(self.root) # ... modified code ... tree=tree) for path, child in leaves.items(): self.root.putChild(path, child) # ... rest of the code ...
59fd414849907f73d5904f46139127ae3638c9bd
ankieta/petition_custom/forms.py
ankieta/petition_custom/forms.py
from petition.forms import SignatureForm from crispy_forms.layout import Layout, Submit from crispy_forms.bootstrap import PrependedText from crispy_forms.helper import FormHelper from django.utils.translation import ugettext as _ import swapper Signature = swapper.load_model("petition", "Signature") class CustomSignatureForm(SignatureForm): def __init__(self, *args, **kwargs): super(CustomSignatureForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_method = 'post' self.helper.add_input(Submit('submit', _('Sign'), css_class="btn-sign btn-lg btn-block")) self.helper.layout = Layout( 'first_name', 'second_name', PrependedText('email', '@'), PrependedText('city', '<i class="fa fa-globe"></i>'), PrependedText('telephone', '<i class="fa fa-phone"></i>'), 'giodo', 'newsletter', ) class Meta: model = Signature field = ['first_name', 'second_name', 'email', 'city', 'telephone']
from petition.forms import SignatureForm from crispy_forms.layout import Layout from crispy_forms.bootstrap import PrependedText import swapper Signature = swapper.load_model("petition", "Signature") class CustomSignatureForm(SignatureForm): def __init__(self, *args, **kwargs): super(CustomSignatureForm, self).__init__(*args, **kwargs) self.helper.layout = Layout( 'first_name', 'second_name', PrependedText('email', '@'), PrependedText('city', '<i class="fa fa-globe"></i>'), PrependedText('telephone', '<i class="fa fa-phone"></i>'), 'giodo', 'newsletter', ) class Meta: model = Signature fields = ['first_name', 'second_name', 'email', 'city', 'newsletter', 'telephone']
Fix typo in CustomSignatureForm fields definition
Fix typo in CustomSignatureForm fields definition
Python
bsd-3-clause
ad-m/petycja-faoo,ad-m/petycja-faoo,ad-m/petycja-faoo
from petition.forms import SignatureForm - from crispy_forms.layout import Layout, Submit + from crispy_forms.layout import Layout from crispy_forms.bootstrap import PrependedText - from crispy_forms.helper import FormHelper - from django.utils.translation import ugettext as _ import swapper Signature = swapper.load_model("petition", "Signature") class CustomSignatureForm(SignatureForm): def __init__(self, *args, **kwargs): super(CustomSignatureForm, self).__init__(*args, **kwargs) - self.helper = FormHelper(self) - self.helper.form_method = 'post' - self.helper.add_input(Submit('submit', _('Sign'), css_class="btn-sign btn-lg btn-block")) self.helper.layout = Layout( 'first_name', 'second_name', PrependedText('email', '@'), PrependedText('city', '<i class="fa fa-globe"></i>'), PrependedText('telephone', '<i class="fa fa-phone"></i>'), 'giodo', 'newsletter', ) class Meta: model = Signature - field = ['first_name', 'second_name', 'email', 'city', 'telephone'] + fields = ['first_name', 'second_name', 'email', 'city', 'newsletter', 'telephone']
Fix typo in CustomSignatureForm fields definition
## Code Before: from petition.forms import SignatureForm from crispy_forms.layout import Layout, Submit from crispy_forms.bootstrap import PrependedText from crispy_forms.helper import FormHelper from django.utils.translation import ugettext as _ import swapper Signature = swapper.load_model("petition", "Signature") class CustomSignatureForm(SignatureForm): def __init__(self, *args, **kwargs): super(CustomSignatureForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_method = 'post' self.helper.add_input(Submit('submit', _('Sign'), css_class="btn-sign btn-lg btn-block")) self.helper.layout = Layout( 'first_name', 'second_name', PrependedText('email', '@'), PrependedText('city', '<i class="fa fa-globe"></i>'), PrependedText('telephone', '<i class="fa fa-phone"></i>'), 'giodo', 'newsletter', ) class Meta: model = Signature field = ['first_name', 'second_name', 'email', 'city', 'telephone'] ## Instruction: Fix typo in CustomSignatureForm fields definition ## Code After: from petition.forms import SignatureForm from crispy_forms.layout import Layout from crispy_forms.bootstrap import PrependedText import swapper Signature = swapper.load_model("petition", "Signature") class CustomSignatureForm(SignatureForm): def __init__(self, *args, **kwargs): super(CustomSignatureForm, self).__init__(*args, **kwargs) self.helper.layout = Layout( 'first_name', 'second_name', PrependedText('email', '@'), PrependedText('city', '<i class="fa fa-globe"></i>'), PrependedText('telephone', '<i class="fa fa-phone"></i>'), 'giodo', 'newsletter', ) class Meta: model = Signature fields = ['first_name', 'second_name', 'email', 'city', 'newsletter', 'telephone']
# ... existing code ... from petition.forms import SignatureForm from crispy_forms.layout import Layout from crispy_forms.bootstrap import PrependedText import swapper # ... modified code ... super(CustomSignatureForm, self).__init__(*args, **kwargs) self.helper.layout = Layout( ... model = Signature fields = ['first_name', 'second_name', 'email', 'city', 'newsletter', 'telephone'] # ... rest of the code ...
d5c65f6ac2cdae3310f41efb9ab0a6d5cae63357
kopytka/managers.py
kopytka/managers.py
from django.db import models class PageQuerySet(models.QuerySet): def published(self): return self.filter(is_published=True)
from django.db import models from .transforms import SKeys class PageQuerySet(models.QuerySet): def published(self): return self.filter(is_published=True) def fragment_keys(self): return self.annotate(keys=SKeys('fragments')).values_list('keys', flat=True)
Add fragment_keys method to PageQuerySet
Add fragment_keys method to PageQuerySet
Python
mit
funkybob/kopytka,funkybob/kopytka,funkybob/kopytka
from django.db import models + from .transforms import SKeys class PageQuerySet(models.QuerySet): def published(self): return self.filter(is_published=True) + def fragment_keys(self): + return self.annotate(keys=SKeys('fragments')).values_list('keys', flat=True) +
Add fragment_keys method to PageQuerySet
## Code Before: from django.db import models class PageQuerySet(models.QuerySet): def published(self): return self.filter(is_published=True) ## Instruction: Add fragment_keys method to PageQuerySet ## Code After: from django.db import models from .transforms import SKeys class PageQuerySet(models.QuerySet): def published(self): return self.filter(is_published=True) def fragment_keys(self): return self.annotate(keys=SKeys('fragments')).values_list('keys', flat=True)
# ... existing code ... from django.db import models from .transforms import SKeys # ... modified code ... return self.filter(is_published=True) def fragment_keys(self): return self.annotate(keys=SKeys('fragments')).values_list('keys', flat=True) # ... rest of the code ...
1f7979edaa918a52702bea5de6f2bdd7a8e60796
encryption.py
encryption.py
import base64 from Crypto.Cipher import AES from Crypto import Random def encrypt(raw, key): raw = pad(raw) iv = Random.new().read(AES.block_size) cipher = AES.new(key, AES.MODE_CBC, iv) return base64.b64encode(iv + cipher.encrypt(raw)) def decrypt(enc, key): enc = base64.b64decode(enc) iv = enc[:AES.block_size] cipher = AES.new(key, AES.MODE_CBC, iv) result = unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8') return result def pad(s): bs = 32 return s + (bs - len(s) % bs) * chr(bs - len(s) % bs) def unpad(s): return s[:-ord(s[len(s)-1:])]
import base64 from Crypto.Cipher import AES from Crypto import Random def encrypt(raw, key): raw = pad(raw) iv = Random.new().read(AES.block_size) cipher = AES.new(key, AES.MODE_CBC, iv) return base64.b64encode(iv + cipher.encrypt(raw)).decode('utf-8') def decrypt(enc, key): enc = base64.b64decode(enc) iv = enc[:AES.block_size] cipher = AES.new(key, AES.MODE_CBC, iv) result = unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8') return result def pad(s): bs = 32 return s + (bs - len(s) % bs) * chr(bs - len(s) % bs) def unpad(s): return s[:-ord(s[len(s)-1:])]
Add decode(utf-8) to return on encrypt
Add decode(utf-8) to return on encrypt
Python
mit
regexpressyourself/passman
import base64 from Crypto.Cipher import AES from Crypto import Random def encrypt(raw, key): raw = pad(raw) iv = Random.new().read(AES.block_size) cipher = AES.new(key, AES.MODE_CBC, iv) - return base64.b64encode(iv + cipher.encrypt(raw)) + return base64.b64encode(iv + cipher.encrypt(raw)).decode('utf-8') def decrypt(enc, key): enc = base64.b64decode(enc) iv = enc[:AES.block_size] cipher = AES.new(key, AES.MODE_CBC, iv) result = unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8') return result def pad(s): bs = 32 return s + (bs - len(s) % bs) * chr(bs - len(s) % bs) def unpad(s): return s[:-ord(s[len(s)-1:])]
Add decode(utf-8) to return on encrypt
## Code Before: import base64 from Crypto.Cipher import AES from Crypto import Random def encrypt(raw, key): raw = pad(raw) iv = Random.new().read(AES.block_size) cipher = AES.new(key, AES.MODE_CBC, iv) return base64.b64encode(iv + cipher.encrypt(raw)) def decrypt(enc, key): enc = base64.b64decode(enc) iv = enc[:AES.block_size] cipher = AES.new(key, AES.MODE_CBC, iv) result = unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8') return result def pad(s): bs = 32 return s + (bs - len(s) % bs) * chr(bs - len(s) % bs) def unpad(s): return s[:-ord(s[len(s)-1:])] ## Instruction: Add decode(utf-8) to return on encrypt ## Code After: import base64 from Crypto.Cipher import AES from Crypto import Random def encrypt(raw, key): raw = pad(raw) iv = Random.new().read(AES.block_size) cipher = AES.new(key, AES.MODE_CBC, iv) return base64.b64encode(iv + cipher.encrypt(raw)).decode('utf-8') def decrypt(enc, key): enc = base64.b64decode(enc) iv = enc[:AES.block_size] cipher = AES.new(key, AES.MODE_CBC, iv) result = unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8') return result def pad(s): bs = 32 return s + (bs - len(s) % bs) * chr(bs - len(s) % bs) def unpad(s): return s[:-ord(s[len(s)-1:])]
... cipher = AES.new(key, AES.MODE_CBC, iv) return base64.b64encode(iv + cipher.encrypt(raw)).decode('utf-8') ...
9837d14d4c9a1fa85d6dd122ebbdda6a6b559087
tests/test_travis.py
tests/test_travis.py
import unittest import permstruct import permstruct.dag class TestTravis(unittest.TestCase): def test_travis(self): perm_prop = lambda p: p.avoids([2,3,1]) perm_bound = 6 inp_dag = permstruct.dag.incr_decr(perm_prop, perm_bound) sol_iter = permstruct.construct_rule(perm_prop, perm_bound, inp_dag, (3, 3), 4, 100) for sol in sol_iter: print '====================================' print "" for rule in sol: print(rule) print ""
import unittest import permstruct import permstruct.dag import sys class TestTravis(unittest.TestCase): def test_travis(self): perm_prop = lambda p: p.avoids([2,3,1]) perm_bound = 6 inp_dag = permstruct.dag.incr_decr(perm_prop, perm_bound) sol_iter = permstruct.construct_rule(perm_prop, perm_bound, inp_dag, (3, 3), 4, 100) for sol in sol_iter: sys.stdout.write('====================================\n') sys.stdout.write('\n') for rule in sol: sys.stdout.write('%s\n\n' % rule)
Make tests working with python 2 and 3
Make tests working with python 2 and 3
Python
bsd-3-clause
PermutaTriangle/PermStruct
import unittest import permstruct import permstruct.dag + import sys class TestTravis(unittest.TestCase): def test_travis(self): perm_prop = lambda p: p.avoids([2,3,1]) perm_bound = 6 inp_dag = permstruct.dag.incr_decr(perm_prop, perm_bound) sol_iter = permstruct.construct_rule(perm_prop, perm_bound, inp_dag, (3, 3), 4, 100) for sol in sol_iter: - print '====================================' + sys.stdout.write('====================================\n') - print "" + sys.stdout.write('\n') for rule in sol: + sys.stdout.write('%s\n\n' % rule) - print(rule) - print ""
Make tests working with python 2 and 3
## Code Before: import unittest import permstruct import permstruct.dag class TestTravis(unittest.TestCase): def test_travis(self): perm_prop = lambda p: p.avoids([2,3,1]) perm_bound = 6 inp_dag = permstruct.dag.incr_decr(perm_prop, perm_bound) sol_iter = permstruct.construct_rule(perm_prop, perm_bound, inp_dag, (3, 3), 4, 100) for sol in sol_iter: print '====================================' print "" for rule in sol: print(rule) print "" ## Instruction: Make tests working with python 2 and 3 ## Code After: import unittest import permstruct import permstruct.dag import sys class TestTravis(unittest.TestCase): def test_travis(self): perm_prop = lambda p: p.avoids([2,3,1]) perm_bound = 6 inp_dag = permstruct.dag.incr_decr(perm_prop, perm_bound) sol_iter = permstruct.construct_rule(perm_prop, perm_bound, inp_dag, (3, 3), 4, 100) for sol in sol_iter: sys.stdout.write('====================================\n') sys.stdout.write('\n') for rule in sol: sys.stdout.write('%s\n\n' % rule)
... import permstruct.dag import sys ... sys.stdout.write('====================================\n') sys.stdout.write('\n') for rule in sol: sys.stdout.write('%s\n\n' % rule) ...
ebfaf30fca157e83ea9e4bf33173221fc9525caf
demo/examples/employees/forms.py
demo/examples/employees/forms.py
from datetime import date from django import forms from django.utils import timezone from .models import Employee, DeptManager, Title, Salary class ChangeManagerForm(forms.Form): manager = forms.ModelChoiceField(queryset=Employee.objects.all()[:100]) def __init__(self, *args, **kwargs): self.department = kwargs.pop('department') super(ChangeManagerForm, self).__init__(*args, **kwargs) def save(self): new_manager = self.cleaned_data['manager'] DeptManager.objects.filter( department=self.department ).set( department=self.department, employee=new_manager ) class ChangeTitleForm(forms.Form): position = forms.CharField() def __init__(self, *args, **kwargs): self.employee = kwargs.pop('employee') super(ChangeTitleForm, self).__init__(*args, **kwargs) def save(self): new_title = self.cleaned_data['position'] Title.objects.filter( employee=self.employee, ).set( employee=self.employee, title=new_title ) class ChangeSalaryForm(forms.Form): salary = forms.IntegerField() def __init__(self, *args, **kwargs): self.employee = kwargs.pop('employee') super(ChangeSalaryForm, self).__init__(*args, **kwargs) def save(self): new_salary = self.cleaned_data['salary'] Salary.objects.filter( employee=self.employee, ).set( employee=self.employee, salary=new_salary, )
from django import forms from .models import Employee, DeptManager, Title, Salary class ChangeManagerForm(forms.Form): manager = forms.ModelChoiceField(queryset=Employee.objects.all()[:100]) def __init__(self, *args, **kwargs): self.department = kwargs.pop('department') super(ChangeManagerForm, self).__init__(*args, **kwargs) def save(self): new_manager = self.cleaned_data['manager'] DeptManager.objects.filter( department=self.department ).set( department=self.department, employee=new_manager ) class ChangeTitleForm(forms.Form): position = forms.CharField() def __init__(self, *args, **kwargs): self.employee = kwargs.pop('employee') super(ChangeTitleForm, self).__init__(*args, **kwargs) def save(self): new_title = self.cleaned_data['position'] Title.objects.filter( employee=self.employee, ).set( employee=self.employee, title=new_title ) class ChangeSalaryForm(forms.Form): salary = forms.IntegerField(max_value=1000000) def __init__(self, *args, **kwargs): self.employee = kwargs.pop('employee') super(ChangeSalaryForm, self).__init__(*args, **kwargs) def save(self): new_salary = self.cleaned_data['salary'] Salary.objects.filter( employee=self.employee, ).set( employee=self.employee, salary=new_salary, )
Fix emplorrs demo salary db error
Fix emplorrs demo salary db error
Python
bsd-3-clause
viewflow/django-material,viewflow/django-material,viewflow/django-material
- from datetime import date - from django import forms - from django.utils import timezone from .models import Employee, DeptManager, Title, Salary class ChangeManagerForm(forms.Form): manager = forms.ModelChoiceField(queryset=Employee.objects.all()[:100]) def __init__(self, *args, **kwargs): self.department = kwargs.pop('department') super(ChangeManagerForm, self).__init__(*args, **kwargs) def save(self): new_manager = self.cleaned_data['manager'] DeptManager.objects.filter( department=self.department ).set( department=self.department, employee=new_manager ) class ChangeTitleForm(forms.Form): position = forms.CharField() def __init__(self, *args, **kwargs): self.employee = kwargs.pop('employee') super(ChangeTitleForm, self).__init__(*args, **kwargs) def save(self): new_title = self.cleaned_data['position'] Title.objects.filter( employee=self.employee, ).set( employee=self.employee, title=new_title ) class ChangeSalaryForm(forms.Form): - salary = forms.IntegerField() + salary = forms.IntegerField(max_value=1000000) def __init__(self, *args, **kwargs): self.employee = kwargs.pop('employee') super(ChangeSalaryForm, self).__init__(*args, **kwargs) def save(self): new_salary = self.cleaned_data['salary'] Salary.objects.filter( employee=self.employee, ).set( employee=self.employee, salary=new_salary, )
Fix emplorrs demo salary db error
## Code Before: from datetime import date from django import forms from django.utils import timezone from .models import Employee, DeptManager, Title, Salary class ChangeManagerForm(forms.Form): manager = forms.ModelChoiceField(queryset=Employee.objects.all()[:100]) def __init__(self, *args, **kwargs): self.department = kwargs.pop('department') super(ChangeManagerForm, self).__init__(*args, **kwargs) def save(self): new_manager = self.cleaned_data['manager'] DeptManager.objects.filter( department=self.department ).set( department=self.department, employee=new_manager ) class ChangeTitleForm(forms.Form): position = forms.CharField() def __init__(self, *args, **kwargs): self.employee = kwargs.pop('employee') super(ChangeTitleForm, self).__init__(*args, **kwargs) def save(self): new_title = self.cleaned_data['position'] Title.objects.filter( employee=self.employee, ).set( employee=self.employee, title=new_title ) class ChangeSalaryForm(forms.Form): salary = forms.IntegerField() def __init__(self, *args, **kwargs): self.employee = kwargs.pop('employee') super(ChangeSalaryForm, self).__init__(*args, **kwargs) def save(self): new_salary = self.cleaned_data['salary'] Salary.objects.filter( employee=self.employee, ).set( employee=self.employee, salary=new_salary, ) ## Instruction: Fix emplorrs demo salary db error ## Code After: from django import forms from .models import Employee, DeptManager, Title, Salary class ChangeManagerForm(forms.Form): manager = forms.ModelChoiceField(queryset=Employee.objects.all()[:100]) def __init__(self, *args, **kwargs): self.department = kwargs.pop('department') super(ChangeManagerForm, self).__init__(*args, **kwargs) def save(self): new_manager = self.cleaned_data['manager'] DeptManager.objects.filter( department=self.department ).set( department=self.department, employee=new_manager ) class ChangeTitleForm(forms.Form): position = forms.CharField() def __init__(self, *args, **kwargs): self.employee = kwargs.pop('employee') super(ChangeTitleForm, self).__init__(*args, **kwargs) def save(self): new_title = self.cleaned_data['position'] Title.objects.filter( employee=self.employee, ).set( employee=self.employee, title=new_title ) class ChangeSalaryForm(forms.Form): salary = forms.IntegerField(max_value=1000000) def __init__(self, *args, **kwargs): self.employee = kwargs.pop('employee') super(ChangeSalaryForm, self).__init__(*args, **kwargs) def save(self): new_salary = self.cleaned_data['salary'] Salary.objects.filter( employee=self.employee, ).set( employee=self.employee, salary=new_salary, )
# ... existing code ... from django import forms # ... modified code ... class ChangeSalaryForm(forms.Form): salary = forms.IntegerField(max_value=1000000) # ... rest of the code ...
b5e6952841d19e75b308fb2ab16ca5b098d376a9
django-tutorial/tutorial/polls/views.py
django-tutorial/tutorial/polls/views.py
from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, Http404 from polls.models import Question # Create your views here. def index(request): latest_question_list = Question.objects.order_by('pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id)
from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect, HttpResponse from django.core.urlresolvers import reverse from polls.models import Choice, Question # Create your views here. def index(request): latest_question_list = Question.objects.order_by('pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): p = get_object_or_404(Question, pk=question_id) try: selected_choice = p.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': p, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
Update the view for the voting
Update the view for the voting
Python
mit
domenicosolazzo/practice-django,domenicosolazzo/practice-django,domenicosolazzo/practice-django
from django.shortcuts import render, get_object_or_404 - from django.http import HttpResponse, Http404 + from django.http import HttpResponseRedirect, HttpResponse + from django.core.urlresolvers import reverse + - from polls.models import Question + from polls.models import Choice, Question # Create your views here. def index(request): latest_question_list = Question.objects.order_by('pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): - return HttpResponse("You're voting on question %s." % question_id) - + p = get_object_or_404(Question, pk=question_id) + try: + selected_choice = p.choice_set.get(pk=request.POST['choice']) + except (KeyError, Choice.DoesNotExist): + # Redisplay the question voting form. + return render(request, 'polls/detail.html', { + 'question': p, + 'error_message': "You didn't select a choice.", + }) + else: + selected_choice.votes += 1 + selected_choice.save() + # Always return an HttpResponseRedirect after successfully dealing + # with POST data. This prevents data from being posted twice if a + # user hits the Back button. + return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
Update the view for the voting
## Code Before: from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, Http404 from polls.models import Question # Create your views here. def index(request): latest_question_list = Question.objects.order_by('pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id) ## Instruction: Update the view for the voting ## Code After: from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect, HttpResponse from django.core.urlresolvers import reverse from polls.models import Choice, Question # Create your views here. def index(request): latest_question_list = Question.objects.order_by('pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): p = get_object_or_404(Question, pk=question_id) try: selected_choice = p.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': p, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
... from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect, HttpResponse from django.core.urlresolvers import reverse from polls.models import Choice, Question ... def vote(request, question_id): p = get_object_or_404(Question, pk=question_id) try: selected_choice = p.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': p, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args=(p.id,))) ...
ab16cd72a2f2ed093f206b48379fb9f03f8d2f36
tests/example.py
tests/example.py
import unittest from src.dojo import Dojo """ Call "python -m tests.example" while being in parent directory to run tests in this file. """ class ExampleTest(unittest.TestCase): def test_example(self): dojo = Dojo() self.assertEqual(dojo.get_random_number(), 4) if __name__ == '__main__': unittest.main()
import unittest from src.dojo import Dojo """ Call "python -m tests.example" while being in parent directory to run tests in this file. """ class ExampleTest(unittest.TestCase): def setUp(self): """ This method will be called *before* each test run. """ pass def tearDown(self): """ This method will be called *after* each test run. """ pass def test_example(self): dojo = Dojo() self.assertEqual(dojo.get_random_number(), 4) if __name__ == '__main__': unittest.main()
Add setUp and tearDown to test file
Add setUp and tearDown to test file
Python
mit
pawel-lewtak/coding-dojo-template-python
import unittest from src.dojo import Dojo """ Call "python -m tests.example" while being in parent directory to run tests in this file. """ class ExampleTest(unittest.TestCase): + def setUp(self): + """ This method will be called *before* each test run. """ + pass + + def tearDown(self): + """ This method will be called *after* each test run. """ + pass + def test_example(self): dojo = Dojo() self.assertEqual(dojo.get_random_number(), 4) if __name__ == '__main__': unittest.main()
Add setUp and tearDown to test file
## Code Before: import unittest from src.dojo import Dojo """ Call "python -m tests.example" while being in parent directory to run tests in this file. """ class ExampleTest(unittest.TestCase): def test_example(self): dojo = Dojo() self.assertEqual(dojo.get_random_number(), 4) if __name__ == '__main__': unittest.main() ## Instruction: Add setUp and tearDown to test file ## Code After: import unittest from src.dojo import Dojo """ Call "python -m tests.example" while being in parent directory to run tests in this file. """ class ExampleTest(unittest.TestCase): def setUp(self): """ This method will be called *before* each test run. """ pass def tearDown(self): """ This method will be called *after* each test run. """ pass def test_example(self): dojo = Dojo() self.assertEqual(dojo.get_random_number(), 4) if __name__ == '__main__': unittest.main()
... class ExampleTest(unittest.TestCase): def setUp(self): """ This method will be called *before* each test run. """ pass def tearDown(self): """ This method will be called *after* each test run. """ pass def test_example(self): ...
6a8f39104a1a7722ee0a0a2437256dd3c123ab18
src/newt/db/tests/base.py
src/newt/db/tests/base.py
import gc import sys PYPY = hasattr(sys, 'pypy_version_info') from .. import pg_connection class DBSetup(object): maxDiff = None @property def dsn(self): return 'postgresql://localhost/' + self.dbname def setUp(self, call_super=True): self.dbname = self.__class__.__name__.lower() + '_newt_test_database' self.base_conn = pg_connection('') self.base_conn.autocommit = True self.base_cursor = self.base_conn.cursor() self.drop_db() self.base_cursor.execute('create database ' + self.dbname) self.call_super = call_super if call_super: super(DBSetup, self).setUp() def drop_db(self): self.base_cursor.execute('drop database if exists ' + self.dbname) def tearDown(self): if self.call_super: super(DBSetup, self).tearDown() if PYPY: # Make sure there aren't any leaked connections around # that would keep us from dropping the DB # (https://travis-ci.org/newtdb/db/jobs/195267673) # This needs a fix from RelStorage post 2.0.0. gc.collect() gc.collect() self.drop_db() self.base_cursor.close() self.base_conn.close()
import gc import sys import unittest PYPY = hasattr(sys, 'pypy_version_info') from .. import pg_connection from .._util import closing class DBSetup(object): maxDiff = None @property def dsn(self): return 'postgresql://localhost/' + self.dbname def setUp(self, call_super=True): self.dbname = self.__class__.__name__.lower() + '_newt_test_database' self.base_conn = pg_connection('') self.base_conn.autocommit = True self.base_cursor = self.base_conn.cursor() self.drop_db() self.base_cursor.execute('create database ' + self.dbname) self.call_super = call_super if call_super: super(DBSetup, self).setUp() def drop_db(self): self.base_cursor.execute( """ select pg_terminate_backend(pid) from pg_stat_activity where datname = %s """, (self.dbname,)) self.base_cursor.execute('drop database if exists ' + self.dbname) def tearDown(self): if self.call_super: super(DBSetup, self).tearDown() if PYPY: # Make sure there aren't any leaked connections around # that would keep us from dropping the DB # (https://travis-ci.org/newtdb/db/jobs/195267673) # This needs a fix from RelStorage post 2.0.0. gc.collect() gc.collect() self.drop_db() self.base_cursor.close() self.base_conn.close() class TestCase(DBSetup, unittest.TestCase): pass
Make it easier to clean up tests by closing db sessions
Make it easier to clean up tests by closing db sessions Also added a convenience test base class
Python
mit
newtdb/db
import gc import sys + import unittest + PYPY = hasattr(sys, 'pypy_version_info') from .. import pg_connection + from .._util import closing class DBSetup(object): maxDiff = None @property def dsn(self): return 'postgresql://localhost/' + self.dbname def setUp(self, call_super=True): self.dbname = self.__class__.__name__.lower() + '_newt_test_database' self.base_conn = pg_connection('') self.base_conn.autocommit = True self.base_cursor = self.base_conn.cursor() self.drop_db() self.base_cursor.execute('create database ' + self.dbname) self.call_super = call_super if call_super: super(DBSetup, self).setUp() def drop_db(self): + self.base_cursor.execute( + """ + select pg_terminate_backend(pid) from pg_stat_activity + where datname = %s + """, (self.dbname,)) self.base_cursor.execute('drop database if exists ' + self.dbname) def tearDown(self): if self.call_super: super(DBSetup, self).tearDown() if PYPY: # Make sure there aren't any leaked connections around # that would keep us from dropping the DB # (https://travis-ci.org/newtdb/db/jobs/195267673) # This needs a fix from RelStorage post 2.0.0. gc.collect() gc.collect() self.drop_db() self.base_cursor.close() self.base_conn.close() + class TestCase(DBSetup, unittest.TestCase): + pass +
Make it easier to clean up tests by closing db sessions
## Code Before: import gc import sys PYPY = hasattr(sys, 'pypy_version_info') from .. import pg_connection class DBSetup(object): maxDiff = None @property def dsn(self): return 'postgresql://localhost/' + self.dbname def setUp(self, call_super=True): self.dbname = self.__class__.__name__.lower() + '_newt_test_database' self.base_conn = pg_connection('') self.base_conn.autocommit = True self.base_cursor = self.base_conn.cursor() self.drop_db() self.base_cursor.execute('create database ' + self.dbname) self.call_super = call_super if call_super: super(DBSetup, self).setUp() def drop_db(self): self.base_cursor.execute('drop database if exists ' + self.dbname) def tearDown(self): if self.call_super: super(DBSetup, self).tearDown() if PYPY: # Make sure there aren't any leaked connections around # that would keep us from dropping the DB # (https://travis-ci.org/newtdb/db/jobs/195267673) # This needs a fix from RelStorage post 2.0.0. gc.collect() gc.collect() self.drop_db() self.base_cursor.close() self.base_conn.close() ## Instruction: Make it easier to clean up tests by closing db sessions ## Code After: import gc import sys import unittest PYPY = hasattr(sys, 'pypy_version_info') from .. import pg_connection from .._util import closing class DBSetup(object): maxDiff = None @property def dsn(self): return 'postgresql://localhost/' + self.dbname def setUp(self, call_super=True): self.dbname = self.__class__.__name__.lower() + '_newt_test_database' self.base_conn = pg_connection('') self.base_conn.autocommit = True self.base_cursor = self.base_conn.cursor() self.drop_db() self.base_cursor.execute('create database ' + self.dbname) self.call_super = call_super if call_super: super(DBSetup, self).setUp() def drop_db(self): self.base_cursor.execute( """ select pg_terminate_backend(pid) from pg_stat_activity where datname = %s """, (self.dbname,)) self.base_cursor.execute('drop database if exists ' + self.dbname) def tearDown(self): if self.call_super: super(DBSetup, self).tearDown() if PYPY: # Make sure there aren't any leaked connections around # that would keep us from dropping the DB # (https://travis-ci.org/newtdb/db/jobs/195267673) # This needs a fix from RelStorage post 2.0.0. gc.collect() gc.collect() self.drop_db() self.base_cursor.close() self.base_conn.close() class TestCase(DBSetup, unittest.TestCase): pass
// ... existing code ... import sys import unittest PYPY = hasattr(sys, 'pypy_version_info') // ... modified code ... from .. import pg_connection from .._util import closing ... def drop_db(self): self.base_cursor.execute( """ select pg_terminate_backend(pid) from pg_stat_activity where datname = %s """, (self.dbname,)) self.base_cursor.execute('drop database if exists ' + self.dbname) ... self.base_conn.close() class TestCase(DBSetup, unittest.TestCase): pass // ... rest of the code ...
8a9e58d2170e3f06228cbc0257d41f0c969da957
tangled/website/resources.py
tangled/website/resources.py
from tangled.web import Resource, represent from tangled.site.resources.entry import Entry class Docs(Entry): @represent('text/html', template_name='tangled.website:templates/docs.mako') def GET(self): static_dirs = self.app.get_all('static_directory', as_dict=True) links = [] for prefix, dir_app in static_dirs.items(): if prefix[0] == 'docs': links.append({ 'href': '/'.join(prefix), 'text': prefix[1], }) self.urlvars['id'] = 'docs' data = super().GET() data['links'] = sorted(links, key=lambda i: i['text']) return data
from tangled.web import Resource, config from tangled.site.resources.entry import Entry class Docs(Entry): @config('text/html', template_name='tangled.website:templates/docs.mako') def GET(self): static_dirs = self.app.get_all('static_directory', as_dict=True) links = [] for prefix, dir_app in static_dirs.items(): if prefix[0] == 'docs': links.append({ 'href': '/'.join(prefix), 'text': prefix[1], }) self.urlvars['id'] = 'docs' data = super().GET() data['links'] = sorted(links, key=lambda i: i['text']) return data
Replace @represent w/ @config throughout
Replace @represent w/ @config throughout New name, same functionality.
Python
mit
TangledWeb/tangled.website
- from tangled.web import Resource, represent + from tangled.web import Resource, config from tangled.site.resources.entry import Entry class Docs(Entry): - @represent('text/html', template_name='tangled.website:templates/docs.mako') + @config('text/html', template_name='tangled.website:templates/docs.mako') def GET(self): static_dirs = self.app.get_all('static_directory', as_dict=True) links = [] for prefix, dir_app in static_dirs.items(): if prefix[0] == 'docs': links.append({ 'href': '/'.join(prefix), 'text': prefix[1], }) self.urlvars['id'] = 'docs' data = super().GET() data['links'] = sorted(links, key=lambda i: i['text']) return data
Replace @represent w/ @config throughout
## Code Before: from tangled.web import Resource, represent from tangled.site.resources.entry import Entry class Docs(Entry): @represent('text/html', template_name='tangled.website:templates/docs.mako') def GET(self): static_dirs = self.app.get_all('static_directory', as_dict=True) links = [] for prefix, dir_app in static_dirs.items(): if prefix[0] == 'docs': links.append({ 'href': '/'.join(prefix), 'text': prefix[1], }) self.urlvars['id'] = 'docs' data = super().GET() data['links'] = sorted(links, key=lambda i: i['text']) return data ## Instruction: Replace @represent w/ @config throughout ## Code After: from tangled.web import Resource, config from tangled.site.resources.entry import Entry class Docs(Entry): @config('text/html', template_name='tangled.website:templates/docs.mako') def GET(self): static_dirs = self.app.get_all('static_directory', as_dict=True) links = [] for prefix, dir_app in static_dirs.items(): if prefix[0] == 'docs': links.append({ 'href': '/'.join(prefix), 'text': prefix[1], }) self.urlvars['id'] = 'docs' data = super().GET() data['links'] = sorted(links, key=lambda i: i['text']) return data
# ... existing code ... from tangled.web import Resource, config # ... modified code ... @config('text/html', template_name='tangled.website:templates/docs.mako') def GET(self): # ... rest of the code ...
c1b600596e49409daf31d20f821f280d0aadf124
emission/net/usercache/formatters/android/motion_activity.py
emission/net/usercache/formatters/android/motion_activity.py
import logging import emission.core.wrapper.motionactivity as ecwa import emission.net.usercache.formatters.common as fc import attrdict as ad def format(entry): formatted_entry = ad.AttrDict() formatted_entry["_id"] = entry["_id"] formatted_entry.user_id = entry.user_id metadata = entry.metadata if "time_zone" not in metadata: metadata.time_zone = "America/Los_Angeles" fc.expand_metadata_times(metadata) formatted_entry.metadata = metadata data = ad.AttrDict() if 'agb' in entry.data: data.type = ecwa.MotionTypes(entry.data.agb).value else: data.type = ecwa.MotionTypes(entry.data.zzaEg).value if 'agc' in entry.data: data.confidence = entry.data.agc else: data.confidence = entry.data.zzaEh data.ts = formatted_entry.metadata.write_ts data.local_dt = formatted_entry.metadata.write_local_dt data.fmt_time = formatted_entry.metadata.write_fmt_time formatted_entry.data = data return formatted_entry
import logging import emission.core.wrapper.motionactivity as ecwa import emission.net.usercache.formatters.common as fc import attrdict as ad def format(entry): formatted_entry = ad.AttrDict() formatted_entry["_id"] = entry["_id"] formatted_entry.user_id = entry.user_id metadata = entry.metadata if "time_zone" not in metadata: metadata.time_zone = "America/Los_Angeles" fc.expand_metadata_times(metadata) formatted_entry.metadata = metadata data = ad.AttrDict() if 'agb' in entry.data: data.type = ecwa.MotionTypes(entry.data.agb).value elif 'zzaEg' in entry.data: data.type = ecwa.MotionTypes(entry.data.zzaEg).value else: data.type = ecwa.MotionTypes(entry.data.zzaKM).value if 'agc' in entry.data: data.confidence = entry.data.agc elif 'zzaEh' in entry.data: data.confidence = entry.data.zzaEh else: data.confidence = entry.data.zzaKN data.ts = formatted_entry.metadata.write_ts data.local_dt = formatted_entry.metadata.write_local_dt data.fmt_time = formatted_entry.metadata.write_fmt_time formatted_entry.data = data return formatted_entry
Support the new google play motion activity format
Support the new google play motion activity format As part of the change to slim down the apk for android, https://github.com/e-mission/e-mission-phone/pull/46, https://github.com/e-mission/e-mission-data-collection/pull/116 we switched from google play version from 8.1.0 to 8.3.0, which is the version that has separate jar files, at least in my install. But this changed the motion activity format - the field names are now `zzaKM` and `zzaKN` instead of `zzaEg` and `zzaEh`. So we change the formatter on the server to handle this use case as well. Note that we should really fix https://github.com/e-mission/e-mission-data-collection/issues/80 to stop running into this in the future
Python
bsd-3-clause
yw374cornell/e-mission-server,yw374cornell/e-mission-server,sunil07t/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server,yw374cornell/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server,shankari/e-mission-server,yw374cornell/e-mission-server
import logging import emission.core.wrapper.motionactivity as ecwa import emission.net.usercache.formatters.common as fc import attrdict as ad def format(entry): formatted_entry = ad.AttrDict() formatted_entry["_id"] = entry["_id"] formatted_entry.user_id = entry.user_id metadata = entry.metadata if "time_zone" not in metadata: metadata.time_zone = "America/Los_Angeles" fc.expand_metadata_times(metadata) formatted_entry.metadata = metadata data = ad.AttrDict() if 'agb' in entry.data: data.type = ecwa.MotionTypes(entry.data.agb).value + elif 'zzaEg' in entry.data: + data.type = ecwa.MotionTypes(entry.data.zzaEg).value else: - data.type = ecwa.MotionTypes(entry.data.zzaEg).value + data.type = ecwa.MotionTypes(entry.data.zzaKM).value + if 'agc' in entry.data: data.confidence = entry.data.agc + elif 'zzaEh' in entry.data: + data.confidence = entry.data.zzaEh else: - data.confidence = entry.data.zzaEh + data.confidence = entry.data.zzaKN data.ts = formatted_entry.metadata.write_ts data.local_dt = formatted_entry.metadata.write_local_dt data.fmt_time = formatted_entry.metadata.write_fmt_time formatted_entry.data = data return formatted_entry
Support the new google play motion activity format
## Code Before: import logging import emission.core.wrapper.motionactivity as ecwa import emission.net.usercache.formatters.common as fc import attrdict as ad def format(entry): formatted_entry = ad.AttrDict() formatted_entry["_id"] = entry["_id"] formatted_entry.user_id = entry.user_id metadata = entry.metadata if "time_zone" not in metadata: metadata.time_zone = "America/Los_Angeles" fc.expand_metadata_times(metadata) formatted_entry.metadata = metadata data = ad.AttrDict() if 'agb' in entry.data: data.type = ecwa.MotionTypes(entry.data.agb).value else: data.type = ecwa.MotionTypes(entry.data.zzaEg).value if 'agc' in entry.data: data.confidence = entry.data.agc else: data.confidence = entry.data.zzaEh data.ts = formatted_entry.metadata.write_ts data.local_dt = formatted_entry.metadata.write_local_dt data.fmt_time = formatted_entry.metadata.write_fmt_time formatted_entry.data = data return formatted_entry ## Instruction: Support the new google play motion activity format ## Code After: import logging import emission.core.wrapper.motionactivity as ecwa import emission.net.usercache.formatters.common as fc import attrdict as ad def format(entry): formatted_entry = ad.AttrDict() formatted_entry["_id"] = entry["_id"] formatted_entry.user_id = entry.user_id metadata = entry.metadata if "time_zone" not in metadata: metadata.time_zone = "America/Los_Angeles" fc.expand_metadata_times(metadata) formatted_entry.metadata = metadata data = ad.AttrDict() if 'agb' in entry.data: data.type = ecwa.MotionTypes(entry.data.agb).value elif 'zzaEg' in entry.data: data.type = ecwa.MotionTypes(entry.data.zzaEg).value else: data.type = ecwa.MotionTypes(entry.data.zzaKM).value if 'agc' in entry.data: data.confidence = entry.data.agc elif 'zzaEh' in entry.data: data.confidence = entry.data.zzaEh else: data.confidence = entry.data.zzaKN data.ts = formatted_entry.metadata.write_ts data.local_dt = formatted_entry.metadata.write_local_dt data.fmt_time = formatted_entry.metadata.write_fmt_time formatted_entry.data = data return formatted_entry
... data.type = ecwa.MotionTypes(entry.data.agb).value elif 'zzaEg' in entry.data: data.type = ecwa.MotionTypes(entry.data.zzaEg).value else: data.type = ecwa.MotionTypes(entry.data.zzaKM).value ... data.confidence = entry.data.agc elif 'zzaEh' in entry.data: data.confidence = entry.data.zzaEh else: data.confidence = entry.data.zzaKN ...
7574528d839dc627ea53032b547e0e1c23a51f6b
rdioexport/_client/__init__.py
rdioexport/_client/__init__.py
import json from ._base import get_base_rdio_client class _RdioExportClient(object): def __init__(self, base_client): self.base_client = base_client def get_current_user_key(self): return self.base_client.call('currentUser')['key'] def get_collection_by_album(self, batch_size=100): current_user_key = self.get_current_user_key() start = 0 result = [] while True: batch = self.base_client.call( 'getAlbumsInCollection', user=current_user_key, sort='dateAdded', start=start, count=batch_size, extras=json.dumps([ {'field': '*', 'exclude': True}, {'field': 'key'}, {'field': 'artist'}, {'field': 'trackKeys'}, ]), ) for album in batch: yield album if (len(batch) < batch_size): break else: start += batch_size def get_album_data(self, album_key): return self.base_client.call( 'get', keys=album_key, extras=json.dumps([ {'field': '*'}, { 'field': 'track', 'extras': [ {'field': '*'}, ], }, ]), ) def get_rdio_client(): base_client = get_base_rdio_client() return _RdioExportClient(base_client)
import json from ._base import get_base_rdio_client class _RdioExportClient(object): def __init__(self, base_client): self.base_client = base_client def get_current_user_key(self): return self.base_client.call('currentUser')['key'] def get_collection_by_album(self, batch_size=100): current_user_key = self.get_current_user_key() start = 0 result = [] while True: batch = self.base_client.call( 'getAlbumsInCollection', user=current_user_key, sort='dateAdded', start=start, count=batch_size, extras=json.dumps([ {'field': '*', 'exclude': True}, {'field': 'key'}, {'field': 'trackKeys'}, ]), ) for album in batch: yield album if (len(batch) < batch_size): break else: start += batch_size def get_album_data(self, album_key): return self.base_client.call( 'get', keys=album_key, extras=json.dumps([ {'field': '*'}, { 'field': 'track', 'extras': [ {'field': '*'}, ], }, ]), ) def get_rdio_client(): base_client = get_base_rdio_client() return _RdioExportClient(base_client)
Remove unused field from request.
Remove unused field from request.
Python
isc
alexhanson/rdio-export
import json from ._base import get_base_rdio_client class _RdioExportClient(object): def __init__(self, base_client): self.base_client = base_client def get_current_user_key(self): return self.base_client.call('currentUser')['key'] def get_collection_by_album(self, batch_size=100): current_user_key = self.get_current_user_key() start = 0 result = [] while True: batch = self.base_client.call( 'getAlbumsInCollection', user=current_user_key, sort='dateAdded', start=start, count=batch_size, extras=json.dumps([ {'field': '*', 'exclude': True}, {'field': 'key'}, - {'field': 'artist'}, {'field': 'trackKeys'}, ]), ) for album in batch: yield album if (len(batch) < batch_size): break else: start += batch_size def get_album_data(self, album_key): return self.base_client.call( 'get', keys=album_key, extras=json.dumps([ {'field': '*'}, { 'field': 'track', 'extras': [ {'field': '*'}, ], }, ]), ) def get_rdio_client(): base_client = get_base_rdio_client() return _RdioExportClient(base_client)
Remove unused field from request.
## Code Before: import json from ._base import get_base_rdio_client class _RdioExportClient(object): def __init__(self, base_client): self.base_client = base_client def get_current_user_key(self): return self.base_client.call('currentUser')['key'] def get_collection_by_album(self, batch_size=100): current_user_key = self.get_current_user_key() start = 0 result = [] while True: batch = self.base_client.call( 'getAlbumsInCollection', user=current_user_key, sort='dateAdded', start=start, count=batch_size, extras=json.dumps([ {'field': '*', 'exclude': True}, {'field': 'key'}, {'field': 'artist'}, {'field': 'trackKeys'}, ]), ) for album in batch: yield album if (len(batch) < batch_size): break else: start += batch_size def get_album_data(self, album_key): return self.base_client.call( 'get', keys=album_key, extras=json.dumps([ {'field': '*'}, { 'field': 'track', 'extras': [ {'field': '*'}, ], }, ]), ) def get_rdio_client(): base_client = get_base_rdio_client() return _RdioExportClient(base_client) ## Instruction: Remove unused field from request. ## Code After: import json from ._base import get_base_rdio_client class _RdioExportClient(object): def __init__(self, base_client): self.base_client = base_client def get_current_user_key(self): return self.base_client.call('currentUser')['key'] def get_collection_by_album(self, batch_size=100): current_user_key = self.get_current_user_key() start = 0 result = [] while True: batch = self.base_client.call( 'getAlbumsInCollection', user=current_user_key, sort='dateAdded', start=start, count=batch_size, extras=json.dumps([ {'field': '*', 'exclude': True}, {'field': 'key'}, {'field': 'trackKeys'}, ]), ) for album in batch: yield album if (len(batch) < batch_size): break else: start += batch_size def get_album_data(self, album_key): return self.base_client.call( 'get', keys=album_key, extras=json.dumps([ {'field': '*'}, { 'field': 'track', 'extras': [ {'field': '*'}, ], }, ]), ) def get_rdio_client(): base_client = get_base_rdio_client() return _RdioExportClient(base_client)
... {'field': 'key'}, {'field': 'trackKeys'}, ...
ab98637aa949a02618f6b119983f40bcbde80d43
examples/play_series_montecarlo_vs_random.py
examples/play_series_montecarlo_vs_random.py
from capstone.game import TicTacToe from capstone.player import MonteCarlo, RandPlayer from capstone.util import play_series game = TicTacToe() players = [MonteCarlo(), RandPlayer()] n_matches = 10 play_series(game, players, n_matches) players.reverse() play_series(game, players, n_matches)
from capstone.game import TicTacToe from capstone.player import MonteCarlo, RandPlayer from capstone.util import play_series game = TicTacToe() players = [MonteCarlo(), RandPlayer()] n_matches = 10 play_series(game, players, n_matches) print('') players.reverse() play_series(game, players, n_matches)
Add line break to play series monte carlo
Add line break to play series monte carlo
Python
mit
davidrobles/mlnd-capstone-code
from capstone.game import TicTacToe from capstone.player import MonteCarlo, RandPlayer from capstone.util import play_series game = TicTacToe() players = [MonteCarlo(), RandPlayer()] n_matches = 10 play_series(game, players, n_matches) + print('') players.reverse() play_series(game, players, n_matches)
Add line break to play series monte carlo
## Code Before: from capstone.game import TicTacToe from capstone.player import MonteCarlo, RandPlayer from capstone.util import play_series game = TicTacToe() players = [MonteCarlo(), RandPlayer()] n_matches = 10 play_series(game, players, n_matches) players.reverse() play_series(game, players, n_matches) ## Instruction: Add line break to play series monte carlo ## Code After: from capstone.game import TicTacToe from capstone.player import MonteCarlo, RandPlayer from capstone.util import play_series game = TicTacToe() players = [MonteCarlo(), RandPlayer()] n_matches = 10 play_series(game, players, n_matches) print('') players.reverse() play_series(game, players, n_matches)
# ... existing code ... play_series(game, players, n_matches) print('') players.reverse() # ... rest of the code ...
e029998f73a77ebd8f4a6e32a8b03edcc93ec0d7
dataproperty/__init__.py
dataproperty/__init__.py
from __future__ import absolute_import from ._align import Align from ._align_getter import align_getter from ._container import MinMaxContainer from ._data_property import ( ColumnDataProperty, DataProperty ) from ._error import TypeConversionError from ._function import ( is_integer, is_hex, is_float, is_nan, is_empty_string, is_not_empty_string, is_list_or_tuple, is_empty_sequence, is_not_empty_sequence, is_empty_list_or_tuple, is_not_empty_list_or_tuple, is_datetime, get_integer_digit, get_number_of_digit, get_text_len, strict_strtobool ) from ._property_extractor import PropertyExtractor from ._type import ( NoneType, StringType, IntegerType, FloatType, DateTimeType, BoolType, InfinityType, NanType ) from ._typecode import Typecode
from __future__ import absolute_import from ._align import Align from ._align_getter import align_getter from ._container import MinMaxContainer from ._data_property import ( ColumnDataProperty, DataProperty ) from ._error import TypeConversionError from ._function import ( is_integer, is_hex, is_float, is_nan, is_empty_string, is_not_empty_string, is_list_or_tuple, is_empty_sequence, is_not_empty_sequence, is_empty_list_or_tuple, is_not_empty_list_or_tuple, is_datetime, get_integer_digit, get_number_of_digit, get_text_len ) from ._property_extractor import PropertyExtractor from ._type import ( NoneType, StringType, IntegerType, FloatType, DateTimeType, BoolType, InfinityType, NanType ) from ._typecode import Typecode
Delete import that no longer used
Delete import that no longer used
Python
mit
thombashi/DataProperty
from __future__ import absolute_import from ._align import Align from ._align_getter import align_getter from ._container import MinMaxContainer from ._data_property import ( ColumnDataProperty, DataProperty ) from ._error import TypeConversionError from ._function import ( is_integer, is_hex, is_float, is_nan, is_empty_string, is_not_empty_string, is_list_or_tuple, is_empty_sequence, is_not_empty_sequence, is_empty_list_or_tuple, is_not_empty_list_or_tuple, is_datetime, get_integer_digit, get_number_of_digit, - get_text_len, + get_text_len - strict_strtobool ) from ._property_extractor import PropertyExtractor from ._type import ( NoneType, StringType, IntegerType, FloatType, DateTimeType, BoolType, InfinityType, NanType ) from ._typecode import Typecode
Delete import that no longer used
## Code Before: from __future__ import absolute_import from ._align import Align from ._align_getter import align_getter from ._container import MinMaxContainer from ._data_property import ( ColumnDataProperty, DataProperty ) from ._error import TypeConversionError from ._function import ( is_integer, is_hex, is_float, is_nan, is_empty_string, is_not_empty_string, is_list_or_tuple, is_empty_sequence, is_not_empty_sequence, is_empty_list_or_tuple, is_not_empty_list_or_tuple, is_datetime, get_integer_digit, get_number_of_digit, get_text_len, strict_strtobool ) from ._property_extractor import PropertyExtractor from ._type import ( NoneType, StringType, IntegerType, FloatType, DateTimeType, BoolType, InfinityType, NanType ) from ._typecode import Typecode ## Instruction: Delete import that no longer used ## Code After: from __future__ import absolute_import from ._align import Align from ._align_getter import align_getter from ._container import MinMaxContainer from ._data_property import ( ColumnDataProperty, DataProperty ) from ._error import TypeConversionError from ._function import ( is_integer, is_hex, is_float, is_nan, is_empty_string, is_not_empty_string, is_list_or_tuple, is_empty_sequence, is_not_empty_sequence, is_empty_list_or_tuple, is_not_empty_list_or_tuple, is_datetime, get_integer_digit, get_number_of_digit, get_text_len ) from ._property_extractor import PropertyExtractor from ._type import ( NoneType, StringType, IntegerType, FloatType, DateTimeType, BoolType, InfinityType, NanType ) from ._typecode import Typecode
... get_number_of_digit, get_text_len ) ...
5d8dafb9bd6a6c5c5964f7076b7d398d285aaf8d
zeus/artifacts/__init__.py
zeus/artifacts/__init__.py
from __future__ import absolute_import, print_function from .manager import Manager from .checkstyle import CheckstyleHandler from .coverage import CoverageHandler from .pycodestyle import PyCodeStyleHandler from .xunit import XunitHandler manager = Manager() manager.register(CheckstyleHandler, [ 'checkstyle.xml', '*.checkstyle.xml']) manager.register(CoverageHandler, [ 'coverage.xml', '*.coverage.xml']) manager.register(XunitHandler, [ 'xunit.xml', 'junit.xml', '*.xunit.xml', '*.junit.xml']) manager.register(PyCodeStyleHandler, [ 'pep8.txt', '*.pep8.txt', 'pycodestyle.txt', '*.pycodestyle.txt'])
from __future__ import absolute_import, print_function from .manager import Manager from .checkstyle import CheckstyleHandler from .coverage import CoverageHandler from .pycodestyle import PyCodeStyleHandler from .pylint import PyLintHandler from .xunit import XunitHandler manager = Manager() manager.register(CheckstyleHandler, [ 'checkstyle.xml', '*.checkstyle.xml']) manager.register(CoverageHandler, [ 'coverage.xml', '*.coverage.xml']) manager.register(XunitHandler, [ 'xunit.xml', 'junit.xml', '*.xunit.xml', '*.junit.xml']) manager.register(PyCodeStyleHandler, [ 'pep8.txt', '*.pep8.txt', 'pycodestyle.txt', '*.pycodestyle.txt']) manager.register(PyLintHandler, [ 'pylint.txt', '*.pylint.txt'])
Add PyLintHandler to artifact manager
fix: Add PyLintHandler to artifact manager
Python
apache-2.0
getsentry/zeus,getsentry/zeus,getsentry/zeus,getsentry/zeus
from __future__ import absolute_import, print_function from .manager import Manager from .checkstyle import CheckstyleHandler from .coverage import CoverageHandler from .pycodestyle import PyCodeStyleHandler + from .pylint import PyLintHandler from .xunit import XunitHandler manager = Manager() manager.register(CheckstyleHandler, [ 'checkstyle.xml', '*.checkstyle.xml']) manager.register(CoverageHandler, [ 'coverage.xml', '*.coverage.xml']) manager.register(XunitHandler, [ 'xunit.xml', 'junit.xml', '*.xunit.xml', '*.junit.xml']) manager.register(PyCodeStyleHandler, [ 'pep8.txt', '*.pep8.txt', 'pycodestyle.txt', '*.pycodestyle.txt']) + manager.register(PyLintHandler, [ + 'pylint.txt', '*.pylint.txt'])
Add PyLintHandler to artifact manager
## Code Before: from __future__ import absolute_import, print_function from .manager import Manager from .checkstyle import CheckstyleHandler from .coverage import CoverageHandler from .pycodestyle import PyCodeStyleHandler from .xunit import XunitHandler manager = Manager() manager.register(CheckstyleHandler, [ 'checkstyle.xml', '*.checkstyle.xml']) manager.register(CoverageHandler, [ 'coverage.xml', '*.coverage.xml']) manager.register(XunitHandler, [ 'xunit.xml', 'junit.xml', '*.xunit.xml', '*.junit.xml']) manager.register(PyCodeStyleHandler, [ 'pep8.txt', '*.pep8.txt', 'pycodestyle.txt', '*.pycodestyle.txt']) ## Instruction: Add PyLintHandler to artifact manager ## Code After: from __future__ import absolute_import, print_function from .manager import Manager from .checkstyle import CheckstyleHandler from .coverage import CoverageHandler from .pycodestyle import PyCodeStyleHandler from .pylint import PyLintHandler from .xunit import XunitHandler manager = Manager() manager.register(CheckstyleHandler, [ 'checkstyle.xml', '*.checkstyle.xml']) manager.register(CoverageHandler, [ 'coverage.xml', '*.coverage.xml']) manager.register(XunitHandler, [ 'xunit.xml', 'junit.xml', '*.xunit.xml', '*.junit.xml']) manager.register(PyCodeStyleHandler, [ 'pep8.txt', '*.pep8.txt', 'pycodestyle.txt', '*.pycodestyle.txt']) manager.register(PyLintHandler, [ 'pylint.txt', '*.pylint.txt'])
... from .pycodestyle import PyCodeStyleHandler from .pylint import PyLintHandler from .xunit import XunitHandler ... 'pep8.txt', '*.pep8.txt', 'pycodestyle.txt', '*.pycodestyle.txt']) manager.register(PyLintHandler, [ 'pylint.txt', '*.pylint.txt']) ...
07fd8bf23917e18ba419859d788d9f51735f3b39
conda_gitenv/__init__.py
conda_gitenv/__init__.py
from __future__ import absolute_import, division, print_function, unicode_literals from distutils.version import StrictVersion from conda import __version__ as CONDA_VERSION from ._version import get_versions __version__ = get_versions()['version'] del get_versions _conda_base = StrictVersion('4.3.0') _conda_support = StrictVersion(CONDA_VERSION) >= _conda_base assert _conda_support, 'Minimum supported conda version is {}.'.format(_conda_base) manifest_branch_prefix = 'manifest/'
from __future__ import absolute_import, division, print_function, unicode_literals from distutils.version import StrictVersion from conda import __version__ as CONDA_VERSION from ._version import get_versions __version__ = get_versions()['version'] del get_versions _conda_base = StrictVersion('4.3.0') _conda_version = StrictVersion(CONDA_VERSION) _conda_supported = _conda_version >= _conda_base assert _conda_support, 'Minimum supported conda version is {}, got {}.'.format(_conda_base, _conda_version) manifest_branch_prefix = 'manifest/'
Update minimum conda version diagnostic
Update minimum conda version diagnostic
Python
bsd-3-clause
SciTools/conda-gitenv
from __future__ import absolute_import, division, print_function, unicode_literals from distutils.version import StrictVersion from conda import __version__ as CONDA_VERSION from ._version import get_versions __version__ = get_versions()['version'] del get_versions _conda_base = StrictVersion('4.3.0') - _conda_support = StrictVersion(CONDA_VERSION) >= _conda_base + _conda_version = StrictVersion(CONDA_VERSION) + _conda_supported = _conda_version >= _conda_base - assert _conda_support, 'Minimum supported conda version is {}.'.format(_conda_base) + assert _conda_support, 'Minimum supported conda version is {}, got {}.'.format(_conda_base, _conda_version) manifest_branch_prefix = 'manifest/'
Update minimum conda version diagnostic
## Code Before: from __future__ import absolute_import, division, print_function, unicode_literals from distutils.version import StrictVersion from conda import __version__ as CONDA_VERSION from ._version import get_versions __version__ = get_versions()['version'] del get_versions _conda_base = StrictVersion('4.3.0') _conda_support = StrictVersion(CONDA_VERSION) >= _conda_base assert _conda_support, 'Minimum supported conda version is {}.'.format(_conda_base) manifest_branch_prefix = 'manifest/' ## Instruction: Update minimum conda version diagnostic ## Code After: from __future__ import absolute_import, division, print_function, unicode_literals from distutils.version import StrictVersion from conda import __version__ as CONDA_VERSION from ._version import get_versions __version__ = get_versions()['version'] del get_versions _conda_base = StrictVersion('4.3.0') _conda_version = StrictVersion(CONDA_VERSION) _conda_supported = _conda_version >= _conda_base assert _conda_support, 'Minimum supported conda version is {}, got {}.'.format(_conda_base, _conda_version) manifest_branch_prefix = 'manifest/'
# ... existing code ... _conda_base = StrictVersion('4.3.0') _conda_version = StrictVersion(CONDA_VERSION) _conda_supported = _conda_version >= _conda_base assert _conda_support, 'Minimum supported conda version is {}, got {}.'.format(_conda_base, _conda_version) # ... rest of the code ...
d5b068b2efc5fca30014ac7b4d58123461bfbdc1
djedi/utils/templates.py
djedi/utils/templates.py
import json from django.core.exceptions import ImproperlyConfigured from ..compat import NoReverseMatch, render, render_to_string, reverse def render_embed(nodes=None, request=None): context = {} if nodes is None: try: prefix = request.build_absolute_uri("/").rstrip("/") context.update( { "cms_url": prefix + reverse("admin:djedi:cms"), "exclude_json_nodes": True, } ) output = render(request, "djedi/cms/embed.html", context) except NoReverseMatch: raise ImproperlyConfigured( "Could not find djedi in your url conf, " "include djedi.rest.urls within the djedi namespace." ) else: context.update( { "cms_url": reverse("admin:djedi:cms"), "exclude_json_nodes": False, "json_nodes": json.dumps(nodes).replace("</", "\\x3C/"), } ) output = render_to_string("djedi/cms/embed.html", context) return output
import json from django.core.exceptions import ImproperlyConfigured from ..compat import NoReverseMatch, render, render_to_string, reverse def render_embed(nodes=None, request=None): context = {} if nodes is None: try: prefix = request.build_absolute_uri("/").rstrip("/") context.update( { "cms_url": prefix + reverse("admin:djedi:cms"), "exclude_json_nodes": True, } ) output = render(request, "djedi/cms/embed.html", context) except NoReverseMatch: raise ImproperlyConfigured( "Could not find djedi in your url conf, " "enable django admin or include " "djedi.urls within the admin namespace." ) else: context.update( { "cms_url": reverse("admin:djedi:cms"), "exclude_json_nodes": False, "json_nodes": json.dumps(nodes).replace("</", "\\x3C/"), } ) output = render_to_string("djedi/cms/embed.html", context) return output
Update rest api url config error message
Update rest api url config error message
Python
bsd-3-clause
5monkeys/djedi-cms,5monkeys/djedi-cms,5monkeys/djedi-cms
import json from django.core.exceptions import ImproperlyConfigured from ..compat import NoReverseMatch, render, render_to_string, reverse def render_embed(nodes=None, request=None): context = {} if nodes is None: try: prefix = request.build_absolute_uri("/").rstrip("/") context.update( { "cms_url": prefix + reverse("admin:djedi:cms"), "exclude_json_nodes": True, } ) output = render(request, "djedi/cms/embed.html", context) except NoReverseMatch: raise ImproperlyConfigured( "Could not find djedi in your url conf, " + "enable django admin or include " - "include djedi.rest.urls within the djedi namespace." + "djedi.urls within the admin namespace." ) else: context.update( { "cms_url": reverse("admin:djedi:cms"), "exclude_json_nodes": False, "json_nodes": json.dumps(nodes).replace("</", "\\x3C/"), } ) output = render_to_string("djedi/cms/embed.html", context) return output
Update rest api url config error message
## Code Before: import json from django.core.exceptions import ImproperlyConfigured from ..compat import NoReverseMatch, render, render_to_string, reverse def render_embed(nodes=None, request=None): context = {} if nodes is None: try: prefix = request.build_absolute_uri("/").rstrip("/") context.update( { "cms_url": prefix + reverse("admin:djedi:cms"), "exclude_json_nodes": True, } ) output = render(request, "djedi/cms/embed.html", context) except NoReverseMatch: raise ImproperlyConfigured( "Could not find djedi in your url conf, " "include djedi.rest.urls within the djedi namespace." ) else: context.update( { "cms_url": reverse("admin:djedi:cms"), "exclude_json_nodes": False, "json_nodes": json.dumps(nodes).replace("</", "\\x3C/"), } ) output = render_to_string("djedi/cms/embed.html", context) return output ## Instruction: Update rest api url config error message ## Code After: import json from django.core.exceptions import ImproperlyConfigured from ..compat import NoReverseMatch, render, render_to_string, reverse def render_embed(nodes=None, request=None): context = {} if nodes is None: try: prefix = request.build_absolute_uri("/").rstrip("/") context.update( { "cms_url": prefix + reverse("admin:djedi:cms"), "exclude_json_nodes": True, } ) output = render(request, "djedi/cms/embed.html", context) except NoReverseMatch: raise ImproperlyConfigured( "Could not find djedi in your url conf, " "enable django admin or include " "djedi.urls within the admin namespace." ) else: context.update( { "cms_url": reverse("admin:djedi:cms"), "exclude_json_nodes": False, "json_nodes": json.dumps(nodes).replace("</", "\\x3C/"), } ) output = render_to_string("djedi/cms/embed.html", context) return output
// ... existing code ... "Could not find djedi in your url conf, " "enable django admin or include " "djedi.urls within the admin namespace." ) // ... rest of the code ...
8b87a55a03422cc499b2f7cc168bcc0c15c0ae42
mycli/clibuffer.py
mycli/clibuffer.py
from prompt_toolkit.buffer import Buffer from prompt_toolkit.filters import Condition class CLIBuffer(Buffer): def __init__(self, always_multiline, *args, **kwargs): self.always_multiline = always_multiline @Condition def is_multiline(): doc = self.document return self.always_multiline and not _multiline_exception(doc.text) super(self.__class__, self).__init__(*args, is_multiline=is_multiline, tempfile_suffix='.sql', **kwargs) def _multiline_exception(text): orig = text text = text.strip() # Multi-statement favorite query is a special case. Because there will # be a semicolon separating statements, we can't consider semicolon an # EOL. Let's consider an empty line an EOL instead. if text.startswith('\\fs'): return orig.endswith('\n') return (text.startswith('\\') or # Special Command text.endswith(';') or # Ended with a semi-colon (text == 'exit') or # Exit doesn't need semi-colon (text == 'quit') or # Quit doesn't need semi-colon (text == ':q') or # To all the vim fans out there (text == '') # Just a plain enter without any text )
from prompt_toolkit.buffer import Buffer from prompt_toolkit.filters import Condition class CLIBuffer(Buffer): def __init__(self, always_multiline, *args, **kwargs): self.always_multiline = always_multiline @Condition def is_multiline(): doc = self.document return self.always_multiline and not _multiline_exception(doc.text) super(self.__class__, self).__init__(*args, is_multiline=is_multiline, tempfile_suffix='.sql', **kwargs) def _multiline_exception(text): orig = text text = text.strip() # Multi-statement favorite query is a special case. Because there will # be a semicolon separating statements, we can't consider semicolon an # EOL. Let's consider an empty line an EOL instead. if text.startswith('\\fs'): return orig.endswith('\n') return (text.startswith('\\') or # Special Command text.endswith(';') or # Ended with a semi-colon text.endswith('\\g') or # Ended with \g text.endswith('\\G') or # Ended with \G (text == 'exit') or # Exit doesn't need semi-colon (text == 'quit') or # Quit doesn't need semi-colon (text == ':q') or # To all the vim fans out there (text == '') # Just a plain enter without any text )
Make \G or \g to end a query.
Make \G or \g to end a query.
Python
bsd-3-clause
j-bennet/mycli,jinstrive/mycli,mdsrosa/mycli,evook/mycli,shoma/mycli,chenpingzhao/mycli,mdsrosa/mycli,D-e-e-m-o/mycli,evook/mycli,jinstrive/mycli,martijnengler/mycli,webwlsong/mycli,webwlsong/mycli,oguzy/mycli,suzukaze/mycli,oguzy/mycli,danieljwest/mycli,MnO2/rediscli,danieljwest/mycli,martijnengler/mycli,D-e-e-m-o/mycli,j-bennet/mycli,MnO2/rediscli,chenpingzhao/mycli,ZuoGuocai/mycli,suzukaze/mycli,ZuoGuocai/mycli,shoma/mycli
from prompt_toolkit.buffer import Buffer from prompt_toolkit.filters import Condition class CLIBuffer(Buffer): def __init__(self, always_multiline, *args, **kwargs): self.always_multiline = always_multiline @Condition def is_multiline(): doc = self.document return self.always_multiline and not _multiline_exception(doc.text) super(self.__class__, self).__init__(*args, is_multiline=is_multiline, tempfile_suffix='.sql', **kwargs) def _multiline_exception(text): orig = text text = text.strip() # Multi-statement favorite query is a special case. Because there will # be a semicolon separating statements, we can't consider semicolon an # EOL. Let's consider an empty line an EOL instead. if text.startswith('\\fs'): return orig.endswith('\n') return (text.startswith('\\') or # Special Command text.endswith(';') or # Ended with a semi-colon + text.endswith('\\g') or # Ended with \g + text.endswith('\\G') or # Ended with \G (text == 'exit') or # Exit doesn't need semi-colon (text == 'quit') or # Quit doesn't need semi-colon (text == ':q') or # To all the vim fans out there (text == '') # Just a plain enter without any text )
Make \G or \g to end a query.
## Code Before: from prompt_toolkit.buffer import Buffer from prompt_toolkit.filters import Condition class CLIBuffer(Buffer): def __init__(self, always_multiline, *args, **kwargs): self.always_multiline = always_multiline @Condition def is_multiline(): doc = self.document return self.always_multiline and not _multiline_exception(doc.text) super(self.__class__, self).__init__(*args, is_multiline=is_multiline, tempfile_suffix='.sql', **kwargs) def _multiline_exception(text): orig = text text = text.strip() # Multi-statement favorite query is a special case. Because there will # be a semicolon separating statements, we can't consider semicolon an # EOL. Let's consider an empty line an EOL instead. if text.startswith('\\fs'): return orig.endswith('\n') return (text.startswith('\\') or # Special Command text.endswith(';') or # Ended with a semi-colon (text == 'exit') or # Exit doesn't need semi-colon (text == 'quit') or # Quit doesn't need semi-colon (text == ':q') or # To all the vim fans out there (text == '') # Just a plain enter without any text ) ## Instruction: Make \G or \g to end a query. ## Code After: from prompt_toolkit.buffer import Buffer from prompt_toolkit.filters import Condition class CLIBuffer(Buffer): def __init__(self, always_multiline, *args, **kwargs): self.always_multiline = always_multiline @Condition def is_multiline(): doc = self.document return self.always_multiline and not _multiline_exception(doc.text) super(self.__class__, self).__init__(*args, is_multiline=is_multiline, tempfile_suffix='.sql', **kwargs) def _multiline_exception(text): orig = text text = text.strip() # Multi-statement favorite query is a special case. Because there will # be a semicolon separating statements, we can't consider semicolon an # EOL. Let's consider an empty line an EOL instead. if text.startswith('\\fs'): return orig.endswith('\n') return (text.startswith('\\') or # Special Command text.endswith(';') or # Ended with a semi-colon text.endswith('\\g') or # Ended with \g text.endswith('\\G') or # Ended with \G (text == 'exit') or # Exit doesn't need semi-colon (text == 'quit') or # Quit doesn't need semi-colon (text == ':q') or # To all the vim fans out there (text == '') # Just a plain enter without any text )
# ... existing code ... text.endswith(';') or # Ended with a semi-colon text.endswith('\\g') or # Ended with \g text.endswith('\\G') or # Ended with \G (text == 'exit') or # Exit doesn't need semi-colon # ... rest of the code ...
e8175497157ed34f91b9ba96118c4e76cd3ed0e4
bmsmodules/Events.py
bmsmodules/Events.py
from operator import isCallable class Events(object): def __init__(self): self._events_ = {} def addEvent(self, eventname, func): if not isCallable(func): raise RuntimeError("func argument must be a function!") elif not isinstance(eventname, basestring): raise RuntimeError("Event name must be a string!") elif eventname in self._events_: raise RuntimeError("Event name already exists!") else: self._events_[eventname] = func def execEvent(self, eventname, *args, **kwargs): if eventname not in self._events_: raise RuntimeError("No such Event name '{0}'".format(eventname))
from operator import isCallable class Events(object): def __init__(self): self._events_ = {} def addEvent(self, eventname, func): if not isCallable(func): raise RuntimeError("func argument must be a function!") elif not isinstance(eventname, (basestring, int)): raise RuntimeError("Event name must be a string!") elif eventname in self._events_: raise RuntimeError("Event name already exists!") else: self._events_[eventname] = func def execEvent(self, eventname, *args, **kwargs): if eventname not in self._events_: raise RuntimeError("No such Event name '{0}'".format(eventname)) else: self._events_[eventname](*args, **kwargs)
Add event execution, allow integers as event name
Add event execution, allow integers as event name
Python
bsd-3-clause
RenolY2/py-playBMS
from operator import isCallable class Events(object): def __init__(self): self._events_ = {} def addEvent(self, eventname, func): if not isCallable(func): raise RuntimeError("func argument must be a function!") - elif not isinstance(eventname, basestring): + elif not isinstance(eventname, (basestring, int)): raise RuntimeError("Event name must be a string!") elif eventname in self._events_: raise RuntimeError("Event name already exists!") else: self._events_[eventname] = func def execEvent(self, eventname, *args, **kwargs): if eventname not in self._events_: raise RuntimeError("No such Event name '{0}'".format(eventname)) + else: + self._events_[eventname](*args, **kwargs)
Add event execution, allow integers as event name
## Code Before: from operator import isCallable class Events(object): def __init__(self): self._events_ = {} def addEvent(self, eventname, func): if not isCallable(func): raise RuntimeError("func argument must be a function!") elif not isinstance(eventname, basestring): raise RuntimeError("Event name must be a string!") elif eventname in self._events_: raise RuntimeError("Event name already exists!") else: self._events_[eventname] = func def execEvent(self, eventname, *args, **kwargs): if eventname not in self._events_: raise RuntimeError("No such Event name '{0}'".format(eventname)) ## Instruction: Add event execution, allow integers as event name ## Code After: from operator import isCallable class Events(object): def __init__(self): self._events_ = {} def addEvent(self, eventname, func): if not isCallable(func): raise RuntimeError("func argument must be a function!") elif not isinstance(eventname, (basestring, int)): raise RuntimeError("Event name must be a string!") elif eventname in self._events_: raise RuntimeError("Event name already exists!") else: self._events_[eventname] = func def execEvent(self, eventname, *args, **kwargs): if eventname not in self._events_: raise RuntimeError("No such Event name '{0}'".format(eventname)) else: self._events_[eventname](*args, **kwargs)
... raise RuntimeError("func argument must be a function!") elif not isinstance(eventname, (basestring, int)): raise RuntimeError("Event name must be a string!") ... raise RuntimeError("No such Event name '{0}'".format(eventname)) else: self._events_[eventname](*args, **kwargs) ...
194e6a34744963e2a7b17b846ee2913e6e01ae11
pyblish_starter/plugins/validate_rig_members.py
pyblish_starter/plugins/validate_rig_members.py
import pyblish.api class ValidateStarterRigFormat(pyblish.api.InstancePlugin): """A rig must have a certain hierarchy and members - Must reside within `rig_GRP` transform - controls_SEL - cache_SEL - resources_SEL (optional) """ label = "Rig Format" order = pyblish.api.ValidatorOrder hosts = ["maya"] families = ["starter.rig"] def process(self, instance): missing = list() for member in ("controls_SEL", "cache_SEL"): if member not in instance: missing.append(member) assert not missing, "\"%s\" is missing members: %s" % ( instance, ", ".join("\"" + member + "\"" for member in missing))
import pyblish.api class ValidateStarterRigFormat(pyblish.api.InstancePlugin): """A rig must have a certain hierarchy and members - Must reside within `rig_GRP` transform - out_SEL - controls_SEL - in_SEL (optional) - resources_SEL (optional) """ label = "Rig Format" order = pyblish.api.ValidatorOrder hosts = ["maya"] families = ["starter.rig"] def process(self, instance): missing = list() for member in ("controls_SEL", "out_SEL"): if member not in instance: missing.append(member) assert not missing, "\"%s\" is missing members: %s" % ( instance, ", ".join("\"" + member + "\"" for member in missing))
Update interface for rigs - in/out versus None/cache
Update interface for rigs - in/out versus None/cache
Python
mit
pyblish/pyblish-starter,pyblish/pyblish-mindbender,mindbender-studio/core,MoonShineVFX/core,getavalon/core,MoonShineVFX/core,mindbender-studio/core,getavalon/core
import pyblish.api class ValidateStarterRigFormat(pyblish.api.InstancePlugin): """A rig must have a certain hierarchy and members - Must reside within `rig_GRP` transform + - out_SEL - controls_SEL - - cache_SEL + - in_SEL (optional) - resources_SEL (optional) """ label = "Rig Format" order = pyblish.api.ValidatorOrder hosts = ["maya"] families = ["starter.rig"] def process(self, instance): missing = list() for member in ("controls_SEL", - "cache_SEL"): + "out_SEL"): if member not in instance: missing.append(member) assert not missing, "\"%s\" is missing members: %s" % ( instance, ", ".join("\"" + member + "\"" for member in missing))
Update interface for rigs - in/out versus None/cache
## Code Before: import pyblish.api class ValidateStarterRigFormat(pyblish.api.InstancePlugin): """A rig must have a certain hierarchy and members - Must reside within `rig_GRP` transform - controls_SEL - cache_SEL - resources_SEL (optional) """ label = "Rig Format" order = pyblish.api.ValidatorOrder hosts = ["maya"] families = ["starter.rig"] def process(self, instance): missing = list() for member in ("controls_SEL", "cache_SEL"): if member not in instance: missing.append(member) assert not missing, "\"%s\" is missing members: %s" % ( instance, ", ".join("\"" + member + "\"" for member in missing)) ## Instruction: Update interface for rigs - in/out versus None/cache ## Code After: import pyblish.api class ValidateStarterRigFormat(pyblish.api.InstancePlugin): """A rig must have a certain hierarchy and members - Must reside within `rig_GRP` transform - out_SEL - controls_SEL - in_SEL (optional) - resources_SEL (optional) """ label = "Rig Format" order = pyblish.api.ValidatorOrder hosts = ["maya"] families = ["starter.rig"] def process(self, instance): missing = list() for member in ("controls_SEL", "out_SEL"): if member not in instance: missing.append(member) assert not missing, "\"%s\" is missing members: %s" % ( instance, ", ".join("\"" + member + "\"" for member in missing))
... - Must reside within `rig_GRP` transform - out_SEL - controls_SEL - in_SEL (optional) - resources_SEL (optional) ... for member in ("controls_SEL", "out_SEL"): if member not in instance: ...
0be3b5bf33a3e0254297eda664c85fd249bce2fe
amostra/tests/test_jsonschema.py
amostra/tests/test_jsonschema.py
import hypothesis_jsonschema from hypothesis import HealthCheck, given, settings from hypothesis import strategies as st from amostra.utils import load_schema sample_dict = load_schema("sample.json") # Pop uuid and revision cause they are created automatically sample_dict['properties'].pop('uuid') sample_dict['properties'].pop('revision') sample_dict['required'].remove('uuid') sample_dict['required'].remove('revision') st_sample = hypothesis_jsonschema.from_schema(sample_dict) container_dict = load_schema("container.json") container_dict['properties'].pop('uuid') container_dict['properties'].pop('revision') container_dict['required'].remove('uuid') container_dict['required'].remove('revision') st_container = hypothesis_jsonschema.from_schema(container_dict) @given(samples_list=st.lists(st_sample, unique_by=lambda x: x['name'], min_size=3, max_size=5), containers_list=st.lists(st_container, unique_by=lambda x: x['name'], min_size=3, max_size=5)) @settings(max_examples=5, suppress_health_check=[HealthCheck.too_slow]) def test_new(client, samples_list, containers_list): for sample in samples_list: client.samples.new(**sample)
from operator import itemgetter import hypothesis_jsonschema from hypothesis import HealthCheck, given, settings from hypothesis import strategies as st from amostra.utils import load_schema sample_dict = load_schema("sample.json") # Pop uuid and revision cause they are created automatically sample_dict['properties'].pop('uuid') sample_dict['properties'].pop('revision') sample_dict['required'].remove('uuid') sample_dict['required'].remove('revision') st_sample = hypothesis_jsonschema.from_schema(sample_dict) container_dict = load_schema("container.json") container_dict['properties'].pop('uuid') container_dict['properties'].pop('revision') container_dict['required'].remove('uuid') container_dict['required'].remove('revision') st_container = hypothesis_jsonschema.from_schema(container_dict) @given(samples_list=st.lists(st_sample, unique_by=itemgetter('name'), min_size=3, max_size=5), containers_list=st.lists(st_container, unique_by=itemgetter('name'), min_size=3, max_size=5)) @settings(max_examples=5, suppress_health_check=[HealthCheck.too_slow]) def test_new(client, samples_list, containers_list): for sample in samples_list: client.samples.new(**sample)
Use itemgetter instead of lambda
TST: Use itemgetter instead of lambda
Python
bsd-3-clause
NSLS-II/amostra
+ from operator import itemgetter + import hypothesis_jsonschema from hypothesis import HealthCheck, given, settings from hypothesis import strategies as st from amostra.utils import load_schema sample_dict = load_schema("sample.json") # Pop uuid and revision cause they are created automatically sample_dict['properties'].pop('uuid') sample_dict['properties'].pop('revision') sample_dict['required'].remove('uuid') sample_dict['required'].remove('revision') st_sample = hypothesis_jsonschema.from_schema(sample_dict) container_dict = load_schema("container.json") container_dict['properties'].pop('uuid') container_dict['properties'].pop('revision') container_dict['required'].remove('uuid') container_dict['required'].remove('revision') st_container = hypothesis_jsonschema.from_schema(container_dict) - @given(samples_list=st.lists(st_sample, unique_by=lambda x: x['name'], min_size=3, max_size=5), + @given(samples_list=st.lists(st_sample, unique_by=itemgetter('name'), min_size=3, max_size=5), - containers_list=st.lists(st_container, unique_by=lambda x: x['name'], min_size=3, max_size=5)) + containers_list=st.lists(st_container, unique_by=itemgetter('name'), min_size=3, max_size=5)) @settings(max_examples=5, suppress_health_check=[HealthCheck.too_slow]) def test_new(client, samples_list, containers_list): for sample in samples_list: client.samples.new(**sample)
Use itemgetter instead of lambda
## Code Before: import hypothesis_jsonschema from hypothesis import HealthCheck, given, settings from hypothesis import strategies as st from amostra.utils import load_schema sample_dict = load_schema("sample.json") # Pop uuid and revision cause they are created automatically sample_dict['properties'].pop('uuid') sample_dict['properties'].pop('revision') sample_dict['required'].remove('uuid') sample_dict['required'].remove('revision') st_sample = hypothesis_jsonschema.from_schema(sample_dict) container_dict = load_schema("container.json") container_dict['properties'].pop('uuid') container_dict['properties'].pop('revision') container_dict['required'].remove('uuid') container_dict['required'].remove('revision') st_container = hypothesis_jsonschema.from_schema(container_dict) @given(samples_list=st.lists(st_sample, unique_by=lambda x: x['name'], min_size=3, max_size=5), containers_list=st.lists(st_container, unique_by=lambda x: x['name'], min_size=3, max_size=5)) @settings(max_examples=5, suppress_health_check=[HealthCheck.too_slow]) def test_new(client, samples_list, containers_list): for sample in samples_list: client.samples.new(**sample) ## Instruction: Use itemgetter instead of lambda ## Code After: from operator import itemgetter import hypothesis_jsonschema from hypothesis import HealthCheck, given, settings from hypothesis import strategies as st from amostra.utils import load_schema sample_dict = load_schema("sample.json") # Pop uuid and revision cause they are created automatically sample_dict['properties'].pop('uuid') sample_dict['properties'].pop('revision') sample_dict['required'].remove('uuid') sample_dict['required'].remove('revision') st_sample = hypothesis_jsonschema.from_schema(sample_dict) container_dict = load_schema("container.json") container_dict['properties'].pop('uuid') container_dict['properties'].pop('revision') container_dict['required'].remove('uuid') container_dict['required'].remove('revision') st_container = hypothesis_jsonschema.from_schema(container_dict) @given(samples_list=st.lists(st_sample, unique_by=itemgetter('name'), min_size=3, max_size=5), containers_list=st.lists(st_container, unique_by=itemgetter('name'), min_size=3, max_size=5)) @settings(max_examples=5, suppress_health_check=[HealthCheck.too_slow]) def test_new(client, samples_list, containers_list): for sample in samples_list: client.samples.new(**sample)
# ... existing code ... from operator import itemgetter import hypothesis_jsonschema # ... modified code ... @given(samples_list=st.lists(st_sample, unique_by=itemgetter('name'), min_size=3, max_size=5), containers_list=st.lists(st_container, unique_by=itemgetter('name'), min_size=3, max_size=5)) @settings(max_examples=5, suppress_health_check=[HealthCheck.too_slow]) # ... rest of the code ...
6740f677903c7d48748fd0a595762b8bf2c7dcb3
test_connector/components/components.py
test_connector/components/components.py
from odoo.addons.connector.components.core import Component from odoo.addons.connector.components.collection import use class BaseComponent(Component): _inherit = 'base' def test_inherit_base(self): return 'test_inherit_base' class Mapper(Component): _name = 'mapper' def test_inherit_component(self): return 'test_inherit_component' class TestMapper(Component): _name = 'test.mapper' _inherit = 'mapper' def name(self): return 'test.mapper'
from odoo.addons.connector.components.core import Component class BaseComponent(Component): _inherit = 'base' def test_inherit_base(self): return 'test_inherit_base' class Mapper(Component): _name = 'mapper' def test_inherit_component(self): return 'test_inherit_component' class TestMapper(Component): _name = 'test.mapper' _inherit = 'mapper' def name(self): return 'test.mapper'
Improve on the collections, work, ...
Improve on the collections, work, ...
Python
agpl-3.0
OCA/connector,OCA/connector
from odoo.addons.connector.components.core import Component - from odoo.addons.connector.components.collection import use class BaseComponent(Component): _inherit = 'base' def test_inherit_base(self): return 'test_inherit_base' class Mapper(Component): _name = 'mapper' def test_inherit_component(self): return 'test_inherit_component' class TestMapper(Component): _name = 'test.mapper' _inherit = 'mapper' def name(self): return 'test.mapper'
Improve on the collections, work, ...
## Code Before: from odoo.addons.connector.components.core import Component from odoo.addons.connector.components.collection import use class BaseComponent(Component): _inherit = 'base' def test_inherit_base(self): return 'test_inherit_base' class Mapper(Component): _name = 'mapper' def test_inherit_component(self): return 'test_inherit_component' class TestMapper(Component): _name = 'test.mapper' _inherit = 'mapper' def name(self): return 'test.mapper' ## Instruction: Improve on the collections, work, ... ## Code After: from odoo.addons.connector.components.core import Component class BaseComponent(Component): _inherit = 'base' def test_inherit_base(self): return 'test_inherit_base' class Mapper(Component): _name = 'mapper' def test_inherit_component(self): return 'test_inherit_component' class TestMapper(Component): _name = 'test.mapper' _inherit = 'mapper' def name(self): return 'test.mapper'
// ... existing code ... from odoo.addons.connector.components.core import Component // ... rest of the code ...
966c8e549e1cb78c64ad2f359162bc5a2171a732
fabfile.py
fabfile.py
from fabric.api import cd, env, local, lcd, run PUPPET_MASTER_IP = '192.168.33.10' def puppet(): env.hosts = [ 'vagrant@' + PUPPET_MASTER_IP + ':22', ] env.passwords = { 'vagrant@' + PUPPET_MASTER_IP + ':22': 'vagrant' } def test(): with lcd('puppet/modules'): with lcd('nginx'): local('rspec') def deploy(): puppet() test() run('rm -rf puppet-untitled-2016') run('git clone https://github.com/zkan/puppet-untitled-2016.git') run('sudo rm -rf /etc/puppet/manifests') run('sudo ln -sf /home/vagrant/puppet-untitled-2016/puppet/manifests /etc/puppet/manifests') run('sudo rm -rf /etc/puppet/modules') run('sudo ln -sf /home/vagrant/puppet-untitled-2016/puppet/modules /etc/puppet/modules')
from fabric.api import cd, env, local, lcd, run PUPPET_MASTER_IP = '192.168.33.10' def puppet(): env.hosts = [ 'vagrant@' + PUPPET_MASTER_IP + ':22', ] env.passwords = { 'vagrant@' + PUPPET_MASTER_IP + ':22': 'vagrant' } def test(): with lcd('puppet/modules'): with lcd('nginx'): local('rspec') def push(): with lcd('puppet'): local('git add .') local('git push origin master') def deploy(): puppet() test() run('rm -rf puppet-untitled-2016') run('git clone https://github.com/zkan/puppet-untitled-2016.git') run('sudo rm -rf /etc/puppet/manifests') run('sudo ln -sf /home/vagrant/puppet-untitled-2016/puppet/manifests /etc/puppet/manifests') run('sudo rm -rf /etc/puppet/modules') run('sudo ln -sf /home/vagrant/puppet-untitled-2016/puppet/modules /etc/puppet/modules')
Add push task (but not use it yet)
Add push task (but not use it yet)
Python
mit
zkan/puppet-untitled-2016,zkan/puppet-untitled-2016
from fabric.api import cd, env, local, lcd, run PUPPET_MASTER_IP = '192.168.33.10' def puppet(): env.hosts = [ 'vagrant@' + PUPPET_MASTER_IP + ':22', ] env.passwords = { 'vagrant@' + PUPPET_MASTER_IP + ':22': 'vagrant' } def test(): with lcd('puppet/modules'): with lcd('nginx'): local('rspec') + def push(): + with lcd('puppet'): + local('git add .') + local('git push origin master') + + def deploy(): puppet() test() run('rm -rf puppet-untitled-2016') run('git clone https://github.com/zkan/puppet-untitled-2016.git') run('sudo rm -rf /etc/puppet/manifests') run('sudo ln -sf /home/vagrant/puppet-untitled-2016/puppet/manifests /etc/puppet/manifests') run('sudo rm -rf /etc/puppet/modules') run('sudo ln -sf /home/vagrant/puppet-untitled-2016/puppet/modules /etc/puppet/modules')
Add push task (but not use it yet)
## Code Before: from fabric.api import cd, env, local, lcd, run PUPPET_MASTER_IP = '192.168.33.10' def puppet(): env.hosts = [ 'vagrant@' + PUPPET_MASTER_IP + ':22', ] env.passwords = { 'vagrant@' + PUPPET_MASTER_IP + ':22': 'vagrant' } def test(): with lcd('puppet/modules'): with lcd('nginx'): local('rspec') def deploy(): puppet() test() run('rm -rf puppet-untitled-2016') run('git clone https://github.com/zkan/puppet-untitled-2016.git') run('sudo rm -rf /etc/puppet/manifests') run('sudo ln -sf /home/vagrant/puppet-untitled-2016/puppet/manifests /etc/puppet/manifests') run('sudo rm -rf /etc/puppet/modules') run('sudo ln -sf /home/vagrant/puppet-untitled-2016/puppet/modules /etc/puppet/modules') ## Instruction: Add push task (but not use it yet) ## Code After: from fabric.api import cd, env, local, lcd, run PUPPET_MASTER_IP = '192.168.33.10' def puppet(): env.hosts = [ 'vagrant@' + PUPPET_MASTER_IP + ':22', ] env.passwords = { 'vagrant@' + PUPPET_MASTER_IP + ':22': 'vagrant' } def test(): with lcd('puppet/modules'): with lcd('nginx'): local('rspec') def push(): with lcd('puppet'): local('git add .') local('git push origin master') def deploy(): puppet() test() run('rm -rf puppet-untitled-2016') run('git clone https://github.com/zkan/puppet-untitled-2016.git') run('sudo rm -rf /etc/puppet/manifests') run('sudo ln -sf /home/vagrant/puppet-untitled-2016/puppet/manifests /etc/puppet/manifests') run('sudo rm -rf /etc/puppet/modules') run('sudo ln -sf /home/vagrant/puppet-untitled-2016/puppet/modules /etc/puppet/modules')
// ... existing code ... def push(): with lcd('puppet'): local('git add .') local('git push origin master') def deploy(): // ... rest of the code ...
3d5093b46763acca9e3b3309073f73a7ca8daf73
src/clients/lib/python/xmmsclient/consts.py
src/clients/lib/python/xmmsclient/consts.py
from xmmsapi import VALUE_TYPE_NONE from xmmsapi import VALUE_TYPE_ERROR from xmmsapi import VALUE_TYPE_UINT32 from xmmsapi import VALUE_TYPE_INT32 from xmmsapi import VALUE_TYPE_STRING from xmmsapi import VALUE_TYPE_COLL from xmmsapi import VALUE_TYPE_BIN from xmmsapi import VALUE_TYPE_LIST from xmmsapi import VALUE_TYPE_DICT from xmmsapi import PLAYBACK_STATUS_STOP from xmmsapi import PLAYBACK_STATUS_PLAY from xmmsapi import PLAYBACK_STATUS_PAUSE from xmmsapi import PLAYLIST_CHANGED_ADD from xmmsapi import PLAYLIST_CHANGED_INSERT from xmmsapi import PLAYLIST_CHANGED_SHUFFLE from xmmsapi import PLAYLIST_CHANGED_REMOVE from xmmsapi import PLAYLIST_CHANGED_CLEAR from xmmsapi import PLAYLIST_CHANGED_MOVE from xmmsapi import PLAYLIST_CHANGED_SORT from xmmsapi import PLAYLIST_CHANGED_UPDATE from xmmsapi import PLUGIN_TYPE_ALL from xmmsapi import PLUGIN_TYPE_XFORM from xmmsapi import PLUGIN_TYPE_OUTPUT from xmmsapi import COLLECTION_CHANGED_ADD from xmmsapi import COLLECTION_CHANGED_UPDATE from xmmsapi import COLLECTION_CHANGED_RENAME from xmmsapi import COLLECTION_CHANGED_REMOVE
from xmmsapi import VALUE_TYPE_NONE from xmmsapi import VALUE_TYPE_ERROR from xmmsapi import VALUE_TYPE_INT32 from xmmsapi import VALUE_TYPE_STRING from xmmsapi import VALUE_TYPE_COLL from xmmsapi import VALUE_TYPE_BIN from xmmsapi import VALUE_TYPE_LIST from xmmsapi import VALUE_TYPE_DICT from xmmsapi import PLAYBACK_STATUS_STOP from xmmsapi import PLAYBACK_STATUS_PLAY from xmmsapi import PLAYBACK_STATUS_PAUSE from xmmsapi import PLAYLIST_CHANGED_ADD from xmmsapi import PLAYLIST_CHANGED_INSERT from xmmsapi import PLAYLIST_CHANGED_SHUFFLE from xmmsapi import PLAYLIST_CHANGED_REMOVE from xmmsapi import PLAYLIST_CHANGED_CLEAR from xmmsapi import PLAYLIST_CHANGED_MOVE from xmmsapi import PLAYLIST_CHANGED_SORT from xmmsapi import PLAYLIST_CHANGED_UPDATE from xmmsapi import PLUGIN_TYPE_ALL from xmmsapi import PLUGIN_TYPE_XFORM from xmmsapi import PLUGIN_TYPE_OUTPUT from xmmsapi import COLLECTION_CHANGED_ADD from xmmsapi import COLLECTION_CHANGED_UPDATE from xmmsapi import COLLECTION_CHANGED_RENAME from xmmsapi import COLLECTION_CHANGED_REMOVE
Remove import of nonexistant UINT32 type in python bindings
BUG(2151): Remove import of nonexistant UINT32 type in python bindings
Python
lgpl-2.1
mantaraya36/xmms2-mantaraya36,theeternalsw0rd/xmms2,oneman/xmms2-oneman-old,mantaraya36/xmms2-mantaraya36,xmms2/xmms2-stable,theefer/xmms2,theeternalsw0rd/xmms2,six600110/xmms2,chrippa/xmms2,oneman/xmms2-oneman,chrippa/xmms2,xmms2/xmms2-stable,xmms2/xmms2-stable,theeternalsw0rd/xmms2,mantaraya36/xmms2-mantaraya36,theefer/xmms2,krad-radio/xmms2-krad,dreamerc/xmms2,theeternalsw0rd/xmms2,krad-radio/xmms2-krad,chrippa/xmms2,six600110/xmms2,xmms2/xmms2-stable,theefer/xmms2,mantaraya36/xmms2-mantaraya36,krad-radio/xmms2-krad,oneman/xmms2-oneman,oneman/xmms2-oneman,dreamerc/xmms2,xmms2/xmms2-stable,krad-radio/xmms2-krad,theefer/xmms2,mantaraya36/xmms2-mantaraya36,xmms2/xmms2-stable,dreamerc/xmms2,dreamerc/xmms2,six600110/xmms2,oneman/xmms2-oneman-old,theefer/xmms2,oneman/xmms2-oneman,six600110/xmms2,krad-radio/xmms2-krad,krad-radio/xmms2-krad,chrippa/xmms2,theeternalsw0rd/xmms2,oneman/xmms2-oneman,oneman/xmms2-oneman,dreamerc/xmms2,chrippa/xmms2,oneman/xmms2-oneman-old,mantaraya36/xmms2-mantaraya36,theefer/xmms2,oneman/xmms2-oneman,six600110/xmms2,chrippa/xmms2,oneman/xmms2-oneman-old,theefer/xmms2,six600110/xmms2,oneman/xmms2-oneman-old,theeternalsw0rd/xmms2,mantaraya36/xmms2-mantaraya36
from xmmsapi import VALUE_TYPE_NONE from xmmsapi import VALUE_TYPE_ERROR - from xmmsapi import VALUE_TYPE_UINT32 from xmmsapi import VALUE_TYPE_INT32 from xmmsapi import VALUE_TYPE_STRING from xmmsapi import VALUE_TYPE_COLL from xmmsapi import VALUE_TYPE_BIN from xmmsapi import VALUE_TYPE_LIST from xmmsapi import VALUE_TYPE_DICT from xmmsapi import PLAYBACK_STATUS_STOP from xmmsapi import PLAYBACK_STATUS_PLAY from xmmsapi import PLAYBACK_STATUS_PAUSE from xmmsapi import PLAYLIST_CHANGED_ADD from xmmsapi import PLAYLIST_CHANGED_INSERT from xmmsapi import PLAYLIST_CHANGED_SHUFFLE from xmmsapi import PLAYLIST_CHANGED_REMOVE from xmmsapi import PLAYLIST_CHANGED_CLEAR from xmmsapi import PLAYLIST_CHANGED_MOVE from xmmsapi import PLAYLIST_CHANGED_SORT from xmmsapi import PLAYLIST_CHANGED_UPDATE from xmmsapi import PLUGIN_TYPE_ALL from xmmsapi import PLUGIN_TYPE_XFORM from xmmsapi import PLUGIN_TYPE_OUTPUT from xmmsapi import COLLECTION_CHANGED_ADD from xmmsapi import COLLECTION_CHANGED_UPDATE from xmmsapi import COLLECTION_CHANGED_RENAME from xmmsapi import COLLECTION_CHANGED_REMOVE
Remove import of nonexistant UINT32 type in python bindings
## Code Before: from xmmsapi import VALUE_TYPE_NONE from xmmsapi import VALUE_TYPE_ERROR from xmmsapi import VALUE_TYPE_UINT32 from xmmsapi import VALUE_TYPE_INT32 from xmmsapi import VALUE_TYPE_STRING from xmmsapi import VALUE_TYPE_COLL from xmmsapi import VALUE_TYPE_BIN from xmmsapi import VALUE_TYPE_LIST from xmmsapi import VALUE_TYPE_DICT from xmmsapi import PLAYBACK_STATUS_STOP from xmmsapi import PLAYBACK_STATUS_PLAY from xmmsapi import PLAYBACK_STATUS_PAUSE from xmmsapi import PLAYLIST_CHANGED_ADD from xmmsapi import PLAYLIST_CHANGED_INSERT from xmmsapi import PLAYLIST_CHANGED_SHUFFLE from xmmsapi import PLAYLIST_CHANGED_REMOVE from xmmsapi import PLAYLIST_CHANGED_CLEAR from xmmsapi import PLAYLIST_CHANGED_MOVE from xmmsapi import PLAYLIST_CHANGED_SORT from xmmsapi import PLAYLIST_CHANGED_UPDATE from xmmsapi import PLUGIN_TYPE_ALL from xmmsapi import PLUGIN_TYPE_XFORM from xmmsapi import PLUGIN_TYPE_OUTPUT from xmmsapi import COLLECTION_CHANGED_ADD from xmmsapi import COLLECTION_CHANGED_UPDATE from xmmsapi import COLLECTION_CHANGED_RENAME from xmmsapi import COLLECTION_CHANGED_REMOVE ## Instruction: Remove import of nonexistant UINT32 type in python bindings ## Code After: from xmmsapi import VALUE_TYPE_NONE from xmmsapi import VALUE_TYPE_ERROR from xmmsapi import VALUE_TYPE_INT32 from xmmsapi import VALUE_TYPE_STRING from xmmsapi import VALUE_TYPE_COLL from xmmsapi import VALUE_TYPE_BIN from xmmsapi import VALUE_TYPE_LIST from xmmsapi import VALUE_TYPE_DICT from xmmsapi import PLAYBACK_STATUS_STOP from xmmsapi import PLAYBACK_STATUS_PLAY from xmmsapi import PLAYBACK_STATUS_PAUSE from xmmsapi import PLAYLIST_CHANGED_ADD from xmmsapi import PLAYLIST_CHANGED_INSERT from xmmsapi import PLAYLIST_CHANGED_SHUFFLE from xmmsapi import PLAYLIST_CHANGED_REMOVE from xmmsapi import PLAYLIST_CHANGED_CLEAR from xmmsapi import PLAYLIST_CHANGED_MOVE from xmmsapi import PLAYLIST_CHANGED_SORT from xmmsapi import PLAYLIST_CHANGED_UPDATE from xmmsapi import PLUGIN_TYPE_ALL from xmmsapi import PLUGIN_TYPE_XFORM from xmmsapi import PLUGIN_TYPE_OUTPUT from xmmsapi import COLLECTION_CHANGED_ADD from xmmsapi import COLLECTION_CHANGED_UPDATE from xmmsapi import COLLECTION_CHANGED_RENAME from xmmsapi import COLLECTION_CHANGED_REMOVE
... from xmmsapi import VALUE_TYPE_ERROR from xmmsapi import VALUE_TYPE_INT32 ...
feddcfd9153da81777c25571f35ee3c97e655c64
generate_migrations.py
generate_migrations.py
import sys from argparse import ArgumentParser from os.path import abspath from os.path import dirname # Modify the path so that our djoauth2 app is in it. parent_dir = dirname(abspath(__file__)) sys.path.insert(0, parent_dir) # Load Django-related settings; necessary for tests to run and for Django # imports to work. import local_settings # Now, imports from Django will work properly without raising errors related to # missing or badly-configured settings. from django.core import management def generate_migrations(initial): management.call_command('syncdb', interactive=False) if initial: management.call_command('schemamigration', 'djoauth2', initial=True) else: management.call_command('schemamigration', 'djoauth2', auto=True) def test_migrations(): management.call_command('syncdb', interactive=False) management.call_command('migrate', 'djoauth2') if __name__ == '__main__': parser = ArgumentParser() parser.add_argument('--initial-migration', action='store_true', default=False, dest='initial') parser.add_argument('--test-migrations', action='store_true', default=False, dest='test_migrations') args = parser.parse_args() if args.test_migrations: test_migrations() else: generate_migrations(args.initial)
import sys from argparse import ArgumentParser from os.path import abspath from os.path import dirname # Modify the path so that our djoauth2 app is in it. parent_dir = dirname(abspath(__file__)) sys.path.insert(0, parent_dir) # Load Django-related settings; necessary for tests to run and for Django # imports to work. import local_settings # Now, imports from Django will work properly without raising errors related to # missing or badly-configured settings. from django.core import management from refactor_migrations import refactor def generate_migrations(initial): management.call_command('syncdb', interactive=False) if initial: management.call_command('schemamigration', 'djoauth2', initial=True) else: management.call_command('schemamigration', 'djoauth2', auto=True) refactor('./djoauth2/migrations/') def test_migrations(): management.call_command('syncdb', interactive=False) management.call_command('migrate', 'djoauth2') if __name__ == '__main__': parser = ArgumentParser() parser.add_argument('--initial-migration', action='store_true', default=False, dest='initial') parser.add_argument('--test-migrations', action='store_true', default=False, dest='test_migrations') args = parser.parse_args() if args.test_migrations: test_migrations() else: generate_migrations(args.initial)
Refactor migrations after generating to ensure custom user model compatibility.
Refactor migrations after generating to ensure custom user model compatibility.
Python
mit
vden/djoauth2-ng,Locu/djoauth2,seler/djoauth2,vden/djoauth2-ng,seler/djoauth2,Locu/djoauth2
import sys from argparse import ArgumentParser from os.path import abspath from os.path import dirname # Modify the path so that our djoauth2 app is in it. parent_dir = dirname(abspath(__file__)) sys.path.insert(0, parent_dir) # Load Django-related settings; necessary for tests to run and for Django # imports to work. import local_settings # Now, imports from Django will work properly without raising errors related to # missing or badly-configured settings. from django.core import management + from refactor_migrations import refactor + def generate_migrations(initial): management.call_command('syncdb', interactive=False) if initial: management.call_command('schemamigration', 'djoauth2', initial=True) else: management.call_command('schemamigration', 'djoauth2', auto=True) + refactor('./djoauth2/migrations/') + def test_migrations(): management.call_command('syncdb', interactive=False) management.call_command('migrate', 'djoauth2') if __name__ == '__main__': parser = ArgumentParser() parser.add_argument('--initial-migration', action='store_true', default=False, dest='initial') parser.add_argument('--test-migrations', action='store_true', default=False, dest='test_migrations') args = parser.parse_args() if args.test_migrations: test_migrations() else: generate_migrations(args.initial)
Refactor migrations after generating to ensure custom user model compatibility.
## Code Before: import sys from argparse import ArgumentParser from os.path import abspath from os.path import dirname # Modify the path so that our djoauth2 app is in it. parent_dir = dirname(abspath(__file__)) sys.path.insert(0, parent_dir) # Load Django-related settings; necessary for tests to run and for Django # imports to work. import local_settings # Now, imports from Django will work properly without raising errors related to # missing or badly-configured settings. from django.core import management def generate_migrations(initial): management.call_command('syncdb', interactive=False) if initial: management.call_command('schemamigration', 'djoauth2', initial=True) else: management.call_command('schemamigration', 'djoauth2', auto=True) def test_migrations(): management.call_command('syncdb', interactive=False) management.call_command('migrate', 'djoauth2') if __name__ == '__main__': parser = ArgumentParser() parser.add_argument('--initial-migration', action='store_true', default=False, dest='initial') parser.add_argument('--test-migrations', action='store_true', default=False, dest='test_migrations') args = parser.parse_args() if args.test_migrations: test_migrations() else: generate_migrations(args.initial) ## Instruction: Refactor migrations after generating to ensure custom user model compatibility. ## Code After: import sys from argparse import ArgumentParser from os.path import abspath from os.path import dirname # Modify the path so that our djoauth2 app is in it. parent_dir = dirname(abspath(__file__)) sys.path.insert(0, parent_dir) # Load Django-related settings; necessary for tests to run and for Django # imports to work. import local_settings # Now, imports from Django will work properly without raising errors related to # missing or badly-configured settings. from django.core import management from refactor_migrations import refactor def generate_migrations(initial): management.call_command('syncdb', interactive=False) if initial: management.call_command('schemamigration', 'djoauth2', initial=True) else: management.call_command('schemamigration', 'djoauth2', auto=True) refactor('./djoauth2/migrations/') def test_migrations(): management.call_command('syncdb', interactive=False) management.call_command('migrate', 'djoauth2') if __name__ == '__main__': parser = ArgumentParser() parser.add_argument('--initial-migration', action='store_true', default=False, dest='initial') parser.add_argument('--test-migrations', action='store_true', default=False, dest='test_migrations') args = parser.parse_args() if args.test_migrations: test_migrations() else: generate_migrations(args.initial)
# ... existing code ... from refactor_migrations import refactor # ... modified code ... management.call_command('schemamigration', 'djoauth2', auto=True) refactor('./djoauth2/migrations/') # ... rest of the code ...
d66a412efad62d47e7df8d2ff4922be4c268a93e
hunittest/utils.py
hunittest/utils.py
import os import re from enum import Enum from contextlib import contextmanager def pyname_join(seq): return ".".join(seq) def is_pkgdir(dirpath): return os.path.isdir(dirpath) \ and os.path.isfile(os.path.join(dirpath, "__init__.py")) def mod_split(modname): mo = re.match(r"^(.+)\.(.*)$", modname) if not mo: raise ValueError("invalid python path identifier") return (mo.group(1), mo.group(2)) def is_empty_generator(generator): try: next(generator) except StopIteration: return True else: return False class AutoEnum(Enum): def __new__(cls): value = len(cls.__members__) + 1 obj = object.__new__(cls) obj._value_ = value return obj def mkdir_p(path): try: os.makedirs(path) except FileExistsError: pass @contextmanager def protect_cwd(dirpath=None): saved_cwd = os.getcwd() if dirpath is not None: os.chdir(dirpath) try: yield finally: os.chdir(saved_cwd) def safe_getcwd(): try: return os.getcwd() except FileNotFoundError: return None
import os import re from enum import Enum from contextlib import contextmanager import unittest def pyname_join(seq): return ".".join(seq) def is_pkgdir(dirpath): return os.path.isdir(dirpath) \ and os.path.isfile(os.path.join(dirpath, "__init__.py")) def mod_split(modname): mo = re.match(r"^(.+)\.(.*)$", modname) if not mo: raise ValueError("invalid python path identifier") return (mo.group(1), mo.group(2)) def is_empty_generator(generator): try: next(generator) except StopIteration: return True else: return False class AutoEnum(Enum): def __new__(cls): value = len(cls.__members__) + 1 obj = object.__new__(cls) obj._value_ = value return obj def mkdir_p(path): try: os.makedirs(path) except FileExistsError: pass @contextmanager def protect_cwd(dirpath=None): saved_cwd = os.getcwd() if dirpath is not None: os.chdir(dirpath) try: yield finally: os.chdir(saved_cwd) def safe_getcwd(): try: return os.getcwd() except FileNotFoundError: return None def load_single_test_case(test_name): test_suite = list(unittest.defaultTestLoader.loadTestsFromName(test_name)) assert len(test_suite) == 1 return test_suite[0]
Add helper to load a single test case.
Add helper to load a single test case.
Python
bsd-2-clause
nicolasdespres/hunittest
import os import re from enum import Enum from contextlib import contextmanager + import unittest def pyname_join(seq): return ".".join(seq) def is_pkgdir(dirpath): return os.path.isdir(dirpath) \ and os.path.isfile(os.path.join(dirpath, "__init__.py")) def mod_split(modname): mo = re.match(r"^(.+)\.(.*)$", modname) if not mo: raise ValueError("invalid python path identifier") return (mo.group(1), mo.group(2)) def is_empty_generator(generator): try: next(generator) except StopIteration: return True else: return False class AutoEnum(Enum): def __new__(cls): value = len(cls.__members__) + 1 obj = object.__new__(cls) obj._value_ = value return obj def mkdir_p(path): try: os.makedirs(path) except FileExistsError: pass @contextmanager def protect_cwd(dirpath=None): saved_cwd = os.getcwd() if dirpath is not None: os.chdir(dirpath) try: yield finally: os.chdir(saved_cwd) def safe_getcwd(): try: return os.getcwd() except FileNotFoundError: return None + def load_single_test_case(test_name): + test_suite = list(unittest.defaultTestLoader.loadTestsFromName(test_name)) + assert len(test_suite) == 1 + return test_suite[0] +
Add helper to load a single test case.
## Code Before: import os import re from enum import Enum from contextlib import contextmanager def pyname_join(seq): return ".".join(seq) def is_pkgdir(dirpath): return os.path.isdir(dirpath) \ and os.path.isfile(os.path.join(dirpath, "__init__.py")) def mod_split(modname): mo = re.match(r"^(.+)\.(.*)$", modname) if not mo: raise ValueError("invalid python path identifier") return (mo.group(1), mo.group(2)) def is_empty_generator(generator): try: next(generator) except StopIteration: return True else: return False class AutoEnum(Enum): def __new__(cls): value = len(cls.__members__) + 1 obj = object.__new__(cls) obj._value_ = value return obj def mkdir_p(path): try: os.makedirs(path) except FileExistsError: pass @contextmanager def protect_cwd(dirpath=None): saved_cwd = os.getcwd() if dirpath is not None: os.chdir(dirpath) try: yield finally: os.chdir(saved_cwd) def safe_getcwd(): try: return os.getcwd() except FileNotFoundError: return None ## Instruction: Add helper to load a single test case. ## Code After: import os import re from enum import Enum from contextlib import contextmanager import unittest def pyname_join(seq): return ".".join(seq) def is_pkgdir(dirpath): return os.path.isdir(dirpath) \ and os.path.isfile(os.path.join(dirpath, "__init__.py")) def mod_split(modname): mo = re.match(r"^(.+)\.(.*)$", modname) if not mo: raise ValueError("invalid python path identifier") return (mo.group(1), mo.group(2)) def is_empty_generator(generator): try: next(generator) except StopIteration: return True else: return False class AutoEnum(Enum): def __new__(cls): value = len(cls.__members__) + 1 obj = object.__new__(cls) obj._value_ = value return obj def mkdir_p(path): try: os.makedirs(path) except FileExistsError: pass @contextmanager def protect_cwd(dirpath=None): saved_cwd = os.getcwd() if dirpath is not None: os.chdir(dirpath) try: yield finally: os.chdir(saved_cwd) def safe_getcwd(): try: return os.getcwd() except FileNotFoundError: return None def load_single_test_case(test_name): test_suite = list(unittest.defaultTestLoader.loadTestsFromName(test_name)) assert len(test_suite) == 1 return test_suite[0]
// ... existing code ... from contextlib import contextmanager import unittest // ... modified code ... return None def load_single_test_case(test_name): test_suite = list(unittest.defaultTestLoader.loadTestsFromName(test_name)) assert len(test_suite) == 1 return test_suite[0] // ... rest of the code ...
26672e83ab1bd1a932d275dfd244fe20749e3b1e
tripleo_common/utils/safe_import.py
tripleo_common/utils/safe_import.py
import eventlet from eventlet.green import subprocess # Due to an eventlet issue subprocess is not being correctly patched # on git module so it has to be done manually git = eventlet.import_patched('git', ('subprocess', subprocess)) Repo = git.Repo # git.refs is lazy loaded when there's a new commit, this needs to be # patched as well. eventlet.import_patched('git.refs')
from eventlet.green import subprocess import eventlet.patcher as patcher # Due to an eventlet issue subprocess is not being correctly patched # on git.refs patcher.inject('git.refs', None, ('subprocess', subprocess), ) # this has to be loaded after the inject. import git # noqa: E402 Repo = git.Repo
Make gitpython and eventlet work with eventlet 0.25.1
Make gitpython and eventlet work with eventlet 0.25.1 Version 0.25 is having a bad interaction with python git. that is due to the way that eventlet unloads some modules now. Changed to use the inject method that supports what we need intead of the imported_patched that was having the problem Change-Id: I79894d4f711c64f536593fffcb6959df97c38838 Closes-bug: #1845181
Python
apache-2.0
openstack/tripleo-common,openstack/tripleo-common
- import eventlet from eventlet.green import subprocess + import eventlet.patcher as patcher # Due to an eventlet issue subprocess is not being correctly patched - # on git module so it has to be done manually + # on git.refs + patcher.inject('git.refs', None, ('subprocess', subprocess), ) - git = eventlet.import_patched('git', ('subprocess', subprocess)) + # this has to be loaded after the inject. + + import git # noqa: E402 + Repo = git.Repo - # git.refs is lazy loaded when there's a new commit, this needs to be - # patched as well. - eventlet.import_patched('git.refs') -
Make gitpython and eventlet work with eventlet 0.25.1
## Code Before: import eventlet from eventlet.green import subprocess # Due to an eventlet issue subprocess is not being correctly patched # on git module so it has to be done manually git = eventlet.import_patched('git', ('subprocess', subprocess)) Repo = git.Repo # git.refs is lazy loaded when there's a new commit, this needs to be # patched as well. eventlet.import_patched('git.refs') ## Instruction: Make gitpython and eventlet work with eventlet 0.25.1 ## Code After: from eventlet.green import subprocess import eventlet.patcher as patcher # Due to an eventlet issue subprocess is not being correctly patched # on git.refs patcher.inject('git.refs', None, ('subprocess', subprocess), ) # this has to be loaded after the inject. import git # noqa: E402 Repo = git.Repo
... from eventlet.green import subprocess import eventlet.patcher as patcher ... # Due to an eventlet issue subprocess is not being correctly patched # on git.refs patcher.inject('git.refs', None, ('subprocess', subprocess), ) # this has to be loaded after the inject. import git # noqa: E402 Repo = git.Repo ...
b1aac6a0b29a6ed46b77aab37ff52c765a280ec6
ikalog/utils/matcher.py
ikalog/utils/matcher.py
from ikalog.utils.image_filters import * from ikalog.utils.ikamatcher1 import IkaMatcher1 as IkaMatcher
from ikalog.utils.image_filters import * from ikalog.utils.ikamatcher1 import IkaMatcher1 as IkaMatcher #from ikalog.utils.ikamatcher2.matcher import IkaMatcher2 as IkaMatcher
Switch to IkaMatcher2 (Numpy_8bit_fast); 10% faster in overall performance
utils: Switch to IkaMatcher2 (Numpy_8bit_fast); 10% faster in overall performance Signed-off-by: Takeshi HASEGAWA <[email protected]>
Python
apache-2.0
deathmetalland/IkaLog,hasegaw/IkaLog,deathmetalland/IkaLog,hasegaw/IkaLog,hasegaw/IkaLog,deathmetalland/IkaLog
from ikalog.utils.image_filters import * from ikalog.utils.ikamatcher1 import IkaMatcher1 as IkaMatcher + #from ikalog.utils.ikamatcher2.matcher import IkaMatcher2 as IkaMatcher
Switch to IkaMatcher2 (Numpy_8bit_fast); 10% faster in overall performance
## Code Before: from ikalog.utils.image_filters import * from ikalog.utils.ikamatcher1 import IkaMatcher1 as IkaMatcher ## Instruction: Switch to IkaMatcher2 (Numpy_8bit_fast); 10% faster in overall performance ## Code After: from ikalog.utils.image_filters import * from ikalog.utils.ikamatcher1 import IkaMatcher1 as IkaMatcher #from ikalog.utils.ikamatcher2.matcher import IkaMatcher2 as IkaMatcher
// ... existing code ... from ikalog.utils.ikamatcher1 import IkaMatcher1 as IkaMatcher #from ikalog.utils.ikamatcher2.matcher import IkaMatcher2 as IkaMatcher // ... rest of the code ...
3f848be239d5fc4ae18d598250e90217b86e8fcf
pywikibot/_wbtypes.py
pywikibot/_wbtypes.py
"""Wikibase data type classes.""" # # (C) Pywikibot team, 2013-2015 # # Distributed under the terms of the MIT license. # from __future__ import absolute_import, unicode_literals __version__ = '$Id$' # import json from pywikibot.tools import StringTypes class WbRepresentation(object): """Abstract class for Wikibase representations.""" def __init__(self): """Constructor.""" raise NotImplementedError def toWikibase(self): """Convert representation to JSON for the Wikibase API.""" raise NotImplementedError @classmethod def fromWikibase(cls, json): """Create a representation object based on JSON from Wikibase API.""" raise NotImplementedError def __str__(self): return json.dumps(self.toWikibase(), indent=4, sort_keys=True, separators=(',', ': ')) def __repr__(self): assert isinstance(self._items, tuple) assert all(isinstance(item, StringTypes) for item in self._items) values = ((attr, getattr(self, attr)) for attr in self._items) attrs = ', '.join('{0}={1}'.format(attr, value) for attr, value in values) return '{0}({1})'.format(self.__class__.__name__, attrs) def __eq__(self, other): return self.__dict__ == other.__dict__
"""Wikibase data type classes.""" # # (C) Pywikibot team, 2013-2015 # # Distributed under the terms of the MIT license. # from __future__ import absolute_import, unicode_literals __version__ = '$Id$' # import json from pywikibot.tools import StringTypes class WbRepresentation(object): """Abstract class for Wikibase representations.""" def __init__(self): """Constructor.""" raise NotImplementedError def toWikibase(self): """Convert representation to JSON for the Wikibase API.""" raise NotImplementedError @classmethod def fromWikibase(cls, json): """Create a representation object based on JSON from Wikibase API.""" raise NotImplementedError def __str__(self): return json.dumps(self.toWikibase(), indent=4, sort_keys=True, separators=(',', ': ')) def __repr__(self): assert isinstance(self._items, tuple) assert all(isinstance(item, StringTypes) for item in self._items) values = ((attr, getattr(self, attr)) for attr in self._items) attrs = ', '.join('{0}={1}'.format(attr, value) for attr, value in values) return '{0}({1})'.format(self.__class__.__name__, attrs) def __eq__(self, other): return self.__dict__ == other.__dict__ def __ne__(self, other): return not self.__eq__(other)
Add missing not-equal comparison for wbtypes
Add missing not-equal comparison for wbtypes Bug: T158848 Change-Id: Ib6e992b7ed1c5b4b8feac205758bdbaebda2b09c
Python
mit
hasteur/g13bot_tools_new,magul/pywikibot-core,jayvdb/pywikibot-core,Darkdadaah/pywikibot-core,happy5214/pywikibot-core,hasteur/g13bot_tools_new,magul/pywikibot-core,happy5214/pywikibot-core,wikimedia/pywikibot-core,npdoty/pywikibot,wikimedia/pywikibot-core,jayvdb/pywikibot-core,npdoty/pywikibot,Darkdadaah/pywikibot-core,PersianWikipedia/pywikibot-core,hasteur/g13bot_tools_new
"""Wikibase data type classes.""" # # (C) Pywikibot team, 2013-2015 # # Distributed under the terms of the MIT license. # from __future__ import absolute_import, unicode_literals __version__ = '$Id$' # import json from pywikibot.tools import StringTypes class WbRepresentation(object): """Abstract class for Wikibase representations.""" def __init__(self): """Constructor.""" raise NotImplementedError def toWikibase(self): """Convert representation to JSON for the Wikibase API.""" raise NotImplementedError @classmethod def fromWikibase(cls, json): """Create a representation object based on JSON from Wikibase API.""" raise NotImplementedError def __str__(self): return json.dumps(self.toWikibase(), indent=4, sort_keys=True, separators=(',', ': ')) def __repr__(self): assert isinstance(self._items, tuple) assert all(isinstance(item, StringTypes) for item in self._items) values = ((attr, getattr(self, attr)) for attr in self._items) attrs = ', '.join('{0}={1}'.format(attr, value) for attr, value in values) return '{0}({1})'.format(self.__class__.__name__, attrs) def __eq__(self, other): return self.__dict__ == other.__dict__ + def __ne__(self, other): + return not self.__eq__(other) +
Add missing not-equal comparison for wbtypes
## Code Before: """Wikibase data type classes.""" # # (C) Pywikibot team, 2013-2015 # # Distributed under the terms of the MIT license. # from __future__ import absolute_import, unicode_literals __version__ = '$Id$' # import json from pywikibot.tools import StringTypes class WbRepresentation(object): """Abstract class for Wikibase representations.""" def __init__(self): """Constructor.""" raise NotImplementedError def toWikibase(self): """Convert representation to JSON for the Wikibase API.""" raise NotImplementedError @classmethod def fromWikibase(cls, json): """Create a representation object based on JSON from Wikibase API.""" raise NotImplementedError def __str__(self): return json.dumps(self.toWikibase(), indent=4, sort_keys=True, separators=(',', ': ')) def __repr__(self): assert isinstance(self._items, tuple) assert all(isinstance(item, StringTypes) for item in self._items) values = ((attr, getattr(self, attr)) for attr in self._items) attrs = ', '.join('{0}={1}'.format(attr, value) for attr, value in values) return '{0}({1})'.format(self.__class__.__name__, attrs) def __eq__(self, other): return self.__dict__ == other.__dict__ ## Instruction: Add missing not-equal comparison for wbtypes ## Code After: """Wikibase data type classes.""" # # (C) Pywikibot team, 2013-2015 # # Distributed under the terms of the MIT license. # from __future__ import absolute_import, unicode_literals __version__ = '$Id$' # import json from pywikibot.tools import StringTypes class WbRepresentation(object): """Abstract class for Wikibase representations.""" def __init__(self): """Constructor.""" raise NotImplementedError def toWikibase(self): """Convert representation to JSON for the Wikibase API.""" raise NotImplementedError @classmethod def fromWikibase(cls, json): """Create a representation object based on JSON from Wikibase API.""" raise NotImplementedError def __str__(self): return json.dumps(self.toWikibase(), indent=4, sort_keys=True, separators=(',', ': ')) def __repr__(self): assert isinstance(self._items, tuple) assert all(isinstance(item, StringTypes) for item in self._items) values = ((attr, getattr(self, attr)) for attr in self._items) attrs = ', '.join('{0}={1}'.format(attr, value) for attr, value in values) return '{0}({1})'.format(self.__class__.__name__, attrs) def __eq__(self, other): return self.__dict__ == other.__dict__ def __ne__(self, other): return not self.__eq__(other)
... return self.__dict__ == other.__dict__ def __ne__(self, other): return not self.__eq__(other) ...
56bc9c79522fd534f2a756bd5a18193635e2adae
tests/test_default_security_groups.py
tests/test_default_security_groups.py
"""Test default Security Groups.""" from unittest import mock from foremast.securitygroup.create_securitygroup import SpinnakerSecurityGroup @mock.patch('foremast.securitygroup.create_securitygroup.get_properties') def test_default_security_groups(mock_properties): """Make sure default Security Groups are added to the ingress rules.""" ingress = { 'test_app': [ { 'start_port': 30, 'end_port': 30, }, ], } mock_properties.return_value = { 'security_group': { 'ingress': ingress, 'description': '', }, } test_sg = {'myapp': [{'start_port': '22', 'end_port': '22', 'protocol': 'tcp' }]} with mock.patch.dict('foremast.securitygroup.create_securitygroup.DEFAULT_SECURITYGROUP_RULES', test_sg): test_sg = SpinnakerSecurityGroup() ingress = test_sg.update_default_securitygroup_rules() assert 'myapp' in ingress
"""Test default Security Groups.""" from unittest import mock from foremast.securitygroup.create_securitygroup import SpinnakerSecurityGroup @mock.patch('foremast.securitygroup.create_securitygroup.get_details') @mock.patch('foremast.securitygroup.create_securitygroup.get_properties') def test_default_security_groups(mock_properties, mock_details): """Make sure default Security Groups are added to the ingress rules.""" ingress = { 'test_app': [ { 'start_port': 30, 'end_port': 30, }, ], } mock_properties.return_value = { 'security_group': { 'ingress': ingress, 'description': '', }, } test_sg = { 'myapp': [ {'start_port': '22', 'end_port': '22', 'protocol': 'tcp'}, ] } with mock.patch.dict('foremast.securitygroup.create_securitygroup.DEFAULT_SECURITYGROUP_RULES', test_sg): sg = SpinnakerSecurityGroup() ingress = sg.update_default_securitygroup_rules() assert 'myapp' in ingress
Fix missing mock and rename variable
tests: Fix missing mock and rename variable
Python
apache-2.0
gogoair/foremast,gogoair/foremast
"""Test default Security Groups.""" from unittest import mock from foremast.securitygroup.create_securitygroup import SpinnakerSecurityGroup + @mock.patch('foremast.securitygroup.create_securitygroup.get_details') @mock.patch('foremast.securitygroup.create_securitygroup.get_properties') - def test_default_security_groups(mock_properties): + def test_default_security_groups(mock_properties, mock_details): """Make sure default Security Groups are added to the ingress rules.""" ingress = { 'test_app': [ { 'start_port': 30, 'end_port': 30, }, ], } mock_properties.return_value = { 'security_group': { 'ingress': ingress, 'description': '', }, } + test_sg = { + 'myapp': [ - test_sg = {'myapp': [{'start_port': '22', 'end_port': '22', 'protocol': 'tcp' }]} + {'start_port': '22', 'end_port': '22', 'protocol': 'tcp'}, + ] + } with mock.patch.dict('foremast.securitygroup.create_securitygroup.DEFAULT_SECURITYGROUP_RULES', test_sg): - test_sg = SpinnakerSecurityGroup() + sg = SpinnakerSecurityGroup() - ingress = test_sg.update_default_securitygroup_rules() + ingress = sg.update_default_securitygroup_rules() assert 'myapp' in ingress
Fix missing mock and rename variable
## Code Before: """Test default Security Groups.""" from unittest import mock from foremast.securitygroup.create_securitygroup import SpinnakerSecurityGroup @mock.patch('foremast.securitygroup.create_securitygroup.get_properties') def test_default_security_groups(mock_properties): """Make sure default Security Groups are added to the ingress rules.""" ingress = { 'test_app': [ { 'start_port': 30, 'end_port': 30, }, ], } mock_properties.return_value = { 'security_group': { 'ingress': ingress, 'description': '', }, } test_sg = {'myapp': [{'start_port': '22', 'end_port': '22', 'protocol': 'tcp' }]} with mock.patch.dict('foremast.securitygroup.create_securitygroup.DEFAULT_SECURITYGROUP_RULES', test_sg): test_sg = SpinnakerSecurityGroup() ingress = test_sg.update_default_securitygroup_rules() assert 'myapp' in ingress ## Instruction: Fix missing mock and rename variable ## Code After: """Test default Security Groups.""" from unittest import mock from foremast.securitygroup.create_securitygroup import SpinnakerSecurityGroup @mock.patch('foremast.securitygroup.create_securitygroup.get_details') @mock.patch('foremast.securitygroup.create_securitygroup.get_properties') def test_default_security_groups(mock_properties, mock_details): """Make sure default Security Groups are added to the ingress rules.""" ingress = { 'test_app': [ { 'start_port': 30, 'end_port': 30, }, ], } mock_properties.return_value = { 'security_group': { 'ingress': ingress, 'description': '', }, } test_sg = { 'myapp': [ {'start_port': '22', 'end_port': '22', 'protocol': 'tcp'}, ] } with mock.patch.dict('foremast.securitygroup.create_securitygroup.DEFAULT_SECURITYGROUP_RULES', test_sg): sg = SpinnakerSecurityGroup() ingress = sg.update_default_securitygroup_rules() assert 'myapp' in ingress
// ... existing code ... @mock.patch('foremast.securitygroup.create_securitygroup.get_details') @mock.patch('foremast.securitygroup.create_securitygroup.get_properties') def test_default_security_groups(mock_properties, mock_details): """Make sure default Security Groups are added to the ingress rules.""" // ... modified code ... test_sg = { 'myapp': [ {'start_port': '22', 'end_port': '22', 'protocol': 'tcp'}, ] } with mock.patch.dict('foremast.securitygroup.create_securitygroup.DEFAULT_SECURITYGROUP_RULES', test_sg): sg = SpinnakerSecurityGroup() ingress = sg.update_default_securitygroup_rules() assert 'myapp' in ingress // ... rest of the code ...
7ec28d5b8be40b505a20a4670857278ad41f760b
src/puzzle/puzzlepedia/puzzlepedia.py
src/puzzle/puzzlepedia/puzzlepedia.py
from IPython import display from puzzle.puzzlepedia import prod_config, puzzle, puzzle_widget _INITIALIZED = False def parse(source, hint=None): _init() result = puzzle.Puzzle('first stage', source, hint=hint) interact_with(result) return result def interact_with(puzzle): _init() display.display(puzzle_widget.PuzzleWidget(puzzle)) def _init(): global _INITIALIZED if not _INITIALIZED: _INITIALIZED = True prod_config.init() def reset(): global _INITIALIZED _INITIALIZED = False prod_config.reset()
from IPython import display from puzzle.puzzlepedia import prod_config, puzzle, puzzle_widget _INITIALIZED = False def parse(source, hint=None, threshold=None): _init() result = puzzle.Puzzle('first stage', source, hint=hint, threshold=threshold) interact_with(result) return result def interact_with(puzzle): _init() display.display(puzzle_widget.PuzzleWidget(puzzle)) def _init(): global _INITIALIZED if not _INITIALIZED: _INITIALIZED = True prod_config.init() def reset(): global _INITIALIZED _INITIALIZED = False prod_config.reset()
Allow "threshold" to be specified during parse(...).
Allow "threshold" to be specified during parse(...).
Python
mit
PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge
from IPython import display from puzzle.puzzlepedia import prod_config, puzzle, puzzle_widget _INITIALIZED = False - def parse(source, hint=None): + def parse(source, hint=None, threshold=None): _init() - result = puzzle.Puzzle('first stage', source, hint=hint) + result = puzzle.Puzzle('first stage', source, hint=hint, threshold=threshold) interact_with(result) return result def interact_with(puzzle): _init() display.display(puzzle_widget.PuzzleWidget(puzzle)) def _init(): global _INITIALIZED if not _INITIALIZED: _INITIALIZED = True prod_config.init() def reset(): global _INITIALIZED _INITIALIZED = False prod_config.reset()
Allow "threshold" to be specified during parse(...).
## Code Before: from IPython import display from puzzle.puzzlepedia import prod_config, puzzle, puzzle_widget _INITIALIZED = False def parse(source, hint=None): _init() result = puzzle.Puzzle('first stage', source, hint=hint) interact_with(result) return result def interact_with(puzzle): _init() display.display(puzzle_widget.PuzzleWidget(puzzle)) def _init(): global _INITIALIZED if not _INITIALIZED: _INITIALIZED = True prod_config.init() def reset(): global _INITIALIZED _INITIALIZED = False prod_config.reset() ## Instruction: Allow "threshold" to be specified during parse(...). ## Code After: from IPython import display from puzzle.puzzlepedia import prod_config, puzzle, puzzle_widget _INITIALIZED = False def parse(source, hint=None, threshold=None): _init() result = puzzle.Puzzle('first stage', source, hint=hint, threshold=threshold) interact_with(result) return result def interact_with(puzzle): _init() display.display(puzzle_widget.PuzzleWidget(puzzle)) def _init(): global _INITIALIZED if not _INITIALIZED: _INITIALIZED = True prod_config.init() def reset(): global _INITIALIZED _INITIALIZED = False prod_config.reset()
# ... existing code ... def parse(source, hint=None, threshold=None): _init() result = puzzle.Puzzle('first stage', source, hint=hint, threshold=threshold) interact_with(result) # ... rest of the code ...
cf16c64e378f64d2267f75444c568aed895f940c
setup.py
setup.py
import platform, sys from distutils.core import setup from distextend import * packages, package_data = findPackages("countershape") setup( name = "countershape", version = "0.1", description = "A framework for rendering static documentation.", author = "Nullcube Pty Ltd", author_email = "[email protected]", url = "http://dev.nullcube.com", packages = packages, package_data = package_data, scripts = ["cshape"], )
import platform, sys from distutils.core import setup from distextend import * packages, package_data = findPackages("countershape") setup( name = "countershape", version = "0.1", description = "A framework for rendering static documentation.", author = "Nullcube Pty Ltd", author_email = "[email protected]", url = "http://dev.nullcube.com", packages = packages, package_data = package_data, scripts = ["cshape", "csblog"], )
Add csblog to installed scripts.
Add csblog to installed scripts.
Python
mit
mhils/countershape,samtaufa/countershape,cortesi/countershape,cortesi/countershape,samtaufa/countershape,mhils/countershape
import platform, sys from distutils.core import setup from distextend import * packages, package_data = findPackages("countershape") setup( name = "countershape", version = "0.1", description = "A framework for rendering static documentation.", author = "Nullcube Pty Ltd", author_email = "[email protected]", url = "http://dev.nullcube.com", packages = packages, package_data = package_data, - scripts = ["cshape"], + scripts = ["cshape", "csblog"], )
Add csblog to installed scripts.
## Code Before: import platform, sys from distutils.core import setup from distextend import * packages, package_data = findPackages("countershape") setup( name = "countershape", version = "0.1", description = "A framework for rendering static documentation.", author = "Nullcube Pty Ltd", author_email = "[email protected]", url = "http://dev.nullcube.com", packages = packages, package_data = package_data, scripts = ["cshape"], ) ## Instruction: Add csblog to installed scripts. ## Code After: import platform, sys from distutils.core import setup from distextend import * packages, package_data = findPackages("countershape") setup( name = "countershape", version = "0.1", description = "A framework for rendering static documentation.", author = "Nullcube Pty Ltd", author_email = "[email protected]", url = "http://dev.nullcube.com", packages = packages, package_data = package_data, scripts = ["cshape", "csblog"], )
# ... existing code ... package_data = package_data, scripts = ["cshape", "csblog"], ) # ... rest of the code ...
74d0e710711f1b499ab32784b751adc55e8b7f00
python/bonetrousle.py
python/bonetrousle.py
import os import sys # n: the integer number of sticks to buy # k: the integer number of box sizes the store carries # b: the integer number of boxes to buy def bonetrousle(n, k, b): if (minimumValue(k, b) <= n <= maximumValue(k, b)): return boxesToBuy(n, k, b) else: return -1 # The minimum number of sticks that may be purchased def minimumValue(k, b): return 0 # The maximum number of sticks that may be purchased def maximumValue(k, b): return 100 # One possible solution of boxes that sum to n def boxesToBuy(n, k, b): return [0] if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') t = int(input()) for t_itr in range(t): nkb = input().split() n = int(nkb[0]) k = int(nkb[1]) b = int(nkb[2]) result = bonetrousle(n, k, b) fptr.write(' '.join(map(str, result))) fptr.write('\n') fptr.close()
import os import sys # n: the integer number of sticks to buy # k: the integer number of box sizes the store carries # b: the integer number of boxes to buy def bonetrousle(n, k, b): if (minimumValue(k, b) <= n <= maximumValue(k, b)): return boxesToBuy(n, k, b) else: return -1 # The minimum number of sticks that may be purchased # Equivalant to: 1 + 2 + 3 ... b # See: https://en.wikipedia.org/wiki/Arithmetic_progression#Sum def minimumValue(k, b): return b * (1 + b) / 2 # The maximum number of sticks that may be purchased # Equivalant to: (k - b + 1) ... (k - 2) + (k -1) + k # See: https://en.wikipedia.org/wiki/Arithmetic_progression#Sum def maximumValue(k, b): return b * ((k - b + 1) + k) / 2 # One possible solution of boxes that sum to n def boxesToBuy(n, k, b): return [0] if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') t = int(input()) for t_itr in range(t): nkb = input().split() n = int(nkb[0]) k = int(nkb[1]) b = int(nkb[2]) result = bonetrousle(n, k, b) fptr.write(' '.join(map(str, result))) fptr.write('\n') fptr.close()
Implement minimum and maximum values
Implement minimum and maximum values
Python
mit
rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank
import os import sys # n: the integer number of sticks to buy # k: the integer number of box sizes the store carries # b: the integer number of boxes to buy def bonetrousle(n, k, b): if (minimumValue(k, b) <= n <= maximumValue(k, b)): return boxesToBuy(n, k, b) else: return -1 # The minimum number of sticks that may be purchased + # Equivalant to: 1 + 2 + 3 ... b + # See: https://en.wikipedia.org/wiki/Arithmetic_progression#Sum def minimumValue(k, b): - return 0 + return b * (1 + b) / 2 # The maximum number of sticks that may be purchased + # Equivalant to: (k - b + 1) ... (k - 2) + (k -1) + k + # See: https://en.wikipedia.org/wiki/Arithmetic_progression#Sum def maximumValue(k, b): - return 100 + return b * ((k - b + 1) + k) / 2 # One possible solution of boxes that sum to n def boxesToBuy(n, k, b): return [0] if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') t = int(input()) for t_itr in range(t): nkb = input().split() n = int(nkb[0]) k = int(nkb[1]) b = int(nkb[2]) result = bonetrousle(n, k, b) fptr.write(' '.join(map(str, result))) fptr.write('\n') fptr.close()
Implement minimum and maximum values
## Code Before: import os import sys # n: the integer number of sticks to buy # k: the integer number of box sizes the store carries # b: the integer number of boxes to buy def bonetrousle(n, k, b): if (minimumValue(k, b) <= n <= maximumValue(k, b)): return boxesToBuy(n, k, b) else: return -1 # The minimum number of sticks that may be purchased def minimumValue(k, b): return 0 # The maximum number of sticks that may be purchased def maximumValue(k, b): return 100 # One possible solution of boxes that sum to n def boxesToBuy(n, k, b): return [0] if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') t = int(input()) for t_itr in range(t): nkb = input().split() n = int(nkb[0]) k = int(nkb[1]) b = int(nkb[2]) result = bonetrousle(n, k, b) fptr.write(' '.join(map(str, result))) fptr.write('\n') fptr.close() ## Instruction: Implement minimum and maximum values ## Code After: import os import sys # n: the integer number of sticks to buy # k: the integer number of box sizes the store carries # b: the integer number of boxes to buy def bonetrousle(n, k, b): if (minimumValue(k, b) <= n <= maximumValue(k, b)): return boxesToBuy(n, k, b) else: return -1 # The minimum number of sticks that may be purchased # Equivalant to: 1 + 2 + 3 ... b # See: https://en.wikipedia.org/wiki/Arithmetic_progression#Sum def minimumValue(k, b): return b * (1 + b) / 2 # The maximum number of sticks that may be purchased # Equivalant to: (k - b + 1) ... (k - 2) + (k -1) + k # See: https://en.wikipedia.org/wiki/Arithmetic_progression#Sum def maximumValue(k, b): return b * ((k - b + 1) + k) / 2 # One possible solution of boxes that sum to n def boxesToBuy(n, k, b): return [0] if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') t = int(input()) for t_itr in range(t): nkb = input().split() n = int(nkb[0]) k = int(nkb[1]) b = int(nkb[2]) result = bonetrousle(n, k, b) fptr.write(' '.join(map(str, result))) fptr.write('\n') fptr.close()
# ... existing code ... # The minimum number of sticks that may be purchased # Equivalant to: 1 + 2 + 3 ... b # See: https://en.wikipedia.org/wiki/Arithmetic_progression#Sum def minimumValue(k, b): return b * (1 + b) / 2 # ... modified code ... # The maximum number of sticks that may be purchased # Equivalant to: (k - b + 1) ... (k - 2) + (k -1) + k # See: https://en.wikipedia.org/wiki/Arithmetic_progression#Sum def maximumValue(k, b): return b * ((k - b + 1) + k) / 2 # ... rest of the code ...
e8c180e65dda3422ab472a6580183c715ef325c3
easyium/decorator.py
easyium/decorator.py
__author__ = 'karl.gong' from .exceptions import UnsupportedOperationException def SupportedBy(*web_driver_types): def handle_func(func): def handle_args(*args, **kwargs): wd_types = [] for wd_type in web_driver_types: if isinstance(wd_type, list): wd_types += wd_type else: wd_types += [wd_type] current_web_driver_type = args[0].get_web_driver_type() if current_web_driver_type not in wd_types: raise UnsupportedOperationException( "This operation is not supported by web driver [%s]." % current_web_driver_type) return func(*args, **kwargs) return handle_args return handle_func
__author__ = 'karl.gong' from .exceptions import UnsupportedOperationException def SupportedBy(*web_driver_types): def handle_func(func): def handle_args(*args, **kwargs): wd_types = [] for wd_type in web_driver_types: if isinstance(wd_type, list): wd_types += wd_type else: wd_types += [wd_type] current_web_driver_type = args[0].get_web_driver_type() if current_web_driver_type not in wd_types: raise UnsupportedOperationException( "Operation [%s] is not supported by web driver [%s]." % (func.__name__, current_web_driver_type)) return func(*args, **kwargs) return handle_args return handle_func
Update error message of UnsupportedOperationException.
Update error message of UnsupportedOperationException.
Python
apache-2.0
KarlGong/easyium-python,KarlGong/easyium
__author__ = 'karl.gong' from .exceptions import UnsupportedOperationException def SupportedBy(*web_driver_types): def handle_func(func): def handle_args(*args, **kwargs): wd_types = [] for wd_type in web_driver_types: if isinstance(wd_type, list): wd_types += wd_type else: wd_types += [wd_type] current_web_driver_type = args[0].get_web_driver_type() if current_web_driver_type not in wd_types: raise UnsupportedOperationException( - "This operation is not supported by web driver [%s]." % current_web_driver_type) + "Operation [%s] is not supported by web driver [%s]." % (func.__name__, current_web_driver_type)) return func(*args, **kwargs) return handle_args return handle_func
Update error message of UnsupportedOperationException.
## Code Before: __author__ = 'karl.gong' from .exceptions import UnsupportedOperationException def SupportedBy(*web_driver_types): def handle_func(func): def handle_args(*args, **kwargs): wd_types = [] for wd_type in web_driver_types: if isinstance(wd_type, list): wd_types += wd_type else: wd_types += [wd_type] current_web_driver_type = args[0].get_web_driver_type() if current_web_driver_type not in wd_types: raise UnsupportedOperationException( "This operation is not supported by web driver [%s]." % current_web_driver_type) return func(*args, **kwargs) return handle_args return handle_func ## Instruction: Update error message of UnsupportedOperationException. ## Code After: __author__ = 'karl.gong' from .exceptions import UnsupportedOperationException def SupportedBy(*web_driver_types): def handle_func(func): def handle_args(*args, **kwargs): wd_types = [] for wd_type in web_driver_types: if isinstance(wd_type, list): wd_types += wd_type else: wd_types += [wd_type] current_web_driver_type = args[0].get_web_driver_type() if current_web_driver_type not in wd_types: raise UnsupportedOperationException( "Operation [%s] is not supported by web driver [%s]." % (func.__name__, current_web_driver_type)) return func(*args, **kwargs) return handle_args return handle_func
... raise UnsupportedOperationException( "Operation [%s] is not supported by web driver [%s]." % (func.__name__, current_web_driver_type)) ...
e2e6e603ddcc317bdd56e3de3f69656b776030bf
avalanche/benchmarks/classic/ctrl.py
avalanche/benchmarks/classic/ctrl.py
import torch from avalanche.benchmarks import GenericCLScenario, dataset_benchmark from avalanche.benchmarks.utils import AvalancheTensorDataset from torchvision import transforms import ctrl def CTrL(stream_name): stream = ctrl.get_stream(stream_name) exps = [[], [], []] norms = [] for t in stream: for split, exp in zip(t.datasets, exps): samples, labels = split.tensors # samples -= torch.tensor(t.statistics['mean']).view(1, 3, 1, 1) # samples /= torch.tensor(t.statistics['std']).view(1, 3, 1, 1) task_labels = [t.id] * samples.size(0) dataset = AvalancheTensorDataset(samples, labels.squeeze(1), task_labels=task_labels) exp.append(dataset) norms.append(transforms.Normalize(t.statistics['mean'], t.statistics['std'])) return dataset_benchmark( train_datasets=exps[0], test_datasets=exps[2], other_streams_datasets=dict(valid=exps[1]), )
import torch from avalanche.benchmarks import GenericCLScenario, dataset_benchmark from avalanche.benchmarks.utils import AvalancheTensorDataset from torchvision import transforms import ctrl def CTrL(stream_name): stream = ctrl.get_stream(stream_name) # Train, val and test experiences exps = [[], [], []] for t in stream: trans = transforms.Normalize(t.statistics['mean'], t.statistics['std']) for split, exp in zip(t.datasets, exps): samples, labels = split.tensors task_labels = [t.id] * samples.size(0) dataset = AvalancheTensorDataset(samples, labels.squeeze(1), task_labels=task_labels, transform=trans) exp.append(dataset) return dataset_benchmark( train_datasets=exps[0], test_datasets=exps[2], other_streams_datasets=dict(valid=exps[1]), )
Add normalization to each task
Add normalization to each task
Python
mit
ContinualAI/avalanche,ContinualAI/avalanche
import torch from avalanche.benchmarks import GenericCLScenario, dataset_benchmark from avalanche.benchmarks.utils import AvalancheTensorDataset from torchvision import transforms import ctrl def CTrL(stream_name): stream = ctrl.get_stream(stream_name) + # Train, val and test experiences exps = [[], [], []] - norms = [] for t in stream: + trans = transforms.Normalize(t.statistics['mean'], + t.statistics['std']) for split, exp in zip(t.datasets, exps): samples, labels = split.tensors - # samples -= torch.tensor(t.statistics['mean']).view(1, 3, 1, 1) - # samples /= torch.tensor(t.statistics['std']).view(1, 3, 1, 1) - task_labels = [t.id] * samples.size(0) dataset = AvalancheTensorDataset(samples, labels.squeeze(1), - task_labels=task_labels) + task_labels=task_labels, + transform=trans) exp.append(dataset) - norms.append(transforms.Normalize(t.statistics['mean'], - t.statistics['std'])) return dataset_benchmark( train_datasets=exps[0], test_datasets=exps[2], other_streams_datasets=dict(valid=exps[1]), )
Add normalization to each task
## Code Before: import torch from avalanche.benchmarks import GenericCLScenario, dataset_benchmark from avalanche.benchmarks.utils import AvalancheTensorDataset from torchvision import transforms import ctrl def CTrL(stream_name): stream = ctrl.get_stream(stream_name) exps = [[], [], []] norms = [] for t in stream: for split, exp in zip(t.datasets, exps): samples, labels = split.tensors # samples -= torch.tensor(t.statistics['mean']).view(1, 3, 1, 1) # samples /= torch.tensor(t.statistics['std']).view(1, 3, 1, 1) task_labels = [t.id] * samples.size(0) dataset = AvalancheTensorDataset(samples, labels.squeeze(1), task_labels=task_labels) exp.append(dataset) norms.append(transforms.Normalize(t.statistics['mean'], t.statistics['std'])) return dataset_benchmark( train_datasets=exps[0], test_datasets=exps[2], other_streams_datasets=dict(valid=exps[1]), ) ## Instruction: Add normalization to each task ## Code After: import torch from avalanche.benchmarks import GenericCLScenario, dataset_benchmark from avalanche.benchmarks.utils import AvalancheTensorDataset from torchvision import transforms import ctrl def CTrL(stream_name): stream = ctrl.get_stream(stream_name) # Train, val and test experiences exps = [[], [], []] for t in stream: trans = transforms.Normalize(t.statistics['mean'], t.statistics['std']) for split, exp in zip(t.datasets, exps): samples, labels = split.tensors task_labels = [t.id] * samples.size(0) dataset = AvalancheTensorDataset(samples, labels.squeeze(1), task_labels=task_labels, transform=trans) exp.append(dataset) return dataset_benchmark( train_datasets=exps[0], test_datasets=exps[2], other_streams_datasets=dict(valid=exps[1]), )
# ... existing code ... # Train, val and test experiences exps = [[], [], []] for t in stream: trans = transforms.Normalize(t.statistics['mean'], t.statistics['std']) for split, exp in zip(t.datasets, exps): # ... modified code ... samples, labels = split.tensors task_labels = [t.id] * samples.size(0) ... dataset = AvalancheTensorDataset(samples, labels.squeeze(1), task_labels=task_labels, transform=trans) exp.append(dataset) return dataset_benchmark( # ... rest of the code ...
4631a2192b24675f61f4eec5ab68e273ea47cca8
sklearn/svm/sparse/base.py
sklearn/svm/sparse/base.py
import numpy as np import scipy.sparse from abc import ABCMeta, abstractmethod from ..base import BaseLibSVM class SparseBaseLibSVM(BaseLibSVM): __metaclass__ = ABCMeta @abstractmethod def __init__(self, impl, kernel, degree, gamma, coef0, tol, C, nu, epsilon, shrinking, probability, cache_size, class_weight, verbose): assert kernel in self._sparse_kernels, \ "kernel should be one of %s, "\ "%s was given." % (self._kernel_types, kernel) super(SparseBaseLibSVM, self).__init__(impl, kernel, degree, gamma, coef0, tol, C, nu, epsilon, shrinking, probability, cache_size, True, class_weight, verbose) def fit(self, X, y, sample_weight=None): X = scipy.sparse.csr_matrix(X, dtype=np.float64) return super(SparseBaseLibSVM, self).fit(X, y, sample_weight)
import numpy as np import scipy.sparse from abc import ABCMeta, abstractmethod from ..base import BaseLibSVM class SparseBaseLibSVM(BaseLibSVM): __metaclass__ = ABCMeta @abstractmethod def __init__(self, impl, kernel, degree, gamma, coef0, tol, C, nu, epsilon, shrinking, probability, cache_size, class_weight, verbose): assert kernel in self._sparse_kernels, \ "kernel should be one of %s, "\ "%s was given." % (self._kernel_types, kernel) super(SparseBaseLibSVM, self).__init__(impl, kernel, degree, gamma, coef0, tol, C, nu, epsilon, shrinking, probability, cache_size, True, class_weight, verbose) def fit(self, X, y, sample_weight=None): X = scipy.sparse.csr_matrix(X, dtype=np.float64) return super(SparseBaseLibSVM, self).fit(X, y, sample_weight=sample_weight)
FIX sparse OneClassSVM was using the wrong parameter
FIX sparse OneClassSVM was using the wrong parameter
Python
bsd-3-clause
rishikksh20/scikit-learn,kmike/scikit-learn,JPFrancoia/scikit-learn,B3AU/waveTree,themrmax/scikit-learn,vybstat/scikit-learn,kaichogami/scikit-learn,IndraVikas/scikit-learn,walterreade/scikit-learn,tosolveit/scikit-learn,macks22/scikit-learn,AlexRobson/scikit-learn,heli522/scikit-learn,robbymeals/scikit-learn,xuewei4d/scikit-learn,zhenv5/scikit-learn,theoryno3/scikit-learn,themrmax/scikit-learn,alexsavio/scikit-learn,Srisai85/scikit-learn,wanggang3333/scikit-learn,walterreade/scikit-learn,rohanp/scikit-learn,loli/semisupervisedforests,luo66/scikit-learn,eg-zhang/scikit-learn,mjudsp/Tsallis,adamgreenhall/scikit-learn,jlegendary/scikit-learn,saiwing-yeung/scikit-learn,liangz0707/scikit-learn,hlin117/scikit-learn,shangwuhencc/scikit-learn,xubenben/scikit-learn,sergeyf/scikit-learn,dingocuster/scikit-learn,billy-inn/scikit-learn,IssamLaradji/scikit-learn,dsullivan7/scikit-learn,moutai/scikit-learn,toastedcornflakes/scikit-learn,xwolf12/scikit-learn,smartscheduling/scikit-learn-categorical-tree,NunoEdgarGub1/scikit-learn,kagayakidan/scikit-learn,phdowling/scikit-learn,fredhusser/scikit-learn,wzbozon/scikit-learn,xubenben/scikit-learn,jereze/scikit-learn,DonBeo/scikit-learn,bnaul/scikit-learn,jmschrei/scikit-learn,Garrett-R/scikit-learn,sumspr/scikit-learn,zaxtax/scikit-learn,CforED/Machine-Learning,Adai0808/scikit-learn,costypetrisor/scikit-learn,appapantula/scikit-learn,arabenjamin/scikit-learn,Adai0808/scikit-learn,alexsavio/scikit-learn,nrhine1/scikit-learn,nhejazi/scikit-learn,samuel1208/scikit-learn,plissonf/scikit-learn,ClimbsRocks/scikit-learn,q1ang/scikit-learn,hlin117/scikit-learn,vivekmishra1991/scikit-learn,IssamLaradji/scikit-learn,DonBeo/scikit-learn,spallavolu/scikit-learn,xwolf12/scikit-learn,fyffyt/scikit-learn,macks22/scikit-learn,vshtanko/scikit-learn,gclenaghan/scikit-learn,herilalaina/scikit-learn,Myasuka/scikit-learn,hsuantien/scikit-learn,hdmetor/scikit-learn,ilyes14/scikit-learn,stylianos-kampakis/scikit-learn,ngoix/OCRF,marcocaccin/scikit-learn,fbagirov/scikit-learn,sanketloke/scikit-learn,0x0all/scikit-learn,ningchi/scikit-learn,alexeyum/scikit-learn,PatrickChrist/scikit-learn,ilo10/scikit-learn,LiaoPan/scikit-learn,yyjiang/scikit-learn,YinongLong/scikit-learn,justincassidy/scikit-learn,pv/scikit-learn,carrillo/scikit-learn,abhishekkrthakur/scikit-learn,chrsrds/scikit-learn,shikhardb/scikit-learn,hainm/scikit-learn,xiaoxiamii/scikit-learn,djgagne/scikit-learn,devanshdalal/scikit-learn,mwv/scikit-learn,rrohan/scikit-learn,jkarnows/scikit-learn,jorge2703/scikit-learn,xwolf12/scikit-learn,thientu/scikit-learn,ilo10/scikit-learn,vibhorag/scikit-learn,Barmaley-exe/scikit-learn,amueller/scikit-learn,ndingwall/scikit-learn,jmschrei/scikit-learn,ngoix/OCRF,ogrisel/scikit-learn,chrisburr/scikit-learn,abimannans/scikit-learn,ky822/scikit-learn,nmayorov/scikit-learn,aetilley/scikit-learn,ankurankan/scikit-learn,shyamalschandra/scikit-learn,Srisai85/scikit-learn,treycausey/scikit-learn,fabianp/scikit-learn,vortex-ape/scikit-learn,RomainBrault/scikit-learn,fzalkow/scikit-learn,terkkila/scikit-learn,madjelan/scikit-learn,rishikksh20/scikit-learn,Jimmy-Morzaria/scikit-learn,frank-tancf/scikit-learn,devanshdalal/scikit-learn,JPFrancoia/scikit-learn,terkkila/scikit-learn,olologin/scikit-learn,loli/sklearn-ensembletrees,aewhatley/scikit-learn,Djabbz/scikit-learn,hsiaoyi0504/scikit-learn,shyamalschandra/scikit-learn,MartinSavc/scikit-learn,mjgrav2001/scikit-learn,xavierwu/scikit-learn,pythonvietnam/scikit-learn,raghavrv/scikit-learn,michigraber/scikit-learn,khkaminska/scikit-learn,wlamond/scikit-learn,procoder317/scikit-learn,YinongLong/scikit-learn,abimannans/scikit-learn,mwv/scikit-learn,IshankGulati/scikit-learn,lucidfrontier45/scikit-learn,mattgiguere/scikit-learn,olologin/scikit-learn,Djabbz/scikit-learn,xuewei4d/scikit-learn,wanggang3333/scikit-learn,Aasmi/scikit-learn,rsivapr/scikit-learn,liberatorqjw/scikit-learn,vermouthmjl/scikit-learn,quheng/scikit-learn,mlyundin/scikit-learn,rvraghav93/scikit-learn,rohanp/scikit-learn,ChanderG/scikit-learn,pkruskal/scikit-learn,466152112/scikit-learn,ldirer/scikit-learn,alexsavio/scikit-learn,Barmaley-exe/scikit-learn,chrsrds/scikit-learn,mlyundin/scikit-learn,thilbern/scikit-learn,victorbergelin/scikit-learn,jaidevd/scikit-learn,scikit-learn/scikit-learn,ishanic/scikit-learn,harshaneelhg/scikit-learn,yask123/scikit-learn,gotomypc/scikit-learn,potash/scikit-learn,meduz/scikit-learn,glemaitre/scikit-learn,xubenben/scikit-learn,hlin117/scikit-learn,murali-munna/scikit-learn,PrashntS/scikit-learn,mfjb/scikit-learn,vinayak-mehta/scikit-learn,simon-pepin/scikit-learn,ephes/scikit-learn,liberatorqjw/scikit-learn,lenovor/scikit-learn,stylianos-kampakis/scikit-learn,hugobowne/scikit-learn,eg-zhang/scikit-learn,Sentient07/scikit-learn,Lawrence-Liu/scikit-learn,samuel1208/scikit-learn,nomadcube/scikit-learn,espg/scikit-learn,Achuth17/scikit-learn,abimannans/scikit-learn,huzq/scikit-learn,jmschrei/scikit-learn,AlexandreAbraham/scikit-learn,lucidfrontier45/scikit-learn,vybstat/scikit-learn,3manuek/scikit-learn,huzq/scikit-learn,arjoly/scikit-learn,alexeyum/scikit-learn,murali-munna/scikit-learn,AlexRobson/scikit-learn,aabadie/scikit-learn,jayflo/scikit-learn,f3r/scikit-learn,PatrickOReilly/scikit-learn,aflaxman/scikit-learn,q1ang/scikit-learn,russel1237/scikit-learn,Obus/scikit-learn,btabibian/scikit-learn,altairpearl/scikit-learn,fabioticconi/scikit-learn,MechCoder/scikit-learn,CVML/scikit-learn,appapantula/scikit-learn,anurag313/scikit-learn,h2educ/scikit-learn,raghavrv/scikit-learn,krez13/scikit-learn,pv/scikit-learn,3manuek/scikit-learn,ephes/scikit-learn,pianomania/scikit-learn,DSLituiev/scikit-learn,sonnyhu/scikit-learn,Garrett-R/scikit-learn,petosegan/scikit-learn,ndingwall/scikit-learn,q1ang/scikit-learn,btabibian/scikit-learn,pkruskal/scikit-learn,rrohan/scikit-learn,billy-inn/scikit-learn,NelisVerhoef/scikit-learn,shusenl/scikit-learn,3manuek/scikit-learn,ltiao/scikit-learn,trankmichael/scikit-learn,manashmndl/scikit-learn,evgchz/scikit-learn,RayMick/scikit-learn,jjx02230808/project0223,Barmaley-exe/scikit-learn,jzt5132/scikit-learn,rajat1994/scikit-learn,victorbergelin/scikit-learn,anurag313/scikit-learn,ssaeger/scikit-learn,mwv/scikit-learn,qifeigit/scikit-learn,joernhees/scikit-learn,yask123/scikit-learn,ycaihua/scikit-learn,yunfeilu/scikit-learn,siutanwong/scikit-learn,fzalkow/scikit-learn,dhruv13J/scikit-learn,glennq/scikit-learn,dsullivan7/scikit-learn,rsivapr/scikit-learn,xyguo/scikit-learn,larsmans/scikit-learn,mojoboss/scikit-learn,mhdella/scikit-learn,procoder317/scikit-learn,tawsifkhan/scikit-learn,JsNoNo/scikit-learn,ChanChiChoi/scikit-learn,dsquareindia/scikit-learn,cainiaocome/scikit-learn,cauchycui/scikit-learn,shyamalschandra/scikit-learn,Akshay0724/scikit-learn,chrisburr/scikit-learn,smartscheduling/scikit-learn-categorical-tree,Barmaley-exe/scikit-learn,kylerbrown/scikit-learn,robin-lai/scikit-learn,rahul-c1/scikit-learn,jayflo/scikit-learn,rsivapr/scikit-learn,clemkoa/scikit-learn,pnedunuri/scikit-learn,xuewei4d/scikit-learn,beepee14/scikit-learn,elkingtonmcb/scikit-learn,cwu2011/scikit-learn,Vimos/scikit-learn,MatthieuBizien/scikit-learn,cl4rke/scikit-learn,jzt5132/scikit-learn,rexshihaoren/scikit-learn,procoder317/scikit-learn,kaichogami/scikit-learn,davidgbe/scikit-learn,jjx02230808/project0223,ivannz/scikit-learn,jpautom/scikit-learn,Achuth17/scikit-learn,akionakamura/scikit-learn,mayblue9/scikit-learn,belltailjp/scikit-learn,nhejazi/scikit-learn,frank-tancf/scikit-learn,yanlend/scikit-learn,CVML/scikit-learn,rrohan/scikit-learn,RPGOne/scikit-learn,herilalaina/scikit-learn,pratapvardhan/scikit-learn,abhishekgahlot/scikit-learn,manhhomienbienthuy/scikit-learn,aabadie/scikit-learn,bthirion/scikit-learn,mehdidc/scikit-learn,giorgiop/scikit-learn,eickenberg/scikit-learn,nelson-liu/scikit-learn,justincassidy/scikit-learn,CVML/scikit-learn,jakirkham/scikit-learn,sonnyhu/scikit-learn,samuel1208/scikit-learn,wazeerzulfikar/scikit-learn,loli/sklearn-ensembletrees,samzhang111/scikit-learn,anurag313/scikit-learn,madjelan/scikit-learn,MartinDelzant/scikit-learn,q1ang/scikit-learn,macks22/scikit-learn,imaculate/scikit-learn,JosmanPS/scikit-learn,mattgiguere/scikit-learn,CforED/Machine-Learning,CforED/Machine-Learning,Windy-Ground/scikit-learn,shahankhatch/scikit-learn,lin-credible/scikit-learn,jlegendary/scikit-learn,carrillo/scikit-learn,ltiao/scikit-learn,pianomania/scikit-learn,jorge2703/scikit-learn,Garrett-R/scikit-learn,hsuantien/scikit-learn,henrykironde/scikit-learn,466152112/scikit-learn,deepesch/scikit-learn,siutanwong/scikit-learn,schets/scikit-learn,ashhher3/scikit-learn,depet/scikit-learn,jayflo/scikit-learn,RPGOne/scikit-learn,beepee14/scikit-learn,quheng/scikit-learn,henrykironde/scikit-learn,rexshihaoren/scikit-learn,PrashntS/scikit-learn,mjudsp/Tsallis,robin-lai/scikit-learn,hugobowne/scikit-learn,liberatorqjw/scikit-learn,OshynSong/scikit-learn,justincassidy/scikit-learn,tomlof/scikit-learn,hrjn/scikit-learn,mikebenfield/scikit-learn,ClimbsRocks/scikit-learn,mblondel/scikit-learn,jereze/scikit-learn,vshtanko/scikit-learn,lbishal/scikit-learn,pkruskal/scikit-learn,OshynSong/scikit-learn,hsuantien/scikit-learn,sarahgrogan/scikit-learn,petosegan/scikit-learn,ChanChiChoi/scikit-learn,gotomypc/scikit-learn,treycausey/scikit-learn,jblackburne/scikit-learn,Jimmy-Morzaria/scikit-learn,ishanic/scikit-learn,spallavolu/scikit-learn,ky822/scikit-learn,aetilley/scikit-learn,gclenaghan/scikit-learn,themrmax/scikit-learn,B3AU/waveTree,Clyde-fare/scikit-learn,tmhm/scikit-learn,yonglehou/scikit-learn,hdmetor/scikit-learn,mugizico/scikit-learn,appapantula/scikit-learn,vibhorag/scikit-learn,vivekmishra1991/scikit-learn,anntzer/scikit-learn,NelisVerhoef/scikit-learn,voxlol/scikit-learn,plissonf/scikit-learn,466152112/scikit-learn,vshtanko/scikit-learn,cl4rke/scikit-learn,aabadie/scikit-learn,lbishal/scikit-learn,trungnt13/scikit-learn,abhishekgahlot/scikit-learn,chrisburr/scikit-learn,henrykironde/scikit-learn,NelisVerhoef/scikit-learn,mhue/scikit-learn,loli/sklearn-ensembletrees,djgagne/scikit-learn,zorroblue/scikit-learn,sarahgrogan/scikit-learn,zorojean/scikit-learn,zuku1985/scikit-learn,hsiaoyi0504/scikit-learn,yyjiang/scikit-learn,altairpearl/scikit-learn,icdishb/scikit-learn,xzh86/scikit-learn,ilyes14/scikit-learn,akionakamura/scikit-learn,tawsifkhan/scikit-learn,rohanp/scikit-learn,sinhrks/scikit-learn,roxyboy/scikit-learn,yask123/scikit-learn,mxjl620/scikit-learn,AIML/scikit-learn,ogrisel/scikit-learn,lesteve/scikit-learn,vigilv/scikit-learn,nikitasingh981/scikit-learn,shahankhatch/scikit-learn,eickenberg/scikit-learn,DSLituiev/scikit-learn,arahuja/scikit-learn,Sentient07/scikit-learn,RomainBrault/scikit-learn,khkaminska/scikit-learn,rishikksh20/scikit-learn,yyjiang/scikit-learn,mjgrav2001/scikit-learn,ldirer/scikit-learn,zaxtax/scikit-learn,mayblue9/scikit-learn,meduz/scikit-learn,PatrickChrist/scikit-learn,icdishb/scikit-learn,massmutual/scikit-learn,pianomania/scikit-learn,ChanderG/scikit-learn,Myasuka/scikit-learn,chrsrds/scikit-learn,madjelan/scikit-learn,sergeyf/scikit-learn,fabianp/scikit-learn,IndraVikas/scikit-learn,iismd17/scikit-learn,iismd17/scikit-learn,harshaneelhg/scikit-learn,terkkila/scikit-learn,scikit-learn/scikit-learn,vinayak-mehta/scikit-learn,mugizico/scikit-learn,rexshihaoren/scikit-learn,xuewei4d/scikit-learn,poryfly/scikit-learn,phdowling/scikit-learn,elkingtonmcb/scikit-learn,bigdataelephants/scikit-learn,kylerbrown/scikit-learn,arjoly/scikit-learn,potash/scikit-learn,MatthieuBizien/scikit-learn,ngoix/OCRF,pompiduskus/scikit-learn,bhargav/scikit-learn,lin-credible/scikit-learn,joshloyal/scikit-learn,ElDeveloper/scikit-learn,ZENGXH/scikit-learn,adamgreenhall/scikit-learn,fbagirov/scikit-learn,clemkoa/scikit-learn,PrashntS/scikit-learn,rohanp/scikit-learn,adamgreenhall/scikit-learn,RomainBrault/scikit-learn,joernhees/scikit-learn,petosegan/scikit-learn,vybstat/scikit-learn,gclenaghan/scikit-learn,espg/scikit-learn,jmetzen/scikit-learn,xiaoxiamii/scikit-learn,cwu2011/scikit-learn,cainiaocome/scikit-learn,aetilley/scikit-learn,mblondel/scikit-learn,wlamond/scikit-learn,IshankGulati/scikit-learn,ngoix/OCRF,liberatorqjw/scikit-learn,costypetrisor/scikit-learn,alvarofierroclavero/scikit-learn,MatthieuBizien/scikit-learn,sumspr/scikit-learn,mattilyra/scikit-learn,ilyes14/scikit-learn,RayMick/scikit-learn,equialgo/scikit-learn,mrshu/scikit-learn,mayblue9/scikit-learn,victorbergelin/scikit-learn,rajat1994/scikit-learn,fyffyt/scikit-learn,akionakamura/scikit-learn,kevin-intel/scikit-learn,toastedcornflakes/scikit-learn,xyguo/scikit-learn,mattilyra/scikit-learn,mugizico/scikit-learn,loli/semisupervisedforests,kashif/scikit-learn,jmschrei/scikit-learn,hugobowne/scikit-learn,nomadcube/scikit-learn,ogrisel/scikit-learn,mattilyra/scikit-learn,jblackburne/scikit-learn,jzt5132/scikit-learn,jzt5132/scikit-learn,nvoron23/scikit-learn,khkaminska/scikit-learn,sinhrks/scikit-learn,jm-begon/scikit-learn,ElDeveloper/scikit-learn,RayMick/scikit-learn,ky822/scikit-learn,michigraber/scikit-learn,hrjn/scikit-learn,TomDLT/scikit-learn,0asa/scikit-learn,ChanderG/scikit-learn,AlexandreAbraham/scikit-learn,h2educ/scikit-learn,xavierwu/scikit-learn,lbishal/scikit-learn,meduz/scikit-learn,Garrett-R/scikit-learn,xzh86/scikit-learn,r-mart/scikit-learn,robbymeals/scikit-learn,massmutual/scikit-learn,siutanwong/scikit-learn,waterponey/scikit-learn,Nyker510/scikit-learn,Akshay0724/scikit-learn,simon-pepin/scikit-learn,DonBeo/scikit-learn,sarahgrogan/scikit-learn,cybernet14/scikit-learn,zaxtax/scikit-learn,toastedcornflakes/scikit-learn,jorik041/scikit-learn,evgchz/scikit-learn,arahuja/scikit-learn,Akshay0724/scikit-learn,imaculate/scikit-learn,pnedunuri/scikit-learn,kaichogami/scikit-learn,nikitasingh981/scikit-learn,poryfly/scikit-learn,ycaihua/scikit-learn,gotomypc/scikit-learn,ycaihua/scikit-learn,kylerbrown/scikit-learn,fengzhyuan/scikit-learn,AnasGhrab/scikit-learn,pnedunuri/scikit-learn,rexshihaoren/scikit-learn,0x0all/scikit-learn,AlexRobson/scikit-learn,nvoron23/scikit-learn,TomDLT/scikit-learn,voxlol/scikit-learn,AlexanderFabisch/scikit-learn,UNR-AERIAL/scikit-learn,beepee14/scikit-learn,cwu2011/scikit-learn,mojoboss/scikit-learn,Achuth17/scikit-learn,bthirion/scikit-learn,bthirion/scikit-learn,jkarnows/scikit-learn,liyu1990/sklearn,anirudhjayaraman/scikit-learn,bikong2/scikit-learn,0asa/scikit-learn,xzh86/scikit-learn,vinayak-mehta/scikit-learn,dingocuster/scikit-learn,jlegendary/scikit-learn,wazeerzulfikar/scikit-learn,anntzer/scikit-learn,abhishekgahlot/scikit-learn,bigdataelephants/scikit-learn,IssamLaradji/scikit-learn,Aasmi/scikit-learn,huzq/scikit-learn,untom/scikit-learn,ssaeger/scikit-learn,jjx02230808/project0223,mattilyra/scikit-learn,Obus/scikit-learn,etkirsch/scikit-learn,rajat1994/scikit-learn,jseabold/scikit-learn,MechCoder/scikit-learn,PatrickOReilly/scikit-learn,themrmax/scikit-learn,Srisai85/scikit-learn,AlexanderFabisch/scikit-learn,larsmans/scikit-learn,hitszxp/scikit-learn,altairpearl/scikit-learn,depet/scikit-learn,mhue/scikit-learn,lucidfrontier45/scikit-learn,untom/scikit-learn,Windy-Ground/scikit-learn,ishanic/scikit-learn,kevin-intel/scikit-learn,MartinSavc/scikit-learn,xavierwu/scikit-learn,glouppe/scikit-learn,larsmans/scikit-learn,dsullivan7/scikit-learn,PatrickOReilly/scikit-learn,trungnt13/scikit-learn,alexeyum/scikit-learn,zorojean/scikit-learn,marcocaccin/scikit-learn,yonglehou/scikit-learn,vortex-ape/scikit-learn,shangwuhencc/scikit-learn,rsivapr/scikit-learn,equialgo/scikit-learn,shenzebang/scikit-learn,shusenl/scikit-learn,waterponey/scikit-learn,fabioticconi/scikit-learn,mehdidc/scikit-learn,hitszxp/scikit-learn,nesterione/scikit-learn,aminert/scikit-learn,jm-begon/scikit-learn,jakirkham/scikit-learn,Nyker510/scikit-learn,poryfly/scikit-learn,ZENGXH/scikit-learn,PatrickChrist/scikit-learn,shusenl/scikit-learn,joernhees/scikit-learn,rahul-c1/scikit-learn,eickenberg/scikit-learn,liyu1990/sklearn,ZENGXH/scikit-learn,0x0all/scikit-learn,mfjb/scikit-learn,ChanChiChoi/scikit-learn,RachitKansal/scikit-learn,ilyes14/scikit-learn,anirudhjayaraman/scikit-learn,pythonvietnam/scikit-learn,giorgiop/scikit-learn,sumspr/scikit-learn,scikit-learn/scikit-learn,andaag/scikit-learn,nesterione/scikit-learn,xavierwu/scikit-learn,LiaoPan/scikit-learn,plissonf/scikit-learn,chrsrds/scikit-learn,BiaDarkia/scikit-learn,yunfeilu/scikit-learn,jakobworldpeace/scikit-learn,jmetzen/scikit-learn,waterponey/scikit-learn,dingocuster/scikit-learn,nhejazi/scikit-learn,Jimmy-Morzaria/scikit-learn,yyjiang/scikit-learn,CVML/scikit-learn,jseabold/scikit-learn,belltailjp/scikit-learn,imaculate/scikit-learn,ankurankan/scikit-learn,carrillo/scikit-learn,shangwuhencc/scikit-learn,zorroblue/scikit-learn,TomDLT/scikit-learn,fengzhyuan/scikit-learn,cybernet14/scikit-learn,abhishekkrthakur/scikit-learn,yonglehou/scikit-learn,mattilyra/scikit-learn,AIML/scikit-learn,mayblue9/scikit-learn,ephes/scikit-learn,arabenjamin/scikit-learn,dsquareindia/scikit-learn,depet/scikit-learn,manhhomienbienthuy/scikit-learn,kevin-intel/scikit-learn,manashmndl/scikit-learn,nrhine1/scikit-learn,Clyde-fare/scikit-learn,yonglehou/scikit-learn,ashhher3/scikit-learn,mjudsp/Tsallis,deepesch/scikit-learn,kagayakidan/scikit-learn,anirudhjayaraman/scikit-learn,ivannz/scikit-learn,RPGOne/scikit-learn,arabenjamin/scikit-learn,nvoron23/scikit-learn,Clyde-fare/scikit-learn,clemkoa/scikit-learn,pompiduskus/scikit-learn,tomlof/scikit-learn,Vimos/scikit-learn,sarahgrogan/scikit-learn,fzalkow/scikit-learn,MohammedWasim/scikit-learn,eg-zhang/scikit-learn,etkirsch/scikit-learn,mikebenfield/scikit-learn,treycausey/scikit-learn,thilbern/scikit-learn,3manuek/scikit-learn,mxjl620/scikit-learn,mfjb/scikit-learn,qifeigit/scikit-learn,voxlol/scikit-learn,AlexandreAbraham/scikit-learn,kagayakidan/scikit-learn,glemaitre/scikit-learn,maheshakya/scikit-learn,alexsavio/scikit-learn,Clyde-fare/scikit-learn,pypot/scikit-learn,ycaihua/scikit-learn,mojoboss/scikit-learn,huobaowangxi/scikit-learn,ZenDevelopmentSystems/scikit-learn,wzbozon/scikit-learn,B3AU/waveTree,siutanwong/scikit-learn,nesterione/scikit-learn,betatim/scikit-learn,plissonf/scikit-learn,rahul-c1/scikit-learn,zhenv5/scikit-learn,xiaoxiamii/scikit-learn,evgchz/scikit-learn,nelson-liu/scikit-learn,robin-lai/scikit-learn,aflaxman/scikit-learn,iismd17/scikit-learn,glemaitre/scikit-learn,fredhusser/scikit-learn,zuku1985/scikit-learn,idlead/scikit-learn,bthirion/scikit-learn,loli/semisupervisedforests,vortex-ape/scikit-learn,pratapvardhan/scikit-learn,ningchi/scikit-learn,sonnyhu/scikit-learn,jorge2703/scikit-learn,cybernet14/scikit-learn,nikitasingh981/scikit-learn,Windy-Ground/scikit-learn,shikhardb/scikit-learn,appapantula/scikit-learn,abhishekkrthakur/scikit-learn,fabianp/scikit-learn,B3AU/waveTree,DonBeo/scikit-learn,trankmichael/scikit-learn,zorroblue/scikit-learn,JeanKossaifi/scikit-learn,kashif/scikit-learn,spallavolu/scikit-learn,mhdella/scikit-learn,heli522/scikit-learn,ldirer/scikit-learn,AlexRobson/scikit-learn,ashhher3/scikit-learn,michigraber/scikit-learn,ssaeger/scikit-learn,arjoly/scikit-learn,nikitasingh981/scikit-learn,zhenv5/scikit-learn,thientu/scikit-learn,espg/scikit-learn,Djabbz/scikit-learn,AlexandreAbraham/scikit-learn,jaidevd/scikit-learn,mblondel/scikit-learn,lazywei/scikit-learn,ssaeger/scikit-learn,BiaDarkia/scikit-learn,henrykironde/scikit-learn,glemaitre/scikit-learn,djgagne/scikit-learn,qifeigit/scikit-learn,elkingtonmcb/scikit-learn,ZENGXH/scikit-learn,vivekmishra1991/scikit-learn,Aasmi/scikit-learn,fabianp/scikit-learn,lesteve/scikit-learn,LohithBlaze/scikit-learn,belltailjp/scikit-learn,phdowling/scikit-learn,pythonvietnam/scikit-learn,Achuth17/scikit-learn,Jimmy-Morzaria/scikit-learn,HolgerPeters/scikit-learn,sanketloke/scikit-learn,Srisai85/scikit-learn,MechCoder/scikit-learn,jm-begon/scikit-learn,maheshakya/scikit-learn,simon-pepin/scikit-learn,kevin-intel/scikit-learn,manashmndl/scikit-learn,dingocuster/scikit-learn,fengzhyuan/scikit-learn,giorgiop/scikit-learn,vibhorag/scikit-learn,ningchi/scikit-learn,loli/semisupervisedforests,HolgerPeters/scikit-learn,kmike/scikit-learn,jblackburne/scikit-learn,walterreade/scikit-learn,ivannz/scikit-learn,mattgiguere/scikit-learn,lenovor/scikit-learn,Titan-C/scikit-learn,untom/scikit-learn,betatim/scikit-learn,bikong2/scikit-learn,glennq/scikit-learn,hrjn/scikit-learn,voxlol/scikit-learn,shikhardb/scikit-learn,fabioticconi/scikit-learn,schets/scikit-learn,shikhardb/scikit-learn,florian-f/sklearn,amueller/scikit-learn,AlexanderFabisch/scikit-learn,quheng/scikit-learn,Vimos/scikit-learn,Akshay0724/scikit-learn,beepee14/scikit-learn,h2educ/scikit-learn,fredhusser/scikit-learn,h2educ/scikit-learn,robin-lai/scikit-learn,MohammedWasim/scikit-learn,jm-begon/scikit-learn,fzalkow/scikit-learn,henridwyer/scikit-learn,treycausey/scikit-learn,ltiao/scikit-learn,hsiaoyi0504/scikit-learn,rishikksh20/scikit-learn,costypetrisor/scikit-learn,waterponey/scikit-learn,procoder317/scikit-learn,ilo10/scikit-learn,luo66/scikit-learn,lazywei/scikit-learn,RachitKansal/scikit-learn,Lawrence-Liu/scikit-learn,pianomania/scikit-learn,abimannans/scikit-learn,huobaowangxi/scikit-learn,xzh86/scikit-learn,ChanChiChoi/scikit-learn,yanlend/scikit-learn,wazeerzulfikar/scikit-learn,jakobworldpeace/scikit-learn,AnasGhrab/scikit-learn,abhishekgahlot/scikit-learn,tdhopper/scikit-learn,lucidfrontier45/scikit-learn,tomlof/scikit-learn,anntzer/scikit-learn,sergeyf/scikit-learn,shahankhatch/scikit-learn,0asa/scikit-learn,andaag/scikit-learn,andaag/scikit-learn,krez13/scikit-learn,espg/scikit-learn,JeanKossaifi/scikit-learn,Nyker510/scikit-learn,Fireblend/scikit-learn,qifeigit/scikit-learn,Obus/scikit-learn,bnaul/scikit-learn,jlegendary/scikit-learn,marcocaccin/scikit-learn,MartinSavc/scikit-learn,DSLituiev/scikit-learn,madjelan/scikit-learn,krez13/scikit-learn,zihua/scikit-learn,russel1237/scikit-learn,alexeyum/scikit-learn,ZenDevelopmentSystems/scikit-learn,Garrett-R/scikit-learn,jmetzen/scikit-learn,cl4rke/scikit-learn,bnaul/scikit-learn,pratapvardhan/scikit-learn,nomadcube/scikit-learn,etkirsch/scikit-learn,frank-tancf/scikit-learn,anntzer/scikit-learn,nmayorov/scikit-learn,MohammedWasim/scikit-learn,evgchz/scikit-learn,samuel1208/scikit-learn,massmutual/scikit-learn,glouppe/scikit-learn,akionakamura/scikit-learn,larsmans/scikit-learn,LohithBlaze/scikit-learn,sanketloke/scikit-learn,0x0all/scikit-learn,glouppe/scikit-learn,mikebenfield/scikit-learn,aetilley/scikit-learn,florian-f/sklearn,IshankGulati/scikit-learn,cwu2011/scikit-learn,raghavrv/scikit-learn,MohammedWasim/scikit-learn,wlamond/scikit-learn,mjudsp/Tsallis,aflaxman/scikit-learn,AnasGhrab/scikit-learn,imaculate/scikit-learn,macks22/scikit-learn,rajat1994/scikit-learn,harshaneelhg/scikit-learn,simon-pepin/scikit-learn,cybernet14/scikit-learn,mehdidc/scikit-learn,lin-credible/scikit-learn,vermouthmjl/scikit-learn,hainm/scikit-learn,vinayak-mehta/scikit-learn,xubenben/scikit-learn,luo66/scikit-learn,trungnt13/scikit-learn,henridwyer/scikit-learn,andrewnc/scikit-learn,fbagirov/scikit-learn,lin-credible/scikit-learn,BiaDarkia/scikit-learn,UNR-AERIAL/scikit-learn,jorik041/scikit-learn,Titan-C/scikit-learn,AIML/scikit-learn,B3AU/waveTree,poryfly/scikit-learn,hugobowne/scikit-learn,alvarofierroclavero/scikit-learn,equialgo/scikit-learn,maheshakya/scikit-learn,mwv/scikit-learn,ilo10/scikit-learn,vermouthmjl/scikit-learn,vortex-ape/scikit-learn,dsquareindia/scikit-learn,victorbergelin/scikit-learn,smartscheduling/scikit-learn-categorical-tree,zihua/scikit-learn,mxjl620/scikit-learn,AnasGhrab/scikit-learn,btabibian/scikit-learn,moutai/scikit-learn,davidgbe/scikit-learn,bigdataelephants/scikit-learn,bikong2/scikit-learn,aewhatley/scikit-learn,JosmanPS/scikit-learn,eickenberg/scikit-learn,yask123/scikit-learn,mlyundin/scikit-learn,ndingwall/scikit-learn,Obus/scikit-learn,massmutual/scikit-learn,nrhine1/scikit-learn,Sentient07/scikit-learn,heli522/scikit-learn,kmike/scikit-learn,0x0all/scikit-learn,mattgiguere/scikit-learn,nmayorov/scikit-learn,khkaminska/scikit-learn,JsNoNo/scikit-learn,RPGOne/scikit-learn,MatthieuBizien/scikit-learn,arahuja/scikit-learn,MartinSavc/scikit-learn,pypot/scikit-learn,smartscheduling/scikit-learn-categorical-tree,TomDLT/scikit-learn,henridwyer/scikit-learn,liyu1990/sklearn,CforED/Machine-Learning,tmhm/scikit-learn,yunfeilu/scikit-learn,joshloyal/scikit-learn,vybstat/scikit-learn,betatim/scikit-learn,hitszxp/scikit-learn,zuku1985/scikit-learn,hsiaoyi0504/scikit-learn,gclenaghan/scikit-learn,billy-inn/scikit-learn,lesteve/scikit-learn,vibhorag/scikit-learn,mfjb/scikit-learn,bhargav/scikit-learn,pkruskal/scikit-learn,kjung/scikit-learn,betatim/scikit-learn,thilbern/scikit-learn,JPFrancoia/scikit-learn,ClimbsRocks/scikit-learn,PrashntS/scikit-learn,loli/sklearn-ensembletrees,ahoyosid/scikit-learn,luo66/scikit-learn,0asa/scikit-learn,equialgo/scikit-learn,potash/scikit-learn,pv/scikit-learn,belltailjp/scikit-learn,xwolf12/scikit-learn,bhargav/scikit-learn,pompiduskus/scikit-learn,icdishb/scikit-learn,quheng/scikit-learn,zuku1985/scikit-learn,jblackburne/scikit-learn,maheshakya/scikit-learn,heli522/scikit-learn,Nyker510/scikit-learn,0asa/scikit-learn,hlin117/scikit-learn,jereze/scikit-learn,spallavolu/scikit-learn,henridwyer/scikit-learn,RachitKansal/scikit-learn,f3r/scikit-learn,jereze/scikit-learn,jpautom/scikit-learn,chrisburr/scikit-learn,robbymeals/scikit-learn,IndraVikas/scikit-learn,ankurankan/scikit-learn,dsullivan7/scikit-learn,MartinDelzant/scikit-learn,theoryno3/scikit-learn,bikong2/scikit-learn,anirudhjayaraman/scikit-learn,tawsifkhan/scikit-learn,loli/sklearn-ensembletrees,jakobworldpeace/scikit-learn,lenovor/scikit-learn,NunoEdgarGub1/scikit-learn,lucidfrontier45/scikit-learn,NunoEdgarGub1/scikit-learn,vivekmishra1991/scikit-learn,nesterione/scikit-learn,jkarnows/scikit-learn,murali-munna/scikit-learn,wlamond/scikit-learn,florian-f/sklearn,liangz0707/scikit-learn,alvarofierroclavero/scikit-learn,krez13/scikit-learn,davidgbe/scikit-learn,schets/scikit-learn,fredhusser/scikit-learn,herilalaina/scikit-learn,Myasuka/scikit-learn,walterreade/scikit-learn,tmhm/scikit-learn,vshtanko/scikit-learn,arahuja/scikit-learn,r-mart/scikit-learn,mjudsp/Tsallis,yanlend/scikit-learn,IssamLaradji/scikit-learn,hainm/scikit-learn,meduz/scikit-learn,kjung/scikit-learn,mlyundin/scikit-learn,rvraghav93/scikit-learn,evgchz/scikit-learn,altairpearl/scikit-learn,fabioticconi/scikit-learn,fengzhyuan/scikit-learn,ky822/scikit-learn,glouppe/scikit-learn,wzbozon/scikit-learn,vigilv/scikit-learn,maheshakya/scikit-learn,deepesch/scikit-learn,costypetrisor/scikit-learn,moutai/scikit-learn,adamgreenhall/scikit-learn,zhenv5/scikit-learn,samzhang111/scikit-learn,idlead/scikit-learn,harshaneelhg/scikit-learn,stylianos-kampakis/scikit-learn,OshynSong/scikit-learn,ndingwall/scikit-learn,ClimbsRocks/scikit-learn,Titan-C/scikit-learn,RomainBrault/scikit-learn,Djabbz/scikit-learn,florian-f/sklearn,stylianos-kampakis/scikit-learn,PatrickChrist/scikit-learn,RachitKansal/scikit-learn,bhargav/scikit-learn,roxyboy/scikit-learn,davidgbe/scikit-learn,thilbern/scikit-learn,murali-munna/scikit-learn,olologin/scikit-learn,NunoEdgarGub1/scikit-learn,jjx02230808/project0223,trankmichael/scikit-learn,samzhang111/scikit-learn,zihua/scikit-learn,mrshu/scikit-learn,aminert/scikit-learn,sonnyhu/scikit-learn,liangz0707/scikit-learn,tmhm/scikit-learn,arjoly/scikit-learn,Adai0808/scikit-learn,nomadcube/scikit-learn,xyguo/scikit-learn,kmike/scikit-learn,eg-zhang/scikit-learn,JsNoNo/scikit-learn,hrjn/scikit-learn,Fireblend/scikit-learn,MartinDelzant/scikit-learn,pypot/scikit-learn,r-mart/scikit-learn,aflaxman/scikit-learn,shusenl/scikit-learn,AlexanderFabisch/scikit-learn,RayMick/scikit-learn,shahankhatch/scikit-learn,cainiaocome/scikit-learn,OshynSong/scikit-learn,jaidevd/scikit-learn,russel1237/scikit-learn,carrillo/scikit-learn,JeanKossaifi/scikit-learn,sergeyf/scikit-learn,kylerbrown/scikit-learn,mjgrav2001/scikit-learn,terkkila/scikit-learn,ahoyosid/scikit-learn,cauchycui/scikit-learn,olologin/scikit-learn,JeanKossaifi/scikit-learn,clemkoa/scikit-learn,IndraVikas/scikit-learn,DSLituiev/scikit-learn,shenzebang/scikit-learn,mrshu/scikit-learn,ElDeveloper/scikit-learn,eickenberg/scikit-learn,btabibian/scikit-learn,theoryno3/scikit-learn,JsNoNo/scikit-learn,Sentient07/scikit-learn,wanggang3333/scikit-learn,rahuldhote/scikit-learn,mhdella/scikit-learn,saiwing-yeung/scikit-learn,jakirkham/scikit-learn,etkirsch/scikit-learn,wanggang3333/scikit-learn,sanketloke/scikit-learn,huzq/scikit-learn,shenzebang/scikit-learn,mojoboss/scikit-learn,nmayorov/scikit-learn,schets/scikit-learn,potash/scikit-learn,glennq/scikit-learn,ahoyosid/scikit-learn,alvarofierroclavero/scikit-learn,mblondel/scikit-learn,YinongLong/scikit-learn,lbishal/scikit-learn,toastedcornflakes/scikit-learn,yunfeilu/scikit-learn,depet/scikit-learn,pompiduskus/scikit-learn,IshankGulati/scikit-learn,rrohan/scikit-learn,trungnt13/scikit-learn,ngoix/OCRF,samzhang111/scikit-learn,mrshu/scikit-learn,tdhopper/scikit-learn,ngoix/OCRF,wazeerzulfikar/scikit-learn,Vimos/scikit-learn,hdmetor/scikit-learn,Aasmi/scikit-learn,scikit-learn/scikit-learn,michigraber/scikit-learn,andaag/scikit-learn,cl4rke/scikit-learn,xyguo/scikit-learn,ephes/scikit-learn,ningchi/scikit-learn,mhue/scikit-learn,nvoron23/scikit-learn,rvraghav93/scikit-learn,frank-tancf/scikit-learn,ltiao/scikit-learn,pv/scikit-learn,mjgrav2001/scikit-learn,untom/scikit-learn,ankurankan/scikit-learn,jakobworldpeace/scikit-learn,aminert/scikit-learn,shyamalschandra/scikit-learn,ZenDevelopmentSystems/scikit-learn,hainm/scikit-learn,hdmetor/scikit-learn,JPFrancoia/scikit-learn,ivannz/scikit-learn,LohithBlaze/scikit-learn,kmike/scikit-learn,466152112/scikit-learn,shangwuhencc/scikit-learn,ycaihua/scikit-learn,ChanderG/scikit-learn,amueller/scikit-learn,tawsifkhan/scikit-learn,AIML/scikit-learn,depet/scikit-learn,tosolveit/scikit-learn,manhhomienbienthuy/scikit-learn,zihua/scikit-learn,tosolveit/scikit-learn,Fireblend/scikit-learn,vigilv/scikit-learn,Lawrence-Liu/scikit-learn,LiaoPan/scikit-learn,jorik041/scikit-learn,ishanic/scikit-learn,LiaoPan/scikit-learn,roxyboy/scikit-learn,hsuantien/scikit-learn,bnaul/scikit-learn,jorik041/scikit-learn,iismd17/scikit-learn,kashif/scikit-learn,huobaowangxi/scikit-learn,aabadie/scikit-learn,lazywei/scikit-learn,phdowling/scikit-learn,nhejazi/scikit-learn,abhishekgahlot/scikit-learn,jmetzen/scikit-learn,thientu/scikit-learn,BiaDarkia/scikit-learn,fyffyt/scikit-learn,zorojean/scikit-learn,Windy-Ground/scikit-learn,ashhher3/scikit-learn,tdhopper/scikit-learn,mrshu/scikit-learn,moutai/scikit-learn,kagayakidan/scikit-learn,roxyboy/scikit-learn,rsivapr/scikit-learn,mhue/scikit-learn,joernhees/scikit-learn,sumspr/scikit-learn,xiaoxiamii/scikit-learn,jakirkham/scikit-learn,jorge2703/scikit-learn,kaichogami/scikit-learn,NelisVerhoef/scikit-learn,rahuldhote/scikit-learn,ElDeveloper/scikit-learn,treycausey/scikit-learn,pythonvietnam/scikit-learn,petosegan/scikit-learn,rvraghav93/scikit-learn,fbagirov/scikit-learn,aewhatley/scikit-learn,icdishb/scikit-learn,florian-f/sklearn,Titan-C/scikit-learn,cainiaocome/scikit-learn,HolgerPeters/scikit-learn,dhruv13J/scikit-learn,andrewnc/scikit-learn,zorroblue/scikit-learn,kjung/scikit-learn,cauchycui/scikit-learn,manhhomienbienthuy/scikit-learn,rahuldhote/scikit-learn,mehdidc/scikit-learn,amueller/scikit-learn,jkarnows/scikit-learn,nelson-liu/scikit-learn,idlead/scikit-learn,wzbozon/scikit-learn,ahoyosid/scikit-learn,idlead/scikit-learn,sinhrks/scikit-learn,theoryno3/scikit-learn,mhdella/scikit-learn,abhishekkrthakur/scikit-learn,yanlend/scikit-learn,justincassidy/scikit-learn,aminert/scikit-learn,herilalaina/scikit-learn,jayflo/scikit-learn,f3r/scikit-learn,UNR-AERIAL/scikit-learn,joshloyal/scikit-learn,YinongLong/scikit-learn,huobaowangxi/scikit-learn,MartinDelzant/scikit-learn,dsquareindia/scikit-learn,Myasuka/scikit-learn,HolgerPeters/scikit-learn,anurag313/scikit-learn,giorgiop/scikit-learn,jaidevd/scikit-learn,billy-inn/scikit-learn,russel1237/scikit-learn,kashif/scikit-learn,MechCoder/scikit-learn,deepesch/scikit-learn,robbymeals/scikit-learn,dhruv13J/scikit-learn,hitszxp/scikit-learn,dhruv13J/scikit-learn,Adai0808/scikit-learn,lesteve/scikit-learn,rahul-c1/scikit-learn,ankurankan/scikit-learn,andrewnc/scikit-learn,UNR-AERIAL/scikit-learn,larsmans/scikit-learn,tdhopper/scikit-learn,saiwing-yeung/scikit-learn,jseabold/scikit-learn,mikebenfield/scikit-learn,shenzebang/scikit-learn,hitszxp/scikit-learn,tosolveit/scikit-learn,mugizico/scikit-learn,lazywei/scikit-learn,manashmndl/scikit-learn,lenovor/scikit-learn,Fireblend/scikit-learn,pypot/scikit-learn,fyffyt/scikit-learn,pnedunuri/scikit-learn,jpautom/scikit-learn,mxjl620/scikit-learn,djgagne/scikit-learn,nelson-liu/scikit-learn,elkingtonmcb/scikit-learn,glennq/scikit-learn,vigilv/scikit-learn,kjung/scikit-learn,r-mart/scikit-learn,nrhine1/scikit-learn,arabenjamin/scikit-learn,gotomypc/scikit-learn,sinhrks/scikit-learn,saiwing-yeung/scikit-learn,rahuldhote/scikit-learn,PatrickOReilly/scikit-learn,raghavrv/scikit-learn,f3r/scikit-learn,thientu/scikit-learn,joshloyal/scikit-learn,Lawrence-Liu/scikit-learn,LohithBlaze/scikit-learn,marcocaccin/scikit-learn,liangz0707/scikit-learn,cauchycui/scikit-learn,ZenDevelopmentSystems/scikit-learn,bigdataelephants/scikit-learn,devanshdalal/scikit-learn,JosmanPS/scikit-learn,liyu1990/sklearn,trankmichael/scikit-learn,jseabold/scikit-learn,JosmanPS/scikit-learn,andrewnc/scikit-learn,pratapvardhan/scikit-learn,ogrisel/scikit-learn,zaxtax/scikit-learn,devanshdalal/scikit-learn,vermouthmjl/scikit-learn,aewhatley/scikit-learn,jpautom/scikit-learn,zorojean/scikit-learn,ldirer/scikit-learn,tomlof/scikit-learn
import numpy as np import scipy.sparse from abc import ABCMeta, abstractmethod from ..base import BaseLibSVM class SparseBaseLibSVM(BaseLibSVM): __metaclass__ = ABCMeta @abstractmethod def __init__(self, impl, kernel, degree, gamma, coef0, tol, C, nu, epsilon, shrinking, probability, cache_size, class_weight, verbose): assert kernel in self._sparse_kernels, \ "kernel should be one of %s, "\ "%s was given." % (self._kernel_types, kernel) super(SparseBaseLibSVM, self).__init__(impl, kernel, degree, gamma, coef0, tol, C, nu, epsilon, shrinking, probability, cache_size, True, class_weight, verbose) def fit(self, X, y, sample_weight=None): X = scipy.sparse.csr_matrix(X, dtype=np.float64) - return super(SparseBaseLibSVM, self).fit(X, y, sample_weight) + return super(SparseBaseLibSVM, self).fit(X, y, + sample_weight=sample_weight)
FIX sparse OneClassSVM was using the wrong parameter
## Code Before: import numpy as np import scipy.sparse from abc import ABCMeta, abstractmethod from ..base import BaseLibSVM class SparseBaseLibSVM(BaseLibSVM): __metaclass__ = ABCMeta @abstractmethod def __init__(self, impl, kernel, degree, gamma, coef0, tol, C, nu, epsilon, shrinking, probability, cache_size, class_weight, verbose): assert kernel in self._sparse_kernels, \ "kernel should be one of %s, "\ "%s was given." % (self._kernel_types, kernel) super(SparseBaseLibSVM, self).__init__(impl, kernel, degree, gamma, coef0, tol, C, nu, epsilon, shrinking, probability, cache_size, True, class_weight, verbose) def fit(self, X, y, sample_weight=None): X = scipy.sparse.csr_matrix(X, dtype=np.float64) return super(SparseBaseLibSVM, self).fit(X, y, sample_weight) ## Instruction: FIX sparse OneClassSVM was using the wrong parameter ## Code After: import numpy as np import scipy.sparse from abc import ABCMeta, abstractmethod from ..base import BaseLibSVM class SparseBaseLibSVM(BaseLibSVM): __metaclass__ = ABCMeta @abstractmethod def __init__(self, impl, kernel, degree, gamma, coef0, tol, C, nu, epsilon, shrinking, probability, cache_size, class_weight, verbose): assert kernel in self._sparse_kernels, \ "kernel should be one of %s, "\ "%s was given." % (self._kernel_types, kernel) super(SparseBaseLibSVM, self).__init__(impl, kernel, degree, gamma, coef0, tol, C, nu, epsilon, shrinking, probability, cache_size, True, class_weight, verbose) def fit(self, X, y, sample_weight=None): X = scipy.sparse.csr_matrix(X, dtype=np.float64) return super(SparseBaseLibSVM, self).fit(X, y, sample_weight=sample_weight)
... X = scipy.sparse.csr_matrix(X, dtype=np.float64) return super(SparseBaseLibSVM, self).fit(X, y, sample_weight=sample_weight) ...
edd4cfd5cf4102ab77e889c680306f25280e6165
lingcod/bookmarks/forms.py
lingcod/bookmarks/forms.py
from lingcod.features.forms import FeatureForm from lingcod.bookmarks.models import Bookmark from django import forms class BookmarkForm(FeatureForm): name = forms.CharField(label='Bookmark Name') latitude = forms.FloatField(widget=forms.HiddenInput()) longitude = forms.FloatField(widget=forms.HiddenInput()) altitude = forms.FloatField(widget=forms.HiddenInput()) heading = forms.FloatField(widget=forms.HiddenInput()) tilt = forms.FloatField(widget=forms.HiddenInput()) roll = forms.FloatField(widget=forms.HiddenInput()) altitudeMode = forms.FloatField(widget=forms.HiddenInput()) publicstate = forms.CharField(widget=forms.HiddenInput()) class Meta(FeatureForm.Meta): model = Bookmark
from lingcod.features.forms import FeatureForm from lingcod.bookmarks.models import Bookmark from django import forms class BookmarkForm(FeatureForm): name = forms.CharField(label='Bookmark Name') latitude = forms.FloatField(widget=forms.HiddenInput()) longitude = forms.FloatField(widget=forms.HiddenInput()) altitude = forms.FloatField(widget=forms.HiddenInput()) heading = forms.FloatField(widget=forms.HiddenInput()) tilt = forms.FloatField(widget=forms.HiddenInput()) roll = forms.FloatField(widget=forms.HiddenInput()) altitudeMode = forms.FloatField(widget=forms.HiddenInput()) publicstate = forms.CharField(widget=forms.HiddenInput()) ip = forms.CharField(widget=forms.HiddenInput()) class Meta(FeatureForm.Meta): model = Bookmark
Hide IP from input form
Hide IP from input form
Python
bsd-3-clause
Alwnikrotikz/marinemap,google-code-export/marinemap,google-code-export/marinemap,Alwnikrotikz/marinemap,Alwnikrotikz/marinemap,Alwnikrotikz/marinemap,google-code-export/marinemap,google-code-export/marinemap
from lingcod.features.forms import FeatureForm from lingcod.bookmarks.models import Bookmark from django import forms class BookmarkForm(FeatureForm): name = forms.CharField(label='Bookmark Name') latitude = forms.FloatField(widget=forms.HiddenInput()) longitude = forms.FloatField(widget=forms.HiddenInput()) altitude = forms.FloatField(widget=forms.HiddenInput()) heading = forms.FloatField(widget=forms.HiddenInput()) tilt = forms.FloatField(widget=forms.HiddenInput()) roll = forms.FloatField(widget=forms.HiddenInput()) altitudeMode = forms.FloatField(widget=forms.HiddenInput()) publicstate = forms.CharField(widget=forms.HiddenInput()) + ip = forms.CharField(widget=forms.HiddenInput()) class Meta(FeatureForm.Meta): model = Bookmark
Hide IP from input form
## Code Before: from lingcod.features.forms import FeatureForm from lingcod.bookmarks.models import Bookmark from django import forms class BookmarkForm(FeatureForm): name = forms.CharField(label='Bookmark Name') latitude = forms.FloatField(widget=forms.HiddenInput()) longitude = forms.FloatField(widget=forms.HiddenInput()) altitude = forms.FloatField(widget=forms.HiddenInput()) heading = forms.FloatField(widget=forms.HiddenInput()) tilt = forms.FloatField(widget=forms.HiddenInput()) roll = forms.FloatField(widget=forms.HiddenInput()) altitudeMode = forms.FloatField(widget=forms.HiddenInput()) publicstate = forms.CharField(widget=forms.HiddenInput()) class Meta(FeatureForm.Meta): model = Bookmark ## Instruction: Hide IP from input form ## Code After: from lingcod.features.forms import FeatureForm from lingcod.bookmarks.models import Bookmark from django import forms class BookmarkForm(FeatureForm): name = forms.CharField(label='Bookmark Name') latitude = forms.FloatField(widget=forms.HiddenInput()) longitude = forms.FloatField(widget=forms.HiddenInput()) altitude = forms.FloatField(widget=forms.HiddenInput()) heading = forms.FloatField(widget=forms.HiddenInput()) tilt = forms.FloatField(widget=forms.HiddenInput()) roll = forms.FloatField(widget=forms.HiddenInput()) altitudeMode = forms.FloatField(widget=forms.HiddenInput()) publicstate = forms.CharField(widget=forms.HiddenInput()) ip = forms.CharField(widget=forms.HiddenInput()) class Meta(FeatureForm.Meta): model = Bookmark
// ... existing code ... publicstate = forms.CharField(widget=forms.HiddenInput()) ip = forms.CharField(widget=forms.HiddenInput()) class Meta(FeatureForm.Meta): // ... rest of the code ...
99f862b6c123b8c6d81e931254c061e64431bccc
pysingcells/logger.py
pysingcells/logger.py
""" Function related to logging """ # stp import import sys import logging # fief import from fief import filter_effective_parameters as fief log = logging.getLogger() @fief def setup_logging(options): log_level = 10 if "logging_level" in options else options["logging_level"] log.setLevel(log_level) handler = logging.StreamHandler(sys.stderr) formatter = logging.Formatter('%(levelname)s :: %(message)s') handler.setFormatter(formatter) handler.setLevel(log_level) log.addHandler(handler)
""" Function related to logging """ # stp import import sys import logging # fief import from fief import filter_effective_parameters as fief log = logging.getLogger() @fief def setup_logging(options): log_level = 10 if "logging_level" in options else options["logging_level"] log.setLevel(log_level) handler = logging.StreamHandler(sys.stderr) formatter = logging.Formatter('%(asctime)s :: %(levelname)s :: %(message)s') handler.setFormatter(formatter) handler.setLevel(log_level) log.addHandler(handler)
Add time in logging trace
Add time in logging trace
Python
mit
Fougere87/pysingcells
""" Function related to logging """ # stp import import sys import logging # fief import from fief import filter_effective_parameters as fief log = logging.getLogger() @fief def setup_logging(options): log_level = 10 if "logging_level" in options else options["logging_level"] log.setLevel(log_level) handler = logging.StreamHandler(sys.stderr) - formatter = logging.Formatter('%(levelname)s :: %(message)s') + formatter = logging.Formatter('%(asctime)s :: %(levelname)s :: %(message)s') handler.setFormatter(formatter) handler.setLevel(log_level) log.addHandler(handler)
Add time in logging trace
## Code Before: """ Function related to logging """ # stp import import sys import logging # fief import from fief import filter_effective_parameters as fief log = logging.getLogger() @fief def setup_logging(options): log_level = 10 if "logging_level" in options else options["logging_level"] log.setLevel(log_level) handler = logging.StreamHandler(sys.stderr) formatter = logging.Formatter('%(levelname)s :: %(message)s') handler.setFormatter(formatter) handler.setLevel(log_level) log.addHandler(handler) ## Instruction: Add time in logging trace ## Code After: """ Function related to logging """ # stp import import sys import logging # fief import from fief import filter_effective_parameters as fief log = logging.getLogger() @fief def setup_logging(options): log_level = 10 if "logging_level" in options else options["logging_level"] log.setLevel(log_level) handler = logging.StreamHandler(sys.stderr) formatter = logging.Formatter('%(asctime)s :: %(levelname)s :: %(message)s') handler.setFormatter(formatter) handler.setLevel(log_level) log.addHandler(handler)
# ... existing code ... handler = logging.StreamHandler(sys.stderr) formatter = logging.Formatter('%(asctime)s :: %(levelname)s :: %(message)s') # ... rest of the code ...
f2b4e4758ae60526e8bb5c57e9c45b0a1901fa14
wagtail/wagtailforms/edit_handlers.py
wagtail/wagtailforms/edit_handlers.py
from __future__ import absolute_import, unicode_literals from django.template.loader import render_to_string from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from wagtail.wagtailadmin.edit_handlers import EditHandler class BaseFormSubmissionsPanel(EditHandler): template = "wagtailforms/edit_handlers/form_responses_panel.html" def render(self): from .models import FormSubmission submissions = FormSubmission.objects.filter(page=self.instance) if not submissions: return '' return mark_safe(render_to_string(self.template, { 'self': self, 'submissions': submissions })) class FormSubmissionsPanel(object): def __init__(self, heading=None): self.heading = heading def bind_to_model(self, model): heading = _('{} submissions').format(model._meta.model_name) return type(str('_FormResponsesPanel'), (BaseFormSubmissionsPanel,), { 'model': model, 'heading': self.heading or heading, })
from __future__ import absolute_import, unicode_literals from django.template.loader import render_to_string from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from wagtail.wagtailadmin.edit_handlers import EditHandler class BaseFormSubmissionsPanel(EditHandler): template = "wagtailforms/edit_handlers/form_responses_panel.html" def render(self): from .models import FormSubmission submissions = FormSubmission.objects.filter(page=self.instance) if not submissions: return '' return mark_safe(render_to_string(self.template, { 'self': self, 'submissions': submissions })) class FormSubmissionsPanel(object): def __init__(self, heading=None): self.heading = heading def bind_to_model(self, model): heading = _('{} submissions').format(model.get_verbose_name()) return type(str('_FormResponsesPanel'), (BaseFormSubmissionsPanel,), { 'model': model, 'heading': self.heading or heading, })
Use verbose name for FormSubmissionsPanel heading
Use verbose name for FormSubmissionsPanel heading
Python
bsd-3-clause
rsalmaso/wagtail,takeflight/wagtail,torchbox/wagtail,rsalmaso/wagtail,FlipperPA/wagtail,zerolab/wagtail,jnns/wagtail,nimasmi/wagtail,kaedroho/wagtail,thenewguy/wagtail,zerolab/wagtail,mikedingjan/wagtail,nimasmi/wagtail,wagtail/wagtail,thenewguy/wagtail,nutztherookie/wagtail,takeflight/wagtail,chrxr/wagtail,jnns/wagtail,gasman/wagtail,rsalmaso/wagtail,chrxr/wagtail,kaedroho/wagtail,gasman/wagtail,thenewguy/wagtail,nilnvoid/wagtail,wagtail/wagtail,timorieber/wagtail,torchbox/wagtail,timorieber/wagtail,zerolab/wagtail,thenewguy/wagtail,zerolab/wagtail,nutztherookie/wagtail,chrxr/wagtail,wagtail/wagtail,Toshakins/wagtail,iansprice/wagtail,iansprice/wagtail,rsalmaso/wagtail,gasman/wagtail,zerolab/wagtail,mixxorz/wagtail,nealtodd/wagtail,jnns/wagtail,timorieber/wagtail,kaedroho/wagtail,mikedingjan/wagtail,takeflight/wagtail,FlipperPA/wagtail,kaedroho/wagtail,Toshakins/wagtail,mixxorz/wagtail,nutztherookie/wagtail,nilnvoid/wagtail,nealtodd/wagtail,FlipperPA/wagtail,nutztherookie/wagtail,rsalmaso/wagtail,torchbox/wagtail,gasman/wagtail,Toshakins/wagtail,mixxorz/wagtail,kaedroho/wagtail,thenewguy/wagtail,chrxr/wagtail,nealtodd/wagtail,torchbox/wagtail,nilnvoid/wagtail,mixxorz/wagtail,mikedingjan/wagtail,gasman/wagtail,FlipperPA/wagtail,nimasmi/wagtail,timorieber/wagtail,Toshakins/wagtail,wagtail/wagtail,iansprice/wagtail,mikedingjan/wagtail,nilnvoid/wagtail,mixxorz/wagtail,nealtodd/wagtail,iansprice/wagtail,wagtail/wagtail,jnns/wagtail,nimasmi/wagtail,takeflight/wagtail
from __future__ import absolute_import, unicode_literals from django.template.loader import render_to_string from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from wagtail.wagtailadmin.edit_handlers import EditHandler class BaseFormSubmissionsPanel(EditHandler): template = "wagtailforms/edit_handlers/form_responses_panel.html" def render(self): from .models import FormSubmission submissions = FormSubmission.objects.filter(page=self.instance) if not submissions: return '' return mark_safe(render_to_string(self.template, { 'self': self, 'submissions': submissions })) class FormSubmissionsPanel(object): def __init__(self, heading=None): self.heading = heading def bind_to_model(self, model): - heading = _('{} submissions').format(model._meta.model_name) + heading = _('{} submissions').format(model.get_verbose_name()) return type(str('_FormResponsesPanel'), (BaseFormSubmissionsPanel,), { 'model': model, 'heading': self.heading or heading, })
Use verbose name for FormSubmissionsPanel heading
## Code Before: from __future__ import absolute_import, unicode_literals from django.template.loader import render_to_string from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from wagtail.wagtailadmin.edit_handlers import EditHandler class BaseFormSubmissionsPanel(EditHandler): template = "wagtailforms/edit_handlers/form_responses_panel.html" def render(self): from .models import FormSubmission submissions = FormSubmission.objects.filter(page=self.instance) if not submissions: return '' return mark_safe(render_to_string(self.template, { 'self': self, 'submissions': submissions })) class FormSubmissionsPanel(object): def __init__(self, heading=None): self.heading = heading def bind_to_model(self, model): heading = _('{} submissions').format(model._meta.model_name) return type(str('_FormResponsesPanel'), (BaseFormSubmissionsPanel,), { 'model': model, 'heading': self.heading or heading, }) ## Instruction: Use verbose name for FormSubmissionsPanel heading ## Code After: from __future__ import absolute_import, unicode_literals from django.template.loader import render_to_string from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from wagtail.wagtailadmin.edit_handlers import EditHandler class BaseFormSubmissionsPanel(EditHandler): template = "wagtailforms/edit_handlers/form_responses_panel.html" def render(self): from .models import FormSubmission submissions = FormSubmission.objects.filter(page=self.instance) if not submissions: return '' return mark_safe(render_to_string(self.template, { 'self': self, 'submissions': submissions })) class FormSubmissionsPanel(object): def __init__(self, heading=None): self.heading = heading def bind_to_model(self, model): heading = _('{} submissions').format(model.get_verbose_name()) return type(str('_FormResponsesPanel'), (BaseFormSubmissionsPanel,), { 'model': model, 'heading': self.heading or heading, })
# ... existing code ... def bind_to_model(self, model): heading = _('{} submissions').format(model.get_verbose_name()) return type(str('_FormResponsesPanel'), (BaseFormSubmissionsPanel,), { # ... rest of the code ...
7f86ab26fb1c6ba01f81fdc3f5b66a0f079c23ff
tests/test_app.py
tests/test_app.py
import asyncio from unittest import mock import aiohttp import pytest from bottery.app import App def test_app_session(): app = App() assert isinstance(app.session, aiohttp.ClientSession) def test_app_already_configured_session(): app = App() app._session = 'session' assert app.session == 'session' def test_app_loop(): app = App() assert isinstance(app.loop, asyncio.AbstractEventLoop) def test_app_already_configured_loop(): app = App() app._loop = 'loop' assert app.loop == 'loop' @mock.patch('bottery.app.settings') def test_app_configure_without_platforms(mocked_settings): """Should raise Exception if no platform was found at settings""" mocked_settings.PLATFORMS = {} app = App() with pytest.raises(Exception): app.configure_platforms()
import asyncio import sys from unittest import mock import aiohttp import pytest from bottery.app import App @pytest.fixture def mocked_engine(): mocked_engine_module = mock.MagicMock() mocked_engine_instance = mocked_engine_module.engine.return_value mocked_engine_instance.tasks.return_value = [(mock.MagicMock(), )] sys.modules['tests.fake_engine'] = mocked_engine_module yield { 'module': mocked_engine_module, 'instance': mocked_engine_instance } del sys.modules['tests.fake_engine'] def test_app_session(): app = App() assert isinstance(app.session, aiohttp.ClientSession) def test_app_already_configured_session(): app = App() app._session = 'session' assert app.session == 'session' def test_app_loop(): app = App() assert isinstance(app.loop, asyncio.AbstractEventLoop) def test_app_already_configured_loop(): app = App() app._loop = 'loop' assert app.loop == 'loop' @mock.patch('bottery.app.settings') def test_app_configure_without_platforms(mocked_settings): """Should raise Exception if no platform was found at settings""" mocked_settings.PLATFORMS = {} app = App() with pytest.raises(Exception): app.configure_platforms() @mock.patch('bottery.app.settings') def test_app_configure_with_platforms(mocked_settings, mocked_engine): """Should call the platform interface methods""" mocked_settings.PLATFORMS = { 'test': { 'ENGINE': 'tests.fake_engine', 'OPTIONS': { 'token': 'should-be-a-valid-token' } } } app = App() app.configure_platforms() mocked_engine['module'].engine.assert_called_with( session=app.session, token='should-be-a-valid-token' ) mocked_engine['instance'].configure.assert_called_with() mocked_engine['instance'].tasks.assert_called_with()
Increase the code coverage of App.configure_platforms method
Increase the code coverage of App.configure_platforms method
Python
mit
rougeth/bottery
import asyncio + import sys from unittest import mock import aiohttp import pytest from bottery.app import App + + + @pytest.fixture + def mocked_engine(): + mocked_engine_module = mock.MagicMock() + mocked_engine_instance = mocked_engine_module.engine.return_value + mocked_engine_instance.tasks.return_value = [(mock.MagicMock(), )] + sys.modules['tests.fake_engine'] = mocked_engine_module + + yield { + 'module': mocked_engine_module, + 'instance': mocked_engine_instance + } + + del sys.modules['tests.fake_engine'] def test_app_session(): app = App() assert isinstance(app.session, aiohttp.ClientSession) def test_app_already_configured_session(): app = App() app._session = 'session' assert app.session == 'session' def test_app_loop(): app = App() assert isinstance(app.loop, asyncio.AbstractEventLoop) def test_app_already_configured_loop(): app = App() app._loop = 'loop' assert app.loop == 'loop' @mock.patch('bottery.app.settings') def test_app_configure_without_platforms(mocked_settings): """Should raise Exception if no platform was found at settings""" mocked_settings.PLATFORMS = {} app = App() with pytest.raises(Exception): app.configure_platforms() + @mock.patch('bottery.app.settings') + def test_app_configure_with_platforms(mocked_settings, mocked_engine): + """Should call the platform interface methods""" + + mocked_settings.PLATFORMS = { + 'test': { + 'ENGINE': 'tests.fake_engine', + 'OPTIONS': { + 'token': 'should-be-a-valid-token' + } + } + } + + app = App() + app.configure_platforms() + + mocked_engine['module'].engine.assert_called_with( + session=app.session, + token='should-be-a-valid-token' + ) + mocked_engine['instance'].configure.assert_called_with() + mocked_engine['instance'].tasks.assert_called_with() +
Increase the code coverage of App.configure_platforms method
## Code Before: import asyncio from unittest import mock import aiohttp import pytest from bottery.app import App def test_app_session(): app = App() assert isinstance(app.session, aiohttp.ClientSession) def test_app_already_configured_session(): app = App() app._session = 'session' assert app.session == 'session' def test_app_loop(): app = App() assert isinstance(app.loop, asyncio.AbstractEventLoop) def test_app_already_configured_loop(): app = App() app._loop = 'loop' assert app.loop == 'loop' @mock.patch('bottery.app.settings') def test_app_configure_without_platforms(mocked_settings): """Should raise Exception if no platform was found at settings""" mocked_settings.PLATFORMS = {} app = App() with pytest.raises(Exception): app.configure_platforms() ## Instruction: Increase the code coverage of App.configure_platforms method ## Code After: import asyncio import sys from unittest import mock import aiohttp import pytest from bottery.app import App @pytest.fixture def mocked_engine(): mocked_engine_module = mock.MagicMock() mocked_engine_instance = mocked_engine_module.engine.return_value mocked_engine_instance.tasks.return_value = [(mock.MagicMock(), )] sys.modules['tests.fake_engine'] = mocked_engine_module yield { 'module': mocked_engine_module, 'instance': mocked_engine_instance } del sys.modules['tests.fake_engine'] def test_app_session(): app = App() assert isinstance(app.session, aiohttp.ClientSession) def test_app_already_configured_session(): app = App() app._session = 'session' assert app.session == 'session' def test_app_loop(): app = App() assert isinstance(app.loop, asyncio.AbstractEventLoop) def test_app_already_configured_loop(): app = App() app._loop = 'loop' assert app.loop == 'loop' @mock.patch('bottery.app.settings') def test_app_configure_without_platforms(mocked_settings): """Should raise Exception if no platform was found at settings""" mocked_settings.PLATFORMS = {} app = App() with pytest.raises(Exception): app.configure_platforms() @mock.patch('bottery.app.settings') def test_app_configure_with_platforms(mocked_settings, mocked_engine): """Should call the platform interface methods""" mocked_settings.PLATFORMS = { 'test': { 'ENGINE': 'tests.fake_engine', 'OPTIONS': { 'token': 'should-be-a-valid-token' } } } app = App() app.configure_platforms() mocked_engine['module'].engine.assert_called_with( session=app.session, token='should-be-a-valid-token' ) mocked_engine['instance'].configure.assert_called_with() mocked_engine['instance'].tasks.assert_called_with()
... import asyncio import sys from unittest import mock ... from bottery.app import App @pytest.fixture def mocked_engine(): mocked_engine_module = mock.MagicMock() mocked_engine_instance = mocked_engine_module.engine.return_value mocked_engine_instance.tasks.return_value = [(mock.MagicMock(), )] sys.modules['tests.fake_engine'] = mocked_engine_module yield { 'module': mocked_engine_module, 'instance': mocked_engine_instance } del sys.modules['tests.fake_engine'] ... app.configure_platforms() @mock.patch('bottery.app.settings') def test_app_configure_with_platforms(mocked_settings, mocked_engine): """Should call the platform interface methods""" mocked_settings.PLATFORMS = { 'test': { 'ENGINE': 'tests.fake_engine', 'OPTIONS': { 'token': 'should-be-a-valid-token' } } } app = App() app.configure_platforms() mocked_engine['module'].engine.assert_called_with( session=app.session, token='should-be-a-valid-token' ) mocked_engine['instance'].configure.assert_called_with() mocked_engine['instance'].tasks.assert_called_with() ...
d937e254ce3c806300ac7763e30bd4303661cba6
whaler/analysis.py
whaler/analysis.py
import os from whaler.dataprep import IO class Analysis(): """ """ def __init__(self): self.loc = os.getcwd() self.structs = next(os.walk('.'))[1] print(self.loc) print(self.structs) def groundstates_all(self): """Compares the energies of each calculated spin state for a structure and writes the energy differences as a table.""" results = [self.spinstates(struct) for struct in self.structs] # write table as groundstates.out file. def spinstates(self, structure): """For a given structure, identifies all of the files optimizing geometries in different spin states. Verifies convergence, and then finds the final single-point energy for each file. Returns an array of energies of the various spin states. Possibilities: S T P D Q (for S = 0, 1, 2, 1/2, 3/2) """
import os import numpy as np from whaler.dataprep import IO class Analysis(): """ """ def __init__(self): self.loc = os.getcwd() self.structs = next(os.walk('.'))[1] print(self.loc) print(self.structs) def groundstates_all(self, outname="groundstates.csv"): """Compares the energies of each calculated spin state for a structure and writes the energy differences as a table.""" results = [self.spinstates(struct) for struct in self.structs] columns = [] #turn list of rows into list of columns # write table as groundstates.out file. writer = IO(outname, self.loc) headers = np.array(['Structures', 'S', 'T', 'P', 'D', 'Q']) writer.tabulate_data(columns, headers, 'Structures') def spinstates(self, structure): """For a given structure, identifies all of the files optimizing geometries in different spin states. Verifies convergence, and then finds the final single-point energy for each file. Returns an array of energies of the various spin states. Possibilities: S T P D Q (for S = 0, 1, 2, 1/2, 3/2) """
Set up data tabulation for gs
Set up data tabulation for gs
Python
mit
tristanbrown/whaler
import os + import numpy as np from whaler.dataprep import IO class Analysis(): """ """ def __init__(self): self.loc = os.getcwd() self.structs = next(os.walk('.'))[1] print(self.loc) print(self.structs) - def groundstates_all(self): + def groundstates_all(self, outname="groundstates.csv"): """Compares the energies of each calculated spin state for a structure and writes the energy differences as a table.""" results = [self.spinstates(struct) for struct in self.structs] + columns = [] #turn list of rows into list of columns # write table as groundstates.out file. + writer = IO(outname, self.loc) + + + headers = np.array(['Structures', 'S', 'T', 'P', 'D', 'Q']) + + writer.tabulate_data(columns, headers, 'Structures') def spinstates(self, structure): """For a given structure, identifies all of the files optimizing geometries in different spin states. Verifies convergence, and then finds the final single-point energy for each file. Returns an array of energies of the various spin states. Possibilities: S T P D Q (for S = 0, 1, 2, 1/2, 3/2) """
Set up data tabulation for gs
## Code Before: import os from whaler.dataprep import IO class Analysis(): """ """ def __init__(self): self.loc = os.getcwd() self.structs = next(os.walk('.'))[1] print(self.loc) print(self.structs) def groundstates_all(self): """Compares the energies of each calculated spin state for a structure and writes the energy differences as a table.""" results = [self.spinstates(struct) for struct in self.structs] # write table as groundstates.out file. def spinstates(self, structure): """For a given structure, identifies all of the files optimizing geometries in different spin states. Verifies convergence, and then finds the final single-point energy for each file. Returns an array of energies of the various spin states. Possibilities: S T P D Q (for S = 0, 1, 2, 1/2, 3/2) """ ## Instruction: Set up data tabulation for gs ## Code After: import os import numpy as np from whaler.dataprep import IO class Analysis(): """ """ def __init__(self): self.loc = os.getcwd() self.structs = next(os.walk('.'))[1] print(self.loc) print(self.structs) def groundstates_all(self, outname="groundstates.csv"): """Compares the energies of each calculated spin state for a structure and writes the energy differences as a table.""" results = [self.spinstates(struct) for struct in self.structs] columns = [] #turn list of rows into list of columns # write table as groundstates.out file. writer = IO(outname, self.loc) headers = np.array(['Structures', 'S', 'T', 'P', 'D', 'Q']) writer.tabulate_data(columns, headers, 'Structures') def spinstates(self, structure): """For a given structure, identifies all of the files optimizing geometries in different spin states. Verifies convergence, and then finds the final single-point energy for each file. Returns an array of energies of the various spin states. Possibilities: S T P D Q (for S = 0, 1, 2, 1/2, 3/2) """
// ... existing code ... import os import numpy as np from whaler.dataprep import IO // ... modified code ... def groundstates_all(self, outname="groundstates.csv"): """Compares the energies of each calculated spin state for a structure ... results = [self.spinstates(struct) for struct in self.structs] columns = [] #turn list of rows into list of columns ... # write table as groundstates.out file. writer = IO(outname, self.loc) headers = np.array(['Structures', 'S', 'T', 'P', 'D', 'Q']) writer.tabulate_data(columns, headers, 'Structures') // ... rest of the code ...
6811b04a0a2e311fc2d014cd601da61a2f17a451
sell/views.py
sell/views.py
from django.core.urlresolvers import reverse from django.forms import model_to_dict from django.http.response import HttpResponseRedirect, HttpResponse from django.shortcuts import render from common.models import Student from sell.forms import PersonalDataForm def index(request): return HttpResponseRedirect(reverse('sell.views.personal_data')) def personal_data(request): if request.method == 'POST': form = PersonalDataForm(request.POST) if form.is_valid(): request.session['personal_data'] = model_to_dict(form.save(commit=False)) return HttpResponseRedirect(reverse('sell.views.books')) else: if request.session['personal_data']: form = PersonalDataForm(instance=Student(**request.session['personal_data'])) else: form = PersonalDataForm() return render(request, 'sell/personal_data.html', {'form': form}) def books(request): return HttpResponse("Hello, world!")
from django.core.urlresolvers import reverse from django.forms import model_to_dict from django.http.response import HttpResponseRedirect, HttpResponse from django.shortcuts import render from common.models import Student from sell.forms import PersonalDataForm def index(request): return HttpResponseRedirect(reverse('sell.views.personal_data')) def personal_data(request): if request.method == 'POST': form = PersonalDataForm(request.POST) if form.is_valid(): request.session['personal_data'] = model_to_dict(form.save(commit=False)) return HttpResponseRedirect(reverse('sell.views.books')) else: if 'personal_data' in request.session: form = PersonalDataForm(instance=Student(**request.session['personal_data'])) else: form = PersonalDataForm() return render(request, 'sell/personal_data.html', {'form': form}) def books(request): return HttpResponse("Hello, world!")
Fix KeyError in Provide personal data form
Fix KeyError in Provide personal data form
Python
agpl-3.0
m4tx/egielda,m4tx/egielda,m4tx/egielda
from django.core.urlresolvers import reverse from django.forms import model_to_dict from django.http.response import HttpResponseRedirect, HttpResponse from django.shortcuts import render from common.models import Student from sell.forms import PersonalDataForm def index(request): return HttpResponseRedirect(reverse('sell.views.personal_data')) def personal_data(request): if request.method == 'POST': form = PersonalDataForm(request.POST) if form.is_valid(): request.session['personal_data'] = model_to_dict(form.save(commit=False)) return HttpResponseRedirect(reverse('sell.views.books')) else: - if request.session['personal_data']: + if 'personal_data' in request.session: form = PersonalDataForm(instance=Student(**request.session['personal_data'])) else: form = PersonalDataForm() return render(request, 'sell/personal_data.html', {'form': form}) def books(request): return HttpResponse("Hello, world!")
Fix KeyError in Provide personal data form
## Code Before: from django.core.urlresolvers import reverse from django.forms import model_to_dict from django.http.response import HttpResponseRedirect, HttpResponse from django.shortcuts import render from common.models import Student from sell.forms import PersonalDataForm def index(request): return HttpResponseRedirect(reverse('sell.views.personal_data')) def personal_data(request): if request.method == 'POST': form = PersonalDataForm(request.POST) if form.is_valid(): request.session['personal_data'] = model_to_dict(form.save(commit=False)) return HttpResponseRedirect(reverse('sell.views.books')) else: if request.session['personal_data']: form = PersonalDataForm(instance=Student(**request.session['personal_data'])) else: form = PersonalDataForm() return render(request, 'sell/personal_data.html', {'form': form}) def books(request): return HttpResponse("Hello, world!") ## Instruction: Fix KeyError in Provide personal data form ## Code After: from django.core.urlresolvers import reverse from django.forms import model_to_dict from django.http.response import HttpResponseRedirect, HttpResponse from django.shortcuts import render from common.models import Student from sell.forms import PersonalDataForm def index(request): return HttpResponseRedirect(reverse('sell.views.personal_data')) def personal_data(request): if request.method == 'POST': form = PersonalDataForm(request.POST) if form.is_valid(): request.session['personal_data'] = model_to_dict(form.save(commit=False)) return HttpResponseRedirect(reverse('sell.views.books')) else: if 'personal_data' in request.session: form = PersonalDataForm(instance=Student(**request.session['personal_data'])) else: form = PersonalDataForm() return render(request, 'sell/personal_data.html', {'form': form}) def books(request): return HttpResponse("Hello, world!")
# ... existing code ... else: if 'personal_data' in request.session: form = PersonalDataForm(instance=Student(**request.session['personal_data'])) # ... rest of the code ...
052c0cfd1ce21b36c9c9a44193e3a9c89ca871f1
ciscripts/coverage/bii/coverage.py
ciscripts/coverage/bii/coverage.py
"""Submit coverage totals for a bii project to coveralls.""" import errno import os from contextlib import contextmanager @contextmanager def _bii_deps_in_place(cont): """Move bii project dependencies into layout. The coverage step may require these dependencies to be present. """ bii_dir = os.path.join(cont.named_cache_dir("cmake-build"), "bii") try: os.rename(bii_dir, os.path.join(os.getcwd(), "bii")) except OSError as error: if error.errno != errno.ENOENT: raise error def run(cont, util, shell, argv=None): """Submit coverage total to coveralls, with bii specific preparation.""" with _bii_deps_in_place(cont): util.fetch_and_import("coverage/cmake/coverage.py").run(cont, util, shell, argv)
"""Submit coverage totals for a bii project to coveralls.""" import errno import os from contextlib import contextmanager def _move_ignore_enoent(src, dst): """Move src to dst, ignoring ENOENT.""" try: os.rename(src, dst) except OSError as error: if error.errno != errno.ENOENT: raise error @contextmanager def _bii_deps_in_place(cont): """Move bii project dependencies into layout. The coverage step may require these dependencies to be present. """ bii_dir = os.path.join(cont.named_cache_dir("cmake-build"), "bii") _move_ignore_enoent(bii_dir, os.path.join(os.getcwd(), "bii")) try: yield finally: _move_ignore_enoent(os.path.join(os.getcwd(), "bii"), bii_dir) def run(cont, util, shell, argv=None): """Submit coverage total to coveralls, with bii specific preparation.""" with _bii_deps_in_place(cont): util.fetch_and_import("coverage/cmake/coverage.py").run(cont, util, shell, argv)
Make _bii_deps_in_place actually behave like a context manager
bii: Make _bii_deps_in_place actually behave like a context manager
Python
mit
polysquare/polysquare-ci-scripts,polysquare/polysquare-ci-scripts
"""Submit coverage totals for a bii project to coveralls.""" import errno import os from contextlib import contextmanager + def _move_ignore_enoent(src, dst): + """Move src to dst, ignoring ENOENT.""" + try: + os.rename(src, dst) + except OSError as error: + if error.errno != errno.ENOENT: + raise error + + @contextmanager def _bii_deps_in_place(cont): """Move bii project dependencies into layout. The coverage step may require these dependencies to be present. """ bii_dir = os.path.join(cont.named_cache_dir("cmake-build"), "bii") + _move_ignore_enoent(bii_dir, os.path.join(os.getcwd(), "bii")) + try: + yield + finally: + _move_ignore_enoent(os.path.join(os.getcwd(), "bii"), bii_dir) - os.rename(bii_dir, os.path.join(os.getcwd(), "bii")) - except OSError as error: - if error.errno != errno.ENOENT: - raise error def run(cont, util, shell, argv=None): """Submit coverage total to coveralls, with bii specific preparation.""" with _bii_deps_in_place(cont): util.fetch_and_import("coverage/cmake/coverage.py").run(cont, util, shell, argv)
Make _bii_deps_in_place actually behave like a context manager
## Code Before: """Submit coverage totals for a bii project to coveralls.""" import errno import os from contextlib import contextmanager @contextmanager def _bii_deps_in_place(cont): """Move bii project dependencies into layout. The coverage step may require these dependencies to be present. """ bii_dir = os.path.join(cont.named_cache_dir("cmake-build"), "bii") try: os.rename(bii_dir, os.path.join(os.getcwd(), "bii")) except OSError as error: if error.errno != errno.ENOENT: raise error def run(cont, util, shell, argv=None): """Submit coverage total to coveralls, with bii specific preparation.""" with _bii_deps_in_place(cont): util.fetch_and_import("coverage/cmake/coverage.py").run(cont, util, shell, argv) ## Instruction: Make _bii_deps_in_place actually behave like a context manager ## Code After: """Submit coverage totals for a bii project to coveralls.""" import errno import os from contextlib import contextmanager def _move_ignore_enoent(src, dst): """Move src to dst, ignoring ENOENT.""" try: os.rename(src, dst) except OSError as error: if error.errno != errno.ENOENT: raise error @contextmanager def _bii_deps_in_place(cont): """Move bii project dependencies into layout. The coverage step may require these dependencies to be present. """ bii_dir = os.path.join(cont.named_cache_dir("cmake-build"), "bii") _move_ignore_enoent(bii_dir, os.path.join(os.getcwd(), "bii")) try: yield finally: _move_ignore_enoent(os.path.join(os.getcwd(), "bii"), bii_dir) def run(cont, util, shell, argv=None): """Submit coverage total to coveralls, with bii specific preparation.""" with _bii_deps_in_place(cont): util.fetch_and_import("coverage/cmake/coverage.py").run(cont, util, shell, argv)
# ... existing code ... def _move_ignore_enoent(src, dst): """Move src to dst, ignoring ENOENT.""" try: os.rename(src, dst) except OSError as error: if error.errno != errno.ENOENT: raise error @contextmanager # ... modified code ... bii_dir = os.path.join(cont.named_cache_dir("cmake-build"), "bii") _move_ignore_enoent(bii_dir, os.path.join(os.getcwd(), "bii")) try: yield finally: _move_ignore_enoent(os.path.join(os.getcwd(), "bii"), bii_dir) # ... rest of the code ...
b631dadb54f90e4abb251f7680f883f2e3e0e914
radar/radar/validation/patient_numbers.py
radar/radar/validation/patient_numbers.py
from radar.groups import is_radar_group from radar.validation.core import Validation, pass_call, ValidationError, Field from radar.validation.sources import RadarSourceValidationMixin from radar.validation.meta import MetaValidationMixin from radar.validation.patients import PatientValidationMixin from radar.validation.validators import required, max_length, not_empty, normalise_whitespace from radar.validation.number_validators import NUMBER_VALIDATORS class PatientNumberValidation(PatientValidationMixin, RadarSourceValidationMixin, MetaValidationMixin, Validation): number = Field([not_empty(), normalise_whitespace(), max_length(50)]) number_group = Field([required()]) def validate_number_group(self, number_group): if is_radar_group(number_group): raise ValidationError("Can't add RaDaR numbers.") return number_group @pass_call def validate(self, call, obj): number_group = obj.number_group number_validators = NUMBER_VALIDATORS.get((number_group.type, number_group.code)) if number_validators is not None: call.validators_for_field(number_validators, obj, self.number) return obj
from radar.groups import is_radar_group, get_radar_group from radar.validation.core import Validation, pass_call, ValidationError, Field from radar.validation.sources import RadarSourceValidationMixin from radar.validation.meta import MetaValidationMixin from radar.validation.patients import PatientValidationMixin from radar.validation.validators import required, max_length, not_empty, normalise_whitespace from radar.validation.number_validators import NUMBER_VALIDATORS from radar.models.patient_numbers import PatientNumber from radar.database import db class PatientNumberValidation(PatientValidationMixin, RadarSourceValidationMixin, MetaValidationMixin, Validation): number = Field([not_empty(), normalise_whitespace(), max_length(50)]) number_group = Field([required()]) def validate_number_group(self, number_group): if is_radar_group(number_group): raise ValidationError("Can't add RaDaR numbers.") return number_group @classmethod def is_duplicate(cls, obj): q = PatientNumber.query q = q.filter(PatientNumber.source_group == get_radar_group()) q = q.filter(PatientNumber.number_group == obj.number_group) q = q.filter(PatientNumber.number == obj.number) if obj.id is not None: q = q.filter(PatientNumber.id != obj.id) q = q.exists() duplicate = db.session.query(q).scalar() return duplicate @pass_call def validate(self, call, obj): number_group = obj.number_group number_validators = NUMBER_VALIDATORS.get((number_group.type, number_group.code)) if number_validators is not None: call.validators_for_field(number_validators, obj, self.number) if self.is_duplicate(obj): raise ValidationError({'number': 'A patient already exists with this number.'}) return obj
Check for duplicate patient numbers
Check for duplicate patient numbers Fixes #286
Python
agpl-3.0
renalreg/radar,renalreg/radar,renalreg/radar,renalreg/radar
- from radar.groups import is_radar_group + from radar.groups import is_radar_group, get_radar_group from radar.validation.core import Validation, pass_call, ValidationError, Field from radar.validation.sources import RadarSourceValidationMixin from radar.validation.meta import MetaValidationMixin from radar.validation.patients import PatientValidationMixin from radar.validation.validators import required, max_length, not_empty, normalise_whitespace from radar.validation.number_validators import NUMBER_VALIDATORS + from radar.models.patient_numbers import PatientNumber + from radar.database import db class PatientNumberValidation(PatientValidationMixin, RadarSourceValidationMixin, MetaValidationMixin, Validation): number = Field([not_empty(), normalise_whitespace(), max_length(50)]) number_group = Field([required()]) def validate_number_group(self, number_group): if is_radar_group(number_group): raise ValidationError("Can't add RaDaR numbers.") return number_group + @classmethod + def is_duplicate(cls, obj): + q = PatientNumber.query + q = q.filter(PatientNumber.source_group == get_radar_group()) + q = q.filter(PatientNumber.number_group == obj.number_group) + q = q.filter(PatientNumber.number == obj.number) + + if obj.id is not None: + q = q.filter(PatientNumber.id != obj.id) + + q = q.exists() + + duplicate = db.session.query(q).scalar() + + return duplicate + @pass_call def validate(self, call, obj): number_group = obj.number_group number_validators = NUMBER_VALIDATORS.get((number_group.type, number_group.code)) if number_validators is not None: call.validators_for_field(number_validators, obj, self.number) + if self.is_duplicate(obj): + raise ValidationError({'number': 'A patient already exists with this number.'}) + return obj
Check for duplicate patient numbers
## Code Before: from radar.groups import is_radar_group from radar.validation.core import Validation, pass_call, ValidationError, Field from radar.validation.sources import RadarSourceValidationMixin from radar.validation.meta import MetaValidationMixin from radar.validation.patients import PatientValidationMixin from radar.validation.validators import required, max_length, not_empty, normalise_whitespace from radar.validation.number_validators import NUMBER_VALIDATORS class PatientNumberValidation(PatientValidationMixin, RadarSourceValidationMixin, MetaValidationMixin, Validation): number = Field([not_empty(), normalise_whitespace(), max_length(50)]) number_group = Field([required()]) def validate_number_group(self, number_group): if is_radar_group(number_group): raise ValidationError("Can't add RaDaR numbers.") return number_group @pass_call def validate(self, call, obj): number_group = obj.number_group number_validators = NUMBER_VALIDATORS.get((number_group.type, number_group.code)) if number_validators is not None: call.validators_for_field(number_validators, obj, self.number) return obj ## Instruction: Check for duplicate patient numbers ## Code After: from radar.groups import is_radar_group, get_radar_group from radar.validation.core import Validation, pass_call, ValidationError, Field from radar.validation.sources import RadarSourceValidationMixin from radar.validation.meta import MetaValidationMixin from radar.validation.patients import PatientValidationMixin from radar.validation.validators import required, max_length, not_empty, normalise_whitespace from radar.validation.number_validators import NUMBER_VALIDATORS from radar.models.patient_numbers import PatientNumber from radar.database import db class PatientNumberValidation(PatientValidationMixin, RadarSourceValidationMixin, MetaValidationMixin, Validation): number = Field([not_empty(), normalise_whitespace(), max_length(50)]) number_group = Field([required()]) def validate_number_group(self, number_group): if is_radar_group(number_group): raise ValidationError("Can't add RaDaR numbers.") return number_group @classmethod def is_duplicate(cls, obj): q = PatientNumber.query q = q.filter(PatientNumber.source_group == get_radar_group()) q = q.filter(PatientNumber.number_group == obj.number_group) q = q.filter(PatientNumber.number == obj.number) if obj.id is not None: q = q.filter(PatientNumber.id != obj.id) q = q.exists() duplicate = db.session.query(q).scalar() return duplicate @pass_call def validate(self, call, obj): number_group = obj.number_group number_validators = NUMBER_VALIDATORS.get((number_group.type, number_group.code)) if number_validators is not None: call.validators_for_field(number_validators, obj, self.number) if self.is_duplicate(obj): raise ValidationError({'number': 'A patient already exists with this number.'}) return obj
# ... existing code ... from radar.groups import is_radar_group, get_radar_group from radar.validation.core import Validation, pass_call, ValidationError, Field # ... modified code ... from radar.validation.number_validators import NUMBER_VALIDATORS from radar.models.patient_numbers import PatientNumber from radar.database import db ... @classmethod def is_duplicate(cls, obj): q = PatientNumber.query q = q.filter(PatientNumber.source_group == get_radar_group()) q = q.filter(PatientNumber.number_group == obj.number_group) q = q.filter(PatientNumber.number == obj.number) if obj.id is not None: q = q.filter(PatientNumber.id != obj.id) q = q.exists() duplicate = db.session.query(q).scalar() return duplicate @pass_call ... if self.is_duplicate(obj): raise ValidationError({'number': 'A patient already exists with this number.'}) return obj # ... rest of the code ...
0d81d93a0c90c8cda2e762255c2d41b99ddc16f3
macdict/cli.py
macdict/cli.py
from __future__ import absolute_import import sys import argparse from macdict.dictionary import lookup_word def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('word') return parser.parse_args() def abort(text): sys.stderr.write(u'%s\n' % text) sys.exit(1) def report(text): sys.stdout.write(u'%s\n' % text) sys.exit(0) def main(): args = parse_args() definition = lookup_word(args.word) if definition is None: abort(u'Definition not found for "%s"' % args.word) else: report(definition)
from __future__ import absolute_import import sys import argparse from macdict.dictionary import lookup_word def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('word') return parser.parse_args() def abort(text): sys.stderr.write(u'%s\n' % text) sys.exit(1) def report(text): sys.stdout.write(u'%s\n' % text) sys.exit(0) def main(): args = parse_args() definition = lookup_word(args.word.decode('utf-8')) if definition is None: abort(u'Definition not found for "%s"' % args.word) else: report(definition)
Fix CJK input in command line arguments
Fix CJK input in command line arguments
Python
mit
tonyseek/macdict
from __future__ import absolute_import import sys import argparse from macdict.dictionary import lookup_word def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('word') return parser.parse_args() def abort(text): sys.stderr.write(u'%s\n' % text) sys.exit(1) def report(text): sys.stdout.write(u'%s\n' % text) sys.exit(0) def main(): args = parse_args() - definition = lookup_word(args.word) + definition = lookup_word(args.word.decode('utf-8')) if definition is None: abort(u'Definition not found for "%s"' % args.word) else: report(definition)
Fix CJK input in command line arguments
## Code Before: from __future__ import absolute_import import sys import argparse from macdict.dictionary import lookup_word def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('word') return parser.parse_args() def abort(text): sys.stderr.write(u'%s\n' % text) sys.exit(1) def report(text): sys.stdout.write(u'%s\n' % text) sys.exit(0) def main(): args = parse_args() definition = lookup_word(args.word) if definition is None: abort(u'Definition not found for "%s"' % args.word) else: report(definition) ## Instruction: Fix CJK input in command line arguments ## Code After: from __future__ import absolute_import import sys import argparse from macdict.dictionary import lookup_word def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('word') return parser.parse_args() def abort(text): sys.stderr.write(u'%s\n' % text) sys.exit(1) def report(text): sys.stdout.write(u'%s\n' % text) sys.exit(0) def main(): args = parse_args() definition = lookup_word(args.word.decode('utf-8')) if definition is None: abort(u'Definition not found for "%s"' % args.word) else: report(definition)
# ... existing code ... args = parse_args() definition = lookup_word(args.word.decode('utf-8')) if definition is None: # ... rest of the code ...
8f82336aed62a18b2c6f824fcf0e6b1a1d00b8d3
tests/test_astroid.py
tests/test_astroid.py
from __future__ import unicode_literals, print_function import re import astroid from . import tools, test_mark_tokens class TestAstroid(test_mark_tokens.TestMarkTokens): is_astroid_test = True module = astroid nodes_classes = astroid.ALL_NODE_CLASSES context_classes = [ (astroid.Name, astroid.DelName, astroid.AssignName), (astroid.Attribute, astroid.DelAttr, astroid.AssignAttr), ] @staticmethod def iter_fields(node): """ Yield a tuple of ``(fieldname, value)`` for each field that is present on *node*. Similar to ast.iter_fields, but for astroid and ignores context """ for field in node._astroid_fields + node._other_fields: if field == 'ctx': continue yield field, getattr(node, field) @classmethod def create_mark_checker(cls, source): builder = astroid.builder.AstroidBuilder() tree = builder.string_build(source) return tools.MarkChecker(source, tree=tree)
from __future__ import unicode_literals, print_function import astroid from astroid.node_classes import NodeNG from . import tools, test_mark_tokens class TestAstroid(test_mark_tokens.TestMarkTokens): is_astroid_test = True module = astroid nodes_classes = NodeNG context_classes = [ (astroid.Name, astroid.DelName, astroid.AssignName), (astroid.Attribute, astroid.DelAttr, astroid.AssignAttr), ] @staticmethod def iter_fields(node): """ Yield a tuple of ``(fieldname, value)`` for each field that is present on *node*. Similar to ast.iter_fields, but for astroid and ignores context """ for field in node._astroid_fields + node._other_fields: if field == 'ctx': continue yield field, getattr(node, field) @classmethod def create_mark_checker(cls, source): builder = astroid.builder.AstroidBuilder() tree = builder.string_build(source) return tools.MarkChecker(source, tree=tree)
Use NodeNG instead of astroid.ALL_NODE_CLASSES
Use NodeNG instead of astroid.ALL_NODE_CLASSES
Python
apache-2.0
gristlabs/asttokens
from __future__ import unicode_literals, print_function - import re - import astroid + from astroid.node_classes import NodeNG from . import tools, test_mark_tokens class TestAstroid(test_mark_tokens.TestMarkTokens): is_astroid_test = True module = astroid - nodes_classes = astroid.ALL_NODE_CLASSES + nodes_classes = NodeNG context_classes = [ (astroid.Name, astroid.DelName, astroid.AssignName), (astroid.Attribute, astroid.DelAttr, astroid.AssignAttr), ] @staticmethod def iter_fields(node): """ Yield a tuple of ``(fieldname, value)`` for each field that is present on *node*. Similar to ast.iter_fields, but for astroid and ignores context """ for field in node._astroid_fields + node._other_fields: if field == 'ctx': continue yield field, getattr(node, field) @classmethod def create_mark_checker(cls, source): builder = astroid.builder.AstroidBuilder() tree = builder.string_build(source) return tools.MarkChecker(source, tree=tree)
Use NodeNG instead of astroid.ALL_NODE_CLASSES
## Code Before: from __future__ import unicode_literals, print_function import re import astroid from . import tools, test_mark_tokens class TestAstroid(test_mark_tokens.TestMarkTokens): is_astroid_test = True module = astroid nodes_classes = astroid.ALL_NODE_CLASSES context_classes = [ (astroid.Name, astroid.DelName, astroid.AssignName), (astroid.Attribute, astroid.DelAttr, astroid.AssignAttr), ] @staticmethod def iter_fields(node): """ Yield a tuple of ``(fieldname, value)`` for each field that is present on *node*. Similar to ast.iter_fields, but for astroid and ignores context """ for field in node._astroid_fields + node._other_fields: if field == 'ctx': continue yield field, getattr(node, field) @classmethod def create_mark_checker(cls, source): builder = astroid.builder.AstroidBuilder() tree = builder.string_build(source) return tools.MarkChecker(source, tree=tree) ## Instruction: Use NodeNG instead of astroid.ALL_NODE_CLASSES ## Code After: from __future__ import unicode_literals, print_function import astroid from astroid.node_classes import NodeNG from . import tools, test_mark_tokens class TestAstroid(test_mark_tokens.TestMarkTokens): is_astroid_test = True module = astroid nodes_classes = NodeNG context_classes = [ (astroid.Name, astroid.DelName, astroid.AssignName), (astroid.Attribute, astroid.DelAttr, astroid.AssignAttr), ] @staticmethod def iter_fields(node): """ Yield a tuple of ``(fieldname, value)`` for each field that is present on *node*. Similar to ast.iter_fields, but for astroid and ignores context """ for field in node._astroid_fields + node._other_fields: if field == 'ctx': continue yield field, getattr(node, field) @classmethod def create_mark_checker(cls, source): builder = astroid.builder.AstroidBuilder() tree = builder.string_build(source) return tools.MarkChecker(source, tree=tree)
... import astroid from astroid.node_classes import NodeNG ... nodes_classes = NodeNG context_classes = [ ...
d2b0aba3e13246193f37758e23f4d26b90552508
social_auth/middleware.py
social_auth/middleware.py
from django.conf import settings from django.contrib import messages from django.shortcuts import redirect from social_auth.backends.exceptions import AuthException class SocialAuthExceptionMiddleware(object): """Middleware that handles Social Auth AuthExceptions by providing the user with a message, logging an error, and redirecting to some next location. By default, the exception message itself is sent to the user and they are redirected to the location specified in the LOGIN_ERROR_URL setting. This middleware can be extended by overriding the get_message or get_redirect_uri methods, which each accept request and exception. """ def process_exception(self, request, exception): if isinstance(exception, AuthException): backend_name = exception.backend.AUTH_BACKEND.name message = self.get_message(request, exception) messages.error(request, message, extra_tags=u'social-auth {0}'.format(backend_name)) url = self.get_redirect_uri(request, exception) return redirect(url) def get_message(self, request, exception): return unicode(exception) def get_redirect_uri(self, request, exception): return settings.LOGIN_ERROR_URL
from django.conf import settings from django.contrib import messages from django.shortcuts import redirect from social_auth.backends.exceptions import AuthException class SocialAuthExceptionMiddleware(object): """Middleware that handles Social Auth AuthExceptions by providing the user with a message, logging an error, and redirecting to some next location. By default, the exception message itself is sent to the user and they are redirected to the location specified in the LOGIN_ERROR_URL setting. This middleware can be extended by overriding the get_message or get_redirect_uri methods, which each accept request and exception. """ def process_exception(self, request, exception): if isinstance(exception, AuthException): backend_name = exception.backend.name message = self.get_message(request, exception) messages.error(request, message, extra_tags=u'social-auth {0}'.format(backend_name)) url = self.get_redirect_uri(request, exception) return redirect(url) def get_message(self, request, exception): return unicode(exception) def get_redirect_uri(self, request, exception): return settings.LOGIN_ERROR_URL
Correct access of backend name from AuthException
Correct access of backend name from AuthException
Python
bsd-3-clause
omab/django-social-auth,duoduo369/django-social-auth,MjAbuz/django-social-auth,beswarm/django-social-auth,getsentry/django-social-auth,omab/django-social-auth,lovehhf/django-social-auth,sk7/django-social-auth,WW-Digital/django-social-auth,qas612820704/django-social-auth,caktus/django-social-auth,gustavoam/django-social-auth,mayankcu/Django-social,vuchau/django-social-auth,caktus/django-social-auth,limdauto/django-social-auth,vuchau/django-social-auth,VishvajitP/django-social-auth,qas612820704/django-social-auth,dongguangming/django-social-auth,VishvajitP/django-social-auth,adw0rd/django-social-auth,MjAbuz/django-social-auth,dongguangming/django-social-auth,gustavoam/django-social-auth,krvss/django-social-auth,lovehhf/django-social-auth,michael-borisov/django-social-auth,michael-borisov/django-social-auth,vxvinh1511/django-social-auth,beswarm/django-social-auth,limdauto/django-social-auth,vxvinh1511/django-social-auth
from django.conf import settings from django.contrib import messages from django.shortcuts import redirect from social_auth.backends.exceptions import AuthException class SocialAuthExceptionMiddleware(object): """Middleware that handles Social Auth AuthExceptions by providing the user with a message, logging an error, and redirecting to some next location. By default, the exception message itself is sent to the user and they are redirected to the location specified in the LOGIN_ERROR_URL setting. This middleware can be extended by overriding the get_message or get_redirect_uri methods, which each accept request and exception. """ def process_exception(self, request, exception): if isinstance(exception, AuthException): - backend_name = exception.backend.AUTH_BACKEND.name + backend_name = exception.backend.name message = self.get_message(request, exception) messages.error(request, message, extra_tags=u'social-auth {0}'.format(backend_name)) url = self.get_redirect_uri(request, exception) return redirect(url) def get_message(self, request, exception): return unicode(exception) def get_redirect_uri(self, request, exception): return settings.LOGIN_ERROR_URL
Correct access of backend name from AuthException
## Code Before: from django.conf import settings from django.contrib import messages from django.shortcuts import redirect from social_auth.backends.exceptions import AuthException class SocialAuthExceptionMiddleware(object): """Middleware that handles Social Auth AuthExceptions by providing the user with a message, logging an error, and redirecting to some next location. By default, the exception message itself is sent to the user and they are redirected to the location specified in the LOGIN_ERROR_URL setting. This middleware can be extended by overriding the get_message or get_redirect_uri methods, which each accept request and exception. """ def process_exception(self, request, exception): if isinstance(exception, AuthException): backend_name = exception.backend.AUTH_BACKEND.name message = self.get_message(request, exception) messages.error(request, message, extra_tags=u'social-auth {0}'.format(backend_name)) url = self.get_redirect_uri(request, exception) return redirect(url) def get_message(self, request, exception): return unicode(exception) def get_redirect_uri(self, request, exception): return settings.LOGIN_ERROR_URL ## Instruction: Correct access of backend name from AuthException ## Code After: from django.conf import settings from django.contrib import messages from django.shortcuts import redirect from social_auth.backends.exceptions import AuthException class SocialAuthExceptionMiddleware(object): """Middleware that handles Social Auth AuthExceptions by providing the user with a message, logging an error, and redirecting to some next location. By default, the exception message itself is sent to the user and they are redirected to the location specified in the LOGIN_ERROR_URL setting. This middleware can be extended by overriding the get_message or get_redirect_uri methods, which each accept request and exception. """ def process_exception(self, request, exception): if isinstance(exception, AuthException): backend_name = exception.backend.name message = self.get_message(request, exception) messages.error(request, message, extra_tags=u'social-auth {0}'.format(backend_name)) url = self.get_redirect_uri(request, exception) return redirect(url) def get_message(self, request, exception): return unicode(exception) def get_redirect_uri(self, request, exception): return settings.LOGIN_ERROR_URL
// ... existing code ... if isinstance(exception, AuthException): backend_name = exception.backend.name message = self.get_message(request, exception) // ... rest of the code ...
c62e1b325a536294b3285f8cbcad7d66a415ee23
heat/objects/base.py
heat/objects/base.py
"""Heat common internal object model""" from oslo_versionedobjects import base as ovoo_base class HeatObject(ovoo_base.VersionedObject): OBJ_PROJECT_NAMESPACE = 'heat' VERSION = '1.0'
"""Heat common internal object model""" import weakref from oslo_versionedobjects import base as ovoo_base class HeatObject(ovoo_base.VersionedObject): OBJ_PROJECT_NAMESPACE = 'heat' VERSION = '1.0' @property def _context(self): if self._contextref is None: return ctxt = self._contextref() assert ctxt is not None, "Need a reference to the context" return ctxt @_context.setter def _context(self, context): if context: self._contextref = weakref.ref(context) else: self._contextref = None
Use a weakref for the data object context
Use a weakref for the data object context There are no known circular reference issues caused by storing the context in data objects, but the following changes will refer to data objects in the context, so this change prevents any later issues. Change-Id: I3680e5678003cf339a98fbb7a2b1b387fb2243c0 Related-Bug: #1578854
Python
apache-2.0
noironetworks/heat,openstack/heat,openstack/heat,cwolferh/heat-scratch,noironetworks/heat,cwolferh/heat-scratch
"""Heat common internal object model""" + + import weakref from oslo_versionedobjects import base as ovoo_base class HeatObject(ovoo_base.VersionedObject): OBJ_PROJECT_NAMESPACE = 'heat' VERSION = '1.0' + @property + def _context(self): + if self._contextref is None: + return + ctxt = self._contextref() + assert ctxt is not None, "Need a reference to the context" + return ctxt + + @_context.setter + def _context(self, context): + if context: + self._contextref = weakref.ref(context) + else: + self._contextref = None +
Use a weakref for the data object context
## Code Before: """Heat common internal object model""" from oslo_versionedobjects import base as ovoo_base class HeatObject(ovoo_base.VersionedObject): OBJ_PROJECT_NAMESPACE = 'heat' VERSION = '1.0' ## Instruction: Use a weakref for the data object context ## Code After: """Heat common internal object model""" import weakref from oslo_versionedobjects import base as ovoo_base class HeatObject(ovoo_base.VersionedObject): OBJ_PROJECT_NAMESPACE = 'heat' VERSION = '1.0' @property def _context(self): if self._contextref is None: return ctxt = self._contextref() assert ctxt is not None, "Need a reference to the context" return ctxt @_context.setter def _context(self, context): if context: self._contextref = weakref.ref(context) else: self._contextref = None
# ... existing code ... """Heat common internal object model""" import weakref # ... modified code ... VERSION = '1.0' @property def _context(self): if self._contextref is None: return ctxt = self._contextref() assert ctxt is not None, "Need a reference to the context" return ctxt @_context.setter def _context(self, context): if context: self._contextref = weakref.ref(context) else: self._contextref = None # ... rest of the code ...
2c38fea1434f8591957c2707359412151c4b6c43
tests/test_timezones.py
tests/test_timezones.py
import unittest import datetime from garage.timezones import TimeZone class TimeZoneTest(unittest.TestCase): def test_time_zone(self): utc = datetime.datetime(2000, 1, 2, 3, 4, 0, 0, TimeZone.UTC) cst = utc.astimezone(TimeZone.CST) print('xxx', utc, cst) self.assertEqual(2000, cst.year) self.assertEqual(1, cst.month) self.assertEqual(2, cst.day) self.assertEqual(11, cst.hour) self.assertEqual(4, cst.minute) self.assertEqual(0, cst.second) self.assertEqual(0, cst.microsecond) if __name__ == '__main__': unittest.main()
import unittest import datetime from garage.timezones import TimeZone class TimeZoneTest(unittest.TestCase): def test_time_zone(self): utc = datetime.datetime(2000, 1, 2, 3, 4, 0, 0, TimeZone.UTC) cst = utc.astimezone(TimeZone.CST) self.assertEqual(2000, cst.year) self.assertEqual(1, cst.month) self.assertEqual(2, cst.day) self.assertEqual(11, cst.hour) self.assertEqual(4, cst.minute) self.assertEqual(0, cst.second) self.assertEqual(0, cst.microsecond) if __name__ == '__main__': unittest.main()
Remove print in unit test
Remove print in unit test
Python
mit
clchiou/garage,clchiou/garage,clchiou/garage,clchiou/garage
import unittest import datetime from garage.timezones import TimeZone class TimeZoneTest(unittest.TestCase): def test_time_zone(self): utc = datetime.datetime(2000, 1, 2, 3, 4, 0, 0, TimeZone.UTC) cst = utc.astimezone(TimeZone.CST) - print('xxx', utc, cst) self.assertEqual(2000, cst.year) self.assertEqual(1, cst.month) self.assertEqual(2, cst.day) self.assertEqual(11, cst.hour) self.assertEqual(4, cst.minute) self.assertEqual(0, cst.second) self.assertEqual(0, cst.microsecond) if __name__ == '__main__': unittest.main()
Remove print in unit test
## Code Before: import unittest import datetime from garage.timezones import TimeZone class TimeZoneTest(unittest.TestCase): def test_time_zone(self): utc = datetime.datetime(2000, 1, 2, 3, 4, 0, 0, TimeZone.UTC) cst = utc.astimezone(TimeZone.CST) print('xxx', utc, cst) self.assertEqual(2000, cst.year) self.assertEqual(1, cst.month) self.assertEqual(2, cst.day) self.assertEqual(11, cst.hour) self.assertEqual(4, cst.minute) self.assertEqual(0, cst.second) self.assertEqual(0, cst.microsecond) if __name__ == '__main__': unittest.main() ## Instruction: Remove print in unit test ## Code After: import unittest import datetime from garage.timezones import TimeZone class TimeZoneTest(unittest.TestCase): def test_time_zone(self): utc = datetime.datetime(2000, 1, 2, 3, 4, 0, 0, TimeZone.UTC) cst = utc.astimezone(TimeZone.CST) self.assertEqual(2000, cst.year) self.assertEqual(1, cst.month) self.assertEqual(2, cst.day) self.assertEqual(11, cst.hour) self.assertEqual(4, cst.minute) self.assertEqual(0, cst.second) self.assertEqual(0, cst.microsecond) if __name__ == '__main__': unittest.main()
# ... existing code ... cst = utc.astimezone(TimeZone.CST) self.assertEqual(2000, cst.year) # ... rest of the code ...
abce02dc1a30b869300eee36b29d5e61320d64c5
test.py
test.py
import os import subprocess import time import glob import unittest class ZxSpecTestCase(unittest.TestCase): def setUp(self): clean() def tearDown(self): clean() def test_zx_spec_header_displayed(self): ZX_SPEC_OUTPUT_FILE = "printout.txt" proc = subprocess.Popen([ "fuse", "--tape", "bin/zx-spec-test.tap", "--auto-load", "--no-autosave-settings"]) while not os.path.exists(ZX_SPEC_OUTPUT_FILE): time.sleep(0.1) time.sleep(1) proc.kill() with open(ZX_SPEC_OUTPUT_FILE, 'r') as f: zx_spec_output = f.read() self.assertRegexpMatches(zx_spec_output, 'ZX Spec - The TDD Framework') def clean(): for f in glob.glob("printout.*"): os.remove(f) if __name__ == '__main__': unittest.main()
import os import subprocess import time import glob import unittest class ZxSpecTestCase(unittest.TestCase): @classmethod def setUpClass(self): clean() self.output = run_zx_spec() def test_zx_spec_header_displayed(self): self.assertRegexpMatches(self.output, 'ZX Spec - The TDD Framework') def test_all_tests_pass(self): self.assertRegexpMatches(self.output, 'Pass: 0, Fail: 0') @classmethod def tearDownClass(self): clean() def clean(): for f in glob.glob("printout.*"): os.remove(f) def run_zx_spec(): ZX_SPEC_OUTPUT_FILE = "printout.txt" proc = subprocess.Popen([ "fuse", "--tape", "bin/zx-spec-test.tap", "--auto-load", "--no-autosave-settings"]) wait_count = 0 while not os.path.exists(ZX_SPEC_OUTPUT_FILE): time.sleep(0.1) wait_count += 1 if wait_count == 20: raise 'Output file not produced in time' time.sleep(1) proc.kill() with open(ZX_SPEC_OUTPUT_FILE, 'r') as f: return f.read() if __name__ == '__main__': unittest.main()
Add timeout for printout production
Add timeout for printout production
Python
mit
rhargreaves/zx-spec
import os import subprocess import time import glob import unittest class ZxSpecTestCase(unittest.TestCase): + + @classmethod - def setUp(self): + def setUpClass(self): clean() + self.output = run_zx_spec() - - def tearDown(self): - clean() def test_zx_spec_header_displayed(self): - ZX_SPEC_OUTPUT_FILE = "printout.txt" + self.assertRegexpMatches(self.output, 'ZX Spec - The TDD Framework') + def test_all_tests_pass(self): + self.assertRegexpMatches(self.output, 'Pass: 0, Fail: 0') - proc = subprocess.Popen([ - "fuse", - "--tape", "bin/zx-spec-test.tap", - "--auto-load", - "--no-autosave-settings"]) + @classmethod + def tearDownClass(self): + clean() - while not os.path.exists(ZX_SPEC_OUTPUT_FILE): - time.sleep(0.1) - - time.sleep(1) - proc.kill() - - with open(ZX_SPEC_OUTPUT_FILE, 'r') as f: - zx_spec_output = f.read() - - self.assertRegexpMatches(zx_spec_output, 'ZX Spec - The TDD Framework') def clean(): for f in glob.glob("printout.*"): os.remove(f) + def run_zx_spec(): + ZX_SPEC_OUTPUT_FILE = "printout.txt" + proc = subprocess.Popen([ + "fuse", + "--tape", "bin/zx-spec-test.tap", + "--auto-load", + "--no-autosave-settings"]) + + wait_count = 0 + while not os.path.exists(ZX_SPEC_OUTPUT_FILE): + time.sleep(0.1) + wait_count += 1 + if wait_count == 20: + raise 'Output file not produced in time' + + time.sleep(1) + proc.kill() + + with open(ZX_SPEC_OUTPUT_FILE, 'r') as f: + return f.read() + if __name__ == '__main__': unittest.main()
Add timeout for printout production
## Code Before: import os import subprocess import time import glob import unittest class ZxSpecTestCase(unittest.TestCase): def setUp(self): clean() def tearDown(self): clean() def test_zx_spec_header_displayed(self): ZX_SPEC_OUTPUT_FILE = "printout.txt" proc = subprocess.Popen([ "fuse", "--tape", "bin/zx-spec-test.tap", "--auto-load", "--no-autosave-settings"]) while not os.path.exists(ZX_SPEC_OUTPUT_FILE): time.sleep(0.1) time.sleep(1) proc.kill() with open(ZX_SPEC_OUTPUT_FILE, 'r') as f: zx_spec_output = f.read() self.assertRegexpMatches(zx_spec_output, 'ZX Spec - The TDD Framework') def clean(): for f in glob.glob("printout.*"): os.remove(f) if __name__ == '__main__': unittest.main() ## Instruction: Add timeout for printout production ## Code After: import os import subprocess import time import glob import unittest class ZxSpecTestCase(unittest.TestCase): @classmethod def setUpClass(self): clean() self.output = run_zx_spec() def test_zx_spec_header_displayed(self): self.assertRegexpMatches(self.output, 'ZX Spec - The TDD Framework') def test_all_tests_pass(self): self.assertRegexpMatches(self.output, 'Pass: 0, Fail: 0') @classmethod def tearDownClass(self): clean() def clean(): for f in glob.glob("printout.*"): os.remove(f) def run_zx_spec(): ZX_SPEC_OUTPUT_FILE = "printout.txt" proc = subprocess.Popen([ "fuse", "--tape", "bin/zx-spec-test.tap", "--auto-load", "--no-autosave-settings"]) wait_count = 0 while not os.path.exists(ZX_SPEC_OUTPUT_FILE): time.sleep(0.1) wait_count += 1 if wait_count == 20: raise 'Output file not produced in time' time.sleep(1) proc.kill() with open(ZX_SPEC_OUTPUT_FILE, 'r') as f: return f.read() if __name__ == '__main__': unittest.main()
// ... existing code ... class ZxSpecTestCase(unittest.TestCase): @classmethod def setUpClass(self): clean() self.output = run_zx_spec() // ... modified code ... def test_zx_spec_header_displayed(self): self.assertRegexpMatches(self.output, 'ZX Spec - The TDD Framework') def test_all_tests_pass(self): self.assertRegexpMatches(self.output, 'Pass: 0, Fail: 0') @classmethod def tearDownClass(self): clean() ... def run_zx_spec(): ZX_SPEC_OUTPUT_FILE = "printout.txt" proc = subprocess.Popen([ "fuse", "--tape", "bin/zx-spec-test.tap", "--auto-load", "--no-autosave-settings"]) wait_count = 0 while not os.path.exists(ZX_SPEC_OUTPUT_FILE): time.sleep(0.1) wait_count += 1 if wait_count == 20: raise 'Output file not produced in time' time.sleep(1) proc.kill() with open(ZX_SPEC_OUTPUT_FILE, 'r') as f: return f.read() if __name__ == '__main__': // ... rest of the code ...
aec62c210bc1746c6fefa12030ada548730faf62
plugins/titlegiver/titlegiver.py
plugins/titlegiver/titlegiver.py
import sys import plugin import re import urllib2 from utils import url_parser from twisted.python import log title_re = re.compile(r'<title>(.*?)</title>', re.IGNORECASE) class Titlegiver(plugin.Plugin): def __init__(self): plugin.Plugin.__init__(self, "Titlegiver") @staticmethod def find_title_url(url): return Titlegiver.find_title(urllib2.urlopen(url).read()) @staticmethod def find_title(text): return title_re.search(text).group(1) def privmsg(self, server_id, user, channel, message): for url in url_parser.find_urls(message): try: self.say(server_id, channel, Titlegiver.find_title_url(url)) except: log.msg("Unable to find title for:", url) if __name__ == "__main__": sys.exit(Titlegiver.run())
import sys import plugin import re import urllib2 from utils import url_parser from twisted.python import log title_re = re.compile(r'<title>(.*?)</title>', re.IGNORECASE|re.DOTALL) class Titlegiver(plugin.Plugin): def __init__(self): plugin.Plugin.__init__(self, "Titlegiver") @staticmethod def find_title_url(url): return Titlegiver.find_title(urllib2.urlopen(url).read()).strip() @staticmethod def find_title(text): return title_re.search(text).group(1) def privmsg(self, server_id, user, channel, message): for url in url_parser.find_urls(message): try: self.say(server_id, channel, Titlegiver.find_title_url(url)) except: log.msg("Unable to find title for:", url) if __name__ == "__main__": sys.exit(Titlegiver.run())
Fix for titles containing cr
Fix for titles containing cr
Python
mit
Tigge/platinumshrimp
import sys import plugin import re import urllib2 from utils import url_parser from twisted.python import log - title_re = re.compile(r'<title>(.*?)</title>', re.IGNORECASE) + title_re = re.compile(r'<title>(.*?)</title>', re.IGNORECASE|re.DOTALL) class Titlegiver(plugin.Plugin): def __init__(self): plugin.Plugin.__init__(self, "Titlegiver") @staticmethod def find_title_url(url): - return Titlegiver.find_title(urllib2.urlopen(url).read()) + return Titlegiver.find_title(urllib2.urlopen(url).read()).strip() @staticmethod def find_title(text): return title_re.search(text).group(1) def privmsg(self, server_id, user, channel, message): for url in url_parser.find_urls(message): try: self.say(server_id, channel, Titlegiver.find_title_url(url)) except: log.msg("Unable to find title for:", url) if __name__ == "__main__": sys.exit(Titlegiver.run())
Fix for titles containing cr
## Code Before: import sys import plugin import re import urllib2 from utils import url_parser from twisted.python import log title_re = re.compile(r'<title>(.*?)</title>', re.IGNORECASE) class Titlegiver(plugin.Plugin): def __init__(self): plugin.Plugin.__init__(self, "Titlegiver") @staticmethod def find_title_url(url): return Titlegiver.find_title(urllib2.urlopen(url).read()) @staticmethod def find_title(text): return title_re.search(text).group(1) def privmsg(self, server_id, user, channel, message): for url in url_parser.find_urls(message): try: self.say(server_id, channel, Titlegiver.find_title_url(url)) except: log.msg("Unable to find title for:", url) if __name__ == "__main__": sys.exit(Titlegiver.run()) ## Instruction: Fix for titles containing cr ## Code After: import sys import plugin import re import urllib2 from utils import url_parser from twisted.python import log title_re = re.compile(r'<title>(.*?)</title>', re.IGNORECASE|re.DOTALL) class Titlegiver(plugin.Plugin): def __init__(self): plugin.Plugin.__init__(self, "Titlegiver") @staticmethod def find_title_url(url): return Titlegiver.find_title(urllib2.urlopen(url).read()).strip() @staticmethod def find_title(text): return title_re.search(text).group(1) def privmsg(self, server_id, user, channel, message): for url in url_parser.find_urls(message): try: self.say(server_id, channel, Titlegiver.find_title_url(url)) except: log.msg("Unable to find title for:", url) if __name__ == "__main__": sys.exit(Titlegiver.run())
// ... existing code ... title_re = re.compile(r'<title>(.*?)</title>', re.IGNORECASE|re.DOTALL) // ... modified code ... def find_title_url(url): return Titlegiver.find_title(urllib2.urlopen(url).read()).strip() // ... rest of the code ...
d7c6a7f78c8620e0e01e57eb082860e90f782a30
parsl/tests/test_swift.py
parsl/tests/test_swift.py
import parsl from parsl import * parsl.set_stream_logger() from parsl.executors.swift_t import * def foo(x, y): return x * y def slow_foo(x, y): import time time.sleep(x) return x * y def bad_foo(x, y): time.sleep(x) return x * y def test_simple(): print("Start") tex = TurbineExecutor() x = tex.submit(foo, 5, 10) print("Got : ", x) print("X result : ", x.result()) assert x.result() == 50, "X != 50" print("done") def test_except(): print("Start") tex = TurbineExecutor() x = tex.submit(bad_foo, 5, 10) print("Got : ", x) print("X exception : ", x.exception()) print("X result : ", x.result()) print("done") if __name__ == "__main__": # test_simple() test_except() exit(0) futs = {} for i in range(0, 1): futs[i] = tex.submit(slow_foo, 3, 10) x.result(timeout=10) for x in range(0, 10): print(futs) time.sleep(4) print("Done")
from nose.tools import assert_raises import parsl from parsl import * parsl.set_stream_logger() from parsl.executors.swift_t import * def foo(x, y): return x * y def slow_foo(x, y): import time time.sleep(x) return x * y def bad_foo(x, y): time.sleep(x) return x * y def test_simple(): print("Start") tex = TurbineExecutor() x = tex.submit(foo, 5, 10) print("Got: ", x) print("X result: ", x.result()) assert x.result() == 50, "X != 50" print("done") def test_slow(): futs = {} tex = TurbineExecutor() for i in range(0, 3): futs[i] = tex.submit(slow_foo, 1, 2) total = sum([futs[i].result(timeout=10) for i in futs]) assert total == 6, "expected 6, got {}".format(total) def test_except(): def get_bad_result(): tex = TurbineExecutor() x = tex.submit(bad_foo, 5, 10) return x.result() assert_raises(NameError, get_bad_result) if __name__ == "__main__": # test_simple() # test_slow() test_except() print("Done")
Make `test_except` swift test pass
Make `test_except` swift test pass Currently it is expected to fail. This asserts that the correct exception is raised. Fixes #155.
Python
apache-2.0
Parsl/parsl,swift-lang/swift-e-lab,Parsl/parsl,Parsl/parsl,swift-lang/swift-e-lab,Parsl/parsl
+ from nose.tools import assert_raises import parsl from parsl import * parsl.set_stream_logger() from parsl.executors.swift_t import * def foo(x, y): return x * y def slow_foo(x, y): import time time.sleep(x) return x * y - def bad_foo(x, y): time.sleep(x) return x * y - def test_simple(): print("Start") tex = TurbineExecutor() x = tex.submit(foo, 5, 10) - print("Got : ", x) + print("Got: ", x) - print("X result : ", x.result()) + print("X result: ", x.result()) assert x.result() == 50, "X != 50" print("done") + def test_slow(): + futs = {} + tex = TurbineExecutor() + for i in range(0, 3): + futs[i] = tex.submit(slow_foo, 1, 2) + + total = sum([futs[i].result(timeout=10) for i in futs]) + assert total == 6, "expected 6, got {}".format(total) def test_except(): - print("Start") + def get_bad_result(): - tex = TurbineExecutor() + tex = TurbineExecutor() - x = tex.submit(bad_foo, 5, 10) + x = tex.submit(bad_foo, 5, 10) - print("Got : ", x) + return x.result() - print("X exception : ", x.exception()) - print("X result : ", x.result()) - print("done") + assert_raises(NameError, get_bad_result) if __name__ == "__main__": # test_simple() + # test_slow() test_except() - exit(0) - futs = {} - for i in range(0, 1): - futs[i] = tex.submit(slow_foo, 3, 10) - - x.result(timeout=10) - for x in range(0, 10): - print(futs) - time.sleep(4) print("Done")
Make `test_except` swift test pass
## Code Before: import parsl from parsl import * parsl.set_stream_logger() from parsl.executors.swift_t import * def foo(x, y): return x * y def slow_foo(x, y): import time time.sleep(x) return x * y def bad_foo(x, y): time.sleep(x) return x * y def test_simple(): print("Start") tex = TurbineExecutor() x = tex.submit(foo, 5, 10) print("Got : ", x) print("X result : ", x.result()) assert x.result() == 50, "X != 50" print("done") def test_except(): print("Start") tex = TurbineExecutor() x = tex.submit(bad_foo, 5, 10) print("Got : ", x) print("X exception : ", x.exception()) print("X result : ", x.result()) print("done") if __name__ == "__main__": # test_simple() test_except() exit(0) futs = {} for i in range(0, 1): futs[i] = tex.submit(slow_foo, 3, 10) x.result(timeout=10) for x in range(0, 10): print(futs) time.sleep(4) print("Done") ## Instruction: Make `test_except` swift test pass ## Code After: from nose.tools import assert_raises import parsl from parsl import * parsl.set_stream_logger() from parsl.executors.swift_t import * def foo(x, y): return x * y def slow_foo(x, y): import time time.sleep(x) return x * y def bad_foo(x, y): time.sleep(x) return x * y def test_simple(): print("Start") tex = TurbineExecutor() x = tex.submit(foo, 5, 10) print("Got: ", x) print("X result: ", x.result()) assert x.result() == 50, "X != 50" print("done") def test_slow(): futs = {} tex = TurbineExecutor() for i in range(0, 3): futs[i] = tex.submit(slow_foo, 1, 2) total = sum([futs[i].result(timeout=10) for i in futs]) assert total == 6, "expected 6, got {}".format(total) def test_except(): def get_bad_result(): tex = TurbineExecutor() x = tex.submit(bad_foo, 5, 10) return x.result() assert_raises(NameError, get_bad_result) if __name__ == "__main__": # test_simple() # test_slow() test_except() print("Done")
// ... existing code ... from nose.tools import assert_raises // ... modified code ... def bad_foo(x, y): ... return x * y ... x = tex.submit(foo, 5, 10) print("Got: ", x) print("X result: ", x.result()) assert x.result() == 50, "X != 50" ... def test_slow(): futs = {} tex = TurbineExecutor() for i in range(0, 3): futs[i] = tex.submit(slow_foo, 1, 2) total = sum([futs[i].result(timeout=10) for i in futs]) assert total == 6, "expected 6, got {}".format(total) ... def test_except(): def get_bad_result(): tex = TurbineExecutor() x = tex.submit(bad_foo, 5, 10) return x.result() assert_raises(NameError, get_bad_result) ... # test_simple() # test_slow() test_except() // ... rest of the code ...
8e58d7cccb837254cc433c7533bff119cc19645d
javascript_settings/templatetags/javascript_settings_tags.py
javascript_settings/templatetags/javascript_settings_tags.py
from django import template from django.utils import simplejson from javascript_settings.configuration_builder import \ DEFAULT_CONFIGURATION_BUILDER register = template.Library() @register.tag(name='javascript_settings') def do_javascript_settings(parser, token): """ Returns a node with generated configuration. """ return JavascriptConfigurationNode() class JavascriptConfigurationNode(template.Node): """ Represents a node that renders JavaScript configuration. """ def __init__(self): pass def render(self, context): """ Renders JS configuration. """ return 'var configuration = ' + simplejson.dumps( DEFAULT_CONFIGURATION_BUILDER.get_configuration() ) + ';'
import json from django import template from javascript_settings.configuration_builder import \ DEFAULT_CONFIGURATION_BUILDER register = template.Library() @register.tag(name='javascript_settings') def do_javascript_settings(parser, token): """ Returns a node with generated configuration. """ return JavascriptConfigurationNode() class JavascriptConfigurationNode(template.Node): """ Represents a node that renders JavaScript configuration. """ def __init__(self): pass def render(self, context): """ Renders JS configuration. """ return 'var configuration = ' + json.dumps( DEFAULT_CONFIGURATION_BUILDER.get_configuration() ) + ';'
Use json instead of django.utils.simplejson.
Use json instead of django.utils.simplejson.
Python
mit
pozytywnie/django-javascript-settings
+ import json + from django import template - from django.utils import simplejson from javascript_settings.configuration_builder import \ DEFAULT_CONFIGURATION_BUILDER register = template.Library() @register.tag(name='javascript_settings') def do_javascript_settings(parser, token): """ Returns a node with generated configuration. """ return JavascriptConfigurationNode() class JavascriptConfigurationNode(template.Node): """ Represents a node that renders JavaScript configuration. """ def __init__(self): pass def render(self, context): """ Renders JS configuration. """ - return 'var configuration = ' + simplejson.dumps( + return 'var configuration = ' + json.dumps( DEFAULT_CONFIGURATION_BUILDER.get_configuration() ) + ';'
Use json instead of django.utils.simplejson.
## Code Before: from django import template from django.utils import simplejson from javascript_settings.configuration_builder import \ DEFAULT_CONFIGURATION_BUILDER register = template.Library() @register.tag(name='javascript_settings') def do_javascript_settings(parser, token): """ Returns a node with generated configuration. """ return JavascriptConfigurationNode() class JavascriptConfigurationNode(template.Node): """ Represents a node that renders JavaScript configuration. """ def __init__(self): pass def render(self, context): """ Renders JS configuration. """ return 'var configuration = ' + simplejson.dumps( DEFAULT_CONFIGURATION_BUILDER.get_configuration() ) + ';' ## Instruction: Use json instead of django.utils.simplejson. ## Code After: import json from django import template from javascript_settings.configuration_builder import \ DEFAULT_CONFIGURATION_BUILDER register = template.Library() @register.tag(name='javascript_settings') def do_javascript_settings(parser, token): """ Returns a node with generated configuration. """ return JavascriptConfigurationNode() class JavascriptConfigurationNode(template.Node): """ Represents a node that renders JavaScript configuration. """ def __init__(self): pass def render(self, context): """ Renders JS configuration. """ return 'var configuration = ' + json.dumps( DEFAULT_CONFIGURATION_BUILDER.get_configuration() ) + ';'
# ... existing code ... import json from django import template # ... modified code ... """ return 'var configuration = ' + json.dumps( DEFAULT_CONFIGURATION_BUILDER.get_configuration() # ... rest of the code ...