commit
stringlengths
40
40
old_file
stringlengths
4
118
new_file
stringlengths
4
118
old_contents
stringlengths
10
3.52k
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
7
43k
ndiff
stringlengths
52
3.32k
instruction
stringlengths
16
444
content
stringlengths
133
4.32k
fuzzy_diff
stringlengths
17
3.24k
6c32e39e2e51a80ebc9e31e88e22cc4aa39f7466
chainer/functions/copy.py
chainer/functions/copy.py
from chainer import cuda from chainer import function class Copy(function.Function): """Copy an input GPUArray onto another device.""" def __init__(self, out_device): self.out_device = out_device def forward_cpu(self, x): return x[0].copy(), def forward_gpu(self, x): return cuda.copy(x[0], out_device=self.out_device), def backward_cpu(self, x, gy): return gy[0].copy(), def backward_gpu(self, x, gy): return cuda.copy(gy[0], out_device=cuda.get_device(x[0])), def copy(x, dst): """Copies the input variable onto the specified device. This function copies the array of input variable onto the device specified by ``dst`` if the original array is on GPU, and otherwise just copies the array within host memory. Args: x (~chainer.Variable): Variable to be copied. dst: Target device specifier. Returns: ~chainer.Variable: Output variable. """ return Copy(dst)(x)
import numpy from chainer import cuda from chainer import function from chainer.utils import type_check class Copy(function.Function): """Copy an input GPUArray onto another device.""" def __init__(self, out_device): self.out_device = out_device def check_type_forward(self, in_types): type_check.expect( in_types.size() == 1, in_types[0].dtype == numpy.float32 ) def check_type_backward(self, in_types, out_types): type_check.expect( out_types.size() == 1, in_types[0].dtype == out_types[0].dtype, in_types[0].ndim == out_types[0].ndim, in_types[0].shape == out_types[0].shape ) def forward_cpu(self, x): return x[0].copy(), def forward_gpu(self, x): return cuda.copy(x[0], out_device=self.out_device), def backward_cpu(self, x, gy): return gy[0].copy(), def backward_gpu(self, x, gy): return cuda.copy(gy[0], out_device=cuda.get_device(x[0])), def copy(x, dst): """Copies the input variable onto the specified device. This function copies the array of input variable onto the device specified by ``dst`` if the original array is on GPU, and otherwise just copies the array within host memory. Args: x (~chainer.Variable): Variable to be copied. dst: Target device specifier. Returns: ~chainer.Variable: Output variable. """ return Copy(dst)(x)
Add unittest(cpu-only) and typecheck for Copy
Add unittest(cpu-only) and typecheck for Copy
Python
mit
chainer/chainer,sinhrks/chainer,ronekko/chainer,ktnyt/chainer,chainer/chainer,jnishi/chainer,niboshi/chainer,tkerola/chainer,elviswf/chainer,tscohen/chainer,muupan/chainer,keisuke-umezawa/chainer,Kaisuke5/chainer,woodshop/chainer,jnishi/chainer,keisuke-umezawa/chainer,tigerneil/chainer,cupy/cupy,niboshi/chainer,chainer/chainer,hvy/chainer,aonotas/chainer,t-abe/chainer,wkentaro/chainer,hvy/chainer,keisuke-umezawa/chainer,umitanuki/chainer,t-abe/chainer,okuta/chainer,kiyukuta/chainer,ktnyt/chainer,wkentaro/chainer,ktnyt/chainer,cupy/cupy,okuta/chainer,hvy/chainer,cemoody/chainer,woodshop/complex-chainer,hidenori-t/chainer,ysekky/chainer,hvy/chainer,ikasumi/chainer,benob/chainer,kashif/chainer,sinhrks/chainer,kikusu/chainer,sou81821/chainer,okuta/chainer,pfnet/chainer,1986ks/chainer,cupy/cupy,kikusu/chainer,wkentaro/chainer,muupan/chainer,kuwa32/chainer,wavelets/chainer,keisuke-umezawa/chainer,AlpacaDB/chainer,ktnyt/chainer,jnishi/chainer,ytoyama/yans_chainer_hackathon,bayerj/chainer,delta2323/chainer,niboshi/chainer,niboshi/chainer,anaruse/chainer,yanweifu/chainer,rezoo/chainer,wkentaro/chainer,truongdq/chainer,okuta/chainer,jnishi/chainer,masia02/chainer,jfsantos/chainer,truongdq/chainer,minhpqn/chainer,benob/chainer,laysakura/chainer,cupy/cupy,chainer/chainer,AlpacaDB/chainer
+ import numpy + from chainer import cuda from chainer import function + from chainer.utils import type_check class Copy(function.Function): """Copy an input GPUArray onto another device.""" def __init__(self, out_device): self.out_device = out_device + + def check_type_forward(self, in_types): + type_check.expect( + in_types.size() == 1, + in_types[0].dtype == numpy.float32 + ) + + def check_type_backward(self, in_types, out_types): + type_check.expect( + out_types.size() == 1, + in_types[0].dtype == out_types[0].dtype, + in_types[0].ndim == out_types[0].ndim, + in_types[0].shape == out_types[0].shape + ) def forward_cpu(self, x): return x[0].copy(), def forward_gpu(self, x): return cuda.copy(x[0], out_device=self.out_device), def backward_cpu(self, x, gy): return gy[0].copy(), def backward_gpu(self, x, gy): return cuda.copy(gy[0], out_device=cuda.get_device(x[0])), def copy(x, dst): """Copies the input variable onto the specified device. This function copies the array of input variable onto the device specified by ``dst`` if the original array is on GPU, and otherwise just copies the array within host memory. Args: x (~chainer.Variable): Variable to be copied. dst: Target device specifier. Returns: ~chainer.Variable: Output variable. """ return Copy(dst)(x)
Add unittest(cpu-only) and typecheck for Copy
## Code Before: from chainer import cuda from chainer import function class Copy(function.Function): """Copy an input GPUArray onto another device.""" def __init__(self, out_device): self.out_device = out_device def forward_cpu(self, x): return x[0].copy(), def forward_gpu(self, x): return cuda.copy(x[0], out_device=self.out_device), def backward_cpu(self, x, gy): return gy[0].copy(), def backward_gpu(self, x, gy): return cuda.copy(gy[0], out_device=cuda.get_device(x[0])), def copy(x, dst): """Copies the input variable onto the specified device. This function copies the array of input variable onto the device specified by ``dst`` if the original array is on GPU, and otherwise just copies the array within host memory. Args: x (~chainer.Variable): Variable to be copied. dst: Target device specifier. Returns: ~chainer.Variable: Output variable. """ return Copy(dst)(x) ## Instruction: Add unittest(cpu-only) and typecheck for Copy ## Code After: import numpy from chainer import cuda from chainer import function from chainer.utils import type_check class Copy(function.Function): """Copy an input GPUArray onto another device.""" def __init__(self, out_device): self.out_device = out_device def check_type_forward(self, in_types): type_check.expect( in_types.size() == 1, in_types[0].dtype == numpy.float32 ) def check_type_backward(self, in_types, out_types): type_check.expect( out_types.size() == 1, in_types[0].dtype == out_types[0].dtype, in_types[0].ndim == out_types[0].ndim, in_types[0].shape == out_types[0].shape ) def forward_cpu(self, x): return x[0].copy(), def forward_gpu(self, x): return cuda.copy(x[0], out_device=self.out_device), def backward_cpu(self, x, gy): return gy[0].copy(), def backward_gpu(self, x, gy): return cuda.copy(gy[0], out_device=cuda.get_device(x[0])), def copy(x, dst): """Copies the input variable onto the specified device. This function copies the array of input variable onto the device specified by ``dst`` if the original array is on GPU, and otherwise just copies the array within host memory. Args: x (~chainer.Variable): Variable to be copied. dst: Target device specifier. Returns: ~chainer.Variable: Output variable. """ return Copy(dst)(x)
# ... existing code ... import numpy from chainer import cuda from chainer import function from chainer.utils import type_check # ... modified code ... def __init__(self, out_device): self.out_device = out_device def check_type_forward(self, in_types): type_check.expect( in_types.size() == 1, in_types[0].dtype == numpy.float32 ) def check_type_backward(self, in_types, out_types): type_check.expect( out_types.size() == 1, in_types[0].dtype == out_types[0].dtype, in_types[0].ndim == out_types[0].ndim, in_types[0].shape == out_types[0].shape ) def forward_cpu(self, x): # ... rest of the code ...
15beb35fff1ea343dc42cf4acc0e9ad5e64cef33
abilian/testing/__init__.py
abilian/testing/__init__.py
from flask.ext.testing import TestCase from abilian.application import Application from abilian.core.entities import db class TestConfig(object): SQLALCHEMY_DATABASE_URI = "sqlite://" SQLALCHEMY_ECHO = False class BaseTestCase(TestCase): config_class = TestConfig def create_app(self): config = self.config_class() self.app = Application(config) return self.app def setUp(self): self.app.create_db() self.session = db.session def tearDown(self): db.session.remove() db.drop_all() db.engine.dispose()
from flask.ext.testing import TestCase from abilian.application import Application from abilian.core.entities import db class TestConfig(object): SQLALCHEMY_DATABASE_URI = "sqlite://" SQLALCHEMY_ECHO = False TESTING = True class BaseTestCase(TestCase): config_class = TestConfig application_class = Application def create_app(self): config = self.config_class() self.app = self.application_class(config) return self.app def setUp(self): self.app.create_db() self.session = db.session def tearDown(self): db.session.remove() db.drop_all() db.engine.dispose()
Add TESTING-True in test config.
Add TESTING-True in test config.
Python
lgpl-2.1
abilian/abilian-core,abilian/abilian-core,abilian/abilian-core,abilian/abilian-core,abilian/abilian-core
from flask.ext.testing import TestCase from abilian.application import Application from abilian.core.entities import db class TestConfig(object): SQLALCHEMY_DATABASE_URI = "sqlite://" SQLALCHEMY_ECHO = False + TESTING = True class BaseTestCase(TestCase): config_class = TestConfig + application_class = Application def create_app(self): config = self.config_class() - self.app = Application(config) + self.app = self.application_class(config) return self.app def setUp(self): self.app.create_db() self.session = db.session def tearDown(self): db.session.remove() db.drop_all() db.engine.dispose()
Add TESTING-True in test config.
## Code Before: from flask.ext.testing import TestCase from abilian.application import Application from abilian.core.entities import db class TestConfig(object): SQLALCHEMY_DATABASE_URI = "sqlite://" SQLALCHEMY_ECHO = False class BaseTestCase(TestCase): config_class = TestConfig def create_app(self): config = self.config_class() self.app = Application(config) return self.app def setUp(self): self.app.create_db() self.session = db.session def tearDown(self): db.session.remove() db.drop_all() db.engine.dispose() ## Instruction: Add TESTING-True in test config. ## Code After: from flask.ext.testing import TestCase from abilian.application import Application from abilian.core.entities import db class TestConfig(object): SQLALCHEMY_DATABASE_URI = "sqlite://" SQLALCHEMY_ECHO = False TESTING = True class BaseTestCase(TestCase): config_class = TestConfig application_class = Application def create_app(self): config = self.config_class() self.app = self.application_class(config) return self.app def setUp(self): self.app.create_db() self.session = db.session def tearDown(self): db.session.remove() db.drop_all() db.engine.dispose()
... SQLALCHEMY_DATABASE_URI = "sqlite://" SQLALCHEMY_ECHO = False TESTING = True ... config_class = TestConfig application_class = Application def create_app(self): config = self.config_class() self.app = self.application_class(config) return self.app ...
7a3ee543960495ed720cfcaccbbe7a8afcfed0dd
l10n_br_coa_generic/hooks.py
l10n_br_coa_generic/hooks.py
from odoo import api, tools, SUPERUSER_ID def post_init_hook(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) coa_generic_tmpl = env.ref( 'l10n_br_coa_generic.l10n_br_coa_generic_template') if env['ir.module.module'].search_count([ ('name', '=', 'l10n_br_account'), ('state', '=', 'installed'), ]): from odoo.addons.l10n_br_account.hooks import load_fiscal_taxes # Relate fiscal taxes to account taxes. load_fiscal_taxes(env, coa_generic_tmpl) # Load COA to Demo Company if not tools.config.get('without_demo'): env.user.company_id = env.ref( 'l10n_br_fiscal.empresa_lucro_presumido') coa_generic_tmpl.try_loading_for_current_company()
from odoo import api, tools, SUPERUSER_ID def post_init_hook(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) coa_generic_tmpl = env.ref( 'l10n_br_coa_generic.l10n_br_coa_generic_template') if env['ir.module.module'].search_count([ ('name', '=', 'l10n_br_account'), ('state', '=', 'installed'), ]): from odoo.addons.l10n_br_account.hooks import load_fiscal_taxes # Relate fiscal taxes to account taxes. load_fiscal_taxes(env, coa_generic_tmpl) # Load COA to Demo Company if not tools.config.get('without_demo'): user_admin = env.ref('base.user_admin') user_admin.company_id = env.ref( 'l10n_br_base.empresa_lucro_presumido') coa_generic_tmpl.sudo( user=user_admin.id).try_loading_for_current_company() user_admin.company_id = env.ref('base.main_company')
Use admin user to create COA
[FIX] l10n_br_coa_generic: Use admin user to create COA
Python
agpl-3.0
akretion/l10n-brazil,akretion/l10n-brazil,OCA/l10n-brazil,akretion/l10n-brazil,OCA/l10n-brazil,OCA/l10n-brazil
from odoo import api, tools, SUPERUSER_ID def post_init_hook(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) coa_generic_tmpl = env.ref( 'l10n_br_coa_generic.l10n_br_coa_generic_template') if env['ir.module.module'].search_count([ ('name', '=', 'l10n_br_account'), ('state', '=', 'installed'), ]): from odoo.addons.l10n_br_account.hooks import load_fiscal_taxes # Relate fiscal taxes to account taxes. load_fiscal_taxes(env, coa_generic_tmpl) # Load COA to Demo Company if not tools.config.get('without_demo'): + user_admin = env.ref('base.user_admin') - env.user.company_id = env.ref( + user_admin.company_id = env.ref( - 'l10n_br_fiscal.empresa_lucro_presumido') + 'l10n_br_base.empresa_lucro_presumido') - coa_generic_tmpl.try_loading_for_current_company() + coa_generic_tmpl.sudo( + user=user_admin.id).try_loading_for_current_company() + user_admin.company_id = env.ref('base.main_company')
Use admin user to create COA
## Code Before: from odoo import api, tools, SUPERUSER_ID def post_init_hook(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) coa_generic_tmpl = env.ref( 'l10n_br_coa_generic.l10n_br_coa_generic_template') if env['ir.module.module'].search_count([ ('name', '=', 'l10n_br_account'), ('state', '=', 'installed'), ]): from odoo.addons.l10n_br_account.hooks import load_fiscal_taxes # Relate fiscal taxes to account taxes. load_fiscal_taxes(env, coa_generic_tmpl) # Load COA to Demo Company if not tools.config.get('without_demo'): env.user.company_id = env.ref( 'l10n_br_fiscal.empresa_lucro_presumido') coa_generic_tmpl.try_loading_for_current_company() ## Instruction: Use admin user to create COA ## Code After: from odoo import api, tools, SUPERUSER_ID def post_init_hook(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) coa_generic_tmpl = env.ref( 'l10n_br_coa_generic.l10n_br_coa_generic_template') if env['ir.module.module'].search_count([ ('name', '=', 'l10n_br_account'), ('state', '=', 'installed'), ]): from odoo.addons.l10n_br_account.hooks import load_fiscal_taxes # Relate fiscal taxes to account taxes. load_fiscal_taxes(env, coa_generic_tmpl) # Load COA to Demo Company if not tools.config.get('without_demo'): user_admin = env.ref('base.user_admin') user_admin.company_id = env.ref( 'l10n_br_base.empresa_lucro_presumido') coa_generic_tmpl.sudo( user=user_admin.id).try_loading_for_current_company() user_admin.company_id = env.ref('base.main_company')
... # Load COA to Demo Company if not tools.config.get('without_demo'): user_admin = env.ref('base.user_admin') user_admin.company_id = env.ref( 'l10n_br_base.empresa_lucro_presumido') coa_generic_tmpl.sudo( user=user_admin.id).try_loading_for_current_company() user_admin.company_id = env.ref('base.main_company') ...
2448e6ab81f8a2a0b320a07b42a3f8707ec918cb
chartflo/apps.py
chartflo/apps.py
from __future__ import unicode_literals import importlib from goerr import err from django.apps import AppConfig GENERATORS = {} cf = None def load_generator(modname, subgenerator=None): try: path = modname + ".chartflo" if subgenerator is not None: path = path + "." + subgenerator mod = importlib.import_module(path) generator = getattr(mod, "run") return generator except ImportError as e: if "No module named" not in str(e): err.new(e) return None except Exception as e: err.new(e, load_generator, "Error loading module") class ChartfloConfig(AppConfig): name = 'chartflo' verbose_name = "Chartflo" def ready(self): """ Load generators and initialize class instance """ global GENERATORS, cf from django.conf import settings apps = settings.INSTALLED_APPS generators = {} for app in apps: try: res = load_generator(app) if res is not None: generators[app] = res except Exception as e: err.new(e) GENERATORS = generators # Initialize class instance from chartflo.engine import ChartFlo cf = ChartFlo() if err.exists: err.trace()
from __future__ import unicode_literals import importlib from goerr import err from django.apps import AppConfig from chartflo.engine import ChartFlo GENERATORS = {} cf = ChartFlo() def load_generator(modname, subgenerator=None): try: path = modname + ".chartflo" if subgenerator is not None: path = path + "." + subgenerator mod = importlib.import_module(path) generator = getattr(mod, "run") return generator except ImportError as e: if "No module named" not in str(e): err.new(e) return None except Exception as e: err.new(e, load_generator, "Error loading module") class ChartfloConfig(AppConfig): name = 'chartflo' verbose_name = "Chartflo" def ready(self): """ Load generators and initialize class instance """ global GENERATORS, cf from django.conf import settings apps = settings.INSTALLED_APPS generators = {} for app in apps: try: res = load_generator(app) if res is not None: generators[app] = res except Exception as e: err.new(e, self.ready, "Can not initialize Chartflo generators") GENERATORS = generators if err.exists: err.trace()
Fix in app initialization for generators
Fix in app initialization for generators
Python
mit
synw/django-chartflo,synw/django-chartflo,synw/django-chartflo
from __future__ import unicode_literals import importlib from goerr import err from django.apps import AppConfig + from chartflo.engine import ChartFlo GENERATORS = {} - cf = None + cf = ChartFlo() def load_generator(modname, subgenerator=None): try: path = modname + ".chartflo" if subgenerator is not None: path = path + "." + subgenerator mod = importlib.import_module(path) generator = getattr(mod, "run") return generator except ImportError as e: if "No module named" not in str(e): err.new(e) return None except Exception as e: err.new(e, load_generator, "Error loading module") class ChartfloConfig(AppConfig): name = 'chartflo' verbose_name = "Chartflo" def ready(self): """ Load generators and initialize class instance """ global GENERATORS, cf from django.conf import settings apps = settings.INSTALLED_APPS generators = {} for app in apps: try: res = load_generator(app) if res is not None: generators[app] = res except Exception as e: - err.new(e) + err.new(e, self.ready, + "Can not initialize Chartflo generators") GENERATORS = generators - # Initialize class instance - from chartflo.engine import ChartFlo - cf = ChartFlo() if err.exists: err.trace()
Fix in app initialization for generators
## Code Before: from __future__ import unicode_literals import importlib from goerr import err from django.apps import AppConfig GENERATORS = {} cf = None def load_generator(modname, subgenerator=None): try: path = modname + ".chartflo" if subgenerator is not None: path = path + "." + subgenerator mod = importlib.import_module(path) generator = getattr(mod, "run") return generator except ImportError as e: if "No module named" not in str(e): err.new(e) return None except Exception as e: err.new(e, load_generator, "Error loading module") class ChartfloConfig(AppConfig): name = 'chartflo' verbose_name = "Chartflo" def ready(self): """ Load generators and initialize class instance """ global GENERATORS, cf from django.conf import settings apps = settings.INSTALLED_APPS generators = {} for app in apps: try: res = load_generator(app) if res is not None: generators[app] = res except Exception as e: err.new(e) GENERATORS = generators # Initialize class instance from chartflo.engine import ChartFlo cf = ChartFlo() if err.exists: err.trace() ## Instruction: Fix in app initialization for generators ## Code After: from __future__ import unicode_literals import importlib from goerr import err from django.apps import AppConfig from chartflo.engine import ChartFlo GENERATORS = {} cf = ChartFlo() def load_generator(modname, subgenerator=None): try: path = modname + ".chartflo" if subgenerator is not None: path = path + "." + subgenerator mod = importlib.import_module(path) generator = getattr(mod, "run") return generator except ImportError as e: if "No module named" not in str(e): err.new(e) return None except Exception as e: err.new(e, load_generator, "Error loading module") class ChartfloConfig(AppConfig): name = 'chartflo' verbose_name = "Chartflo" def ready(self): """ Load generators and initialize class instance """ global GENERATORS, cf from django.conf import settings apps = settings.INSTALLED_APPS generators = {} for app in apps: try: res = load_generator(app) if res is not None: generators[app] = res except Exception as e: err.new(e, self.ready, "Can not initialize Chartflo generators") GENERATORS = generators if err.exists: err.trace()
# ... existing code ... from goerr import err from django.apps import AppConfig from chartflo.engine import ChartFlo GENERATORS = {} cf = ChartFlo() # ... modified code ... generators[app] = res except Exception as e: err.new(e, self.ready, "Can not initialize Chartflo generators") GENERATORS = generators if err.exists: err.trace() # ... rest of the code ...
f5e67a55535b48afd95272083336d61dd1175765
administrator/admin.py
administrator/admin.py
from __future__ import unicode_literals from django.contrib import admin from .models import User # Register your models here. admin.site.register(User)
from __future__ import unicode_literals from django import forms from django.contrib import admin from django.contrib.auth.admin import UserAdmin as Admin from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import Group from .models import User class RegistrationForm(UserCreationForm): """A form for user creation. Email, username, password and role are given. """ email = forms.EmailField(required=True) class Meta: """Give some options (metadata) attached to the form.""" model = User fields = ('role',) def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.email = self.cleaned_data['email'] user.role = self.cleaned_data['role'] user.set_is_staff(user.role) if commit: user.save() return user class UserAdmin(Admin): """Represent a model in the admin interface.""" add_form = RegistrationForm # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin # overrides get_fieldsets to use this attribute when creating a user. add_fieldsets = ( (None, { 'fields': ('email', 'username', 'password1', 'password2', 'role')} ), ) admin.site.register(User, UserAdmin) admin.site.unregister(Group)
Add form for user creation
Add form for user creation
Python
mit
Social-projects-Rivne/Rv-025.Python,Social-projects-Rivne/Rv-025.Python,Social-projects-Rivne/Rv-025.Python
from __future__ import unicode_literals + from django import forms from django.contrib import admin + from django.contrib.auth.admin import UserAdmin as Admin + from django.contrib.auth.forms import UserCreationForm + from django.contrib.auth.models import Group + from .models import User - # Register your models here. - admin.site.register(User) + class RegistrationForm(UserCreationForm): + + """A form for user creation. + + Email, username, password and role are given. + """ + + email = forms.EmailField(required=True) + + + class Meta: + + """Give some options (metadata) attached to the form.""" + + model = User + fields = ('role',) + + + def save(self, commit=True): + user = super(RegistrationForm, self).save(commit=False) + user.email = self.cleaned_data['email'] + user.role = self.cleaned_data['role'] + user.set_is_staff(user.role) + if commit: + user.save() + return user + + + class UserAdmin(Admin): + + """Represent a model in the admin interface.""" + + add_form = RegistrationForm + + # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin + # overrides get_fieldsets to use this attribute when creating a user. + add_fieldsets = ( + (None, { + 'fields': ('email', 'username', 'password1', 'password2', 'role')} + ), + ) + + + admin.site.register(User, UserAdmin) + admin.site.unregister(Group) +
Add form for user creation
## Code Before: from __future__ import unicode_literals from django.contrib import admin from .models import User # Register your models here. admin.site.register(User) ## Instruction: Add form for user creation ## Code After: from __future__ import unicode_literals from django import forms from django.contrib import admin from django.contrib.auth.admin import UserAdmin as Admin from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import Group from .models import User class RegistrationForm(UserCreationForm): """A form for user creation. Email, username, password and role are given. """ email = forms.EmailField(required=True) class Meta: """Give some options (metadata) attached to the form.""" model = User fields = ('role',) def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.email = self.cleaned_data['email'] user.role = self.cleaned_data['role'] user.set_is_staff(user.role) if commit: user.save() return user class UserAdmin(Admin): """Represent a model in the admin interface.""" add_form = RegistrationForm # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin # overrides get_fieldsets to use this attribute when creating a user. add_fieldsets = ( (None, { 'fields': ('email', 'username', 'password1', 'password2', 'role')} ), ) admin.site.register(User, UserAdmin) admin.site.unregister(Group)
... from __future__ import unicode_literals from django import forms from django.contrib import admin from django.contrib.auth.admin import UserAdmin as Admin from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import Group from .models import User class RegistrationForm(UserCreationForm): """A form for user creation. Email, username, password and role are given. """ email = forms.EmailField(required=True) class Meta: """Give some options (metadata) attached to the form.""" model = User fields = ('role',) def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.email = self.cleaned_data['email'] user.role = self.cleaned_data['role'] user.set_is_staff(user.role) if commit: user.save() return user class UserAdmin(Admin): """Represent a model in the admin interface.""" add_form = RegistrationForm # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin # overrides get_fieldsets to use this attribute when creating a user. add_fieldsets = ( (None, { 'fields': ('email', 'username', 'password1', 'password2', 'role')} ), ) admin.site.register(User, UserAdmin) admin.site.unregister(Group) ...
839f9edc811776b8898cdf1fa7116eec9aef50a7
tests/xmlsec/test_templates.py
tests/xmlsec/test_templates.py
import xmlsec def test_create_signature_template(): node = xmlsec.create_signature_template() assert node.tag.endswith('Signature') assert node.xpath('*[local-name() = "SignatureValue"]') assert node.xpath('*[local-name() = "SignedInfo"]') return node def test_add_reference(): node = test_create_signature_template() ref = xmlsec.add_reference(node, uri=b'#_34275907093489075620748690') assert ref.tag.endswith('Reference') assert node.xpath('.//*[local-name() = "Reference"]')
import xmlsec def test_create_signature_template(): node = xmlsec.create_signature_template() assert node.tag.endswith('Signature') assert node.xpath('*[local-name() = "SignatureValue"]') assert node.xpath('*[local-name() = "SignedInfo"]') def test_add_reference(): node = xmlsec.create_signature_template() ref = xmlsec.add_reference(node, uri=b'#_34275907093489075620748690') assert ref.tag.endswith('Reference') assert node.xpath('.//*[local-name() = "Reference"]') def test_add_transform(): node = xmlsec.create_signature_template() ref = xmlsec.add_reference(node, uri=b'#_34275907093489075620748690') xmlsec.add_transform(ref, xmlsec.method.ENVELOPED) assert ref.xpath('.//*[local-name() = "Transform"]') def test_ensure_key_info(): node = xmlsec.create_signature_template() xmlsec.ensure_key_info(node) assert node.xpath('.//*[local-name() = "KeyInfo"]') def test_add_x509_data(): node = xmlsec.create_signature_template() info = xmlsec.ensure_key_info(node) xmlsec.add_x509_data(info) assert node.xpath('.//*[local-name() = "X509Data"]') def test_add_key_name(): node = xmlsec.create_signature_template() info = xmlsec.ensure_key_info(node) xmlsec.add_key_name(info, b'bob.pem') assert node.xpath('.//*[local-name() = "KeyName" and text() = "bob.pem"]')
Add additional tests for templates.
Add additional tests for templates.
Python
mit
devsisters/python-xmlsec,concordusapps/python-xmlsec,mehcode/python-xmlsec,devsisters/python-xmlsec,mehcode/python-xmlsec,concordusapps/python-xmlsec
import xmlsec def test_create_signature_template(): node = xmlsec.create_signature_template() assert node.tag.endswith('Signature') assert node.xpath('*[local-name() = "SignatureValue"]') assert node.xpath('*[local-name() = "SignedInfo"]') - return node - def test_add_reference(): - node = test_create_signature_template() + node = xmlsec.create_signature_template() ref = xmlsec.add_reference(node, uri=b'#_34275907093489075620748690') assert ref.tag.endswith('Reference') assert node.xpath('.//*[local-name() = "Reference"]') + + def test_add_transform(): + node = xmlsec.create_signature_template() + ref = xmlsec.add_reference(node, uri=b'#_34275907093489075620748690') + xmlsec.add_transform(ref, xmlsec.method.ENVELOPED) + + assert ref.xpath('.//*[local-name() = "Transform"]') + + + def test_ensure_key_info(): + node = xmlsec.create_signature_template() + xmlsec.ensure_key_info(node) + + assert node.xpath('.//*[local-name() = "KeyInfo"]') + + + def test_add_x509_data(): + node = xmlsec.create_signature_template() + info = xmlsec.ensure_key_info(node) + xmlsec.add_x509_data(info) + + assert node.xpath('.//*[local-name() = "X509Data"]') + + + def test_add_key_name(): + node = xmlsec.create_signature_template() + info = xmlsec.ensure_key_info(node) + xmlsec.add_key_name(info, b'bob.pem') + + assert node.xpath('.//*[local-name() = "KeyName" and text() = "bob.pem"]') +
Add additional tests for templates.
## Code Before: import xmlsec def test_create_signature_template(): node = xmlsec.create_signature_template() assert node.tag.endswith('Signature') assert node.xpath('*[local-name() = "SignatureValue"]') assert node.xpath('*[local-name() = "SignedInfo"]') return node def test_add_reference(): node = test_create_signature_template() ref = xmlsec.add_reference(node, uri=b'#_34275907093489075620748690') assert ref.tag.endswith('Reference') assert node.xpath('.//*[local-name() = "Reference"]') ## Instruction: Add additional tests for templates. ## Code After: import xmlsec def test_create_signature_template(): node = xmlsec.create_signature_template() assert node.tag.endswith('Signature') assert node.xpath('*[local-name() = "SignatureValue"]') assert node.xpath('*[local-name() = "SignedInfo"]') def test_add_reference(): node = xmlsec.create_signature_template() ref = xmlsec.add_reference(node, uri=b'#_34275907093489075620748690') assert ref.tag.endswith('Reference') assert node.xpath('.//*[local-name() = "Reference"]') def test_add_transform(): node = xmlsec.create_signature_template() ref = xmlsec.add_reference(node, uri=b'#_34275907093489075620748690') xmlsec.add_transform(ref, xmlsec.method.ENVELOPED) assert ref.xpath('.//*[local-name() = "Transform"]') def test_ensure_key_info(): node = xmlsec.create_signature_template() xmlsec.ensure_key_info(node) assert node.xpath('.//*[local-name() = "KeyInfo"]') def test_add_x509_data(): node = xmlsec.create_signature_template() info = xmlsec.ensure_key_info(node) xmlsec.add_x509_data(info) assert node.xpath('.//*[local-name() = "X509Data"]') def test_add_key_name(): node = xmlsec.create_signature_template() info = xmlsec.ensure_key_info(node) xmlsec.add_key_name(info, b'bob.pem') assert node.xpath('.//*[local-name() = "KeyName" and text() = "bob.pem"]')
// ... existing code ... assert node.xpath('*[local-name() = "SignedInfo"]') def test_add_reference(): node = xmlsec.create_signature_template() ref = xmlsec.add_reference(node, uri=b'#_34275907093489075620748690') // ... modified code ... assert ref.tag.endswith('Reference') assert node.xpath('.//*[local-name() = "Reference"]') def test_add_transform(): node = xmlsec.create_signature_template() ref = xmlsec.add_reference(node, uri=b'#_34275907093489075620748690') xmlsec.add_transform(ref, xmlsec.method.ENVELOPED) assert ref.xpath('.//*[local-name() = "Transform"]') def test_ensure_key_info(): node = xmlsec.create_signature_template() xmlsec.ensure_key_info(node) assert node.xpath('.//*[local-name() = "KeyInfo"]') def test_add_x509_data(): node = xmlsec.create_signature_template() info = xmlsec.ensure_key_info(node) xmlsec.add_x509_data(info) assert node.xpath('.//*[local-name() = "X509Data"]') def test_add_key_name(): node = xmlsec.create_signature_template() info = xmlsec.ensure_key_info(node) xmlsec.add_key_name(info, b'bob.pem') assert node.xpath('.//*[local-name() = "KeyName" and text() = "bob.pem"]') // ... rest of the code ...
28f9f7e85bb8353435db322138d1bd624934110f
london_commute_alert.py
london_commute_alert.py
import datetime import os import requests import sys def update(lines): url = 'http://api.tfl.gov.uk/Line/Mode/tube/Status' resp = requests.get(url).json() result = [] for el in resp: value = el['lineStatuses'][0] state = value['statusSeverityDescription'] if el['id'] in lines and state != 'Good Service': result.append('{}: {} ({})'.format( el['id'].capitalize(), state, value['reason'])) return result def email(delays): os.chdir(sys.path[0]) with open('curl_raw_command.sh') as f: raw_command = f.read() # Running on PythonAnywhere - Monday to Sunday. Skip on the weekend if delays and datetime.date.today().isoweekday() in range(1, 6): os.system(raw_command.format(subject='Tube delays for commute', body='\n\n'.join(delays))) def main(): commute_lines = ['metropolitan', 'jubilee', 'central'] email(update(commute_lines)) if __name__ == '__main__': main()
import datetime import os import requests import sys def update(lines): url = 'http://api.tfl.gov.uk/Line/Mode/tube/Status' resp = requests.get(url).json() result = [] for el in resp: value = el['lineStatuses'][0] state = value['statusSeverityDescription'] if el['id'] in lines and state != 'Good Service': result.append('{}: {} ({})'.format( el['id'].capitalize(), state, value['reason'])) return result def email(delays): # While tube is on shuttle service, don't email return os.chdir(sys.path[0]) with open('curl_raw_command.sh') as f: raw_command = f.read() # Running on PythonAnywhere - Monday to Sunday. Skip on the weekend if delays and datetime.date.today().isoweekday() in range(1, 6): os.system(raw_command.format(subject='Tube delays for commute', body='\n\n'.join(delays))) def main(): commute_lines = ['metropolitan', 'jubilee', 'central'] email(update(commute_lines)) if __name__ == '__main__': main()
Halt emails for time being
Halt emails for time being
Python
mit
noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit
import datetime import os import requests import sys def update(lines): url = 'http://api.tfl.gov.uk/Line/Mode/tube/Status' resp = requests.get(url).json() result = [] for el in resp: value = el['lineStatuses'][0] state = value['statusSeverityDescription'] if el['id'] in lines and state != 'Good Service': result.append('{}: {} ({})'.format( el['id'].capitalize(), state, value['reason'])) return result def email(delays): + # While tube is on shuttle service, don't email + return os.chdir(sys.path[0]) with open('curl_raw_command.sh') as f: raw_command = f.read() # Running on PythonAnywhere - Monday to Sunday. Skip on the weekend if delays and datetime.date.today().isoweekday() in range(1, 6): os.system(raw_command.format(subject='Tube delays for commute', body='\n\n'.join(delays))) def main(): commute_lines = ['metropolitan', 'jubilee', 'central'] email(update(commute_lines)) if __name__ == '__main__': main()
Halt emails for time being
## Code Before: import datetime import os import requests import sys def update(lines): url = 'http://api.tfl.gov.uk/Line/Mode/tube/Status' resp = requests.get(url).json() result = [] for el in resp: value = el['lineStatuses'][0] state = value['statusSeverityDescription'] if el['id'] in lines and state != 'Good Service': result.append('{}: {} ({})'.format( el['id'].capitalize(), state, value['reason'])) return result def email(delays): os.chdir(sys.path[0]) with open('curl_raw_command.sh') as f: raw_command = f.read() # Running on PythonAnywhere - Monday to Sunday. Skip on the weekend if delays and datetime.date.today().isoweekday() in range(1, 6): os.system(raw_command.format(subject='Tube delays for commute', body='\n\n'.join(delays))) def main(): commute_lines = ['metropolitan', 'jubilee', 'central'] email(update(commute_lines)) if __name__ == '__main__': main() ## Instruction: Halt emails for time being ## Code After: import datetime import os import requests import sys def update(lines): url = 'http://api.tfl.gov.uk/Line/Mode/tube/Status' resp = requests.get(url).json() result = [] for el in resp: value = el['lineStatuses'][0] state = value['statusSeverityDescription'] if el['id'] in lines and state != 'Good Service': result.append('{}: {} ({})'.format( el['id'].capitalize(), state, value['reason'])) return result def email(delays): # While tube is on shuttle service, don't email return os.chdir(sys.path[0]) with open('curl_raw_command.sh') as f: raw_command = f.read() # Running on PythonAnywhere - Monday to Sunday. Skip on the weekend if delays and datetime.date.today().isoweekday() in range(1, 6): os.system(raw_command.format(subject='Tube delays for commute', body='\n\n'.join(delays))) def main(): commute_lines = ['metropolitan', 'jubilee', 'central'] email(update(commute_lines)) if __name__ == '__main__': main()
// ... existing code ... def email(delays): # While tube is on shuttle service, don't email return os.chdir(sys.path[0]) with open('curl_raw_command.sh') as f: // ... rest of the code ...
266027514c740c30c0efae5fcd1e2932f1be9933
perfrunner/tests/ycsb2.py
perfrunner/tests/ycsb2.py
from perfrunner.helpers.cbmonitor import with_stats from perfrunner.helpers.local import clone_ycsb from perfrunner.helpers.worker import ycsb_data_load_task, ycsb_task from perfrunner.tests import PerfTest from perfrunner.tests.n1ql import N1QLTest class YCSBTest(PerfTest): def download_ycsb(self): clone_ycsb(repo=self.test_config.ycsb_settings.repo, branch=self.test_config.ycsb_settings.branch) def load(self, *args, **kwargs): PerfTest.load(self, task=ycsb_data_load_task) self.check_num_items() @with_stats def access(self, *args, **kwargs): PerfTest.access(self, task=ycsb_task) def _report_kpi(self): self.reporter.post_to_sf( self.metric_helper.parse_ycsb_throughput() ) def run(self): self.download_ycsb() self.load() self.wait_for_persistence() self.access() self.report_kpi() class YCSBN1QLTest(YCSBTest, N1QLTest): def run(self): self.download_ycsb() self.load() self.wait_for_persistence() self.build_index() self.access() self.report_kpi()
from perfrunner.helpers.cbmonitor import with_stats from perfrunner.helpers.local import clone_ycsb from perfrunner.helpers.worker import ycsb_data_load_task, ycsb_task from perfrunner.tests import PerfTest from perfrunner.tests.n1ql import N1QLTest class YCSBTest(PerfTest): def download_ycsb(self): clone_ycsb(repo=self.test_config.ycsb_settings.repo, branch=self.test_config.ycsb_settings.branch) def load(self, *args, **kwargs): PerfTest.load(self, task=ycsb_data_load_task) @with_stats def access(self, *args, **kwargs): PerfTest.access(self, task=ycsb_task) def _report_kpi(self): self.reporter.post_to_sf( self.metric_helper.parse_ycsb_throughput() ) def run(self): self.download_ycsb() self.load() self.wait_for_persistence() self.check_num_items() self.access() self.report_kpi() class YCSBN1QLTest(YCSBTest, N1QLTest): def run(self): self.download_ycsb() self.load() self.wait_for_persistence() self.check_num_items() self.build_index() self.access() self.report_kpi()
Check the number of items a little bit later
Check the number of items a little bit later Due to MB-22749 Change-Id: Icffe46201223efa5645644ca40b99dffe4f0fb31 Reviewed-on: http://review.couchbase.org/76413 Tested-by: Build Bot <[email protected]> Reviewed-by: Pavel Paulau <[email protected]>
Python
apache-2.0
couchbase/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,pavel-paulau/perfrunner,pavel-paulau/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,couchbase/perfrunner
from perfrunner.helpers.cbmonitor import with_stats from perfrunner.helpers.local import clone_ycsb from perfrunner.helpers.worker import ycsb_data_load_task, ycsb_task from perfrunner.tests import PerfTest from perfrunner.tests.n1ql import N1QLTest class YCSBTest(PerfTest): def download_ycsb(self): clone_ycsb(repo=self.test_config.ycsb_settings.repo, branch=self.test_config.ycsb_settings.branch) def load(self, *args, **kwargs): PerfTest.load(self, task=ycsb_data_load_task) - self.check_num_items() @with_stats def access(self, *args, **kwargs): PerfTest.access(self, task=ycsb_task) def _report_kpi(self): self.reporter.post_to_sf( self.metric_helper.parse_ycsb_throughput() ) def run(self): self.download_ycsb() self.load() self.wait_for_persistence() + self.check_num_items() self.access() self.report_kpi() class YCSBN1QLTest(YCSBTest, N1QLTest): def run(self): self.download_ycsb() self.load() self.wait_for_persistence() + self.check_num_items() self.build_index() self.access() self.report_kpi()
Check the number of items a little bit later
## Code Before: from perfrunner.helpers.cbmonitor import with_stats from perfrunner.helpers.local import clone_ycsb from perfrunner.helpers.worker import ycsb_data_load_task, ycsb_task from perfrunner.tests import PerfTest from perfrunner.tests.n1ql import N1QLTest class YCSBTest(PerfTest): def download_ycsb(self): clone_ycsb(repo=self.test_config.ycsb_settings.repo, branch=self.test_config.ycsb_settings.branch) def load(self, *args, **kwargs): PerfTest.load(self, task=ycsb_data_load_task) self.check_num_items() @with_stats def access(self, *args, **kwargs): PerfTest.access(self, task=ycsb_task) def _report_kpi(self): self.reporter.post_to_sf( self.metric_helper.parse_ycsb_throughput() ) def run(self): self.download_ycsb() self.load() self.wait_for_persistence() self.access() self.report_kpi() class YCSBN1QLTest(YCSBTest, N1QLTest): def run(self): self.download_ycsb() self.load() self.wait_for_persistence() self.build_index() self.access() self.report_kpi() ## Instruction: Check the number of items a little bit later ## Code After: from perfrunner.helpers.cbmonitor import with_stats from perfrunner.helpers.local import clone_ycsb from perfrunner.helpers.worker import ycsb_data_load_task, ycsb_task from perfrunner.tests import PerfTest from perfrunner.tests.n1ql import N1QLTest class YCSBTest(PerfTest): def download_ycsb(self): clone_ycsb(repo=self.test_config.ycsb_settings.repo, branch=self.test_config.ycsb_settings.branch) def load(self, *args, **kwargs): PerfTest.load(self, task=ycsb_data_load_task) @with_stats def access(self, *args, **kwargs): PerfTest.access(self, task=ycsb_task) def _report_kpi(self): self.reporter.post_to_sf( self.metric_helper.parse_ycsb_throughput() ) def run(self): self.download_ycsb() self.load() self.wait_for_persistence() self.check_num_items() self.access() self.report_kpi() class YCSBN1QLTest(YCSBTest, N1QLTest): def run(self): self.download_ycsb() self.load() self.wait_for_persistence() self.check_num_items() self.build_index() self.access() self.report_kpi()
# ... existing code ... def load(self, *args, **kwargs): PerfTest.load(self, task=ycsb_data_load_task) @with_stats # ... modified code ... self.load() self.wait_for_persistence() self.check_num_items() self.access() ... self.load() self.wait_for_persistence() self.check_num_items() self.build_index() # ... rest of the code ...
16d0f3f0ca4ce59f08e598b6f9f25bb6dc8e1713
benchmark/benchmark.py
benchmark/benchmark.py
import time import sys from utils import format_duration if sys.platform == "win32": default_timer = time.clock else: default_timer = time.time class Benchmark(): def __init__(self, func, name="", repeat=5): self.func = func self.repeat = repeat self.name = name self.verbose = False def run(self, conn): self.results = [] for x in range(self.repeat): start = default_timer() self.func() end = default_timer() elapsed = end - start self.results.append(elapsed) conn.rollback() return min(self.results) def __str__(self): s = format_duration(min(self.results)) if self.verbose: s_min = format_duration(min(self.results)) s_avg = format_duration(sum(self.results) / len(self.results)) s_max = format_duration(max(self.results)) s_all = [format_duration(t) for t in self.results] s += "(min={} avg={} max={} all={})".format(s_min, s_avg, s_max, s_all) return " ".join(s)
import time import sys from utils import format_duration if sys.platform == "win32": default_timer = time.clock else: default_timer = time.time class Benchmark(): def __init__(self, func, name="", repeat=5): self.func = func self.repeat = repeat self.name = name self.verbose = False def run(self, conn): self.results = [] for x in range(self.repeat): start = default_timer() self.func() end = default_timer() elapsed = end - start self.results.append(elapsed) conn.rollback() return min(self.results) def __str__(self): s = format_duration(min(self.results)) if self.verbose: s_min = format_duration(min(self.results)) s_avg = format_duration(sum(self.results) / len(self.results)) s_max = format_duration(max(self.results)) s_all = [format_duration(t) for t in self.results] s += "(min={} avg={} max={} all={})".format(s_min, s_avg, s_max, s_all) return s
Fix bad console output formatting
Fix bad console output formatting
Python
mit
jameshy/libtree,conceptsandtraining/libtree
import time import sys from utils import format_duration if sys.platform == "win32": default_timer = time.clock else: default_timer = time.time class Benchmark(): def __init__(self, func, name="", repeat=5): self.func = func self.repeat = repeat self.name = name self.verbose = False def run(self, conn): self.results = [] for x in range(self.repeat): start = default_timer() self.func() end = default_timer() elapsed = end - start self.results.append(elapsed) conn.rollback() return min(self.results) def __str__(self): s = format_duration(min(self.results)) if self.verbose: s_min = format_duration(min(self.results)) s_avg = format_duration(sum(self.results) / len(self.results)) s_max = format_duration(max(self.results)) s_all = [format_duration(t) for t in self.results] s += "(min={} avg={} max={} all={})".format(s_min, s_avg, s_max, s_all) - return " ".join(s) + return s
Fix bad console output formatting
## Code Before: import time import sys from utils import format_duration if sys.platform == "win32": default_timer = time.clock else: default_timer = time.time class Benchmark(): def __init__(self, func, name="", repeat=5): self.func = func self.repeat = repeat self.name = name self.verbose = False def run(self, conn): self.results = [] for x in range(self.repeat): start = default_timer() self.func() end = default_timer() elapsed = end - start self.results.append(elapsed) conn.rollback() return min(self.results) def __str__(self): s = format_duration(min(self.results)) if self.verbose: s_min = format_duration(min(self.results)) s_avg = format_duration(sum(self.results) / len(self.results)) s_max = format_duration(max(self.results)) s_all = [format_duration(t) for t in self.results] s += "(min={} avg={} max={} all={})".format(s_min, s_avg, s_max, s_all) return " ".join(s) ## Instruction: Fix bad console output formatting ## Code After: import time import sys from utils import format_duration if sys.platform == "win32": default_timer = time.clock else: default_timer = time.time class Benchmark(): def __init__(self, func, name="", repeat=5): self.func = func self.repeat = repeat self.name = name self.verbose = False def run(self, conn): self.results = [] for x in range(self.repeat): start = default_timer() self.func() end = default_timer() elapsed = end - start self.results.append(elapsed) conn.rollback() return min(self.results) def __str__(self): s = format_duration(min(self.results)) if self.verbose: s_min = format_duration(min(self.results)) s_avg = format_duration(sum(self.results) / len(self.results)) s_max = format_duration(max(self.results)) s_all = [format_duration(t) for t in self.results] s += "(min={} avg={} max={} all={})".format(s_min, s_avg, s_max, s_all) return s
... s += "(min={} avg={} max={} all={})".format(s_min, s_avg, s_max, s_all) return s ...
858bc6f152a87298f9bd3568712aed49b6e02e42
suave/suave.py
suave/suave.py
import curses import os import time from box import Box from utils import load_yaml def main(screen): """ Draws and redraws the screen. """ # Hide the cursor. curses.curs_set(0) # Load config from file. config = load_yaml(os.path.expanduser('~/.suave/config.yml')) # Create boxes from config. boxes = [] for box in config: boxes.append( Box( screen=screen, rows=box['rows'], columns=box['columns'], rows_offset=box['rows-offset'], columns_offset=box['columns-offset'], command=box['command'], interval=box['interval'], ) ) while True: # Redraw the screen only when it changes. if screen.is_wintouched(): screen.clear() screen.refresh() # Give every box an opportunity to redraw if it has changed. [box.redraw_if_changed() for box in boxes] # Wait before redrawing again. time.sleep(1) curses.wrapper(main)
import curses import os from box import Box from utils import load_yaml def main(screen): """ Draws and redraws the screen. """ # Hide the cursor. curses.curs_set(0) # Load config from file. config = load_yaml(os.path.expanduser('~/.suave/config.yml')) # Create boxes from config. boxes = [] for box in config: boxes.append( Box( screen=screen, rows=box['rows'], columns=box['columns'], rows_offset=box['rows-offset'], columns_offset=box['columns-offset'], command=box['command'], interval=box['interval'], ) ) while True: # Redraw the screen only when it changes. if screen.is_wintouched(): screen.clear() screen.refresh() # Give every box an opportunity to redraw if it has changed. [box.redraw_if_changed() for box in boxes] # Wait before redrawing again. curses.napms(1000) curses.wrapper(main)
Use napms method from curses rather than sleep method from time
Use napms method from curses rather than sleep method from time
Python
mit
countermeasure/suave
import curses import os - import time from box import Box from utils import load_yaml def main(screen): """ Draws and redraws the screen. """ # Hide the cursor. curses.curs_set(0) # Load config from file. config = load_yaml(os.path.expanduser('~/.suave/config.yml')) # Create boxes from config. boxes = [] for box in config: boxes.append( Box( screen=screen, rows=box['rows'], columns=box['columns'], rows_offset=box['rows-offset'], columns_offset=box['columns-offset'], command=box['command'], interval=box['interval'], ) ) while True: # Redraw the screen only when it changes. if screen.is_wintouched(): screen.clear() screen.refresh() # Give every box an opportunity to redraw if it has changed. [box.redraw_if_changed() for box in boxes] # Wait before redrawing again. - time.sleep(1) + curses.napms(1000) curses.wrapper(main)
Use napms method from curses rather than sleep method from time
## Code Before: import curses import os import time from box import Box from utils import load_yaml def main(screen): """ Draws and redraws the screen. """ # Hide the cursor. curses.curs_set(0) # Load config from file. config = load_yaml(os.path.expanduser('~/.suave/config.yml')) # Create boxes from config. boxes = [] for box in config: boxes.append( Box( screen=screen, rows=box['rows'], columns=box['columns'], rows_offset=box['rows-offset'], columns_offset=box['columns-offset'], command=box['command'], interval=box['interval'], ) ) while True: # Redraw the screen only when it changes. if screen.is_wintouched(): screen.clear() screen.refresh() # Give every box an opportunity to redraw if it has changed. [box.redraw_if_changed() for box in boxes] # Wait before redrawing again. time.sleep(1) curses.wrapper(main) ## Instruction: Use napms method from curses rather than sleep method from time ## Code After: import curses import os from box import Box from utils import load_yaml def main(screen): """ Draws and redraws the screen. """ # Hide the cursor. curses.curs_set(0) # Load config from file. config = load_yaml(os.path.expanduser('~/.suave/config.yml')) # Create boxes from config. boxes = [] for box in config: boxes.append( Box( screen=screen, rows=box['rows'], columns=box['columns'], rows_offset=box['rows-offset'], columns_offset=box['columns-offset'], command=box['command'], interval=box['interval'], ) ) while True: # Redraw the screen only when it changes. if screen.is_wintouched(): screen.clear() screen.refresh() # Give every box an opportunity to redraw if it has changed. [box.redraw_if_changed() for box in boxes] # Wait before redrawing again. curses.napms(1000) curses.wrapper(main)
// ... existing code ... import curses import os from box import Box // ... modified code ... # Wait before redrawing again. curses.napms(1000) // ... rest of the code ...
8ada9ee4b394119a73de8d85a9db2be9df547aae
lib/pegasus/python/Pegasus/cli/startup-validation.py
lib/pegasus/python/Pegasus/cli/startup-validation.py
import sys if not sys.version_info >= (3, 5): sys.stderr.write('Pegasus requires Python 3.5 or above\n') sys.exit(1) try: import yaml except: sys.stderr.write('Pegasus requires the Python3 YAML module to be installed\n') sys.exit(1) try: import OpenSSL except: sys.stderr.write('Pegasus requires the Python3 PyOpenSSL module to be installed\n') sys.exit(1)
import sys if not sys.version_info >= (3, 5): sys.stderr.write("Pegasus requires Python 3.5 or above\n") sys.exit(1) try: import yaml except: sys.stderr.write("Pegasus requires the Python3 YAML module to be installed\n") sys.exit(1)
Remove check for pyOpenSSL as it is only needed in pegasus-service to use ssl certs.
Remove check for pyOpenSSL as it is only needed in pegasus-service to use ssl certs.
Python
apache-2.0
pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus
import sys if not sys.version_info >= (3, 5): - sys.stderr.write('Pegasus requires Python 3.5 or above\n') + sys.stderr.write("Pegasus requires Python 3.5 or above\n") sys.exit(1) try: import yaml except: - sys.stderr.write('Pegasus requires the Python3 YAML module to be installed\n') + sys.stderr.write("Pegasus requires the Python3 YAML module to be installed\n") sys.exit(1) - try: - import OpenSSL - except: - sys.stderr.write('Pegasus requires the Python3 PyOpenSSL module to be installed\n') - sys.exit(1) - -
Remove check for pyOpenSSL as it is only needed in pegasus-service to use ssl certs.
## Code Before: import sys if not sys.version_info >= (3, 5): sys.stderr.write('Pegasus requires Python 3.5 or above\n') sys.exit(1) try: import yaml except: sys.stderr.write('Pegasus requires the Python3 YAML module to be installed\n') sys.exit(1) try: import OpenSSL except: sys.stderr.write('Pegasus requires the Python3 PyOpenSSL module to be installed\n') sys.exit(1) ## Instruction: Remove check for pyOpenSSL as it is only needed in pegasus-service to use ssl certs. ## Code After: import sys if not sys.version_info >= (3, 5): sys.stderr.write("Pegasus requires Python 3.5 or above\n") sys.exit(1) try: import yaml except: sys.stderr.write("Pegasus requires the Python3 YAML module to be installed\n") sys.exit(1)
// ... existing code ... if not sys.version_info >= (3, 5): sys.stderr.write("Pegasus requires Python 3.5 or above\n") sys.exit(1) // ... modified code ... import yaml except: sys.stderr.write("Pegasus requires the Python3 YAML module to be installed\n") sys.exit(1) // ... rest of the code ...
4ec5a83837fada00f77c25ff0f4725714a88420a
bokeh/models/tests/test_renderers.py
bokeh/models/tests/test_renderers.py
from __future__ import absolute_import import unittest from mock import patch from bokeh.models.renderers import GlyphRenderer from bokeh.plotting import ColumnDataSource, figure from bokeh.validation import check_integrity class TestGlyphRenderer(unittest.TestCase): def test_warning_about_colons_in_column_labels(self): sh = ['0', '1:0'] p = figure() p.rect('a', 'b', 1, 1, source=ColumnDataSource(data={'a': sh, 'b': sh})) renderer = p.renderers[-1] errors = renderer._check_colon_in_category_label() self.assertEqual(errors, [( 1003, 'COLON_IN_CATEGORY_LABEL', 'Category label contains colons', '[field:a] [first_value: 1:0] [field:b] [first_value: 1:0] ' '[renderer: ' 'GlyphRenderer, ViewModel:GlyphRenderer, ref _id: ' '%s]' % renderer._id )]) if __name__ == '__main__': unittest.main()
from __future__ import absolute_import import unittest from mock import patch from bokeh.models.renderers import GlyphRenderer from bokeh.plotting import ColumnDataSource, figure from bokeh.validation import check_integrity class TestGlyphRenderer(unittest.TestCase): def test_warning_about_colons_in_column_labels(self): sh = ['0', '1:0'] plot = figure() plot.rect('a', 'b', 1, 1, source=ColumnDataSource(data={'a': sh, 'b': sh})) renderer = plot.select({'type': GlyphRenderer})[0] errors = renderer._check_colon_in_category_label() self.assertEqual(errors, [( 1003, 'COLON_IN_CATEGORY_LABEL', 'Category label contains colons', '[field:a] [first_value: 1:0] [field:b] [first_value: 1:0] ' '[renderer: ' 'GlyphRenderer, ViewModel:GlyphRenderer, ref _id: ' '%s]' % renderer._id )]) if __name__ == '__main__': unittest.main()
Fix direct glyph selection with select method
Fix direct glyph selection with select method
Python
bsd-3-clause
xguse/bokeh,Karel-van-de-Plassche/bokeh,mindriot101/bokeh,aavanian/bokeh,evidation-health/bokeh,matbra/bokeh,KasperPRasmussen/bokeh,philippjfr/bokeh,timsnyder/bokeh,htygithub/bokeh,tacaswell/bokeh,paultcochrane/bokeh,bokeh/bokeh,justacec/bokeh,DuCorey/bokeh,msarahan/bokeh,htygithub/bokeh,jakirkham/bokeh,jplourenco/bokeh,clairetang6/bokeh,rs2/bokeh,ericmjl/bokeh,phobson/bokeh,stonebig/bokeh,tacaswell/bokeh,timsnyder/bokeh,muku42/bokeh,saifrahmed/bokeh,gpfreitas/bokeh,aiguofer/bokeh,deeplook/bokeh,draperjames/bokeh,timsnyder/bokeh,DuCorey/bokeh,maxalbert/bokeh,schoolie/bokeh,khkaminska/bokeh,justacec/bokeh,mindriot101/bokeh,paultcochrane/bokeh,philippjfr/bokeh,daodaoliang/bokeh,muku42/bokeh,rothnic/bokeh,philippjfr/bokeh,phobson/bokeh,maxalbert/bokeh,khkaminska/bokeh,bokeh/bokeh,KasperPRasmussen/bokeh,clairetang6/bokeh,ChinaQuants/bokeh,deeplook/bokeh,phobson/bokeh,gpfreitas/bokeh,bokeh/bokeh,dennisobrien/bokeh,justacec/bokeh,KasperPRasmussen/bokeh,quasiben/bokeh,percyfal/bokeh,msarahan/bokeh,ericdill/bokeh,Karel-van-de-Plassche/bokeh,rothnic/bokeh,ptitjano/bokeh,KasperPRasmussen/bokeh,aiguofer/bokeh,azjps/bokeh,draperjames/bokeh,ptitjano/bokeh,stonebig/bokeh,jplourenco/bokeh,deeplook/bokeh,clairetang6/bokeh,khkaminska/bokeh,jplourenco/bokeh,aavanian/bokeh,clairetang6/bokeh,evidation-health/bokeh,schoolie/bokeh,dennisobrien/bokeh,jakirkham/bokeh,schoolie/bokeh,rothnic/bokeh,muku42/bokeh,tacaswell/bokeh,percyfal/bokeh,schoolie/bokeh,ptitjano/bokeh,ericmjl/bokeh,azjps/bokeh,ericmjl/bokeh,muku42/bokeh,matbra/bokeh,xguse/bokeh,jakirkham/bokeh,gpfreitas/bokeh,aavanian/bokeh,htygithub/bokeh,matbra/bokeh,aiguofer/bokeh,saifrahmed/bokeh,schoolie/bokeh,justacec/bokeh,srinathv/bokeh,paultcochrane/bokeh,jakirkham/bokeh,aiguofer/bokeh,philippjfr/bokeh,draperjames/bokeh,khkaminska/bokeh,Karel-van-de-Plassche/bokeh,daodaoliang/bokeh,xguse/bokeh,evidation-health/bokeh,mindriot101/bokeh,dennisobrien/bokeh,ChinaQuants/bokeh,ericmjl/bokeh,aiguofer/bokeh,DuCorey/bokeh,percyfal/bokeh,bokeh/bokeh,rs2/bokeh,rs2/bokeh,bokeh/bokeh,srinathv/bokeh,saifrahmed/bokeh,draperjames/bokeh,jplourenco/bokeh,evidation-health/bokeh,quasiben/bokeh,percyfal/bokeh,phobson/bokeh,maxalbert/bokeh,DuCorey/bokeh,maxalbert/bokeh,msarahan/bokeh,ChinaQuants/bokeh,philippjfr/bokeh,timsnyder/bokeh,tacaswell/bokeh,paultcochrane/bokeh,timsnyder/bokeh,gpfreitas/bokeh,percyfal/bokeh,draperjames/bokeh,ericdill/bokeh,mindriot101/bokeh,dennisobrien/bokeh,dennisobrien/bokeh,deeplook/bokeh,ptitjano/bokeh,KasperPRasmussen/bokeh,rs2/bokeh,aavanian/bokeh,ptitjano/bokeh,matbra/bokeh,ChinaQuants/bokeh,azjps/bokeh,aavanian/bokeh,ericdill/bokeh,ericdill/bokeh,rs2/bokeh,saifrahmed/bokeh,daodaoliang/bokeh,DuCorey/bokeh,stonebig/bokeh,azjps/bokeh,xguse/bokeh,htygithub/bokeh,phobson/bokeh,daodaoliang/bokeh,stonebig/bokeh,Karel-van-de-Plassche/bokeh,quasiben/bokeh,srinathv/bokeh,azjps/bokeh,ericmjl/bokeh,jakirkham/bokeh,rothnic/bokeh,srinathv/bokeh,msarahan/bokeh,Karel-van-de-Plassche/bokeh
from __future__ import absolute_import import unittest from mock import patch from bokeh.models.renderers import GlyphRenderer from bokeh.plotting import ColumnDataSource, figure from bokeh.validation import check_integrity class TestGlyphRenderer(unittest.TestCase): def test_warning_about_colons_in_column_labels(self): sh = ['0', '1:0'] - p = figure() + plot = figure() - p.rect('a', 'b', 1, 1, source=ColumnDataSource(data={'a': sh, 'b': sh})) + plot.rect('a', 'b', 1, 1, source=ColumnDataSource(data={'a': sh, 'b': sh})) - renderer = p.renderers[-1] + renderer = plot.select({'type': GlyphRenderer})[0] errors = renderer._check_colon_in_category_label() self.assertEqual(errors, [( 1003, 'COLON_IN_CATEGORY_LABEL', 'Category label contains colons', '[field:a] [first_value: 1:0] [field:b] [first_value: 1:0] ' '[renderer: ' 'GlyphRenderer, ViewModel:GlyphRenderer, ref _id: ' '%s]' % renderer._id )]) if __name__ == '__main__': unittest.main()
Fix direct glyph selection with select method
## Code Before: from __future__ import absolute_import import unittest from mock import patch from bokeh.models.renderers import GlyphRenderer from bokeh.plotting import ColumnDataSource, figure from bokeh.validation import check_integrity class TestGlyphRenderer(unittest.TestCase): def test_warning_about_colons_in_column_labels(self): sh = ['0', '1:0'] p = figure() p.rect('a', 'b', 1, 1, source=ColumnDataSource(data={'a': sh, 'b': sh})) renderer = p.renderers[-1] errors = renderer._check_colon_in_category_label() self.assertEqual(errors, [( 1003, 'COLON_IN_CATEGORY_LABEL', 'Category label contains colons', '[field:a] [first_value: 1:0] [field:b] [first_value: 1:0] ' '[renderer: ' 'GlyphRenderer, ViewModel:GlyphRenderer, ref _id: ' '%s]' % renderer._id )]) if __name__ == '__main__': unittest.main() ## Instruction: Fix direct glyph selection with select method ## Code After: from __future__ import absolute_import import unittest from mock import patch from bokeh.models.renderers import GlyphRenderer from bokeh.plotting import ColumnDataSource, figure from bokeh.validation import check_integrity class TestGlyphRenderer(unittest.TestCase): def test_warning_about_colons_in_column_labels(self): sh = ['0', '1:0'] plot = figure() plot.rect('a', 'b', 1, 1, source=ColumnDataSource(data={'a': sh, 'b': sh})) renderer = plot.select({'type': GlyphRenderer})[0] errors = renderer._check_colon_in_category_label() self.assertEqual(errors, [( 1003, 'COLON_IN_CATEGORY_LABEL', 'Category label contains colons', '[field:a] [first_value: 1:0] [field:b] [first_value: 1:0] ' '[renderer: ' 'GlyphRenderer, ViewModel:GlyphRenderer, ref _id: ' '%s]' % renderer._id )]) if __name__ == '__main__': unittest.main()
// ... existing code ... def test_warning_about_colons_in_column_labels(self): sh = ['0', '1:0'] plot = figure() plot.rect('a', 'b', 1, 1, source=ColumnDataSource(data={'a': sh, 'b': sh})) renderer = plot.select({'type': GlyphRenderer})[0] errors = renderer._check_colon_in_category_label() // ... rest of the code ...
6dfbbba5abf380e3f47f9190a864faa13cf1599d
data_preparation.py
data_preparation.py
import pandas as pd import numpy as np orders_prior_df = pd.read_csv('Data/orders_prior_sample.csv') order_products_prior_df = pd.read_csv('Data/order_products_prior_sample.csv') grouped = order_products_prior_df.groupby('order_id', as_index = False) grouped_data = pd.DataFrame() grouped_data['order_id'] = grouped['order_id'].aggregate(np.mean) def product_ids(group): l = [] for e in group['product_id']: l.append(str(e)) return ' '.join(l) grouped_data['product_ids'] = grouped.apply(product_ids) def add_to_cart_orders(group): l = [] for e in group['add_to_cart_order']: l.append(str(e)) return ' '.join(l) grouped_data['add_to_cart_orders'] = grouped.apply(add_to_cart_orders) print('First five rows of grouped_data:\n', grouped_data.head()) orders_prior_merged = pd.merge(orders_prior_df, grouped_data, on='order_id') print('First five rows of orders_prior_merged:\n', orders_prior_merged.head())
import pandas as pd import numpy as np orders_prior_df = pd.read_csv('Data/orders_prior_sample.csv') order_products_prior_df = pd.read_csv('Data/order_products_prior_sample.csv') grouped = order_products_prior_df.groupby('order_id', as_index = False) grouped_data = pd.DataFrame() grouped_data['order_id'] = grouped['order_id'].aggregate(np.mean) def product_ids(group): l = [] for e in group['product_id']: l.append(str(e)) return ' '.join(l) grouped_data['product_ids'] = grouped.apply(product_ids) def add_to_cart_orders(group): l = [] for e in group['add_to_cart_order']: l.append(str(e)) return ' '.join(l) grouped_data['add_to_cart_orders'] = grouped.apply(add_to_cart_orders) grouped_data['reordered'] = grouped['reordered'].aggregate(np.mean)['reordered'].round() print('First five rows of grouped_data:\n', grouped_data.head()) orders_prior_merged = pd.merge(orders_prior_df, grouped_data, on='order_id') print('First five rows of orders_prior_merged:\n', orders_prior_merged.head())
Merge product reordered column with order ids
feat: Merge product reordered column with order ids
Python
mit
rjegankumar/instacart_prediction_model
import pandas as pd import numpy as np orders_prior_df = pd.read_csv('Data/orders_prior_sample.csv') order_products_prior_df = pd.read_csv('Data/order_products_prior_sample.csv') grouped = order_products_prior_df.groupby('order_id', as_index = False) grouped_data = pd.DataFrame() grouped_data['order_id'] = grouped['order_id'].aggregate(np.mean) def product_ids(group): l = [] for e in group['product_id']: l.append(str(e)) return ' '.join(l) grouped_data['product_ids'] = grouped.apply(product_ids) def add_to_cart_orders(group): l = [] for e in group['add_to_cart_order']: l.append(str(e)) return ' '.join(l) grouped_data['add_to_cart_orders'] = grouped.apply(add_to_cart_orders) + + grouped_data['reordered'] = grouped['reordered'].aggregate(np.mean)['reordered'].round() print('First five rows of grouped_data:\n', grouped_data.head()) orders_prior_merged = pd.merge(orders_prior_df, grouped_data, on='order_id') print('First five rows of orders_prior_merged:\n', orders_prior_merged.head())
Merge product reordered column with order ids
## Code Before: import pandas as pd import numpy as np orders_prior_df = pd.read_csv('Data/orders_prior_sample.csv') order_products_prior_df = pd.read_csv('Data/order_products_prior_sample.csv') grouped = order_products_prior_df.groupby('order_id', as_index = False) grouped_data = pd.DataFrame() grouped_data['order_id'] = grouped['order_id'].aggregate(np.mean) def product_ids(group): l = [] for e in group['product_id']: l.append(str(e)) return ' '.join(l) grouped_data['product_ids'] = grouped.apply(product_ids) def add_to_cart_orders(group): l = [] for e in group['add_to_cart_order']: l.append(str(e)) return ' '.join(l) grouped_data['add_to_cart_orders'] = grouped.apply(add_to_cart_orders) print('First five rows of grouped_data:\n', grouped_data.head()) orders_prior_merged = pd.merge(orders_prior_df, grouped_data, on='order_id') print('First five rows of orders_prior_merged:\n', orders_prior_merged.head()) ## Instruction: Merge product reordered column with order ids ## Code After: import pandas as pd import numpy as np orders_prior_df = pd.read_csv('Data/orders_prior_sample.csv') order_products_prior_df = pd.read_csv('Data/order_products_prior_sample.csv') grouped = order_products_prior_df.groupby('order_id', as_index = False) grouped_data = pd.DataFrame() grouped_data['order_id'] = grouped['order_id'].aggregate(np.mean) def product_ids(group): l = [] for e in group['product_id']: l.append(str(e)) return ' '.join(l) grouped_data['product_ids'] = grouped.apply(product_ids) def add_to_cart_orders(group): l = [] for e in group['add_to_cart_order']: l.append(str(e)) return ' '.join(l) grouped_data['add_to_cart_orders'] = grouped.apply(add_to_cart_orders) grouped_data['reordered'] = grouped['reordered'].aggregate(np.mean)['reordered'].round() print('First five rows of grouped_data:\n', grouped_data.head()) orders_prior_merged = pd.merge(orders_prior_df, grouped_data, on='order_id') print('First five rows of orders_prior_merged:\n', orders_prior_merged.head())
... grouped_data['add_to_cart_orders'] = grouped.apply(add_to_cart_orders) grouped_data['reordered'] = grouped['reordered'].aggregate(np.mean)['reordered'].round() print('First five rows of grouped_data:\n', grouped_data.head()) ...
25cd8afdfede8a522f8d0f08ee4678a2e9c46a4b
curious/commands/__init__.py
curious/commands/__init__.py
import functools from curious.commands.command import Command def command(*args, **kwargs): """ A decorator to mark a function as a command. This will put a `factory` attribute on the function, which can later be called to create the Command instance. All arguments are passed to the Command class. """ def __inner(func): factory = functools.partial(Command, func, *args, **kwargs) func.factory = factory return func return __inner def event(func): """ Marks a function as an event. :param func: Either the function, or the name to give to the event. """ if isinstance(func, str): def __innr(f): f.event = func return f return __innr else: func.event = func.__name__[3:] return func
import functools from curious.commands.command import Command def command(*args, klass: type=Command, **kwargs): """ A decorator to mark a function as a command. This will put a `factory` attribute on the function, which can later be called to create the Command instance. All arguments are passed to the Command class. :param klass: The command class type to wrap the object in. """ def __inner(func): factory = functools.partial(klass, func, *args, **kwargs) func.factory = factory return func return __inner def event(func): """ Marks a function as an event. :param func: Either the function, or the name to give to the event. """ if isinstance(func, str): def __innr(f): f.event = func return f return __innr else: func.event = func.__name__[3:] return func
Allow changing what object is returned from Command instances.
Allow changing what object is returned from Command instances.
Python
mit
SunDwarf/curious
import functools from curious.commands.command import Command - def command(*args, **kwargs): + def command(*args, klass: type=Command, **kwargs): """ A decorator to mark a function as a command. This will put a `factory` attribute on the function, which can later be called to create the Command instance. All arguments are passed to the Command class. + + :param klass: The command class type to wrap the object in. """ def __inner(func): - factory = functools.partial(Command, func, *args, **kwargs) + factory = functools.partial(klass, func, *args, **kwargs) func.factory = factory return func return __inner def event(func): """ Marks a function as an event. :param func: Either the function, or the name to give to the event. """ if isinstance(func, str): def __innr(f): f.event = func return f return __innr else: func.event = func.__name__[3:] return func
Allow changing what object is returned from Command instances.
## Code Before: import functools from curious.commands.command import Command def command(*args, **kwargs): """ A decorator to mark a function as a command. This will put a `factory` attribute on the function, which can later be called to create the Command instance. All arguments are passed to the Command class. """ def __inner(func): factory = functools.partial(Command, func, *args, **kwargs) func.factory = factory return func return __inner def event(func): """ Marks a function as an event. :param func: Either the function, or the name to give to the event. """ if isinstance(func, str): def __innr(f): f.event = func return f return __innr else: func.event = func.__name__[3:] return func ## Instruction: Allow changing what object is returned from Command instances. ## Code After: import functools from curious.commands.command import Command def command(*args, klass: type=Command, **kwargs): """ A decorator to mark a function as a command. This will put a `factory` attribute on the function, which can later be called to create the Command instance. All arguments are passed to the Command class. :param klass: The command class type to wrap the object in. """ def __inner(func): factory = functools.partial(klass, func, *args, **kwargs) func.factory = factory return func return __inner def event(func): """ Marks a function as an event. :param func: Either the function, or the name to give to the event. """ if isinstance(func, str): def __innr(f): f.event = func return f return __innr else: func.event = func.__name__[3:] return func
... def command(*args, klass: type=Command, **kwargs): """ A decorator to mark a function as a command. ... All arguments are passed to the Command class. :param klass: The command class type to wrap the object in. """ def __inner(func): factory = functools.partial(klass, func, *args, **kwargs) func.factory = factory return func ...
67c1855f75a3c29bc650c193235576f6b591c805
payment_redsys/__manifest__.py
payment_redsys/__manifest__.py
{ "name": "Pasarela de pago Redsys", "category": "Payment Acquirer", "summary": "Payment Acquirer: Redsys Implementation", "version": "14.0.2.0.0", "author": "Tecnativa," "Odoo Community Association (OCA)", "website": "https://github.com/OCA/l10n-spain", "depends": ["payment", "website_sale"], "external_dependencies": {"python": ["Crypto.Cipher.DES3"]}, "data": [ "views/redsys.xml", "views/payment_acquirer.xml", "views/payment_redsys_templates.xml", "data/payment_redsys.xml", ], "license": "AGPL-3", "installable": True, }
{ "name": "Pasarela de pago Redsys", "category": "Payment Acquirer", "summary": "Payment Acquirer: Redsys Implementation", "version": "14.0.2.0.0", "author": "Tecnativa," "Odoo Community Association (OCA)", "website": "https://github.com/OCA/l10n-spain", "depends": ["payment", "website_sale"], "external_dependencies": {"python": ["pycrypto"]}, "data": [ "views/redsys.xml", "views/payment_acquirer.xml", "views/payment_redsys_templates.xml", "data/payment_redsys.xml", ], "license": "AGPL-3", "installable": True, }
Put real package on pypi
[IMP] payment_redsys: Put real package on pypi
Python
agpl-3.0
cubells/l10n-spain,cubells/l10n-spain,cubells/l10n-spain
{ "name": "Pasarela de pago Redsys", "category": "Payment Acquirer", "summary": "Payment Acquirer: Redsys Implementation", "version": "14.0.2.0.0", "author": "Tecnativa," "Odoo Community Association (OCA)", "website": "https://github.com/OCA/l10n-spain", "depends": ["payment", "website_sale"], - "external_dependencies": {"python": ["Crypto.Cipher.DES3"]}, + "external_dependencies": {"python": ["pycrypto"]}, "data": [ "views/redsys.xml", "views/payment_acquirer.xml", "views/payment_redsys_templates.xml", "data/payment_redsys.xml", ], "license": "AGPL-3", "installable": True, }
Put real package on pypi
## Code Before: { "name": "Pasarela de pago Redsys", "category": "Payment Acquirer", "summary": "Payment Acquirer: Redsys Implementation", "version": "14.0.2.0.0", "author": "Tecnativa," "Odoo Community Association (OCA)", "website": "https://github.com/OCA/l10n-spain", "depends": ["payment", "website_sale"], "external_dependencies": {"python": ["Crypto.Cipher.DES3"]}, "data": [ "views/redsys.xml", "views/payment_acquirer.xml", "views/payment_redsys_templates.xml", "data/payment_redsys.xml", ], "license": "AGPL-3", "installable": True, } ## Instruction: Put real package on pypi ## Code After: { "name": "Pasarela de pago Redsys", "category": "Payment Acquirer", "summary": "Payment Acquirer: Redsys Implementation", "version": "14.0.2.0.0", "author": "Tecnativa," "Odoo Community Association (OCA)", "website": "https://github.com/OCA/l10n-spain", "depends": ["payment", "website_sale"], "external_dependencies": {"python": ["pycrypto"]}, "data": [ "views/redsys.xml", "views/payment_acquirer.xml", "views/payment_redsys_templates.xml", "data/payment_redsys.xml", ], "license": "AGPL-3", "installable": True, }
// ... existing code ... "website": "https://github.com/OCA/l10n-spain", "depends": ["payment", "website_sale"], "external_dependencies": {"python": ["pycrypto"]}, "data": [ "views/redsys.xml", // ... rest of the code ...
c811e0e02d06f8d5fd6a0b738546b0e200c706cd
fairseq/criterions/fairseq_criterion.py
fairseq/criterions/fairseq_criterion.py
from torch.nn.modules.loss import _Loss class FairseqCriterion(_Loss): def __init__(self, args, task): super().__init__() self.args = args self.padding_idx = task.target_dictionary.pad() if task.target_dictionary is not None else -100 @staticmethod def add_args(parser): """Add criterion-specific arguments to the parser.""" pass @classmethod def build_criterion(cls, args, task): return cls(args, task) def forward(self, model, sample, reduce=True): """Compute the loss for the given sample. Returns a tuple with three elements: 1) the loss 2) the sample size, which is used as the denominator for the gradient 3) logging outputs to display while training """ raise NotImplementedError @staticmethod def aggregate_logging_outputs(logging_outputs): """Aggregate logging outputs from data parallel training.""" raise NotImplementedError @staticmethod def grad_denom(sample_sizes): """Compute the gradient denominator for a set of sample sizes.""" return sum(sample_sizes)
from torch.nn.modules.loss import _Loss class FairseqCriterion(_Loss): def __init__(self, args, task): super().__init__() self.args = args self.task = task self.padding_idx = task.target_dictionary.pad() if task.target_dictionary is not None else -100 @staticmethod def add_args(parser): """Add criterion-specific arguments to the parser.""" pass @classmethod def build_criterion(cls, args, task): return cls(args, task) def forward(self, model, sample, reduce=True): """Compute the loss for the given sample. Returns a tuple with three elements: 1) the loss 2) the sample size, which is used as the denominator for the gradient 3) logging outputs to display while training """ raise NotImplementedError @staticmethod def aggregate_logging_outputs(logging_outputs): """Aggregate logging outputs from data parallel training.""" raise NotImplementedError @staticmethod def grad_denom(sample_sizes): """Compute the gradient denominator for a set of sample sizes.""" return sum(sample_sizes)
Store task in the criterion base class
Store task in the criterion base class Summary: Pull Request resolved: https://github.com/fairinternal/fairseq-py/pull/737 Differential Revision: D16377805 Pulled By: myleott fbshipit-source-id: 1e090a02ff4fbba8695173f57d3cc5b88ae98bbf
Python
mit
pytorch/fairseq,pytorch/fairseq,pytorch/fairseq
from torch.nn.modules.loss import _Loss class FairseqCriterion(_Loss): def __init__(self, args, task): super().__init__() self.args = args + self.task = task self.padding_idx = task.target_dictionary.pad() if task.target_dictionary is not None else -100 @staticmethod def add_args(parser): """Add criterion-specific arguments to the parser.""" pass @classmethod def build_criterion(cls, args, task): return cls(args, task) def forward(self, model, sample, reduce=True): """Compute the loss for the given sample. Returns a tuple with three elements: 1) the loss 2) the sample size, which is used as the denominator for the gradient 3) logging outputs to display while training """ raise NotImplementedError @staticmethod def aggregate_logging_outputs(logging_outputs): """Aggregate logging outputs from data parallel training.""" raise NotImplementedError @staticmethod def grad_denom(sample_sizes): """Compute the gradient denominator for a set of sample sizes.""" return sum(sample_sizes)
Store task in the criterion base class
## Code Before: from torch.nn.modules.loss import _Loss class FairseqCriterion(_Loss): def __init__(self, args, task): super().__init__() self.args = args self.padding_idx = task.target_dictionary.pad() if task.target_dictionary is not None else -100 @staticmethod def add_args(parser): """Add criterion-specific arguments to the parser.""" pass @classmethod def build_criterion(cls, args, task): return cls(args, task) def forward(self, model, sample, reduce=True): """Compute the loss for the given sample. Returns a tuple with three elements: 1) the loss 2) the sample size, which is used as the denominator for the gradient 3) logging outputs to display while training """ raise NotImplementedError @staticmethod def aggregate_logging_outputs(logging_outputs): """Aggregate logging outputs from data parallel training.""" raise NotImplementedError @staticmethod def grad_denom(sample_sizes): """Compute the gradient denominator for a set of sample sizes.""" return sum(sample_sizes) ## Instruction: Store task in the criterion base class ## Code After: from torch.nn.modules.loss import _Loss class FairseqCriterion(_Loss): def __init__(self, args, task): super().__init__() self.args = args self.task = task self.padding_idx = task.target_dictionary.pad() if task.target_dictionary is not None else -100 @staticmethod def add_args(parser): """Add criterion-specific arguments to the parser.""" pass @classmethod def build_criterion(cls, args, task): return cls(args, task) def forward(self, model, sample, reduce=True): """Compute the loss for the given sample. Returns a tuple with three elements: 1) the loss 2) the sample size, which is used as the denominator for the gradient 3) logging outputs to display while training """ raise NotImplementedError @staticmethod def aggregate_logging_outputs(logging_outputs): """Aggregate logging outputs from data parallel training.""" raise NotImplementedError @staticmethod def grad_denom(sample_sizes): """Compute the gradient denominator for a set of sample sizes.""" return sum(sample_sizes)
// ... existing code ... super().__init__() self.args = args self.task = task self.padding_idx = task.target_dictionary.pad() if task.target_dictionary is not None else -100 // ... rest of the code ...
3af95029c3f784e17247abcd0123156ff9384513
pronto/serializers/base.py
pronto/serializers/base.py
import abc import io import typing from typing import BinaryIO, ClassVar from ..ontology import Ontology class BaseSerializer(abc.ABC): format: ClassVar[str] = NotImplemented def __init__(self, ont: Ontology): self.ont = ont @abc.abstractmethod def dump(self, file: BinaryIO, encoding: str = "utf-8") -> None: return NotImplemented def dumps(self) -> str: s = io.BytesIO() self.dump(s) return s.getvalue().decode('utf-8')
import abc import io import typing from typing import BinaryIO, ClassVar from ..ontology import Ontology class BaseSerializer(abc.ABC): format: ClassVar[str] = NotImplemented def __init__(self, ont: Ontology): self.ont = ont @abc.abstractmethod def dump(self, file: BinaryIO) -> None: return NotImplemented def dumps(self) -> str: s = io.BytesIO() self.dump(s) return s.getvalue().decode('utf-8')
Fix signature of `BaseSerializer.dump` to remove `encoding` argument
Fix signature of `BaseSerializer.dump` to remove `encoding` argument
Python
mit
althonos/pronto
import abc import io import typing from typing import BinaryIO, ClassVar from ..ontology import Ontology class BaseSerializer(abc.ABC): format: ClassVar[str] = NotImplemented def __init__(self, ont: Ontology): self.ont = ont @abc.abstractmethod - def dump(self, file: BinaryIO, encoding: str = "utf-8") -> None: + def dump(self, file: BinaryIO) -> None: return NotImplemented def dumps(self) -> str: s = io.BytesIO() self.dump(s) return s.getvalue().decode('utf-8')
Fix signature of `BaseSerializer.dump` to remove `encoding` argument
## Code Before: import abc import io import typing from typing import BinaryIO, ClassVar from ..ontology import Ontology class BaseSerializer(abc.ABC): format: ClassVar[str] = NotImplemented def __init__(self, ont: Ontology): self.ont = ont @abc.abstractmethod def dump(self, file: BinaryIO, encoding: str = "utf-8") -> None: return NotImplemented def dumps(self) -> str: s = io.BytesIO() self.dump(s) return s.getvalue().decode('utf-8') ## Instruction: Fix signature of `BaseSerializer.dump` to remove `encoding` argument ## Code After: import abc import io import typing from typing import BinaryIO, ClassVar from ..ontology import Ontology class BaseSerializer(abc.ABC): format: ClassVar[str] = NotImplemented def __init__(self, ont: Ontology): self.ont = ont @abc.abstractmethod def dump(self, file: BinaryIO) -> None: return NotImplemented def dumps(self) -> str: s = io.BytesIO() self.dump(s) return s.getvalue().decode('utf-8')
... @abc.abstractmethod def dump(self, file: BinaryIO) -> None: return NotImplemented ...
0a78f0cc03124662871c27ae2ac8647ecac58457
rasa_nlu/tokenizers/spacy_tokenizer.py
rasa_nlu/tokenizers/spacy_tokenizer.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import typing from typing import Any, List from rasa_nlu.components import Component from rasa_nlu.config import RasaNLUModelConfig from rasa_nlu.tokenizers import Tokenizer, Token from rasa_nlu.training_data import Message from rasa_nlu.training_data import TrainingData if typing.TYPE_CHECKING: from spacy.tokens.doc import Doc class SpacyTokenizer(Tokenizer, Component): name = "tokenizer_spacy" provides = ["tokens"] def train(self, training_data, config, **kwargs): # type: (TrainingData, RasaNLUModelConfig, **Any) -> None for example in training_data.training_examples: example.set("tokens", self.tokenize(example.get("spacy_doc"))) def process(self, message, **kwargs): # type: (Message, **Any) -> None message.set("tokens", self.tokenize(message.get("spacy_doc"))) def tokenize(self, doc): # type: (Doc) -> List[Token] return [Token(t.text, t.idx) for t in doc]
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import typing from typing import Any, List from rasa_nlu.components import Component from rasa_nlu.config import RasaNLUModelConfig from rasa_nlu.tokenizers import Tokenizer, Token from rasa_nlu.training_data import Message from rasa_nlu.training_data import TrainingData if typing.TYPE_CHECKING: from spacy.tokens.doc import Doc class SpacyTokenizer(Tokenizer, Component): name = "tokenizer_spacy" provides = ["tokens"] requires = ["spacy_doc"] def train(self, training_data, config, **kwargs): # type: (TrainingData, RasaNLUModelConfig, **Any) -> None for example in training_data.training_examples: example.set("tokens", self.tokenize(example.get("spacy_doc"))) def process(self, message, **kwargs): # type: (Message, **Any) -> None message.set("tokens", self.tokenize(message.get("spacy_doc"))) def tokenize(self, doc): # type: (Doc) -> List[Token] return [Token(t.text, t.idx) for t in doc]
Add missing "requires" to spacy tokenizer
Add missing "requires" to spacy tokenizer
Python
apache-2.0
RasaHQ/rasa_nlu,RasaHQ/rasa_nlu,RasaHQ/rasa_nlu
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import typing from typing import Any, List from rasa_nlu.components import Component from rasa_nlu.config import RasaNLUModelConfig from rasa_nlu.tokenizers import Tokenizer, Token from rasa_nlu.training_data import Message from rasa_nlu.training_data import TrainingData if typing.TYPE_CHECKING: from spacy.tokens.doc import Doc class SpacyTokenizer(Tokenizer, Component): name = "tokenizer_spacy" provides = ["tokens"] + requires = ["spacy_doc"] + def train(self, training_data, config, **kwargs): # type: (TrainingData, RasaNLUModelConfig, **Any) -> None for example in training_data.training_examples: example.set("tokens", self.tokenize(example.get("spacy_doc"))) def process(self, message, **kwargs): # type: (Message, **Any) -> None message.set("tokens", self.tokenize(message.get("spacy_doc"))) def tokenize(self, doc): # type: (Doc) -> List[Token] return [Token(t.text, t.idx) for t in doc]
Add missing "requires" to spacy tokenizer
## Code Before: from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import typing from typing import Any, List from rasa_nlu.components import Component from rasa_nlu.config import RasaNLUModelConfig from rasa_nlu.tokenizers import Tokenizer, Token from rasa_nlu.training_data import Message from rasa_nlu.training_data import TrainingData if typing.TYPE_CHECKING: from spacy.tokens.doc import Doc class SpacyTokenizer(Tokenizer, Component): name = "tokenizer_spacy" provides = ["tokens"] def train(self, training_data, config, **kwargs): # type: (TrainingData, RasaNLUModelConfig, **Any) -> None for example in training_data.training_examples: example.set("tokens", self.tokenize(example.get("spacy_doc"))) def process(self, message, **kwargs): # type: (Message, **Any) -> None message.set("tokens", self.tokenize(message.get("spacy_doc"))) def tokenize(self, doc): # type: (Doc) -> List[Token] return [Token(t.text, t.idx) for t in doc] ## Instruction: Add missing "requires" to spacy tokenizer ## Code After: from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import typing from typing import Any, List from rasa_nlu.components import Component from rasa_nlu.config import RasaNLUModelConfig from rasa_nlu.tokenizers import Tokenizer, Token from rasa_nlu.training_data import Message from rasa_nlu.training_data import TrainingData if typing.TYPE_CHECKING: from spacy.tokens.doc import Doc class SpacyTokenizer(Tokenizer, Component): name = "tokenizer_spacy" provides = ["tokens"] requires = ["spacy_doc"] def train(self, training_data, config, **kwargs): # type: (TrainingData, RasaNLUModelConfig, **Any) -> None for example in training_data.training_examples: example.set("tokens", self.tokenize(example.get("spacy_doc"))) def process(self, message, **kwargs): # type: (Message, **Any) -> None message.set("tokens", self.tokenize(message.get("spacy_doc"))) def tokenize(self, doc): # type: (Doc) -> List[Token] return [Token(t.text, t.idx) for t in doc]
... provides = ["tokens"] requires = ["spacy_doc"] def train(self, training_data, config, **kwargs): # type: (TrainingData, RasaNLUModelConfig, **Any) -> None ...
0428522c8df724ce49a32686676b2c5345abfda9
sdklib/util/timetizer.py
sdklib/util/timetizer.py
import time import datetime def get_current_utc(time_format="%Y-%m-%d %H:%M:%S"): """ @return a string representation of the current time in UTC. """ return time.strftime(time_format, time.gmtime()) def today_strf(): t = datetime.date.today() return t.strftime("%d/%m/%Y") def tomorrow_strf(): t = datetime.date.today() + datetime.timedelta(days=1) return t.strftime("%d/%m/%Y") def yesterday_strf(): t = datetime.date.today() - datetime.timedelta(days=1) return t.strftime("%d/%m/%Y") def seconds_to_milliseconds_timestamp(seconds_timestamp): return int(round(seconds_timestamp * 1000)) def current_milliseconds_timestamp(): return seconds_to_milliseconds_timestamp(time.time()) def datetime_to_milliseconds_timestamp(datetime_obj): seconds_timestamp = time.mktime(datetime_obj.timetuple()) return seconds_to_milliseconds_timestamp(seconds_timestamp)
import time import datetime def get_current_utc(time_format="%Y-%m-%d %H:%M:%S"): """ @return a string representation of the current time in UTC. """ return time.strftime(time_format, time.gmtime()) def today_strf(format="%d/%m/%Y"): t = datetime.date.today() return t.strftime(format) def tomorrow_strf(format="%d/%m/%Y"): t = datetime.date.today() + datetime.timedelta(days=1) return t.strftime(format) def yesterday_strf(format="%d/%m/%Y"): t = datetime.date.today() - datetime.timedelta(days=1) return t.strftime(format) def seconds_to_milliseconds_timestamp(seconds_timestamp): return int(round(seconds_timestamp * 1000)) def current_milliseconds_timestamp(): return seconds_to_milliseconds_timestamp(time.time()) def datetime_to_milliseconds_timestamp(datetime_obj): seconds_timestamp = time.mktime(datetime_obj.timetuple()) return seconds_to_milliseconds_timestamp(seconds_timestamp)
Add format parameter to strf functions
Add format parameter to strf functions
Python
bsd-2-clause
ivanprjcts/sdklib,ivanprjcts/sdklib
import time import datetime def get_current_utc(time_format="%Y-%m-%d %H:%M:%S"): """ @return a string representation of the current time in UTC. """ return time.strftime(time_format, time.gmtime()) - def today_strf(): + def today_strf(format="%d/%m/%Y"): t = datetime.date.today() - return t.strftime("%d/%m/%Y") + return t.strftime(format) - def tomorrow_strf(): + def tomorrow_strf(format="%d/%m/%Y"): t = datetime.date.today() + datetime.timedelta(days=1) - return t.strftime("%d/%m/%Y") + return t.strftime(format) - def yesterday_strf(): + def yesterday_strf(format="%d/%m/%Y"): t = datetime.date.today() - datetime.timedelta(days=1) - return t.strftime("%d/%m/%Y") + return t.strftime(format) def seconds_to_milliseconds_timestamp(seconds_timestamp): return int(round(seconds_timestamp * 1000)) def current_milliseconds_timestamp(): return seconds_to_milliseconds_timestamp(time.time()) def datetime_to_milliseconds_timestamp(datetime_obj): seconds_timestamp = time.mktime(datetime_obj.timetuple()) return seconds_to_milliseconds_timestamp(seconds_timestamp)
Add format parameter to strf functions
## Code Before: import time import datetime def get_current_utc(time_format="%Y-%m-%d %H:%M:%S"): """ @return a string representation of the current time in UTC. """ return time.strftime(time_format, time.gmtime()) def today_strf(): t = datetime.date.today() return t.strftime("%d/%m/%Y") def tomorrow_strf(): t = datetime.date.today() + datetime.timedelta(days=1) return t.strftime("%d/%m/%Y") def yesterday_strf(): t = datetime.date.today() - datetime.timedelta(days=1) return t.strftime("%d/%m/%Y") def seconds_to_milliseconds_timestamp(seconds_timestamp): return int(round(seconds_timestamp * 1000)) def current_milliseconds_timestamp(): return seconds_to_milliseconds_timestamp(time.time()) def datetime_to_milliseconds_timestamp(datetime_obj): seconds_timestamp = time.mktime(datetime_obj.timetuple()) return seconds_to_milliseconds_timestamp(seconds_timestamp) ## Instruction: Add format parameter to strf functions ## Code After: import time import datetime def get_current_utc(time_format="%Y-%m-%d %H:%M:%S"): """ @return a string representation of the current time in UTC. """ return time.strftime(time_format, time.gmtime()) def today_strf(format="%d/%m/%Y"): t = datetime.date.today() return t.strftime(format) def tomorrow_strf(format="%d/%m/%Y"): t = datetime.date.today() + datetime.timedelta(days=1) return t.strftime(format) def yesterday_strf(format="%d/%m/%Y"): t = datetime.date.today() - datetime.timedelta(days=1) return t.strftime(format) def seconds_to_milliseconds_timestamp(seconds_timestamp): return int(round(seconds_timestamp * 1000)) def current_milliseconds_timestamp(): return seconds_to_milliseconds_timestamp(time.time()) def datetime_to_milliseconds_timestamp(datetime_obj): seconds_timestamp = time.mktime(datetime_obj.timetuple()) return seconds_to_milliseconds_timestamp(seconds_timestamp)
// ... existing code ... def today_strf(format="%d/%m/%Y"): t = datetime.date.today() return t.strftime(format) def tomorrow_strf(format="%d/%m/%Y"): t = datetime.date.today() + datetime.timedelta(days=1) return t.strftime(format) def yesterday_strf(format="%d/%m/%Y"): t = datetime.date.today() - datetime.timedelta(days=1) return t.strftime(format) // ... rest of the code ...
5d663ae690f0c488f7a38f4556c30b169389c441
flaskiwsapp/projects/models/target.py
flaskiwsapp/projects/models/target.py
''' Created on Sep 24, 2016 @author: rtorres ''' from flaskiwsapp.database import SurrogatePK, Model, db, reference_col, relationship, Column from sqlalchemy.dialects.postgresql.base import ENUM from sqlalchemy_utils.types.url import URLType from flask_validator.constraints.internet import ValidateURL AREAS = ('Policies', 'Billing', 'Claims', 'Reports') class Target(SurrogatePK, Model): """A user of the app.""" __tablename__ = 'targets' title = Column(db.String(80), nullable=False) description = Column(db.Text(), nullable=False) client_id = reference_col('clients', nullable=False) client = relationship('Client', backref='targets') client_priority = Column(db.SmallInteger(), nullable=False) product_area = Column(ENUM(*AREAS, name='areas', create_type=False), nullable=False) target_date = Column(db.DateTime(), nullable=False) ticket_url = Column(db.String(256), nullable=False) def __init__(self, title="", password=None, **kwargs): """Create instance.""" db.Model.__init__(self, title=title.strip(), **kwargs) def __str__(self): """String representation of the user. Shows the target title.""" return self.title def get_id(self): return self.id
''' Created on Sep 24, 2016 @author: rtorres ''' from flaskiwsapp.database import SurrogatePK, Model, db, reference_col, relationship, Column from sqlalchemy.dialects.postgresql.base import ENUM AREAS = ('Policies', 'Billing', 'Claims', 'Reports') class Target(SurrogatePK, Model): """A user of the app.""" __tablename__ = 'targets' title = Column(db.String(80), nullable=False) description = Column(db.Text(), nullable=False) client_id = reference_col('clients', nullable=False) client = relationship('Client', backref='targets') client_priority = Column(db.SmallInteger(), nullable=False) product_area = Column(ENUM(*AREAS, name='areas', create_type=False), nullable=False) target_date = Column(db.DateTime(), nullable=False) ticket_url = Column(db.String(256), nullable=False) def __init__(self, title="", password=None, **kwargs): """Create instance.""" db.Model.__init__(self, title=title.strip(), **kwargs) def __str__(self): """String representation of the user. Shows the target title.""" return self.title def get_id(self): return self.id
Remove import from testing packages
Remove import from testing packages
Python
mit
rafasis1986/EngineeringMidLevel,rafasis1986/EngineeringMidLevel,rafasis1986/EngineeringMidLevel,rafasis1986/EngineeringMidLevel,rafasis1986/EngineeringMidLevel
''' Created on Sep 24, 2016 @author: rtorres ''' from flaskiwsapp.database import SurrogatePK, Model, db, reference_col, relationship, Column from sqlalchemy.dialects.postgresql.base import ENUM - from sqlalchemy_utils.types.url import URLType - from flask_validator.constraints.internet import ValidateURL AREAS = ('Policies', 'Billing', 'Claims', 'Reports') class Target(SurrogatePK, Model): """A user of the app.""" __tablename__ = 'targets' title = Column(db.String(80), nullable=False) description = Column(db.Text(), nullable=False) client_id = reference_col('clients', nullable=False) client = relationship('Client', backref='targets') client_priority = Column(db.SmallInteger(), nullable=False) product_area = Column(ENUM(*AREAS, name='areas', create_type=False), nullable=False) target_date = Column(db.DateTime(), nullable=False) ticket_url = Column(db.String(256), nullable=False) def __init__(self, title="", password=None, **kwargs): """Create instance.""" db.Model.__init__(self, title=title.strip(), **kwargs) def __str__(self): """String representation of the user. Shows the target title.""" return self.title def get_id(self): return self.id
Remove import from testing packages
## Code Before: ''' Created on Sep 24, 2016 @author: rtorres ''' from flaskiwsapp.database import SurrogatePK, Model, db, reference_col, relationship, Column from sqlalchemy.dialects.postgresql.base import ENUM from sqlalchemy_utils.types.url import URLType from flask_validator.constraints.internet import ValidateURL AREAS = ('Policies', 'Billing', 'Claims', 'Reports') class Target(SurrogatePK, Model): """A user of the app.""" __tablename__ = 'targets' title = Column(db.String(80), nullable=False) description = Column(db.Text(), nullable=False) client_id = reference_col('clients', nullable=False) client = relationship('Client', backref='targets') client_priority = Column(db.SmallInteger(), nullable=False) product_area = Column(ENUM(*AREAS, name='areas', create_type=False), nullable=False) target_date = Column(db.DateTime(), nullable=False) ticket_url = Column(db.String(256), nullable=False) def __init__(self, title="", password=None, **kwargs): """Create instance.""" db.Model.__init__(self, title=title.strip(), **kwargs) def __str__(self): """String representation of the user. Shows the target title.""" return self.title def get_id(self): return self.id ## Instruction: Remove import from testing packages ## Code After: ''' Created on Sep 24, 2016 @author: rtorres ''' from flaskiwsapp.database import SurrogatePK, Model, db, reference_col, relationship, Column from sqlalchemy.dialects.postgresql.base import ENUM AREAS = ('Policies', 'Billing', 'Claims', 'Reports') class Target(SurrogatePK, Model): """A user of the app.""" __tablename__ = 'targets' title = Column(db.String(80), nullable=False) description = Column(db.Text(), nullable=False) client_id = reference_col('clients', nullable=False) client = relationship('Client', backref='targets') client_priority = Column(db.SmallInteger(), nullable=False) product_area = Column(ENUM(*AREAS, name='areas', create_type=False), nullable=False) target_date = Column(db.DateTime(), nullable=False) ticket_url = Column(db.String(256), nullable=False) def __init__(self, title="", password=None, **kwargs): """Create instance.""" db.Model.__init__(self, title=title.strip(), **kwargs) def __str__(self): """String representation of the user. Shows the target title.""" return self.title def get_id(self): return self.id
# ... existing code ... from flaskiwsapp.database import SurrogatePK, Model, db, reference_col, relationship, Column from sqlalchemy.dialects.postgresql.base import ENUM # ... rest of the code ...
d0e7d3578fe79432ad2b2cc62be2203d4ff36014
examples/charts/file/cat_heatmap.py
examples/charts/file/cat_heatmap.py
from bokeh.charts import HeatMap, output_file, show from bokeh.sampledata.unemployment1948 import data # pandas magic df = data[data.columns[:-2]] df2 = df.set_index(df[df.columns[0]].astype(str)) df2.drop(df.columns[0], axis=1, inplace=True) df3 = df2.transpose() output_file("cat_heatmap.html") hm = HeatMap(df3, title="categorical heatmap", width=800) show(hm)
from bokeh.charts import HeatMap, output_file, show from bokeh.palettes import YlOrRd9 as palette from bokeh.sampledata.unemployment1948 import data # pandas magic df = data[data.columns[:-1]] df2 = df.set_index(df[df.columns[0]].astype(str)) df2.drop(df.columns[0], axis=1, inplace=True) df3 = df2.transpose() output_file("cat_heatmap.html") palette = palette[::-1] # Reverse the color order so dark red is highest unemployment hm = HeatMap(df3, title="categorical heatmap", width=800, palette=palette) show(hm)
Use all the months of the year and tweak palette.
Use all the months of the year and tweak palette. - Picked a continuous palette and reversed as better for the data.
Python
bsd-3-clause
abele/bokeh,laurent-george/bokeh,azjps/bokeh,josherick/bokeh,rs2/bokeh,timsnyder/bokeh,draperjames/bokeh,matbra/bokeh,ptitjano/bokeh,DuCorey/bokeh,awanke/bokeh,akloster/bokeh,xguse/bokeh,stonebig/bokeh,KasperPRasmussen/bokeh,phobson/bokeh,stonebig/bokeh,CrazyGuo/bokeh,ericmjl/bokeh,rhiever/bokeh,caseyclements/bokeh,roxyboy/bokeh,maxalbert/bokeh,ericdill/bokeh,KasperPRasmussen/bokeh,maxalbert/bokeh,stuart-knock/bokeh,draperjames/bokeh,carlvlewis/bokeh,akloster/bokeh,srinathv/bokeh,timsnyder/bokeh,khkaminska/bokeh,gpfreitas/bokeh,bokeh/bokeh,dennisobrien/bokeh,rothnic/bokeh,Karel-van-de-Plassche/bokeh,deeplook/bokeh,PythonCharmers/bokeh,matbra/bokeh,ericmjl/bokeh,ahmadia/bokeh,justacec/bokeh,aiguofer/bokeh,muku42/bokeh,ChristosChristofidis/bokeh,matbra/bokeh,rothnic/bokeh,mindriot101/bokeh,phobson/bokeh,Karel-van-de-Plassche/bokeh,timothydmorton/bokeh,ChristosChristofidis/bokeh,philippjfr/bokeh,josherick/bokeh,rhiever/bokeh,roxyboy/bokeh,alan-unravel/bokeh,jakirkham/bokeh,timsnyder/bokeh,philippjfr/bokeh,ahmadia/bokeh,aavanian/bokeh,carlvlewis/bokeh,maxalbert/bokeh,muku42/bokeh,laurent-george/bokeh,justacec/bokeh,evidation-health/bokeh,laurent-george/bokeh,bsipocz/bokeh,DuCorey/bokeh,rs2/bokeh,saifrahmed/bokeh,quasiben/bokeh,justacec/bokeh,ptitjano/bokeh,saifrahmed/bokeh,jakirkham/bokeh,jplourenco/bokeh,ChinaQuants/bokeh,percyfal/bokeh,stonebig/bokeh,ericmjl/bokeh,daodaoliang/bokeh,eteq/bokeh,abele/bokeh,htygithub/bokeh,aiguofer/bokeh,khkaminska/bokeh,ahmadia/bokeh,stuart-knock/bokeh,htygithub/bokeh,paultcochrane/bokeh,jakirkham/bokeh,muku42/bokeh,srinathv/bokeh,alan-unravel/bokeh,philippjfr/bokeh,htygithub/bokeh,eteq/bokeh,bokeh/bokeh,ChinaQuants/bokeh,KasperPRasmussen/bokeh,daodaoliang/bokeh,eteq/bokeh,schoolie/bokeh,satishgoda/bokeh,aavanian/bokeh,carlvlewis/bokeh,PythonCharmers/bokeh,phobson/bokeh,josherick/bokeh,schoolie/bokeh,aiguofer/bokeh,daodaoliang/bokeh,jplourenco/bokeh,roxyboy/bokeh,Karel-van-de-Plassche/bokeh,jplourenco/bokeh,tacaswell/bokeh,azjps/bokeh,quasiben/bokeh,dennisobrien/bokeh,saifrahmed/bokeh,mindriot101/bokeh,azjps/bokeh,xguse/bokeh,bsipocz/bokeh,caseyclements/bokeh,clairetang6/bokeh,paultcochrane/bokeh,saifrahmed/bokeh,stuart-knock/bokeh,gpfreitas/bokeh,dennisobrien/bokeh,alan-unravel/bokeh,jakirkham/bokeh,KasperPRasmussen/bokeh,Karel-van-de-Plassche/bokeh,DuCorey/bokeh,xguse/bokeh,jplourenco/bokeh,PythonCharmers/bokeh,PythonCharmers/bokeh,schoolie/bokeh,philippjfr/bokeh,gpfreitas/bokeh,xguse/bokeh,timsnyder/bokeh,deeplook/bokeh,khkaminska/bokeh,evidation-health/bokeh,paultcochrane/bokeh,aiguofer/bokeh,aavanian/bokeh,DuCorey/bokeh,msarahan/bokeh,stonebig/bokeh,ChristosChristofidis/bokeh,abele/bokeh,rhiever/bokeh,draperjames/bokeh,bsipocz/bokeh,ericdill/bokeh,rhiever/bokeh,awanke/bokeh,azjps/bokeh,muku42/bokeh,srinathv/bokeh,timsnyder/bokeh,satishgoda/bokeh,satishgoda/bokeh,eteq/bokeh,msarahan/bokeh,daodaoliang/bokeh,rothnic/bokeh,awanke/bokeh,maxalbert/bokeh,evidation-health/bokeh,ericmjl/bokeh,jakirkham/bokeh,ericdill/bokeh,ChinaQuants/bokeh,satishgoda/bokeh,Karel-van-de-Plassche/bokeh,paultcochrane/bokeh,CrazyGuo/bokeh,deeplook/bokeh,akloster/bokeh,caseyclements/bokeh,draperjames/bokeh,aavanian/bokeh,deeplook/bokeh,ChinaQuants/bokeh,CrazyGuo/bokeh,rs2/bokeh,bokeh/bokeh,clairetang6/bokeh,dennisobrien/bokeh,timothydmorton/bokeh,rs2/bokeh,ahmadia/bokeh,dennisobrien/bokeh,matbra/bokeh,justacec/bokeh,mindriot101/bokeh,timothydmorton/bokeh,akloster/bokeh,clairetang6/bokeh,awanke/bokeh,tacaswell/bokeh,schoolie/bokeh,evidation-health/bokeh,ptitjano/bokeh,schoolie/bokeh,htygithub/bokeh,alan-unravel/bokeh,ptitjano/bokeh,bokeh/bokeh,stuart-knock/bokeh,srinathv/bokeh,rs2/bokeh,ChristosChristofidis/bokeh,carlvlewis/bokeh,mindriot101/bokeh,msarahan/bokeh,gpfreitas/bokeh,KasperPRasmussen/bokeh,roxyboy/bokeh,percyfal/bokeh,aavanian/bokeh,CrazyGuo/bokeh,percyfal/bokeh,caseyclements/bokeh,azjps/bokeh,msarahan/bokeh,ericdill/bokeh,ptitjano/bokeh,percyfal/bokeh,aiguofer/bokeh,clairetang6/bokeh,bokeh/bokeh,josherick/bokeh,bsipocz/bokeh,phobson/bokeh,abele/bokeh,timothydmorton/bokeh,percyfal/bokeh,DuCorey/bokeh,quasiben/bokeh,tacaswell/bokeh,khkaminska/bokeh,phobson/bokeh,tacaswell/bokeh,rothnic/bokeh,draperjames/bokeh,philippjfr/bokeh,ericmjl/bokeh,laurent-george/bokeh
from bokeh.charts import HeatMap, output_file, show + from bokeh.palettes import YlOrRd9 as palette from bokeh.sampledata.unemployment1948 import data # pandas magic - df = data[data.columns[:-2]] + df = data[data.columns[:-1]] df2 = df.set_index(df[df.columns[0]].astype(str)) df2.drop(df.columns[0], axis=1, inplace=True) df3 = df2.transpose() output_file("cat_heatmap.html") + palette = palette[::-1] # Reverse the color order so dark red is highest unemployment - hm = HeatMap(df3, title="categorical heatmap", width=800) + hm = HeatMap(df3, title="categorical heatmap", width=800, palette=palette) show(hm) +
Use all the months of the year and tweak palette.
## Code Before: from bokeh.charts import HeatMap, output_file, show from bokeh.sampledata.unemployment1948 import data # pandas magic df = data[data.columns[:-2]] df2 = df.set_index(df[df.columns[0]].astype(str)) df2.drop(df.columns[0], axis=1, inplace=True) df3 = df2.transpose() output_file("cat_heatmap.html") hm = HeatMap(df3, title="categorical heatmap", width=800) show(hm) ## Instruction: Use all the months of the year and tweak palette. ## Code After: from bokeh.charts import HeatMap, output_file, show from bokeh.palettes import YlOrRd9 as palette from bokeh.sampledata.unemployment1948 import data # pandas magic df = data[data.columns[:-1]] df2 = df.set_index(df[df.columns[0]].astype(str)) df2.drop(df.columns[0], axis=1, inplace=True) df3 = df2.transpose() output_file("cat_heatmap.html") palette = palette[::-1] # Reverse the color order so dark red is highest unemployment hm = HeatMap(df3, title="categorical heatmap", width=800, palette=palette) show(hm)
... from bokeh.charts import HeatMap, output_file, show from bokeh.palettes import YlOrRd9 as palette from bokeh.sampledata.unemployment1948 import data # pandas magic df = data[data.columns[:-1]] df2 = df.set_index(df[df.columns[0]].astype(str)) df2.drop(df.columns[0], axis=1, inplace=True) ... output_file("cat_heatmap.html") palette = palette[::-1] # Reverse the color order so dark red is highest unemployment hm = HeatMap(df3, title="categorical heatmap", width=800, palette=palette) show(hm) ...
7f44c6a114f95c25b533c9b69988798ba3919d68
wger/email/forms.py
wger/email/forms.py
from django.utils.translation import ( pgettext, ugettext_lazy as _ ) from django.forms import ( Form, CharField, Textarea ) class EmailListForm(Form): ''' Small form to send emails ''' subject = CharField(label=pgettext('Subject', 'As in "email subject"')) body = CharField(widget=Textarea, label=pgettext('Content', 'As in "content of an email"'))
from django.utils.translation import ( pgettext, ugettext_lazy as _ ) from django.forms import ( Form, CharField, Textarea ) class EmailListForm(Form): ''' Small form to send emails ''' subject = CharField(label=pgettext('As in "email subject"', 'Subject')) body = CharField(widget=Textarea, label=pgettext('As in "content of an email"', 'Content'))
Use correct order of arguments of pgettext
Use correct order of arguments of pgettext
Python
agpl-3.0
rolandgeider/wger,rolandgeider/wger,wger-project/wger,DeveloperMal/wger,DeveloperMal/wger,wger-project/wger,rolandgeider/wger,kjagoo/wger_stark,petervanderdoes/wger,rolandgeider/wger,petervanderdoes/wger,wger-project/wger,wger-project/wger,petervanderdoes/wger,DeveloperMal/wger,kjagoo/wger_stark,kjagoo/wger_stark,petervanderdoes/wger,kjagoo/wger_stark,DeveloperMal/wger
from django.utils.translation import ( pgettext, ugettext_lazy as _ ) from django.forms import ( Form, CharField, Textarea ) class EmailListForm(Form): ''' Small form to send emails ''' - subject = CharField(label=pgettext('Subject', 'As in "email subject"')) + subject = CharField(label=pgettext('As in "email subject"', 'Subject')) - body = CharField(widget=Textarea, label=pgettext('Content', 'As in "content of an email"')) + body = CharField(widget=Textarea, label=pgettext('As in "content of an email"', 'Content'))
Use correct order of arguments of pgettext
## Code Before: from django.utils.translation import ( pgettext, ugettext_lazy as _ ) from django.forms import ( Form, CharField, Textarea ) class EmailListForm(Form): ''' Small form to send emails ''' subject = CharField(label=pgettext('Subject', 'As in "email subject"')) body = CharField(widget=Textarea, label=pgettext('Content', 'As in "content of an email"')) ## Instruction: Use correct order of arguments of pgettext ## Code After: from django.utils.translation import ( pgettext, ugettext_lazy as _ ) from django.forms import ( Form, CharField, Textarea ) class EmailListForm(Form): ''' Small form to send emails ''' subject = CharField(label=pgettext('As in "email subject"', 'Subject')) body = CharField(widget=Textarea, label=pgettext('As in "content of an email"', 'Content'))
# ... existing code ... ''' subject = CharField(label=pgettext('As in "email subject"', 'Subject')) body = CharField(widget=Textarea, label=pgettext('As in "content of an email"', 'Content')) # ... rest of the code ...
59c9b0a3914920c19c9ccdbf5d77e4ce990d7d58
rdmo/core/models.py
rdmo/core/models.py
from django.db import models from django.utils.timezone import now from django.utils.translation import get_language from django.utils.translation import ugettext_lazy as _ from rdmo.core.utils import get_languages class Model(models.Model): created = models.DateTimeField(editable=False, verbose_name=_('created')) updated = models.DateTimeField(editable=False, verbose_name=_('updated')) class Meta: abstract = True def save(self, *args, **kwargs): if self.created is None: self.created = now() self.updated = now() super(Model, self).save(*args, **kwargs) class TranslationMixin(object): def trans(self, field): current_language = get_language() languages = get_languages() for lang_code, lang_string, lang_field in languages: if lang_code == current_language: return getattr(self, '%s_%s' % (field, lang_field)) r = '' for i in range(1, 6): try: r = getattr(self, '%s_%s' % (field, 'lang' + str(i))) except AttributeError: pass else: if r != '': return r primary_lang_field = languages[0][2] return getattr(self, '%s_%s' % (field, primary_lang_field)) or ''
from django.db import models from django.utils.timezone import now from django.utils.translation import get_language from django.utils.translation import ugettext_lazy as _ from rdmo.core.utils import get_languages class Model(models.Model): created = models.DateTimeField(editable=False, verbose_name=_('created')) updated = models.DateTimeField(editable=False, verbose_name=_('updated')) class Meta: abstract = True def save(self, *args, **kwargs): if self.created is None: self.created = now() self.updated = now() super(Model, self).save(*args, **kwargs) class TranslationMixin(object): def trans(self, field): current_language = get_language() languages = get_languages() for lang_code, lang_string, lang_field in languages: if lang_code == current_language: return getattr(self, '%s_%s' % (field, lang_field)) r = '' for i in range(1, 6): try: r = getattr(self, '%s_%s' % (field, 'lang' + str(i))) except AttributeError: pass else: if r != '': return r return r primary_lang_field = languages[0][2] return getattr(self, '%s_%s' % (field, primary_lang_field)) or ''
Add value to return if nothing is found
Add value to return if nothing is found
Python
apache-2.0
rdmorganiser/rdmo,DMPwerkzeug/DMPwerkzeug,DMPwerkzeug/DMPwerkzeug,rdmorganiser/rdmo,DMPwerkzeug/DMPwerkzeug,rdmorganiser/rdmo
from django.db import models from django.utils.timezone import now from django.utils.translation import get_language from django.utils.translation import ugettext_lazy as _ from rdmo.core.utils import get_languages class Model(models.Model): created = models.DateTimeField(editable=False, verbose_name=_('created')) updated = models.DateTimeField(editable=False, verbose_name=_('updated')) class Meta: abstract = True def save(self, *args, **kwargs): if self.created is None: self.created = now() self.updated = now() super(Model, self).save(*args, **kwargs) class TranslationMixin(object): def trans(self, field): current_language = get_language() languages = get_languages() for lang_code, lang_string, lang_field in languages: if lang_code == current_language: return getattr(self, '%s_%s' % (field, lang_field)) r = '' for i in range(1, 6): try: r = getattr(self, '%s_%s' % (field, 'lang' + str(i))) except AttributeError: pass else: if r != '': return r + return r primary_lang_field = languages[0][2] return getattr(self, '%s_%s' % (field, primary_lang_field)) or ''
Add value to return if nothing is found
## Code Before: from django.db import models from django.utils.timezone import now from django.utils.translation import get_language from django.utils.translation import ugettext_lazy as _ from rdmo.core.utils import get_languages class Model(models.Model): created = models.DateTimeField(editable=False, verbose_name=_('created')) updated = models.DateTimeField(editable=False, verbose_name=_('updated')) class Meta: abstract = True def save(self, *args, **kwargs): if self.created is None: self.created = now() self.updated = now() super(Model, self).save(*args, **kwargs) class TranslationMixin(object): def trans(self, field): current_language = get_language() languages = get_languages() for lang_code, lang_string, lang_field in languages: if lang_code == current_language: return getattr(self, '%s_%s' % (field, lang_field)) r = '' for i in range(1, 6): try: r = getattr(self, '%s_%s' % (field, 'lang' + str(i))) except AttributeError: pass else: if r != '': return r primary_lang_field = languages[0][2] return getattr(self, '%s_%s' % (field, primary_lang_field)) or '' ## Instruction: Add value to return if nothing is found ## Code After: from django.db import models from django.utils.timezone import now from django.utils.translation import get_language from django.utils.translation import ugettext_lazy as _ from rdmo.core.utils import get_languages class Model(models.Model): created = models.DateTimeField(editable=False, verbose_name=_('created')) updated = models.DateTimeField(editable=False, verbose_name=_('updated')) class Meta: abstract = True def save(self, *args, **kwargs): if self.created is None: self.created = now() self.updated = now() super(Model, self).save(*args, **kwargs) class TranslationMixin(object): def trans(self, field): current_language = get_language() languages = get_languages() for lang_code, lang_string, lang_field in languages: if lang_code == current_language: return getattr(self, '%s_%s' % (field, lang_field)) r = '' for i in range(1, 6): try: r = getattr(self, '%s_%s' % (field, 'lang' + str(i))) except AttributeError: pass else: if r != '': return r return r primary_lang_field = languages[0][2] return getattr(self, '%s_%s' % (field, primary_lang_field)) or ''
// ... existing code ... if r != '': return r return r primary_lang_field = languages[0][2] // ... rest of the code ...
01dd4901532df4f3da51501d4f223c873dd49dd8
ideascube/tests/test_settings.py
ideascube/tests/test_settings.py
import glob import os import importlib import pytest @pytest.fixture(params=glob.glob('ideascube/conf/*.py')) def setting_module(request): basename = os.path.basename(request.param) module, _ = os.path.splitext(basename) return '.conf.%s' % module def test_setting_file(setting_module): from ideascube.forms import UserImportForm settings = importlib.import_module(setting_module, package="ideascube") assert isinstance(getattr(settings, 'IDEASCUBE_NAME', ''), str) for name, _ in getattr(settings, 'USER_IMPORT_FORMATS', []): assert hasattr(UserImportForm, '_get_{}_mapping'.format(name)) assert hasattr(UserImportForm, '_get_{}_reader'.format(name))
import glob import os import importlib import pytest @pytest.fixture(params=sorted([ f for f in glob.glob('ideascube/conf/*.py') if not f.endswith('/__init__.py') ])) def setting_module(request): basename = os.path.basename(request.param) module, _ = os.path.splitext(basename) return '.conf.%s' % module def test_setting_file(setting_module): from ideascube.forms import UserImportForm settings = importlib.import_module(setting_module, package="ideascube") assert isinstance(getattr(settings, 'IDEASCUBE_NAME', ''), str) for name, _ in getattr(settings, 'USER_IMPORT_FORMATS', []): assert hasattr(UserImportForm, '_get_{}_mapping'.format(name)) assert hasattr(UserImportForm, '_get_{}_reader'.format(name))
Improve the settings files testing fixture
tests: Improve the settings files testing fixture Let's order these files, as it makes it nicer in the pytest output. In addition, we can filter out the __init__.py file, since it is completely empty.
Python
agpl-3.0
ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube
import glob import os import importlib import pytest - @pytest.fixture(params=glob.glob('ideascube/conf/*.py')) + @pytest.fixture(params=sorted([ + f for f in glob.glob('ideascube/conf/*.py') + if not f.endswith('/__init__.py') + ])) def setting_module(request): basename = os.path.basename(request.param) module, _ = os.path.splitext(basename) return '.conf.%s' % module def test_setting_file(setting_module): from ideascube.forms import UserImportForm settings = importlib.import_module(setting_module, package="ideascube") assert isinstance(getattr(settings, 'IDEASCUBE_NAME', ''), str) for name, _ in getattr(settings, 'USER_IMPORT_FORMATS', []): assert hasattr(UserImportForm, '_get_{}_mapping'.format(name)) assert hasattr(UserImportForm, '_get_{}_reader'.format(name))
Improve the settings files testing fixture
## Code Before: import glob import os import importlib import pytest @pytest.fixture(params=glob.glob('ideascube/conf/*.py')) def setting_module(request): basename = os.path.basename(request.param) module, _ = os.path.splitext(basename) return '.conf.%s' % module def test_setting_file(setting_module): from ideascube.forms import UserImportForm settings = importlib.import_module(setting_module, package="ideascube") assert isinstance(getattr(settings, 'IDEASCUBE_NAME', ''), str) for name, _ in getattr(settings, 'USER_IMPORT_FORMATS', []): assert hasattr(UserImportForm, '_get_{}_mapping'.format(name)) assert hasattr(UserImportForm, '_get_{}_reader'.format(name)) ## Instruction: Improve the settings files testing fixture ## Code After: import glob import os import importlib import pytest @pytest.fixture(params=sorted([ f for f in glob.glob('ideascube/conf/*.py') if not f.endswith('/__init__.py') ])) def setting_module(request): basename = os.path.basename(request.param) module, _ = os.path.splitext(basename) return '.conf.%s' % module def test_setting_file(setting_module): from ideascube.forms import UserImportForm settings = importlib.import_module(setting_module, package="ideascube") assert isinstance(getattr(settings, 'IDEASCUBE_NAME', ''), str) for name, _ in getattr(settings, 'USER_IMPORT_FORMATS', []): assert hasattr(UserImportForm, '_get_{}_mapping'.format(name)) assert hasattr(UserImportForm, '_get_{}_reader'.format(name))
# ... existing code ... @pytest.fixture(params=sorted([ f for f in glob.glob('ideascube/conf/*.py') if not f.endswith('/__init__.py') ])) def setting_module(request): basename = os.path.basename(request.param) # ... rest of the code ...
2230832033df7f5d8511dc75f799a9cc738dc46f
games/managers.py
games/managers.py
from django.db.models import Manager class ScreenshotManager(Manager): def published(self, user=None, is_staff=False): query = self.get_query_set() query = query.order_by('uploaded_at') if is_staff: return query elif user: return query.filter(Q(published=True) | Q(user=user)) else: return query.filter(published=True)
from django.db.models import Manager from django.db.models import Q class ScreenshotManager(Manager): def published(self, user=None, is_staff=False): query = self.get_query_set() query = query.order_by('uploaded_at') if is_staff: return query elif user: return query.filter(Q(published=True) | Q(uploaded_by=user)) else: return query.filter(published=True)
Fix missing import and bad query for screenshots
Fix missing import and bad query for screenshots
Python
agpl-3.0
Turupawn/website,Turupawn/website,lutris/website,lutris/website,lutris/website,lutris/website,Turupawn/website,Turupawn/website
from django.db.models import Manager + from django.db.models import Q class ScreenshotManager(Manager): def published(self, user=None, is_staff=False): query = self.get_query_set() query = query.order_by('uploaded_at') if is_staff: return query elif user: - return query.filter(Q(published=True) | Q(user=user)) + return query.filter(Q(published=True) | Q(uploaded_by=user)) else: return query.filter(published=True)
Fix missing import and bad query for screenshots
## Code Before: from django.db.models import Manager class ScreenshotManager(Manager): def published(self, user=None, is_staff=False): query = self.get_query_set() query = query.order_by('uploaded_at') if is_staff: return query elif user: return query.filter(Q(published=True) | Q(user=user)) else: return query.filter(published=True) ## Instruction: Fix missing import and bad query for screenshots ## Code After: from django.db.models import Manager from django.db.models import Q class ScreenshotManager(Manager): def published(self, user=None, is_staff=False): query = self.get_query_set() query = query.order_by('uploaded_at') if is_staff: return query elif user: return query.filter(Q(published=True) | Q(uploaded_by=user)) else: return query.filter(published=True)
// ... existing code ... from django.db.models import Manager from django.db.models import Q // ... modified code ... return query elif user: return query.filter(Q(published=True) | Q(uploaded_by=user)) else: return query.filter(published=True) // ... rest of the code ...
52d15d09ed079d1b8598f314524066b56273af3d
addie/_version.py
addie/_version.py
import json import sys version_json = ''' { "dirty": false, "error": null, "full-revisionid": "aaeac9708788e1b02d6a763b86333eff9bad7122", "version": "5.0.4" } ''' # END VERSION_JSON def get_versions(): return json.loads(version_json)
import json version_json = ''' { "dirty": false, "error": null, "full-revisionid": "aaeac9708788e1b02d6a763b86333eff9bad7122", "version": "5.0.4" } ''' # END VERSION_JSON def get_versions(): return json.loads(version_json)
Remove sys import in versioneer file
Remove sys import in versioneer file
Python
mit
neutrons/FastGR,neutrons/FastGR,neutrons/FastGR
import json - import sys version_json = ''' { "dirty": false, "error": null, "full-revisionid": "aaeac9708788e1b02d6a763b86333eff9bad7122", "version": "5.0.4" } ''' # END VERSION_JSON def get_versions(): return json.loads(version_json)
Remove sys import in versioneer file
## Code Before: import json import sys version_json = ''' { "dirty": false, "error": null, "full-revisionid": "aaeac9708788e1b02d6a763b86333eff9bad7122", "version": "5.0.4" } ''' # END VERSION_JSON def get_versions(): return json.loads(version_json) ## Instruction: Remove sys import in versioneer file ## Code After: import json version_json = ''' { "dirty": false, "error": null, "full-revisionid": "aaeac9708788e1b02d6a763b86333eff9bad7122", "version": "5.0.4" } ''' # END VERSION_JSON def get_versions(): return json.loads(version_json)
# ... existing code ... import json version_json = ''' # ... rest of the code ...
f5356198f30002b4b4d26fba424a4bdd546a26e5
keeper/api_v1/errorhandlers.py
keeper/api_v1/errorhandlers.py
from flask import jsonify from ..exceptions import ValidationError from . import api @api.errorhandler(ValidationError) def bad_request(e): """Handler for ValidationError exceptions.""" response = jsonify({'status': 400, 'error': 'bad request', 'message': e.args[0]}) response.status_code = 400 return response @api.app_errorhandler(404) def not_found(e): """App-wide handler for HTTP 404 errors.""" response = jsonify({'status': 404, 'error': 'not found', 'message': 'invalid resource URI'}) response.status_code = 404 return response @api.errorhandler(405) def method_not_supported(e): """Handler for HTTP 405 exceptions.""" response = jsonify({'status': 405, 'error': 'method not supported', 'message': 'the method is not supported'}) response.status_code = 405 return response @api.app_errorhandler(500) def internal_server_error(e): """App-wide handler for HTTP 500 errors.""" response = jsonify({'status': 500, 'error': 'internal server error', 'message': e.args[0]}) response.status_code = 500 return response
from flask import jsonify import structlog from ..exceptions import ValidationError from . import api @api.errorhandler(ValidationError) def bad_request(e): """Handler for ValidationError exceptions.""" response = jsonify({'status': 400, 'error': 'bad request', 'message': e.args[0]}) response.status_code = 400 return response @api.app_errorhandler(404) def not_found(e): """App-wide handler for HTTP 404 errors.""" response = jsonify({'status': 404, 'error': 'not found', 'message': 'invalid resource URI'}) response.status_code = 404 return response @api.errorhandler(405) def method_not_supported(e): """Handler for HTTP 405 exceptions.""" response = jsonify({'status': 405, 'error': 'method not supported', 'message': 'the method is not supported'}) response.status_code = 405 return response @api.app_errorhandler(500) def internal_server_error(e): """App-wide handler for HTTP 500 errors.""" logger = structlog.get_logger() logger.error(status=500, message=e.args[0]) response = jsonify({'status': 500, 'error': 'internal server error', 'message': e.args[0]}) response.status_code = 500 return response
Add an error logger to the 500 handler
Add an error logger to the 500 handler
Python
mit
lsst-sqre/ltd-keeper,lsst-sqre/ltd-keeper
from flask import jsonify + import structlog + from ..exceptions import ValidationError from . import api @api.errorhandler(ValidationError) def bad_request(e): """Handler for ValidationError exceptions.""" response = jsonify({'status': 400, 'error': 'bad request', 'message': e.args[0]}) response.status_code = 400 return response @api.app_errorhandler(404) def not_found(e): """App-wide handler for HTTP 404 errors.""" response = jsonify({'status': 404, 'error': 'not found', 'message': 'invalid resource URI'}) response.status_code = 404 return response @api.errorhandler(405) def method_not_supported(e): """Handler for HTTP 405 exceptions.""" response = jsonify({'status': 405, 'error': 'method not supported', 'message': 'the method is not supported'}) response.status_code = 405 return response @api.app_errorhandler(500) def internal_server_error(e): """App-wide handler for HTTP 500 errors.""" + logger = structlog.get_logger() + logger.error(status=500, message=e.args[0]) + response = jsonify({'status': 500, 'error': 'internal server error', 'message': e.args[0]}) response.status_code = 500 return response
Add an error logger to the 500 handler
## Code Before: from flask import jsonify from ..exceptions import ValidationError from . import api @api.errorhandler(ValidationError) def bad_request(e): """Handler for ValidationError exceptions.""" response = jsonify({'status': 400, 'error': 'bad request', 'message': e.args[0]}) response.status_code = 400 return response @api.app_errorhandler(404) def not_found(e): """App-wide handler for HTTP 404 errors.""" response = jsonify({'status': 404, 'error': 'not found', 'message': 'invalid resource URI'}) response.status_code = 404 return response @api.errorhandler(405) def method_not_supported(e): """Handler for HTTP 405 exceptions.""" response = jsonify({'status': 405, 'error': 'method not supported', 'message': 'the method is not supported'}) response.status_code = 405 return response @api.app_errorhandler(500) def internal_server_error(e): """App-wide handler for HTTP 500 errors.""" response = jsonify({'status': 500, 'error': 'internal server error', 'message': e.args[0]}) response.status_code = 500 return response ## Instruction: Add an error logger to the 500 handler ## Code After: from flask import jsonify import structlog from ..exceptions import ValidationError from . import api @api.errorhandler(ValidationError) def bad_request(e): """Handler for ValidationError exceptions.""" response = jsonify({'status': 400, 'error': 'bad request', 'message': e.args[0]}) response.status_code = 400 return response @api.app_errorhandler(404) def not_found(e): """App-wide handler for HTTP 404 errors.""" response = jsonify({'status': 404, 'error': 'not found', 'message': 'invalid resource URI'}) response.status_code = 404 return response @api.errorhandler(405) def method_not_supported(e): """Handler for HTTP 405 exceptions.""" response = jsonify({'status': 405, 'error': 'method not supported', 'message': 'the method is not supported'}) response.status_code = 405 return response @api.app_errorhandler(500) def internal_server_error(e): """App-wide handler for HTTP 500 errors.""" logger = structlog.get_logger() logger.error(status=500, message=e.args[0]) response = jsonify({'status': 500, 'error': 'internal server error', 'message': e.args[0]}) response.status_code = 500 return response
# ... existing code ... from flask import jsonify import structlog from ..exceptions import ValidationError from . import api # ... modified code ... def internal_server_error(e): """App-wide handler for HTTP 500 errors.""" logger = structlog.get_logger() logger.error(status=500, message=e.args[0]) response = jsonify({'status': 500, 'error': 'internal server error', 'message': e.args[0]}) # ... rest of the code ...
88d49172417ef7c99fa59313a10808c2b1a38b86
api/views.py
api/views.py
from rest_framework import generics from rest_framework_extensions.cache.decorators import cache_response from api.serializers import EventListSerializers from api.processors import get_approved_events from api.serializers import ScoreboardSerializer from web.processors.event import count_approved_events_for_country class CachedListAPIView(generics.ListAPIView): """ Concrete cached view for listing a queryset. """ @cache_response(240) def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) class EventListApi(CachedListAPIView): """ Lists approved Events, takes the following optional GET parameters: * limit * order * country_code * past """ serializer_class = EventListSerializers def get_queryset(self): params = { 'limit': self.request.GET.get('limit', None), 'order': self.request.GET.get('order', None), 'country_code': self.request.GET.get('country_code', None), 'past': self.request.GET.get('past', False) } return get_approved_events(**params) class ScoreBoardApi(CachedListAPIView): "Lists scoreboard entries" serializer_class = ScoreboardSerializer def get_queryset(self): return count_approved_events_for_country()
from hashlib import sha1 from rest_framework import generics from rest_framework_extensions.cache.decorators import cache_response from api.serializers import EventListSerializers from api.processors import get_approved_events from api.serializers import ScoreboardSerializer from web.processors.event import count_approved_events_for_country class CachedListAPIView(generics.ListAPIView): """ Concrete cached view for listing a queryset. """ @cache_response(timeout=240, key_func='calculate_cache_key') def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def calculate_cache_key(self, view_instance, view_method, request, args, kwargs): return sha1('-'.join([ repr(request.GET), repr(args), repr(kwargs), ])).hexdigest() class EventListApi(CachedListAPIView): """ Lists approved Events, takes the following optional GET parameters: * limit * order * country_code * past """ serializer_class = EventListSerializers def get_queryset(self): params = { 'limit': self.request.GET.get('limit', None), 'order': self.request.GET.get('order', None), 'country_code': self.request.GET.get('country_code', None), 'past': self.request.GET.get('past', False) } return get_approved_events(**params) class ScoreBoardApi(CachedListAPIView): "Lists scoreboard entries" serializer_class = ScoreboardSerializer def get_queryset(self): return count_approved_events_for_country()
Include the query string in the API cache key
Include the query string in the API cache key Otherwise, these two URLs would return the same data: /api/event/list/?format=json&past=yes /api/event/list/?format=json
Python
mit
codeeu/coding-events,codeeu/coding-events,codeeu/coding-events,codeeu/coding-events,codeeu/coding-events
+ from hashlib import sha1 + from rest_framework import generics from rest_framework_extensions.cache.decorators import cache_response from api.serializers import EventListSerializers from api.processors import get_approved_events from api.serializers import ScoreboardSerializer from web.processors.event import count_approved_events_for_country class CachedListAPIView(generics.ListAPIView): """ Concrete cached view for listing a queryset. """ - @cache_response(240) + @cache_response(timeout=240, key_func='calculate_cache_key') def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) + + def calculate_cache_key(self, view_instance, view_method, request, args, kwargs): + return sha1('-'.join([ + repr(request.GET), + repr(args), + repr(kwargs), + ])).hexdigest() class EventListApi(CachedListAPIView): """ Lists approved Events, takes the following optional GET parameters: * limit * order * country_code * past """ serializer_class = EventListSerializers def get_queryset(self): params = { 'limit': self.request.GET.get('limit', None), 'order': self.request.GET.get('order', None), 'country_code': self.request.GET.get('country_code', None), 'past': self.request.GET.get('past', False) } return get_approved_events(**params) class ScoreBoardApi(CachedListAPIView): "Lists scoreboard entries" serializer_class = ScoreboardSerializer def get_queryset(self): return count_approved_events_for_country()
Include the query string in the API cache key
## Code Before: from rest_framework import generics from rest_framework_extensions.cache.decorators import cache_response from api.serializers import EventListSerializers from api.processors import get_approved_events from api.serializers import ScoreboardSerializer from web.processors.event import count_approved_events_for_country class CachedListAPIView(generics.ListAPIView): """ Concrete cached view for listing a queryset. """ @cache_response(240) def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) class EventListApi(CachedListAPIView): """ Lists approved Events, takes the following optional GET parameters: * limit * order * country_code * past """ serializer_class = EventListSerializers def get_queryset(self): params = { 'limit': self.request.GET.get('limit', None), 'order': self.request.GET.get('order', None), 'country_code': self.request.GET.get('country_code', None), 'past': self.request.GET.get('past', False) } return get_approved_events(**params) class ScoreBoardApi(CachedListAPIView): "Lists scoreboard entries" serializer_class = ScoreboardSerializer def get_queryset(self): return count_approved_events_for_country() ## Instruction: Include the query string in the API cache key ## Code After: from hashlib import sha1 from rest_framework import generics from rest_framework_extensions.cache.decorators import cache_response from api.serializers import EventListSerializers from api.processors import get_approved_events from api.serializers import ScoreboardSerializer from web.processors.event import count_approved_events_for_country class CachedListAPIView(generics.ListAPIView): """ Concrete cached view for listing a queryset. """ @cache_response(timeout=240, key_func='calculate_cache_key') def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def calculate_cache_key(self, view_instance, view_method, request, args, kwargs): return sha1('-'.join([ repr(request.GET), repr(args), repr(kwargs), ])).hexdigest() class EventListApi(CachedListAPIView): """ Lists approved Events, takes the following optional GET parameters: * limit * order * country_code * past """ serializer_class = EventListSerializers def get_queryset(self): params = { 'limit': self.request.GET.get('limit', None), 'order': self.request.GET.get('order', None), 'country_code': self.request.GET.get('country_code', None), 'past': self.request.GET.get('past', False) } return get_approved_events(**params) class ScoreBoardApi(CachedListAPIView): "Lists scoreboard entries" serializer_class = ScoreboardSerializer def get_queryset(self): return count_approved_events_for_country()
... from hashlib import sha1 from rest_framework import generics from rest_framework_extensions.cache.decorators import cache_response ... Concrete cached view for listing a queryset. """ @cache_response(timeout=240, key_func='calculate_cache_key') def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def calculate_cache_key(self, view_instance, view_method, request, args, kwargs): return sha1('-'.join([ repr(request.GET), repr(args), repr(kwargs), ])).hexdigest() ...
593e826b24d83997a5be450be1401e16ec17c07c
application.py
application.py
from __future__ import print_function import os from flask.ext.script import Manager, Server from flask.ext.migrate import Migrate, MigrateCommand from app import create_app, db application = create_app(os.getenv('DM_ENVIRONMENT') or 'development') manager = Manager(application) manager.add_command("runserver", Server(port=5000)) migrate = Migrate(application, db) manager.add_command('db', MigrateCommand) @manager.command def list_routes(): """List URLs of all application routes.""" for rule in sorted(application.url_map.iter_rules(), key=lambda r: r.rule): print("{:10} {}".format(", ".join(rule.methods - set(['OPTIONS', 'HEAD'])), rule.rule)) if __name__ == '__main__': manager.run()
from __future__ import print_function import os from dmutils import init_manager from flask.ext.migrate import Migrate, MigrateCommand from app import create_app, db application = create_app(os.getenv('DM_ENVIRONMENT') or 'development') manager = init_manager(application, 5000, ['./json_schemas']) migrate = Migrate(application, db) manager.add_command('db', MigrateCommand) if __name__ == '__main__': manager.run()
Use new dmutils init_manager to set up reload on schema changes
Use new dmutils init_manager to set up reload on schema changes
Python
mit
alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api
from __future__ import print_function import os - from flask.ext.script import Manager, Server + from dmutils import init_manager from flask.ext.migrate import Migrate, MigrateCommand from app import create_app, db application = create_app(os.getenv('DM_ENVIRONMENT') or 'development') - manager = Manager(application) - manager.add_command("runserver", Server(port=5000)) + manager = init_manager(application, 5000, ['./json_schemas']) + migrate = Migrate(application, db) manager.add_command('db', MigrateCommand) - @manager.command - def list_routes(): - """List URLs of all application routes.""" - for rule in sorted(application.url_map.iter_rules(), key=lambda r: r.rule): - print("{:10} {}".format(", ".join(rule.methods - set(['OPTIONS', 'HEAD'])), rule.rule)) - if __name__ == '__main__': manager.run()
Use new dmutils init_manager to set up reload on schema changes
## Code Before: from __future__ import print_function import os from flask.ext.script import Manager, Server from flask.ext.migrate import Migrate, MigrateCommand from app import create_app, db application = create_app(os.getenv('DM_ENVIRONMENT') or 'development') manager = Manager(application) manager.add_command("runserver", Server(port=5000)) migrate = Migrate(application, db) manager.add_command('db', MigrateCommand) @manager.command def list_routes(): """List URLs of all application routes.""" for rule in sorted(application.url_map.iter_rules(), key=lambda r: r.rule): print("{:10} {}".format(", ".join(rule.methods - set(['OPTIONS', 'HEAD'])), rule.rule)) if __name__ == '__main__': manager.run() ## Instruction: Use new dmutils init_manager to set up reload on schema changes ## Code After: from __future__ import print_function import os from dmutils import init_manager from flask.ext.migrate import Migrate, MigrateCommand from app import create_app, db application = create_app(os.getenv('DM_ENVIRONMENT') or 'development') manager = init_manager(application, 5000, ['./json_schemas']) migrate = Migrate(application, db) manager.add_command('db', MigrateCommand) if __name__ == '__main__': manager.run()
... import os from dmutils import init_manager from flask.ext.migrate import Migrate, MigrateCommand ... application = create_app(os.getenv('DM_ENVIRONMENT') or 'development') manager = init_manager(application, 5000, ['./json_schemas']) migrate = Migrate(application, db) manager.add_command('db', MigrateCommand) ... if __name__ == '__main__': manager.run() ...
6b762607914e1c79bc05f7e8d5cdbe6c6d7a49e4
hiro/patches.py
hiro/patches.py
import abc from datetime import date as realdate from datetime import datetime as realdatetime import time import six class DatetimeMeta(abc.ABCMeta): """ meta class to allow interaction between :class:`datetime.datetime` objects create inside the :class:`hiro.Timeline` with those created outside it. """ def __instancecheck__(cls, instance): return isinstance(instance, realdatetime) class DateMeta(type): """ meta class to allow interaction between :class:`datetime.date` objects create inside the :class:`hiro.Timeline` with those created outside it. """ def __instancecheck__(cls, instance): return isinstance(instance, realdate) @six.add_metaclass(DatetimeMeta) class Datetime(realdatetime): """ used to patch :class:`datetime.datetime` to follow the rules of the parent :class:`hiro.Timeline` """ @classmethod def now(cls, tz=None): return cls.fromtimestamp(time.time(), tz) @classmethod def utcnow(cls): return cls.fromtimestamp(time.mktime(time.gmtime())) @six.add_metaclass(DateMeta) class Date(realdate): """ used to patch :class:`datetime.date` to follow the rules of the parent :class:`hiro.Timeline` """ __metaclass__ = DateMeta @classmethod def today(cls): return cls.fromtimestamp(time.time())
import abc from datetime import date as realdate from datetime import datetime as realdatetime import time import six class DatetimeMeta(abc.ABCMeta): """ meta class to allow interaction between :class:`datetime.datetime` objects create inside the :class:`hiro.Timeline` with those created outside it. """ def __instancecheck__(cls, instance): return isinstance(instance, realdatetime) class DateMeta(type): """ meta class to allow interaction between :class:`datetime.date` objects create inside the :class:`hiro.Timeline` with those created outside it. """ def __instancecheck__(cls, instance): return isinstance(instance, realdate) @six.add_metaclass(DatetimeMeta) class Datetime(realdatetime): """ used to patch :class:`datetime.datetime` to follow the rules of the parent :class:`hiro.Timeline` """ @classmethod def now(cls, tz=None): return cls.fromtimestamp(time.time(), tz) @classmethod def utcnow(cls): return cls.utcfromtimestamp(time.time()) @six.add_metaclass(DateMeta) class Date(realdate): """ used to patch :class:`datetime.date` to follow the rules of the parent :class:`hiro.Timeline` """ __metaclass__ = DateMeta @classmethod def today(cls): return cls.fromtimestamp(time.time())
Fix issue with daylight saving time + utcnow
Fix issue with daylight saving time + utcnow Fixes issue #2
Python
mit
alisaifee/hiro,alisaifee/hiro
import abc from datetime import date as realdate from datetime import datetime as realdatetime import time import six class DatetimeMeta(abc.ABCMeta): """ meta class to allow interaction between :class:`datetime.datetime` objects create inside the :class:`hiro.Timeline` with those created outside it. """ def __instancecheck__(cls, instance): return isinstance(instance, realdatetime) class DateMeta(type): """ meta class to allow interaction between :class:`datetime.date` objects create inside the :class:`hiro.Timeline` with those created outside it. """ def __instancecheck__(cls, instance): return isinstance(instance, realdate) @six.add_metaclass(DatetimeMeta) class Datetime(realdatetime): """ used to patch :class:`datetime.datetime` to follow the rules of the parent :class:`hiro.Timeline` """ @classmethod def now(cls, tz=None): return cls.fromtimestamp(time.time(), tz) @classmethod def utcnow(cls): - return cls.fromtimestamp(time.mktime(time.gmtime())) + return cls.utcfromtimestamp(time.time()) @six.add_metaclass(DateMeta) class Date(realdate): """ used to patch :class:`datetime.date` to follow the rules of the parent :class:`hiro.Timeline` """ __metaclass__ = DateMeta @classmethod def today(cls): return cls.fromtimestamp(time.time())
Fix issue with daylight saving time + utcnow
## Code Before: import abc from datetime import date as realdate from datetime import datetime as realdatetime import time import six class DatetimeMeta(abc.ABCMeta): """ meta class to allow interaction between :class:`datetime.datetime` objects create inside the :class:`hiro.Timeline` with those created outside it. """ def __instancecheck__(cls, instance): return isinstance(instance, realdatetime) class DateMeta(type): """ meta class to allow interaction between :class:`datetime.date` objects create inside the :class:`hiro.Timeline` with those created outside it. """ def __instancecheck__(cls, instance): return isinstance(instance, realdate) @six.add_metaclass(DatetimeMeta) class Datetime(realdatetime): """ used to patch :class:`datetime.datetime` to follow the rules of the parent :class:`hiro.Timeline` """ @classmethod def now(cls, tz=None): return cls.fromtimestamp(time.time(), tz) @classmethod def utcnow(cls): return cls.fromtimestamp(time.mktime(time.gmtime())) @six.add_metaclass(DateMeta) class Date(realdate): """ used to patch :class:`datetime.date` to follow the rules of the parent :class:`hiro.Timeline` """ __metaclass__ = DateMeta @classmethod def today(cls): return cls.fromtimestamp(time.time()) ## Instruction: Fix issue with daylight saving time + utcnow ## Code After: import abc from datetime import date as realdate from datetime import datetime as realdatetime import time import six class DatetimeMeta(abc.ABCMeta): """ meta class to allow interaction between :class:`datetime.datetime` objects create inside the :class:`hiro.Timeline` with those created outside it. """ def __instancecheck__(cls, instance): return isinstance(instance, realdatetime) class DateMeta(type): """ meta class to allow interaction between :class:`datetime.date` objects create inside the :class:`hiro.Timeline` with those created outside it. """ def __instancecheck__(cls, instance): return isinstance(instance, realdate) @six.add_metaclass(DatetimeMeta) class Datetime(realdatetime): """ used to patch :class:`datetime.datetime` to follow the rules of the parent :class:`hiro.Timeline` """ @classmethod def now(cls, tz=None): return cls.fromtimestamp(time.time(), tz) @classmethod def utcnow(cls): return cls.utcfromtimestamp(time.time()) @six.add_metaclass(DateMeta) class Date(realdate): """ used to patch :class:`datetime.date` to follow the rules of the parent :class:`hiro.Timeline` """ __metaclass__ = DateMeta @classmethod def today(cls): return cls.fromtimestamp(time.time())
# ... existing code ... @classmethod def utcnow(cls): return cls.utcfromtimestamp(time.time()) @six.add_metaclass(DateMeta) # ... rest of the code ...
8df58655f5a7a46a781fc0e126b148943a8d5b50
tests/sentry/metrics/test_datadog.py
tests/sentry/metrics/test_datadog.py
from __future__ import absolute_import import socket from mock import patch from sentry.metrics.datadog import DatadogMetricsBackend from sentry.testutils import TestCase class DatadogMetricsBackendTest(TestCase): def setUp(self): self.backend = DatadogMetricsBackend(prefix='sentrytest.') @patch('datadog.threadstats.base.ThreadStats.increment') def test_incr(self, mock_incr): self.backend.incr('foo', instance='bar') mock_incr.assert_called_once_with( 'sentrytest.foo', 1, sample_rate=1, tags=['instance:bar'], host=socket.gethostname(), ) @patch('datadog.threadstats.base.ThreadStats.timing') def test_timing(self, mock_timing): self.backend.timing('foo', 30, instance='bar') mock_timing.assert_called_once_with( 'sentrytest.foo', 30, sample_rate=1, tags=['instance:bar'], host=socket.gethostname(), )
from __future__ import absolute_import import socket from mock import patch from sentry.metrics.datadog import DatadogMetricsBackend from sentry.testutils import TestCase class DatadogMetricsBackendTest(TestCase): def setUp(self): self.backend = DatadogMetricsBackend(prefix='sentrytest.') @patch('datadog.threadstats.base.ThreadStats.increment') def test_incr(self, mock_incr): self.backend.incr('foo', instance='bar') mock_incr.assert_called_once_with( 'sentrytest.foo', 1, tags=['instance:bar'], host=socket.gethostname(), ) @patch('datadog.threadstats.base.ThreadStats.timing') def test_timing(self, mock_timing): self.backend.timing('foo', 30, instance='bar') mock_timing.assert_called_once_with( 'sentrytest.foo', 30, sample_rate=1, tags=['instance:bar'], host=socket.gethostname(), )
Remove no longer valid test
Remove no longer valid test
Python
bsd-3-clause
BuildingLink/sentry,mvaled/sentry,jean/sentry,kevinlondon/sentry,imankulov/sentry,mitsuhiko/sentry,nicholasserra/sentry,ifduyue/sentry,gencer/sentry,fotinakis/sentry,mvaled/sentry,alexm92/sentry,alexm92/sentry,kevinlondon/sentry,beeftornado/sentry,looker/sentry,korealerts1/sentry,jean/sentry,beeftornado/sentry,fotinakis/sentry,ngonzalvez/sentry,JackDanger/sentry,ngonzalvez/sentry,nicholasserra/sentry,JamesMura/sentry,jean/sentry,gencer/sentry,daevaorn/sentry,imankulov/sentry,JamesMura/sentry,JackDanger/sentry,zenefits/sentry,alexm92/sentry,gencer/sentry,BayanGroup/sentry,ifduyue/sentry,felixbuenemann/sentry,mvaled/sentry,ifduyue/sentry,looker/sentry,ifduyue/sentry,mitsuhiko/sentry,BuildingLink/sentry,korealerts1/sentry,daevaorn/sentry,JamesMura/sentry,Natim/sentry,gencer/sentry,mvaled/sentry,Natim/sentry,zenefits/sentry,ngonzalvez/sentry,Kryz/sentry,BayanGroup/sentry,looker/sentry,daevaorn/sentry,JackDanger/sentry,daevaorn/sentry,imankulov/sentry,BuildingLink/sentry,JamesMura/sentry,ifduyue/sentry,zenefits/sentry,nicholasserra/sentry,BuildingLink/sentry,gencer/sentry,fotinakis/sentry,mvaled/sentry,Kryz/sentry,kevinlondon/sentry,JamesMura/sentry,Kryz/sentry,felixbuenemann/sentry,jean/sentry,fotinakis/sentry,Natim/sentry,looker/sentry,jean/sentry,beeftornado/sentry,zenefits/sentry,korealerts1/sentry,felixbuenemann/sentry,zenefits/sentry,BayanGroup/sentry,mvaled/sentry,BuildingLink/sentry,looker/sentry
from __future__ import absolute_import import socket from mock import patch from sentry.metrics.datadog import DatadogMetricsBackend from sentry.testutils import TestCase class DatadogMetricsBackendTest(TestCase): def setUp(self): self.backend = DatadogMetricsBackend(prefix='sentrytest.') @patch('datadog.threadstats.base.ThreadStats.increment') def test_incr(self, mock_incr): self.backend.incr('foo', instance='bar') mock_incr.assert_called_once_with( 'sentrytest.foo', 1, - sample_rate=1, tags=['instance:bar'], host=socket.gethostname(), ) @patch('datadog.threadstats.base.ThreadStats.timing') def test_timing(self, mock_timing): self.backend.timing('foo', 30, instance='bar') mock_timing.assert_called_once_with( 'sentrytest.foo', 30, sample_rate=1, tags=['instance:bar'], host=socket.gethostname(), )
Remove no longer valid test
## Code Before: from __future__ import absolute_import import socket from mock import patch from sentry.metrics.datadog import DatadogMetricsBackend from sentry.testutils import TestCase class DatadogMetricsBackendTest(TestCase): def setUp(self): self.backend = DatadogMetricsBackend(prefix='sentrytest.') @patch('datadog.threadstats.base.ThreadStats.increment') def test_incr(self, mock_incr): self.backend.incr('foo', instance='bar') mock_incr.assert_called_once_with( 'sentrytest.foo', 1, sample_rate=1, tags=['instance:bar'], host=socket.gethostname(), ) @patch('datadog.threadstats.base.ThreadStats.timing') def test_timing(self, mock_timing): self.backend.timing('foo', 30, instance='bar') mock_timing.assert_called_once_with( 'sentrytest.foo', 30, sample_rate=1, tags=['instance:bar'], host=socket.gethostname(), ) ## Instruction: Remove no longer valid test ## Code After: from __future__ import absolute_import import socket from mock import patch from sentry.metrics.datadog import DatadogMetricsBackend from sentry.testutils import TestCase class DatadogMetricsBackendTest(TestCase): def setUp(self): self.backend = DatadogMetricsBackend(prefix='sentrytest.') @patch('datadog.threadstats.base.ThreadStats.increment') def test_incr(self, mock_incr): self.backend.incr('foo', instance='bar') mock_incr.assert_called_once_with( 'sentrytest.foo', 1, tags=['instance:bar'], host=socket.gethostname(), ) @patch('datadog.threadstats.base.ThreadStats.timing') def test_timing(self, mock_timing): self.backend.timing('foo', 30, instance='bar') mock_timing.assert_called_once_with( 'sentrytest.foo', 30, sample_rate=1, tags=['instance:bar'], host=socket.gethostname(), )
# ... existing code ... mock_incr.assert_called_once_with( 'sentrytest.foo', 1, tags=['instance:bar'], host=socket.gethostname(), # ... rest of the code ...
b6e9e37350a4b435df00a54b2ccd9da70a4db788
nogotofail/mitm/util/ip.py
nogotofail/mitm/util/ip.py
r''' Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' import subprocess import re def get_interface_addresses(): """Get all ip addresses assigned to interfaces. Returns a tuple of (v4 addresses, v6 addresses) """ try: output = subprocess.check_output("ifconfig") except subprocess.CalledProcessError: # Couldn't call ifconfig. Best guess it. return (["127.0.0.1"], []) # Parse out the results. v4 = re.findall("inet addr:([^ ]*)", output) v6 = re.findall("inet6 addr: ([^ ]*)", output) return v4, v6
r''' Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' import subprocess import re def get_interface_addresses(): """Get all ip addresses assigned to interfaces. Returns a tuple of (v4 addresses, v6 addresses) """ try: output = subprocess.check_output("ifconfig") except subprocess.CalledProcessError: # Couldn't call ifconfig. Best guess it. return (["127.0.0.1"], []) # Parse out the results. v4 = re.findall("inet (addr:)?([^ ]*)", output) v6 = re.findall("inet6 (addr: )?([^ ]*)", output) v4 = [e[1] for e in v4] v6 = [e[1] for e in v6] return v4, v6
Fix local interface addr parsing
Fix local interface addr parsing On Fedora 21 the format of ifconfig is a little different. Fixes #17
Python
apache-2.0
google/nogotofail,leasual/nogotofail,mkenne11/nogotofail,joshcooper/nogotofail,digideskio/nogotofail,mkenne11/nogotofail-pii,joshcooper/nogotofail,google/nogotofail,mkenne11/nogotofail,digideskio/nogotofail,leasual/nogotofail,mkenne11/nogotofail-pii
r''' Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' import subprocess import re def get_interface_addresses(): """Get all ip addresses assigned to interfaces. Returns a tuple of (v4 addresses, v6 addresses) """ try: output = subprocess.check_output("ifconfig") except subprocess.CalledProcessError: # Couldn't call ifconfig. Best guess it. return (["127.0.0.1"], []) # Parse out the results. - v4 = re.findall("inet addr:([^ ]*)", output) + v4 = re.findall("inet (addr:)?([^ ]*)", output) - v6 = re.findall("inet6 addr: ([^ ]*)", output) + v6 = re.findall("inet6 (addr: )?([^ ]*)", output) + v4 = [e[1] for e in v4] + v6 = [e[1] for e in v6] return v4, v6
Fix local interface addr parsing
## Code Before: r''' Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' import subprocess import re def get_interface_addresses(): """Get all ip addresses assigned to interfaces. Returns a tuple of (v4 addresses, v6 addresses) """ try: output = subprocess.check_output("ifconfig") except subprocess.CalledProcessError: # Couldn't call ifconfig. Best guess it. return (["127.0.0.1"], []) # Parse out the results. v4 = re.findall("inet addr:([^ ]*)", output) v6 = re.findall("inet6 addr: ([^ ]*)", output) return v4, v6 ## Instruction: Fix local interface addr parsing ## Code After: r''' Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' import subprocess import re def get_interface_addresses(): """Get all ip addresses assigned to interfaces. Returns a tuple of (v4 addresses, v6 addresses) """ try: output = subprocess.check_output("ifconfig") except subprocess.CalledProcessError: # Couldn't call ifconfig. Best guess it. return (["127.0.0.1"], []) # Parse out the results. v4 = re.findall("inet (addr:)?([^ ]*)", output) v6 = re.findall("inet6 (addr: )?([^ ]*)", output) v4 = [e[1] for e in v4] v6 = [e[1] for e in v6] return v4, v6
... return (["127.0.0.1"], []) # Parse out the results. v4 = re.findall("inet (addr:)?([^ ]*)", output) v6 = re.findall("inet6 (addr: )?([^ ]*)", output) v4 = [e[1] for e in v4] v6 = [e[1] for e in v6] return v4, v6 ...
0bbe6a915f8c289a9960f3cba9354955a19854f4
inpassing/pass_util.py
inpassing/pass_util.py
from sqlalchemy.sql import and_ from .models import Pass def query_user_passes(session, user_id, verified=None): if verified: # Only verified passes return session.query(Pass).filter( and_(Pass.owner_id == user_id, Pass.assigned_time != None) ).all() elif not verified: # Only non-verified passes return session.query(Pass).filter( and_(Pass.owner_id == user_id, Pass.assigned_time == None) ).all() else: # All passes return session.query(Pass).filter(Pass.owner_id == user_id).all() def query_org_passes(session, org_id, verified=None): if verified: # Only verified passes return session.query(Pass).filter( and_(Pass.org_id == org_id, Pass.assigned_time != None) ).all() elif not verified: # Only non-verified passes return session.query(Pass).filter( and_(Pass.org_id == org_id, Pass.assigned_time == None) ).all() else: # All passes return session.query(Pass).filter(Pass.org_id == org_id).all()
from sqlalchemy.sql import and_ from .models import Pass def query_user_passes(session, user_id, verified=None): if verified: # Only verified passes return session.query(Pass).filter( and_(Pass.owner_id == user_id, Pass.assigned_time != None) ).all() elif not verified and verified is not None: # Only non-verified passes return session.query(Pass).filter( and_(Pass.owner_id == user_id, Pass.assigned_time == None) ).all() else: # All passes return session.query(Pass).filter(Pass.owner_id == user_id).all() def query_org_passes(session, org_id, verified=None): if verified: # Only verified passes return session.query(Pass).filter( and_(Pass.org_id == org_id, Pass.assigned_time != None) ).all() elif not verified and verified is not None: # Only non-verified passes return session.query(Pass).filter( and_(Pass.org_id == org_id, Pass.assigned_time == None) ).all() else: # All passes return session.query(Pass).filter(Pass.org_id == org_id).all()
Fix bug in user pass code
Fix bug in user pass code The functions to query user and org passes return non-verified passes when verified=None, which was not intended.
Python
mit
lukesanantonio/inpassing-backend,lukesanantonio/inpassing-backend
from sqlalchemy.sql import and_ from .models import Pass def query_user_passes(session, user_id, verified=None): if verified: # Only verified passes return session.query(Pass).filter( and_(Pass.owner_id == user_id, Pass.assigned_time != None) ).all() - elif not verified: + elif not verified and verified is not None: # Only non-verified passes return session.query(Pass).filter( and_(Pass.owner_id == user_id, Pass.assigned_time == None) ).all() else: # All passes return session.query(Pass).filter(Pass.owner_id == user_id).all() def query_org_passes(session, org_id, verified=None): if verified: # Only verified passes return session.query(Pass).filter( and_(Pass.org_id == org_id, Pass.assigned_time != None) ).all() - elif not verified: + elif not verified and verified is not None: # Only non-verified passes return session.query(Pass).filter( and_(Pass.org_id == org_id, Pass.assigned_time == None) ).all() else: # All passes return session.query(Pass).filter(Pass.org_id == org_id).all()
Fix bug in user pass code
## Code Before: from sqlalchemy.sql import and_ from .models import Pass def query_user_passes(session, user_id, verified=None): if verified: # Only verified passes return session.query(Pass).filter( and_(Pass.owner_id == user_id, Pass.assigned_time != None) ).all() elif not verified: # Only non-verified passes return session.query(Pass).filter( and_(Pass.owner_id == user_id, Pass.assigned_time == None) ).all() else: # All passes return session.query(Pass).filter(Pass.owner_id == user_id).all() def query_org_passes(session, org_id, verified=None): if verified: # Only verified passes return session.query(Pass).filter( and_(Pass.org_id == org_id, Pass.assigned_time != None) ).all() elif not verified: # Only non-verified passes return session.query(Pass).filter( and_(Pass.org_id == org_id, Pass.assigned_time == None) ).all() else: # All passes return session.query(Pass).filter(Pass.org_id == org_id).all() ## Instruction: Fix bug in user pass code ## Code After: from sqlalchemy.sql import and_ from .models import Pass def query_user_passes(session, user_id, verified=None): if verified: # Only verified passes return session.query(Pass).filter( and_(Pass.owner_id == user_id, Pass.assigned_time != None) ).all() elif not verified and verified is not None: # Only non-verified passes return session.query(Pass).filter( and_(Pass.owner_id == user_id, Pass.assigned_time == None) ).all() else: # All passes return session.query(Pass).filter(Pass.owner_id == user_id).all() def query_org_passes(session, org_id, verified=None): if verified: # Only verified passes return session.query(Pass).filter( and_(Pass.org_id == org_id, Pass.assigned_time != None) ).all() elif not verified and verified is not None: # Only non-verified passes return session.query(Pass).filter( and_(Pass.org_id == org_id, Pass.assigned_time == None) ).all() else: # All passes return session.query(Pass).filter(Pass.org_id == org_id).all()
// ... existing code ... and_(Pass.owner_id == user_id, Pass.assigned_time != None) ).all() elif not verified and verified is not None: # Only non-verified passes return session.query(Pass).filter( // ... modified code ... and_(Pass.org_id == org_id, Pass.assigned_time != None) ).all() elif not verified and verified is not None: # Only non-verified passes return session.query(Pass).filter( // ... rest of the code ...
25494622a88f172fb14abf10eb5936246d475066
other/wrapping-cpp/swig/cpointerproblem/test_examples.py
other/wrapping-cpp/swig/cpointerproblem/test_examples.py
import os import pytest #print("pwd:") #os.system('pwd') #import subprocess #subprocess.check_output('pwd') os.system('make all') import example1 def test_f(): assert example1.f(1) - 1 <= 10 ** -7 def test_myfun(): """Demonstrate that calling code with wrong object type results in TypeError exception.""" with pytest.raises(TypeError): assert example1.myfun(example1.f, 2.0) - 4.0 <= 10 ** -7 os.system('make alternate') import example2 def test2_f(): assert example2.f(1) - 1 <= 10 ** -7 def test2_myfun(): assert example2.myfun(example2.f, 2.0) - 4.0 <= 10 ** -7 os.system('make clean')
import os import pytest # Need to call Makefile in directory where this test file is def call_make(target): # where is this file this_file = os.path.realpath(__file__) this_dir = os.path.split(this_file)[0] cd_command = "cd {}".format(this_dir) make_command = "make {}".format(target) command = '{}; {}'.format(cd_command, make_command) print("About to execute: '{}'".format(command)) os.system(command) call_make('all') import example1 def test_f(): assert example1.f(1) - 1 <= 10 ** -7 def test_myfun(): """Demonstrate that calling code with wrong object type results in TypeError exception.""" with pytest.raises(TypeError): assert example1.myfun(example1.f, 2.0) - 4.0 <= 10 ** -7 call_make('alternate') import example2 def test2_f(): assert example2.f(1) - 1 <= 10 ** -7 def test2_myfun(): assert example2.myfun(example2.f, 2.0) - 4.0 <= 10 ** -7 call_make('clean')
Modify testing code to work if executed from above its own directory
Modify testing code to work if executed from above its own directory
Python
bsd-2-clause
ryanpepper/oommf-python,ryanpepper/oommf-python,ryanpepper/oommf-python,fangohr/oommf-python,fangohr/oommf-python,fangohr/oommf-python,ryanpepper/oommf-python
import os import pytest - #print("pwd:") - #os.system('pwd') - #import subprocess - #subprocess.check_output('pwd') + + # Need to call Makefile in directory where this test file is + def call_make(target): + # where is this file + this_file = os.path.realpath(__file__) + this_dir = os.path.split(this_file)[0] + cd_command = "cd {}".format(this_dir) + make_command = "make {}".format(target) + command = '{}; {}'.format(cd_command, make_command) + print("About to execute: '{}'".format(command)) + os.system(command) - os.system('make all') + call_make('all') import example1 def test_f(): assert example1.f(1) - 1 <= 10 ** -7 def test_myfun(): """Demonstrate that calling code with wrong object type results in TypeError exception.""" with pytest.raises(TypeError): assert example1.myfun(example1.f, 2.0) - 4.0 <= 10 ** -7 - os.system('make alternate') + call_make('alternate') import example2 def test2_f(): assert example2.f(1) - 1 <= 10 ** -7 def test2_myfun(): assert example2.myfun(example2.f, 2.0) - 4.0 <= 10 ** -7 - os.system('make clean') + call_make('clean')
Modify testing code to work if executed from above its own directory
## Code Before: import os import pytest #print("pwd:") #os.system('pwd') #import subprocess #subprocess.check_output('pwd') os.system('make all') import example1 def test_f(): assert example1.f(1) - 1 <= 10 ** -7 def test_myfun(): """Demonstrate that calling code with wrong object type results in TypeError exception.""" with pytest.raises(TypeError): assert example1.myfun(example1.f, 2.0) - 4.0 <= 10 ** -7 os.system('make alternate') import example2 def test2_f(): assert example2.f(1) - 1 <= 10 ** -7 def test2_myfun(): assert example2.myfun(example2.f, 2.0) - 4.0 <= 10 ** -7 os.system('make clean') ## Instruction: Modify testing code to work if executed from above its own directory ## Code After: import os import pytest # Need to call Makefile in directory where this test file is def call_make(target): # where is this file this_file = os.path.realpath(__file__) this_dir = os.path.split(this_file)[0] cd_command = "cd {}".format(this_dir) make_command = "make {}".format(target) command = '{}; {}'.format(cd_command, make_command) print("About to execute: '{}'".format(command)) os.system(command) call_make('all') import example1 def test_f(): assert example1.f(1) - 1 <= 10 ** -7 def test_myfun(): """Demonstrate that calling code with wrong object type results in TypeError exception.""" with pytest.raises(TypeError): assert example1.myfun(example1.f, 2.0) - 4.0 <= 10 ** -7 call_make('alternate') import example2 def test2_f(): assert example2.f(1) - 1 <= 10 ** -7 def test2_myfun(): assert example2.myfun(example2.f, 2.0) - 4.0 <= 10 ** -7 call_make('clean')
... import pytest # Need to call Makefile in directory where this test file is def call_make(target): # where is this file this_file = os.path.realpath(__file__) this_dir = os.path.split(this_file)[0] cd_command = "cd {}".format(this_dir) make_command = "make {}".format(target) command = '{}; {}'.format(cd_command, make_command) print("About to execute: '{}'".format(command)) os.system(command) call_make('all') import example1 ... assert example1.myfun(example1.f, 2.0) - 4.0 <= 10 ** -7 call_make('alternate') import example2 ... assert example2.myfun(example2.f, 2.0) - 4.0 <= 10 ** -7 call_make('clean') ...
99952c977eee74ecc95a6af4b2867738850bc435
topoflow_utils/hook.py
topoflow_utils/hook.py
def get_dtype(parameter_value): """Get the TopoFlow data type of a parameter. Parameters ---------- parameter_value : object An object, a scalar. """ try: float(parameter_value) except ValueError: return 'string' else: return 'float' def assign_parameters(env, file_list): """Assign values for input parameters in a TopoFlow component. A subset of TopoFlow input parameters can take a scalar value, or, through an uploaded file, a time series, a grid, or a grid sequence. This function assigns such parameters a scalar value, or the name of a file, based on the user's selection in WMT. Parameters ---------- env : dict A dict of component parameter values from WMT. file_list : list A list of file names used by the component. """ terminator = '_ptype' for key in env.copy().iterkeys(): if key.endswith(terminator): key_root, sep, end = key.partition(terminator) if env[key] == 'Scalar': env[key_root] = env[key_root + '_scalar'] else: env[key_root] = env[key_root + '_file'] file_list.append(key_root) env[key_root + '_dtype'] = get_dtype(env[key_root])
"""Routines used by WMT hooks for TopoFlow components.""" choices_map = { 'Yes': 1, 'No': 0 } units_map = { 'meters': 'm^2', 'kilometers': 'km^2' } def get_dtype(parameter_value): """Get the TopoFlow data type of a parameter. Parameters ---------- parameter_value : object An object, a scalar. """ try: float(parameter_value) except ValueError: return 'string' else: return 'float' def assign_parameters(env, file_list): """Assign values for input parameters in a TopoFlow component. A subset of TopoFlow input parameters can take a scalar value, or, through an uploaded file, a time series, a grid, or a grid sequence. This function assigns such parameters a scalar value, or the name of a file, based on the user's selection in WMT. Parameters ---------- env : dict A dict of component parameter values from WMT. file_list : list A list of file names used by the component. """ terminator = '_ptype' for key in env.copy().iterkeys(): if key.endswith(terminator): key_root, sep, end = key.partition(terminator) if env[key] == 'Scalar': env[key_root] = env[key_root + '_scalar'] else: env[key_root] = env[key_root + '_file'] file_list.append(key_root) env[key_root + '_dtype'] = get_dtype(env[key_root])
Add choices_map and units_map global variables
Add choices_map and units_map global variables
Python
mit
csdms/topoflow-utils
+ """Routines used by WMT hooks for TopoFlow components.""" + + choices_map = { + 'Yes': 1, + 'No': 0 + } + units_map = { + 'meters': 'm^2', + 'kilometers': 'km^2' + } + + def get_dtype(parameter_value): """Get the TopoFlow data type of a parameter. Parameters ---------- parameter_value : object An object, a scalar. """ try: float(parameter_value) except ValueError: return 'string' else: return 'float' def assign_parameters(env, file_list): """Assign values for input parameters in a TopoFlow component. A subset of TopoFlow input parameters can take a scalar value, or, through an uploaded file, a time series, a grid, or a grid sequence. This function assigns such parameters a scalar value, or the name of a file, based on the user's selection in WMT. Parameters ---------- env : dict A dict of component parameter values from WMT. file_list : list A list of file names used by the component. """ terminator = '_ptype' for key in env.copy().iterkeys(): if key.endswith(terminator): key_root, sep, end = key.partition(terminator) if env[key] == 'Scalar': env[key_root] = env[key_root + '_scalar'] else: env[key_root] = env[key_root + '_file'] file_list.append(key_root) env[key_root + '_dtype'] = get_dtype(env[key_root])
Add choices_map and units_map global variables
## Code Before: def get_dtype(parameter_value): """Get the TopoFlow data type of a parameter. Parameters ---------- parameter_value : object An object, a scalar. """ try: float(parameter_value) except ValueError: return 'string' else: return 'float' def assign_parameters(env, file_list): """Assign values for input parameters in a TopoFlow component. A subset of TopoFlow input parameters can take a scalar value, or, through an uploaded file, a time series, a grid, or a grid sequence. This function assigns such parameters a scalar value, or the name of a file, based on the user's selection in WMT. Parameters ---------- env : dict A dict of component parameter values from WMT. file_list : list A list of file names used by the component. """ terminator = '_ptype' for key in env.copy().iterkeys(): if key.endswith(terminator): key_root, sep, end = key.partition(terminator) if env[key] == 'Scalar': env[key_root] = env[key_root + '_scalar'] else: env[key_root] = env[key_root + '_file'] file_list.append(key_root) env[key_root + '_dtype'] = get_dtype(env[key_root]) ## Instruction: Add choices_map and units_map global variables ## Code After: """Routines used by WMT hooks for TopoFlow components.""" choices_map = { 'Yes': 1, 'No': 0 } units_map = { 'meters': 'm^2', 'kilometers': 'km^2' } def get_dtype(parameter_value): """Get the TopoFlow data type of a parameter. Parameters ---------- parameter_value : object An object, a scalar. """ try: float(parameter_value) except ValueError: return 'string' else: return 'float' def assign_parameters(env, file_list): """Assign values for input parameters in a TopoFlow component. A subset of TopoFlow input parameters can take a scalar value, or, through an uploaded file, a time series, a grid, or a grid sequence. This function assigns such parameters a scalar value, or the name of a file, based on the user's selection in WMT. Parameters ---------- env : dict A dict of component parameter values from WMT. file_list : list A list of file names used by the component. """ terminator = '_ptype' for key in env.copy().iterkeys(): if key.endswith(terminator): key_root, sep, end = key.partition(terminator) if env[key] == 'Scalar': env[key_root] = env[key_root + '_scalar'] else: env[key_root] = env[key_root + '_file'] file_list.append(key_root) env[key_root + '_dtype'] = get_dtype(env[key_root])
// ... existing code ... """Routines used by WMT hooks for TopoFlow components.""" choices_map = { 'Yes': 1, 'No': 0 } units_map = { 'meters': 'm^2', 'kilometers': 'km^2' } def get_dtype(parameter_value): """Get the TopoFlow data type of a parameter. // ... rest of the code ...
32b51cb7d63d9d122c0d678a46d56a735a9bea3e
dodo_commands/framework/decorator_scope.py
dodo_commands/framework/decorator_scope.py
from dodo_commands.framework.singleton import Dodo # Resp: add the current command_name # to the list of commands decorated by decorator_name. class DecoratorScope: def __init__(self, decorator_name): self.decorators = Dodo.get_config('/ROOT').setdefault( 'decorators', {}).setdefault(decorator_name, []) def __enter__(self): # noqa self.decorators.append(Dodo.command_name) def __exit__(self, type, value, traceback): # noqa self.decorators.remove(Dodo.command_name)
from dodo_commands.framework.singleton import Dodo # Resp: add the current command_name # to the list of commands decorated by decorator_name. class DecoratorScope: def __init__(self, decorator_name, remove=False): self.decorators = Dodo.get_config('/ROOT').setdefault( 'decorators', {}).setdefault(decorator_name, []) self.prefix = "!" if remove else "" def __enter__(self): # noqa self.decorators.append(self.prefix + Dodo.command_name) def __exit__(self, type, value, traceback): # noqa self.decorators.remove(self.prefix + Dodo.command_name)
Add ``remove`` flag to DecoratorScope
Add ``remove`` flag to DecoratorScope
Python
mit
mnieber/dodo_commands
from dodo_commands.framework.singleton import Dodo # Resp: add the current command_name # to the list of commands decorated by decorator_name. class DecoratorScope: - def __init__(self, decorator_name): + def __init__(self, decorator_name, remove=False): self.decorators = Dodo.get_config('/ROOT').setdefault( 'decorators', {}).setdefault(decorator_name, []) + self.prefix = "!" if remove else "" def __enter__(self): # noqa - self.decorators.append(Dodo.command_name) + self.decorators.append(self.prefix + Dodo.command_name) def __exit__(self, type, value, traceback): # noqa - self.decorators.remove(Dodo.command_name) + self.decorators.remove(self.prefix + Dodo.command_name)
Add ``remove`` flag to DecoratorScope
## Code Before: from dodo_commands.framework.singleton import Dodo # Resp: add the current command_name # to the list of commands decorated by decorator_name. class DecoratorScope: def __init__(self, decorator_name): self.decorators = Dodo.get_config('/ROOT').setdefault( 'decorators', {}).setdefault(decorator_name, []) def __enter__(self): # noqa self.decorators.append(Dodo.command_name) def __exit__(self, type, value, traceback): # noqa self.decorators.remove(Dodo.command_name) ## Instruction: Add ``remove`` flag to DecoratorScope ## Code After: from dodo_commands.framework.singleton import Dodo # Resp: add the current command_name # to the list of commands decorated by decorator_name. class DecoratorScope: def __init__(self, decorator_name, remove=False): self.decorators = Dodo.get_config('/ROOT').setdefault( 'decorators', {}).setdefault(decorator_name, []) self.prefix = "!" if remove else "" def __enter__(self): # noqa self.decorators.append(self.prefix + Dodo.command_name) def __exit__(self, type, value, traceback): # noqa self.decorators.remove(self.prefix + Dodo.command_name)
... # to the list of commands decorated by decorator_name. class DecoratorScope: def __init__(self, decorator_name, remove=False): self.decorators = Dodo.get_config('/ROOT').setdefault( 'decorators', {}).setdefault(decorator_name, []) self.prefix = "!" if remove else "" def __enter__(self): # noqa self.decorators.append(self.prefix + Dodo.command_name) def __exit__(self, type, value, traceback): # noqa self.decorators.remove(self.prefix + Dodo.command_name) ...
c4eef5919fa60c87b59d60c1bd005f97183ce057
aiozk/test/test_connection.py
aiozk/test/test_connection.py
from unittest import mock import pytest import aiozk.connection @pytest.fixture def connection(event_loop): connection = aiozk.connection.Connection( host='zookeeper.test', port=2181, watch_handler=mock.MagicMock(), read_timeout=30, loop=mock.MagicMock(wraps=event_loop)) connection.writer = mock.MagicMock() return connection @pytest.mark.asyncio async def test_close_connection_in_state_closing_do_not_performs_abort(connection): connection.abort = mock.AsyncMock() connection.closing = True await connection.close(mock.ANY) connection.abort.assert_not_awaited() @pytest.mark.asyncio async def test_close_cancels_read_loop_task(connection): connection.start_read_loop() connection.read_response = mock.AsyncMock(return_value=(0, mock.ANY, mock.ANY)) task_cancelled_future = connection.loop.create_future() def set_result(task): task_cancelled_future.set_result(task.cancelled()) connection.read_loop_task.add_done_callback(set_result) await connection.close(mock.ANY) assert await task_cancelled_future
from unittest import mock import pytest import aiozk.connection @pytest.fixture def connection(event_loop): connection = aiozk.connection.Connection( host='zookeeper.test', port=2181, watch_handler=mock.MagicMock(), read_timeout=30, loop=event_loop) connection.writer = mock.MagicMock() return connection @pytest.mark.asyncio async def test_close_connection_in_state_closing_do_not_performs_abort(connection): connection.abort = mock.AsyncMock() connection.closing = True await connection.close(0.1) connection.abort.assert_not_awaited() @pytest.mark.asyncio async def test_close_cancels_read_loop_task(connection): connection.read_loop_task = connection.loop.create_future() connection.read_loop_task.done = mock.MagicMock(return_value=False) connection.read_loop_task.cancel = mock.MagicMock( wraps=connection.read_loop_task.cancel) await connection.close(0.1) connection.read_loop_task.cancel.assert_called_once() @pytest.mark.asyncio async def test_connection_abort(connection): connection.pending_count = mock.MagicMock(return_value=1) connection.abort = mock.MagicMock() await connection.close(0.1) connection.abort.assert_called_once()
Modify and add tests for the revised connection.close
Modify and add tests for the revised connection.close
Python
mit
tipsi/aiozk,tipsi/aiozk
from unittest import mock import pytest import aiozk.connection @pytest.fixture def connection(event_loop): connection = aiozk.connection.Connection( host='zookeeper.test', port=2181, watch_handler=mock.MagicMock(), read_timeout=30, - loop=mock.MagicMock(wraps=event_loop)) + loop=event_loop) connection.writer = mock.MagicMock() return connection @pytest.mark.asyncio async def test_close_connection_in_state_closing_do_not_performs_abort(connection): connection.abort = mock.AsyncMock() connection.closing = True - await connection.close(mock.ANY) + await connection.close(0.1) connection.abort.assert_not_awaited() @pytest.mark.asyncio async def test_close_cancels_read_loop_task(connection): - connection.start_read_loop() - connection.read_response = mock.AsyncMock(return_value=(0, mock.ANY, mock.ANY)) + connection.read_loop_task = connection.loop.create_future() + connection.read_loop_task.done = mock.MagicMock(return_value=False) + connection.read_loop_task.cancel = mock.MagicMock( + wraps=connection.read_loop_task.cancel) + await connection.close(0.1) + connection.read_loop_task.cancel.assert_called_once() - task_cancelled_future = connection.loop.create_future() - def set_result(task): - task_cancelled_future.set_result(task.cancelled()) + @pytest.mark.asyncio + async def test_connection_abort(connection): + connection.pending_count = mock.MagicMock(return_value=1) + connection.abort = mock.MagicMock() + await connection.close(0.1) + connection.abort.assert_called_once() - connection.read_loop_task.add_done_callback(set_result) - - await connection.close(mock.ANY) - assert await task_cancelled_future -
Modify and add tests for the revised connection.close
## Code Before: from unittest import mock import pytest import aiozk.connection @pytest.fixture def connection(event_loop): connection = aiozk.connection.Connection( host='zookeeper.test', port=2181, watch_handler=mock.MagicMock(), read_timeout=30, loop=mock.MagicMock(wraps=event_loop)) connection.writer = mock.MagicMock() return connection @pytest.mark.asyncio async def test_close_connection_in_state_closing_do_not_performs_abort(connection): connection.abort = mock.AsyncMock() connection.closing = True await connection.close(mock.ANY) connection.abort.assert_not_awaited() @pytest.mark.asyncio async def test_close_cancels_read_loop_task(connection): connection.start_read_loop() connection.read_response = mock.AsyncMock(return_value=(0, mock.ANY, mock.ANY)) task_cancelled_future = connection.loop.create_future() def set_result(task): task_cancelled_future.set_result(task.cancelled()) connection.read_loop_task.add_done_callback(set_result) await connection.close(mock.ANY) assert await task_cancelled_future ## Instruction: Modify and add tests for the revised connection.close ## Code After: from unittest import mock import pytest import aiozk.connection @pytest.fixture def connection(event_loop): connection = aiozk.connection.Connection( host='zookeeper.test', port=2181, watch_handler=mock.MagicMock(), read_timeout=30, loop=event_loop) connection.writer = mock.MagicMock() return connection @pytest.mark.asyncio async def test_close_connection_in_state_closing_do_not_performs_abort(connection): connection.abort = mock.AsyncMock() connection.closing = True await connection.close(0.1) connection.abort.assert_not_awaited() @pytest.mark.asyncio async def test_close_cancels_read_loop_task(connection): connection.read_loop_task = connection.loop.create_future() connection.read_loop_task.done = mock.MagicMock(return_value=False) connection.read_loop_task.cancel = mock.MagicMock( wraps=connection.read_loop_task.cancel) await connection.close(0.1) connection.read_loop_task.cancel.assert_called_once() @pytest.mark.asyncio async def test_connection_abort(connection): connection.pending_count = mock.MagicMock(return_value=1) connection.abort = mock.MagicMock() await connection.close(0.1) connection.abort.assert_called_once()
# ... existing code ... watch_handler=mock.MagicMock(), read_timeout=30, loop=event_loop) connection.writer = mock.MagicMock() # ... modified code ... connection.closing = True await connection.close(0.1) connection.abort.assert_not_awaited() ... @pytest.mark.asyncio async def test_close_cancels_read_loop_task(connection): connection.read_loop_task = connection.loop.create_future() connection.read_loop_task.done = mock.MagicMock(return_value=False) connection.read_loop_task.cancel = mock.MagicMock( wraps=connection.read_loop_task.cancel) await connection.close(0.1) connection.read_loop_task.cancel.assert_called_once() @pytest.mark.asyncio async def test_connection_abort(connection): connection.pending_count = mock.MagicMock(return_value=1) connection.abort = mock.MagicMock() await connection.close(0.1) connection.abort.assert_called_once() # ... rest of the code ...
1fd2299b2a0c993bd463ab88c0a7544ade2c945b
test_kasp/disk/test_disk.py
test_kasp/disk/test_disk.py
import pytest from utils.disk_utils import DiskIO class TestDisk: def __init__(self): self.WRITE_MB = 128 self.WRITE_BLOCK_KB = 1024 self.READ_BLOCK_B = 512 @staticmethod def all_free_disk_space_gb(): return reduce(lambda res, x: res+x[1], DiskIO().disks, 0) @pytest.mark.disk @pytest.mark.storage def test_disk_space_storage(self): assert self.all_free_disk_space_gb() > 3000
import pytest from utils.disk_utils import DiskIO class TestDisk: @staticmethod def all_free_disk_space_gb(): return reduce(lambda res, x: res+x[1], DiskIO().disks, 0) @pytest.mark.disk @pytest.mark.storage def test_disk_space_storage(self): assert self.all_free_disk_space_gb() > 3000
Remove init mrthod from disk test
Remove init mrthod from disk test Removed init method from test class for disk test
Python
apache-2.0
vrovachev/kaspersky-framework
import pytest from utils.disk_utils import DiskIO class TestDisk: - - def __init__(self): - self.WRITE_MB = 128 - self.WRITE_BLOCK_KB = 1024 - self.READ_BLOCK_B = 512 @staticmethod def all_free_disk_space_gb(): return reduce(lambda res, x: res+x[1], DiskIO().disks, 0) @pytest.mark.disk @pytest.mark.storage def test_disk_space_storage(self): assert self.all_free_disk_space_gb() > 3000
Remove init mrthod from disk test
## Code Before: import pytest from utils.disk_utils import DiskIO class TestDisk: def __init__(self): self.WRITE_MB = 128 self.WRITE_BLOCK_KB = 1024 self.READ_BLOCK_B = 512 @staticmethod def all_free_disk_space_gb(): return reduce(lambda res, x: res+x[1], DiskIO().disks, 0) @pytest.mark.disk @pytest.mark.storage def test_disk_space_storage(self): assert self.all_free_disk_space_gb() > 3000 ## Instruction: Remove init mrthod from disk test ## Code After: import pytest from utils.disk_utils import DiskIO class TestDisk: @staticmethod def all_free_disk_space_gb(): return reduce(lambda res, x: res+x[1], DiskIO().disks, 0) @pytest.mark.disk @pytest.mark.storage def test_disk_space_storage(self): assert self.all_free_disk_space_gb() > 3000
# ... existing code ... class TestDisk: @staticmethod # ... rest of the code ...
003034caa0072d3e13b997df219b6612ae4b128e
setup.py
setup.py
from distutils.core import setup version = "0.1.1" setup(name="riemann-sumd", version=version, description="Python agent for scheduling event generating processes and sending the results to Riemann", author="Brian Hatfield", author_email="[email protected]", url="https://github.com/bmhatfield/riemann-sumd", package_dir={'': 'lib'}, py_modules=['event', 'loader', 'scheduler', 'sender', 'task'], data_files=[('/etc/init/', ["init/ubuntu/sumd.conf"]), ('/etc/sumd', ['examples/etc/sumd/sumd.conf']), ('/etc/sumd/tasks.d', ['examples/etc/sumd/tasks.d/simple.task.example']), ('/etc/sumd/tags.d', ['examples/etc/sumd/tags.d/simple.tag.example'])], scripts=["bin/sumd"] )
from distutils.core import setup version = "0.2.0" setup(name="riemann-sumd", version=version, description="Python agent for scheduling event generating processes and sending the results to Riemann", author="Brian Hatfield", author_email="[email protected]", url="https://github.com/bmhatfield/riemann-sumd", package_dir={'': 'lib'}, py_modules=['event', 'loader', 'scheduler', 'sender', 'task'], data_files=[('/etc/init/', ["init/ubuntu/sumd.conf"]), ('/etc/sumd', ['examples/etc/sumd/sumd.conf']), ('/etc/sumd/tasks.d', ['examples/etc/sumd/tasks.d/simple.task.example']), ('/etc/sumd/tags.d', ['examples/etc/sumd/tags.d/simple.tag.example'])], scripts=["bin/sumd"], install_requires=[ "pyyaml", "python-daemon", "bernhard>=0.0.5", "requests" ] )
Update Riemann-sumd version, add install_requires
Update Riemann-sumd version, add install_requires
Python
mit
crashlytics/riemann-sumd
from distutils.core import setup - version = "0.1.1" + version = "0.2.0" setup(name="riemann-sumd", version=version, description="Python agent for scheduling event generating processes and sending the results to Riemann", author="Brian Hatfield", author_email="[email protected]", url="https://github.com/bmhatfield/riemann-sumd", package_dir={'': 'lib'}, py_modules=['event', 'loader', 'scheduler', 'sender', 'task'], data_files=[('/etc/init/', ["init/ubuntu/sumd.conf"]), ('/etc/sumd', ['examples/etc/sumd/sumd.conf']), ('/etc/sumd/tasks.d', ['examples/etc/sumd/tasks.d/simple.task.example']), ('/etc/sumd/tags.d', ['examples/etc/sumd/tags.d/simple.tag.example'])], - scripts=["bin/sumd"] + scripts=["bin/sumd"], - ) + install_requires=[ + "pyyaml", + "python-daemon", + "bernhard>=0.0.5", + "requests" + ] + ) +
Update Riemann-sumd version, add install_requires
## Code Before: from distutils.core import setup version = "0.1.1" setup(name="riemann-sumd", version=version, description="Python agent for scheduling event generating processes and sending the results to Riemann", author="Brian Hatfield", author_email="[email protected]", url="https://github.com/bmhatfield/riemann-sumd", package_dir={'': 'lib'}, py_modules=['event', 'loader', 'scheduler', 'sender', 'task'], data_files=[('/etc/init/', ["init/ubuntu/sumd.conf"]), ('/etc/sumd', ['examples/etc/sumd/sumd.conf']), ('/etc/sumd/tasks.d', ['examples/etc/sumd/tasks.d/simple.task.example']), ('/etc/sumd/tags.d', ['examples/etc/sumd/tags.d/simple.tag.example'])], scripts=["bin/sumd"] ) ## Instruction: Update Riemann-sumd version, add install_requires ## Code After: from distutils.core import setup version = "0.2.0" setup(name="riemann-sumd", version=version, description="Python agent for scheduling event generating processes and sending the results to Riemann", author="Brian Hatfield", author_email="[email protected]", url="https://github.com/bmhatfield/riemann-sumd", package_dir={'': 'lib'}, py_modules=['event', 'loader', 'scheduler', 'sender', 'task'], data_files=[('/etc/init/', ["init/ubuntu/sumd.conf"]), ('/etc/sumd', ['examples/etc/sumd/sumd.conf']), ('/etc/sumd/tasks.d', ['examples/etc/sumd/tasks.d/simple.task.example']), ('/etc/sumd/tags.d', ['examples/etc/sumd/tags.d/simple.tag.example'])], scripts=["bin/sumd"], install_requires=[ "pyyaml", "python-daemon", "bernhard>=0.0.5", "requests" ] )
... from distutils.core import setup version = "0.2.0" setup(name="riemann-sumd", ... ('/etc/sumd/tasks.d', ['examples/etc/sumd/tasks.d/simple.task.example']), ('/etc/sumd/tags.d', ['examples/etc/sumd/tags.d/simple.tag.example'])], scripts=["bin/sumd"], install_requires=[ "pyyaml", "python-daemon", "bernhard>=0.0.5", "requests" ] ) ...
b6dea08a0a9908d2303693cf4534c7b0beec4154
analyticpi/db.py
analyticpi/db.py
import os import peewee APP_DIR = os.path.dirname(__file__) try: import urlparse import psycopg2 urlparse.uses_netloc.append('postgres') url = urlparse.urlparse(os.environ["DATABASE_URL"]) database = peewee.PostgresqlDatabase(database=url.path[1:], user=url.username, password=url.password, host=url.hostname, port=url.port) except KeyError: database = peewee.MySQLDatabase(os.environ["MYSQL_DATABASE"], os.environ["MYSQL_HOST"], user=os.environ["MYSQL_USER"], passwd=os.environ["MYSQL_PASSWD"])
import os import peewee APP_DIR = os.path.dirname(__file__) try: import urlparse import psycopg2 urlparse.uses_netloc.append('postgres') url = urlparse.urlparse(os.environ["DATABASE_URL"]) database = peewee.PostgresqlDatabase(database=url.path[1:], user=url.username, password=url.password, host=url.hostname, port=url.port) except KeyError: database = peewee.SqliteDatabase('my_app.db')
Change from MySQL to SQLite3
Change from MySQL to SQLite3
Python
mit
analyticpi/analyticpi,analyticpi/analyticpi,analyticpi/analyticpi
import os import peewee APP_DIR = os.path.dirname(__file__) try: import urlparse import psycopg2 urlparse.uses_netloc.append('postgres') url = urlparse.urlparse(os.environ["DATABASE_URL"]) database = peewee.PostgresqlDatabase(database=url.path[1:], user=url.username, password=url.password, host=url.hostname, port=url.port) except KeyError: + database = peewee.SqliteDatabase('my_app.db') - database = peewee.MySQLDatabase(os.environ["MYSQL_DATABASE"], - os.environ["MYSQL_HOST"], - user=os.environ["MYSQL_USER"], - passwd=os.environ["MYSQL_PASSWD"])
Change from MySQL to SQLite3
## Code Before: import os import peewee APP_DIR = os.path.dirname(__file__) try: import urlparse import psycopg2 urlparse.uses_netloc.append('postgres') url = urlparse.urlparse(os.environ["DATABASE_URL"]) database = peewee.PostgresqlDatabase(database=url.path[1:], user=url.username, password=url.password, host=url.hostname, port=url.port) except KeyError: database = peewee.MySQLDatabase(os.environ["MYSQL_DATABASE"], os.environ["MYSQL_HOST"], user=os.environ["MYSQL_USER"], passwd=os.environ["MYSQL_PASSWD"]) ## Instruction: Change from MySQL to SQLite3 ## Code After: import os import peewee APP_DIR = os.path.dirname(__file__) try: import urlparse import psycopg2 urlparse.uses_netloc.append('postgres') url = urlparse.urlparse(os.environ["DATABASE_URL"]) database = peewee.PostgresqlDatabase(database=url.path[1:], user=url.username, password=url.password, host=url.hostname, port=url.port) except KeyError: database = peewee.SqliteDatabase('my_app.db')
// ... existing code ... port=url.port) except KeyError: database = peewee.SqliteDatabase('my_app.db') // ... rest of the code ...
a52bd5acd50d37314247e4ffaed501ba08e0eca3
tests/test_simple_model.py
tests/test_simple_model.py
"""Tests for creating a simple tight-binding model.""" import pytest from parameters import T_VALUES, KPT @pytest.mark.parametrize('t1', T_VALUES) @pytest.mark.parametrize('k', KPT) def test_simple(t1, get_model, k, compare_data, models_equal, compare_isclose): """Regression test for a simple manually created tight-binding model.""" model = get_model(*t1) compare_isclose(model.hamilton(k), tag='hamilton') compare_isclose(model.eigenval(k), tag='eigenval') compare_data(models_equal, model) @pytest.mark.parametrize('t1', T_VALUES) def test_invalid_dim(t1, get_model): """ Check that an error is raised when the dimension does not match the hopping matrix keys. """ with pytest.raises(ValueError): get_model(*t1, dim=2)
"""Tests for creating a simple tight-binding model.""" import pytest from parameters import T_VALUES, KPT @pytest.mark.parametrize('t1', T_VALUES) @pytest.mark.parametrize('k', KPT) def test_simple(t1, get_model, k, compare_data, models_equal, compare_isclose): """Regression test for a simple manually created tight-binding model.""" model = get_model(*t1) compare_isclose(model.hamilton(k), tag='hamilton') compare_isclose(model.eigenval(k), tag='eigenval') compare_data(models_equal, model) def test_invalid_dim(get_model): """ Check that an error is raised when the reciprocal lattice vector does not match the dimension. """ model = get_model(0.1, 0.2) model.add_hop(1j, 0, 1, (0, 1, 2)) with pytest.raises(ValueError): model.add_hop(1j, 0, 1, (0, 1))
Fix test broken by previous commit.
Fix test broken by previous commit.
Python
apache-2.0
Z2PackDev/TBmodels,Z2PackDev/TBmodels
"""Tests for creating a simple tight-binding model.""" import pytest from parameters import T_VALUES, KPT @pytest.mark.parametrize('t1', T_VALUES) @pytest.mark.parametrize('k', KPT) def test_simple(t1, get_model, k, compare_data, models_equal, compare_isclose): """Regression test for a simple manually created tight-binding model.""" model = get_model(*t1) compare_isclose(model.hamilton(k), tag='hamilton') compare_isclose(model.eigenval(k), tag='eigenval') compare_data(models_equal, model) - @pytest.mark.parametrize('t1', T_VALUES) - def test_invalid_dim(t1, get_model): + def test_invalid_dim(get_model): """ - Check that an error is raised when the dimension does not match - the hopping matrix keys. + Check that an error is raised when the reciprocal lattice vector + does not match the dimension. """ + model = get_model(0.1, 0.2) + model.add_hop(1j, 0, 1, (0, 1, 2)) with pytest.raises(ValueError): - get_model(*t1, dim=2) + model.add_hop(1j, 0, 1, (0, 1))
Fix test broken by previous commit.
## Code Before: """Tests for creating a simple tight-binding model.""" import pytest from parameters import T_VALUES, KPT @pytest.mark.parametrize('t1', T_VALUES) @pytest.mark.parametrize('k', KPT) def test_simple(t1, get_model, k, compare_data, models_equal, compare_isclose): """Regression test for a simple manually created tight-binding model.""" model = get_model(*t1) compare_isclose(model.hamilton(k), tag='hamilton') compare_isclose(model.eigenval(k), tag='eigenval') compare_data(models_equal, model) @pytest.mark.parametrize('t1', T_VALUES) def test_invalid_dim(t1, get_model): """ Check that an error is raised when the dimension does not match the hopping matrix keys. """ with pytest.raises(ValueError): get_model(*t1, dim=2) ## Instruction: Fix test broken by previous commit. ## Code After: """Tests for creating a simple tight-binding model.""" import pytest from parameters import T_VALUES, KPT @pytest.mark.parametrize('t1', T_VALUES) @pytest.mark.parametrize('k', KPT) def test_simple(t1, get_model, k, compare_data, models_equal, compare_isclose): """Regression test for a simple manually created tight-binding model.""" model = get_model(*t1) compare_isclose(model.hamilton(k), tag='hamilton') compare_isclose(model.eigenval(k), tag='eigenval') compare_data(models_equal, model) def test_invalid_dim(get_model): """ Check that an error is raised when the reciprocal lattice vector does not match the dimension. """ model = get_model(0.1, 0.2) model.add_hop(1j, 0, 1, (0, 1, 2)) with pytest.raises(ValueError): model.add_hop(1j, 0, 1, (0, 1))
... def test_invalid_dim(get_model): """ Check that an error is raised when the reciprocal lattice vector does not match the dimension. """ model = get_model(0.1, 0.2) model.add_hop(1j, 0, 1, (0, 1, 2)) with pytest.raises(ValueError): model.add_hop(1j, 0, 1, (0, 1)) ...
00a497b21b9c788cb38da6c92a985e1b5c22801a
apps/survey/urls.py
apps/survey/urls.py
from django.conf.urls.defaults import * from . import views urlpatterns = patterns('', url(r'^profile/$', views.profile_index, name='survey_profile'), url(r'^profile/electric/$', views.profile_electric, name='survey_profile_electric'), #url(r'^profile/intake/$', views.survey_intake, name='survey_profile_intake'), url(r'^profile/surveys/$', views.survey_management, name='survey_management'), url(r'^main/$', views.main_index), url(r'^survey_management/$', views.survey_management, name='survey_management'), #url(r'^survey_data/(?P<survey_shortname>.+)/(?P<id>\d+)/$', views.survey_data, name='survey_data'), url(r'^intake/$', views.survey_data, name='survey_data'), url(r'^monthly/(?P<id>\d+)/$', views.survey_data_monthly ,name='survey_data_monthly'), url(r'^thanks_profile/$', views.thanks_profile, name='profile_thanks'), #url(r'^select/$', views.select_user, name='survey_select_user'), url(r'^$', views.index, name='survey_index'), )
from django.conf.urls.defaults import * from . import views urlpatterns = patterns('', url(r'^profile/$', views.profile_index, name='survey_profile'), url(r'^profile/electric/$', views.profile_electric, name='survey_profile_electric'), url(r'^profile/surveys/$', views.survey_management, name='survey_management'), url(r'^main/$', views.main_index), url(r'^survey_management/$', views.survey_management, name='survey_management'), url(r'^intake/view/$', views.survey_intake_view, name='survey_intake_view'), url(r'^intake/update/$', views.survey_intake_update, name='survey_intake_update'), url(r'^monthly/(?P<id>\d+)/$', views.survey_monthly ,name='survey_monthly'), url(r'^monthly/(?P<id>\d+)/update/$', views.survey_monthly_update ,name='survey_monthly_update'), url(r'^thanks_profile/$', views.thanks_profile, name='profile_thanks'), #url(r'^select/$', views.select_user, name='survey_select_user'), url(r'^$', views.index, name='survey_index'), )
Add view and update decorators
Add view and update decorators
Python
agpl-3.0
chispita/epiwork,chispita/epiwork,chispita/epiwork,chispita/epiwork,chispita/epiwork,chispita/epiwork,chispita/epiwork
from django.conf.urls.defaults import * from . import views urlpatterns = patterns('', url(r'^profile/$', views.profile_index, name='survey_profile'), url(r'^profile/electric/$', views.profile_electric, name='survey_profile_electric'), - #url(r'^profile/intake/$', views.survey_intake, name='survey_profile_intake'), url(r'^profile/surveys/$', views.survey_management, name='survey_management'), url(r'^main/$', views.main_index), url(r'^survey_management/$', views.survey_management, name='survey_management'), - #url(r'^survey_data/(?P<survey_shortname>.+)/(?P<id>\d+)/$', views.survey_data, name='survey_data'), - - url(r'^intake/$', views.survey_data, name='survey_data'), + + url(r'^intake/view/$', views.survey_intake_view, name='survey_intake_view'), + url(r'^intake/update/$', views.survey_intake_update, name='survey_intake_update'), + - url(r'^monthly/(?P<id>\d+)/$', views.survey_data_monthly ,name='survey_data_monthly'), + url(r'^monthly/(?P<id>\d+)/$', views.survey_monthly ,name='survey_monthly'), - + url(r'^monthly/(?P<id>\d+)/update/$', views.survey_monthly_update ,name='survey_monthly_update'), url(r'^thanks_profile/$', views.thanks_profile, name='profile_thanks'), #url(r'^select/$', views.select_user, name='survey_select_user'), url(r'^$', views.index, name='survey_index'), )
Add view and update decorators
## Code Before: from django.conf.urls.defaults import * from . import views urlpatterns = patterns('', url(r'^profile/$', views.profile_index, name='survey_profile'), url(r'^profile/electric/$', views.profile_electric, name='survey_profile_electric'), #url(r'^profile/intake/$', views.survey_intake, name='survey_profile_intake'), url(r'^profile/surveys/$', views.survey_management, name='survey_management'), url(r'^main/$', views.main_index), url(r'^survey_management/$', views.survey_management, name='survey_management'), #url(r'^survey_data/(?P<survey_shortname>.+)/(?P<id>\d+)/$', views.survey_data, name='survey_data'), url(r'^intake/$', views.survey_data, name='survey_data'), url(r'^monthly/(?P<id>\d+)/$', views.survey_data_monthly ,name='survey_data_monthly'), url(r'^thanks_profile/$', views.thanks_profile, name='profile_thanks'), #url(r'^select/$', views.select_user, name='survey_select_user'), url(r'^$', views.index, name='survey_index'), ) ## Instruction: Add view and update decorators ## Code After: from django.conf.urls.defaults import * from . import views urlpatterns = patterns('', url(r'^profile/$', views.profile_index, name='survey_profile'), url(r'^profile/electric/$', views.profile_electric, name='survey_profile_electric'), url(r'^profile/surveys/$', views.survey_management, name='survey_management'), url(r'^main/$', views.main_index), url(r'^survey_management/$', views.survey_management, name='survey_management'), url(r'^intake/view/$', views.survey_intake_view, name='survey_intake_view'), url(r'^intake/update/$', views.survey_intake_update, name='survey_intake_update'), url(r'^monthly/(?P<id>\d+)/$', views.survey_monthly ,name='survey_monthly'), url(r'^monthly/(?P<id>\d+)/update/$', views.survey_monthly_update ,name='survey_monthly_update'), url(r'^thanks_profile/$', views.thanks_profile, name='profile_thanks'), #url(r'^select/$', views.select_user, name='survey_select_user'), url(r'^$', views.index, name='survey_index'), )
// ... existing code ... url(r'^profile/$', views.profile_index, name='survey_profile'), url(r'^profile/electric/$', views.profile_electric, name='survey_profile_electric'), url(r'^profile/surveys/$', views.survey_management, name='survey_management'), url(r'^main/$', views.main_index), url(r'^survey_management/$', views.survey_management, name='survey_management'), url(r'^intake/view/$', views.survey_intake_view, name='survey_intake_view'), url(r'^intake/update/$', views.survey_intake_update, name='survey_intake_update'), url(r'^monthly/(?P<id>\d+)/$', views.survey_monthly ,name='survey_monthly'), url(r'^monthly/(?P<id>\d+)/update/$', views.survey_monthly_update ,name='survey_monthly_update'), url(r'^thanks_profile/$', views.thanks_profile, name='profile_thanks'), // ... rest of the code ...
a2713927beb4b80ba62cc0273df24d33cca4a689
namuhub/__init__.py
namuhub/__init__.py
"""namuhub --- namu.wiki contribution graph""" from flask import Flask, jsonify, render_template, request, url_for app = Flask('namuhub') @app.route('/', methods=['GET']) def index(): return render_template('index.html') @app.route('/<user>', methods=['GET']) def index_user(user=''): return render_template('index.html', **{'user': user}) @app.route('/', methods=['POST']) def namu(): user = request.POST.get('user', None) if not user: return '', 501
"""namuhub --- namu.wiki contribution graph""" import time from collections import defaultdict from datetime import timedelta from flask import Flask, jsonify, render_template, request, url_for from namuhub import namu as namuwiki app = Flask('namuhub') @app.route('/', methods=['GET']) def index(): return render_template('index.html') @app.route('/<user>', methods=['GET']) def index_user(user=''): return render_template('index.html', **{'user': user}) @app.route('/', methods=['POST']) def namu(): user = request.form.get('user', None) if not user: return jsonify({}), 501 contribs = namuwiki.contrib(user) data = defaultdict(lambda: []) # First, separate contributions into list by their activity date for contrib in contribs: date = (contrib.when - timedelta(hours=9)).date().strftime('%Y-%m-%d') data[date].append(contrib) # Convert defaultdict to dict # However, this may be inefficient but I don't care about performance at this point because it doesn't matter while it's a small project data = dict(data) # Next, we should serialize it as dict object to make sure that all the values are JSON serialiable for key, value in data.items(): value = [c.as_dict() for c in value] # Almost done, fix timezone and convert its date property to unix timestamp number that can be parsed by javascript's date object for i, c in enumerate(value): value[i]['when'] = int(time.mktime((c['when'] + timedelta(hours=9)).timetuple())) * 1000 # Overwrite existing value data[key] = value return jsonify(data)
Return namu.wiki contribution data as JSON
Return namu.wiki contribution data as JSON
Python
apache-2.0
ssut/namuhub,ssut/namuhub,ssut/namuhub
"""namuhub --- namu.wiki contribution graph""" + import time + from collections import defaultdict + from datetime import timedelta + from flask import Flask, jsonify, render_template, request, url_for + + from namuhub import namu as namuwiki app = Flask('namuhub') @app.route('/', methods=['GET']) def index(): return render_template('index.html') @app.route('/<user>', methods=['GET']) def index_user(user=''): return render_template('index.html', **{'user': user}) @app.route('/', methods=['POST']) def namu(): - user = request.POST.get('user', None) + user = request.form.get('user', None) if not user: - return '', 501 + return jsonify({}), 501 + + contribs = namuwiki.contrib(user) + data = defaultdict(lambda: []) + # First, separate contributions into list by their activity date + for contrib in contribs: + date = (contrib.when - timedelta(hours=9)).date().strftime('%Y-%m-%d') + data[date].append(contrib) + # Convert defaultdict to dict + # However, this may be inefficient but I don't care about performance at this point because it doesn't matter while it's a small project + data = dict(data) + # Next, we should serialize it as dict object to make sure that all the values are JSON serialiable + for key, value in data.items(): + value = [c.as_dict() for c in value] + # Almost done, fix timezone and convert its date property to unix timestamp number that can be parsed by javascript's date object + for i, c in enumerate(value): + value[i]['when'] = int(time.mktime((c['when'] + timedelta(hours=9)).timetuple())) * 1000 + # Overwrite existing value + data[key] = value + + return jsonify(data)
Return namu.wiki contribution data as JSON
## Code Before: """namuhub --- namu.wiki contribution graph""" from flask import Flask, jsonify, render_template, request, url_for app = Flask('namuhub') @app.route('/', methods=['GET']) def index(): return render_template('index.html') @app.route('/<user>', methods=['GET']) def index_user(user=''): return render_template('index.html', **{'user': user}) @app.route('/', methods=['POST']) def namu(): user = request.POST.get('user', None) if not user: return '', 501 ## Instruction: Return namu.wiki contribution data as JSON ## Code After: """namuhub --- namu.wiki contribution graph""" import time from collections import defaultdict from datetime import timedelta from flask import Flask, jsonify, render_template, request, url_for from namuhub import namu as namuwiki app = Flask('namuhub') @app.route('/', methods=['GET']) def index(): return render_template('index.html') @app.route('/<user>', methods=['GET']) def index_user(user=''): return render_template('index.html', **{'user': user}) @app.route('/', methods=['POST']) def namu(): user = request.form.get('user', None) if not user: return jsonify({}), 501 contribs = namuwiki.contrib(user) data = defaultdict(lambda: []) # First, separate contributions into list by their activity date for contrib in contribs: date = (contrib.when - timedelta(hours=9)).date().strftime('%Y-%m-%d') data[date].append(contrib) # Convert defaultdict to dict # However, this may be inefficient but I don't care about performance at this point because it doesn't matter while it's a small project data = dict(data) # Next, we should serialize it as dict object to make sure that all the values are JSON serialiable for key, value in data.items(): value = [c.as_dict() for c in value] # Almost done, fix timezone and convert its date property to unix timestamp number that can be parsed by javascript's date object for i, c in enumerate(value): value[i]['when'] = int(time.mktime((c['when'] + timedelta(hours=9)).timetuple())) * 1000 # Overwrite existing value data[key] = value return jsonify(data)
# ... existing code ... """namuhub --- namu.wiki contribution graph""" import time from collections import defaultdict from datetime import timedelta from flask import Flask, jsonify, render_template, request, url_for from namuhub import namu as namuwiki app = Flask('namuhub') # ... modified code ... @app.route('/', methods=['POST']) def namu(): user = request.form.get('user', None) if not user: return jsonify({}), 501 contribs = namuwiki.contrib(user) data = defaultdict(lambda: []) # First, separate contributions into list by their activity date for contrib in contribs: date = (contrib.when - timedelta(hours=9)).date().strftime('%Y-%m-%d') data[date].append(contrib) # Convert defaultdict to dict # However, this may be inefficient but I don't care about performance at this point because it doesn't matter while it's a small project data = dict(data) # Next, we should serialize it as dict object to make sure that all the values are JSON serialiable for key, value in data.items(): value = [c.as_dict() for c in value] # Almost done, fix timezone and convert its date property to unix timestamp number that can be parsed by javascript's date object for i, c in enumerate(value): value[i]['when'] = int(time.mktime((c['when'] + timedelta(hours=9)).timetuple())) * 1000 # Overwrite existing value data[key] = value return jsonify(data) # ... rest of the code ...
a6441de03522f9352742cba5a8a656785de05455
tests/mock_vws/test_query.py
tests/mock_vws/test_query.py
import pytest import requests from tests.mock_vws.utils import Endpoint, assert_query_success @pytest.mark.usefixtures('verify_mock_vuforia') class TestQuery: """ Tests for the query endpoint. """ def test_no_results( self, query_endpoint: Endpoint, ) -> None: """ When there are no matching images in the database, an empty list of results is returned. """ session = requests.Session() response = session.send( # type: ignore request=query_endpoint.prepared_request, ) assert_query_success(response=response) assert response.json()['results'] == []
import io from urllib.parse import urljoin import pytest import requests from requests_mock import POST from urllib3.filepost import encode_multipart_formdata from tests.mock_vws.utils import ( VuforiaDatabaseKeys, assert_query_success, authorization_header, rfc_1123_date, ) VWQ_HOST = 'https://cloudreco.vuforia.com' @pytest.mark.usefixtures('verify_mock_vuforia') class TestQuery: """ Tests for the query endpoint. """ def test_no_results( self, high_quality_image: io.BytesIO, vuforia_database_keys: VuforiaDatabaseKeys, ) -> None: """ When there are no matching images in the database, an empty list of results is returned. """ image_content = high_quality_image.read() date = rfc_1123_date() request_path = '/v1/query' files = {'image': ('image.jpeg', image_content, 'image/jpeg')} content, content_type_header = encode_multipart_formdata(files) method = POST access_key = vuforia_database_keys.client_access_key secret_key = vuforia_database_keys.client_secret_key authorization_string = authorization_header( access_key=access_key, secret_key=secret_key, method=method, content=content, # Note that this is not the actual Content-Type header value sent. content_type='multipart/form-data', date=date, request_path=request_path, ) headers = { 'Authorization': authorization_string, 'Date': date, 'Content-Type': content_type_header, } response = requests.request( method=method, url=urljoin(base=VWQ_HOST, url=request_path), headers=headers, data=content, ) assert_query_success(response=response) assert response.json()['results'] == []
Use raw request making in query test
Use raw request making in query test
Python
mit
adamtheturtle/vws-python,adamtheturtle/vws-python
+ + import io + from urllib.parse import urljoin import pytest import requests + from requests_mock import POST + from urllib3.filepost import encode_multipart_formdata - from tests.mock_vws.utils import Endpoint, assert_query_success + from tests.mock_vws.utils import ( + VuforiaDatabaseKeys, + assert_query_success, + authorization_header, + rfc_1123_date, + ) + + + VWQ_HOST = 'https://cloudreco.vuforia.com' @pytest.mark.usefixtures('verify_mock_vuforia') class TestQuery: """ Tests for the query endpoint. """ def test_no_results( self, - query_endpoint: Endpoint, + high_quality_image: io.BytesIO, + vuforia_database_keys: VuforiaDatabaseKeys, ) -> None: """ When there are no matching images in the database, an empty list of results is returned. """ - session = requests.Session() - response = session.send( # type: ignore - request=query_endpoint.prepared_request, + image_content = high_quality_image.read() + date = rfc_1123_date() + request_path = '/v1/query' + files = {'image': ('image.jpeg', image_content, 'image/jpeg')} + content, content_type_header = encode_multipart_formdata(files) + method = POST + + access_key = vuforia_database_keys.client_access_key + secret_key = vuforia_database_keys.client_secret_key + authorization_string = authorization_header( + access_key=access_key, + secret_key=secret_key, + method=method, + content=content, + # Note that this is not the actual Content-Type header value sent. + content_type='multipart/form-data', + date=date, + request_path=request_path, ) + + headers = { + 'Authorization': authorization_string, + 'Date': date, + 'Content-Type': content_type_header, + } + + response = requests.request( + method=method, + url=urljoin(base=VWQ_HOST, url=request_path), + headers=headers, + data=content, + ) + assert_query_success(response=response) assert response.json()['results'] == []
Use raw request making in query test
## Code Before: import pytest import requests from tests.mock_vws.utils import Endpoint, assert_query_success @pytest.mark.usefixtures('verify_mock_vuforia') class TestQuery: """ Tests for the query endpoint. """ def test_no_results( self, query_endpoint: Endpoint, ) -> None: """ When there are no matching images in the database, an empty list of results is returned. """ session = requests.Session() response = session.send( # type: ignore request=query_endpoint.prepared_request, ) assert_query_success(response=response) assert response.json()['results'] == [] ## Instruction: Use raw request making in query test ## Code After: import io from urllib.parse import urljoin import pytest import requests from requests_mock import POST from urllib3.filepost import encode_multipart_formdata from tests.mock_vws.utils import ( VuforiaDatabaseKeys, assert_query_success, authorization_header, rfc_1123_date, ) VWQ_HOST = 'https://cloudreco.vuforia.com' @pytest.mark.usefixtures('verify_mock_vuforia') class TestQuery: """ Tests for the query endpoint. """ def test_no_results( self, high_quality_image: io.BytesIO, vuforia_database_keys: VuforiaDatabaseKeys, ) -> None: """ When there are no matching images in the database, an empty list of results is returned. """ image_content = high_quality_image.read() date = rfc_1123_date() request_path = '/v1/query' files = {'image': ('image.jpeg', image_content, 'image/jpeg')} content, content_type_header = encode_multipart_formdata(files) method = POST access_key = vuforia_database_keys.client_access_key secret_key = vuforia_database_keys.client_secret_key authorization_string = authorization_header( access_key=access_key, secret_key=secret_key, method=method, content=content, # Note that this is not the actual Content-Type header value sent. content_type='multipart/form-data', date=date, request_path=request_path, ) headers = { 'Authorization': authorization_string, 'Date': date, 'Content-Type': content_type_header, } response = requests.request( method=method, url=urljoin(base=VWQ_HOST, url=request_path), headers=headers, data=content, ) assert_query_success(response=response) assert response.json()['results'] == []
... import io from urllib.parse import urljoin import pytest import requests from requests_mock import POST from urllib3.filepost import encode_multipart_formdata from tests.mock_vws.utils import ( VuforiaDatabaseKeys, assert_query_success, authorization_header, rfc_1123_date, ) VWQ_HOST = 'https://cloudreco.vuforia.com' ... def test_no_results( self, high_quality_image: io.BytesIO, vuforia_database_keys: VuforiaDatabaseKeys, ) -> None: """ ... results is returned. """ image_content = high_quality_image.read() date = rfc_1123_date() request_path = '/v1/query' files = {'image': ('image.jpeg', image_content, 'image/jpeg')} content, content_type_header = encode_multipart_formdata(files) method = POST access_key = vuforia_database_keys.client_access_key secret_key = vuforia_database_keys.client_secret_key authorization_string = authorization_header( access_key=access_key, secret_key=secret_key, method=method, content=content, # Note that this is not the actual Content-Type header value sent. content_type='multipart/form-data', date=date, request_path=request_path, ) headers = { 'Authorization': authorization_string, 'Date': date, 'Content-Type': content_type_header, } response = requests.request( method=method, url=urljoin(base=VWQ_HOST, url=request_path), headers=headers, data=content, ) assert_query_success(response=response) assert response.json()['results'] == [] ...
8bfe6e791228ccbc3143f3a8747c68d2e8b0cbb5
runtests.py
runtests.py
from django.conf import settings from django.core.management import execute_from_command_line import django import os import sys if not settings.configured: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproj.settings") django.setup() module_root = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, module_root) def runtests(): argv = sys.argv[:1] + ['test', 'testproj'] + sys.argv[1:] execute_from_command_line(argv) if __name__ == '__main__': runtests()
from django.conf import settings from django.core.management import execute_from_command_line import django import os import sys if not settings.configured: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproj.settings") if django.VERSION >= (1,7): django.setup() module_root = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, module_root) def runtests(): argv = sys.argv[:1] + ['test', 'testproj'] + sys.argv[1:] execute_from_command_line(argv) if __name__ == '__main__': runtests()
Fix running tests on lower Django versions
Fix running tests on lower Django versions
Python
apache-2.0
AdrianLC/django-parler-rest,edoburu/django-parler-rest
from django.conf import settings from django.core.management import execute_from_command_line import django import os import sys if not settings.configured: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproj.settings") + if django.VERSION >= (1,7): - django.setup() + django.setup() module_root = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, module_root) def runtests(): argv = sys.argv[:1] + ['test', 'testproj'] + sys.argv[1:] execute_from_command_line(argv) if __name__ == '__main__': runtests()
Fix running tests on lower Django versions
## Code Before: from django.conf import settings from django.core.management import execute_from_command_line import django import os import sys if not settings.configured: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproj.settings") django.setup() module_root = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, module_root) def runtests(): argv = sys.argv[:1] + ['test', 'testproj'] + sys.argv[1:] execute_from_command_line(argv) if __name__ == '__main__': runtests() ## Instruction: Fix running tests on lower Django versions ## Code After: from django.conf import settings from django.core.management import execute_from_command_line import django import os import sys if not settings.configured: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproj.settings") if django.VERSION >= (1,7): django.setup() module_root = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, module_root) def runtests(): argv = sys.argv[:1] + ['test', 'testproj'] + sys.argv[1:] execute_from_command_line(argv) if __name__ == '__main__': runtests()
# ... existing code ... if not settings.configured: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproj.settings") if django.VERSION >= (1,7): django.setup() module_root = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, module_root) # ... rest of the code ...
f33bbdaae182eee27ad372a6f0d10e9c7be66a6f
polygraph/types/__init__.py
polygraph/types/__init__.py
from .enum import EnumType from .field import field from .input_object import InputObject from .interface import Interface from .lazy_type import LazyType from .list import List from .nonnull import NonNull from .object_type import ObjectType from .scalar import ID, Boolean, Float, Int, String from .union import Union __all__ = [ "Boolean", "EnumType", "field", "Float", "ID", "InputObject", "Int", "Interface", "LazyType", "List", "NonNull", "ObjectType", "String", "Union", ]
from .enum import EnumType, EnumValue from .field import field from .input_object import InputObject, InputValue from .interface import Interface from .lazy_type import LazyType from .list import List from .nonnull import NonNull from .object_type import ObjectType from .scalar import ID, Boolean, Float, Int, String from .union import Union __all__ = [ "Boolean", "EnumType", "EnumValue", "field", "Float", "ID", "InputObject", "InputValue", "Int", "Interface", "LazyType", "List", "NonNull", "ObjectType", "String", "Union", ]
Fix polygraph.types import to include EnumValue and InputValue
Fix polygraph.types import to include EnumValue and InputValue
Python
mit
polygraph-python/polygraph
- from .enum import EnumType + from .enum import EnumType, EnumValue from .field import field - from .input_object import InputObject + from .input_object import InputObject, InputValue from .interface import Interface from .lazy_type import LazyType from .list import List from .nonnull import NonNull from .object_type import ObjectType from .scalar import ID, Boolean, Float, Int, String from .union import Union __all__ = [ "Boolean", "EnumType", + "EnumValue", "field", "Float", "ID", "InputObject", + "InputValue", "Int", "Interface", "LazyType", "List", "NonNull", "ObjectType", "String", "Union", ]
Fix polygraph.types import to include EnumValue and InputValue
## Code Before: from .enum import EnumType from .field import field from .input_object import InputObject from .interface import Interface from .lazy_type import LazyType from .list import List from .nonnull import NonNull from .object_type import ObjectType from .scalar import ID, Boolean, Float, Int, String from .union import Union __all__ = [ "Boolean", "EnumType", "field", "Float", "ID", "InputObject", "Int", "Interface", "LazyType", "List", "NonNull", "ObjectType", "String", "Union", ] ## Instruction: Fix polygraph.types import to include EnumValue and InputValue ## Code After: from .enum import EnumType, EnumValue from .field import field from .input_object import InputObject, InputValue from .interface import Interface from .lazy_type import LazyType from .list import List from .nonnull import NonNull from .object_type import ObjectType from .scalar import ID, Boolean, Float, Int, String from .union import Union __all__ = [ "Boolean", "EnumType", "EnumValue", "field", "Float", "ID", "InputObject", "InputValue", "Int", "Interface", "LazyType", "List", "NonNull", "ObjectType", "String", "Union", ]
... from .enum import EnumType, EnumValue from .field import field from .input_object import InputObject, InputValue from .interface import Interface from .lazy_type import LazyType ... "Boolean", "EnumType", "EnumValue", "field", "Float", ... "ID", "InputObject", "InputValue", "Int", "Interface", ...
4e94612f7fad4b231de9c1a4044259be6079a982
fabtasks.py
fabtasks.py
from fabric.api import task, run def _generate_password(): import string from random import sample chars = string.letters + string.digits return ''.join(sample(chars, 8)) def create_mysql_instance(mysql_user, mysql_password, instance_code): user = instance_code password = _generate_password() cmd = "/usr/bin/mysql -h localhost -u '%s' '--password=%s' -P %s -e \"create database %s; grant all on %s.* to '%s'@'%%' identified by '%s'\"" % ( mysql_user, mysql_password, 3306, user, user, user, password,) return run(cmd) # Local Variables: ** # comment-column: 56 ** # indent-tabs-mode: nil ** # python-indent: 4 ** # End: **
from fabric.api import run def _generate_password(): import string from random import sample chars = string.letters + string.digits return ''.join(sample(chars, 8)) def create_mysql_instance(mysql_user, mysql_password, instance_code): user = instance_code password = _generate_password() cmd_create_database = "/usr/bin/mysql -h localhost -u '%s' '--password=%s' -P %s -e \"create database %s;\"" % ( mysql_user, mysql_password, 3306, user,) cmd_create_user = "/usr/bin/mysql -h localhost -u '%s' '--password=%s' -P %s -e \"grant all on %s.* to '%s'@'%%' identified by '%s';\"" % ( mysql_user, mysql_password, 3306, user, user, password,) run(cmd_create_database) run(cmd_create_user) # Local Variables: ** # comment-column: 56 ** # indent-tabs-mode: nil ** # python-indent: 4 ** # End: **
Split create database and create user into to individual commands
Split create database and create user into to individual commands
Python
mit
goncha/fablib
- from fabric.api import task, run + from fabric.api import run def _generate_password(): import string from random import sample chars = string.letters + string.digits return ''.join(sample(chars, 8)) def create_mysql_instance(mysql_user, mysql_password, instance_code): user = instance_code password = _generate_password() - cmd = "/usr/bin/mysql -h localhost -u '%s' '--password=%s' -P %s -e \"create database %s; grant all on %s.* to '%s'@'%%' identified by '%s'\"" % ( + cmd_create_database = "/usr/bin/mysql -h localhost -u '%s' '--password=%s' -P %s -e \"create database %s;\"" % ( mysql_user, mysql_password, 3306, + user,) + cmd_create_user = "/usr/bin/mysql -h localhost -u '%s' '--password=%s' -P %s -e \"grant all on %s.* to '%s'@'%%' identified by '%s';\"" % ( + mysql_user, mysql_password, 3306, - user, user, user, password,) + user, user, password,) - return run(cmd) + + run(cmd_create_database) + run(cmd_create_user) # Local Variables: ** # comment-column: 56 ** # indent-tabs-mode: nil ** # python-indent: 4 ** # End: **
Split create database and create user into to individual commands
## Code Before: from fabric.api import task, run def _generate_password(): import string from random import sample chars = string.letters + string.digits return ''.join(sample(chars, 8)) def create_mysql_instance(mysql_user, mysql_password, instance_code): user = instance_code password = _generate_password() cmd = "/usr/bin/mysql -h localhost -u '%s' '--password=%s' -P %s -e \"create database %s; grant all on %s.* to '%s'@'%%' identified by '%s'\"" % ( mysql_user, mysql_password, 3306, user, user, user, password,) return run(cmd) # Local Variables: ** # comment-column: 56 ** # indent-tabs-mode: nil ** # python-indent: 4 ** # End: ** ## Instruction: Split create database and create user into to individual commands ## Code After: from fabric.api import run def _generate_password(): import string from random import sample chars = string.letters + string.digits return ''.join(sample(chars, 8)) def create_mysql_instance(mysql_user, mysql_password, instance_code): user = instance_code password = _generate_password() cmd_create_database = "/usr/bin/mysql -h localhost -u '%s' '--password=%s' -P %s -e \"create database %s;\"" % ( mysql_user, mysql_password, 3306, user,) cmd_create_user = "/usr/bin/mysql -h localhost -u '%s' '--password=%s' -P %s -e \"grant all on %s.* to '%s'@'%%' identified by '%s';\"" % ( mysql_user, mysql_password, 3306, user, user, password,) run(cmd_create_database) run(cmd_create_user) # Local Variables: ** # comment-column: 56 ** # indent-tabs-mode: nil ** # python-indent: 4 ** # End: **
# ... existing code ... from fabric.api import run def _generate_password(): # ... modified code ... user = instance_code password = _generate_password() cmd_create_database = "/usr/bin/mysql -h localhost -u '%s' '--password=%s' -P %s -e \"create database %s;\"" % ( mysql_user, mysql_password, 3306, user,) cmd_create_user = "/usr/bin/mysql -h localhost -u '%s' '--password=%s' -P %s -e \"grant all on %s.* to '%s'@'%%' identified by '%s';\"" % ( mysql_user, mysql_password, 3306, user, user, password,) run(cmd_create_database) run(cmd_create_user) # ... rest of the code ...
8f36430e6fc17485b422ed5e620de4b156101623
polyaxon_client/stores/stores/local_store.py
polyaxon_client/stores/stores/local_store.py
from __future__ import absolute_import, division, print_function from polyaxon_client.stores.stores.base_store import Store class LocalStore(Store): """ Local filesystem store. This store is noop store since all data is accessible through the filesystem. """ # pylint:disable=arguments-differ STORE_TYPE = Store._LOCAL_STORE # pylint:disable=protected-access def download_file(self, *args, **kwargs): pass def upload_file(self, *args, **kwargs): pass def upload_dir(self, *args, **kwargs): pass def download_dir(self, *args, **kwargs): pass
from __future__ import absolute_import, division, print_function from polyaxon_client.stores.stores.base_store import BaseStore class LocalStore(BaseStore): """ Local filesystem store. This store is noop store since all data is accessible through the filesystem. """ # pylint:disable=arguments-differ STORE_TYPE = BaseStore._LOCAL_STORE # pylint:disable=protected-access def download_file(self, *args, **kwargs): pass def upload_file(self, *args, **kwargs): pass def upload_dir(self, *args, **kwargs): pass def download_dir(self, *args, **kwargs): pass
Update local store base class
Update local store base class
Python
apache-2.0
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
from __future__ import absolute_import, division, print_function - from polyaxon_client.stores.stores.base_store import Store + from polyaxon_client.stores.stores.base_store import BaseStore - class LocalStore(Store): + class LocalStore(BaseStore): """ Local filesystem store. This store is noop store since all data is accessible through the filesystem. """ # pylint:disable=arguments-differ - STORE_TYPE = Store._LOCAL_STORE # pylint:disable=protected-access + STORE_TYPE = BaseStore._LOCAL_STORE # pylint:disable=protected-access def download_file(self, *args, **kwargs): pass def upload_file(self, *args, **kwargs): pass def upload_dir(self, *args, **kwargs): pass def download_dir(self, *args, **kwargs): pass
Update local store base class
## Code Before: from __future__ import absolute_import, division, print_function from polyaxon_client.stores.stores.base_store import Store class LocalStore(Store): """ Local filesystem store. This store is noop store since all data is accessible through the filesystem. """ # pylint:disable=arguments-differ STORE_TYPE = Store._LOCAL_STORE # pylint:disable=protected-access def download_file(self, *args, **kwargs): pass def upload_file(self, *args, **kwargs): pass def upload_dir(self, *args, **kwargs): pass def download_dir(self, *args, **kwargs): pass ## Instruction: Update local store base class ## Code After: from __future__ import absolute_import, division, print_function from polyaxon_client.stores.stores.base_store import BaseStore class LocalStore(BaseStore): """ Local filesystem store. This store is noop store since all data is accessible through the filesystem. """ # pylint:disable=arguments-differ STORE_TYPE = BaseStore._LOCAL_STORE # pylint:disable=protected-access def download_file(self, *args, **kwargs): pass def upload_file(self, *args, **kwargs): pass def upload_dir(self, *args, **kwargs): pass def download_dir(self, *args, **kwargs): pass
// ... existing code ... from __future__ import absolute_import, division, print_function from polyaxon_client.stores.stores.base_store import BaseStore class LocalStore(BaseStore): """ Local filesystem store. // ... modified code ... # pylint:disable=arguments-differ STORE_TYPE = BaseStore._LOCAL_STORE # pylint:disable=protected-access def download_file(self, *args, **kwargs): // ... rest of the code ...
fce3dd3b08f2ff8500be4d694e9d384bd61b82ab
quickly/families/models.py
quickly/families/models.py
from django.db import models from quickly.buttons.models import EmergencyButtonClient class FamilyMember(models.Model): """ Model which defines families of the platform with authentication possibilities and a phone number which can be sent to emergency services. """ phone_number = models.CharField(max_length=15) email = models.EmailField() emergency_button_client = models.ForeignKey(EmergencyButtonClient)
from django.db import models from quickly.buttons.models import EmergencyButtonClient class FamilyMember(models.Model): """ Model which defines families of the platform with authentication possibilities and a phone number which can be sent to emergency services. """ phone_number = models.CharField(max_length=15) email = models.EmailField() name = models.CharField(max_length=255, blank=True) emergency_button_client = models.ForeignKey(EmergencyButtonClient)
Add name to family member
Add name to family member
Python
mit
wearespindle/quickly.press,wearespindle/quickly.press,wearespindle/quickly.press
from django.db import models from quickly.buttons.models import EmergencyButtonClient class FamilyMember(models.Model): """ Model which defines families of the platform with authentication possibilities and a phone number which can be sent to emergency services. """ phone_number = models.CharField(max_length=15) email = models.EmailField() + name = models.CharField(max_length=255, blank=True) emergency_button_client = models.ForeignKey(EmergencyButtonClient)
Add name to family member
## Code Before: from django.db import models from quickly.buttons.models import EmergencyButtonClient class FamilyMember(models.Model): """ Model which defines families of the platform with authentication possibilities and a phone number which can be sent to emergency services. """ phone_number = models.CharField(max_length=15) email = models.EmailField() emergency_button_client = models.ForeignKey(EmergencyButtonClient) ## Instruction: Add name to family member ## Code After: from django.db import models from quickly.buttons.models import EmergencyButtonClient class FamilyMember(models.Model): """ Model which defines families of the platform with authentication possibilities and a phone number which can be sent to emergency services. """ phone_number = models.CharField(max_length=15) email = models.EmailField() name = models.CharField(max_length=255, blank=True) emergency_button_client = models.ForeignKey(EmergencyButtonClient)
// ... existing code ... phone_number = models.CharField(max_length=15) email = models.EmailField() name = models.CharField(max_length=255, blank=True) emergency_button_client = models.ForeignKey(EmergencyButtonClient) // ... rest of the code ...
323a92afd125bd97c960ab71c64f78601ec4b000
aioinotify/watch.py
aioinotify/watch.py
import asyncio class Watch: """Represents an inotify watch as added by InotifyProtocol.watch()""" def __init__(self, watch_descriptor, callback, protocol): """ :param int watch_descriptor: The watch descriptor as returned by inotify_add_watch :param callback: A function with one positional argument (the event object) called when an inotify event happens. """ self.watch_descriptor = watch_descriptor self._callback = callback self._closed = False self._protocol = protocol @asyncio.coroutine def dispatch_event(self, event): if not self._closed: yield from self._callback(event) def close(self): if not self._closed: self._protocol._remove_watch(self.watch_descriptor) self._closed = True
import asyncio class Watch: """Represents an inotify watch as added by InotifyProtocol.watch()""" def __init__(self, watch_descriptor, callback, protocol): """ :param int watch_descriptor: The watch descriptor as returned by inotify_add_watch :param callback: A function with one positional argument (the event object) called when an inotify event happens. """ self.watch_descriptor = watch_descriptor self._callback = callback self._closed = False self._protocol = protocol def __enter__(self): return self def __exit__(self, *exc): self.close() @asyncio.coroutine def dispatch_event(self, event): if not self._closed: yield from self._callback(event) def close(self): if not self._closed: self._protocol._remove_watch(self.watch_descriptor) self._closed = True
Make Watch also a context manager
Make Watch also a context manager
Python
apache-2.0
mwfrojdman/aioinotify
import asyncio class Watch: """Represents an inotify watch as added by InotifyProtocol.watch()""" def __init__(self, watch_descriptor, callback, protocol): """ :param int watch_descriptor: The watch descriptor as returned by inotify_add_watch :param callback: A function with one positional argument (the event object) called when an inotify event happens. """ self.watch_descriptor = watch_descriptor self._callback = callback self._closed = False self._protocol = protocol + def __enter__(self): + return self + + def __exit__(self, *exc): + self.close() + @asyncio.coroutine def dispatch_event(self, event): if not self._closed: yield from self._callback(event) def close(self): if not self._closed: self._protocol._remove_watch(self.watch_descriptor) self._closed = True
Make Watch also a context manager
## Code Before: import asyncio class Watch: """Represents an inotify watch as added by InotifyProtocol.watch()""" def __init__(self, watch_descriptor, callback, protocol): """ :param int watch_descriptor: The watch descriptor as returned by inotify_add_watch :param callback: A function with one positional argument (the event object) called when an inotify event happens. """ self.watch_descriptor = watch_descriptor self._callback = callback self._closed = False self._protocol = protocol @asyncio.coroutine def dispatch_event(self, event): if not self._closed: yield from self._callback(event) def close(self): if not self._closed: self._protocol._remove_watch(self.watch_descriptor) self._closed = True ## Instruction: Make Watch also a context manager ## Code After: import asyncio class Watch: """Represents an inotify watch as added by InotifyProtocol.watch()""" def __init__(self, watch_descriptor, callback, protocol): """ :param int watch_descriptor: The watch descriptor as returned by inotify_add_watch :param callback: A function with one positional argument (the event object) called when an inotify event happens. """ self.watch_descriptor = watch_descriptor self._callback = callback self._closed = False self._protocol = protocol def __enter__(self): return self def __exit__(self, *exc): self.close() @asyncio.coroutine def dispatch_event(self, event): if not self._closed: yield from self._callback(event) def close(self): if not self._closed: self._protocol._remove_watch(self.watch_descriptor) self._closed = True
# ... existing code ... self._protocol = protocol def __enter__(self): return self def __exit__(self, *exc): self.close() @asyncio.coroutine def dispatch_event(self, event): # ... rest of the code ...
2a6f0f7fbb655c568a42493e1181aeef9fa1ead1
test_setup.py
test_setup.py
"""Test setup.py.""" import os import subprocess import sys def test_setup(): """Run setup.py check.""" command = [sys.executable, 'setup.py', 'check', '--metadata', '--strict'] assert subprocess.run(command).returncode == 0 def test_console_scripts(): """Ensure console scripts were installed correctly.""" assert any( os.path.isfile(os.path.join(directory, 'backlog')) for directory in sys.path )
"""Test setup.py.""" import os import subprocess import sys def test_setup(): """Run setup.py check.""" command = [sys.executable, 'setup.py', 'check', '--metadata', '--strict'] assert subprocess.run(command).returncode == 0 def test_console_scripts(): """Ensure console scripts were installed correctly.""" assert any( os.path.isfile(os.path.join(directory, 'backlog')) for directory in os.environ['PATH'].split(':') )
Use $PATH instead of sys.path
Use $PATH instead of sys.path
Python
lgpl-2.1
dmtucker/backlog
"""Test setup.py.""" import os import subprocess import sys def test_setup(): """Run setup.py check.""" command = [sys.executable, 'setup.py', 'check', '--metadata', '--strict'] assert subprocess.run(command).returncode == 0 def test_console_scripts(): """Ensure console scripts were installed correctly.""" assert any( os.path.isfile(os.path.join(directory, 'backlog')) - for directory in sys.path + for directory in os.environ['PATH'].split(':') )
Use $PATH instead of sys.path
## Code Before: """Test setup.py.""" import os import subprocess import sys def test_setup(): """Run setup.py check.""" command = [sys.executable, 'setup.py', 'check', '--metadata', '--strict'] assert subprocess.run(command).returncode == 0 def test_console_scripts(): """Ensure console scripts were installed correctly.""" assert any( os.path.isfile(os.path.join(directory, 'backlog')) for directory in sys.path ) ## Instruction: Use $PATH instead of sys.path ## Code After: """Test setup.py.""" import os import subprocess import sys def test_setup(): """Run setup.py check.""" command = [sys.executable, 'setup.py', 'check', '--metadata', '--strict'] assert subprocess.run(command).returncode == 0 def test_console_scripts(): """Ensure console scripts were installed correctly.""" assert any( os.path.isfile(os.path.join(directory, 'backlog')) for directory in os.environ['PATH'].split(':') )
... assert any( os.path.isfile(os.path.join(directory, 'backlog')) for directory in os.environ['PATH'].split(':') ) ...
14e9bda5de10ef5a1c6dd96692d083f4e0f16025
python/ql/test/experimental/library-tests/frameworks/yaml/Decoding.py
python/ql/test/experimental/library-tests/frameworks/yaml/Decoding.py
import yaml from yaml import SafeLoader yaml.load(payload) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.load(payload, SafeLoader) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML yaml.load(payload, Loader=SafeLoader) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML yaml.load(payload, Loader=yaml.BaseLoader) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML yaml.safe_load(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML yaml.unsafe_load(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.full_load(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.load_all(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.safe_load_all(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML yaml.unsafe_load_all(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.full_load_all(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput
import yaml # Unsafe: yaml.load(payload) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.load(payload, yaml.Loader) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.unsafe_load(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.full_load(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput # Safe yaml.load(payload, yaml.SafeLoader) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML yaml.load(payload, Loader=yaml.SafeLoader) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML yaml.load(payload, yaml.BaseLoader) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML yaml.safe_load(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML # load_all variants yaml.load_all(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.safe_load_all(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML yaml.unsafe_load_all(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.full_load_all(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput
Refactor PyYAML tests a bit
Python: Refactor PyYAML tests a bit
Python
mit
github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql
import yaml - from yaml import SafeLoader + # Unsafe: yaml.load(payload) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput - yaml.load(payload, SafeLoader) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML + yaml.load(payload, yaml.Loader) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput - yaml.load(payload, Loader=SafeLoader) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML - yaml.load(payload, Loader=yaml.BaseLoader) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML - - yaml.safe_load(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML yaml.unsafe_load(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.full_load(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput + # Safe + yaml.load(payload, yaml.SafeLoader) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML + yaml.load(payload, Loader=yaml.SafeLoader) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML + yaml.load(payload, yaml.BaseLoader) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML + yaml.safe_load(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML + + # load_all variants yaml.load_all(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.safe_load_all(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML yaml.unsafe_load_all(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.full_load_all(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput
Refactor PyYAML tests a bit
## Code Before: import yaml from yaml import SafeLoader yaml.load(payload) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.load(payload, SafeLoader) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML yaml.load(payload, Loader=SafeLoader) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML yaml.load(payload, Loader=yaml.BaseLoader) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML yaml.safe_load(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML yaml.unsafe_load(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.full_load(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.load_all(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.safe_load_all(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML yaml.unsafe_load_all(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.full_load_all(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput ## Instruction: Refactor PyYAML tests a bit ## Code After: import yaml # Unsafe: yaml.load(payload) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.load(payload, yaml.Loader) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.unsafe_load(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.full_load(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput # Safe yaml.load(payload, yaml.SafeLoader) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML yaml.load(payload, Loader=yaml.SafeLoader) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML yaml.load(payload, yaml.BaseLoader) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML yaml.safe_load(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML # load_all variants yaml.load_all(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.safe_load_all(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML yaml.unsafe_load_all(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.full_load_all(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput
... import yaml # Unsafe: yaml.load(payload) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.load(payload, yaml.Loader) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.unsafe_load(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.full_load(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput # Safe yaml.load(payload, yaml.SafeLoader) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML yaml.load(payload, Loader=yaml.SafeLoader) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML yaml.load(payload, yaml.BaseLoader) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML yaml.safe_load(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML # load_all variants yaml.load_all(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput yaml.safe_load_all(payload) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML ...
787fef7c74ca46b83557edaf3bb4d0189a586204
build.py
build.py
from elixir.compilers import ModelCompiler from elixir.processors import NevermoreProcessor ModelCompiler("src/", "model.rbxmx", NevermoreProcessor).compile()
from elixir.compilers import ModelCompiler ModelCompiler("src/", "model.rbxmx").compile()
Remove the use of the Nevermore processor
Remove the use of the Nevermore processor
Python
mit
VoxelDavid/echo-ridge
from elixir.compilers import ModelCompiler - from elixir.processors import NevermoreProcessor - ModelCompiler("src/", "model.rbxmx", NevermoreProcessor).compile() + ModelCompiler("src/", "model.rbxmx").compile()
Remove the use of the Nevermore processor
## Code Before: from elixir.compilers import ModelCompiler from elixir.processors import NevermoreProcessor ModelCompiler("src/", "model.rbxmx", NevermoreProcessor).compile() ## Instruction: Remove the use of the Nevermore processor ## Code After: from elixir.compilers import ModelCompiler ModelCompiler("src/", "model.rbxmx").compile()
... from elixir.compilers import ModelCompiler ModelCompiler("src/", "model.rbxmx").compile() ...
f3875956cda23c4b0086dbc083161dc6f2c1a771
spicedham/split_tokenizer.py
spicedham/split_tokenizer.py
from re import split from spicedham.tokenizer import BaseTokenizer class SplitTokenizer(BaseTokenizer): """ Split the text on punctuation and newlines, lowercase everything, and filter the empty strings """ def tokenize(self, text): text = split('[ ,.?!\n\r]', text) is_not_blank = lambda x: x != '' text = filter(is_not_blank, text) lower_case = lambda x: x.lower() text = map(lower_case, text) return text
from re import split from spicedham.tokenizer import BaseTokenizer class SplitTokenizer(BaseTokenizer): """ Split the text on punctuation and newlines, lowercase everything, and filter the empty strings """ def tokenize(self, text): text = split('[ ,.?!\n\r]', text) text = [token.lower() for token in text if token] return text
Make mapping & filtering into a list comprehension
Make mapping & filtering into a list comprehension
Python
mpl-2.0
mozilla/spicedham,mozilla/spicedham
from re import split from spicedham.tokenizer import BaseTokenizer class SplitTokenizer(BaseTokenizer): """ Split the text on punctuation and newlines, lowercase everything, and filter the empty strings """ def tokenize(self, text): text = split('[ ,.?!\n\r]', text) + text = [token.lower() for token in text if token] - is_not_blank = lambda x: x != '' - text = filter(is_not_blank, text) - lower_case = lambda x: x.lower() - text = map(lower_case, text) return text
Make mapping & filtering into a list comprehension
## Code Before: from re import split from spicedham.tokenizer import BaseTokenizer class SplitTokenizer(BaseTokenizer): """ Split the text on punctuation and newlines, lowercase everything, and filter the empty strings """ def tokenize(self, text): text = split('[ ,.?!\n\r]', text) is_not_blank = lambda x: x != '' text = filter(is_not_blank, text) lower_case = lambda x: x.lower() text = map(lower_case, text) return text ## Instruction: Make mapping & filtering into a list comprehension ## Code After: from re import split from spicedham.tokenizer import BaseTokenizer class SplitTokenizer(BaseTokenizer): """ Split the text on punctuation and newlines, lowercase everything, and filter the empty strings """ def tokenize(self, text): text = split('[ ,.?!\n\r]', text) text = [token.lower() for token in text if token] return text
// ... existing code ... def tokenize(self, text): text = split('[ ,.?!\n\r]', text) text = [token.lower() for token in text if token] return text // ... rest of the code ...
9ebc81565171866462dae5eb068bb7c1d98948a7
ovp_users/serializers/__init__.py
ovp_users/serializers/__init__.py
from ovp_users.serializers.user import UserCreateSerializer from ovp_users.serializers.user import UserUpdateSerializer from ovp_users.serializers.user import CurrentUserSerializer from ovp_users.serializers.user import UserPublicRetrieveSerializer from ovp_users.serializers.user import UserProjectRetrieveSerializer from ovp_users.serializers.user import UserApplyRetrieveSerializer from ovp_users.serializers.password_recovery import RecoveryTokenSerializer from ovp_users.serializers.password_recovery import RecoverPasswordSerializer from ovp_users.serializers.profile import ProfileCreateUpdateSerializer from ovp_users.serializers.profile import ProfileRetrieveSerializer
from ovp_users.serializers.user import UserCreateSerializer from ovp_users.serializers.user import UserUpdateSerializer from ovp_users.serializers.user import CurrentUserSerializer from ovp_users.serializers.user import ShortUserPublicRetrieveSerializer from ovp_users.serializers.user import LongUserPublicRetrieveSerializer from ovp_users.serializers.user import UserProjectRetrieveSerializer from ovp_users.serializers.user import UserApplyRetrieveSerializer from ovp_users.serializers.password_recovery import RecoveryTokenSerializer from ovp_users.serializers.password_recovery import RecoverPasswordSerializer from ovp_users.serializers.profile import ProfileCreateUpdateSerializer from ovp_users.serializers.profile import ProfileRetrieveSerializer
Add ShortUserRetrieve and LongUserRetrieve serializers
Add ShortUserRetrieve and LongUserRetrieve serializers
Python
agpl-3.0
OpenVolunteeringPlatform/django-ovp-users,OpenVolunteeringPlatform/django-ovp-users
from ovp_users.serializers.user import UserCreateSerializer from ovp_users.serializers.user import UserUpdateSerializer from ovp_users.serializers.user import CurrentUserSerializer + from ovp_users.serializers.user import ShortUserPublicRetrieveSerializer - from ovp_users.serializers.user import UserPublicRetrieveSerializer + from ovp_users.serializers.user import LongUserPublicRetrieveSerializer from ovp_users.serializers.user import UserProjectRetrieveSerializer from ovp_users.serializers.user import UserApplyRetrieveSerializer from ovp_users.serializers.password_recovery import RecoveryTokenSerializer from ovp_users.serializers.password_recovery import RecoverPasswordSerializer from ovp_users.serializers.profile import ProfileCreateUpdateSerializer from ovp_users.serializers.profile import ProfileRetrieveSerializer
Add ShortUserRetrieve and LongUserRetrieve serializers
## Code Before: from ovp_users.serializers.user import UserCreateSerializer from ovp_users.serializers.user import UserUpdateSerializer from ovp_users.serializers.user import CurrentUserSerializer from ovp_users.serializers.user import UserPublicRetrieveSerializer from ovp_users.serializers.user import UserProjectRetrieveSerializer from ovp_users.serializers.user import UserApplyRetrieveSerializer from ovp_users.serializers.password_recovery import RecoveryTokenSerializer from ovp_users.serializers.password_recovery import RecoverPasswordSerializer from ovp_users.serializers.profile import ProfileCreateUpdateSerializer from ovp_users.serializers.profile import ProfileRetrieveSerializer ## Instruction: Add ShortUserRetrieve and LongUserRetrieve serializers ## Code After: from ovp_users.serializers.user import UserCreateSerializer from ovp_users.serializers.user import UserUpdateSerializer from ovp_users.serializers.user import CurrentUserSerializer from ovp_users.serializers.user import ShortUserPublicRetrieveSerializer from ovp_users.serializers.user import LongUserPublicRetrieveSerializer from ovp_users.serializers.user import UserProjectRetrieveSerializer from ovp_users.serializers.user import UserApplyRetrieveSerializer from ovp_users.serializers.password_recovery import RecoveryTokenSerializer from ovp_users.serializers.password_recovery import RecoverPasswordSerializer from ovp_users.serializers.profile import ProfileCreateUpdateSerializer from ovp_users.serializers.profile import ProfileRetrieveSerializer
# ... existing code ... from ovp_users.serializers.user import UserUpdateSerializer from ovp_users.serializers.user import CurrentUserSerializer from ovp_users.serializers.user import ShortUserPublicRetrieveSerializer from ovp_users.serializers.user import LongUserPublicRetrieveSerializer from ovp_users.serializers.user import UserProjectRetrieveSerializer from ovp_users.serializers.user import UserApplyRetrieveSerializer # ... rest of the code ...
d369b2ba967643d16c58fbad0be5b3a24785f602
neurodsp/tests/test_spectral_utils.py
neurodsp/tests/test_spectral_utils.py
"""Test the utility function from spectral.""" import numpy as np from numpy.testing import assert_equal from neurodsp.spectral.utils import * ################################################################################################### ################################################################################################### def test_trim_spectrum(): freqs = np.array([5, 6, 7, 8, 9]) pows = np.array([1, 2, 3, 4, 5]) freqs_new, pows_new = trim_spectrum(freqs, pows, [6, 8]) assert_equal(freqs_new, np.array([6, 7, 8])) assert_equal(pows_new, np.array([2, 3, 4])) def test_rotate_powerlaw(): freqs = np.array([5, 6, 7, 8, 9]) pows = np.array([1, 2, 3, 4, 5]) d_exp = 1 pows_new = rotate_powerlaw(freqs, pows, d_exp) assert pows.shape == pows_new.shape
"""Test the utility function from spectral.""" import numpy as np from numpy.testing import assert_equal from neurodsp.spectral.utils import * ################################################################################################### ################################################################################################### def test_trim_spectrum(): freqs = np.array([5, 6, 7, 8, 9]) pows = np.array([1, 2, 3, 4, 5]) freqs_new, pows_new = trim_spectrum(freqs, pows, [6, 8]) assert_equal(freqs_new, np.array([6, 7, 8])) assert_equal(pows_new, np.array([2, 3, 4])) def test_trim_spectrogram(): freqs = np.array([5, 6, 7, 8]) times = np.array([0, 1, 2,]) pows = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]) freqs_new, t_new, pows_new = trim_spectrogram(freqs, times, pows, f_range=[6, 8], t_range=[0,1]) assert_equal(freqs_new, np.array([6, 7, 8])) assert_equal(t_new, np.array([0, 1])) assert_equal(pows_new, np.array([[4, 5], [7, 8], [10, 11]])) def test_rotate_powerlaw(): freqs = np.array([5, 6, 7, 8, 9]) pows = np.array([1, 2, 3, 4, 5]) d_exp = 1 pows_new = rotate_powerlaw(freqs, pows, d_exp) assert pows.shape == pows_new.shape
Add smoke test for trim_spectrogram
Add smoke test for trim_spectrogram
Python
apache-2.0
voytekresearch/neurodsp
"""Test the utility function from spectral.""" import numpy as np from numpy.testing import assert_equal from neurodsp.spectral.utils import * ################################################################################################### ################################################################################################### def test_trim_spectrum(): freqs = np.array([5, 6, 7, 8, 9]) pows = np.array([1, 2, 3, 4, 5]) freqs_new, pows_new = trim_spectrum(freqs, pows, [6, 8]) assert_equal(freqs_new, np.array([6, 7, 8])) assert_equal(pows_new, np.array([2, 3, 4])) + def test_trim_spectrogram(): + + freqs = np.array([5, 6, 7, 8]) + times = np.array([0, 1, 2,]) + pows = np.array([[1, 2, 3], + [4, 5, 6], + [7, 8, 9], + [10, 11, 12]]) + + freqs_new, t_new, pows_new = trim_spectrogram(freqs, times, pows, f_range=[6, 8], t_range=[0,1]) + assert_equal(freqs_new, np.array([6, 7, 8])) + assert_equal(t_new, np.array([0, 1])) + assert_equal(pows_new, np.array([[4, 5], [7, 8], [10, 11]])) + def test_rotate_powerlaw(): freqs = np.array([5, 6, 7, 8, 9]) pows = np.array([1, 2, 3, 4, 5]) d_exp = 1 pows_new = rotate_powerlaw(freqs, pows, d_exp) assert pows.shape == pows_new.shape
Add smoke test for trim_spectrogram
## Code Before: """Test the utility function from spectral.""" import numpy as np from numpy.testing import assert_equal from neurodsp.spectral.utils import * ################################################################################################### ################################################################################################### def test_trim_spectrum(): freqs = np.array([5, 6, 7, 8, 9]) pows = np.array([1, 2, 3, 4, 5]) freqs_new, pows_new = trim_spectrum(freqs, pows, [6, 8]) assert_equal(freqs_new, np.array([6, 7, 8])) assert_equal(pows_new, np.array([2, 3, 4])) def test_rotate_powerlaw(): freqs = np.array([5, 6, 7, 8, 9]) pows = np.array([1, 2, 3, 4, 5]) d_exp = 1 pows_new = rotate_powerlaw(freqs, pows, d_exp) assert pows.shape == pows_new.shape ## Instruction: Add smoke test for trim_spectrogram ## Code After: """Test the utility function from spectral.""" import numpy as np from numpy.testing import assert_equal from neurodsp.spectral.utils import * ################################################################################################### ################################################################################################### def test_trim_spectrum(): freqs = np.array([5, 6, 7, 8, 9]) pows = np.array([1, 2, 3, 4, 5]) freqs_new, pows_new = trim_spectrum(freqs, pows, [6, 8]) assert_equal(freqs_new, np.array([6, 7, 8])) assert_equal(pows_new, np.array([2, 3, 4])) def test_trim_spectrogram(): freqs = np.array([5, 6, 7, 8]) times = np.array([0, 1, 2,]) pows = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]) freqs_new, t_new, pows_new = trim_spectrogram(freqs, times, pows, f_range=[6, 8], t_range=[0,1]) assert_equal(freqs_new, np.array([6, 7, 8])) assert_equal(t_new, np.array([0, 1])) assert_equal(pows_new, np.array([[4, 5], [7, 8], [10, 11]])) def test_rotate_powerlaw(): freqs = np.array([5, 6, 7, 8, 9]) pows = np.array([1, 2, 3, 4, 5]) d_exp = 1 pows_new = rotate_powerlaw(freqs, pows, d_exp) assert pows.shape == pows_new.shape
# ... existing code ... assert_equal(pows_new, np.array([2, 3, 4])) def test_trim_spectrogram(): freqs = np.array([5, 6, 7, 8]) times = np.array([0, 1, 2,]) pows = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]) freqs_new, t_new, pows_new = trim_spectrogram(freqs, times, pows, f_range=[6, 8], t_range=[0,1]) assert_equal(freqs_new, np.array([6, 7, 8])) assert_equal(t_new, np.array([0, 1])) assert_equal(pows_new, np.array([[4, 5], [7, 8], [10, 11]])) def test_rotate_powerlaw(): # ... rest of the code ...
d01b09256f8fda4b222f3e26366817f4ac5b4c5a
zinnia/tests/test_admin_forms.py
zinnia/tests/test_admin_forms.py
"""Test cases for Zinnia's admin forms""" from django.test import TestCase from django.contrib.admin.widgets import RelatedFieldWidgetWrapper from zinnia.models import Category from zinnia.admin.forms import EntryAdminForm from zinnia.admin.forms import CategoryAdminForm class EntryAdminFormTestCase(TestCase): def test_categories_has_related_widget(self): form = EntryAdminForm() self.assertTrue( isinstance(form.fields['categories'].widget, RelatedFieldWidgetWrapper)) def test_initial_sites(self): form = EntryAdminForm() self.assertEqual( len(form.fields['sites'].initial), 1) class CategoryAdminFormTestCase(TestCase): def test_parent_has_related_widget(self): form = CategoryAdminForm() self.assertTrue( isinstance(form.fields['parent'].widget, RelatedFieldWidgetWrapper)) def test_clean_parent(self): category = Category.objects.create( title='Category 1', slug='cat-1') datas = {'parent': category.pk, 'title': category.title, 'slug': category.slug} form = CategoryAdminForm(datas, instance=category) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors['parent']), 1) subcategory = Category.objects.create( title='Category 2', slug='cat-2') self.assertEqual(subcategory.parent, None) datas = {'parent': category.pk, 'title': subcategory.title, 'slug': subcategory.slug} form = CategoryAdminForm(datas, instance=subcategory) self.assertTrue(form.is_valid())
"""Test cases for Zinnia's admin forms""" from django.test import TestCase from django.contrib.admin.widgets import RelatedFieldWidgetWrapper from zinnia.models import Category from zinnia.admin.forms import EntryAdminForm from zinnia.admin.forms import CategoryAdminForm class EntryAdminFormTestCase(TestCase): def test_categories_has_related_widget(self): form = EntryAdminForm() self.assertTrue( isinstance(form.fields['categories'].widget, RelatedFieldWidgetWrapper)) class CategoryAdminFormTestCase(TestCase): def test_parent_has_related_widget(self): form = CategoryAdminForm() self.assertTrue( isinstance(form.fields['parent'].widget, RelatedFieldWidgetWrapper)) def test_clean_parent(self): category = Category.objects.create( title='Category 1', slug='cat-1') datas = {'parent': category.pk, 'title': category.title, 'slug': category.slug} form = CategoryAdminForm(datas, instance=category) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors['parent']), 1) subcategory = Category.objects.create( title='Category 2', slug='cat-2') self.assertEqual(subcategory.parent, None) datas = {'parent': category.pk, 'title': subcategory.title, 'slug': subcategory.slug} form = CategoryAdminForm(datas, instance=subcategory) self.assertTrue(form.is_valid())
Remove now useless test for initial sites value in form
Remove now useless test for initial sites value in form
Python
bsd-3-clause
extertioner/django-blog-zinnia,Maplecroft/django-blog-zinnia,Zopieux/django-blog-zinnia,ghachey/django-blog-zinnia,dapeng0802/django-blog-zinnia,bywbilly/django-blog-zinnia,dapeng0802/django-blog-zinnia,Zopieux/django-blog-zinnia,aorzh/django-blog-zinnia,Zopieux/django-blog-zinnia,bywbilly/django-blog-zinnia,aorzh/django-blog-zinnia,aorzh/django-blog-zinnia,extertioner/django-blog-zinnia,ZuluPro/django-blog-zinnia,petecummings/django-blog-zinnia,Fantomas42/django-blog-zinnia,marctc/django-blog-zinnia,petecummings/django-blog-zinnia,ZuluPro/django-blog-zinnia,ZuluPro/django-blog-zinnia,Fantomas42/django-blog-zinnia,ghachey/django-blog-zinnia,Maplecroft/django-blog-zinnia,petecummings/django-blog-zinnia,marctc/django-blog-zinnia,bywbilly/django-blog-zinnia,extertioner/django-blog-zinnia,Maplecroft/django-blog-zinnia,Fantomas42/django-blog-zinnia,ghachey/django-blog-zinnia,dapeng0802/django-blog-zinnia,marctc/django-blog-zinnia
"""Test cases for Zinnia's admin forms""" from django.test import TestCase from django.contrib.admin.widgets import RelatedFieldWidgetWrapper from zinnia.models import Category from zinnia.admin.forms import EntryAdminForm from zinnia.admin.forms import CategoryAdminForm class EntryAdminFormTestCase(TestCase): def test_categories_has_related_widget(self): form = EntryAdminForm() self.assertTrue( isinstance(form.fields['categories'].widget, RelatedFieldWidgetWrapper)) - - def test_initial_sites(self): - form = EntryAdminForm() - self.assertEqual( - len(form.fields['sites'].initial), 1) class CategoryAdminFormTestCase(TestCase): def test_parent_has_related_widget(self): form = CategoryAdminForm() self.assertTrue( isinstance(form.fields['parent'].widget, RelatedFieldWidgetWrapper)) def test_clean_parent(self): category = Category.objects.create( title='Category 1', slug='cat-1') datas = {'parent': category.pk, 'title': category.title, 'slug': category.slug} form = CategoryAdminForm(datas, instance=category) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors['parent']), 1) subcategory = Category.objects.create( title='Category 2', slug='cat-2') self.assertEqual(subcategory.parent, None) datas = {'parent': category.pk, 'title': subcategory.title, 'slug': subcategory.slug} form = CategoryAdminForm(datas, instance=subcategory) self.assertTrue(form.is_valid())
Remove now useless test for initial sites value in form
## Code Before: """Test cases for Zinnia's admin forms""" from django.test import TestCase from django.contrib.admin.widgets import RelatedFieldWidgetWrapper from zinnia.models import Category from zinnia.admin.forms import EntryAdminForm from zinnia.admin.forms import CategoryAdminForm class EntryAdminFormTestCase(TestCase): def test_categories_has_related_widget(self): form = EntryAdminForm() self.assertTrue( isinstance(form.fields['categories'].widget, RelatedFieldWidgetWrapper)) def test_initial_sites(self): form = EntryAdminForm() self.assertEqual( len(form.fields['sites'].initial), 1) class CategoryAdminFormTestCase(TestCase): def test_parent_has_related_widget(self): form = CategoryAdminForm() self.assertTrue( isinstance(form.fields['parent'].widget, RelatedFieldWidgetWrapper)) def test_clean_parent(self): category = Category.objects.create( title='Category 1', slug='cat-1') datas = {'parent': category.pk, 'title': category.title, 'slug': category.slug} form = CategoryAdminForm(datas, instance=category) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors['parent']), 1) subcategory = Category.objects.create( title='Category 2', slug='cat-2') self.assertEqual(subcategory.parent, None) datas = {'parent': category.pk, 'title': subcategory.title, 'slug': subcategory.slug} form = CategoryAdminForm(datas, instance=subcategory) self.assertTrue(form.is_valid()) ## Instruction: Remove now useless test for initial sites value in form ## Code After: """Test cases for Zinnia's admin forms""" from django.test import TestCase from django.contrib.admin.widgets import RelatedFieldWidgetWrapper from zinnia.models import Category from zinnia.admin.forms import EntryAdminForm from zinnia.admin.forms import CategoryAdminForm class EntryAdminFormTestCase(TestCase): def test_categories_has_related_widget(self): form = EntryAdminForm() self.assertTrue( isinstance(form.fields['categories'].widget, RelatedFieldWidgetWrapper)) class CategoryAdminFormTestCase(TestCase): def test_parent_has_related_widget(self): form = CategoryAdminForm() self.assertTrue( isinstance(form.fields['parent'].widget, RelatedFieldWidgetWrapper)) def test_clean_parent(self): category = Category.objects.create( title='Category 1', slug='cat-1') datas = {'parent': category.pk, 'title': category.title, 'slug': category.slug} form = CategoryAdminForm(datas, instance=category) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors['parent']), 1) subcategory = Category.objects.create( title='Category 2', slug='cat-2') self.assertEqual(subcategory.parent, None) datas = {'parent': category.pk, 'title': subcategory.title, 'slug': subcategory.slug} form = CategoryAdminForm(datas, instance=subcategory) self.assertTrue(form.is_valid())
// ... existing code ... isinstance(form.fields['categories'].widget, RelatedFieldWidgetWrapper)) // ... rest of the code ...
3d86b4473f66a9311a94b1def4c40189eae23990
lancet/git.py
lancet/git.py
import sys import click from slugify import slugify class SlugBranchGetter(object): def __init__(self, base_branch='master'): self.base_branch = base_branch def __call__(self, repo, issue): discriminator = 'features/{}'.format(issue.key) slug = slugify(issue.fields.summary[:30]) full_name = '{}_{}'.format(discriminator, slug) branches = [b for b in repo.listall_branches() if b.startswith(discriminator)] if len(branches) > 1: click.secho('Multiple matching branches found!', fg='red', bold=True) click.echo() click.echo('The prefix {} matched the following branches:' .format(discriminator)) click.echo() for b in branches: click.echo(' {} {}'.format(click.style('*', fg='red'), b)) click.echo() click.echo('Please remove all but one in order to continue.') sys.exit(1) elif branches: branch = repo.lookup_branch(branches[0]) if branch.branch_name != full_name: branch.rename(full_name) branch = repo.lookup_branch(full_name) else: base = repo.lookup_branch(self.base_branch) if not base: click.secho('Base branch not found: "{}", aborting.' .format(self.base_branch), fg='red', bold=True) sys.exit(1) branch = repo.create_branch(full_name, base.get_object()) return branch
import sys import click from slugify import slugify class SlugBranchGetter(object): prefix = 'feature/' def __init__(self, base_branch='master'): self.base_branch = base_branch def __call__(self, repo, issue): discriminator = '{}{}'.format(self.prefix, issue.key) slug = slugify(issue.fields.summary[:30]) full_name = '{}_{}'.format(discriminator, slug) branches = [b for b in repo.listall_branches() if b.startswith(discriminator)] if len(branches) > 1: click.secho('Multiple matching branches found!', fg='red', bold=True) click.echo() click.echo('The prefix {} matched the following branches:' .format(discriminator)) click.echo() for b in branches: click.echo(' {} {}'.format(click.style('*', fg='red'), b)) click.echo() click.echo('Please remove all but one in order to continue.') sys.exit(1) elif branches: branch = repo.lookup_branch(branches[0]) if branch.branch_name != full_name: branch.rename(full_name) branch = repo.lookup_branch(full_name) else: base = repo.lookup_branch(self.base_branch) if not base: click.secho('Base branch not found: "{}", aborting.' .format(self.base_branch), fg='red', bold=True) sys.exit(1) branch = repo.create_branch(full_name, base.get_object()) return branch
Change the prefix from features/ to feature/.
Change the prefix from features/ to feature/.
Python
mit
GaretJax/lancet,GaretJax/lancet
import sys import click from slugify import slugify class SlugBranchGetter(object): + prefix = 'feature/' + def __init__(self, base_branch='master'): self.base_branch = base_branch def __call__(self, repo, issue): - discriminator = 'features/{}'.format(issue.key) + discriminator = '{}{}'.format(self.prefix, issue.key) slug = slugify(issue.fields.summary[:30]) full_name = '{}_{}'.format(discriminator, slug) branches = [b for b in repo.listall_branches() if b.startswith(discriminator)] if len(branches) > 1: click.secho('Multiple matching branches found!', fg='red', bold=True) click.echo() click.echo('The prefix {} matched the following branches:' .format(discriminator)) click.echo() for b in branches: click.echo(' {} {}'.format(click.style('*', fg='red'), b)) click.echo() click.echo('Please remove all but one in order to continue.') sys.exit(1) elif branches: branch = repo.lookup_branch(branches[0]) if branch.branch_name != full_name: branch.rename(full_name) branch = repo.lookup_branch(full_name) else: base = repo.lookup_branch(self.base_branch) if not base: click.secho('Base branch not found: "{}", aborting.' .format(self.base_branch), fg='red', bold=True) sys.exit(1) branch = repo.create_branch(full_name, base.get_object()) return branch
Change the prefix from features/ to feature/.
## Code Before: import sys import click from slugify import slugify class SlugBranchGetter(object): def __init__(self, base_branch='master'): self.base_branch = base_branch def __call__(self, repo, issue): discriminator = 'features/{}'.format(issue.key) slug = slugify(issue.fields.summary[:30]) full_name = '{}_{}'.format(discriminator, slug) branches = [b for b in repo.listall_branches() if b.startswith(discriminator)] if len(branches) > 1: click.secho('Multiple matching branches found!', fg='red', bold=True) click.echo() click.echo('The prefix {} matched the following branches:' .format(discriminator)) click.echo() for b in branches: click.echo(' {} {}'.format(click.style('*', fg='red'), b)) click.echo() click.echo('Please remove all but one in order to continue.') sys.exit(1) elif branches: branch = repo.lookup_branch(branches[0]) if branch.branch_name != full_name: branch.rename(full_name) branch = repo.lookup_branch(full_name) else: base = repo.lookup_branch(self.base_branch) if not base: click.secho('Base branch not found: "{}", aborting.' .format(self.base_branch), fg='red', bold=True) sys.exit(1) branch = repo.create_branch(full_name, base.get_object()) return branch ## Instruction: Change the prefix from features/ to feature/. ## Code After: import sys import click from slugify import slugify class SlugBranchGetter(object): prefix = 'feature/' def __init__(self, base_branch='master'): self.base_branch = base_branch def __call__(self, repo, issue): discriminator = '{}{}'.format(self.prefix, issue.key) slug = slugify(issue.fields.summary[:30]) full_name = '{}_{}'.format(discriminator, slug) branches = [b for b in repo.listall_branches() if b.startswith(discriminator)] if len(branches) > 1: click.secho('Multiple matching branches found!', fg='red', bold=True) click.echo() click.echo('The prefix {} matched the following branches:' .format(discriminator)) click.echo() for b in branches: click.echo(' {} {}'.format(click.style('*', fg='red'), b)) click.echo() click.echo('Please remove all but one in order to continue.') sys.exit(1) elif branches: branch = repo.lookup_branch(branches[0]) if branch.branch_name != full_name: branch.rename(full_name) branch = repo.lookup_branch(full_name) else: base = repo.lookup_branch(self.base_branch) if not base: click.secho('Base branch not found: "{}", aborting.' .format(self.base_branch), fg='red', bold=True) sys.exit(1) branch = repo.create_branch(full_name, base.get_object()) return branch
// ... existing code ... class SlugBranchGetter(object): prefix = 'feature/' def __init__(self, base_branch='master'): self.base_branch = base_branch // ... modified code ... def __call__(self, repo, issue): discriminator = '{}{}'.format(self.prefix, issue.key) slug = slugify(issue.fields.summary[:30]) full_name = '{}_{}'.format(discriminator, slug) // ... rest of the code ...
b400be73feba0b571ac6453841426db9a78dfa00
flowerconfig.py
flowerconfig.py
import os AMPQ_ADMIN_USERNAME = os.getenv('AMQP_ADMIN_USERNAME', 'guest') AMPQ_ADMIN_PASSWORD = os.getenv('AMQP_ADMIN_PASSWORD', 'guest') AMQP_ADMIN_HOST = os.getenv('AMQP_ADMIN_HOST', '172.17.42.1') AMQP_ADMIN_PORT = int(os.getenv('AMQP_ADMIN_PORT', '15672')) DEFAULT_BROKER_API = 'http://%s:%s@%s:%d/api/' \ % (AMPQ_ADMIN_USERNAME, AMPQ_ADMIN_PASSWORD, AMQP_ADMIN_HOST, AMQP_ADMIN_PORT) FLOWER_USERNAME = os.getenv('FLOWER_USERNAME', 'root') FLOWER_PASSWORD = os.getenv('FLOWER_PASSWORD', 'changeit') port = int(os.getenv('FLOWER_PORT', '5555')) broker_api = os.getenv('FLOWER_BROKER_API', DEFAULT_BROKER_API) max_tasks = int(os.getenv('FLOWER_MAX_TASKS', '3600')) basic_auth = [os.getenv('FLOWER_BASIC_AUTH', '%s:%s' % (FLOWER_USERNAME, FLOWER_PASSWORD))]
import os AMPQ_ADMIN_USERNAME = os.getenv('AMQP_ADMIN_USERNAME', 'guest') AMPQ_ADMIN_PASSWORD = os.getenv('AMQP_ADMIN_PASSWORD', 'guest') AMQP_ADMIN_HOST = os.getenv('AMQP_ADMIN_HOST', '172.17.42.1') AMQP_ADMIN_PORT = int(os.getenv('AMQP_ADMIN_PORT', '15672')) DEFAULT_BROKER_API = 'http://%s:%s@%s:%d/api/' \ % (AMPQ_ADMIN_USERNAME, AMPQ_ADMIN_PASSWORD, AMQP_ADMIN_HOST, AMQP_ADMIN_PORT) USERNAME = os.getenv('USERNAME', 'root') PASSWORD = os.getenv('PASSWORD', 'changeit') port = int(os.getenv('FLOWER_PORT', '5555')) broker_api = os.getenv('FLOWER_BROKER_API', DEFAULT_BROKER_API) max_tasks = int(os.getenv('FLOWER_MAX_TASKS', '3600')) basic_auth = [os.getenv('FLOWER_BASIC_AUTH', '%s:%s' % (USERNAME, PASSWORD))]
Remove FLOWER_ prefix for non flower based vars
Remove FLOWER_ prefix for non flower based vars
Python
mit
totem/celery-flower-docker,totem/celery-flower-docker
import os AMPQ_ADMIN_USERNAME = os.getenv('AMQP_ADMIN_USERNAME', 'guest') AMPQ_ADMIN_PASSWORD = os.getenv('AMQP_ADMIN_PASSWORD', 'guest') AMQP_ADMIN_HOST = os.getenv('AMQP_ADMIN_HOST', '172.17.42.1') AMQP_ADMIN_PORT = int(os.getenv('AMQP_ADMIN_PORT', '15672')) DEFAULT_BROKER_API = 'http://%s:%s@%s:%d/api/' \ % (AMPQ_ADMIN_USERNAME, AMPQ_ADMIN_PASSWORD, AMQP_ADMIN_HOST, AMQP_ADMIN_PORT) - FLOWER_USERNAME = os.getenv('FLOWER_USERNAME', 'root') + USERNAME = os.getenv('USERNAME', 'root') - FLOWER_PASSWORD = os.getenv('FLOWER_PASSWORD', 'changeit') + PASSWORD = os.getenv('PASSWORD', 'changeit') port = int(os.getenv('FLOWER_PORT', '5555')) broker_api = os.getenv('FLOWER_BROKER_API', DEFAULT_BROKER_API) max_tasks = int(os.getenv('FLOWER_MAX_TASKS', '3600')) basic_auth = [os.getenv('FLOWER_BASIC_AUTH', '%s:%s' - % (FLOWER_USERNAME, FLOWER_PASSWORD))] + % (USERNAME, PASSWORD))]
Remove FLOWER_ prefix for non flower based vars
## Code Before: import os AMPQ_ADMIN_USERNAME = os.getenv('AMQP_ADMIN_USERNAME', 'guest') AMPQ_ADMIN_PASSWORD = os.getenv('AMQP_ADMIN_PASSWORD', 'guest') AMQP_ADMIN_HOST = os.getenv('AMQP_ADMIN_HOST', '172.17.42.1') AMQP_ADMIN_PORT = int(os.getenv('AMQP_ADMIN_PORT', '15672')) DEFAULT_BROKER_API = 'http://%s:%s@%s:%d/api/' \ % (AMPQ_ADMIN_USERNAME, AMPQ_ADMIN_PASSWORD, AMQP_ADMIN_HOST, AMQP_ADMIN_PORT) FLOWER_USERNAME = os.getenv('FLOWER_USERNAME', 'root') FLOWER_PASSWORD = os.getenv('FLOWER_PASSWORD', 'changeit') port = int(os.getenv('FLOWER_PORT', '5555')) broker_api = os.getenv('FLOWER_BROKER_API', DEFAULT_BROKER_API) max_tasks = int(os.getenv('FLOWER_MAX_TASKS', '3600')) basic_auth = [os.getenv('FLOWER_BASIC_AUTH', '%s:%s' % (FLOWER_USERNAME, FLOWER_PASSWORD))] ## Instruction: Remove FLOWER_ prefix for non flower based vars ## Code After: import os AMPQ_ADMIN_USERNAME = os.getenv('AMQP_ADMIN_USERNAME', 'guest') AMPQ_ADMIN_PASSWORD = os.getenv('AMQP_ADMIN_PASSWORD', 'guest') AMQP_ADMIN_HOST = os.getenv('AMQP_ADMIN_HOST', '172.17.42.1') AMQP_ADMIN_PORT = int(os.getenv('AMQP_ADMIN_PORT', '15672')) DEFAULT_BROKER_API = 'http://%s:%s@%s:%d/api/' \ % (AMPQ_ADMIN_USERNAME, AMPQ_ADMIN_PASSWORD, AMQP_ADMIN_HOST, AMQP_ADMIN_PORT) USERNAME = os.getenv('USERNAME', 'root') PASSWORD = os.getenv('PASSWORD', 'changeit') port = int(os.getenv('FLOWER_PORT', '5555')) broker_api = os.getenv('FLOWER_BROKER_API', DEFAULT_BROKER_API) max_tasks = int(os.getenv('FLOWER_MAX_TASKS', '3600')) basic_auth = [os.getenv('FLOWER_BASIC_AUTH', '%s:%s' % (USERNAME, PASSWORD))]
... % (AMPQ_ADMIN_USERNAME, AMPQ_ADMIN_PASSWORD, AMQP_ADMIN_HOST, AMQP_ADMIN_PORT) USERNAME = os.getenv('USERNAME', 'root') PASSWORD = os.getenv('PASSWORD', 'changeit') port = int(os.getenv('FLOWER_PORT', '5555')) ... max_tasks = int(os.getenv('FLOWER_MAX_TASKS', '3600')) basic_auth = [os.getenv('FLOWER_BASIC_AUTH', '%s:%s' % (USERNAME, PASSWORD))] ...
7a735bebf195f766a0db97b3fba6793a69a5731a
microcosm_elasticsearch/main.py
microcosm_elasticsearch/main.py
from argparse import ArgumentParser def createall_main(graph): """ Initialize indexes and mappings. """ parser = ArgumentParser() parser.add_argument("--only", action="append") parser.add_argument("--skip", action="append") parser.add_argument("-D", "--drop", action="store_true") args = parser.parse_args() graph.elasticsearch_index_registry.createall( force=args.drop, only=args.only, skip=args.skip, )
from argparse import ArgumentParser from json import dump, loads from sys import stdout def createall_main(graph): """ Initialize indexes and mappings. """ parser = ArgumentParser() parser.add_argument("--only", action="append") parser.add_argument("--skip", action="append") parser.add_argument("-D", "--drop", action="store_true") args = parser.parse_args() graph.elasticsearch_index_registry.createall( force=args.drop, only=args.only, skip=args.skip, ) def query_main(graph, default_index): parser = ArgumentParser() parser.add_argument("--index", default=default_index) parser.add_argument("--query", default='{"match_all": {}}') args = parser.parse_args() try: query = loads(args.query) except: parser.error("query must be valid json") response = graph.elasticsearch_client.search( index=args.index, body=dict(query=query), ) dump(response, stdout)
Add a query entry point
Add a query entry point
Python
apache-2.0
globality-corp/microcosm-elasticsearch,globality-corp/microcosm-elasticsearch
from argparse import ArgumentParser + from json import dump, loads + from sys import stdout def createall_main(graph): """ Initialize indexes and mappings. """ parser = ArgumentParser() parser.add_argument("--only", action="append") parser.add_argument("--skip", action="append") parser.add_argument("-D", "--drop", action="store_true") args = parser.parse_args() graph.elasticsearch_index_registry.createall( force=args.drop, only=args.only, skip=args.skip, ) + + def query_main(graph, default_index): + parser = ArgumentParser() + parser.add_argument("--index", default=default_index) + parser.add_argument("--query", default='{"match_all": {}}') + args = parser.parse_args() + + try: + query = loads(args.query) + except: + parser.error("query must be valid json") + + response = graph.elasticsearch_client.search( + index=args.index, + body=dict(query=query), + ) + dump(response, stdout) +
Add a query entry point
## Code Before: from argparse import ArgumentParser def createall_main(graph): """ Initialize indexes and mappings. """ parser = ArgumentParser() parser.add_argument("--only", action="append") parser.add_argument("--skip", action="append") parser.add_argument("-D", "--drop", action="store_true") args = parser.parse_args() graph.elasticsearch_index_registry.createall( force=args.drop, only=args.only, skip=args.skip, ) ## Instruction: Add a query entry point ## Code After: from argparse import ArgumentParser from json import dump, loads from sys import stdout def createall_main(graph): """ Initialize indexes and mappings. """ parser = ArgumentParser() parser.add_argument("--only", action="append") parser.add_argument("--skip", action="append") parser.add_argument("-D", "--drop", action="store_true") args = parser.parse_args() graph.elasticsearch_index_registry.createall( force=args.drop, only=args.only, skip=args.skip, ) def query_main(graph, default_index): parser = ArgumentParser() parser.add_argument("--index", default=default_index) parser.add_argument("--query", default='{"match_all": {}}') args = parser.parse_args() try: query = loads(args.query) except: parser.error("query must be valid json") response = graph.elasticsearch_client.search( index=args.index, body=dict(query=query), ) dump(response, stdout)
... from argparse import ArgumentParser from json import dump, loads from sys import stdout ... skip=args.skip, ) def query_main(graph, default_index): parser = ArgumentParser() parser.add_argument("--index", default=default_index) parser.add_argument("--query", default='{"match_all": {}}') args = parser.parse_args() try: query = loads(args.query) except: parser.error("query must be valid json") response = graph.elasticsearch_client.search( index=args.index, body=dict(query=query), ) dump(response, stdout) ...
f94bc30004aa9977bac652d337f69069efc132bd
marmoset/pxe/__init__.py
marmoset/pxe/__init__.py
from .label import Label from .client_config import ClientConfig def create(args): pxe_client = ClientConfig(args.ip_address, args.password, args.script) pxe_client.create(Label.find(args.label)) msg = 'Created %s with password %s' print(msg % (pxe_client.file_path(), pxe_client.password)) def list(args): for pxe_client in ClientConfig.all(): print('%s: %s' % (pxe_client.ip_address, pxe_client.label)) def remove(args): pxe_client = ClientConfig(args.ip_address) if pxe_client.remove(): print('Removed', pxe_client.file_path()) else: print('No entry found for', pxe_client.ip_address)
from .label import Label from .client_config import ClientConfig def create(args): pxe_client = ClientConfig(args.ip_address, args.password, args.script) used_options = pxe_client.create(Label.find(args.label)) msg = 'Created %s with following Options:' print(msg % pxe_client.file_path()) for option in used_options: print("\t%s" % option) def list(args): for pxe_client in ClientConfig.all(): print('%s: %s' % (pxe_client.ip_address, pxe_client.label)) def remove(args): pxe_client = ClientConfig(args.ip_address) if pxe_client.remove(): print('Removed', pxe_client.file_path()) else: print('No entry found for', pxe_client.ip_address)
Implement better result output for pxe config file crete
Implement better result output for pxe config file crete
Python
agpl-3.0
aibor/marmoset
from .label import Label from .client_config import ClientConfig def create(args): pxe_client = ClientConfig(args.ip_address, args.password, args.script) - pxe_client.create(Label.find(args.label)) + used_options = pxe_client.create(Label.find(args.label)) - msg = 'Created %s with password %s' + + msg = 'Created %s with following Options:' + - print(msg % (pxe_client.file_path(), pxe_client.password)) + print(msg % pxe_client.file_path()) + for option in used_options: + print("\t%s" % option) def list(args): for pxe_client in ClientConfig.all(): print('%s: %s' % (pxe_client.ip_address, pxe_client.label)) def remove(args): pxe_client = ClientConfig(args.ip_address) if pxe_client.remove(): print('Removed', pxe_client.file_path()) else: print('No entry found for', pxe_client.ip_address)
Implement better result output for pxe config file crete
## Code Before: from .label import Label from .client_config import ClientConfig def create(args): pxe_client = ClientConfig(args.ip_address, args.password, args.script) pxe_client.create(Label.find(args.label)) msg = 'Created %s with password %s' print(msg % (pxe_client.file_path(), pxe_client.password)) def list(args): for pxe_client in ClientConfig.all(): print('%s: %s' % (pxe_client.ip_address, pxe_client.label)) def remove(args): pxe_client = ClientConfig(args.ip_address) if pxe_client.remove(): print('Removed', pxe_client.file_path()) else: print('No entry found for', pxe_client.ip_address) ## Instruction: Implement better result output for pxe config file crete ## Code After: from .label import Label from .client_config import ClientConfig def create(args): pxe_client = ClientConfig(args.ip_address, args.password, args.script) used_options = pxe_client.create(Label.find(args.label)) msg = 'Created %s with following Options:' print(msg % pxe_client.file_path()) for option in used_options: print("\t%s" % option) def list(args): for pxe_client in ClientConfig.all(): print('%s: %s' % (pxe_client.ip_address, pxe_client.label)) def remove(args): pxe_client = ClientConfig(args.ip_address) if pxe_client.remove(): print('Removed', pxe_client.file_path()) else: print('No entry found for', pxe_client.ip_address)
# ... existing code ... def create(args): pxe_client = ClientConfig(args.ip_address, args.password, args.script) used_options = pxe_client.create(Label.find(args.label)) msg = 'Created %s with following Options:' print(msg % pxe_client.file_path()) for option in used_options: print("\t%s" % option) # ... rest of the code ...
d6433001f3660c9c4506fe5e1f62c0a52edd02f7
project/djenerator/tests.py
project/djenerator/tests.py
from django.test import TestCase
from django.test import TestCase from model_reader import is_instance_of_model from models import ExtendingModel from models import NotExtendingModel from models import TestModel0 from models import TestModel1 from models import TestModelA from models import TestModelB from models import TestModelC from models import TestModelD from models import TestModelE from models import TestModelX from models import TestModelY class TestInstanceOfModel(TestCase): def test(self): models = [TestModel0, TestModel1, TestModelA, TestModelB, TestModelC, TestModelD, TestModelE, TestModelX, TestModelY, ExtendingModel] for model in models: self.assertTrue(is_instance_of_model(model)) self.assertFalse(is_instance_of_model(NotExtendingModel)) def not_extending_model_function(): pass self.assertFalse(is_instance_of_model(not_extending_model_function))
Test Cases for is instance of Model function
Test Cases for is instance of Model function
Python
mit
mostafa-mahmoud/djenerator,aelguindy/djenerator,mostafa-mahmoud/djenerator
from django.test import TestCase + from model_reader import is_instance_of_model + from models import ExtendingModel + from models import NotExtendingModel + from models import TestModel0 + from models import TestModel1 + from models import TestModelA + from models import TestModelB + from models import TestModelC + from models import TestModelD + from models import TestModelE + from models import TestModelX + from models import TestModelY + class TestInstanceOfModel(TestCase): + def test(self): + models = [TestModel0, TestModel1, TestModelA, TestModelB, TestModelC, + TestModelD, TestModelE, TestModelX, TestModelY, ExtendingModel] + for model in models: + self.assertTrue(is_instance_of_model(model)) + self.assertFalse(is_instance_of_model(NotExtendingModel)) + def not_extending_model_function(): + pass + + self.assertFalse(is_instance_of_model(not_extending_model_function)) + + + +
Test Cases for is instance of Model function
## Code Before: from django.test import TestCase ## Instruction: Test Cases for is instance of Model function ## Code After: from django.test import TestCase from model_reader import is_instance_of_model from models import ExtendingModel from models import NotExtendingModel from models import TestModel0 from models import TestModel1 from models import TestModelA from models import TestModelB from models import TestModelC from models import TestModelD from models import TestModelE from models import TestModelX from models import TestModelY class TestInstanceOfModel(TestCase): def test(self): models = [TestModel0, TestModel1, TestModelA, TestModelB, TestModelC, TestModelD, TestModelE, TestModelX, TestModelY, ExtendingModel] for model in models: self.assertTrue(is_instance_of_model(model)) self.assertFalse(is_instance_of_model(NotExtendingModel)) def not_extending_model_function(): pass self.assertFalse(is_instance_of_model(not_extending_model_function))
... from django.test import TestCase from model_reader import is_instance_of_model from models import ExtendingModel from models import NotExtendingModel from models import TestModel0 from models import TestModel1 from models import TestModelA from models import TestModelB from models import TestModelC from models import TestModelD from models import TestModelE from models import TestModelX from models import TestModelY class TestInstanceOfModel(TestCase): def test(self): models = [TestModel0, TestModel1, TestModelA, TestModelB, TestModelC, TestModelD, TestModelE, TestModelX, TestModelY, ExtendingModel] for model in models: self.assertTrue(is_instance_of_model(model)) self.assertFalse(is_instance_of_model(NotExtendingModel)) def not_extending_model_function(): pass self.assertFalse(is_instance_of_model(not_extending_model_function)) ...
bfc7e08ba70ba0e3acb9e4cc69b70c816845b6cb
djofx/views/home.py
djofx/views/home.py
from django.db.models import Sum from django.views.generic import TemplateView from djofx.forms import OFXForm from djofx.views.base import PageTitleMixin, UserRequiredMixin from djofx import models class HomePageView(PageTitleMixin, UserRequiredMixin, TemplateView): template_name = "djofx/home.html" def get_context_data(self, **kwargs): context = super(HomePageView, self).get_context_data(**kwargs) context['accounts'] = models.Account.objects.filter( owner=self.request.user ) context['form'] = OFXForm() breakdown = models.Transaction.objects.filter( amount__lt=0, transaction_category__is_void=False ).values( 'transaction_category__pk', 'transaction_category__name' ).annotate( total=Sum('amount') ).order_by('-total') context['breakdown'] = [ ( abs(item['total']), item['transaction_category__pk'], item['transaction_category__name'] ) for item in breakdown ] return context
from datetime import date, timedelta from django.db.models import Sum from django.views.generic import TemplateView from djofx.forms import OFXForm from djofx.views.base import PageTitleMixin, UserRequiredMixin from djofx import models from operator import itemgetter class HomePageView(PageTitleMixin, UserRequiredMixin, TemplateView): template_name = "djofx/home.html" def get_context_data(self, **kwargs): context = super(HomePageView, self).get_context_data(**kwargs) context['accounts'] = models.Account.objects.filter( owner=self.request.user ) context['form'] = OFXForm() cutoff = date.today() - timedelta(days=120) uncategorised_breakdown = models.Transaction.objects.filter( amount__lt=0, transaction_category__isnull=True, date__gte=cutoff ).aggregate( total=Sum('amount') ) breakdown = models.Transaction.objects.filter( amount__lt=0, transaction_category__is_void=False, date__gte=cutoff ).values( 'transaction_category__pk', 'transaction_category__name' ).annotate( total=Sum('amount') ).order_by('-total') context['breakdown'] = [ ( abs(item['total']), item['transaction_category__pk'], item['transaction_category__name'] ) for item in breakdown ] context['breakdown'].append( ( uncategorised_breakdown['total'] * -1, 0, 'Uncategorised' ) ) context['breakdown'] = sorted(context['breakdown'], key=itemgetter(0), reverse=True) return context
Include uncategorised spending in overview pie chart
Include uncategorised spending in overview pie chart Also, only show last 120 days
Python
mit
dominicrodger/djofx,dominicrodger/djofx,dominicrodger/djofx
+ from datetime import date, timedelta from django.db.models import Sum from django.views.generic import TemplateView from djofx.forms import OFXForm from djofx.views.base import PageTitleMixin, UserRequiredMixin from djofx import models + from operator import itemgetter class HomePageView(PageTitleMixin, UserRequiredMixin, TemplateView): template_name = "djofx/home.html" def get_context_data(self, **kwargs): context = super(HomePageView, self).get_context_data(**kwargs) context['accounts'] = models.Account.objects.filter( owner=self.request.user ) context['form'] = OFXForm() + cutoff = date.today() - timedelta(days=120) + + uncategorised_breakdown = models.Transaction.objects.filter( + amount__lt=0, + transaction_category__isnull=True, + date__gte=cutoff + ).aggregate( + total=Sum('amount') + ) + breakdown = models.Transaction.objects.filter( amount__lt=0, - transaction_category__is_void=False + transaction_category__is_void=False, + date__gte=cutoff ).values( 'transaction_category__pk', 'transaction_category__name' ).annotate( total=Sum('amount') ).order_by('-total') + context['breakdown'] = [ ( abs(item['total']), item['transaction_category__pk'], item['transaction_category__name'] ) for item in breakdown ] + context['breakdown'].append( + ( + uncategorised_breakdown['total'] * -1, + 0, + 'Uncategorised' + ) + ) + context['breakdown'] = sorted(context['breakdown'], + key=itemgetter(0), + reverse=True) return context
Include uncategorised spending in overview pie chart
## Code Before: from django.db.models import Sum from django.views.generic import TemplateView from djofx.forms import OFXForm from djofx.views.base import PageTitleMixin, UserRequiredMixin from djofx import models class HomePageView(PageTitleMixin, UserRequiredMixin, TemplateView): template_name = "djofx/home.html" def get_context_data(self, **kwargs): context = super(HomePageView, self).get_context_data(**kwargs) context['accounts'] = models.Account.objects.filter( owner=self.request.user ) context['form'] = OFXForm() breakdown = models.Transaction.objects.filter( amount__lt=0, transaction_category__is_void=False ).values( 'transaction_category__pk', 'transaction_category__name' ).annotate( total=Sum('amount') ).order_by('-total') context['breakdown'] = [ ( abs(item['total']), item['transaction_category__pk'], item['transaction_category__name'] ) for item in breakdown ] return context ## Instruction: Include uncategorised spending in overview pie chart ## Code After: from datetime import date, timedelta from django.db.models import Sum from django.views.generic import TemplateView from djofx.forms import OFXForm from djofx.views.base import PageTitleMixin, UserRequiredMixin from djofx import models from operator import itemgetter class HomePageView(PageTitleMixin, UserRequiredMixin, TemplateView): template_name = "djofx/home.html" def get_context_data(self, **kwargs): context = super(HomePageView, self).get_context_data(**kwargs) context['accounts'] = models.Account.objects.filter( owner=self.request.user ) context['form'] = OFXForm() cutoff = date.today() - timedelta(days=120) uncategorised_breakdown = models.Transaction.objects.filter( amount__lt=0, transaction_category__isnull=True, date__gte=cutoff ).aggregate( total=Sum('amount') ) breakdown = models.Transaction.objects.filter( amount__lt=0, transaction_category__is_void=False, date__gte=cutoff ).values( 'transaction_category__pk', 'transaction_category__name' ).annotate( total=Sum('amount') ).order_by('-total') context['breakdown'] = [ ( abs(item['total']), item['transaction_category__pk'], item['transaction_category__name'] ) for item in breakdown ] context['breakdown'].append( ( uncategorised_breakdown['total'] * -1, 0, 'Uncategorised' ) ) context['breakdown'] = sorted(context['breakdown'], key=itemgetter(0), reverse=True) return context
// ... existing code ... from datetime import date, timedelta from django.db.models import Sum from django.views.generic import TemplateView // ... modified code ... from djofx.views.base import PageTitleMixin, UserRequiredMixin from djofx import models from operator import itemgetter ... context['form'] = OFXForm() cutoff = date.today() - timedelta(days=120) uncategorised_breakdown = models.Transaction.objects.filter( amount__lt=0, transaction_category__isnull=True, date__gte=cutoff ).aggregate( total=Sum('amount') ) breakdown = models.Transaction.objects.filter( amount__lt=0, transaction_category__is_void=False, date__gte=cutoff ).values( 'transaction_category__pk', ... total=Sum('amount') ).order_by('-total') context['breakdown'] = [ ( ... for item in breakdown ] context['breakdown'].append( ( uncategorised_breakdown['total'] * -1, 0, 'Uncategorised' ) ) context['breakdown'] = sorted(context['breakdown'], key=itemgetter(0), reverse=True) return context // ... rest of the code ...
0563882d0d1bfdf4e64a65bcd91e8d6d4ab6ed8f
core/polyaxon/polypod/compiler/lineage/artifacts_collector.py
core/polyaxon/polypod/compiler/lineage/artifacts_collector.py
import os from typing import Optional from polyaxon.utils.fqn_utils import to_fqn_name from traceml.artifacts import V1ArtifactKind, V1RunArtifact def collect_lineage_artifacts_path(artifact_path: str) -> Optional[V1RunArtifact]: name = os.path.basename(artifact_path.rstrip("/")) # Trim handles cases like `foo/` -> '' return V1RunArtifact( name=to_fqn_name(name), kind=V1ArtifactKind.DIR, path=artifact_path, summary={"path": artifact_path}, is_input=True, )
import os from typing import Optional from polyaxon.utils.fqn_utils import to_fqn_name from traceml.artifacts import V1ArtifactKind, V1RunArtifact def collect_lineage_artifacts_path(artifact_path: str) -> Optional[V1RunArtifact]: name = os.path.basename(artifact_path.rstrip("/")) # Trim handles cases like `foo/` -> '' return V1RunArtifact( name=to_fqn_name(name) if name else "_", kind=V1ArtifactKind.DIR, path=artifact_path, summary={"path": artifact_path}, is_input=True, )
Fix artifacts name sanitization for root folders
Fix artifacts name sanitization for root folders
Python
apache-2.0
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
import os from typing import Optional from polyaxon.utils.fqn_utils import to_fqn_name from traceml.artifacts import V1ArtifactKind, V1RunArtifact def collect_lineage_artifacts_path(artifact_path: str) -> Optional[V1RunArtifact]: name = os.path.basename(artifact_path.rstrip("/")) # Trim handles cases like `foo/` -> '' return V1RunArtifact( - name=to_fqn_name(name), + name=to_fqn_name(name) if name else "_", kind=V1ArtifactKind.DIR, path=artifact_path, summary={"path": artifact_path}, is_input=True, )
Fix artifacts name sanitization for root folders
## Code Before: import os from typing import Optional from polyaxon.utils.fqn_utils import to_fqn_name from traceml.artifacts import V1ArtifactKind, V1RunArtifact def collect_lineage_artifacts_path(artifact_path: str) -> Optional[V1RunArtifact]: name = os.path.basename(artifact_path.rstrip("/")) # Trim handles cases like `foo/` -> '' return V1RunArtifact( name=to_fqn_name(name), kind=V1ArtifactKind.DIR, path=artifact_path, summary={"path": artifact_path}, is_input=True, ) ## Instruction: Fix artifacts name sanitization for root folders ## Code After: import os from typing import Optional from polyaxon.utils.fqn_utils import to_fqn_name from traceml.artifacts import V1ArtifactKind, V1RunArtifact def collect_lineage_artifacts_path(artifact_path: str) -> Optional[V1RunArtifact]: name = os.path.basename(artifact_path.rstrip("/")) # Trim handles cases like `foo/` -> '' return V1RunArtifact( name=to_fqn_name(name) if name else "_", kind=V1ArtifactKind.DIR, path=artifact_path, summary={"path": artifact_path}, is_input=True, )
... name = os.path.basename(artifact_path.rstrip("/")) # Trim handles cases like `foo/` -> '' return V1RunArtifact( name=to_fqn_name(name) if name else "_", kind=V1ArtifactKind.DIR, path=artifact_path, ...
7a7856d9ec56de91325c7bf7c62ff25c0241badc
tests/test_connect.py
tests/test_connect.py
import pypuppetdb def test_connect_api(): puppetdb = pypuppetdb.connect() assert puppetdb.version == 'v4'
import pypuppetdb def test_connect_api(): puppetdb = pypuppetdb.connect() assert puppetdb.version == 'v4' def test_connect_with_statement(): with pypuppetdb.connect() as puppetdb: assert puppetdb.version == 'v4'
Add test for creating connection with 'with' statement.
Add test for creating connection with 'with' statement.
Python
apache-2.0
puppet-community/pypuppetdb,voxpupuli/pypuppetdb
import pypuppetdb def test_connect_api(): puppetdb = pypuppetdb.connect() assert puppetdb.version == 'v4' + + def test_connect_with_statement(): + with pypuppetdb.connect() as puppetdb: + assert puppetdb.version == 'v4' +
Add test for creating connection with 'with' statement.
## Code Before: import pypuppetdb def test_connect_api(): puppetdb = pypuppetdb.connect() assert puppetdb.version == 'v4' ## Instruction: Add test for creating connection with 'with' statement. ## Code After: import pypuppetdb def test_connect_api(): puppetdb = pypuppetdb.connect() assert puppetdb.version == 'v4' def test_connect_with_statement(): with pypuppetdb.connect() as puppetdb: assert puppetdb.version == 'v4'
// ... existing code ... puppetdb = pypuppetdb.connect() assert puppetdb.version == 'v4' def test_connect_with_statement(): with pypuppetdb.connect() as puppetdb: assert puppetdb.version == 'v4' // ... rest of the code ...
59789bae7df5de6d7568a1b372b95a891fd5c3a2
confluent_server/confluent/userutil.py
confluent_server/confluent/userutil.py
from ctypes import * from ctypes.util import find_library import grp import pwd import os libc = cdll.LoadLibrary(find_library('libc')) _getgrouplist = libc.getgrouplist _getgrouplist.restype = c_int32 class TooSmallException(Exception): def __init__(self, count): self.count = count super(TooSmallException, self).__init__() def getgrouplist(name, gid, ng=32): _getgrouplist.argtypes = [c_char_p, c_uint, POINTER(c_uint * ng), POINTER(c_int)] glist = (c_uint * ng)() nglist = c_int(ng) count = _getgrouplist(name, gid, byref(glist), byref(nglist)) if count < 0: raise TooSmallException(nglist.value) for gidx in range(count): gent = glist[gidx] yield grp.getgrgid(gent).gr_name def grouplist(username): pent = pwd.getpwnam(username) try: groups = getgrouplist(pent.pw_name, pent.pw_gid) except TooSmallException as e: groups = getgrouplist(pent.pw_name, pent.pw_gid, e.count) return list(groups) if __name__ == '__main__': import sys print(repr(grouplist(sys.argv[1])))
from ctypes import * from ctypes.util import find_library import grp import pwd import os libc = cdll.LoadLibrary(find_library('libc')) _getgrouplist = libc.getgrouplist _getgrouplist.restype = c_int32 class TooSmallException(Exception): def __init__(self, count): self.count = count super(TooSmallException, self).__init__() def getgrouplist(name, gid, ng=32): _getgrouplist.argtypes = [c_char_p, c_uint, POINTER(c_uint * ng), POINTER(c_int)] glist = (c_uint * ng)() nglist = c_int(ng) if not isinstance(name, bytes): name = name.encode('utf-8') count = _getgrouplist(name, gid, byref(glist), byref(nglist)) if count < 0: raise TooSmallException(nglist.value) for gidx in range(count): gent = glist[gidx] yield grp.getgrgid(gent).gr_name def grouplist(username): pent = pwd.getpwnam(username) try: groups = getgrouplist(pent.pw_name, pent.pw_gid) except TooSmallException as e: groups = getgrouplist(pent.pw_name, pent.pw_gid, e.count) return list(groups) if __name__ == '__main__': import sys print(repr(grouplist(sys.argv[1])))
Fix python3 ctypes str usage
Fix python3 ctypes str usage In python3, the string is likely to be unicode and incompatible with the libc function. If it isn't bytes, force it to be bytes.
Python
apache-2.0
xcat2/confluent,xcat2/confluent,jjohnson42/confluent,xcat2/confluent,jjohnson42/confluent,jjohnson42/confluent,xcat2/confluent,xcat2/confluent,jjohnson42/confluent,jjohnson42/confluent
from ctypes import * from ctypes.util import find_library import grp import pwd import os libc = cdll.LoadLibrary(find_library('libc')) _getgrouplist = libc.getgrouplist _getgrouplist.restype = c_int32 class TooSmallException(Exception): def __init__(self, count): self.count = count super(TooSmallException, self).__init__() def getgrouplist(name, gid, ng=32): _getgrouplist.argtypes = [c_char_p, c_uint, POINTER(c_uint * ng), POINTER(c_int)] glist = (c_uint * ng)() nglist = c_int(ng) + if not isinstance(name, bytes): + name = name.encode('utf-8') count = _getgrouplist(name, gid, byref(glist), byref(nglist)) if count < 0: raise TooSmallException(nglist.value) for gidx in range(count): gent = glist[gidx] yield grp.getgrgid(gent).gr_name def grouplist(username): pent = pwd.getpwnam(username) try: groups = getgrouplist(pent.pw_name, pent.pw_gid) except TooSmallException as e: groups = getgrouplist(pent.pw_name, pent.pw_gid, e.count) return list(groups) if __name__ == '__main__': import sys print(repr(grouplist(sys.argv[1])))
Fix python3 ctypes str usage
## Code Before: from ctypes import * from ctypes.util import find_library import grp import pwd import os libc = cdll.LoadLibrary(find_library('libc')) _getgrouplist = libc.getgrouplist _getgrouplist.restype = c_int32 class TooSmallException(Exception): def __init__(self, count): self.count = count super(TooSmallException, self).__init__() def getgrouplist(name, gid, ng=32): _getgrouplist.argtypes = [c_char_p, c_uint, POINTER(c_uint * ng), POINTER(c_int)] glist = (c_uint * ng)() nglist = c_int(ng) count = _getgrouplist(name, gid, byref(glist), byref(nglist)) if count < 0: raise TooSmallException(nglist.value) for gidx in range(count): gent = glist[gidx] yield grp.getgrgid(gent).gr_name def grouplist(username): pent = pwd.getpwnam(username) try: groups = getgrouplist(pent.pw_name, pent.pw_gid) except TooSmallException as e: groups = getgrouplist(pent.pw_name, pent.pw_gid, e.count) return list(groups) if __name__ == '__main__': import sys print(repr(grouplist(sys.argv[1]))) ## Instruction: Fix python3 ctypes str usage ## Code After: from ctypes import * from ctypes.util import find_library import grp import pwd import os libc = cdll.LoadLibrary(find_library('libc')) _getgrouplist = libc.getgrouplist _getgrouplist.restype = c_int32 class TooSmallException(Exception): def __init__(self, count): self.count = count super(TooSmallException, self).__init__() def getgrouplist(name, gid, ng=32): _getgrouplist.argtypes = [c_char_p, c_uint, POINTER(c_uint * ng), POINTER(c_int)] glist = (c_uint * ng)() nglist = c_int(ng) if not isinstance(name, bytes): name = name.encode('utf-8') count = _getgrouplist(name, gid, byref(glist), byref(nglist)) if count < 0: raise TooSmallException(nglist.value) for gidx in range(count): gent = glist[gidx] yield grp.getgrgid(gent).gr_name def grouplist(username): pent = pwd.getpwnam(username) try: groups = getgrouplist(pent.pw_name, pent.pw_gid) except TooSmallException as e: groups = getgrouplist(pent.pw_name, pent.pw_gid, e.count) return list(groups) if __name__ == '__main__': import sys print(repr(grouplist(sys.argv[1])))
// ... existing code ... glist = (c_uint * ng)() nglist = c_int(ng) if not isinstance(name, bytes): name = name.encode('utf-8') count = _getgrouplist(name, gid, byref(glist), byref(nglist)) if count < 0: // ... rest of the code ...
93c978ba422b26971180a4277a0b69e82848ee78
src/yunohost/data_migrations/0009_migrate_to_apps_json.py
src/yunohost/data_migrations/0009_migrate_to_apps_json.py
from moulinette.utils.log import getActionLogger from yunohost.app import app_fetchlist, app_removelist, _read_appslist_list from yunohost.tools import Migration logger = getActionLogger('yunohost.migration') class MyMigration(Migration): "Migrate from official.json to apps.json" def migrate(self): # Remove all the deprecated lists lists_to_remove = [ "https://app.yunohost.org/official.json", "https://app.yunohost.org/community.json", "https://labriqueinter.net/apps/labriqueinternet.json" ] appslists = _read_appslist_list() for appslist, infos in appslists.items(): if infos["url"] in lists_to_remove: app_removelist(name=appslist) # Replace by apps.json list app_fetchlist(name="yunohost", url="https://app.yunohost.org/apps.json") def backward(self): # Remove apps.json list app_removelist(name="yunohost") # Replace by official.json list app_fetchlist(name="yunohost", url="https://app.yunohost.org/official.json")
import os from moulinette.utils.log import getActionLogger from yunohost.app import app_fetchlist, app_removelist, _read_appslist_list, APPSLISTS_JSON from yunohost.tools import Migration logger = getActionLogger('yunohost.migration') BASE_CONF_PATH = '/home/yunohost.conf' BACKUP_CONF_DIR = os.path.join(BASE_CONF_PATH, 'backup') APPSLISTS_BACKUP = os.path.join(BACKUP_CONF_DIR, "appslist_before_migration_0009.json") class MyMigration(Migration): "Migrate from official.json to apps.json" def migrate(self): # Backup current app list json os.system("cp %s %s") % (APPSLISTS_JSON, APPSLISTS_BACKUP) # Remove all the deprecated lists lists_to_remove = [ "https://app.yunohost.org/official.json", "https://app.yunohost.org/community.json", "https://labriqueinter.net/apps/labriqueinternet.json" ] appslists = _read_appslist_list() for appslist, infos in appslists.items(): if infos["url"] in lists_to_remove: app_removelist(name=appslist) # Replace by apps.json list app_fetchlist(name="yunohost", url="https://app.yunohost.org/apps.json") def backward(self): if os.path.exists(APPSLISTS_BACKUP): os.system("cp %s %s") % (APPSLISTS_BACKUP, APPSLISTS_JSON)
Backup / restore original appslist to handle backward case properly
Backup / restore original appslist to handle backward case properly
Python
agpl-3.0
YunoHost/moulinette-yunohost,YunoHost/yunohost,YunoHost/yunohost,YunoHost/moulinette-yunohost,YunoHost/moulinette-yunohost,YunoHost/moulinette-yunohost,YunoHost/moulinette-yunohost,YunoHost/yunohost,YunoHost/yunohost
+ import os + from moulinette.utils.log import getActionLogger - from yunohost.app import app_fetchlist, app_removelist, _read_appslist_list + from yunohost.app import app_fetchlist, app_removelist, _read_appslist_list, APPSLISTS_JSON from yunohost.tools import Migration logger = getActionLogger('yunohost.migration') + + BASE_CONF_PATH = '/home/yunohost.conf' + BACKUP_CONF_DIR = os.path.join(BASE_CONF_PATH, 'backup') + APPSLISTS_BACKUP = os.path.join(BACKUP_CONF_DIR, "appslist_before_migration_0009.json") + class MyMigration(Migration): "Migrate from official.json to apps.json" def migrate(self): + + # Backup current app list json + os.system("cp %s %s") % (APPSLISTS_JSON, APPSLISTS_BACKUP) # Remove all the deprecated lists lists_to_remove = [ "https://app.yunohost.org/official.json", "https://app.yunohost.org/community.json", "https://labriqueinter.net/apps/labriqueinternet.json" ] appslists = _read_appslist_list() for appslist, infos in appslists.items(): if infos["url"] in lists_to_remove: app_removelist(name=appslist) # Replace by apps.json list app_fetchlist(name="yunohost", url="https://app.yunohost.org/apps.json") def backward(self): - # Remove apps.json list - app_removelist(name="yunohost") + if os.path.exists(APPSLISTS_BACKUP): + os.system("cp %s %s") % (APPSLISTS_BACKUP, APPSLISTS_JSON) - # Replace by official.json list - app_fetchlist(name="yunohost", - url="https://app.yunohost.org/official.json") -
Backup / restore original appslist to handle backward case properly
## Code Before: from moulinette.utils.log import getActionLogger from yunohost.app import app_fetchlist, app_removelist, _read_appslist_list from yunohost.tools import Migration logger = getActionLogger('yunohost.migration') class MyMigration(Migration): "Migrate from official.json to apps.json" def migrate(self): # Remove all the deprecated lists lists_to_remove = [ "https://app.yunohost.org/official.json", "https://app.yunohost.org/community.json", "https://labriqueinter.net/apps/labriqueinternet.json" ] appslists = _read_appslist_list() for appslist, infos in appslists.items(): if infos["url"] in lists_to_remove: app_removelist(name=appslist) # Replace by apps.json list app_fetchlist(name="yunohost", url="https://app.yunohost.org/apps.json") def backward(self): # Remove apps.json list app_removelist(name="yunohost") # Replace by official.json list app_fetchlist(name="yunohost", url="https://app.yunohost.org/official.json") ## Instruction: Backup / restore original appslist to handle backward case properly ## Code After: import os from moulinette.utils.log import getActionLogger from yunohost.app import app_fetchlist, app_removelist, _read_appslist_list, APPSLISTS_JSON from yunohost.tools import Migration logger = getActionLogger('yunohost.migration') BASE_CONF_PATH = '/home/yunohost.conf' BACKUP_CONF_DIR = os.path.join(BASE_CONF_PATH, 'backup') APPSLISTS_BACKUP = os.path.join(BACKUP_CONF_DIR, "appslist_before_migration_0009.json") class MyMigration(Migration): "Migrate from official.json to apps.json" def migrate(self): # Backup current app list json os.system("cp %s %s") % (APPSLISTS_JSON, APPSLISTS_BACKUP) # Remove all the deprecated lists lists_to_remove = [ "https://app.yunohost.org/official.json", "https://app.yunohost.org/community.json", "https://labriqueinter.net/apps/labriqueinternet.json" ] appslists = _read_appslist_list() for appslist, infos in appslists.items(): if infos["url"] in lists_to_remove: app_removelist(name=appslist) # Replace by apps.json list app_fetchlist(name="yunohost", url="https://app.yunohost.org/apps.json") def backward(self): if os.path.exists(APPSLISTS_BACKUP): os.system("cp %s %s") % (APPSLISTS_BACKUP, APPSLISTS_JSON)
# ... existing code ... import os from moulinette.utils.log import getActionLogger from yunohost.app import app_fetchlist, app_removelist, _read_appslist_list, APPSLISTS_JSON from yunohost.tools import Migration logger = getActionLogger('yunohost.migration') BASE_CONF_PATH = '/home/yunohost.conf' BACKUP_CONF_DIR = os.path.join(BASE_CONF_PATH, 'backup') APPSLISTS_BACKUP = os.path.join(BACKUP_CONF_DIR, "appslist_before_migration_0009.json") class MyMigration(Migration): # ... modified code ... def migrate(self): # Backup current app list json os.system("cp %s %s") % (APPSLISTS_JSON, APPSLISTS_BACKUP) # Remove all the deprecated lists ... def backward(self): if os.path.exists(APPSLISTS_BACKUP): os.system("cp %s %s") % (APPSLISTS_BACKUP, APPSLISTS_JSON) # ... rest of the code ...
67fadc0ed846a95f6d603827313b555e98985959
skimage/viewer/qt.py
skimage/viewer/qt.py
has_qt = True try: from matplotlib.backends.qt_compat import QtGui, QtCore, QtWidgets except ImportError: try: from matplotlib.backends.qt4_compat import QtGui, QtCore QtWidgets = QtGui except ImportError: # Mock objects class QtGui(object): QMainWindow = object QDialog = object QWidget = object class QtCore_cls(object): class Qt(object): TopDockWidgetArea = None BottomDockWidgetArea = None LeftDockWidgetArea = None RightDockWidgetArea = None def Signal(self, *args, **kwargs): pass QWidget = object QtCore = QtWidgets = QtCore_cls() has_qt = False Qt = QtCore.Qt Signal = QtCore.Signal
has_qt = True try: from matplotlib.backends.qt_compat import QtGui, QtCore, QtWidgets except ImportError: try: from matplotlib.backends.qt4_compat import QtGui, QtCore QtWidgets = QtGui except ImportError: # Mock objects class QtGui_cls(object): QMainWindow = object QDialog = object QWidget = object class QtCore_cls(object): class Qt(object): TopDockWidgetArea = None BottomDockWidgetArea = None LeftDockWidgetArea = None RightDockWidgetArea = None def Signal(self, *args, **kwargs): pass QtGui = QtWidgets = QtGui_cls() QtCore = QtCore_cls() has_qt = False Qt = QtCore.Qt Signal = QtCore.Signal
Fix mock Qt objects again
Fix mock Qt objects again
Python
bsd-3-clause
jwiggins/scikit-image,Hiyorimi/scikit-image,paalge/scikit-image,michaelaye/scikit-image,ajaybhat/scikit-image,ofgulban/scikit-image,oew1v07/scikit-image,newville/scikit-image,juliusbierk/scikit-image,chriscrosscutler/scikit-image,vighneshbirodkar/scikit-image,newville/scikit-image,keflavich/scikit-image,bennlich/scikit-image,bsipocz/scikit-image,ClinicalGraphics/scikit-image,rjeli/scikit-image,WarrenWeckesser/scikits-image,pratapvardhan/scikit-image,rjeli/scikit-image,blink1073/scikit-image,paalge/scikit-image,Hiyorimi/scikit-image,oew1v07/scikit-image,bennlich/scikit-image,michaelaye/scikit-image,rjeli/scikit-image,GaZ3ll3/scikit-image,keflavich/scikit-image,Britefury/scikit-image,pratapvardhan/scikit-image,Midafi/scikit-image,youprofit/scikit-image,ofgulban/scikit-image,Midafi/scikit-image,vighneshbirodkar/scikit-image,robintw/scikit-image,warmspringwinds/scikit-image,emon10005/scikit-image,michaelpacer/scikit-image,chriscrosscutler/scikit-image,emon10005/scikit-image,ClinicalGraphics/scikit-image,warmspringwinds/scikit-image,ofgulban/scikit-image,dpshelio/scikit-image,blink1073/scikit-image,michaelpacer/scikit-image,Britefury/scikit-image,WarrenWeckesser/scikits-image,paalge/scikit-image,bsipocz/scikit-image,robintw/scikit-image,GaZ3ll3/scikit-image,ajaybhat/scikit-image,juliusbierk/scikit-image,vighneshbirodkar/scikit-image,jwiggins/scikit-image,youprofit/scikit-image,dpshelio/scikit-image
has_qt = True try: from matplotlib.backends.qt_compat import QtGui, QtCore, QtWidgets except ImportError: try: from matplotlib.backends.qt4_compat import QtGui, QtCore QtWidgets = QtGui except ImportError: # Mock objects - class QtGui(object): + class QtGui_cls(object): QMainWindow = object QDialog = object QWidget = object class QtCore_cls(object): class Qt(object): TopDockWidgetArea = None BottomDockWidgetArea = None LeftDockWidgetArea = None RightDockWidgetArea = None def Signal(self, *args, **kwargs): pass + QtGui = QtWidgets = QtGui_cls() - QWidget = object - - QtCore = QtWidgets = QtCore_cls() + QtCore = QtCore_cls() has_qt = False Qt = QtCore.Qt Signal = QtCore.Signal
Fix mock Qt objects again
## Code Before: has_qt = True try: from matplotlib.backends.qt_compat import QtGui, QtCore, QtWidgets except ImportError: try: from matplotlib.backends.qt4_compat import QtGui, QtCore QtWidgets = QtGui except ImportError: # Mock objects class QtGui(object): QMainWindow = object QDialog = object QWidget = object class QtCore_cls(object): class Qt(object): TopDockWidgetArea = None BottomDockWidgetArea = None LeftDockWidgetArea = None RightDockWidgetArea = None def Signal(self, *args, **kwargs): pass QWidget = object QtCore = QtWidgets = QtCore_cls() has_qt = False Qt = QtCore.Qt Signal = QtCore.Signal ## Instruction: Fix mock Qt objects again ## Code After: has_qt = True try: from matplotlib.backends.qt_compat import QtGui, QtCore, QtWidgets except ImportError: try: from matplotlib.backends.qt4_compat import QtGui, QtCore QtWidgets = QtGui except ImportError: # Mock objects class QtGui_cls(object): QMainWindow = object QDialog = object QWidget = object class QtCore_cls(object): class Qt(object): TopDockWidgetArea = None BottomDockWidgetArea = None LeftDockWidgetArea = None RightDockWidgetArea = None def Signal(self, *args, **kwargs): pass QtGui = QtWidgets = QtGui_cls() QtCore = QtCore_cls() has_qt = False Qt = QtCore.Qt Signal = QtCore.Signal
# ... existing code ... except ImportError: # Mock objects class QtGui_cls(object): QMainWindow = object QDialog = object # ... modified code ... pass QtGui = QtWidgets = QtGui_cls() QtCore = QtCore_cls() has_qt = False # ... rest of the code ...
14e000acafe7c374294a7de6ffe295c9d56df68f
tests/test_postgresql_specific.py
tests/test_postgresql_specific.py
import pytest from tests.utils import is_postgresql_env_with_json_field @pytest.mark.skipif(not is_postgresql_env_with_json_field(), reason="requires postgresql and Django 1.9+") @pytest.mark.django_db def test_dirty_json_field(): from tests.models import TestModelWithJSONField tm = TestModelWithJSONField.objects.create(json_field={'data': 'dummy_data'}) assert tm.get_dirty_fields() == {} tm.json_field = {'data': 'foo'} assert tm.get_dirty_fields() == {'json_field': {'data': 'dummy_data'}}
import pytest from tests.utils import is_postgresql_env_with_json_field @pytest.mark.skipif(not is_postgresql_env_with_json_field(), reason="requires postgresql and Django 1.9+") @pytest.mark.django_db def test_dirty_json_field(): from tests.models import TestModelWithJSONField tm = TestModelWithJSONField.objects.create(json_field={'data': [1, 2, 3]}) data = tm.json_field['data'] data.append(4) assert tm.get_dirty_fields(verbose=True) == { 'json_field': { 'current': {'data': [1, 2, 3, 4]}, 'saved': {'data': [1, 2, 3]} } }
Update postgresql json_field to reflect deepcopy fix
Update postgresql json_field to reflect deepcopy fix
Python
bsd-3-clause
jdotjdot/django-dirtyfields,romgar/django-dirtyfields,smn/django-dirtyfields
import pytest from tests.utils import is_postgresql_env_with_json_field @pytest.mark.skipif(not is_postgresql_env_with_json_field(), reason="requires postgresql and Django 1.9+") @pytest.mark.django_db def test_dirty_json_field(): from tests.models import TestModelWithJSONField - tm = TestModelWithJSONField.objects.create(json_field={'data': 'dummy_data'}) + tm = TestModelWithJSONField.objects.create(json_field={'data': [1, 2, 3]}) - assert tm.get_dirty_fields() == {} - tm.json_field = {'data': 'foo'} - assert tm.get_dirty_fields() == {'json_field': {'data': 'dummy_data'}} + data = tm.json_field['data'] + data.append(4) + assert tm.get_dirty_fields(verbose=True) == { + 'json_field': { + 'current': {'data': [1, 2, 3, 4]}, + 'saved': {'data': [1, 2, 3]} + } + } +
Update postgresql json_field to reflect deepcopy fix
## Code Before: import pytest from tests.utils import is_postgresql_env_with_json_field @pytest.mark.skipif(not is_postgresql_env_with_json_field(), reason="requires postgresql and Django 1.9+") @pytest.mark.django_db def test_dirty_json_field(): from tests.models import TestModelWithJSONField tm = TestModelWithJSONField.objects.create(json_field={'data': 'dummy_data'}) assert tm.get_dirty_fields() == {} tm.json_field = {'data': 'foo'} assert tm.get_dirty_fields() == {'json_field': {'data': 'dummy_data'}} ## Instruction: Update postgresql json_field to reflect deepcopy fix ## Code After: import pytest from tests.utils import is_postgresql_env_with_json_field @pytest.mark.skipif(not is_postgresql_env_with_json_field(), reason="requires postgresql and Django 1.9+") @pytest.mark.django_db def test_dirty_json_field(): from tests.models import TestModelWithJSONField tm = TestModelWithJSONField.objects.create(json_field={'data': [1, 2, 3]}) data = tm.json_field['data'] data.append(4) assert tm.get_dirty_fields(verbose=True) == { 'json_field': { 'current': {'data': [1, 2, 3, 4]}, 'saved': {'data': [1, 2, 3]} } }
// ... existing code ... from tests.models import TestModelWithJSONField tm = TestModelWithJSONField.objects.create(json_field={'data': [1, 2, 3]}) data = tm.json_field['data'] data.append(4) assert tm.get_dirty_fields(verbose=True) == { 'json_field': { 'current': {'data': [1, 2, 3, 4]}, 'saved': {'data': [1, 2, 3]} } } // ... rest of the code ...
5c7161858fa7ca2962f08b66f6d20ae49715c206
ci_scripts/buildLinuxWheels.py
ci_scripts/buildLinuxWheels.py
from subprocess import call, check_output import sys isPython3 = sys.version_info.major == 3 # https://stackoverflow.com/a/3357357 command = 'git log --format=%B -n 1'.split() out = check_output(command) if b'build wheels' not in out.lower() or not isPython3: exit(0) path = os.path.abspath(argv[1]) call('pip install cibuildwheel==0.7.0'.split()) call('cibuildwheel --output-dir {}'.format(path).split()) from dropboxUpload import uploadAll uploadAll(path)
from subprocess import call, check_output import sys import os isPython3 = sys.version_info.major == 3 # https://stackoverflow.com/a/3357357 command = 'git log --format=%B -n 1'.split() out = check_output(command) if b'build wheels' not in out.lower() or not isPython3: exit(0) path = os.path.abspath(argv[1]) call('pip install cibuildwheel==0.7.0'.split()) call('cibuildwheel --output-dir {}'.format(path).split()) from dropboxUpload import uploadAll uploadAll(path)
Fix build wheels and upload 3.
Fix build wheels and upload 3.
Python
bsd-3-clause
jr-garcia/AssimpCy,jr-garcia/AssimpCy
from subprocess import call, check_output import sys + import os isPython3 = sys.version_info.major == 3 # https://stackoverflow.com/a/3357357 command = 'git log --format=%B -n 1'.split() out = check_output(command) if b'build wheels' not in out.lower() or not isPython3: exit(0) path = os.path.abspath(argv[1]) call('pip install cibuildwheel==0.7.0'.split()) call('cibuildwheel --output-dir {}'.format(path).split()) from dropboxUpload import uploadAll uploadAll(path)
Fix build wheels and upload 3.
## Code Before: from subprocess import call, check_output import sys isPython3 = sys.version_info.major == 3 # https://stackoverflow.com/a/3357357 command = 'git log --format=%B -n 1'.split() out = check_output(command) if b'build wheels' not in out.lower() or not isPython3: exit(0) path = os.path.abspath(argv[1]) call('pip install cibuildwheel==0.7.0'.split()) call('cibuildwheel --output-dir {}'.format(path).split()) from dropboxUpload import uploadAll uploadAll(path) ## Instruction: Fix build wheels and upload 3. ## Code After: from subprocess import call, check_output import sys import os isPython3 = sys.version_info.major == 3 # https://stackoverflow.com/a/3357357 command = 'git log --format=%B -n 1'.split() out = check_output(command) if b'build wheels' not in out.lower() or not isPython3: exit(0) path = os.path.abspath(argv[1]) call('pip install cibuildwheel==0.7.0'.split()) call('cibuildwheel --output-dir {}'.format(path).split()) from dropboxUpload import uploadAll uploadAll(path)
// ... existing code ... from subprocess import call, check_output import sys import os isPython3 = sys.version_info.major == 3 // ... rest of the code ...
7ebda7fca01372ae49a8c66812c958fc8200f4b0
apps/events/filters.py
apps/events/filters.py
import django_filters from django_filters.filters import Lookup from apps.events.models import Event class ListFilter(django_filters.Filter): # https://github.com/carltongibson/django-filter/issues/137#issuecomment-37820702 def filter(self, qs, value): value_list = value.split(u',') return super(ListFilter, self).filter(qs, Lookup(value_list, 'in')) class EventDateFilter(django_filters.FilterSet): event_start__gte = django_filters.DateTimeFilter(name='event_start', lookup_expr='gte') event_start__lte = django_filters.DateTimeFilter(name='event_start', lookup_expr='lte') event_end__gte = django_filters.DateTimeFilter(name='event_end', lookup_expr='gte') event_end__lte = django_filters.DateTimeFilter(name='event_end', lookup_expr='lte') attendance_event__isnull = django_filters.BooleanFilter(name='attendance_event', lookup_expr='isnull') event_type = ListFilter() class Meta: model = Event fields = ('event_start', 'event_end', 'event_type')
import django_filters from django_filters.filters import Lookup from apps.events.models import Event class ListFilter(django_filters.Filter): # https://github.com/carltongibson/django-filter/issues/137#issuecomment-37820702 def filter(self, qs, value): value_list = value.split(u',') return super(ListFilter, self).filter(qs, Lookup(value_list, 'in')) class EventDateFilter(django_filters.FilterSet): event_start__gte = django_filters.DateTimeFilter(field_name='event_start', lookup_expr='gte') event_start__lte = django_filters.DateTimeFilter(field_name='event_start', lookup_expr='lte') event_end__gte = django_filters.DateTimeFilter(field_name='event_end', lookup_expr='gte') event_end__lte = django_filters.DateTimeFilter(field_name='event_end', lookup_expr='lte') attendance_event__isnull = django_filters.BooleanFilter(field_name='attendance_event', lookup_expr='isnull') event_type = ListFilter() class Meta: model = Event fields = ('event_start', 'event_end', 'event_type')
Change Django field filter kwarg from name to field_name for Django 2 support
Change Django field filter kwarg from name to field_name for Django 2 support
Python
mit
dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4
import django_filters from django_filters.filters import Lookup from apps.events.models import Event class ListFilter(django_filters.Filter): # https://github.com/carltongibson/django-filter/issues/137#issuecomment-37820702 def filter(self, qs, value): value_list = value.split(u',') return super(ListFilter, self).filter(qs, Lookup(value_list, 'in')) class EventDateFilter(django_filters.FilterSet): - event_start__gte = django_filters.DateTimeFilter(name='event_start', lookup_expr='gte') + event_start__gte = django_filters.DateTimeFilter(field_name='event_start', lookup_expr='gte') - event_start__lte = django_filters.DateTimeFilter(name='event_start', lookup_expr='lte') + event_start__lte = django_filters.DateTimeFilter(field_name='event_start', lookup_expr='lte') - event_end__gte = django_filters.DateTimeFilter(name='event_end', lookup_expr='gte') + event_end__gte = django_filters.DateTimeFilter(field_name='event_end', lookup_expr='gte') - event_end__lte = django_filters.DateTimeFilter(name='event_end', lookup_expr='lte') + event_end__lte = django_filters.DateTimeFilter(field_name='event_end', lookup_expr='lte') - attendance_event__isnull = django_filters.BooleanFilter(name='attendance_event', lookup_expr='isnull') + attendance_event__isnull = django_filters.BooleanFilter(field_name='attendance_event', lookup_expr='isnull') event_type = ListFilter() class Meta: model = Event fields = ('event_start', 'event_end', 'event_type')
Change Django field filter kwarg from name to field_name for Django 2 support
## Code Before: import django_filters from django_filters.filters import Lookup from apps.events.models import Event class ListFilter(django_filters.Filter): # https://github.com/carltongibson/django-filter/issues/137#issuecomment-37820702 def filter(self, qs, value): value_list = value.split(u',') return super(ListFilter, self).filter(qs, Lookup(value_list, 'in')) class EventDateFilter(django_filters.FilterSet): event_start__gte = django_filters.DateTimeFilter(name='event_start', lookup_expr='gte') event_start__lte = django_filters.DateTimeFilter(name='event_start', lookup_expr='lte') event_end__gte = django_filters.DateTimeFilter(name='event_end', lookup_expr='gte') event_end__lte = django_filters.DateTimeFilter(name='event_end', lookup_expr='lte') attendance_event__isnull = django_filters.BooleanFilter(name='attendance_event', lookup_expr='isnull') event_type = ListFilter() class Meta: model = Event fields = ('event_start', 'event_end', 'event_type') ## Instruction: Change Django field filter kwarg from name to field_name for Django 2 support ## Code After: import django_filters from django_filters.filters import Lookup from apps.events.models import Event class ListFilter(django_filters.Filter): # https://github.com/carltongibson/django-filter/issues/137#issuecomment-37820702 def filter(self, qs, value): value_list = value.split(u',') return super(ListFilter, self).filter(qs, Lookup(value_list, 'in')) class EventDateFilter(django_filters.FilterSet): event_start__gte = django_filters.DateTimeFilter(field_name='event_start', lookup_expr='gte') event_start__lte = django_filters.DateTimeFilter(field_name='event_start', lookup_expr='lte') event_end__gte = django_filters.DateTimeFilter(field_name='event_end', lookup_expr='gte') event_end__lte = django_filters.DateTimeFilter(field_name='event_end', lookup_expr='lte') attendance_event__isnull = django_filters.BooleanFilter(field_name='attendance_event', lookup_expr='isnull') event_type = ListFilter() class Meta: model = Event fields = ('event_start', 'event_end', 'event_type')
// ... existing code ... class EventDateFilter(django_filters.FilterSet): event_start__gte = django_filters.DateTimeFilter(field_name='event_start', lookup_expr='gte') event_start__lte = django_filters.DateTimeFilter(field_name='event_start', lookup_expr='lte') event_end__gte = django_filters.DateTimeFilter(field_name='event_end', lookup_expr='gte') event_end__lte = django_filters.DateTimeFilter(field_name='event_end', lookup_expr='lte') attendance_event__isnull = django_filters.BooleanFilter(field_name='attendance_event', lookup_expr='isnull') event_type = ListFilter() // ... rest of the code ...
943d575749d34a985b4bb9bdde40a8c3fe1cd911
spritecss/css/__init__.py
spritecss/css/__init__.py
"""Pure-Python CSS parser - no dependencies!""" # Copyright held by Yo Studios AB <[email protected]>, 2011 # # Some kind of BSD license, contact above e-mail for more information on # matters of licensing. from .parser import CSSParser, print_css from itertools import ifilter, imap __all__ = ["CSSParser", "iter_events", "split_declaration", "print_css", "iter_declarations"] def iter_events(parser, lexemes=None, predicate=None): if lexemes and predicate: raise TypeError("specify either events or predicate, not both") elif lexemes: predicate = lambda e: e.lexeme in lexemes return ifilter(predicate, iter(parser)) def split_declaration(decl): parts = decl.split(":", 1) if len(parts) == 1: return (parts[0], None) else: (prop, val) = parts return (prop, val) def iter_declarations(parser, predicate=None): evs = iter_events(parser, lexemes=("declaration",)) return imap(split_declaration, evs)
"""Pure-Python CSS parser - no dependencies!""" # Copyright held by Yo Studios AB <[email protected]>, 2011 # # Part of Spritemapper (https://github.com/yostudios/Spritemapper) # Released under a MIT/X11 license from .parser import CSSParser, print_css from itertools import ifilter, imap __all__ = ["CSSParser", "iter_events", "split_declaration", "print_css", "iter_declarations"] def iter_events(parser, lexemes=None, predicate=None): if lexemes and predicate: raise TypeError("specify either events or predicate, not both") elif lexemes: predicate = lambda e: e.lexeme in lexemes return ifilter(predicate, iter(parser)) def split_declaration(decl): parts = decl.split(":", 1) if len(parts) == 1: return (parts[0], None) else: (prop, val) = parts return (prop, val) def iter_declarations(parser, predicate=None): evs = iter_events(parser, lexemes=("declaration",)) return imap(split_declaration, evs)
Modify licensing info for css parser
Modify licensing info for css parser
Python
mit
wpj-cz/Spritemapper,wpj-cz/Spritemapper,wpj-cz/Spritemapper,yostudios/Spritemapper,wpj-cz/Spritemapper,yostudios/Spritemapper,yostudios/Spritemapper
"""Pure-Python CSS parser - no dependencies!""" # Copyright held by Yo Studios AB <[email protected]>, 2011 # - # Some kind of BSD license, contact above e-mail for more information on - # matters of licensing. + # Part of Spritemapper (https://github.com/yostudios/Spritemapper) + # Released under a MIT/X11 license from .parser import CSSParser, print_css from itertools import ifilter, imap __all__ = ["CSSParser", "iter_events", "split_declaration", "print_css", "iter_declarations"] def iter_events(parser, lexemes=None, predicate=None): if lexemes and predicate: raise TypeError("specify either events or predicate, not both") elif lexemes: predicate = lambda e: e.lexeme in lexemes return ifilter(predicate, iter(parser)) def split_declaration(decl): parts = decl.split(":", 1) if len(parts) == 1: return (parts[0], None) else: (prop, val) = parts return (prop, val) def iter_declarations(parser, predicate=None): evs = iter_events(parser, lexemes=("declaration",)) return imap(split_declaration, evs)
Modify licensing info for css parser
## Code Before: """Pure-Python CSS parser - no dependencies!""" # Copyright held by Yo Studios AB <[email protected]>, 2011 # # Some kind of BSD license, contact above e-mail for more information on # matters of licensing. from .parser import CSSParser, print_css from itertools import ifilter, imap __all__ = ["CSSParser", "iter_events", "split_declaration", "print_css", "iter_declarations"] def iter_events(parser, lexemes=None, predicate=None): if lexemes and predicate: raise TypeError("specify either events or predicate, not both") elif lexemes: predicate = lambda e: e.lexeme in lexemes return ifilter(predicate, iter(parser)) def split_declaration(decl): parts = decl.split(":", 1) if len(parts) == 1: return (parts[0], None) else: (prop, val) = parts return (prop, val) def iter_declarations(parser, predicate=None): evs = iter_events(parser, lexemes=("declaration",)) return imap(split_declaration, evs) ## Instruction: Modify licensing info for css parser ## Code After: """Pure-Python CSS parser - no dependencies!""" # Copyright held by Yo Studios AB <[email protected]>, 2011 # # Part of Spritemapper (https://github.com/yostudios/Spritemapper) # Released under a MIT/X11 license from .parser import CSSParser, print_css from itertools import ifilter, imap __all__ = ["CSSParser", "iter_events", "split_declaration", "print_css", "iter_declarations"] def iter_events(parser, lexemes=None, predicate=None): if lexemes and predicate: raise TypeError("specify either events or predicate, not both") elif lexemes: predicate = lambda e: e.lexeme in lexemes return ifilter(predicate, iter(parser)) def split_declaration(decl): parts = decl.split(":", 1) if len(parts) == 1: return (parts[0], None) else: (prop, val) = parts return (prop, val) def iter_declarations(parser, predicate=None): evs = iter_events(parser, lexemes=("declaration",)) return imap(split_declaration, evs)
... # Copyright held by Yo Studios AB <[email protected]>, 2011 # # Part of Spritemapper (https://github.com/yostudios/Spritemapper) # Released under a MIT/X11 license from .parser import CSSParser, print_css ...
64bf087f818e58bec8c39c03fb51b62f4253b2ad
settings.py
settings.py
import os LOWAGE = 15 UPAGE = 70 MAXAGE = 120 DATADIR = '/home/pieter/projects/factors/data' INFILE = 'lifedb.xls' XLSWB = os.path.join(DATADIR, INFILE) INSURANCE_IDS = ['OPLL', 'NPLL-B', 'NPLL-O', 'NPLLRS', 'NPTL-B', 'NPTL-O', 'ay_avg']
import os LOWAGE = 15 UPAGE = 70 MAXAGE = 120 DATADIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'data') INFILE = 'lifedb.xls' XLSWB = os.path.join(DATADIR, INFILE) INSURANCE_IDS = ['OPLL', 'NPLL-B', 'NPLL-O', 'NPLLRS', 'NPTL-B', 'NPTL-O', 'ay_avg']
Make DATADIR absolute path agnostic
Make DATADIR absolute path agnostic
Python
mit
Oxylo/factors
import os + LOWAGE = 15 UPAGE = 70 MAXAGE = 120 - DATADIR = '/home/pieter/projects/factors/data' + DATADIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'data') INFILE = 'lifedb.xls' XLSWB = os.path.join(DATADIR, INFILE) INSURANCE_IDS = ['OPLL', 'NPLL-B', 'NPLL-O', 'NPLLRS', 'NPTL-B', 'NPTL-O', 'ay_avg']
Make DATADIR absolute path agnostic
## Code Before: import os LOWAGE = 15 UPAGE = 70 MAXAGE = 120 DATADIR = '/home/pieter/projects/factors/data' INFILE = 'lifedb.xls' XLSWB = os.path.join(DATADIR, INFILE) INSURANCE_IDS = ['OPLL', 'NPLL-B', 'NPLL-O', 'NPLLRS', 'NPTL-B', 'NPTL-O', 'ay_avg'] ## Instruction: Make DATADIR absolute path agnostic ## Code After: import os LOWAGE = 15 UPAGE = 70 MAXAGE = 120 DATADIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'data') INFILE = 'lifedb.xls' XLSWB = os.path.join(DATADIR, INFILE) INSURANCE_IDS = ['OPLL', 'NPLL-B', 'NPLL-O', 'NPLLRS', 'NPTL-B', 'NPTL-O', 'ay_avg']
// ... existing code ... import os LOWAGE = 15 // ... modified code ... MAXAGE = 120 DATADIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'data') INFILE = 'lifedb.xls' // ... rest of the code ...
b1bd07038b0c6a6d801e686372996b3478c71af9
iss/management/commands/upsert_iss_organizations.py
iss/management/commands/upsert_iss_organizations.py
import logging import os from django.core.management.base import BaseCommand import iss.salesforce import iss.utils logger = logging.getLogger(os.path.basename(__file__)) class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument( '-m', '--modified-within', type=int, metavar='n-days', default=7, help='upsert organizations for accounts modified within n-days') def handle(self, *args, **options): upsert_organizations_for_recently_modified_accounts( options['modified_within']) def upsert_organizations_for_recently_modified_accounts(since=7): """Upsert organizations for SF Accounts modified in last `since` days.""" logger.info('upserting orgs for accounts modified in last {since} days'. format(since=since)) recently_modified_accounts = ( iss.salesforce.Account.get_recently_modified_accounts(since=since)) iss.utils.upsert_organizations_for_accounts(recently_modified_accounts)
import logging import os from django.core.management.base import BaseCommand import iss.models import iss.salesforce import iss.utils logger = logging.getLogger(os.path.basename(__file__)) class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument( '-m', '--modified-within', type=int, metavar='n-days', default=7, help='upsert organizations for accounts modified within n-days') parser.add_argument( '-i', '--include-aashe-in-website', action='store_true', help='force AASHE exclude_from_website to be False') def handle(self, *args, **options): upsert_organizations_for_recently_modified_accounts( since=options['modified_within'], include_aashe_in_website=options['include_aashe_in_website']) def upsert_organizations_for_recently_modified_accounts( since=7, include_aashe_in_website=False): """Upsert organizations for SF Accounts modified in last `since` days. When `include_aashe_in_website` is true, set the `exclude_from_website` flag on the Organization representing AASHE to False (0, actually). (Added for the Hub project.) """ logger.info('upserting orgs for accounts modified in last {since} days'. format(since=since)) recently_modified_accounts = ( iss.salesforce.Account.get_recently_modified_accounts(since=since)) iss.utils.upsert_organizations_for_accounts(recently_modified_accounts) if include_aashe_in_website: aashe = iss.models.Organization.objects.get(org_name="AASHE") if aashe.exclude_from_website: aashe.exclude_from_website = 0 aashe.save()
Add --include-aashe-in-website flag to org upsert
Add --include-aashe-in-website flag to org upsert
Python
mit
AASHE/iss
import logging import os from django.core.management.base import BaseCommand + import iss.models import iss.salesforce import iss.utils logger = logging.getLogger(os.path.basename(__file__)) class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument( '-m', '--modified-within', type=int, metavar='n-days', default=7, help='upsert organizations for accounts modified within n-days') + parser.add_argument( + '-i', '--include-aashe-in-website', + action='store_true', + help='force AASHE exclude_from_website to be False') def handle(self, *args, **options): upsert_organizations_for_recently_modified_accounts( - options['modified_within']) + since=options['modified_within'], + include_aashe_in_website=options['include_aashe_in_website']) - def upsert_organizations_for_recently_modified_accounts(since=7): + def upsert_organizations_for_recently_modified_accounts( + since=7, include_aashe_in_website=False): - """Upsert organizations for SF Accounts modified in last `since` days.""" + """Upsert organizations for SF Accounts modified in last `since` days. + + When `include_aashe_in_website` is true, set the + `exclude_from_website` flag on the Organization representing AASHE + to False (0, actually). (Added for the Hub project.) + """ logger.info('upserting orgs for accounts modified in last {since} days'. format(since=since)) recently_modified_accounts = ( iss.salesforce.Account.get_recently_modified_accounts(since=since)) iss.utils.upsert_organizations_for_accounts(recently_modified_accounts) + if include_aashe_in_website: + aashe = iss.models.Organization.objects.get(org_name="AASHE") + if aashe.exclude_from_website: + aashe.exclude_from_website = 0 + aashe.save() +
Add --include-aashe-in-website flag to org upsert
## Code Before: import logging import os from django.core.management.base import BaseCommand import iss.salesforce import iss.utils logger = logging.getLogger(os.path.basename(__file__)) class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument( '-m', '--modified-within', type=int, metavar='n-days', default=7, help='upsert organizations for accounts modified within n-days') def handle(self, *args, **options): upsert_organizations_for_recently_modified_accounts( options['modified_within']) def upsert_organizations_for_recently_modified_accounts(since=7): """Upsert organizations for SF Accounts modified in last `since` days.""" logger.info('upserting orgs for accounts modified in last {since} days'. format(since=since)) recently_modified_accounts = ( iss.salesforce.Account.get_recently_modified_accounts(since=since)) iss.utils.upsert_organizations_for_accounts(recently_modified_accounts) ## Instruction: Add --include-aashe-in-website flag to org upsert ## Code After: import logging import os from django.core.management.base import BaseCommand import iss.models import iss.salesforce import iss.utils logger = logging.getLogger(os.path.basename(__file__)) class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument( '-m', '--modified-within', type=int, metavar='n-days', default=7, help='upsert organizations for accounts modified within n-days') parser.add_argument( '-i', '--include-aashe-in-website', action='store_true', help='force AASHE exclude_from_website to be False') def handle(self, *args, **options): upsert_organizations_for_recently_modified_accounts( since=options['modified_within'], include_aashe_in_website=options['include_aashe_in_website']) def upsert_organizations_for_recently_modified_accounts( since=7, include_aashe_in_website=False): """Upsert organizations for SF Accounts modified in last `since` days. When `include_aashe_in_website` is true, set the `exclude_from_website` flag on the Organization representing AASHE to False (0, actually). (Added for the Hub project.) """ logger.info('upserting orgs for accounts modified in last {since} days'. format(since=since)) recently_modified_accounts = ( iss.salesforce.Account.get_recently_modified_accounts(since=since)) iss.utils.upsert_organizations_for_accounts(recently_modified_accounts) if include_aashe_in_website: aashe = iss.models.Organization.objects.get(org_name="AASHE") if aashe.exclude_from_website: aashe.exclude_from_website = 0 aashe.save()
// ... existing code ... from django.core.management.base import BaseCommand import iss.models import iss.salesforce import iss.utils // ... modified code ... default=7, help='upsert organizations for accounts modified within n-days') parser.add_argument( '-i', '--include-aashe-in-website', action='store_true', help='force AASHE exclude_from_website to be False') def handle(self, *args, **options): upsert_organizations_for_recently_modified_accounts( since=options['modified_within'], include_aashe_in_website=options['include_aashe_in_website']) def upsert_organizations_for_recently_modified_accounts( since=7, include_aashe_in_website=False): """Upsert organizations for SF Accounts modified in last `since` days. When `include_aashe_in_website` is true, set the `exclude_from_website` flag on the Organization representing AASHE to False (0, actually). (Added for the Hub project.) """ logger.info('upserting orgs for accounts modified in last {since} days'. format(since=since)) ... iss.salesforce.Account.get_recently_modified_accounts(since=since)) iss.utils.upsert_organizations_for_accounts(recently_modified_accounts) if include_aashe_in_website: aashe = iss.models.Organization.objects.get(org_name="AASHE") if aashe.exclude_from_website: aashe.exclude_from_website = 0 aashe.save() // ... rest of the code ...
9aaf3bd6c376f608911b232d5f811e0b7964022f
tests/django_mysql_tests/tests.py
tests/django_mysql_tests/tests.py
from __future__ import (absolute_import, division, print_function, unicode_literals) from django.test import TestCase from django_mysql_tests.models import MyModel class SimpleTests(TestCase): def test_simple(self): MyModel.objects.create()
from __future__ import (absolute_import, division, print_function, unicode_literals) from django.test import TestCase from django_mysql_tests.models import MyModel class SimpleTests(TestCase): def test_simple(self): MyModel.objects.create() def test_two(self): MyModel.objects.create() MyModel.objects.create()
Add second test, trying to trigger travis
Add second test, trying to trigger travis
Python
mit
nickmeharry/django-mysql,nickmeharry/django-mysql,arnau126/django-mysql,adamchainz/django-mysql,arnau126/django-mysql,graingert/django-mysql,graingert/django-mysql
from __future__ import (absolute_import, division, print_function, unicode_literals) from django.test import TestCase from django_mysql_tests.models import MyModel class SimpleTests(TestCase): def test_simple(self): MyModel.objects.create() + def test_two(self): + MyModel.objects.create() + MyModel.objects.create() +
Add second test, trying to trigger travis
## Code Before: from __future__ import (absolute_import, division, print_function, unicode_literals) from django.test import TestCase from django_mysql_tests.models import MyModel class SimpleTests(TestCase): def test_simple(self): MyModel.objects.create() ## Instruction: Add second test, trying to trigger travis ## Code After: from __future__ import (absolute_import, division, print_function, unicode_literals) from django.test import TestCase from django_mysql_tests.models import MyModel class SimpleTests(TestCase): def test_simple(self): MyModel.objects.create() def test_two(self): MyModel.objects.create() MyModel.objects.create()
// ... existing code ... def test_simple(self): MyModel.objects.create() def test_two(self): MyModel.objects.create() MyModel.objects.create() // ... rest of the code ...
ea56607fa7ae7257682170e881c67ae5e0f6719c
tests/rest_views.py
tests/rest_views.py
from django.views.generic import View from nap.datamapper.models import ModelDataMapper from nap.rest import views from .models import Poll class PollMapper(ModelDataMapper): class Meta: model = Poll fields = ['question', 'pub_date'] class SinglePollView(views.ObjectGetMixin, views.ObjectPutMixin, views.ObjectPatchMixin, views.ObjectDeleteMixin, views.ObjectMixin, View): model = Poll mapper_class = PollMapper
from django.views.generic import View from nap.datamapper.models import ModelDataMapper from nap.rest import views from .models import Poll class PollMapper(ModelDataMapper): class Meta: model = Poll fields = ['question', 'pub_date'] class SinglePollView(views.ObjectGetMixin, views.ObjectPutMixin, views.ObjectPatchMixin, views.ObjectDeleteMixin, views.BaseObjectView): model = Poll mapper_class = PollMapper
Update test to use Base view
Update test to use Base view
Python
bsd-3-clause
MarkusH/django-nap,limbera/django-nap
from django.views.generic import View from nap.datamapper.models import ModelDataMapper from nap.rest import views from .models import Poll class PollMapper(ModelDataMapper): class Meta: model = Poll fields = ['question', 'pub_date'] - class SinglePollView(views.ObjectGetMixin, views.ObjectPutMixin, views.ObjectPatchMixin, views.ObjectDeleteMixin, views.ObjectMixin, View): + class SinglePollView(views.ObjectGetMixin, views.ObjectPutMixin, views.ObjectPatchMixin, views.ObjectDeleteMixin, views.BaseObjectView): model = Poll mapper_class = PollMapper
Update test to use Base view
## Code Before: from django.views.generic import View from nap.datamapper.models import ModelDataMapper from nap.rest import views from .models import Poll class PollMapper(ModelDataMapper): class Meta: model = Poll fields = ['question', 'pub_date'] class SinglePollView(views.ObjectGetMixin, views.ObjectPutMixin, views.ObjectPatchMixin, views.ObjectDeleteMixin, views.ObjectMixin, View): model = Poll mapper_class = PollMapper ## Instruction: Update test to use Base view ## Code After: from django.views.generic import View from nap.datamapper.models import ModelDataMapper from nap.rest import views from .models import Poll class PollMapper(ModelDataMapper): class Meta: model = Poll fields = ['question', 'pub_date'] class SinglePollView(views.ObjectGetMixin, views.ObjectPutMixin, views.ObjectPatchMixin, views.ObjectDeleteMixin, views.BaseObjectView): model = Poll mapper_class = PollMapper
// ... existing code ... class SinglePollView(views.ObjectGetMixin, views.ObjectPutMixin, views.ObjectPatchMixin, views.ObjectDeleteMixin, views.BaseObjectView): model = Poll mapper_class = PollMapper // ... rest of the code ...
9dfe31f52d1cf4dfb11a1ffd8c14274e4b9ec135
tests/test_tokenizer.py
tests/test_tokenizer.py
import unittest from halng.tokenizer import MegaHALTokenizer class testMegaHALTokenizer(unittest.TestCase): def setUp(self): self.tokenizer = MegaHALTokenizer() def testSplitEmpty(self): self.assertEquals(len(self.tokenizer.split("")), 0) def testSplitSentence(self): words = self.tokenizer.split("hi.") self.assertEquals(len(words), 2) self.assertEquals(words[0], "HI") self.assertEquals(words[1], ".") def testSplitImplicitStop(self): words = self.tokenizer.split("hi") self.assertEquals(len(words), 2) self.assertEquals(words[0], "HI") self.assertEquals(words[1], ".") def testSplitUrl(self): words = self.tokenizer.split("http://www.google.com/") self.assertEquals(len(words), 8) self.assertEquals(words[0], "HTTP") self.assertEquals(words[1], "://") self.assertEquals(words[2], "WWW") self.assertEquals(words[3], ".") self.assertEquals(words[4], "GOOGLE") self.assertEquals(words[5], ".") self.assertEquals(words[6], "COM") self.assertEquals(words[7], "/.") if __name__ == '__main__': unittest.main()
import unittest from halng.tokenizer import MegaHALTokenizer class testMegaHALTokenizer(unittest.TestCase): def setUp(self): self.tokenizer = MegaHALTokenizer() def testSplitEmpty(self): self.assertEquals(len(self.tokenizer.split("")), 0) def testSplitSentence(self): words = self.tokenizer.split("hi.") self.assertEquals(len(words), 2) self.assertEquals(words[0], "HI") self.assertEquals(words[1], ".") def testSplitComma(self): words = self.tokenizer.split("hi, hal") self.assertEquals(len(words), 4) self.assertEquals(words[0], "HI") self.assertEquals(words[1], ", ") self.assertEquals(words[2], "HAL") self.assertEquals(words[3], ".") def testSplitImplicitStop(self): words = self.tokenizer.split("hi") self.assertEquals(len(words), 2) self.assertEquals(words[0], "HI") self.assertEquals(words[1], ".") def testSplitUrl(self): words = self.tokenizer.split("http://www.google.com/") self.assertEquals(len(words), 8) self.assertEquals(words[0], "HTTP") self.assertEquals(words[1], "://") self.assertEquals(words[2], "WWW") self.assertEquals(words[3], ".") self.assertEquals(words[4], "GOOGLE") self.assertEquals(words[5], ".") self.assertEquals(words[6], "COM") self.assertEquals(words[7], "/.") if __name__ == '__main__': unittest.main()
Add a test that ensures commas are part of non-word runs.
Add a test that ensures commas are part of non-word runs.
Python
mit
meska/cobe,wodim/cobe-ng,meska/cobe,tiagochiavericosta/cobe,DarkMio/cobe,LeMagnesium/cobe,tiagochiavericosta/cobe,pteichman/cobe,pteichman/cobe,LeMagnesium/cobe,DarkMio/cobe,wodim/cobe-ng
import unittest from halng.tokenizer import MegaHALTokenizer class testMegaHALTokenizer(unittest.TestCase): def setUp(self): self.tokenizer = MegaHALTokenizer() def testSplitEmpty(self): self.assertEquals(len(self.tokenizer.split("")), 0) def testSplitSentence(self): words = self.tokenizer.split("hi.") self.assertEquals(len(words), 2) self.assertEquals(words[0], "HI") self.assertEquals(words[1], ".") + + def testSplitComma(self): + words = self.tokenizer.split("hi, hal") + self.assertEquals(len(words), 4) + self.assertEquals(words[0], "HI") + self.assertEquals(words[1], ", ") + self.assertEquals(words[2], "HAL") + self.assertEquals(words[3], ".") def testSplitImplicitStop(self): words = self.tokenizer.split("hi") self.assertEquals(len(words), 2) self.assertEquals(words[0], "HI") self.assertEquals(words[1], ".") def testSplitUrl(self): words = self.tokenizer.split("http://www.google.com/") self.assertEquals(len(words), 8) self.assertEquals(words[0], "HTTP") self.assertEquals(words[1], "://") self.assertEquals(words[2], "WWW") self.assertEquals(words[3], ".") self.assertEquals(words[4], "GOOGLE") self.assertEquals(words[5], ".") self.assertEquals(words[6], "COM") self.assertEquals(words[7], "/.") if __name__ == '__main__': unittest.main()
Add a test that ensures commas are part of non-word runs.
## Code Before: import unittest from halng.tokenizer import MegaHALTokenizer class testMegaHALTokenizer(unittest.TestCase): def setUp(self): self.tokenizer = MegaHALTokenizer() def testSplitEmpty(self): self.assertEquals(len(self.tokenizer.split("")), 0) def testSplitSentence(self): words = self.tokenizer.split("hi.") self.assertEquals(len(words), 2) self.assertEquals(words[0], "HI") self.assertEquals(words[1], ".") def testSplitImplicitStop(self): words = self.tokenizer.split("hi") self.assertEquals(len(words), 2) self.assertEquals(words[0], "HI") self.assertEquals(words[1], ".") def testSplitUrl(self): words = self.tokenizer.split("http://www.google.com/") self.assertEquals(len(words), 8) self.assertEquals(words[0], "HTTP") self.assertEquals(words[1], "://") self.assertEquals(words[2], "WWW") self.assertEquals(words[3], ".") self.assertEquals(words[4], "GOOGLE") self.assertEquals(words[5], ".") self.assertEquals(words[6], "COM") self.assertEquals(words[7], "/.") if __name__ == '__main__': unittest.main() ## Instruction: Add a test that ensures commas are part of non-word runs. ## Code After: import unittest from halng.tokenizer import MegaHALTokenizer class testMegaHALTokenizer(unittest.TestCase): def setUp(self): self.tokenizer = MegaHALTokenizer() def testSplitEmpty(self): self.assertEquals(len(self.tokenizer.split("")), 0) def testSplitSentence(self): words = self.tokenizer.split("hi.") self.assertEquals(len(words), 2) self.assertEquals(words[0], "HI") self.assertEquals(words[1], ".") def testSplitComma(self): words = self.tokenizer.split("hi, hal") self.assertEquals(len(words), 4) self.assertEquals(words[0], "HI") self.assertEquals(words[1], ", ") self.assertEquals(words[2], "HAL") self.assertEquals(words[3], ".") def testSplitImplicitStop(self): words = self.tokenizer.split("hi") self.assertEquals(len(words), 2) self.assertEquals(words[0], "HI") self.assertEquals(words[1], ".") def testSplitUrl(self): words = self.tokenizer.split("http://www.google.com/") self.assertEquals(len(words), 8) self.assertEquals(words[0], "HTTP") self.assertEquals(words[1], "://") self.assertEquals(words[2], "WWW") self.assertEquals(words[3], ".") self.assertEquals(words[4], "GOOGLE") self.assertEquals(words[5], ".") self.assertEquals(words[6], "COM") self.assertEquals(words[7], "/.") if __name__ == '__main__': unittest.main()
// ... existing code ... self.assertEquals(words[0], "HI") self.assertEquals(words[1], ".") def testSplitComma(self): words = self.tokenizer.split("hi, hal") self.assertEquals(len(words), 4) self.assertEquals(words[0], "HI") self.assertEquals(words[1], ", ") self.assertEquals(words[2], "HAL") self.assertEquals(words[3], ".") def testSplitImplicitStop(self): // ... rest of the code ...
b503a6e893d71b96b3737e567dde16f110db5fc7
src/prepare_turk_batch.py
src/prepare_turk_batch.py
import os import sys import csv import json import html def do_command(args): assert os.path.exists(args.input) writer = csv.writer(args.output) writer.writerow(["document"]) for fname in os.listdir(args.input): if not fname.endswith('.json'): continue with open(os.path.join(args.input, fname)) as f: doc = json.load(f) writer.writerow([html.escape(json.dumps(doc))]) if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description='') parser.add_argument('-i', '--input', type=str, default='../data/pilot', help="Directory with JSON files") parser.add_argument('-o', '--output', type=argparse.FileType('w'), default=sys.stdout, help="A CSV to use with MTurk") parser.set_defaults(func=do_command) #subparsers = parser.add_subparsers() #command_parser = subparsers.add_parser('command', help='' ) #command_parser.set_defaults(func=do_command) ARGS = parser.parse_args() if ARGS.func is None: parser.print_help() sys.exit(1) else: ARGS.func(ARGS)
import os import sys import csv import json import html def do_command(args): assert os.path.exists(args.input) writer = csv.writer(args.output) writer.writerow(["document"]) for i, fname in enumerate(os.listdir(args.input)): if not fname.endswith('.json'): continue with open(os.path.join(args.input, fname)) as f: doc = json.load(f) for j, (prompt, time_range) in enumerate(doc["prompts"]): doc["id"] = "doc-{}-{}".format(i,j) doc["prompt"] = prompt doc["recommendedMinWordCount"] = time_range[0] doc["recommendedMaxWordCount"] = time_range[1] writer.writerow([html.escape(json.dumps(doc))]) if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description='') parser.add_argument('-i', '--input', type=str, default='../data/pilot', help="Directory with JSON files") parser.add_argument('-o', '--output', type=argparse.FileType('w'), default=sys.stdout, help="A CSV to use with MTurk") parser.set_defaults(func=do_command) #subparsers = parser.add_subparsers() #command_parser = subparsers.add_parser('command', help='' ) #command_parser.set_defaults(func=do_command) ARGS = parser.parse_args() if ARGS.func is None: parser.print_help() sys.exit(1) else: ARGS.func(ARGS)
Prepare data with the new fiields and prompts
Prepare data with the new fiields and prompts
Python
mit
arunchaganty/briefly,arunchaganty/briefly,arunchaganty/briefly,arunchaganty/briefly
import os import sys import csv import json import html def do_command(args): assert os.path.exists(args.input) writer = csv.writer(args.output) writer.writerow(["document"]) - for fname in os.listdir(args.input): + for i, fname in enumerate(os.listdir(args.input)): if not fname.endswith('.json'): continue with open(os.path.join(args.input, fname)) as f: doc = json.load(f) + for j, (prompt, time_range) in enumerate(doc["prompts"]): + doc["id"] = "doc-{}-{}".format(i,j) + doc["prompt"] = prompt + doc["recommendedMinWordCount"] = time_range[0] + doc["recommendedMaxWordCount"] = time_range[1] - writer.writerow([html.escape(json.dumps(doc))]) + writer.writerow([html.escape(json.dumps(doc))]) if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description='') parser.add_argument('-i', '--input', type=str, default='../data/pilot', help="Directory with JSON files") parser.add_argument('-o', '--output', type=argparse.FileType('w'), default=sys.stdout, help="A CSV to use with MTurk") parser.set_defaults(func=do_command) #subparsers = parser.add_subparsers() #command_parser = subparsers.add_parser('command', help='' ) #command_parser.set_defaults(func=do_command) ARGS = parser.parse_args() if ARGS.func is None: parser.print_help() sys.exit(1) else: ARGS.func(ARGS)
Prepare data with the new fiields and prompts
## Code Before: import os import sys import csv import json import html def do_command(args): assert os.path.exists(args.input) writer = csv.writer(args.output) writer.writerow(["document"]) for fname in os.listdir(args.input): if not fname.endswith('.json'): continue with open(os.path.join(args.input, fname)) as f: doc = json.load(f) writer.writerow([html.escape(json.dumps(doc))]) if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description='') parser.add_argument('-i', '--input', type=str, default='../data/pilot', help="Directory with JSON files") parser.add_argument('-o', '--output', type=argparse.FileType('w'), default=sys.stdout, help="A CSV to use with MTurk") parser.set_defaults(func=do_command) #subparsers = parser.add_subparsers() #command_parser = subparsers.add_parser('command', help='' ) #command_parser.set_defaults(func=do_command) ARGS = parser.parse_args() if ARGS.func is None: parser.print_help() sys.exit(1) else: ARGS.func(ARGS) ## Instruction: Prepare data with the new fiields and prompts ## Code After: import os import sys import csv import json import html def do_command(args): assert os.path.exists(args.input) writer = csv.writer(args.output) writer.writerow(["document"]) for i, fname in enumerate(os.listdir(args.input)): if not fname.endswith('.json'): continue with open(os.path.join(args.input, fname)) as f: doc = json.load(f) for j, (prompt, time_range) in enumerate(doc["prompts"]): doc["id"] = "doc-{}-{}".format(i,j) doc["prompt"] = prompt doc["recommendedMinWordCount"] = time_range[0] doc["recommendedMaxWordCount"] = time_range[1] writer.writerow([html.escape(json.dumps(doc))]) if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description='') parser.add_argument('-i', '--input', type=str, default='../data/pilot', help="Directory with JSON files") parser.add_argument('-o', '--output', type=argparse.FileType('w'), default=sys.stdout, help="A CSV to use with MTurk") parser.set_defaults(func=do_command) #subparsers = parser.add_subparsers() #command_parser = subparsers.add_parser('command', help='' ) #command_parser.set_defaults(func=do_command) ARGS = parser.parse_args() if ARGS.func is None: parser.print_help() sys.exit(1) else: ARGS.func(ARGS)
... writer.writerow(["document"]) for i, fname in enumerate(os.listdir(args.input)): if not fname.endswith('.json'): continue with open(os.path.join(args.input, fname)) as f: doc = json.load(f) for j, (prompt, time_range) in enumerate(doc["prompts"]): doc["id"] = "doc-{}-{}".format(i,j) doc["prompt"] = prompt doc["recommendedMinWordCount"] = time_range[0] doc["recommendedMaxWordCount"] = time_range[1] writer.writerow([html.escape(json.dumps(doc))]) if __name__ == "__main__": ...
f68e8cb9751a32cc4d8bdc97c6f753395381e1e1
python/dnest4/utils.py
python/dnest4/utils.py
__all__ = ["randh", "wrap"] import numpy as np import numpy.random as rng def randh(): """ Generate from the heavy-tailed distribution. """ return 10.0**(1.5 - 3*np.abs(rng.randn()/np.sqrt(-np.log(rng.rand()))))*rng.randn() def wrap(x, a, b): assert b > a return (x - a)%(b - a) + a
__all__ = ["randh", "wrap"] import numpy as np import numpy.random as rng def randh(N=1): """ Generate from the heavy-tailed distribution. """ if N==1: return 10.0**(1.5 - 3*np.abs(rng.randn()/np.sqrt(-np.log(rng.rand()))))*rng.randn() return 10.0**(1.5 - 3*np.abs(rng.randn(N)/np.sqrt(-np.log(rng.rand(N)))))*rng.randn(N) def wrap(x, a, b): assert b > a return (x - a)%(b - a) + a
Allow N > 1 randhs to be generated
Allow N > 1 randhs to be generated
Python
mit
eggplantbren/DNest4,eggplantbren/DNest4,eggplantbren/DNest4,eggplantbren/DNest4,eggplantbren/DNest4
__all__ = ["randh", "wrap"] import numpy as np import numpy.random as rng - def randh(): + def randh(N=1): """ Generate from the heavy-tailed distribution. """ + if N==1: - return 10.0**(1.5 - 3*np.abs(rng.randn()/np.sqrt(-np.log(rng.rand()))))*rng.randn() + return 10.0**(1.5 - 3*np.abs(rng.randn()/np.sqrt(-np.log(rng.rand()))))*rng.randn() + return 10.0**(1.5 - 3*np.abs(rng.randn(N)/np.sqrt(-np.log(rng.rand(N)))))*rng.randn(N) + def wrap(x, a, b): assert b > a return (x - a)%(b - a) + a
Allow N > 1 randhs to be generated
## Code Before: __all__ = ["randh", "wrap"] import numpy as np import numpy.random as rng def randh(): """ Generate from the heavy-tailed distribution. """ return 10.0**(1.5 - 3*np.abs(rng.randn()/np.sqrt(-np.log(rng.rand()))))*rng.randn() def wrap(x, a, b): assert b > a return (x - a)%(b - a) + a ## Instruction: Allow N > 1 randhs to be generated ## Code After: __all__ = ["randh", "wrap"] import numpy as np import numpy.random as rng def randh(N=1): """ Generate from the heavy-tailed distribution. """ if N==1: return 10.0**(1.5 - 3*np.abs(rng.randn()/np.sqrt(-np.log(rng.rand()))))*rng.randn() return 10.0**(1.5 - 3*np.abs(rng.randn(N)/np.sqrt(-np.log(rng.rand(N)))))*rng.randn(N) def wrap(x, a, b): assert b > a return (x - a)%(b - a) + a
// ... existing code ... import numpy.random as rng def randh(N=1): """ Generate from the heavy-tailed distribution. """ if N==1: return 10.0**(1.5 - 3*np.abs(rng.randn()/np.sqrt(-np.log(rng.rand()))))*rng.randn() return 10.0**(1.5 - 3*np.abs(rng.randn(N)/np.sqrt(-np.log(rng.rand(N)))))*rng.randn(N) def wrap(x, a, b): // ... rest of the code ...
b946768acb8c9e34dbb72cb6d3bc33a7e67f4548
setup.py
setup.py
from distutils.core import setup setup( requires=['beautifulsoup4', 'requests'], name='python-ninegag', version='0.1', py_modules=['pyninegag'], url='https://github.com/sashgorokhov/python-ninegag', license='MIT', author='sashgorokhov', author_email='[email protected]', description='Python library to get stuff from 9gag.com' )
from distutils.core import setup with open('README.md') as file: long_description = file.read() setup( requires=['beautifulsoup4', 'requests'], name='python-ninegag', version='0.1', py_modules=['pyninegag'], url='https://github.com/sashgorokhov/python-ninegag', download_url='https://github.com/sashgorokhov/python-ninegag/archive/master.zip', long_description=long_description, license='MIT License', author='sashgorokhov', author_email='[email protected]', description='Python library to get stuff from 9gag.com' )
Add download url and long description
Add download url and long description
Python
mit
sashgorokhov/python-ninegag
from distutils.core import setup + + with open('README.md') as file: + long_description = file.read() setup( requires=['beautifulsoup4', 'requests'], name='python-ninegag', version='0.1', py_modules=['pyninegag'], url='https://github.com/sashgorokhov/python-ninegag', + download_url='https://github.com/sashgorokhov/python-ninegag/archive/master.zip', + long_description=long_description, - license='MIT', + license='MIT License', author='sashgorokhov', author_email='[email protected]', description='Python library to get stuff from 9gag.com' )
Add download url and long description
## Code Before: from distutils.core import setup setup( requires=['beautifulsoup4', 'requests'], name='python-ninegag', version='0.1', py_modules=['pyninegag'], url='https://github.com/sashgorokhov/python-ninegag', license='MIT', author='sashgorokhov', author_email='[email protected]', description='Python library to get stuff from 9gag.com' ) ## Instruction: Add download url and long description ## Code After: from distutils.core import setup with open('README.md') as file: long_description = file.read() setup( requires=['beautifulsoup4', 'requests'], name='python-ninegag', version='0.1', py_modules=['pyninegag'], url='https://github.com/sashgorokhov/python-ninegag', download_url='https://github.com/sashgorokhov/python-ninegag/archive/master.zip', long_description=long_description, license='MIT License', author='sashgorokhov', author_email='[email protected]', description='Python library to get stuff from 9gag.com' )
# ... existing code ... from distutils.core import setup with open('README.md') as file: long_description = file.read() setup( # ... modified code ... py_modules=['pyninegag'], url='https://github.com/sashgorokhov/python-ninegag', download_url='https://github.com/sashgorokhov/python-ninegag/archive/master.zip', long_description=long_description, license='MIT License', author='sashgorokhov', author_email='[email protected]', # ... rest of the code ...
ef7163a18ee1cf11c1290f2a8832d8cf39fb552c
fjord/base/tests/test_commands.py
fjord/base/tests/test_commands.py
from django.core.management import call_command from fjord.base.tests import TestCase class TestGenerateData(TestCase): def test_generate_data(self): """Make sure ./manage.py generatedata runs.""" call_command('generatedata') call_command('generatedata', bigsample=True) class TestPOLint(TestCase): def test_polint(self): """Make sure ./manage.py polint runs.""" # Note: This doesn't make sure it works--just that it doesn't kick # up obvious errors when it runs like if Dennis has changed in # some way that prevents it from working correctly. try: call_command('polint') except SystemExit: # WOAH! WTF ARE YOU DOING? The lint command calls # sys.exit() because it needs to return correct exit codes # so we catch that here and ignore it. Otherwise testing # it will kill the test suite. pass
from django.core.management import call_command from fjord.base.tests import TestCase class TestGenerateData(TestCase): def test_generate_data(self): """Make sure ./manage.py generatedata runs.""" call_command('generatedata') call_command('generatedata', bigsample=True) class TestPOLint(TestCase): def test_polint(self): """Make sure ./manage.py polint runs.""" # Note: This doesn't make sure it works--just that it doesn't kick # up obvious errors when it runs like if Dennis has changed in # some way that prevents it from working correctly. try: call_command('polint', '--version') except SystemExit: # WOAH! WTF ARE YOU DOING? The lint command calls # sys.exit() because it needs to return correct exit codes # so we catch that here and ignore it. Otherwise testing # it will kill the test suite. pass
Adjust test_polint to be less stdout-spammy
Adjust test_polint to be less stdout-spammy
Python
bsd-3-clause
hoosteeno/fjord,lgp171188/fjord,mozilla/fjord,Ritsyy/fjord,lgp171188/fjord,rlr/fjord,staranjeet/fjord,DESHRAJ/fjord,hoosteeno/fjord,Ritsyy/fjord,rlr/fjord,lgp171188/fjord,DESHRAJ/fjord,mozilla/fjord,hoosteeno/fjord,hoosteeno/fjord,rlr/fjord,Ritsyy/fjord,staranjeet/fjord,lgp171188/fjord,mozilla/fjord,Ritsyy/fjord,DESHRAJ/fjord,rlr/fjord,staranjeet/fjord,mozilla/fjord,staranjeet/fjord
from django.core.management import call_command from fjord.base.tests import TestCase class TestGenerateData(TestCase): def test_generate_data(self): """Make sure ./manage.py generatedata runs.""" call_command('generatedata') call_command('generatedata', bigsample=True) class TestPOLint(TestCase): def test_polint(self): """Make sure ./manage.py polint runs.""" # Note: This doesn't make sure it works--just that it doesn't kick # up obvious errors when it runs like if Dennis has changed in # some way that prevents it from working correctly. try: - call_command('polint') + call_command('polint', '--version') except SystemExit: # WOAH! WTF ARE YOU DOING? The lint command calls # sys.exit() because it needs to return correct exit codes # so we catch that here and ignore it. Otherwise testing # it will kill the test suite. pass
Adjust test_polint to be less stdout-spammy
## Code Before: from django.core.management import call_command from fjord.base.tests import TestCase class TestGenerateData(TestCase): def test_generate_data(self): """Make sure ./manage.py generatedata runs.""" call_command('generatedata') call_command('generatedata', bigsample=True) class TestPOLint(TestCase): def test_polint(self): """Make sure ./manage.py polint runs.""" # Note: This doesn't make sure it works--just that it doesn't kick # up obvious errors when it runs like if Dennis has changed in # some way that prevents it from working correctly. try: call_command('polint') except SystemExit: # WOAH! WTF ARE YOU DOING? The lint command calls # sys.exit() because it needs to return correct exit codes # so we catch that here and ignore it. Otherwise testing # it will kill the test suite. pass ## Instruction: Adjust test_polint to be less stdout-spammy ## Code After: from django.core.management import call_command from fjord.base.tests import TestCase class TestGenerateData(TestCase): def test_generate_data(self): """Make sure ./manage.py generatedata runs.""" call_command('generatedata') call_command('generatedata', bigsample=True) class TestPOLint(TestCase): def test_polint(self): """Make sure ./manage.py polint runs.""" # Note: This doesn't make sure it works--just that it doesn't kick # up obvious errors when it runs like if Dennis has changed in # some way that prevents it from working correctly. try: call_command('polint', '--version') except SystemExit: # WOAH! WTF ARE YOU DOING? The lint command calls # sys.exit() because it needs to return correct exit codes # so we catch that here and ignore it. Otherwise testing # it will kill the test suite. pass
// ... existing code ... try: call_command('polint', '--version') except SystemExit: # WOAH! WTF ARE YOU DOING? The lint command calls // ... rest of the code ...
04c82d00517428bc60e7c4204f01e55452c2c8f2
oscar_mws/receivers.py
oscar_mws/receivers.py
import logging from django.utils.translation import ugettext_lazy as _ from oscar_mws.fulfillment import gateway logger = logging.getLogger('oscar_mws') def submit_order_to_mws(order, user, **kwargs): if kwargs.get('raw', False): return from oscar_mws.fulfillment.creator import FulfillmentOrderCreator order_creator = FulfillmentOrderCreator() submitted_orders = order_creator.create_fulfillment_order(order) gateway.submit_fulfillment_orders(submitted_orders) if not order_creator.errors: logger.info( _("Successfully submitted {0} orders to Amazon").format( len(submitted_orders) ) ) else: for order_id, error in order_creator.errors.iteritems(): logger.error( _("Error submitting order {0} to Amazon: {1}").format( order_id, error ) )
import logging from django.utils.translation import ugettext_lazy as _ logger = logging.getLogger('oscar_mws') def submit_order_to_mws(order, user, **kwargs): if kwargs.get('raw', False): return # these modules have to be imported here because they rely on loading # models from oscar_mws using get_model which are not fully loaded at this # point because the receivers module is imported into models.py from oscar_mws.fulfillment import gateway from oscar_mws.fulfillment.creator import FulfillmentOrderCreator order_creator = FulfillmentOrderCreator() submitted_orders = order_creator.create_fulfillment_order(order) gateway.submit_fulfillment_orders(submitted_orders) if not order_creator.errors: logger.info( _("Successfully submitted {0} orders to Amazon").format( len(submitted_orders) ) ) else: for order_id, error in order_creator.errors.iteritems(): logger.error( _("Error submitting order {0} to Amazon: {1}").format( order_id, error ) )
Fix issue with importing models in fulfillment gateway
Fix issue with importing models in fulfillment gateway
Python
bsd-3-clause
django-oscar/django-oscar-mws,django-oscar/django-oscar-mws
import logging from django.utils.translation import ugettext_lazy as _ - - from oscar_mws.fulfillment import gateway logger = logging.getLogger('oscar_mws') def submit_order_to_mws(order, user, **kwargs): if kwargs.get('raw', False): return + # these modules have to be imported here because they rely on loading + # models from oscar_mws using get_model which are not fully loaded at this + # point because the receivers module is imported into models.py + from oscar_mws.fulfillment import gateway from oscar_mws.fulfillment.creator import FulfillmentOrderCreator order_creator = FulfillmentOrderCreator() submitted_orders = order_creator.create_fulfillment_order(order) gateway.submit_fulfillment_orders(submitted_orders) if not order_creator.errors: logger.info( _("Successfully submitted {0} orders to Amazon").format( len(submitted_orders) ) ) else: for order_id, error in order_creator.errors.iteritems(): logger.error( _("Error submitting order {0} to Amazon: {1}").format( order_id, error ) )
Fix issue with importing models in fulfillment gateway
## Code Before: import logging from django.utils.translation import ugettext_lazy as _ from oscar_mws.fulfillment import gateway logger = logging.getLogger('oscar_mws') def submit_order_to_mws(order, user, **kwargs): if kwargs.get('raw', False): return from oscar_mws.fulfillment.creator import FulfillmentOrderCreator order_creator = FulfillmentOrderCreator() submitted_orders = order_creator.create_fulfillment_order(order) gateway.submit_fulfillment_orders(submitted_orders) if not order_creator.errors: logger.info( _("Successfully submitted {0} orders to Amazon").format( len(submitted_orders) ) ) else: for order_id, error in order_creator.errors.iteritems(): logger.error( _("Error submitting order {0} to Amazon: {1}").format( order_id, error ) ) ## Instruction: Fix issue with importing models in fulfillment gateway ## Code After: import logging from django.utils.translation import ugettext_lazy as _ logger = logging.getLogger('oscar_mws') def submit_order_to_mws(order, user, **kwargs): if kwargs.get('raw', False): return # these modules have to be imported here because they rely on loading # models from oscar_mws using get_model which are not fully loaded at this # point because the receivers module is imported into models.py from oscar_mws.fulfillment import gateway from oscar_mws.fulfillment.creator import FulfillmentOrderCreator order_creator = FulfillmentOrderCreator() submitted_orders = order_creator.create_fulfillment_order(order) gateway.submit_fulfillment_orders(submitted_orders) if not order_creator.errors: logger.info( _("Successfully submitted {0} orders to Amazon").format( len(submitted_orders) ) ) else: for order_id, error in order_creator.errors.iteritems(): logger.error( _("Error submitting order {0} to Amazon: {1}").format( order_id, error ) )
// ... existing code ... from django.utils.translation import ugettext_lazy as _ logger = logging.getLogger('oscar_mws') // ... modified code ... return # these modules have to be imported here because they rely on loading # models from oscar_mws using get_model which are not fully loaded at this # point because the receivers module is imported into models.py from oscar_mws.fulfillment import gateway from oscar_mws.fulfillment.creator import FulfillmentOrderCreator // ... rest of the code ...
0c01cb42527fdc2a094d3cc3f2f99a75da6992fa
geoportailv3/models.py
geoportailv3/models.py
import logging from pyramid.i18n import TranslationStringFactory from c2cgeoportal.models import * # noqa _ = TranslationStringFactory('geoportailv3') log = logging.getLogger(__name__)
import logging from pyramid.i18n import TranslationStringFactory from c2cgeoportal.models import * # noqa from pyramid.security import Allow, ALL_PERMISSIONS from formalchemy import Column from sqlalchemy import ForeignKey from sqlalchemy.types import Integer, Boolean, Unicode from c2cgeoportal.models import AUTHORIZED_ROLE, _schema _ = TranslationStringFactory('geoportailv3') log = logging.getLogger(__name__) class LuxLayerInternalWMS(LayerInternalWMS): __label__ = _(u'Internal WMS layer') __plural__ = _(u'Internal WMS layers') __tablename__ = 'lux_layer_internal_wms' __table_args__ = {'schema': _schema} __acl__ = [ (Allow, AUTHORIZED_ROLE, ALL_PERMISSIONS), ] __mapper_args__ = {'polymorphic_identity': 'lu_int_wms'} id = Column( Integer, ForeignKey(_schema + '.layer_internal_wms.id'), primary_key=True ) url = Column(Unicode, label=_(u'Url')) layers = Column(Unicode, label=_(u'Layers')) class LuxLayerExternalWMS(LayerExternalWMS): __label__ = _(u'External WMS layer') __plural__ = _(u'External WMS layers') __tablename__ = 'lux_layer_external_wms' __table_args__ = {'schema': _schema} __acl__ = [ (Allow, AUTHORIZED_ROLE, ALL_PERMISSIONS), ] __mapper_args__ = {'polymorphic_identity': 'lu_ext_wms'} id = Column( Integer, ForeignKey(_schema + '.layer_external_wms.id'), primary_key=True ) category_id = Column(Integer, label=_(u'Category ID')) is_poi = Column(Boolean, label=_(u'Is a POI')) collection_id = Column(Integer, label=_(u'Collection ID')) class LuxRoleTheme(Base): __label__ = _(u'LuxRoleTheme') __plural__ = _(u'LuxRoleTheme') __tablename__ = 'lux_role_theme' __table_args__ = {'schema': _schema} __acl__ = [ (Allow, AUTHORIZED_ROLE, ALL_PERMISSIONS), ] theme_id = Column( Integer, ForeignKey(_schema + '.theme.id'), primary_key=True ) role_id = Column( Integer, label=_(u'Role ID'), primary_key=True )
Create the model for project specific tables
Create the model for project specific tables
Python
mit
Geoportail-Luxembourg/geoportailv3,Geoportail-Luxembourg/geoportailv3,Geoportail-Luxembourg/geoportailv3,Geoportail-Luxembourg/geoportailv3,geoportallux/geoportailv3-gisgr,geoportallux/geoportailv3-gisgr,geoportallux/geoportailv3-gisgr,Geoportail-Luxembourg/geoportailv3,geoportallux/geoportailv3-gisgr
import logging from pyramid.i18n import TranslationStringFactory from c2cgeoportal.models import * # noqa + from pyramid.security import Allow, ALL_PERMISSIONS + from formalchemy import Column + from sqlalchemy import ForeignKey + from sqlalchemy.types import Integer, Boolean, Unicode + from c2cgeoportal.models import AUTHORIZED_ROLE, _schema _ = TranslationStringFactory('geoportailv3') log = logging.getLogger(__name__) + + class LuxLayerInternalWMS(LayerInternalWMS): + __label__ = _(u'Internal WMS layer') + __plural__ = _(u'Internal WMS layers') + __tablename__ = 'lux_layer_internal_wms' + __table_args__ = {'schema': _schema} + __acl__ = [ + (Allow, AUTHORIZED_ROLE, ALL_PERMISSIONS), + ] + __mapper_args__ = {'polymorphic_identity': 'lu_int_wms'} + + id = Column( + Integer, + ForeignKey(_schema + '.layer_internal_wms.id'), + primary_key=True + ) + url = Column(Unicode, label=_(u'Url')) + layers = Column(Unicode, label=_(u'Layers')) + + + class LuxLayerExternalWMS(LayerExternalWMS): + __label__ = _(u'External WMS layer') + __plural__ = _(u'External WMS layers') + __tablename__ = 'lux_layer_external_wms' + __table_args__ = {'schema': _schema} + __acl__ = [ + (Allow, AUTHORIZED_ROLE, ALL_PERMISSIONS), + ] + __mapper_args__ = {'polymorphic_identity': 'lu_ext_wms'} + + id = Column( + Integer, + ForeignKey(_schema + '.layer_external_wms.id'), + primary_key=True + ) + category_id = Column(Integer, label=_(u'Category ID')) + is_poi = Column(Boolean, label=_(u'Is a POI')) + collection_id = Column(Integer, label=_(u'Collection ID')) + + + class LuxRoleTheme(Base): + __label__ = _(u'LuxRoleTheme') + __plural__ = _(u'LuxRoleTheme') + __tablename__ = 'lux_role_theme' + __table_args__ = {'schema': _schema} + __acl__ = [ + (Allow, AUTHORIZED_ROLE, ALL_PERMISSIONS), + ] + + theme_id = Column( + Integer, + ForeignKey(_schema + '.theme.id'), + primary_key=True + ) + role_id = Column( + Integer, + label=_(u'Role ID'), + primary_key=True + ) +
Create the model for project specific tables
## Code Before: import logging from pyramid.i18n import TranslationStringFactory from c2cgeoportal.models import * # noqa _ = TranslationStringFactory('geoportailv3') log = logging.getLogger(__name__) ## Instruction: Create the model for project specific tables ## Code After: import logging from pyramid.i18n import TranslationStringFactory from c2cgeoportal.models import * # noqa from pyramid.security import Allow, ALL_PERMISSIONS from formalchemy import Column from sqlalchemy import ForeignKey from sqlalchemy.types import Integer, Boolean, Unicode from c2cgeoportal.models import AUTHORIZED_ROLE, _schema _ = TranslationStringFactory('geoportailv3') log = logging.getLogger(__name__) class LuxLayerInternalWMS(LayerInternalWMS): __label__ = _(u'Internal WMS layer') __plural__ = _(u'Internal WMS layers') __tablename__ = 'lux_layer_internal_wms' __table_args__ = {'schema': _schema} __acl__ = [ (Allow, AUTHORIZED_ROLE, ALL_PERMISSIONS), ] __mapper_args__ = {'polymorphic_identity': 'lu_int_wms'} id = Column( Integer, ForeignKey(_schema + '.layer_internal_wms.id'), primary_key=True ) url = Column(Unicode, label=_(u'Url')) layers = Column(Unicode, label=_(u'Layers')) class LuxLayerExternalWMS(LayerExternalWMS): __label__ = _(u'External WMS layer') __plural__ = _(u'External WMS layers') __tablename__ = 'lux_layer_external_wms' __table_args__ = {'schema': _schema} __acl__ = [ (Allow, AUTHORIZED_ROLE, ALL_PERMISSIONS), ] __mapper_args__ = {'polymorphic_identity': 'lu_ext_wms'} id = Column( Integer, ForeignKey(_schema + '.layer_external_wms.id'), primary_key=True ) category_id = Column(Integer, label=_(u'Category ID')) is_poi = Column(Boolean, label=_(u'Is a POI')) collection_id = Column(Integer, label=_(u'Collection ID')) class LuxRoleTheme(Base): __label__ = _(u'LuxRoleTheme') __plural__ = _(u'LuxRoleTheme') __tablename__ = 'lux_role_theme' __table_args__ = {'schema': _schema} __acl__ = [ (Allow, AUTHORIZED_ROLE, ALL_PERMISSIONS), ] theme_id = Column( Integer, ForeignKey(_schema + '.theme.id'), primary_key=True ) role_id = Column( Integer, label=_(u'Role ID'), primary_key=True )
// ... existing code ... from c2cgeoportal.models import * # noqa from pyramid.security import Allow, ALL_PERMISSIONS from formalchemy import Column from sqlalchemy import ForeignKey from sqlalchemy.types import Integer, Boolean, Unicode from c2cgeoportal.models import AUTHORIZED_ROLE, _schema _ = TranslationStringFactory('geoportailv3') log = logging.getLogger(__name__) class LuxLayerInternalWMS(LayerInternalWMS): __label__ = _(u'Internal WMS layer') __plural__ = _(u'Internal WMS layers') __tablename__ = 'lux_layer_internal_wms' __table_args__ = {'schema': _schema} __acl__ = [ (Allow, AUTHORIZED_ROLE, ALL_PERMISSIONS), ] __mapper_args__ = {'polymorphic_identity': 'lu_int_wms'} id = Column( Integer, ForeignKey(_schema + '.layer_internal_wms.id'), primary_key=True ) url = Column(Unicode, label=_(u'Url')) layers = Column(Unicode, label=_(u'Layers')) class LuxLayerExternalWMS(LayerExternalWMS): __label__ = _(u'External WMS layer') __plural__ = _(u'External WMS layers') __tablename__ = 'lux_layer_external_wms' __table_args__ = {'schema': _schema} __acl__ = [ (Allow, AUTHORIZED_ROLE, ALL_PERMISSIONS), ] __mapper_args__ = {'polymorphic_identity': 'lu_ext_wms'} id = Column( Integer, ForeignKey(_schema + '.layer_external_wms.id'), primary_key=True ) category_id = Column(Integer, label=_(u'Category ID')) is_poi = Column(Boolean, label=_(u'Is a POI')) collection_id = Column(Integer, label=_(u'Collection ID')) class LuxRoleTheme(Base): __label__ = _(u'LuxRoleTheme') __plural__ = _(u'LuxRoleTheme') __tablename__ = 'lux_role_theme' __table_args__ = {'schema': _schema} __acl__ = [ (Allow, AUTHORIZED_ROLE, ALL_PERMISSIONS), ] theme_id = Column( Integer, ForeignKey(_schema + '.theme.id'), primary_key=True ) role_id = Column( Integer, label=_(u'Role ID'), primary_key=True ) // ... rest of the code ...
40a59efec51661d4325e97f2e307963811336b94
calaccess_processed/__init__.py
calaccess_processed/__init__.py
from __future__ import absolute_import default_app_config = 'calaccess_processed.apps.CalAccessProcessedConfig'
import os default_app_config = 'calaccess_processed.apps.CalAccessProcessedConfig' def get_model_list(): """ Returns a model list of """ from django.apps import apps model_list = apps.get_app_config("calaccess_processed").models.values() return [ m for m in model_list if m.__module__.split('.')[-1] != 'tracking' ] def archive_directory_path(instance, filename): """ Returns a path to an archived processed data file or zip """ from calaccess_processed.models.tracking import ( ProcessedDataVersion, ProcessedDataFile, ) if isinstance(instance, ProcessedDataVersion): release_datetime = instance.raw_version.release_datetime f_name, f_ext = filename.split('.') path = '{fn}_{dt:%Y-%m-%d_%H-%M-%S}.{fx}'.format( fn=f_name, dt=release_datetime, fx=f_ext, ) elif isinstance(instance, ProcessedDataFile): release_datetime = instance.version.raw_version.release_datetime path = '{dt:%Y-%m-%d_%H-%M-%S}/{f}'.format(dt=release_datetime, f=filename) else: raise TypeError( "Must be ProcessedDataVersion or ProcessedDataFile instance." ) return path
Add get_model_list and archive_directory_path functions
Add get_model_list and archive_directory_path functions
Python
mit
california-civic-data-coalition/django-calaccess-processed-data,california-civic-data-coalition/django-calaccess-processed-data
- from __future__ import absolute_import + import os default_app_config = 'calaccess_processed.apps.CalAccessProcessedConfig' + + def get_model_list(): + """ + Returns a model list of + """ + from django.apps import apps + model_list = apps.get_app_config("calaccess_processed").models.values() + return [ + m for m in model_list + if m.__module__.split('.')[-1] != 'tracking' + ] + + def archive_directory_path(instance, filename): + """ + Returns a path to an archived processed data file or zip + """ + from calaccess_processed.models.tracking import ( + ProcessedDataVersion, + ProcessedDataFile, + ) + + if isinstance(instance, ProcessedDataVersion): + release_datetime = instance.raw_version.release_datetime + f_name, f_ext = filename.split('.') + path = '{fn}_{dt:%Y-%m-%d_%H-%M-%S}.{fx}'.format( + fn=f_name, + dt=release_datetime, + fx=f_ext, + ) + elif isinstance(instance, ProcessedDataFile): + release_datetime = instance.version.raw_version.release_datetime + path = '{dt:%Y-%m-%d_%H-%M-%S}/{f}'.format(dt=release_datetime, f=filename) + else: + raise TypeError( + "Must be ProcessedDataVersion or ProcessedDataFile instance." + ) + return path +
Add get_model_list and archive_directory_path functions
## Code Before: from __future__ import absolute_import default_app_config = 'calaccess_processed.apps.CalAccessProcessedConfig' ## Instruction: Add get_model_list and archive_directory_path functions ## Code After: import os default_app_config = 'calaccess_processed.apps.CalAccessProcessedConfig' def get_model_list(): """ Returns a model list of """ from django.apps import apps model_list = apps.get_app_config("calaccess_processed").models.values() return [ m for m in model_list if m.__module__.split('.')[-1] != 'tracking' ] def archive_directory_path(instance, filename): """ Returns a path to an archived processed data file or zip """ from calaccess_processed.models.tracking import ( ProcessedDataVersion, ProcessedDataFile, ) if isinstance(instance, ProcessedDataVersion): release_datetime = instance.raw_version.release_datetime f_name, f_ext = filename.split('.') path = '{fn}_{dt:%Y-%m-%d_%H-%M-%S}.{fx}'.format( fn=f_name, dt=release_datetime, fx=f_ext, ) elif isinstance(instance, ProcessedDataFile): release_datetime = instance.version.raw_version.release_datetime path = '{dt:%Y-%m-%d_%H-%M-%S}/{f}'.format(dt=release_datetime, f=filename) else: raise TypeError( "Must be ProcessedDataVersion or ProcessedDataFile instance." ) return path
... import os default_app_config = 'calaccess_processed.apps.CalAccessProcessedConfig' def get_model_list(): """ Returns a model list of """ from django.apps import apps model_list = apps.get_app_config("calaccess_processed").models.values() return [ m for m in model_list if m.__module__.split('.')[-1] != 'tracking' ] def archive_directory_path(instance, filename): """ Returns a path to an archived processed data file or zip """ from calaccess_processed.models.tracking import ( ProcessedDataVersion, ProcessedDataFile, ) if isinstance(instance, ProcessedDataVersion): release_datetime = instance.raw_version.release_datetime f_name, f_ext = filename.split('.') path = '{fn}_{dt:%Y-%m-%d_%H-%M-%S}.{fx}'.format( fn=f_name, dt=release_datetime, fx=f_ext, ) elif isinstance(instance, ProcessedDataFile): release_datetime = instance.version.raw_version.release_datetime path = '{dt:%Y-%m-%d_%H-%M-%S}/{f}'.format(dt=release_datetime, f=filename) else: raise TypeError( "Must be ProcessedDataVersion or ProcessedDataFile instance." ) return path ...
233ce96d96caff3070f24d9d3dff3ed85be81fee
halaqat/settings/shaha.py
halaqat/settings/shaha.py
from .base_settings import * import dj_database_url import os ALLOWED_HOSTS = ['0.0.0.0'] db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') STATIC_URL = '/static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, 'static'), ) # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
from .base_settings import * import dj_database_url import os ALLOWED_HOSTS = ['0.0.0.0'] db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') STATIC_URL = '/static/' # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
Fix The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting
Fix The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting
Python
mit
EmadMokhtar/halaqat,EmadMokhtar/halaqat,EmadMokhtar/halaqat
from .base_settings import * import dj_database_url import os ALLOWED_HOSTS = ['0.0.0.0'] db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') STATIC_URL = '/static/' - # Extra places for collectstatic to find static files. - STATICFILES_DIRS = ( - os.path.join(PROJECT_ROOT, 'static'), - ) - # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
Fix The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting
## Code Before: from .base_settings import * import dj_database_url import os ALLOWED_HOSTS = ['0.0.0.0'] db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') STATIC_URL = '/static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, 'static'), ) # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' ## Instruction: Fix The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting ## Code After: from .base_settings import * import dj_database_url import os ALLOWED_HOSTS = ['0.0.0.0'] db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') STATIC_URL = '/static/' # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
# ... existing code ... STATIC_URL = '/static/' # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ # ... rest of the code ...
a233f685f6cb514420fd534388d51ee92459d886
src/diamond/__init__.py
src/diamond/__init__.py
import os import sys import string import logging import time import traceback import configobj import socket import re import os import sys import re import logging import time import datetime import random import urllib2 import base64 import csv import platform import string import traceback import configobj import socket from urlparse import urlparse
import os import sys import logging import time import traceback import configobj import socket import re import datetime import random import urllib2 import base64 import csv import platform from urlparse import urlparse
Remove duplicate imports and remove entirly unused string
Remove duplicate imports and remove entirly unused string
Python
mit
szibis/Diamond,russss/Diamond,TAKEALOT/Diamond,szibis/Diamond,signalfx/Diamond,dcsquared13/Diamond,python-diamond/Diamond,eMerzh/Diamond-1,jumping/Diamond,codepython/Diamond,socialwareinc/Diamond,actmd/Diamond,cannium/Diamond,Slach/Diamond,eMerzh/Diamond-1,saucelabs/Diamond,zoidbergwill/Diamond,disqus/Diamond,bmhatfield/Diamond,Slach/Diamond,cannium/Diamond,tusharmakkar08/Diamond,actmd/Diamond,saucelabs/Diamond,TAKEALOT/Diamond,jaingaurav/Diamond,MediaMath/Diamond,Ormod/Diamond,TAKEALOT/Diamond,Ssawa/Diamond,Nihn/Diamond-1,timchenxiaoyu/Diamond,bmhatfield/Diamond,mzupan/Diamond,CYBERBUGJR/Diamond,sebbrandt87/Diamond,Basis/Diamond,Netuitive/netuitive-diamond,tellapart/Diamond,gg7/diamond,hvnsweeting/Diamond,skbkontur/Diamond,actmd/Diamond,jriguera/Diamond,MediaMath/Diamond,stuartbfox/Diamond,Precis/Diamond,MichaelDoyle/Diamond,cannium/Diamond,stuartbfox/Diamond,Netuitive/Diamond,TinLe/Diamond,russss/Diamond,CYBERBUGJR/Diamond,dcsquared13/Diamond,TinLe/Diamond,zoidbergwill/Diamond,krbaker/Diamond,Nihn/Diamond-1,signalfx/Diamond,metamx/Diamond,Basis/Diamond,rtoma/Diamond,disqus/Diamond,saucelabs/Diamond,Ormod/Diamond,bmhatfield/Diamond,Ensighten/Diamond,jaingaurav/Diamond,TAKEALOT/Diamond,datafiniti/Diamond,datafiniti/Diamond,sebbrandt87/Diamond,actmd/Diamond,ceph/Diamond,timchenxiaoyu/Diamond,Precis/Diamond,jaingaurav/Diamond,anandbhoraskar/Diamond,Ensighten/Diamond,janisz/Diamond-1,metamx/Diamond,MediaMath/Diamond,acquia/Diamond,CYBERBUGJR/Diamond,Slach/Diamond,thardie/Diamond,signalfx/Diamond,signalfx/Diamond,Precis/Diamond,tusharmakkar08/Diamond,works-mobile/Diamond,tuenti/Diamond,rtoma/Diamond,joel-airspring/Diamond,CYBERBUGJR/Diamond,Ormod/Diamond,codepython/Diamond,joel-airspring/Diamond,Basis/Diamond,krbaker/Diamond,TinLe/Diamond,mfriedenhagen/Diamond,skbkontur/Diamond,eMerzh/Diamond-1,python-diamond/Diamond,krbaker/Diamond,disqus/Diamond,anandbhoraskar/Diamond,rtoma/Diamond,hvnsweeting/Diamond,janisz/Diamond-1,skbkontur/Diamond,hvnsweeting/Diamond,tuenti/Diamond,hamelg/Diamond,szibis/Diamond,stuartbfox/Diamond,janisz/Diamond-1,rtoma/Diamond,dcsquared13/Diamond,socialwareinc/Diamond,timchenxiaoyu/Diamond,sebbrandt87/Diamond,sebbrandt87/Diamond,acquia/Diamond,krbaker/Diamond,EzyInsights/Diamond,anandbhoraskar/Diamond,jumping/Diamond,tellapart/Diamond,EzyInsights/Diamond,thardie/Diamond,gg7/diamond,cannium/Diamond,Nihn/Diamond-1,socialwareinc/Diamond,Slach/Diamond,Basis/Diamond,skbkontur/Diamond,Ensighten/Diamond,janisz/Diamond-1,EzyInsights/Diamond,python-diamond/Diamond,codepython/Diamond,Clever/Diamond,hvnsweeting/Diamond,Ssawa/Diamond,ramjothikumar/Diamond,saucelabs/Diamond,EzyInsights/Diamond,Netuitive/netuitive-diamond,Netuitive/netuitive-diamond,szibis/Diamond,socialwareinc/Diamond,joel-airspring/Diamond,Ssawa/Diamond,gg7/diamond,Ensighten/Diamond,Clever/Diamond,h00dy/Diamond,gg7/diamond,MichaelDoyle/Diamond,bmhatfield/Diamond,Netuitive/netuitive-diamond,Precis/Diamond,joel-airspring/Diamond,ramjothikumar/Diamond,Netuitive/Diamond,MichaelDoyle/Diamond,timchenxiaoyu/Diamond,mfriedenhagen/Diamond,mzupan/Diamond,anandbhoraskar/Diamond,tellapart/Diamond,ramjothikumar/Diamond,datafiniti/Diamond,hamelg/Diamond,ramjothikumar/Diamond,codepython/Diamond,thardie/Diamond,jriguera/Diamond,h00dy/Diamond,h00dy/Diamond,jriguera/Diamond,Clever/Diamond,russss/Diamond,hamelg/Diamond,zoidbergwill/Diamond,mfriedenhagen/Diamond,jaingaurav/Diamond,hamelg/Diamond,Ssawa/Diamond,thardie/Diamond,mzupan/Diamond,tellapart/Diamond,ceph/Diamond,zoidbergwill/Diamond,datafiniti/Diamond,works-mobile/Diamond,Nihn/Diamond-1,tuenti/Diamond,acquia/Diamond,tusharmakkar08/Diamond,h00dy/Diamond,TinLe/Diamond,jriguera/Diamond,tuenti/Diamond,jumping/Diamond,Netuitive/Diamond,eMerzh/Diamond-1,works-mobile/Diamond,ceph/Diamond,MichaelDoyle/Diamond,Ormod/Diamond,jumping/Diamond,tusharmakkar08/Diamond,dcsquared13/Diamond,Clever/Diamond,ceph/Diamond,stuartbfox/Diamond,acquia/Diamond,works-mobile/Diamond,mfriedenhagen/Diamond,Netuitive/Diamond,metamx/Diamond,russss/Diamond,MediaMath/Diamond,mzupan/Diamond
import os import sys - import string import logging import time import traceback import configobj import socket import re - import os - import sys - import re - import logging - import time import datetime import random import urllib2 import base64 import csv import platform - import string - import traceback - import configobj - import socket from urlparse import urlparse
Remove duplicate imports and remove entirly unused string
## Code Before: import os import sys import string import logging import time import traceback import configobj import socket import re import os import sys import re import logging import time import datetime import random import urllib2 import base64 import csv import platform import string import traceback import configobj import socket from urlparse import urlparse ## Instruction: Remove duplicate imports and remove entirly unused string ## Code After: import os import sys import logging import time import traceback import configobj import socket import re import datetime import random import urllib2 import base64 import csv import platform from urlparse import urlparse
# ... existing code ... import os import sys import logging import time # ... modified code ... import socket import re import datetime import random ... import csv import platform from urlparse import urlparse # ... rest of the code ...
21a4c6c5cdf3461ef2bd6048a7399044e8b1a0e8
spyder_unittest/backend/pytestworker.py
spyder_unittest/backend/pytestworker.py
# Standard library imports import sys # Third party imports import pytest pytest.main(sys.argv[1:])
# Standard library imports import sys # Third party imports import pytest class SpyderPlugin(): """Pytest plugin which reports in format suitable for Spyder.""" def pytest_itemcollected(self, item): """Called by py.test when a test item is collected.""" name = item.name module = item.parent.name module = module.replace('/', '.') # convert path to dotted path if module.endswith('.py'): module = module[:-3] print('pytest_item_collected(name={}, module={})'.format(name, module)) pytest.main(sys.argv[1:], plugins=[SpyderPlugin()])
Add py.test plugin which prints out test names as they are collected
Add py.test plugin which prints out test names as they are collected
Python
mit
jitseniesen/spyder-unittest
# Standard library imports import sys # Third party imports import pytest - pytest.main(sys.argv[1:]) + class SpyderPlugin(): + """Pytest plugin which reports in format suitable for Spyder.""" + + def pytest_itemcollected(self, item): + """Called by py.test when a test item is collected.""" + name = item.name + module = item.parent.name + module = module.replace('/', '.') # convert path to dotted path + if module.endswith('.py'): + module = module[:-3] + print('pytest_item_collected(name={}, module={})'.format(name, module)) + + + pytest.main(sys.argv[1:], plugins=[SpyderPlugin()]) +
Add py.test plugin which prints out test names as they are collected
## Code Before: # Standard library imports import sys # Third party imports import pytest pytest.main(sys.argv[1:]) ## Instruction: Add py.test plugin which prints out test names as they are collected ## Code After: # Standard library imports import sys # Third party imports import pytest class SpyderPlugin(): """Pytest plugin which reports in format suitable for Spyder.""" def pytest_itemcollected(self, item): """Called by py.test when a test item is collected.""" name = item.name module = item.parent.name module = module.replace('/', '.') # convert path to dotted path if module.endswith('.py'): module = module[:-3] print('pytest_item_collected(name={}, module={})'.format(name, module)) pytest.main(sys.argv[1:], plugins=[SpyderPlugin()])
# ... existing code ... import pytest class SpyderPlugin(): """Pytest plugin which reports in format suitable for Spyder.""" def pytest_itemcollected(self, item): """Called by py.test when a test item is collected.""" name = item.name module = item.parent.name module = module.replace('/', '.') # convert path to dotted path if module.endswith('.py'): module = module[:-3] print('pytest_item_collected(name={}, module={})'.format(name, module)) pytest.main(sys.argv[1:], plugins=[SpyderPlugin()]) # ... rest of the code ...
dc82d59b739934d093ed0d704583e7edf1278fc3
core/management/commands/delete_old_sessions.py
core/management/commands/delete_old_sessions.py
from datetime import datetime from django.core.management.base import BaseCommand from django.contrib.sessions.models import Session class Command(BaseCommand): args = '<count count ...>' help = "Delete old sessions" def handle(self, *args, **options): old_sessions = Session.objects.filter(expire_date__lt=datetime.now()) self.stdout.write("Deleting {0} expired sessions".format( old_sessions.count() ) ) for index, session in enumerate(old_sessions): session.delete() if str(index).endswith('000'): self.stdout.write("{0} records deleted".format(index)) self.stdout.write("{0} expired sessions remaining".format( Session.objects.filter(expire_date__lt=datetime.now()) ) )
from datetime import datetime from django.core.management.base import NoArgsCommand from django.contrib.sessions.models import Session class Command(NoArgsCommand): help = "Delete old sessions" def handle_noargs(self, **options): old_sessions = Session.objects.filter(expire_date__lt=datetime.now()) self.stdout.write("Deleting {0} expired sessions".format( old_sessions.count() ) ) for index, session in enumerate(old_sessions)[:10000]: session.delete() if str(index).endswith('000'): self.stdout.write("{0} records deleted".format(index)) self.stdout.write("{0} expired sessions remaining".format( Session.objects.filter(expire_date__lt=datetime.now()) ) )
Add delete old sessions command
Add delete old sessions command
Python
mit
QLGu/djangopackages,nanuxbe/djangopackages,pydanny/djangopackages,QLGu/djangopackages,pydanny/djangopackages,pydanny/djangopackages,nanuxbe/djangopackages,QLGu/djangopackages,nanuxbe/djangopackages
from datetime import datetime - from django.core.management.base import BaseCommand + from django.core.management.base import NoArgsCommand from django.contrib.sessions.models import Session - class Command(BaseCommand): + class Command(NoArgsCommand): - args = '<count count ...>' help = "Delete old sessions" - def handle(self, *args, **options): + def handle_noargs(self, **options): old_sessions = Session.objects.filter(expire_date__lt=datetime.now()) self.stdout.write("Deleting {0} expired sessions".format( old_sessions.count() ) ) - for index, session in enumerate(old_sessions): + for index, session in enumerate(old_sessions)[:10000]: session.delete() if str(index).endswith('000'): self.stdout.write("{0} records deleted".format(index)) self.stdout.write("{0} expired sessions remaining".format( Session.objects.filter(expire_date__lt=datetime.now()) ) )
Add delete old sessions command
## Code Before: from datetime import datetime from django.core.management.base import BaseCommand from django.contrib.sessions.models import Session class Command(BaseCommand): args = '<count count ...>' help = "Delete old sessions" def handle(self, *args, **options): old_sessions = Session.objects.filter(expire_date__lt=datetime.now()) self.stdout.write("Deleting {0} expired sessions".format( old_sessions.count() ) ) for index, session in enumerate(old_sessions): session.delete() if str(index).endswith('000'): self.stdout.write("{0} records deleted".format(index)) self.stdout.write("{0} expired sessions remaining".format( Session.objects.filter(expire_date__lt=datetime.now()) ) ) ## Instruction: Add delete old sessions command ## Code After: from datetime import datetime from django.core.management.base import NoArgsCommand from django.contrib.sessions.models import Session class Command(NoArgsCommand): help = "Delete old sessions" def handle_noargs(self, **options): old_sessions = Session.objects.filter(expire_date__lt=datetime.now()) self.stdout.write("Deleting {0} expired sessions".format( old_sessions.count() ) ) for index, session in enumerate(old_sessions)[:10000]: session.delete() if str(index).endswith('000'): self.stdout.write("{0} records deleted".format(index)) self.stdout.write("{0} expired sessions remaining".format( Session.objects.filter(expire_date__lt=datetime.now()) ) )
... from datetime import datetime from django.core.management.base import NoArgsCommand from django.contrib.sessions.models import Session class Command(NoArgsCommand): help = "Delete old sessions" def handle_noargs(self, **options): old_sessions = Session.objects.filter(expire_date__lt=datetime.now()) ... ) for index, session in enumerate(old_sessions)[:10000]: session.delete() if str(index).endswith('000'): ...
005c6ceae1b80f5092e78231242b01af2ba64fed
tests/integration/api/conftest.py
tests/integration/api/conftest.py
import pytest from tests.base import create_admin_app from tests.conftest import CONFIG_PATH_DATA_KEY from .helpers import assemble_authorization_header API_TOKEN = 'just-say-PLEASE!' @pytest.fixture(scope='session') def app(admin_app, data_path): config_overrides = { 'API_TOKEN': API_TOKEN, CONFIG_PATH_DATA_KEY: data_path, 'SERVER_NAME': 'api.acmecon.test', } app = create_admin_app(config_overrides) with app.app_context(): yield app @pytest.fixture(scope='session') def api_client(app): """Provide a test HTTP client against the API.""" return app.test_client() @pytest.fixture(scope='session') def api_client_authz_header(): """Provide a test HTTP client against the API.""" return assemble_authorization_header(API_TOKEN)
import pytest from tests.base import create_admin_app from tests.conftest import CONFIG_PATH_DATA_KEY from .helpers import assemble_authorization_header API_TOKEN = 'just-say-PLEASE!' @pytest.fixture(scope='session') # `admin_app` fixture is required because it sets up the database. def app(admin_app, make_admin_app): config_overrides = { 'API_TOKEN': API_TOKEN, 'SERVER_NAME': 'api.acmecon.test', } app = make_admin_app(**config_overrides) with app.app_context(): yield app @pytest.fixture(scope='session') def api_client(app): """Provide a test HTTP client against the API.""" return app.test_client() @pytest.fixture(scope='session') def api_client_authz_header(): """Provide a test HTTP client against the API.""" return assemble_authorization_header(API_TOKEN)
Use `make_admin_app`, document why `admin_app` is still needed
Use `make_admin_app`, document why `admin_app` is still needed
Python
bsd-3-clause
homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps
import pytest from tests.base import create_admin_app from tests.conftest import CONFIG_PATH_DATA_KEY from .helpers import assemble_authorization_header API_TOKEN = 'just-say-PLEASE!' @pytest.fixture(scope='session') - def app(admin_app, data_path): + # `admin_app` fixture is required because it sets up the database. + def app(admin_app, make_admin_app): config_overrides = { 'API_TOKEN': API_TOKEN, - CONFIG_PATH_DATA_KEY: data_path, 'SERVER_NAME': 'api.acmecon.test', } - app = create_admin_app(config_overrides) + app = make_admin_app(**config_overrides) with app.app_context(): yield app @pytest.fixture(scope='session') def api_client(app): """Provide a test HTTP client against the API.""" return app.test_client() @pytest.fixture(scope='session') def api_client_authz_header(): """Provide a test HTTP client against the API.""" return assemble_authorization_header(API_TOKEN)
Use `make_admin_app`, document why `admin_app` is still needed
## Code Before: import pytest from tests.base import create_admin_app from tests.conftest import CONFIG_PATH_DATA_KEY from .helpers import assemble_authorization_header API_TOKEN = 'just-say-PLEASE!' @pytest.fixture(scope='session') def app(admin_app, data_path): config_overrides = { 'API_TOKEN': API_TOKEN, CONFIG_PATH_DATA_KEY: data_path, 'SERVER_NAME': 'api.acmecon.test', } app = create_admin_app(config_overrides) with app.app_context(): yield app @pytest.fixture(scope='session') def api_client(app): """Provide a test HTTP client against the API.""" return app.test_client() @pytest.fixture(scope='session') def api_client_authz_header(): """Provide a test HTTP client against the API.""" return assemble_authorization_header(API_TOKEN) ## Instruction: Use `make_admin_app`, document why `admin_app` is still needed ## Code After: import pytest from tests.base import create_admin_app from tests.conftest import CONFIG_PATH_DATA_KEY from .helpers import assemble_authorization_header API_TOKEN = 'just-say-PLEASE!' @pytest.fixture(scope='session') # `admin_app` fixture is required because it sets up the database. def app(admin_app, make_admin_app): config_overrides = { 'API_TOKEN': API_TOKEN, 'SERVER_NAME': 'api.acmecon.test', } app = make_admin_app(**config_overrides) with app.app_context(): yield app @pytest.fixture(scope='session') def api_client(app): """Provide a test HTTP client against the API.""" return app.test_client() @pytest.fixture(scope='session') def api_client_authz_header(): """Provide a test HTTP client against the API.""" return assemble_authorization_header(API_TOKEN)
// ... existing code ... @pytest.fixture(scope='session') # `admin_app` fixture is required because it sets up the database. def app(admin_app, make_admin_app): config_overrides = { 'API_TOKEN': API_TOKEN, 'SERVER_NAME': 'api.acmecon.test', } app = make_admin_app(**config_overrides) with app.app_context(): yield app // ... rest of the code ...
c2b3173a1246538d0b11a89a696288e41993eb5a
paws/conf.py
paws/conf.py
import os class env(object): def __init__(self, default=None): self.name = None self.default = default def __get__(self, obj, cls=None): if cls: return os.environ.get(self.name.upper(), self.default) class MetaConfig(type): '''Quickly tell the env attrs their names.''' def __new__(mcs, name, bases, attrs): for name, attr in attrs.items(): if isinstance(attr, env): env.name = name return super(MetaConfig, mcs).__new__(mcs, name, bases, attrs) class Conf(dict): ''' Handy wrapper and placeholder of config values. ''' __metaclass__ = MetaConfig def __getattr__(self, key): return os.environ[key]
import os class env(object): def __init__(self, default=None): self.name = None self.default = default def __get__(self, obj, cls=None): if not obj: return self return os.environ.get(self.name.upper(), self.default) class MetaConfig(type): '''Quickly tell the env attrs their names.''' def __new__(mcs, name, bases, attrs): for name, attr in attrs.items(): if isinstance(attr, env): attr.name = name return super(MetaConfig, mcs).__new__(mcs, name, bases, attrs) class Conf(dict): ''' Handy wrapper and placeholder of config values. ''' __metaclass__ = MetaConfig def __getattr__(self, key): return os.environ[key]
Fix detecting class access of descriptor. Set name on attr, not env class!
Fix detecting class access of descriptor. Set name on attr, not env class!
Python
bsd-3-clause
funkybob/paws
import os class env(object): def __init__(self, default=None): self.name = None self.default = default def __get__(self, obj, cls=None): - if cls: + if not obj: + return self - return os.environ.get(self.name.upper(), self.default) + return os.environ.get(self.name.upper(), self.default) class MetaConfig(type): '''Quickly tell the env attrs their names.''' def __new__(mcs, name, bases, attrs): for name, attr in attrs.items(): if isinstance(attr, env): - env.name = name + attr.name = name return super(MetaConfig, mcs).__new__(mcs, name, bases, attrs) class Conf(dict): ''' Handy wrapper and placeholder of config values. ''' __metaclass__ = MetaConfig def __getattr__(self, key): return os.environ[key]
Fix detecting class access of descriptor. Set name on attr, not env class!
## Code Before: import os class env(object): def __init__(self, default=None): self.name = None self.default = default def __get__(self, obj, cls=None): if cls: return os.environ.get(self.name.upper(), self.default) class MetaConfig(type): '''Quickly tell the env attrs their names.''' def __new__(mcs, name, bases, attrs): for name, attr in attrs.items(): if isinstance(attr, env): env.name = name return super(MetaConfig, mcs).__new__(mcs, name, bases, attrs) class Conf(dict): ''' Handy wrapper and placeholder of config values. ''' __metaclass__ = MetaConfig def __getattr__(self, key): return os.environ[key] ## Instruction: Fix detecting class access of descriptor. Set name on attr, not env class! ## Code After: import os class env(object): def __init__(self, default=None): self.name = None self.default = default def __get__(self, obj, cls=None): if not obj: return self return os.environ.get(self.name.upper(), self.default) class MetaConfig(type): '''Quickly tell the env attrs their names.''' def __new__(mcs, name, bases, attrs): for name, attr in attrs.items(): if isinstance(attr, env): attr.name = name return super(MetaConfig, mcs).__new__(mcs, name, bases, attrs) class Conf(dict): ''' Handy wrapper and placeholder of config values. ''' __metaclass__ = MetaConfig def __getattr__(self, key): return os.environ[key]
... def __get__(self, obj, cls=None): if not obj: return self return os.environ.get(self.name.upper(), self.default) ... for name, attr in attrs.items(): if isinstance(attr, env): attr.name = name return super(MetaConfig, mcs).__new__(mcs, name, bases, attrs) ...
eb9fa38f2c4c82a5674474f9a535bc8c35f8e38e
tests/test_bookmarks.py
tests/test_bookmarks.py
import bookmarks import unittest class FlaskrTestCase(unittest.TestCase): def setUp(self): bookmarks.app.config['DATABASE_NAME'] = bookmarks.app.config['TEST_DATABASE_NAME'] bookmarks.app.testing = True self.app = bookmarks.app.test_client() with bookmarks.app.app_context(): bookmarks.database.init_db() # def tearDown(self): # os.close(self.db_fd) # os.unlink(bookmarks.app.config['DATABASE']) def test_empty_db(self): rv = self.app.get('/') assert b'There aren\'t any bookmarks yet.' in rv.data if __name__ == '__main__': unittest.main()
import bookmarks import unittest class FlaskrTestCase(unittest.TestCase): def setUp(self): self.app = bookmarks.app.test_client() with bookmarks.app.app_context(): bookmarks.database.init_db() def tearDown(self): with bookmarks.app.app_context(): bookmarks.database.db_session.remove() bookmarks.database.Base.metadata.drop_all( bind=bookmarks.database.engine) def test_empty_db(self): rv = self.app.get('/') assert b'There aren\'t any bookmarks yet.' in rv.data if __name__ == '__main__': unittest.main()
Adjust test file to match new env config options
Adjust test file to match new env config options
Python
apache-2.0
byanofsky/bookmarks,byanofsky/bookmarks,byanofsky/bookmarks
import bookmarks import unittest class FlaskrTestCase(unittest.TestCase): def setUp(self): - bookmarks.app.config['DATABASE_NAME'] = bookmarks.app.config['TEST_DATABASE_NAME'] - bookmarks.app.testing = True self.app = bookmarks.app.test_client() with bookmarks.app.app_context(): bookmarks.database.init_db() - # def tearDown(self): + def tearDown(self): - # os.close(self.db_fd) - # os.unlink(bookmarks.app.config['DATABASE']) + with bookmarks.app.app_context(): + bookmarks.database.db_session.remove() + bookmarks.database.Base.metadata.drop_all( + bind=bookmarks.database.engine) def test_empty_db(self): rv = self.app.get('/') assert b'There aren\'t any bookmarks yet.' in rv.data if __name__ == '__main__': unittest.main()
Adjust test file to match new env config options
## Code Before: import bookmarks import unittest class FlaskrTestCase(unittest.TestCase): def setUp(self): bookmarks.app.config['DATABASE_NAME'] = bookmarks.app.config['TEST_DATABASE_NAME'] bookmarks.app.testing = True self.app = bookmarks.app.test_client() with bookmarks.app.app_context(): bookmarks.database.init_db() # def tearDown(self): # os.close(self.db_fd) # os.unlink(bookmarks.app.config['DATABASE']) def test_empty_db(self): rv = self.app.get('/') assert b'There aren\'t any bookmarks yet.' in rv.data if __name__ == '__main__': unittest.main() ## Instruction: Adjust test file to match new env config options ## Code After: import bookmarks import unittest class FlaskrTestCase(unittest.TestCase): def setUp(self): self.app = bookmarks.app.test_client() with bookmarks.app.app_context(): bookmarks.database.init_db() def tearDown(self): with bookmarks.app.app_context(): bookmarks.database.db_session.remove() bookmarks.database.Base.metadata.drop_all( bind=bookmarks.database.engine) def test_empty_db(self): rv = self.app.get('/') assert b'There aren\'t any bookmarks yet.' in rv.data if __name__ == '__main__': unittest.main()
// ... existing code ... class FlaskrTestCase(unittest.TestCase): def setUp(self): self.app = bookmarks.app.test_client() with bookmarks.app.app_context(): // ... modified code ... bookmarks.database.init_db() def tearDown(self): with bookmarks.app.app_context(): bookmarks.database.db_session.remove() bookmarks.database.Base.metadata.drop_all( bind=bookmarks.database.engine) def test_empty_db(self): // ... rest of the code ...
ec7bbe8ac8715ea22142680f0d880a7d0b71c687
paws/request.py
paws/request.py
from urlparse import parse_qs from utils import cached_property, MultiDict class Request(object): def __init__(self, event, context): self.event = event self.context = context @property def method(self): return self.event['httpMethod'] @property def query(self): return self.event['queryStringParameters'] @cached_property def post(self): return MultiDict(parse_qs(self.event.get('body', '') or '')) @property def stage(self): return self.event['stage'] @property def stageVar(self): return self.event['stageVariables'] @property def params(self): return self.event['pathParameters']
from Cookie import SimpleCookie from urlparse import parse_qs from utils import MultiDict, cached_property class Request(object): def __init__(self, event, context): self.event = event self.context = context @property def method(self): return self.event['httpMethod'] @property def query(self): return self.event['queryStringParameters'] @cached_property def post(self): return MultiDict(parse_qs(self.event.get('body', '') or '')) @cached_property def cookies(self): jar = SimpleCookie() if self.event['headers'].get('Cookie'): jar.load(self.event['headers']['Cookie'].encode('utf-8')) return jar @property def stage(self): return self.event['stage'] @property def stageVar(self): return self.event['stageVariables'] @property def params(self): return self.event['pathParameters']
Add cookies property to Request
Add cookies property to Request
Python
bsd-3-clause
funkybob/paws
+ from Cookie import SimpleCookie from urlparse import parse_qs - from utils import cached_property, MultiDict + from utils import MultiDict, cached_property class Request(object): def __init__(self, event, context): self.event = event self.context = context @property def method(self): return self.event['httpMethod'] @property def query(self): return self.event['queryStringParameters'] @cached_property def post(self): return MultiDict(parse_qs(self.event.get('body', '') or '')) + @cached_property + def cookies(self): + jar = SimpleCookie() + if self.event['headers'].get('Cookie'): + jar.load(self.event['headers']['Cookie'].encode('utf-8')) + return jar + @property def stage(self): return self.event['stage'] @property def stageVar(self): return self.event['stageVariables'] @property def params(self): return self.event['pathParameters']
Add cookies property to Request
## Code Before: from urlparse import parse_qs from utils import cached_property, MultiDict class Request(object): def __init__(self, event, context): self.event = event self.context = context @property def method(self): return self.event['httpMethod'] @property def query(self): return self.event['queryStringParameters'] @cached_property def post(self): return MultiDict(parse_qs(self.event.get('body', '') or '')) @property def stage(self): return self.event['stage'] @property def stageVar(self): return self.event['stageVariables'] @property def params(self): return self.event['pathParameters'] ## Instruction: Add cookies property to Request ## Code After: from Cookie import SimpleCookie from urlparse import parse_qs from utils import MultiDict, cached_property class Request(object): def __init__(self, event, context): self.event = event self.context = context @property def method(self): return self.event['httpMethod'] @property def query(self): return self.event['queryStringParameters'] @cached_property def post(self): return MultiDict(parse_qs(self.event.get('body', '') or '')) @cached_property def cookies(self): jar = SimpleCookie() if self.event['headers'].get('Cookie'): jar.load(self.event['headers']['Cookie'].encode('utf-8')) return jar @property def stage(self): return self.event['stage'] @property def stageVar(self): return self.event['stageVariables'] @property def params(self): return self.event['pathParameters']
# ... existing code ... from Cookie import SimpleCookie from urlparse import parse_qs from utils import MultiDict, cached_property # ... modified code ... return MultiDict(parse_qs(self.event.get('body', '') or '')) @cached_property def cookies(self): jar = SimpleCookie() if self.event['headers'].get('Cookie'): jar.load(self.event['headers']['Cookie'].encode('utf-8')) return jar @property def stage(self): # ... rest of the code ...
c057f4865052c893af9abcae2c2f37ec02d56118
example_test_set/tests/test_set_root.py
example_test_set/tests/test_set_root.py
import pytest class Dut(object): 'fake a device under test' _allowed = ('a', 'b', 'c') def __init__(self, mode=None): self._mode = mode def get_mode(self): return self._mode def set_mode(self, val): self._mode = val def check_mode(self): assert self._mode in self._allowed # fixtures @pytest.fixture def dut(request): return Dut('c') @pytest.yield_fixture(params=('a', 'b', 'c')) def mode(request, dut): orig_mode = dut.get_mode() dut.set_mode(request.param) yield dut dut.set_mode(orig_mode) @pytest.yield_fixture(params=[1, 2, 3]) def inputs(request): yield request.param def test_modes(mode): assert mode.check_mode() def test_inputs(inputs): assert inputs < 2 class TestBoth(object): def test_m(self, mode, inputs): assert mode.check_mode() assert inputs < 2
import pytest class Dut(object): 'fake a device under test' _allowed = ('a', 'b', 'c') def __init__(self, mode=None): self._mode = mode def get_mode(self): return self._mode def set_mode(self, val): self._mode = val def check_mode(self): assert self._mode in self._allowed # fixtures @pytest.fixture def dut(request): return Dut('c') @pytest.yield_fixture(params=('a', 'b', 'c')) def mode(request, dut): orig_mode = dut.get_mode() dut.set_mode(request.param) yield dut dut.set_mode(orig_mode) @pytest.yield_fixture(params=['dog', 'cat', 'mouse']) def inputs(request): yield request.param def test_modes(mode): assert mode.check_mode() def test_inputs(inputs): assert inputs < 2 class TestBoth(object): def test_m(self, mode, inputs): assert mode.check_mode() assert inputs < 2
Tweak some example fixture ids
Tweak some example fixture ids
Python
mit
tgoodlet/pytest-interactive
import pytest class Dut(object): 'fake a device under test' _allowed = ('a', 'b', 'c') def __init__(self, mode=None): self._mode = mode def get_mode(self): return self._mode def set_mode(self, val): self._mode = val def check_mode(self): assert self._mode in self._allowed # fixtures @pytest.fixture def dut(request): return Dut('c') @pytest.yield_fixture(params=('a', 'b', 'c')) def mode(request, dut): orig_mode = dut.get_mode() dut.set_mode(request.param) yield dut dut.set_mode(orig_mode) - @pytest.yield_fixture(params=[1, 2, 3]) + @pytest.yield_fixture(params=['dog', 'cat', 'mouse']) def inputs(request): yield request.param def test_modes(mode): assert mode.check_mode() def test_inputs(inputs): assert inputs < 2 class TestBoth(object): def test_m(self, mode, inputs): assert mode.check_mode() assert inputs < 2
Tweak some example fixture ids
## Code Before: import pytest class Dut(object): 'fake a device under test' _allowed = ('a', 'b', 'c') def __init__(self, mode=None): self._mode = mode def get_mode(self): return self._mode def set_mode(self, val): self._mode = val def check_mode(self): assert self._mode in self._allowed # fixtures @pytest.fixture def dut(request): return Dut('c') @pytest.yield_fixture(params=('a', 'b', 'c')) def mode(request, dut): orig_mode = dut.get_mode() dut.set_mode(request.param) yield dut dut.set_mode(orig_mode) @pytest.yield_fixture(params=[1, 2, 3]) def inputs(request): yield request.param def test_modes(mode): assert mode.check_mode() def test_inputs(inputs): assert inputs < 2 class TestBoth(object): def test_m(self, mode, inputs): assert mode.check_mode() assert inputs < 2 ## Instruction: Tweak some example fixture ids ## Code After: import pytest class Dut(object): 'fake a device under test' _allowed = ('a', 'b', 'c') def __init__(self, mode=None): self._mode = mode def get_mode(self): return self._mode def set_mode(self, val): self._mode = val def check_mode(self): assert self._mode in self._allowed # fixtures @pytest.fixture def dut(request): return Dut('c') @pytest.yield_fixture(params=('a', 'b', 'c')) def mode(request, dut): orig_mode = dut.get_mode() dut.set_mode(request.param) yield dut dut.set_mode(orig_mode) @pytest.yield_fixture(params=['dog', 'cat', 'mouse']) def inputs(request): yield request.param def test_modes(mode): assert mode.check_mode() def test_inputs(inputs): assert inputs < 2 class TestBoth(object): def test_m(self, mode, inputs): assert mode.check_mode() assert inputs < 2
# ... existing code ... @pytest.yield_fixture(params=['dog', 'cat', 'mouse']) def inputs(request): yield request.param # ... rest of the code ...
2da853601e9746663aed35b51db3bfc7640dc9c3
publisher/middleware.py
publisher/middleware.py
from threading import current_thread class PublisherMiddleware(object): _draft_status = {} @staticmethod def is_draft(request): authenticated = request.user.is_authenticated() and request.user.is_staff is_draft = 'edit' in request.GET and authenticated return is_draft def process_request(self, request): PublisherMiddleware._draft_status[current_thread()] = self.is_draft(request) @staticmethod def process_response(request, response): try: del PublisherMiddleware._draft_status[current_thread()] except KeyError: pass return response @staticmethod def get_draft_status(): try: return PublisherMiddleware._draft_status[current_thread()] except KeyError: return False def get_draft_status(): return PublisherMiddleware.get_draft_status()
from threading import current_thread class PublisherMiddleware(object): _draft_status = {} @staticmethod def is_draft(request): authenticated = request.user.is_authenticated() and request.user.is_staff is_draft = 'edit' in request.GET and authenticated return is_draft def process_request(self, request): PublisherMiddleware._draft_status[current_thread()] = self.is_draft(request) @staticmethod def process_response(request, response): del PublisherMiddleware._draft_status[current_thread()] return response @staticmethod def get_draft_status(): try: return PublisherMiddleware._draft_status[current_thread()] except KeyError: return False def get_draft_status(): return PublisherMiddleware.get_draft_status()
Remove unecessary try.. except.. block from PublisherMiddleware.process_response().
Remove unecessary try.. except.. block from PublisherMiddleware.process_response(). The key should always be set by process_request(), which should always be called before process_response().
Python
bsd-3-clause
wearehoods/django-model-publisher-ai,wearehoods/django-model-publisher-ai,jp74/django-model-publisher,jp74/django-model-publisher,wearehoods/django-model-publisher-ai,jp74/django-model-publisher
from threading import current_thread class PublisherMiddleware(object): _draft_status = {} @staticmethod def is_draft(request): authenticated = request.user.is_authenticated() and request.user.is_staff is_draft = 'edit' in request.GET and authenticated return is_draft def process_request(self, request): PublisherMiddleware._draft_status[current_thread()] = self.is_draft(request) @staticmethod def process_response(request, response): - try: - del PublisherMiddleware._draft_status[current_thread()] + del PublisherMiddleware._draft_status[current_thread()] - except KeyError: - pass - return response @staticmethod def get_draft_status(): try: return PublisherMiddleware._draft_status[current_thread()] except KeyError: return False def get_draft_status(): return PublisherMiddleware.get_draft_status()
Remove unecessary try.. except.. block from PublisherMiddleware.process_response().
## Code Before: from threading import current_thread class PublisherMiddleware(object): _draft_status = {} @staticmethod def is_draft(request): authenticated = request.user.is_authenticated() and request.user.is_staff is_draft = 'edit' in request.GET and authenticated return is_draft def process_request(self, request): PublisherMiddleware._draft_status[current_thread()] = self.is_draft(request) @staticmethod def process_response(request, response): try: del PublisherMiddleware._draft_status[current_thread()] except KeyError: pass return response @staticmethod def get_draft_status(): try: return PublisherMiddleware._draft_status[current_thread()] except KeyError: return False def get_draft_status(): return PublisherMiddleware.get_draft_status() ## Instruction: Remove unecessary try.. except.. block from PublisherMiddleware.process_response(). ## Code After: from threading import current_thread class PublisherMiddleware(object): _draft_status = {} @staticmethod def is_draft(request): authenticated = request.user.is_authenticated() and request.user.is_staff is_draft = 'edit' in request.GET and authenticated return is_draft def process_request(self, request): PublisherMiddleware._draft_status[current_thread()] = self.is_draft(request) @staticmethod def process_response(request, response): del PublisherMiddleware._draft_status[current_thread()] return response @staticmethod def get_draft_status(): try: return PublisherMiddleware._draft_status[current_thread()] except KeyError: return False def get_draft_status(): return PublisherMiddleware.get_draft_status()
// ... existing code ... @staticmethod def process_response(request, response): del PublisherMiddleware._draft_status[current_thread()] return response // ... rest of the code ...
082a2d481c0ae118dfcb1456bb7f095d05a5eb0e
mycroft/tts/dummy_tts.py
mycroft/tts/dummy_tts.py
"""A Dummy TTS without any audio output.""" from mycroft.util.log import LOG from .tts import TTS, TTSValidator class DummyTTS(TTS): def __init__(self, lang, config): super().__init__(lang, config, DummyValidator(self), 'wav') def execute(self, sentence, ident=None, listen=False): """Don't do anything, return nothing.""" LOG.info('Mycroft: {}'.format(sentence)) return None class DummyValidator(TTSValidator): """Do no tests.""" def __init__(self, tts): super().__init__(tts) def validate_lang(self): pass def validate_connection(self): pass def get_tts_class(self): return DummyTTS
"""A Dummy TTS without any audio output.""" from mycroft.util.log import LOG from .tts import TTS, TTSValidator class DummyTTS(TTS): def __init__(self, lang, config): super().__init__(lang, config, DummyValidator(self), 'wav') def execute(self, sentence, ident=None, listen=False): """Don't do anything, return nothing.""" LOG.info('Mycroft: {}'.format(sentence)) self.end_audio(listen) return None class DummyValidator(TTSValidator): """Do no tests.""" def __init__(self, tts): super().__init__(tts) def validate_lang(self): pass def validate_connection(self): pass def get_tts_class(self): return DummyTTS
Mark that audio has completed in dummy tts
Mark that audio has completed in dummy tts
Python
apache-2.0
forslund/mycroft-core,forslund/mycroft-core,MycroftAI/mycroft-core,MycroftAI/mycroft-core
"""A Dummy TTS without any audio output.""" from mycroft.util.log import LOG from .tts import TTS, TTSValidator class DummyTTS(TTS): def __init__(self, lang, config): super().__init__(lang, config, DummyValidator(self), 'wav') def execute(self, sentence, ident=None, listen=False): """Don't do anything, return nothing.""" LOG.info('Mycroft: {}'.format(sentence)) + self.end_audio(listen) return None class DummyValidator(TTSValidator): """Do no tests.""" def __init__(self, tts): super().__init__(tts) def validate_lang(self): pass def validate_connection(self): pass def get_tts_class(self): return DummyTTS
Mark that audio has completed in dummy tts
## Code Before: """A Dummy TTS without any audio output.""" from mycroft.util.log import LOG from .tts import TTS, TTSValidator class DummyTTS(TTS): def __init__(self, lang, config): super().__init__(lang, config, DummyValidator(self), 'wav') def execute(self, sentence, ident=None, listen=False): """Don't do anything, return nothing.""" LOG.info('Mycroft: {}'.format(sentence)) return None class DummyValidator(TTSValidator): """Do no tests.""" def __init__(self, tts): super().__init__(tts) def validate_lang(self): pass def validate_connection(self): pass def get_tts_class(self): return DummyTTS ## Instruction: Mark that audio has completed in dummy tts ## Code After: """A Dummy TTS without any audio output.""" from mycroft.util.log import LOG from .tts import TTS, TTSValidator class DummyTTS(TTS): def __init__(self, lang, config): super().__init__(lang, config, DummyValidator(self), 'wav') def execute(self, sentence, ident=None, listen=False): """Don't do anything, return nothing.""" LOG.info('Mycroft: {}'.format(sentence)) self.end_audio(listen) return None class DummyValidator(TTSValidator): """Do no tests.""" def __init__(self, tts): super().__init__(tts) def validate_lang(self): pass def validate_connection(self): pass def get_tts_class(self): return DummyTTS
// ... existing code ... """Don't do anything, return nothing.""" LOG.info('Mycroft: {}'.format(sentence)) self.end_audio(listen) return None // ... rest of the code ...
46328b5baaf25b04703ca04fd376f3f79a26a00f
sockjs/cyclone/proto.py
sockjs/cyclone/proto.py
import simplejson json_encode = lambda data: simplejson.dumps(data, separators=(',', ':')) json_decode = lambda data: simplejson.loads(data) JSONDecodeError = ValueError # Protocol handlers CONNECT = 'o' DISCONNECT = 'c' MESSAGE = 'm' HEARTBEAT = 'h' # Various protocol helpers def disconnect(code, reason): """Return SockJS packet with code and close reason @param code: Closing code @param reason: Closing reason """ return 'c[%d,"%s"]' % (code, reason)
try: import simplejson except ImportError: import json as simplejson json_encode = lambda data: simplejson.dumps(data, separators=(',', ':')) json_decode = lambda data: simplejson.loads(data) JSONDecodeError = ValueError # Protocol handlers CONNECT = 'o' DISCONNECT = 'c' MESSAGE = 'm' HEARTBEAT = 'h' # Various protocol helpers def disconnect(code, reason): """Return SockJS packet with code and close reason @param code: Closing code @param reason: Closing reason """ return 'c[%d,"%s"]' % (code, reason)
Use the json module from stdlib (Python 2.6+) as fallback
Use the json module from stdlib (Python 2.6+) as fallback
Python
mit
flaviogrossi/sockjs-cyclone
+ try: - import simplejson + import simplejson + except ImportError: + import json as simplejson json_encode = lambda data: simplejson.dumps(data, separators=(',', ':')) json_decode = lambda data: simplejson.loads(data) JSONDecodeError = ValueError # Protocol handlers CONNECT = 'o' DISCONNECT = 'c' MESSAGE = 'm' HEARTBEAT = 'h' # Various protocol helpers def disconnect(code, reason): """Return SockJS packet with code and close reason @param code: Closing code @param reason: Closing reason """ return 'c[%d,"%s"]' % (code, reason)
Use the json module from stdlib (Python 2.6+) as fallback
## Code Before: import simplejson json_encode = lambda data: simplejson.dumps(data, separators=(',', ':')) json_decode = lambda data: simplejson.loads(data) JSONDecodeError = ValueError # Protocol handlers CONNECT = 'o' DISCONNECT = 'c' MESSAGE = 'm' HEARTBEAT = 'h' # Various protocol helpers def disconnect(code, reason): """Return SockJS packet with code and close reason @param code: Closing code @param reason: Closing reason """ return 'c[%d,"%s"]' % (code, reason) ## Instruction: Use the json module from stdlib (Python 2.6+) as fallback ## Code After: try: import simplejson except ImportError: import json as simplejson json_encode = lambda data: simplejson.dumps(data, separators=(',', ':')) json_decode = lambda data: simplejson.loads(data) JSONDecodeError = ValueError # Protocol handlers CONNECT = 'o' DISCONNECT = 'c' MESSAGE = 'm' HEARTBEAT = 'h' # Various protocol helpers def disconnect(code, reason): """Return SockJS packet with code and close reason @param code: Closing code @param reason: Closing reason """ return 'c[%d,"%s"]' % (code, reason)
... try: import simplejson except ImportError: import json as simplejson json_encode = lambda data: simplejson.dumps(data, separators=(',', ':')) ...
1b07cb1ec2fbe48af4f38a225c2237846ce8b314
pyramid_es/tests/__init__.py
pyramid_es/tests/__init__.py
import logging def setUp(): log = logging.getLogger('elasticsearch.trace') log.setLevel(logging.CRITICAL)
import logging def setUp(): log = logging.getLogger('elasticsearch.trace') log.addHandler(logging.NullHandler())
Use a better method for silencing 'no handlers found' error
Use a better method for silencing 'no handlers found' error
Python
mit
storborg/pyramid_es
import logging def setUp(): log = logging.getLogger('elasticsearch.trace') - log.setLevel(logging.CRITICAL) + log.addHandler(logging.NullHandler())
Use a better method for silencing 'no handlers found' error
## Code Before: import logging def setUp(): log = logging.getLogger('elasticsearch.trace') log.setLevel(logging.CRITICAL) ## Instruction: Use a better method for silencing 'no handlers found' error ## Code After: import logging def setUp(): log = logging.getLogger('elasticsearch.trace') log.addHandler(logging.NullHandler())
// ... existing code ... def setUp(): log = logging.getLogger('elasticsearch.trace') log.addHandler(logging.NullHandler()) // ... rest of the code ...
fb1db28198b54b6288a9e7d499b43f6f1a51284c
partner_deduplicate_by_website/__manifest__.py
partner_deduplicate_by_website/__manifest__.py
{ "name": "Deduplicate Contacts by Website", "version": "13.0.1.0.0", "category": "Tools", "website": "https://github.com/OCA/crm", "author": "Tecnativa, " "Odoo Community Association (OCA)", "license": "AGPL-3", "installable": True, "depends": ["contacts"], "data": ["wizards/partner_merge_view.xml"], }
{ "name": "Deduplicate Contacts by Website", "version": "13.0.1.0.0", "category": "Tools", "website": "https://github.com/OCA/partner-contact", "author": "Tecnativa, " "Odoo Community Association (OCA)", "license": "AGPL-3", "installable": True, "depends": ["contacts"], "data": ["wizards/partner_merge_view.xml"], }
Fix website attribute in manifest
Fix website attribute in manifest
Python
agpl-3.0
OCA/partner-contact,OCA/partner-contact
{ "name": "Deduplicate Contacts by Website", "version": "13.0.1.0.0", "category": "Tools", - "website": "https://github.com/OCA/crm", + "website": "https://github.com/OCA/partner-contact", "author": "Tecnativa, " "Odoo Community Association (OCA)", "license": "AGPL-3", "installable": True, "depends": ["contacts"], "data": ["wizards/partner_merge_view.xml"], }
Fix website attribute in manifest
## Code Before: { "name": "Deduplicate Contacts by Website", "version": "13.0.1.0.0", "category": "Tools", "website": "https://github.com/OCA/crm", "author": "Tecnativa, " "Odoo Community Association (OCA)", "license": "AGPL-3", "installable": True, "depends": ["contacts"], "data": ["wizards/partner_merge_view.xml"], } ## Instruction: Fix website attribute in manifest ## Code After: { "name": "Deduplicate Contacts by Website", "version": "13.0.1.0.0", "category": "Tools", "website": "https://github.com/OCA/partner-contact", "author": "Tecnativa, " "Odoo Community Association (OCA)", "license": "AGPL-3", "installable": True, "depends": ["contacts"], "data": ["wizards/partner_merge_view.xml"], }
# ... existing code ... "version": "13.0.1.0.0", "category": "Tools", "website": "https://github.com/OCA/partner-contact", "author": "Tecnativa, " "Odoo Community Association (OCA)", "license": "AGPL-3", # ... rest of the code ...
0c5abad8259cccfd1ce50b27a124089d9ea946dd
copr_build.py
copr_build.py
import json, os, sys import requests api_url = "https://copr.fedorainfracloud.org/api_2" api_login = os.environ["copr_login"] api_token = os.environ["copr_token"] r = requests.get("%s/projects/%s/chroots" % (api_url, os.environ["copr_projectid"])).json() chroots = [] for i in r.get("chroots"): chroots.append(i.get("chroot").get("name")) metadata = { 'chroots': chroots, 'project_id': int(os.environ["copr_projectid"]), } files = { "srpm": (os.path.basename(sys.argv[1]), open(sys.argv[1], 'rb'), 'application/x-rpm'), "metadata": ('', json.dumps(metadata)) } r = requests.post("%s/builds" % api_url, auth=(api_login, api_token), files=files)
import os import sys import requests api_url = "https://copr.fedorainfracloud.org/api_2" api_login = os.environ["copr_login"] api_token = os.environ["copr_token"] project_id = int(os.environ["copr_projectid"]) r = requests.get("%s/projects/%s/chroots" % (api_url, project_id)) if not r.ok: print(r.json().get("message", "Error returned, but no message")) sys.exit(1) chroots = [i.get("chroot").get("name") for i in r.json().get("chroots")] gh_url = "https://api.github.com/repos/{}/{}/releases/latest".format( os.environ["CIRCLE_PROJECT_USERNAME"], os.environ["CIRCLE_PROJECT_REPONAME"] ) gh = requests.get(gh_url) if not gh.ok: print("Failed to fetch latest Github release") print(gh.json()) sys.exit(1) assets = gh.json().get("assets") if len(assets) > 1: print("More than 1 asset uploaded to Github, unexpected") sys.exit(1) asset = assets[0].get("browser_download_url") if not asset.endswith(".src.rpm"): print("Github asset is not a .src.rpm") sys.exit(1) metadata = { 'chroots': chroots, 'project_id': project_id, 'srpm_url': asset, } r = requests.post("%s/builds" % api_url, auth=(api_login, api_token), json=metadata) if r.status_code != 201: print(r.json().get("message", "Error returned, but no message")) sys.exit(1) print("Build started at {}".format(r.headers["Location"]))
Fix copr build trigger script
Fix copr build trigger script
Python
mit
kyl191/nginx-pagespeed,kyl191/nginx-pagespeed,kyl191/nginx-pagespeed
- import json, os, sys + import os + import sys import requests api_url = "https://copr.fedorainfracloud.org/api_2" api_login = os.environ["copr_login"] api_token = os.environ["copr_token"] + project_id = int(os.environ["copr_projectid"]) - r = requests.get("%s/projects/%s/chroots" % (api_url, os.environ["copr_projectid"])).json() + r = requests.get("%s/projects/%s/chroots" % (api_url, project_id)) - chroots = [] - for i in r.get("chroots"): - chroots.append(i.get("chroot").get("name")) + if not r.ok: + print(r.json().get("message", "Error returned, but no message")) + sys.exit(1) + + chroots = [i.get("chroot").get("name") for i in r.json().get("chroots")] + + gh_url = "https://api.github.com/repos/{}/{}/releases/latest".format( + os.environ["CIRCLE_PROJECT_USERNAME"], + os.environ["CIRCLE_PROJECT_REPONAME"] + ) + gh = requests.get(gh_url) + if not gh.ok: + print("Failed to fetch latest Github release") + print(gh.json()) + sys.exit(1) + + assets = gh.json().get("assets") + if len(assets) > 1: + print("More than 1 asset uploaded to Github, unexpected") + sys.exit(1) + asset = assets[0].get("browser_download_url") + if not asset.endswith(".src.rpm"): + print("Github asset is not a .src.rpm") + sys.exit(1) metadata = { 'chroots': chroots, - 'project_id': int(os.environ["copr_projectid"]), + 'project_id': project_id, + 'srpm_url': asset, } - files = { - "srpm": (os.path.basename(sys.argv[1]), open(sys.argv[1], 'rb'), 'application/x-rpm'), - "metadata": ('', json.dumps(metadata)) - } - r = requests.post("%s/builds" % api_url, auth=(api_login, api_token), files=files) + r = requests.post("%s/builds" % api_url, + auth=(api_login, api_token), + json=metadata) + if r.status_code != 201: + print(r.json().get("message", "Error returned, but no message")) + sys.exit(1) + print("Build started at {}".format(r.headers["Location"])) +
Fix copr build trigger script
## Code Before: import json, os, sys import requests api_url = "https://copr.fedorainfracloud.org/api_2" api_login = os.environ["copr_login"] api_token = os.environ["copr_token"] r = requests.get("%s/projects/%s/chroots" % (api_url, os.environ["copr_projectid"])).json() chroots = [] for i in r.get("chroots"): chroots.append(i.get("chroot").get("name")) metadata = { 'chroots': chroots, 'project_id': int(os.environ["copr_projectid"]), } files = { "srpm": (os.path.basename(sys.argv[1]), open(sys.argv[1], 'rb'), 'application/x-rpm'), "metadata": ('', json.dumps(metadata)) } r = requests.post("%s/builds" % api_url, auth=(api_login, api_token), files=files) ## Instruction: Fix copr build trigger script ## Code After: import os import sys import requests api_url = "https://copr.fedorainfracloud.org/api_2" api_login = os.environ["copr_login"] api_token = os.environ["copr_token"] project_id = int(os.environ["copr_projectid"]) r = requests.get("%s/projects/%s/chroots" % (api_url, project_id)) if not r.ok: print(r.json().get("message", "Error returned, but no message")) sys.exit(1) chroots = [i.get("chroot").get("name") for i in r.json().get("chroots")] gh_url = "https://api.github.com/repos/{}/{}/releases/latest".format( os.environ["CIRCLE_PROJECT_USERNAME"], os.environ["CIRCLE_PROJECT_REPONAME"] ) gh = requests.get(gh_url) if not gh.ok: print("Failed to fetch latest Github release") print(gh.json()) sys.exit(1) assets = gh.json().get("assets") if len(assets) > 1: print("More than 1 asset uploaded to Github, unexpected") sys.exit(1) asset = assets[0].get("browser_download_url") if not asset.endswith(".src.rpm"): print("Github asset is not a .src.rpm") sys.exit(1) metadata = { 'chroots': chroots, 'project_id': project_id, 'srpm_url': asset, } r = requests.post("%s/builds" % api_url, auth=(api_login, api_token), json=metadata) if r.status_code != 201: print(r.json().get("message", "Error returned, but no message")) sys.exit(1) print("Build started at {}".format(r.headers["Location"]))
... import os import sys import requests api_url = "https://copr.fedorainfracloud.org/api_2" ... api_login = os.environ["copr_login"] api_token = os.environ["copr_token"] project_id = int(os.environ["copr_projectid"]) r = requests.get("%s/projects/%s/chroots" % (api_url, project_id)) if not r.ok: print(r.json().get("message", "Error returned, but no message")) sys.exit(1) chroots = [i.get("chroot").get("name") for i in r.json().get("chroots")] gh_url = "https://api.github.com/repos/{}/{}/releases/latest".format( os.environ["CIRCLE_PROJECT_USERNAME"], os.environ["CIRCLE_PROJECT_REPONAME"] ) gh = requests.get(gh_url) if not gh.ok: print("Failed to fetch latest Github release") print(gh.json()) sys.exit(1) assets = gh.json().get("assets") if len(assets) > 1: print("More than 1 asset uploaded to Github, unexpected") sys.exit(1) asset = assets[0].get("browser_download_url") if not asset.endswith(".src.rpm"): print("Github asset is not a .src.rpm") sys.exit(1) metadata = { 'chroots': chroots, 'project_id': project_id, 'srpm_url': asset, } r = requests.post("%s/builds" % api_url, auth=(api_login, api_token), json=metadata) if r.status_code != 201: print(r.json().get("message", "Error returned, but no message")) sys.exit(1) print("Build started at {}".format(r.headers["Location"])) ...
b7bafa86cf6e2f568e99335fa6aeb6d8f3509170
dont_tread_on_memes/__init__.py
dont_tread_on_memes/__init__.py
import os from PIL import Image, ImageDraw, ImageFont localdir = os.path.dirname(__file__) BLANK_FLAG = Image.open(os.path.join(localdir, "dont-tread-on-blank.png")) LORA_FONT = ImageFont.truetype( os.path.join(localdir, "../fonts/Lora-Regular.ttf"), 120 ) def tread_on(caption, color="black"): """Caption the "Don't Tread on Me" snake with `caption`""" flag = BLANK_FLAG.copy() draw = ImageDraw.Draw(flag) text = caption.upper() font_pos = (flag.width / 2 - LORA_FONT.getsize(text)[0] / 2, 1088) draw.text(font_pos, text, font=LORA_FONT, fill=color) return flag def dont_me(phrase): """Caption the "Don't tread on me" flag with "Don't [phrase] me" """ return tread_on("don't {} me".format(phrase))
import os from PIL import Image, ImageDraw, ImageFont localdir = os.path.dirname(__file__) BLANK_FLAG = Image.open(os.path.join(localdir, "dont-tread-on-blank.png")) LORA_FONT = ImageFont.truetype( os.path.join(localdir, "../fonts/Lora-Regular.ttf"), 120 ) def tread_on(caption, color="black"): """Caption the "Don't Tread on Me" snake with `caption`""" flag = BLANK_FLAG.copy() draw = ImageDraw.Draw(flag) text = caption.upper() font_pos = (flag.width / 2 - LORA_FONT.getsize(text)[0] / 2, 1088) draw.text(font_pos, text, font=LORA_FONT, fill=color) return flag def dont_me(phrase, *args, **kwargs): """Caption the "Don't tread on me" flag with "Don't [phrase] me" """ return tread_on("don't {} me".format(phrase), *args, **kwargs)
Allow passing arguments through dont_me to tread_on
Allow passing arguments through dont_me to tread_on
Python
mit
controversial/dont-tread-on-memes
import os from PIL import Image, ImageDraw, ImageFont localdir = os.path.dirname(__file__) BLANK_FLAG = Image.open(os.path.join(localdir, "dont-tread-on-blank.png")) LORA_FONT = ImageFont.truetype( os.path.join(localdir, "../fonts/Lora-Regular.ttf"), 120 ) def tread_on(caption, color="black"): """Caption the "Don't Tread on Me" snake with `caption`""" flag = BLANK_FLAG.copy() draw = ImageDraw.Draw(flag) text = caption.upper() font_pos = (flag.width / 2 - LORA_FONT.getsize(text)[0] / 2, 1088) draw.text(font_pos, text, font=LORA_FONT, fill=color) return flag - def dont_me(phrase): + def dont_me(phrase, *args, **kwargs): """Caption the "Don't tread on me" flag with "Don't [phrase] me" """ - return tread_on("don't {} me".format(phrase)) + return tread_on("don't {} me".format(phrase), *args, **kwargs)
Allow passing arguments through dont_me to tread_on
## Code Before: import os from PIL import Image, ImageDraw, ImageFont localdir = os.path.dirname(__file__) BLANK_FLAG = Image.open(os.path.join(localdir, "dont-tread-on-blank.png")) LORA_FONT = ImageFont.truetype( os.path.join(localdir, "../fonts/Lora-Regular.ttf"), 120 ) def tread_on(caption, color="black"): """Caption the "Don't Tread on Me" snake with `caption`""" flag = BLANK_FLAG.copy() draw = ImageDraw.Draw(flag) text = caption.upper() font_pos = (flag.width / 2 - LORA_FONT.getsize(text)[0] / 2, 1088) draw.text(font_pos, text, font=LORA_FONT, fill=color) return flag def dont_me(phrase): """Caption the "Don't tread on me" flag with "Don't [phrase] me" """ return tread_on("don't {} me".format(phrase)) ## Instruction: Allow passing arguments through dont_me to tread_on ## Code After: import os from PIL import Image, ImageDraw, ImageFont localdir = os.path.dirname(__file__) BLANK_FLAG = Image.open(os.path.join(localdir, "dont-tread-on-blank.png")) LORA_FONT = ImageFont.truetype( os.path.join(localdir, "../fonts/Lora-Regular.ttf"), 120 ) def tread_on(caption, color="black"): """Caption the "Don't Tread on Me" snake with `caption`""" flag = BLANK_FLAG.copy() draw = ImageDraw.Draw(flag) text = caption.upper() font_pos = (flag.width / 2 - LORA_FONT.getsize(text)[0] / 2, 1088) draw.text(font_pos, text, font=LORA_FONT, fill=color) return flag def dont_me(phrase, *args, **kwargs): """Caption the "Don't tread on me" flag with "Don't [phrase] me" """ return tread_on("don't {} me".format(phrase), *args, **kwargs)
# ... existing code ... def dont_me(phrase, *args, **kwargs): """Caption the "Don't tread on me" flag with "Don't [phrase] me" """ return tread_on("don't {} me".format(phrase), *args, **kwargs) # ... rest of the code ...