commit
stringlengths
40
40
old_file
stringlengths
4
118
new_file
stringlengths
4
118
old_contents
stringlengths
10
2.94k
new_contents
stringlengths
21
3.18k
subject
stringlengths
16
444
message
stringlengths
17
2.63k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
5
43k
ndiff
stringlengths
52
3.32k
instruction
stringlengths
16
444
content
stringlengths
133
4.32k
fuzzy_diff
stringlengths
16
3.18k
e28541c00be7f02b3ca6de25e4f95ce4dd099524
nodeconductor/iaas/perms.py
nodeconductor/iaas/perms.py
from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic, StaffPermissionLogic from nodeconductor.structure.models import ProjectRole PERMISSION_LOGICS = ( ('iaas.Instance', FilteredCollaboratorsPermissionLogic( collaborators_query='project__roles__permission_group__user', collaborators_filter={ 'project__roles__role_type': ProjectRole.ADMINISTRATOR, }, any_permission=True, )), ('iaas.Template', StaffPermissionLogic(any_permission=True)), ('iaas.TemplateMapping', StaffPermissionLogic(any_permission=True)), ('iaas.Image', StaffPermissionLogic(any_permission=True)), ('iaas.TemplateLicense', StaffPermissionLogic(any_permission=True)), )
from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic, StaffPermissionLogic from nodeconductor.structure.models import ProjectRole PERMISSION_LOGICS = ( ('iaas.Instance', FilteredCollaboratorsPermissionLogic( collaborators_query='project__roles__permission_group__user', collaborators_filter={ 'project__roles__role_type': ProjectRole.ADMINISTRATOR, }, any_permission=True, )), ('iaas.Template', StaffPermissionLogic(any_permission=True)), ('iaas.TemplateMapping', StaffPermissionLogic(any_permission=True)), ('iaas.Image', StaffPermissionLogic(any_permission=True)), ('iaas.TemplateLicense', StaffPermissionLogic(any_permission=True)), ('iaas.InstanceSlaHistory', StaffPermissionLogic(any_permission=True)), )
Allow InstanceSlaHistory to be managed by staff
Allow InstanceSlaHistory to be managed by staff
Python
mit
opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor
from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic, StaffPermissionLogic from nodeconductor.structure.models import ProjectRole PERMISSION_LOGICS = ( ('iaas.Instance', FilteredCollaboratorsPermissionLogic( collaborators_query='project__roles__permission_group__user', collaborators_filter={ 'project__roles__role_type': ProjectRole.ADMINISTRATOR, }, any_permission=True, )), ('iaas.Template', StaffPermissionLogic(any_permission=True)), ('iaas.TemplateMapping', StaffPermissionLogic(any_permission=True)), ('iaas.Image', StaffPermissionLogic(any_permission=True)), ('iaas.TemplateLicense', StaffPermissionLogic(any_permission=True)), - + ('iaas.InstanceSlaHistory', StaffPermissionLogic(any_permission=True)), )
Allow InstanceSlaHistory to be managed by staff
## Code Before: from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic, StaffPermissionLogic from nodeconductor.structure.models import ProjectRole PERMISSION_LOGICS = ( ('iaas.Instance', FilteredCollaboratorsPermissionLogic( collaborators_query='project__roles__permission_group__user', collaborators_filter={ 'project__roles__role_type': ProjectRole.ADMINISTRATOR, }, any_permission=True, )), ('iaas.Template', StaffPermissionLogic(any_permission=True)), ('iaas.TemplateMapping', StaffPermissionLogic(any_permission=True)), ('iaas.Image', StaffPermissionLogic(any_permission=True)), ('iaas.TemplateLicense', StaffPermissionLogic(any_permission=True)), ) ## Instruction: Allow InstanceSlaHistory to be managed by staff ## Code After: from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic, StaffPermissionLogic from nodeconductor.structure.models import ProjectRole PERMISSION_LOGICS = ( ('iaas.Instance', FilteredCollaboratorsPermissionLogic( collaborators_query='project__roles__permission_group__user', collaborators_filter={ 'project__roles__role_type': ProjectRole.ADMINISTRATOR, }, any_permission=True, )), ('iaas.Template', StaffPermissionLogic(any_permission=True)), ('iaas.TemplateMapping', StaffPermissionLogic(any_permission=True)), ('iaas.Image', StaffPermissionLogic(any_permission=True)), ('iaas.TemplateLicense', StaffPermissionLogic(any_permission=True)), ('iaas.InstanceSlaHistory', StaffPermissionLogic(any_permission=True)), )
# ... existing code ... ('iaas.TemplateLicense', StaffPermissionLogic(any_permission=True)), ('iaas.InstanceSlaHistory', StaffPermissionLogic(any_permission=True)), ) # ... rest of the code ...
030e64d7aee6c3f0b3a0d0508ac1d5ece0bf4a40
astroquery/fermi/__init__.py
astroquery/fermi/__init__.py
from astropy.config import ConfigurationItem FERMI_URL = ConfigurationItem('fermi_url', ['http://fermi.gsfc.nasa.gov/cgi-bin/ssc/LAT/LATDataQuery.cgi'], "Fermi query URL") FERMI_TIMEOUT = ConfigurationItem('timeout', 60, 'time limit for connecting to FERMI server') FERMI_RETRIEVAL_TIMEOUT = ConfigurationItem('retrieval_timeout', 120, 'time limit for retrieving a data file once it has been located') from .core import FermiLAT, GetFermilatDatafile, get_fermilat_datafile import warnings warnings.warn("Experimental: Fermi-LAT has not yet been refactored to have its API match the rest of astroquery.")
from astropy.config import ConfigurationItem FERMI_URL = ConfigurationItem('fermi_url', ['http://fermi.gsfc.nasa.gov/cgi-bin/ssc/LAT/LATDataQuery.cgi'], "Fermi query URL") FERMI_TIMEOUT = ConfigurationItem('timeout', 60, 'time limit for connecting to FERMI server') FERMI_RETRIEVAL_TIMEOUT = ConfigurationItem('retrieval_timeout', 120, 'time limit for retrieving a data file once it has been located') from .core import FermiLAT, GetFermilatDatafile, get_fermilat_datafile import warnings warnings.warn("Experimental: Fermi-LAT has not yet been refactored to have its API match the rest of astroquery.") del ConfigurationItem # clean up namespace - prevents doc warnings
Clean up namespace to get rid of sphinx warnings
Clean up namespace to get rid of sphinx warnings
Python
bsd-3-clause
imbasimba/astroquery,imbasimba/astroquery,ceb8/astroquery,ceb8/astroquery
from astropy.config import ConfigurationItem FERMI_URL = ConfigurationItem('fermi_url', ['http://fermi.gsfc.nasa.gov/cgi-bin/ssc/LAT/LATDataQuery.cgi'], "Fermi query URL") FERMI_TIMEOUT = ConfigurationItem('timeout', 60, 'time limit for connecting to FERMI server') FERMI_RETRIEVAL_TIMEOUT = ConfigurationItem('retrieval_timeout', 120, 'time limit for retrieving a data file once it has been located') from .core import FermiLAT, GetFermilatDatafile, get_fermilat_datafile import warnings warnings.warn("Experimental: Fermi-LAT has not yet been refactored to have its API match the rest of astroquery.") + del ConfigurationItem # clean up namespace - prevents doc warnings +
Clean up namespace to get rid of sphinx warnings
## Code Before: from astropy.config import ConfigurationItem FERMI_URL = ConfigurationItem('fermi_url', ['http://fermi.gsfc.nasa.gov/cgi-bin/ssc/LAT/LATDataQuery.cgi'], "Fermi query URL") FERMI_TIMEOUT = ConfigurationItem('timeout', 60, 'time limit for connecting to FERMI server') FERMI_RETRIEVAL_TIMEOUT = ConfigurationItem('retrieval_timeout', 120, 'time limit for retrieving a data file once it has been located') from .core import FermiLAT, GetFermilatDatafile, get_fermilat_datafile import warnings warnings.warn("Experimental: Fermi-LAT has not yet been refactored to have its API match the rest of astroquery.") ## Instruction: Clean up namespace to get rid of sphinx warnings ## Code After: from astropy.config import ConfigurationItem FERMI_URL = ConfigurationItem('fermi_url', ['http://fermi.gsfc.nasa.gov/cgi-bin/ssc/LAT/LATDataQuery.cgi'], "Fermi query URL") FERMI_TIMEOUT = ConfigurationItem('timeout', 60, 'time limit for connecting to FERMI server') FERMI_RETRIEVAL_TIMEOUT = ConfigurationItem('retrieval_timeout', 120, 'time limit for retrieving a data file once it has been located') from .core import FermiLAT, GetFermilatDatafile, get_fermilat_datafile import warnings warnings.warn("Experimental: Fermi-LAT has not yet been refactored to have its API match the rest of astroquery.") del ConfigurationItem # clean up namespace - prevents doc warnings
... warnings.warn("Experimental: Fermi-LAT has not yet been refactored to have its API match the rest of astroquery.") del ConfigurationItem # clean up namespace - prevents doc warnings ...
216216df9e3b42766a755f63519c84fda2fcebe0
amy/workshops/migrations/0221_workshoprequest_rq_jobs.py
amy/workshops/migrations/0221_workshoprequest_rq_jobs.py
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('workshops', '0220_event_public_status'), ] operations = [ migrations.AddField( model_name='workshoprequest', name='rq_jobs', field=models.ManyToManyField(blank=True, help_text='This should be filled out by AMY itself.', to='autoemails.RQJob', verbose_name='Related Redis Queue jobs'), ), ]
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('workshops', '0221_auto_20201025_1113'), ] operations = [ migrations.AddField( model_name='workshoprequest', name='rq_jobs', field=models.ManyToManyField(blank=True, help_text='This should be filled out by AMY itself.', to='autoemails.RQJob', verbose_name='Related Redis Queue jobs'), ), ]
Fix migrations conflict after rebase
Fix migrations conflict after rebase
Python
mit
swcarpentry/amy,pbanaszkiewicz/amy,pbanaszkiewicz/amy,pbanaszkiewicz/amy,swcarpentry/amy,swcarpentry/amy
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ - ('workshops', '0220_event_public_status'), + ('workshops', '0221_auto_20201025_1113'), ] operations = [ migrations.AddField( model_name='workshoprequest', name='rq_jobs', field=models.ManyToManyField(blank=True, help_text='This should be filled out by AMY itself.', to='autoemails.RQJob', verbose_name='Related Redis Queue jobs'), ), ]
Fix migrations conflict after rebase
## Code Before: from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('workshops', '0220_event_public_status'), ] operations = [ migrations.AddField( model_name='workshoprequest', name='rq_jobs', field=models.ManyToManyField(blank=True, help_text='This should be filled out by AMY itself.', to='autoemails.RQJob', verbose_name='Related Redis Queue jobs'), ), ] ## Instruction: Fix migrations conflict after rebase ## Code After: from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('workshops', '0221_auto_20201025_1113'), ] operations = [ migrations.AddField( model_name='workshoprequest', name='rq_jobs', field=models.ManyToManyField(blank=True, help_text='This should be filled out by AMY itself.', to='autoemails.RQJob', verbose_name='Related Redis Queue jobs'), ), ]
// ... existing code ... dependencies = [ ('workshops', '0221_auto_20201025_1113'), ] // ... rest of the code ...
34bd55b33e865c65386f934c7ac0b89f3cc76485
edgedb/lang/common/shell/reqs.py
edgedb/lang/common/shell/reqs.py
from metamagic import app from metamagic.exceptions import MetamagicError class UnsatisfiedRequirementError(MetamagicError): pass class CommandRequirement: pass class ValidApplication(CommandRequirement): def __init__(self, args): if not app.Application.active: raise UnsatisfiedRequirementError('need active Application')
from metamagic.exceptions import MetamagicError class UnsatisfiedRequirementError(MetamagicError): pass class CommandRequirement: pass
Drop 'metamagic.app' package. Long live Node.
app: Drop 'metamagic.app' package. Long live Node.
Python
apache-2.0
edgedb/edgedb,edgedb/edgedb,edgedb/edgedb
- from metamagic import app from metamagic.exceptions import MetamagicError class UnsatisfiedRequirementError(MetamagicError): pass class CommandRequirement: pass - - class ValidApplication(CommandRequirement): - def __init__(self, args): - if not app.Application.active: - raise UnsatisfiedRequirementError('need active Application') -
Drop 'metamagic.app' package. Long live Node.
## Code Before: from metamagic import app from metamagic.exceptions import MetamagicError class UnsatisfiedRequirementError(MetamagicError): pass class CommandRequirement: pass class ValidApplication(CommandRequirement): def __init__(self, args): if not app.Application.active: raise UnsatisfiedRequirementError('need active Application') ## Instruction: Drop 'metamagic.app' package. Long live Node. ## Code After: from metamagic.exceptions import MetamagicError class UnsatisfiedRequirementError(MetamagicError): pass class CommandRequirement: pass
# ... existing code ... from metamagic.exceptions import MetamagicError # ... modified code ... pass # ... rest of the code ...
2a7ce1ac70f8767e9d2b2a9f1d335cfcc63a92b6
rplugin/python3/LanguageClient/logger.py
rplugin/python3/LanguageClient/logger.py
import logging import tempfile logger = logging.getLogger("LanguageClient") with tempfile.NamedTemporaryFile( prefix="LanguageClient-", suffix=".log", delete=False) as tmp: tmpname = tmp.name fileHandler = logging.FileHandler(filename=tmpname) fileHandler.setFormatter( logging.Formatter( "%(asctime)s %(levelname)-8s %(message)s", "%H:%M:%S")) logger.addHandler(fileHandler) logger.setLevel(logging.WARN)
import logging logger = logging.getLogger("LanguageClient") fileHandler = logging.FileHandler(filename="/tmp/LanguageClient.log") fileHandler.setFormatter( logging.Formatter( "%(asctime)s %(levelname)-8s %(message)s", "%H:%M:%S")) logger.addHandler(fileHandler) logger.setLevel(logging.WARN)
Revert "Use tempfile lib for log file"
Revert "Use tempfile lib for log file" This reverts commit 6e8f35b83fc563c8349cb3be040c61a0588ca745. The commit caused severer issue than it fixed. In case one need to check the content of log file, there is no way to tell where the log file location/name is.
Python
mit
autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim
import logging - import tempfile logger = logging.getLogger("LanguageClient") - with tempfile.NamedTemporaryFile( - prefix="LanguageClient-", - suffix=".log", delete=False) as tmp: - tmpname = tmp.name - fileHandler = logging.FileHandler(filename=tmpname) + fileHandler = logging.FileHandler(filename="/tmp/LanguageClient.log") fileHandler.setFormatter( logging.Formatter( "%(asctime)s %(levelname)-8s %(message)s", "%H:%M:%S")) logger.addHandler(fileHandler) logger.setLevel(logging.WARN)
Revert "Use tempfile lib for log file"
## Code Before: import logging import tempfile logger = logging.getLogger("LanguageClient") with tempfile.NamedTemporaryFile( prefix="LanguageClient-", suffix=".log", delete=False) as tmp: tmpname = tmp.name fileHandler = logging.FileHandler(filename=tmpname) fileHandler.setFormatter( logging.Formatter( "%(asctime)s %(levelname)-8s %(message)s", "%H:%M:%S")) logger.addHandler(fileHandler) logger.setLevel(logging.WARN) ## Instruction: Revert "Use tempfile lib for log file" ## Code After: import logging logger = logging.getLogger("LanguageClient") fileHandler = logging.FileHandler(filename="/tmp/LanguageClient.log") fileHandler.setFormatter( logging.Formatter( "%(asctime)s %(levelname)-8s %(message)s", "%H:%M:%S")) logger.addHandler(fileHandler) logger.setLevel(logging.WARN)
... import logging ... logger = logging.getLogger("LanguageClient") fileHandler = logging.FileHandler(filename="/tmp/LanguageClient.log") fileHandler.setFormatter( ...
0a4d3f5b837cfa0d41a927c193a831a1c00b51f5
setup.py
setup.py
from distutils.core import setup from hydra_agent import __version__ setup( name = 'hydra-agent', version = __version__, author = "Whamcloud, Inc.", author_email = "[email protected]", packages = ['hydra_agent', 'hydra_agent/cmds'], scripts = ['bin/hydra-agent.py', 'bin/hydra-rmmod.py'], data_files=[('/usr/lib/ocf/resource.d/hydra', ['Target'])], url = 'http://www.whamcloud.com/', license = 'Proprietary', description = 'The Whamcloud Lustre Monitoring and Adminisration Interface Agent', long_description = open('README.txt').read(), )
from distutils.core import setup from hydra_agent import __version__ setup( name = 'hydra-agent', version = __version__, author = "Whamcloud, Inc.", author_email = "[email protected]", packages = ['hydra_agent', 'hydra_agent/cmds', 'hydra_agent/audit', 'hydra_agent/audit/lustre'], scripts = ['bin/hydra-agent.py', 'bin/hydra-rmmod.py'], data_files=[('/usr/lib/ocf/resource.d/hydra', ['Target'])], url = 'http://www.whamcloud.com/', license = 'Proprietary', description = 'The Whamcloud Lustre Monitoring and Adminisration Interface Agent', long_description = open('README.txt').read(), )
Add new paths for audit/
Add new paths for audit/
Python
mit
intel-hpdd/intel-manager-for-lustre,intel-hpdd/intel-manager-for-lustre,intel-hpdd/intel-manager-for-lustre
from distutils.core import setup from hydra_agent import __version__ setup( name = 'hydra-agent', version = __version__, author = "Whamcloud, Inc.", author_email = "[email protected]", - packages = ['hydra_agent', 'hydra_agent/cmds'], + packages = ['hydra_agent', 'hydra_agent/cmds', 'hydra_agent/audit', 'hydra_agent/audit/lustre'], scripts = ['bin/hydra-agent.py', 'bin/hydra-rmmod.py'], data_files=[('/usr/lib/ocf/resource.d/hydra', ['Target'])], url = 'http://www.whamcloud.com/', license = 'Proprietary', description = 'The Whamcloud Lustre Monitoring and Adminisration Interface Agent', long_description = open('README.txt').read(), )
Add new paths for audit/
## Code Before: from distutils.core import setup from hydra_agent import __version__ setup( name = 'hydra-agent', version = __version__, author = "Whamcloud, Inc.", author_email = "[email protected]", packages = ['hydra_agent', 'hydra_agent/cmds'], scripts = ['bin/hydra-agent.py', 'bin/hydra-rmmod.py'], data_files=[('/usr/lib/ocf/resource.d/hydra', ['Target'])], url = 'http://www.whamcloud.com/', license = 'Proprietary', description = 'The Whamcloud Lustre Monitoring and Adminisration Interface Agent', long_description = open('README.txt').read(), ) ## Instruction: Add new paths for audit/ ## Code After: from distutils.core import setup from hydra_agent import __version__ setup( name = 'hydra-agent', version = __version__, author = "Whamcloud, Inc.", author_email = "[email protected]", packages = ['hydra_agent', 'hydra_agent/cmds', 'hydra_agent/audit', 'hydra_agent/audit/lustre'], scripts = ['bin/hydra-agent.py', 'bin/hydra-rmmod.py'], data_files=[('/usr/lib/ocf/resource.d/hydra', ['Target'])], url = 'http://www.whamcloud.com/', license = 'Proprietary', description = 'The Whamcloud Lustre Monitoring and Adminisration Interface Agent', long_description = open('README.txt').read(), )
# ... existing code ... author_email = "[email protected]", packages = ['hydra_agent', 'hydra_agent/cmds', 'hydra_agent/audit', 'hydra_agent/audit/lustre'], scripts = ['bin/hydra-agent.py', 'bin/hydra-rmmod.py'], # ... rest of the code ...
c5eb0358e763d626f503fa45228752da10b7c70d
openfisca_core/commons.py
openfisca_core/commons.py
unicode_type = u"".__class__ basestring_type = (b"".__class__, unicode_type) def to_unicode(string): """ :param string: a string that needs to be unicoded :param encoding: a string that represent the encoding type :return: a unicode string if the string is a python 2 str type, returns a unicode version of the string. """ if not isinstance(string, basestring_type): string = str(string) if isinstance(string, unicode_type): return string # Next line only gets triggered if the code is run in python 2 return unicode(string, 'utf-8') class Dummy(object): """A class that does nothing Used by function ``empty_clone`` to create an empty instance from an existing object. """ pass def empty_clone(original): """Create a new empty instance of the same class of the original object.""" new = Dummy() new.__class__ = original.__class__ return new def stringify_array(array): """ Generate a clean string representation of a NumPY array. """ return u'[{}]'.format(u', '.join( to_unicode(cell) for cell in array )) if array is not None else u'None'
unicode_type = u"".__class__ basestring_type = (b"".__class__, unicode_type) def to_unicode(string): """ :param string: a string that needs to be unicoded :param encoding: a string that represent the encoding type :return: a unicode string if the string is a python 2 str type, returns a unicode version of the string. """ if not isinstance(string, basestring_type): string = str(string) if isinstance(string, unicode_type): return string # Next line only gets triggered if the code is run in python 2 return string.decode('utf-8') class Dummy(object): """A class that does nothing Used by function ``empty_clone`` to create an empty instance from an existing object. """ pass def empty_clone(original): """Create a new empty instance of the same class of the original object.""" new = Dummy() new.__class__ = original.__class__ return new def stringify_array(array): """ Generate a clean string representation of a NumPY array. """ return u'[{}]'.format(u', '.join( to_unicode(cell) for cell in array )) if array is not None else u'None'
Make to_unicode work in Python 3
Make to_unicode work in Python 3
Python
agpl-3.0
openfisca/openfisca-core,openfisca/openfisca-core
unicode_type = u"".__class__ basestring_type = (b"".__class__, unicode_type) def to_unicode(string): """ :param string: a string that needs to be unicoded :param encoding: a string that represent the encoding type :return: a unicode string if the string is a python 2 str type, returns a unicode version of the string. """ if not isinstance(string, basestring_type): string = str(string) if isinstance(string, unicode_type): return string # Next line only gets triggered if the code is run in python 2 - return unicode(string, 'utf-8') + return string.decode('utf-8') class Dummy(object): """A class that does nothing Used by function ``empty_clone`` to create an empty instance from an existing object. """ pass def empty_clone(original): """Create a new empty instance of the same class of the original object.""" new = Dummy() new.__class__ = original.__class__ return new def stringify_array(array): """ Generate a clean string representation of a NumPY array. """ return u'[{}]'.format(u', '.join( to_unicode(cell) for cell in array )) if array is not None else u'None'
Make to_unicode work in Python 3
## Code Before: unicode_type = u"".__class__ basestring_type = (b"".__class__, unicode_type) def to_unicode(string): """ :param string: a string that needs to be unicoded :param encoding: a string that represent the encoding type :return: a unicode string if the string is a python 2 str type, returns a unicode version of the string. """ if not isinstance(string, basestring_type): string = str(string) if isinstance(string, unicode_type): return string # Next line only gets triggered if the code is run in python 2 return unicode(string, 'utf-8') class Dummy(object): """A class that does nothing Used by function ``empty_clone`` to create an empty instance from an existing object. """ pass def empty_clone(original): """Create a new empty instance of the same class of the original object.""" new = Dummy() new.__class__ = original.__class__ return new def stringify_array(array): """ Generate a clean string representation of a NumPY array. """ return u'[{}]'.format(u', '.join( to_unicode(cell) for cell in array )) if array is not None else u'None' ## Instruction: Make to_unicode work in Python 3 ## Code After: unicode_type = u"".__class__ basestring_type = (b"".__class__, unicode_type) def to_unicode(string): """ :param string: a string that needs to be unicoded :param encoding: a string that represent the encoding type :return: a unicode string if the string is a python 2 str type, returns a unicode version of the string. """ if not isinstance(string, basestring_type): string = str(string) if isinstance(string, unicode_type): return string # Next line only gets triggered if the code is run in python 2 return string.decode('utf-8') class Dummy(object): """A class that does nothing Used by function ``empty_clone`` to create an empty instance from an existing object. """ pass def empty_clone(original): """Create a new empty instance of the same class of the original object.""" new = Dummy() new.__class__ = original.__class__ return new def stringify_array(array): """ Generate a clean string representation of a NumPY array. """ return u'[{}]'.format(u', '.join( to_unicode(cell) for cell in array )) if array is not None else u'None'
# ... existing code ... # Next line only gets triggered if the code is run in python 2 return string.decode('utf-8') # ... rest of the code ...
afe90ba2a9720ffd80780e7696353510501362c7
studygroups/management/commands/generate_reminders.py
studygroups/management/commands/generate_reminders.py
from django.core.management.base import BaseCommand, CommandError from studygroups.tasks import gen_reminders class Command(BaseCommand): help = 'Generate reminders for all study groups happening in 3 days from now' def handle(self, *args, **options): gen_reminders()
from django.core.management.base import BaseCommand, CommandError from django.utils import timezone from studygroups.models import Meeting from studygroups.models.learningcircle import generate_meeting_reminder class Command(BaseCommand): help = 'Transitional command to generate reminders for all meetings in the future.' def handle(self, *args, **options): today = timezone.now().date() meetings = Meeting.objects.active().filter(study_group__deleted_at__isnull=True).filter(meeting_date__gte=today) for meeting in meetings: print(f'Generating meeting reminder for meeting happening {meeting.meeting_date}') generate_meeting_reminder(meeting)
Update task to generate reminders for all future meetings
Update task to generate reminders for all future meetings
Python
mit
p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles
from django.core.management.base import BaseCommand, CommandError + from django.utils import timezone - from studygroups.tasks import gen_reminders + from studygroups.models import Meeting + from studygroups.models.learningcircle import generate_meeting_reminder class Command(BaseCommand): - help = 'Generate reminders for all study groups happening in 3 days from now' + help = 'Transitional command to generate reminders for all meetings in the future.' def handle(self, *args, **options): - gen_reminders() + today = timezone.now().date() + meetings = Meeting.objects.active().filter(study_group__deleted_at__isnull=True).filter(meeting_date__gte=today) + for meeting in meetings: + print(f'Generating meeting reminder for meeting happening {meeting.meeting_date}') + generate_meeting_reminder(meeting)
Update task to generate reminders for all future meetings
## Code Before: from django.core.management.base import BaseCommand, CommandError from studygroups.tasks import gen_reminders class Command(BaseCommand): help = 'Generate reminders for all study groups happening in 3 days from now' def handle(self, *args, **options): gen_reminders() ## Instruction: Update task to generate reminders for all future meetings ## Code After: from django.core.management.base import BaseCommand, CommandError from django.utils import timezone from studygroups.models import Meeting from studygroups.models.learningcircle import generate_meeting_reminder class Command(BaseCommand): help = 'Transitional command to generate reminders for all meetings in the future.' def handle(self, *args, **options): today = timezone.now().date() meetings = Meeting.objects.active().filter(study_group__deleted_at__isnull=True).filter(meeting_date__gte=today) for meeting in meetings: print(f'Generating meeting reminder for meeting happening {meeting.meeting_date}') generate_meeting_reminder(meeting)
# ... existing code ... from django.core.management.base import BaseCommand, CommandError from django.utils import timezone from studygroups.models import Meeting from studygroups.models.learningcircle import generate_meeting_reminder # ... modified code ... class Command(BaseCommand): help = 'Transitional command to generate reminders for all meetings in the future.' ... def handle(self, *args, **options): today = timezone.now().date() meetings = Meeting.objects.active().filter(study_group__deleted_at__isnull=True).filter(meeting_date__gte=today) for meeting in meetings: print(f'Generating meeting reminder for meeting happening {meeting.meeting_date}') generate_meeting_reminder(meeting) # ... rest of the code ...
2a71b48fb3ff2ec720ace74e30a83102c31863dc
labonneboite/common/email_util.py
labonneboite/common/email_util.py
import json import logging from labonneboite.conf import settings logger = logging.getLogger('main') class MailNoSendException(Exception): pass class EmailClient(object): to = settings.FORM_EMAIL from_email = settings.ADMIN_EMAIL subject = 'nouveau message entreprise LBB' class MandrillClient(EmailClient): def __init__(self, mandrill): self.mandrill = mandrill def send(self, html): from_email = self.from_email to_email = self.to response = self.mandrill.send_email( subject=self.subject, to=[{'email': to_email}], html=html, from_email=from_email) content = json.loads(response.content.decode()) if content[0]["status"] != "sent": raise MailNoSendException("email was not sent from %s to %s" % (from_email, to_email)) return response
import json import logging from urllib.error import HTTPError from labonneboite.conf import settings logger = logging.getLogger('main') class MailNoSendException(Exception): pass class EmailClient(object): to = settings.FORM_EMAIL from_email = settings.ADMIN_EMAIL subject = 'nouveau message entreprise LBB' class MandrillClient(EmailClient): def __init__(self, mandrill): self.mandrill = mandrill def send(self, html): from_email = self.from_email to_email = self.to try: response = self.mandrill.send_email( subject=self.subject, to=[{'email': to_email}], html=html, from_email=from_email) content = json.loads(response.content.decode()) if content[0]["status"] != "sent": raise MailNoSendException("email was not sent from %s to %s" % (from_email, to_email)) except HTTPError: raise MailNoSendException("email was not sent from %s to %s" % (from_email, to_email)) return response
Handle HttpError when sending email
Handle HttpError when sending email
Python
agpl-3.0
StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite
import json import logging + from urllib.error import HTTPError from labonneboite.conf import settings logger = logging.getLogger('main') class MailNoSendException(Exception): pass class EmailClient(object): to = settings.FORM_EMAIL from_email = settings.ADMIN_EMAIL subject = 'nouveau message entreprise LBB' class MandrillClient(EmailClient): def __init__(self, mandrill): self.mandrill = mandrill def send(self, html): from_email = self.from_email to_email = self.to + + try: - response = self.mandrill.send_email( + response = self.mandrill.send_email( - subject=self.subject, + subject=self.subject, - to=[{'email': to_email}], + to=[{'email': to_email}], - html=html, + html=html, - from_email=from_email) + from_email=from_email) - content = json.loads(response.content.decode()) + content = json.loads(response.content.decode()) - if content[0]["status"] != "sent": + if content[0]["status"] != "sent": + raise MailNoSendException("email was not sent from %s to %s" % (from_email, to_email)) + except HTTPError: raise MailNoSendException("email was not sent from %s to %s" % (from_email, to_email)) + return response
Handle HttpError when sending email
## Code Before: import json import logging from labonneboite.conf import settings logger = logging.getLogger('main') class MailNoSendException(Exception): pass class EmailClient(object): to = settings.FORM_EMAIL from_email = settings.ADMIN_EMAIL subject = 'nouveau message entreprise LBB' class MandrillClient(EmailClient): def __init__(self, mandrill): self.mandrill = mandrill def send(self, html): from_email = self.from_email to_email = self.to response = self.mandrill.send_email( subject=self.subject, to=[{'email': to_email}], html=html, from_email=from_email) content = json.loads(response.content.decode()) if content[0]["status"] != "sent": raise MailNoSendException("email was not sent from %s to %s" % (from_email, to_email)) return response ## Instruction: Handle HttpError when sending email ## Code After: import json import logging from urllib.error import HTTPError from labonneboite.conf import settings logger = logging.getLogger('main') class MailNoSendException(Exception): pass class EmailClient(object): to = settings.FORM_EMAIL from_email = settings.ADMIN_EMAIL subject = 'nouveau message entreprise LBB' class MandrillClient(EmailClient): def __init__(self, mandrill): self.mandrill = mandrill def send(self, html): from_email = self.from_email to_email = self.to try: response = self.mandrill.send_email( subject=self.subject, to=[{'email': to_email}], html=html, from_email=from_email) content = json.loads(response.content.decode()) if content[0]["status"] != "sent": raise MailNoSendException("email was not sent from %s to %s" % (from_email, to_email)) except HTTPError: raise MailNoSendException("email was not sent from %s to %s" % (from_email, to_email)) return response
... import logging from urllib.error import HTTPError ... to_email = self.to try: response = self.mandrill.send_email( subject=self.subject, to=[{'email': to_email}], html=html, from_email=from_email) content = json.loads(response.content.decode()) if content[0]["status"] != "sent": raise MailNoSendException("email was not sent from %s to %s" % (from_email, to_email)) except HTTPError: raise MailNoSendException("email was not sent from %s to %s" % (from_email, to_email)) return response ...
6bd8ecf5719e15674ef67100b92822be3cf8e5ec
dataportal/tests/test_replay_persistance.py
dataportal/tests/test_replay_persistance.py
import nose from dataportal.replay.persist import History h = None def setup(): h = History(':memory:') def test_history(): pass
from nose.tools import assert_equal from dataportal.replay.persist import History import dataportal.replay.persist OBJ_ID_LEN = 36 h = None def setup(): global h h = History(':memory:') def test_history(): run_id = ''.join(['a'] * OBJ_ID_LEN) # Simple round-trip: put and get config1 = {'plot_x': 'long', 'plot_y': 'island'} h.put(run_id, config1) result1 = h.get(run_id) assert_equal(result1, config1) # Put a second entry. Check that get returns most recent. config2 = {'plot_x': 'new', 'plot_y': 'york'} h.put(run_id, config2) result2 = h.get(run_id) assert_equal(result2, config2) # And get(..., 1) returns previous. result1 = h.get(run_id, 1) assert_equal(result1, config1)
Add real tests of replay History.
TST: Add real tests of replay History.
Python
bsd-3-clause
tacaswell/dataportal,danielballan/datamuxer,danielballan/datamuxer,NSLS-II/dataportal,ericdill/datamuxer,danielballan/dataportal,NSLS-II/datamuxer,danielballan/dataportal,ericdill/databroker,tacaswell/dataportal,NSLS-II/dataportal,ericdill/datamuxer,ericdill/databroker
- import nose + from nose.tools import assert_equal from dataportal.replay.persist import History + import dataportal.replay.persist + OBJ_ID_LEN = 36 h = None + def setup(): + global h h = History(':memory:') + def test_history(): - pass + run_id = ''.join(['a'] * OBJ_ID_LEN) + # Simple round-trip: put and get + config1 = {'plot_x': 'long', 'plot_y': 'island'} + h.put(run_id, config1) + result1 = h.get(run_id) + assert_equal(result1, config1) + # Put a second entry. Check that get returns most recent. + config2 = {'plot_x': 'new', 'plot_y': 'york'} + h.put(run_id, config2) + result2 = h.get(run_id) + assert_equal(result2, config2) + # And get(..., 1) returns previous. + result1 = h.get(run_id, 1) + assert_equal(result1, config1) +
Add real tests of replay History.
## Code Before: import nose from dataportal.replay.persist import History h = None def setup(): h = History(':memory:') def test_history(): pass ## Instruction: Add real tests of replay History. ## Code After: from nose.tools import assert_equal from dataportal.replay.persist import History import dataportal.replay.persist OBJ_ID_LEN = 36 h = None def setup(): global h h = History(':memory:') def test_history(): run_id = ''.join(['a'] * OBJ_ID_LEN) # Simple round-trip: put and get config1 = {'plot_x': 'long', 'plot_y': 'island'} h.put(run_id, config1) result1 = h.get(run_id) assert_equal(result1, config1) # Put a second entry. Check that get returns most recent. config2 = {'plot_x': 'new', 'plot_y': 'york'} h.put(run_id, config2) result2 = h.get(run_id) assert_equal(result2, config2) # And get(..., 1) returns previous. result1 = h.get(run_id, 1) assert_equal(result1, config1)
... from nose.tools import assert_equal from dataportal.replay.persist import History import dataportal.replay.persist OBJ_ID_LEN = 36 h = None ... def setup(): global h h = History(':memory:') ... def test_history(): run_id = ''.join(['a'] * OBJ_ID_LEN) # Simple round-trip: put and get config1 = {'plot_x': 'long', 'plot_y': 'island'} h.put(run_id, config1) result1 = h.get(run_id) assert_equal(result1, config1) # Put a second entry. Check that get returns most recent. config2 = {'plot_x': 'new', 'plot_y': 'york'} h.put(run_id, config2) result2 = h.get(run_id) assert_equal(result2, config2) # And get(..., 1) returns previous. result1 = h.get(run_id, 1) assert_equal(result1, config1) ...
5e03af4b0f920e97507b3ada6b4b925136ddbf07
froide/upload/serializers.py
froide/upload/serializers.py
from rest_framework import serializers from .models import Upload class UploadSerializer(serializers.ModelSerializer): class Meta: model = Upload fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['guid'].required = True
from rest_framework import serializers from .models import Upload class UploadSerializer(serializers.ModelSerializer): class Meta: model = Upload fields = '__all__' def __init__(self, *args, **kwargs): ''' Add required marker, so OpenAPI schema generator can remove it again -.- ''' super().__init__(*args, **kwargs) self.fields['guid'].required = True
Add some documentation for weird init
Add some documentation for weird init
Python
mit
fin/froide,stefanw/froide,stefanw/froide,fin/froide,fin/froide,fin/froide,stefanw/froide,stefanw/froide,stefanw/froide
from rest_framework import serializers from .models import Upload class UploadSerializer(serializers.ModelSerializer): class Meta: model = Upload fields = '__all__' def __init__(self, *args, **kwargs): + ''' + Add required marker, so OpenAPI schema generator can remove it again + -.- + ''' super().__init__(*args, **kwargs) self.fields['guid'].required = True
Add some documentation for weird init
## Code Before: from rest_framework import serializers from .models import Upload class UploadSerializer(serializers.ModelSerializer): class Meta: model = Upload fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['guid'].required = True ## Instruction: Add some documentation for weird init ## Code After: from rest_framework import serializers from .models import Upload class UploadSerializer(serializers.ModelSerializer): class Meta: model = Upload fields = '__all__' def __init__(self, *args, **kwargs): ''' Add required marker, so OpenAPI schema generator can remove it again -.- ''' super().__init__(*args, **kwargs) self.fields['guid'].required = True
... def __init__(self, *args, **kwargs): ''' Add required marker, so OpenAPI schema generator can remove it again -.- ''' super().__init__(*args, **kwargs) ...
7086b1967c3a3666260e6358c72cb15c74213bea
sunpy/net/tests/test_attr.py
sunpy/net/tests/test_attr.py
from __future__ import absolute_import from sunpy.net import attr def test_dummyattr(): one = attr.DummyAttr() other = attr.ValueAttr({'a': 'b'}) assert (one | other) is other assert (one & other) is other
from __future__ import absolute_import from sunpy.net import attr from sunpy.net.vso import attrs def test_dummyattr(): one = attr.DummyAttr() other = attr.ValueAttr({'a': 'b'}) assert (one | other) is other assert (one & other) is other def test_and_nesting(): a = attr.and_(attrs.Level(0), attr.AttrAnd((attrs.Instrument('EVE'), attrs.Time("2012/1/1", "2012/01/02")))) # Test that the nesting has been removed. assert len(a.attrs) == 3 def test_or_nesting(): a = attr.or_(attrs.Instrument('a'), attr.AttrOr((attrs.Instrument('b'), attrs.Instrument('c')))) # Test that the nesting has been removed. assert len(a.attrs) == 3
Add tests for Attr nesting
Add tests for Attr nesting
Python
bsd-2-clause
dpshelio/sunpy,dpshelio/sunpy,dpshelio/sunpy
from __future__ import absolute_import from sunpy.net import attr + from sunpy.net.vso import attrs def test_dummyattr(): one = attr.DummyAttr() other = attr.ValueAttr({'a': 'b'}) assert (one | other) is other assert (one & other) is other + def test_and_nesting(): + a = attr.and_(attrs.Level(0), + attr.AttrAnd((attrs.Instrument('EVE'), + attrs.Time("2012/1/1", "2012/01/02")))) + # Test that the nesting has been removed. + assert len(a.attrs) == 3 + + def test_or_nesting(): + a = attr.or_(attrs.Instrument('a'), + attr.AttrOr((attrs.Instrument('b'), + attrs.Instrument('c')))) + # Test that the nesting has been removed. + assert len(a.attrs) == 3 +
Add tests for Attr nesting
## Code Before: from __future__ import absolute_import from sunpy.net import attr def test_dummyattr(): one = attr.DummyAttr() other = attr.ValueAttr({'a': 'b'}) assert (one | other) is other assert (one & other) is other ## Instruction: Add tests for Attr nesting ## Code After: from __future__ import absolute_import from sunpy.net import attr from sunpy.net.vso import attrs def test_dummyattr(): one = attr.DummyAttr() other = attr.ValueAttr({'a': 'b'}) assert (one | other) is other assert (one & other) is other def test_and_nesting(): a = attr.and_(attrs.Level(0), attr.AttrAnd((attrs.Instrument('EVE'), attrs.Time("2012/1/1", "2012/01/02")))) # Test that the nesting has been removed. assert len(a.attrs) == 3 def test_or_nesting(): a = attr.or_(attrs.Instrument('a'), attr.AttrOr((attrs.Instrument('b'), attrs.Instrument('c')))) # Test that the nesting has been removed. assert len(a.attrs) == 3
... from sunpy.net import attr from sunpy.net.vso import attrs ... assert (one & other) is other def test_and_nesting(): a = attr.and_(attrs.Level(0), attr.AttrAnd((attrs.Instrument('EVE'), attrs.Time("2012/1/1", "2012/01/02")))) # Test that the nesting has been removed. assert len(a.attrs) == 3 def test_or_nesting(): a = attr.or_(attrs.Instrument('a'), attr.AttrOr((attrs.Instrument('b'), attrs.Instrument('c')))) # Test that the nesting has been removed. assert len(a.attrs) == 3 ...
917ba14418f01fa2fc866fc1c18989cc500c2cfd
bin/license_finder_pip.py
bin/license_finder_pip.py
import json import sys from pip._internal.req import parse_requirements from pip._internal.download import PipSession from pip._vendor import pkg_resources from pip._vendor.six import print_ requirements = [pkg_resources.Requirement.parse(str(req.req)) for req in parse_requirements(sys.argv[1], session=PipSession()) if req.req != None] transform = lambda dist: { 'name': dist.project_name, 'version': dist.version, 'location': dist.location, 'dependencies': list(map(lambda dependency: dependency.project_name, dist.requires())), } packages = [transform(dist) for dist in pkg_resources.working_set.resolve(requirements)] print_(json.dumps(packages))
import json import sys try: from pip._internal.req import parse_requirements except ImportError: from pip.req import parse_requirements try: from pip._internal.download import PipSession except ImportError: from pip.download import PipSession from pip._vendor import pkg_resources from pip._vendor.six import print_ requirements = [pkg_resources.Requirement.parse(str(req.req)) for req in parse_requirements(sys.argv[1], session=PipSession()) if req.req != None] transform = lambda dist: { 'name': dist.project_name, 'version': dist.version, 'location': dist.location, 'dependencies': list(map(lambda dependency: dependency.project_name, dist.requires())), } packages = [transform(dist) for dist in pkg_resources.working_set.resolve(requirements)] print_(json.dumps(packages))
Add backwards compatibility with pip v9
Add backwards compatibility with pip v9
Python
mit
pivotal/LicenseFinder,pivotal/LicenseFinder,pivotal/LicenseFinder,pivotal/LicenseFinder,pivotal/LicenseFinder,pivotal/LicenseFinder,pivotal/LicenseFinder
import json import sys + + try: - from pip._internal.req import parse_requirements + from pip._internal.req import parse_requirements + except ImportError: + from pip.req import parse_requirements + try: - from pip._internal.download import PipSession + from pip._internal.download import PipSession + except ImportError: + from pip.download import PipSession + from pip._vendor import pkg_resources from pip._vendor.six import print_ requirements = [pkg_resources.Requirement.parse(str(req.req)) for req in parse_requirements(sys.argv[1], session=PipSession()) if req.req != None] transform = lambda dist: { 'name': dist.project_name, 'version': dist.version, 'location': dist.location, 'dependencies': list(map(lambda dependency: dependency.project_name, dist.requires())), } packages = [transform(dist) for dist in pkg_resources.working_set.resolve(requirements)] print_(json.dumps(packages))
Add backwards compatibility with pip v9
## Code Before: import json import sys from pip._internal.req import parse_requirements from pip._internal.download import PipSession from pip._vendor import pkg_resources from pip._vendor.six import print_ requirements = [pkg_resources.Requirement.parse(str(req.req)) for req in parse_requirements(sys.argv[1], session=PipSession()) if req.req != None] transform = lambda dist: { 'name': dist.project_name, 'version': dist.version, 'location': dist.location, 'dependencies': list(map(lambda dependency: dependency.project_name, dist.requires())), } packages = [transform(dist) for dist in pkg_resources.working_set.resolve(requirements)] print_(json.dumps(packages)) ## Instruction: Add backwards compatibility with pip v9 ## Code After: import json import sys try: from pip._internal.req import parse_requirements except ImportError: from pip.req import parse_requirements try: from pip._internal.download import PipSession except ImportError: from pip.download import PipSession from pip._vendor import pkg_resources from pip._vendor.six import print_ requirements = [pkg_resources.Requirement.parse(str(req.req)) for req in parse_requirements(sys.argv[1], session=PipSession()) if req.req != None] transform = lambda dist: { 'name': dist.project_name, 'version': dist.version, 'location': dist.location, 'dependencies': list(map(lambda dependency: dependency.project_name, dist.requires())), } packages = [transform(dist) for dist in pkg_resources.working_set.resolve(requirements)] print_(json.dumps(packages))
# ... existing code ... import sys try: from pip._internal.req import parse_requirements except ImportError: from pip.req import parse_requirements try: from pip._internal.download import PipSession except ImportError: from pip.download import PipSession from pip._vendor import pkg_resources # ... rest of the code ...
1fa6bcbd5ab5e51f9e4250024c848933ea0911e7
examples/upsidedownternet.py
examples/upsidedownternet.py
import Image, cStringIO def response(context, flow): if flow.response.headers["content-type"] == ["image/png"]: s = cStringIO.StringIO(flow.response.content) img = Image.open(s).rotate(180) s2 = cStringIO.StringIO() img.save(s2, "png") flow.response.content = s2.getvalue()
import cStringIO from PIL import Image def response(context, flow): if flow.response.headers["content-type"] == ["image/png"]: s = cStringIO.StringIO(flow.response.content) img = Image.open(s).rotate(180) s2 = cStringIO.StringIO() img.save(s2, "png") flow.response.content = s2.getvalue()
Update another reference to PIL.
Update another reference to PIL.
Python
mit
dwfreed/mitmproxy,tdickers/mitmproxy,StevenVanAcker/mitmproxy,bazzinotti/mitmproxy,owers19856/mitmproxy,liorvh/mitmproxy,liorvh/mitmproxy,ryoqun/mitmproxy,guiquanz/mitmproxy,Endika/mitmproxy,dufferzafar/mitmproxy,dwfreed/mitmproxy,laurmurclar/mitmproxy,jvillacorta/mitmproxy,dufferzafar/mitmproxy,mosajjal/mitmproxy,dxq-git/mitmproxy,rauburtin/mitmproxy,mitmproxy/mitmproxy,byt3bl33d3r/mitmproxy,mosajjal/mitmproxy,meizhoubao/mitmproxy,Kriechi/mitmproxy,dxq-git/mitmproxy,ZeYt/mitmproxy,dwfreed/mitmproxy,macmantrl/mitmproxy,cortesi/mitmproxy,fimad/mitmproxy,macmantrl/mitmproxy,zlorb/mitmproxy,laurmurclar/mitmproxy,ujjwal96/mitmproxy,dufferzafar/mitmproxy,byt3bl33d3r/mitmproxy,ujjwal96/mitmproxy,ParthGanatra/mitmproxy,ryoqun/mitmproxy,ParthGanatra/mitmproxy,xaxa89/mitmproxy,scriptmediala/mitmproxy,onlywade/mitmproxy,onlywade/mitmproxy,0x0mar/mitmproxy,claimsmall/mitmproxy,tfeagle/mitmproxy,bltb/mitmproxy,sethp-jive/mitmproxy,guiquanz/mitmproxy,mitmproxy/mitmproxy,zbuc/mitmproxy,tfeagle/mitmproxy,noikiy/mitmproxy,syjzwjj/mitmproxy,tfeagle/mitmproxy,byt3bl33d3r/mitmproxy,scriptmediala/mitmproxy,gzzhanghao/mitmproxy,sethp-jive/mitmproxy,sethp-jive/mitmproxy,mhils/mitmproxy,azureplus/mitmproxy,dufferzafar/mitmproxy,vhaupert/mitmproxy,MatthewShao/mitmproxy,MatthewShao/mitmproxy,tekii/mitmproxy,mhils/mitmproxy,ujjwal96/mitmproxy,dweinstein/mitmproxy,owers19856/mitmproxy,tdickers/mitmproxy,tekii/mitmproxy,ADemonisis/mitmproxy,bazzinotti/mitmproxy,meizhoubao/mitmproxy,pombredanne/mitmproxy,xtso520ok/mitmproxy,guiquanz/mitmproxy,devasia1000/anti_adblock,syjzwjj/mitmproxy,Endika/mitmproxy,pombredanne/mitmproxy,xaxa89/mitmproxy,liorvh/mitmproxy,azureplus/mitmproxy,sethp-jive/mitmproxy,tekii/mitmproxy,xaxa89/mitmproxy,ZeYt/mitmproxy,elitest/mitmproxy,bltb/mitmproxy,zlorb/mitmproxy,dwfreed/mitmproxy,jvillacorta/mitmproxy,jvillacorta/mitmproxy,inscriptionweb/mitmproxy,claimsmall/mitmproxy,scriptmediala/mitmproxy,meizhoubao/mitmproxy,ParthGanatra/mitmproxy,jvillacorta/mitmproxy,xbzbing/mitmproxy,claimsmall/mitmproxy,onlywade/mitmproxy,owers19856/mitmproxy,tdickers/mitmproxy,Endika/mitmproxy,jpic/mitmproxy,Kriechi/mitmproxy,guiquanz/mitmproxy,MatthewShao/mitmproxy,StevenVanAcker/mitmproxy,zbuc/mitmproxy,0x0mar/mitmproxy,ZeYt/mitmproxy,fimad/mitmproxy,liorvh/mitmproxy,zlorb/mitmproxy,ccccccccccc/mitmproxy,ccccccccccc/mitmproxy,fimad/mitmproxy,0x0mar/mitmproxy,bltb/mitmproxy,ikoz/mitmproxy,legendtang/mitmproxy,jpic/mitmproxy,gzzhanghao/mitmproxy,devasia1000/mitmproxy,0xwindows/InfoLeak,xbzbing/mitmproxy,ADemonisis/mitmproxy,cortesi/mitmproxy,claimsmall/mitmproxy,ADemonisis/mitmproxy,byt3bl33d3r/mitmproxy,mitmproxy/mitmproxy,tekii/mitmproxy,mitmproxy/mitmproxy,rauburtin/mitmproxy,bazzinotti/mitmproxy,pombredanne/mitmproxy,vhaupert/mitmproxy,bltb/mitmproxy,azureplus/mitmproxy,devasia1000/mitmproxy,ikoz/mitmproxy,legendtang/mitmproxy,mosajjal/mitmproxy,ddworken/mitmproxy,Endika/mitmproxy,legendtang/mitmproxy,ikoz/mitmproxy,elitest/mitmproxy,laurmurclar/mitmproxy,inscriptionweb/mitmproxy,ujjwal96/mitmproxy,ADemonisis/mitmproxy,vhaupert/mitmproxy,ddworken/mitmproxy,gzzhanghao/mitmproxy,ryoqun/mitmproxy,gzzhanghao/mitmproxy,macmantrl/mitmproxy,mosajjal/mitmproxy,MatthewShao/mitmproxy,meizhoubao/mitmproxy,owers19856/mitmproxy,Fuzion24/mitmproxy,ryoqun/mitmproxy,legendtang/mitmproxy,devasia1000/mitmproxy,xbzbing/mitmproxy,mhils/mitmproxy,ZeYt/mitmproxy,devasia1000/mitmproxy,dweinstein/mitmproxy,mhils/mitmproxy,Fuzion24/mitmproxy,0xwindows/InfoLeak,zbuc/mitmproxy,ParthGanatra/mitmproxy,mhils/mitmproxy,noikiy/mitmproxy,azureplus/mitmproxy,inscriptionweb/mitmproxy,jpic/mitmproxy,cortesi/mitmproxy,xbzbing/mitmproxy,bazzinotti/mitmproxy,macmantrl/mitmproxy,zbuc/mitmproxy,noikiy/mitmproxy,vhaupert/mitmproxy,rauburtin/mitmproxy,onlywade/mitmproxy,Fuzion24/mitmproxy,Fuzion24/mitmproxy,xtso520ok/mitmproxy,ccccccccccc/mitmproxy,Kriechi/mitmproxy,noikiy/mitmproxy,ddworken/mitmproxy,0xwindows/InfoLeak,scriptmediala/mitmproxy,rauburtin/mitmproxy,tdickers/mitmproxy,syjzwjj/mitmproxy,devasia1000/anti_adblock,ikoz/mitmproxy,xtso520ok/mitmproxy,dweinstein/mitmproxy,StevenVanAcker/mitmproxy,dxq-git/mitmproxy,inscriptionweb/mitmproxy,ccccccccccc/mitmproxy,laurmurclar/mitmproxy,elitest/mitmproxy,ddworken/mitmproxy,StevenVanAcker/mitmproxy,syjzwjj/mitmproxy,devasia1000/anti_adblock,dxq-git/mitmproxy,0xwindows/InfoLeak,zlorb/mitmproxy,cortesi/mitmproxy,fimad/mitmproxy,elitest/mitmproxy,Kriechi/mitmproxy,xaxa89/mitmproxy,tfeagle/mitmproxy,pombredanne/mitmproxy,mitmproxy/mitmproxy,dweinstein/mitmproxy,jpic/mitmproxy
- import Image, cStringIO + import cStringIO + from PIL import Image + def response(context, flow): if flow.response.headers["content-type"] == ["image/png"]: s = cStringIO.StringIO(flow.response.content) img = Image.open(s).rotate(180) s2 = cStringIO.StringIO() img.save(s2, "png") flow.response.content = s2.getvalue()
Update another reference to PIL.
## Code Before: import Image, cStringIO def response(context, flow): if flow.response.headers["content-type"] == ["image/png"]: s = cStringIO.StringIO(flow.response.content) img = Image.open(s).rotate(180) s2 = cStringIO.StringIO() img.save(s2, "png") flow.response.content = s2.getvalue() ## Instruction: Update another reference to PIL. ## Code After: import cStringIO from PIL import Image def response(context, flow): if flow.response.headers["content-type"] == ["image/png"]: s = cStringIO.StringIO(flow.response.content) img = Image.open(s).rotate(180) s2 = cStringIO.StringIO() img.save(s2, "png") flow.response.content = s2.getvalue()
// ... existing code ... import cStringIO from PIL import Image def response(context, flow): // ... rest of the code ...
20d7c4113a96c92f8353761da2c2a00ed7a35e0e
gym_ple/__init__.py
gym_ple/__init__.py
from gym.envs.registration import registry, register, make, spec from gym_ple.ple_env import PLEEnv # Pygame # ---------------------------------------- for game in ['Catcher', 'MonsterKong', 'FlappyBird', 'PixelCopter', 'PuckWorld', 'RaycastMaze', 'Snake', 'WaterWorld']: nondeterministic = False register( id='{}-v0'.format(game), entry_point='gym_ple:PLEEnv', kwargs={'game_name': game, 'display_screen':False}, timestep_limit=10000, nondeterministic=nondeterministic, )
from gym.envs.registration import registry, register, make, spec from gym_ple.ple_env import PLEEnv # Pygame # ---------------------------------------- for game in ['Catcher', 'MonsterKong', 'FlappyBird', 'PixelCopter', 'PuckWorld', 'RaycastMaze', 'Snake', 'WaterWorld']: nondeterministic = False register( id='{}-v0'.format(game), entry_point='gym_ple:PLEEnv', kwargs={'game_name': game, 'display_screen':False}, tags={'wrapper_config.TimeLimit.max_episode_steps': 10000}, nondeterministic=nondeterministic, )
Replace the timestep_limit call with the new tags api.
Replace the timestep_limit call with the new tags api.
Python
mit
lusob/gym-ple
from gym.envs.registration import registry, register, make, spec from gym_ple.ple_env import PLEEnv # Pygame # ---------------------------------------- for game in ['Catcher', 'MonsterKong', 'FlappyBird', 'PixelCopter', 'PuckWorld', 'RaycastMaze', 'Snake', 'WaterWorld']: nondeterministic = False register( id='{}-v0'.format(game), entry_point='gym_ple:PLEEnv', kwargs={'game_name': game, 'display_screen':False}, - timestep_limit=10000, + tags={'wrapper_config.TimeLimit.max_episode_steps': 10000}, nondeterministic=nondeterministic, )
Replace the timestep_limit call with the new tags api.
## Code Before: from gym.envs.registration import registry, register, make, spec from gym_ple.ple_env import PLEEnv # Pygame # ---------------------------------------- for game in ['Catcher', 'MonsterKong', 'FlappyBird', 'PixelCopter', 'PuckWorld', 'RaycastMaze', 'Snake', 'WaterWorld']: nondeterministic = False register( id='{}-v0'.format(game), entry_point='gym_ple:PLEEnv', kwargs={'game_name': game, 'display_screen':False}, timestep_limit=10000, nondeterministic=nondeterministic, ) ## Instruction: Replace the timestep_limit call with the new tags api. ## Code After: from gym.envs.registration import registry, register, make, spec from gym_ple.ple_env import PLEEnv # Pygame # ---------------------------------------- for game in ['Catcher', 'MonsterKong', 'FlappyBird', 'PixelCopter', 'PuckWorld', 'RaycastMaze', 'Snake', 'WaterWorld']: nondeterministic = False register( id='{}-v0'.format(game), entry_point='gym_ple:PLEEnv', kwargs={'game_name': game, 'display_screen':False}, tags={'wrapper_config.TimeLimit.max_episode_steps': 10000}, nondeterministic=nondeterministic, )
// ... existing code ... kwargs={'game_name': game, 'display_screen':False}, tags={'wrapper_config.TimeLimit.max_episode_steps': 10000}, nondeterministic=nondeterministic, // ... rest of the code ...
f861ca1f315a414f809993170ea95640505c0506
c2corg_api/scripts/migration/sequences.py
c2corg_api/scripts/migration/sequences.py
from sqlalchemy.sql import text from c2corg_api.scripts.migration.migrate_base import MigrateBase class UpdateSequences(MigrateBase): sequences = [ ('guidebook', 'documents_archives', 'id', 'documents_archives_id_seq'), ('guidebook', 'documents', 'document_id', 'documents_document_id_seq'), ('guidebook', 'documents_geometries_archives', 'id', 'documents_geometries_archives_id_seq'), ('guidebook', 'documents_locales_archives', 'id', 'documents_locales_archives_id_seq'), ('guidebook', 'documents_locales', 'id', 'documents_locales_id_seq'), ('guidebook', 'documents_versions', 'id', 'documents_versions_id_seq'), ('guidebook', 'history_metadata', 'id', 'history_metadata_id_seq'), ] def migrate(self): self.start('sequences') stmt = "select setval('{0}.{1}', (select max({2}) from {0}.{3}));" for schema, table, field, sequence in UpdateSequences.sequences: self.session_target.execute(text( stmt.format(schema, sequence, field, table))) self.stop()
from sqlalchemy.sql import text from c2corg_api.scripts.migration.migrate_base import MigrateBase class UpdateSequences(MigrateBase): sequences = [ ('guidebook', 'documents_archives', 'id', 'documents_archives_id_seq'), ('guidebook', 'documents', 'document_id', 'documents_document_id_seq'), ('guidebook', 'documents_geometries_archives', 'id', 'documents_geometries_archives_id_seq'), ('guidebook', 'documents_locales_archives', 'id', 'documents_locales_archives_id_seq'), ('guidebook', 'documents_locales', 'id', 'documents_locales_id_seq'), ('guidebook', 'documents_versions', 'id', 'documents_versions_id_seq'), ('guidebook', 'history_metadata', 'id', 'history_metadata_id_seq'), ('users', 'user', 'id', 'user_id_seq'), ] def migrate(self): self.start('sequences') stmt = "select setval('{0}.{1}', (select max({2}) from {0}.{3}));" for schema, table, field, sequence in UpdateSequences.sequences: self.session_target.execute(text( stmt.format(schema, sequence, field, table))) self.stop()
Add missing user_id_seq in migration script
Add missing user_id_seq in migration script
Python
agpl-3.0
c2corg/v6_api,c2corg/v6_api,c2corg/v6_api
from sqlalchemy.sql import text from c2corg_api.scripts.migration.migrate_base import MigrateBase class UpdateSequences(MigrateBase): sequences = [ ('guidebook', 'documents_archives', 'id', 'documents_archives_id_seq'), ('guidebook', 'documents', 'document_id', 'documents_document_id_seq'), ('guidebook', 'documents_geometries_archives', 'id', 'documents_geometries_archives_id_seq'), ('guidebook', 'documents_locales_archives', 'id', 'documents_locales_archives_id_seq'), ('guidebook', 'documents_locales', 'id', 'documents_locales_id_seq'), ('guidebook', 'documents_versions', 'id', 'documents_versions_id_seq'), ('guidebook', 'history_metadata', 'id', 'history_metadata_id_seq'), + ('users', 'user', 'id', 'user_id_seq'), ] def migrate(self): self.start('sequences') stmt = "select setval('{0}.{1}', (select max({2}) from {0}.{3}));" for schema, table, field, sequence in UpdateSequences.sequences: self.session_target.execute(text( stmt.format(schema, sequence, field, table))) self.stop()
Add missing user_id_seq in migration script
## Code Before: from sqlalchemy.sql import text from c2corg_api.scripts.migration.migrate_base import MigrateBase class UpdateSequences(MigrateBase): sequences = [ ('guidebook', 'documents_archives', 'id', 'documents_archives_id_seq'), ('guidebook', 'documents', 'document_id', 'documents_document_id_seq'), ('guidebook', 'documents_geometries_archives', 'id', 'documents_geometries_archives_id_seq'), ('guidebook', 'documents_locales_archives', 'id', 'documents_locales_archives_id_seq'), ('guidebook', 'documents_locales', 'id', 'documents_locales_id_seq'), ('guidebook', 'documents_versions', 'id', 'documents_versions_id_seq'), ('guidebook', 'history_metadata', 'id', 'history_metadata_id_seq'), ] def migrate(self): self.start('sequences') stmt = "select setval('{0}.{1}', (select max({2}) from {0}.{3}));" for schema, table, field, sequence in UpdateSequences.sequences: self.session_target.execute(text( stmt.format(schema, sequence, field, table))) self.stop() ## Instruction: Add missing user_id_seq in migration script ## Code After: from sqlalchemy.sql import text from c2corg_api.scripts.migration.migrate_base import MigrateBase class UpdateSequences(MigrateBase): sequences = [ ('guidebook', 'documents_archives', 'id', 'documents_archives_id_seq'), ('guidebook', 'documents', 'document_id', 'documents_document_id_seq'), ('guidebook', 'documents_geometries_archives', 'id', 'documents_geometries_archives_id_seq'), ('guidebook', 'documents_locales_archives', 'id', 'documents_locales_archives_id_seq'), ('guidebook', 'documents_locales', 'id', 'documents_locales_id_seq'), ('guidebook', 'documents_versions', 'id', 'documents_versions_id_seq'), ('guidebook', 'history_metadata', 'id', 'history_metadata_id_seq'), ('users', 'user', 'id', 'user_id_seq'), ] def migrate(self): self.start('sequences') stmt = "select setval('{0}.{1}', (select max({2}) from {0}.{3}));" for schema, table, field, sequence in UpdateSequences.sequences: self.session_target.execute(text( stmt.format(schema, sequence, field, table))) self.stop()
// ... existing code ... ('guidebook', 'history_metadata', 'id', 'history_metadata_id_seq'), ('users', 'user', 'id', 'user_id_seq'), ] // ... rest of the code ...
bbb4496a99a5c65218b12c56de01c12ab83a1056
demo/recent_questions.py
demo/recent_questions.py
from __future__ import print_function # Same directory hack import sys sys.path.append('.') sys.path.append('..') try: get_input = raw_input except NameError: get_input = input user_api_key = get_input("Please enter an API key if you have one (Return for none):") if not user_api_key: user_api_key = None import stackexchange, thread so = stackexchange.Site(stackexchange.StackOverflow, app_key=user_api_key, impose_throttling=True) so.be_inclusive() sys.stdout.write('Loading...') sys.stdout.flush() questions = so.recent_questions(pagesize=10, filter='_b') print('\r # vote ans view') cur = 1 for question in questions: print('%2d %3d %3d %3d \t%s' % (cur, question.score, len(question.answers), question.view_count, question.title)) cur += 1 num = int(get_input('Question no.: ')) qu = questions[num - 1] print('--- %s' % qu.title) print('%d votes, %d answers, %d views.' % (qu.score, len(qu.answers), qu.view_count)) print('Tagged: ' + ', '.join(qu.tags)) print() print(qu.body[:250] + ('...' if len(qu.body) > 250 else ''))
from __future__ import print_function from six.moves import input # Same directory hack import sys sys.path.append('.') sys.path.append('..') user_api_key = input("Please enter an API key if you have one (Return for none):") if not user_api_key: user_api_key = None import stackexchange, thread so = stackexchange.Site(stackexchange.StackOverflow, app_key=user_api_key, impose_throttling=True) so.be_inclusive() sys.stdout.write('Loading...') sys.stdout.flush() questions = so.recent_questions(pagesize=10, filter='_b') print('\r # vote ans view') cur = 1 for question in questions: print('%2d %3d %3d %3d \t%s' % (cur, question.score, len(question.answers), question.view_count, question.title)) cur += 1 num = int(get_input('Question no.: ')) qu = questions[num - 1] print('--- %s' % qu.title) print('%d votes, %d answers, %d views.' % (qu.score, len(qu.answers), qu.view_count)) print('Tagged: ' + ', '.join(qu.tags)) print() print(qu.body[:250] + ('...' if len(qu.body) > 250 else ''))
Use six function for input() in recent questions demo
Use six function for input() in recent questions demo
Python
bsd-3-clause
Khilo84/Py-StackExchange,lucjon/Py-StackExchange,damanjitsingh/StackExchange-python-
from __future__ import print_function + from six.moves import input # Same directory hack import sys sys.path.append('.') sys.path.append('..') - try: - get_input = raw_input - except NameError: - get_input = input - - user_api_key = get_input("Please enter an API key if you have one (Return for none):") + user_api_key = input("Please enter an API key if you have one (Return for none):") if not user_api_key: user_api_key = None import stackexchange, thread so = stackexchange.Site(stackexchange.StackOverflow, app_key=user_api_key, impose_throttling=True) so.be_inclusive() sys.stdout.write('Loading...') sys.stdout.flush() questions = so.recent_questions(pagesize=10, filter='_b') print('\r # vote ans view') cur = 1 for question in questions: print('%2d %3d %3d %3d \t%s' % (cur, question.score, len(question.answers), question.view_count, question.title)) cur += 1 num = int(get_input('Question no.: ')) qu = questions[num - 1] print('--- %s' % qu.title) print('%d votes, %d answers, %d views.' % (qu.score, len(qu.answers), qu.view_count)) print('Tagged: ' + ', '.join(qu.tags)) print() print(qu.body[:250] + ('...' if len(qu.body) > 250 else ''))
Use six function for input() in recent questions demo
## Code Before: from __future__ import print_function # Same directory hack import sys sys.path.append('.') sys.path.append('..') try: get_input = raw_input except NameError: get_input = input user_api_key = get_input("Please enter an API key if you have one (Return for none):") if not user_api_key: user_api_key = None import stackexchange, thread so = stackexchange.Site(stackexchange.StackOverflow, app_key=user_api_key, impose_throttling=True) so.be_inclusive() sys.stdout.write('Loading...') sys.stdout.flush() questions = so.recent_questions(pagesize=10, filter='_b') print('\r # vote ans view') cur = 1 for question in questions: print('%2d %3d %3d %3d \t%s' % (cur, question.score, len(question.answers), question.view_count, question.title)) cur += 1 num = int(get_input('Question no.: ')) qu = questions[num - 1] print('--- %s' % qu.title) print('%d votes, %d answers, %d views.' % (qu.score, len(qu.answers), qu.view_count)) print('Tagged: ' + ', '.join(qu.tags)) print() print(qu.body[:250] + ('...' if len(qu.body) > 250 else '')) ## Instruction: Use six function for input() in recent questions demo ## Code After: from __future__ import print_function from six.moves import input # Same directory hack import sys sys.path.append('.') sys.path.append('..') user_api_key = input("Please enter an API key if you have one (Return for none):") if not user_api_key: user_api_key = None import stackexchange, thread so = stackexchange.Site(stackexchange.StackOverflow, app_key=user_api_key, impose_throttling=True) so.be_inclusive() sys.stdout.write('Loading...') sys.stdout.flush() questions = so.recent_questions(pagesize=10, filter='_b') print('\r # vote ans view') cur = 1 for question in questions: print('%2d %3d %3d %3d \t%s' % (cur, question.score, len(question.answers), question.view_count, question.title)) cur += 1 num = int(get_input('Question no.: ')) qu = questions[num - 1] print('--- %s' % qu.title) print('%d votes, %d answers, %d views.' % (qu.score, len(qu.answers), qu.view_count)) print('Tagged: ' + ', '.join(qu.tags)) print() print(qu.body[:250] + ('...' if len(qu.body) > 250 else ''))
# ... existing code ... from __future__ import print_function from six.moves import input # ... modified code ... user_api_key = input("Please enter an API key if you have one (Return for none):") if not user_api_key: user_api_key = None # ... rest of the code ...
899882be398f8a31e706a590c0a7e297c1589c25
threat_intel/util/error_messages.py
threat_intel/util/error_messages.py
import sys from traceback import extract_tb from traceback import format_list def write_exception(e): exc_type, __, exc_traceback = sys.exc_info() sys.stderr.write('[ERROR] {0} {1}\n'.format(exc_type.__name__, e.message if e.message else '')) for line in format_list(extract_tb(exc_traceback)): sys.stderr.write(line) def write_error_message(message): sys.stderr.write('[ERROR] ') sys.stderr.write(message) sys.stderr.write('\n')
import sys from traceback import extract_tb from traceback import format_list def write_exception(e): exc_type, __, exc_traceback = sys.exc_info() sys.stderr.write('[ERROR] {0} {1}\n'.format(exc_type.__name__, str(e))) for line in format_list(extract_tb(exc_traceback)): sys.stderr.write(line) def write_error_message(message): sys.stderr.write('[ERROR] ') sys.stderr.write(message) sys.stderr.write('\n')
Fix deprecation warning interfering with tests
Fix deprecation warning interfering with tests
Python
mit
Yelp/threat_intel,megancarney/threat_intel,SYNchroACK/threat_intel
import sys from traceback import extract_tb from traceback import format_list def write_exception(e): exc_type, __, exc_traceback = sys.exc_info() - sys.stderr.write('[ERROR] {0} {1}\n'.format(exc_type.__name__, e.message if e.message else '')) + sys.stderr.write('[ERROR] {0} {1}\n'.format(exc_type.__name__, str(e))) for line in format_list(extract_tb(exc_traceback)): sys.stderr.write(line) def write_error_message(message): sys.stderr.write('[ERROR] ') sys.stderr.write(message) sys.stderr.write('\n')
Fix deprecation warning interfering with tests
## Code Before: import sys from traceback import extract_tb from traceback import format_list def write_exception(e): exc_type, __, exc_traceback = sys.exc_info() sys.stderr.write('[ERROR] {0} {1}\n'.format(exc_type.__name__, e.message if e.message else '')) for line in format_list(extract_tb(exc_traceback)): sys.stderr.write(line) def write_error_message(message): sys.stderr.write('[ERROR] ') sys.stderr.write(message) sys.stderr.write('\n') ## Instruction: Fix deprecation warning interfering with tests ## Code After: import sys from traceback import extract_tb from traceback import format_list def write_exception(e): exc_type, __, exc_traceback = sys.exc_info() sys.stderr.write('[ERROR] {0} {1}\n'.format(exc_type.__name__, str(e))) for line in format_list(extract_tb(exc_traceback)): sys.stderr.write(line) def write_error_message(message): sys.stderr.write('[ERROR] ') sys.stderr.write(message) sys.stderr.write('\n')
# ... existing code ... exc_type, __, exc_traceback = sys.exc_info() sys.stderr.write('[ERROR] {0} {1}\n'.format(exc_type.__name__, str(e))) for line in format_list(extract_tb(exc_traceback)): # ... rest of the code ...
97535245f7da3d7e54d64dc384d6cd81caa9a689
tests/test_story.py
tests/test_story.py
from py101 import Story from py101 import variables from py101 import lists import unittest class TestStory(unittest.TestCase): def test_name(self): self.assertEqual(Story().name, 'py101', "name should be py101") class TestAdventureVariables(unittest.TestCase): good_solution = """ myinteger = 4 mystring = 'Python String Here' print(myinteger) print(mystring) """ def test_solution(self): test = variables.TestOutput(self.good_solution) test.setUp() try: test.runTest() finally: test.tearDown() class TestAdventureLists(unittest.TestCase): good_solution = """ languages = ["ADA", "Pascal", "Fortran", "Smalltalk"] print(languages) """ def test_solution(self): test = lists.TestOutput(self.good_solution) test.setUp() try: test.runTest() finally: test.tearDown()
import py101 import py101.boilerplate import py101.introduction import py101.lists import py101.variables import unittest class TestStory(unittest.TestCase): def test_name(self): self.assertEqual(py101.Story().name, 'py101', "name should be py101") class AdventureData(object): def __init__(self, test_module, good_solution): self.module = test_module self.good_solution = good_solution class TestAdventures(unittest.TestCase): adventures = [ AdventureData( py101.boilerplate, "" ), AdventureData( py101.introduction, """print('Hello World')""" ), AdventureData( py101.variables, """myinteger = 4; mystring = 'Python String Here'; print(myinteger); print(mystring)""" ), AdventureData( py101.lists, """languages = ["ADA", "Pascal", "Fortran", "Smalltalk"]; print(languages)""" ) ] def test_solution(self): for adventure in self.adventures: with self.subTest(adventure=adventure.module.__name__): test = adventure.module.TestOutput(adventure.good_solution) test.setUp() try: test.runTest() finally: test.tearDown()
Refactor tests to remove duplicate code
Refactor tests to remove duplicate code
Python
mit
sophilabs/py101
- from py101 import Story - from py101 import variables - from py101 import lists + import py101 + import py101.boilerplate + import py101.introduction + import py101.lists + import py101.variables import unittest class TestStory(unittest.TestCase): def test_name(self): - self.assertEqual(Story().name, 'py101', "name should be py101") + self.assertEqual(py101.Story().name, 'py101', "name should be py101") + class AdventureData(object): + def __init__(self, test_module, good_solution): + self.module = test_module + self.good_solution = good_solution + + - class TestAdventureVariables(unittest.TestCase): + class TestAdventures(unittest.TestCase): - good_solution = """ - myinteger = 4 - mystring = 'Python String Here' - print(myinteger) - print(mystring) - """ + adventures = [ + AdventureData( + py101.boilerplate, + "" + ), + AdventureData( + py101.introduction, + """print('Hello World')""" + ), + AdventureData( + py101.variables, + """myinteger = 4; mystring = 'Python String Here'; print(myinteger); print(mystring)""" + ), + AdventureData( + py101.lists, + """languages = ["ADA", "Pascal", "Fortran", "Smalltalk"]; print(languages)""" + ) + ] def test_solution(self): - test = variables.TestOutput(self.good_solution) + for adventure in self.adventures: + with self.subTest(adventure=adventure.module.__name__): + test = adventure.module.TestOutput(adventure.good_solution) - test.setUp() + test.setUp() - try: + try: - test.runTest() + test.runTest() - finally: + finally: - test.tearDown() + test.tearDown() - - class TestAdventureLists(unittest.TestCase): - good_solution = """ - languages = ["ADA", "Pascal", "Fortran", "Smalltalk"] - print(languages) - """ - - def test_solution(self): - test = lists.TestOutput(self.good_solution) - test.setUp() - try: - test.runTest() - finally: - test.tearDown() - -
Refactor tests to remove duplicate code
## Code Before: from py101 import Story from py101 import variables from py101 import lists import unittest class TestStory(unittest.TestCase): def test_name(self): self.assertEqual(Story().name, 'py101', "name should be py101") class TestAdventureVariables(unittest.TestCase): good_solution = """ myinteger = 4 mystring = 'Python String Here' print(myinteger) print(mystring) """ def test_solution(self): test = variables.TestOutput(self.good_solution) test.setUp() try: test.runTest() finally: test.tearDown() class TestAdventureLists(unittest.TestCase): good_solution = """ languages = ["ADA", "Pascal", "Fortran", "Smalltalk"] print(languages) """ def test_solution(self): test = lists.TestOutput(self.good_solution) test.setUp() try: test.runTest() finally: test.tearDown() ## Instruction: Refactor tests to remove duplicate code ## Code After: import py101 import py101.boilerplate import py101.introduction import py101.lists import py101.variables import unittest class TestStory(unittest.TestCase): def test_name(self): self.assertEqual(py101.Story().name, 'py101', "name should be py101") class AdventureData(object): def __init__(self, test_module, good_solution): self.module = test_module self.good_solution = good_solution class TestAdventures(unittest.TestCase): adventures = [ AdventureData( py101.boilerplate, "" ), AdventureData( py101.introduction, """print('Hello World')""" ), AdventureData( py101.variables, """myinteger = 4; mystring = 'Python String Here'; print(myinteger); print(mystring)""" ), AdventureData( py101.lists, """languages = ["ADA", "Pascal", "Fortran", "Smalltalk"]; print(languages)""" ) ] def test_solution(self): for adventure in self.adventures: with self.subTest(adventure=adventure.module.__name__): test = adventure.module.TestOutput(adventure.good_solution) test.setUp() try: test.runTest() finally: test.tearDown()
... import py101 import py101.boilerplate import py101.introduction import py101.lists import py101.variables import unittest ... def test_name(self): self.assertEqual(py101.Story().name, 'py101', "name should be py101") ... class AdventureData(object): def __init__(self, test_module, good_solution): self.module = test_module self.good_solution = good_solution class TestAdventures(unittest.TestCase): adventures = [ AdventureData( py101.boilerplate, "" ), AdventureData( py101.introduction, """print('Hello World')""" ), AdventureData( py101.variables, """myinteger = 4; mystring = 'Python String Here'; print(myinteger); print(mystring)""" ), AdventureData( py101.lists, """languages = ["ADA", "Pascal", "Fortran", "Smalltalk"]; print(languages)""" ) ] ... def test_solution(self): for adventure in self.adventures: with self.subTest(adventure=adventure.module.__name__): test = adventure.module.TestOutput(adventure.good_solution) test.setUp() try: test.runTest() finally: test.tearDown() ...
c416c998d73e27713fd57ec97c70bacb2390f8c9
DashDoc.py
DashDoc.py
import sublime import sublime_plugin import os import subprocess def syntax_name(view): syntax = os.path.basename(view.settings().get('syntax')) syntax = os.path.splitext(syntax)[0] return syntax def docset_prefix(view, settings): syntax_docset_map = settings.get('syntax_docset_map', {}) syntax = syntax_name(view) if syntax in syntax_docset_map: return syntax_docset_map[syntax] + ':' return None class DashDocCommand(sublime_plugin.TextCommand): def run(self, edit, syntax_sensitive=False): selection = self.view.sel()[0] if len(selection) == 0: selection = self.view.word(selection) word = self.view.substr(selection) settings = sublime.load_settings('DashDoc.sublime-settings') if syntax_sensitive or settings.get('syntax_sensitive', False): docset = docset_prefix(self.view, settings) else: docset = None subprocess.call(["open", "dash://%s%s" % (docset or '', word)])
import sublime import sublime_plugin import os import subprocess def syntax_name(view): syntax = os.path.basename(view.settings().get('syntax')) syntax = os.path.splitext(syntax)[0] return syntax def camel_case(word): return ''.join(w.capitalize() if i > 0 else w for i, w in enumerate(word.split())) def docset_prefix(view, settings): syntax_docset_map = settings.get('syntax_docset_map', {}) syntax = syntax_name(view) if syntax in syntax_docset_map: return syntax_docset_map[syntax] + ':' return None class DashDocCommand(sublime_plugin.TextCommand): def run(self, edit, syntax_sensitive=False): selection = self.view.sel()[0] if len(selection) == 0: selection = self.view.word(selection) word = self.view.substr(selection) settings = sublime.load_settings('DashDoc.sublime-settings') if syntax_sensitive or settings.get('syntax_sensitive', False): docset = docset_prefix(self.view, settings) else: docset = None subprocess.call(["open", "dash://%s%s" % (docset or '', camel_case(word))])
Use Dash's new CamelCase convention to lookup words that contain whitespace
Use Dash's new CamelCase convention to lookup words that contain whitespace - Example: converting "create table" into "createTable" will lookup "CREATE TABLE"
Python
apache-2.0
farcaller/DashDoc
import sublime import sublime_plugin import os import subprocess def syntax_name(view): syntax = os.path.basename(view.settings().get('syntax')) syntax = os.path.splitext(syntax)[0] return syntax + + + def camel_case(word): + return ''.join(w.capitalize() if i > 0 else w + for i, w in enumerate(word.split())) def docset_prefix(view, settings): syntax_docset_map = settings.get('syntax_docset_map', {}) syntax = syntax_name(view) if syntax in syntax_docset_map: return syntax_docset_map[syntax] + ':' return None class DashDocCommand(sublime_plugin.TextCommand): def run(self, edit, syntax_sensitive=False): selection = self.view.sel()[0] if len(selection) == 0: selection = self.view.word(selection) word = self.view.substr(selection) settings = sublime.load_settings('DashDoc.sublime-settings') if syntax_sensitive or settings.get('syntax_sensitive', False): docset = docset_prefix(self.view, settings) else: docset = None - subprocess.call(["open", "dash://%s%s" % (docset or '', word)]) + subprocess.call(["open", "dash://%s%s" % (docset or '', camel_case(word))])
Use Dash's new CamelCase convention to lookup words that contain whitespace
## Code Before: import sublime import sublime_plugin import os import subprocess def syntax_name(view): syntax = os.path.basename(view.settings().get('syntax')) syntax = os.path.splitext(syntax)[0] return syntax def docset_prefix(view, settings): syntax_docset_map = settings.get('syntax_docset_map', {}) syntax = syntax_name(view) if syntax in syntax_docset_map: return syntax_docset_map[syntax] + ':' return None class DashDocCommand(sublime_plugin.TextCommand): def run(self, edit, syntax_sensitive=False): selection = self.view.sel()[0] if len(selection) == 0: selection = self.view.word(selection) word = self.view.substr(selection) settings = sublime.load_settings('DashDoc.sublime-settings') if syntax_sensitive or settings.get('syntax_sensitive', False): docset = docset_prefix(self.view, settings) else: docset = None subprocess.call(["open", "dash://%s%s" % (docset or '', word)]) ## Instruction: Use Dash's new CamelCase convention to lookup words that contain whitespace ## Code After: import sublime import sublime_plugin import os import subprocess def syntax_name(view): syntax = os.path.basename(view.settings().get('syntax')) syntax = os.path.splitext(syntax)[0] return syntax def camel_case(word): return ''.join(w.capitalize() if i > 0 else w for i, w in enumerate(word.split())) def docset_prefix(view, settings): syntax_docset_map = settings.get('syntax_docset_map', {}) syntax = syntax_name(view) if syntax in syntax_docset_map: return syntax_docset_map[syntax] + ':' return None class DashDocCommand(sublime_plugin.TextCommand): def run(self, edit, syntax_sensitive=False): selection = self.view.sel()[0] if len(selection) == 0: selection = self.view.word(selection) word = self.view.substr(selection) settings = sublime.load_settings('DashDoc.sublime-settings') if syntax_sensitive or settings.get('syntax_sensitive', False): docset = docset_prefix(self.view, settings) else: docset = None subprocess.call(["open", "dash://%s%s" % (docset or '', camel_case(word))])
... return syntax def camel_case(word): return ''.join(w.capitalize() if i > 0 else w for i, w in enumerate(word.split())) ... subprocess.call(["open", "dash://%s%s" % (docset or '', camel_case(word))]) ...
f3eb94bbe10160a4337c5eb9241166f60b9724a8
pyvideo/settings.py
pyvideo/settings.py
from richard.settings import * ALLOWED_HOSTS = ['pyvideo.ru'] TIME_ZONE = 'Europe/Moscow' LANGUAGE_CODE = 'ru' SECRET_KEY = 'this_is_not_production_so_who_cares' ROOT_URLCONF = 'pyvideo.urls' WSGI_APPLICATION = 'pyvideo.wsgi.application' TEMPLATE_DIRS = ( os.path.join(ROOT, 'templates'), ) INSTALLED_APPS = INSTALLED_APPS + ( 'raven.contrib.django.raven_compat', )
from richard.settings import * ALLOWED_HOSTS = ['pyvideo.ru', 'pyvideoru.herokuapp.com'] TIME_ZONE = 'Europe/Moscow' LANGUAGE_CODE = 'ru' SECRET_KEY = 'this_is_not_production_so_who_cares' ROOT_URLCONF = 'pyvideo.urls' WSGI_APPLICATION = 'pyvideo.wsgi.application' TEMPLATE_DIRS = ( os.path.join(ROOT, 'templates'), ) INSTALLED_APPS = INSTALLED_APPS + ( 'raven.contrib.django.raven_compat', )
Add heroku host to ALLOWED_HOSTS
Add heroku host to ALLOWED_HOSTS
Python
bsd-3-clause
WarmongeR1/pyvideo.ru,WarmongeR1/pyvideo.ru,WarmongeR1/pyvideo.ru,coagulant/pyvideo.ru,coagulant/pyvideo.ru,coagulant/pyvideo.ru
from richard.settings import * - ALLOWED_HOSTS = ['pyvideo.ru'] + ALLOWED_HOSTS = ['pyvideo.ru', 'pyvideoru.herokuapp.com'] TIME_ZONE = 'Europe/Moscow' LANGUAGE_CODE = 'ru' SECRET_KEY = 'this_is_not_production_so_who_cares' ROOT_URLCONF = 'pyvideo.urls' WSGI_APPLICATION = 'pyvideo.wsgi.application' TEMPLATE_DIRS = ( os.path.join(ROOT, 'templates'), ) INSTALLED_APPS = INSTALLED_APPS + ( 'raven.contrib.django.raven_compat', )
Add heroku host to ALLOWED_HOSTS
## Code Before: from richard.settings import * ALLOWED_HOSTS = ['pyvideo.ru'] TIME_ZONE = 'Europe/Moscow' LANGUAGE_CODE = 'ru' SECRET_KEY = 'this_is_not_production_so_who_cares' ROOT_URLCONF = 'pyvideo.urls' WSGI_APPLICATION = 'pyvideo.wsgi.application' TEMPLATE_DIRS = ( os.path.join(ROOT, 'templates'), ) INSTALLED_APPS = INSTALLED_APPS + ( 'raven.contrib.django.raven_compat', ) ## Instruction: Add heroku host to ALLOWED_HOSTS ## Code After: from richard.settings import * ALLOWED_HOSTS = ['pyvideo.ru', 'pyvideoru.herokuapp.com'] TIME_ZONE = 'Europe/Moscow' LANGUAGE_CODE = 'ru' SECRET_KEY = 'this_is_not_production_so_who_cares' ROOT_URLCONF = 'pyvideo.urls' WSGI_APPLICATION = 'pyvideo.wsgi.application' TEMPLATE_DIRS = ( os.path.join(ROOT, 'templates'), ) INSTALLED_APPS = INSTALLED_APPS + ( 'raven.contrib.django.raven_compat', )
// ... existing code ... ALLOWED_HOSTS = ['pyvideo.ru', 'pyvideoru.herokuapp.com'] TIME_ZONE = 'Europe/Moscow' // ... rest of the code ...
663a61362c30b737f2532de42b5b680795ccf608
quran_text/models.py
quran_text/models.py
from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ from django.db import models class Sura(models.Model): """ Model to hold the Quran Chapters "Sura" """ index = models.PositiveIntegerField(primary_key=True) name = models.CharField(max_length=20, unique=True, verbose_name=_('Sura')) def __str__(self): return self.name class Meta: ordering = ['index'] class Ayah(models.Model): """ Model to hold chapters' text ot Verse "Ayat" """ number = models.PositiveIntegerField(verbose_name=_('Number')) sura = models.ForeignKey(Sura, related_name='ayat') text = models.TextField() def __str__(self): return '{} - {}'.format(self.sura.index, self.number) class Meta: unique_together = ['number', 'sura']
from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ from django.db import models class Sura(models.Model): """ Model to hold the Quran Chapters "Sura" """ index = models.PositiveIntegerField(primary_key=True) name = models.CharField(max_length=20, unique=True, verbose_name=_('Sura')) def __str__(self): return self.name class Meta: ordering = ['index'] class Ayah(models.Model): """ Model to hold chapters' text ot Verse "Ayat" """ number = models.PositiveIntegerField(verbose_name=_('Number')) sura = models.ForeignKey(Sura, related_name='ayat') text = models.TextField() def __str__(self): return '{} - {}'.format(self.sura.index, self.number) class Meta: unique_together = ['number', 'sura'] ordering = ['sura', 'number']
Add ordering to Ayah model
Add ordering to Ayah model
Python
mit
EmadMokhtar/tafseer_api
from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ from django.db import models class Sura(models.Model): """ Model to hold the Quran Chapters "Sura" """ index = models.PositiveIntegerField(primary_key=True) name = models.CharField(max_length=20, unique=True, verbose_name=_('Sura')) def __str__(self): return self.name class Meta: ordering = ['index'] class Ayah(models.Model): """ Model to hold chapters' text ot Verse "Ayat" """ number = models.PositiveIntegerField(verbose_name=_('Number')) sura = models.ForeignKey(Sura, related_name='ayat') text = models.TextField() def __str__(self): return '{} - {}'.format(self.sura.index, self.number) class Meta: unique_together = ['number', 'sura'] + ordering = ['sura', 'number']
Add ordering to Ayah model
## Code Before: from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ from django.db import models class Sura(models.Model): """ Model to hold the Quran Chapters "Sura" """ index = models.PositiveIntegerField(primary_key=True) name = models.CharField(max_length=20, unique=True, verbose_name=_('Sura')) def __str__(self): return self.name class Meta: ordering = ['index'] class Ayah(models.Model): """ Model to hold chapters' text ot Verse "Ayat" """ number = models.PositiveIntegerField(verbose_name=_('Number')) sura = models.ForeignKey(Sura, related_name='ayat') text = models.TextField() def __str__(self): return '{} - {}'.format(self.sura.index, self.number) class Meta: unique_together = ['number', 'sura'] ## Instruction: Add ordering to Ayah model ## Code After: from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ from django.db import models class Sura(models.Model): """ Model to hold the Quran Chapters "Sura" """ index = models.PositiveIntegerField(primary_key=True) name = models.CharField(max_length=20, unique=True, verbose_name=_('Sura')) def __str__(self): return self.name class Meta: ordering = ['index'] class Ayah(models.Model): """ Model to hold chapters' text ot Verse "Ayat" """ number = models.PositiveIntegerField(verbose_name=_('Number')) sura = models.ForeignKey(Sura, related_name='ayat') text = models.TextField() def __str__(self): return '{} - {}'.format(self.sura.index, self.number) class Meta: unique_together = ['number', 'sura'] ordering = ['sura', 'number']
... unique_together = ['number', 'sura'] ordering = ['sura', 'number'] ...
01f43d80fd4324f596904e22409c0b76bcb1b015
totalsum/templatetags/totalsum.py
totalsum/templatetags/totalsum.py
from django.template import Library, loader, Context from django.contrib.admin.templatetags.admin_list import result_headers, result_hidden_fields, results, admin_actions register = Library() admin_actions = admin_actions @register.simple_tag(takes_context=True) def totalsum_result_list(context, cl, totals, unit_of_measure, template_name="totalsum_change_list_results.html"): pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page headers = list(result_headers(cl)) num_sorted_fields = 0 for h in headers: if h['sortable'] and h['sorted']: num_sorted_fields += 1 c = { 'cl': cl, 'totals': totals, 'unit_of_measure': unit_of_measure, 'result_hidden_fields': list(result_hidden_fields(cl)), 'result_headers': headers, 'num_sorted_fields': num_sorted_fields, 'results': list(results(cl)), 'pagination_required': pagination_required } t = loader.get_template(template_name) return t.render(Context(c)) @register.filter def get_total(totals, column): if column in totals.keys(): return totals[column] return ''
from django.template import Library, loader from django.contrib.admin.templatetags.admin_list import result_headers, result_hidden_fields, results, admin_actions register = Library() admin_actions = admin_actions @register.simple_tag(takes_context=True) def totalsum_result_list(context, cl, totals, unit_of_measure, template_name="totalsum_change_list_results.html"): pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page headers = list(result_headers(cl)) num_sorted_fields = 0 for h in headers: if h['sortable'] and h['sorted']: num_sorted_fields += 1 c = { 'cl': cl, 'totals': totals, 'unit_of_measure': unit_of_measure, 'result_hidden_fields': list(result_hidden_fields(cl)), 'result_headers': headers, 'num_sorted_fields': num_sorted_fields, 'results': list(results(cl)), 'pagination_required': pagination_required } t = loader.get_template(template_name) return t.render(c) @register.filter def get_total(totals, column): if column in totals.keys(): return totals[column] return ''
Update for Django version 1.11
Update for Django version 1.11
Python
mit
20tab/twentytab-totalsum-admin,20tab/twentytab-totalsum-admin
- from django.template import Library, loader, Context + from django.template import Library, loader from django.contrib.admin.templatetags.admin_list import result_headers, result_hidden_fields, results, admin_actions register = Library() admin_actions = admin_actions @register.simple_tag(takes_context=True) def totalsum_result_list(context, cl, totals, unit_of_measure, template_name="totalsum_change_list_results.html"): pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page headers = list(result_headers(cl)) num_sorted_fields = 0 for h in headers: if h['sortable'] and h['sorted']: num_sorted_fields += 1 c = { 'cl': cl, 'totals': totals, 'unit_of_measure': unit_of_measure, 'result_hidden_fields': list(result_hidden_fields(cl)), 'result_headers': headers, 'num_sorted_fields': num_sorted_fields, 'results': list(results(cl)), 'pagination_required': pagination_required } t = loader.get_template(template_name) - return t.render(Context(c)) + return t.render(c) @register.filter def get_total(totals, column): if column in totals.keys(): return totals[column] return ''
Update for Django version 1.11
## Code Before: from django.template import Library, loader, Context from django.contrib.admin.templatetags.admin_list import result_headers, result_hidden_fields, results, admin_actions register = Library() admin_actions = admin_actions @register.simple_tag(takes_context=True) def totalsum_result_list(context, cl, totals, unit_of_measure, template_name="totalsum_change_list_results.html"): pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page headers = list(result_headers(cl)) num_sorted_fields = 0 for h in headers: if h['sortable'] and h['sorted']: num_sorted_fields += 1 c = { 'cl': cl, 'totals': totals, 'unit_of_measure': unit_of_measure, 'result_hidden_fields': list(result_hidden_fields(cl)), 'result_headers': headers, 'num_sorted_fields': num_sorted_fields, 'results': list(results(cl)), 'pagination_required': pagination_required } t = loader.get_template(template_name) return t.render(Context(c)) @register.filter def get_total(totals, column): if column in totals.keys(): return totals[column] return '' ## Instruction: Update for Django version 1.11 ## Code After: from django.template import Library, loader from django.contrib.admin.templatetags.admin_list import result_headers, result_hidden_fields, results, admin_actions register = Library() admin_actions = admin_actions @register.simple_tag(takes_context=True) def totalsum_result_list(context, cl, totals, unit_of_measure, template_name="totalsum_change_list_results.html"): pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page headers = list(result_headers(cl)) num_sorted_fields = 0 for h in headers: if h['sortable'] and h['sorted']: num_sorted_fields += 1 c = { 'cl': cl, 'totals': totals, 'unit_of_measure': unit_of_measure, 'result_hidden_fields': list(result_hidden_fields(cl)), 'result_headers': headers, 'num_sorted_fields': num_sorted_fields, 'results': list(results(cl)), 'pagination_required': pagination_required } t = loader.get_template(template_name) return t.render(c) @register.filter def get_total(totals, column): if column in totals.keys(): return totals[column] return ''
... from django.template import Library, loader from django.contrib.admin.templatetags.admin_list import result_headers, result_hidden_fields, results, admin_actions ... t = loader.get_template(template_name) return t.render(c) ...
49a371728a2e9167494264e0c07c6dd90abec0ff
saleor/core/views.py
saleor/core/views.py
from django.template.response import TemplateResponse from ..product.utils import products_with_availability, products_with_details def home(request): products = Product.objects.get_available_products()[:6] products = products.prefetch_related('categories', 'images', 'variants__stock') return TemplateResponse( request, 'home.html', {'products': products, 'parent': None})
from django.template.response import TemplateResponse from ..product.utils import products_with_availability, products_with_details def home(request): products = products_with_details(request.user)[:6] products = products_with_availability( products, discounts=request.discounts, local_currency=request.currency) return TemplateResponse( request, 'home.html', {'products': products, 'parent': None})
Fix homepage after wrong rebase
Fix homepage after wrong rebase
Python
bsd-3-clause
jreigel/saleor,car3oon/saleor,HyperManTT/ECommerceSaleor,tfroehlich82/saleor,HyperManTT/ECommerceSaleor,UITools/saleor,mociepka/saleor,car3oon/saleor,KenMutemi/saleor,jreigel/saleor,UITools/saleor,UITools/saleor,mociepka/saleor,maferelo/saleor,itbabu/saleor,UITools/saleor,KenMutemi/saleor,mociepka/saleor,itbabu/saleor,maferelo/saleor,tfroehlich82/saleor,HyperManTT/ECommerceSaleor,jreigel/saleor,itbabu/saleor,tfroehlich82/saleor,UITools/saleor,KenMutemi/saleor,car3oon/saleor,maferelo/saleor
from django.template.response import TemplateResponse from ..product.utils import products_with_availability, products_with_details def home(request): - products = Product.objects.get_available_products()[:6] - products = products.prefetch_related('categories', 'images', - 'variants__stock') + products = products_with_details(request.user)[:6] + products = products_with_availability( + products, discounts=request.discounts, local_currency=request.currency) return TemplateResponse( request, 'home.html', {'products': products, 'parent': None})
Fix homepage after wrong rebase
## Code Before: from django.template.response import TemplateResponse from ..product.utils import products_with_availability, products_with_details def home(request): products = Product.objects.get_available_products()[:6] products = products.prefetch_related('categories', 'images', 'variants__stock') return TemplateResponse( request, 'home.html', {'products': products, 'parent': None}) ## Instruction: Fix homepage after wrong rebase ## Code After: from django.template.response import TemplateResponse from ..product.utils import products_with_availability, products_with_details def home(request): products = products_with_details(request.user)[:6] products = products_with_availability( products, discounts=request.discounts, local_currency=request.currency) return TemplateResponse( request, 'home.html', {'products': products, 'parent': None})
# ... existing code ... def home(request): products = products_with_details(request.user)[:6] products = products_with_availability( products, discounts=request.discounts, local_currency=request.currency) return TemplateResponse( # ... rest of the code ...
ac209811feb25dfe9b5eac8b1488b42a8b5d73ba
kitsune/kbadge/migrations/0002_auto_20181023_1319.py
kitsune/kbadge/migrations/0002_auto_20181023_1319.py
from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('kbadge', '0001_initial'), ] operations = [ migrations.RunSQL( "UPDATE badger_badge SET image = CONCAT('uploads/', image) WHERE image NOT LIKE 'uploads/%'" ) ]
from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('kbadge', '0001_initial'), ] operations = [ migrations.RunSQL( "UPDATE badger_badge SET image = CONCAT('uploads/', image) WHERE image NOT LIKE 'uploads/%' AND image IS NOT NULL AND image != ''" ) ]
Update SQL data migration to exclude NULL and blank image values.
Update SQL data migration to exclude NULL and blank image values.
Python
bsd-3-clause
mozilla/kitsune,anushbmx/kitsune,anushbmx/kitsune,mozilla/kitsune,mozilla/kitsune,anushbmx/kitsune,anushbmx/kitsune,mozilla/kitsune
from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('kbadge', '0001_initial'), ] operations = [ migrations.RunSQL( - "UPDATE badger_badge SET image = CONCAT('uploads/', image) WHERE image NOT LIKE 'uploads/%'" + "UPDATE badger_badge SET image = CONCAT('uploads/', image) WHERE image NOT LIKE 'uploads/%' AND image IS NOT NULL AND image != ''" ) ]
Update SQL data migration to exclude NULL and blank image values.
## Code Before: from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('kbadge', '0001_initial'), ] operations = [ migrations.RunSQL( "UPDATE badger_badge SET image = CONCAT('uploads/', image) WHERE image NOT LIKE 'uploads/%'" ) ] ## Instruction: Update SQL data migration to exclude NULL and blank image values. ## Code After: from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('kbadge', '0001_initial'), ] operations = [ migrations.RunSQL( "UPDATE badger_badge SET image = CONCAT('uploads/', image) WHERE image NOT LIKE 'uploads/%' AND image IS NOT NULL AND image != ''" ) ]
// ... existing code ... migrations.RunSQL( "UPDATE badger_badge SET image = CONCAT('uploads/', image) WHERE image NOT LIKE 'uploads/%' AND image IS NOT NULL AND image != ''" ) // ... rest of the code ...
ee37119a4f77eef5c8163936d982e178c42cbc00
src/adhocracy/lib/machine_name.py
src/adhocracy/lib/machine_name.py
import platform class IncludeMachineName(object): def __init__(self, app, config): self.app = app self.config = config def __call__(self, environ, start_response): def local_response(status, headers, exc_info=None): headers.append(('X-Server-Machine', platform.node())) start_response(status, headers, exc_info) return self.app(environ, local_response)
import os import platform class IncludeMachineName(object): def __init__(self, app, config): self.app = app self.config = config def __call__(self, environ, start_response): def local_response(status, headers, exc_info=None): machine_id = '%s:%s (PID %d)' % ( platform.node(), environ.get('SERVER_PORT'), os.getpid()) headers.append(('X-Server-Machine', machine_id)) start_response(status, headers, exc_info) return self.app(environ, local_response)
Add Server Port and PID to the X-Server-Machine header
Add Server Port and PID to the X-Server-Machine header Fixes hhucn/adhocracy.hhu_theme#429
Python
agpl-3.0
liqd/adhocracy,liqd/adhocracy,DanielNeugebauer/adhocracy,DanielNeugebauer/adhocracy,alkadis/vcv,liqd/adhocracy,alkadis/vcv,phihag/adhocracy,alkadis/vcv,DanielNeugebauer/adhocracy,phihag/adhocracy,liqd/adhocracy,phihag/adhocracy,phihag/adhocracy,alkadis/vcv,phihag/adhocracy,alkadis/vcv,DanielNeugebauer/adhocracy,DanielNeugebauer/adhocracy
+ import os import platform class IncludeMachineName(object): def __init__(self, app, config): self.app = app self.config = config def __call__(self, environ, start_response): def local_response(status, headers, exc_info=None): + machine_id = '%s:%s (PID %d)' % ( + platform.node(), environ.get('SERVER_PORT'), os.getpid()) - headers.append(('X-Server-Machine', platform.node())) + headers.append(('X-Server-Machine', machine_id)) start_response(status, headers, exc_info) return self.app(environ, local_response)
Add Server Port and PID to the X-Server-Machine header
## Code Before: import platform class IncludeMachineName(object): def __init__(self, app, config): self.app = app self.config = config def __call__(self, environ, start_response): def local_response(status, headers, exc_info=None): headers.append(('X-Server-Machine', platform.node())) start_response(status, headers, exc_info) return self.app(environ, local_response) ## Instruction: Add Server Port and PID to the X-Server-Machine header ## Code After: import os import platform class IncludeMachineName(object): def __init__(self, app, config): self.app = app self.config = config def __call__(self, environ, start_response): def local_response(status, headers, exc_info=None): machine_id = '%s:%s (PID %d)' % ( platform.node(), environ.get('SERVER_PORT'), os.getpid()) headers.append(('X-Server-Machine', machine_id)) start_response(status, headers, exc_info) return self.app(environ, local_response)
... import os import platform ... def local_response(status, headers, exc_info=None): machine_id = '%s:%s (PID %d)' % ( platform.node(), environ.get('SERVER_PORT'), os.getpid()) headers.append(('X-Server-Machine', machine_id)) start_response(status, headers, exc_info) ...
4799fbb78503e16095b72e39fa243dcbaeef94b2
lib/rapidsms/tests/test_backend_irc.py
lib/rapidsms/tests/test_backend_irc.py
import unittest from harness import MockRouter class TestLog(unittest.TestCase): def test_backend_irc (self): router = MockRouter() try: import irclib from rapidsms.backends.irc import Backend backend = Backend("irc", router) backend.configure(host="localhost",nick="test",channels="#test1,#test2") self.assertEquals(type(backend), Backend, "IRC backend loads") self.assertEquals(backend.nick, "test", "IRC backend has nick set") self.assertEquals(backend.host, "localhost", "IRC backend has host set") self.assertEquals(backend.channels, ["#test1","#test2"], "IRC backend has channels correctly set") except ImportError: pass if __name__ == "__main__": unittest.main()
import unittest from harness import MockRouter class TestBackendIRC(unittest.TestCase): def test_backend_irc (self): router = MockRouter() try: import irclib from rapidsms.backends.irc import Backend backend = Backend("irc", router) backend.configure(host="localhost",nick="test",channels="#test1,#test2") self.assertEquals(type(backend), Backend, "IRC backend loads") self.assertEquals(backend.nick, "test", "IRC backend has nick set") self.assertEquals(backend.host, "localhost", "IRC backend has host set") self.assertEquals(backend.channels, ["#test1","#test2"], "IRC backend has channels correctly set") except ImportError: pass if __name__ == "__main__": unittest.main()
Rename test class (sloppy cut n' paste job)
Rename test class (sloppy cut n' paste job)
Python
bsd-3-clause
dimagi/rapidsms-core-dev,dimagi/rapidsms-core-dev,unicefuganda/edtrac,unicefuganda/edtrac,ken-muturi/rapidsms,catalpainternational/rapidsms,caktus/rapidsms,rapidsms/rapidsms-core-dev,ehealthafrica-ci/rapidsms,peterayeni/rapidsms,peterayeni/rapidsms,dimagi/rapidsms,catalpainternational/rapidsms,lsgunth/rapidsms,dimagi/rapidsms,lsgunth/rapidsms,caktus/rapidsms,caktus/rapidsms,eHealthAfrica/rapidsms,eHealthAfrica/rapidsms,lsgunth/rapidsms,peterayeni/rapidsms,ken-muturi/rapidsms,lsgunth/rapidsms,eHealthAfrica/rapidsms,rapidsms/rapidsms-core-dev,ehealthafrica-ci/rapidsms,catalpainternational/rapidsms,unicefuganda/edtrac,ehealthafrica-ci/rapidsms,catalpainternational/rapidsms,peterayeni/rapidsms,ken-muturi/rapidsms
import unittest from harness import MockRouter - class TestLog(unittest.TestCase): + class TestBackendIRC(unittest.TestCase): def test_backend_irc (self): router = MockRouter() try: import irclib from rapidsms.backends.irc import Backend backend = Backend("irc", router) backend.configure(host="localhost",nick="test",channels="#test1,#test2") self.assertEquals(type(backend), Backend, "IRC backend loads") self.assertEquals(backend.nick, "test", "IRC backend has nick set") self.assertEquals(backend.host, "localhost", "IRC backend has host set") self.assertEquals(backend.channels, ["#test1","#test2"], "IRC backend has channels correctly set") except ImportError: pass if __name__ == "__main__": unittest.main()
Rename test class (sloppy cut n' paste job)
## Code Before: import unittest from harness import MockRouter class TestLog(unittest.TestCase): def test_backend_irc (self): router = MockRouter() try: import irclib from rapidsms.backends.irc import Backend backend = Backend("irc", router) backend.configure(host="localhost",nick="test",channels="#test1,#test2") self.assertEquals(type(backend), Backend, "IRC backend loads") self.assertEquals(backend.nick, "test", "IRC backend has nick set") self.assertEquals(backend.host, "localhost", "IRC backend has host set") self.assertEquals(backend.channels, ["#test1","#test2"], "IRC backend has channels correctly set") except ImportError: pass if __name__ == "__main__": unittest.main() ## Instruction: Rename test class (sloppy cut n' paste job) ## Code After: import unittest from harness import MockRouter class TestBackendIRC(unittest.TestCase): def test_backend_irc (self): router = MockRouter() try: import irclib from rapidsms.backends.irc import Backend backend = Backend("irc", router) backend.configure(host="localhost",nick="test",channels="#test1,#test2") self.assertEquals(type(backend), Backend, "IRC backend loads") self.assertEquals(backend.nick, "test", "IRC backend has nick set") self.assertEquals(backend.host, "localhost", "IRC backend has host set") self.assertEquals(backend.channels, ["#test1","#test2"], "IRC backend has channels correctly set") except ImportError: pass if __name__ == "__main__": unittest.main()
... class TestBackendIRC(unittest.TestCase): def test_backend_irc (self): ...
c3762443859ada75687e5a62d576fe8140a42a7c
tests/test_csv2iati.py
tests/test_csv2iati.py
import pytest from web_test_base import * class TestCSV2IATI(WebTestBase): requests_to_load = { 'CSV2IATI Homepage': { 'url': 'http://csv2iati.iatistandard.org/' } } def test_contains_links(self, loaded_request): """ Test that each page contains links to the defined URLs. """ result = utility.get_links_from_page(loaded_request) assert "http://iatistandard.org" in result @pytest.mark.parametrize("target_request", ["CSV2IATI Homepage"]) def test_login_form_presence(self, target_request): """ Test that there is a valid login form on the CSV2IATI Homepage. """ req = self.loaded_request_from_test_name(target_request) form_xpath = '//*[@id="login_register_forms_container"]/fieldset[1]/form' form_action_xpath = '//*[@id="login_register_forms_container"]/fieldset[1]/form/@action' input_xpath = '//*[@id="login_register_forms_container"]/fieldset[1]/form/dl/dd/input' forms = utility.locate_xpath_result(req, form_xpath) form_action = utility.locate_xpath_result(req, form_action_xpath) form_inputs = utility.locate_xpath_result(req, input_xpath) assert len(forms) == 1 assert form_action == ['/login'] assert len(form_inputs) == 3
import pytest from web_test_base import * class TestCSV2IATI(WebTestBase): requests_to_load = { 'CSV2IATI Homepage': { 'url': 'http://csv2iati.iatistandard.org/' } }
Remove redundant csv2iati test now site has been decommissioned
Remove redundant csv2iati test now site has been decommissioned
Python
mit
IATI/IATI-Website-Tests
import pytest from web_test_base import * class TestCSV2IATI(WebTestBase): requests_to_load = { 'CSV2IATI Homepage': { 'url': 'http://csv2iati.iatistandard.org/' } } - def test_contains_links(self, loaded_request): - """ - Test that each page contains links to the defined URLs. - """ - result = utility.get_links_from_page(loaded_request) - - assert "http://iatistandard.org" in result - - @pytest.mark.parametrize("target_request", ["CSV2IATI Homepage"]) - def test_login_form_presence(self, target_request): - """ - Test that there is a valid login form on the CSV2IATI Homepage. - """ - req = self.loaded_request_from_test_name(target_request) - form_xpath = '//*[@id="login_register_forms_container"]/fieldset[1]/form' - form_action_xpath = '//*[@id="login_register_forms_container"]/fieldset[1]/form/@action' - input_xpath = '//*[@id="login_register_forms_container"]/fieldset[1]/form/dl/dd/input' - - forms = utility.locate_xpath_result(req, form_xpath) - form_action = utility.locate_xpath_result(req, form_action_xpath) - form_inputs = utility.locate_xpath_result(req, input_xpath) - - assert len(forms) == 1 - assert form_action == ['/login'] - assert len(form_inputs) == 3 -
Remove redundant csv2iati test now site has been decommissioned
## Code Before: import pytest from web_test_base import * class TestCSV2IATI(WebTestBase): requests_to_load = { 'CSV2IATI Homepage': { 'url': 'http://csv2iati.iatistandard.org/' } } def test_contains_links(self, loaded_request): """ Test that each page contains links to the defined URLs. """ result = utility.get_links_from_page(loaded_request) assert "http://iatistandard.org" in result @pytest.mark.parametrize("target_request", ["CSV2IATI Homepage"]) def test_login_form_presence(self, target_request): """ Test that there is a valid login form on the CSV2IATI Homepage. """ req = self.loaded_request_from_test_name(target_request) form_xpath = '//*[@id="login_register_forms_container"]/fieldset[1]/form' form_action_xpath = '//*[@id="login_register_forms_container"]/fieldset[1]/form/@action' input_xpath = '//*[@id="login_register_forms_container"]/fieldset[1]/form/dl/dd/input' forms = utility.locate_xpath_result(req, form_xpath) form_action = utility.locate_xpath_result(req, form_action_xpath) form_inputs = utility.locate_xpath_result(req, input_xpath) assert len(forms) == 1 assert form_action == ['/login'] assert len(form_inputs) == 3 ## Instruction: Remove redundant csv2iati test now site has been decommissioned ## Code After: import pytest from web_test_base import * class TestCSV2IATI(WebTestBase): requests_to_load = { 'CSV2IATI Homepage': { 'url': 'http://csv2iati.iatistandard.org/' } }
// ... existing code ... } // ... rest of the code ...
c0a74ce4110d295b3662066e4d08c4ab65fb0905
bills/views.py
bills/views.py
from django.shortcuts import render, redirect from bills.utils import get_all_subjects, get_all_locations from opencivicdata.models import Bill def bill_list(request): subjects = get_all_subjects() if request.POST.getlist('bill_subjects'): filter_subjects = request.POST.getlist('bill_subjects') all_bills = Bill.objects.filter(subject__in=filter_subjects) else: all_bills = Bill.objects.all() details = [] for bill in all_bills: bill_detail = {} bill_detail['title'] = bill.title bill_detail['from_organization'] = bill.from_organization.name bill_detail['actions'] = [] bill_detail['sponsorships'] = [] for action in bill.actions.all(): bill_detail['actions'].append({'description': action.description, 'date': action.date}) for sponsorship in bill.sponsorships.all(): bill_detail['sponsorships'].append({ 'sponsor': sponsorship.name, 'id': sponsorship.id, 'primary': sponsorship.primary }) details.append(bill_detail) if request.method == 'POST': with transaction.atomic(): filter_subjects = request.POST.getlist('bill_subjects') return redirect('.') return render( request, 'bills/all.html', {'bills': details, 'subjects': subjects} )
from django.db import transaction from django.shortcuts import render, redirect from preferences.views import _mark_selected from bills.utils import get_all_subjects, get_all_locations from opencivicdata.models import Bill def bill_list(request): subjects = get_all_subjects() if request.POST.getlist('bill_subjects'): filter_subjects = request.POST.getlist('bill_subjects') all_bills = Bill.objects.filter(subject__contains=filter_subjects) else: filter_subjects = [] all_bills = Bill.objects.all() subjects = _mark_selected(subjects, filter_subjects) details = [] for bill in all_bills: bill_detail = {} bill_detail['title'] = bill.title bill_detail['from_organization'] = bill.from_organization.name bill_detail['actions'] = [] bill_detail['sponsorships'] = [] for action in bill.actions.all(): bill_detail['actions'].append({'description': action.description, 'date': action.date}) for sponsorship in bill.sponsorships.all(): bill_detail['sponsorships'].append({ 'sponsor': sponsorship.name, 'id': sponsorship.id, 'primary': sponsorship.primary }) details.append(bill_detail) return render( request, 'bills/all.html', {'bills': details, 'subjects': subjects} )
Mark pre-selected topics on form
Mark pre-selected topics on form
Python
mit
jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot
+ from django.db import transaction from django.shortcuts import render, redirect + from preferences.views import _mark_selected from bills.utils import get_all_subjects, get_all_locations from opencivicdata.models import Bill def bill_list(request): subjects = get_all_subjects() if request.POST.getlist('bill_subjects'): filter_subjects = request.POST.getlist('bill_subjects') - all_bills = Bill.objects.filter(subject__in=filter_subjects) + all_bills = Bill.objects.filter(subject__contains=filter_subjects) else: + filter_subjects = [] all_bills = Bill.objects.all() + subjects = _mark_selected(subjects, filter_subjects) details = [] for bill in all_bills: bill_detail = {} bill_detail['title'] = bill.title bill_detail['from_organization'] = bill.from_organization.name bill_detail['actions'] = [] bill_detail['sponsorships'] = [] for action in bill.actions.all(): bill_detail['actions'].append({'description': action.description, 'date': action.date}) for sponsorship in bill.sponsorships.all(): bill_detail['sponsorships'].append({ 'sponsor': sponsorship.name, 'id': sponsorship.id, 'primary': sponsorship.primary }) details.append(bill_detail) - if request.method == 'POST': - with transaction.atomic(): - filter_subjects = request.POST.getlist('bill_subjects') - return redirect('.') - return render( request, 'bills/all.html', {'bills': details, 'subjects': subjects} )
Mark pre-selected topics on form
## Code Before: from django.shortcuts import render, redirect from bills.utils import get_all_subjects, get_all_locations from opencivicdata.models import Bill def bill_list(request): subjects = get_all_subjects() if request.POST.getlist('bill_subjects'): filter_subjects = request.POST.getlist('bill_subjects') all_bills = Bill.objects.filter(subject__in=filter_subjects) else: all_bills = Bill.objects.all() details = [] for bill in all_bills: bill_detail = {} bill_detail['title'] = bill.title bill_detail['from_organization'] = bill.from_organization.name bill_detail['actions'] = [] bill_detail['sponsorships'] = [] for action in bill.actions.all(): bill_detail['actions'].append({'description': action.description, 'date': action.date}) for sponsorship in bill.sponsorships.all(): bill_detail['sponsorships'].append({ 'sponsor': sponsorship.name, 'id': sponsorship.id, 'primary': sponsorship.primary }) details.append(bill_detail) if request.method == 'POST': with transaction.atomic(): filter_subjects = request.POST.getlist('bill_subjects') return redirect('.') return render( request, 'bills/all.html', {'bills': details, 'subjects': subjects} ) ## Instruction: Mark pre-selected topics on form ## Code After: from django.db import transaction from django.shortcuts import render, redirect from preferences.views import _mark_selected from bills.utils import get_all_subjects, get_all_locations from opencivicdata.models import Bill def bill_list(request): subjects = get_all_subjects() if request.POST.getlist('bill_subjects'): filter_subjects = request.POST.getlist('bill_subjects') all_bills = Bill.objects.filter(subject__contains=filter_subjects) else: filter_subjects = [] all_bills = Bill.objects.all() subjects = _mark_selected(subjects, filter_subjects) details = [] for bill in all_bills: bill_detail = {} bill_detail['title'] = bill.title bill_detail['from_organization'] = bill.from_organization.name bill_detail['actions'] = [] bill_detail['sponsorships'] = [] for action in bill.actions.all(): bill_detail['actions'].append({'description': action.description, 'date': action.date}) for sponsorship in bill.sponsorships.all(): bill_detail['sponsorships'].append({ 'sponsor': sponsorship.name, 'id': sponsorship.id, 'primary': sponsorship.primary }) details.append(bill_detail) return render( request, 'bills/all.html', {'bills': details, 'subjects': subjects} )
# ... existing code ... from django.db import transaction from django.shortcuts import render, redirect # ... modified code ... from preferences.views import _mark_selected from bills.utils import get_all_subjects, get_all_locations ... filter_subjects = request.POST.getlist('bill_subjects') all_bills = Bill.objects.filter(subject__contains=filter_subjects) else: filter_subjects = [] all_bills = Bill.objects.all() ... subjects = _mark_selected(subjects, filter_subjects) details = [] ... return render( # ... rest of the code ...
133a085f40f1536d5ebb26e912d15fa3bddcc82c
manager.py
manager.py
from cement.core.foundation import CementApp import command import util.config util.config.Configuration() class Manager(CementApp): class Meta: label = 'QLDS-Manager' handlers = [ command.default.ManagerBaseController, command.setup.SetupController ] with Manager() as app: app.run()
from cement.core.foundation import CementApp import command import util.config class Manager(CementApp): class Meta: label = 'QLDS-Manager' handlers = command.commands with Manager() as app: app.run()
Use handlers defined in command package
Use handlers defined in command package
Python
mit
rzeka/QLDS-Manager
from cement.core.foundation import CementApp import command import util.config - util.config.Configuration() - - class Manager(CementApp): class Meta: label = 'QLDS-Manager' + handlers = command.commands - handlers = [ - command.default.ManagerBaseController, - command.setup.SetupController - ] with Manager() as app: app.run()
Use handlers defined in command package
## Code Before: from cement.core.foundation import CementApp import command import util.config util.config.Configuration() class Manager(CementApp): class Meta: label = 'QLDS-Manager' handlers = [ command.default.ManagerBaseController, command.setup.SetupController ] with Manager() as app: app.run() ## Instruction: Use handlers defined in command package ## Code After: from cement.core.foundation import CementApp import command import util.config class Manager(CementApp): class Meta: label = 'QLDS-Manager' handlers = command.commands with Manager() as app: app.run()
// ... existing code ... class Manager(CementApp): // ... modified code ... label = 'QLDS-Manager' handlers = command.commands // ... rest of the code ...
7255033298cad9a4a7c51bdceafe84c0536e78ba
pytopkapi/infiltration.py
pytopkapi/infiltration.py
import numpy as np from scipy.optimize import fsolve def green_ampt_cum_infiltration(F, psi, dtheta, K, t): """The Green-Ampt cumulative infiltration equation. """ tmp = psi*dtheta # np.log(x) computes ln(x) return F - tmp*np.log(1 + F/tmp) - K*t if __name__ == '__main__': psi = 16.7 dtheta = 0.34 K = 0.65 t = 1 F = K*t # initial guess print fsolve(green_ampt_cum_infiltration, F, args=(psi, dtheta, K, t), full_output=True)
import numpy as np from scipy.optimize import fsolve def _green_ampt_cum_eq(F, psi, dtheta, K, t): """The Green-Ampt cumulative infiltration equation """ tmp = psi*dtheta # np.log(x) computes ln(x) return F - tmp*np.log(1 + F/tmp) - K*t def green_ampt_cum_infiltration(psi, dtheta, K, t): """Compute the Green-Ampt cumulative infiltration Compute the potential cumulative infiltration up to time `t`, using Green-Ampt. Parameters ---------- psi : array_like Soil suction head at wetting front. dtheta : array_like Ratio of initial effective saturation to effective porosity. K : array_like Saturated hydraulic conductivity. t : array_like Time since beginning of event Returns ------- soln : array_like Cumulative infiltration up to time `t`. Raises ------ ValueError - If no solution can be found. """ F = K*t # initial guess soln, infodict, ierr, mesg = fsolve(_green_ampt_cum_eq, F, args=(psi, dtheta, K, t), full_output=True) if ierr == 1: return soln else: raise ValueError(mesg) def test_basic_green_ampt(): """Test the Green-Ampt cumulative infiltration solution""" psi = 16.7 dtheta = 0.34 K = 0.65 t = 1 result = green_ampt_cum_infiltration(psi, dtheta, K, t) assert np.allclose(result, [3.16641923])
Change the API and add a test and documentation
ENH: Change the API and add a test and documentation
Python
bsd-3-clause
scottza/PyTOPKAPI,sahg/PyTOPKAPI
import numpy as np from scipy.optimize import fsolve - def green_ampt_cum_infiltration(F, psi, dtheta, K, t): + def _green_ampt_cum_eq(F, psi, dtheta, K, t): - """The Green-Ampt cumulative infiltration equation. + """The Green-Ampt cumulative infiltration equation """ tmp = psi*dtheta - + # np.log(x) computes ln(x) return F - tmp*np.log(1 + F/tmp) - K*t - if __name__ == '__main__': + def green_ampt_cum_infiltration(psi, dtheta, K, t): + """Compute the Green-Ampt cumulative infiltration + + Compute the potential cumulative infiltration up to time `t`, + using Green-Ampt. + + Parameters + ---------- + psi : array_like + Soil suction head at wetting front. + dtheta : array_like + Ratio of initial effective saturation to effective porosity. + K : array_like + Saturated hydraulic conductivity. + t : array_like + Time since beginning of event + + Returns + ------- + soln : array_like + Cumulative infiltration up to time `t`. + + Raises + ------ + ValueError - If no solution can be found. + + """ + + F = K*t # initial guess + + soln, infodict, ierr, mesg = fsolve(_green_ampt_cum_eq, F, + args=(psi, dtheta, K, t), + full_output=True) + + if ierr == 1: + return soln + else: + raise ValueError(mesg) + + def test_basic_green_ampt(): + """Test the Green-Ampt cumulative infiltration solution""" + psi = 16.7 dtheta = 0.34 K = 0.65 t = 1 - - F = K*t # initial guess - - print fsolve(green_ampt_cum_infiltration, - F, args=(psi, dtheta, K, t), full_output=True) + result = green_ampt_cum_infiltration(psi, dtheta, K, t) + + assert np.allclose(result, [3.16641923]) +
Change the API and add a test and documentation
## Code Before: import numpy as np from scipy.optimize import fsolve def green_ampt_cum_infiltration(F, psi, dtheta, K, t): """The Green-Ampt cumulative infiltration equation. """ tmp = psi*dtheta # np.log(x) computes ln(x) return F - tmp*np.log(1 + F/tmp) - K*t if __name__ == '__main__': psi = 16.7 dtheta = 0.34 K = 0.65 t = 1 F = K*t # initial guess print fsolve(green_ampt_cum_infiltration, F, args=(psi, dtheta, K, t), full_output=True) ## Instruction: Change the API and add a test and documentation ## Code After: import numpy as np from scipy.optimize import fsolve def _green_ampt_cum_eq(F, psi, dtheta, K, t): """The Green-Ampt cumulative infiltration equation """ tmp = psi*dtheta # np.log(x) computes ln(x) return F - tmp*np.log(1 + F/tmp) - K*t def green_ampt_cum_infiltration(psi, dtheta, K, t): """Compute the Green-Ampt cumulative infiltration Compute the potential cumulative infiltration up to time `t`, using Green-Ampt. Parameters ---------- psi : array_like Soil suction head at wetting front. dtheta : array_like Ratio of initial effective saturation to effective porosity. K : array_like Saturated hydraulic conductivity. t : array_like Time since beginning of event Returns ------- soln : array_like Cumulative infiltration up to time `t`. Raises ------ ValueError - If no solution can be found. """ F = K*t # initial guess soln, infodict, ierr, mesg = fsolve(_green_ampt_cum_eq, F, args=(psi, dtheta, K, t), full_output=True) if ierr == 1: return soln else: raise ValueError(mesg) def test_basic_green_ampt(): """Test the Green-Ampt cumulative infiltration solution""" psi = 16.7 dtheta = 0.34 K = 0.65 t = 1 result = green_ampt_cum_infiltration(psi, dtheta, K, t) assert np.allclose(result, [3.16641923])
# ... existing code ... def _green_ampt_cum_eq(F, psi, dtheta, K, t): """The Green-Ampt cumulative infiltration equation # ... modified code ... tmp = psi*dtheta # np.log(x) computes ln(x) ... def green_ampt_cum_infiltration(psi, dtheta, K, t): """Compute the Green-Ampt cumulative infiltration Compute the potential cumulative infiltration up to time `t`, using Green-Ampt. Parameters ---------- psi : array_like Soil suction head at wetting front. dtheta : array_like Ratio of initial effective saturation to effective porosity. K : array_like Saturated hydraulic conductivity. t : array_like Time since beginning of event Returns ------- soln : array_like Cumulative infiltration up to time `t`. Raises ------ ValueError - If no solution can be found. """ F = K*t # initial guess soln, infodict, ierr, mesg = fsolve(_green_ampt_cum_eq, F, args=(psi, dtheta, K, t), full_output=True) if ierr == 1: return soln else: raise ValueError(mesg) def test_basic_green_ampt(): """Test the Green-Ampt cumulative infiltration solution""" psi = 16.7 ... t = 1 result = green_ampt_cum_infiltration(psi, dtheta, K, t) assert np.allclose(result, [3.16641923]) # ... rest of the code ...
becc9ff7e1d260f9a4f47a36a0e6403e71f9f0b0
contentcuration/contentcuration/utils/messages.py
contentcuration/contentcuration/utils/messages.py
import json import os from django.conf import settings from django.utils.translation import get_language from django.utils.translation import to_locale _JSON_MESSAGES_FILE_CACHE = {} def locale_data_file(locale): path = getattr(settings, 'LOCALE_PATHS')[0] locale_path = os.path.join(path, locale) return os.path.join(locale_path, "LC_FRONTEND_MESSAGES", "contentcuration-messages.json") def get_messages(): global _JSON_MESSAGES_FILE_CACHE locale = to_locale(get_language()) if locale not in _JSON_MESSAGES_FILE_CACHE: try: with open(locale_data_file(locale), 'rb') as data: message_json = json.load(data) translation_dict = {} for key, value in message_json.items(): namespace, key = key.split(".") translation_dict[namespace] = translation_dict.get(namespace) or {} translation_dict[namespace][key] = value _JSON_MESSAGES_FILE_CACHE[locale] = json.dumps(translation_dict) except IOError: _JSON_MESSAGES_FILE_CACHE[locale] = json.dumps({}) return _JSON_MESSAGES_FILE_CACHE[locale]
import json import os from django.conf import settings from django.utils.translation import get_language from django.utils.translation import to_locale _JSON_MESSAGES_FILE_CACHE = {} def locale_data_file(locale): path = getattr(settings, 'LOCALE_PATHS')[0] return os.path.join(path, locale, "LC_FRONTEND_MESSAGES", "contentcuration-messages.json") def get_messages(): global _JSON_MESSAGES_FILE_CACHE locale = to_locale(get_language()) if locale not in _JSON_MESSAGES_FILE_CACHE: try: with open(locale_data_file(locale), 'rb') as data: message_json = json.load(data) translation_dict = {} for key, value in message_json.items(): namespace, key = key.split(".") translation_dict[namespace] = translation_dict.get(namespace) or {} translation_dict[namespace][key] = value _JSON_MESSAGES_FILE_CACHE[locale] = json.dumps(translation_dict) except IOError: _JSON_MESSAGES_FILE_CACHE[locale] = json.dumps({}) return _JSON_MESSAGES_FILE_CACHE[locale]
Remove no longer needed local variable.
Remove no longer needed local variable.
Python
mit
DXCanas/content-curation,DXCanas/content-curation,DXCanas/content-curation,DXCanas/content-curation
import json import os from django.conf import settings from django.utils.translation import get_language from django.utils.translation import to_locale _JSON_MESSAGES_FILE_CACHE = {} def locale_data_file(locale): path = getattr(settings, 'LOCALE_PATHS')[0] - locale_path = os.path.join(path, locale) - return os.path.join(locale_path, "LC_FRONTEND_MESSAGES", "contentcuration-messages.json") + return os.path.join(path, locale, "LC_FRONTEND_MESSAGES", "contentcuration-messages.json") def get_messages(): global _JSON_MESSAGES_FILE_CACHE locale = to_locale(get_language()) if locale not in _JSON_MESSAGES_FILE_CACHE: try: with open(locale_data_file(locale), 'rb') as data: message_json = json.load(data) translation_dict = {} for key, value in message_json.items(): namespace, key = key.split(".") translation_dict[namespace] = translation_dict.get(namespace) or {} translation_dict[namespace][key] = value _JSON_MESSAGES_FILE_CACHE[locale] = json.dumps(translation_dict) except IOError: _JSON_MESSAGES_FILE_CACHE[locale] = json.dumps({}) return _JSON_MESSAGES_FILE_CACHE[locale]
Remove no longer needed local variable.
## Code Before: import json import os from django.conf import settings from django.utils.translation import get_language from django.utils.translation import to_locale _JSON_MESSAGES_FILE_CACHE = {} def locale_data_file(locale): path = getattr(settings, 'LOCALE_PATHS')[0] locale_path = os.path.join(path, locale) return os.path.join(locale_path, "LC_FRONTEND_MESSAGES", "contentcuration-messages.json") def get_messages(): global _JSON_MESSAGES_FILE_CACHE locale = to_locale(get_language()) if locale not in _JSON_MESSAGES_FILE_CACHE: try: with open(locale_data_file(locale), 'rb') as data: message_json = json.load(data) translation_dict = {} for key, value in message_json.items(): namespace, key = key.split(".") translation_dict[namespace] = translation_dict.get(namespace) or {} translation_dict[namespace][key] = value _JSON_MESSAGES_FILE_CACHE[locale] = json.dumps(translation_dict) except IOError: _JSON_MESSAGES_FILE_CACHE[locale] = json.dumps({}) return _JSON_MESSAGES_FILE_CACHE[locale] ## Instruction: Remove no longer needed local variable. ## Code After: import json import os from django.conf import settings from django.utils.translation import get_language from django.utils.translation import to_locale _JSON_MESSAGES_FILE_CACHE = {} def locale_data_file(locale): path = getattr(settings, 'LOCALE_PATHS')[0] return os.path.join(path, locale, "LC_FRONTEND_MESSAGES", "contentcuration-messages.json") def get_messages(): global _JSON_MESSAGES_FILE_CACHE locale = to_locale(get_language()) if locale not in _JSON_MESSAGES_FILE_CACHE: try: with open(locale_data_file(locale), 'rb') as data: message_json = json.load(data) translation_dict = {} for key, value in message_json.items(): namespace, key = key.split(".") translation_dict[namespace] = translation_dict.get(namespace) or {} translation_dict[namespace][key] = value _JSON_MESSAGES_FILE_CACHE[locale] = json.dumps(translation_dict) except IOError: _JSON_MESSAGES_FILE_CACHE[locale] = json.dumps({}) return _JSON_MESSAGES_FILE_CACHE[locale]
// ... existing code ... path = getattr(settings, 'LOCALE_PATHS')[0] return os.path.join(path, locale, "LC_FRONTEND_MESSAGES", "contentcuration-messages.json") // ... rest of the code ...
e90cc08b755b96ef892e4fb25d43f3b25d89fae8
_tests/python_check_version.py
_tests/python_check_version.py
import os import sys current_version = list(sys.version_info[:3]) print("current_version: %s" % str(current_version)) expected_version = map(int, os.environ["EXPECTED_PYTHON_VERSION"].split(".")) print("expected_version: %s" % str(expected_version)) assert current_version == expected_version
import os import sys current_version = list(sys.version_info[:3]) print("current_version: %s" % str(current_version)) expected_version = list( map(int, os.environ["EXPECTED_PYTHON_VERSION"].split("."))) print("expected_version: %s" % str(expected_version)) assert current_version == expected_version
Fix python_version_check on python 3
tests: Fix python_version_check on python 3
Python
apache-2.0
scikit-build/scikit-ci-addons,scikit-build/scikit-ci-addons
import os import sys current_version = list(sys.version_info[:3]) print("current_version: %s" % str(current_version)) + expected_version = list( - expected_version = map(int, os.environ["EXPECTED_PYTHON_VERSION"].split(".")) + map(int, os.environ["EXPECTED_PYTHON_VERSION"].split("."))) print("expected_version: %s" % str(expected_version)) assert current_version == expected_version
Fix python_version_check on python 3
## Code Before: import os import sys current_version = list(sys.version_info[:3]) print("current_version: %s" % str(current_version)) expected_version = map(int, os.environ["EXPECTED_PYTHON_VERSION"].split(".")) print("expected_version: %s" % str(expected_version)) assert current_version == expected_version ## Instruction: Fix python_version_check on python 3 ## Code After: import os import sys current_version = list(sys.version_info[:3]) print("current_version: %s" % str(current_version)) expected_version = list( map(int, os.environ["EXPECTED_PYTHON_VERSION"].split("."))) print("expected_version: %s" % str(expected_version)) assert current_version == expected_version
// ... existing code ... expected_version = list( map(int, os.environ["EXPECTED_PYTHON_VERSION"].split("."))) print("expected_version: %s" % str(expected_version)) // ... rest of the code ...
db0253a228b3253e23bb5190fba9930a2f313d66
basictracer/context.py
basictracer/context.py
from __future__ import absolute_import import opentracing class SpanContext(opentracing.SpanContext): """SpanContext satisfies the opentracing.SpanContext contract. trace_id and span_id are uint64's, so their range is [0, 2^64). """ def __init__( self, trace_id=None, span_id=None, baggage=None, sampled=True): self.trace_id = trace_id self.span_id = span_id self.sampled = sampled self._baggage = baggage or opentracing.SpanContext.EMPTY_BAGGAGE @property def baggage(self): return self._baggage or opentracing.SpanContext.EMPTY_BAGGAGE def with_baggage_item(self, key, value): new_baggage = self._baggage.copy() new_baggage[key] = value return SpanContext( trace_id=self.trace_id, span_id=self.span_id, sampled=self.sampled, baggage=new_baggage)
from __future__ import absolute_import import opentracing class SpanContext(opentracing.SpanContext): """SpanContext satisfies the opentracing.SpanContext contract. trace_id and span_id are uint64's, so their range is [0, 2^64). """ def __init__( self, trace_id=None, span_id=None, baggage=None, sampled=True): self.trace_id = trace_id self.span_id = span_id self.sampled = sampled self._baggage = baggage or opentracing.SpanContext.EMPTY_BAGGAGE @property def baggage(self): return self._baggage def with_baggage_item(self, key, value): new_baggage = self._baggage.copy() new_baggage[key] = value return SpanContext( trace_id=self.trace_id, span_id=self.span_id, sampled=self.sampled, baggage=new_baggage)
Remove superfluous check for None baggage
Remove superfluous check for None baggage
Python
apache-2.0
opentracing/basictracer-python
from __future__ import absolute_import import opentracing class SpanContext(opentracing.SpanContext): """SpanContext satisfies the opentracing.SpanContext contract. trace_id and span_id are uint64's, so their range is [0, 2^64). """ def __init__( self, trace_id=None, span_id=None, baggage=None, sampled=True): self.trace_id = trace_id self.span_id = span_id self.sampled = sampled self._baggage = baggage or opentracing.SpanContext.EMPTY_BAGGAGE @property def baggage(self): - return self._baggage or opentracing.SpanContext.EMPTY_BAGGAGE + return self._baggage def with_baggage_item(self, key, value): new_baggage = self._baggage.copy() new_baggage[key] = value return SpanContext( trace_id=self.trace_id, span_id=self.span_id, sampled=self.sampled, baggage=new_baggage)
Remove superfluous check for None baggage
## Code Before: from __future__ import absolute_import import opentracing class SpanContext(opentracing.SpanContext): """SpanContext satisfies the opentracing.SpanContext contract. trace_id and span_id are uint64's, so their range is [0, 2^64). """ def __init__( self, trace_id=None, span_id=None, baggage=None, sampled=True): self.trace_id = trace_id self.span_id = span_id self.sampled = sampled self._baggage = baggage or opentracing.SpanContext.EMPTY_BAGGAGE @property def baggage(self): return self._baggage or opentracing.SpanContext.EMPTY_BAGGAGE def with_baggage_item(self, key, value): new_baggage = self._baggage.copy() new_baggage[key] = value return SpanContext( trace_id=self.trace_id, span_id=self.span_id, sampled=self.sampled, baggage=new_baggage) ## Instruction: Remove superfluous check for None baggage ## Code After: from __future__ import absolute_import import opentracing class SpanContext(opentracing.SpanContext): """SpanContext satisfies the opentracing.SpanContext contract. trace_id and span_id are uint64's, so their range is [0, 2^64). """ def __init__( self, trace_id=None, span_id=None, baggage=None, sampled=True): self.trace_id = trace_id self.span_id = span_id self.sampled = sampled self._baggage = baggage or opentracing.SpanContext.EMPTY_BAGGAGE @property def baggage(self): return self._baggage def with_baggage_item(self, key, value): new_baggage = self._baggage.copy() new_baggage[key] = value return SpanContext( trace_id=self.trace_id, span_id=self.span_id, sampled=self.sampled, baggage=new_baggage)
// ... existing code ... def baggage(self): return self._baggage // ... rest of the code ...
52d38e360b14fcfad01f87ff1e9ca5db27004877
src/comms/admin.py
src/comms/admin.py
from django.contrib import admin from src.comms.models import ChannelDB class MsgAdmin(admin.ModelAdmin): list_display = ('id', 'db_date_sent', 'db_sender', 'db_receivers', 'db_channels', 'db_message', 'db_lock_storage') list_display_links = ("id",) ordering = ["db_date_sent", 'db_sender', 'db_receivers', 'db_channels'] #readonly_fields = ['db_message', 'db_sender', 'db_receivers', 'db_channels'] search_fields = ['id', '^db_date_sent', '^db_message'] save_as = True save_on_top = True list_select_related = True #admin.site.register(Msg, MsgAdmin) class ChannelAdmin(admin.ModelAdmin): list_display = ('id', 'db_key', 'db_lock_storage', "db_subscriptions") list_display_links = ("id", 'db_key') ordering = ["db_key"] search_fields = ['id', 'db_key', 'db_aliases'] save_as = True save_on_top = True list_select_related = True fieldsets = ( (None, {'fields': (('db_key',), 'db_lock_storage')}), ) admin.site.register(ChannelDB, ChannelAdmin)
from django.contrib import admin from src.comms.models import ChannelDB class MsgAdmin(admin.ModelAdmin): list_display = ('id', 'db_date_sent', 'db_sender', 'db_receivers', 'db_channels', 'db_message', 'db_lock_storage') list_display_links = ("id",) ordering = ["db_date_sent", 'db_sender', 'db_receivers', 'db_channels'] #readonly_fields = ['db_message', 'db_sender', 'db_receivers', 'db_channels'] search_fields = ['id', '^db_date_sent', '^db_message'] save_as = True save_on_top = True list_select_related = True #admin.site.register(Msg, MsgAdmin) class ChannelAdmin(admin.ModelAdmin): list_display = ('id', 'db_key', 'db_lock_storage') list_display_links = ("id", 'db_key') ordering = ["db_key"] search_fields = ['id', 'db_key', 'db_aliases'] save_as = True save_on_top = True list_select_related = True fieldsets = ( (None, {'fields': (('db_key',), 'db_lock_storage')}), ) admin.site.register(ChannelDB, ChannelAdmin)
Remove unsupport M2M field in channelAdmin handler. Removes traceback when DEBUG=True.
Remove unsupport M2M field in channelAdmin handler. Removes traceback when DEBUG=True.
Python
bsd-3-clause
ypwalter/evennia,TheTypoMaster/evennia,TheTypoMaster/evennia,mrkulk/text-world,mrkulk/text-world,titeuf87/evennia,ergodicbreak/evennia,mrkulk/text-world,feend78/evennia,shollen/evennia,jamesbeebop/evennia,shollen/evennia,feend78/evennia,ergodicbreak/evennia,feend78/evennia,titeuf87/evennia,mrkulk/text-world,jamesbeebop/evennia,emergebtc/evennia,ypwalter/evennia,titeuf87/evennia,TheTypoMaster/evennia,emergebtc/evennia,titeuf87/evennia,ypwalter/evennia,feend78/evennia,emergebtc/evennia,jamesbeebop/evennia,ergodicbreak/evennia
from django.contrib import admin from src.comms.models import ChannelDB class MsgAdmin(admin.ModelAdmin): list_display = ('id', 'db_date_sent', 'db_sender', 'db_receivers', 'db_channels', 'db_message', 'db_lock_storage') list_display_links = ("id",) ordering = ["db_date_sent", 'db_sender', 'db_receivers', 'db_channels'] #readonly_fields = ['db_message', 'db_sender', 'db_receivers', 'db_channels'] search_fields = ['id', '^db_date_sent', '^db_message'] save_as = True save_on_top = True list_select_related = True #admin.site.register(Msg, MsgAdmin) class ChannelAdmin(admin.ModelAdmin): - list_display = ('id', 'db_key', 'db_lock_storage', "db_subscriptions") + list_display = ('id', 'db_key', 'db_lock_storage') list_display_links = ("id", 'db_key') ordering = ["db_key"] search_fields = ['id', 'db_key', 'db_aliases'] save_as = True save_on_top = True list_select_related = True fieldsets = ( (None, {'fields': (('db_key',), 'db_lock_storage')}), ) admin.site.register(ChannelDB, ChannelAdmin)
Remove unsupport M2M field in channelAdmin handler. Removes traceback when DEBUG=True.
## Code Before: from django.contrib import admin from src.comms.models import ChannelDB class MsgAdmin(admin.ModelAdmin): list_display = ('id', 'db_date_sent', 'db_sender', 'db_receivers', 'db_channels', 'db_message', 'db_lock_storage') list_display_links = ("id",) ordering = ["db_date_sent", 'db_sender', 'db_receivers', 'db_channels'] #readonly_fields = ['db_message', 'db_sender', 'db_receivers', 'db_channels'] search_fields = ['id', '^db_date_sent', '^db_message'] save_as = True save_on_top = True list_select_related = True #admin.site.register(Msg, MsgAdmin) class ChannelAdmin(admin.ModelAdmin): list_display = ('id', 'db_key', 'db_lock_storage', "db_subscriptions") list_display_links = ("id", 'db_key') ordering = ["db_key"] search_fields = ['id', 'db_key', 'db_aliases'] save_as = True save_on_top = True list_select_related = True fieldsets = ( (None, {'fields': (('db_key',), 'db_lock_storage')}), ) admin.site.register(ChannelDB, ChannelAdmin) ## Instruction: Remove unsupport M2M field in channelAdmin handler. Removes traceback when DEBUG=True. ## Code After: from django.contrib import admin from src.comms.models import ChannelDB class MsgAdmin(admin.ModelAdmin): list_display = ('id', 'db_date_sent', 'db_sender', 'db_receivers', 'db_channels', 'db_message', 'db_lock_storage') list_display_links = ("id",) ordering = ["db_date_sent", 'db_sender', 'db_receivers', 'db_channels'] #readonly_fields = ['db_message', 'db_sender', 'db_receivers', 'db_channels'] search_fields = ['id', '^db_date_sent', '^db_message'] save_as = True save_on_top = True list_select_related = True #admin.site.register(Msg, MsgAdmin) class ChannelAdmin(admin.ModelAdmin): list_display = ('id', 'db_key', 'db_lock_storage') list_display_links = ("id", 'db_key') ordering = ["db_key"] search_fields = ['id', 'db_key', 'db_aliases'] save_as = True save_on_top = True list_select_related = True fieldsets = ( (None, {'fields': (('db_key',), 'db_lock_storage')}), ) admin.site.register(ChannelDB, ChannelAdmin)
// ... existing code ... class ChannelAdmin(admin.ModelAdmin): list_display = ('id', 'db_key', 'db_lock_storage') list_display_links = ("id", 'db_key') // ... rest of the code ...
6ae84a6e098275cdaac8598695c97403dcb2092e
volttron/__init__.py
volttron/__init__.py
''' Copyright (c) 2013, Battelle Memorial Institute All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. ''' ''' This material was prepared as an account of work sponsored by an agency of the United States Government. Neither the United States Government nor the United States Department of Energy, nor Battelle, nor any of their employees, nor any jurisdiction or organization that has cooperated in the development of these materials, makes any warranty, express or implied, or assumes any legal liability or responsibility for the accuracy, completeness, or usefulness or any information, apparatus, product, software, or process disclosed, or represents that its use would not infringe privately owned rights. Reference herein to any specific commercial product, process, or service by trade name, trademark, manufacturer, or otherwise does not necessarily constitute or imply its endorsement, recommendation, r favoring by the United States Government or any agency thereof, or Battelle Memorial Institute. The views and opinions of authors expressed herein do not necessarily state or reflect those of the United States Government or any agency thereof. PACIFIC NORTHWEST NATIONAL LABORATORY operated by BATTELLE for the UNITED STATES DEPARTMENT OF ENERGY under Contract DE-AC05-76RL01830 '''
from pkgutil import extend_path __path__ = extend_path(__path__, __name__)
Make volttron a namespace package.
Make volttron a namespace package.
Python
bsd-2-clause
schandrika/volttron,schandrika/volttron,schandrika/volttron,schandrika/volttron
+ from pkgutil import extend_path + __path__ = extend_path(__path__, __name__) - ''' - Copyright (c) 2013, Battelle Memorial Institute - All rights reserved. - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - The views and conclusions contained in the software and documentation are those - of the authors and should not be interpreted as representing official policies, - either expressed or implied, of the FreeBSD Project. - ''' - - ''' - This material was prepared as an account of work sponsored by an - agency of the United States Government. Neither the United States - Government nor the United States Department of Energy, nor Battelle, - nor any of their employees, nor any jurisdiction or organization - that has cooperated in the development of these materials, makes - any warranty, express or implied, or assumes any legal liability - or responsibility for the accuracy, completeness, or usefulness or - any information, apparatus, product, software, or process disclosed, - or represents that its use would not infringe privately owned rights. - - Reference herein to any specific commercial product, process, or - service by trade name, trademark, manufacturer, or otherwise does - not necessarily constitute or imply its endorsement, recommendation, - r favoring by the United States Government or any agency thereof, - or Battelle Memorial Institute. The views and opinions of authors - expressed herein do not necessarily state or reflect those of the - United States Government or any agency thereof. - - PACIFIC NORTHWEST NATIONAL LABORATORY - operated by BATTELLE for the UNITED STATES DEPARTMENT OF ENERGY - under Contract DE-AC05-76RL01830 - ''' -
Make volttron a namespace package.
## Code Before: ''' Copyright (c) 2013, Battelle Memorial Institute All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. ''' ''' This material was prepared as an account of work sponsored by an agency of the United States Government. Neither the United States Government nor the United States Department of Energy, nor Battelle, nor any of their employees, nor any jurisdiction or organization that has cooperated in the development of these materials, makes any warranty, express or implied, or assumes any legal liability or responsibility for the accuracy, completeness, or usefulness or any information, apparatus, product, software, or process disclosed, or represents that its use would not infringe privately owned rights. Reference herein to any specific commercial product, process, or service by trade name, trademark, manufacturer, or otherwise does not necessarily constitute or imply its endorsement, recommendation, r favoring by the United States Government or any agency thereof, or Battelle Memorial Institute. The views and opinions of authors expressed herein do not necessarily state or reflect those of the United States Government or any agency thereof. PACIFIC NORTHWEST NATIONAL LABORATORY operated by BATTELLE for the UNITED STATES DEPARTMENT OF ENERGY under Contract DE-AC05-76RL01830 ''' ## Instruction: Make volttron a namespace package. ## Code After: from pkgutil import extend_path __path__ = extend_path(__path__, __name__)
# ... existing code ... from pkgutil import extend_path __path__ = extend_path(__path__, __name__) # ... rest of the code ...
417196332246474b306e81c8d7d2f3a7a5065eb5
senic_hub/backend/subprocess_run.py
senic_hub/backend/subprocess_run.py
"""Provides `subprocess.run()` from Python 3.5+ if available. Otherwise falls back to `subprocess.check_output()`.""" try: from subprocess import run except ImportError: from collections import namedtuple from subprocess import check_output def run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, timeout=None, check=False, encoding=None, errors=None): stdout_bytes = check_output(args, stdin=stdin, stderr=stderr, shell=shell, timeout=timeout) Output = namedtuple('Output', ['stdout']) return Output(stdout=stdout_bytes)
"""Provides `subprocess.run()` from Python 3.5+ if available. Otherwise falls back to `subprocess.check_output()`.""" try: from subprocess import run except ImportError: from collections import namedtuple from subprocess import check_output, CalledProcessError def run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, timeout=None, check=False, encoding=None, errors=None): try: stdout_bytes = check_output(args, stdin=stdin, stderr=stderr, shell=shell, timeout=timeout) except CalledProcessError as e: if check: raise else: stdout_bytes = e.output Output = namedtuple('Output', ['stdout']) return Output(stdout=stdout_bytes)
Fix throwing error although check arg is false
Fix throwing error although check arg is false
Python
mit
grunskis/senic-hub,grunskis/nuimo-hub-backend,grunskis/senic-hub,grunskis/senic-hub,grunskis/senic-hub,grunskis/senic-hub,grunskis/nuimo-hub-backend,getsenic/senic-hub,grunskis/nuimo-hub-backend,grunskis/nuimo-hub-backend,grunskis/senic-hub,getsenic/senic-hub,grunskis/nuimo-hub-backend
"""Provides `subprocess.run()` from Python 3.5+ if available. Otherwise falls back to `subprocess.check_output()`.""" try: from subprocess import run except ImportError: from collections import namedtuple - from subprocess import check_output + from subprocess import check_output, CalledProcessError def run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, timeout=None, check=False, encoding=None, errors=None): + try: - stdout_bytes = check_output(args, stdin=stdin, stderr=stderr, shell=shell, timeout=timeout) + stdout_bytes = check_output(args, stdin=stdin, stderr=stderr, shell=shell, timeout=timeout) + except CalledProcessError as e: + if check: + raise + else: + stdout_bytes = e.output Output = namedtuple('Output', ['stdout']) return Output(stdout=stdout_bytes)
Fix throwing error although check arg is false
## Code Before: """Provides `subprocess.run()` from Python 3.5+ if available. Otherwise falls back to `subprocess.check_output()`.""" try: from subprocess import run except ImportError: from collections import namedtuple from subprocess import check_output def run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, timeout=None, check=False, encoding=None, errors=None): stdout_bytes = check_output(args, stdin=stdin, stderr=stderr, shell=shell, timeout=timeout) Output = namedtuple('Output', ['stdout']) return Output(stdout=stdout_bytes) ## Instruction: Fix throwing error although check arg is false ## Code After: """Provides `subprocess.run()` from Python 3.5+ if available. Otherwise falls back to `subprocess.check_output()`.""" try: from subprocess import run except ImportError: from collections import namedtuple from subprocess import check_output, CalledProcessError def run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, timeout=None, check=False, encoding=None, errors=None): try: stdout_bytes = check_output(args, stdin=stdin, stderr=stderr, shell=shell, timeout=timeout) except CalledProcessError as e: if check: raise else: stdout_bytes = e.output Output = namedtuple('Output', ['stdout']) return Output(stdout=stdout_bytes)
... from collections import namedtuple from subprocess import check_output, CalledProcessError ... encoding=None, errors=None): try: stdout_bytes = check_output(args, stdin=stdin, stderr=stderr, shell=shell, timeout=timeout) except CalledProcessError as e: if check: raise else: stdout_bytes = e.output Output = namedtuple('Output', ['stdout']) ...
28cdad6e8ab6bd400ef50331a2f93af93620cc7f
app/models.py
app/models.py
from django.db import models class Event(models.Model): when = models.DateTimeField(auto_now=True) what = models.TextField()
from django.db import models class Event(models.Model): when = models.DateTimeField(auto_now=True) what = models.TextField() def time(self): return '{:%H:%M}'.format(self.when)
Return human-sensible time in Event
Return human-sensible time in Event
Python
mit
schatten/logan
from django.db import models class Event(models.Model): when = models.DateTimeField(auto_now=True) what = models.TextField() + def time(self): + return '{:%H:%M}'.format(self.when) +
Return human-sensible time in Event
## Code Before: from django.db import models class Event(models.Model): when = models.DateTimeField(auto_now=True) what = models.TextField() ## Instruction: Return human-sensible time in Event ## Code After: from django.db import models class Event(models.Model): when = models.DateTimeField(auto_now=True) what = models.TextField() def time(self): return '{:%H:%M}'.format(self.when)
... what = models.TextField() def time(self): return '{:%H:%M}'.format(self.when) ...
a58c3cbfa2c0147525e1afb355e355a9edeb22f8
discussion/admin.py
discussion/admin.py
from django.contrib import admin from discussion.models import Comment, Discussion, Post class CommentInline(admin.TabularInline): exclude = ('user',) extra = 1 model = Comment class PostAdmin(admin.ModelAdmin): inlines = (CommentInline,) list_filter = ('discussion',) class DiscussionAdmin(admin.ModelAdmin): prepopulated_fields = { 'slug': ('name',) } admin.site.register(Discussion, DiscussionAdmin) admin.site.register(Post, PostAdmin) admin.site.register(Comment)
from django.contrib import admin from discussion.models import Comment, Discussion, Post class CommentInline(admin.TabularInline): extra = 1 model = Comment raw_id_fields = ('user',) class PostAdmin(admin.ModelAdmin): inlines = (CommentInline,) list_filter = ('discussion',) class DiscussionAdmin(admin.ModelAdmin): prepopulated_fields = { 'slug': ('name',) } admin.site.register(Discussion, DiscussionAdmin) admin.site.register(Post, PostAdmin) admin.site.register(Comment)
Add user back onto the comment inline for posts
Add user back onto the comment inline for posts
Python
bsd-2-clause
lehins/lehins-discussion,lehins/lehins-discussion,incuna/django-discussion,incuna/django-discussion,lehins/lehins-discussion
from django.contrib import admin from discussion.models import Comment, Discussion, Post class CommentInline(admin.TabularInline): - exclude = ('user',) extra = 1 model = Comment + raw_id_fields = ('user',) class PostAdmin(admin.ModelAdmin): inlines = (CommentInline,) list_filter = ('discussion',) class DiscussionAdmin(admin.ModelAdmin): prepopulated_fields = { 'slug': ('name',) } admin.site.register(Discussion, DiscussionAdmin) admin.site.register(Post, PostAdmin) admin.site.register(Comment)
Add user back onto the comment inline for posts
## Code Before: from django.contrib import admin from discussion.models import Comment, Discussion, Post class CommentInline(admin.TabularInline): exclude = ('user',) extra = 1 model = Comment class PostAdmin(admin.ModelAdmin): inlines = (CommentInline,) list_filter = ('discussion',) class DiscussionAdmin(admin.ModelAdmin): prepopulated_fields = { 'slug': ('name',) } admin.site.register(Discussion, DiscussionAdmin) admin.site.register(Post, PostAdmin) admin.site.register(Comment) ## Instruction: Add user back onto the comment inline for posts ## Code After: from django.contrib import admin from discussion.models import Comment, Discussion, Post class CommentInline(admin.TabularInline): extra = 1 model = Comment raw_id_fields = ('user',) class PostAdmin(admin.ModelAdmin): inlines = (CommentInline,) list_filter = ('discussion',) class DiscussionAdmin(admin.ModelAdmin): prepopulated_fields = { 'slug': ('name',) } admin.site.register(Discussion, DiscussionAdmin) admin.site.register(Post, PostAdmin) admin.site.register(Comment)
// ... existing code ... class CommentInline(admin.TabularInline): extra = 1 // ... modified code ... model = Comment raw_id_fields = ('user',) // ... rest of the code ...
2db334e452e2ee2d5f0cbc516dc6cb04b61e598d
yargy/labels.py
yargy/labels.py
GENDERS = ("masc", "femn", "neut", "Ms-f") def gram_label(token, value, stack): return value in token.grammemes def gram_not_label(token, value, stack): return not value in token.grammemes def gender_match_label(token, index, stack, genders=GENDERS): results = ((g in t.grammemes for g in genders) for t in (stack[index], token)) *case_token_genders, case_token_msf = next(results) *candidate_token_genders, candidate_token_msf = next(results) if not candidate_token_genders == case_token_genders: if case_token_msf: if any(candidate_token_genders[:2]): return True else: return True return False def dictionary_label(token, values, stack): return any((n in values) for n in token.forms) LABELS_LOOKUP_MAP = { "gram": gram_label, "gram-not": gram_not_label, "dictionary": dictionary_label, "gender-match": gender_match_label, }
GENDERS = ("masc", "femn", "neut", "Ms-f", "GNdr") def gram_label(token, value, stack): return value in token.grammemes def gram_not_label(token, value, stack): return not value in token.grammemes def gender_match_label(token, index, stack, genders=GENDERS): results = ((g in t.grammemes for g in genders) for t in (stack[index], token)) *case_token_genders, case_token_msf, case_token_gndr = next(results) *candidate_token_genders, candidate_token_msf, candidate_token_gndr = next(results) if not candidate_token_genders == case_token_genders: if case_token_msf: if any(candidate_token_genders[:2]): return True elif case_token_gndr or candidate_token_gndr: return True else: return True return False def dictionary_label(token, values, stack): return any((n in values) for n in token.forms) LABELS_LOOKUP_MAP = { "gram": gram_label, "gram-not": gram_not_label, "dictionary": dictionary_label, "gender-match": gender_match_label, }
Check for `GNdr` grammeme in `gender-match` label
Check for `GNdr` grammeme in `gender-match` label
Python
mit
bureaucratic-labs/yargy
- GENDERS = ("masc", "femn", "neut", "Ms-f") + GENDERS = ("masc", "femn", "neut", "Ms-f", "GNdr") def gram_label(token, value, stack): return value in token.grammemes def gram_not_label(token, value, stack): return not value in token.grammemes def gender_match_label(token, index, stack, genders=GENDERS): results = ((g in t.grammemes for g in genders) for t in (stack[index], token)) - *case_token_genders, case_token_msf = next(results) + *case_token_genders, case_token_msf, case_token_gndr = next(results) - *candidate_token_genders, candidate_token_msf = next(results) + *candidate_token_genders, candidate_token_msf, candidate_token_gndr = next(results) if not candidate_token_genders == case_token_genders: if case_token_msf: if any(candidate_token_genders[:2]): return True + elif case_token_gndr or candidate_token_gndr: + return True else: return True return False def dictionary_label(token, values, stack): return any((n in values) for n in token.forms) LABELS_LOOKUP_MAP = { "gram": gram_label, "gram-not": gram_not_label, "dictionary": dictionary_label, "gender-match": gender_match_label, }
Check for `GNdr` grammeme in `gender-match` label
## Code Before: GENDERS = ("masc", "femn", "neut", "Ms-f") def gram_label(token, value, stack): return value in token.grammemes def gram_not_label(token, value, stack): return not value in token.grammemes def gender_match_label(token, index, stack, genders=GENDERS): results = ((g in t.grammemes for g in genders) for t in (stack[index], token)) *case_token_genders, case_token_msf = next(results) *candidate_token_genders, candidate_token_msf = next(results) if not candidate_token_genders == case_token_genders: if case_token_msf: if any(candidate_token_genders[:2]): return True else: return True return False def dictionary_label(token, values, stack): return any((n in values) for n in token.forms) LABELS_LOOKUP_MAP = { "gram": gram_label, "gram-not": gram_not_label, "dictionary": dictionary_label, "gender-match": gender_match_label, } ## Instruction: Check for `GNdr` grammeme in `gender-match` label ## Code After: GENDERS = ("masc", "femn", "neut", "Ms-f", "GNdr") def gram_label(token, value, stack): return value in token.grammemes def gram_not_label(token, value, stack): return not value in token.grammemes def gender_match_label(token, index, stack, genders=GENDERS): results = ((g in t.grammemes for g in genders) for t in (stack[index], token)) *case_token_genders, case_token_msf, case_token_gndr = next(results) *candidate_token_genders, candidate_token_msf, candidate_token_gndr = next(results) if not candidate_token_genders == case_token_genders: if case_token_msf: if any(candidate_token_genders[:2]): return True elif case_token_gndr or candidate_token_gndr: return True else: return True return False def dictionary_label(token, values, stack): return any((n in values) for n in token.forms) LABELS_LOOKUP_MAP = { "gram": gram_label, "gram-not": gram_not_label, "dictionary": dictionary_label, "gender-match": gender_match_label, }
... GENDERS = ("masc", "femn", "neut", "Ms-f", "GNdr") ... *case_token_genders, case_token_msf, case_token_gndr = next(results) *candidate_token_genders, candidate_token_msf, candidate_token_gndr = next(results) ... return True elif case_token_gndr or candidate_token_gndr: return True else: ...
6d43df828cb34c8949c8f87c256bde2e6ccb7d3c
atamatracker/moviefile.py
atamatracker/moviefile.py
import cv2 class Movie(object): """Movie file object. """ def __init__(self, file_path): self.__capture = cv2.VideoCapture(file_path) def __del__(self): self.__capture.release() def load_image(self, time_sec): """Load image at the desired time. Retruns None if no image could load. """ self.__capture.set(cv2.cv.CV_CAP_PROP_POS_MSEC, time_sec * 1000) f, image = self.__capture.read() return image
import cv2 class Movie(object): """Movie file object. Public properties: fps (read-only) -- [float] frames per second width (read-only) -- [int] frame dimension height (read-only) -- [int] frame dimension """ def __init__(self, file_path): capture = cv2.VideoCapture(file_path) self.__capture = capture self.__fps = capture.get(cv2.cv.CV_CAP_PROP_FPS) self.__width = int(capture.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH)) self.__height = int(capture.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT)) def __del__(self): self.__capture.release() @property def fps(self): """frames per second """ return self.__fps @property def width(self): """frame dimension """ return self.__width @property def height(self): """frame dimension """ return self.__height def load_image(self, time_sec): """Load image at the desired time. Retruns None if no image could load. """ self.__capture.set(cv2.cv.CV_CAP_PROP_POS_MSEC, time_sec * 1000) f, image = self.__capture.read() return image
Add some useful read-only properties to Movie class
Add some useful read-only properties to Movie class
Python
mit
ptsg/AtamaTracker
import cv2 class Movie(object): """Movie file object. + + Public properties: + fps (read-only) -- [float] frames per second + width (read-only) -- [int] frame dimension + height (read-only) -- [int] frame dimension """ def __init__(self, file_path): - self.__capture = cv2.VideoCapture(file_path) + capture = cv2.VideoCapture(file_path) + + self.__capture = capture + self.__fps = capture.get(cv2.cv.CV_CAP_PROP_FPS) + self.__width = int(capture.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH)) + self.__height = int(capture.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT)) def __del__(self): self.__capture.release() + + @property + def fps(self): + """frames per second + """ + return self.__fps + + @property + def width(self): + """frame dimension + """ + return self.__width + + @property + def height(self): + """frame dimension + """ + return self.__height def load_image(self, time_sec): """Load image at the desired time. Retruns None if no image could load. """ self.__capture.set(cv2.cv.CV_CAP_PROP_POS_MSEC, time_sec * 1000) f, image = self.__capture.read() return image
Add some useful read-only properties to Movie class
## Code Before: import cv2 class Movie(object): """Movie file object. """ def __init__(self, file_path): self.__capture = cv2.VideoCapture(file_path) def __del__(self): self.__capture.release() def load_image(self, time_sec): """Load image at the desired time. Retruns None if no image could load. """ self.__capture.set(cv2.cv.CV_CAP_PROP_POS_MSEC, time_sec * 1000) f, image = self.__capture.read() return image ## Instruction: Add some useful read-only properties to Movie class ## Code After: import cv2 class Movie(object): """Movie file object. Public properties: fps (read-only) -- [float] frames per second width (read-only) -- [int] frame dimension height (read-only) -- [int] frame dimension """ def __init__(self, file_path): capture = cv2.VideoCapture(file_path) self.__capture = capture self.__fps = capture.get(cv2.cv.CV_CAP_PROP_FPS) self.__width = int(capture.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH)) self.__height = int(capture.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT)) def __del__(self): self.__capture.release() @property def fps(self): """frames per second """ return self.__fps @property def width(self): """frame dimension """ return self.__width @property def height(self): """frame dimension """ return self.__height def load_image(self, time_sec): """Load image at the desired time. Retruns None if no image could load. """ self.__capture.set(cv2.cv.CV_CAP_PROP_POS_MSEC, time_sec * 1000) f, image = self.__capture.read() return image
... """Movie file object. Public properties: fps (read-only) -- [float] frames per second width (read-only) -- [int] frame dimension height (read-only) -- [int] frame dimension """ ... def __init__(self, file_path): capture = cv2.VideoCapture(file_path) self.__capture = capture self.__fps = capture.get(cv2.cv.CV_CAP_PROP_FPS) self.__width = int(capture.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH)) self.__height = int(capture.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT)) ... self.__capture.release() @property def fps(self): """frames per second """ return self.__fps @property def width(self): """frame dimension """ return self.__width @property def height(self): """frame dimension """ return self.__height ...
131cb9abd711cc71c558e5a89d5e2b8a28ae8517
tests/integration/test_gists.py
tests/integration/test_gists.py
from .helper import IntegrationHelper import github3 class TestGist(IntegrationHelper): def test_comments(self): """Show that a user can iterate over the comments on a gist.""" cassette_name = self.cassette_name('comments') with self.recorder.use_cassette(cassette_name): gist = self.gh.gist(3342247) assert gist is not None for comment in gist.comments(): assert isinstance(comment, github3.gists.comment.GistComment) def test_iter_commits(self): cassette_name = self.cassette_name('commits') with self.recorder.use_cassette(cassette_name, preserve_exact_body_bytes=True): gist = self.gh.gist(1834570) assert gist is not None for commit in gist.iter_commits(): assert isinstance(commit, github3.gists.history.GistHistory) def test_iter_forks(self): cassette_name = self.cassette_name('forks') with self.recorder.use_cassette(cassette_name, preserve_exact_body_bytes=True): gist = self.gh.gist(1834570) assert gist is not None for commit in gist.iter_forks(): assert isinstance(commit, github3.gists.gist.Gist)
"""Integration tests for methods implemented on Gist.""" from .helper import IntegrationHelper import github3 class TestGist(IntegrationHelper): """Gist integration tests.""" def test_comments(self): """Show that a user can iterate over the comments on a gist.""" cassette_name = self.cassette_name('comments') with self.recorder.use_cassette(cassette_name): gist = self.gh.gist(3342247) assert gist is not None for comment in gist.comments(): assert isinstance(comment, github3.gists.comment.GistComment) def test_iter_commits(self): """Show that a user can iterate over the commits in a gist.""" cassette_name = self.cassette_name('commits') with self.recorder.use_cassette(cassette_name, preserve_exact_body_bytes=True): gist = self.gh.gist(1834570) assert gist is not None for commit in gist.iter_commits(): assert isinstance(commit, github3.gists.history.GistHistory) def test_iter_forks(self): """Show that a user can iterate over the forks of a gist.""" cassette_name = self.cassette_name('forks') with self.recorder.use_cassette(cassette_name, preserve_exact_body_bytes=True): gist = self.gh.gist(1834570) assert gist is not None for commit in gist.iter_forks(): assert isinstance(commit, github3.gists.gist.Gist)
Add docstrings to Gist integration tests
Add docstrings to Gist integration tests @esacteksab would be so proud
Python
bsd-3-clause
krxsky/github3.py,balloob/github3.py,jim-minter/github3.py,ueg1990/github3.py,wbrefvem/github3.py,agamdua/github3.py,christophelec/github3.py,icio/github3.py,sigmavirus24/github3.py,itsmemattchung/github3.py,h4ck3rm1k3/github3.py,degustaf/github3.py
+ """Integration tests for methods implemented on Gist.""" from .helper import IntegrationHelper import github3 class TestGist(IntegrationHelper): + + """Gist integration tests.""" + def test_comments(self): """Show that a user can iterate over the comments on a gist.""" cassette_name = self.cassette_name('comments') with self.recorder.use_cassette(cassette_name): gist = self.gh.gist(3342247) assert gist is not None for comment in gist.comments(): assert isinstance(comment, github3.gists.comment.GistComment) def test_iter_commits(self): + """Show that a user can iterate over the commits in a gist.""" cassette_name = self.cassette_name('commits') with self.recorder.use_cassette(cassette_name, preserve_exact_body_bytes=True): gist = self.gh.gist(1834570) assert gist is not None for commit in gist.iter_commits(): assert isinstance(commit, github3.gists.history.GistHistory) def test_iter_forks(self): + """Show that a user can iterate over the forks of a gist.""" cassette_name = self.cassette_name('forks') with self.recorder.use_cassette(cassette_name, preserve_exact_body_bytes=True): gist = self.gh.gist(1834570) assert gist is not None for commit in gist.iter_forks(): assert isinstance(commit, github3.gists.gist.Gist)
Add docstrings to Gist integration tests
## Code Before: from .helper import IntegrationHelper import github3 class TestGist(IntegrationHelper): def test_comments(self): """Show that a user can iterate over the comments on a gist.""" cassette_name = self.cassette_name('comments') with self.recorder.use_cassette(cassette_name): gist = self.gh.gist(3342247) assert gist is not None for comment in gist.comments(): assert isinstance(comment, github3.gists.comment.GistComment) def test_iter_commits(self): cassette_name = self.cassette_name('commits') with self.recorder.use_cassette(cassette_name, preserve_exact_body_bytes=True): gist = self.gh.gist(1834570) assert gist is not None for commit in gist.iter_commits(): assert isinstance(commit, github3.gists.history.GistHistory) def test_iter_forks(self): cassette_name = self.cassette_name('forks') with self.recorder.use_cassette(cassette_name, preserve_exact_body_bytes=True): gist = self.gh.gist(1834570) assert gist is not None for commit in gist.iter_forks(): assert isinstance(commit, github3.gists.gist.Gist) ## Instruction: Add docstrings to Gist integration tests ## Code After: """Integration tests for methods implemented on Gist.""" from .helper import IntegrationHelper import github3 class TestGist(IntegrationHelper): """Gist integration tests.""" def test_comments(self): """Show that a user can iterate over the comments on a gist.""" cassette_name = self.cassette_name('comments') with self.recorder.use_cassette(cassette_name): gist = self.gh.gist(3342247) assert gist is not None for comment in gist.comments(): assert isinstance(comment, github3.gists.comment.GistComment) def test_iter_commits(self): """Show that a user can iterate over the commits in a gist.""" cassette_name = self.cassette_name('commits') with self.recorder.use_cassette(cassette_name, preserve_exact_body_bytes=True): gist = self.gh.gist(1834570) assert gist is not None for commit in gist.iter_commits(): assert isinstance(commit, github3.gists.history.GistHistory) def test_iter_forks(self): """Show that a user can iterate over the forks of a gist.""" cassette_name = self.cassette_name('forks') with self.recorder.use_cassette(cassette_name, preserve_exact_body_bytes=True): gist = self.gh.gist(1834570) assert gist is not None for commit in gist.iter_forks(): assert isinstance(commit, github3.gists.gist.Gist)
// ... existing code ... """Integration tests for methods implemented on Gist.""" from .helper import IntegrationHelper // ... modified code ... class TestGist(IntegrationHelper): """Gist integration tests.""" def test_comments(self): ... def test_iter_commits(self): """Show that a user can iterate over the commits in a gist.""" cassette_name = self.cassette_name('commits') ... def test_iter_forks(self): """Show that a user can iterate over the forks of a gist.""" cassette_name = self.cassette_name('forks') // ... rest of the code ...
4d7dff1c335a49d13d420f3c62b1a2d2382351dd
trajprocess/tests/utils.py
trajprocess/tests/utils.py
"""Tools for setting up a fake directory structure for processing.""" from tempfile import mkdtemp import os import shutil import json from pkg_resources import resource_filename def write_run_clone(proj, run, clone, gens=None): if gens is None: gens = [0, 1] rc = "data/PROJ{proj}/RUN{run}/CLONE{clone}/".format(proj=proj, run=run, clone=clone) os.makedirs(rc, exist_ok=True) tpr_fn = resource_filename(__name__, 'topol.tpr') shutil.copy(tpr_fn, "{}/frame0.tpr".format(rc)) for gen in gens: shutil.copy(resource_filename(__name__, "traj_comp.part{:04d}.xtc".format( gen + 1)), "{}/frame{}.xtc".format(rc, gen)) def generate_project(): global wd wd = mkdtemp() os.chdir(wd) write_run_clone(1234, 5, 7) write_run_clone(1234, 6, 0) with open('structs-p1234.json', 'w') as f: json.dump({ 5: {'struct': 'stru1', 'fext': 'pdb'}, 6: {'struct': 'stru2', 'fext': 'pdb'} }, f) def cleanup(): shutil.rmtree(wd)
"""Tools for setting up a fake directory structure for processing.""" from tempfile import mkdtemp import os import shutil import json from pkg_resources import resource_filename # command for generating reference data: # gmx mdrun -nsteps 5000 -s frame0.tpr -cpi -noappend # # Do that three times. def write_run_clone(proj, run, clone, gens=None): if gens is None: gens = [0, 1] rc = "data/PROJ{proj}/RUN{run}/CLONE{clone}/".format(proj=proj, run=run, clone=clone) os.makedirs(rc, exist_ok=True) tpr_fn = resource_filename(__name__, 'topol.tpr') shutil.copy(tpr_fn, "{}/frame0.tpr".format(rc)) for gen in gens: shutil.copy(resource_filename(__name__, "traj_comp.part{:04d}.xtc".format( gen + 1)), "{}/frame{}.xtc".format(rc, gen)) def generate_project(): global wd wd = mkdtemp() os.chdir(wd) write_run_clone(1234, 5, 7) write_run_clone(1234, 6, 0) with open('structs-p1234.json', 'w') as f: json.dump({ 5: {'struct': 'stru1', 'fext': 'pdb'}, 6: {'struct': 'stru2', 'fext': 'pdb'} }, f) def cleanup(): shutil.rmtree(wd)
Add note about how to generate trajectories
Add note about how to generate trajectories
Python
mit
mpharrigan/trajprocess,mpharrigan/trajprocess
"""Tools for setting up a fake directory structure for processing.""" from tempfile import mkdtemp import os import shutil import json from pkg_resources import resource_filename + + + # command for generating reference data: + # gmx mdrun -nsteps 5000 -s frame0.tpr -cpi -noappend + # + # Do that three times. def write_run_clone(proj, run, clone, gens=None): if gens is None: gens = [0, 1] rc = "data/PROJ{proj}/RUN{run}/CLONE{clone}/".format(proj=proj, run=run, clone=clone) os.makedirs(rc, exist_ok=True) tpr_fn = resource_filename(__name__, 'topol.tpr') shutil.copy(tpr_fn, "{}/frame0.tpr".format(rc)) for gen in gens: shutil.copy(resource_filename(__name__, "traj_comp.part{:04d}.xtc".format( gen + 1)), "{}/frame{}.xtc".format(rc, gen)) def generate_project(): global wd wd = mkdtemp() os.chdir(wd) write_run_clone(1234, 5, 7) write_run_clone(1234, 6, 0) with open('structs-p1234.json', 'w') as f: json.dump({ 5: {'struct': 'stru1', 'fext': 'pdb'}, 6: {'struct': 'stru2', 'fext': 'pdb'} }, f) def cleanup(): shutil.rmtree(wd)
Add note about how to generate trajectories
## Code Before: """Tools for setting up a fake directory structure for processing.""" from tempfile import mkdtemp import os import shutil import json from pkg_resources import resource_filename def write_run_clone(proj, run, clone, gens=None): if gens is None: gens = [0, 1] rc = "data/PROJ{proj}/RUN{run}/CLONE{clone}/".format(proj=proj, run=run, clone=clone) os.makedirs(rc, exist_ok=True) tpr_fn = resource_filename(__name__, 'topol.tpr') shutil.copy(tpr_fn, "{}/frame0.tpr".format(rc)) for gen in gens: shutil.copy(resource_filename(__name__, "traj_comp.part{:04d}.xtc".format( gen + 1)), "{}/frame{}.xtc".format(rc, gen)) def generate_project(): global wd wd = mkdtemp() os.chdir(wd) write_run_clone(1234, 5, 7) write_run_clone(1234, 6, 0) with open('structs-p1234.json', 'w') as f: json.dump({ 5: {'struct': 'stru1', 'fext': 'pdb'}, 6: {'struct': 'stru2', 'fext': 'pdb'} }, f) def cleanup(): shutil.rmtree(wd) ## Instruction: Add note about how to generate trajectories ## Code After: """Tools for setting up a fake directory structure for processing.""" from tempfile import mkdtemp import os import shutil import json from pkg_resources import resource_filename # command for generating reference data: # gmx mdrun -nsteps 5000 -s frame0.tpr -cpi -noappend # # Do that three times. def write_run_clone(proj, run, clone, gens=None): if gens is None: gens = [0, 1] rc = "data/PROJ{proj}/RUN{run}/CLONE{clone}/".format(proj=proj, run=run, clone=clone) os.makedirs(rc, exist_ok=True) tpr_fn = resource_filename(__name__, 'topol.tpr') shutil.copy(tpr_fn, "{}/frame0.tpr".format(rc)) for gen in gens: shutil.copy(resource_filename(__name__, "traj_comp.part{:04d}.xtc".format( gen + 1)), "{}/frame{}.xtc".format(rc, gen)) def generate_project(): global wd wd = mkdtemp() os.chdir(wd) write_run_clone(1234, 5, 7) write_run_clone(1234, 6, 0) with open('structs-p1234.json', 'w') as f: json.dump({ 5: {'struct': 'stru1', 'fext': 'pdb'}, 6: {'struct': 'stru2', 'fext': 'pdb'} }, f) def cleanup(): shutil.rmtree(wd)
... from pkg_resources import resource_filename # command for generating reference data: # gmx mdrun -nsteps 5000 -s frame0.tpr -cpi -noappend # # Do that three times. ...
ca777965c26b8dfd43b472adeb032f048e2537ed
acceptancetests/tests/acc_test_login_page.py
acceptancetests/tests/acc_test_login_page.py
import os import unittest from splinter import Browser class TestLoginPage (unittest.TestCase): def setUp(self): self.browser = Browser('phantomjs') def test_login_page_appears(self): # This needs to come from an environment variable at some point # For now, this will only pass if the lighthouse-app-server host is # running. url = "http://%s/login" % os.environ['LIGHTHOUSE_HOST'] title = 'Lighthouse' self.browser.visit(url) self.assertEqual(self.browser.url, url) self.assertEqual(self.browser.status_code.code, 200) self.assertIn(self.browser.title, title) self.assertIn('Login with ID.', self.browser.html)
import os import unittest from splinter import Browser class TestLoginPage (unittest.TestCase): def setUp(self): self.browser = Browser('phantomjs') def test_login_page_appears(self): # This needs to come from an environment variable at some point # For now, this will only pass if the lighthouse-app-server host is # running. url = "http://%s/login" % os.environ['LIGHTHOUSE_HOST'] title = 'Lighthouse' self.browser.visit(url) self.assertEqual(self.browser.url, url) self.assertEqual(self.browser.status_code.code, 200) self.assertIn(title, self.browser.title) self.assertIn('Login with ID.', self.browser.html)
Check that expected title exists in the actual title, not the other way round
Check that expected title exists in the actual title, not the other way round
Python
mit
dstl/lighthouse,dstl/lighthouse,dstl/lighthouse,dstl/lighthouse,dstl/lighthouse
import os import unittest from splinter import Browser class TestLoginPage (unittest.TestCase): def setUp(self): self.browser = Browser('phantomjs') def test_login_page_appears(self): # This needs to come from an environment variable at some point # For now, this will only pass if the lighthouse-app-server host is # running. url = "http://%s/login" % os.environ['LIGHTHOUSE_HOST'] title = 'Lighthouse' self.browser.visit(url) self.assertEqual(self.browser.url, url) self.assertEqual(self.browser.status_code.code, 200) - self.assertIn(self.browser.title, title) + self.assertIn(title, self.browser.title) self.assertIn('Login with ID.', self.browser.html)
Check that expected title exists in the actual title, not the other way round
## Code Before: import os import unittest from splinter import Browser class TestLoginPage (unittest.TestCase): def setUp(self): self.browser = Browser('phantomjs') def test_login_page_appears(self): # This needs to come from an environment variable at some point # For now, this will only pass if the lighthouse-app-server host is # running. url = "http://%s/login" % os.environ['LIGHTHOUSE_HOST'] title = 'Lighthouse' self.browser.visit(url) self.assertEqual(self.browser.url, url) self.assertEqual(self.browser.status_code.code, 200) self.assertIn(self.browser.title, title) self.assertIn('Login with ID.', self.browser.html) ## Instruction: Check that expected title exists in the actual title, not the other way round ## Code After: import os import unittest from splinter import Browser class TestLoginPage (unittest.TestCase): def setUp(self): self.browser = Browser('phantomjs') def test_login_page_appears(self): # This needs to come from an environment variable at some point # For now, this will only pass if the lighthouse-app-server host is # running. url = "http://%s/login" % os.environ['LIGHTHOUSE_HOST'] title = 'Lighthouse' self.browser.visit(url) self.assertEqual(self.browser.url, url) self.assertEqual(self.browser.status_code.code, 200) self.assertIn(title, self.browser.title) self.assertIn('Login with ID.', self.browser.html)
... self.assertEqual(self.browser.status_code.code, 200) self.assertIn(title, self.browser.title) ...
11443eda1a192c0f3a4aa8225263b4e312fa5a55
spam_lists/exceptions.py
spam_lists/exceptions.py
class SpamListsError(Exception): '''There was an error during testing a url or host''' class UnknownCodeError(SpamListsError): '''The classification code from the service was not recognized''' class UnathorizedAPIKeyError(SpamListsError): '''The API key used to query the service was not authorized'''
class SpamListsError(Exception): '''There was an error during testing a url or host''' class UnknownCodeError(SpamListsError, KeyError): '''The classification code from the service was not recognized''' class UnathorizedAPIKeyError(SpamListsError): '''The API key used to query the service was not authorized'''
Make UnknownCodeError additionally extend KeyError
Make UnknownCodeError additionally extend KeyError
Python
mit
piotr-rusin/spam-lists
class SpamListsError(Exception): '''There was an error during testing a url or host''' - class UnknownCodeError(SpamListsError): + class UnknownCodeError(SpamListsError, KeyError): '''The classification code from the service was not recognized''' class UnathorizedAPIKeyError(SpamListsError): '''The API key used to query the service was not authorized'''
Make UnknownCodeError additionally extend KeyError
## Code Before: class SpamListsError(Exception): '''There was an error during testing a url or host''' class UnknownCodeError(SpamListsError): '''The classification code from the service was not recognized''' class UnathorizedAPIKeyError(SpamListsError): '''The API key used to query the service was not authorized''' ## Instruction: Make UnknownCodeError additionally extend KeyError ## Code After: class SpamListsError(Exception): '''There was an error during testing a url or host''' class UnknownCodeError(SpamListsError, KeyError): '''The classification code from the service was not recognized''' class UnathorizedAPIKeyError(SpamListsError): '''The API key used to query the service was not authorized'''
// ... existing code ... class UnknownCodeError(SpamListsError, KeyError): '''The classification code from the service was not recognized''' // ... rest of the code ...
b4120ec570624ae4c66269ae2a8f916ec55734e9
ipywidgets/widgets/valuewidget.py
ipywidgets/widgets/valuewidget.py
"""Contains the ValueWidget class""" from .widget import Widget class ValueWidget(Widget): """Widget that can be used for the input of an interactive function""" def get_interact_value(self): """Return the value for this widget which should be passed to interactive functions. Custom widgets can change this method to process the raw value ``self.value``. """ return self.value
"""Contains the ValueWidget class""" from .widget import Widget from traitlets import Any class ValueWidget(Widget): """Widget that can be used for the input of an interactive function""" value = Any(help="The value of the widget.") def get_interact_value(self): """Return the value for this widget which should be passed to interactive functions. Custom widgets can change this method to process the raw value ``self.value``. """ return self.value
Add a value trait to Value widgets.
Add a value trait to Value widgets.
Python
bsd-3-clause
ipython/ipywidgets,jupyter-widgets/ipywidgets,jupyter-widgets/ipywidgets,jupyter-widgets/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets
"""Contains the ValueWidget class""" from .widget import Widget + from traitlets import Any class ValueWidget(Widget): """Widget that can be used for the input of an interactive function""" + + value = Any(help="The value of the widget.") def get_interact_value(self): """Return the value for this widget which should be passed to interactive functions. Custom widgets can change this method to process the raw value ``self.value``. """ return self.value
Add a value trait to Value widgets.
## Code Before: """Contains the ValueWidget class""" from .widget import Widget class ValueWidget(Widget): """Widget that can be used for the input of an interactive function""" def get_interact_value(self): """Return the value for this widget which should be passed to interactive functions. Custom widgets can change this method to process the raw value ``self.value``. """ return self.value ## Instruction: Add a value trait to Value widgets. ## Code After: """Contains the ValueWidget class""" from .widget import Widget from traitlets import Any class ValueWidget(Widget): """Widget that can be used for the input of an interactive function""" value = Any(help="The value of the widget.") def get_interact_value(self): """Return the value for this widget which should be passed to interactive functions. Custom widgets can change this method to process the raw value ``self.value``. """ return self.value
... from .widget import Widget from traitlets import Any ... """Widget that can be used for the input of an interactive function""" value = Any(help="The value of the widget.") ...
d9e9f8f1968ecc62a22b53dc58367cd8698b8bdb
project_generator/util.py
project_generator/util.py
import os import shutil import locale def rmtree_if_exists(directory): if os.path.exists(directory): shutil.rmtree(directory) def uniqify(l): # see: http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order/29898968#29898968 reduce(lambda r, v: v in r[1] and r or (r[0].append(v) or r[1].add(v)) or r, l, ([], set()))[0] def flatten_list(l): all_items = [item if len(item) > 1 else sublist for sublist in l for item in sublist] return uniqify(all_items) def unicode_available(): return locale.getdefaultlocale()[1] == 'UTF-8'
import os import shutil import locale def rmtree_if_exists(directory): if os.path.exists(directory): shutil.rmtree(directory) def uniqify(_list): # see: http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order/29898968#29898968 reduce(lambda r, v: v in r[1] and r or (r[0].append(v) or r[1].add(v)) or r, _list, ([], set()))[0] def flatten_list(_list): all_items = [item if len(item) > 1 else sublist for sublist in _list for item in sublist] return uniqify(all_items) def unicode_available(): return locale.getdefaultlocale()[1] == 'UTF-8'
Remove all traces of ls.
Remove all traces of ls.
Python
apache-2.0
0xc0170/project_generator,sarahmarshy/project_generator,project-generator/project_generator,hwfwgrp/project_generator,ohagendorf/project_generator,molejar/project_generator
import os import shutil import locale def rmtree_if_exists(directory): if os.path.exists(directory): shutil.rmtree(directory) - def uniqify(l): + def uniqify(_list): # see: http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order/29898968#29898968 - reduce(lambda r, v: v in r[1] and r or (r[0].append(v) or r[1].add(v)) or r, l, ([], set()))[0] + reduce(lambda r, v: v in r[1] and r or (r[0].append(v) or r[1].add(v)) or r, _list, ([], set()))[0] - def flatten_list(l): + def flatten_list(_list): - all_items = [item if len(item) > 1 else sublist for sublist in l for item in sublist] + all_items = [item if len(item) > 1 else sublist for sublist in _list for item in sublist] return uniqify(all_items) def unicode_available(): return locale.getdefaultlocale()[1] == 'UTF-8'
Remove all traces of ls.
## Code Before: import os import shutil import locale def rmtree_if_exists(directory): if os.path.exists(directory): shutil.rmtree(directory) def uniqify(l): # see: http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order/29898968#29898968 reduce(lambda r, v: v in r[1] and r or (r[0].append(v) or r[1].add(v)) or r, l, ([], set()))[0] def flatten_list(l): all_items = [item if len(item) > 1 else sublist for sublist in l for item in sublist] return uniqify(all_items) def unicode_available(): return locale.getdefaultlocale()[1] == 'UTF-8' ## Instruction: Remove all traces of ls. ## Code After: import os import shutil import locale def rmtree_if_exists(directory): if os.path.exists(directory): shutil.rmtree(directory) def uniqify(_list): # see: http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order/29898968#29898968 reduce(lambda r, v: v in r[1] and r or (r[0].append(v) or r[1].add(v)) or r, _list, ([], set()))[0] def flatten_list(_list): all_items = [item if len(item) > 1 else sublist for sublist in _list for item in sublist] return uniqify(all_items) def unicode_available(): return locale.getdefaultlocale()[1] == 'UTF-8'
// ... existing code ... def uniqify(_list): # see: http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order/29898968#29898968 reduce(lambda r, v: v in r[1] and r or (r[0].append(v) or r[1].add(v)) or r, _list, ([], set()))[0] def flatten_list(_list): all_items = [item if len(item) > 1 else sublist for sublist in _list for item in sublist] return uniqify(all_items) // ... rest of the code ...
ff9a8cb1f68785cc16c99fe26dd96e9fa01c325e
src/hunter/const.py
src/hunter/const.py
import site import sys from distutils.sysconfig import get_python_lib SITE_PACKAGES_PATHS = set(site.getsitepackages()) SITE_PACKAGES_PATHS.add(site.getusersitepackages()) SITE_PACKAGES_PATHS.add(get_python_lib()) SITE_PACKAGES_PATHS = tuple(SITE_PACKAGES_PATHS) SYS_PREFIX_PATHS = set(( sys.prefix, sys.exec_prefix )) for prop in 'real_prefix', 'real_exec_prefix', 'base_prefix', 'base_exec_prefix': if hasattr(sys, prop): SYS_PREFIX_PATHS.add(getattr(sys, prop)) SYS_PREFIX_PATHS = tuple(SYS_PREFIX_PATHS)
import site import sys from distutils.sysconfig import get_python_lib SITE_PACKAGES_PATHS = set() if hasattr(site, 'getsitepackages'): SITE_PACKAGES_PATHS.update(site.getsitepackages()) if hasattr(site, 'getusersitepackages'): SITE_PACKAGES_PATHS.add(site.getusersitepackages()) SITE_PACKAGES_PATHS.add(get_python_lib()) SITE_PACKAGES_PATHS = tuple(SITE_PACKAGES_PATHS) SYS_PREFIX_PATHS = set(( sys.prefix, sys.exec_prefix )) for prop in 'real_prefix', 'real_exec_prefix', 'base_prefix', 'base_exec_prefix': if hasattr(sys, prop): SYS_PREFIX_PATHS.add(getattr(sys, prop)) SYS_PREFIX_PATHS = tuple(SYS_PREFIX_PATHS)
Add checks in case site.py is broken (eg: virtualenv).
Add checks in case site.py is broken (eg: virtualenv).
Python
bsd-2-clause
ionelmc/python-hunter
import site import sys from distutils.sysconfig import get_python_lib + SITE_PACKAGES_PATHS = set() + if hasattr(site, 'getsitepackages'): - SITE_PACKAGES_PATHS = set(site.getsitepackages()) + SITE_PACKAGES_PATHS.update(site.getsitepackages()) + if hasattr(site, 'getusersitepackages'): - SITE_PACKAGES_PATHS.add(site.getusersitepackages()) + SITE_PACKAGES_PATHS.add(site.getusersitepackages()) SITE_PACKAGES_PATHS.add(get_python_lib()) SITE_PACKAGES_PATHS = tuple(SITE_PACKAGES_PATHS) SYS_PREFIX_PATHS = set(( sys.prefix, sys.exec_prefix )) for prop in 'real_prefix', 'real_exec_prefix', 'base_prefix', 'base_exec_prefix': if hasattr(sys, prop): SYS_PREFIX_PATHS.add(getattr(sys, prop)) SYS_PREFIX_PATHS = tuple(SYS_PREFIX_PATHS)
Add checks in case site.py is broken (eg: virtualenv).
## Code Before: import site import sys from distutils.sysconfig import get_python_lib SITE_PACKAGES_PATHS = set(site.getsitepackages()) SITE_PACKAGES_PATHS.add(site.getusersitepackages()) SITE_PACKAGES_PATHS.add(get_python_lib()) SITE_PACKAGES_PATHS = tuple(SITE_PACKAGES_PATHS) SYS_PREFIX_PATHS = set(( sys.prefix, sys.exec_prefix )) for prop in 'real_prefix', 'real_exec_prefix', 'base_prefix', 'base_exec_prefix': if hasattr(sys, prop): SYS_PREFIX_PATHS.add(getattr(sys, prop)) SYS_PREFIX_PATHS = tuple(SYS_PREFIX_PATHS) ## Instruction: Add checks in case site.py is broken (eg: virtualenv). ## Code After: import site import sys from distutils.sysconfig import get_python_lib SITE_PACKAGES_PATHS = set() if hasattr(site, 'getsitepackages'): SITE_PACKAGES_PATHS.update(site.getsitepackages()) if hasattr(site, 'getusersitepackages'): SITE_PACKAGES_PATHS.add(site.getusersitepackages()) SITE_PACKAGES_PATHS.add(get_python_lib()) SITE_PACKAGES_PATHS = tuple(SITE_PACKAGES_PATHS) SYS_PREFIX_PATHS = set(( sys.prefix, sys.exec_prefix )) for prop in 'real_prefix', 'real_exec_prefix', 'base_prefix', 'base_exec_prefix': if hasattr(sys, prop): SYS_PREFIX_PATHS.add(getattr(sys, prop)) SYS_PREFIX_PATHS = tuple(SYS_PREFIX_PATHS)
# ... existing code ... SITE_PACKAGES_PATHS = set() if hasattr(site, 'getsitepackages'): SITE_PACKAGES_PATHS.update(site.getsitepackages()) if hasattr(site, 'getusersitepackages'): SITE_PACKAGES_PATHS.add(site.getusersitepackages()) SITE_PACKAGES_PATHS.add(get_python_lib()) # ... rest of the code ...
18e1e0a1c1b4492e623d5b86d7a23fff00d5fa72
pysingcells/__main__.py
pysingcells/__main__.py
import os import sys import configparser from subprocess import call # project import from . import logger from .mapper import hisat2 def main(config_path): """ Main function of pro'gramme read configuration and run enable step """ config = configparser.ConfigParser() logger.setup_logging(**config) config.read(config_path) print(config.sections()) for key in config['paths']: print(config['paths'][key]) def trimming(files_dir, rep_out , paired=1) : file_list = os.listdir(files_dir) for fastq in file_list : call(['cmd', 'options...']) if __name__ == "__main__": main(sys.argv[1])
import os import sys import configparser from subprocess import call # project import from . import logger from .mapper import hisat2 def main(config_path): """ Main function of pro'gramme read configuration and run enable step """ config = configparser.ConfigParser() config.read(config_path) print(config.sections()) logger.setup_logging(**config) for key in config['paths']: print(config['paths'][key]) mapper = hisat2.Hisat2() mapper.read_configuration(**config) if mapper.check_configuration() : mapper.run() def trimming(files_dir, rep_out , paired=1) : file_list = os.listdir(files_dir) for fastq in file_list : call(['cmd', 'options...']) if __name__ == "__main__": main(sys.argv[1])
Add test of hisat2 object
Add test of hisat2 object
Python
mit
Fougere87/pysingcells
import os import sys import configparser from subprocess import call # project import from . import logger from .mapper import hisat2 def main(config_path): """ Main function of pro'gramme read configuration and run enable step """ config = configparser.ConfigParser() - logger.setup_logging(**config) - config.read(config_path) print(config.sections()) + logger.setup_logging(**config) for key in config['paths']: print(config['paths'][key]) + mapper = hisat2.Hisat2() + mapper.read_configuration(**config) + if mapper.check_configuration() : + mapper.run() def trimming(files_dir, rep_out , paired=1) : file_list = os.listdir(files_dir) for fastq in file_list : call(['cmd', 'options...']) if __name__ == "__main__": main(sys.argv[1])
Add test of hisat2 object
## Code Before: import os import sys import configparser from subprocess import call # project import from . import logger from .mapper import hisat2 def main(config_path): """ Main function of pro'gramme read configuration and run enable step """ config = configparser.ConfigParser() logger.setup_logging(**config) config.read(config_path) print(config.sections()) for key in config['paths']: print(config['paths'][key]) def trimming(files_dir, rep_out , paired=1) : file_list = os.listdir(files_dir) for fastq in file_list : call(['cmd', 'options...']) if __name__ == "__main__": main(sys.argv[1]) ## Instruction: Add test of hisat2 object ## Code After: import os import sys import configparser from subprocess import call # project import from . import logger from .mapper import hisat2 def main(config_path): """ Main function of pro'gramme read configuration and run enable step """ config = configparser.ConfigParser() config.read(config_path) print(config.sections()) logger.setup_logging(**config) for key in config['paths']: print(config['paths'][key]) mapper = hisat2.Hisat2() mapper.read_configuration(**config) if mapper.check_configuration() : mapper.run() def trimming(files_dir, rep_out , paired=1) : file_list = os.listdir(files_dir) for fastq in file_list : call(['cmd', 'options...']) if __name__ == "__main__": main(sys.argv[1])
... config.read(config_path) ... print(config.sections()) logger.setup_logging(**config) ... mapper = hisat2.Hisat2() mapper.read_configuration(**config) if mapper.check_configuration() : mapper.run() ...
9a474cbea3a2713a94e9e5dbc0b90762b4f354c6
automated_ebs_snapshots/connection_manager.py
automated_ebs_snapshots/connection_manager.py
""" Handles connections to AWS """ import logging import sys from boto import ec2 from boto.utils import get_instance_metadata logger = logging.getLogger(__name__) def connect_to_ec2(region='us-east-1', access_key=None, secret_key=None): """ Connect to AWS ec2 :type region: str :param region: AWS region to connect to :type access_key: str :param access_key: AWS access key id :type secret_key: str :param secret_key: AWS secret access key :returns: boto.ec2.connection.EC2Connection -- EC2 connection """ logger.info('Connecting to AWS EC2 in {}'.format(region)) if access_key: # Connect using supplied credentials connection = ec2.connect_to_region( region, aws_access_key_id=access_key, aws_secret_access_key=secret_key) else: # Fetch instance metadata metadata = get_instance_metadata(timeout=1, num_retries=1) if metadata: try: region = metadata['placement']['availability-zone'][:-1] except KeyError: pass # Connect using env vars or boto credentials connection = ec2.connect_to_region(region) if not connection: logger.error('An error occurred when connecting to EC2') sys.exit(1) return connection
""" Handles connections to AWS """ import logging import sys from boto import ec2 from boto.utils import get_instance_metadata logger = logging.getLogger(__name__) def connect_to_ec2(region='us-east-1', access_key=None, secret_key=None): """ Connect to AWS ec2 :type region: str :param region: AWS region to connect to :type access_key: str :param access_key: AWS access key id :type secret_key: str :param secret_key: AWS secret access key :returns: boto.ec2.connection.EC2Connection -- EC2 connection """ if access_key: # Connect using supplied credentials logger.info('Connecting to AWS EC2 in {}'.format(region)) connection = ec2.connect_to_region( region, aws_access_key_id=access_key, aws_secret_access_key=secret_key) else: # Fetch instance metadata metadata = get_instance_metadata(timeout=1, num_retries=1) if metadata: try: region = metadata['placement']['availability-zone'][:-1] except KeyError: pass # Connect using env vars or boto credentials logger.info('Connecting to AWS EC2 in {}'.format(region)) connection = ec2.connect_to_region(region) if not connection: logger.error('An error occurred when connecting to EC2') sys.exit(1) return connection
Fix for logging incorrect region information when using instance role for authentication.
Fix for logging incorrect region information when using instance role for authentication.
Python
apache-2.0
bkarakashev/automated-ebs-snapshots,skymill/automated-ebs-snapshots,CBitLabs/automated-ebs-snapshots
""" Handles connections to AWS """ import logging import sys from boto import ec2 from boto.utils import get_instance_metadata logger = logging.getLogger(__name__) def connect_to_ec2(region='us-east-1', access_key=None, secret_key=None): """ Connect to AWS ec2 :type region: str :param region: AWS region to connect to :type access_key: str :param access_key: AWS access key id :type secret_key: str :param secret_key: AWS secret access key :returns: boto.ec2.connection.EC2Connection -- EC2 connection """ - logger.info('Connecting to AWS EC2 in {}'.format(region)) if access_key: # Connect using supplied credentials + logger.info('Connecting to AWS EC2 in {}'.format(region)) connection = ec2.connect_to_region( region, aws_access_key_id=access_key, aws_secret_access_key=secret_key) else: # Fetch instance metadata metadata = get_instance_metadata(timeout=1, num_retries=1) if metadata: try: region = metadata['placement']['availability-zone'][:-1] except KeyError: pass # Connect using env vars or boto credentials + logger.info('Connecting to AWS EC2 in {}'.format(region)) connection = ec2.connect_to_region(region) if not connection: logger.error('An error occurred when connecting to EC2') sys.exit(1) return connection
Fix for logging incorrect region information when using instance role for authentication.
## Code Before: """ Handles connections to AWS """ import logging import sys from boto import ec2 from boto.utils import get_instance_metadata logger = logging.getLogger(__name__) def connect_to_ec2(region='us-east-1', access_key=None, secret_key=None): """ Connect to AWS ec2 :type region: str :param region: AWS region to connect to :type access_key: str :param access_key: AWS access key id :type secret_key: str :param secret_key: AWS secret access key :returns: boto.ec2.connection.EC2Connection -- EC2 connection """ logger.info('Connecting to AWS EC2 in {}'.format(region)) if access_key: # Connect using supplied credentials connection = ec2.connect_to_region( region, aws_access_key_id=access_key, aws_secret_access_key=secret_key) else: # Fetch instance metadata metadata = get_instance_metadata(timeout=1, num_retries=1) if metadata: try: region = metadata['placement']['availability-zone'][:-1] except KeyError: pass # Connect using env vars or boto credentials connection = ec2.connect_to_region(region) if not connection: logger.error('An error occurred when connecting to EC2') sys.exit(1) return connection ## Instruction: Fix for logging incorrect region information when using instance role for authentication. ## Code After: """ Handles connections to AWS """ import logging import sys from boto import ec2 from boto.utils import get_instance_metadata logger = logging.getLogger(__name__) def connect_to_ec2(region='us-east-1', access_key=None, secret_key=None): """ Connect to AWS ec2 :type region: str :param region: AWS region to connect to :type access_key: str :param access_key: AWS access key id :type secret_key: str :param secret_key: AWS secret access key :returns: boto.ec2.connection.EC2Connection -- EC2 connection """ if access_key: # Connect using supplied credentials logger.info('Connecting to AWS EC2 in {}'.format(region)) connection = ec2.connect_to_region( region, aws_access_key_id=access_key, aws_secret_access_key=secret_key) else: # Fetch instance metadata metadata = get_instance_metadata(timeout=1, num_retries=1) if metadata: try: region = metadata['placement']['availability-zone'][:-1] except KeyError: pass # Connect using env vars or boto credentials logger.info('Connecting to AWS EC2 in {}'.format(region)) connection = ec2.connect_to_region(region) if not connection: logger.error('An error occurred when connecting to EC2') sys.exit(1) return connection
// ... existing code ... """ // ... modified code ... # Connect using supplied credentials logger.info('Connecting to AWS EC2 in {}'.format(region)) connection = ec2.connect_to_region( ... # Connect using env vars or boto credentials logger.info('Connecting to AWS EC2 in {}'.format(region)) connection = ec2.connect_to_region(region) // ... rest of the code ...
3364747195f0f3d2711169fb92c250fc10823d82
default_settings.py
default_settings.py
import logging import os UV4 = os.path.join("C:","Keil","UV4","UV4.exe") IARBUILD = os.path.join('C:','Program Files (x86)','IAR Systems','Embedded Workbench 7.0','common','bin','IarBuild.exe') # Be able to locate project generator anywhere in a project # By default it's tools/project_generator (2 folders deep from root) PROJECT_ROOT= os.path.join('..','..') if os.name == "posix": # Expects either arm-none-eabi to be installed here, or # even better, a symlink from /usr/local/arm-none-eabi to the most recent # version. gcc_bin_path = "/usr/local/arm-none-eabi/bin/" elif os.name == "nt": gcc_bin_path = "" try: from user_settings import * except: pass
import logging import os UV4 = os.path.join("C:","Keil","UV4","UV4.exe") IARBUILD = os.path.join('C:','Program Files (x86)','IAR Systems','Embedded Workbench 7.0','common','bin','IarBuild.exe') # Be able to locate project generator anywhere in a project # By default it's tools/project_generator (2 folders deep from root) PROJECT_ROOT= os.path.join('..','..') if os.name == "posix": # Expects either arm-none-eabi to be installed here, or # even better, a symlink from /usr/local/arm-none-eabi to the most recent # version. gcc_bin_path = "/usr/local/arm-none-eabi/bin/" elif os.name == "nt": gcc_bin_path = "" try: from user_settings import * except: logging.info("Using default settings.")
Add message if you're using default settings
Add message if you're using default settings
Python
apache-2.0
0xc0170/valinor,sarahmarshy/project_generator,autopulated/valinor,ARMmbed/valinor,sg-/project_generator,ohagendorf/project_generator,molejar/project_generator,aethaniel/project_generator,0xc0170/project_generator,sg-/project_generator,project-generator/project_generator,hwfwgrp/project_generator
import logging import os UV4 = os.path.join("C:","Keil","UV4","UV4.exe") IARBUILD = os.path.join('C:','Program Files (x86)','IAR Systems','Embedded Workbench 7.0','common','bin','IarBuild.exe') # Be able to locate project generator anywhere in a project # By default it's tools/project_generator (2 folders deep from root) PROJECT_ROOT= os.path.join('..','..') if os.name == "posix": # Expects either arm-none-eabi to be installed here, or # even better, a symlink from /usr/local/arm-none-eabi to the most recent # version. gcc_bin_path = "/usr/local/arm-none-eabi/bin/" elif os.name == "nt": gcc_bin_path = "" try: from user_settings import * except: - pass + logging.info("Using default settings.")
Add message if you're using default settings
## Code Before: import logging import os UV4 = os.path.join("C:","Keil","UV4","UV4.exe") IARBUILD = os.path.join('C:','Program Files (x86)','IAR Systems','Embedded Workbench 7.0','common','bin','IarBuild.exe') # Be able to locate project generator anywhere in a project # By default it's tools/project_generator (2 folders deep from root) PROJECT_ROOT= os.path.join('..','..') if os.name == "posix": # Expects either arm-none-eabi to be installed here, or # even better, a symlink from /usr/local/arm-none-eabi to the most recent # version. gcc_bin_path = "/usr/local/arm-none-eabi/bin/" elif os.name == "nt": gcc_bin_path = "" try: from user_settings import * except: pass ## Instruction: Add message if you're using default settings ## Code After: import logging import os UV4 = os.path.join("C:","Keil","UV4","UV4.exe") IARBUILD = os.path.join('C:','Program Files (x86)','IAR Systems','Embedded Workbench 7.0','common','bin','IarBuild.exe') # Be able to locate project generator anywhere in a project # By default it's tools/project_generator (2 folders deep from root) PROJECT_ROOT= os.path.join('..','..') if os.name == "posix": # Expects either arm-none-eabi to be installed here, or # even better, a symlink from /usr/local/arm-none-eabi to the most recent # version. gcc_bin_path = "/usr/local/arm-none-eabi/bin/" elif os.name == "nt": gcc_bin_path = "" try: from user_settings import * except: logging.info("Using default settings.")
# ... existing code ... except: logging.info("Using default settings.") # ... rest of the code ...
8c01b3536026d56abb42daaf9d300e53e7c6dc18
detox/main.py
detox/main.py
import sys import py import detox from detox.proc import Detox def parse(args): from tox.session import prepare return prepare(args) def main(args=None): if args is None: args = sys.argv[1:] config = parse(args) #now = py.std.time.time() detox = Detox(config) detox.startloopreport() retcode = detox.runtestsmulti(config.envlist) #elapsed = py.std.time.time() - now #cumulated = detox.toxsession.report.cumulated_time #detox.toxsession.report.line( # "detox speed-up: %.2f (elapsed %.2f, cumulated %.2f)" % ( # cumulated / elapsed, elapsed, cumulated), bold=True) return retcode
import sys import py import detox from detox.proc import Detox def parse(args): from tox.session import prepare return prepare(args) def main(args=None): if args is None: args = sys.argv[1:] config = parse(args) #now = py.std.time.time() detox = Detox(config) detox.startloopreport() retcode = detox.runtestsmulti(config.envlist) #elapsed = py.std.time.time() - now #cumulated = detox.toxsession.report.cumulated_time #detox.toxsession.report.line( # "detox speed-up: %.2f (elapsed %.2f, cumulated %.2f)" % ( # cumulated / elapsed, elapsed, cumulated), bold=True) raise SystemExit(retcode)
Raise system code on exit from `python -m detox`
Raise system code on exit from `python -m detox`
Python
mit
tox-dev/detox
import sys import py import detox from detox.proc import Detox def parse(args): from tox.session import prepare return prepare(args) def main(args=None): if args is None: args = sys.argv[1:] config = parse(args) #now = py.std.time.time() detox = Detox(config) detox.startloopreport() retcode = detox.runtestsmulti(config.envlist) #elapsed = py.std.time.time() - now #cumulated = detox.toxsession.report.cumulated_time #detox.toxsession.report.line( # "detox speed-up: %.2f (elapsed %.2f, cumulated %.2f)" % ( # cumulated / elapsed, elapsed, cumulated), bold=True) - return retcode + raise SystemExit(retcode)
Raise system code on exit from `python -m detox`
## Code Before: import sys import py import detox from detox.proc import Detox def parse(args): from tox.session import prepare return prepare(args) def main(args=None): if args is None: args = sys.argv[1:] config = parse(args) #now = py.std.time.time() detox = Detox(config) detox.startloopreport() retcode = detox.runtestsmulti(config.envlist) #elapsed = py.std.time.time() - now #cumulated = detox.toxsession.report.cumulated_time #detox.toxsession.report.line( # "detox speed-up: %.2f (elapsed %.2f, cumulated %.2f)" % ( # cumulated / elapsed, elapsed, cumulated), bold=True) return retcode ## Instruction: Raise system code on exit from `python -m detox` ## Code After: import sys import py import detox from detox.proc import Detox def parse(args): from tox.session import prepare return prepare(args) def main(args=None): if args is None: args = sys.argv[1:] config = parse(args) #now = py.std.time.time() detox = Detox(config) detox.startloopreport() retcode = detox.runtestsmulti(config.envlist) #elapsed = py.std.time.time() - now #cumulated = detox.toxsession.report.cumulated_time #detox.toxsession.report.line( # "detox speed-up: %.2f (elapsed %.2f, cumulated %.2f)" % ( # cumulated / elapsed, elapsed, cumulated), bold=True) raise SystemExit(retcode)
... # cumulated / elapsed, elapsed, cumulated), bold=True) raise SystemExit(retcode) ...
0a718ccee8301f28e86791e06159e6ed8a2674b4
twobuntu/articles/forms.py
twobuntu/articles/forms.py
from django import forms from twobuntu.articles.models import Article, ScheduledArticle class EditorForm(forms.ModelForm): """ Form for entering or editing articles. """ class Meta: model = Article fields = ('category', 'title', 'body') class ScheduledArticleForm(forms.ModelForm): """ Form for scheduling articles. """ class Meta: model = ScheduledArticle fields = ('date',) class DeleteArticleForm(forms.Form): """ Form for deleting articles. """ # Intentionally blank - submitting the form # is considered consent to delete the article.
from django import forms from twobuntu.articles.models import Article, ScheduledArticle class EditorForm(forms.ModelForm): """ Form for entering or editing articles. """ # The <textarea> needs this set so that the form can validate on the client # side without any content (due to ACE editor) use_required_attribute = False class Meta: model = Article fields = ('category', 'title', 'body') class ScheduledArticleForm(forms.ModelForm): """ Form for scheduling articles. """ class Meta: model = ScheduledArticle fields = ('date',) class DeleteArticleForm(forms.Form): """ Form for deleting articles. """ # Intentionally blank - submitting the form # is considered consent to delete the article.
Fix error submitting article caused by extra HTML attribute.
Fix error submitting article caused by extra HTML attribute.
Python
apache-2.0
2buntu/2buntu-blog,2buntu/2buntu-blog,2buntu/2buntu-blog
from django import forms from twobuntu.articles.models import Article, ScheduledArticle class EditorForm(forms.ModelForm): """ Form for entering or editing articles. """ + + # The <textarea> needs this set so that the form can validate on the client + # side without any content (due to ACE editor) + use_required_attribute = False class Meta: model = Article fields = ('category', 'title', 'body') class ScheduledArticleForm(forms.ModelForm): """ Form for scheduling articles. """ class Meta: model = ScheduledArticle fields = ('date',) class DeleteArticleForm(forms.Form): """ Form for deleting articles. """ # Intentionally blank - submitting the form # is considered consent to delete the article.
Fix error submitting article caused by extra HTML attribute.
## Code Before: from django import forms from twobuntu.articles.models import Article, ScheduledArticle class EditorForm(forms.ModelForm): """ Form for entering or editing articles. """ class Meta: model = Article fields = ('category', 'title', 'body') class ScheduledArticleForm(forms.ModelForm): """ Form for scheduling articles. """ class Meta: model = ScheduledArticle fields = ('date',) class DeleteArticleForm(forms.Form): """ Form for deleting articles. """ # Intentionally blank - submitting the form # is considered consent to delete the article. ## Instruction: Fix error submitting article caused by extra HTML attribute. ## Code After: from django import forms from twobuntu.articles.models import Article, ScheduledArticle class EditorForm(forms.ModelForm): """ Form for entering or editing articles. """ # The <textarea> needs this set so that the form can validate on the client # side without any content (due to ACE editor) use_required_attribute = False class Meta: model = Article fields = ('category', 'title', 'body') class ScheduledArticleForm(forms.ModelForm): """ Form for scheduling articles. """ class Meta: model = ScheduledArticle fields = ('date',) class DeleteArticleForm(forms.Form): """ Form for deleting articles. """ # Intentionally blank - submitting the form # is considered consent to delete the article.
# ... existing code ... """ # The <textarea> needs this set so that the form can validate on the client # side without any content (due to ACE editor) use_required_attribute = False # ... rest of the code ...
4bbfdfc63cdfa0a6f54b09683033f23a71115547
src/pyws/protocols/rest.py
src/pyws/protocols/rest.py
from functools import partial from pyws.errors import BadRequest from pyws.functions.args.types.complex import List from pyws.response import Response from pyws.utils import json from pyws.protocols.base import Protocol __all__ = ('RestProtocol', 'JsonProtocol', ) create_response = partial(Response, content_type='application/json') create_error_response = partial(create_response, status=Response.STATUS_ERROR) class RestProtocol(Protocol): name = 'rest' def get_function(self, request): return request.tail def get_arguments(self, request, arguments): result = {} for field in arguments.fields: value = request.GET.get(field.name) if issubclass(field.type, List): result[field.name] = value elif field.name in request.GET: result[field.name] = value[0] return result def get_response(self, result, name, return_type): return create_response(json.dumps({'result': result})) def get_error_response(self, error): return create_error_response( json.dumps({'error': self.get_error(error)})) class JsonProtocol(RestProtocol): name = 'json' def get_arguments(self, request, arguments): try: return json.loads(request.text) except ValueError: raise BadRequest()
from functools import partial from pyws.errors import BadRequest from pyws.functions.args.types.complex import List from pyws.response import Response from pyws.utils import json class encoder( json.JSONEncoder ): # JSON Serializer with datetime support def default(self,obj): if isinstance(obj, datetime.datetime): return obj.isoformat() return json.JSONEncoder.default( self,obj) from pyws.protocols.base import Protocol __all__ = ('RestProtocol', 'JsonProtocol', ) create_response = partial(Response, content_type='application/json') create_error_response = partial(create_response, status=Response.STATUS_ERROR) class RestProtocol(Protocol): name = 'rest' def get_function(self, request): return request.tail def get_arguments(self, request, arguments): result = {} for field in arguments.fields: value = request.GET.get(field.name) if issubclass(field.type, List): result[field.name] = value elif field.name in request.GET: result[field.name] = value[0] return result def get_response(self, result, name, return_type): return create_response(json.dumps({'result': result},cls=encoder)) def get_error_response(self, error): return create_error_response( json.dumps({'error': self.get_error(error)})) class JsonProtocol(RestProtocol): name = 'json' def get_arguments(self, request, arguments): try: return json.loads(request.text) except ValueError: raise BadRequest()
Add custom JSON serialize for Python datetime
Add custom JSON serialize for Python datetime This adds a custom JSON serializer class which stringifies Python datetime objects in to ISO 8601. JSON does not specify a date/time format, and many parsers break trying to parse a Date() javascript object. 8601 seems a resonable compromise.
Python
mit
stepank/pyws,stepank/pyws,stepank/pyws,stepank/pyws,stepank/pyws
from functools import partial from pyws.errors import BadRequest from pyws.functions.args.types.complex import List from pyws.response import Response from pyws.utils import json + class encoder( json.JSONEncoder ): + # JSON Serializer with datetime support + def default(self,obj): + if isinstance(obj, datetime.datetime): + return obj.isoformat() + return json.JSONEncoder.default( self,obj) + from pyws.protocols.base import Protocol __all__ = ('RestProtocol', 'JsonProtocol', ) create_response = partial(Response, content_type='application/json') create_error_response = partial(create_response, status=Response.STATUS_ERROR) class RestProtocol(Protocol): name = 'rest' def get_function(self, request): return request.tail def get_arguments(self, request, arguments): result = {} for field in arguments.fields: value = request.GET.get(field.name) if issubclass(field.type, List): result[field.name] = value elif field.name in request.GET: result[field.name] = value[0] return result def get_response(self, result, name, return_type): - return create_response(json.dumps({'result': result})) + return create_response(json.dumps({'result': result},cls=encoder)) def get_error_response(self, error): return create_error_response( json.dumps({'error': self.get_error(error)})) class JsonProtocol(RestProtocol): name = 'json' def get_arguments(self, request, arguments): try: return json.loads(request.text) except ValueError: raise BadRequest()
Add custom JSON serialize for Python datetime
## Code Before: from functools import partial from pyws.errors import BadRequest from pyws.functions.args.types.complex import List from pyws.response import Response from pyws.utils import json from pyws.protocols.base import Protocol __all__ = ('RestProtocol', 'JsonProtocol', ) create_response = partial(Response, content_type='application/json') create_error_response = partial(create_response, status=Response.STATUS_ERROR) class RestProtocol(Protocol): name = 'rest' def get_function(self, request): return request.tail def get_arguments(self, request, arguments): result = {} for field in arguments.fields: value = request.GET.get(field.name) if issubclass(field.type, List): result[field.name] = value elif field.name in request.GET: result[field.name] = value[0] return result def get_response(self, result, name, return_type): return create_response(json.dumps({'result': result})) def get_error_response(self, error): return create_error_response( json.dumps({'error': self.get_error(error)})) class JsonProtocol(RestProtocol): name = 'json' def get_arguments(self, request, arguments): try: return json.loads(request.text) except ValueError: raise BadRequest() ## Instruction: Add custom JSON serialize for Python datetime ## Code After: from functools import partial from pyws.errors import BadRequest from pyws.functions.args.types.complex import List from pyws.response import Response from pyws.utils import json class encoder( json.JSONEncoder ): # JSON Serializer with datetime support def default(self,obj): if isinstance(obj, datetime.datetime): return obj.isoformat() return json.JSONEncoder.default( self,obj) from pyws.protocols.base import Protocol __all__ = ('RestProtocol', 'JsonProtocol', ) create_response = partial(Response, content_type='application/json') create_error_response = partial(create_response, status=Response.STATUS_ERROR) class RestProtocol(Protocol): name = 'rest' def get_function(self, request): return request.tail def get_arguments(self, request, arguments): result = {} for field in arguments.fields: value = request.GET.get(field.name) if issubclass(field.type, List): result[field.name] = value elif field.name in request.GET: result[field.name] = value[0] return result def get_response(self, result, name, return_type): return create_response(json.dumps({'result': result},cls=encoder)) def get_error_response(self, error): return create_error_response( json.dumps({'error': self.get_error(error)})) class JsonProtocol(RestProtocol): name = 'json' def get_arguments(self, request, arguments): try: return json.loads(request.text) except ValueError: raise BadRequest()
# ... existing code ... class encoder( json.JSONEncoder ): # JSON Serializer with datetime support def default(self,obj): if isinstance(obj, datetime.datetime): return obj.isoformat() return json.JSONEncoder.default( self,obj) from pyws.protocols.base import Protocol # ... modified code ... def get_response(self, result, name, return_type): return create_response(json.dumps({'result': result},cls=encoder)) # ... rest of the code ...
7a78525bb8cc6176dfbe348e5f95373c1d70628f
functions.py
functions.py
def getClientIP( req ): ''' Get the client ip address ''' xForwardedFor=req.META.get('HTTP_X_FORWARDED_FOR') if xForwardedFor: ip=xForwardedFor.split(',')[0] else: ip=req.META.get('REMOTE_ADDR') return ip def getBool( val, trueOpts=['YES', 'Y', '1', 'TRUE', 'T'] ): ''' Retrieve the boolean value from string ''' if val: return str(val).upper() in trueOpts return False
def getClientIP( req ): ''' Get the client ip address @param req The request; ''' xForwardedFor=req.META.get('HTTP_X_FORWARDED_FOR') if xForwardedFor: ip=xForwardedFor.split(',')[0] else: ip=req.META.get('REMOTE_ADDR') return ip def getBool( val, defVal=False, trueOpts=['YES', 'Y', '1', 'TRUE', 'T'] ): ''' Retrieve the boolean value from string @param val The value to be parse to bool @param defVal The default value if the val is None @param trueOpts The available values of TRUE ''' if val: return str(val).upper() in trueOpts return defVal def checkRecaptcha( req, secret, simple=True ): ''' Checking the recaptcha and return the result. @param req The request; @param secret The secret retreived from Google reCaptcha registration; @param simple Retrue the simple boolean value of verification if True, otherwise, return the JSON value of verification; ''' import requests apiurl='https://www.google.com/recaptcha/api/siteverify' fieldname='g-recaptcha-response' answer=req.POST.get(fieldname, None) clientIP=getClientIP( req ) rst=requests.post(apiurl, data={'secret': secret, 'response':answer, 'remoteip': clientIP}).json() if simple: return getBool(rst.get('success', 'False')) return r.json()
Add the checkRecaptcha( req, secret, simple=True ) function
Add the checkRecaptcha( req, secret, simple=True ) function
Python
apache-2.0
kensonman/webframe,kensonman/webframe,kensonman/webframe
def getClientIP( req ): ''' Get the client ip address + + @param req The request; ''' xForwardedFor=req.META.get('HTTP_X_FORWARDED_FOR') if xForwardedFor: ip=xForwardedFor.split(',')[0] else: ip=req.META.get('REMOTE_ADDR') return ip - def getBool( val, trueOpts=['YES', 'Y', '1', 'TRUE', 'T'] ): + def getBool( val, defVal=False, trueOpts=['YES', 'Y', '1', 'TRUE', 'T'] ): ''' Retrieve the boolean value from string + + @param val The value to be parse to bool + @param defVal The default value if the val is None + @param trueOpts The available values of TRUE ''' if val: return str(val).upper() in trueOpts - return False + return defVal + def checkRecaptcha( req, secret, simple=True ): + ''' + Checking the recaptcha and return the result. + + @param req The request; + @param secret The secret retreived from Google reCaptcha registration; + @param simple Retrue the simple boolean value of verification if True, otherwise, return the JSON value of verification; + ''' + import requests + apiurl='https://www.google.com/recaptcha/api/siteverify' + fieldname='g-recaptcha-response' + + answer=req.POST.get(fieldname, None) + clientIP=getClientIP( req ) + rst=requests.post(apiurl, data={'secret': secret, 'response':answer, 'remoteip': clientIP}).json() + if simple: + return getBool(rst.get('success', 'False')) + return r.json() + +
Add the checkRecaptcha( req, secret, simple=True ) function
## Code Before: def getClientIP( req ): ''' Get the client ip address ''' xForwardedFor=req.META.get('HTTP_X_FORWARDED_FOR') if xForwardedFor: ip=xForwardedFor.split(',')[0] else: ip=req.META.get('REMOTE_ADDR') return ip def getBool( val, trueOpts=['YES', 'Y', '1', 'TRUE', 'T'] ): ''' Retrieve the boolean value from string ''' if val: return str(val).upper() in trueOpts return False ## Instruction: Add the checkRecaptcha( req, secret, simple=True ) function ## Code After: def getClientIP( req ): ''' Get the client ip address @param req The request; ''' xForwardedFor=req.META.get('HTTP_X_FORWARDED_FOR') if xForwardedFor: ip=xForwardedFor.split(',')[0] else: ip=req.META.get('REMOTE_ADDR') return ip def getBool( val, defVal=False, trueOpts=['YES', 'Y', '1', 'TRUE', 'T'] ): ''' Retrieve the boolean value from string @param val The value to be parse to bool @param defVal The default value if the val is None @param trueOpts The available values of TRUE ''' if val: return str(val).upper() in trueOpts return defVal def checkRecaptcha( req, secret, simple=True ): ''' Checking the recaptcha and return the result. @param req The request; @param secret The secret retreived from Google reCaptcha registration; @param simple Retrue the simple boolean value of verification if True, otherwise, return the JSON value of verification; ''' import requests apiurl='https://www.google.com/recaptcha/api/siteverify' fieldname='g-recaptcha-response' answer=req.POST.get(fieldname, None) clientIP=getClientIP( req ) rst=requests.post(apiurl, data={'secret': secret, 'response':answer, 'remoteip': clientIP}).json() if simple: return getBool(rst.get('success', 'False')) return r.json()
# ... existing code ... Get the client ip address @param req The request; ''' # ... modified code ... def getBool( val, defVal=False, trueOpts=['YES', 'Y', '1', 'TRUE', 'T'] ): ''' ... Retrieve the boolean value from string @param val The value to be parse to bool @param defVal The default value if the val is None @param trueOpts The available values of TRUE ''' ... return str(val).upper() in trueOpts return defVal def checkRecaptcha( req, secret, simple=True ): ''' Checking the recaptcha and return the result. @param req The request; @param secret The secret retreived from Google reCaptcha registration; @param simple Retrue the simple boolean value of verification if True, otherwise, return the JSON value of verification; ''' import requests apiurl='https://www.google.com/recaptcha/api/siteverify' fieldname='g-recaptcha-response' answer=req.POST.get(fieldname, None) clientIP=getClientIP( req ) rst=requests.post(apiurl, data={'secret': secret, 'response':answer, 'remoteip': clientIP}).json() if simple: return getBool(rst.get('success', 'False')) return r.json() # ... rest of the code ...
0bdc48ce94a8c501dba1ce2925615714a46a1728
pygameMidi_extended.py
pygameMidi_extended.py
from pygame.midi import Output class Output(Output):#pygame.midi.Output): def set_pan(self, pan, channel): assert (0 <= channel <= 15) assert pan <= 127 self.write_short(0xB0 + channel, 0x0A, pan) def set_volume(self, volume, channel): assert (0 <= channel <= 15) assert volume <= 127 self.write_short(0xB0 + channel, 0x07, volume) def set_pitch(self, pitch, channel): assert (0 <= channel <= 15) assert pitch <= (2**14-1) # the 7 least significant bits come into the first data byte, # the 7 most significant bits come into the second data byte pitch_lsb = (pitch >> 7) & 127 pitch_msb = pitch & 127 self.write_short(0xE0 + channel, pitch_lsb, pitch_msb)
from pygame.midi import Output class Output(Output):#pygame.midi.Output): def set_pan(self, pan, channel): assert (0 <= channel <= 15) assert pan <= 127 self.write_short(0xB0 + channel, 0x0A, pan) def set_volume(self, volume, channel): assert (0 <= channel <= 15) assert volume <= 127 self.write_short(0xB0 + channel, 0x07, volume) def set_pitch(self, pitch, channel): assert (0 <= channel <= 15) assert pitch <= (2**14-1) # the 7 least significant bits come into the first data byte, # the 7 most significant bits come into the second data byte pitch_lsb = (pitch >> 7) & 127 pitch_msb = pitch & 127 self.write_short(0xE0 + channel, pitch_lsb, pitch_msb) def set_instrument_bank(self, bank, channel): assert (0 <= channel <= 15) assert bank <= 127 self.write_short(0xB0 + channel, 0x00, bank)
Add method for instrument bank
Add method for instrument bank
Python
bsd-3-clause
RenolY2/py-playBMS
from pygame.midi import Output class Output(Output):#pygame.midi.Output): def set_pan(self, pan, channel): assert (0 <= channel <= 15) assert pan <= 127 self.write_short(0xB0 + channel, 0x0A, pan) def set_volume(self, volume, channel): assert (0 <= channel <= 15) assert volume <= 127 self.write_short(0xB0 + channel, 0x07, volume) def set_pitch(self, pitch, channel): assert (0 <= channel <= 15) assert pitch <= (2**14-1) # the 7 least significant bits come into the first data byte, # the 7 most significant bits come into the second data byte pitch_lsb = (pitch >> 7) & 127 pitch_msb = pitch & 127 self.write_short(0xE0 + channel, pitch_lsb, pitch_msb) + + def set_instrument_bank(self, bank, channel): + assert (0 <= channel <= 15) + assert bank <= 127 + + self.write_short(0xB0 + channel, 0x00, bank)
Add method for instrument bank
## Code Before: from pygame.midi import Output class Output(Output):#pygame.midi.Output): def set_pan(self, pan, channel): assert (0 <= channel <= 15) assert pan <= 127 self.write_short(0xB0 + channel, 0x0A, pan) def set_volume(self, volume, channel): assert (0 <= channel <= 15) assert volume <= 127 self.write_short(0xB0 + channel, 0x07, volume) def set_pitch(self, pitch, channel): assert (0 <= channel <= 15) assert pitch <= (2**14-1) # the 7 least significant bits come into the first data byte, # the 7 most significant bits come into the second data byte pitch_lsb = (pitch >> 7) & 127 pitch_msb = pitch & 127 self.write_short(0xE0 + channel, pitch_lsb, pitch_msb) ## Instruction: Add method for instrument bank ## Code After: from pygame.midi import Output class Output(Output):#pygame.midi.Output): def set_pan(self, pan, channel): assert (0 <= channel <= 15) assert pan <= 127 self.write_short(0xB0 + channel, 0x0A, pan) def set_volume(self, volume, channel): assert (0 <= channel <= 15) assert volume <= 127 self.write_short(0xB0 + channel, 0x07, volume) def set_pitch(self, pitch, channel): assert (0 <= channel <= 15) assert pitch <= (2**14-1) # the 7 least significant bits come into the first data byte, # the 7 most significant bits come into the second data byte pitch_lsb = (pitch >> 7) & 127 pitch_msb = pitch & 127 self.write_short(0xE0 + channel, pitch_lsb, pitch_msb) def set_instrument_bank(self, bank, channel): assert (0 <= channel <= 15) assert bank <= 127 self.write_short(0xB0 + channel, 0x00, bank)
... self.write_short(0xE0 + channel, pitch_lsb, pitch_msb) def set_instrument_bank(self, bank, channel): assert (0 <= channel <= 15) assert bank <= 127 self.write_short(0xB0 + channel, 0x00, bank) ...
f17611b39c9cc3ec6815093db2eb85cb6b30b5ba
lwr/lwr_client/transport/standard.py
lwr/lwr_client/transport/standard.py
from __future__ import with_statement from os.path import getsize import mmap try: from urllib2 import urlopen except ImportError: from urllib.request import urlopen try: from urllib2 import Request except ImportError: from urllib.request import Request class Urllib2Transport(object): def _url_open(self, request, data): return urlopen(request, data) def execute(self, url, data=None, input_path=None, output_path=None): request = Request(url=url, data=data) input = None try: if input_path: input = open(input_path, 'rb') if getsize(input_path): input = open(input_path, 'rb') data = mmap.mmap(input.fileno(), 0, access=mmap.ACCESS_READ) else: data = b"" response = self._url_open(request, data) finally: if input: input.close() if output_path: with open(output_path, 'wb') as output: while True: buffer = response.read(1024) if not buffer: break output.write(buffer) return response else: return response.read()
from __future__ import with_statement from os.path import getsize import mmap try: from urllib2 import urlopen except ImportError: from urllib.request import urlopen try: from urllib2 import Request except ImportError: from urllib.request import Request class Urllib2Transport(object): def _url_open(self, request, data): return urlopen(request, data) def execute(self, url, data=None, input_path=None, output_path=None): request = Request(url=url, data=data) input = None try: if input_path: if getsize(input_path): input = open(input_path, 'rb') data = mmap.mmap(input.fileno(), 0, access=mmap.ACCESS_READ) else: data = b"" response = self._url_open(request, data) finally: if input: input.close() if output_path: with open(output_path, 'wb') as output: while True: buffer = response.read(1024) if not buffer: break output.write(buffer) return response else: return response.read()
Fix small bug introduced in 0b8e5d428e60.
Fix small bug introduced in 0b8e5d428e60. Opening file twice.
Python
apache-2.0
jmchilton/pulsar,natefoo/pulsar,ssorgatem/pulsar,jmchilton/lwr,galaxyproject/pulsar,jmchilton/pulsar,ssorgatem/pulsar,galaxyproject/pulsar,natefoo/pulsar,jmchilton/lwr
from __future__ import with_statement from os.path import getsize import mmap try: from urllib2 import urlopen except ImportError: from urllib.request import urlopen try: from urllib2 import Request except ImportError: from urllib.request import Request class Urllib2Transport(object): def _url_open(self, request, data): return urlopen(request, data) def execute(self, url, data=None, input_path=None, output_path=None): request = Request(url=url, data=data) input = None try: if input_path: - input = open(input_path, 'rb') if getsize(input_path): input = open(input_path, 'rb') data = mmap.mmap(input.fileno(), 0, access=mmap.ACCESS_READ) else: data = b"" response = self._url_open(request, data) finally: if input: input.close() if output_path: with open(output_path, 'wb') as output: while True: buffer = response.read(1024) if not buffer: break output.write(buffer) return response else: return response.read()
Fix small bug introduced in 0b8e5d428e60.
## Code Before: from __future__ import with_statement from os.path import getsize import mmap try: from urllib2 import urlopen except ImportError: from urllib.request import urlopen try: from urllib2 import Request except ImportError: from urllib.request import Request class Urllib2Transport(object): def _url_open(self, request, data): return urlopen(request, data) def execute(self, url, data=None, input_path=None, output_path=None): request = Request(url=url, data=data) input = None try: if input_path: input = open(input_path, 'rb') if getsize(input_path): input = open(input_path, 'rb') data = mmap.mmap(input.fileno(), 0, access=mmap.ACCESS_READ) else: data = b"" response = self._url_open(request, data) finally: if input: input.close() if output_path: with open(output_path, 'wb') as output: while True: buffer = response.read(1024) if not buffer: break output.write(buffer) return response else: return response.read() ## Instruction: Fix small bug introduced in 0b8e5d428e60. ## Code After: from __future__ import with_statement from os.path import getsize import mmap try: from urllib2 import urlopen except ImportError: from urllib.request import urlopen try: from urllib2 import Request except ImportError: from urllib.request import Request class Urllib2Transport(object): def _url_open(self, request, data): return urlopen(request, data) def execute(self, url, data=None, input_path=None, output_path=None): request = Request(url=url, data=data) input = None try: if input_path: if getsize(input_path): input = open(input_path, 'rb') data = mmap.mmap(input.fileno(), 0, access=mmap.ACCESS_READ) else: data = b"" response = self._url_open(request, data) finally: if input: input.close() if output_path: with open(output_path, 'wb') as output: while True: buffer = response.read(1024) if not buffer: break output.write(buffer) return response else: return response.read()
// ... existing code ... if input_path: if getsize(input_path): // ... rest of the code ...
36e8b7f7dd4de93c61f49d65106f2a0410945e2d
pyoracc/model/line.py
pyoracc/model/line.py
from mako.template import Template class Line(object): template = Template("""${label}. \\ % for word in words: ${word} \\ % endfor % if lemmas: \n#lem: \\ % for lemma in lemmas: ${lemma}; \\ % endfor \n %endif """, output_encoding='utf-8') def __init__(self, label): self.label = label self.words = [] self.lemmas = [] self.witnesses = [] self.translation = None self.notes = [] self.references = [] self.links = [] def __str__(self): return self.template.render_unicode(**vars(self)) def serialize(self): return self.template.render_unicode(**vars(self))
from mako.template import Template class Line(object): template = Template("""\n${label}.\t\\ ${' '.join(words)}\\ % if references: % for reference in references: ^${reference}^ % endfor % endif % if lemmas: \n#lem:\\ ${'; '.join(lemmas)}\\ % endif % if notes: \n % for note in notes: ${note.serialize()} % endfor % endif % if links: \n#link: \\ % for link in links: ${link}; % endfor % endif """, output_encoding='utf-8') def __init__(self, label): self.label = label self.words = [] self.lemmas = [] self.witnesses = [] self.translation = None self.notes = [] self.references = [] self.links = [] def __str__(self): return self.template.render_unicode(**vars(self)) def serialize(self): return self.template.render_unicode(**vars(self))
Use join for serializing words and lemmas to avoid printing last ; as required by ATF format. Print also references, notes and links.
Use join for serializing words and lemmas to avoid printing last ; as required by ATF format. Print also references, notes and links.
Python
mit
UCL/pyoracc
from mako.template import Template class Line(object): - template = Template("""${label}. \\ + template = Template("""\n${label}.\t\\ - % for word in words: - ${word} \\ + ${' '.join(words)}\\ + % if references: + % for reference in references: + ^${reference}^ - % endfor + % endfor + % endif % if lemmas: - \n#lem: \\ + \n#lem:\\ + ${'; '.join(lemmas)}\\ - % for lemma in lemmas: - ${lemma}; \\ - % endfor \n - %endif + % endif + % if notes: + \n + % for note in notes: + ${note.serialize()} + % endfor + % endif + % if links: + \n#link: \\ + % for link in links: + ${link}; + % endfor + % endif """, output_encoding='utf-8') def __init__(self, label): self.label = label self.words = [] self.lemmas = [] self.witnesses = [] self.translation = None self.notes = [] self.references = [] self.links = [] def __str__(self): return self.template.render_unicode(**vars(self)) def serialize(self): return self.template.render_unicode(**vars(self))
Use join for serializing words and lemmas to avoid printing last ; as required by ATF format. Print also references, notes and links.
## Code Before: from mako.template import Template class Line(object): template = Template("""${label}. \\ % for word in words: ${word} \\ % endfor % if lemmas: \n#lem: \\ % for lemma in lemmas: ${lemma}; \\ % endfor \n %endif """, output_encoding='utf-8') def __init__(self, label): self.label = label self.words = [] self.lemmas = [] self.witnesses = [] self.translation = None self.notes = [] self.references = [] self.links = [] def __str__(self): return self.template.render_unicode(**vars(self)) def serialize(self): return self.template.render_unicode(**vars(self)) ## Instruction: Use join for serializing words and lemmas to avoid printing last ; as required by ATF format. Print also references, notes and links. ## Code After: from mako.template import Template class Line(object): template = Template("""\n${label}.\t\\ ${' '.join(words)}\\ % if references: % for reference in references: ^${reference}^ % endfor % endif % if lemmas: \n#lem:\\ ${'; '.join(lemmas)}\\ % endif % if notes: \n % for note in notes: ${note.serialize()} % endfor % endif % if links: \n#link: \\ % for link in links: ${link}; % endfor % endif """, output_encoding='utf-8') def __init__(self, label): self.label = label self.words = [] self.lemmas = [] self.witnesses = [] self.translation = None self.notes = [] self.references = [] self.links = [] def __str__(self): return self.template.render_unicode(**vars(self)) def serialize(self): return self.template.render_unicode(**vars(self))
... class Line(object): template = Template("""\n${label}.\t\\ ${' '.join(words)}\\ % if references: % for reference in references: ^${reference}^ % endfor % endif % if lemmas: \n#lem:\\ ${'; '.join(lemmas)}\\ % endif % if notes: \n % for note in notes: ${note.serialize()} % endfor % endif % if links: \n#link: \\ % for link in links: ${link}; % endfor % endif """, output_encoding='utf-8') ...
0cab34e5f87b4484e0309aba8860d651afe06fb0
app/__init__.py
app/__init__.py
from flask import Flask, request, redirect from flask.ext.bootstrap import Bootstrap from config import configs from dmutils import apiclient, init_app, flask_featureflags from dmutils.content_loader import ContentLoader bootstrap = Bootstrap() data_api_client = apiclient.DataAPIClient() search_api_client = apiclient.SearchAPIClient() feature_flags = flask_featureflags.FeatureFlag() def create_app(config_name): application = Flask(__name__) init_app( application, configs[config_name], bootstrap=bootstrap, data_api_client=data_api_client, feature_flags=feature_flags, search_api_client=search_api_client ) questions_builder = ContentLoader( "app/helpers/questions_manifest.yml", "app/content/g6/" ).get_builder() from .main import main as main_blueprint from .status import status as status_blueprint application.register_blueprint(status_blueprint) application.register_blueprint(main_blueprint) main_blueprint.config = { 'BASE_TEMPLATE_DATA': application.config['BASE_TEMPLATE_DATA'], 'QUESTIONS_BUILDER': questions_builder } @application.before_request def remove_trailing_slash(): if request.path != '/' and request.path.endswith('/'): if request.query_string: return redirect( '{}?{}'.format( request.path[:-1], request.query_string.decode('utf-8') ), code=301 ) else: return redirect(request.path[:-1], code=301) return application
from flask import Flask, request, redirect from flask.ext.bootstrap import Bootstrap from config import configs from dmutils import apiclient, init_app, flask_featureflags from dmutils.content_loader import ContentLoader bootstrap = Bootstrap() data_api_client = apiclient.DataAPIClient() search_api_client = apiclient.SearchAPIClient() feature_flags = flask_featureflags.FeatureFlag() questions_loader = ContentLoader( "app/helpers/questions_manifest.yml", "app/content/g6/" ) def create_app(config_name): application = Flask(__name__) init_app( application, configs[config_name], bootstrap=bootstrap, data_api_client=data_api_client, feature_flags=feature_flags, search_api_client=search_api_client ) from .main import main as main_blueprint from .status import status as status_blueprint application.register_blueprint(status_blueprint) application.register_blueprint(main_blueprint) main_blueprint.config = { 'BASE_TEMPLATE_DATA': application.config['BASE_TEMPLATE_DATA'], } @application.before_request def remove_trailing_slash(): if request.path != '/' and request.path.endswith('/'): if request.query_string: return redirect( '{}?{}'.format( request.path[:-1], request.query_string.decode('utf-8') ), code=301 ) else: return redirect(request.path[:-1], code=301) return application
Move QUESTIONS_BUILDER from blueprint to a global variable
Move QUESTIONS_BUILDER from blueprint to a global variable
Python
mit
mtekel/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,mtekel/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,mtekel/digitalmarketplace-buyer-frontend,mtekel/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend
from flask import Flask, request, redirect from flask.ext.bootstrap import Bootstrap from config import configs from dmutils import apiclient, init_app, flask_featureflags from dmutils.content_loader import ContentLoader bootstrap = Bootstrap() data_api_client = apiclient.DataAPIClient() search_api_client = apiclient.SearchAPIClient() feature_flags = flask_featureflags.FeatureFlag() + + questions_loader = ContentLoader( + "app/helpers/questions_manifest.yml", + "app/content/g6/" + ) def create_app(config_name): application = Flask(__name__) init_app( application, configs[config_name], bootstrap=bootstrap, data_api_client=data_api_client, feature_flags=feature_flags, search_api_client=search_api_client ) - questions_builder = ContentLoader( - "app/helpers/questions_manifest.yml", - "app/content/g6/" - ).get_builder() - from .main import main as main_blueprint from .status import status as status_blueprint application.register_blueprint(status_blueprint) application.register_blueprint(main_blueprint) main_blueprint.config = { 'BASE_TEMPLATE_DATA': application.config['BASE_TEMPLATE_DATA'], - 'QUESTIONS_BUILDER': questions_builder } @application.before_request def remove_trailing_slash(): if request.path != '/' and request.path.endswith('/'): if request.query_string: return redirect( '{}?{}'.format( request.path[:-1], request.query_string.decode('utf-8') ), code=301 ) else: return redirect(request.path[:-1], code=301) return application
Move QUESTIONS_BUILDER from blueprint to a global variable
## Code Before: from flask import Flask, request, redirect from flask.ext.bootstrap import Bootstrap from config import configs from dmutils import apiclient, init_app, flask_featureflags from dmutils.content_loader import ContentLoader bootstrap = Bootstrap() data_api_client = apiclient.DataAPIClient() search_api_client = apiclient.SearchAPIClient() feature_flags = flask_featureflags.FeatureFlag() def create_app(config_name): application = Flask(__name__) init_app( application, configs[config_name], bootstrap=bootstrap, data_api_client=data_api_client, feature_flags=feature_flags, search_api_client=search_api_client ) questions_builder = ContentLoader( "app/helpers/questions_manifest.yml", "app/content/g6/" ).get_builder() from .main import main as main_blueprint from .status import status as status_blueprint application.register_blueprint(status_blueprint) application.register_blueprint(main_blueprint) main_blueprint.config = { 'BASE_TEMPLATE_DATA': application.config['BASE_TEMPLATE_DATA'], 'QUESTIONS_BUILDER': questions_builder } @application.before_request def remove_trailing_slash(): if request.path != '/' and request.path.endswith('/'): if request.query_string: return redirect( '{}?{}'.format( request.path[:-1], request.query_string.decode('utf-8') ), code=301 ) else: return redirect(request.path[:-1], code=301) return application ## Instruction: Move QUESTIONS_BUILDER from blueprint to a global variable ## Code After: from flask import Flask, request, redirect from flask.ext.bootstrap import Bootstrap from config import configs from dmutils import apiclient, init_app, flask_featureflags from dmutils.content_loader import ContentLoader bootstrap = Bootstrap() data_api_client = apiclient.DataAPIClient() search_api_client = apiclient.SearchAPIClient() feature_flags = flask_featureflags.FeatureFlag() questions_loader = ContentLoader( "app/helpers/questions_manifest.yml", "app/content/g6/" ) def create_app(config_name): application = Flask(__name__) init_app( application, configs[config_name], bootstrap=bootstrap, data_api_client=data_api_client, feature_flags=feature_flags, search_api_client=search_api_client ) from .main import main as main_blueprint from .status import status as status_blueprint application.register_blueprint(status_blueprint) application.register_blueprint(main_blueprint) main_blueprint.config = { 'BASE_TEMPLATE_DATA': application.config['BASE_TEMPLATE_DATA'], } @application.before_request def remove_trailing_slash(): if request.path != '/' and request.path.endswith('/'): if request.query_string: return redirect( '{}?{}'.format( request.path[:-1], request.query_string.decode('utf-8') ), code=301 ) else: return redirect(request.path[:-1], code=301) return application
// ... existing code ... feature_flags = flask_featureflags.FeatureFlag() questions_loader = ContentLoader( "app/helpers/questions_manifest.yml", "app/content/g6/" ) // ... modified code ... from .main import main as main_blueprint ... 'BASE_TEMPLATE_DATA': application.config['BASE_TEMPLATE_DATA'], } // ... rest of the code ...
83e83cdd90364e037530974e2cea977a05ac449b
pos_picking_state_fix/models/pos_picking.py
pos_picking_state_fix/models/pos_picking.py
import time from openerp import models, api from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT class PosPicking(models.Model): _inherit = 'pos.order' @api.multi def create_picking(self): try: super(PosPicking, self).create_picking() except: if self.picking_id.state != 'done': for move in self.picking_id.move_lines: if move.quant_ids: # We pass this move to done because the quants were already moved move.write({'state': 'done', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}) else: # If there are no moved quants we pass the move to Waiting Availability move.do_unreserve() return True
import time from openerp import models, api from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT class PosPicking(models.Model): _inherit = 'pos.order' @api.multi def create_picking(self): try: super(PosPicking, self).create_picking() except: pass if self.picking_id.state != 'done': for move in self.picking_id.move_lines: if move.quant_ids: # We pass this move to done because the quants were already moved move.write({'state': 'done', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}) else: # If there are no moved quants we pass the move to Waiting Availability move.do_unreserve() return True
Move code outside of exception
[FIX] Move code outside of exception
Python
agpl-3.0
rgbconsulting/rgb-pos,rgbconsulting/rgb-addons,rgbconsulting/rgb-pos,rgbconsulting/rgb-addons
import time from openerp import models, api from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT class PosPicking(models.Model): _inherit = 'pos.order' @api.multi def create_picking(self): try: super(PosPicking, self).create_picking() except: + pass + - if self.picking_id.state != 'done': + if self.picking_id.state != 'done': - for move in self.picking_id.move_lines: + for move in self.picking_id.move_lines: - if move.quant_ids: + if move.quant_ids: - # We pass this move to done because the quants were already moved + # We pass this move to done because the quants were already moved - move.write({'state': 'done', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}) + move.write({'state': 'done', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}) - else: + else: - # If there are no moved quants we pass the move to Waiting Availability + # If there are no moved quants we pass the move to Waiting Availability - move.do_unreserve() + move.do_unreserve() return True
Move code outside of exception
## Code Before: import time from openerp import models, api from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT class PosPicking(models.Model): _inherit = 'pos.order' @api.multi def create_picking(self): try: super(PosPicking, self).create_picking() except: if self.picking_id.state != 'done': for move in self.picking_id.move_lines: if move.quant_ids: # We pass this move to done because the quants were already moved move.write({'state': 'done', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}) else: # If there are no moved quants we pass the move to Waiting Availability move.do_unreserve() return True ## Instruction: Move code outside of exception ## Code After: import time from openerp import models, api from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT class PosPicking(models.Model): _inherit = 'pos.order' @api.multi def create_picking(self): try: super(PosPicking, self).create_picking() except: pass if self.picking_id.state != 'done': for move in self.picking_id.move_lines: if move.quant_ids: # We pass this move to done because the quants were already moved move.write({'state': 'done', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}) else: # If there are no moved quants we pass the move to Waiting Availability move.do_unreserve() return True
// ... existing code ... except: pass if self.picking_id.state != 'done': for move in self.picking_id.move_lines: if move.quant_ids: # We pass this move to done because the quants were already moved move.write({'state': 'done', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}) else: # If there are no moved quants we pass the move to Waiting Availability move.do_unreserve() return True // ... rest of the code ...
901a47adf6726d50c01ac743e9661c0caac2b555
test_openfolder.py
test_openfolder.py
import pytest from mock import patch, MagicMock from open_folder import * def test_folder_exists(): with patch('subprocess.check_call', MagicMock(return_value="NOOP")): result = open_folder(".") assert result == None def test_folder_does_not_exists(): with patch('subprocess.check_call', MagicMock(return_value="NOOP")): with pytest.raises(Exception): open_folder("it_is_very_unlikely_that_this_file_exists_20150718") def test_unsupported_os(): with patch('subprocess.check_call', MagicMock(return_value="NOOP")): with patch('platform.system', MagicMock(return_value="NotDarwinWindowsLinux")): with pytest.raises(Exception): result = open_folder("/") def test_supported_os(): with patch('subprocess.check_call', MagicMock(return_value="NOOP")): with patch('platform.system', MagicMock(return_value="Linux")): result = open_folder("/") assert result == None with patch('platform.system', MagicMock(return_value="Darwin")): result = open_folder("/") assert result == None with patch('platform.system', MagicMock(return_value="Windows")): result = open_folder("/") assert result == None
import pytest from mock import patch, MagicMock from open_folder import * def test_folder_exists(): with patch('subprocess.check_call', MagicMock(return_value="NOOP")): result = open_folder(".") assert result == None def test_folder_does_not_exists(): with patch('subprocess.check_call', MagicMock(return_value="NOOP")): with pytest.raises(Exception) as excinfo: open_folder("it_is_very_unlikely_that_this_file_exists_20150718") assert str(excinfo.value) == ('Folder does not exist.') def test_unsupported_os(): with patch('subprocess.check_call', MagicMock(return_value="NOOP")): with patch('platform.system', MagicMock(return_value="NotDarwinWindowsLinux")): with pytest.raises(Exception) as excinfo: open_folder("/") assert str(excinfo.value).startswith('Your operating system was not recognized.') def test_supported_os(): with patch('subprocess.check_call', MagicMock(return_value="NOOP")): with patch('platform.system', MagicMock(return_value="Linux")): result = open_folder("/") assert result == None with patch('platform.system', MagicMock(return_value="Darwin")): result = open_folder("/") assert result == None with patch('platform.system', MagicMock(return_value="Windows")): result = open_folder("/") assert result == None
Check to ensure the excpetions return the text we expect.
Check to ensure the excpetions return the text we expect.
Python
mit
golliher/dg-tickler-file
import pytest from mock import patch, MagicMock from open_folder import * def test_folder_exists(): with patch('subprocess.check_call', MagicMock(return_value="NOOP")): result = open_folder(".") assert result == None def test_folder_does_not_exists(): with patch('subprocess.check_call', MagicMock(return_value="NOOP")): - with pytest.raises(Exception): + with pytest.raises(Exception) as excinfo: open_folder("it_is_very_unlikely_that_this_file_exists_20150718") + assert str(excinfo.value) == ('Folder does not exist.') def test_unsupported_os(): with patch('subprocess.check_call', MagicMock(return_value="NOOP")): + with patch('platform.system', MagicMock(return_value="NotDarwinWindowsLinux")): - with pytest.raises(Exception): + with pytest.raises(Exception) as excinfo: - result = open_folder("/") + open_folder("/") + assert str(excinfo.value).startswith('Your operating system was not recognized.') def test_supported_os(): with patch('subprocess.check_call', MagicMock(return_value="NOOP")): with patch('platform.system', MagicMock(return_value="Linux")): result = open_folder("/") assert result == None with patch('platform.system', MagicMock(return_value="Darwin")): result = open_folder("/") assert result == None with patch('platform.system', MagicMock(return_value="Windows")): result = open_folder("/") assert result == None
Check to ensure the excpetions return the text we expect.
## Code Before: import pytest from mock import patch, MagicMock from open_folder import * def test_folder_exists(): with patch('subprocess.check_call', MagicMock(return_value="NOOP")): result = open_folder(".") assert result == None def test_folder_does_not_exists(): with patch('subprocess.check_call', MagicMock(return_value="NOOP")): with pytest.raises(Exception): open_folder("it_is_very_unlikely_that_this_file_exists_20150718") def test_unsupported_os(): with patch('subprocess.check_call', MagicMock(return_value="NOOP")): with patch('platform.system', MagicMock(return_value="NotDarwinWindowsLinux")): with pytest.raises(Exception): result = open_folder("/") def test_supported_os(): with patch('subprocess.check_call', MagicMock(return_value="NOOP")): with patch('platform.system', MagicMock(return_value="Linux")): result = open_folder("/") assert result == None with patch('platform.system', MagicMock(return_value="Darwin")): result = open_folder("/") assert result == None with patch('platform.system', MagicMock(return_value="Windows")): result = open_folder("/") assert result == None ## Instruction: Check to ensure the excpetions return the text we expect. ## Code After: import pytest from mock import patch, MagicMock from open_folder import * def test_folder_exists(): with patch('subprocess.check_call', MagicMock(return_value="NOOP")): result = open_folder(".") assert result == None def test_folder_does_not_exists(): with patch('subprocess.check_call', MagicMock(return_value="NOOP")): with pytest.raises(Exception) as excinfo: open_folder("it_is_very_unlikely_that_this_file_exists_20150718") assert str(excinfo.value) == ('Folder does not exist.') def test_unsupported_os(): with patch('subprocess.check_call', MagicMock(return_value="NOOP")): with patch('platform.system', MagicMock(return_value="NotDarwinWindowsLinux")): with pytest.raises(Exception) as excinfo: open_folder("/") assert str(excinfo.value).startswith('Your operating system was not recognized.') def test_supported_os(): with patch('subprocess.check_call', MagicMock(return_value="NOOP")): with patch('platform.system', MagicMock(return_value="Linux")): result = open_folder("/") assert result == None with patch('platform.system', MagicMock(return_value="Darwin")): result = open_folder("/") assert result == None with patch('platform.system', MagicMock(return_value="Windows")): result = open_folder("/") assert result == None
// ... existing code ... with patch('subprocess.check_call', MagicMock(return_value="NOOP")): with pytest.raises(Exception) as excinfo: open_folder("it_is_very_unlikely_that_this_file_exists_20150718") assert str(excinfo.value) == ('Folder does not exist.') // ... modified code ... with patch('subprocess.check_call', MagicMock(return_value="NOOP")): with patch('platform.system', MagicMock(return_value="NotDarwinWindowsLinux")): with pytest.raises(Exception) as excinfo: open_folder("/") assert str(excinfo.value).startswith('Your operating system was not recognized.') // ... rest of the code ...
0baf08c61348f4fa6a657e1c0e2ff9bdf65eaa15
leetcode/RemoveElement.py
leetcode/RemoveElement.py
class Solution: # @param A a list of integers # @param elem an integer, value need to be removed # @return an integer def removeElement(self, A, elem): if len(A) == 0: return 0 else: k=0 for i in range(0, len(A)): if A[i] != elem: A[k] = A[i] k += 1 return k
class Solution: # @param A a list of integers # @param elem an integer, value need to be removed # @return an integer def removeElement(self, A, elem): if len(A) == 0: return 0 else: k=0 for i in range(0, len(A)): if A[i] != elem: if i!= k: A[k] = A[i] k += 1 return k
Add one more if to speed up
Add one more if to speed up
Python
mit
aenon/OnlineJudge,aenon/OnlineJudge
class Solution: # @param A a list of integers # @param elem an integer, value need to be removed # @return an integer def removeElement(self, A, elem): if len(A) == 0: return 0 else: k=0 for i in range(0, len(A)): if A[i] != elem: + if i!= k: - A[k] = A[i] + A[k] = A[i] k += 1 return k
Add one more if to speed up
## Code Before: class Solution: # @param A a list of integers # @param elem an integer, value need to be removed # @return an integer def removeElement(self, A, elem): if len(A) == 0: return 0 else: k=0 for i in range(0, len(A)): if A[i] != elem: A[k] = A[i] k += 1 return k ## Instruction: Add one more if to speed up ## Code After: class Solution: # @param A a list of integers # @param elem an integer, value need to be removed # @return an integer def removeElement(self, A, elem): if len(A) == 0: return 0 else: k=0 for i in range(0, len(A)): if A[i] != elem: if i!= k: A[k] = A[i] k += 1 return k
# ... existing code ... if A[i] != elem: if i!= k: A[k] = A[i] k += 1 # ... rest of the code ...
63d1eb69fc614cb3f019e7b37dd4ec10896c644e
chartflo/views.py
chartflo/views.py
from django.views.generic import TemplateView from chartflo.factory import ChartDataPack class ChartsView(TemplateView): template_name = 'chartflo/charts.html' graph_type = "pie" title = "" def get_data(self): return {} def get_context_data(self, **kwargs): context = super(ChartsView, self).get_context_data(**kwargs) # get data P = ChartDataPack() dataset = self.get_data() # package the data datapack = P.package("chart_id", self.title, dataset) # options datapack['legend'] = True datapack['export'] = False context['datapack'] = datapack context["graph_type"] = self.graph_type context["title"] = context["label"] = self.title context["chart_url"] = self._get_chart_url() return context def _get_chart_url(self): url = "chartflo/charts/" + self.graph_type + ".html" return url
from django.views.generic import TemplateView from chartflo.factory import ChartDataPack class ChartsView(TemplateView): template_name = 'chartflo/charts.html' chart_type = "pie" title = "" def get_data(self): return {} def get_context_data(self, **kwargs): context = super(ChartsView, self).get_context_data(**kwargs) # get data P = ChartDataPack() dataset = self.get_data() # package the data datapack = P.package("chart_id", self.title, dataset) # options datapack['legend'] = True datapack['export'] = False context['datapack'] = datapack context["title"] = context["label"] = self.title context["chart_url"] = self._get_chart_url() return context def _get_chart_url(self): url = "chartflo/charts/" + self.chart_type + ".html" return url
Change graph_type for chart_type and remove it from context
Change graph_type for chart_type and remove it from context
Python
mit
synw/django-chartflo,synw/django-chartflo,synw/django-chartflo
from django.views.generic import TemplateView from chartflo.factory import ChartDataPack class ChartsView(TemplateView): template_name = 'chartflo/charts.html' - graph_type = "pie" + chart_type = "pie" title = "" def get_data(self): return {} def get_context_data(self, **kwargs): context = super(ChartsView, self).get_context_data(**kwargs) # get data P = ChartDataPack() dataset = self.get_data() # package the data datapack = P.package("chart_id", self.title, dataset) # options datapack['legend'] = True datapack['export'] = False context['datapack'] = datapack - context["graph_type"] = self.graph_type context["title"] = context["label"] = self.title context["chart_url"] = self._get_chart_url() return context def _get_chart_url(self): - url = "chartflo/charts/" + self.graph_type + ".html" + url = "chartflo/charts/" + self.chart_type + ".html" return url
Change graph_type for chart_type and remove it from context
## Code Before: from django.views.generic import TemplateView from chartflo.factory import ChartDataPack class ChartsView(TemplateView): template_name = 'chartflo/charts.html' graph_type = "pie" title = "" def get_data(self): return {} def get_context_data(self, **kwargs): context = super(ChartsView, self).get_context_data(**kwargs) # get data P = ChartDataPack() dataset = self.get_data() # package the data datapack = P.package("chart_id", self.title, dataset) # options datapack['legend'] = True datapack['export'] = False context['datapack'] = datapack context["graph_type"] = self.graph_type context["title"] = context["label"] = self.title context["chart_url"] = self._get_chart_url() return context def _get_chart_url(self): url = "chartflo/charts/" + self.graph_type + ".html" return url ## Instruction: Change graph_type for chart_type and remove it from context ## Code After: from django.views.generic import TemplateView from chartflo.factory import ChartDataPack class ChartsView(TemplateView): template_name = 'chartflo/charts.html' chart_type = "pie" title = "" def get_data(self): return {} def get_context_data(self, **kwargs): context = super(ChartsView, self).get_context_data(**kwargs) # get data P = ChartDataPack() dataset = self.get_data() # package the data datapack = P.package("chart_id", self.title, dataset) # options datapack['legend'] = True datapack['export'] = False context['datapack'] = datapack context["title"] = context["label"] = self.title context["chart_url"] = self._get_chart_url() return context def _get_chart_url(self): url = "chartflo/charts/" + self.chart_type + ".html" return url
... template_name = 'chartflo/charts.html' chart_type = "pie" title = "" ... context['datapack'] = datapack context["title"] = context["label"] = self.title ... def _get_chart_url(self): url = "chartflo/charts/" + self.chart_type + ".html" return url ...
05e8170326c5aa2be48eee5f90ab5a3919775e01
io_EDM/__init__.py
io_EDM/__init__.py
bl_info = { 'name': "Import: .EDM model files", 'description': "Importing of .EDM model files", 'author': "Nicholas Devenish", 'version': (0,0,1), 'blender': (2, 78, 0), 'location': "File > Import/Export > .EDM Files", 'category': 'Import-Export', } try: import bpy def register(): from .io_operators import register as importer_register from .rna import register as rna_register from .panels import register as panels_register rna_register() panels_register() importer_register() bpy.utils.register_module(__name__) def unregister(): from .io_operators import unregister as importer_unregister from .rna import unregister as rna_unregister from .panels import unregister as panels_unregister importer_unregister() panels_unregister() rna_unregister() bpy.utils.unregister_module(__name__) if __name__ == "__main__": register() except ImportError: # Allow for now, as we might just want to import the sub-package pass
bl_info = { 'name': "Import: .EDM model files", 'description': "Importing of .EDM model files", 'author': "Nicholas Devenish", 'version': (0,0,1), 'blender': (2, 78, 0), 'location': "File > Import/Export > .EDM Files", 'category': 'Import-Export', } try: import bpy def register(): from .io_operators import register as importer_register from .rna import register as rna_register from .panels import register as panels_register rna_register() panels_register() importer_register() def unregister(): from .io_operators import unregister as importer_unregister from .rna import unregister as rna_unregister from .panels import unregister as panels_unregister importer_unregister() panels_unregister() rna_unregister() if __name__ == "__main__": register() except ImportError: # Allow for now, as we might just want to import the sub-package pass
Remove potential duplicate registration code
Remove potential duplicate registration code Was sometimes causing an error when importing the project
Python
mit
ndevenish/Blender_ioEDM,ndevenish/Blender_ioEDM
bl_info = { 'name': "Import: .EDM model files", 'description': "Importing of .EDM model files", 'author': "Nicholas Devenish", 'version': (0,0,1), 'blender': (2, 78, 0), 'location': "File > Import/Export > .EDM Files", 'category': 'Import-Export', } try: import bpy def register(): from .io_operators import register as importer_register from .rna import register as rna_register from .panels import register as panels_register rna_register() panels_register() importer_register() + - bpy.utils.register_module(__name__) - def unregister(): from .io_operators import unregister as importer_unregister from .rna import unregister as rna_unregister from .panels import unregister as panels_unregister importer_unregister() panels_unregister() rna_unregister() - bpy.utils.unregister_module(__name__) if __name__ == "__main__": register() except ImportError: # Allow for now, as we might just want to import the sub-package pass
Remove potential duplicate registration code
## Code Before: bl_info = { 'name': "Import: .EDM model files", 'description': "Importing of .EDM model files", 'author': "Nicholas Devenish", 'version': (0,0,1), 'blender': (2, 78, 0), 'location': "File > Import/Export > .EDM Files", 'category': 'Import-Export', } try: import bpy def register(): from .io_operators import register as importer_register from .rna import register as rna_register from .panels import register as panels_register rna_register() panels_register() importer_register() bpy.utils.register_module(__name__) def unregister(): from .io_operators import unregister as importer_unregister from .rna import unregister as rna_unregister from .panels import unregister as panels_unregister importer_unregister() panels_unregister() rna_unregister() bpy.utils.unregister_module(__name__) if __name__ == "__main__": register() except ImportError: # Allow for now, as we might just want to import the sub-package pass ## Instruction: Remove potential duplicate registration code ## Code After: bl_info = { 'name': "Import: .EDM model files", 'description': "Importing of .EDM model files", 'author': "Nicholas Devenish", 'version': (0,0,1), 'blender': (2, 78, 0), 'location': "File > Import/Export > .EDM Files", 'category': 'Import-Export', } try: import bpy def register(): from .io_operators import register as importer_register from .rna import register as rna_register from .panels import register as panels_register rna_register() panels_register() importer_register() def unregister(): from .io_operators import unregister as importer_unregister from .rna import unregister as rna_unregister from .panels import unregister as panels_unregister importer_unregister() panels_unregister() rna_unregister() if __name__ == "__main__": register() except ImportError: # Allow for now, as we might just want to import the sub-package pass
# ... existing code ... importer_register() def unregister(): # ... modified code ... rna_unregister() # ... rest of the code ...
a6d05f3c1a33381a07d459c1fdff93bc4ba30594
pidman/pid/migrations/0002_pid_sequence_initial_value.py
pidman/pid/migrations/0002_pid_sequence_initial_value.py
from __future__ import unicode_literals from django.db import migrations, models from pidman.pid.noid import decode_noid from pidman.pid import models as pid_models def pid_sequence_lastvalue(apps, schema_editor): # if the database has existing pids, update the sequence last value # so it will start minting pids starting after the current set Pid = apps.get_model("pid", "Pid") Sequence = apps.get_model("sequences", "Sequence") if Pid.objects.count(): max_noid = Pid.objects.all() \ .aggregate(models.Max('pid')).values()[0] last_val = decode_noid(max_noid) pid_seq, created = Sequence.objects.get_or_create(name=pid_models.Pid.SEQUENCE_NAME, last=last_val) pid_seq.save() def remove_pid_sequence(apps, schema_editor): Sequence = apps.get_model("sequences", "Sequence") Sequence.objects.get(name=pid_models.Pid.SEQUENCE_NAME).delete() class Migration(migrations.Migration): dependencies = [ ('pid', '0001_initial'), ('sequences', '0001_initial'), ] operations = [ migrations.RunPython(pid_sequence_lastvalue, remove_pid_sequence), ]
from __future__ import unicode_literals from django.db import migrations, models from pidman.pid.noid import decode_noid, encode_noid from pidman.pid import models as pid_models def pid_sequence_lastvalue(apps, schema_editor): # if the database has existing pids, update the sequence last value # so it will start minting pids starting after the current set Pid = apps.get_model("pid", "Pid") Sequence = apps.get_model("sequences", "Sequence") if Pid.objects.count(): # pid noids are generated in sequence, so the pid with the # highest pk _should_ be the one with the highest noid max_noid = Pid.objects.all().order_by('pk').last().pid # (previously using aggregate max, but doesn't seem to find # the highest pid value correctly) last_val = decode_noid(max_noid) pid_seq, created = Sequence.objects.get_or_create(name=pid_models.Pid.SEQUENCE_NAME, last=last_val) pid_seq.save() def remove_pid_sequence(apps, schema_editor): Sequence = apps.get_model("sequences", "Sequence") Sequence.objects.get(name=pid_models.Pid.SEQUENCE_NAME).delete() class Migration(migrations.Migration): dependencies = [ ('pid', '0001_initial'), ('sequences', '0001_initial'), ] operations = [ migrations.RunPython(pid_sequence_lastvalue, remove_pid_sequence), ]
Fix max noid detection when setting pid sequence
Fix max noid detection when setting pid sequence
Python
apache-2.0
emory-libraries/pidman,emory-libraries/pidman
from __future__ import unicode_literals from django.db import migrations, models - from pidman.pid.noid import decode_noid + from pidman.pid.noid import decode_noid, encode_noid from pidman.pid import models as pid_models def pid_sequence_lastvalue(apps, schema_editor): # if the database has existing pids, update the sequence last value # so it will start minting pids starting after the current set Pid = apps.get_model("pid", "Pid") Sequence = apps.get_model("sequences", "Sequence") if Pid.objects.count(): - max_noid = Pid.objects.all() \ - .aggregate(models.Max('pid')).values()[0] + # pid noids are generated in sequence, so the pid with the + # highest pk _should_ be the one with the highest noid + max_noid = Pid.objects.all().order_by('pk').last().pid + # (previously using aggregate max, but doesn't seem to find + # the highest pid value correctly) last_val = decode_noid(max_noid) pid_seq, created = Sequence.objects.get_or_create(name=pid_models.Pid.SEQUENCE_NAME, last=last_val) pid_seq.save() def remove_pid_sequence(apps, schema_editor): Sequence = apps.get_model("sequences", "Sequence") Sequence.objects.get(name=pid_models.Pid.SEQUENCE_NAME).delete() class Migration(migrations.Migration): dependencies = [ ('pid', '0001_initial'), ('sequences', '0001_initial'), ] operations = [ migrations.RunPython(pid_sequence_lastvalue, remove_pid_sequence), ]
Fix max noid detection when setting pid sequence
## Code Before: from __future__ import unicode_literals from django.db import migrations, models from pidman.pid.noid import decode_noid from pidman.pid import models as pid_models def pid_sequence_lastvalue(apps, schema_editor): # if the database has existing pids, update the sequence last value # so it will start minting pids starting after the current set Pid = apps.get_model("pid", "Pid") Sequence = apps.get_model("sequences", "Sequence") if Pid.objects.count(): max_noid = Pid.objects.all() \ .aggregate(models.Max('pid')).values()[0] last_val = decode_noid(max_noid) pid_seq, created = Sequence.objects.get_or_create(name=pid_models.Pid.SEQUENCE_NAME, last=last_val) pid_seq.save() def remove_pid_sequence(apps, schema_editor): Sequence = apps.get_model("sequences", "Sequence") Sequence.objects.get(name=pid_models.Pid.SEQUENCE_NAME).delete() class Migration(migrations.Migration): dependencies = [ ('pid', '0001_initial'), ('sequences', '0001_initial'), ] operations = [ migrations.RunPython(pid_sequence_lastvalue, remove_pid_sequence), ] ## Instruction: Fix max noid detection when setting pid sequence ## Code After: from __future__ import unicode_literals from django.db import migrations, models from pidman.pid.noid import decode_noid, encode_noid from pidman.pid import models as pid_models def pid_sequence_lastvalue(apps, schema_editor): # if the database has existing pids, update the sequence last value # so it will start minting pids starting after the current set Pid = apps.get_model("pid", "Pid") Sequence = apps.get_model("sequences", "Sequence") if Pid.objects.count(): # pid noids are generated in sequence, so the pid with the # highest pk _should_ be the one with the highest noid max_noid = Pid.objects.all().order_by('pk').last().pid # (previously using aggregate max, but doesn't seem to find # the highest pid value correctly) last_val = decode_noid(max_noid) pid_seq, created = Sequence.objects.get_or_create(name=pid_models.Pid.SEQUENCE_NAME, last=last_val) pid_seq.save() def remove_pid_sequence(apps, schema_editor): Sequence = apps.get_model("sequences", "Sequence") Sequence.objects.get(name=pid_models.Pid.SEQUENCE_NAME).delete() class Migration(migrations.Migration): dependencies = [ ('pid', '0001_initial'), ('sequences', '0001_initial'), ] operations = [ migrations.RunPython(pid_sequence_lastvalue, remove_pid_sequence), ]
# ... existing code ... from django.db import migrations, models from pidman.pid.noid import decode_noid, encode_noid from pidman.pid import models as pid_models # ... modified code ... if Pid.objects.count(): # pid noids are generated in sequence, so the pid with the # highest pk _should_ be the one with the highest noid max_noid = Pid.objects.all().order_by('pk').last().pid # (previously using aggregate max, but doesn't seem to find # the highest pid value correctly) last_val = decode_noid(max_noid) # ... rest of the code ...
f042f6c9799d70edb41ae9495adf8bb78ed23e13
elections/ar_elections_2015/settings.py
elections/ar_elections_2015/settings.py
ELECTION_RE = '(?P<election>diputados-argentina-paso-2015|gobernadores-argentina-paso-2015|senadores-argentina-paso-2015|presidentes-argentina-paso-2015)' MAPIT_BASE_URL = 'http://argentina.mapit.staging.mysociety.org/' SITE_OWNER = 'YoQuieroSaber' COPYRIGHT_HOLDER = 'YoQuieroSaber'
ELECTION_RE = '(?P<election>diputados-argentina-paso-2015|gobernadores-argentina-paso-2015|senadores-argentina-paso-2015|presidentes-argentina-paso-2015|parlamentarios-mercosur-regional-paso-2015|parlamentarios-mercosur-unico-paso-2015)' MAPIT_BASE_URL = 'http://argentina.mapit.staging.mysociety.org/' SITE_OWNER = 'YoQuieroSaber' COPYRIGHT_HOLDER = 'YoQuieroSaber'
Add some missing election slugs to Argentina's ELECTION_RE
AR: Add some missing election slugs to Argentina's ELECTION_RE
Python
agpl-3.0
mysociety/yournextmp-popit,DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,neavouli/yournextrepresentative,neavouli/yournextrepresentative,neavouli/yournextrepresentative,DemocracyClub/yournextrepresentative,mysociety/yournextmp-popit,datamade/yournextmp-popit,neavouli/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextmp-popit,datamade/yournextmp-popit,mysociety/yournextrepresentative,mysociety/yournextrepresentative,DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,datamade/yournextmp-popit,datamade/yournextmp-popit,neavouli/yournextrepresentative,mysociety/yournextrepresentative,datamade/yournextmp-popit
- ELECTION_RE = '(?P<election>diputados-argentina-paso-2015|gobernadores-argentina-paso-2015|senadores-argentina-paso-2015|presidentes-argentina-paso-2015)' + ELECTION_RE = '(?P<election>diputados-argentina-paso-2015|gobernadores-argentina-paso-2015|senadores-argentina-paso-2015|presidentes-argentina-paso-2015|parlamentarios-mercosur-regional-paso-2015|parlamentarios-mercosur-unico-paso-2015)' MAPIT_BASE_URL = 'http://argentina.mapit.staging.mysociety.org/' SITE_OWNER = 'YoQuieroSaber' COPYRIGHT_HOLDER = 'YoQuieroSaber'
Add some missing election slugs to Argentina's ELECTION_RE
## Code Before: ELECTION_RE = '(?P<election>diputados-argentina-paso-2015|gobernadores-argentina-paso-2015|senadores-argentina-paso-2015|presidentes-argentina-paso-2015)' MAPIT_BASE_URL = 'http://argentina.mapit.staging.mysociety.org/' SITE_OWNER = 'YoQuieroSaber' COPYRIGHT_HOLDER = 'YoQuieroSaber' ## Instruction: Add some missing election slugs to Argentina's ELECTION_RE ## Code After: ELECTION_RE = '(?P<election>diputados-argentina-paso-2015|gobernadores-argentina-paso-2015|senadores-argentina-paso-2015|presidentes-argentina-paso-2015|parlamentarios-mercosur-regional-paso-2015|parlamentarios-mercosur-unico-paso-2015)' MAPIT_BASE_URL = 'http://argentina.mapit.staging.mysociety.org/' SITE_OWNER = 'YoQuieroSaber' COPYRIGHT_HOLDER = 'YoQuieroSaber'
... ELECTION_RE = '(?P<election>diputados-argentina-paso-2015|gobernadores-argentina-paso-2015|senadores-argentina-paso-2015|presidentes-argentina-paso-2015|parlamentarios-mercosur-regional-paso-2015|parlamentarios-mercosur-unico-paso-2015)' MAPIT_BASE_URL = 'http://argentina.mapit.staging.mysociety.org/' ...
63946ef78a842b82064b560dd0f73c9a5fe7ac82
puzzle/urls.py
puzzle/urls.py
from django.conf.urls import include, url from django.contrib.auth import views as auth_views from puzzle import views from puzzle.feeds import PuzzleFeed urlpatterns = [ #pylint: disable=invalid-name url(r'^$', views.latest, name='latest'), url(r'^login/$', auth_views.login, {'template_name': 'puzzle/login.html'}, name='login'), url(r'^logout/$', auth_views.logout, {'next_page': 'latest'}, name='logout'), url(r'^create/$', views.create, name='create'), url(r'^save/$', views.save, name='save'), url(r'^rss/$', PuzzleFeed(), name='rss'), url(r'^archive/$', views.users, name='users'), url(r'^profile/$', views.profile, name='profile'), url(r'^puzzle/(?P<number>\d+)/$', views.puzzle_redirect), url(r'^setter/(?P<author>\w+)/(?P<number>\d+)/', include([ url(r'^$', views.puzzle, name='puzzle'), url(r'^solution/$', views.solution, name='solution'), url(r'^edit/$', views.edit, name='edit'), ])), ]
from django.conf.urls import include, url from django.contrib.auth import views as auth_views from puzzle import views from puzzle.feeds import PuzzleFeed urlpatterns = [ #pylint: disable=invalid-name url(r'^$', views.latest, name='latest'), url(r'^login/$', auth_views.LoginView.as_view(template_name='puzzle/login.html'), name='login'), url(r'^logout/$', auth_views.LogoutView.as_view(next_page='latest'), name='logout'), url(r'^create/$', views.create, name='create'), url(r'^save/$', views.save, name='save'), url(r'^rss/$', PuzzleFeed(), name='rss'), url(r'^archive/$', views.users, name='users'), url(r'^profile/$', views.profile, name='profile'), url(r'^puzzle/(?P<number>\d+)/$', views.puzzle_redirect), url(r'^setter/(?P<author>\w+)/(?P<number>\d+)/', include([ url(r'^$', views.puzzle, name='puzzle'), url(r'^solution/$', views.solution, name='solution'), url(r'^edit/$', views.edit, name='edit'), ])), ]
Replace deprecated login/logout function-based views
Replace deprecated login/logout function-based views
Python
mit
jomoore/threepins,jomoore/threepins,jomoore/threepins
from django.conf.urls import include, url from django.contrib.auth import views as auth_views from puzzle import views from puzzle.feeds import PuzzleFeed urlpatterns = [ #pylint: disable=invalid-name url(r'^$', views.latest, name='latest'), - url(r'^login/$', auth_views.login, {'template_name': 'puzzle/login.html'}, name='login'), + url(r'^login/$', auth_views.LoginView.as_view(template_name='puzzle/login.html'), name='login'), - url(r'^logout/$', auth_views.logout, {'next_page': 'latest'}, name='logout'), + url(r'^logout/$', auth_views.LogoutView.as_view(next_page='latest'), name='logout'), url(r'^create/$', views.create, name='create'), url(r'^save/$', views.save, name='save'), url(r'^rss/$', PuzzleFeed(), name='rss'), url(r'^archive/$', views.users, name='users'), url(r'^profile/$', views.profile, name='profile'), url(r'^puzzle/(?P<number>\d+)/$', views.puzzle_redirect), url(r'^setter/(?P<author>\w+)/(?P<number>\d+)/', include([ url(r'^$', views.puzzle, name='puzzle'), url(r'^solution/$', views.solution, name='solution'), url(r'^edit/$', views.edit, name='edit'), ])), ]
Replace deprecated login/logout function-based views
## Code Before: from django.conf.urls import include, url from django.contrib.auth import views as auth_views from puzzle import views from puzzle.feeds import PuzzleFeed urlpatterns = [ #pylint: disable=invalid-name url(r'^$', views.latest, name='latest'), url(r'^login/$', auth_views.login, {'template_name': 'puzzle/login.html'}, name='login'), url(r'^logout/$', auth_views.logout, {'next_page': 'latest'}, name='logout'), url(r'^create/$', views.create, name='create'), url(r'^save/$', views.save, name='save'), url(r'^rss/$', PuzzleFeed(), name='rss'), url(r'^archive/$', views.users, name='users'), url(r'^profile/$', views.profile, name='profile'), url(r'^puzzle/(?P<number>\d+)/$', views.puzzle_redirect), url(r'^setter/(?P<author>\w+)/(?P<number>\d+)/', include([ url(r'^$', views.puzzle, name='puzzle'), url(r'^solution/$', views.solution, name='solution'), url(r'^edit/$', views.edit, name='edit'), ])), ] ## Instruction: Replace deprecated login/logout function-based views ## Code After: from django.conf.urls import include, url from django.contrib.auth import views as auth_views from puzzle import views from puzzle.feeds import PuzzleFeed urlpatterns = [ #pylint: disable=invalid-name url(r'^$', views.latest, name='latest'), url(r'^login/$', auth_views.LoginView.as_view(template_name='puzzle/login.html'), name='login'), url(r'^logout/$', auth_views.LogoutView.as_view(next_page='latest'), name='logout'), url(r'^create/$', views.create, name='create'), url(r'^save/$', views.save, name='save'), url(r'^rss/$', PuzzleFeed(), name='rss'), url(r'^archive/$', views.users, name='users'), url(r'^profile/$', views.profile, name='profile'), url(r'^puzzle/(?P<number>\d+)/$', views.puzzle_redirect), url(r'^setter/(?P<author>\w+)/(?P<number>\d+)/', include([ url(r'^$', views.puzzle, name='puzzle'), url(r'^solution/$', views.solution, name='solution'), url(r'^edit/$', views.edit, name='edit'), ])), ]
... url(r'^$', views.latest, name='latest'), url(r'^login/$', auth_views.LoginView.as_view(template_name='puzzle/login.html'), name='login'), url(r'^logout/$', auth_views.LogoutView.as_view(next_page='latest'), name='logout'), url(r'^create/$', views.create, name='create'), ...
1e0d3c0d0b20f92fd901163a4f2b41627f9e931e
oonib/handlers.py
oonib/handlers.py
from cyclone import web class OONIBHandler(web.RequestHandler): pass class OONIBError(web.HTTPError): pass
import types from cyclone import escape from cyclone import web class OONIBHandler(web.RequestHandler): def write(self, chunk): """ This is a monkey patch to RequestHandler to allow us to serialize also json list objects. """ if isinstance(chunk, types.ListType): chunk = escape.json_encode(chunk) web.RequestHandler.write(self, chunk) self.set_header("Content-Type", "application/json") else: web.RequestHandler.write(self, chunk) class OONIBError(web.HTTPError): pass
Add support for serializing lists to json via self.write()
Add support for serializing lists to json via self.write()
Python
bsd-2-clause
DoNotUseThisCodeJUSTFORKS/ooni-backend,dstufft/ooni-backend,DoNotUseThisCodeJUSTFORKS/ooni-backend,dstufft/ooni-backend
+ import types + + from cyclone import escape from cyclone import web class OONIBHandler(web.RequestHandler): - pass + def write(self, chunk): + """ + This is a monkey patch to RequestHandler to allow us to serialize also + json list objects. + """ + if isinstance(chunk, types.ListType): + chunk = escape.json_encode(chunk) + web.RequestHandler.write(self, chunk) + self.set_header("Content-Type", "application/json") + else: + web.RequestHandler.write(self, chunk) class OONIBError(web.HTTPError): pass
Add support for serializing lists to json via self.write()
## Code Before: from cyclone import web class OONIBHandler(web.RequestHandler): pass class OONIBError(web.HTTPError): pass ## Instruction: Add support for serializing lists to json via self.write() ## Code After: import types from cyclone import escape from cyclone import web class OONIBHandler(web.RequestHandler): def write(self, chunk): """ This is a monkey patch to RequestHandler to allow us to serialize also json list objects. """ if isinstance(chunk, types.ListType): chunk = escape.json_encode(chunk) web.RequestHandler.write(self, chunk) self.set_header("Content-Type", "application/json") else: web.RequestHandler.write(self, chunk) class OONIBError(web.HTTPError): pass
# ... existing code ... import types from cyclone import escape from cyclone import web # ... modified code ... class OONIBHandler(web.RequestHandler): def write(self, chunk): """ This is a monkey patch to RequestHandler to allow us to serialize also json list objects. """ if isinstance(chunk, types.ListType): chunk = escape.json_encode(chunk) web.RequestHandler.write(self, chunk) self.set_header("Content-Type", "application/json") else: web.RequestHandler.write(self, chunk) # ... rest of the code ...
952704b93004e5763231ad3e64f32135474651b2
common/templatetags/uqam.py
common/templatetags/uqam.py
from django import template register = template.Library() @register.filter def dimension(value, arg): """ Dimension integers If value, append arg, otherwise output nothing """ if value: return str(value) + " " + arg return "" @register.filter def verbose_name(obj): """ Return the verbose name of a model """ return obj._meta.verbose_name @register.filter def pdb(element): """ Inside a template do {{ template_var|pdb }} """ import ipdb ipdb.set_trace() return element from cat.models import Category from location.models import Country @register.inclusion_tag('snippets/advanced_search_fields.html') def advanced_search_fields(): categories = Category.objects.all() places = Country.objects.all() return { 'categories': categories, 'places': places, }
from django import template register = template.Library() @register.filter def dimension(value, arg): """ Dimension integers If value, append arg, otherwise output nothing """ if value: return str(value) + " " + arg return "" @register.filter def verbose_name(obj): """ Return the verbose name of a model """ return obj._meta.verbose_name @register.filter def pdb(element): """ Inside a template do {{ template_var|pdb }} """ import ipdb ipdb.set_trace() return element from cat.models import Category from location.models import Country @register.inclusion_tag('snippets/advanced_search_fields.html') def advanced_search_fields(): categories = Category.objects.all().order_by('name') places = Country.objects.all() return { 'categories': categories, 'places': places, }
Order categories in search fields
Order categories in search fields
Python
bsd-3-clause
uq-eresearch/uqam,uq-eresearch/uqam,uq-eresearch/uqam,uq-eresearch/uqam
from django import template register = template.Library() @register.filter def dimension(value, arg): """ Dimension integers If value, append arg, otherwise output nothing """ if value: return str(value) + " " + arg return "" @register.filter def verbose_name(obj): """ Return the verbose name of a model """ return obj._meta.verbose_name @register.filter def pdb(element): """ Inside a template do {{ template_var|pdb }} """ import ipdb ipdb.set_trace() return element from cat.models import Category from location.models import Country @register.inclusion_tag('snippets/advanced_search_fields.html') def advanced_search_fields(): - categories = Category.objects.all() + categories = Category.objects.all().order_by('name') places = Country.objects.all() return { 'categories': categories, 'places': places, }
Order categories in search fields
## Code Before: from django import template register = template.Library() @register.filter def dimension(value, arg): """ Dimension integers If value, append arg, otherwise output nothing """ if value: return str(value) + " " + arg return "" @register.filter def verbose_name(obj): """ Return the verbose name of a model """ return obj._meta.verbose_name @register.filter def pdb(element): """ Inside a template do {{ template_var|pdb }} """ import ipdb ipdb.set_trace() return element from cat.models import Category from location.models import Country @register.inclusion_tag('snippets/advanced_search_fields.html') def advanced_search_fields(): categories = Category.objects.all() places = Country.objects.all() return { 'categories': categories, 'places': places, } ## Instruction: Order categories in search fields ## Code After: from django import template register = template.Library() @register.filter def dimension(value, arg): """ Dimension integers If value, append arg, otherwise output nothing """ if value: return str(value) + " " + arg return "" @register.filter def verbose_name(obj): """ Return the verbose name of a model """ return obj._meta.verbose_name @register.filter def pdb(element): """ Inside a template do {{ template_var|pdb }} """ import ipdb ipdb.set_trace() return element from cat.models import Category from location.models import Country @register.inclusion_tag('snippets/advanced_search_fields.html') def advanced_search_fields(): categories = Category.objects.all().order_by('name') places = Country.objects.all() return { 'categories': categories, 'places': places, }
... def advanced_search_fields(): categories = Category.objects.all().order_by('name') places = Country.objects.all() ...
7f9c9b947948654d7557aa0fcfbb1c015521da9b
tests/modular_templates/routing.py
tests/modular_templates/routing.py
import unittest from framework.routing import Rule class RuleTestCase(unittest.TestCase): def _make_rule(self, **kwargs): def vf(): return {} return Rule( kwargs.get('routes', ['/', ]), kwargs.get('methods', ['GET', ]), kwargs.get('view_func', vf), kwargs.get('render_func'), kwargs.get('view_kwargs'), ) def test_rule_single_route(self): r = self._make_rule(routes='/') self.assertEqual(r.routes, ['/', ]) def test_rule_single_method(self): r = self._make_rule(methods='GET') self.assertEqual(r.methods, ['GET', ]) def test_rule_lambda_view(self): r = self._make_rule(view_func=lambda: '') self.assertTrue(callable(r.view_func))
import unittest from framework.routing import Rule, json_renderer class RuleTestCase(unittest.TestCase): def _make_rule(self, **kwargs): def vf(): return {} return Rule( kwargs.get('routes', ['/', ]), kwargs.get('methods', ['GET', ]), kwargs.get('view_func', vf), kwargs.get('render_func', json_renderer), kwargs.get('view_kwargs'), ) def test_rule_single_route(self): r = self._make_rule(routes='/') self.assertEqual(r.routes, ['/', ]) def test_rule_single_method(self): r = self._make_rule(methods='GET') self.assertEqual(r.methods, ['GET', ]) def test_rule_lambda_view(self): r = self._make_rule(view_func=lambda: '') self.assertTrue(callable(r.view_func))
Fix RuleTestCase -> tests passing
Fix RuleTestCase -> tests passing
Python
apache-2.0
caneruguz/osf.io,brandonPurvis/osf.io,rdhyee/osf.io,KAsante95/osf.io,pattisdr/osf.io,KAsante95/osf.io,barbour-em/osf.io,HarryRybacki/osf.io,mluke93/osf.io,aaxelb/osf.io,jinluyuan/osf.io,ZobairAlijan/osf.io,wearpants/osf.io,sbt9uc/osf.io,ticklemepierce/osf.io,jnayak1/osf.io,caseyrygt/osf.io,kwierman/osf.io,adlius/osf.io,baylee-d/osf.io,alexschiller/osf.io,rdhyee/osf.io,DanielSBrown/osf.io,danielneis/osf.io,leb2dg/osf.io,alexschiller/osf.io,ZobairAlijan/osf.io,jinluyuan/osf.io,danielneis/osf.io,emetsger/osf.io,DanielSBrown/osf.io,samchrisinger/osf.io,zamattiac/osf.io,amyshi188/osf.io,dplorimer/osf,brianjgeiger/osf.io,kwierman/osf.io,danielneis/osf.io,cosenal/osf.io,arpitar/osf.io,njantrania/osf.io,caneruguz/osf.io,saradbowman/osf.io,KAsante95/osf.io,Nesiehr/osf.io,adlius/osf.io,mluke93/osf.io,billyhunt/osf.io,jmcarp/osf.io,bdyetton/prettychart,baylee-d/osf.io,fabianvf/osf.io,zachjanicki/osf.io,hmoco/osf.io,zamattiac/osf.io,cwisecarver/osf.io,brandonPurvis/osf.io,lamdnhan/osf.io,zkraime/osf.io,HarryRybacki/osf.io,sbt9uc/osf.io,mattclark/osf.io,acshi/osf.io,haoyuchen1992/osf.io,mluo613/osf.io,caseyrygt/osf.io,Nesiehr/osf.io,zkraime/osf.io,zamattiac/osf.io,alexschiller/osf.io,acshi/osf.io,ckc6cz/osf.io,zkraime/osf.io,himanshuo/osf.io,ckc6cz/osf.io,monikagrabowska/osf.io,brandonPurvis/osf.io,HalcyonChimera/osf.io,Johnetordoff/osf.io,aaxelb/osf.io,DanielSBrown/osf.io,lamdnhan/osf.io,Ghalko/osf.io,chrisseto/osf.io,jolene-esposito/osf.io,mfraezz/osf.io,erinspace/osf.io,njantrania/osf.io,lamdnhan/osf.io,GaryKriebel/osf.io,abought/osf.io,brandonPurvis/osf.io,jnayak1/osf.io,RomanZWang/osf.io,mfraezz/osf.io,TomBaxter/osf.io,sloria/osf.io,acshi/osf.io,jolene-esposito/osf.io,jeffreyliu3230/osf.io,GageGaskins/osf.io,HalcyonChimera/osf.io,Ghalko/osf.io,TomHeatwole/osf.io,bdyetton/prettychart,mluo613/osf.io,RomanZWang/osf.io,himanshuo/osf.io,erinspace/osf.io,barbour-em/osf.io,crcresearch/osf.io,doublebits/osf.io,RomanZWang/osf.io,Johnetordoff/osf.io,doublebits/osf.io,abought/osf.io,chennan47/osf.io,lamdnhan/osf.io,revanthkolli/osf.io,hmoco/osf.io,asanfilippo7/osf.io,ckc6cz/osf.io,caseyrygt/osf.io,AndrewSallans/osf.io,doublebits/osf.io,caseyrygt/osf.io,baylee-d/osf.io,cldershem/osf.io,HarryRybacki/osf.io,dplorimer/osf,felliott/osf.io,leb2dg/osf.io,MerlinZhang/osf.io,DanielSBrown/osf.io,haoyuchen1992/osf.io,petermalcolm/osf.io,ticklemepierce/osf.io,emetsger/osf.io,jnayak1/osf.io,doublebits/osf.io,dplorimer/osf,amyshi188/osf.io,GaryKriebel/osf.io,billyhunt/osf.io,CenterForOpenScience/osf.io,njantrania/osf.io,asanfilippo7/osf.io,rdhyee/osf.io,SSJohns/osf.io,zachjanicki/osf.io,GageGaskins/osf.io,brianjgeiger/osf.io,hmoco/osf.io,aaxelb/osf.io,ZobairAlijan/osf.io,cwisecarver/osf.io,MerlinZhang/osf.io,billyhunt/osf.io,icereval/osf.io,monikagrabowska/osf.io,revanthkolli/osf.io,cldershem/osf.io,mattclark/osf.io,jinluyuan/osf.io,pattisdr/osf.io,brandonPurvis/osf.io,danielneis/osf.io,fabianvf/osf.io,arpitar/osf.io,jeffreyliu3230/osf.io,billyhunt/osf.io,laurenrevere/osf.io,samanehsan/osf.io,adlius/osf.io,ZobairAlijan/osf.io,kushG/osf.io,amyshi188/osf.io,mluo613/osf.io,reinaH/osf.io,mluo613/osf.io,petermalcolm/osf.io,kushG/osf.io,mfraezz/osf.io,himanshuo/osf.io,abought/osf.io,cosenal/osf.io,GaryKriebel/osf.io,mattclark/osf.io,CenterForOpenScience/osf.io,TomHeatwole/osf.io,cosenal/osf.io,jmcarp/osf.io,fabianvf/osf.io,acshi/osf.io,icereval/osf.io,monikagrabowska/osf.io,binoculars/osf.io,caseyrollins/osf.io,doublebits/osf.io,SSJohns/osf.io,acshi/osf.io,cslzchen/osf.io,aaxelb/osf.io,binoculars/osf.io,adlius/osf.io,himanshuo/osf.io,ticklemepierce/osf.io,GageGaskins/osf.io,TomBaxter/osf.io,TomHeatwole/osf.io,abought/osf.io,fabianvf/osf.io,reinaH/osf.io,alexschiller/osf.io,monikagrabowska/osf.io,leb2dg/osf.io,HarryRybacki/osf.io,GageGaskins/osf.io,monikagrabowska/osf.io,billyhunt/osf.io,brianjgeiger/osf.io,kwierman/osf.io,felliott/osf.io,samanehsan/osf.io,RomanZWang/osf.io,mluo613/osf.io,caneruguz/osf.io,lyndsysimon/osf.io,cldershem/osf.io,cslzchen/osf.io,kushG/osf.io,barbour-em/osf.io,lyndsysimon/osf.io,chrisseto/osf.io,zachjanicki/osf.io,crcresearch/osf.io,zachjanicki/osf.io,sbt9uc/osf.io,KAsante95/osf.io,sbt9uc/osf.io,hmoco/osf.io,zamattiac/osf.io,zkraime/osf.io,jnayak1/osf.io,emetsger/osf.io,asanfilippo7/osf.io,jeffreyliu3230/osf.io,ticklemepierce/osf.io,kch8qx/osf.io,cosenal/osf.io,dplorimer/osf,jolene-esposito/osf.io,laurenrevere/osf.io,jeffreyliu3230/osf.io,GaryKriebel/osf.io,lyndsysimon/osf.io,samanehsan/osf.io,lyndsysimon/osf.io,wearpants/osf.io,saradbowman/osf.io,bdyetton/prettychart,caseyrollins/osf.io,jinluyuan/osf.io,TomBaxter/osf.io,samchrisinger/osf.io,icereval/osf.io,ckc6cz/osf.io,samchrisinger/osf.io,caseyrollins/osf.io,laurenrevere/osf.io,njantrania/osf.io,chrisseto/osf.io,caneruguz/osf.io,arpitar/osf.io,Johnetordoff/osf.io,pattisdr/osf.io,haoyuchen1992/osf.io,kch8qx/osf.io,SSJohns/osf.io,chrisseto/osf.io,leb2dg/osf.io,Johnetordoff/osf.io,felliott/osf.io,petermalcolm/osf.io,emetsger/osf.io,cwisecarver/osf.io,kushG/osf.io,petermalcolm/osf.io,erinspace/osf.io,kch8qx/osf.io,arpitar/osf.io,jolene-esposito/osf.io,cldershem/osf.io,KAsante95/osf.io,binoculars/osf.io,brianjgeiger/osf.io,HalcyonChimera/osf.io,mfraezz/osf.io,HalcyonChimera/osf.io,SSJohns/osf.io,felliott/osf.io,wearpants/osf.io,Nesiehr/osf.io,reinaH/osf.io,crcresearch/osf.io,Ghalko/osf.io,kch8qx/osf.io,RomanZWang/osf.io,barbour-em/osf.io,Nesiehr/osf.io,kwierman/osf.io,revanthkolli/osf.io,cwisecarver/osf.io,chennan47/osf.io,haoyuchen1992/osf.io,samanehsan/osf.io,alexschiller/osf.io,Ghalko/osf.io,rdhyee/osf.io,sloria/osf.io,reinaH/osf.io,kch8qx/osf.io,amyshi188/osf.io,cslzchen/osf.io,jmcarp/osf.io,bdyetton/prettychart,mluke93/osf.io,cslzchen/osf.io,chennan47/osf.io,sloria/osf.io,GageGaskins/osf.io,jmcarp/osf.io,AndrewSallans/osf.io,TomHeatwole/osf.io,wearpants/osf.io,mluke93/osf.io,samchrisinger/osf.io,CenterForOpenScience/osf.io,revanthkolli/osf.io,asanfilippo7/osf.io,CenterForOpenScience/osf.io,MerlinZhang/osf.io,MerlinZhang/osf.io
import unittest - from framework.routing import Rule + from framework.routing import Rule, json_renderer class RuleTestCase(unittest.TestCase): def _make_rule(self, **kwargs): def vf(): return {} return Rule( kwargs.get('routes', ['/', ]), kwargs.get('methods', ['GET', ]), kwargs.get('view_func', vf), - kwargs.get('render_func'), + kwargs.get('render_func', json_renderer), kwargs.get('view_kwargs'), ) def test_rule_single_route(self): r = self._make_rule(routes='/') self.assertEqual(r.routes, ['/', ]) def test_rule_single_method(self): r = self._make_rule(methods='GET') self.assertEqual(r.methods, ['GET', ]) def test_rule_lambda_view(self): r = self._make_rule(view_func=lambda: '') self.assertTrue(callable(r.view_func)) +
Fix RuleTestCase -> tests passing
## Code Before: import unittest from framework.routing import Rule class RuleTestCase(unittest.TestCase): def _make_rule(self, **kwargs): def vf(): return {} return Rule( kwargs.get('routes', ['/', ]), kwargs.get('methods', ['GET', ]), kwargs.get('view_func', vf), kwargs.get('render_func'), kwargs.get('view_kwargs'), ) def test_rule_single_route(self): r = self._make_rule(routes='/') self.assertEqual(r.routes, ['/', ]) def test_rule_single_method(self): r = self._make_rule(methods='GET') self.assertEqual(r.methods, ['GET', ]) def test_rule_lambda_view(self): r = self._make_rule(view_func=lambda: '') self.assertTrue(callable(r.view_func)) ## Instruction: Fix RuleTestCase -> tests passing ## Code After: import unittest from framework.routing import Rule, json_renderer class RuleTestCase(unittest.TestCase): def _make_rule(self, **kwargs): def vf(): return {} return Rule( kwargs.get('routes', ['/', ]), kwargs.get('methods', ['GET', ]), kwargs.get('view_func', vf), kwargs.get('render_func', json_renderer), kwargs.get('view_kwargs'), ) def test_rule_single_route(self): r = self._make_rule(routes='/') self.assertEqual(r.routes, ['/', ]) def test_rule_single_method(self): r = self._make_rule(methods='GET') self.assertEqual(r.methods, ['GET', ]) def test_rule_lambda_view(self): r = self._make_rule(view_func=lambda: '') self.assertTrue(callable(r.view_func))
// ... existing code ... import unittest from framework.routing import Rule, json_renderer // ... modified code ... kwargs.get('view_func', vf), kwargs.get('render_func', json_renderer), kwargs.get('view_kwargs'), // ... rest of the code ...
c05b06577785bdf34f1fcd051ecf6d4398d2f77e
tasks.py
tasks.py
from os.path import join from invoke import Collection, ctask as task from invocations import docs as _docs d = 'sites' # Usage doc/API site (published as docs.paramiko.org) path = join(d, 'docs') docs = Collection.from_module(_docs, name='docs', config={ 'sphinx.source': path, 'sphinx.target': join(path, '_build'), }) # Main/about/changelog site ((www.)?paramiko.org) path = join(d, 'www') www = Collection.from_module(_docs, name='www', config={ 'sphinx.source': path, 'sphinx.target': join(path, '_build'), }) # Until we move to spec-based testing @task def test(ctx): ctx.run("python test.py --verbose") @task def coverage(ctx): ctx.run("coverage run --source=paramiko test.py --verbose") ns = Collection(test, coverage, docs=docs, www=www)
from os.path import join from shutil import rmtree, move from invoke import Collection, ctask as task from invocations import docs as _docs from invocations.packaging import publish d = 'sites' # Usage doc/API site (published as docs.paramiko.org) docs_path = join(d, 'docs') docs_build = join(docs_path, '_build') docs = Collection.from_module(_docs, name='docs', config={ 'sphinx.source': docs_path, 'sphinx.target': docs_build, }) # Main/about/changelog site ((www.)?paramiko.org) www_path = join(d, 'www') www = Collection.from_module(_docs, name='www', config={ 'sphinx.source': www_path, 'sphinx.target': join(www_path, '_build'), }) # Until we move to spec-based testing @task def test(ctx): ctx.run("python test.py --verbose") @task def coverage(ctx): ctx.run("coverage run --source=paramiko test.py --verbose") # Until we stop bundling docs w/ releases. Need to discover use cases first. @task('docs') # Will invoke the API doc site build def release(ctx): # Move the built docs into where Epydocs used to live rmtree('docs') move(docs_build, 'docs') # Publish publish(ctx) ns = Collection(test, coverage, release, docs=docs, www=www)
Add new release task w/ API doc prebuilding
Add new release task w/ API doc prebuilding
Python
lgpl-2.1
thusoy/paramiko,CptLemming/paramiko,rcorrieri/paramiko,redixin/paramiko,Automatic/paramiko,jaraco/paramiko,esc/paramiko,ameily/paramiko,zarr12steven/paramiko,dorianpula/paramiko,mirrorcoder/paramiko,jorik041/paramiko,thisch/paramiko,dlitz/paramiko,paramiko/paramiko,digitalquacks/paramiko,fvicente/paramiko,SebastianDeiss/paramiko,anadigi/paramiko,varunarya10/paramiko,zpzgone/paramiko,torkil/paramiko,mhdaimi/paramiko,reaperhulk/paramiko,selboo/paramiko,remram44/paramiko,toby82/paramiko,davidbistolas/paramiko
from os.path import join + from shutil import rmtree, move from invoke import Collection, ctask as task from invocations import docs as _docs + from invocations.packaging import publish d = 'sites' # Usage doc/API site (published as docs.paramiko.org) - path = join(d, 'docs') + docs_path = join(d, 'docs') + docs_build = join(docs_path, '_build') docs = Collection.from_module(_docs, name='docs', config={ - 'sphinx.source': path, + 'sphinx.source': docs_path, - 'sphinx.target': join(path, '_build'), + 'sphinx.target': docs_build, }) # Main/about/changelog site ((www.)?paramiko.org) - path = join(d, 'www') + www_path = join(d, 'www') www = Collection.from_module(_docs, name='www', config={ - 'sphinx.source': path, + 'sphinx.source': www_path, - 'sphinx.target': join(path, '_build'), + 'sphinx.target': join(www_path, '_build'), }) # Until we move to spec-based testing @task def test(ctx): ctx.run("python test.py --verbose") @task def coverage(ctx): ctx.run("coverage run --source=paramiko test.py --verbose") - ns = Collection(test, coverage, docs=docs, www=www) + # Until we stop bundling docs w/ releases. Need to discover use cases first. + @task('docs') # Will invoke the API doc site build + def release(ctx): + # Move the built docs into where Epydocs used to live + rmtree('docs') + move(docs_build, 'docs') + # Publish + publish(ctx) + + ns = Collection(test, coverage, release, docs=docs, www=www) +
Add new release task w/ API doc prebuilding
## Code Before: from os.path import join from invoke import Collection, ctask as task from invocations import docs as _docs d = 'sites' # Usage doc/API site (published as docs.paramiko.org) path = join(d, 'docs') docs = Collection.from_module(_docs, name='docs', config={ 'sphinx.source': path, 'sphinx.target': join(path, '_build'), }) # Main/about/changelog site ((www.)?paramiko.org) path = join(d, 'www') www = Collection.from_module(_docs, name='www', config={ 'sphinx.source': path, 'sphinx.target': join(path, '_build'), }) # Until we move to spec-based testing @task def test(ctx): ctx.run("python test.py --verbose") @task def coverage(ctx): ctx.run("coverage run --source=paramiko test.py --verbose") ns = Collection(test, coverage, docs=docs, www=www) ## Instruction: Add new release task w/ API doc prebuilding ## Code After: from os.path import join from shutil import rmtree, move from invoke import Collection, ctask as task from invocations import docs as _docs from invocations.packaging import publish d = 'sites' # Usage doc/API site (published as docs.paramiko.org) docs_path = join(d, 'docs') docs_build = join(docs_path, '_build') docs = Collection.from_module(_docs, name='docs', config={ 'sphinx.source': docs_path, 'sphinx.target': docs_build, }) # Main/about/changelog site ((www.)?paramiko.org) www_path = join(d, 'www') www = Collection.from_module(_docs, name='www', config={ 'sphinx.source': www_path, 'sphinx.target': join(www_path, '_build'), }) # Until we move to spec-based testing @task def test(ctx): ctx.run("python test.py --verbose") @task def coverage(ctx): ctx.run("coverage run --source=paramiko test.py --verbose") # Until we stop bundling docs w/ releases. Need to discover use cases first. @task('docs') # Will invoke the API doc site build def release(ctx): # Move the built docs into where Epydocs used to live rmtree('docs') move(docs_build, 'docs') # Publish publish(ctx) ns = Collection(test, coverage, release, docs=docs, www=www)
... from os.path import join from shutil import rmtree, move ... from invocations import docs as _docs from invocations.packaging import publish ... # Usage doc/API site (published as docs.paramiko.org) docs_path = join(d, 'docs') docs_build = join(docs_path, '_build') docs = Collection.from_module(_docs, name='docs', config={ 'sphinx.source': docs_path, 'sphinx.target': docs_build, }) ... # Main/about/changelog site ((www.)?paramiko.org) www_path = join(d, 'www') www = Collection.from_module(_docs, name='www', config={ 'sphinx.source': www_path, 'sphinx.target': join(www_path, '_build'), }) ... # Until we stop bundling docs w/ releases. Need to discover use cases first. @task('docs') # Will invoke the API doc site build def release(ctx): # Move the built docs into where Epydocs used to live rmtree('docs') move(docs_build, 'docs') # Publish publish(ctx) ns = Collection(test, coverage, release, docs=docs, www=www) ...
8c177eec8edd0006fd9a86ce7b9b91a28c536971
02_ganymede/ganymede/jupyter_notebook_config.py
02_ganymede/ganymede/jupyter_notebook_config.py
c.NotebookApp.server_extensions = [ 'ganymede.ganymede', 'jupyter_nbgallery' ] c.NotebookApp.allow_origin = 'https://nb.gallery' from ganymede.ganymede import GanymedeHandler import logstash import os if {"L41_LOGSTASH_HOST", "L41_LOGSTASH_PORT"} < set(os.environ): GanymedeHandler.handlers = [ logstash.TCPLogstashHandler( os.environ["L41_LOGSTASH_HOST"], os.environ["L41_LOGSTASH_PORT"], version=1, ) ]
c.NotebookApp.nbserver_extensions = { 'ganymede.ganymede': 'ganymede.ganymede', 'jupyter_nbgallery': 'jupyter_nbgallery' } c.NotebookApp.allow_origin = 'https://nb.gallery' from ganymede.ganymede import GanymedeHandler import logstash import os if {"L41_LOGSTASH_HOST", "L41_LOGSTASH_PORT"} < set(os.environ): GanymedeHandler.handlers = [ logstash.TCPLogstashHandler( os.environ["L41_LOGSTASH_HOST"], os.environ["L41_LOGSTASH_PORT"], version=1, ) ]
Change server_extensions to nbserver_extensions since server_extensions is deprecated.
Change server_extensions to nbserver_extensions since server_extensions is deprecated.
Python
apache-2.0
kylemvz/nbserver,agude/nbserver,kylemvz/nbserver,Lab41/nbserver,agude/nbserver,Lab41/nbserver
- c.NotebookApp.server_extensions = [ + c.NotebookApp.nbserver_extensions = { - 'ganymede.ganymede', - 'jupyter_nbgallery' - ] + 'ganymede.ganymede': 'ganymede.ganymede', + 'jupyter_nbgallery': 'jupyter_nbgallery' + } c.NotebookApp.allow_origin = 'https://nb.gallery' from ganymede.ganymede import GanymedeHandler import logstash import os if {"L41_LOGSTASH_HOST", "L41_LOGSTASH_PORT"} < set(os.environ): GanymedeHandler.handlers = [ logstash.TCPLogstashHandler( os.environ["L41_LOGSTASH_HOST"], os.environ["L41_LOGSTASH_PORT"], version=1, ) ]
Change server_extensions to nbserver_extensions since server_extensions is deprecated.
## Code Before: c.NotebookApp.server_extensions = [ 'ganymede.ganymede', 'jupyter_nbgallery' ] c.NotebookApp.allow_origin = 'https://nb.gallery' from ganymede.ganymede import GanymedeHandler import logstash import os if {"L41_LOGSTASH_HOST", "L41_LOGSTASH_PORT"} < set(os.environ): GanymedeHandler.handlers = [ logstash.TCPLogstashHandler( os.environ["L41_LOGSTASH_HOST"], os.environ["L41_LOGSTASH_PORT"], version=1, ) ] ## Instruction: Change server_extensions to nbserver_extensions since server_extensions is deprecated. ## Code After: c.NotebookApp.nbserver_extensions = { 'ganymede.ganymede': 'ganymede.ganymede', 'jupyter_nbgallery': 'jupyter_nbgallery' } c.NotebookApp.allow_origin = 'https://nb.gallery' from ganymede.ganymede import GanymedeHandler import logstash import os if {"L41_LOGSTASH_HOST", "L41_LOGSTASH_PORT"} < set(os.environ): GanymedeHandler.handlers = [ logstash.TCPLogstashHandler( os.environ["L41_LOGSTASH_HOST"], os.environ["L41_LOGSTASH_PORT"], version=1, ) ]
... c.NotebookApp.nbserver_extensions = { 'ganymede.ganymede': 'ganymede.ganymede', 'jupyter_nbgallery': 'jupyter_nbgallery' } c.NotebookApp.allow_origin = 'https://nb.gallery' ...
f032501126e7bb6d86441e38112c6bdf5035c62e
icekit/search_indexes.py
icekit/search_indexes.py
from fluent_pages.pagetypes.flatpage.models import FlatPage from fluent_pages.pagetypes.fluentpage.models import FluentPage from haystack import indexes class FluentPageIndex(indexes.SearchIndex, indexes.Indexable): """ Search index for a fluent page. """ text = indexes.CharField(document=True, use_template=True) author = indexes.CharField(model_attr='author') publication_date = indexes.DateTimeField(model_attr='publication_date', null=True) @staticmethod def get_model(): """ Get the model for the search index. """ return FluentPage def index_queryset(self, using=None): """ Queryset appropriate for this object to allow search for. """ return self.get_model().objects.published() class FlatPageIndex(FluentPageIndex): """ Search index for a flat page. As everything except the model is the same as for a FluentPageIndex we shall subclass it and overwrite the one part we need. """ @staticmethod def get_model(): """ Get the model for the search index. """ return FlatPage
from fluent_pages.pagetypes.flatpage.models import FlatPage from fluent_pages.pagetypes.fluentpage.models import FluentPage from haystack import indexes from django.conf import settings # Optional search indexes which can be used with the default FluentPage and FlatPage models. if getattr(settings, 'ICEKIT_USE_SEARCH_INDEXES', True): class FluentPageIndex(indexes.SearchIndex, indexes.Indexable): """ Search index for a fluent page. """ text = indexes.CharField(document=True, use_template=True) author = indexes.CharField(model_attr='author') publication_date = indexes.DateTimeField(model_attr='publication_date', null=True) @staticmethod def get_model(): """ Get the model for the search index. """ return FluentPage def index_queryset(self, using=None): """ Queryset appropriate for this object to allow search for. """ return self.get_model().objects.published() class FlatPageIndex(FluentPageIndex): """ Search index for a flat page. As everything except the model is the same as for a FluentPageIndex we shall subclass it and overwrite the one part we need. """ @staticmethod def get_model(): """ Get the model for the search index. """ return FlatPage
Add setting to turn of search indexes.
Add setting to turn of search indexes.
Python
mit
ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit
from fluent_pages.pagetypes.flatpage.models import FlatPage from fluent_pages.pagetypes.fluentpage.models import FluentPage from haystack import indexes + from django.conf import settings + # Optional search indexes which can be used with the default FluentPage and FlatPage models. + if getattr(settings, 'ICEKIT_USE_SEARCH_INDEXES', True): - class FluentPageIndex(indexes.SearchIndex, indexes.Indexable): + class FluentPageIndex(indexes.SearchIndex, indexes.Indexable): - """ + """ - Search index for a fluent page. + Search index for a fluent page. - """ + """ - text = indexes.CharField(document=True, use_template=True) + text = indexes.CharField(document=True, use_template=True) - author = indexes.CharField(model_attr='author') + author = indexes.CharField(model_attr='author') - publication_date = indexes.DateTimeField(model_attr='publication_date', null=True) + publication_date = indexes.DateTimeField(model_attr='publication_date', null=True) - @staticmethod + @staticmethod - def get_model(): + def get_model(): - """ + """ - Get the model for the search index. + Get the model for the search index. - """ + """ - return FluentPage + return FluentPage - def index_queryset(self, using=None): + def index_queryset(self, using=None): - """ + """ - Queryset appropriate for this object to allow search for. + Queryset appropriate for this object to allow search for. - """ + """ - return self.get_model().objects.published() + return self.get_model().objects.published() - class FlatPageIndex(FluentPageIndex): + class FlatPageIndex(FluentPageIndex): - """ + """ - Search index for a flat page. + Search index for a flat page. - As everything except the model is the same as for a FluentPageIndex + As everything except the model is the same as for a FluentPageIndex - we shall subclass it and overwrite the one part we need. + we shall subclass it and overwrite the one part we need. - """ - @staticmethod - def get_model(): """ + @staticmethod + def get_model(): + """ - Get the model for the search index. + Get the model for the search index. - """ + """ - return FlatPage + return FlatPage
Add setting to turn of search indexes.
## Code Before: from fluent_pages.pagetypes.flatpage.models import FlatPage from fluent_pages.pagetypes.fluentpage.models import FluentPage from haystack import indexes class FluentPageIndex(indexes.SearchIndex, indexes.Indexable): """ Search index for a fluent page. """ text = indexes.CharField(document=True, use_template=True) author = indexes.CharField(model_attr='author') publication_date = indexes.DateTimeField(model_attr='publication_date', null=True) @staticmethod def get_model(): """ Get the model for the search index. """ return FluentPage def index_queryset(self, using=None): """ Queryset appropriate for this object to allow search for. """ return self.get_model().objects.published() class FlatPageIndex(FluentPageIndex): """ Search index for a flat page. As everything except the model is the same as for a FluentPageIndex we shall subclass it and overwrite the one part we need. """ @staticmethod def get_model(): """ Get the model for the search index. """ return FlatPage ## Instruction: Add setting to turn of search indexes. ## Code After: from fluent_pages.pagetypes.flatpage.models import FlatPage from fluent_pages.pagetypes.fluentpage.models import FluentPage from haystack import indexes from django.conf import settings # Optional search indexes which can be used with the default FluentPage and FlatPage models. if getattr(settings, 'ICEKIT_USE_SEARCH_INDEXES', True): class FluentPageIndex(indexes.SearchIndex, indexes.Indexable): """ Search index for a fluent page. """ text = indexes.CharField(document=True, use_template=True) author = indexes.CharField(model_attr='author') publication_date = indexes.DateTimeField(model_attr='publication_date', null=True) @staticmethod def get_model(): """ Get the model for the search index. """ return FluentPage def index_queryset(self, using=None): """ Queryset appropriate for this object to allow search for. """ return self.get_model().objects.published() class FlatPageIndex(FluentPageIndex): """ Search index for a flat page. As everything except the model is the same as for a FluentPageIndex we shall subclass it and overwrite the one part we need. """ @staticmethod def get_model(): """ Get the model for the search index. """ return FlatPage
... from haystack import indexes from django.conf import settings ... # Optional search indexes which can be used with the default FluentPage and FlatPage models. if getattr(settings, 'ICEKIT_USE_SEARCH_INDEXES', True): class FluentPageIndex(indexes.SearchIndex, indexes.Indexable): """ Search index for a fluent page. """ text = indexes.CharField(document=True, use_template=True) author = indexes.CharField(model_attr='author') publication_date = indexes.DateTimeField(model_attr='publication_date', null=True) @staticmethod def get_model(): """ Get the model for the search index. """ return FluentPage def index_queryset(self, using=None): """ Queryset appropriate for this object to allow search for. """ return self.get_model().objects.published() ... class FlatPageIndex(FluentPageIndex): """ Search index for a flat page. As everything except the model is the same as for a FluentPageIndex we shall subclass it and overwrite the one part we need. """ @staticmethod def get_model(): """ Get the model for the search index. """ return FlatPage ...
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])
... """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): ...
02c74c5235b8ad821786213a3bcf5f824162454d
flax/linen/combinators.py
flax/linen/combinators.py
"""Combinators of modules, such as a Sequential.""" from typing import Callable, Sequence from flax.linen.module import Module class Sequential(Module): """Applies a linear chain of Modules. Meant to be used only for the simple case of fusing together callables where the input of a particular module/op is the output of the previous one. Modules will be applied in the order that they are passed in the constructor. The apply() method of Sequential accepts any input and forwards it to the first module it contains. It chains the output sequentially to the input of the next module and returns the output of the final module. Example usage:: class Foo(nn.Module): feature_sizes: Sequence[int] @nn.compact def __call__(self, x): return nn.Sequential([nn.Dense(layer_size, name=f'layers_{idx}') for idx, layer_size in enumerate(self.feature_sizes)])(x) """ layers: Sequence[Callable] def __call__(self, *args, **kwargs): if not self.layers: raise ValueError(f'Empty Sequential module {self.name}.') outputs = self.layers[0](*args, **kwargs) for layer in self.layers[1:]: outputs = layer(outputs) return outputs
"""Combinators of modules, such as a Sequential.""" from typing import Callable, Sequence from flax.linen.module import Module class Sequential(Module): """Applies a linear chain of Modules. Meant to be used only for the simple case of fusing together callables where the input of a particular module/op is the output of the previous one. Modules will be applied in the order that they are passed in the constructor. The apply() method of Sequential accepts any input and forwards it to the first module it contains. It chains the output sequentially to the input of the next module and returns the output of the final module. Example usage:: class Foo(nn.Module): feature_sizes: Sequence[int] @nn.compact def __call__(self, x): return nn.Sequential([nn.Dense(4), nn.relu, nn.Dense(2), nn.log_softmax])(x) """ layers: Sequence[Callable] def __call__(self, *args, **kwargs): if not self.layers: raise ValueError(f'Empty Sequential module {self.name}.') outputs = self.layers[0](*args, **kwargs) for layer in self.layers[1:]: outputs = layer(outputs) return outputs
Include activations in Sequential example.
Include activations in Sequential example.
Python
apache-2.0
google/flax,google/flax
"""Combinators of modules, such as a Sequential.""" from typing import Callable, Sequence from flax.linen.module import Module class Sequential(Module): """Applies a linear chain of Modules. Meant to be used only for the simple case of fusing together callables where the input of a particular module/op is the output of the previous one. Modules will be applied in the order that they are passed in the constructor. The apply() method of Sequential accepts any input and forwards it to the first module it contains. It chains the output sequentially to the input of the next module and returns the output of the final module. Example usage:: class Foo(nn.Module): - feature_sizes: Sequence[int] + feature_sizes: Sequence[int] - @nn.compact + @nn.compact - def __call__(self, x): + def __call__(self, x): - return nn.Sequential([nn.Dense(layer_size, name=f'layers_{idx}') - for idx, layer_size - in enumerate(self.feature_sizes)])(x) + return nn.Sequential([nn.Dense(4), + nn.relu, + nn.Dense(2), + nn.log_softmax])(x) """ layers: Sequence[Callable] def __call__(self, *args, **kwargs): if not self.layers: raise ValueError(f'Empty Sequential module {self.name}.') outputs = self.layers[0](*args, **kwargs) for layer in self.layers[1:]: outputs = layer(outputs) return outputs
Include activations in Sequential example.
## Code Before: """Combinators of modules, such as a Sequential.""" from typing import Callable, Sequence from flax.linen.module import Module class Sequential(Module): """Applies a linear chain of Modules. Meant to be used only for the simple case of fusing together callables where the input of a particular module/op is the output of the previous one. Modules will be applied in the order that they are passed in the constructor. The apply() method of Sequential accepts any input and forwards it to the first module it contains. It chains the output sequentially to the input of the next module and returns the output of the final module. Example usage:: class Foo(nn.Module): feature_sizes: Sequence[int] @nn.compact def __call__(self, x): return nn.Sequential([nn.Dense(layer_size, name=f'layers_{idx}') for idx, layer_size in enumerate(self.feature_sizes)])(x) """ layers: Sequence[Callable] def __call__(self, *args, **kwargs): if not self.layers: raise ValueError(f'Empty Sequential module {self.name}.') outputs = self.layers[0](*args, **kwargs) for layer in self.layers[1:]: outputs = layer(outputs) return outputs ## Instruction: Include activations in Sequential example. ## Code After: """Combinators of modules, such as a Sequential.""" from typing import Callable, Sequence from flax.linen.module import Module class Sequential(Module): """Applies a linear chain of Modules. Meant to be used only for the simple case of fusing together callables where the input of a particular module/op is the output of the previous one. Modules will be applied in the order that they are passed in the constructor. The apply() method of Sequential accepts any input and forwards it to the first module it contains. It chains the output sequentially to the input of the next module and returns the output of the final module. Example usage:: class Foo(nn.Module): feature_sizes: Sequence[int] @nn.compact def __call__(self, x): return nn.Sequential([nn.Dense(4), nn.relu, nn.Dense(2), nn.log_softmax])(x) """ layers: Sequence[Callable] def __call__(self, *args, **kwargs): if not self.layers: raise ValueError(f'Empty Sequential module {self.name}.') outputs = self.layers[0](*args, **kwargs) for layer in self.layers[1:]: outputs = layer(outputs) return outputs
# ... existing code ... class Foo(nn.Module): feature_sizes: Sequence[int] @nn.compact def __call__(self, x): return nn.Sequential([nn.Dense(4), nn.relu, nn.Dense(2), nn.log_softmax])(x) """ # ... rest of the code ...
a42a7e237a72825080fa0afea263dbd5766417bb
conary/lib/digestlib.py
conary/lib/digestlib.py
"Compatibility module for python 2.4 - 2.6" try: import hashlib sha1 = hashlib.sha1 md5 = hashlib.md5 sha256 = hashlib.sha256 except ImportError: import sha import md5 from Crypto.Hash import SHA256 sha1 = sha.new md5 = md5.new sha256 = SHA256.new
"Compatibility module for python 2.4 - 2.6" try: import hashlib sha1 = hashlib.sha1 md5 = hashlib.md5 except ImportError: import sha import md5 sha1 = sha.new md5 = md5.new from Crypto.Hash import SHA256 sha256 = SHA256.new
Use sha256 algorithm from pycrypto.
Use sha256 algorithm from pycrypto.
Python
apache-2.0
fedora-conary/conary,fedora-conary/conary,fedora-conary/conary,fedora-conary/conary,fedora-conary/conary
"Compatibility module for python 2.4 - 2.6" try: import hashlib sha1 = hashlib.sha1 md5 = hashlib.md5 - sha256 = hashlib.sha256 except ImportError: import sha import md5 - from Crypto.Hash import SHA256 sha1 = sha.new md5 = md5.new + from Crypto.Hash import SHA256 - sha256 = SHA256.new + sha256 = SHA256.new
Use sha256 algorithm from pycrypto.
## Code Before: "Compatibility module for python 2.4 - 2.6" try: import hashlib sha1 = hashlib.sha1 md5 = hashlib.md5 sha256 = hashlib.sha256 except ImportError: import sha import md5 from Crypto.Hash import SHA256 sha1 = sha.new md5 = md5.new sha256 = SHA256.new ## Instruction: Use sha256 algorithm from pycrypto. ## Code After: "Compatibility module for python 2.4 - 2.6" try: import hashlib sha1 = hashlib.sha1 md5 = hashlib.md5 except ImportError: import sha import md5 sha1 = sha.new md5 = md5.new from Crypto.Hash import SHA256 sha256 = SHA256.new
// ... existing code ... md5 = hashlib.md5 except ImportError: // ... modified code ... import md5 sha1 = sha.new ... md5 = md5.new from Crypto.Hash import SHA256 sha256 = SHA256.new // ... rest of the code ...
a0e835cbf382cb55ff872bb8d6cc57a5326a82de
ckanext/ckanext-apicatalog_scheming/ckanext/apicatalog_scheming/validators.py
ckanext/ckanext-apicatalog_scheming/ckanext/apicatalog_scheming/validators.py
from ckan.common import _ import ckan.lib.navl.dictization_functions as df def lower_if_exists(s): return s.lower() if s else s def upper_if_exists(s): return s.upper() if s else s def valid_resources(private, context): package = context.get('package') if not private or private == u'False': for resource in package.resources: if resource.extras.get('valid_content') == 'no': raise df.Invalid(_("Package contains invalid resources")) return private
from ckan.common import _ import ckan.lib.navl.dictization_functions as df def lower_if_exists(s): return s.lower() if s else s def upper_if_exists(s): return s.upper() if s else s def valid_resources(private, context): package = context.get('package') if package and (not private or private == u'False'): for resource in package.resources: if resource.extras.get('valid_content') == 'no': raise df.Invalid(_("Package contains invalid resources")) return private
Fix package resource validator for new packages
LK-271: Fix package resource validator for new packages
Python
mit
vrk-kpa/api-catalog,vrk-kpa/api-catalog,vrk-kpa/api-catalog,vrk-kpa/api-catalog
from ckan.common import _ import ckan.lib.navl.dictization_functions as df def lower_if_exists(s): return s.lower() if s else s def upper_if_exists(s): return s.upper() if s else s def valid_resources(private, context): package = context.get('package') - if not private or private == u'False': + if package and (not private or private == u'False'): for resource in package.resources: if resource.extras.get('valid_content') == 'no': raise df.Invalid(_("Package contains invalid resources")) return private
Fix package resource validator for new packages
## Code Before: from ckan.common import _ import ckan.lib.navl.dictization_functions as df def lower_if_exists(s): return s.lower() if s else s def upper_if_exists(s): return s.upper() if s else s def valid_resources(private, context): package = context.get('package') if not private or private == u'False': for resource in package.resources: if resource.extras.get('valid_content') == 'no': raise df.Invalid(_("Package contains invalid resources")) return private ## Instruction: Fix package resource validator for new packages ## Code After: from ckan.common import _ import ckan.lib.navl.dictization_functions as df def lower_if_exists(s): return s.lower() if s else s def upper_if_exists(s): return s.upper() if s else s def valid_resources(private, context): package = context.get('package') if package and (not private or private == u'False'): for resource in package.resources: if resource.extras.get('valid_content') == 'no': raise df.Invalid(_("Package contains invalid resources")) return private
# ... existing code ... package = context.get('package') if package and (not private or private == u'False'): for resource in package.resources: # ... rest of the code ...
98552a4cb683e25ec9af53024e58644c04b55872
molly/external_media/views.py
molly/external_media/views.py
from email.utils import formatdate from datetime import datetime, timedelta from time import mktime from django.shortcuts import get_object_or_404 from django.http import HttpResponse, Http404 from molly.utils.views import BaseView from molly.utils.breadcrumbs import NullBreadcrumb from models import ExternalImageSized class IndexView(BaseView): breadcrumb = NullBreadcrumb def handle_GET(self, request, context): raise Http404 class ExternalImageView(BaseView): breadcrumb = NullBreadcrumb def handle_GET(self, request, context, slug): eis = get_object_or_404(ExternalImageSized, slug=slug) response = HttpResponse(open(eis.get_filename(), 'rb').read(), mimetype=eis.content_type.encode('ascii')) response['ETag'] = slug response['Expires'] = formatdate(mktime((datetime.now() + timedelta(days=7)).timetuple())) response['Last-Modified'] = formatdate(mktime(eis.external_image.last_updated.timetuple())) return response
from email.utils import formatdate from datetime import datetime, timedelta from time import mktime from django.shortcuts import get_object_or_404 from django.http import HttpResponse, Http404 from molly.utils.views import BaseView from molly.utils.breadcrumbs import NullBreadcrumb from models import ExternalImageSized class IndexView(BaseView): breadcrumb = NullBreadcrumb def handle_GET(self, request, context): raise Http404 class ExternalImageView(BaseView): breadcrumb = NullBreadcrumb def handle_GET(self, request, context, slug): eis = get_object_or_404(ExternalImageSized, slug=slug) try: response = HttpResponse(open(eis.get_filename(), 'rb').read(), mimetype=eis.content_type.encode('ascii')) except IOError: eis.delete() raise Http404() response['ETag'] = slug response['Expires'] = formatdate(mktime((datetime.now() + timedelta(days=7)).timetuple())) response['Last-Modified'] = formatdate(mktime(eis.external_image.last_updated.timetuple())) return response
Handle missing external files gracefully
MOX-182: Handle missing external files gracefully
Python
apache-2.0
mollyproject/mollyproject,mollyproject/mollyproject,mollyproject/mollyproject
from email.utils import formatdate from datetime import datetime, timedelta from time import mktime from django.shortcuts import get_object_or_404 from django.http import HttpResponse, Http404 from molly.utils.views import BaseView from molly.utils.breadcrumbs import NullBreadcrumb from models import ExternalImageSized class IndexView(BaseView): breadcrumb = NullBreadcrumb def handle_GET(self, request, context): raise Http404 class ExternalImageView(BaseView): breadcrumb = NullBreadcrumb def handle_GET(self, request, context, slug): eis = get_object_or_404(ExternalImageSized, slug=slug) - response = HttpResponse(open(eis.get_filename(), 'rb').read(), mimetype=eis.content_type.encode('ascii')) + try: + response = HttpResponse(open(eis.get_filename(), 'rb').read(), + mimetype=eis.content_type.encode('ascii')) + except IOError: + eis.delete() + raise Http404() response['ETag'] = slug response['Expires'] = formatdate(mktime((datetime.now() + timedelta(days=7)).timetuple())) response['Last-Modified'] = formatdate(mktime(eis.external_image.last_updated.timetuple())) return response
Handle missing external files gracefully
## Code Before: from email.utils import formatdate from datetime import datetime, timedelta from time import mktime from django.shortcuts import get_object_or_404 from django.http import HttpResponse, Http404 from molly.utils.views import BaseView from molly.utils.breadcrumbs import NullBreadcrumb from models import ExternalImageSized class IndexView(BaseView): breadcrumb = NullBreadcrumb def handle_GET(self, request, context): raise Http404 class ExternalImageView(BaseView): breadcrumb = NullBreadcrumb def handle_GET(self, request, context, slug): eis = get_object_or_404(ExternalImageSized, slug=slug) response = HttpResponse(open(eis.get_filename(), 'rb').read(), mimetype=eis.content_type.encode('ascii')) response['ETag'] = slug response['Expires'] = formatdate(mktime((datetime.now() + timedelta(days=7)).timetuple())) response['Last-Modified'] = formatdate(mktime(eis.external_image.last_updated.timetuple())) return response ## Instruction: Handle missing external files gracefully ## Code After: from email.utils import formatdate from datetime import datetime, timedelta from time import mktime from django.shortcuts import get_object_or_404 from django.http import HttpResponse, Http404 from molly.utils.views import BaseView from molly.utils.breadcrumbs import NullBreadcrumb from models import ExternalImageSized class IndexView(BaseView): breadcrumb = NullBreadcrumb def handle_GET(self, request, context): raise Http404 class ExternalImageView(BaseView): breadcrumb = NullBreadcrumb def handle_GET(self, request, context, slug): eis = get_object_or_404(ExternalImageSized, slug=slug) try: response = HttpResponse(open(eis.get_filename(), 'rb').read(), mimetype=eis.content_type.encode('ascii')) except IOError: eis.delete() raise Http404() response['ETag'] = slug response['Expires'] = formatdate(mktime((datetime.now() + timedelta(days=7)).timetuple())) response['Last-Modified'] = formatdate(mktime(eis.external_image.last_updated.timetuple())) return response
// ... existing code ... eis = get_object_or_404(ExternalImageSized, slug=slug) try: response = HttpResponse(open(eis.get_filename(), 'rb').read(), mimetype=eis.content_type.encode('ascii')) except IOError: eis.delete() raise Http404() // ... rest of the code ...
aa8234d1e6b4916e6945468a2bc5772df2d53e28
bot/admin.py
bot/admin.py
from __future__ import unicode_literals from django.contrib import admin from . import models @admin.register(models.Notification) class NotificationAdmin(admin.ModelAdmin): list_display = ('launch', 'last_net_stamp', 'last_twitter_post', 'last_notification_sent', 'last_notification_recipient_count', 'days_to_launch') readonly_fields = ('days_to_launch',) ordering = ('launch__net',) search_fields = ('launch__name',) @admin.register(models.DailyDigestRecord) class DailyDigestRecordAdmin(admin.ModelAdmin): list_display = ('id', 'timestamp', 'messages', 'count', 'data')
from __future__ import unicode_literals from django.contrib import admin from . import models @admin.register(models.Notification) class NotificationAdmin(admin.ModelAdmin): list_display = ('launch', 'last_net_stamp', 'last_twitter_post', 'last_notification_sent', 'last_notification_recipient_count', 'days_to_launch') readonly_fields = ('days_to_launch',) ordering = ('launch__net',) search_fields = ('launch__name',) @admin.register(models.DailyDigestRecord) class DailyDigestRecordAdmin(admin.ModelAdmin): list_display = ('id', 'timestamp', 'messages', 'count', 'data') @admin.register(models.DiscordChannel) class DiscordBotAdmin(admin.ModelAdmin): list_display = ('name', 'channel_id', 'server_id')
Add Discord Admin for debugging.
Add Discord Admin for debugging.
Python
apache-2.0
ItsCalebJones/SpaceLaunchNow-Server,ItsCalebJones/SpaceLaunchNow-Server,ItsCalebJones/SpaceLaunchNow-Server
from __future__ import unicode_literals from django.contrib import admin from . import models @admin.register(models.Notification) class NotificationAdmin(admin.ModelAdmin): list_display = ('launch', 'last_net_stamp', 'last_twitter_post', 'last_notification_sent', 'last_notification_recipient_count', 'days_to_launch') readonly_fields = ('days_to_launch',) ordering = ('launch__net',) search_fields = ('launch__name',) @admin.register(models.DailyDigestRecord) class DailyDigestRecordAdmin(admin.ModelAdmin): list_display = ('id', 'timestamp', 'messages', 'count', 'data') + + + @admin.register(models.DiscordChannel) + class DiscordBotAdmin(admin.ModelAdmin): + list_display = ('name', 'channel_id', 'server_id')
Add Discord Admin for debugging.
## Code Before: from __future__ import unicode_literals from django.contrib import admin from . import models @admin.register(models.Notification) class NotificationAdmin(admin.ModelAdmin): list_display = ('launch', 'last_net_stamp', 'last_twitter_post', 'last_notification_sent', 'last_notification_recipient_count', 'days_to_launch') readonly_fields = ('days_to_launch',) ordering = ('launch__net',) search_fields = ('launch__name',) @admin.register(models.DailyDigestRecord) class DailyDigestRecordAdmin(admin.ModelAdmin): list_display = ('id', 'timestamp', 'messages', 'count', 'data') ## Instruction: Add Discord Admin for debugging. ## Code After: from __future__ import unicode_literals from django.contrib import admin from . import models @admin.register(models.Notification) class NotificationAdmin(admin.ModelAdmin): list_display = ('launch', 'last_net_stamp', 'last_twitter_post', 'last_notification_sent', 'last_notification_recipient_count', 'days_to_launch') readonly_fields = ('days_to_launch',) ordering = ('launch__net',) search_fields = ('launch__name',) @admin.register(models.DailyDigestRecord) class DailyDigestRecordAdmin(admin.ModelAdmin): list_display = ('id', 'timestamp', 'messages', 'count', 'data') @admin.register(models.DiscordChannel) class DiscordBotAdmin(admin.ModelAdmin): list_display = ('name', 'channel_id', 'server_id')
// ... existing code ... list_display = ('id', 'timestamp', 'messages', 'count', 'data') @admin.register(models.DiscordChannel) class DiscordBotAdmin(admin.ModelAdmin): list_display = ('name', 'channel_id', 'server_id') // ... rest of the code ...
1de4a0edd0f3c43b53e3a91c10d23155889791c6
tca/chat/tests.py
tca/chat/tests.py
from django.test import TestCase # Create your tests here.
from django.test import TestCase from django.core.urlresolvers import reverse from urllib import urlencode import json class ViewTestCaseMixin(object): """A mixin providing some convenience methods for testing views. Expects that a ``view_name`` property exists on the class which mixes it in. """ def get_view_url(self, *args, **kwargs): return reverse(self.view_name, args=args, kwargs=kwargs) def build_url(self, base_url, query_dict=None): url_template = "{base_url}?{query_string}" if query_dict is None: return base_url return url_template.format( base_url=base_url, query_string=urlencode(query_dict) ) def get(self, parameters=None, *args, **kwargs): """ Sends a GET request to the view-under-test and returns the response :param parameters: The query string parameters of the GET request """ base_url = self.get_view_url(*args, **kwargs) return self.client.get(self.build_url(base_url, parameters)) def post(self, body=None, content_type='application/json', *args, **kwargs): """ Sends a POST request to the view-under-test and returns the response :param body: The content to be included in the body of the request """ base_url = self.get_view_url(*args, **kwargs) if body is None: body = '' return self.client.post( self.build_url(base_url), body, content_type=content_type) def post_json(self, json_payload, *args, **kwargs): """ Sends a POST request to the view-under-test and returns the response. The body of the POST request is formed by serializing the ``json_payload`` object to JSON. """ payload = json.dumps(json_payload) return self.post( body=payload, content_type='application/json', *args, **kwargs)
Add a helper mixin for view test cases
Add a helper mixin for view test cases The mixin defines some helper methods which are useful when testing views (REST endpoints).
Python
bsd-3-clause
mlalic/TumCampusAppBackend,mlalic/TumCampusAppBackend
from django.test import TestCase - # Create your tests here. + from django.core.urlresolvers import reverse + from urllib import urlencode + import json + + + class ViewTestCaseMixin(object): + """A mixin providing some convenience methods for testing views. + + Expects that a ``view_name`` property exists on the class which + mixes it in. + """ + + def get_view_url(self, *args, **kwargs): + return reverse(self.view_name, args=args, kwargs=kwargs) + + def build_url(self, base_url, query_dict=None): + url_template = "{base_url}?{query_string}" + + if query_dict is None: + return base_url + + return url_template.format( + base_url=base_url, + query_string=urlencode(query_dict) + ) + + def get(self, parameters=None, *args, **kwargs): + """ + Sends a GET request to the view-under-test and returns the response + + :param parameters: The query string parameters of the GET request + """ + base_url = self.get_view_url(*args, **kwargs) + + return self.client.get(self.build_url(base_url, parameters)) + + def post(self, body=None, content_type='application/json', *args, **kwargs): + """ + Sends a POST request to the view-under-test and returns the response + + :param body: The content to be included in the body of the request + """ + base_url = self.get_view_url(*args, **kwargs) + + if body is None: + body = '' + + return self.client.post( + self.build_url(base_url), + body, + content_type=content_type) + + def post_json(self, json_payload, *args, **kwargs): + """ + Sends a POST request to the view-under-test and returns the response. + The body of the POST request is formed by serializing the + ``json_payload`` object to JSON. + """ + payload = json.dumps(json_payload) + + return self.post( + body=payload, + content_type='application/json', + *args, **kwargs) +
Add a helper mixin for view test cases
## Code Before: from django.test import TestCase # Create your tests here. ## Instruction: Add a helper mixin for view test cases ## Code After: from django.test import TestCase from django.core.urlresolvers import reverse from urllib import urlencode import json class ViewTestCaseMixin(object): """A mixin providing some convenience methods for testing views. Expects that a ``view_name`` property exists on the class which mixes it in. """ def get_view_url(self, *args, **kwargs): return reverse(self.view_name, args=args, kwargs=kwargs) def build_url(self, base_url, query_dict=None): url_template = "{base_url}?{query_string}" if query_dict is None: return base_url return url_template.format( base_url=base_url, query_string=urlencode(query_dict) ) def get(self, parameters=None, *args, **kwargs): """ Sends a GET request to the view-under-test and returns the response :param parameters: The query string parameters of the GET request """ base_url = self.get_view_url(*args, **kwargs) return self.client.get(self.build_url(base_url, parameters)) def post(self, body=None, content_type='application/json', *args, **kwargs): """ Sends a POST request to the view-under-test and returns the response :param body: The content to be included in the body of the request """ base_url = self.get_view_url(*args, **kwargs) if body is None: body = '' return self.client.post( self.build_url(base_url), body, content_type=content_type) def post_json(self, json_payload, *args, **kwargs): """ Sends a POST request to the view-under-test and returns the response. The body of the POST request is formed by serializing the ``json_payload`` object to JSON. """ payload = json.dumps(json_payload) return self.post( body=payload, content_type='application/json', *args, **kwargs)
// ... existing code ... from django.core.urlresolvers import reverse from urllib import urlencode import json class ViewTestCaseMixin(object): """A mixin providing some convenience methods for testing views. Expects that a ``view_name`` property exists on the class which mixes it in. """ def get_view_url(self, *args, **kwargs): return reverse(self.view_name, args=args, kwargs=kwargs) def build_url(self, base_url, query_dict=None): url_template = "{base_url}?{query_string}" if query_dict is None: return base_url return url_template.format( base_url=base_url, query_string=urlencode(query_dict) ) def get(self, parameters=None, *args, **kwargs): """ Sends a GET request to the view-under-test and returns the response :param parameters: The query string parameters of the GET request """ base_url = self.get_view_url(*args, **kwargs) return self.client.get(self.build_url(base_url, parameters)) def post(self, body=None, content_type='application/json', *args, **kwargs): """ Sends a POST request to the view-under-test and returns the response :param body: The content to be included in the body of the request """ base_url = self.get_view_url(*args, **kwargs) if body is None: body = '' return self.client.post( self.build_url(base_url), body, content_type=content_type) def post_json(self, json_payload, *args, **kwargs): """ Sends a POST request to the view-under-test and returns the response. The body of the POST request is formed by serializing the ``json_payload`` object to JSON. """ payload = json.dumps(json_payload) return self.post( body=payload, content_type='application/json', *args, **kwargs) // ... rest of the code ...
82b4e19e4d12c9a44c4258afaa78a7e386e0f7de
wiblog/formatting.py
wiblog/formatting.py
from django.utils.safestring import mark_safe import CommonMark # Convert a markdown string into HTML5, and prevent Django from escaping it def mdToHTML(value): return mark_safe(CommonMark.commonmark(value)) # Get a summary of a post def summarize(fullBody): firstNewline = fullBody.find("\n") if firstNewline > 0: return fullBody[:firstNewline] return fullBody
import CommonMark from images.models import Image from django.utils.safestring import mark_safe from django.core.exceptions import ObjectDoesNotExist import re def mdToHTML(value): """Convert a markdown string into HTML5, and prevent Django from escaping it """ tags = [] # Find all instance of the dynamic image markdown for tag in re.finditer(r'\!\[I:([\w-]+)\]', value): tag_slug = tag.group(1) try: image = Image.objects.get(slug=tag_slug) tag_dict = dict() tag_dict['start'] = tag.start() tag_dict['end'] = tag.end() tag_dict['image'] = image tags.append(tag_dict) except ObjectDoesNotExist: pass # Replace all of the tags with actual markdown image tags, backwards, to # prevent changing string positions and messing up substitution for tag_dict in reversed(tags): value = value[:tag_dict['start']] + \ '![{}]({})'.format(tag_dict['image'].desc, tag_dict['image'].get_absolute_url()) + \ value[tag_dict['end']:] return mark_safe(CommonMark.commonmark(value)) def summarize(fullBody): """ Get a summary of a post """ firstNewline = fullBody.find("\n") if firstNewline > 0: return fullBody[:firstNewline] return fullBody
Add code to replace custom dynamic image tag with standard markdown image syntax
Add code to replace custom dynamic image tag with standard markdown image syntax
Python
agpl-3.0
lo-windigo/fragdev,lo-windigo/fragdev
+ import CommonMark + from images.models import Image from django.utils.safestring import mark_safe - import CommonMark + from django.core.exceptions import ObjectDoesNotExist + import re - # Convert a markdown string into HTML5, and prevent Django from escaping it def mdToHTML(value): + """Convert a markdown string into HTML5, and prevent Django from escaping it + """ + tags = [] + + # Find all instance of the dynamic image markdown + for tag in re.finditer(r'\!\[I:([\w-]+)\]', value): + + tag_slug = tag.group(1) + + try: + image = Image.objects.get(slug=tag_slug) + tag_dict = dict() + + tag_dict['start'] = tag.start() + tag_dict['end'] = tag.end() + tag_dict['image'] = image + + tags.append(tag_dict) + + except ObjectDoesNotExist: + pass + + # Replace all of the tags with actual markdown image tags, backwards, to + # prevent changing string positions and messing up substitution + for tag_dict in reversed(tags): + + value = value[:tag_dict['start']] + \ + '![{}]({})'.format(tag_dict['image'].desc, + tag_dict['image'].get_absolute_url()) + \ + value[tag_dict['end']:] return mark_safe(CommonMark.commonmark(value)) - # Get a summary of a post def summarize(fullBody): + """ Get a summary of a post + """ firstNewline = fullBody.find("\n") if firstNewline > 0: return fullBody[:firstNewline] return fullBody
Add code to replace custom dynamic image tag with standard markdown image syntax
## Code Before: from django.utils.safestring import mark_safe import CommonMark # Convert a markdown string into HTML5, and prevent Django from escaping it def mdToHTML(value): return mark_safe(CommonMark.commonmark(value)) # Get a summary of a post def summarize(fullBody): firstNewline = fullBody.find("\n") if firstNewline > 0: return fullBody[:firstNewline] return fullBody ## Instruction: Add code to replace custom dynamic image tag with standard markdown image syntax ## Code After: import CommonMark from images.models import Image from django.utils.safestring import mark_safe from django.core.exceptions import ObjectDoesNotExist import re def mdToHTML(value): """Convert a markdown string into HTML5, and prevent Django from escaping it """ tags = [] # Find all instance of the dynamic image markdown for tag in re.finditer(r'\!\[I:([\w-]+)\]', value): tag_slug = tag.group(1) try: image = Image.objects.get(slug=tag_slug) tag_dict = dict() tag_dict['start'] = tag.start() tag_dict['end'] = tag.end() tag_dict['image'] = image tags.append(tag_dict) except ObjectDoesNotExist: pass # Replace all of the tags with actual markdown image tags, backwards, to # prevent changing string positions and messing up substitution for tag_dict in reversed(tags): value = value[:tag_dict['start']] + \ '![{}]({})'.format(tag_dict['image'].desc, tag_dict['image'].get_absolute_url()) + \ value[tag_dict['end']:] return mark_safe(CommonMark.commonmark(value)) def summarize(fullBody): """ Get a summary of a post """ firstNewline = fullBody.find("\n") if firstNewline > 0: return fullBody[:firstNewline] return fullBody
# ... existing code ... import CommonMark from images.models import Image from django.utils.safestring import mark_safe from django.core.exceptions import ObjectDoesNotExist import re # ... modified code ... def mdToHTML(value): """Convert a markdown string into HTML5, and prevent Django from escaping it """ tags = [] # Find all instance of the dynamic image markdown for tag in re.finditer(r'\!\[I:([\w-]+)\]', value): tag_slug = tag.group(1) try: image = Image.objects.get(slug=tag_slug) tag_dict = dict() tag_dict['start'] = tag.start() tag_dict['end'] = tag.end() tag_dict['image'] = image tags.append(tag_dict) except ObjectDoesNotExist: pass # Replace all of the tags with actual markdown image tags, backwards, to # prevent changing string positions and messing up substitution for tag_dict in reversed(tags): value = value[:tag_dict['start']] + \ '![{}]({})'.format(tag_dict['image'].desc, tag_dict['image'].get_absolute_url()) + \ value[tag_dict['end']:] ... def summarize(fullBody): """ Get a summary of a post """ # ... rest of the code ...
3e81a2bfd026475b9ab0548c3127aa102066707d
guest-talks/20170828-oo-intro/exercises/test_square_grid.py
guest-talks/20170828-oo-intro/exercises/test_square_grid.py
import unittest from square_grid import SquareGrid class TestSquareGrid(unittest.TestCase): def setUp(self): a = [0] * 3 b = [1] * 3 c = [2] * 3 self.matrix= [a,b,c] self.good_grid = SquareGrid(self.matrix) def test_error_on_mixed_dimensions(self): """Test object initialization""" four_by_three = self.matrix + [[3] * 3] with self.assertRaises(ValueError) as err: g = SquareGrid(four_by_three) def test_string_representation(self): """Test that the object behaves correctly with the `str()` built-n""" expected_string = '\n'.join(' '.join(str(x) for x in row) for row in m) self.assertEqual(str(self.good_grid), expected_string) def test_length(self): """Test that the object returns a useful length""" self.assertEqual(len(self.good_grid), 3)
import unittest from square_grid import SquareGrid class TestSquareGrid(unittest.TestCase): def setUp(self): a = [0] * 3 b = [1] * 3 c = [2] * 3 self.matrix= [a,b,c] self.good_grid = SquareGrid(self.matrix) def test_error_on_mixed_dimensions(self): """Test object initialization""" four_by_three = self.matrix + [[3] * 3] with self.assertRaises(ValueError) as err: g = SquareGrid(four_by_three) def test_string_representation(self): """Test that the object behaves correctly with the `str()` built-in""" expected_string = "0 0 0\n1 1 1\n2 2 2" self.assertEqual(str(self.good_grid), expected_string) def test_length(self): """Test that the object returns a useful length""" self.assertEqual(len(self.good_grid), 3)
Use literals in tests instead of code ;)
Use literals in tests instead of code ;)
Python
mit
noisebridge/PythonClass,razzius/PyClassLessons,PyClass/PyClassLessons,PyClass/PyClassLessons,noisebridge/PythonClass,razzius/PyClassLessons,noisebridge/PythonClass,razzius/PyClassLessons,noisebridge/PythonClass,PyClass/PyClassLessons,razzius/PyClassLessons
import unittest from square_grid import SquareGrid class TestSquareGrid(unittest.TestCase): def setUp(self): a = [0] * 3 b = [1] * 3 c = [2] * 3 self.matrix= [a,b,c] self.good_grid = SquareGrid(self.matrix) def test_error_on_mixed_dimensions(self): """Test object initialization""" four_by_three = self.matrix + [[3] * 3] with self.assertRaises(ValueError) as err: g = SquareGrid(four_by_three) def test_string_representation(self): - """Test that the object behaves correctly with the `str()` built-n""" + """Test that the object behaves correctly with the `str()` built-in""" - expected_string = '\n'.join(' '.join(str(x) for x in row) for row in m) + expected_string = "0 0 0\n1 1 1\n2 2 2" self.assertEqual(str(self.good_grid), expected_string) def test_length(self): """Test that the object returns a useful length""" self.assertEqual(len(self.good_grid), 3)
Use literals in tests instead of code ;)
## Code Before: import unittest from square_grid import SquareGrid class TestSquareGrid(unittest.TestCase): def setUp(self): a = [0] * 3 b = [1] * 3 c = [2] * 3 self.matrix= [a,b,c] self.good_grid = SquareGrid(self.matrix) def test_error_on_mixed_dimensions(self): """Test object initialization""" four_by_three = self.matrix + [[3] * 3] with self.assertRaises(ValueError) as err: g = SquareGrid(four_by_three) def test_string_representation(self): """Test that the object behaves correctly with the `str()` built-n""" expected_string = '\n'.join(' '.join(str(x) for x in row) for row in m) self.assertEqual(str(self.good_grid), expected_string) def test_length(self): """Test that the object returns a useful length""" self.assertEqual(len(self.good_grid), 3) ## Instruction: Use literals in tests instead of code ;) ## Code After: import unittest from square_grid import SquareGrid class TestSquareGrid(unittest.TestCase): def setUp(self): a = [0] * 3 b = [1] * 3 c = [2] * 3 self.matrix= [a,b,c] self.good_grid = SquareGrid(self.matrix) def test_error_on_mixed_dimensions(self): """Test object initialization""" four_by_three = self.matrix + [[3] * 3] with self.assertRaises(ValueError) as err: g = SquareGrid(four_by_three) def test_string_representation(self): """Test that the object behaves correctly with the `str()` built-in""" expected_string = "0 0 0\n1 1 1\n2 2 2" self.assertEqual(str(self.good_grid), expected_string) def test_length(self): """Test that the object returns a useful length""" self.assertEqual(len(self.good_grid), 3)
// ... existing code ... def test_string_representation(self): """Test that the object behaves correctly with the `str()` built-in""" expected_string = "0 0 0\n1 1 1\n2 2 2" self.assertEqual(str(self.good_grid), expected_string) // ... rest of the code ...
2ad2d488b4d7b0997355c068646a6a38b2668dae
meetuppizza/tests.py
meetuppizza/tests.py
from django.test import TestCase class Test(TestCase): def test_landing_page_is_there(self): response = self.client.get('/') self.assertEqual(response.status_code, 200)
from django.test import TestCase class Test(TestCase): def test_landing_page_is_there(self): response = self.client.get('/') self.assertEqual(response.status_code, 200) def test_page_contains_pizza(self): response = self.client.get('/') self.assertContains(response, "Pizza")
Add test that checks if landing page contains the word Pizza.
Add test that checks if landing page contains the word Pizza.
Python
mit
nicole-a-tesla/meetup.pizza,nicole-a-tesla/meetup.pizza
from django.test import TestCase class Test(TestCase): def test_landing_page_is_there(self): response = self.client.get('/') self.assertEqual(response.status_code, 200) + def test_page_contains_pizza(self): + response = self.client.get('/') + self.assertContains(response, "Pizza") +
Add test that checks if landing page contains the word Pizza.
## Code Before: from django.test import TestCase class Test(TestCase): def test_landing_page_is_there(self): response = self.client.get('/') self.assertEqual(response.status_code, 200) ## Instruction: Add test that checks if landing page contains the word Pizza. ## Code After: from django.test import TestCase class Test(TestCase): def test_landing_page_is_there(self): response = self.client.get('/') self.assertEqual(response.status_code, 200) def test_page_contains_pizza(self): response = self.client.get('/') self.assertContains(response, "Pizza")
// ... existing code ... self.assertEqual(response.status_code, 200) def test_page_contains_pizza(self): response = self.client.get('/') self.assertContains(response, "Pizza") // ... rest of the code ...
fdd1604ae64d72dc2391abe137adba07da830bcd
imagersite/imager_profile/models.py
imagersite/imager_profile/models.py
"""Models.""" from django.db import models from django.contrib.auth.models import User # Create your models here. class ImagerProfile(models.Model): """Imager Profile Model.""" camera_model = models.CharField(max_length=200) photography_type = models.TextField() # friends = models.ManyToManyField('self') region = models.CharField(max_length=200) user = models.OneToOneField(User, unique=True, null=False) def is_active(self): """Return if the user can log in.""" return self.user.is_active class ActiveUserManager(models.Manager): """Manager to grab active users.""" def get_query_set(self): """Return only active users.""" return super(ActiveUserManager, self).get_query_set().filter(user.is_active())
"""Models.""" from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User # Create your models here. class ActiveUserManager(models.Manager): """Manager to grab active users.""" def get_query_set(self): """Return only active users.""" return super(ActiveUserManager, self).get_query_set().filter(user.is_active) class ImagerProfile(models.Model): """Imager Profile Model.""" camera_model = models.CharField(max_length=200) photography_type = models.TextField() # friends = models.ManyToManyField('self') region = models.CharField(max_length=200) user = models.OneToOneField(User, unique=True, null=False) # Need to have models.Manager since we overwrote default with ActiveUser # Without it, we would have lost reference to 'objects' objects = models.Manager() active = ActiveUserManager() @property def is_active(self): """Return all instances of active ImagerProfile.""" return self.user.is_active # We control the profile, don't have code for user # If profile is deleted, user is deleted. We want the opposite. # How do we do that? # Idea of Signals (pyramid also has) # Signals hook into the listener pattern (like event listeners) # Imager profile exists, and gets removed (handelers.py) # first arg(sender(class that sent signal), **kwargs) # Must ensure errors aren't raised. Log problem, do nothing. # If errors are raised, it will prevent other things from happening # Must put signal code into a place where Django can execute it. # in apps.py def ready(self): from imager_profile import handlers (will register handlers) # In init.py add default_app_config = 'imager_rofile.apps.ImagerProfileConfig' # now Django knows about handlers
Add ability to access all 'objects' and only 'active' users
Add ability to access all 'objects' and only 'active' users
Python
mit
DZwell/django-imager
"""Models.""" + from __future__ import unicode_literals + from django.db import models from django.contrib.auth.models import User # Create your models here. + + + class ActiveUserManager(models.Manager): + """Manager to grab active users.""" + + def get_query_set(self): + """Return only active users.""" + return super(ActiveUserManager, self).get_query_set().filter(user.is_active) class ImagerProfile(models.Model): """Imager Profile Model.""" camera_model = models.CharField(max_length=200) photography_type = models.TextField() # friends = models.ManyToManyField('self') region = models.CharField(max_length=200) user = models.OneToOneField(User, unique=True, null=False) + # Need to have models.Manager since we overwrote default with ActiveUser + # Without it, we would have lost reference to 'objects' + objects = models.Manager() + active = ActiveUserManager() + + @property def is_active(self): - """Return if the user can log in.""" + """Return all instances of active ImagerProfile.""" return self.user.is_active - - - class ActiveUserManager(models.Manager): - """Manager to grab active users.""" - - def get_query_set(self): - """Return only active users.""" - return super(ActiveUserManager, self).get_query_set().filter(user.is_active()) + + # We control the profile, don't have code for user + # If profile is deleted, user is deleted. We want the opposite. + # How do we do that? + # Idea of Signals (pyramid also has) + # Signals hook into the listener pattern (like event listeners) + # Imager profile exists, and gets removed (handelers.py) + # first arg(sender(class that sent signal), **kwargs) + # Must ensure errors aren't raised. Log problem, do nothing. + # If errors are raised, it will prevent other things from happening + # Must put signal code into a place where Django can execute it. + # in apps.py def ready(self): from imager_profile import handlers (will register handlers) + # In init.py add default_app_config = 'imager_rofile.apps.ImagerProfileConfig' + # now Django knows about handlers +
Add ability to access all 'objects' and only 'active' users
## Code Before: """Models.""" from django.db import models from django.contrib.auth.models import User # Create your models here. class ImagerProfile(models.Model): """Imager Profile Model.""" camera_model = models.CharField(max_length=200) photography_type = models.TextField() # friends = models.ManyToManyField('self') region = models.CharField(max_length=200) user = models.OneToOneField(User, unique=True, null=False) def is_active(self): """Return if the user can log in.""" return self.user.is_active class ActiveUserManager(models.Manager): """Manager to grab active users.""" def get_query_set(self): """Return only active users.""" return super(ActiveUserManager, self).get_query_set().filter(user.is_active()) ## Instruction: Add ability to access all 'objects' and only 'active' users ## Code After: """Models.""" from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User # Create your models here. class ActiveUserManager(models.Manager): """Manager to grab active users.""" def get_query_set(self): """Return only active users.""" return super(ActiveUserManager, self).get_query_set().filter(user.is_active) class ImagerProfile(models.Model): """Imager Profile Model.""" camera_model = models.CharField(max_length=200) photography_type = models.TextField() # friends = models.ManyToManyField('self') region = models.CharField(max_length=200) user = models.OneToOneField(User, unique=True, null=False) # Need to have models.Manager since we overwrote default with ActiveUser # Without it, we would have lost reference to 'objects' objects = models.Manager() active = ActiveUserManager() @property def is_active(self): """Return all instances of active ImagerProfile.""" return self.user.is_active # We control the profile, don't have code for user # If profile is deleted, user is deleted. We want the opposite. # How do we do that? # Idea of Signals (pyramid also has) # Signals hook into the listener pattern (like event listeners) # Imager profile exists, and gets removed (handelers.py) # first arg(sender(class that sent signal), **kwargs) # Must ensure errors aren't raised. Log problem, do nothing. # If errors are raised, it will prevent other things from happening # Must put signal code into a place where Django can execute it. # in apps.py def ready(self): from imager_profile import handlers (will register handlers) # In init.py add default_app_config = 'imager_rofile.apps.ImagerProfileConfig' # now Django knows about handlers
# ... existing code ... """Models.""" from __future__ import unicode_literals from django.db import models # ... modified code ... # Create your models here. class ActiveUserManager(models.Manager): """Manager to grab active users.""" def get_query_set(self): """Return only active users.""" return super(ActiveUserManager, self).get_query_set().filter(user.is_active) ... # Need to have models.Manager since we overwrote default with ActiveUser # Without it, we would have lost reference to 'objects' objects = models.Manager() active = ActiveUserManager() @property def is_active(self): """Return all instances of active ImagerProfile.""" return self.user.is_active ... # We control the profile, don't have code for user # If profile is deleted, user is deleted. We want the opposite. # How do we do that? # Idea of Signals (pyramid also has) # Signals hook into the listener pattern (like event listeners) # Imager profile exists, and gets removed (handelers.py) # first arg(sender(class that sent signal), **kwargs) # Must ensure errors aren't raised. Log problem, do nothing. # If errors are raised, it will prevent other things from happening # Must put signal code into a place where Django can execute it. # in apps.py def ready(self): from imager_profile import handlers (will register handlers) # In init.py add default_app_config = 'imager_rofile.apps.ImagerProfileConfig' # now Django knows about handlers # ... rest of the code ...
a1f5a392d5270dd6f80a40e45c5e25b6ae04b7c3
embed_video/fields.py
embed_video/fields.py
from django.db import models from django import forms from django.utils.translation import ugettext_lazy as _ from .backends import detect_backend, UnknownIdException, \ UnknownBackendException __all__ = ('EmbedVideoField', 'EmbedVideoFormField') class EmbedVideoField(models.URLField): """ Model field for embeded video. Descendant of :py:class:`django.db.models.URLField`. """ def formfield(self, **kwargs): defaults = {'form_class': EmbedVideoFormField} defaults.update(kwargs) return super(EmbedVideoField, self).formfield(**defaults) def south_field_triple(self): from south.modelsinspector import introspector cls_name = '%s.%s' % ( self.__class__.__module__, self.__class__.__name__ ) args, kwargs = introspector(self) return (cls_name, args, kwargs) class EmbedVideoFormField(forms.URLField): """ Form field for embeded video. Descendant of :py:class:`django.forms.URLField` """ def validate(self, url): super(EmbedVideoFormField, self).validate(url) if url: try: detect_backend(url) except UnknownBackendException: raise forms.ValidationError(_(u'URL could not be recognized.')) except UnknownIdException: raise forms.ValidationError(_(u'ID of this video could not be \ recognized.')) return url
from django.db import models from django import forms from django.utils.translation import ugettext_lazy as _ from .backends import detect_backend, UnknownIdException, \ UnknownBackendException __all__ = ('EmbedVideoField', 'EmbedVideoFormField') class EmbedVideoField(models.URLField): """ Model field for embeded video. Descendant of :py:class:`django.db.models.URLField`. """ def formfield(self, **kwargs): defaults = {'form_class': EmbedVideoFormField} defaults.update(kwargs) return super(EmbedVideoField, self).formfield(**defaults) def south_field_triple(self): from south.modelsinspector import introspector cls_name = '%s.%s' % ( self.__class__.__module__, self.__class__.__name__ ) args, kwargs = introspector(self) return (cls_name, args, kwargs) class EmbedVideoFormField(forms.URLField): """ Form field for embeded video. Descendant of :py:class:`django.forms.URLField` """ def validate(self, url): # if empty url is not allowed throws an exception super(EmbedVideoFormField, self).validate(url) if not url: return try: detect_backend(url) except UnknownBackendException: raise forms.ValidationError(_(u'URL could not be recognized.')) except UnknownIdException: raise forms.ValidationError(_(u'ID of this video could not be \ recognized.')) return url
Simplify validate method in FormField.
Simplify validate method in FormField.
Python
mit
yetty/django-embed-video,jazzband/django-embed-video,jazzband/django-embed-video,mpachas/django-embed-video,yetty/django-embed-video,mpachas/django-embed-video
from django.db import models from django import forms from django.utils.translation import ugettext_lazy as _ from .backends import detect_backend, UnknownIdException, \ UnknownBackendException __all__ = ('EmbedVideoField', 'EmbedVideoFormField') class EmbedVideoField(models.URLField): """ Model field for embeded video. Descendant of :py:class:`django.db.models.URLField`. """ def formfield(self, **kwargs): defaults = {'form_class': EmbedVideoFormField} defaults.update(kwargs) return super(EmbedVideoField, self).formfield(**defaults) def south_field_triple(self): from south.modelsinspector import introspector cls_name = '%s.%s' % ( self.__class__.__module__, self.__class__.__name__ ) args, kwargs = introspector(self) return (cls_name, args, kwargs) class EmbedVideoFormField(forms.URLField): """ Form field for embeded video. Descendant of :py:class:`django.forms.URLField` """ def validate(self, url): + # if empty url is not allowed throws an exception super(EmbedVideoFormField, self).validate(url) + + if not url: + return - if url: - try: + try: - detect_backend(url) + detect_backend(url) - except UnknownBackendException: + except UnknownBackendException: - raise forms.ValidationError(_(u'URL could not be recognized.')) + raise forms.ValidationError(_(u'URL could not be recognized.')) - except UnknownIdException: + except UnknownIdException: - raise forms.ValidationError(_(u'ID of this video could not be \ + raise forms.ValidationError(_(u'ID of this video could not be \ - recognized.')) + recognized.')) - return url
Simplify validate method in FormField.
## Code Before: from django.db import models from django import forms from django.utils.translation import ugettext_lazy as _ from .backends import detect_backend, UnknownIdException, \ UnknownBackendException __all__ = ('EmbedVideoField', 'EmbedVideoFormField') class EmbedVideoField(models.URLField): """ Model field for embeded video. Descendant of :py:class:`django.db.models.URLField`. """ def formfield(self, **kwargs): defaults = {'form_class': EmbedVideoFormField} defaults.update(kwargs) return super(EmbedVideoField, self).formfield(**defaults) def south_field_triple(self): from south.modelsinspector import introspector cls_name = '%s.%s' % ( self.__class__.__module__, self.__class__.__name__ ) args, kwargs = introspector(self) return (cls_name, args, kwargs) class EmbedVideoFormField(forms.URLField): """ Form field for embeded video. Descendant of :py:class:`django.forms.URLField` """ def validate(self, url): super(EmbedVideoFormField, self).validate(url) if url: try: detect_backend(url) except UnknownBackendException: raise forms.ValidationError(_(u'URL could not be recognized.')) except UnknownIdException: raise forms.ValidationError(_(u'ID of this video could not be \ recognized.')) return url ## Instruction: Simplify validate method in FormField. ## Code After: from django.db import models from django import forms from django.utils.translation import ugettext_lazy as _ from .backends import detect_backend, UnknownIdException, \ UnknownBackendException __all__ = ('EmbedVideoField', 'EmbedVideoFormField') class EmbedVideoField(models.URLField): """ Model field for embeded video. Descendant of :py:class:`django.db.models.URLField`. """ def formfield(self, **kwargs): defaults = {'form_class': EmbedVideoFormField} defaults.update(kwargs) return super(EmbedVideoField, self).formfield(**defaults) def south_field_triple(self): from south.modelsinspector import introspector cls_name = '%s.%s' % ( self.__class__.__module__, self.__class__.__name__ ) args, kwargs = introspector(self) return (cls_name, args, kwargs) class EmbedVideoFormField(forms.URLField): """ Form field for embeded video. Descendant of :py:class:`django.forms.URLField` """ def validate(self, url): # if empty url is not allowed throws an exception super(EmbedVideoFormField, self).validate(url) if not url: return try: detect_backend(url) except UnknownBackendException: raise forms.ValidationError(_(u'URL could not be recognized.')) except UnknownIdException: raise forms.ValidationError(_(u'ID of this video could not be \ recognized.')) return url
... def validate(self, url): # if empty url is not allowed throws an exception super(EmbedVideoFormField, self).validate(url) if not url: return try: detect_backend(url) except UnknownBackendException: raise forms.ValidationError(_(u'URL could not be recognized.')) except UnknownIdException: raise forms.ValidationError(_(u'ID of this video could not be \ recognized.')) return url ...
8c2db8786a0dd08c7ca039f491260f9407eb946c
dodo.py
dodo.py
DOIT_CONFIG = {'default_tasks': []} CITEULIKE_GROUP = 19073 BIBFILE = 'docs/pyfssa.bib' def task_download_bib(): """Download bibliography from CiteULike group""" return { 'actions': [' '.join([ 'wget', '-O', BIBFILE, '"http://www.citeulike.org/bibtex/group/{}?incl_amazon=0&key_type=4"'.format(CITEULIKE_GROUP), ])], # 'file_dep': [CITEULIKE_COOKIES], 'targets': [BIBFILE], }
import os DOIT_CONFIG = {'default_tasks': []} CITEULIKE_GROUP = 19073 BIBFILE = 'docs/pyfssa.bib' def task_download_bib(): """Download bibliography from CiteULike group""" return { 'actions': [' '.join([ 'wget', '-O', BIBFILE, '"http://www.citeulike.org/bibtex/group/{}?incl_amazon=0&key_type=4"'.format(CITEULIKE_GROUP), ])], # 'file_dep': [CITEULIKE_COOKIES], 'targets': [BIBFILE], } def task_upload_doc(): """Upload built html documentation to GitHub pages""" return { 'actions': [[ 'ghp-import', '-n', # Include a .nojekyll file in the branch. '-p', # Push the branch to origin/{branch} after committing. os.path.join('docs', '_build', 'html') ]], }
Add task to upload documentation to github pages
Add task to upload documentation to github pages
Python
isc
andsor/pyfssa,andsor/pyfssa
+ + import os DOIT_CONFIG = {'default_tasks': []} CITEULIKE_GROUP = 19073 BIBFILE = 'docs/pyfssa.bib' def task_download_bib(): """Download bibliography from CiteULike group""" return { 'actions': [' '.join([ 'wget', '-O', BIBFILE, '"http://www.citeulike.org/bibtex/group/{}?incl_amazon=0&key_type=4"'.format(CITEULIKE_GROUP), ])], # 'file_dep': [CITEULIKE_COOKIES], 'targets': [BIBFILE], } + + def task_upload_doc(): + """Upload built html documentation to GitHub pages""" + + return { + 'actions': [[ + 'ghp-import', + '-n', # Include a .nojekyll file in the branch. + '-p', # Push the branch to origin/{branch} after committing. + os.path.join('docs', '_build', 'html') + ]], + } +
Add task to upload documentation to github pages
## Code Before: DOIT_CONFIG = {'default_tasks': []} CITEULIKE_GROUP = 19073 BIBFILE = 'docs/pyfssa.bib' def task_download_bib(): """Download bibliography from CiteULike group""" return { 'actions': [' '.join([ 'wget', '-O', BIBFILE, '"http://www.citeulike.org/bibtex/group/{}?incl_amazon=0&key_type=4"'.format(CITEULIKE_GROUP), ])], # 'file_dep': [CITEULIKE_COOKIES], 'targets': [BIBFILE], } ## Instruction: Add task to upload documentation to github pages ## Code After: import os DOIT_CONFIG = {'default_tasks': []} CITEULIKE_GROUP = 19073 BIBFILE = 'docs/pyfssa.bib' def task_download_bib(): """Download bibliography from CiteULike group""" return { 'actions': [' '.join([ 'wget', '-O', BIBFILE, '"http://www.citeulike.org/bibtex/group/{}?incl_amazon=0&key_type=4"'.format(CITEULIKE_GROUP), ])], # 'file_dep': [CITEULIKE_COOKIES], 'targets': [BIBFILE], } def task_upload_doc(): """Upload built html documentation to GitHub pages""" return { 'actions': [[ 'ghp-import', '-n', # Include a .nojekyll file in the branch. '-p', # Push the branch to origin/{branch} after committing. os.path.join('docs', '_build', 'html') ]], }
... import os ... } def task_upload_doc(): """Upload built html documentation to GitHub pages""" return { 'actions': [[ 'ghp-import', '-n', # Include a .nojekyll file in the branch. '-p', # Push the branch to origin/{branch} after committing. os.path.join('docs', '_build', 'html') ]], } ...
2a41cae0e1992b23647ebdc7d49c435e4a187cf2
jujubigdata/__init__.py
jujubigdata/__init__.py
from . import utils # noqa from . import relations # noqa from . import handlers # noqa
from . import utils # noqa from . import handlers # noqa # relations doesn't work with stock charmhelpers and is being phased out in the # layered charms, so this makes it conditional try: from charmhelpers.core import charmframework # noqa except ImportError: pass else: from . import relations # noqa
Make relations import conditional for layers migration
Make relations import conditional for layers migration
Python
apache-2.0
tsakas/jujubigdata,johnsca/jujubigdata,ktsakalozos/jujubigdata-dev,juju-solutions/jujubigdata,juju-solutions/jujubigdata,ktsakalozos/jujubigdata-dev,andrewdmcleod/jujubigdata,andrewdmcleod/jujubigdata,johnsca/jujubigdata,ktsakalozos/jujubigdata,ktsakalozos/jujubigdata,tsakas/jujubigdata
from . import utils # noqa - from . import relations # noqa from . import handlers # noqa + # relations doesn't work with stock charmhelpers and is being phased out in the + # layered charms, so this makes it conditional + try: + from charmhelpers.core import charmframework # noqa + except ImportError: + pass + else: + from . import relations # noqa +
Make relations import conditional for layers migration
## Code Before: from . import utils # noqa from . import relations # noqa from . import handlers # noqa ## Instruction: Make relations import conditional for layers migration ## Code After: from . import utils # noqa from . import handlers # noqa # relations doesn't work with stock charmhelpers and is being phased out in the # layered charms, so this makes it conditional try: from charmhelpers.core import charmframework # noqa except ImportError: pass else: from . import relations # noqa
# ... existing code ... from . import utils # noqa from . import handlers # noqa # relations doesn't work with stock charmhelpers and is being phased out in the # layered charms, so this makes it conditional try: from charmhelpers.core import charmframework # noqa except ImportError: pass else: from . import relations # noqa # ... rest of the code ...
f80c11efb4bcbca6d20cdbbc1a552ebb04aa8302
api/config/settings/production.py
api/config/settings/production.py
import os import dj_database_url from .base import * # BASE_NAME and BASE_DOMAIN are intentionally unset # They are only needed to seed data in staging and local BASE_URL = "https://voterengagement.com" ############################################################################### # Core SECRET_KEY = os.environ['SECRET_KEY'] ALLOWED_HOSTS = [ '127.0.0.1', 'localhost', # TODO: Prevent access from herokuapp.com when domain is registered # '.voterengagement.com', '.herokuapp.com', ] ############################################################################### # Static files STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' ############################################################################### # Database DATABASES = {} DATABASES['default'] = dj_database_url.config()
import os import dj_database_url from .base import * # BASE_NAME and BASE_DOMAIN are intentionally unset # They are only needed to seed data in staging and local BASE_URL = "https://voterengagement.com" ############################################################################### # Core SECRET_KEY = os.environ['SECRET_KEY'] ALLOWED_HOSTS = [ '127.0.0.1', 'localhost', '.citizenlabs.org', ] ############################################################################### # Static files STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' ############################################################################### # Database DATABASES = {} DATABASES['default'] = dj_database_url.config()
Allow citizenlabs.org as a host
Allow citizenlabs.org as a host
Python
mit
citizenlabsgr/voter-engagement,citizenlabsgr/voter-engagement,citizenlabsgr/voter-engagement,citizenlabsgr/voter-engagement,citizenlabsgr/voter-engagement
import os import dj_database_url from .base import * # BASE_NAME and BASE_DOMAIN are intentionally unset # They are only needed to seed data in staging and local BASE_URL = "https://voterengagement.com" ############################################################################### # Core SECRET_KEY = os.environ['SECRET_KEY'] ALLOWED_HOSTS = [ '127.0.0.1', 'localhost', + '.citizenlabs.org', - # TODO: Prevent access from herokuapp.com when domain is registered - # '.voterengagement.com', - '.herokuapp.com', ] ############################################################################### # Static files STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' ############################################################################### # Database DATABASES = {} DATABASES['default'] = dj_database_url.config()
Allow citizenlabs.org as a host
## Code Before: import os import dj_database_url from .base import * # BASE_NAME and BASE_DOMAIN are intentionally unset # They are only needed to seed data in staging and local BASE_URL = "https://voterengagement.com" ############################################################################### # Core SECRET_KEY = os.environ['SECRET_KEY'] ALLOWED_HOSTS = [ '127.0.0.1', 'localhost', # TODO: Prevent access from herokuapp.com when domain is registered # '.voterengagement.com', '.herokuapp.com', ] ############################################################################### # Static files STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' ############################################################################### # Database DATABASES = {} DATABASES['default'] = dj_database_url.config() ## Instruction: Allow citizenlabs.org as a host ## Code After: import os import dj_database_url from .base import * # BASE_NAME and BASE_DOMAIN are intentionally unset # They are only needed to seed data in staging and local BASE_URL = "https://voterengagement.com" ############################################################################### # Core SECRET_KEY = os.environ['SECRET_KEY'] ALLOWED_HOSTS = [ '127.0.0.1', 'localhost', '.citizenlabs.org', ] ############################################################################### # Static files STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' ############################################################################### # Database DATABASES = {} DATABASES['default'] = dj_database_url.config()
# ... existing code ... 'localhost', '.citizenlabs.org', ] # ... rest of the code ...
1b8efb09ac512622ea3541d950ffc67b0a183178
survey/signals.py
survey/signals.py
import django.dispatch survey_completed = django.dispatch.Signal(providing_args=["instance", "data"])
import django.dispatch # providing_args=["instance", "data"] survey_completed = django.dispatch.Signal()
Remove puyrely documental providing-args argument
Remove puyrely documental providing-args argument See https://docs.djangoproject.com/en/4.0/releases/3.1/#id2
Python
agpl-3.0
Pierre-Sassoulas/django-survey,Pierre-Sassoulas/django-survey,Pierre-Sassoulas/django-survey
import django.dispatch - survey_completed = django.dispatch.Signal(providing_args=["instance", "data"]) + # providing_args=["instance", "data"] + survey_completed = django.dispatch.Signal()
Remove puyrely documental providing-args argument
## Code Before: import django.dispatch survey_completed = django.dispatch.Signal(providing_args=["instance", "data"]) ## Instruction: Remove puyrely documental providing-args argument ## Code After: import django.dispatch # providing_args=["instance", "data"] survey_completed = django.dispatch.Signal()
# ... existing code ... # providing_args=["instance", "data"] survey_completed = django.dispatch.Signal() # ... rest of the code ...
c0b3a482b8ef5284070da1398350acf936e50121
rplugin/python3/deoplete/sources/LanguageClientSource.py
rplugin/python3/deoplete/sources/LanguageClientSource.py
import re from .base import Base CompleteResults = "g:LanguageClient_completeResults" def simplify_snippet(snip: str) -> str: return re.sub(r'(?<!\\)\$\d+', '', snip) class Source(Base): def __init__(self, vim): super().__init__(vim) self.name = "LanguageClient" self.mark = "[LC]" self.rank = 1000 self.filetypes = vim.eval( "get(g:, 'LanguageClient_serverCommands', {})").keys() self.min_pattern_length = 1 self.input_pattern = r'(\.|::)\w*' def gather_candidates(self, context): if not context["is_async"]: context["is_async"] = True self.vim.funcs.LanguageClient_omniComplete() return [] elif self.vim.funcs.eval("len({})".format(CompleteResults)) == 0: return [] context["is_async"] = False result = self.vim.funcs.eval("remove({}, 0)".format(CompleteResults)) if result is None: result = [] return result
import re from .base import Base CompleteResults = "g:LanguageClient_completeResults" def simplify_snippet(snip: str) -> str: snip = re.sub(r'(?<!\\)\$(?P<num>\d+)', '<`\g<num>`>', snip) return re.sub(r'(?<!\\)\${(?P<num>\d+):(?P<desc>.+?)}', '<`\g<num>:\g<desc>`>', snip) class Source(Base): def __init__(self, vim): super().__init__(vim) self.name = "LanguageClient" self.mark = "[LC]" self.rank = 1000 self.filetypes = vim.eval( "get(g:, 'LanguageClient_serverCommands', {})").keys() self.min_pattern_length = 1 self.input_pattern = r'(\.|::)\w*' def gather_candidates(self, context): if not context["is_async"]: context["is_async"] = True self.vim.funcs.LanguageClient_omniComplete() return [] elif self.vim.funcs.eval("len({})".format(CompleteResults)) == 0: return [] context["is_async"] = False result = self.vim.funcs.eval("remove({}, 0)".format(CompleteResults)) if result is None: result = [] return result
Replace placeholders in completion text
Replace placeholders in completion text In deoplete source, replace the placeholders with the neosnippet format.
Python
mit
autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim
import re from .base import Base CompleteResults = "g:LanguageClient_completeResults" def simplify_snippet(snip: str) -> str: - return re.sub(r'(?<!\\)\$\d+', '', snip) + snip = re.sub(r'(?<!\\)\$(?P<num>\d+)', '<`\g<num>`>', snip) + return re.sub(r'(?<!\\)\${(?P<num>\d+):(?P<desc>.+?)}', + '<`\g<num>:\g<desc>`>', snip) class Source(Base): def __init__(self, vim): super().__init__(vim) self.name = "LanguageClient" self.mark = "[LC]" self.rank = 1000 self.filetypes = vim.eval( "get(g:, 'LanguageClient_serverCommands', {})").keys() self.min_pattern_length = 1 self.input_pattern = r'(\.|::)\w*' def gather_candidates(self, context): if not context["is_async"]: context["is_async"] = True self.vim.funcs.LanguageClient_omniComplete() return [] elif self.vim.funcs.eval("len({})".format(CompleteResults)) == 0: return [] context["is_async"] = False result = self.vim.funcs.eval("remove({}, 0)".format(CompleteResults)) if result is None: result = [] return result
Replace placeholders in completion text
## Code Before: import re from .base import Base CompleteResults = "g:LanguageClient_completeResults" def simplify_snippet(snip: str) -> str: return re.sub(r'(?<!\\)\$\d+', '', snip) class Source(Base): def __init__(self, vim): super().__init__(vim) self.name = "LanguageClient" self.mark = "[LC]" self.rank = 1000 self.filetypes = vim.eval( "get(g:, 'LanguageClient_serverCommands', {})").keys() self.min_pattern_length = 1 self.input_pattern = r'(\.|::)\w*' def gather_candidates(self, context): if not context["is_async"]: context["is_async"] = True self.vim.funcs.LanguageClient_omniComplete() return [] elif self.vim.funcs.eval("len({})".format(CompleteResults)) == 0: return [] context["is_async"] = False result = self.vim.funcs.eval("remove({}, 0)".format(CompleteResults)) if result is None: result = [] return result ## Instruction: Replace placeholders in completion text ## Code After: import re from .base import Base CompleteResults = "g:LanguageClient_completeResults" def simplify_snippet(snip: str) -> str: snip = re.sub(r'(?<!\\)\$(?P<num>\d+)', '<`\g<num>`>', snip) return re.sub(r'(?<!\\)\${(?P<num>\d+):(?P<desc>.+?)}', '<`\g<num>:\g<desc>`>', snip) class Source(Base): def __init__(self, vim): super().__init__(vim) self.name = "LanguageClient" self.mark = "[LC]" self.rank = 1000 self.filetypes = vim.eval( "get(g:, 'LanguageClient_serverCommands', {})").keys() self.min_pattern_length = 1 self.input_pattern = r'(\.|::)\w*' def gather_candidates(self, context): if not context["is_async"]: context["is_async"] = True self.vim.funcs.LanguageClient_omniComplete() return [] elif self.vim.funcs.eval("len({})".format(CompleteResults)) == 0: return [] context["is_async"] = False result = self.vim.funcs.eval("remove({}, 0)".format(CompleteResults)) if result is None: result = [] return result
# ... existing code ... def simplify_snippet(snip: str) -> str: snip = re.sub(r'(?<!\\)\$(?P<num>\d+)', '<`\g<num>`>', snip) return re.sub(r'(?<!\\)\${(?P<num>\d+):(?P<desc>.+?)}', '<`\g<num>:\g<desc>`>', snip) # ... rest of the code ...
1a0339b85d852526c184eeace73021fc7d68b2c6
python_dispatcher.py
python_dispatcher.py
import traceback from routes import Mapper import ppp_core import example_ppp_module as flower import ppp_questionparsing_grammatical as qp_grammatical import ppp_cas #import ppp_nlp_ml_standalone class Application: def __init__(self): self.mapper = Mapper() self.mapper.connect('core', '/core/', app=ppp_core.app) self.mapper.connect('qp_grammatical', '/qp_grammatical/', app=qp_grammatical.app) self.mapper.connect('flower', '/flower/', app=flower.app) self.mapper.connect('cas', '/cas/', app=ppp_cas.app) self.mapper.connect('spellcheck', '/spell_checker/', app=ppp_cas.app) #self.mapper.connect('nlp_ml_standalone', '/nlp_ml_standalone/', app=ppp_nlp_ml_standalone.app) def __call__(self, environ, start_response): match = self.mapper.routematch(environ=environ) app = match[0]['app'] if match else self.not_found try: return app(environ, start_response) except KeyboardInterrupt: raise except Exception as e: traceback.print_exc(e) def not_found(self, environ, start_response): headers = [('Content-Type', 'text/plain')] start_response('404 Not Found', headers) return [b'Not found.'] app = Application()
import traceback from routes import Mapper import ppp_core import example_ppp_module as flower import ppp_questionparsing_grammatical as qp_grammatical import ppp_cas import ppp_spell_checker #import ppp_nlp_ml_standalone class Application: def __init__(self): self.mapper = Mapper() self.mapper.connect('core', '/core/', app=ppp_core.app) self.mapper.connect('qp_grammatical', '/qp_grammatical/', app=qp_grammatical.app) self.mapper.connect('flower', '/flower/', app=flower.app) self.mapper.connect('cas', '/cas/', app=ppp_cas.app) self.mapper.connect('spellcheck', '/spell_checker/', app=ppp_spell_checker.app) #self.mapper.connect('nlp_ml_standalone', '/nlp_ml_standalone/', app=ppp_nlp_ml_standalone.app) def __call__(self, environ, start_response): match = self.mapper.routematch(environ=environ) app = match[0]['app'] if match else self.not_found try: return app(environ, start_response) except KeyboardInterrupt: raise except Exception as e: traceback.print_exc(e) def not_found(self, environ, start_response): headers = [('Content-Type', 'text/plain')] start_response('404 Not Found', headers) return [b'Not found.'] app = Application()
Fix name of spell checker.
Fix name of spell checker.
Python
cc0-1.0
ProjetPP/Deployment,ProjetPP/Deployment,ProjetPP/Deployment
import traceback from routes import Mapper import ppp_core import example_ppp_module as flower import ppp_questionparsing_grammatical as qp_grammatical import ppp_cas + import ppp_spell_checker #import ppp_nlp_ml_standalone class Application: def __init__(self): self.mapper = Mapper() self.mapper.connect('core', '/core/', app=ppp_core.app) self.mapper.connect('qp_grammatical', '/qp_grammatical/', app=qp_grammatical.app) self.mapper.connect('flower', '/flower/', app=flower.app) self.mapper.connect('cas', '/cas/', app=ppp_cas.app) - self.mapper.connect('spellcheck', '/spell_checker/', app=ppp_cas.app) + self.mapper.connect('spellcheck', '/spell_checker/', app=ppp_spell_checker.app) #self.mapper.connect('nlp_ml_standalone', '/nlp_ml_standalone/', app=ppp_nlp_ml_standalone.app) def __call__(self, environ, start_response): match = self.mapper.routematch(environ=environ) app = match[0]['app'] if match else self.not_found try: return app(environ, start_response) except KeyboardInterrupt: raise except Exception as e: traceback.print_exc(e) def not_found(self, environ, start_response): headers = [('Content-Type', 'text/plain')] start_response('404 Not Found', headers) return [b'Not found.'] app = Application()
Fix name of spell checker.
## Code Before: import traceback from routes import Mapper import ppp_core import example_ppp_module as flower import ppp_questionparsing_grammatical as qp_grammatical import ppp_cas #import ppp_nlp_ml_standalone class Application: def __init__(self): self.mapper = Mapper() self.mapper.connect('core', '/core/', app=ppp_core.app) self.mapper.connect('qp_grammatical', '/qp_grammatical/', app=qp_grammatical.app) self.mapper.connect('flower', '/flower/', app=flower.app) self.mapper.connect('cas', '/cas/', app=ppp_cas.app) self.mapper.connect('spellcheck', '/spell_checker/', app=ppp_cas.app) #self.mapper.connect('nlp_ml_standalone', '/nlp_ml_standalone/', app=ppp_nlp_ml_standalone.app) def __call__(self, environ, start_response): match = self.mapper.routematch(environ=environ) app = match[0]['app'] if match else self.not_found try: return app(environ, start_response) except KeyboardInterrupt: raise except Exception as e: traceback.print_exc(e) def not_found(self, environ, start_response): headers = [('Content-Type', 'text/plain')] start_response('404 Not Found', headers) return [b'Not found.'] app = Application() ## Instruction: Fix name of spell checker. ## Code After: import traceback from routes import Mapper import ppp_core import example_ppp_module as flower import ppp_questionparsing_grammatical as qp_grammatical import ppp_cas import ppp_spell_checker #import ppp_nlp_ml_standalone class Application: def __init__(self): self.mapper = Mapper() self.mapper.connect('core', '/core/', app=ppp_core.app) self.mapper.connect('qp_grammatical', '/qp_grammatical/', app=qp_grammatical.app) self.mapper.connect('flower', '/flower/', app=flower.app) self.mapper.connect('cas', '/cas/', app=ppp_cas.app) self.mapper.connect('spellcheck', '/spell_checker/', app=ppp_spell_checker.app) #self.mapper.connect('nlp_ml_standalone', '/nlp_ml_standalone/', app=ppp_nlp_ml_standalone.app) def __call__(self, environ, start_response): match = self.mapper.routematch(environ=environ) app = match[0]['app'] if match else self.not_found try: return app(environ, start_response) except KeyboardInterrupt: raise except Exception as e: traceback.print_exc(e) def not_found(self, environ, start_response): headers = [('Content-Type', 'text/plain')] start_response('404 Not Found', headers) return [b'Not found.'] app = Application()
... import ppp_cas import ppp_spell_checker #import ppp_nlp_ml_standalone ... self.mapper.connect('cas', '/cas/', app=ppp_cas.app) self.mapper.connect('spellcheck', '/spell_checker/', app=ppp_spell_checker.app) #self.mapper.connect('nlp_ml_standalone', '/nlp_ml_standalone/', app=ppp_nlp_ml_standalone.app) ...
37da65953471b5dd0930e102b861878012938701
registration/__init__.py
registration/__init__.py
from django.utils.version import get_version as django_get_version VERSION = (0, 9, 0, 'beta', 1) def get_version(): return django_get_version(VERSION) # pragma: no cover
VERSION = (0, 9, 0, 'beta', 1) def get_version(): from django.utils.version import get_version as django_get_version return django_get_version(VERSION) # pragma: no cover
Move import of Django's get_version into django-registration's get_version, to avoid dependency-order problems.
Move import of Django's get_version into django-registration's get_version, to avoid dependency-order problems.
Python
bsd-3-clause
lubosz/django-registration,lubosz/django-registration
- from django.utils.version import get_version as django_get_version - - VERSION = (0, 9, 0, 'beta', 1) def get_version(): + from django.utils.version import get_version as django_get_version return django_get_version(VERSION) # pragma: no cover
Move import of Django's get_version into django-registration's get_version, to avoid dependency-order problems.
## Code Before: from django.utils.version import get_version as django_get_version VERSION = (0, 9, 0, 'beta', 1) def get_version(): return django_get_version(VERSION) # pragma: no cover ## Instruction: Move import of Django's get_version into django-registration's get_version, to avoid dependency-order problems. ## Code After: VERSION = (0, 9, 0, 'beta', 1) def get_version(): from django.utils.version import get_version as django_get_version return django_get_version(VERSION) # pragma: no cover
# ... existing code ... VERSION = (0, 9, 0, 'beta', 1) # ... modified code ... def get_version(): from django.utils.version import get_version as django_get_version return django_get_version(VERSION) # pragma: no cover # ... rest of the code ...
e81cf35231e77d64f619169fc0625c0ae7d0edc8
AWSLambdas/vote.py
AWSLambdas/vote.py
import json import boto3 import time import decimal from boto3.dynamodb.conditions import Key, Attr def vote_handler(event, context): dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('Samples') for record in event['Records']: print(record['dynamodb']['NewImage'])
import json import boto3 import time import decimal from boto3.dynamodb.conditions import Key, Attr def vote_handler(event, context): dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('Samples') ratings = dict() for record in event['Records']: type = record['eventName'] disposition = 0 if type == "INSERT" or type == "MODIFY": disposition = int(record['dynamodb']['NewImage']['vote']['N']) if type == "MODIFY" or type == "REMOVE": disposition += -int(record['dynamodb']['OldImage']['vote']['N']) sample = record['dynamodb']['Keys']['sample']['B'] ratings[sample] = ratings.get(sample, 0) + disposition
Determine rating dispositions noted by the data changes and store them in a dictionary with the sample identification as the key.
Determine rating dispositions noted by the data changes and store them in a dictionary with the sample identification as the key.
Python
mit
SandcastleApps/partyup,SandcastleApps/partyup,SandcastleApps/partyup
import json import boto3 import time import decimal from boto3.dynamodb.conditions import Key, Attr def vote_handler(event, context): dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('Samples') + + ratings = dict() for record in event['Records']: - print(record['dynamodb']['NewImage']) + type = record['eventName'] + disposition = 0 + if type == "INSERT" or type == "MODIFY": + disposition = int(record['dynamodb']['NewImage']['vote']['N']) + if type == "MODIFY" or type == "REMOVE": + disposition += -int(record['dynamodb']['OldImage']['vote']['N']) + sample = record['dynamodb']['Keys']['sample']['B'] + ratings[sample] = ratings.get(sample, 0) + disposition + +
Determine rating dispositions noted by the data changes and store them in a dictionary with the sample identification as the key.
## Code Before: import json import boto3 import time import decimal from boto3.dynamodb.conditions import Key, Attr def vote_handler(event, context): dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('Samples') for record in event['Records']: print(record['dynamodb']['NewImage']) ## Instruction: Determine rating dispositions noted by the data changes and store them in a dictionary with the sample identification as the key. ## Code After: import json import boto3 import time import decimal from boto3.dynamodb.conditions import Key, Attr def vote_handler(event, context): dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('Samples') ratings = dict() for record in event['Records']: type = record['eventName'] disposition = 0 if type == "INSERT" or type == "MODIFY": disposition = int(record['dynamodb']['NewImage']['vote']['N']) if type == "MODIFY" or type == "REMOVE": disposition += -int(record['dynamodb']['OldImage']['vote']['N']) sample = record['dynamodb']['Keys']['sample']['B'] ratings[sample] = ratings.get(sample, 0) + disposition
... table = dynamodb.Table('Samples') ratings = dict() ... for record in event['Records']: type = record['eventName'] disposition = 0 if type == "INSERT" or type == "MODIFY": disposition = int(record['dynamodb']['NewImage']['vote']['N']) if type == "MODIFY" or type == "REMOVE": disposition += -int(record['dynamodb']['OldImage']['vote']['N']) sample = record['dynamodb']['Keys']['sample']['B'] ratings[sample] = ratings.get(sample, 0) + disposition ...
0bcecfdf33f42f85bb9a8e32e79686a41fb5226a
django_validator/exceptions.py
django_validator/exceptions.py
from rest_framework import status import rest_framework.exceptions class ValidationError(rest_framework.exceptions.ValidationError): code = '' def __init__(self, detail, code=None, status_code=status.HTTP_400_BAD_REQUEST): super(ValidationError, self).__init__(detail) self.status_code = status_code self.code = code
from rest_framework import status import rest_framework.exceptions class ValidationError(rest_framework.exceptions.APIException): code = '' def __init__(self, detail, code=None, status_code=status.HTTP_400_BAD_REQUEST): super(ValidationError, self).__init__(detail) self.code = code self.status_code = status_code
Fix Validation import error in older DRF.
Fix Validation import error in older DRF.
Python
mit
romain-li/django-validator,romain-li/django-validator
from rest_framework import status import rest_framework.exceptions - class ValidationError(rest_framework.exceptions.ValidationError): + class ValidationError(rest_framework.exceptions.APIException): code = '' def __init__(self, detail, code=None, status_code=status.HTTP_400_BAD_REQUEST): super(ValidationError, self).__init__(detail) + self.code = code self.status_code = status_code - self.code = code
Fix Validation import error in older DRF.
## Code Before: from rest_framework import status import rest_framework.exceptions class ValidationError(rest_framework.exceptions.ValidationError): code = '' def __init__(self, detail, code=None, status_code=status.HTTP_400_BAD_REQUEST): super(ValidationError, self).__init__(detail) self.status_code = status_code self.code = code ## Instruction: Fix Validation import error in older DRF. ## Code After: from rest_framework import status import rest_framework.exceptions class ValidationError(rest_framework.exceptions.APIException): code = '' def __init__(self, detail, code=None, status_code=status.HTTP_400_BAD_REQUEST): super(ValidationError, self).__init__(detail) self.code = code self.status_code = status_code
... class ValidationError(rest_framework.exceptions.APIException): code = '' ... super(ValidationError, self).__init__(detail) self.code = code self.status_code = status_code ...
fe9a47f480b8db8de3b2b572f333e56497462ea2
Python/item15.py
Python/item15.py
def sort_priority(num,pro): res=num[:] def helper(x): if x in pro: return (0,x) return (1,x) res.sort(key=helper) return res def sort_priority3(num,pro): found=False def helper(x): nonlocal found if x in pro: found=True return (0,x) return (1,x) num.sort(key=helper) return found if __name__=='__main__': numbers=[2,5,7,4,1,3,8,6] group=[2,4,8] print(sort_priority(numbers,group)) print(numbers) print(sort_priority3(numbers,group)) print(numbers)
def sort_priority(num,pro): res=num[:] def helper(x): if x in pro: return (0,x) return (1,x) res.sort(key=helper) return res def sort_priority2(num,pro): found=[False] def helper(x): nonlocal found if x in pro: found[0]=True return (0,x) return (1,x) num.sort(key=helper) return found def sort_priority3(num,pro): found=False def helper(x): nonlocal found if x in pro: found=True return (0,x) return (1,x) num.sort(key=helper) return found if __name__=='__main__': numbers=[2,5,7,4,1,3,8,6] group=[2,4,8] print(sort_priority(numbers,group)) print(numbers) print(sort_priority2(numbers,group)) print(numbers) print(sort_priority3(numbers,group)) print(numbers)
Add the sort_priority2 for python2.
Add the sort_priority2 for python2.
Python
mit
Vayne-Lover/Effective
def sort_priority(num,pro): res=num[:] def helper(x): if x in pro: return (0,x) return (1,x) res.sort(key=helper) return res + + def sort_priority2(num,pro): + found=[False] + def helper(x): + nonlocal found + if x in pro: + found[0]=True + return (0,x) + return (1,x) + num.sort(key=helper) + return found def sort_priority3(num,pro): found=False def helper(x): nonlocal found if x in pro: found=True return (0,x) return (1,x) num.sort(key=helper) return found if __name__=='__main__': numbers=[2,5,7,4,1,3,8,6] group=[2,4,8] print(sort_priority(numbers,group)) print(numbers) + print(sort_priority2(numbers,group)) + print(numbers) print(sort_priority3(numbers,group)) print(numbers)
Add the sort_priority2 for python2.
## Code Before: def sort_priority(num,pro): res=num[:] def helper(x): if x in pro: return (0,x) return (1,x) res.sort(key=helper) return res def sort_priority3(num,pro): found=False def helper(x): nonlocal found if x in pro: found=True return (0,x) return (1,x) num.sort(key=helper) return found if __name__=='__main__': numbers=[2,5,7,4,1,3,8,6] group=[2,4,8] print(sort_priority(numbers,group)) print(numbers) print(sort_priority3(numbers,group)) print(numbers) ## Instruction: Add the sort_priority2 for python2. ## Code After: def sort_priority(num,pro): res=num[:] def helper(x): if x in pro: return (0,x) return (1,x) res.sort(key=helper) return res def sort_priority2(num,pro): found=[False] def helper(x): nonlocal found if x in pro: found[0]=True return (0,x) return (1,x) num.sort(key=helper) return found def sort_priority3(num,pro): found=False def helper(x): nonlocal found if x in pro: found=True return (0,x) return (1,x) num.sort(key=helper) return found if __name__=='__main__': numbers=[2,5,7,4,1,3,8,6] group=[2,4,8] print(sort_priority(numbers,group)) print(numbers) print(sort_priority2(numbers,group)) print(numbers) print(sort_priority3(numbers,group)) print(numbers)
... return res def sort_priority2(num,pro): found=[False] def helper(x): nonlocal found if x in pro: found[0]=True return (0,x) return (1,x) num.sort(key=helper) return found ... print(numbers) print(sort_priority2(numbers,group)) print(numbers) print(sort_priority3(numbers,group)) ...
471d9c2ab901a018ef7b64464f19898dfbc9dd12
ca_mb/__init__.py
ca_mb/__init__.py
from utils import CanadianJurisdiction class Manitoba(CanadianJurisdiction): classification = 'legislature' division_id = 'ocd-division/country:ca/province:mb' division_name = 'Manitoba' name = 'Legislative Assembly of Manitoba' url = 'http://www.gov.mb.ca/legislature/' parties = [ {'name': 'New Democratic Party of Manitoba'}, {'name': 'Progressive Conservative Party of Manitoba'}, {'name': 'Manitoba Liberal Party'}, {'name': 'Manitoba Party'}, {'name': 'Independent'}, ]
from utils import CanadianJurisdiction class Manitoba(CanadianJurisdiction): classification = 'legislature' division_id = 'ocd-division/country:ca/province:mb' division_name = 'Manitoba' name = 'Legislative Assembly of Manitoba' url = 'http://www.gov.mb.ca/legislature/' parties = [ {'name': 'Independent'}, {'name': 'Independent Liberal'}, {'name': 'Manitoba Liberal Party'}, {'name': 'Manitoba Party'}, {'name': 'New Democratic Party of Manitoba'}, {'name': 'Progressive Conservative Party of Manitoba'}, ] skip_null_valid_from = True valid_from = '2019-09-10'
Fix for new divisions and parties
ca_mb: Fix for new divisions and parties
Python
mit
opencivicdata/scrapers-ca,opencivicdata/scrapers-ca
from utils import CanadianJurisdiction class Manitoba(CanadianJurisdiction): classification = 'legislature' division_id = 'ocd-division/country:ca/province:mb' division_name = 'Manitoba' name = 'Legislative Assembly of Manitoba' url = 'http://www.gov.mb.ca/legislature/' parties = [ + {'name': 'Independent'}, + {'name': 'Independent Liberal'}, + {'name': 'Manitoba Liberal Party'}, + {'name': 'Manitoba Party'}, {'name': 'New Democratic Party of Manitoba'}, {'name': 'Progressive Conservative Party of Manitoba'}, - {'name': 'Manitoba Liberal Party'}, - {'name': 'Manitoba Party'}, - {'name': 'Independent'}, ] + skip_null_valid_from = True + valid_from = '2019-09-10'
Fix for new divisions and parties
## Code Before: from utils import CanadianJurisdiction class Manitoba(CanadianJurisdiction): classification = 'legislature' division_id = 'ocd-division/country:ca/province:mb' division_name = 'Manitoba' name = 'Legislative Assembly of Manitoba' url = 'http://www.gov.mb.ca/legislature/' parties = [ {'name': 'New Democratic Party of Manitoba'}, {'name': 'Progressive Conservative Party of Manitoba'}, {'name': 'Manitoba Liberal Party'}, {'name': 'Manitoba Party'}, {'name': 'Independent'}, ] ## Instruction: Fix for new divisions and parties ## Code After: from utils import CanadianJurisdiction class Manitoba(CanadianJurisdiction): classification = 'legislature' division_id = 'ocd-division/country:ca/province:mb' division_name = 'Manitoba' name = 'Legislative Assembly of Manitoba' url = 'http://www.gov.mb.ca/legislature/' parties = [ {'name': 'Independent'}, {'name': 'Independent Liberal'}, {'name': 'Manitoba Liberal Party'}, {'name': 'Manitoba Party'}, {'name': 'New Democratic Party of Manitoba'}, {'name': 'Progressive Conservative Party of Manitoba'}, ] skip_null_valid_from = True valid_from = '2019-09-10'
// ... existing code ... parties = [ {'name': 'Independent'}, {'name': 'Independent Liberal'}, {'name': 'Manitoba Liberal Party'}, {'name': 'Manitoba Party'}, {'name': 'New Democratic Party of Manitoba'}, // ... modified code ... {'name': 'Progressive Conservative Party of Manitoba'}, ] skip_null_valid_from = True valid_from = '2019-09-10' // ... rest of the code ...
227d4c152367292e8b0b8801d9ce6179af92432a
python/014_longest_common_prefix.py
python/014_longest_common_prefix.py
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if len(strs)==0: return "" lcp=list(strs[0]) for i,string in enumerate(strs): if list(string[0:len(lcp)])==lcp: continue else: while len(lcp)>0 and list(string[0:len(lcp)])!=lcp: lcp.pop() if lcp==0: return "" return "".join(lcp)
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if strs is None or strs == "": return "" lcp = list(strs[0]) for i, string in enumerate(strs): if list(string[0:len(lcp)]) == lcp: continue else: while len(lcp) > 0 and list(string[0:len(lcp)]) != lcp: lcp.pop() if lcp == 0: return "" return "".join(lcp) a = Solution() print(a.longestCommonPrefix(["apps","apple","append"]) == "app")
Add test case to 014
Add test case to 014
Python
mit
ufjfeng/leetcode-jf-soln,ufjfeng/leetcode-jf-soln
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ - if len(strs)==0: + if strs is None or strs == "": return "" - lcp=list(strs[0]) + lcp = list(strs[0]) - for i,string in enumerate(strs): + for i, string in enumerate(strs): - if list(string[0:len(lcp)])==lcp: + if list(string[0:len(lcp)]) == lcp: continue else: - while len(lcp)>0 and list(string[0:len(lcp)])!=lcp: + while len(lcp) > 0 and list(string[0:len(lcp)]) != lcp: lcp.pop() - if lcp==0: + if lcp == 0: return "" return "".join(lcp) + a = Solution() + print(a.longestCommonPrefix(["apps","apple","append"]) == "app") +
Add test case to 014
## Code Before: class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if len(strs)==0: return "" lcp=list(strs[0]) for i,string in enumerate(strs): if list(string[0:len(lcp)])==lcp: continue else: while len(lcp)>0 and list(string[0:len(lcp)])!=lcp: lcp.pop() if lcp==0: return "" return "".join(lcp) ## Instruction: Add test case to 014 ## Code After: class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if strs is None or strs == "": return "" lcp = list(strs[0]) for i, string in enumerate(strs): if list(string[0:len(lcp)]) == lcp: continue else: while len(lcp) > 0 and list(string[0:len(lcp)]) != lcp: lcp.pop() if lcp == 0: return "" return "".join(lcp) a = Solution() print(a.longestCommonPrefix(["apps","apple","append"]) == "app")
# ... existing code ... """ if strs is None or strs == "": return "" lcp = list(strs[0]) for i, string in enumerate(strs): if list(string[0:len(lcp)]) == lcp: continue # ... modified code ... else: while len(lcp) > 0 and list(string[0:len(lcp)]) != lcp: lcp.pop() if lcp == 0: return "" ... return "".join(lcp) a = Solution() print(a.longestCommonPrefix(["apps","apple","append"]) == "app") # ... rest of the code ...
838063cc08da66a31666f798437b8dcdde0286f0
mpf/config_players/flasher_player.py
mpf/config_players/flasher_player.py
"""Flasher config player.""" from mpf.config_players.device_config_player import DeviceConfigPlayer from mpf.core.delays import DelayManager class FlasherPlayer(DeviceConfigPlayer): """Triggers flashers based on config.""" config_file_section = 'flasher_player' show_section = 'flashers' __slots__ = ["delay"] def __init__(self, machine): """Initialise flasher_player.""" super().__init__(machine) self.delay = DelayManager(self.machine.delayRegistry) def play(self, settings, context, calling_context, priority=0, **kwargs): """Flash flashers.""" del kwargs for flasher, s in settings.items(): if isinstance(flasher, str): self._flash(self.machine.lights[flasher], duration_ms=s['ms'], key=context) else: self._flash(flasher, duration_ms=s['ms'], key=context) def _flash(self, light, duration_ms, key): light.color("white", fade_ms=0, key=key) self.delay.add(duration_ms, self._remove_flash, light=light, key=key) @staticmethod def _remove_flash(light, key): light.remove_from_stack_by_key(key=key, fade_ms=0) def get_express_config(self, value): """Parse express config.""" return dict(ms=value)
"""Flasher config player.""" from mpf.config_players.device_config_player import DeviceConfigPlayer from mpf.core.delays import DelayManager from mpf.core.utility_functions import Util class FlasherPlayer(DeviceConfigPlayer): """Triggers flashers based on config.""" config_file_section = 'flasher_player' show_section = 'flashers' __slots__ = ["delay"] def __init__(self, machine): """Initialise flasher_player.""" super().__init__(machine) self.delay = DelayManager(self.machine.delayRegistry) def play(self, settings, context, calling_context, priority=0, **kwargs): """Flash flashers.""" del kwargs for flasher, s in settings.items(): if isinstance(flasher, str): flasher_names = Util.string_to_list(flasher) for flasher_name in flasher_names: self._flash(self.machine.lights[flasher_name], duration_ms=s['ms'], key=context) else: self._flash(flasher, duration_ms=s['ms'], key=context) def _flash(self, light, duration_ms, key): light.color("white", fade_ms=0, key=key) self.delay.add(duration_ms, self._remove_flash, light=light, key=key) @staticmethod def _remove_flash(light, key): light.remove_from_stack_by_key(key=key, fade_ms=0) def get_express_config(self, value): """Parse express config.""" return dict(ms=value)
Allow list of flashers as show token value
Allow list of flashers as show token value
Python
mit
missionpinball/mpf,missionpinball/mpf
"""Flasher config player.""" from mpf.config_players.device_config_player import DeviceConfigPlayer from mpf.core.delays import DelayManager + from mpf.core.utility_functions import Util class FlasherPlayer(DeviceConfigPlayer): """Triggers flashers based on config.""" config_file_section = 'flasher_player' show_section = 'flashers' __slots__ = ["delay"] def __init__(self, machine): """Initialise flasher_player.""" super().__init__(machine) self.delay = DelayManager(self.machine.delayRegistry) def play(self, settings, context, calling_context, priority=0, **kwargs): """Flash flashers.""" del kwargs for flasher, s in settings.items(): if isinstance(flasher, str): + flasher_names = Util.string_to_list(flasher) + for flasher_name in flasher_names: - self._flash(self.machine.lights[flasher], + self._flash(self.machine.lights[flasher_name], - duration_ms=s['ms'], + duration_ms=s['ms'], - key=context) + key=context) else: self._flash(flasher, duration_ms=s['ms'], key=context) def _flash(self, light, duration_ms, key): light.color("white", fade_ms=0, key=key) self.delay.add(duration_ms, self._remove_flash, light=light, key=key) @staticmethod def _remove_flash(light, key): light.remove_from_stack_by_key(key=key, fade_ms=0) def get_express_config(self, value): """Parse express config.""" return dict(ms=value)
Allow list of flashers as show token value
## Code Before: """Flasher config player.""" from mpf.config_players.device_config_player import DeviceConfigPlayer from mpf.core.delays import DelayManager class FlasherPlayer(DeviceConfigPlayer): """Triggers flashers based on config.""" config_file_section = 'flasher_player' show_section = 'flashers' __slots__ = ["delay"] def __init__(self, machine): """Initialise flasher_player.""" super().__init__(machine) self.delay = DelayManager(self.machine.delayRegistry) def play(self, settings, context, calling_context, priority=0, **kwargs): """Flash flashers.""" del kwargs for flasher, s in settings.items(): if isinstance(flasher, str): self._flash(self.machine.lights[flasher], duration_ms=s['ms'], key=context) else: self._flash(flasher, duration_ms=s['ms'], key=context) def _flash(self, light, duration_ms, key): light.color("white", fade_ms=0, key=key) self.delay.add(duration_ms, self._remove_flash, light=light, key=key) @staticmethod def _remove_flash(light, key): light.remove_from_stack_by_key(key=key, fade_ms=0) def get_express_config(self, value): """Parse express config.""" return dict(ms=value) ## Instruction: Allow list of flashers as show token value ## Code After: """Flasher config player.""" from mpf.config_players.device_config_player import DeviceConfigPlayer from mpf.core.delays import DelayManager from mpf.core.utility_functions import Util class FlasherPlayer(DeviceConfigPlayer): """Triggers flashers based on config.""" config_file_section = 'flasher_player' show_section = 'flashers' __slots__ = ["delay"] def __init__(self, machine): """Initialise flasher_player.""" super().__init__(machine) self.delay = DelayManager(self.machine.delayRegistry) def play(self, settings, context, calling_context, priority=0, **kwargs): """Flash flashers.""" del kwargs for flasher, s in settings.items(): if isinstance(flasher, str): flasher_names = Util.string_to_list(flasher) for flasher_name in flasher_names: self._flash(self.machine.lights[flasher_name], duration_ms=s['ms'], key=context) else: self._flash(flasher, duration_ms=s['ms'], key=context) def _flash(self, light, duration_ms, key): light.color("white", fade_ms=0, key=key) self.delay.add(duration_ms, self._remove_flash, light=light, key=key) @staticmethod def _remove_flash(light, key): light.remove_from_stack_by_key(key=key, fade_ms=0) def get_express_config(self, value): """Parse express config.""" return dict(ms=value)
... from mpf.core.delays import DelayManager from mpf.core.utility_functions import Util ... if isinstance(flasher, str): flasher_names = Util.string_to_list(flasher) for flasher_name in flasher_names: self._flash(self.machine.lights[flasher_name], duration_ms=s['ms'], key=context) else: ...
fe768f5d8c1081f69acd8cf656aa618da7caf93b
cbpos/mod/currency/views/config.py
cbpos/mod/currency/views/config.py
from PySide import QtGui import cbpos from cbpos.mod.currency.models.currency import Currency class CurrencyConfigPage(QtGui.QWidget): label = 'Currency' def __init__(self): super(CurrencyConfigPage, self).__init__() self.default = QtGui.QComboBox() form = QtGui.QFormLayout() form.setSpacing(10) form.addRow('Default Currency', self.default) self.setLayout(form) def populate(self): session = cbpos.database.session() default_id = cbpos.config['mod.currency', 'default'] selected_index = -1 self.default.clear() for i, c in enumerate(session.query(Currency)): self.default.addItem(c.display, c) if default_id == c.id: selected_index = i self.default.setCurrentIndex(selected_index) def update(self): default = self.default.itemData(self.default.currentIndex()) cbpos.config['mod.currency', 'default'] = unicode(default.id)
from PySide import QtGui import cbpos import cbpos.mod.currency.controllers as currency from cbpos.mod.currency.models.currency import Currency class CurrencyConfigPage(QtGui.QWidget): label = 'Currency' def __init__(self): super(CurrencyConfigPage, self).__init__() self.default = QtGui.QComboBox() form = QtGui.QFormLayout() form.setSpacing(10) form.addRow('Default Currency', self.default) self.setLayout(form) def populate(self): session = cbpos.database.session() default_id = currency.default.id selected_index = -1 self.default.clear() for i, c in enumerate(session.query(Currency)): self.default.addItem(c.display, c) if default_id == c.id: selected_index = i self.default.setCurrentIndex(selected_index) def update(self): default = self.default.itemData(self.default.currentIndex()) cbpos.config['mod.currency', 'default'] = unicode(default.id)
Handle unset default currency better
Handle unset default currency better
Python
mit
coinbox/coinbox-mod-currency
from PySide import QtGui import cbpos + import cbpos.mod.currency.controllers as currency from cbpos.mod.currency.models.currency import Currency class CurrencyConfigPage(QtGui.QWidget): label = 'Currency' def __init__(self): super(CurrencyConfigPage, self).__init__() self.default = QtGui.QComboBox() form = QtGui.QFormLayout() form.setSpacing(10) form.addRow('Default Currency', self.default) self.setLayout(form) def populate(self): session = cbpos.database.session() - default_id = cbpos.config['mod.currency', 'default'] + default_id = currency.default.id selected_index = -1 self.default.clear() for i, c in enumerate(session.query(Currency)): self.default.addItem(c.display, c) if default_id == c.id: selected_index = i self.default.setCurrentIndex(selected_index) def update(self): default = self.default.itemData(self.default.currentIndex()) cbpos.config['mod.currency', 'default'] = unicode(default.id)
Handle unset default currency better
## Code Before: from PySide import QtGui import cbpos from cbpos.mod.currency.models.currency import Currency class CurrencyConfigPage(QtGui.QWidget): label = 'Currency' def __init__(self): super(CurrencyConfigPage, self).__init__() self.default = QtGui.QComboBox() form = QtGui.QFormLayout() form.setSpacing(10) form.addRow('Default Currency', self.default) self.setLayout(form) def populate(self): session = cbpos.database.session() default_id = cbpos.config['mod.currency', 'default'] selected_index = -1 self.default.clear() for i, c in enumerate(session.query(Currency)): self.default.addItem(c.display, c) if default_id == c.id: selected_index = i self.default.setCurrentIndex(selected_index) def update(self): default = self.default.itemData(self.default.currentIndex()) cbpos.config['mod.currency', 'default'] = unicode(default.id) ## Instruction: Handle unset default currency better ## Code After: from PySide import QtGui import cbpos import cbpos.mod.currency.controllers as currency from cbpos.mod.currency.models.currency import Currency class CurrencyConfigPage(QtGui.QWidget): label = 'Currency' def __init__(self): super(CurrencyConfigPage, self).__init__() self.default = QtGui.QComboBox() form = QtGui.QFormLayout() form.setSpacing(10) form.addRow('Default Currency', self.default) self.setLayout(form) def populate(self): session = cbpos.database.session() default_id = currency.default.id selected_index = -1 self.default.clear() for i, c in enumerate(session.query(Currency)): self.default.addItem(c.display, c) if default_id == c.id: selected_index = i self.default.setCurrentIndex(selected_index) def update(self): default = self.default.itemData(self.default.currentIndex()) cbpos.config['mod.currency', 'default'] = unicode(default.id)
# ... existing code ... import cbpos.mod.currency.controllers as currency from cbpos.mod.currency.models.currency import Currency # ... modified code ... default_id = currency.default.id # ... rest of the code ...
63241b7fb62166f4a31ef7ece38edf8b36129f63
dictionary/management/commands/writeLiblouisTables.py
dictionary/management/commands/writeLiblouisTables.py
from daisyproducer.dictionary.brailleTables import writeWhiteListTables, writeLocalTables from daisyproducer.dictionary.models import Word from daisyproducer.documents.models import Document from django.core.management.base import BaseCommand class Command(BaseCommand): args = '' help = 'Write Liblouis tables from the confirmed words in the dictionary' def handle(self, *args, **options): # write new global white lists if options['verbosity'] >= 2: self.stderr.write('Writing new global white lists...\n') writeWhiteListTables(Word.objects.filter(isConfirmed=True).filter(isLocal=False).order_by('untranslated')) # update local tables if options['verbosity'] >= 2: self.stderr.write('Updating local tables...\n') writeLocalTables(Document.objects.all())
from daisyproducer.dictionary.brailleTables import writeWhiteListTables, writeLocalTables from daisyproducer.dictionary.models import Word from daisyproducer.documents.models import Document from django.core.management.base import BaseCommand class Command(BaseCommand): args = '' help = 'Write Liblouis tables from the confirmed words in the dictionary' def handle(self, *args, **options): # write new global white lists verbosity = int(options['verbosity']) if verbosity >= 2: self.stderr.write('Writing new global white lists...\n') writeWhiteListTables(Word.objects.filter(isConfirmed=True).filter(isLocal=False).order_by('untranslated')) # update local tables if verbosity >= 2: self.stderr.write('Updating local tables...\n') writeLocalTables(Document.objects.all())
Make sure the verbosity stuff actually works
Make sure the verbosity stuff actually works
Python
agpl-3.0
sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer
from daisyproducer.dictionary.brailleTables import writeWhiteListTables, writeLocalTables from daisyproducer.dictionary.models import Word from daisyproducer.documents.models import Document from django.core.management.base import BaseCommand class Command(BaseCommand): args = '' help = 'Write Liblouis tables from the confirmed words in the dictionary' def handle(self, *args, **options): # write new global white lists + verbosity = int(options['verbosity']) - if options['verbosity'] >= 2: + if verbosity >= 2: self.stderr.write('Writing new global white lists...\n') writeWhiteListTables(Word.objects.filter(isConfirmed=True).filter(isLocal=False).order_by('untranslated')) # update local tables - if options['verbosity'] >= 2: + if verbosity >= 2: self.stderr.write('Updating local tables...\n') writeLocalTables(Document.objects.all())
Make sure the verbosity stuff actually works
## Code Before: from daisyproducer.dictionary.brailleTables import writeWhiteListTables, writeLocalTables from daisyproducer.dictionary.models import Word from daisyproducer.documents.models import Document from django.core.management.base import BaseCommand class Command(BaseCommand): args = '' help = 'Write Liblouis tables from the confirmed words in the dictionary' def handle(self, *args, **options): # write new global white lists if options['verbosity'] >= 2: self.stderr.write('Writing new global white lists...\n') writeWhiteListTables(Word.objects.filter(isConfirmed=True).filter(isLocal=False).order_by('untranslated')) # update local tables if options['verbosity'] >= 2: self.stderr.write('Updating local tables...\n') writeLocalTables(Document.objects.all()) ## Instruction: Make sure the verbosity stuff actually works ## Code After: from daisyproducer.dictionary.brailleTables import writeWhiteListTables, writeLocalTables from daisyproducer.dictionary.models import Word from daisyproducer.documents.models import Document from django.core.management.base import BaseCommand class Command(BaseCommand): args = '' help = 'Write Liblouis tables from the confirmed words in the dictionary' def handle(self, *args, **options): # write new global white lists verbosity = int(options['verbosity']) if verbosity >= 2: self.stderr.write('Writing new global white lists...\n') writeWhiteListTables(Word.objects.filter(isConfirmed=True).filter(isLocal=False).order_by('untranslated')) # update local tables if verbosity >= 2: self.stderr.write('Updating local tables...\n') writeLocalTables(Document.objects.all())
# ... existing code ... # write new global white lists verbosity = int(options['verbosity']) if verbosity >= 2: self.stderr.write('Writing new global white lists...\n') # ... modified code ... # update local tables if verbosity >= 2: self.stderr.write('Updating local tables...\n') # ... rest of the code ...