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
09a6e2528f062581c90ed3f3225f19b36f0ac0f9
eve_api/forms.py
eve_api/forms.py
import re from django import forms from eve_api.models import EVEAccount, EVEPlayerCharacter, EVEPlayerCorporation class EveAPIForm(forms.Form): """ EVE API input form """ user_id = forms.IntegerField(label=u'User ID') api_key = forms.CharField(label=u'API Key', max_length=64) description = forms.CharField(max_length=100, required=False) def clean_api_key(self): if not len(self.cleaned_data['api_key']) == 64: raise forms.ValidationError("Provided API Key is not 64 characters long.") if re.search(r'[^\.a-zA-Z0-9]', self.cleaned_data['api_key']): raise forms.ValidationError("Provided API Key has invalid characters.") def clean_user_id(self): if not 'user_id' in self.cleaned_data or self.cleaned_data['user_id'] == '': raise forms.ValidationError("Please provide a valid User ID") try: eaccount = EVEAccount.objects.get(api_user_id=self.cleaned_data['user_id']) except EVEAccount.DoesNotExist: return self.cleaned_data else: raise forms.ValidationError("This API User ID is already registered")
import re from django import forms from eve_api.models import EVEAccount, EVEPlayerCharacter, EVEPlayerCorporation class EveAPIForm(forms.Form): """ EVE API input form """ user_id = forms.IntegerField(label=u'User ID') api_key = forms.CharField(label=u'API Key', max_length=64) description = forms.CharField(max_length=100, required=False) def clean_api_key(self): if not len(self.cleaned_data['api_key']) == 64: raise forms.ValidationError("Provided API Key is not 64 characters long.") if re.search(r'[^\.a-zA-Z0-9]', self.cleaned_data['api_key']): raise forms.ValidationError("Provided API Key has invalid characters.") return self.cleaned_data['api_key'] def clean_user_id(self): if not 'user_id' in self.cleaned_data or self.cleaned_data['user_id'] == '': raise forms.ValidationError("Please provide a valid User ID") try: eaccount = EVEAccount.objects.get(api_user_id=self.cleaned_data['user_id']) except EVEAccount.DoesNotExist: pass else: raise forms.ValidationError("This API User ID is already registered") return self.cleaned_data['user_id']
Fix the validation data on the EVEAPIForm
Fix the validation data on the EVEAPIForm
Python
bsd-3-clause
nikdoof/test-auth
import re from django import forms from eve_api.models import EVEAccount, EVEPlayerCharacter, EVEPlayerCorporation class EveAPIForm(forms.Form): """ EVE API input form """ user_id = forms.IntegerField(label=u'User ID') api_key = forms.CharField(label=u'API Key', max_length=64) description = forms.CharField(max_length=100, required=False) def clean_api_key(self): if not len(self.cleaned_data['api_key']) == 64: raise forms.ValidationError("Provided API Key is not 64 characters long.") if re.search(r'[^\.a-zA-Z0-9]', self.cleaned_data['api_key']): raise forms.ValidationError("Provided API Key has invalid characters.") + return self.cleaned_data['api_key'] + def clean_user_id(self): if not 'user_id' in self.cleaned_data or self.cleaned_data['user_id'] == '': raise forms.ValidationError("Please provide a valid User ID") try: eaccount = EVEAccount.objects.get(api_user_id=self.cleaned_data['user_id']) except EVEAccount.DoesNotExist: - return self.cleaned_data + pass else: raise forms.ValidationError("This API User ID is already registered") + return self.cleaned_data['user_id']
Fix the validation data on the EVEAPIForm
## Code Before: import re from django import forms from eve_api.models import EVEAccount, EVEPlayerCharacter, EVEPlayerCorporation class EveAPIForm(forms.Form): """ EVE API input form """ user_id = forms.IntegerField(label=u'User ID') api_key = forms.CharField(label=u'API Key', max_length=64) description = forms.CharField(max_length=100, required=False) def clean_api_key(self): if not len(self.cleaned_data['api_key']) == 64: raise forms.ValidationError("Provided API Key is not 64 characters long.") if re.search(r'[^\.a-zA-Z0-9]', self.cleaned_data['api_key']): raise forms.ValidationError("Provided API Key has invalid characters.") def clean_user_id(self): if not 'user_id' in self.cleaned_data or self.cleaned_data['user_id'] == '': raise forms.ValidationError("Please provide a valid User ID") try: eaccount = EVEAccount.objects.get(api_user_id=self.cleaned_data['user_id']) except EVEAccount.DoesNotExist: return self.cleaned_data else: raise forms.ValidationError("This API User ID is already registered") ## Instruction: Fix the validation data on the EVEAPIForm ## Code After: import re from django import forms from eve_api.models import EVEAccount, EVEPlayerCharacter, EVEPlayerCorporation class EveAPIForm(forms.Form): """ EVE API input form """ user_id = forms.IntegerField(label=u'User ID') api_key = forms.CharField(label=u'API Key', max_length=64) description = forms.CharField(max_length=100, required=False) def clean_api_key(self): if not len(self.cleaned_data['api_key']) == 64: raise forms.ValidationError("Provided API Key is not 64 characters long.") if re.search(r'[^\.a-zA-Z0-9]', self.cleaned_data['api_key']): raise forms.ValidationError("Provided API Key has invalid characters.") return self.cleaned_data['api_key'] def clean_user_id(self): if not 'user_id' in self.cleaned_data or self.cleaned_data['user_id'] == '': raise forms.ValidationError("Please provide a valid User ID") try: eaccount = EVEAccount.objects.get(api_user_id=self.cleaned_data['user_id']) except EVEAccount.DoesNotExist: pass else: raise forms.ValidationError("This API User ID is already registered") return self.cleaned_data['user_id']
// ... existing code ... return self.cleaned_data['api_key'] def clean_user_id(self): // ... modified code ... except EVEAccount.DoesNotExist: pass else: ... return self.cleaned_data['user_id'] // ... rest of the code ...
b202e1cc5e6c5aa65c3ed22ad1e78ec505fa36c4
cmsplugin_rst/forms.py
cmsplugin_rst/forms.py
from cmsplugin_rst.models import RstPluginModel from django import forms help_text = '<a href="http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html">Reference</a>' class RstPluginForm(forms.ModelForm): body = forms.CharField( widget=forms.Textarea(attrs={ 'rows':30, 'cols':80, 'style':'font-family:monospace' }), help_text=help_text ) class Meta: model = RstPluginModel
from cmsplugin_rst.models import RstPluginModel from django import forms help_text = '<a href="http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html">Reference</a>' class RstPluginForm(forms.ModelForm): body = forms.CharField( widget=forms.Textarea(attrs={ 'rows':30, 'cols':80, 'style':'font-family:monospace' }), help_text=help_text ) class Meta: model = RstPluginModel fields = ["name", "body"]
Add "fields" attribute to ModelForm.
Add "fields" attribute to ModelForm.
Python
bsd-3-clause
pakal/cmsplugin-rst,ojii/cmsplugin-rst
from cmsplugin_rst.models import RstPluginModel from django import forms help_text = '<a href="http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html">Reference</a>' class RstPluginForm(forms.ModelForm): body = forms.CharField( widget=forms.Textarea(attrs={ 'rows':30, 'cols':80, 'style':'font-family:monospace' }), help_text=help_text ) class Meta: model = RstPluginModel + fields = ["name", "body"]
Add "fields" attribute to ModelForm.
## Code Before: from cmsplugin_rst.models import RstPluginModel from django import forms help_text = '<a href="http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html">Reference</a>' class RstPluginForm(forms.ModelForm): body = forms.CharField( widget=forms.Textarea(attrs={ 'rows':30, 'cols':80, 'style':'font-family:monospace' }), help_text=help_text ) class Meta: model = RstPluginModel ## Instruction: Add "fields" attribute to ModelForm. ## Code After: from cmsplugin_rst.models import RstPluginModel from django import forms help_text = '<a href="http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html">Reference</a>' class RstPluginForm(forms.ModelForm): body = forms.CharField( widget=forms.Textarea(attrs={ 'rows':30, 'cols':80, 'style':'font-family:monospace' }), help_text=help_text ) class Meta: model = RstPluginModel fields = ["name", "body"]
# ... existing code ... model = RstPluginModel fields = ["name", "body"] # ... rest of the code ...
1edf69ac029bf8e35cd897fa123ad4e0943d6bc9
src/wikicurses/__init__.py
src/wikicurses/__init__.py
from enum import Enum class BitEnum(int, Enum): def __new__(cls, *args): value = 1 << len(cls.__members__) return int.__new__(cls, value) formats = BitEnum("formats", "i b blockquote")
from enum import IntEnum class formats(IntEnum): i, b, blockquote = (1<<i for i in range(3))
Remove BitEnum class, use IntEnum
Remove BitEnum class, use IntEnum
Python
mit
ids1024/wikicurses
- from enum import Enum + from enum import IntEnum + class formats(IntEnum): + i, b, blockquote = (1<<i for i in range(3)) - class BitEnum(int, Enum): - def __new__(cls, *args): - value = 1 << len(cls.__members__) - return int.__new__(cls, value) - formats = BitEnum("formats", "i b blockquote") -
Remove BitEnum class, use IntEnum
## Code Before: from enum import Enum class BitEnum(int, Enum): def __new__(cls, *args): value = 1 << len(cls.__members__) return int.__new__(cls, value) formats = BitEnum("formats", "i b blockquote") ## Instruction: Remove BitEnum class, use IntEnum ## Code After: from enum import IntEnum class formats(IntEnum): i, b, blockquote = (1<<i for i in range(3))
// ... existing code ... from enum import IntEnum class formats(IntEnum): i, b, blockquote = (1<<i for i in range(3)) // ... rest of the code ...
26581b24dd00c3b0a0928fe0b24ae129c701fb58
jarbas/frontend/tests/test_bundle_dependecies.py
jarbas/frontend/tests/test_bundle_dependecies.py
from django.test import TestCase from webassets.bundle import get_all_bundle_files from jarbas.frontend.assets import elm class TestDependencies(TestCase): def test_dependencies(self): files = set(get_all_bundle_files(elm)) self.assertEqual(9, len(files), files)
from glob import glob from django.test import TestCase from webassets.bundle import get_all_bundle_files from jarbas.frontend.assets import elm class TestDependencies(TestCase): def test_dependencies(self): expected = len(glob('jarbas/frontend/elm/**/*.elm', recursive=True)) files = set(get_all_bundle_files(elm)) self.assertEqual(expected, len(files), files)
Fix test for Elm files lookup
Fix test for Elm files lookup
Python
mit
datasciencebr/jarbas,rogeriochaves/jarbas,Guilhermeslucas/jarbas,marcusrehm/serenata-de-amor,marcusrehm/serenata-de-amor,datasciencebr/jarbas,marcusrehm/serenata-de-amor,Guilhermeslucas/jarbas,datasciencebr/jarbas,Guilhermeslucas/jarbas,rogeriochaves/jarbas,rogeriochaves/jarbas,Guilhermeslucas/jarbas,datasciencebr/jarbas,datasciencebr/serenata-de-amor,rogeriochaves/jarbas,datasciencebr/serenata-de-amor,marcusrehm/serenata-de-amor
+ from glob import glob from django.test import TestCase from webassets.bundle import get_all_bundle_files from jarbas.frontend.assets import elm class TestDependencies(TestCase): def test_dependencies(self): + expected = len(glob('jarbas/frontend/elm/**/*.elm', recursive=True)) files = set(get_all_bundle_files(elm)) - self.assertEqual(9, len(files), files) + self.assertEqual(expected, len(files), files)
Fix test for Elm files lookup
## Code Before: from django.test import TestCase from webassets.bundle import get_all_bundle_files from jarbas.frontend.assets import elm class TestDependencies(TestCase): def test_dependencies(self): files = set(get_all_bundle_files(elm)) self.assertEqual(9, len(files), files) ## Instruction: Fix test for Elm files lookup ## Code After: from glob import glob from django.test import TestCase from webassets.bundle import get_all_bundle_files from jarbas.frontend.assets import elm class TestDependencies(TestCase): def test_dependencies(self): expected = len(glob('jarbas/frontend/elm/**/*.elm', recursive=True)) files = set(get_all_bundle_files(elm)) self.assertEqual(expected, len(files), files)
# ... existing code ... from glob import glob from django.test import TestCase # ... modified code ... def test_dependencies(self): expected = len(glob('jarbas/frontend/elm/**/*.elm', recursive=True)) files = set(get_all_bundle_files(elm)) self.assertEqual(expected, len(files), files) # ... rest of the code ...
3c9b49ef968c7e59028eb0bda78b1474a49339f3
numscons/tools/intel_common/common.py
numscons/tools/intel_common/common.py
_ARG2ABI = {'x86': 'ia32', 'amd64': 'em64t', 'default': 'ia32'} def get_abi(env): try: abi = env['ICC_ABI'] except KeyError: abi = 'default' try: return _ARG2ABI[abi] except KeyError: ValueError("Unknown abi %s" % abi)
_ARG2ABI = {'x86': 'ia32', 'amd64': 'em64t', 'default': 'ia32'} def get_abi(env, lang='C'): if lang == 'C' or lang == 'CXX': try: abi = env['ICC_ABI'] except KeyError: abi = 'default' elif lang == 'FORTRAN': try: abi = env['IFORT_ABI'] except KeyError: abi = 'default' try: return _ARG2ABI[abi] except KeyError: ValueError("Unknown abi %s" % abi)
Add a language argument to get abi for intel tools.
Add a language argument to get abi for intel tools.
Python
bsd-3-clause
cournape/numscons,cournape/numscons,cournape/numscons
_ARG2ABI = {'x86': 'ia32', 'amd64': 'em64t', 'default': 'ia32'} - def get_abi(env): + def get_abi(env, lang='C'): + if lang == 'C' or lang == 'CXX': - try: + try: - abi = env['ICC_ABI'] + abi = env['ICC_ABI'] - except KeyError: + except KeyError: - abi = 'default' + abi = 'default' + elif lang == 'FORTRAN': + try: + abi = env['IFORT_ABI'] + except KeyError: + abi = 'default' try: return _ARG2ABI[abi] except KeyError: ValueError("Unknown abi %s" % abi)
Add a language argument to get abi for intel tools.
## Code Before: _ARG2ABI = {'x86': 'ia32', 'amd64': 'em64t', 'default': 'ia32'} def get_abi(env): try: abi = env['ICC_ABI'] except KeyError: abi = 'default' try: return _ARG2ABI[abi] except KeyError: ValueError("Unknown abi %s" % abi) ## Instruction: Add a language argument to get abi for intel tools. ## Code After: _ARG2ABI = {'x86': 'ia32', 'amd64': 'em64t', 'default': 'ia32'} def get_abi(env, lang='C'): if lang == 'C' or lang == 'CXX': try: abi = env['ICC_ABI'] except KeyError: abi = 'default' elif lang == 'FORTRAN': try: abi = env['IFORT_ABI'] except KeyError: abi = 'default' try: return _ARG2ABI[abi] except KeyError: ValueError("Unknown abi %s" % abi)
... def get_abi(env, lang='C'): if lang == 'C' or lang == 'CXX': try: abi = env['ICC_ABI'] except KeyError: abi = 'default' elif lang == 'FORTRAN': try: abi = env['IFORT_ABI'] except KeyError: abi = 'default' ...
e80cc896396b217a3e3a4f01294b50061faf68cd
cyder/cydhcp/range/forms.py
cyder/cydhcp/range/forms.py
from django import forms from cyder.base.eav.forms import get_eav_form from cyder.base.mixins import UsabilityFormMixin from cyder.cydhcp.range.models import Range, RangeAV from cyder.cydns.forms import ViewChoiceForm class RangeForm(ViewChoiceForm, UsabilityFormMixin): class Meta: model = Range exclude = ('start_upper', 'start_lower', 'end_upper', 'end_lower') fields = ('network', 'ip_type', 'range_type', 'start_str', 'end_str', 'domain', 'is_reserved', 'allow', 'views', 'dhcpd_raw_include', 'dhcp_enabled', 'name') widgets = {'views': forms.CheckboxSelectMultiple, 'range_type': forms.RadioSelect, 'ip_type': forms.RadioSelect} exclude = 'range_usage' def __init__(self, *args, **kwargs): super(RangeForm, self).__init__(*args, **kwargs) self.fields['dhcpd_raw_include'].label = "DHCP Config Extras" self.fields['dhcpd_raw_include'].widget.attrs.update( {'cols': '80', 'style': 'display: none;width: 680px'}) RangeAVForm = get_eav_form(RangeAV, Range)
from django import forms from cyder.base.eav.forms import get_eav_form from cyder.base.mixins import UsabilityFormMixin from cyder.cydhcp.range.models import Range, RangeAV from cyder.cydns.forms import ViewChoiceForm class RangeForm(ViewChoiceForm, UsabilityFormMixin): class Meta: model = Range exclude = ('start_upper', 'start_lower', 'end_upper', 'end_lower') fields = ('name', 'network', 'ip_type', 'range_type', 'start_str', 'end_str', 'domain', 'is_reserved', 'allow', 'views', 'dhcpd_raw_include', 'dhcp_enabled') widgets = {'views': forms.CheckboxSelectMultiple, 'range_type': forms.RadioSelect, 'ip_type': forms.RadioSelect} exclude = 'range_usage' def __init__(self, *args, **kwargs): super(RangeForm, self).__init__(*args, **kwargs) self.fields['dhcpd_raw_include'].label = "DHCP Config Extras" self.fields['dhcpd_raw_include'].widget.attrs.update( {'cols': '80', 'style': 'display: none;width: 680px'}) RangeAVForm = get_eav_form(RangeAV, Range)
Put name first in range form
Put name first in range form
Python
bsd-3-clause
zeeman/cyder,zeeman/cyder,akeym/cyder,akeym/cyder,akeym/cyder,OSU-Net/cyder,OSU-Net/cyder,murrown/cyder,zeeman/cyder,OSU-Net/cyder,OSU-Net/cyder,murrown/cyder,akeym/cyder,zeeman/cyder,drkitty/cyder,murrown/cyder,murrown/cyder,drkitty/cyder,drkitty/cyder,drkitty/cyder
from django import forms from cyder.base.eav.forms import get_eav_form from cyder.base.mixins import UsabilityFormMixin from cyder.cydhcp.range.models import Range, RangeAV from cyder.cydns.forms import ViewChoiceForm class RangeForm(ViewChoiceForm, UsabilityFormMixin): class Meta: model = Range exclude = ('start_upper', 'start_lower', 'end_upper', 'end_lower') - fields = ('network', 'ip_type', 'range_type', 'start_str', 'end_str', + fields = ('name', 'network', 'ip_type', 'range_type', 'start_str', - 'domain', 'is_reserved', 'allow', 'views', + 'end_str', 'domain', 'is_reserved', 'allow', 'views', - 'dhcpd_raw_include', 'dhcp_enabled', 'name') + 'dhcpd_raw_include', 'dhcp_enabled') widgets = {'views': forms.CheckboxSelectMultiple, 'range_type': forms.RadioSelect, 'ip_type': forms.RadioSelect} exclude = 'range_usage' def __init__(self, *args, **kwargs): super(RangeForm, self).__init__(*args, **kwargs) self.fields['dhcpd_raw_include'].label = "DHCP Config Extras" self.fields['dhcpd_raw_include'].widget.attrs.update( {'cols': '80', 'style': 'display: none;width: 680px'}) RangeAVForm = get_eav_form(RangeAV, Range)
Put name first in range form
## Code Before: from django import forms from cyder.base.eav.forms import get_eav_form from cyder.base.mixins import UsabilityFormMixin from cyder.cydhcp.range.models import Range, RangeAV from cyder.cydns.forms import ViewChoiceForm class RangeForm(ViewChoiceForm, UsabilityFormMixin): class Meta: model = Range exclude = ('start_upper', 'start_lower', 'end_upper', 'end_lower') fields = ('network', 'ip_type', 'range_type', 'start_str', 'end_str', 'domain', 'is_reserved', 'allow', 'views', 'dhcpd_raw_include', 'dhcp_enabled', 'name') widgets = {'views': forms.CheckboxSelectMultiple, 'range_type': forms.RadioSelect, 'ip_type': forms.RadioSelect} exclude = 'range_usage' def __init__(self, *args, **kwargs): super(RangeForm, self).__init__(*args, **kwargs) self.fields['dhcpd_raw_include'].label = "DHCP Config Extras" self.fields['dhcpd_raw_include'].widget.attrs.update( {'cols': '80', 'style': 'display: none;width: 680px'}) RangeAVForm = get_eav_form(RangeAV, Range) ## Instruction: Put name first in range form ## Code After: from django import forms from cyder.base.eav.forms import get_eav_form from cyder.base.mixins import UsabilityFormMixin from cyder.cydhcp.range.models import Range, RangeAV from cyder.cydns.forms import ViewChoiceForm class RangeForm(ViewChoiceForm, UsabilityFormMixin): class Meta: model = Range exclude = ('start_upper', 'start_lower', 'end_upper', 'end_lower') fields = ('name', 'network', 'ip_type', 'range_type', 'start_str', 'end_str', 'domain', 'is_reserved', 'allow', 'views', 'dhcpd_raw_include', 'dhcp_enabled') widgets = {'views': forms.CheckboxSelectMultiple, 'range_type': forms.RadioSelect, 'ip_type': forms.RadioSelect} exclude = 'range_usage' def __init__(self, *args, **kwargs): super(RangeForm, self).__init__(*args, **kwargs) self.fields['dhcpd_raw_include'].label = "DHCP Config Extras" self.fields['dhcpd_raw_include'].widget.attrs.update( {'cols': '80', 'style': 'display: none;width: 680px'}) RangeAVForm = get_eav_form(RangeAV, Range)
# ... existing code ... exclude = ('start_upper', 'start_lower', 'end_upper', 'end_lower') fields = ('name', 'network', 'ip_type', 'range_type', 'start_str', 'end_str', 'domain', 'is_reserved', 'allow', 'views', 'dhcpd_raw_include', 'dhcp_enabled') widgets = {'views': forms.CheckboxSelectMultiple, # ... rest of the code ...
eac78bcb95e2c34a5c2de75db785dd6532306819
ibei/main.py
ibei/main.py
import numpy as np from astropy import constants from astropy import units from sympy.mpmath import polylog def uibei(order, energy_lo, temp, chem_potential): """ Upper incomplete Bose-Einstein integral. """ kT = temp * constants.k_B reduced_energy_lo = energy_lo / kT reduced_chem_potential = chem_potential / kT prefactor = (2 * np.pi * np.math.factorial(order) * kT**(order + 1)) / \ (constants.h**3 * constants.c**2) summand = 0 for indx in range(1, order + 2): expt = (reduced_chem_potential - reduced_energy_lo).decompose() term = reduced_energy_lo**(order - indx + 1) * polylog(indx, np.exp(expt)) / np.math.factorial(order - indx + 1) summand += term return summand def bb_rad_power(temp): """ Blackbody radiant power (Stefan-Boltzmann). """ return constants.sigma_sb * temp**4
import numpy as np from astropy import constants from astropy import units from sympy.mpmath import polylog def uibei(order, energy_lo, temp, chem_potential): """ Upper incomplete Bose-Einstein integral. """ kT = temp * constants.k_B reduced_energy_lo = energy_lo / kT reduced_chem_potential = chem_potential / kT prefactor = (2 * np.pi * np.math.factorial(order) * kT**(order + 1)) / \ (constants.h**3 * constants.c**2) summand = 0 for indx in range(1, order + 2): expt = (reduced_chem_potential - reduced_energy_lo).decompose() term = reduced_energy_lo**(order - indx + 1) * polylog(indx, np.exp(expt)) / np.math.factorial(order - indx + 1) summand += term return summand def bb_rad_power(temp): """ Blackbody radiant power (Stefan-Boltzmann). """ return constants.sigma_sb * temp**4 def devos_power(bandgap, temp_sun, temp_planet, voltage): """ Power calculated according to DeVos Eq. 6.4. """ sun = uibei(2, bandgap, temp_sun, 0) solar_cell = uibei(2, bandgap, temp_sun, constants.q * voltage) return voltage * constants.e * (sun - solar_cell)
Add draft of DeVos solar cell power function
Add draft of DeVos solar cell power function
Python
mit
jrsmith3/tec,jrsmith3/ibei,jrsmith3/tec
import numpy as np from astropy import constants from astropy import units from sympy.mpmath import polylog def uibei(order, energy_lo, temp, chem_potential): """ Upper incomplete Bose-Einstein integral. """ kT = temp * constants.k_B reduced_energy_lo = energy_lo / kT reduced_chem_potential = chem_potential / kT prefactor = (2 * np.pi * np.math.factorial(order) * kT**(order + 1)) / \ (constants.h**3 * constants.c**2) summand = 0 for indx in range(1, order + 2): expt = (reduced_chem_potential - reduced_energy_lo).decompose() term = reduced_energy_lo**(order - indx + 1) * polylog(indx, np.exp(expt)) / np.math.factorial(order - indx + 1) summand += term return summand def bb_rad_power(temp): """ Blackbody radiant power (Stefan-Boltzmann). """ return constants.sigma_sb * temp**4 + + def devos_power(bandgap, temp_sun, temp_planet, voltage): + """ + Power calculated according to DeVos Eq. 6.4. + """ + sun = uibei(2, bandgap, temp_sun, 0) + solar_cell = uibei(2, bandgap, temp_sun, constants.q * voltage) + return voltage * constants.e * (sun - solar_cell) + +
Add draft of DeVos solar cell power function
## Code Before: import numpy as np from astropy import constants from astropy import units from sympy.mpmath import polylog def uibei(order, energy_lo, temp, chem_potential): """ Upper incomplete Bose-Einstein integral. """ kT = temp * constants.k_B reduced_energy_lo = energy_lo / kT reduced_chem_potential = chem_potential / kT prefactor = (2 * np.pi * np.math.factorial(order) * kT**(order + 1)) / \ (constants.h**3 * constants.c**2) summand = 0 for indx in range(1, order + 2): expt = (reduced_chem_potential - reduced_energy_lo).decompose() term = reduced_energy_lo**(order - indx + 1) * polylog(indx, np.exp(expt)) / np.math.factorial(order - indx + 1) summand += term return summand def bb_rad_power(temp): """ Blackbody radiant power (Stefan-Boltzmann). """ return constants.sigma_sb * temp**4 ## Instruction: Add draft of DeVos solar cell power function ## Code After: import numpy as np from astropy import constants from astropy import units from sympy.mpmath import polylog def uibei(order, energy_lo, temp, chem_potential): """ Upper incomplete Bose-Einstein integral. """ kT = temp * constants.k_B reduced_energy_lo = energy_lo / kT reduced_chem_potential = chem_potential / kT prefactor = (2 * np.pi * np.math.factorial(order) * kT**(order + 1)) / \ (constants.h**3 * constants.c**2) summand = 0 for indx in range(1, order + 2): expt = (reduced_chem_potential - reduced_energy_lo).decompose() term = reduced_energy_lo**(order - indx + 1) * polylog(indx, np.exp(expt)) / np.math.factorial(order - indx + 1) summand += term return summand def bb_rad_power(temp): """ Blackbody radiant power (Stefan-Boltzmann). """ return constants.sigma_sb * temp**4 def devos_power(bandgap, temp_sun, temp_planet, voltage): """ Power calculated according to DeVos Eq. 6.4. """ sun = uibei(2, bandgap, temp_sun, 0) solar_cell = uibei(2, bandgap, temp_sun, constants.q * voltage) return voltage * constants.e * (sun - solar_cell)
... return constants.sigma_sb * temp**4 def devos_power(bandgap, temp_sun, temp_planet, voltage): """ Power calculated according to DeVos Eq. 6.4. """ sun = uibei(2, bandgap, temp_sun, 0) solar_cell = uibei(2, bandgap, temp_sun, constants.q * voltage) return voltage * constants.e * (sun - solar_cell) ...
1ba4d84fb72a343cdf288d905d2029f1d2fbee12
wagtail/api/v2/pagination.py
wagtail/api/v2/pagination.py
from collections import OrderedDict from django.conf import settings from rest_framework.pagination import BasePagination from rest_framework.response import Response from .utils import BadRequestError class WagtailPagination(BasePagination): def paginate_queryset(self, queryset, request, view=None): limit_max = getattr(settings, 'WAGTAILAPI_LIMIT_MAX', 20) try: offset = int(request.GET.get('offset', 0)) assert offset >= 0 except (ValueError, AssertionError): raise BadRequestError("offset must be a positive integer") try: limit_default = 20 if not limit_max else min(20, limit_max) limit = int(request.GET.get('limit', limit_default)) if limit_max and limit > limit_max: raise BadRequestError("limit cannot be higher than %d" % limit_max) assert limit >= 0 except (ValueError, AssertionError): raise BadRequestError("limit must be a positive integer") start = offset stop = offset + limit self.view = view self.total_count = queryset.count() return queryset[start:stop] def get_paginated_response(self, data): data = OrderedDict([ ('meta', OrderedDict([ ('total_count', self.total_count), ])), ('items', data), ]) return Response(data)
from collections import OrderedDict from django.conf import settings from rest_framework.pagination import BasePagination from rest_framework.response import Response from .utils import BadRequestError class WagtailPagination(BasePagination): def paginate_queryset(self, queryset, request, view=None): limit_max = getattr(settings, 'WAGTAILAPI_LIMIT_MAX', 20) try: offset = int(request.GET.get('offset', 0)) if offset < 0: raise ValueError() except ValueError: raise BadRequestError("offset must be a positive integer") try: limit_default = 20 if not limit_max else min(20, limit_max) limit = int(request.GET.get('limit', limit_default)) if limit < 0: raise ValueError() except ValueError: raise BadRequestError("limit must be a positive integer") if limit_max and limit > limit_max: raise BadRequestError( "limit cannot be higher than %d" % limit_max) start = offset stop = offset + limit self.view = view self.total_count = queryset.count() return queryset[start:stop] def get_paginated_response(self, data): data = OrderedDict([ ('meta', OrderedDict([ ('total_count', self.total_count), ])), ('items', data), ]) return Response(data)
Remove assert from WagtailPagination.paginate_queryset method
Remove assert from WagtailPagination.paginate_queryset method
Python
bsd-3-clause
mikedingjan/wagtail,rsalmaso/wagtail,rsalmaso/wagtail,jnns/wagtail,mixxorz/wagtail,wagtail/wagtail,mixxorz/wagtail,FlipperPA/wagtail,wagtail/wagtail,gasman/wagtail,zerolab/wagtail,torchbox/wagtail,mikedingjan/wagtail,timorieber/wagtail,zerolab/wagtail,gasman/wagtail,jnns/wagtail,zerolab/wagtail,kaedroho/wagtail,thenewguy/wagtail,FlipperPA/wagtail,nimasmi/wagtail,thenewguy/wagtail,mixxorz/wagtail,torchbox/wagtail,mikedingjan/wagtail,mixxorz/wagtail,rsalmaso/wagtail,kaedroho/wagtail,nealtodd/wagtail,takeflight/wagtail,mixxorz/wagtail,nimasmi/wagtail,torchbox/wagtail,kaedroho/wagtail,jnns/wagtail,mikedingjan/wagtail,timorieber/wagtail,nealtodd/wagtail,wagtail/wagtail,nealtodd/wagtail,thenewguy/wagtail,thenewguy/wagtail,thenewguy/wagtail,FlipperPA/wagtail,takeflight/wagtail,gasman/wagtail,zerolab/wagtail,torchbox/wagtail,takeflight/wagtail,nimasmi/wagtail,FlipperPA/wagtail,wagtail/wagtail,zerolab/wagtail,jnns/wagtail,rsalmaso/wagtail,nimasmi/wagtail,timorieber/wagtail,takeflight/wagtail,gasman/wagtail,kaedroho/wagtail,rsalmaso/wagtail,gasman/wagtail,timorieber/wagtail,wagtail/wagtail,kaedroho/wagtail,nealtodd/wagtail
from collections import OrderedDict from django.conf import settings from rest_framework.pagination import BasePagination from rest_framework.response import Response from .utils import BadRequestError class WagtailPagination(BasePagination): def paginate_queryset(self, queryset, request, view=None): limit_max = getattr(settings, 'WAGTAILAPI_LIMIT_MAX', 20) try: offset = int(request.GET.get('offset', 0)) - assert offset >= 0 + if offset < 0: - except (ValueError, AssertionError): + raise ValueError() + except ValueError: raise BadRequestError("offset must be a positive integer") try: limit_default = 20 if not limit_max else min(20, limit_max) limit = int(request.GET.get('limit', limit_default)) + if limit < 0: + raise ValueError() + except ValueError: + raise BadRequestError("limit must be a positive integer") - if limit_max and limit > limit_max: + if limit_max and limit > limit_max: + raise BadRequestError( - raise BadRequestError("limit cannot be higher than %d" % limit_max) + "limit cannot be higher than %d" % limit_max) - - assert limit >= 0 - except (ValueError, AssertionError): - raise BadRequestError("limit must be a positive integer") start = offset stop = offset + limit self.view = view self.total_count = queryset.count() return queryset[start:stop] def get_paginated_response(self, data): data = OrderedDict([ ('meta', OrderedDict([ ('total_count', self.total_count), ])), ('items', data), ]) return Response(data)
Remove assert from WagtailPagination.paginate_queryset method
## Code Before: from collections import OrderedDict from django.conf import settings from rest_framework.pagination import BasePagination from rest_framework.response import Response from .utils import BadRequestError class WagtailPagination(BasePagination): def paginate_queryset(self, queryset, request, view=None): limit_max = getattr(settings, 'WAGTAILAPI_LIMIT_MAX', 20) try: offset = int(request.GET.get('offset', 0)) assert offset >= 0 except (ValueError, AssertionError): raise BadRequestError("offset must be a positive integer") try: limit_default = 20 if not limit_max else min(20, limit_max) limit = int(request.GET.get('limit', limit_default)) if limit_max and limit > limit_max: raise BadRequestError("limit cannot be higher than %d" % limit_max) assert limit >= 0 except (ValueError, AssertionError): raise BadRequestError("limit must be a positive integer") start = offset stop = offset + limit self.view = view self.total_count = queryset.count() return queryset[start:stop] def get_paginated_response(self, data): data = OrderedDict([ ('meta', OrderedDict([ ('total_count', self.total_count), ])), ('items', data), ]) return Response(data) ## Instruction: Remove assert from WagtailPagination.paginate_queryset method ## Code After: from collections import OrderedDict from django.conf import settings from rest_framework.pagination import BasePagination from rest_framework.response import Response from .utils import BadRequestError class WagtailPagination(BasePagination): def paginate_queryset(self, queryset, request, view=None): limit_max = getattr(settings, 'WAGTAILAPI_LIMIT_MAX', 20) try: offset = int(request.GET.get('offset', 0)) if offset < 0: raise ValueError() except ValueError: raise BadRequestError("offset must be a positive integer") try: limit_default = 20 if not limit_max else min(20, limit_max) limit = int(request.GET.get('limit', limit_default)) if limit < 0: raise ValueError() except ValueError: raise BadRequestError("limit must be a positive integer") if limit_max and limit > limit_max: raise BadRequestError( "limit cannot be higher than %d" % limit_max) start = offset stop = offset + limit self.view = view self.total_count = queryset.count() return queryset[start:stop] def get_paginated_response(self, data): data = OrderedDict([ ('meta', OrderedDict([ ('total_count', self.total_count), ])), ('items', data), ]) return Response(data)
... offset = int(request.GET.get('offset', 0)) if offset < 0: raise ValueError() except ValueError: raise BadRequestError("offset must be a positive integer") ... limit = int(request.GET.get('limit', limit_default)) if limit < 0: raise ValueError() except ValueError: raise BadRequestError("limit must be a positive integer") if limit_max and limit > limit_max: raise BadRequestError( "limit cannot be higher than %d" % limit_max) ...
b89f6981d4f55790aa919f36e02a6312bd5f1583
tests/__init__.py
tests/__init__.py
import unittest import sys from six import PY3 if PY3: from urllib.parse import urlsplit, parse_qsl else: from urlparse import urlsplit, parse_qsl import werkzeug as wz from flask import Flask, url_for, render_template_string from flask.ext.images import Images, ImageSize, resized_img_src import flask flask_version = tuple(map(int, flask.__version__.split('.'))) class TestCase(unittest.TestCase): def setUp(self): self.app = self.create_app() self.app_ctx = self.app.app_context() self.app_ctx.push() self.req_ctx = self.app.test_request_context('http://localhost:8000/') self.req_ctx.push() self.client = self.app.test_client() def create_app(self): app = Flask(__name__) app.config['TESTING'] = True app.config['SERVER_NAME'] = 'localhost' app.config['SECRET_KEY'] = 'secret secret' app.config['IMAGES_PATH'] = ['assets'] self.images = Images(app) return app def assert200(self, res): self.assertEqual(res.status_code, 200)
import unittest import sys from six import PY3 if PY3: from urllib.parse import urlsplit, parse_qsl else: from urlparse import urlsplit, parse_qsl import werkzeug as wz from flask import Flask, url_for, render_template_string import flask from flask_images import Images, ImageSize, resized_img_src flask_version = tuple(map(int, flask.__version__.split('.'))) class TestCase(unittest.TestCase): def setUp(self): self.app = self.create_app() self.app_ctx = self.app.app_context() self.app_ctx.push() self.req_ctx = self.app.test_request_context('http://localhost:8000/') self.req_ctx.push() self.client = self.app.test_client() def create_app(self): app = Flask(__name__) app.config['TESTING'] = True app.config['SERVER_NAME'] = 'localhost' app.config['SECRET_KEY'] = 'secret secret' app.config['IMAGES_PATH'] = ['assets'] self.images = Images(app) return app def assert200(self, res): self.assertEqual(res.status_code, 200)
Stop using `flask.ext.*` in tests.
Stop using `flask.ext.*` in tests.
Python
bsd-3-clause
mikeboers/Flask-Images
import unittest import sys from six import PY3 if PY3: from urllib.parse import urlsplit, parse_qsl else: from urlparse import urlsplit, parse_qsl import werkzeug as wz from flask import Flask, url_for, render_template_string - from flask.ext.images import Images, ImageSize, resized_img_src import flask + + from flask_images import Images, ImageSize, resized_img_src + flask_version = tuple(map(int, flask.__version__.split('.'))) class TestCase(unittest.TestCase): def setUp(self): self.app = self.create_app() self.app_ctx = self.app.app_context() self.app_ctx.push() self.req_ctx = self.app.test_request_context('http://localhost:8000/') self.req_ctx.push() self.client = self.app.test_client() def create_app(self): app = Flask(__name__) app.config['TESTING'] = True app.config['SERVER_NAME'] = 'localhost' app.config['SECRET_KEY'] = 'secret secret' app.config['IMAGES_PATH'] = ['assets'] self.images = Images(app) return app def assert200(self, res): self.assertEqual(res.status_code, 200)
Stop using `flask.ext.*` in tests.
## Code Before: import unittest import sys from six import PY3 if PY3: from urllib.parse import urlsplit, parse_qsl else: from urlparse import urlsplit, parse_qsl import werkzeug as wz from flask import Flask, url_for, render_template_string from flask.ext.images import Images, ImageSize, resized_img_src import flask flask_version = tuple(map(int, flask.__version__.split('.'))) class TestCase(unittest.TestCase): def setUp(self): self.app = self.create_app() self.app_ctx = self.app.app_context() self.app_ctx.push() self.req_ctx = self.app.test_request_context('http://localhost:8000/') self.req_ctx.push() self.client = self.app.test_client() def create_app(self): app = Flask(__name__) app.config['TESTING'] = True app.config['SERVER_NAME'] = 'localhost' app.config['SECRET_KEY'] = 'secret secret' app.config['IMAGES_PATH'] = ['assets'] self.images = Images(app) return app def assert200(self, res): self.assertEqual(res.status_code, 200) ## Instruction: Stop using `flask.ext.*` in tests. ## Code After: import unittest import sys from six import PY3 if PY3: from urllib.parse import urlsplit, parse_qsl else: from urlparse import urlsplit, parse_qsl import werkzeug as wz from flask import Flask, url_for, render_template_string import flask from flask_images import Images, ImageSize, resized_img_src flask_version = tuple(map(int, flask.__version__.split('.'))) class TestCase(unittest.TestCase): def setUp(self): self.app = self.create_app() self.app_ctx = self.app.app_context() self.app_ctx.push() self.req_ctx = self.app.test_request_context('http://localhost:8000/') self.req_ctx.push() self.client = self.app.test_client() def create_app(self): app = Flask(__name__) app.config['TESTING'] = True app.config['SERVER_NAME'] = 'localhost' app.config['SECRET_KEY'] = 'secret secret' app.config['IMAGES_PATH'] = ['assets'] self.images = Images(app) return app def assert200(self, res): self.assertEqual(res.status_code, 200)
... from flask import Flask, url_for, render_template_string import flask from flask_images import Images, ImageSize, resized_img_src ...
8fa346532068aadf510ebcc1ef795527f7b68597
frigg_worker/api.py
frigg_worker/api.py
import logging import socket import requests logger = logging.getLogger(__name__) class APIWrapper(object): def __init__(self, options): self.token = options['hq_token'] self.url = options['hq_url'] @property def headers(self): return { 'content-type': 'application/json', 'FRIGG_WORKER_TOKEN': self.token, 'x-frigg-worker-host': socket.getfqdn() } def get(self, url): return requests.post(url, headers=self.headers) def post(self, url, data): return requests.post(url, data=data, headers=self.headers) def report_run(self, endpoint, build_id, build): response = self.post(self.url, data=build) logger.info('Reported build to hq, hq response status-code: {0}, data:\n{1}'.format( response.status_code, build )) if response.status_code != 200: logger.error('Report of build failed, response status-code: {0}, data:\n{1}'.format( response.status_code, build )) with open('build-{0}-hq-response.html'.format(build_id), 'w') as f: f.write(response.text) return response
import logging import socket import requests logger = logging.getLogger(__name__) class APIWrapper(object): def __init__(self, options): self.token = options['hq_token'] self.url = options['hq_url'] @property def headers(self): return { 'content-type': 'application/json', 'FRIGG_WORKER_TOKEN': self.token, 'x-frigg-worker-token': self.token, 'x-frigg-worker-host': socket.getfqdn() } def get(self, url): return requests.post(url, headers=self.headers) def post(self, url, data): return requests.post(url, data=data, headers=self.headers) def report_run(self, endpoint, build_id, build): response = self.post(self.url, data=build) logger.info('Reported build to hq, hq response status-code: {0}, data:\n{1}'.format( response.status_code, build )) if response.status_code != 200: logger.error('Report of build failed, response status-code: {0}, data:\n{1}'.format( response.status_code, build )) with open('build-{0}-hq-response.html'.format(build_id), 'w') as f: f.write(response.text) return response
Add x-frigg-worker-token header to hq requests
fix: Add x-frigg-worker-token header to hq requests This will in time be to remove the FRIGG_WORKER_TOKEN header.
Python
mit
frigg/frigg-worker
import logging import socket import requests logger = logging.getLogger(__name__) class APIWrapper(object): def __init__(self, options): self.token = options['hq_token'] self.url = options['hq_url'] @property def headers(self): return { 'content-type': 'application/json', 'FRIGG_WORKER_TOKEN': self.token, + 'x-frigg-worker-token': self.token, 'x-frigg-worker-host': socket.getfqdn() } def get(self, url): return requests.post(url, headers=self.headers) def post(self, url, data): return requests.post(url, data=data, headers=self.headers) def report_run(self, endpoint, build_id, build): response = self.post(self.url, data=build) logger.info('Reported build to hq, hq response status-code: {0}, data:\n{1}'.format( response.status_code, build )) if response.status_code != 200: logger.error('Report of build failed, response status-code: {0}, data:\n{1}'.format( response.status_code, build )) with open('build-{0}-hq-response.html'.format(build_id), 'w') as f: f.write(response.text) return response
Add x-frigg-worker-token header to hq requests
## Code Before: import logging import socket import requests logger = logging.getLogger(__name__) class APIWrapper(object): def __init__(self, options): self.token = options['hq_token'] self.url = options['hq_url'] @property def headers(self): return { 'content-type': 'application/json', 'FRIGG_WORKER_TOKEN': self.token, 'x-frigg-worker-host': socket.getfqdn() } def get(self, url): return requests.post(url, headers=self.headers) def post(self, url, data): return requests.post(url, data=data, headers=self.headers) def report_run(self, endpoint, build_id, build): response = self.post(self.url, data=build) logger.info('Reported build to hq, hq response status-code: {0}, data:\n{1}'.format( response.status_code, build )) if response.status_code != 200: logger.error('Report of build failed, response status-code: {0}, data:\n{1}'.format( response.status_code, build )) with open('build-{0}-hq-response.html'.format(build_id), 'w') as f: f.write(response.text) return response ## Instruction: Add x-frigg-worker-token header to hq requests ## Code After: import logging import socket import requests logger = logging.getLogger(__name__) class APIWrapper(object): def __init__(self, options): self.token = options['hq_token'] self.url = options['hq_url'] @property def headers(self): return { 'content-type': 'application/json', 'FRIGG_WORKER_TOKEN': self.token, 'x-frigg-worker-token': self.token, 'x-frigg-worker-host': socket.getfqdn() } def get(self, url): return requests.post(url, headers=self.headers) def post(self, url, data): return requests.post(url, data=data, headers=self.headers) def report_run(self, endpoint, build_id, build): response = self.post(self.url, data=build) logger.info('Reported build to hq, hq response status-code: {0}, data:\n{1}'.format( response.status_code, build )) if response.status_code != 200: logger.error('Report of build failed, response status-code: {0}, data:\n{1}'.format( response.status_code, build )) with open('build-{0}-hq-response.html'.format(build_id), 'w') as f: f.write(response.text) return response
... 'FRIGG_WORKER_TOKEN': self.token, 'x-frigg-worker-token': self.token, 'x-frigg-worker-host': socket.getfqdn() ...
1e010e940390ae5b650224363e4acecd816b2611
settings_dev.py
settings_dev.py
import sublime_plugin from .sublime_lib.path import root_at_packages, get_package_name PLUGIN_NAME = get_package_name() SETTINGS_SYNTAX = ("Packages/%s/Package/Sublime Text Settings/Sublime Settings.tmLanguage" % PLUGIN_NAME) TPL = "{\n\t$0\n}" class NewSettingsCommand(sublime_plugin.WindowCommand): def run(self): v = self.window.new_file() v.settings().set('default_dir', root_at_packages('User')) v.set_syntax_file(SETTINGS_SYNTAX) v.run_command('insert_snippet', {'contents': TPL})
import sublime_plugin from .sublime_lib.path import root_at_packages, get_package_name PLUGIN_NAME = get_package_name() SETTINGS_SYNTAX = ("Packages/%s/Package/Sublime Text Settings/Sublime Text Settings.sublime-syntax" % PLUGIN_NAME) TPL = '''\ { "$1": $0 }'''.replace(" " * 4, "\t") class NewSettingsCommand(sublime_plugin.WindowCommand): def run(self): v = self.window.new_file() v.settings().set('default_dir', root_at_packages('User')) v.set_syntax_file(SETTINGS_SYNTAX) v.run_command('insert_snippet', {'contents': TPL})
Update syntax path for new settings file command
Update syntax path for new settings file command
Python
mit
SublimeText/AAAPackageDev,SublimeText/AAAPackageDev,SublimeText/PackageDev
import sublime_plugin from .sublime_lib.path import root_at_packages, get_package_name PLUGIN_NAME = get_package_name() - SETTINGS_SYNTAX = ("Packages/%s/Package/Sublime Text Settings/Sublime Settings.tmLanguage" + SETTINGS_SYNTAX = ("Packages/%s/Package/Sublime Text Settings/Sublime Text Settings.sublime-syntax" % PLUGIN_NAME) - TPL = "{\n\t$0\n}" + TPL = '''\ + { + "$1": $0 + }'''.replace(" " * 4, "\t") class NewSettingsCommand(sublime_plugin.WindowCommand): def run(self): v = self.window.new_file() v.settings().set('default_dir', root_at_packages('User')) v.set_syntax_file(SETTINGS_SYNTAX) v.run_command('insert_snippet', {'contents': TPL})
Update syntax path for new settings file command
## Code Before: import sublime_plugin from .sublime_lib.path import root_at_packages, get_package_name PLUGIN_NAME = get_package_name() SETTINGS_SYNTAX = ("Packages/%s/Package/Sublime Text Settings/Sublime Settings.tmLanguage" % PLUGIN_NAME) TPL = "{\n\t$0\n}" class NewSettingsCommand(sublime_plugin.WindowCommand): def run(self): v = self.window.new_file() v.settings().set('default_dir', root_at_packages('User')) v.set_syntax_file(SETTINGS_SYNTAX) v.run_command('insert_snippet', {'contents': TPL}) ## Instruction: Update syntax path for new settings file command ## Code After: import sublime_plugin from .sublime_lib.path import root_at_packages, get_package_name PLUGIN_NAME = get_package_name() SETTINGS_SYNTAX = ("Packages/%s/Package/Sublime Text Settings/Sublime Text Settings.sublime-syntax" % PLUGIN_NAME) TPL = '''\ { "$1": $0 }'''.replace(" " * 4, "\t") class NewSettingsCommand(sublime_plugin.WindowCommand): def run(self): v = self.window.new_file() v.settings().set('default_dir', root_at_packages('User')) v.set_syntax_file(SETTINGS_SYNTAX) v.run_command('insert_snippet', {'contents': TPL})
# ... existing code ... SETTINGS_SYNTAX = ("Packages/%s/Package/Sublime Text Settings/Sublime Text Settings.sublime-syntax" % PLUGIN_NAME) TPL = '''\ { "$1": $0 }'''.replace(" " * 4, "\t") # ... rest of the code ...
8ccffcf02cd5ba8352bc8182d7be13ea015332ca
plinth/utils.py
plinth/utils.py
import importlib def import_from_gi(library, version): """Import and return a GObject introspection library.""" try: import gi as package package_name = 'gi' except ImportError: import pgi as package package_name = 'pgi' package.require_version(library, version) return importlib.import_module(package_name + '.repository.' + library)
import importlib from django.utils.functional import lazy def import_from_gi(library, version): """Import and return a GObject introspection library.""" try: import gi as package package_name = 'gi' except ImportError: import pgi as package package_name = 'pgi' package.require_version(library, version) return importlib.import_module(package_name + '.repository.' + library) def _format_lazy(string, *args, **kwargs): """Lazily format a lazy string.""" string = str(string) return string.format(*args, **kwargs) format_lazy = lazy(_format_lazy, str)
Add utility method to lazy format lazy string
Add utility method to lazy format lazy string This method is useful to format strings that are lazy (such as those in Forms).
Python
agpl-3.0
freedomboxtwh/Plinth,harry-7/Plinth,kkampardi/Plinth,vignanl/Plinth,vignanl/Plinth,freedomboxtwh/Plinth,kkampardi/Plinth,harry-7/Plinth,harry-7/Plinth,freedomboxtwh/Plinth,vignanl/Plinth,freedomboxtwh/Plinth,kkampardi/Plinth,kkampardi/Plinth,freedomboxtwh/Plinth,vignanl/Plinth,harry-7/Plinth,harry-7/Plinth,kkampardi/Plinth,vignanl/Plinth
import importlib + from django.utils.functional import lazy def import_from_gi(library, version): """Import and return a GObject introspection library.""" try: import gi as package package_name = 'gi' except ImportError: import pgi as package package_name = 'pgi' package.require_version(library, version) return importlib.import_module(package_name + '.repository.' + library) + + def _format_lazy(string, *args, **kwargs): + """Lazily format a lazy string.""" + string = str(string) + return string.format(*args, **kwargs) + + + format_lazy = lazy(_format_lazy, str) +
Add utility method to lazy format lazy string
## Code Before: import importlib def import_from_gi(library, version): """Import and return a GObject introspection library.""" try: import gi as package package_name = 'gi' except ImportError: import pgi as package package_name = 'pgi' package.require_version(library, version) return importlib.import_module(package_name + '.repository.' + library) ## Instruction: Add utility method to lazy format lazy string ## Code After: import importlib from django.utils.functional import lazy def import_from_gi(library, version): """Import and return a GObject introspection library.""" try: import gi as package package_name = 'gi' except ImportError: import pgi as package package_name = 'pgi' package.require_version(library, version) return importlib.import_module(package_name + '.repository.' + library) def _format_lazy(string, *args, **kwargs): """Lazily format a lazy string.""" string = str(string) return string.format(*args, **kwargs) format_lazy = lazy(_format_lazy, str)
... import importlib from django.utils.functional import lazy ... return importlib.import_module(package_name + '.repository.' + library) def _format_lazy(string, *args, **kwargs): """Lazily format a lazy string.""" string = str(string) return string.format(*args, **kwargs) format_lazy = lazy(_format_lazy, str) ...
0a5e2134fda46269626b6fac367a28218734b256
conf_site/accounts/tests/__init__.py
conf_site/accounts/tests/__init__.py
from factory import fuzzy from django.contrib.auth import get_user_model from django.test import TestCase class AccountsTestCase(TestCase): def setUp(self): super(AccountsTestCase, self).setUp() self.password = fuzzy.FuzzyText(length=16) self.new_password = fuzzy.FuzzyText(length=16) user_model = get_user_model() self.user = user_model.objects.get_or_create( username="test", email="[email protected]", first_name="Test", last_name="User", )[0] self.user.set_password(self.password) self.user.save() def _become_superuser(self): """Make this testcase's user a superuser.""" self.user.is_superuser = True self.user.save()
from factory import fuzzy from django.contrib.auth import get_user_model from django.test import TestCase class AccountsTestCase(TestCase): def setUp(self): super(AccountsTestCase, self).setUp() self.password = fuzzy.FuzzyText(length=16) self.new_password = fuzzy.FuzzyText(length=16) user_model = get_user_model() self.user = user_model.objects.get_or_create( username="test", email="[email protected]", first_name="Test", last_name="User", )[0] self.user.set_password(self.password) self.user.save() def _become_staff(self): """Make this testcase's user a staff user.""" self.user.is_staff = True self.user.is_superuser = False self.user.save() def _become_superuser(self): """Make this testcase's user a superuser.""" self.user.is_superuser = True self.user.save()
Add `_become_staff` method to AccountsTestCase.
Add `_become_staff` method to AccountsTestCase.
Python
mit
pydata/conf_site,pydata/conf_site,pydata/conf_site
from factory import fuzzy from django.contrib.auth import get_user_model from django.test import TestCase class AccountsTestCase(TestCase): def setUp(self): super(AccountsTestCase, self).setUp() self.password = fuzzy.FuzzyText(length=16) self.new_password = fuzzy.FuzzyText(length=16) user_model = get_user_model() self.user = user_model.objects.get_or_create( username="test", email="[email protected]", first_name="Test", last_name="User", )[0] self.user.set_password(self.password) self.user.save() + def _become_staff(self): + """Make this testcase's user a staff user.""" + self.user.is_staff = True + self.user.is_superuser = False + self.user.save() + def _become_superuser(self): """Make this testcase's user a superuser.""" self.user.is_superuser = True self.user.save()
Add `_become_staff` method to AccountsTestCase.
## Code Before: from factory import fuzzy from django.contrib.auth import get_user_model from django.test import TestCase class AccountsTestCase(TestCase): def setUp(self): super(AccountsTestCase, self).setUp() self.password = fuzzy.FuzzyText(length=16) self.new_password = fuzzy.FuzzyText(length=16) user_model = get_user_model() self.user = user_model.objects.get_or_create( username="test", email="[email protected]", first_name="Test", last_name="User", )[0] self.user.set_password(self.password) self.user.save() def _become_superuser(self): """Make this testcase's user a superuser.""" self.user.is_superuser = True self.user.save() ## Instruction: Add `_become_staff` method to AccountsTestCase. ## Code After: from factory import fuzzy from django.contrib.auth import get_user_model from django.test import TestCase class AccountsTestCase(TestCase): def setUp(self): super(AccountsTestCase, self).setUp() self.password = fuzzy.FuzzyText(length=16) self.new_password = fuzzy.FuzzyText(length=16) user_model = get_user_model() self.user = user_model.objects.get_or_create( username="test", email="[email protected]", first_name="Test", last_name="User", )[0] self.user.set_password(self.password) self.user.save() def _become_staff(self): """Make this testcase's user a staff user.""" self.user.is_staff = True self.user.is_superuser = False self.user.save() def _become_superuser(self): """Make this testcase's user a superuser.""" self.user.is_superuser = True self.user.save()
// ... existing code ... def _become_staff(self): """Make this testcase's user a staff user.""" self.user.is_staff = True self.user.is_superuser = False self.user.save() def _become_superuser(self): // ... rest of the code ...
ea7177614dc2094e95aeea33f6249f14c792fee8
Discord/modules/ciphers.py
Discord/modules/ciphers.py
def encode_caesar(message, key): encoded_message = "" for character in message: if not ('a' <= character <= 'z' or 'A' <= character <= 'Z'): # .isalpha() ? encoded_message += character continue shifted = ord(character) + int(key) if character.islower() and shifted > ord('z') or character.isupper() and shifted > ord('Z'): encoded_message += chr(shifted - 26) else: encoded_message += chr(shifted) return encoded_message def decode_caesar(message, key): decoded_message = "" for character in message: if not ('a' <= character <= 'z' or 'A' <= character <= 'Z'): # .isalpha() ? decoded_message += character continue shifted = ord(character) - int(key) if character.islower() and shifted < ord('a') or character.isupper() and shifted < ord('A'): decoded_message += chr(shifted + 26) else: decoded_message += chr(shifted) return decoded_message def brute_force_caesar(message): decodes = "" for key in range(26): decodes += str(key) + ": " + decode_caesar(message, key) + '\n' return decodes
def encode_caesar(message, key): encoded_message = "" for character in message: if not character.isalpha() or not character.isascii(): encoded_message += character continue shifted = ord(character) + int(key) if character.islower() and shifted > ord('z') or character.isupper() and shifted > ord('Z'): encoded_message += chr(shifted - 26) else: encoded_message += chr(shifted) return encoded_message def decode_caesar(message, key): decoded_message = "" for character in message: if not character.isalpha() or not character.isascii(): decoded_message += character continue shifted = ord(character) - int(key) if character.islower() and shifted < ord('a') or character.isupper() and shifted < ord('A'): decoded_message += chr(shifted + 26) else: decoded_message += chr(shifted) return decoded_message def brute_force_caesar(message): decodes = "" for key in range(26): decodes += str(key) + ": " + decode_caesar(message, key) + '\n' return decodes
Use string methods for encode and decode caesar functions
[Discord] Use string methods for encode and decode caesar functions To determine (in)valid characters to encode and decode
Python
mit
Harmon758/Harmonbot,Harmon758/Harmonbot
def encode_caesar(message, key): encoded_message = "" for character in message: - if not ('a' <= character <= 'z' or 'A' <= character <= 'Z'): # .isalpha() ? + if not character.isalpha() or not character.isascii(): encoded_message += character continue shifted = ord(character) + int(key) if character.islower() and shifted > ord('z') or character.isupper() and shifted > ord('Z'): encoded_message += chr(shifted - 26) else: encoded_message += chr(shifted) return encoded_message def decode_caesar(message, key): decoded_message = "" for character in message: - if not ('a' <= character <= 'z' or 'A' <= character <= 'Z'): # .isalpha() ? + if not character.isalpha() or not character.isascii(): decoded_message += character continue shifted = ord(character) - int(key) if character.islower() and shifted < ord('a') or character.isupper() and shifted < ord('A'): decoded_message += chr(shifted + 26) else: decoded_message += chr(shifted) return decoded_message def brute_force_caesar(message): decodes = "" for key in range(26): decodes += str(key) + ": " + decode_caesar(message, key) + '\n' return decodes
Use string methods for encode and decode caesar functions
## Code Before: def encode_caesar(message, key): encoded_message = "" for character in message: if not ('a' <= character <= 'z' or 'A' <= character <= 'Z'): # .isalpha() ? encoded_message += character continue shifted = ord(character) + int(key) if character.islower() and shifted > ord('z') or character.isupper() and shifted > ord('Z'): encoded_message += chr(shifted - 26) else: encoded_message += chr(shifted) return encoded_message def decode_caesar(message, key): decoded_message = "" for character in message: if not ('a' <= character <= 'z' or 'A' <= character <= 'Z'): # .isalpha() ? decoded_message += character continue shifted = ord(character) - int(key) if character.islower() and shifted < ord('a') or character.isupper() and shifted < ord('A'): decoded_message += chr(shifted + 26) else: decoded_message += chr(shifted) return decoded_message def brute_force_caesar(message): decodes = "" for key in range(26): decodes += str(key) + ": " + decode_caesar(message, key) + '\n' return decodes ## Instruction: Use string methods for encode and decode caesar functions ## Code After: def encode_caesar(message, key): encoded_message = "" for character in message: if not character.isalpha() or not character.isascii(): encoded_message += character continue shifted = ord(character) + int(key) if character.islower() and shifted > ord('z') or character.isupper() and shifted > ord('Z'): encoded_message += chr(shifted - 26) else: encoded_message += chr(shifted) return encoded_message def decode_caesar(message, key): decoded_message = "" for character in message: if not character.isalpha() or not character.isascii(): decoded_message += character continue shifted = ord(character) - int(key) if character.islower() and shifted < ord('a') or character.isupper() and shifted < ord('A'): decoded_message += chr(shifted + 26) else: decoded_message += chr(shifted) return decoded_message def brute_force_caesar(message): decodes = "" for key in range(26): decodes += str(key) + ": " + decode_caesar(message, key) + '\n' return decodes
... for character in message: if not character.isalpha() or not character.isascii(): encoded_message += character ... for character in message: if not character.isalpha() or not character.isascii(): decoded_message += character ...
cc0c43c3131161902de3a8a68688766cacd637b9
lowercasing_test/src/tests/lowercasing/fetchletters.py
lowercasing_test/src/tests/lowercasing/fetchletters.py
import sys def add_character(unicodespec, characterstore): characterstora def main(raw, out): # Fetch upper and lower case characters in Unicode characters = filter(lambda x: x[2] == 'Lu' or x[2] == 'Ll', raw) image = [unichr(int(c[0], 16)) for c in characters] output = u"\n".join(image) out.write(output.encode("UTF-8")) out.write(u"\n".encode("UTF-8")) if __name__ == '__main__': try: raw = [x.split(";") for x in open("./UnicodeData.txt", "r").readlines()] except: sys.stderr.write("Problems reading ./UnicodeData.txt.\n") sys.exit(1) main(raw, sys.stdout)
import sys def add_character(unicodespec, characterstore): characterstora def main(raw, out): # Fetch upper and lower case characters in Unicode characters = [x for x in raw if x[2] == 'Lu' or x[2] == 'Ll'] image = [chr(int(c[0], 16)) for c in characters] output = "\n".join(image) out.write(output.encode("UTF-8")) out.write(u"\n".encode("UTF-8")) if __name__ == '__main__': try: raw = [x.split(";") for x in open("./UnicodeData.txt", "r").readlines()] except: sys.stderr.write("Problems reading ./UnicodeData.txt.\n") sys.exit(1) main(raw, sys.stdout)
Migrate script ot Python 3
Migrate script ot Python 3
Python
apache-2.0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
import sys def add_character(unicodespec, characterstore): characterstora def main(raw, out): # Fetch upper and lower case characters in Unicode - characters = filter(lambda x: x[2] == 'Lu' or x[2] == 'Ll', raw) + characters = [x for x in raw if x[2] == 'Lu' or x[2] == 'Ll'] - image = [unichr(int(c[0], 16)) for c in characters] + image = [chr(int(c[0], 16)) for c in characters] - output = u"\n".join(image) + output = "\n".join(image) out.write(output.encode("UTF-8")) out.write(u"\n".encode("UTF-8")) if __name__ == '__main__': try: raw = [x.split(";") for x in open("./UnicodeData.txt", "r").readlines()] except: sys.stderr.write("Problems reading ./UnicodeData.txt.\n") sys.exit(1) main(raw, sys.stdout)
Migrate script ot Python 3
## Code Before: import sys def add_character(unicodespec, characterstore): characterstora def main(raw, out): # Fetch upper and lower case characters in Unicode characters = filter(lambda x: x[2] == 'Lu' or x[2] == 'Ll', raw) image = [unichr(int(c[0], 16)) for c in characters] output = u"\n".join(image) out.write(output.encode("UTF-8")) out.write(u"\n".encode("UTF-8")) if __name__ == '__main__': try: raw = [x.split(";") for x in open("./UnicodeData.txt", "r").readlines()] except: sys.stderr.write("Problems reading ./UnicodeData.txt.\n") sys.exit(1) main(raw, sys.stdout) ## Instruction: Migrate script ot Python 3 ## Code After: import sys def add_character(unicodespec, characterstore): characterstora def main(raw, out): # Fetch upper and lower case characters in Unicode characters = [x for x in raw if x[2] == 'Lu' or x[2] == 'Ll'] image = [chr(int(c[0], 16)) for c in characters] output = "\n".join(image) out.write(output.encode("UTF-8")) out.write(u"\n".encode("UTF-8")) if __name__ == '__main__': try: raw = [x.split(";") for x in open("./UnicodeData.txt", "r").readlines()] except: sys.stderr.write("Problems reading ./UnicodeData.txt.\n") sys.exit(1) main(raw, sys.stdout)
// ... existing code ... # Fetch upper and lower case characters in Unicode characters = [x for x in raw if x[2] == 'Lu' or x[2] == 'Ll'] image = [chr(int(c[0], 16)) for c in characters] output = "\n".join(image) out.write(output.encode("UTF-8")) // ... rest of the code ...
aaad392fedca6b3f9879240591877f6a64d907c3
wordcloud/wordcloud.py
wordcloud/wordcloud.py
import os from operator import itemgetter from haystack.query import SearchQuerySet from pombola.hansard import models as hansard_models BASEDIR = os.path.dirname(__file__) # normal english stop words and hansard-centric words to ignore STOP_WORDS = open(os.path.join(BASEDIR, 'stopwords.txt'), 'rU').read().splitlines() def popular_words(max_entries=20): sqs = SearchQuerySet().models(hansard_models.Entry).order_by('-sitting_start_date') cloudlist = [] try: # Generate tag cloud from content of returned entries words = {} for entry in sqs[:max_entries]: text = entry.object.content for x in text.lower().split(): cleanx = x.replace(',', '').replace('.', '').replace('"', '').strip() if cleanx not in STOP_WORDS: # and not cleanx in hansard_words: words[cleanx] = 1 + words.get(cleanx, 0) for word in words: cloudlist.append( { "text": word, "weight": words.get(word), "link": "/search/hansard/?q=%s" % word, } ) sortedlist = sorted(cloudlist, key=itemgetter('weight'), reverse=True)[:25] except: sortedlist = [] return sortedlist
import os from operator import itemgetter from haystack.query import SearchQuerySet from pombola.hansard import models as hansard_models BASEDIR = os.path.dirname(__file__) # normal english stop words and hansard-centric words to ignore STOP_WORDS = open(os.path.join(BASEDIR, 'stopwords.txt'), 'rU').read().splitlines() def popular_words(max_entries=20, max_words=25): sqs = SearchQuerySet().models(hansard_models.Entry).order_by('-sitting_start_date') cloudlist = [] try: # Generate tag cloud from content of returned entries words = {} for entry in sqs[:max_entries]: text = entry.object.content for x in text.lower().split(): cleanx = x.replace(',', '').replace('.', '').replace('"', '').strip() if cleanx not in STOP_WORDS: # and not cleanx in hansard_words: words[cleanx] = 1 + words.get(cleanx, 0) for word in words: cloudlist.append( { "text": word, "weight": words.get(word), "link": "/search/hansard/?q=%s" % word, } ) sortedlist = sorted(cloudlist, key=itemgetter('weight'), reverse=True)[:max_words] except: sortedlist = [] return sortedlist
Make maximum number of words a parameter
Make maximum number of words a parameter
Python
agpl-3.0
geoffkilpin/pombola,geoffkilpin/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,geoffkilpin/pombola,mysociety/pombola,geoffkilpin/pombola,geoffkilpin/pombola,geoffkilpin/pombola,mysociety/pombola
import os from operator import itemgetter from haystack.query import SearchQuerySet from pombola.hansard import models as hansard_models BASEDIR = os.path.dirname(__file__) # normal english stop words and hansard-centric words to ignore STOP_WORDS = open(os.path.join(BASEDIR, 'stopwords.txt'), 'rU').read().splitlines() - def popular_words(max_entries=20): + def popular_words(max_entries=20, max_words=25): sqs = SearchQuerySet().models(hansard_models.Entry).order_by('-sitting_start_date') cloudlist = [] try: # Generate tag cloud from content of returned entries words = {} for entry in sqs[:max_entries]: text = entry.object.content for x in text.lower().split(): cleanx = x.replace(',', '').replace('.', '').replace('"', '').strip() if cleanx not in STOP_WORDS: # and not cleanx in hansard_words: words[cleanx] = 1 + words.get(cleanx, 0) for word in words: cloudlist.append( { "text": word, "weight": words.get(word), "link": "/search/hansard/?q=%s" % word, } ) - sortedlist = sorted(cloudlist, key=itemgetter('weight'), reverse=True)[:25] + sortedlist = sorted(cloudlist, key=itemgetter('weight'), reverse=True)[:max_words] except: sortedlist = [] return sortedlist
Make maximum number of words a parameter
## Code Before: import os from operator import itemgetter from haystack.query import SearchQuerySet from pombola.hansard import models as hansard_models BASEDIR = os.path.dirname(__file__) # normal english stop words and hansard-centric words to ignore STOP_WORDS = open(os.path.join(BASEDIR, 'stopwords.txt'), 'rU').read().splitlines() def popular_words(max_entries=20): sqs = SearchQuerySet().models(hansard_models.Entry).order_by('-sitting_start_date') cloudlist = [] try: # Generate tag cloud from content of returned entries words = {} for entry in sqs[:max_entries]: text = entry.object.content for x in text.lower().split(): cleanx = x.replace(',', '').replace('.', '').replace('"', '').strip() if cleanx not in STOP_WORDS: # and not cleanx in hansard_words: words[cleanx] = 1 + words.get(cleanx, 0) for word in words: cloudlist.append( { "text": word, "weight": words.get(word), "link": "/search/hansard/?q=%s" % word, } ) sortedlist = sorted(cloudlist, key=itemgetter('weight'), reverse=True)[:25] except: sortedlist = [] return sortedlist ## Instruction: Make maximum number of words a parameter ## Code After: import os from operator import itemgetter from haystack.query import SearchQuerySet from pombola.hansard import models as hansard_models BASEDIR = os.path.dirname(__file__) # normal english stop words and hansard-centric words to ignore STOP_WORDS = open(os.path.join(BASEDIR, 'stopwords.txt'), 'rU').read().splitlines() def popular_words(max_entries=20, max_words=25): sqs = SearchQuerySet().models(hansard_models.Entry).order_by('-sitting_start_date') cloudlist = [] try: # Generate tag cloud from content of returned entries words = {} for entry in sqs[:max_entries]: text = entry.object.content for x in text.lower().split(): cleanx = x.replace(',', '').replace('.', '').replace('"', '').strip() if cleanx not in STOP_WORDS: # and not cleanx in hansard_words: words[cleanx] = 1 + words.get(cleanx, 0) for word in words: cloudlist.append( { "text": word, "weight": words.get(word), "link": "/search/hansard/?q=%s" % word, } ) sortedlist = sorted(cloudlist, key=itemgetter('weight'), reverse=True)[:max_words] except: sortedlist = [] return sortedlist
... def popular_words(max_entries=20, max_words=25): sqs = SearchQuerySet().models(hansard_models.Entry).order_by('-sitting_start_date') ... sortedlist = sorted(cloudlist, key=itemgetter('weight'), reverse=True)[:max_words] except: ...
27e7f47f2506be8607f29961dd629a8038c7e67f
ecmd-core/pyecmd/test_api.py
ecmd-core/pyecmd/test_api.py
from pyecmd import * with Ecmd(fapi2="ver1"): t = loopTargets("pu", ECMD_SELECTED_TARGETS_LOOP)[0] data = t.getScom(0x1234) t.putScom(0x1234, 0x10100000) # These interfaces may not be defined for some plugins # Pull them to prevent compile issues #core_id, thread_id = t.targetToSequenceId() #unit_id_string = unitIdToString(2) #clock_state = t.queryClockState("SOMECLOCK") t.relatedTargets("pu.c") retval = t.queryFileLocation(ECMD_FILE_SCANDEF, "") for loc in retval.fileLocations: testval = loc.textFile + loc.hashFile + retval.version try: t.fapi2GetAttr("ATTR_DOES_NOT_EXIST") assert(""=="That was supposed to throw!") except KeyError: pass t.fapi2SetAttr("ATTR_CHIP_ID", 42) assert(42 == t.fapi2GetAttr("ATTR_CHIP_ID"))
from pyecmd import * extensions = {} if hasattr(ecmd, "fapi2InitExtension"): extensions["fapi2"] = "ver1" with Ecmd(**extensions): t = loopTargets("pu", ECMD_SELECTED_TARGETS_LOOP)[0] data = t.getScom(0x1234) t.putScom(0x1234, 0x10100000) # These interfaces may not be defined for some plugins # Pull them to prevent compile issues #core_id, thread_id = t.targetToSequenceId() #unit_id_string = unitIdToString(2) #clock_state = t.queryClockState("SOMECLOCK") t.relatedTargets("pu.c") retval = t.queryFileLocation(ECMD_FILE_SCANDEF, "") for loc in retval.fileLocations: testval = loc.textFile + loc.hashFile + retval.version if "fapi2" in extensions: try: t.fapi2GetAttr("ATTR_DOES_NOT_EXIST") assert(""=="That was supposed to throw!") except KeyError: pass t.fapi2SetAttr("ATTR_CHIP_ID", 42) assert(42 == t.fapi2GetAttr("ATTR_CHIP_ID"))
Make fapi2 test conditional on fapi2 being built into ecmd
pyecmd: Make fapi2 test conditional on fapi2 being built into ecmd
Python
apache-2.0
open-power/eCMD,open-power/eCMD,open-power/eCMD,open-power/eCMD,open-power/eCMD
from pyecmd import * - with Ecmd(fapi2="ver1"): + extensions = {} + if hasattr(ecmd, "fapi2InitExtension"): + extensions["fapi2"] = "ver1" + + with Ecmd(**extensions): t = loopTargets("pu", ECMD_SELECTED_TARGETS_LOOP)[0] data = t.getScom(0x1234) t.putScom(0x1234, 0x10100000) # These interfaces may not be defined for some plugins # Pull them to prevent compile issues #core_id, thread_id = t.targetToSequenceId() #unit_id_string = unitIdToString(2) #clock_state = t.queryClockState("SOMECLOCK") t.relatedTargets("pu.c") retval = t.queryFileLocation(ECMD_FILE_SCANDEF, "") for loc in retval.fileLocations: testval = loc.textFile + loc.hashFile + retval.version - try: - t.fapi2GetAttr("ATTR_DOES_NOT_EXIST") - assert(""=="That was supposed to throw!") - except KeyError: - pass - t.fapi2SetAttr("ATTR_CHIP_ID", 42) - assert(42 == t.fapi2GetAttr("ATTR_CHIP_ID")) + if "fapi2" in extensions: + try: + t.fapi2GetAttr("ATTR_DOES_NOT_EXIST") + assert(""=="That was supposed to throw!") + except KeyError: + pass + t.fapi2SetAttr("ATTR_CHIP_ID", 42) + assert(42 == t.fapi2GetAttr("ATTR_CHIP_ID")) +
Make fapi2 test conditional on fapi2 being built into ecmd
## Code Before: from pyecmd import * with Ecmd(fapi2="ver1"): t = loopTargets("pu", ECMD_SELECTED_TARGETS_LOOP)[0] data = t.getScom(0x1234) t.putScom(0x1234, 0x10100000) # These interfaces may not be defined for some plugins # Pull them to prevent compile issues #core_id, thread_id = t.targetToSequenceId() #unit_id_string = unitIdToString(2) #clock_state = t.queryClockState("SOMECLOCK") t.relatedTargets("pu.c") retval = t.queryFileLocation(ECMD_FILE_SCANDEF, "") for loc in retval.fileLocations: testval = loc.textFile + loc.hashFile + retval.version try: t.fapi2GetAttr("ATTR_DOES_NOT_EXIST") assert(""=="That was supposed to throw!") except KeyError: pass t.fapi2SetAttr("ATTR_CHIP_ID", 42) assert(42 == t.fapi2GetAttr("ATTR_CHIP_ID")) ## Instruction: Make fapi2 test conditional on fapi2 being built into ecmd ## Code After: from pyecmd import * extensions = {} if hasattr(ecmd, "fapi2InitExtension"): extensions["fapi2"] = "ver1" with Ecmd(**extensions): t = loopTargets("pu", ECMD_SELECTED_TARGETS_LOOP)[0] data = t.getScom(0x1234) t.putScom(0x1234, 0x10100000) # These interfaces may not be defined for some plugins # Pull them to prevent compile issues #core_id, thread_id = t.targetToSequenceId() #unit_id_string = unitIdToString(2) #clock_state = t.queryClockState("SOMECLOCK") t.relatedTargets("pu.c") retval = t.queryFileLocation(ECMD_FILE_SCANDEF, "") for loc in retval.fileLocations: testval = loc.textFile + loc.hashFile + retval.version if "fapi2" in extensions: try: t.fapi2GetAttr("ATTR_DOES_NOT_EXIST") assert(""=="That was supposed to throw!") except KeyError: pass t.fapi2SetAttr("ATTR_CHIP_ID", 42) assert(42 == t.fapi2GetAttr("ATTR_CHIP_ID"))
// ... existing code ... extensions = {} if hasattr(ecmd, "fapi2InitExtension"): extensions["fapi2"] = "ver1" with Ecmd(**extensions): t = loopTargets("pu", ECMD_SELECTED_TARGETS_LOOP)[0] // ... modified code ... testval = loc.textFile + loc.hashFile + retval.version if "fapi2" in extensions: try: t.fapi2GetAttr("ATTR_DOES_NOT_EXIST") assert(""=="That was supposed to throw!") except KeyError: pass t.fapi2SetAttr("ATTR_CHIP_ID", 42) assert(42 == t.fapi2GetAttr("ATTR_CHIP_ID")) // ... rest of the code ...
ee28fdc66fbb0f91821ff18ff219791bf5de8f4d
corehq/apps/fixtures/tasks.py
corehq/apps/fixtures/tasks.py
from __future__ import absolute_import from __future__ import unicode_literals from corehq.apps.fixtures.upload import upload_fixture_file from soil import DownloadBase from celery.task import task @task(serializer='pickle') def fixture_upload_async(domain, download_id, replace): task = fixture_upload_async DownloadBase.set_progress(task, 0, 100) download_ref = DownloadBase.get(download_id) result = upload_fixture_file(domain, download_ref.get_filename(), replace, task) DownloadBase.set_progress(task, 100, 100) return { 'messages': { 'success': result.success, 'messages': result.messages, 'errors': result.errors, 'number_of_fixtures': result.number_of_fixtures, }, } @task(serializer='pickle') def fixture_download_async(prepare_download, *args, **kw): task = fixture_download_async DownloadBase.set_progress(task, 0, 100) prepare_download(task=task, *args, **kw) DownloadBase.set_progress(task, 100, 100)
from __future__ import absolute_import, unicode_literals from celery.task import task from soil import DownloadBase from corehq.apps.fixtures.upload import upload_fixture_file @task def fixture_upload_async(domain, download_id, replace): task = fixture_upload_async DownloadBase.set_progress(task, 0, 100) download_ref = DownloadBase.get(download_id) result = upload_fixture_file(domain, download_ref.get_filename(), replace, task) DownloadBase.set_progress(task, 100, 100) return { 'messages': { 'success': result.success, 'messages': result.messages, 'errors': result.errors, 'number_of_fixtures': result.number_of_fixtures, }, } @task(serializer='pickle') def fixture_download_async(prepare_download, *args, **kw): task = fixture_download_async DownloadBase.set_progress(task, 0, 100) prepare_download(task=task, *args, **kw) DownloadBase.set_progress(task, 100, 100)
Change fixture upload task to json serializer
Change fixture upload task to json serializer
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
- from __future__ import absolute_import - from __future__ import unicode_literals + from __future__ import absolute_import, unicode_literals + - from corehq.apps.fixtures.upload import upload_fixture_file - from soil import DownloadBase from celery.task import task + from soil import DownloadBase - @task(serializer='pickle') + from corehq.apps.fixtures.upload import upload_fixture_file + + + @task def fixture_upload_async(domain, download_id, replace): task = fixture_upload_async DownloadBase.set_progress(task, 0, 100) download_ref = DownloadBase.get(download_id) result = upload_fixture_file(domain, download_ref.get_filename(), replace, task) DownloadBase.set_progress(task, 100, 100) return { 'messages': { 'success': result.success, 'messages': result.messages, 'errors': result.errors, 'number_of_fixtures': result.number_of_fixtures, }, } @task(serializer='pickle') def fixture_download_async(prepare_download, *args, **kw): task = fixture_download_async DownloadBase.set_progress(task, 0, 100) prepare_download(task=task, *args, **kw) DownloadBase.set_progress(task, 100, 100)
Change fixture upload task to json serializer
## Code Before: from __future__ import absolute_import from __future__ import unicode_literals from corehq.apps.fixtures.upload import upload_fixture_file from soil import DownloadBase from celery.task import task @task(serializer='pickle') def fixture_upload_async(domain, download_id, replace): task = fixture_upload_async DownloadBase.set_progress(task, 0, 100) download_ref = DownloadBase.get(download_id) result = upload_fixture_file(domain, download_ref.get_filename(), replace, task) DownloadBase.set_progress(task, 100, 100) return { 'messages': { 'success': result.success, 'messages': result.messages, 'errors': result.errors, 'number_of_fixtures': result.number_of_fixtures, }, } @task(serializer='pickle') def fixture_download_async(prepare_download, *args, **kw): task = fixture_download_async DownloadBase.set_progress(task, 0, 100) prepare_download(task=task, *args, **kw) DownloadBase.set_progress(task, 100, 100) ## Instruction: Change fixture upload task to json serializer ## Code After: from __future__ import absolute_import, unicode_literals from celery.task import task from soil import DownloadBase from corehq.apps.fixtures.upload import upload_fixture_file @task def fixture_upload_async(domain, download_id, replace): task = fixture_upload_async DownloadBase.set_progress(task, 0, 100) download_ref = DownloadBase.get(download_id) result = upload_fixture_file(domain, download_ref.get_filename(), replace, task) DownloadBase.set_progress(task, 100, 100) return { 'messages': { 'success': result.success, 'messages': result.messages, 'errors': result.errors, 'number_of_fixtures': result.number_of_fixtures, }, } @task(serializer='pickle') def fixture_download_async(prepare_download, *args, **kw): task = fixture_download_async DownloadBase.set_progress(task, 0, 100) prepare_download(task=task, *args, **kw) DownloadBase.set_progress(task, 100, 100)
// ... existing code ... from __future__ import absolute_import, unicode_literals from celery.task import task // ... modified code ... from soil import DownloadBase from corehq.apps.fixtures.upload import upload_fixture_file @task def fixture_upload_async(domain, download_id, replace): // ... rest of the code ...
24e780dd0f30e4bf9696a6fd185d20fb297f0bd0
rsk_mind/transformer/transformer.py
rsk_mind/transformer/transformer.py
class Transformer(object): class Feats(): exclude = None def __init__(self): for field in self.get_feats(): getattr(self.Feats, field).bind(field, self) def get_feats(self): return [x for x in dir(self.Feats) if not (x.startswith('__') or x in ['exclude'])] def get_transformer_func(self, feat_name): return getattr(self.Feats, feat_name).transform
class Transformer(object): """ Base class for all transformer """ class Feats: """ Define feats on dataset """ exclude = None def __init__(self): for field in self.get_feats(): getattr(self.Feats, field).bind(field, self) def get_feats(self): """ :return: a list of feats """ return [x for x in dir(self.Feats) if not (x.startswith('__') or x in ['exclude'])] def get_transformer_func(self, feat_name): """ :param feat_name: name of feat :return: a transformer function on feat """ return getattr(self.Feats, feat_name).transform def get_excluded_feats(self): """ :return: a list with excluded feats """ return self.Feats.exclude
Add documentation and some methods
Add documentation and some methods
Python
mit
rsk-mind/rsk-mind-framework
class Transformer(object): + """ + Base class for all transformer + """ + - class Feats(): + class Feats: + """ + Define feats on dataset + """ exclude = None def __init__(self): for field in self.get_feats(): getattr(self.Feats, field).bind(field, self) def get_feats(self): + """ + + :return: a list of feats + """ return [x for x in dir(self.Feats) if not (x.startswith('__') or x in ['exclude'])] def get_transformer_func(self, feat_name): + """ + + :param feat_name: name of feat + :return: a transformer function on feat + """ return getattr(self.Feats, feat_name).transform + def get_excluded_feats(self): + """ + + :return: a list with excluded feats + """ + return self.Feats.exclude +
Add documentation and some methods
## Code Before: class Transformer(object): class Feats(): exclude = None def __init__(self): for field in self.get_feats(): getattr(self.Feats, field).bind(field, self) def get_feats(self): return [x for x in dir(self.Feats) if not (x.startswith('__') or x in ['exclude'])] def get_transformer_func(self, feat_name): return getattr(self.Feats, feat_name).transform ## Instruction: Add documentation and some methods ## Code After: class Transformer(object): """ Base class for all transformer """ class Feats: """ Define feats on dataset """ exclude = None def __init__(self): for field in self.get_feats(): getattr(self.Feats, field).bind(field, self) def get_feats(self): """ :return: a list of feats """ return [x for x in dir(self.Feats) if not (x.startswith('__') or x in ['exclude'])] def get_transformer_func(self, feat_name): """ :param feat_name: name of feat :return: a transformer function on feat """ return getattr(self.Feats, feat_name).transform def get_excluded_feats(self): """ :return: a list with excluded feats """ return self.Feats.exclude
# ... existing code ... class Transformer(object): """ Base class for all transformer """ class Feats: """ Define feats on dataset """ exclude = None # ... modified code ... def get_feats(self): """ :return: a list of feats """ return [x for x in dir(self.Feats) if not (x.startswith('__') or x in ['exclude'])] ... def get_transformer_func(self, feat_name): """ :param feat_name: name of feat :return: a transformer function on feat """ return getattr(self.Feats, feat_name).transform def get_excluded_feats(self): """ :return: a list with excluded feats """ return self.Feats.exclude # ... rest of the code ...
061386e402fb3f1300c0c71be9b07ecc16590ecc
cronjobs/extract_kalliope_originators.py
cronjobs/extract_kalliope_originators.py
import re import sys import xml.etree.ElementTree as ET valid_gnd = re.compile('[0-9\-X]+') def Main(): if len(sys.argv) != 2: print("Usage: " + sys.argv[0] + " kalliope_originator_record_file") exit(1) root = ET.parse(sys.argv[1]).getroot() gnds_and_type = {} for recordData in root.findall('.//{*}recordData'): genre = recordData.find('.//{*}genre') name = recordData.find('.//{*}name') if genre is not None and name is not None : gnd = name.get('valueURI').replace('https://d-nb.info/gnd/','') if name.get('valueURI') else None originator_type = genre.text if gnd and originator_type and valid_gnd.match(gnd): if gnd in gnds_and_type and not originator_type in gnds_and_type[gnd]: gnds_and_type[gnd].add(originator_type) else: gnds_and_type[gnd] = { originator_type } for gnd, originator_type in gnds_and_type.items(): print(gnd, ' - ', end='') print(*originator_type, sep=', ') try: Main() except Exception as e: print("ERROR: " + e)
import re import sys import xml.etree.ElementTree as ET valid_gnd = re.compile('[0-9\-X]+') def Main(): if len(sys.argv) != 2: print("Usage: " + sys.argv[0] + " kalliope_originator_record_file") exit(1) root = ET.parse(sys.argv[1]).getroot() gnds_and_type = {} for recordData in root.findall('.//{http://www.loc.gov/zing/srw/}recordData'): genre = recordData.find('.//{http://www.loc.gov/mods/v3}genre') name = recordData.find('.//{http://www.loc.gov/mods/v3}name') if genre is not None and name is not None : gnd = name.get('valueURI').replace('https://d-nb.info/gnd/','') if name.get('valueURI') else None originator_type = genre.text if gnd and originator_type and valid_gnd.match(gnd): if gnd in gnds_and_type and not originator_type in gnds_and_type[gnd]: gnds_and_type[gnd].add(originator_type) else: gnds_and_type[gnd] = { originator_type } for gnd, originator_type in gnds_and_type.items(): print(gnd, ' - ', end='') print(*originator_type, sep=', ') try: Main() except Exception as e: print("ERROR: " + e)
Make compatible with CentOS 8
Make compatible with CentOS 8
Python
agpl-3.0
ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools
import re import sys import xml.etree.ElementTree as ET valid_gnd = re.compile('[0-9\-X]+') def Main(): if len(sys.argv) != 2: print("Usage: " + sys.argv[0] + " kalliope_originator_record_file") exit(1) root = ET.parse(sys.argv[1]).getroot() gnds_and_type = {} - for recordData in root.findall('.//{*}recordData'): + for recordData in root.findall('.//{http://www.loc.gov/zing/srw/}recordData'): - genre = recordData.find('.//{*}genre') + genre = recordData.find('.//{http://www.loc.gov/mods/v3}genre') - name = recordData.find('.//{*}name') + name = recordData.find('.//{http://www.loc.gov/mods/v3}name') if genre is not None and name is not None : gnd = name.get('valueURI').replace('https://d-nb.info/gnd/','') if name.get('valueURI') else None originator_type = genre.text if gnd and originator_type and valid_gnd.match(gnd): if gnd in gnds_and_type and not originator_type in gnds_and_type[gnd]: gnds_and_type[gnd].add(originator_type) else: gnds_and_type[gnd] = { originator_type } for gnd, originator_type in gnds_and_type.items(): print(gnd, ' - ', end='') print(*originator_type, sep=', ') try: Main() except Exception as e: print("ERROR: " + e)
Make compatible with CentOS 8
## Code Before: import re import sys import xml.etree.ElementTree as ET valid_gnd = re.compile('[0-9\-X]+') def Main(): if len(sys.argv) != 2: print("Usage: " + sys.argv[0] + " kalliope_originator_record_file") exit(1) root = ET.parse(sys.argv[1]).getroot() gnds_and_type = {} for recordData in root.findall('.//{*}recordData'): genre = recordData.find('.//{*}genre') name = recordData.find('.//{*}name') if genre is not None and name is not None : gnd = name.get('valueURI').replace('https://d-nb.info/gnd/','') if name.get('valueURI') else None originator_type = genre.text if gnd and originator_type and valid_gnd.match(gnd): if gnd in gnds_and_type and not originator_type in gnds_and_type[gnd]: gnds_and_type[gnd].add(originator_type) else: gnds_and_type[gnd] = { originator_type } for gnd, originator_type in gnds_and_type.items(): print(gnd, ' - ', end='') print(*originator_type, sep=', ') try: Main() except Exception as e: print("ERROR: " + e) ## Instruction: Make compatible with CentOS 8 ## Code After: import re import sys import xml.etree.ElementTree as ET valid_gnd = re.compile('[0-9\-X]+') def Main(): if len(sys.argv) != 2: print("Usage: " + sys.argv[0] + " kalliope_originator_record_file") exit(1) root = ET.parse(sys.argv[1]).getroot() gnds_and_type = {} for recordData in root.findall('.//{http://www.loc.gov/zing/srw/}recordData'): genre = recordData.find('.//{http://www.loc.gov/mods/v3}genre') name = recordData.find('.//{http://www.loc.gov/mods/v3}name') if genre is not None and name is not None : gnd = name.get('valueURI').replace('https://d-nb.info/gnd/','') if name.get('valueURI') else None originator_type = genre.text if gnd and originator_type and valid_gnd.match(gnd): if gnd in gnds_and_type and not originator_type in gnds_and_type[gnd]: gnds_and_type[gnd].add(originator_type) else: gnds_and_type[gnd] = { originator_type } for gnd, originator_type in gnds_and_type.items(): print(gnd, ' - ', end='') print(*originator_type, sep=', ') try: Main() except Exception as e: print("ERROR: " + e)
... gnds_and_type = {} for recordData in root.findall('.//{http://www.loc.gov/zing/srw/}recordData'): genre = recordData.find('.//{http://www.loc.gov/mods/v3}genre') name = recordData.find('.//{http://www.loc.gov/mods/v3}name') if genre is not None and name is not None : ...
62eea0104615b5d75183d5392fe250fa07d2a988
src/bulksms/config.py
src/bulksms/config.py
CONFIG = { 'BULK_SMS': { 'AUTH': { 'USERNAME': '', 'PASSWORD': '' }, 'URL': { 'SINGLE': 'https://bulksms.2way.co.za/eapi/submission/send_sms/2/2.0', 'BATCH': 'http://bulksms.2way.co.za/eapi/submission/send_batch/1/1.0' } }, 'CLEAN_MOBILE_NUMBERS': False }
CONFIG = { 'BULK_SMS': { 'AUTH': { 'USERNAME': '', 'PASSWORD': '' }, 'URL': { 'SENDING': { { 'SINGLE': 'https://bulksms.2way.co.za/eapi/submission/send_sms/2/2.0', 'BATCH': 'https://bulksms.2way.co.za/eapi/submission/send_batch/1/1.0' } }, 'CREDITS': { 'CREDITS': 'https://bulksms.2way.co.za/user/get_credits/1/1.1' } } }, 'CLEAN_MOBILE_NUMBERS': False }
Add url for getting credits.
Add url for getting credits.
Python
mit
tsotetsi/django-bulksms
CONFIG = { 'BULK_SMS': { 'AUTH': { 'USERNAME': '', 'PASSWORD': '' }, 'URL': { + 'SENDING': { + { - 'SINGLE': 'https://bulksms.2way.co.za/eapi/submission/send_sms/2/2.0', + 'SINGLE': 'https://bulksms.2way.co.za/eapi/submission/send_sms/2/2.0', - 'BATCH': 'http://bulksms.2way.co.za/eapi/submission/send_batch/1/1.0' + 'BATCH': 'https://bulksms.2way.co.za/eapi/submission/send_batch/1/1.0' + } + }, + 'CREDITS': { + 'CREDITS': 'https://bulksms.2way.co.za/user/get_credits/1/1.1' + } } }, 'CLEAN_MOBILE_NUMBERS': False }
Add url for getting credits.
## Code Before: CONFIG = { 'BULK_SMS': { 'AUTH': { 'USERNAME': '', 'PASSWORD': '' }, 'URL': { 'SINGLE': 'https://bulksms.2way.co.za/eapi/submission/send_sms/2/2.0', 'BATCH': 'http://bulksms.2way.co.za/eapi/submission/send_batch/1/1.0' } }, 'CLEAN_MOBILE_NUMBERS': False } ## Instruction: Add url for getting credits. ## Code After: CONFIG = { 'BULK_SMS': { 'AUTH': { 'USERNAME': '', 'PASSWORD': '' }, 'URL': { 'SENDING': { { 'SINGLE': 'https://bulksms.2way.co.za/eapi/submission/send_sms/2/2.0', 'BATCH': 'https://bulksms.2way.co.za/eapi/submission/send_batch/1/1.0' } }, 'CREDITS': { 'CREDITS': 'https://bulksms.2way.co.za/user/get_credits/1/1.1' } } }, 'CLEAN_MOBILE_NUMBERS': False }
... 'URL': { 'SENDING': { { 'SINGLE': 'https://bulksms.2way.co.za/eapi/submission/send_sms/2/2.0', 'BATCH': 'https://bulksms.2way.co.za/eapi/submission/send_batch/1/1.0' } }, 'CREDITS': { 'CREDITS': 'https://bulksms.2way.co.za/user/get_credits/1/1.1' } } ...
272ece1774cebaf8d6d6ae9e0dfb5fe0cce97083
manage.py
manage.py
import os import sys if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'conductor.settings.development') if 'test' in sys.argv: # For now, fake setting the environment for testing. os.environ['DJANGO_SETTINGS_MODULE'] = 'conductor.settings.test' os.environ['SECRET_KEY'] = 'asecrettoeverybody' from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
import os import sys if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'conductor.settings.development') if 'test' in sys.argv: # For now, fake setting the environment for testing. os.environ['DJANGO_SETTINGS_MODULE'] = 'conductor.settings.test' os.environ['CORS_ORIGIN_WHITELIST'] = 'localhost:4200' os.environ['SECRET_KEY'] = 'asecrettoeverybody' os.environ['STATIC_URL'] = '/static/' from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
Add missing env variables for testing.
Add missing env variables for testing.
Python
bsd-2-clause
mblayman/lcp,mblayman/lcp,mblayman/lcp
import os import sys if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'conductor.settings.development') if 'test' in sys.argv: # For now, fake setting the environment for testing. os.environ['DJANGO_SETTINGS_MODULE'] = 'conductor.settings.test' + os.environ['CORS_ORIGIN_WHITELIST'] = 'localhost:4200' os.environ['SECRET_KEY'] = 'asecrettoeverybody' + os.environ['STATIC_URL'] = '/static/' from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
Add missing env variables for testing.
## Code Before: import os import sys if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'conductor.settings.development') if 'test' in sys.argv: # For now, fake setting the environment for testing. os.environ['DJANGO_SETTINGS_MODULE'] = 'conductor.settings.test' os.environ['SECRET_KEY'] = 'asecrettoeverybody' from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) ## Instruction: Add missing env variables for testing. ## Code After: import os import sys if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'conductor.settings.development') if 'test' in sys.argv: # For now, fake setting the environment for testing. os.environ['DJANGO_SETTINGS_MODULE'] = 'conductor.settings.test' os.environ['CORS_ORIGIN_WHITELIST'] = 'localhost:4200' os.environ['SECRET_KEY'] = 'asecrettoeverybody' os.environ['STATIC_URL'] = '/static/' from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
// ... existing code ... os.environ['DJANGO_SETTINGS_MODULE'] = 'conductor.settings.test' os.environ['CORS_ORIGIN_WHITELIST'] = 'localhost:4200' os.environ['SECRET_KEY'] = 'asecrettoeverybody' os.environ['STATIC_URL'] = '/static/' // ... rest of the code ...
37bb334a1c59920d92649b0cedddf62863bf6da8
scipy/weave/tests/test_inline_tools.py
scipy/weave/tests/test_inline_tools.py
from numpy import * from numpy.testing import * from scipy.weave import inline_tools class TestInline(TestCase): """ These are long running tests... I'd like to benchmark these things somehow. """ @dec.slow def test_exceptions(self): a = 3 code = """ if (a < 2) throw_error(PyExc_ValueError, "the variable 'a' should not be less than 2"); else return_val = PyInt_FromLong(a+1); """ result = inline_tools.inline(code,['a']) assert(result == 4) try: a = 1 result = inline_tools.inline(code,['a']) assert(1) # should've thrown a ValueError except ValueError: pass from distutils.errors import DistutilsError, CompileError try: a = 'string' result = inline_tools.inline(code,['a']) assert(1) # should've gotten an error except: # ?CompileError is the error reported, but catching it doesn't work pass if __name__ == "__main__": nose.run(argv=['', __file__])
from numpy import * from numpy.testing import * from scipy.weave import inline_tools class TestInline(TestCase): """ These are long running tests... I'd like to benchmark these things somehow. """ @dec.slow def test_exceptions(self): a = 3 code = """ if (a < 2) throw_error(PyExc_ValueError, "the variable 'a' should not be less than 2"); else return_val = PyInt_FromLong(a+1); """ result = inline_tools.inline(code,['a']) assert(result == 4) ## Unfortunately, it is not always possible to catch distutils compiler ## errors, since SystemExit is used. Until that is fixed, these tests ## cannot be run in the same process as the test suite. ## try: ## a = 1 ## result = inline_tools.inline(code,['a']) ## assert(1) # should've thrown a ValueError ## except ValueError: ## pass ## from distutils.errors import DistutilsError, CompileError ## try: ## a = 'string' ## result = inline_tools.inline(code,['a']) ## assert(1) # should've gotten an error ## except: ## # ?CompileError is the error reported, but catching it doesn't work ## pass if __name__ == "__main__": nose.run(argv=['', __file__])
Disable weave tests that cause compilation failure, since this causes distutils to do a SystemExit, which break the test suite.
Disable weave tests that cause compilation failure, since this causes distutils to do a SystemExit, which break the test suite.
Python
bsd-3-clause
kalvdans/scipy,chatcannon/scipy,trankmichael/scipy,ilayn/scipy,jsilter/scipy,tylerjereddy/scipy,mikebenfield/scipy,minhlongdo/scipy,trankmichael/scipy,WillieMaddox/scipy,piyush0609/scipy,surhudm/scipy,Dapid/scipy,chatcannon/scipy,grlee77/scipy,vanpact/scipy,Kamp9/scipy,Srisai85/scipy,ilayn/scipy,dch312/scipy,chatcannon/scipy,kleskjr/scipy,gef756/scipy,ndchorley/scipy,Shaswat27/scipy,woodscn/scipy,jjhelmus/scipy,cpaulik/scipy,anielsen001/scipy,mortada/scipy,njwilson23/scipy,lukauskas/scipy,anntzer/scipy,zerothi/scipy,aman-iitj/scipy,ChanderG/scipy,befelix/scipy,vhaasteren/scipy,arokem/scipy,pizzathief/scipy,trankmichael/scipy,sriki18/scipy,maniteja123/scipy,ChanderG/scipy,pyramania/scipy,sargas/scipy,e-q/scipy,rgommers/scipy,jakevdp/scipy,Dapid/scipy,maciejkula/scipy,gdooper/scipy,Newman101/scipy,ChanderG/scipy,larsmans/scipy,giorgiop/scipy,petebachant/scipy,WillieMaddox/scipy,jonycgn/scipy,WarrenWeckesser/scipy,fernand/scipy,kalvdans/scipy,Eric89GXL/scipy,perimosocordiae/scipy,pizzathief/scipy,sonnyhu/scipy,jonycgn/scipy,apbard/scipy,aeklant/scipy,sonnyhu/scipy,mhogg/scipy,niknow/scipy,anielsen001/scipy,matthew-brett/scipy,endolith/scipy,andim/scipy,ortylp/scipy,vberaudi/scipy,futurulus/scipy,jsilter/scipy,mortada/scipy,sauliusl/scipy,vberaudi/scipy,jjhelmus/scipy,felipebetancur/scipy,pnedunuri/scipy,Kamp9/scipy,ales-erjavec/scipy,zxsted/scipy,sriki18/scipy,vberaudi/scipy,FRidh/scipy,sargas/scipy,pnedunuri/scipy,mgaitan/scipy,haudren/scipy,hainm/scipy,tylerjereddy/scipy,nonhermitian/scipy,pbrod/scipy,gertingold/scipy,teoliphant/scipy,vhaasteren/scipy,kleskjr/scipy,woodscn/scipy,jor-/scipy,newemailjdm/scipy,grlee77/scipy,hainm/scipy,chatcannon/scipy,gdooper/scipy,sonnyhu/scipy,dominicelse/scipy,fernand/scipy,mhogg/scipy,nonhermitian/scipy,sonnyhu/scipy,rgommers/scipy,FRidh/scipy,piyush0609/scipy,cpaulik/scipy,cpaulik/scipy,arokem/scipy,gef756/scipy,bkendzior/scipy,vanpact/scipy,njwilson23/scipy,ogrisel/scipy,raoulbq/scipy,vanpact/scipy,mortonjt/scipy,mgaitan/scipy,jjhelmus/scipy,ilayn/scipy,pyramania/scipy,matthew-brett/scipy,surhudm/scipy,hainm/scipy,FRidh/scipy,jonycgn/scipy,endolith/scipy,behzadnouri/scipy,richardotis/scipy,e-q/scipy,gdooper/scipy,jseabold/scipy,pizzathief/scipy,WillieMaddox/scipy,aarchiba/scipy,dch312/scipy,futurulus/scipy,lukauskas/scipy,pyramania/scipy,aeklant/scipy,giorgiop/scipy,felipebetancur/scipy,gef756/scipy,pnedunuri/scipy,jamestwebber/scipy,mortonjt/scipy,witcxc/scipy,Eric89GXL/scipy,mtrbean/scipy,andyfaff/scipy,argriffing/scipy,fernand/scipy,fredrikw/scipy,haudren/scipy,surhudm/scipy,Shaswat27/scipy,kleskjr/scipy,person142/scipy,jor-/scipy,aeklant/scipy,perimosocordiae/scipy,newemailjdm/scipy,juliantaylor/scipy,Shaswat27/scipy,maniteja123/scipy,surhudm/scipy,mingwpy/scipy,zxsted/scipy,jamestwebber/scipy,perimosocordiae/scipy,ilayn/scipy,argriffing/scipy,zxsted/scipy,anielsen001/scipy,fredrikw/scipy,felipebetancur/scipy,Kamp9/scipy,gdooper/scipy,petebachant/scipy,chatcannon/scipy,Dapid/scipy,behzadnouri/scipy,witcxc/scipy,teoliphant/scipy,vigna/scipy,FRidh/scipy,scipy/scipy,josephcslater/scipy,zerothi/scipy,efiring/scipy,raoulbq/scipy,rmcgibbo/scipy,mtrbean/scipy,nonhermitian/scipy,chatcannon/scipy,anntzer/scipy,cpaulik/scipy,kleskjr/scipy,pnedunuri/scipy,mhogg/scipy,juliantaylor/scipy,woodscn/scipy,befelix/scipy,jakevdp/scipy,zaxliu/scipy,maciejkula/scipy,scipy/scipy,petebachant/scipy,scipy/scipy,giorgiop/scipy,larsmans/scipy,nvoron23/scipy,Shaswat27/scipy,mtrbean/scipy,Newman101/scipy,lhilt/scipy,Gillu13/scipy,endolith/scipy,felipebetancur/scipy,efiring/scipy,raoulbq/scipy,aarchiba/scipy,ogrisel/scipy,trankmichael/scipy,niknow/scipy,richardotis/scipy,mortonjt/scipy,jonycgn/scipy,matthewalbani/scipy,Gillu13/scipy,WillieMaddox/scipy,nvoron23/scipy,zerothi/scipy,dominicelse/scipy,perimosocordiae/scipy,aman-iitj/scipy,kleskjr/scipy,vanpact/scipy,jor-/scipy,person142/scipy,befelix/scipy,Gillu13/scipy,vigna/scipy,aman-iitj/scipy,jjhelmus/scipy,pschella/scipy,argriffing/scipy,anielsen001/scipy,sauliusl/scipy,tylerjereddy/scipy,vanpact/scipy,aarchiba/scipy,Stefan-Endres/scipy,zxsted/scipy,Eric89GXL/scipy,pbrod/scipy,ogrisel/scipy,jsilter/scipy,scipy/scipy,vanpact/scipy,Newman101/scipy,sargas/scipy,rmcgibbo/scipy,vberaudi/scipy,jamestwebber/scipy,ndchorley/scipy,lukauskas/scipy,pnedunuri/scipy,larsmans/scipy,Kamp9/scipy,mtrbean/scipy,grlee77/scipy,andim/scipy,newemailjdm/scipy,gdooper/scipy,andim/scipy,FRidh/scipy,josephcslater/scipy,newemailjdm/scipy,Kamp9/scipy,haudren/scipy,anielsen001/scipy,jseabold/scipy,richardotis/scipy,arokem/scipy,gfyoung/scipy,anielsen001/scipy,vhaasteren/scipy,vhaasteren/scipy,dominicelse/scipy,ChanderG/scipy,nmayorov/scipy,tylerjereddy/scipy,matthew-brett/scipy,jseabold/scipy,mingwpy/scipy,apbard/scipy,Stefan-Endres/scipy,person142/scipy,Kamp9/scipy,jonycgn/scipy,arokem/scipy,mdhaber/scipy,witcxc/scipy,jsilter/scipy,hainm/scipy,hainm/scipy,mgaitan/scipy,pyramania/scipy,sonnyhu/scipy,WarrenWeckesser/scipy,perimosocordiae/scipy,ogrisel/scipy,mikebenfield/scipy,ndchorley/scipy,maniteja123/scipy,pbrod/scipy,mortonjt/scipy,andyfaff/scipy,Gillu13/scipy,matthewalbani/scipy,rmcgibbo/scipy,ChanderG/scipy,mgaitan/scipy,argriffing/scipy,zerothi/scipy,mdhaber/scipy,Stefan-Endres/scipy,richardotis/scipy,cpaulik/scipy,fredrikw/scipy,piyush0609/scipy,fredrikw/scipy,Gillu13/scipy,trankmichael/scipy,niknow/scipy,andyfaff/scipy,WillieMaddox/scipy,lukauskas/scipy,nvoron23/scipy,sriki18/scipy,minhlongdo/scipy,aeklant/scipy,e-q/scipy,rmcgibbo/scipy,pschella/scipy,ales-erjavec/scipy,lhilt/scipy,mdhaber/scipy,mingwpy/scipy,witcxc/scipy,niknow/scipy,piyush0609/scipy,anntzer/scipy,mortonjt/scipy,kalvdans/scipy,jor-/scipy,sauliusl/scipy,aman-iitj/scipy,jjhelmus/scipy,ortylp/scipy,behzadnouri/scipy,surhudm/scipy,njwilson23/scipy,mdhaber/scipy,lhilt/scipy,teoliphant/scipy,gertingold/scipy,gfyoung/scipy,pizzathief/scipy,josephcslater/scipy,dominicelse/scipy,anntzer/scipy,giorgiop/scipy,andim/scipy,andyfaff/scipy,mortada/scipy,e-q/scipy,vhaasteren/scipy,aarchiba/scipy,teoliphant/scipy,Eric89GXL/scipy,maniteja123/scipy,dch312/scipy,newemailjdm/scipy,efiring/scipy,gef756/scipy,lukauskas/scipy,zaxliu/scipy,Shaswat27/scipy,zaxliu/scipy,Dapid/scipy,surhudm/scipy,minhlongdo/scipy,ales-erjavec/scipy,sonnyhu/scipy,endolith/scipy,mtrbean/scipy,rmcgibbo/scipy,lukauskas/scipy,dominicelse/scipy,behzadnouri/scipy,Shaswat27/scipy,richardotis/scipy,endolith/scipy,Srisai85/scipy,argriffing/scipy,rgommers/scipy,ogrisel/scipy,woodscn/scipy,behzadnouri/scipy,mingwpy/scipy,aman-iitj/scipy,mhogg/scipy,jsilter/scipy,mingwpy/scipy,jonycgn/scipy,Eric89GXL/scipy,mortada/scipy,dch312/scipy,giorgiop/scipy,sriki18/scipy,Srisai85/scipy,jseabold/scipy,sargas/scipy,nmayorov/scipy,Srisai85/scipy,mikebenfield/scipy,efiring/scipy,apbard/scipy,zaxliu/scipy,pizzathief/scipy,grlee77/scipy,pbrod/scipy,minhlongdo/scipy,matthewalbani/scipy,Eric89GXL/scipy,woodscn/scipy,jakevdp/scipy,gef756/scipy,hainm/scipy,WillieMaddox/scipy,teoliphant/scipy,juliantaylor/scipy,newemailjdm/scipy,behzadnouri/scipy,vberaudi/scipy,jakevdp/scipy,kalvdans/scipy,vigna/scipy,andyfaff/scipy,njwilson23/scipy,ortylp/scipy,argriffing/scipy,futurulus/scipy,WarrenWeckesser/scipy,maciejkula/scipy,mortada/scipy,richardotis/scipy,efiring/scipy,nvoron23/scipy,jakevdp/scipy,maciejkula/scipy,vigna/scipy,zaxliu/scipy,juliantaylor/scipy,maniteja123/scipy,ilayn/scipy,aeklant/scipy,befelix/scipy,nvoron23/scipy,Stefan-Endres/scipy,ortylp/scipy,mdhaber/scipy,njwilson23/scipy,Newman101/scipy,josephcslater/scipy,minhlongdo/scipy,sriki18/scipy,FRidh/scipy,Stefan-Endres/scipy,jor-/scipy,pnedunuri/scipy,WarrenWeckesser/scipy,kleskjr/scipy,befelix/scipy,sargas/scipy,sriki18/scipy,zerothi/scipy,gfyoung/scipy,tylerjereddy/scipy,gef756/scipy,Srisai85/scipy,mortada/scipy,ilayn/scipy,pschella/scipy,nmayorov/scipy,felipebetancur/scipy,nmayorov/scipy,mhogg/scipy,gertingold/scipy,matthewalbani/scipy,bkendzior/scipy,larsmans/scipy,arokem/scipy,jseabold/scipy,person142/scipy,bkendzior/scipy,futurulus/scipy,matthewalbani/scipy,anntzer/scipy,rgommers/scipy,mingwpy/scipy,Gillu13/scipy,larsmans/scipy,nonhermitian/scipy,vhaasteren/scipy,aman-iitj/scipy,larsmans/scipy,vberaudi/scipy,andim/scipy,Newman101/scipy,njwilson23/scipy,Srisai85/scipy,cpaulik/scipy,aarchiba/scipy,jseabold/scipy,haudren/scipy,WarrenWeckesser/scipy,kalvdans/scipy,ndchorley/scipy,zaxliu/scipy,gfyoung/scipy,fernand/scipy,mikebenfield/scipy,woodscn/scipy,maniteja123/scipy,person142/scipy,raoulbq/scipy,niknow/scipy,mgaitan/scipy,maciejkula/scipy,matthew-brett/scipy,Dapid/scipy,ndchorley/scipy,ales-erjavec/scipy,zerothi/scipy,endolith/scipy,fredrikw/scipy,vigna/scipy,zxsted/scipy,futurulus/scipy,gertingold/scipy,jamestwebber/scipy,anntzer/scipy,matthew-brett/scipy,perimosocordiae/scipy,efiring/scipy,andyfaff/scipy,pschella/scipy,pschella/scipy,sauliusl/scipy,fredrikw/scipy,gfyoung/scipy,petebachant/scipy,mikebenfield/scipy,rgommers/scipy,fernand/scipy,scipy/scipy,bkendzior/scipy,nonhermitian/scipy,fernand/scipy,zxsted/scipy,mgaitan/scipy,petebachant/scipy,mhogg/scipy,grlee77/scipy,mortonjt/scipy,futurulus/scipy,nvoron23/scipy,sauliusl/scipy,WarrenWeckesser/scipy,pyramania/scipy,bkendzior/scipy,lhilt/scipy,haudren/scipy,apbard/scipy,ales-erjavec/scipy,pbrod/scipy,ortylp/scipy,ChanderG/scipy,andim/scipy,Dapid/scipy,juliantaylor/scipy,apbard/scipy,ales-erjavec/scipy,lhilt/scipy,ndchorley/scipy,raoulbq/scipy,haudren/scipy,nmayorov/scipy,piyush0609/scipy,sauliusl/scipy,mdhaber/scipy,minhlongdo/scipy,piyush0609/scipy,Stefan-Endres/scipy,jamestwebber/scipy,witcxc/scipy,dch312/scipy,gertingold/scipy,raoulbq/scipy,felipebetancur/scipy,niknow/scipy,e-q/scipy,pbrod/scipy,josephcslater/scipy,ortylp/scipy,rmcgibbo/scipy,petebachant/scipy,scipy/scipy,trankmichael/scipy,Newman101/scipy,mtrbean/scipy,giorgiop/scipy
from numpy import * from numpy.testing import * from scipy.weave import inline_tools class TestInline(TestCase): """ These are long running tests... I'd like to benchmark these things somehow. """ @dec.slow def test_exceptions(self): a = 3 code = """ if (a < 2) throw_error(PyExc_ValueError, "the variable 'a' should not be less than 2"); else return_val = PyInt_FromLong(a+1); """ result = inline_tools.inline(code,['a']) assert(result == 4) + ## Unfortunately, it is not always possible to catch distutils compiler + ## errors, since SystemExit is used. Until that is fixed, these tests + ## cannot be run in the same process as the test suite. - try: - a = 1 - result = inline_tools.inline(code,['a']) - assert(1) # should've thrown a ValueError - except ValueError: - pass + ## try: + ## a = 1 + ## result = inline_tools.inline(code,['a']) + ## assert(1) # should've thrown a ValueError + ## except ValueError: + ## pass + - from distutils.errors import DistutilsError, CompileError + ## from distutils.errors import DistutilsError, CompileError - try: + ## try: - a = 'string' + ## a = 'string' - result = inline_tools.inline(code,['a']) + ## result = inline_tools.inline(code,['a']) - assert(1) # should've gotten an error + ## assert(1) # should've gotten an error - except: + ## except: - # ?CompileError is the error reported, but catching it doesn't work + ## # ?CompileError is the error reported, but catching it doesn't work - pass + ## pass if __name__ == "__main__": nose.run(argv=['', __file__])
Disable weave tests that cause compilation failure, since this causes distutils to do a SystemExit, which break the test suite.
## Code Before: from numpy import * from numpy.testing import * from scipy.weave import inline_tools class TestInline(TestCase): """ These are long running tests... I'd like to benchmark these things somehow. """ @dec.slow def test_exceptions(self): a = 3 code = """ if (a < 2) throw_error(PyExc_ValueError, "the variable 'a' should not be less than 2"); else return_val = PyInt_FromLong(a+1); """ result = inline_tools.inline(code,['a']) assert(result == 4) try: a = 1 result = inline_tools.inline(code,['a']) assert(1) # should've thrown a ValueError except ValueError: pass from distutils.errors import DistutilsError, CompileError try: a = 'string' result = inline_tools.inline(code,['a']) assert(1) # should've gotten an error except: # ?CompileError is the error reported, but catching it doesn't work pass if __name__ == "__main__": nose.run(argv=['', __file__]) ## Instruction: Disable weave tests that cause compilation failure, since this causes distutils to do a SystemExit, which break the test suite. ## Code After: from numpy import * from numpy.testing import * from scipy.weave import inline_tools class TestInline(TestCase): """ These are long running tests... I'd like to benchmark these things somehow. """ @dec.slow def test_exceptions(self): a = 3 code = """ if (a < 2) throw_error(PyExc_ValueError, "the variable 'a' should not be less than 2"); else return_val = PyInt_FromLong(a+1); """ result = inline_tools.inline(code,['a']) assert(result == 4) ## Unfortunately, it is not always possible to catch distutils compiler ## errors, since SystemExit is used. Until that is fixed, these tests ## cannot be run in the same process as the test suite. ## try: ## a = 1 ## result = inline_tools.inline(code,['a']) ## assert(1) # should've thrown a ValueError ## except ValueError: ## pass ## from distutils.errors import DistutilsError, CompileError ## try: ## a = 'string' ## result = inline_tools.inline(code,['a']) ## assert(1) # should've gotten an error ## except: ## # ?CompileError is the error reported, but catching it doesn't work ## pass if __name__ == "__main__": nose.run(argv=['', __file__])
// ... existing code ... ## Unfortunately, it is not always possible to catch distutils compiler ## errors, since SystemExit is used. Until that is fixed, these tests ## cannot be run in the same process as the test suite. ## try: ## a = 1 ## result = inline_tools.inline(code,['a']) ## assert(1) # should've thrown a ValueError ## except ValueError: ## pass ## from distutils.errors import DistutilsError, CompileError ## try: ## a = 'string' ## result = inline_tools.inline(code,['a']) ## assert(1) # should've gotten an error ## except: ## # ?CompileError is the error reported, but catching it doesn't work ## pass // ... rest of the code ...
ddd3373ce078cf9bf40da7ebd8591995e819b750
phell/utils.py
phell/utils.py
import sys def to_hex(value): if sys.version_info.major < 3: return value.encode('hex') return "".join("%02x" % b for b in value) def from_hex(value): if sys.version_info.major < 3: return value.decode('hex') return bytes.fromhex(value) # vim: set ts=4 sw=4 tw=80:
import sys def to_hex(value): if sys.version_info.major < 3: return value.encode('hex') return "".join("%02x" % b for b in value) def from_hex(value): if sys.version_info.major < 3: return value.decode('hex') return bytes.fromhex(value) def swap_bytes(value): if sys.version_info.major < 3: return "".join([bytes(b) for b in reversed(value)]) return bytes(reversed(value)) # vim: set ts=4 sw=4 tw=80:
Add function to swap byte order
Add function to swap byte order
Python
mit
bjoernricks/phell
import sys def to_hex(value): if sys.version_info.major < 3: return value.encode('hex') return "".join("%02x" % b for b in value) def from_hex(value): if sys.version_info.major < 3: return value.decode('hex') return bytes.fromhex(value) + def swap_bytes(value): + if sys.version_info.major < 3: + return "".join([bytes(b) for b in reversed(value)]) + return bytes(reversed(value)) + # vim: set ts=4 sw=4 tw=80:
Add function to swap byte order
## Code Before: import sys def to_hex(value): if sys.version_info.major < 3: return value.encode('hex') return "".join("%02x" % b for b in value) def from_hex(value): if sys.version_info.major < 3: return value.decode('hex') return bytes.fromhex(value) # vim: set ts=4 sw=4 tw=80: ## Instruction: Add function to swap byte order ## Code After: import sys def to_hex(value): if sys.version_info.major < 3: return value.encode('hex') return "".join("%02x" % b for b in value) def from_hex(value): if sys.version_info.major < 3: return value.decode('hex') return bytes.fromhex(value) def swap_bytes(value): if sys.version_info.major < 3: return "".join([bytes(b) for b in reversed(value)]) return bytes(reversed(value)) # vim: set ts=4 sw=4 tw=80:
// ... existing code ... def swap_bytes(value): if sys.version_info.major < 3: return "".join([bytes(b) for b in reversed(value)]) return bytes(reversed(value)) # vim: set ts=4 sw=4 tw=80: // ... rest of the code ...
aefa8a3d6d4c809c7e470b22a0c9fb2c0875ba8b
project/project/urls.py
project/project/urls.py
from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from django.conf.urls.static import static from django.contrib.auth import views urlpatterns = [ url( r'^silk/', include('silk.urls', namespace='silk', app_name='silk') ), url( r'^example_app/', include('example_app.urls', namespace='example_app', app_name='example_app') ), url(r'^admin/', include(admin.site.urls)), ] urlpatterns += [ url( r'^login/$', views.login, {'template_name': 'example_app/login.html'}, name='login'), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + \ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from django.conf.urls.static import static from django.contrib.auth import views urlpatterns = [ url( r'^silk/', include('silk.urls', namespace='silk') ), url( r'^example_app/', include('example_app.urls', namespace='example_app') ), url( r'^admin/', admin.site.urls ), ] urlpatterns += [ url( r'^login/$', views.login, {'template_name': 'example_app/login.html'}, name='login'), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + \ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Remove unneeded app_name from test project to be django 2 compatible
Remove unneeded app_name from test project to be django 2 compatible
Python
mit
crunchr/silk,mtford90/silk,jazzband/silk,crunchr/silk,mtford90/silk,jazzband/silk,crunchr/silk,django-silk/silk,django-silk/silk,jazzband/silk,django-silk/silk,crunchr/silk,mtford90/silk,jazzband/silk,mtford90/silk,django-silk/silk
from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from django.conf.urls.static import static from django.contrib.auth import views urlpatterns = [ url( r'^silk/', - include('silk.urls', namespace='silk', app_name='silk') + include('silk.urls', namespace='silk') ), url( r'^example_app/', - include('example_app.urls', namespace='example_app', app_name='example_app') + include('example_app.urls', namespace='example_app') ), - url(r'^admin/', include(admin.site.urls)), + url( + r'^admin/', + admin.site.urls + ), ] urlpatterns += [ url( r'^login/$', views.login, {'template_name': 'example_app/login.html'}, name='login'), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + \ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Remove unneeded app_name from test project to be django 2 compatible
## Code Before: from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from django.conf.urls.static import static from django.contrib.auth import views urlpatterns = [ url( r'^silk/', include('silk.urls', namespace='silk', app_name='silk') ), url( r'^example_app/', include('example_app.urls', namespace='example_app', app_name='example_app') ), url(r'^admin/', include(admin.site.urls)), ] urlpatterns += [ url( r'^login/$', views.login, {'template_name': 'example_app/login.html'}, name='login'), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + \ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ## Instruction: Remove unneeded app_name from test project to be django 2 compatible ## Code After: from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from django.conf.urls.static import static from django.contrib.auth import views urlpatterns = [ url( r'^silk/', include('silk.urls', namespace='silk') ), url( r'^example_app/', include('example_app.urls', namespace='example_app') ), url( r'^admin/', admin.site.urls ), ] urlpatterns += [ url( r'^login/$', views.login, {'template_name': 'example_app/login.html'}, name='login'), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + \ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# ... existing code ... r'^silk/', include('silk.urls', namespace='silk') ), # ... modified code ... r'^example_app/', include('example_app.urls', namespace='example_app') ), url( r'^admin/', admin.site.urls ), ] # ... rest of the code ...
d565786278eaf32761957dd1e064a5d549ef3ab4
praw/models/reddit/mixins/savable.py
praw/models/reddit/mixins/savable.py
"""Provide the SavableMixin class.""" from ....const import API_PATH class SavableMixin(object): """Interface for RedditBase classes that can be saved.""" def save(self, category=None): """Save the object. :param category: The category to save to (Default: None). """ self._reddit.post(API_PATH['save'], data={'category': category, 'id': self.fullname}) def unsave(self): """Unsave the object.""" self._reddit.post(API_PATH['unsave'], data={'id': self.fullname})
"""Provide the SavableMixin class.""" from ....const import API_PATH class SavableMixin(object): """Interface for RedditBase classes that can be saved.""" def save(self, category=None): """Save the object. :param category: (Gold) The category to save to (Default: None). If your user does not have gold this value is ignored by Reddit. """ self._reddit.post(API_PATH['save'], data={'category': category, 'id': self.fullname}) def unsave(self): """Unsave the object.""" self._reddit.post(API_PATH['unsave'], data={'id': self.fullname})
Clarify that category is a gold feature for saving an item
Clarify that category is a gold feature for saving an item
Python
bsd-2-clause
13steinj/praw,RGood/praw,RGood/praw,darthkedrik/praw,darthkedrik/praw,leviroth/praw,gschizas/praw,leviroth/praw,gschizas/praw,praw-dev/praw,nmtake/praw,praw-dev/praw,nmtake/praw,13steinj/praw
"""Provide the SavableMixin class.""" from ....const import API_PATH class SavableMixin(object): """Interface for RedditBase classes that can be saved.""" def save(self, category=None): """Save the object. - :param category: The category to save to (Default: None). + :param category: (Gold) The category to save to (Default: + None). If your user does not have gold this value is ignored by + Reddit. """ self._reddit.post(API_PATH['save'], data={'category': category, 'id': self.fullname}) def unsave(self): """Unsave the object.""" self._reddit.post(API_PATH['unsave'], data={'id': self.fullname})
Clarify that category is a gold feature for saving an item
## Code Before: """Provide the SavableMixin class.""" from ....const import API_PATH class SavableMixin(object): """Interface for RedditBase classes that can be saved.""" def save(self, category=None): """Save the object. :param category: The category to save to (Default: None). """ self._reddit.post(API_PATH['save'], data={'category': category, 'id': self.fullname}) def unsave(self): """Unsave the object.""" self._reddit.post(API_PATH['unsave'], data={'id': self.fullname}) ## Instruction: Clarify that category is a gold feature for saving an item ## Code After: """Provide the SavableMixin class.""" from ....const import API_PATH class SavableMixin(object): """Interface for RedditBase classes that can be saved.""" def save(self, category=None): """Save the object. :param category: (Gold) The category to save to (Default: None). If your user does not have gold this value is ignored by Reddit. """ self._reddit.post(API_PATH['save'], data={'category': category, 'id': self.fullname}) def unsave(self): """Unsave the object.""" self._reddit.post(API_PATH['unsave'], data={'id': self.fullname})
// ... existing code ... :param category: (Gold) The category to save to (Default: None). If your user does not have gold this value is ignored by Reddit. // ... rest of the code ...
61398045cb6bb5a0849fd203ebbe85bfa305ea60
favicon/templatetags/favtags.py
favicon/templatetags/favtags.py
from django import template from django.utils.safestring import mark_safe from favicon.models import Favicon, config register = template.Library() @register.simple_tag(takes_context=True) def placeFavicon(context): """ Gets Favicon-URL for the Model. Template Syntax: {% placeFavicon %} """ fav = Favicon.objects.filter(isFavicon=True).first() if not fav: return '<!-- no favicon -->' html = '' for rel in config: for size in sorted(config[rel], reverse=True): n = fav.get_favicon(size=size, rel=rel) html += '<link rel="%s" sizes="%sx%s" href="%s"/>' % ( n.rel, n.size, n.size, n.faviconImage.url) default_fav = fav.get_favicon(size=32, rel='shortcut icon') html += '<link rel="%s" sizes="%sx%s" href="%s"/>' % ( default_fav.rel, default_fav.size, default_fav.size, default_fav.faviconImage.url) return mark_safe(html)
from django import template from django.utils.safestring import mark_safe from favicon.models import Favicon, config register = template.Library() @register.simple_tag(takes_context=True) def placeFavicon(context): """ Gets Favicon-URL for the Model. Template Syntax: {% placeFavicon %} """ fav = Favicon.objects.filter(isFavicon=True).first() if not fav: return mark_safe('<!-- no favicon -->') html = '' for rel in config: for size in sorted(config[rel], reverse=True): n = fav.get_favicon(size=size, rel=rel) html += '<link rel="%s" sizes="%sx%s" href="%s"/>' % ( n.rel, n.size, n.size, n.faviconImage.url) default_fav = fav.get_favicon(size=32, rel='shortcut icon') html += '<link rel="%s" sizes="%sx%s" href="%s"/>' % ( default_fav.rel, default_fav.size, default_fav.size, default_fav.faviconImage.url) return mark_safe(html)
Mark comment as safe. Otherwise it is displayed.
Mark comment as safe. Otherwise it is displayed.
Python
mit
arteria/django-favicon-plus
from django import template from django.utils.safestring import mark_safe from favicon.models import Favicon, config register = template.Library() @register.simple_tag(takes_context=True) def placeFavicon(context): """ Gets Favicon-URL for the Model. Template Syntax: {% placeFavicon %} """ fav = Favicon.objects.filter(isFavicon=True).first() if not fav: - return '<!-- no favicon -->' + return mark_safe('<!-- no favicon -->') html = '' for rel in config: for size in sorted(config[rel], reverse=True): n = fav.get_favicon(size=size, rel=rel) html += '<link rel="%s" sizes="%sx%s" href="%s"/>' % ( n.rel, n.size, n.size, n.faviconImage.url) default_fav = fav.get_favicon(size=32, rel='shortcut icon') html += '<link rel="%s" sizes="%sx%s" href="%s"/>' % ( default_fav.rel, default_fav.size, default_fav.size, default_fav.faviconImage.url) return mark_safe(html)
Mark comment as safe. Otherwise it is displayed.
## Code Before: from django import template from django.utils.safestring import mark_safe from favicon.models import Favicon, config register = template.Library() @register.simple_tag(takes_context=True) def placeFavicon(context): """ Gets Favicon-URL for the Model. Template Syntax: {% placeFavicon %} """ fav = Favicon.objects.filter(isFavicon=True).first() if not fav: return '<!-- no favicon -->' html = '' for rel in config: for size in sorted(config[rel], reverse=True): n = fav.get_favicon(size=size, rel=rel) html += '<link rel="%s" sizes="%sx%s" href="%s"/>' % ( n.rel, n.size, n.size, n.faviconImage.url) default_fav = fav.get_favicon(size=32, rel='shortcut icon') html += '<link rel="%s" sizes="%sx%s" href="%s"/>' % ( default_fav.rel, default_fav.size, default_fav.size, default_fav.faviconImage.url) return mark_safe(html) ## Instruction: Mark comment as safe. Otherwise it is displayed. ## Code After: from django import template from django.utils.safestring import mark_safe from favicon.models import Favicon, config register = template.Library() @register.simple_tag(takes_context=True) def placeFavicon(context): """ Gets Favicon-URL for the Model. Template Syntax: {% placeFavicon %} """ fav = Favicon.objects.filter(isFavicon=True).first() if not fav: return mark_safe('<!-- no favicon -->') html = '' for rel in config: for size in sorted(config[rel], reverse=True): n = fav.get_favicon(size=size, rel=rel) html += '<link rel="%s" sizes="%sx%s" href="%s"/>' % ( n.rel, n.size, n.size, n.faviconImage.url) default_fav = fav.get_favicon(size=32, rel='shortcut icon') html += '<link rel="%s" sizes="%sx%s" href="%s"/>' % ( default_fav.rel, default_fav.size, default_fav.size, default_fav.faviconImage.url) return mark_safe(html)
... if not fav: return mark_safe('<!-- no favicon -->') html = '' ...
0c89a78d3a0574ef491d3695366cd786b4c3f950
indico/migrations/versions/20200904_1543_f37d509e221c_add_user_profile_picture_column.py
indico/migrations/versions/20200904_1543_f37d509e221c_add_user_profile_picture_column.py
import sqlalchemy as sa from alembic import op from indico.core.db.sqlalchemy import PyIntEnum from indico.modules.users.models.users import ProfilePictureSource # revision identifiers, used by Alembic. revision = 'f37d509e221c' down_revision = 'c997dc927fbc' branch_labels = None depends_on = None def upgrade(): op.add_column('users', sa.Column('picture_source', PyIntEnum(ProfilePictureSource), nullable=False, server_default='0'), schema='users') op.alter_column('users', 'picture_source', server_default=None, schema='users') op.execute('UPDATE users.users SET picture_source = 3 WHERE picture IS NOT NULL') def downgrade(): op.drop_column('users', 'picture_source', schema='users')
from enum import Enum import sqlalchemy as sa from alembic import op from indico.core.db.sqlalchemy import PyIntEnum # revision identifiers, used by Alembic. revision = 'f37d509e221c' down_revision = 'c997dc927fbc' branch_labels = None depends_on = None class _ProfilePictureSource(int, Enum): standard = 0 identicon = 1 gravatar = 2 custom = 3 def upgrade(): op.add_column('users', sa.Column('picture_source', PyIntEnum(_ProfilePictureSource), nullable=False, server_default='0'), schema='users') op.alter_column('users', 'picture_source', server_default=None, schema='users') op.execute('UPDATE users.users SET picture_source = 3 WHERE picture IS NOT NULL') def downgrade(): op.drop_column('users', 'picture_source', schema='users')
Use embedded enum in alembic revision
Use embedded enum in alembic revision Unlikely to matter here but like this it will work correctly even in a future where someone may add new sources to the original enum (in that case this particular revision should not add those newer ones, which would be the case when using the imported enum)
Python
mit
DirkHoffmann/indico,indico/indico,DirkHoffmann/indico,ThiefMaster/indico,indico/indico,indico/indico,pferreir/indico,ThiefMaster/indico,pferreir/indico,pferreir/indico,pferreir/indico,indico/indico,ThiefMaster/indico,DirkHoffmann/indico,DirkHoffmann/indico,ThiefMaster/indico
+ + from enum import Enum import sqlalchemy as sa from alembic import op from indico.core.db.sqlalchemy import PyIntEnum - from indico.modules.users.models.users import ProfilePictureSource # revision identifiers, used by Alembic. revision = 'f37d509e221c' down_revision = 'c997dc927fbc' branch_labels = None depends_on = None + class _ProfilePictureSource(int, Enum): + standard = 0 + identicon = 1 + gravatar = 2 + custom = 3 + + def upgrade(): op.add_column('users', - sa.Column('picture_source', PyIntEnum(ProfilePictureSource), nullable=False, server_default='0'), + sa.Column('picture_source', PyIntEnum(_ProfilePictureSource), nullable=False, server_default='0'), schema='users') op.alter_column('users', 'picture_source', server_default=None, schema='users') op.execute('UPDATE users.users SET picture_source = 3 WHERE picture IS NOT NULL') def downgrade(): op.drop_column('users', 'picture_source', schema='users')
Use embedded enum in alembic revision
## Code Before: import sqlalchemy as sa from alembic import op from indico.core.db.sqlalchemy import PyIntEnum from indico.modules.users.models.users import ProfilePictureSource # revision identifiers, used by Alembic. revision = 'f37d509e221c' down_revision = 'c997dc927fbc' branch_labels = None depends_on = None def upgrade(): op.add_column('users', sa.Column('picture_source', PyIntEnum(ProfilePictureSource), nullable=False, server_default='0'), schema='users') op.alter_column('users', 'picture_source', server_default=None, schema='users') op.execute('UPDATE users.users SET picture_source = 3 WHERE picture IS NOT NULL') def downgrade(): op.drop_column('users', 'picture_source', schema='users') ## Instruction: Use embedded enum in alembic revision ## Code After: from enum import Enum import sqlalchemy as sa from alembic import op from indico.core.db.sqlalchemy import PyIntEnum # revision identifiers, used by Alembic. revision = 'f37d509e221c' down_revision = 'c997dc927fbc' branch_labels = None depends_on = None class _ProfilePictureSource(int, Enum): standard = 0 identicon = 1 gravatar = 2 custom = 3 def upgrade(): op.add_column('users', sa.Column('picture_source', PyIntEnum(_ProfilePictureSource), nullable=False, server_default='0'), schema='users') op.alter_column('users', 'picture_source', server_default=None, schema='users') op.execute('UPDATE users.users SET picture_source = 3 WHERE picture IS NOT NULL') def downgrade(): op.drop_column('users', 'picture_source', schema='users')
# ... existing code ... from enum import Enum # ... modified code ... from indico.core.db.sqlalchemy import PyIntEnum ... class _ProfilePictureSource(int, Enum): standard = 0 identicon = 1 gravatar = 2 custom = 3 def upgrade(): ... op.add_column('users', sa.Column('picture_source', PyIntEnum(_ProfilePictureSource), nullable=False, server_default='0'), schema='users') # ... rest of the code ...
027178a21083ceaa4151806e877a58ec7792f625
pysswords/__main__.py
pysswords/__main__.py
import argparse from getpass import getpass from pysswords.db import Database from pysswords.crypt import CryptOptions def get_args(): parser = argparse.ArgumentParser() parser.add_argument('path') parser.add_argument('--create', action='store_true') parser.add_argument('--password', default=None) parser.add_argument('--salt', default=None) parser.add_argument('--iterations', default=100000) return parser.parse_args() def main(args=None): if not args: args = get_args() if not args.password: args.password = getpass() crypt_options = CryptOptions( password=args.password, salt=args.salt, iterations=args.iterations ) if args.create: Database.create(args.path, crypt_options) elif args.add: database = Database(args.path, crypt_options) database.add_credential(args.path, crypt_options) if __name__ == "__main__": main()
import argparse from getpass import getpass from pysswords.db import Database from pysswords.crypt import CryptOptions def get_args(): parser = argparse.ArgumentParser() main_group = parser.add_argument_group('Main options') main_group.add_argument('path', help='Path to database file') main_group.add_argument('--create', action='store_true', help='Create a new encrypted password database') crypt_group = parser.add_argument_group('Encryption options') crypt_group.add_argument('--password', default=None, help='Password to open database') crypt_group.add_argument('--salt', default=None, help='Salt for encryption') crypt_group.add_argument('--iterations', default=100000, help='Number of iterations for encryption') return parser.parse_args() def main(args=None): if not args: args = get_args() if not args.password: args.password = getpass() crypt_options = CryptOptions( password=args.password, salt=args.salt, iterations=args.iterations ) if args.create: Database.create(args.path, crypt_options) elif args.add: database = Database(args.path, crypt_options) database.add_credential(args.path, crypt_options) if __name__ == "__main__": main()
Refactor get args function from console interface
Refactor get args function from console interface
Python
mit
eiginn/passpie,scorphus/passpie,marcwebbie/passpie,scorphus/passpie,marcwebbie/pysswords,eiginn/passpie,marcwebbie/passpie
import argparse from getpass import getpass from pysswords.db import Database from pysswords.crypt import CryptOptions def get_args(): parser = argparse.ArgumentParser() - parser.add_argument('path') + main_group = parser.add_argument_group('Main options') + main_group.add_argument('path', help='Path to database file') - parser.add_argument('--create', action='store_true') + main_group.add_argument('--create', action='store_true', + help='Create a new encrypted password database') + + crypt_group = parser.add_argument_group('Encryption options') - parser.add_argument('--password', default=None) + crypt_group.add_argument('--password', default=None, + help='Password to open database') - parser.add_argument('--salt', default=None) + crypt_group.add_argument('--salt', default=None, + help='Salt for encryption') - parser.add_argument('--iterations', default=100000) + crypt_group.add_argument('--iterations', default=100000, + help='Number of iterations for encryption') return parser.parse_args() def main(args=None): if not args: args = get_args() if not args.password: args.password = getpass() crypt_options = CryptOptions( password=args.password, salt=args.salt, iterations=args.iterations ) if args.create: Database.create(args.path, crypt_options) elif args.add: database = Database(args.path, crypt_options) database.add_credential(args.path, crypt_options) if __name__ == "__main__": main()
Refactor get args function from console interface
## Code Before: import argparse from getpass import getpass from pysswords.db import Database from pysswords.crypt import CryptOptions def get_args(): parser = argparse.ArgumentParser() parser.add_argument('path') parser.add_argument('--create', action='store_true') parser.add_argument('--password', default=None) parser.add_argument('--salt', default=None) parser.add_argument('--iterations', default=100000) return parser.parse_args() def main(args=None): if not args: args = get_args() if not args.password: args.password = getpass() crypt_options = CryptOptions( password=args.password, salt=args.salt, iterations=args.iterations ) if args.create: Database.create(args.path, crypt_options) elif args.add: database = Database(args.path, crypt_options) database.add_credential(args.path, crypt_options) if __name__ == "__main__": main() ## Instruction: Refactor get args function from console interface ## Code After: import argparse from getpass import getpass from pysswords.db import Database from pysswords.crypt import CryptOptions def get_args(): parser = argparse.ArgumentParser() main_group = parser.add_argument_group('Main options') main_group.add_argument('path', help='Path to database file') main_group.add_argument('--create', action='store_true', help='Create a new encrypted password database') crypt_group = parser.add_argument_group('Encryption options') crypt_group.add_argument('--password', default=None, help='Password to open database') crypt_group.add_argument('--salt', default=None, help='Salt for encryption') crypt_group.add_argument('--iterations', default=100000, help='Number of iterations for encryption') return parser.parse_args() def main(args=None): if not args: args = get_args() if not args.password: args.password = getpass() crypt_options = CryptOptions( password=args.password, salt=args.salt, iterations=args.iterations ) if args.create: Database.create(args.path, crypt_options) elif args.add: database = Database(args.path, crypt_options) database.add_credential(args.path, crypt_options) if __name__ == "__main__": main()
... parser = argparse.ArgumentParser() main_group = parser.add_argument_group('Main options') main_group.add_argument('path', help='Path to database file') main_group.add_argument('--create', action='store_true', help='Create a new encrypted password database') crypt_group = parser.add_argument_group('Encryption options') crypt_group.add_argument('--password', default=None, help='Password to open database') crypt_group.add_argument('--salt', default=None, help='Salt for encryption') crypt_group.add_argument('--iterations', default=100000, help='Number of iterations for encryption') ...
5daef3041ced3e8a3fc8e9d7d64ab43607bb24ae
allauth/socialaccount/providers/feedly/views.py
allauth/socialaccount/providers/feedly/views.py
from __future__ import unicode_literals import requests from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter, OAuth2LoginView, OAuth2CallbackView) from .provider import FeedlyProvider class FeedlyOAuth2Adapter(OAuth2Adapter): provider_id = FeedlyProvider.id access_token_url = 'https://cloud.feedly.com/v3/auth/token' authorize_url = 'https://cloud.feedly.com/v3/auth/auth' profile_url = 'https://cloud.feedly.com/v3/profile' def complete_login(self, request, app, token, **kwargs): headers = {'Authorization': 'OAuth {0}'.format(token.token)} resp = requests.get(self.profile_url, headers=headers) extra_data = resp.json() return self.get_provider().sociallogin_from_response(request, extra_data) oauth2_login = OAuth2LoginView.adapter_view(FeedlyOAuth2Adapter) oauth2_callback = OAuth2CallbackView.adapter_view(FeedlyOAuth2Adapter)
from __future__ import unicode_literals import requests from allauth.socialaccount import app_settings from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter, OAuth2LoginView, OAuth2CallbackView) from .provider import FeedlyProvider class FeedlyOAuth2Adapter(OAuth2Adapter): provider_id = FeedlyProvider.id access_token_url = 'https://%s/v3/auth/token' % settings.get('FEEDLY_HOST', 'cloud.feedly.com') authorize_url = 'https://%s/v3/auth/auth' % settings.get('FEEDLY_HOST', 'cloud.feedly.com') profile_url = 'https://%s/v3/profile' % settings.get('FEEDLY_HOST', 'cloud.feedly.com') access_token_url = 'https://%s/oauth' % (settings.get( 'EVERNOTE_HOSTNAME', 'sandbox.evernote.com')) def complete_login(self, request, app, token, **kwargs): headers = {'Authorization': 'OAuth {0}'.format(token.token)} resp = requests.get(self.profile_url, headers=headers) extra_data = resp.json() return self.get_provider().sociallogin_from_response(request, extra_data) oauth2_login = OAuth2LoginView.adapter_view(FeedlyOAuth2Adapter) oauth2_callback = OAuth2CallbackView.adapter_view(FeedlyOAuth2Adapter)
Add option FEEDLY_HOST for feedly.com provider
Add option FEEDLY_HOST for feedly.com provider
Python
mit
wli/django-allauth,rsalmaso/django-allauth,lukeburden/django-allauth,spool/django-allauth,pennersr/django-allauth,rsalmaso/django-allauth,lukeburden/django-allauth,bittner/django-allauth,AltSchool/django-allauth,joshowen/django-allauth,lukeburden/django-allauth,bittner/django-allauth,jwhitlock/django-allauth,jwhitlock/django-allauth,pztrick/django-allauth,AltSchool/django-allauth,jwhitlock/django-allauth,spool/django-allauth,pennersr/django-allauth,joshowen/django-allauth,wli/django-allauth,pztrick/django-allauth,rsalmaso/django-allauth,joshowen/django-allauth,bittner/django-allauth,nimbis/django-allauth,pztrick/django-allauth,spool/django-allauth,AltSchool/django-allauth,nimbis/django-allauth,pennersr/django-allauth,wli/django-allauth,nimbis/django-allauth
from __future__ import unicode_literals import requests + from allauth.socialaccount import app_settings from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter, OAuth2LoginView, OAuth2CallbackView) from .provider import FeedlyProvider class FeedlyOAuth2Adapter(OAuth2Adapter): provider_id = FeedlyProvider.id - access_token_url = 'https://cloud.feedly.com/v3/auth/token' - authorize_url = 'https://cloud.feedly.com/v3/auth/auth' - profile_url = 'https://cloud.feedly.com/v3/profile' + access_token_url = 'https://%s/v3/auth/token' % settings.get('FEEDLY_HOST', 'cloud.feedly.com') + authorize_url = 'https://%s/v3/auth/auth' % settings.get('FEEDLY_HOST', 'cloud.feedly.com') + profile_url = 'https://%s/v3/profile' % settings.get('FEEDLY_HOST', 'cloud.feedly.com') + + + access_token_url = 'https://%s/oauth' % (settings.get( + 'EVERNOTE_HOSTNAME', + 'sandbox.evernote.com')) def complete_login(self, request, app, token, **kwargs): headers = {'Authorization': 'OAuth {0}'.format(token.token)} resp = requests.get(self.profile_url, headers=headers) extra_data = resp.json() return self.get_provider().sociallogin_from_response(request, extra_data) oauth2_login = OAuth2LoginView.adapter_view(FeedlyOAuth2Adapter) oauth2_callback = OAuth2CallbackView.adapter_view(FeedlyOAuth2Adapter)
Add option FEEDLY_HOST for feedly.com provider
## Code Before: from __future__ import unicode_literals import requests from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter, OAuth2LoginView, OAuth2CallbackView) from .provider import FeedlyProvider class FeedlyOAuth2Adapter(OAuth2Adapter): provider_id = FeedlyProvider.id access_token_url = 'https://cloud.feedly.com/v3/auth/token' authorize_url = 'https://cloud.feedly.com/v3/auth/auth' profile_url = 'https://cloud.feedly.com/v3/profile' def complete_login(self, request, app, token, **kwargs): headers = {'Authorization': 'OAuth {0}'.format(token.token)} resp = requests.get(self.profile_url, headers=headers) extra_data = resp.json() return self.get_provider().sociallogin_from_response(request, extra_data) oauth2_login = OAuth2LoginView.adapter_view(FeedlyOAuth2Adapter) oauth2_callback = OAuth2CallbackView.adapter_view(FeedlyOAuth2Adapter) ## Instruction: Add option FEEDLY_HOST for feedly.com provider ## Code After: from __future__ import unicode_literals import requests from allauth.socialaccount import app_settings from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter, OAuth2LoginView, OAuth2CallbackView) from .provider import FeedlyProvider class FeedlyOAuth2Adapter(OAuth2Adapter): provider_id = FeedlyProvider.id access_token_url = 'https://%s/v3/auth/token' % settings.get('FEEDLY_HOST', 'cloud.feedly.com') authorize_url = 'https://%s/v3/auth/auth' % settings.get('FEEDLY_HOST', 'cloud.feedly.com') profile_url = 'https://%s/v3/profile' % settings.get('FEEDLY_HOST', 'cloud.feedly.com') access_token_url = 'https://%s/oauth' % (settings.get( 'EVERNOTE_HOSTNAME', 'sandbox.evernote.com')) def complete_login(self, request, app, token, **kwargs): headers = {'Authorization': 'OAuth {0}'.format(token.token)} resp = requests.get(self.profile_url, headers=headers) extra_data = resp.json() return self.get_provider().sociallogin_from_response(request, extra_data) oauth2_login = OAuth2LoginView.adapter_view(FeedlyOAuth2Adapter) oauth2_callback = OAuth2CallbackView.adapter_view(FeedlyOAuth2Adapter)
# ... existing code ... import requests from allauth.socialaccount import app_settings from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter, # ... modified code ... provider_id = FeedlyProvider.id access_token_url = 'https://%s/v3/auth/token' % settings.get('FEEDLY_HOST', 'cloud.feedly.com') authorize_url = 'https://%s/v3/auth/auth' % settings.get('FEEDLY_HOST', 'cloud.feedly.com') profile_url = 'https://%s/v3/profile' % settings.get('FEEDLY_HOST', 'cloud.feedly.com') access_token_url = 'https://%s/oauth' % (settings.get( 'EVERNOTE_HOSTNAME', 'sandbox.evernote.com')) # ... rest of the code ...
621c69b22c6364020cf1ed66e4563bd7b43263fc
src/pytest_django_casperjs/fixtures.py
src/pytest_django_casperjs/fixtures.py
import os import pytest from pytest_django.lazy_django import skip_if_no_django @pytest.fixture(scope='session') def casper_js(request): skip_if_no_django() from pytest_django_casperjs.helper import CasperJSLiveServer addr = request.config.getvalue('liveserver') if not addr: addr = os.getenv('DJANGO_TEST_LIVE_SERVER_ADDRESS') if not addr: addr = 'localhost:8081,8100-8200' server = CasperJSLiveServer(addr) request.addfinalizer(server.stop) return server @pytest.fixture(autouse=True, scope='function') def _casper_js_live_server_helper(request): if 'capser_js' in request.funcargnames: request.getfuncargvalue('transactional_db')
import os import pytest from pytest_django.lazy_django import skip_if_no_django @pytest.fixture(scope='session') def casper_js(request): skip_if_no_django() from pytest_django_casperjs.helper import CasperJSLiveServer addr = request.config.getvalue('liveserver') if not addr: addr = os.getenv('DJANGO_TEST_LIVE_SERVER_ADDRESS') if not addr: addr = 'localhost:8081,8100-8200' server = CasperJSLiveServer(addr) request.addfinalizer(server.stop) return server
Remove the helper-fixture, we make transactions explicit. Will write documentation about that
Remove the helper-fixture, we make transactions explicit. Will write documentation about that
Python
bsd-3-clause
EnTeQuAk/pytest-django-casperjs
import os import pytest from pytest_django.lazy_django import skip_if_no_django @pytest.fixture(scope='session') def casper_js(request): skip_if_no_django() from pytest_django_casperjs.helper import CasperJSLiveServer addr = request.config.getvalue('liveserver') if not addr: addr = os.getenv('DJANGO_TEST_LIVE_SERVER_ADDRESS') if not addr: addr = 'localhost:8081,8100-8200' server = CasperJSLiveServer(addr) request.addfinalizer(server.stop) return server - - @pytest.fixture(autouse=True, scope='function') - def _casper_js_live_server_helper(request): - if 'capser_js' in request.funcargnames: - request.getfuncargvalue('transactional_db') -
Remove the helper-fixture, we make transactions explicit. Will write documentation about that
## Code Before: import os import pytest from pytest_django.lazy_django import skip_if_no_django @pytest.fixture(scope='session') def casper_js(request): skip_if_no_django() from pytest_django_casperjs.helper import CasperJSLiveServer addr = request.config.getvalue('liveserver') if not addr: addr = os.getenv('DJANGO_TEST_LIVE_SERVER_ADDRESS') if not addr: addr = 'localhost:8081,8100-8200' server = CasperJSLiveServer(addr) request.addfinalizer(server.stop) return server @pytest.fixture(autouse=True, scope='function') def _casper_js_live_server_helper(request): if 'capser_js' in request.funcargnames: request.getfuncargvalue('transactional_db') ## Instruction: Remove the helper-fixture, we make transactions explicit. Will write documentation about that ## Code After: import os import pytest from pytest_django.lazy_django import skip_if_no_django @pytest.fixture(scope='session') def casper_js(request): skip_if_no_django() from pytest_django_casperjs.helper import CasperJSLiveServer addr = request.config.getvalue('liveserver') if not addr: addr = os.getenv('DJANGO_TEST_LIVE_SERVER_ADDRESS') if not addr: addr = 'localhost:8081,8100-8200' server = CasperJSLiveServer(addr) request.addfinalizer(server.stop) return server
... return server ...
a2430b67423ce036d2a96541e86d356ace04db69
Twitch/cogs/words.py
Twitch/cogs/words.py
from twitchio.ext import commands @commands.cog() class Words: def __init__(self, bot): self.bot = bot @commands.command() async def audiodefine(self, ctx, word): url = f"http://api.wordnik.com:80/v4/word.json/{word}/audio" params = {"useCanonical": "false", "limit": 1, "api_key": self.bot.WORDNIK_API_KEY} async with self.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.json() if data: await ctx.send(f"{data[0]['word'].capitalize()}: {data[0]['fileUrl']}") else: await ctx.send("Word or audio not found.") @commands.command() async def define(self, ctx, word): url = f"http://api.wordnik.com:80/v4/word.json/{word}/definitions" params = {"limit": 1, "includeRelated": "false", "useCanonical": "false", "includeTags": "false", "api_key": self.bot.WORDNIK_API_KEY} async with self.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.json() if data: await ctx.send(data[0]["word"].capitalize() + ": " + data[0]["text"]) else: await ctx.send("Definition not found.")
from twitchio.ext import commands @commands.cog() class Words: def __init__(self, bot): self.bot = bot @commands.command() async def audiodefine(self, ctx, word): url = f"http://api.wordnik.com:80/v4/word.json/{word}/audio" params = {"useCanonical": "false", "limit": 1, "api_key": self.bot.WORDNIK_API_KEY} async with self.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.json() if data: await ctx.send(f"{data[0]['word'].capitalize()}: {data[0]['fileUrl']}") else: await ctx.send("Word or audio not found.") @commands.command() async def define(self, ctx, word): url = f"http://api.wordnik.com:80/v4/word.json/{word}/definitions" params = {"limit": 1, "includeRelated": "false", "useCanonical": "false", "includeTags": "false", "api_key": self.bot.WORDNIK_API_KEY} async with self.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.json() if data: await ctx.send(f"{data[0]['word'].capitalize()}: {data[0]['text']}") else: await ctx.send("Definition not found.")
Use f-string for define command
[TwitchIO] Use f-string for define command
Python
mit
Harmon758/Harmonbot,Harmon758/Harmonbot
from twitchio.ext import commands @commands.cog() class Words: def __init__(self, bot): self.bot = bot @commands.command() async def audiodefine(self, ctx, word): url = f"http://api.wordnik.com:80/v4/word.json/{word}/audio" params = {"useCanonical": "false", "limit": 1, "api_key": self.bot.WORDNIK_API_KEY} async with self.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.json() if data: await ctx.send(f"{data[0]['word'].capitalize()}: {data[0]['fileUrl']}") else: await ctx.send("Word or audio not found.") @commands.command() async def define(self, ctx, word): url = f"http://api.wordnik.com:80/v4/word.json/{word}/definitions" params = {"limit": 1, "includeRelated": "false", "useCanonical": "false", "includeTags": "false", "api_key": self.bot.WORDNIK_API_KEY} async with self.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.json() if data: - await ctx.send(data[0]["word"].capitalize() + ": " + data[0]["text"]) + await ctx.send(f"{data[0]['word'].capitalize()}: {data[0]['text']}") else: await ctx.send("Definition not found.")
Use f-string for define command
## Code Before: from twitchio.ext import commands @commands.cog() class Words: def __init__(self, bot): self.bot = bot @commands.command() async def audiodefine(self, ctx, word): url = f"http://api.wordnik.com:80/v4/word.json/{word}/audio" params = {"useCanonical": "false", "limit": 1, "api_key": self.bot.WORDNIK_API_KEY} async with self.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.json() if data: await ctx.send(f"{data[0]['word'].capitalize()}: {data[0]['fileUrl']}") else: await ctx.send("Word or audio not found.") @commands.command() async def define(self, ctx, word): url = f"http://api.wordnik.com:80/v4/word.json/{word}/definitions" params = {"limit": 1, "includeRelated": "false", "useCanonical": "false", "includeTags": "false", "api_key": self.bot.WORDNIK_API_KEY} async with self.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.json() if data: await ctx.send(data[0]["word"].capitalize() + ": " + data[0]["text"]) else: await ctx.send("Definition not found.") ## Instruction: Use f-string for define command ## Code After: from twitchio.ext import commands @commands.cog() class Words: def __init__(self, bot): self.bot = bot @commands.command() async def audiodefine(self, ctx, word): url = f"http://api.wordnik.com:80/v4/word.json/{word}/audio" params = {"useCanonical": "false", "limit": 1, "api_key": self.bot.WORDNIK_API_KEY} async with self.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.json() if data: await ctx.send(f"{data[0]['word'].capitalize()}: {data[0]['fileUrl']}") else: await ctx.send("Word or audio not found.") @commands.command() async def define(self, ctx, word): url = f"http://api.wordnik.com:80/v4/word.json/{word}/definitions" params = {"limit": 1, "includeRelated": "false", "useCanonical": "false", "includeTags": "false", "api_key": self.bot.WORDNIK_API_KEY} async with self.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.json() if data: await ctx.send(f"{data[0]['word'].capitalize()}: {data[0]['text']}") else: await ctx.send("Definition not found.")
// ... existing code ... if data: await ctx.send(f"{data[0]['word'].capitalize()}: {data[0]['text']}") else: // ... rest of the code ...
bfbc2bc38cbc7cbcd0afbb8d077fccf1925c0c16
gaphor/SysML/blocks/grouping.py
gaphor/SysML/blocks/grouping.py
from gaphor.diagram.grouping import AbstractGroup, Group from gaphor.SysML.blocks.block import BlockItem from gaphor.SysML.blocks.property import PropertyItem @Group.register(BlockItem, PropertyItem) class NodeGroup(AbstractGroup): """ Add node to another node. """ def group(self): self.parent.subject.ownedAttribute = self.item.subject def ungroup(self): del self.parent.subject.ownedAttribute[self.item.subject]
from gaphor.diagram.grouping import AbstractGroup, Group from gaphor.SysML.blocks.block import BlockItem from gaphor.SysML.blocks.property import PropertyItem @Group.register(BlockItem, PropertyItem) class PropertyGroup(AbstractGroup): """ Add Property to a Block. """ def group(self): self.parent.subject.ownedAttribute = self.item.subject def ungroup(self): del self.parent.subject.ownedAttribute[self.item.subject]
Fix name for property/block group
Fix name for property/block group
Python
lgpl-2.1
amolenaar/gaphor,amolenaar/gaphor
from gaphor.diagram.grouping import AbstractGroup, Group from gaphor.SysML.blocks.block import BlockItem from gaphor.SysML.blocks.property import PropertyItem @Group.register(BlockItem, PropertyItem) - class NodeGroup(AbstractGroup): + class PropertyGroup(AbstractGroup): """ - Add node to another node. + Add Property to a Block. """ def group(self): self.parent.subject.ownedAttribute = self.item.subject def ungroup(self): del self.parent.subject.ownedAttribute[self.item.subject]
Fix name for property/block group
## Code Before: from gaphor.diagram.grouping import AbstractGroup, Group from gaphor.SysML.blocks.block import BlockItem from gaphor.SysML.blocks.property import PropertyItem @Group.register(BlockItem, PropertyItem) class NodeGroup(AbstractGroup): """ Add node to another node. """ def group(self): self.parent.subject.ownedAttribute = self.item.subject def ungroup(self): del self.parent.subject.ownedAttribute[self.item.subject] ## Instruction: Fix name for property/block group ## Code After: from gaphor.diagram.grouping import AbstractGroup, Group from gaphor.SysML.blocks.block import BlockItem from gaphor.SysML.blocks.property import PropertyItem @Group.register(BlockItem, PropertyItem) class PropertyGroup(AbstractGroup): """ Add Property to a Block. """ def group(self): self.parent.subject.ownedAttribute = self.item.subject def ungroup(self): del self.parent.subject.ownedAttribute[self.item.subject]
// ... existing code ... @Group.register(BlockItem, PropertyItem) class PropertyGroup(AbstractGroup): """ Add Property to a Block. """ // ... rest of the code ...
5082354efec86bb0ebb111e51c8e5a039ab7ae88
pypika/dialects.py
pypika/dialects.py
from .enums import Dialects from .queries import ( Query, QueryBuilder, ) class MySQLQuery(Query): """ Defines a query class for use with MySQL. """ @classmethod def _builder(cls): return QueryBuilder(quote_char='`', dialect=Dialects.MYSQL, wrap_union_queries=False) class VerticaQuery(Query): """ Defines a query class for use with Vertica. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.VERTICA) class OracleQuery(Query): """ Defines a query class for use with Oracle. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.ORACLE) class PostgreSQLQuery(Query): """ Defines a query class for use with PostgreSQL. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.POSTGRESQL) class RedshiftQuery(Query): """ Defines a query class for use with Amazon Redshift. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.REDSHIFT) class MSSQLQuery(Query): """ Defines a query class for use with Microsoft SQL Server. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.MSSQL) class ClickHouseQuery(Query): """ Defines a query class for use with Yandex ClickHouse. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.CLICKHOUSE)
from .enums import Dialects from .queries import ( Query, QueryBuilder, ) class MySQLQuery(Query): """ Defines a query class for use with MySQL. """ @classmethod def _builder(cls): return QueryBuilder(quote_char='`', dialect=Dialects.MYSQL, wrap_union_queries=False) class VerticaQuery(Query): """ Defines a query class for use with Vertica. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.VERTICA) class OracleQuery(Query): """ Defines a query class for use with Oracle. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.ORACLE) class PostgreSQLQuery(Query): """ Defines a query class for use with PostgreSQL. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.POSTGRESQL) class RedshiftQuery(Query): """ Defines a query class for use with Amazon Redshift. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.REDSHIFT) class MSSQLQuery(Query): """ Defines a query class for use with Microsoft SQL Server. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.MSSQL) class ClickHouseQuery(Query): """ Defines a query class for use with Yandex ClickHouse. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.CLICKHOUSE, wrap_union_queries=False)
Disable union wrap for clickhouse
Disable union wrap for clickhouse
Python
apache-2.0
kayak/pypika
from .enums import Dialects from .queries import ( Query, QueryBuilder, ) class MySQLQuery(Query): """ Defines a query class for use with MySQL. """ @classmethod def _builder(cls): return QueryBuilder(quote_char='`', dialect=Dialects.MYSQL, wrap_union_queries=False) class VerticaQuery(Query): """ Defines a query class for use with Vertica. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.VERTICA) class OracleQuery(Query): """ Defines a query class for use with Oracle. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.ORACLE) class PostgreSQLQuery(Query): """ Defines a query class for use with PostgreSQL. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.POSTGRESQL) class RedshiftQuery(Query): """ Defines a query class for use with Amazon Redshift. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.REDSHIFT) class MSSQLQuery(Query): """ Defines a query class for use with Microsoft SQL Server. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.MSSQL) class ClickHouseQuery(Query): """ Defines a query class for use with Yandex ClickHouse. """ @classmethod def _builder(cls): - return QueryBuilder(dialect=Dialects.CLICKHOUSE) + return QueryBuilder(dialect=Dialects.CLICKHOUSE, wrap_union_queries=False)
Disable union wrap for clickhouse
## Code Before: from .enums import Dialects from .queries import ( Query, QueryBuilder, ) class MySQLQuery(Query): """ Defines a query class for use with MySQL. """ @classmethod def _builder(cls): return QueryBuilder(quote_char='`', dialect=Dialects.MYSQL, wrap_union_queries=False) class VerticaQuery(Query): """ Defines a query class for use with Vertica. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.VERTICA) class OracleQuery(Query): """ Defines a query class for use with Oracle. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.ORACLE) class PostgreSQLQuery(Query): """ Defines a query class for use with PostgreSQL. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.POSTGRESQL) class RedshiftQuery(Query): """ Defines a query class for use with Amazon Redshift. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.REDSHIFT) class MSSQLQuery(Query): """ Defines a query class for use with Microsoft SQL Server. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.MSSQL) class ClickHouseQuery(Query): """ Defines a query class for use with Yandex ClickHouse. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.CLICKHOUSE) ## Instruction: Disable union wrap for clickhouse ## Code After: from .enums import Dialects from .queries import ( Query, QueryBuilder, ) class MySQLQuery(Query): """ Defines a query class for use with MySQL. """ @classmethod def _builder(cls): return QueryBuilder(quote_char='`', dialect=Dialects.MYSQL, wrap_union_queries=False) class VerticaQuery(Query): """ Defines a query class for use with Vertica. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.VERTICA) class OracleQuery(Query): """ Defines a query class for use with Oracle. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.ORACLE) class PostgreSQLQuery(Query): """ Defines a query class for use with PostgreSQL. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.POSTGRESQL) class RedshiftQuery(Query): """ Defines a query class for use with Amazon Redshift. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.REDSHIFT) class MSSQLQuery(Query): """ Defines a query class for use with Microsoft SQL Server. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.MSSQL) class ClickHouseQuery(Query): """ Defines a query class for use with Yandex ClickHouse. """ @classmethod def _builder(cls): return QueryBuilder(dialect=Dialects.CLICKHOUSE, wrap_union_queries=False)
# ... existing code ... def _builder(cls): return QueryBuilder(dialect=Dialects.CLICKHOUSE, wrap_union_queries=False) # ... rest of the code ...
b91b0d667f64960fd1f07b7dc42290f287ab4c5b
scripts/endpoints_json.py
scripts/endpoints_json.py
import lxml.html from lxml.cssselect import CSSSelector import requests import json class EndpointIdentifier: _page = 'https://www.reddit.com/dev/api/oauth' _no_scope = '(any scope)' def __init__(self): pass def find(self): page = requests.get(self._page) if page.status_code != 200: print("Bad status code:", page.status_code) from sys import exit exit(1) tree = lxml.html.fromstring(page.text) sel = CSSSelector('div[class="toc"] > ul > li > ul > li') results = sel(tree) sections = {} for result in results: scope = result.find('a').text_content() if not scope: scope = self._no_scope endpointlist = [] endpoints = result.cssselect('li > a') for endpoint in endpoints[1:]: descriptor = endpoint.get('href')[1:].replace('_', ' /', 1).replace('_', '/') endpointlist.append(descriptor) sections[scope] = endpointlist from pprint import pprint pprint(sections) return sections if __name__ == "__main__": json.dumps(EndpointIdentifier().find(), indent=4, sort_keys=True)
import lxml.html from lxml.cssselect import CSSSelector import requests import json class EndpointIdentifier: _page = 'https://www.reddit.com/dev/api/oauth' _no_scope = '(any scope)' _headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36' } def __init__(self): pass def find(self): page = requests.get(self._page, headers=self._headers) if page.status_code != 200: print("Bad status code:", page.status_code) from sys import exit exit(1) tree = lxml.html.fromstring(page.text) sel = CSSSelector('div[class="toc"] > ul > li > ul > li') results = sel(tree) sections = {} for result in results: scope = result.find('a').text_content() if not scope: scope = self._no_scope endpointlist = [] endpoints = result.cssselect('li > a') for endpoint in endpoints[1:]: descriptor = endpoint.get('href')[1:].replace('_', ' /', 1).replace('_', '/') endpointlist.append(descriptor) sections[scope] = endpointlist return sections if __name__ == "__main__": print(json.dumps(EndpointIdentifier().find(), indent=4, sort_keys=True))
Add default headers, fix output
Add default headers, fix output
Python
mit
thatJavaNerd/JRAW,ccrama/JRAW,fbis251/JRAW,fbis251/JRAW,fbis251/JRAW,thatJavaNerd/JRAW,Saketme/JRAW,hzsweers/JRAW,hzsweers/JRAW,ccrama/JRAW,thatJavaNerd/JRAW,ccrama/JRAW,Saketme/JRAW,hzsweers/JRAW,Saketme/JRAW
import lxml.html from lxml.cssselect import CSSSelector import requests import json class EndpointIdentifier: _page = 'https://www.reddit.com/dev/api/oauth' _no_scope = '(any scope)' + _headers = { + 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36' + } def __init__(self): pass def find(self): - page = requests.get(self._page) + page = requests.get(self._page, headers=self._headers) if page.status_code != 200: print("Bad status code:", page.status_code) from sys import exit exit(1) tree = lxml.html.fromstring(page.text) sel = CSSSelector('div[class="toc"] > ul > li > ul > li') results = sel(tree) sections = {} for result in results: scope = result.find('a').text_content() if not scope: scope = self._no_scope endpointlist = [] endpoints = result.cssselect('li > a') for endpoint in endpoints[1:]: descriptor = endpoint.get('href')[1:].replace('_', ' /', 1).replace('_', '/') endpointlist.append(descriptor) sections[scope] = endpointlist - from pprint import pprint - pprint(sections) return sections if __name__ == "__main__": - json.dumps(EndpointIdentifier().find(), indent=4, sort_keys=True) + print(json.dumps(EndpointIdentifier().find(), indent=4, sort_keys=True))
Add default headers, fix output
## Code Before: import lxml.html from lxml.cssselect import CSSSelector import requests import json class EndpointIdentifier: _page = 'https://www.reddit.com/dev/api/oauth' _no_scope = '(any scope)' def __init__(self): pass def find(self): page = requests.get(self._page) if page.status_code != 200: print("Bad status code:", page.status_code) from sys import exit exit(1) tree = lxml.html.fromstring(page.text) sel = CSSSelector('div[class="toc"] > ul > li > ul > li') results = sel(tree) sections = {} for result in results: scope = result.find('a').text_content() if not scope: scope = self._no_scope endpointlist = [] endpoints = result.cssselect('li > a') for endpoint in endpoints[1:]: descriptor = endpoint.get('href')[1:].replace('_', ' /', 1).replace('_', '/') endpointlist.append(descriptor) sections[scope] = endpointlist from pprint import pprint pprint(sections) return sections if __name__ == "__main__": json.dumps(EndpointIdentifier().find(), indent=4, sort_keys=True) ## Instruction: Add default headers, fix output ## Code After: import lxml.html from lxml.cssselect import CSSSelector import requests import json class EndpointIdentifier: _page = 'https://www.reddit.com/dev/api/oauth' _no_scope = '(any scope)' _headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36' } def __init__(self): pass def find(self): page = requests.get(self._page, headers=self._headers) if page.status_code != 200: print("Bad status code:", page.status_code) from sys import exit exit(1) tree = lxml.html.fromstring(page.text) sel = CSSSelector('div[class="toc"] > ul > li > ul > li') results = sel(tree) sections = {} for result in results: scope = result.find('a').text_content() if not scope: scope = self._no_scope endpointlist = [] endpoints = result.cssselect('li > a') for endpoint in endpoints[1:]: descriptor = endpoint.get('href')[1:].replace('_', ' /', 1).replace('_', '/') endpointlist.append(descriptor) sections[scope] = endpointlist return sections if __name__ == "__main__": print(json.dumps(EndpointIdentifier().find(), indent=4, sort_keys=True))
// ... existing code ... _no_scope = '(any scope)' _headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36' } // ... modified code ... def find(self): page = requests.get(self._page, headers=self._headers) if page.status_code != 200: ... sections[scope] = endpointlist return sections ... if __name__ == "__main__": print(json.dumps(EndpointIdentifier().find(), indent=4, sort_keys=True)) // ... rest of the code ...
7a552161eab19d24b7b221635e51a915adff0166
templater.py
templater.py
import string if __name__ == "__main__": import sys template_file = sys.argv[1] with open(template_file) as f: data = f.read() template = string.Template(data) template_mapping = {} for item in sys.argv[2:]: # item is in the following form: KEY=VALUE print("-> Current replacer %s" % item) key, value = item.split("=", 1) template_mapping[key] = value print("-> Using mapping: %s" % str(template_mapping)) result = template.substitute(template_mapping) print("-----\n") print(result)
import string import os if __name__ == "__main__": from optparse import OptionParser parser = OptionParser() parser.add_option("-t", "--template", dest="template_file", help="Input template file") (options, args) = parser.parse_args() if not os.path.isfile(options.template_file): sys.stderr.write("Invalid input template file") exit(1) with open(options.template_file) as f: data = f.read() template = string.Template(data) template_mapping = {} for item in args: # item is in the following form: KEY=VALUE print("-> Current replacer %s" % item) key, value = item.split("=", 1) template_mapping[key] = value print("-> Using mapping: %s" % str(template_mapping)) result = template.substitute(template_mapping) print("-----\n") print(result)
Use OptionParser instead of simple sys.argv.
Use OptionParser instead of simple sys.argv.
Python
mit
elecro/strep
import string + import os + if __name__ == "__main__": - import sys + from optparse import OptionParser - template_file = sys.argv[1] + parser = OptionParser() + parser.add_option("-t", "--template", dest="template_file", + help="Input template file") + (options, args) = parser.parse_args() + + if not os.path.isfile(options.template_file): + sys.stderr.write("Invalid input template file") + exit(1) + - with open(template_file) as f: + with open(options.template_file) as f: data = f.read() template = string.Template(data) template_mapping = {} - for item in sys.argv[2:]: + for item in args: # item is in the following form: KEY=VALUE print("-> Current replacer %s" % item) key, value = item.split("=", 1) template_mapping[key] = value print("-> Using mapping: %s" % str(template_mapping)) result = template.substitute(template_mapping) print("-----\n") print(result)
Use OptionParser instead of simple sys.argv.
## Code Before: import string if __name__ == "__main__": import sys template_file = sys.argv[1] with open(template_file) as f: data = f.read() template = string.Template(data) template_mapping = {} for item in sys.argv[2:]: # item is in the following form: KEY=VALUE print("-> Current replacer %s" % item) key, value = item.split("=", 1) template_mapping[key] = value print("-> Using mapping: %s" % str(template_mapping)) result = template.substitute(template_mapping) print("-----\n") print(result) ## Instruction: Use OptionParser instead of simple sys.argv. ## Code After: import string import os if __name__ == "__main__": from optparse import OptionParser parser = OptionParser() parser.add_option("-t", "--template", dest="template_file", help="Input template file") (options, args) = parser.parse_args() if not os.path.isfile(options.template_file): sys.stderr.write("Invalid input template file") exit(1) with open(options.template_file) as f: data = f.read() template = string.Template(data) template_mapping = {} for item in args: # item is in the following form: KEY=VALUE print("-> Current replacer %s" % item) key, value = item.split("=", 1) template_mapping[key] = value print("-> Using mapping: %s" % str(template_mapping)) result = template.substitute(template_mapping) print("-----\n") print(result)
... import string import os ... if __name__ == "__main__": from optparse import OptionParser parser = OptionParser() parser.add_option("-t", "--template", dest="template_file", help="Input template file") (options, args) = parser.parse_args() if not os.path.isfile(options.template_file): sys.stderr.write("Invalid input template file") exit(1) with open(options.template_file) as f: data = f.read() ... for item in args: # item is in the following form: KEY=VALUE ...
0b32ae7a09dd961f379104b6628eaf5700cca785
tests/test_unlocking.py
tests/test_unlocking.py
import unittest from secretstorage import dbus_init, get_any_collection from secretstorage.util import BUS_NAME from secretstorage.exceptions import LockedException @unittest.skipIf(BUS_NAME == "org.freedesktop.secrets", "This test should only be run with the mocked server.") class LockingUnlockingTest(unittest.TestCase): def setUp(self) -> None: self.connection = dbus_init() self.collection = get_any_collection(self.connection) def test_lock_unlock(self) -> None: self.collection.lock() self.assertTrue(self.collection.is_locked()) self.assertRaises(LockedException, self.collection.ensure_not_locked) self.assertIs(self.collection.unlock(), False) self.assertFalse(self.collection.is_locked()) self.collection.ensure_not_locked()
import unittest from secretstorage import dbus_init, Collection from secretstorage.util import BUS_NAME from secretstorage.exceptions import LockedException @unittest.skipIf(BUS_NAME == "org.freedesktop.secrets", "This test should only be run with the mocked server.") class LockingUnlockingTest(unittest.TestCase): def setUp(self) -> None: self.connection = dbus_init() collection_path = "/org/freedesktop/secrets/collection/english" self.collection = Collection(self.connection, collection_path) def test_lock_unlock(self) -> None: self.assertFalse(self.collection.is_locked()) self.collection.lock() self.assertTrue(self.collection.is_locked()) self.assertRaises(LockedException, self.collection.ensure_not_locked) item, = self.collection.search_items({"number": "1"}) self.assertRaises(LockedException, item.ensure_not_locked) self.assertIs(self.collection.unlock(), False) self.assertFalse(self.collection.is_locked()) self.collection.ensure_not_locked()
Add test coverage for Item.ensure_not_locked() method
Add test coverage for Item.ensure_not_locked() method
Python
bsd-3-clause
mitya57/secretstorage
import unittest - from secretstorage import dbus_init, get_any_collection + from secretstorage import dbus_init, Collection from secretstorage.util import BUS_NAME from secretstorage.exceptions import LockedException @unittest.skipIf(BUS_NAME == "org.freedesktop.secrets", "This test should only be run with the mocked server.") class LockingUnlockingTest(unittest.TestCase): def setUp(self) -> None: self.connection = dbus_init() + collection_path = "/org/freedesktop/secrets/collection/english" - self.collection = get_any_collection(self.connection) + self.collection = Collection(self.connection, collection_path) def test_lock_unlock(self) -> None: + self.assertFalse(self.collection.is_locked()) self.collection.lock() self.assertTrue(self.collection.is_locked()) self.assertRaises(LockedException, self.collection.ensure_not_locked) + item, = self.collection.search_items({"number": "1"}) + self.assertRaises(LockedException, item.ensure_not_locked) self.assertIs(self.collection.unlock(), False) self.assertFalse(self.collection.is_locked()) self.collection.ensure_not_locked()
Add test coverage for Item.ensure_not_locked() method
## Code Before: import unittest from secretstorage import dbus_init, get_any_collection from secretstorage.util import BUS_NAME from secretstorage.exceptions import LockedException @unittest.skipIf(BUS_NAME == "org.freedesktop.secrets", "This test should only be run with the mocked server.") class LockingUnlockingTest(unittest.TestCase): def setUp(self) -> None: self.connection = dbus_init() self.collection = get_any_collection(self.connection) def test_lock_unlock(self) -> None: self.collection.lock() self.assertTrue(self.collection.is_locked()) self.assertRaises(LockedException, self.collection.ensure_not_locked) self.assertIs(self.collection.unlock(), False) self.assertFalse(self.collection.is_locked()) self.collection.ensure_not_locked() ## Instruction: Add test coverage for Item.ensure_not_locked() method ## Code After: import unittest from secretstorage import dbus_init, Collection from secretstorage.util import BUS_NAME from secretstorage.exceptions import LockedException @unittest.skipIf(BUS_NAME == "org.freedesktop.secrets", "This test should only be run with the mocked server.") class LockingUnlockingTest(unittest.TestCase): def setUp(self) -> None: self.connection = dbus_init() collection_path = "/org/freedesktop/secrets/collection/english" self.collection = Collection(self.connection, collection_path) def test_lock_unlock(self) -> None: self.assertFalse(self.collection.is_locked()) self.collection.lock() self.assertTrue(self.collection.is_locked()) self.assertRaises(LockedException, self.collection.ensure_not_locked) item, = self.collection.search_items({"number": "1"}) self.assertRaises(LockedException, item.ensure_not_locked) self.assertIs(self.collection.unlock(), False) self.assertFalse(self.collection.is_locked()) self.collection.ensure_not_locked()
... from secretstorage import dbus_init, Collection from secretstorage.util import BUS_NAME ... self.connection = dbus_init() collection_path = "/org/freedesktop/secrets/collection/english" self.collection = Collection(self.connection, collection_path) ... def test_lock_unlock(self) -> None: self.assertFalse(self.collection.is_locked()) self.collection.lock() ... self.assertRaises(LockedException, self.collection.ensure_not_locked) item, = self.collection.search_items({"number": "1"}) self.assertRaises(LockedException, item.ensure_not_locked) self.assertIs(self.collection.unlock(), False) ...
b77956a993f7f703626dbc9fc85003d6840b24fe
partner_compassion/models/partner_bank_compassion.py
partner_compassion/models/partner_bank_compassion.py
from odoo import api, models, _ # pylint: disable=C8107 class ResPartnerBank(models.Model): """ This class upgrade the partners.bank to match Compassion needs. """ _inherit = 'res.partner.bank' @api.model def create(self, data): """Override function to notify creation in a message """ result = super(ResPartnerBank, self).create(data) part = result.partner_id part.message_post(_("<b>Account number: </b>" + result.acc_number), _("New account created"), 'comment') return result @api.multi def unlink(self): """Override function to notify delte in a message """ for account in self: part = account.partner_id part.message_post(_("<b>Account number: </b>" + account.acc_number), _("Account deleted"), 'comment') result = super(ResPartnerBank, self).unlink() return result
from odoo import api, models, _ # pylint: disable=C8107 class ResPartnerBank(models.Model): """ This class upgrade the partners.bank to match Compassion needs. """ _inherit = 'res.partner.bank' @api.model def create(self, data): """Override function to notify creation in a message """ result = super(ResPartnerBank, self).create(data) part = result.partner_id if part: part.message_post(_("<b>Account number: </b>" + result.acc_number), _("New account created"), 'comment') return result @api.multi def unlink(self): """Override function to notify delte in a message """ for account in self: part = account.partner_id part.message_post(_("<b>Account number: </b>" + account.acc_number), _("Account deleted"), 'comment') result = super(ResPartnerBank, self).unlink() return result
FIX only post message if a partner is existent
FIX only post message if a partner is existent
Python
agpl-3.0
CompassionCH/compassion-switzerland,eicher31/compassion-switzerland,eicher31/compassion-switzerland,eicher31/compassion-switzerland,ecino/compassion-switzerland,ecino/compassion-switzerland,CompassionCH/compassion-switzerland,ecino/compassion-switzerland,CompassionCH/compassion-switzerland
from odoo import api, models, _ # pylint: disable=C8107 class ResPartnerBank(models.Model): """ This class upgrade the partners.bank to match Compassion needs. """ _inherit = 'res.partner.bank' @api.model def create(self, data): """Override function to notify creation in a message """ result = super(ResPartnerBank, self).create(data) part = result.partner_id + if part: - part.message_post(_("<b>Account number: </b>" + result.acc_number), + part.message_post(_("<b>Account number: </b>" + result.acc_number), - _("New account created"), 'comment') + _("New account created"), 'comment') return result @api.multi def unlink(self): """Override function to notify delte in a message """ for account in self: part = account.partner_id part.message_post(_("<b>Account number: </b>" + account.acc_number), _("Account deleted"), 'comment') result = super(ResPartnerBank, self).unlink() return result
FIX only post message if a partner is existent
## Code Before: from odoo import api, models, _ # pylint: disable=C8107 class ResPartnerBank(models.Model): """ This class upgrade the partners.bank to match Compassion needs. """ _inherit = 'res.partner.bank' @api.model def create(self, data): """Override function to notify creation in a message """ result = super(ResPartnerBank, self).create(data) part = result.partner_id part.message_post(_("<b>Account number: </b>" + result.acc_number), _("New account created"), 'comment') return result @api.multi def unlink(self): """Override function to notify delte in a message """ for account in self: part = account.partner_id part.message_post(_("<b>Account number: </b>" + account.acc_number), _("Account deleted"), 'comment') result = super(ResPartnerBank, self).unlink() return result ## Instruction: FIX only post message if a partner is existent ## Code After: from odoo import api, models, _ # pylint: disable=C8107 class ResPartnerBank(models.Model): """ This class upgrade the partners.bank to match Compassion needs. """ _inherit = 'res.partner.bank' @api.model def create(self, data): """Override function to notify creation in a message """ result = super(ResPartnerBank, self).create(data) part = result.partner_id if part: part.message_post(_("<b>Account number: </b>" + result.acc_number), _("New account created"), 'comment') return result @api.multi def unlink(self): """Override function to notify delte in a message """ for account in self: part = account.partner_id part.message_post(_("<b>Account number: </b>" + account.acc_number), _("Account deleted"), 'comment') result = super(ResPartnerBank, self).unlink() return result
... part = result.partner_id if part: part.message_post(_("<b>Account number: </b>" + result.acc_number), _("New account created"), 'comment') ...
399430076227f42f5d168c5b2264933c32f4b52a
lib/ansible/release.py
lib/ansible/release.py
from __future__ import (absolute_import, division, print_function) __metaclass__ = type __version__ = '2.7.0.a1.post0' __author__ = 'Ansible, Inc.' __codename__ = 'In the Light'
from __future__ import (absolute_import, division, print_function) __metaclass__ = type __version__ = '2.8.0.dev0' __author__ = 'Ansible, Inc.' __codename__ = 'TBD'
Update ansible version number to 2.8.0.dev0
Update ansible version number to 2.8.0.dev0
Python
mit
thaim/ansible,thaim/ansible
from __future__ import (absolute_import, division, print_function) __metaclass__ = type - __version__ = '2.7.0.a1.post0' + __version__ = '2.8.0.dev0' __author__ = 'Ansible, Inc.' - __codename__ = 'In the Light' + __codename__ = 'TBD'
Update ansible version number to 2.8.0.dev0
## Code Before: from __future__ import (absolute_import, division, print_function) __metaclass__ = type __version__ = '2.7.0.a1.post0' __author__ = 'Ansible, Inc.' __codename__ = 'In the Light' ## Instruction: Update ansible version number to 2.8.0.dev0 ## Code After: from __future__ import (absolute_import, division, print_function) __metaclass__ = type __version__ = '2.8.0.dev0' __author__ = 'Ansible, Inc.' __codename__ = 'TBD'
// ... existing code ... __version__ = '2.8.0.dev0' __author__ = 'Ansible, Inc.' __codename__ = 'TBD' // ... rest of the code ...
b44dc164e6dd1e9a07f460c2be07829744029cea
server/tests/test_admin.py
server/tests/test_admin.py
"""General functional tests for the Server admin.""" from sal.test_utils import AdminTestCase class ServerAdminTest(AdminTestCase): """Test the admin site is configured to have all expected views.""" admin_endpoints = { 'apikey', 'businessunit', 'condition', 'fact', 'historicalfact', 'installedupdate', 'machinedetailplugin', 'machinegroup', 'machine', 'pendingappleupdate', 'pendingupdate', 'pluginscriptrow', 'pluginscriptsubmission', 'plugin', 'report', 'salsetting', 'updatehistoryitem', 'updatehistory', 'userprofile'}
"""General functional tests for the Server admin.""" from sal.test_utils import AdminTestCase class ServerAdminTest(AdminTestCase): """Test the admin site is configured to have all expected views.""" admin_endpoints = { 'apikey', 'businessunit', 'condition', 'fact', 'historicalfact', 'installedupdate', 'machinedetailplugin', 'machinegroup', 'machine', 'pendingappleupdate', 'pendingupdate', 'pluginscriptrow', 'pluginscriptsubmission', 'plugin', 'report', 'salsetting', 'updatehistoryitem', 'updatehistory'}
Remove endpoint from test (it has been removed in lieu of User admin).
Remove endpoint from test (it has been removed in lieu of User admin).
Python
apache-2.0
sheagcraig/sal,salopensource/sal,sheagcraig/sal,sheagcraig/sal,sheagcraig/sal,salopensource/sal,salopensource/sal,salopensource/sal
"""General functional tests for the Server admin.""" from sal.test_utils import AdminTestCase class ServerAdminTest(AdminTestCase): """Test the admin site is configured to have all expected views.""" admin_endpoints = { 'apikey', 'businessunit', 'condition', 'fact', 'historicalfact', 'installedupdate', 'machinedetailplugin', 'machinegroup', 'machine', 'pendingappleupdate', 'pendingupdate', 'pluginscriptrow', 'pluginscriptsubmission', 'plugin', 'report', 'salsetting', 'updatehistoryitem', - 'updatehistory', 'userprofile'} + 'updatehistory'}
Remove endpoint from test (it has been removed in lieu of User admin).
## Code Before: """General functional tests for the Server admin.""" from sal.test_utils import AdminTestCase class ServerAdminTest(AdminTestCase): """Test the admin site is configured to have all expected views.""" admin_endpoints = { 'apikey', 'businessunit', 'condition', 'fact', 'historicalfact', 'installedupdate', 'machinedetailplugin', 'machinegroup', 'machine', 'pendingappleupdate', 'pendingupdate', 'pluginscriptrow', 'pluginscriptsubmission', 'plugin', 'report', 'salsetting', 'updatehistoryitem', 'updatehistory', 'userprofile'} ## Instruction: Remove endpoint from test (it has been removed in lieu of User admin). ## Code After: """General functional tests for the Server admin.""" from sal.test_utils import AdminTestCase class ServerAdminTest(AdminTestCase): """Test the admin site is configured to have all expected views.""" admin_endpoints = { 'apikey', 'businessunit', 'condition', 'fact', 'historicalfact', 'installedupdate', 'machinedetailplugin', 'machinegroup', 'machine', 'pendingappleupdate', 'pendingupdate', 'pluginscriptrow', 'pluginscriptsubmission', 'plugin', 'report', 'salsetting', 'updatehistoryitem', 'updatehistory'}
... 'pluginscriptsubmission', 'plugin', 'report', 'salsetting', 'updatehistoryitem', 'updatehistory'} ...
51943abe4c5dc072d5e4e4f938f0d66aade93d57
pombola/settings/nigeria_base.py
pombola/settings/nigeria_base.py
COUNTRY_APP = 'nigeria' OPTIONAL_APPS = [] TWITTER_USERNAME = 'NGShineyoureye' TWITTER_WIDGET_ID = '354909651910918144' BLOG_RSS_FEED = 'http://eienigeria.org/rss.xml' MAP_BOUNDING_BOX_NORTH = 14.1 MAP_BOUNDING_BOX_EAST = 14.7 MAP_BOUNDING_BOX_SOUTH = 4 MAP_BOUNDING_BOX_WEST = 2.5 MAPIT_COUNTRY = 'NG'
COUNTRY_APP = 'nigeria' OPTIONAL_APPS = ['pombola.spinner'] TWITTER_USERNAME = 'NGShineyoureye' TWITTER_WIDGET_ID = '354909651910918144' BLOG_RSS_FEED = 'http://eienigeria.org/rss.xml' MAP_BOUNDING_BOX_NORTH = 14.1 MAP_BOUNDING_BOX_EAST = 14.7 MAP_BOUNDING_BOX_SOUTH = 4 MAP_BOUNDING_BOX_WEST = 2.5 MAPIT_COUNTRY = 'NG'
Add pombola.spinner to OPTIONAL_APPS in the new settings modules
Add pombola.spinner to OPTIONAL_APPS in the new settings modules
Python
agpl-3.0
geoffkilpin/pombola,patricmutwiri/pombola,ken-muturi/pombola,mysociety/pombola,ken-muturi/pombola,patricmutwiri/pombola,hzj123/56th,mysociety/pombola,mysociety/pombola,patricmutwiri/pombola,mysociety/pombola,hzj123/56th,ken-muturi/pombola,ken-muturi/pombola,hzj123/56th,geoffkilpin/pombola,mysociety/pombola,geoffkilpin/pombola,geoffkilpin/pombola,ken-muturi/pombola,geoffkilpin/pombola,patricmutwiri/pombola,hzj123/56th,geoffkilpin/pombola,ken-muturi/pombola,hzj123/56th,patricmutwiri/pombola,patricmutwiri/pombola,hzj123/56th,mysociety/pombola
COUNTRY_APP = 'nigeria' - OPTIONAL_APPS = [] + OPTIONAL_APPS = ['pombola.spinner'] TWITTER_USERNAME = 'NGShineyoureye' TWITTER_WIDGET_ID = '354909651910918144' BLOG_RSS_FEED = 'http://eienigeria.org/rss.xml' MAP_BOUNDING_BOX_NORTH = 14.1 MAP_BOUNDING_BOX_EAST = 14.7 MAP_BOUNDING_BOX_SOUTH = 4 MAP_BOUNDING_BOX_WEST = 2.5 MAPIT_COUNTRY = 'NG'
Add pombola.spinner to OPTIONAL_APPS in the new settings modules
## Code Before: COUNTRY_APP = 'nigeria' OPTIONAL_APPS = [] TWITTER_USERNAME = 'NGShineyoureye' TWITTER_WIDGET_ID = '354909651910918144' BLOG_RSS_FEED = 'http://eienigeria.org/rss.xml' MAP_BOUNDING_BOX_NORTH = 14.1 MAP_BOUNDING_BOX_EAST = 14.7 MAP_BOUNDING_BOX_SOUTH = 4 MAP_BOUNDING_BOX_WEST = 2.5 MAPIT_COUNTRY = 'NG' ## Instruction: Add pombola.spinner to OPTIONAL_APPS in the new settings modules ## Code After: COUNTRY_APP = 'nigeria' OPTIONAL_APPS = ['pombola.spinner'] TWITTER_USERNAME = 'NGShineyoureye' TWITTER_WIDGET_ID = '354909651910918144' BLOG_RSS_FEED = 'http://eienigeria.org/rss.xml' MAP_BOUNDING_BOX_NORTH = 14.1 MAP_BOUNDING_BOX_EAST = 14.7 MAP_BOUNDING_BOX_SOUTH = 4 MAP_BOUNDING_BOX_WEST = 2.5 MAPIT_COUNTRY = 'NG'
// ... existing code ... OPTIONAL_APPS = ['pombola.spinner'] // ... rest of the code ...
7cc1a78d4fefcb216a6c8d5128d05ba9e70f5246
jazzband/hooks.py
jazzband/hooks.py
from flask.ext.hookserver import Hooks from .models import db, User hooks = Hooks() @hooks.hook('ping') def ping(data, guid): return 'pong' @hooks.hook('membership') def membership(data, guid): if data['scope'] != 'team': return member = User.query.filter_by(id=data['member']['id']).first() if member is None: return if data['action'] == 'added': member.is_member = True db.session.commit() elif data['action'] == 'removed': member.is_member = False db.session.commit()
from flask.ext.hookserver import Hooks from .models import db, User hooks = Hooks() @hooks.hook('ping') def ping(data, guid): return 'pong' @hooks.hook('membership') def membership(data, guid): if data['scope'] != 'team': return member = User.query.filter_by(id=data['member']['id']).first() if member is None: return if data['action'] == 'added': member.is_member = True db.session.commit() elif data['action'] == 'removed': member.is_member = False db.session.commit() return "Thanks"
Return a response for the membership webhook.
Return a response for the membership webhook.
Python
mit
jazzband/website,jazzband/website,jazzband/website,jazzband/site,jazzband/jazzband-site,jazzband/site,jazzband/jazzband-site,jazzband/website
from flask.ext.hookserver import Hooks from .models import db, User hooks = Hooks() @hooks.hook('ping') def ping(data, guid): return 'pong' @hooks.hook('membership') def membership(data, guid): if data['scope'] != 'team': return member = User.query.filter_by(id=data['member']['id']).first() if member is None: return if data['action'] == 'added': member.is_member = True db.session.commit() elif data['action'] == 'removed': member.is_member = False db.session.commit() + return "Thanks"
Return a response for the membership webhook.
## Code Before: from flask.ext.hookserver import Hooks from .models import db, User hooks = Hooks() @hooks.hook('ping') def ping(data, guid): return 'pong' @hooks.hook('membership') def membership(data, guid): if data['scope'] != 'team': return member = User.query.filter_by(id=data['member']['id']).first() if member is None: return if data['action'] == 'added': member.is_member = True db.session.commit() elif data['action'] == 'removed': member.is_member = False db.session.commit() ## Instruction: Return a response for the membership webhook. ## Code After: from flask.ext.hookserver import Hooks from .models import db, User hooks = Hooks() @hooks.hook('ping') def ping(data, guid): return 'pong' @hooks.hook('membership') def membership(data, guid): if data['scope'] != 'team': return member = User.query.filter_by(id=data['member']['id']).first() if member is None: return if data['action'] == 'added': member.is_member = True db.session.commit() elif data['action'] == 'removed': member.is_member = False db.session.commit() return "Thanks"
// ... existing code ... db.session.commit() return "Thanks" // ... rest of the code ...
1e513d901dfef9135a62c8f99633b10d3900ecb8
orator/schema/mysql_builder.py
orator/schema/mysql_builder.py
from .builder import SchemaBuilder class MySQLSchemaBuilder(SchemaBuilder): def has_table(self, table): """ Determine if the given table exists. :param table: The table :type table: str :rtype: bool """ sql = self._grammar.compile_table_exists() database = self._connection.get_database_name() table = self._connection.get_table_prefix() + table return len(self._connection.select(sql, [database, table])) > 0 def get_column_listing(self, table): """ Get the column listing for a given table. :param table: The table :type table: str :rtype: list """ sql = self._grammar.compile_column_exists() database = self._connection.get_database_name() table = self._connection.get_table_prefix() + table results = self._connection.select(sql, [database, table]) return self._connection.get_post_processor().process_column_listing(results)
from .builder import SchemaBuilder class MySQLSchemaBuilder(SchemaBuilder): def has_table(self, table): """ Determine if the given table exists. :param table: The table :type table: str :rtype: bool """ sql = self._grammar.compile_table_exists() database = self._connection.get_database_name() table = self._connection.get_table_prefix() + table return len(self._connection.select(sql, [database, table])) > 0 def get_column_listing(self, table): """ Get the column listing for a given table. :param table: The table :type table: str :rtype: list """ sql = self._grammar.compile_column_exists() database = self._connection.get_database_name() table = self._connection.get_table_prefix() + table results = [] for result in self._connection.select(sql, [database, table]): new_result = {} for key, value in result.items(): new_result[key.lower()] = value results.append(new_result) return self._connection.get_post_processor().process_column_listing(results)
Fix case when processing column names for MySQL
Fix case when processing column names for MySQL
Python
mit
sdispater/orator
from .builder import SchemaBuilder class MySQLSchemaBuilder(SchemaBuilder): - def has_table(self, table): """ Determine if the given table exists. :param table: The table :type table: str :rtype: bool """ sql = self._grammar.compile_table_exists() database = self._connection.get_database_name() table = self._connection.get_table_prefix() + table return len(self._connection.select(sql, [database, table])) > 0 def get_column_listing(self, table): """ Get the column listing for a given table. :param table: The table :type table: str :rtype: list """ sql = self._grammar.compile_column_exists() database = self._connection.get_database_name() table = self._connection.get_table_prefix() + table + results = [] - results = self._connection.select(sql, [database, table]) + for result in self._connection.select(sql, [database, table]): + new_result = {} + for key, value in result.items(): + new_result[key.lower()] = value + + results.append(new_result) return self._connection.get_post_processor().process_column_listing(results)
Fix case when processing column names for MySQL
## Code Before: from .builder import SchemaBuilder class MySQLSchemaBuilder(SchemaBuilder): def has_table(self, table): """ Determine if the given table exists. :param table: The table :type table: str :rtype: bool """ sql = self._grammar.compile_table_exists() database = self._connection.get_database_name() table = self._connection.get_table_prefix() + table return len(self._connection.select(sql, [database, table])) > 0 def get_column_listing(self, table): """ Get the column listing for a given table. :param table: The table :type table: str :rtype: list """ sql = self._grammar.compile_column_exists() database = self._connection.get_database_name() table = self._connection.get_table_prefix() + table results = self._connection.select(sql, [database, table]) return self._connection.get_post_processor().process_column_listing(results) ## Instruction: Fix case when processing column names for MySQL ## Code After: from .builder import SchemaBuilder class MySQLSchemaBuilder(SchemaBuilder): def has_table(self, table): """ Determine if the given table exists. :param table: The table :type table: str :rtype: bool """ sql = self._grammar.compile_table_exists() database = self._connection.get_database_name() table = self._connection.get_table_prefix() + table return len(self._connection.select(sql, [database, table])) > 0 def get_column_listing(self, table): """ Get the column listing for a given table. :param table: The table :type table: str :rtype: list """ sql = self._grammar.compile_column_exists() database = self._connection.get_database_name() table = self._connection.get_table_prefix() + table results = [] for result in self._connection.select(sql, [database, table]): new_result = {} for key, value in result.items(): new_result[key.lower()] = value results.append(new_result) return self._connection.get_post_processor().process_column_listing(results)
# ... existing code ... class MySQLSchemaBuilder(SchemaBuilder): def has_table(self, table): # ... modified code ... results = [] for result in self._connection.select(sql, [database, table]): new_result = {} for key, value in result.items(): new_result[key.lower()] = value results.append(new_result) # ... rest of the code ...
18998011bb52616a3002ca298a64ea61c5727a76
skeleton/website/jasyscript.py
skeleton/website/jasyscript.py
import konstrukteur.Konstrukteur import jasy.asset.Manager2 as AssetManager @task def build(regenerate = False): """Generate source (development) version""" # Initialize assets AssetManager.AssetManager(profile, session) # Build static website konstrukteur.Konstrukteur.build(regenerate)
import konstrukteur.Konstrukteur import jasy.asset.Manager2 as AssetManager @task def build(regenerate = False): """Generate source (development) version""" # Initialize assets assetManager = AssetManager.AssetManager(profile, session) # Build static website konstrukteur.Konstrukteur.build(regenerate) # Copy assets to build path assetManager.copyAssets()
Copy used assets to output path
Copy used assets to output path
Python
mit
fastner/konstrukteur,fastner/konstrukteur,fastner/konstrukteur
import konstrukteur.Konstrukteur import jasy.asset.Manager2 as AssetManager @task def build(regenerate = False): """Generate source (development) version""" # Initialize assets - AssetManager.AssetManager(profile, session) + assetManager = AssetManager.AssetManager(profile, session) # Build static website konstrukteur.Konstrukteur.build(regenerate) + # Copy assets to build path + assetManager.copyAssets()
Copy used assets to output path
## Code Before: import konstrukteur.Konstrukteur import jasy.asset.Manager2 as AssetManager @task def build(regenerate = False): """Generate source (development) version""" # Initialize assets AssetManager.AssetManager(profile, session) # Build static website konstrukteur.Konstrukteur.build(regenerate) ## Instruction: Copy used assets to output path ## Code After: import konstrukteur.Konstrukteur import jasy.asset.Manager2 as AssetManager @task def build(regenerate = False): """Generate source (development) version""" # Initialize assets assetManager = AssetManager.AssetManager(profile, session) # Build static website konstrukteur.Konstrukteur.build(regenerate) # Copy assets to build path assetManager.copyAssets()
# ... existing code ... # Initialize assets assetManager = AssetManager.AssetManager(profile, session) # ... modified code ... konstrukteur.Konstrukteur.build(regenerate) # Copy assets to build path assetManager.copyAssets() # ... rest of the code ...
d7bea2995fc54c15404b4b47cefae5fc7b0201de
partner_internal_code/res_partner.py
partner_internal_code/res_partner.py
from openerp import fields, models, api class partner(models.Model): """""" _inherit = 'res.partner' internal_code = fields.Char( 'Internal Code') # we let this to base nane search improoved # def name_search(self, cr, uid, name, args=None, # operator='ilike', context=None, limit=100): # args = args or [] # res = [] # if name: # recs = self.search( # cr, uid, [('internal_code', operator, name)] + args, # limit=limit, context=context) # res = self.name_get(cr, uid, recs) # res += super(partner, self).name_search( # cr, uid, # name=name, args=args, operator=operator, limit=limit) # return res @api.model def create(self, vals): if not vals.get('internal_code', False): vals['internal_code'] = self.env[ 'ir.sequence'].next_by_code('partner.internal.code') or '/' return super(partner, self).create(vals) _sql_constraints = { ('internal_code_uniq', 'unique(internal_code)', 'Internal Code mast be unique!') }
from openerp import fields, models, api class partner(models.Model): """""" _inherit = 'res.partner' internal_code = fields.Char( 'Internal Code', copy=False, ) # we let this to base nane search improoved # def name_search(self, cr, uid, name, args=None, # operator='ilike', context=None, limit=100): # args = args or [] # res = [] # if name: # recs = self.search( # cr, uid, [('internal_code', operator, name)] + args, # limit=limit, context=context) # res = self.name_get(cr, uid, recs) # res += super(partner, self).name_search( # cr, uid, # name=name, args=args, operator=operator, limit=limit) # return res @api.model def create(self, vals): if not vals.get('internal_code', False): vals['internal_code'] = self.env[ 'ir.sequence'].next_by_code('partner.internal.code') or '/' return super(partner, self).create(vals) _sql_constraints = { ('internal_code_uniq', 'unique(internal_code)', 'Internal Code mast be unique!') }
FIX partner internal code compatibility with sign up
FIX partner internal code compatibility with sign up
Python
agpl-3.0
ingadhoc/partner
from openerp import fields, models, api class partner(models.Model): """""" _inherit = 'res.partner' internal_code = fields.Char( - 'Internal Code') + 'Internal Code', + copy=False, + ) # we let this to base nane search improoved # def name_search(self, cr, uid, name, args=None, # operator='ilike', context=None, limit=100): # args = args or [] # res = [] # if name: # recs = self.search( # cr, uid, [('internal_code', operator, name)] + args, # limit=limit, context=context) # res = self.name_get(cr, uid, recs) # res += super(partner, self).name_search( # cr, uid, # name=name, args=args, operator=operator, limit=limit) # return res @api.model def create(self, vals): if not vals.get('internal_code', False): vals['internal_code'] = self.env[ 'ir.sequence'].next_by_code('partner.internal.code') or '/' return super(partner, self).create(vals) _sql_constraints = { ('internal_code_uniq', 'unique(internal_code)', 'Internal Code mast be unique!') }
FIX partner internal code compatibility with sign up
## Code Before: from openerp import fields, models, api class partner(models.Model): """""" _inherit = 'res.partner' internal_code = fields.Char( 'Internal Code') # we let this to base nane search improoved # def name_search(self, cr, uid, name, args=None, # operator='ilike', context=None, limit=100): # args = args or [] # res = [] # if name: # recs = self.search( # cr, uid, [('internal_code', operator, name)] + args, # limit=limit, context=context) # res = self.name_get(cr, uid, recs) # res += super(partner, self).name_search( # cr, uid, # name=name, args=args, operator=operator, limit=limit) # return res @api.model def create(self, vals): if not vals.get('internal_code', False): vals['internal_code'] = self.env[ 'ir.sequence'].next_by_code('partner.internal.code') or '/' return super(partner, self).create(vals) _sql_constraints = { ('internal_code_uniq', 'unique(internal_code)', 'Internal Code mast be unique!') } ## Instruction: FIX partner internal code compatibility with sign up ## Code After: from openerp import fields, models, api class partner(models.Model): """""" _inherit = 'res.partner' internal_code = fields.Char( 'Internal Code', copy=False, ) # we let this to base nane search improoved # def name_search(self, cr, uid, name, args=None, # operator='ilike', context=None, limit=100): # args = args or [] # res = [] # if name: # recs = self.search( # cr, uid, [('internal_code', operator, name)] + args, # limit=limit, context=context) # res = self.name_get(cr, uid, recs) # res += super(partner, self).name_search( # cr, uid, # name=name, args=args, operator=operator, limit=limit) # return res @api.model def create(self, vals): if not vals.get('internal_code', False): vals['internal_code'] = self.env[ 'ir.sequence'].next_by_code('partner.internal.code') or '/' return super(partner, self).create(vals) _sql_constraints = { ('internal_code_uniq', 'unique(internal_code)', 'Internal Code mast be unique!') }
... internal_code = fields.Char( 'Internal Code', copy=False, ) ...
c5f9b9bc76f797156b73a2bb26b80ebf23d62fe4
polyaxon/pipelines/celery_task.py
polyaxon/pipelines/celery_task.py
from pipelines.models import Operation from polyaxon.celery_api import CeleryTask class OperationTask(CeleryTask): """Base operation celery task with basic logging.""" _operation = None def run(self, *args, **kwargs): self._operation = Operation.objects.get(id=kwargs['query_id']) super(OperationTask, self).run(*args, **kwargs) def on_failure(self, exc, task_id, args, kwargs, einfo): """Update query status and send email notification to a user""" super(OperationTask, self).on_failure(exc, task_id, args, kwargs, einfo) self._operation.on_failure() def on_retry(self, exc, task_id, args, kwargs, einfo): super(OperationTask, self).on_retry(exc, task_id, args, kwargs, einfo) self._operation.on_retry() def on_success(self, retval, task_id, args, kwargs): """Send email notification and a file, if requested to do so by a user""" super(OperationTask, self).on_success(retval, task_id, args, kwargs) self._operation.on_success()
from pipelines.models import Operation from polyaxon.celery_api import CeleryTask class OperationTask(CeleryTask): """Base operation celery task with basic logging.""" _operation = None def __call__(self, *args, **kwargs): self._operation = Operation.objects.get(id=kwargs['query_id']) self._operation.on_run() self.max_retries = self._operation.max_retries self.countdown = self._operation.get_countdown(self.request.retries) super(OperationTask, self).__call__(*args, **kwargs) def on_failure(self, exc, task_id, args, kwargs, einfo): """Update query status and send email notification to a user""" super(OperationTask, self).on_failure(exc, task_id, args, kwargs, einfo) self._operation.on_failure() def on_retry(self, exc, task_id, args, kwargs, einfo): super(OperationTask, self).on_retry(exc, task_id, args, kwargs, einfo) self._operation.on_retry() def on_success(self, retval, task_id, args, kwargs): """Send email notification and a file, if requested to do so by a user""" super(OperationTask, self).on_success(retval, task_id, args, kwargs) self._operation.on_success()
Update OperationCelery with max_retries and countdown logic
Update OperationCelery with max_retries and countdown logic
Python
apache-2.0
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
from pipelines.models import Operation from polyaxon.celery_api import CeleryTask class OperationTask(CeleryTask): """Base operation celery task with basic logging.""" _operation = None - def run(self, *args, **kwargs): + def __call__(self, *args, **kwargs): self._operation = Operation.objects.get(id=kwargs['query_id']) + self._operation.on_run() + self.max_retries = self._operation.max_retries + self.countdown = self._operation.get_countdown(self.request.retries) + - super(OperationTask, self).run(*args, **kwargs) + super(OperationTask, self).__call__(*args, **kwargs) def on_failure(self, exc, task_id, args, kwargs, einfo): """Update query status and send email notification to a user""" super(OperationTask, self).on_failure(exc, task_id, args, kwargs, einfo) self._operation.on_failure() def on_retry(self, exc, task_id, args, kwargs, einfo): super(OperationTask, self).on_retry(exc, task_id, args, kwargs, einfo) self._operation.on_retry() def on_success(self, retval, task_id, args, kwargs): """Send email notification and a file, if requested to do so by a user""" super(OperationTask, self).on_success(retval, task_id, args, kwargs) self._operation.on_success()
Update OperationCelery with max_retries and countdown logic
## Code Before: from pipelines.models import Operation from polyaxon.celery_api import CeleryTask class OperationTask(CeleryTask): """Base operation celery task with basic logging.""" _operation = None def run(self, *args, **kwargs): self._operation = Operation.objects.get(id=kwargs['query_id']) super(OperationTask, self).run(*args, **kwargs) def on_failure(self, exc, task_id, args, kwargs, einfo): """Update query status and send email notification to a user""" super(OperationTask, self).on_failure(exc, task_id, args, kwargs, einfo) self._operation.on_failure() def on_retry(self, exc, task_id, args, kwargs, einfo): super(OperationTask, self).on_retry(exc, task_id, args, kwargs, einfo) self._operation.on_retry() def on_success(self, retval, task_id, args, kwargs): """Send email notification and a file, if requested to do so by a user""" super(OperationTask, self).on_success(retval, task_id, args, kwargs) self._operation.on_success() ## Instruction: Update OperationCelery with max_retries and countdown logic ## Code After: from pipelines.models import Operation from polyaxon.celery_api import CeleryTask class OperationTask(CeleryTask): """Base operation celery task with basic logging.""" _operation = None def __call__(self, *args, **kwargs): self._operation = Operation.objects.get(id=kwargs['query_id']) self._operation.on_run() self.max_retries = self._operation.max_retries self.countdown = self._operation.get_countdown(self.request.retries) super(OperationTask, self).__call__(*args, **kwargs) def on_failure(self, exc, task_id, args, kwargs, einfo): """Update query status and send email notification to a user""" super(OperationTask, self).on_failure(exc, task_id, args, kwargs, einfo) self._operation.on_failure() def on_retry(self, exc, task_id, args, kwargs, einfo): super(OperationTask, self).on_retry(exc, task_id, args, kwargs, einfo) self._operation.on_retry() def on_success(self, retval, task_id, args, kwargs): """Send email notification and a file, if requested to do so by a user""" super(OperationTask, self).on_success(retval, task_id, args, kwargs) self._operation.on_success()
// ... existing code ... def __call__(self, *args, **kwargs): self._operation = Operation.objects.get(id=kwargs['query_id']) self._operation.on_run() self.max_retries = self._operation.max_retries self.countdown = self._operation.get_countdown(self.request.retries) super(OperationTask, self).__call__(*args, **kwargs) // ... rest of the code ...
fc30efcbea90835314be50e65608102fa538e55c
sri21_vmx_pvs_to_file.py
sri21_vmx_pvs_to_file.py
from utilities import get_pv_names, write_pvs_to_file import argparse parser = argparse.ArgumentParser('optional named arguments') parser.add_argument("-f", "--file", dest="filename", help="write report to FILE", metavar="FILE", default = 'test.txt') requiredArgv = parser.add_argument_group('required arguments') requiredArgv.add_argument("-m", "--mode", dest="mode", help="Machine MODE to use", metavar="MODE", required = True) argv = parser.parse_args() mode_pvs = get_pv_names(argv.mode) write_pvs_to_file(argv.filename, mode_pvs) print argv.filename
from utilities import get_pv_names, write_pvs_to_file import argparse parser = argparse.ArgumentParser('optional named arguments') parser.add_argument("-f", "--file", dest="filename", help="write report to FILE", metavar="FILE", default = 'test.txt') requiredArgv = parser.add_argument_group('required arguments') requiredArgv.add_argument("-m", "--mode", dest="mode", help="Machine MODE to use", metavar="MODE", required = True) argv = parser.parse_args() mode_pvs = get_pv_names(argv.mode) # File appears to be already sorted, so no need for next line # sorted(mode_pvs) write_pvs_to_file(argv.filename, mode_pvs)
Clear unnecessary code, add comments on sorting
Clear unnecessary code, add comments on sorting
Python
apache-2.0
razvanvasile/Work-Mini-Projects,razvanvasile/Work-Mini-Projects,razvanvasile/Work-Mini-Projects
from utilities import get_pv_names, write_pvs_to_file import argparse parser = argparse.ArgumentParser('optional named arguments') parser.add_argument("-f", "--file", dest="filename", help="write report to FILE", metavar="FILE", default = 'test.txt') requiredArgv = parser.add_argument_group('required arguments') requiredArgv.add_argument("-m", "--mode", dest="mode", help="Machine MODE to use", metavar="MODE", required = True) argv = parser.parse_args() mode_pvs = get_pv_names(argv.mode) + # File appears to be already sorted, so no need for next line + # sorted(mode_pvs) write_pvs_to_file(argv.filename, mode_pvs) - print argv.filename -
Clear unnecessary code, add comments on sorting
## Code Before: from utilities import get_pv_names, write_pvs_to_file import argparse parser = argparse.ArgumentParser('optional named arguments') parser.add_argument("-f", "--file", dest="filename", help="write report to FILE", metavar="FILE", default = 'test.txt') requiredArgv = parser.add_argument_group('required arguments') requiredArgv.add_argument("-m", "--mode", dest="mode", help="Machine MODE to use", metavar="MODE", required = True) argv = parser.parse_args() mode_pvs = get_pv_names(argv.mode) write_pvs_to_file(argv.filename, mode_pvs) print argv.filename ## Instruction: Clear unnecessary code, add comments on sorting ## Code After: from utilities import get_pv_names, write_pvs_to_file import argparse parser = argparse.ArgumentParser('optional named arguments') parser.add_argument("-f", "--file", dest="filename", help="write report to FILE", metavar="FILE", default = 'test.txt') requiredArgv = parser.add_argument_group('required arguments') requiredArgv.add_argument("-m", "--mode", dest="mode", help="Machine MODE to use", metavar="MODE", required = True) argv = parser.parse_args() mode_pvs = get_pv_names(argv.mode) # File appears to be already sorted, so no need for next line # sorted(mode_pvs) write_pvs_to_file(argv.filename, mode_pvs)
... mode_pvs = get_pv_names(argv.mode) # File appears to be already sorted, so no need for next line # sorted(mode_pvs) write_pvs_to_file(argv.filename, mode_pvs) ...
f60363b3d24d2f4af5ddb894cc1f6494b371b18e
mass_mailing_switzerland/wizards/mailchimp_export_update_wizard.py
mass_mailing_switzerland/wizards/mailchimp_export_update_wizard.py
from odoo import api, models, fields, _ from odoo.exceptions import UserError class ExportMailchimpWizard(models.TransientModel): _inherit = "partner.export.mailchimp" @api.multi def get_mailing_contact_id(self, partner_id, force_create=False): # Avoid exporting opt_out partner if force_create: partner = self.env["res.partner"].browse(partner_id) if partner.opt_out: return False # Push the partner_id in mailing_contact creation return super( ExportMailchimpWizard, self.with_context(default_partner_id=partner_id) ).get_mailing_contact_id(partner_id, force_create)
from odoo import api, models, fields, _ from odoo.exceptions import UserError class ExportMailchimpWizard(models.TransientModel): _inherit = "partner.export.mailchimp" @api.multi def get_mailing_contact_id(self, partner_id, force_create=False): # Avoid exporting opt_out partner if force_create and partner_id.opt_out: return False # Push the partner_id in mailing_contact creation return super( ExportMailchimpWizard, self.with_context(default_partner_id=partner_id) ).get_mailing_contact_id(partner_id, force_create)
FIX opt_out prevention for mailchimp export
FIX opt_out prevention for mailchimp export
Python
agpl-3.0
CompassionCH/compassion-switzerland,eicher31/compassion-switzerland,CompassionCH/compassion-switzerland,CompassionCH/compassion-switzerland,eicher31/compassion-switzerland,eicher31/compassion-switzerland
from odoo import api, models, fields, _ from odoo.exceptions import UserError class ExportMailchimpWizard(models.TransientModel): _inherit = "partner.export.mailchimp" @api.multi def get_mailing_contact_id(self, partner_id, force_create=False): # Avoid exporting opt_out partner + if force_create and partner_id.opt_out: - if force_create: - partner = self.env["res.partner"].browse(partner_id) - if partner.opt_out: - return False + return False # Push the partner_id in mailing_contact creation return super( ExportMailchimpWizard, self.with_context(default_partner_id=partner_id) ).get_mailing_contact_id(partner_id, force_create)
FIX opt_out prevention for mailchimp export
## Code Before: from odoo import api, models, fields, _ from odoo.exceptions import UserError class ExportMailchimpWizard(models.TransientModel): _inherit = "partner.export.mailchimp" @api.multi def get_mailing_contact_id(self, partner_id, force_create=False): # Avoid exporting opt_out partner if force_create: partner = self.env["res.partner"].browse(partner_id) if partner.opt_out: return False # Push the partner_id in mailing_contact creation return super( ExportMailchimpWizard, self.with_context(default_partner_id=partner_id) ).get_mailing_contact_id(partner_id, force_create) ## Instruction: FIX opt_out prevention for mailchimp export ## Code After: from odoo import api, models, fields, _ from odoo.exceptions import UserError class ExportMailchimpWizard(models.TransientModel): _inherit = "partner.export.mailchimp" @api.multi def get_mailing_contact_id(self, partner_id, force_create=False): # Avoid exporting opt_out partner if force_create and partner_id.opt_out: return False # Push the partner_id in mailing_contact creation return super( ExportMailchimpWizard, self.with_context(default_partner_id=partner_id) ).get_mailing_contact_id(partner_id, force_create)
... # Avoid exporting opt_out partner if force_create and partner_id.opt_out: return False # Push the partner_id in mailing_contact creation ...
e33a68f14a13c0340b2dfcbb13931d2185735951
scripts/nanopolish_makerange.py
scripts/nanopolish_makerange.py
from __future__ import print_function import sys import argparse from Bio import SeqIO parser = argparse.ArgumentParser(description='Partition a genome into a set of overlapping segments') parser.add_argument('--segment-length', type=int, default=50000) parser.add_argument('--overlap-length', type=int, default=200) args, extra = parser.parse_known_args() if len(extra) != 1: sys.stderr.write("Error: a genome file is expected\n") filename = extra[0] recs = [ (rec.name, len(rec.seq)) for rec in SeqIO.parse(open(filename), "fasta")] SEGMENT_LENGTH = args.segment_length OVERLAP_LENGTH = args.overlap_length MIN_SEGMENT_LENGTH = 5 * OVERLAP_LENGTH for name, length in recs: n_segments = (length / SEGMENT_LENGTH) + 1 start = 0 while start < length: end = start + SEGMENT_LENGTH # If this segment will end near the end of the contig, extend it to end if length - end < MIN_SEGMENT_LENGTH: print("%s:%d-%d" % (name, start, length - 1)) start = length else: print("%s:%d-%d" % (name, start, end + OVERLAP_LENGTH)) start = end
from __future__ import print_function import sys import argparse from Bio.SeqIO.FastaIO import SimpleFastaParser parser = argparse.ArgumentParser(description='Partition a genome into a set of overlapping segments') parser.add_argument('--segment-length', type=int, default=50000) parser.add_argument('--overlap-length', type=int, default=200) args, extra = parser.parse_known_args() if len(extra) != 1: sys.stderr.write("Error: a genome file is expected\n") filename = extra[0] with open(filename) as handle: recs = [(title.split(None, 1)[0], len(seq)) for title, seq in SimpleFastaParser(handle)] SEGMENT_LENGTH = args.segment_length OVERLAP_LENGTH = args.overlap_length MIN_SEGMENT_LENGTH = 5 * OVERLAP_LENGTH for name, length in recs: n_segments = (length / SEGMENT_LENGTH) + 1 start = 0 while start < length: end = start + SEGMENT_LENGTH # If this segment will end near the end of the contig, extend it to end if length - end < MIN_SEGMENT_LENGTH: print("%s:%d-%d" % (name, start, length - 1)) start = length else: print("%s:%d-%d" % (name, start, end + OVERLAP_LENGTH)) start = end
Use Biopython's string based FASTA parser
Use Biopython's string based FASTA parser This was introduced in Biopython 1.61 back in February 2013, so the dependencies shouldn't matter. You could go further here and use a generator expression over a list comprehension?
Python
mit
jts/nanopolish,jts/nanopolish,jts/nanopolish,jts/nanopolish,jts/nanopolish
from __future__ import print_function import sys import argparse - from Bio import SeqIO + from Bio.SeqIO.FastaIO import SimpleFastaParser parser = argparse.ArgumentParser(description='Partition a genome into a set of overlapping segments') parser.add_argument('--segment-length', type=int, default=50000) parser.add_argument('--overlap-length', type=int, default=200) args, extra = parser.parse_known_args() if len(extra) != 1: sys.stderr.write("Error: a genome file is expected\n") filename = extra[0] - recs = [ (rec.name, len(rec.seq)) for rec in SeqIO.parse(open(filename), "fasta")] + with open(filename) as handle: + recs = [(title.split(None, 1)[0], len(seq)) + for title, seq in SimpleFastaParser(handle)] SEGMENT_LENGTH = args.segment_length OVERLAP_LENGTH = args.overlap_length MIN_SEGMENT_LENGTH = 5 * OVERLAP_LENGTH for name, length in recs: n_segments = (length / SEGMENT_LENGTH) + 1 start = 0 while start < length: end = start + SEGMENT_LENGTH # If this segment will end near the end of the contig, extend it to end if length - end < MIN_SEGMENT_LENGTH: print("%s:%d-%d" % (name, start, length - 1)) start = length else: print("%s:%d-%d" % (name, start, end + OVERLAP_LENGTH)) start = end
Use Biopython's string based FASTA parser
## Code Before: from __future__ import print_function import sys import argparse from Bio import SeqIO parser = argparse.ArgumentParser(description='Partition a genome into a set of overlapping segments') parser.add_argument('--segment-length', type=int, default=50000) parser.add_argument('--overlap-length', type=int, default=200) args, extra = parser.parse_known_args() if len(extra) != 1: sys.stderr.write("Error: a genome file is expected\n") filename = extra[0] recs = [ (rec.name, len(rec.seq)) for rec in SeqIO.parse(open(filename), "fasta")] SEGMENT_LENGTH = args.segment_length OVERLAP_LENGTH = args.overlap_length MIN_SEGMENT_LENGTH = 5 * OVERLAP_LENGTH for name, length in recs: n_segments = (length / SEGMENT_LENGTH) + 1 start = 0 while start < length: end = start + SEGMENT_LENGTH # If this segment will end near the end of the contig, extend it to end if length - end < MIN_SEGMENT_LENGTH: print("%s:%d-%d" % (name, start, length - 1)) start = length else: print("%s:%d-%d" % (name, start, end + OVERLAP_LENGTH)) start = end ## Instruction: Use Biopython's string based FASTA parser ## Code After: from __future__ import print_function import sys import argparse from Bio.SeqIO.FastaIO import SimpleFastaParser parser = argparse.ArgumentParser(description='Partition a genome into a set of overlapping segments') parser.add_argument('--segment-length', type=int, default=50000) parser.add_argument('--overlap-length', type=int, default=200) args, extra = parser.parse_known_args() if len(extra) != 1: sys.stderr.write("Error: a genome file is expected\n") filename = extra[0] with open(filename) as handle: recs = [(title.split(None, 1)[0], len(seq)) for title, seq in SimpleFastaParser(handle)] SEGMENT_LENGTH = args.segment_length OVERLAP_LENGTH = args.overlap_length MIN_SEGMENT_LENGTH = 5 * OVERLAP_LENGTH for name, length in recs: n_segments = (length / SEGMENT_LENGTH) + 1 start = 0 while start < length: end = start + SEGMENT_LENGTH # If this segment will end near the end of the contig, extend it to end if length - end < MIN_SEGMENT_LENGTH: print("%s:%d-%d" % (name, start, length - 1)) start = length else: print("%s:%d-%d" % (name, start, end + OVERLAP_LENGTH)) start = end
... import argparse from Bio.SeqIO.FastaIO import SimpleFastaParser ... with open(filename) as handle: recs = [(title.split(None, 1)[0], len(seq)) for title, seq in SimpleFastaParser(handle)] ...
a9cd0a385253cef42d03d6a45e81ef4dd582e9de
base/settings/testing.py
base/settings/testing.py
from .base import Base as Settings class Testing(Settings): # Database Configuration. # -------------------------------------------------------------------------- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test', } } # django-celery. # -------------------------------------------------------------------------- Settings.INSTALLED_APPS += ['kombu.transport.django', 'djcelery'] BROKER_URL = 'django://' # django-haystack. # -------------------------------------------------------------------------- HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, } # Media Storage Configuration. # -------------------------------------------------------------------------- # Amazon Web Services AWS_STORAGE_BUCKET_NAME = 'test-bucket' # django-s3-folder-storage DEFAULT_S3_PATH = 'media' STATIC_S3_PATH = 'static' CDN_DOMAIN = 'cdn.example.net' MEDIA_URL = 'https://%s/%s/' % (CDN_DOMAIN, DEFAULT_S3_PATH) STATIC_URL = 'https://%s/%s/' % (CDN_DOMAIN, STATIC_S3_PATH) # Authentication Configuration. # -------------------------------------------------------------------------- HELLO_BASE_CLIENT_ID = 'client-id' HELLO_BASE_CLIENT_SECRET = 'client-secret' OAUTH_AUTHORIZATION_URL = 'https://testserver/oauth/authorize/' OAUTH_TOKEN_URL = 'https://testserver/oauth/token/'
from .base import Base as Settings class Testing(Settings): # Database Configuration. # -------------------------------------------------------------------------- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } # django-celery. # -------------------------------------------------------------------------- Settings.INSTALLED_APPS += ['kombu.transport.django', 'djcelery'] BROKER_URL = 'django://' # django-haystack. # -------------------------------------------------------------------------- HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, } # Media Storage Configuration. # -------------------------------------------------------------------------- # Amazon Web Services AWS_STORAGE_BUCKET_NAME = 'test-bucket' # django-s3-folder-storage DEFAULT_S3_PATH = 'media' STATIC_S3_PATH = 'static' CDN_DOMAIN = 'cdn.example.net' MEDIA_URL = 'https://%s/%s/' % (CDN_DOMAIN, DEFAULT_S3_PATH) STATIC_URL = 'https://%s/%s/' % (CDN_DOMAIN, STATIC_S3_PATH) # Authentication Configuration. # -------------------------------------------------------------------------- HELLO_BASE_CLIENT_ID = 'client-id' HELLO_BASE_CLIENT_SECRET = 'client-secret' OAUTH_AUTHORIZATION_URL = 'https://testserver/oauth/authorize/' OAUTH_TOKEN_URL = 'https://testserver/oauth/token/'
Use SQLite in an attempt to speed up the tests.
Use SQLite in an attempt to speed up the tests.
Python
apache-2.0
hello-base/web,hello-base/web,hello-base/web,hello-base/web
from .base import Base as Settings class Testing(Settings): # Database Configuration. # -------------------------------------------------------------------------- DATABASES = { 'default': { - 'ENGINE': 'django.db.backends.postgresql_psycopg2', + 'ENGINE': 'django.db.backends.sqlite3', - 'NAME': 'test', + 'NAME': ':memory:', } } # django-celery. # -------------------------------------------------------------------------- Settings.INSTALLED_APPS += ['kombu.transport.django', 'djcelery'] BROKER_URL = 'django://' # django-haystack. # -------------------------------------------------------------------------- HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, } # Media Storage Configuration. # -------------------------------------------------------------------------- # Amazon Web Services AWS_STORAGE_BUCKET_NAME = 'test-bucket' # django-s3-folder-storage DEFAULT_S3_PATH = 'media' STATIC_S3_PATH = 'static' CDN_DOMAIN = 'cdn.example.net' MEDIA_URL = 'https://%s/%s/' % (CDN_DOMAIN, DEFAULT_S3_PATH) STATIC_URL = 'https://%s/%s/' % (CDN_DOMAIN, STATIC_S3_PATH) # Authentication Configuration. # -------------------------------------------------------------------------- HELLO_BASE_CLIENT_ID = 'client-id' HELLO_BASE_CLIENT_SECRET = 'client-secret' OAUTH_AUTHORIZATION_URL = 'https://testserver/oauth/authorize/' OAUTH_TOKEN_URL = 'https://testserver/oauth/token/'
Use SQLite in an attempt to speed up the tests.
## Code Before: from .base import Base as Settings class Testing(Settings): # Database Configuration. # -------------------------------------------------------------------------- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test', } } # django-celery. # -------------------------------------------------------------------------- Settings.INSTALLED_APPS += ['kombu.transport.django', 'djcelery'] BROKER_URL = 'django://' # django-haystack. # -------------------------------------------------------------------------- HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, } # Media Storage Configuration. # -------------------------------------------------------------------------- # Amazon Web Services AWS_STORAGE_BUCKET_NAME = 'test-bucket' # django-s3-folder-storage DEFAULT_S3_PATH = 'media' STATIC_S3_PATH = 'static' CDN_DOMAIN = 'cdn.example.net' MEDIA_URL = 'https://%s/%s/' % (CDN_DOMAIN, DEFAULT_S3_PATH) STATIC_URL = 'https://%s/%s/' % (CDN_DOMAIN, STATIC_S3_PATH) # Authentication Configuration. # -------------------------------------------------------------------------- HELLO_BASE_CLIENT_ID = 'client-id' HELLO_BASE_CLIENT_SECRET = 'client-secret' OAUTH_AUTHORIZATION_URL = 'https://testserver/oauth/authorize/' OAUTH_TOKEN_URL = 'https://testserver/oauth/token/' ## Instruction: Use SQLite in an attempt to speed up the tests. ## Code After: from .base import Base as Settings class Testing(Settings): # Database Configuration. # -------------------------------------------------------------------------- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } # django-celery. # -------------------------------------------------------------------------- Settings.INSTALLED_APPS += ['kombu.transport.django', 'djcelery'] BROKER_URL = 'django://' # django-haystack. # -------------------------------------------------------------------------- HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, } # Media Storage Configuration. # -------------------------------------------------------------------------- # Amazon Web Services AWS_STORAGE_BUCKET_NAME = 'test-bucket' # django-s3-folder-storage DEFAULT_S3_PATH = 'media' STATIC_S3_PATH = 'static' CDN_DOMAIN = 'cdn.example.net' MEDIA_URL = 'https://%s/%s/' % (CDN_DOMAIN, DEFAULT_S3_PATH) STATIC_URL = 'https://%s/%s/' % (CDN_DOMAIN, STATIC_S3_PATH) # Authentication Configuration. # -------------------------------------------------------------------------- HELLO_BASE_CLIENT_ID = 'client-id' HELLO_BASE_CLIENT_SECRET = 'client-secret' OAUTH_AUTHORIZATION_URL = 'https://testserver/oauth/authorize/' OAUTH_TOKEN_URL = 'https://testserver/oauth/token/'
// ... existing code ... 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } // ... rest of the code ...
c4d58ef971b850d3f201903bb6091d159241112f
histomicstk/features/__init__.py
histomicstk/features/__init__.py
from .ReinhardNorm import ReinhardNorm from .ReinhardSample import ReinhardSample __all__ = ( 'FeatureExtraction' )
__all__ = ( 'FeatureExtraction' )
Resolve import issue in color_normalization_test
Resolve import issue in color_normalization_test
Python
apache-2.0
DigitalSlideArchive/HistomicsTK,DigitalSlideArchive/HistomicsTK
- from .ReinhardNorm import ReinhardNorm - from .ReinhardSample import ReinhardSample - __all__ = ( 'FeatureExtraction' )
Resolve import issue in color_normalization_test
## Code Before: from .ReinhardNorm import ReinhardNorm from .ReinhardSample import ReinhardSample __all__ = ( 'FeatureExtraction' ) ## Instruction: Resolve import issue in color_normalization_test ## Code After: __all__ = ( 'FeatureExtraction' )
// ... existing code ... __all__ = ( // ... rest of the code ...
bdeb28f2f7840c04dbf65b6c0771c121f229e59a
tests.py
tests.py
import sys import os import unittest from straight.plugin.loader import StraightPluginLoader class PluginTestCase(unittest.TestCase): def setUp(self): self.loader = StraightPluginLoader() self.added_path = os.path.join(os.path.dirname(__file__), 'more-test-plugins') self.added_path = os.path.join(os.path.dirname(__file__), 'some-test-plugins') sys.path.append(self.added_path) def tearDown(self): del sys.path[-1] del sys.path[-1] def test_load(self): modules = list(self.loader.load('testplugin')) assert len(modules) == 2, modules def test_plugin(self): assert self.loader.load('testplugin')[0].do(1) == 2 if __name__ == '__main__': unittest.main()
import sys import os import unittest from straight.plugin.loader import StraightPluginLoader class PluginTestCase(unittest.TestCase): def setUp(self): self.loader = StraightPluginLoader() sys.path.append(os.path.join(os.path.dirname(__file__), 'more-test-plugins')) sys.path.append(os.path.join(os.path.dirname(__file__), 'some-test-plugins')) def tearDown(self): del sys.path[-1] del sys.path[-1] def test_load(self): modules = list(self.loader.load('testplugin')) assert len(modules) == 2, modules def test_plugin(self): assert self.loader.load('testplugin')[0].do(1) == 2 if __name__ == '__main__': unittest.main()
Fix test case for multiple locations of a namespace
Fix test case for multiple locations of a namespace
Python
mit
ironfroggy/straight.plugin,pombredanne/straight.plugin
import sys import os import unittest from straight.plugin.loader import StraightPluginLoader class PluginTestCase(unittest.TestCase): def setUp(self): self.loader = StraightPluginLoader() - self.added_path = os.path.join(os.path.dirname(__file__), 'more-test-plugins') + sys.path.append(os.path.join(os.path.dirname(__file__), 'more-test-plugins')) - self.added_path = os.path.join(os.path.dirname(__file__), 'some-test-plugins') + sys.path.append(os.path.join(os.path.dirname(__file__), 'some-test-plugins')) - sys.path.append(self.added_path) def tearDown(self): del sys.path[-1] del sys.path[-1] def test_load(self): modules = list(self.loader.load('testplugin')) assert len(modules) == 2, modules def test_plugin(self): assert self.loader.load('testplugin')[0].do(1) == 2 if __name__ == '__main__': unittest.main()
Fix test case for multiple locations of a namespace
## Code Before: import sys import os import unittest from straight.plugin.loader import StraightPluginLoader class PluginTestCase(unittest.TestCase): def setUp(self): self.loader = StraightPluginLoader() self.added_path = os.path.join(os.path.dirname(__file__), 'more-test-plugins') self.added_path = os.path.join(os.path.dirname(__file__), 'some-test-plugins') sys.path.append(self.added_path) def tearDown(self): del sys.path[-1] del sys.path[-1] def test_load(self): modules = list(self.loader.load('testplugin')) assert len(modules) == 2, modules def test_plugin(self): assert self.loader.load('testplugin')[0].do(1) == 2 if __name__ == '__main__': unittest.main() ## Instruction: Fix test case for multiple locations of a namespace ## Code After: import sys import os import unittest from straight.plugin.loader import StraightPluginLoader class PluginTestCase(unittest.TestCase): def setUp(self): self.loader = StraightPluginLoader() sys.path.append(os.path.join(os.path.dirname(__file__), 'more-test-plugins')) sys.path.append(os.path.join(os.path.dirname(__file__), 'some-test-plugins')) def tearDown(self): del sys.path[-1] del sys.path[-1] def test_load(self): modules = list(self.loader.load('testplugin')) assert len(modules) == 2, modules def test_plugin(self): assert self.loader.load('testplugin')[0].do(1) == 2 if __name__ == '__main__': unittest.main()
# ... existing code ... self.loader = StraightPluginLoader() sys.path.append(os.path.join(os.path.dirname(__file__), 'more-test-plugins')) sys.path.append(os.path.join(os.path.dirname(__file__), 'some-test-plugins')) # ... rest of the code ...
a0556156651b6c8f5dd230ba99998efa890e1506
test/unit/test_template.py
test/unit/test_template.py
import os import unittest import rapport.template class TemplateTestCase(unittest.TestCase): def test__get_template_dirs(self): for type in ["plugin", "email", "web"]: template_dirs = rapport.template._get_template_dirs(type) self.assertIn(os.path.expanduser(os.path.join("~", ".rapport", "templates", type)), template_dirs) self.assertIn(os.path.join("templates", type), template_dirs)
import os import unittest import rapport.template class TemplateTestCase(unittest.TestCase): def test__get_template_dirs(self): for type in ["plugin", "email", "web"]: template_dirs = rapport.template._get_template_dirs(type) self.assertIn(os.path.expanduser(os.path.join("~", ".rapport", "templates", type)), template_dirs) self.assertIn(os.path.join("rapport", "templates", type), template_dirs)
Adjust template path after change
Adjust template path after change
Python
apache-2.0
saschpe/rapport
import os import unittest import rapport.template class TemplateTestCase(unittest.TestCase): def test__get_template_dirs(self): for type in ["plugin", "email", "web"]: template_dirs = rapport.template._get_template_dirs(type) self.assertIn(os.path.expanduser(os.path.join("~", ".rapport", "templates", type)), template_dirs) - self.assertIn(os.path.join("templates", type), template_dirs) + self.assertIn(os.path.join("rapport", "templates", type), template_dirs)
Adjust template path after change
## Code Before: import os import unittest import rapport.template class TemplateTestCase(unittest.TestCase): def test__get_template_dirs(self): for type in ["plugin", "email", "web"]: template_dirs = rapport.template._get_template_dirs(type) self.assertIn(os.path.expanduser(os.path.join("~", ".rapport", "templates", type)), template_dirs) self.assertIn(os.path.join("templates", type), template_dirs) ## Instruction: Adjust template path after change ## Code After: import os import unittest import rapport.template class TemplateTestCase(unittest.TestCase): def test__get_template_dirs(self): for type in ["plugin", "email", "web"]: template_dirs = rapport.template._get_template_dirs(type) self.assertIn(os.path.expanduser(os.path.join("~", ".rapport", "templates", type)), template_dirs) self.assertIn(os.path.join("rapport", "templates", type), template_dirs)
... self.assertIn(os.path.expanduser(os.path.join("~", ".rapport", "templates", type)), template_dirs) self.assertIn(os.path.join("rapport", "templates", type), template_dirs) ...
07096ba58e61580168c85dbcbecb107824096871
python/tutorial/example.py
python/tutorial/example.py
from matasano.util.byte_xor import byte_list_xor import sys if __name__ == "__main__": if len(sys.argv) != 2: print("Usage:\n\t python -m example.py <string to encrypt>") quit() input_str = sys.argv[1] # Convert string to list of bytes byte_list_input = [ord(c) for c in input_str] # XOR the string with the byte 1 (flips last bit) output_list = byte_list_xor(byte_list_input, [1]*len(input_str)) # Convert list back to string output_str = "".join(chr(b) for b in output_list) print("The encrypted string is: {}".format(output_str))
from matasano.util.byte_xor import byte_list_xor import sys if __name__ == "__main__": if len(sys.argv) != 2: print("Usage:\n\t python -m example.py <string to encrypt>") quit() input_str = sys.argv[1] # Convert string to list of bytes byte_list_input = [ord(c) for c in input_str] # XOR the string with the byte 2 (flips secondd last bit) output_list = byte_list_xor(byte_list_input, [2]*len(input_str)) # Convert list back to string output_str = "".join(chr(b) for b in output_list) print("The encrypted string is: {}".format(output_str))
Change XOR to flip second last bit
Change XOR to flip second last bit Making change to cause merge conflict as an example.
Python
mit
TheLunchtimeAttack/matasano-challenges,TheLunchtimeAttack/matasano-challenges
from matasano.util.byte_xor import byte_list_xor import sys if __name__ == "__main__": if len(sys.argv) != 2: print("Usage:\n\t python -m example.py <string to encrypt>") quit() input_str = sys.argv[1] # Convert string to list of bytes byte_list_input = [ord(c) for c in input_str] - # XOR the string with the byte 1 (flips last bit) + # XOR the string with the byte 2 (flips secondd last bit) - output_list = byte_list_xor(byte_list_input, [1]*len(input_str)) + output_list = byte_list_xor(byte_list_input, [2]*len(input_str)) # Convert list back to string output_str = "".join(chr(b) for b in output_list) print("The encrypted string is: {}".format(output_str))
Change XOR to flip second last bit
## Code Before: from matasano.util.byte_xor import byte_list_xor import sys if __name__ == "__main__": if len(sys.argv) != 2: print("Usage:\n\t python -m example.py <string to encrypt>") quit() input_str = sys.argv[1] # Convert string to list of bytes byte_list_input = [ord(c) for c in input_str] # XOR the string with the byte 1 (flips last bit) output_list = byte_list_xor(byte_list_input, [1]*len(input_str)) # Convert list back to string output_str = "".join(chr(b) for b in output_list) print("The encrypted string is: {}".format(output_str)) ## Instruction: Change XOR to flip second last bit ## Code After: from matasano.util.byte_xor import byte_list_xor import sys if __name__ == "__main__": if len(sys.argv) != 2: print("Usage:\n\t python -m example.py <string to encrypt>") quit() input_str = sys.argv[1] # Convert string to list of bytes byte_list_input = [ord(c) for c in input_str] # XOR the string with the byte 2 (flips secondd last bit) output_list = byte_list_xor(byte_list_input, [2]*len(input_str)) # Convert list back to string output_str = "".join(chr(b) for b in output_list) print("The encrypted string is: {}".format(output_str))
# ... existing code ... # XOR the string with the byte 2 (flips secondd last bit) output_list = byte_list_xor(byte_list_input, [2]*len(input_str)) # ... rest of the code ...
ce3948b2aacddfb9debd4834d9aa446e99987a0d
app/views.py
app/views.py
from app import mulungwishi_app as url from flask import render_template @url.route('/') def index(): return render_template('index.html') @url.route('/<query>') def print_user_input(query): if '=' in query: query_container, query_value = query.split('=') return 'Your query is {} which is equal to {}'.format(query_container, query_value) return "You've entered an incorrect query. Please check and try again. Input : "+query @url.errorhandler(404) def page_not_found(error): return render_template('404.html'), 404 @url.errorhandler(403) def page_forbidden(error): return render_template('403.html', title='Page Forbidden'), 403 @url.errorhandler(500) def page_server_error(error): return render_template('500.html', title='Server Error'), 500
from app import mulungwishi_app as url from flask import render_template @url.route('/') def index(): return render_template('index.html') @url.route('/<query>') def print_user_input(query): if '=' in query: query_container, query_value = query.split('=') return 'Your query is {} which is equal to {}'.format(query_container, query_value) return "You've entered an incorrect query. Please check and try again. Input : {}".format(query) @url.errorhandler(404) def page_not_found(error): return render_template('404.html'), 404 @url.errorhandler(403) def page_forbidden(error): return render_template('403.html', title='Page Forbidden'), 403 @url.errorhandler(500) def page_server_error(error): return render_template('500.html', title='Server Error'), 500
Replace string concatenation with .format function
Replace string concatenation with .format function
Python
mit
admiral96/mulungwishi-webhook,engagespark/public-webhooks,admiral96/public-webhooks,admiral96/mulungwishi-webhook,admiral96/public-webhooks,engagespark/mulungwishi-webhook,engagespark/mulungwishi-webhook,engagespark/public-webhooks
from app import mulungwishi_app as url from flask import render_template @url.route('/') def index(): return render_template('index.html') @url.route('/<query>') def print_user_input(query): if '=' in query: query_container, query_value = query.split('=') return 'Your query is {} which is equal to {}'.format(query_container, query_value) - return "You've entered an incorrect query. Please check and try again. Input : "+query + return "You've entered an incorrect query. Please check and try again. Input : {}".format(query) @url.errorhandler(404) def page_not_found(error): return render_template('404.html'), 404 @url.errorhandler(403) def page_forbidden(error): return render_template('403.html', title='Page Forbidden'), 403 @url.errorhandler(500) def page_server_error(error): return render_template('500.html', title='Server Error'), 500
Replace string concatenation with .format function
## Code Before: from app import mulungwishi_app as url from flask import render_template @url.route('/') def index(): return render_template('index.html') @url.route('/<query>') def print_user_input(query): if '=' in query: query_container, query_value = query.split('=') return 'Your query is {} which is equal to {}'.format(query_container, query_value) return "You've entered an incorrect query. Please check and try again. Input : "+query @url.errorhandler(404) def page_not_found(error): return render_template('404.html'), 404 @url.errorhandler(403) def page_forbidden(error): return render_template('403.html', title='Page Forbidden'), 403 @url.errorhandler(500) def page_server_error(error): return render_template('500.html', title='Server Error'), 500 ## Instruction: Replace string concatenation with .format function ## Code After: from app import mulungwishi_app as url from flask import render_template @url.route('/') def index(): return render_template('index.html') @url.route('/<query>') def print_user_input(query): if '=' in query: query_container, query_value = query.split('=') return 'Your query is {} which is equal to {}'.format(query_container, query_value) return "You've entered an incorrect query. Please check and try again. Input : {}".format(query) @url.errorhandler(404) def page_not_found(error): return render_template('404.html'), 404 @url.errorhandler(403) def page_forbidden(error): return render_template('403.html', title='Page Forbidden'), 403 @url.errorhandler(500) def page_server_error(error): return render_template('500.html', title='Server Error'), 500
// ... existing code ... return 'Your query is {} which is equal to {}'.format(query_container, query_value) return "You've entered an incorrect query. Please check and try again. Input : {}".format(query) // ... rest of the code ...
6deebdc7e5c93d5f61cad97870cea7fb445bb860
onitu/utils.py
onitu/utils.py
import time import redis def connect_to_redis(*args, **kwargs): client = redis.Redis(*args, unix_socket_path='redis/redis.sock', **kwargs) while True: try: assert client.ping() except (redis.exceptions.ConnectionError, AssertionError): time.sleep(0.5) else: return client
import time import redis def connect_to_redis(*args, **kwargs): client = redis.Redis( *args, unix_socket_path='redis/redis.sock', decode_responses=True, **kwargs ) while True: try: assert client.ping() except (redis.exceptions.ConnectionError, AssertionError): time.sleep(0.5) else: return client
Convert Redis keys and values to str
Convert Redis keys and values to str
Python
mit
onitu/onitu,onitu/onitu,onitu/onitu
import time import redis def connect_to_redis(*args, **kwargs): - client = redis.Redis(*args, unix_socket_path='redis/redis.sock', **kwargs) + client = redis.Redis( + *args, + unix_socket_path='redis/redis.sock', + decode_responses=True, + **kwargs + ) while True: try: assert client.ping() except (redis.exceptions.ConnectionError, AssertionError): time.sleep(0.5) else: return client
Convert Redis keys and values to str
## Code Before: import time import redis def connect_to_redis(*args, **kwargs): client = redis.Redis(*args, unix_socket_path='redis/redis.sock', **kwargs) while True: try: assert client.ping() except (redis.exceptions.ConnectionError, AssertionError): time.sleep(0.5) else: return client ## Instruction: Convert Redis keys and values to str ## Code After: import time import redis def connect_to_redis(*args, **kwargs): client = redis.Redis( *args, unix_socket_path='redis/redis.sock', decode_responses=True, **kwargs ) while True: try: assert client.ping() except (redis.exceptions.ConnectionError, AssertionError): time.sleep(0.5) else: return client
// ... existing code ... def connect_to_redis(*args, **kwargs): client = redis.Redis( *args, unix_socket_path='redis/redis.sock', decode_responses=True, **kwargs ) // ... rest of the code ...
bfd8d1126e771702dfe4869923927b8f4fb81ef1
openstack/tests/functional/network/v2/test_extension.py
openstack/tests/functional/network/v2/test_extension.py
import six from openstack.tests.functional import base class TestExtension(base.BaseFunctionalTest): def test_list_and_find(self): extensions = list(self.conn.network.extensions()) self.assertGreater(len(extensions), 0) for ext in extensions: self.assertIsInstance(ext.name, six.string_types) self.assertIsInstance(ext.namespace, six.string_types) self.assertIsInstance(ext.alias, six.string_types)
import six from openstack.tests.functional import base class TestExtension(base.BaseFunctionalTest): def test_list_and_find(self): extensions = list(self.conn.network.extensions()) self.assertGreater(len(extensions), 0) for ext in extensions: self.assertIsInstance(ext.name, six.string_types) self.assertIsInstance(ext.alias, six.string_types)
Remove namespace from network ext test
Remove namespace from network ext test Change-Id: Id9b97d67ac6745fe962a76ccd9c0e4f7cbed4a89
Python
apache-2.0
mtougeron/python-openstacksdk,briancurtin/python-openstacksdk,stackforge/python-openstacksdk,stackforge/python-openstacksdk,dudymas/python-openstacksdk,dtroyer/python-openstacksdk,dtroyer/python-openstacksdk,mtougeron/python-openstacksdk,briancurtin/python-openstacksdk,openstack/python-openstacksdk,openstack/python-openstacksdk,dudymas/python-openstacksdk
import six from openstack.tests.functional import base class TestExtension(base.BaseFunctionalTest): def test_list_and_find(self): extensions = list(self.conn.network.extensions()) self.assertGreater(len(extensions), 0) for ext in extensions: self.assertIsInstance(ext.name, six.string_types) - self.assertIsInstance(ext.namespace, six.string_types) self.assertIsInstance(ext.alias, six.string_types)
Remove namespace from network ext test
## Code Before: import six from openstack.tests.functional import base class TestExtension(base.BaseFunctionalTest): def test_list_and_find(self): extensions = list(self.conn.network.extensions()) self.assertGreater(len(extensions), 0) for ext in extensions: self.assertIsInstance(ext.name, six.string_types) self.assertIsInstance(ext.namespace, six.string_types) self.assertIsInstance(ext.alias, six.string_types) ## Instruction: Remove namespace from network ext test ## Code After: import six from openstack.tests.functional import base class TestExtension(base.BaseFunctionalTest): def test_list_and_find(self): extensions = list(self.conn.network.extensions()) self.assertGreater(len(extensions), 0) for ext in extensions: self.assertIsInstance(ext.name, six.string_types) self.assertIsInstance(ext.alias, six.string_types)
// ... existing code ... self.assertIsInstance(ext.name, six.string_types) self.assertIsInstance(ext.alias, six.string_types) // ... rest of the code ...
3ac86b4c058f920c9ec774c192d84050d61c8cc3
tests/__init__.py
tests/__init__.py
import os from hycc.util import hycc_main def clean(): for path in os.listdir("tests/resources"): if path not in ["hello.hy", "__init__.py"]: os.remove(os.path.join("tests/resources", path)) def test_build_executable(): hycc_main("tests/resources/hello.hy".split()) assert os.path.exists("tests/resources/hello") clean() def test_shared_library(): hycc_main("tests/resources/hello.hy --shared".split()) from tests.resources.hello import hello assert hello() == "hello" clean()
import os from hycc.util import hycc_main def clean(): for path in os.listdir("tests/resources"): if path not in ["hello.hy", "__init__.py"]: path = os.path.join("tests/resources", path) if os.path.isdir(path): os.rmdir(path) else: os.remove(path) def test_build_executable(): hycc_main("tests/resources/hello.hy".split()) assert os.path.exists("tests/resources/hello") clean() def test_shared_library(): hycc_main("tests/resources/hello.hy --shared".split()) from tests.resources.hello import hello assert hello() == "hello" clean()
Fix bug; os.remove cannot remove directories
Fix bug; os.remove cannot remove directories
Python
mit
koji-kojiro/hylang-hycc
import os from hycc.util import hycc_main def clean(): for path in os.listdir("tests/resources"): if path not in ["hello.hy", "__init__.py"]: - os.remove(os.path.join("tests/resources", path)) + path = os.path.join("tests/resources", path) + if os.path.isdir(path): + os.rmdir(path) + else: + os.remove(path) def test_build_executable(): hycc_main("tests/resources/hello.hy".split()) assert os.path.exists("tests/resources/hello") clean() def test_shared_library(): hycc_main("tests/resources/hello.hy --shared".split()) from tests.resources.hello import hello assert hello() == "hello" clean()
Fix bug; os.remove cannot remove directories
## Code Before: import os from hycc.util import hycc_main def clean(): for path in os.listdir("tests/resources"): if path not in ["hello.hy", "__init__.py"]: os.remove(os.path.join("tests/resources", path)) def test_build_executable(): hycc_main("tests/resources/hello.hy".split()) assert os.path.exists("tests/resources/hello") clean() def test_shared_library(): hycc_main("tests/resources/hello.hy --shared".split()) from tests.resources.hello import hello assert hello() == "hello" clean() ## Instruction: Fix bug; os.remove cannot remove directories ## Code After: import os from hycc.util import hycc_main def clean(): for path in os.listdir("tests/resources"): if path not in ["hello.hy", "__init__.py"]: path = os.path.join("tests/resources", path) if os.path.isdir(path): os.rmdir(path) else: os.remove(path) def test_build_executable(): hycc_main("tests/resources/hello.hy".split()) assert os.path.exists("tests/resources/hello") clean() def test_shared_library(): hycc_main("tests/resources/hello.hy --shared".split()) from tests.resources.hello import hello assert hello() == "hello" clean()
... if path not in ["hello.hy", "__init__.py"]: path = os.path.join("tests/resources", path) if os.path.isdir(path): os.rmdir(path) else: os.remove(path) ...
5389fb8575251e2bd8ed18d96f4aa615e9a37bfa
deploy.py
deploy.py
import argparse import os import requests my_domain = "www.proporti.onl" username = "emptysquare" parser = argparse.ArgumentParser() parser.add_argument( "token", metavar="PYTHON_ANYWHERE_TOKEN", help="A Python Anywhere API token for your account", ) args = parser.parse_args() print("Rsync files....") os.system( "rsync -rv --exclude '*.pyc' *" " [email protected]:www.proporti.onl/" ) print("Reinstall dependencies....") os.system( "ssh [email protected]" " '~/my-venv3/bin/pip install -U -r ~/www.proporti.onl/requirements.txt'" ) print("Restarting....") uri = "https://www.pythonanywhere.com/api/v0/user/{uname}/webapps/{dom}/reload/" response = requests.post( uri.format(uname=username, dom=my_domain), headers={"Authorization": "Token {token}".format(token=args.token)}, ) if response.status_code == 200: print("All OK") else: print( "Got unexpected status code {}: {!r}".format( response.status_code, response.content ) )
import argparse import os import requests my_domain = "www.proporti.onl" username = "emptysquare" parser = argparse.ArgumentParser() parser.add_argument( "token", metavar="PYTHON_ANYWHERE_TOKEN", help="A Python Anywhere API token for your account", ) args = parser.parse_args() print("Rsync files....") os.system( "rsync -rv --exclude '*.pyc' *" " [email protected]:www.proporti.onl/" ) print("Reinstall dependencies....") os.system( "ssh [email protected]" " '~/proporti.onl.venv/bin/pip install -U -r ~/www.proporti.onl/requirements.txt'" ) print("Restarting....") uri = "https://www.pythonanywhere.com/api/v0/user/{uname}/webapps/{dom}/reload/" response = requests.post( uri.format(uname=username, dom=my_domain), headers={"Authorization": "Token {token}".format(token=args.token)}, ) if response.status_code == 200: print("All OK") else: print( "Got unexpected status code {}: {!r}".format( response.status_code, response.content ) )
Fix virtualenv path on PythonAnywhere
Fix virtualenv path on PythonAnywhere
Python
apache-2.0
ajdavis/twitter-gender-ratio,ajdavis/twitter-gender-distribution,ajdavis/twitter-gender-distribution,ajdavis/twitter-gender-ratio
import argparse import os import requests my_domain = "www.proporti.onl" username = "emptysquare" parser = argparse.ArgumentParser() parser.add_argument( "token", metavar="PYTHON_ANYWHERE_TOKEN", help="A Python Anywhere API token for your account", ) args = parser.parse_args() print("Rsync files....") os.system( "rsync -rv --exclude '*.pyc' *" " [email protected]:www.proporti.onl/" ) print("Reinstall dependencies....") os.system( "ssh [email protected]" - " '~/my-venv3/bin/pip install -U -r ~/www.proporti.onl/requirements.txt'" + " '~/proporti.onl.venv/bin/pip install -U -r ~/www.proporti.onl/requirements.txt'" ) print("Restarting....") uri = "https://www.pythonanywhere.com/api/v0/user/{uname}/webapps/{dom}/reload/" response = requests.post( uri.format(uname=username, dom=my_domain), headers={"Authorization": "Token {token}".format(token=args.token)}, ) if response.status_code == 200: print("All OK") else: print( "Got unexpected status code {}: {!r}".format( response.status_code, response.content ) )
Fix virtualenv path on PythonAnywhere
## Code Before: import argparse import os import requests my_domain = "www.proporti.onl" username = "emptysquare" parser = argparse.ArgumentParser() parser.add_argument( "token", metavar="PYTHON_ANYWHERE_TOKEN", help="A Python Anywhere API token for your account", ) args = parser.parse_args() print("Rsync files....") os.system( "rsync -rv --exclude '*.pyc' *" " [email protected]:www.proporti.onl/" ) print("Reinstall dependencies....") os.system( "ssh [email protected]" " '~/my-venv3/bin/pip install -U -r ~/www.proporti.onl/requirements.txt'" ) print("Restarting....") uri = "https://www.pythonanywhere.com/api/v0/user/{uname}/webapps/{dom}/reload/" response = requests.post( uri.format(uname=username, dom=my_domain), headers={"Authorization": "Token {token}".format(token=args.token)}, ) if response.status_code == 200: print("All OK") else: print( "Got unexpected status code {}: {!r}".format( response.status_code, response.content ) ) ## Instruction: Fix virtualenv path on PythonAnywhere ## Code After: import argparse import os import requests my_domain = "www.proporti.onl" username = "emptysquare" parser = argparse.ArgumentParser() parser.add_argument( "token", metavar="PYTHON_ANYWHERE_TOKEN", help="A Python Anywhere API token for your account", ) args = parser.parse_args() print("Rsync files....") os.system( "rsync -rv --exclude '*.pyc' *" " [email protected]:www.proporti.onl/" ) print("Reinstall dependencies....") os.system( "ssh [email protected]" " '~/proporti.onl.venv/bin/pip install -U -r ~/www.proporti.onl/requirements.txt'" ) print("Restarting....") uri = "https://www.pythonanywhere.com/api/v0/user/{uname}/webapps/{dom}/reload/" response = requests.post( uri.format(uname=username, dom=my_domain), headers={"Authorization": "Token {token}".format(token=args.token)}, ) if response.status_code == 200: print("All OK") else: print( "Got unexpected status code {}: {!r}".format( response.status_code, response.content ) )
... "ssh [email protected]" " '~/proporti.onl.venv/bin/pip install -U -r ~/www.proporti.onl/requirements.txt'" ) ...
ddb3665a1450e8a1eeee57bbe4b5c0eb7f3f05b1
molly/utils/management/commands/generate_cache_manifest.py
molly/utils/management/commands/generate_cache_manifest.py
import os import os.path from django.core.management.base import NoArgsCommand from django.conf import settings class Command(NoArgsCommand): can_import_settings = True def handle_noargs(self, **options): cache_manifest_path = os.path.join(settings.STATIC_ROOT, 'cache.manifest') static_prefix_length = len(settings.STATIC_ROOT.split(os.sep)) with open(cache_manifest_path, 'w') as cache_manifest: print >>cache_manifest, "CACHE MANIFEST" print >>cache_manifest, "CACHE:" for root, dirs, files in os.walk(settings.STATIC_ROOT): if root == settings.STATIC_ROOT: # Don't cache admin media, desktop or markers dirs.remove('admin') dirs.remove('desktop') dirs.remove('markers') url = '/'.join(root.split(os.sep)[static_prefix_length:]) for file in files: # Don't cache uncompressed JS/CSS _, ext = os.path.splitext(file) if ext in ('.js','.css') and 'c' != url.split('/')[0]: continue print >>cache_manifest, "%s%s/%s" % (settings.STATIC_URL, url, file)
import os import os.path from django.core.management.base import NoArgsCommand from django.conf import settings class Command(NoArgsCommand): can_import_settings = True def handle_noargs(self, **options): cache_manifest_path = os.path.join(settings.STATIC_ROOT, 'cache.manifest') static_prefix_length = len(settings.STATIC_ROOT.split(os.sep)) with open(cache_manifest_path, 'w') as cache_manifest: print >>cache_manifest, "CACHE MANIFEST" print >>cache_manifest, "CACHE:" for root, dirs, files in os.walk(settings.STATIC_ROOT): if root == settings.STATIC_ROOT: # Don't cache admin media, desktop or markers if 'admin' in dirs: dirs.remove('admin') if 'desktop' in dirs: dirs.remove('desktop') if 'markers' in dirs: dirs.remove('markers') if root == os.path.join(setting.STATIC_ROOT, 'touchmaplite', 'images'): # Don't cache touchmaplite markers, we don't use them if 'markers' in dirs: dirs.remove('markers') if 'iui' in dirs: dirs.remove('iui') url = '/'.join(root.split(os.sep)[static_prefix_length:]) for file in files: # Don't cache uncompressed JS/CSS _, ext = os.path.splitext(file) if ext in ('.js','.css') and 'c' != url.split('/')[0]: continue # Don't cache ourselves! print >>cache_manifest, "%s%s/%s" % (settings.STATIC_URL, url, file)
Fix cache.manifest generation when desktop app isn't loaded, also don't include unnecessary touchmaplite files (MOLLY-113)
Fix cache.manifest generation when desktop app isn't loaded, also don't include unnecessary touchmaplite files (MOLLY-113)
Python
apache-2.0
mollyproject/mollyproject,mollyproject/mollyproject,mollyproject/mollyproject
import os import os.path from django.core.management.base import NoArgsCommand from django.conf import settings class Command(NoArgsCommand): can_import_settings = True def handle_noargs(self, **options): cache_manifest_path = os.path.join(settings.STATIC_ROOT, 'cache.manifest') static_prefix_length = len(settings.STATIC_ROOT.split(os.sep)) with open(cache_manifest_path, 'w') as cache_manifest: print >>cache_manifest, "CACHE MANIFEST" print >>cache_manifest, "CACHE:" for root, dirs, files in os.walk(settings.STATIC_ROOT): if root == settings.STATIC_ROOT: # Don't cache admin media, desktop or markers - dirs.remove('admin') + if 'admin' in dirs: dirs.remove('admin') - dirs.remove('desktop') + if 'desktop' in dirs: dirs.remove('desktop') - dirs.remove('markers') + if 'markers' in dirs: dirs.remove('markers') + + if root == os.path.join(setting.STATIC_ROOT, 'touchmaplite', 'images'): + # Don't cache touchmaplite markers, we don't use them + if 'markers' in dirs: dirs.remove('markers') + if 'iui' in dirs: dirs.remove('iui') url = '/'.join(root.split(os.sep)[static_prefix_length:]) for file in files: # Don't cache uncompressed JS/CSS _, ext = os.path.splitext(file) if ext in ('.js','.css') and 'c' != url.split('/')[0]: continue + + # Don't cache ourselves! + print >>cache_manifest, "%s%s/%s" % (settings.STATIC_URL, url, file)
Fix cache.manifest generation when desktop app isn't loaded, also don't include unnecessary touchmaplite files (MOLLY-113)
## Code Before: import os import os.path from django.core.management.base import NoArgsCommand from django.conf import settings class Command(NoArgsCommand): can_import_settings = True def handle_noargs(self, **options): cache_manifest_path = os.path.join(settings.STATIC_ROOT, 'cache.manifest') static_prefix_length = len(settings.STATIC_ROOT.split(os.sep)) with open(cache_manifest_path, 'w') as cache_manifest: print >>cache_manifest, "CACHE MANIFEST" print >>cache_manifest, "CACHE:" for root, dirs, files in os.walk(settings.STATIC_ROOT): if root == settings.STATIC_ROOT: # Don't cache admin media, desktop or markers dirs.remove('admin') dirs.remove('desktop') dirs.remove('markers') url = '/'.join(root.split(os.sep)[static_prefix_length:]) for file in files: # Don't cache uncompressed JS/CSS _, ext = os.path.splitext(file) if ext in ('.js','.css') and 'c' != url.split('/')[0]: continue print >>cache_manifest, "%s%s/%s" % (settings.STATIC_URL, url, file) ## Instruction: Fix cache.manifest generation when desktop app isn't loaded, also don't include unnecessary touchmaplite files (MOLLY-113) ## Code After: import os import os.path from django.core.management.base import NoArgsCommand from django.conf import settings class Command(NoArgsCommand): can_import_settings = True def handle_noargs(self, **options): cache_manifest_path = os.path.join(settings.STATIC_ROOT, 'cache.manifest') static_prefix_length = len(settings.STATIC_ROOT.split(os.sep)) with open(cache_manifest_path, 'w') as cache_manifest: print >>cache_manifest, "CACHE MANIFEST" print >>cache_manifest, "CACHE:" for root, dirs, files in os.walk(settings.STATIC_ROOT): if root == settings.STATIC_ROOT: # Don't cache admin media, desktop or markers if 'admin' in dirs: dirs.remove('admin') if 'desktop' in dirs: dirs.remove('desktop') if 'markers' in dirs: dirs.remove('markers') if root == os.path.join(setting.STATIC_ROOT, 'touchmaplite', 'images'): # Don't cache touchmaplite markers, we don't use them if 'markers' in dirs: dirs.remove('markers') if 'iui' in dirs: dirs.remove('iui') url = '/'.join(root.split(os.sep)[static_prefix_length:]) for file in files: # Don't cache uncompressed JS/CSS _, ext = os.path.splitext(file) if ext in ('.js','.css') and 'c' != url.split('/')[0]: continue # Don't cache ourselves! print >>cache_manifest, "%s%s/%s" % (settings.STATIC_URL, url, file)
// ... existing code ... # Don't cache admin media, desktop or markers if 'admin' in dirs: dirs.remove('admin') if 'desktop' in dirs: dirs.remove('desktop') if 'markers' in dirs: dirs.remove('markers') if root == os.path.join(setting.STATIC_ROOT, 'touchmaplite', 'images'): # Don't cache touchmaplite markers, we don't use them if 'markers' in dirs: dirs.remove('markers') if 'iui' in dirs: dirs.remove('iui') url = '/'.join(root.split(os.sep)[static_prefix_length:]) // ... modified code ... continue # Don't cache ourselves! print >>cache_manifest, "%s%s/%s" % (settings.STATIC_URL, url, file) // ... rest of the code ...
8925c3a827659e1983827368948e95e764a40585
utf9/__init__.py
utf9/__init__.py
from bitarray import bitarray as _bitarray def utf9encode(string): bits = _bitarray() for char in string: for idx, byte in enumerate(char.encode('utf-8')): bits.append(idx) bits.extend('{0:b}'.format(ord(byte)).zfill(8)) return bits.tobytes() def utf9decode(data): bits = _bitarray() bits.frombytes(data) chunks = (bits[x:x+9] for x in xrange(0, len(bits), 9)) string = u'' codepoint = '' for chunk in chunks: if len(chunk) < 9: break if chunk[0] == 0: codepoint, string = '', string + codepoint.decode('utf-8') codepoint += chr(int(chunk[1:].to01(), 2)) return string + codepoint.decode('utf-8')
from bitarray import bitarray as _bitarray def utf9encode(string): """Takes a string and returns a utf9-encoded version.""" bits = _bitarray() for char in string: for idx, byte in enumerate(char.encode('utf-8')): bits.append(idx) bits.extend('{0:b}'.format(ord(byte)).zfill(8)) return bits.tobytes() def utf9decode(data): """Takes utf9-encoded data and returns the corresponding string.""" bits = _bitarray() bits.frombytes(data) chunks = (bits[x:x+9] for x in xrange(0, len(bits), 9)) string = u'' codepoint = '' for chunk in chunks: if len(chunk) < 9: break if chunk[0] == 0: codepoint, string = '', string + codepoint.decode('utf-8') codepoint += chr(int(chunk[1:].to01(), 2)) return string + codepoint.decode('utf-8')
Add module and functions docstring
Add module and functions docstring
Python
mit
enricobacis/utf9
from bitarray import bitarray as _bitarray def utf9encode(string): + """Takes a string and returns a utf9-encoded version.""" bits = _bitarray() for char in string: for idx, byte in enumerate(char.encode('utf-8')): bits.append(idx) bits.extend('{0:b}'.format(ord(byte)).zfill(8)) return bits.tobytes() def utf9decode(data): + """Takes utf9-encoded data and returns the corresponding string.""" bits = _bitarray() bits.frombytes(data) chunks = (bits[x:x+9] for x in xrange(0, len(bits), 9)) string = u'' codepoint = '' for chunk in chunks: if len(chunk) < 9: break if chunk[0] == 0: codepoint, string = '', string + codepoint.decode('utf-8') codepoint += chr(int(chunk[1:].to01(), 2)) return string + codepoint.decode('utf-8')
Add module and functions docstring
## Code Before: from bitarray import bitarray as _bitarray def utf9encode(string): bits = _bitarray() for char in string: for idx, byte in enumerate(char.encode('utf-8')): bits.append(idx) bits.extend('{0:b}'.format(ord(byte)).zfill(8)) return bits.tobytes() def utf9decode(data): bits = _bitarray() bits.frombytes(data) chunks = (bits[x:x+9] for x in xrange(0, len(bits), 9)) string = u'' codepoint = '' for chunk in chunks: if len(chunk) < 9: break if chunk[0] == 0: codepoint, string = '', string + codepoint.decode('utf-8') codepoint += chr(int(chunk[1:].to01(), 2)) return string + codepoint.decode('utf-8') ## Instruction: Add module and functions docstring ## Code After: from bitarray import bitarray as _bitarray def utf9encode(string): """Takes a string and returns a utf9-encoded version.""" bits = _bitarray() for char in string: for idx, byte in enumerate(char.encode('utf-8')): bits.append(idx) bits.extend('{0:b}'.format(ord(byte)).zfill(8)) return bits.tobytes() def utf9decode(data): """Takes utf9-encoded data and returns the corresponding string.""" bits = _bitarray() bits.frombytes(data) chunks = (bits[x:x+9] for x in xrange(0, len(bits), 9)) string = u'' codepoint = '' for chunk in chunks: if len(chunk) < 9: break if chunk[0] == 0: codepoint, string = '', string + codepoint.decode('utf-8') codepoint += chr(int(chunk[1:].to01(), 2)) return string + codepoint.decode('utf-8')
# ... existing code ... def utf9encode(string): """Takes a string and returns a utf9-encoded version.""" bits = _bitarray() # ... modified code ... def utf9decode(data): """Takes utf9-encoded data and returns the corresponding string.""" bits = _bitarray() # ... rest of the code ...
20506c1463c1be9639bceae1168ba97178280796
mrburns/main/tests.py
mrburns/main/tests.py
from django.test import TestCase from nose.tools import ok_ from mrburns.main import views class TestViewHelpers(TestCase): def test_twitter_share_url_fn(self): """Should return a proper and endoded twitter share url.""" url = views.get_tw_share_url(url='http://example.com', text='The Dude abides.') ok_(url.startswith(views.TWITTER_URL + '?')) ok_('dnt=true' in url) ok_('hashtags=firefox' in url) ok_('url=http%3A%2F%2Fexample.com' in url) ok_('text=The+Dude+abides.' in url) def test_facebook_share_url_fn(self): """Should return a proper and encoded facebook share url.""" url = views.get_fb_share_url('http://example.com') ok_(url.startswith(views.FB_URL + '?')) ok_('u=http%3A%2F%2Fexample.com' in url)
from django.test import TestCase from nose.tools import ok_ from mrburns.main import views class TestViewHelpers(TestCase): def test_twitter_share_url_fn(self): """Should return a proper and endoded twitter share url.""" url = views.get_tw_share_url(url='http://example.com', text='The Dude abides.', hashtags='firefox') ok_(url.startswith(views.TWITTER_URL + '?')) ok_('dnt=true' in url) ok_('hashtags=firefox' in url) ok_('url=http%3A%2F%2Fexample.com' in url) ok_('text=The+Dude+abides.' in url) def test_facebook_share_url_fn(self): """Should return a proper and encoded facebook share url.""" url = views.get_fb_share_url('http://example.com') ok_(url.startswith(views.FB_URL + '?')) ok_('u=http%3A%2F%2Fexample.com' in url)
Fix twitter url helper test.
Fix twitter url helper test.
Python
mpl-2.0
almossawi/mrburns,almossawi/mrburns,mozilla/mrburns,mozilla/mrburns,mozilla/mrburns,almossawi/mrburns,almossawi/mrburns
from django.test import TestCase from nose.tools import ok_ from mrburns.main import views class TestViewHelpers(TestCase): def test_twitter_share_url_fn(self): """Should return a proper and endoded twitter share url.""" - url = views.get_tw_share_url(url='http://example.com', text='The Dude abides.') + url = views.get_tw_share_url(url='http://example.com', text='The Dude abides.', + hashtags='firefox') ok_(url.startswith(views.TWITTER_URL + '?')) ok_('dnt=true' in url) ok_('hashtags=firefox' in url) ok_('url=http%3A%2F%2Fexample.com' in url) ok_('text=The+Dude+abides.' in url) def test_facebook_share_url_fn(self): """Should return a proper and encoded facebook share url.""" url = views.get_fb_share_url('http://example.com') ok_(url.startswith(views.FB_URL + '?')) ok_('u=http%3A%2F%2Fexample.com' in url)
Fix twitter url helper test.
## Code Before: from django.test import TestCase from nose.tools import ok_ from mrburns.main import views class TestViewHelpers(TestCase): def test_twitter_share_url_fn(self): """Should return a proper and endoded twitter share url.""" url = views.get_tw_share_url(url='http://example.com', text='The Dude abides.') ok_(url.startswith(views.TWITTER_URL + '?')) ok_('dnt=true' in url) ok_('hashtags=firefox' in url) ok_('url=http%3A%2F%2Fexample.com' in url) ok_('text=The+Dude+abides.' in url) def test_facebook_share_url_fn(self): """Should return a proper and encoded facebook share url.""" url = views.get_fb_share_url('http://example.com') ok_(url.startswith(views.FB_URL + '?')) ok_('u=http%3A%2F%2Fexample.com' in url) ## Instruction: Fix twitter url helper test. ## Code After: from django.test import TestCase from nose.tools import ok_ from mrburns.main import views class TestViewHelpers(TestCase): def test_twitter_share_url_fn(self): """Should return a proper and endoded twitter share url.""" url = views.get_tw_share_url(url='http://example.com', text='The Dude abides.', hashtags='firefox') ok_(url.startswith(views.TWITTER_URL + '?')) ok_('dnt=true' in url) ok_('hashtags=firefox' in url) ok_('url=http%3A%2F%2Fexample.com' in url) ok_('text=The+Dude+abides.' in url) def test_facebook_share_url_fn(self): """Should return a proper and encoded facebook share url.""" url = views.get_fb_share_url('http://example.com') ok_(url.startswith(views.FB_URL + '?')) ok_('u=http%3A%2F%2Fexample.com' in url)
# ... existing code ... """Should return a proper and endoded twitter share url.""" url = views.get_tw_share_url(url='http://example.com', text='The Dude abides.', hashtags='firefox') ok_(url.startswith(views.TWITTER_URL + '?')) # ... rest of the code ...
bee9373dcf852e7af9f0f1a78dcc17a0922f96fe
anchorhub/tests/test_main.py
anchorhub/tests/test_main.py
from nose.tools import * import anchorhub.main as main def test_one(): """ main.py: Test defaults with local directory as input. """ main.main(['.'])
from nose.tools import * import anchorhub.main as main from anchorhub.util.getanchorhubpath import get_anchorhub_path from anchorhub.compatibility import get_path_separator def test_one(): """ main.py: Test defaults with local directory as input. """ main.main([get_anchorhub_path() + get_path_separator() + '../sample/multi-file'])
Modify main.py tests to use get_anchorhub_path()
Modify main.py tests to use get_anchorhub_path()
Python
apache-2.0
samjabrahams/anchorhub
from nose.tools import * import anchorhub.main as main + from anchorhub.util.getanchorhubpath import get_anchorhub_path + from anchorhub.compatibility import get_path_separator def test_one(): """ main.py: Test defaults with local directory as input. """ - main.main(['.']) + main.main([get_anchorhub_path() + get_path_separator() + + '../sample/multi-file'])
Modify main.py tests to use get_anchorhub_path()
## Code Before: from nose.tools import * import anchorhub.main as main def test_one(): """ main.py: Test defaults with local directory as input. """ main.main(['.']) ## Instruction: Modify main.py tests to use get_anchorhub_path() ## Code After: from nose.tools import * import anchorhub.main as main from anchorhub.util.getanchorhubpath import get_anchorhub_path from anchorhub.compatibility import get_path_separator def test_one(): """ main.py: Test defaults with local directory as input. """ main.main([get_anchorhub_path() + get_path_separator() + '../sample/multi-file'])
... import anchorhub.main as main from anchorhub.util.getanchorhubpath import get_anchorhub_path from anchorhub.compatibility import get_path_separator ... """ main.main([get_anchorhub_path() + get_path_separator() + '../sample/multi-file']) ...
601fe6fd1fc2f34f7cefe2fac0ff343144d139cc
src/ipf/ipfblock/rgb2gray.py
src/ipf/ipfblock/rgb2gray.py
import ipfblock import ioport import ipf.ipfblock.processing from ipf.ipftype.ipfimage3ctype import IPFImage3cType from ipf.ipftype.ipfimage1ctype import IPFImage1cType class RGB2Gray(ipfblock.IPFBlock): """ Convert 3 channel image to 1 channel gray block class """ type = "RGB2Gray" category = "Channel operations" is_abstract_block = False def __init__(self): super(RGB2Gray, self).__init__() self.input_ports["input_image"] = ioport.IPort(self, IPFImage3cType) self.output_ports["output_image"] = ioport.OPort(self, IPFImage1cType) self.processing_function = ipf.ipfblock.processing.rgb2gray def get_preview_image(self): return IPFImage3cType.convert(self.output_ports["output_image"]._value)
import ipfblock import ioport import ipf.ipfblock.processing from ipf.ipftype.ipfimage3ctype import IPFImage3cType from ipf.ipftype.ipfimage1ctype import IPFImage1cType class RGB2Gray(ipfblock.IPFBlock): """ Convert 3 channel image to 1 channel gray block class """ type = "RGB2Gray" category = "Channel operations" is_abstract_block = False def __init__(self): super(RGB2Gray, self).__init__() self.input_ports["input_image"] = ioport.IPort(self, IPFImage3cType) self.output_ports["output_image"] = ioport.OPort(self, IPFImage1cType) self.processing_function = ipf.ipfblock.processing.rgb2gray def get_preview_image(self): return self.output_ports["output_image"]._value
Change get_preview_image to same as other blocks (because we fix ipl to pil convert for 1-channel images)
Change get_preview_image to same as other blocks (because we fix ipl to pil convert for 1-channel images)
Python
lgpl-2.1
anton-golubkov/Garland,anton-golubkov/Garland
import ipfblock import ioport import ipf.ipfblock.processing from ipf.ipftype.ipfimage3ctype import IPFImage3cType from ipf.ipftype.ipfimage1ctype import IPFImage1cType class RGB2Gray(ipfblock.IPFBlock): """ Convert 3 channel image to 1 channel gray block class """ type = "RGB2Gray" category = "Channel operations" is_abstract_block = False def __init__(self): super(RGB2Gray, self).__init__() self.input_ports["input_image"] = ioport.IPort(self, IPFImage3cType) self.output_ports["output_image"] = ioport.OPort(self, IPFImage1cType) self.processing_function = ipf.ipfblock.processing.rgb2gray def get_preview_image(self): - return IPFImage3cType.convert(self.output_ports["output_image"]._value) + return self.output_ports["output_image"]._value
Change get_preview_image to same as other blocks (because we fix ipl to pil convert for 1-channel images)
## Code Before: import ipfblock import ioport import ipf.ipfblock.processing from ipf.ipftype.ipfimage3ctype import IPFImage3cType from ipf.ipftype.ipfimage1ctype import IPFImage1cType class RGB2Gray(ipfblock.IPFBlock): """ Convert 3 channel image to 1 channel gray block class """ type = "RGB2Gray" category = "Channel operations" is_abstract_block = False def __init__(self): super(RGB2Gray, self).__init__() self.input_ports["input_image"] = ioport.IPort(self, IPFImage3cType) self.output_ports["output_image"] = ioport.OPort(self, IPFImage1cType) self.processing_function = ipf.ipfblock.processing.rgb2gray def get_preview_image(self): return IPFImage3cType.convert(self.output_ports["output_image"]._value) ## Instruction: Change get_preview_image to same as other blocks (because we fix ipl to pil convert for 1-channel images) ## Code After: import ipfblock import ioport import ipf.ipfblock.processing from ipf.ipftype.ipfimage3ctype import IPFImage3cType from ipf.ipftype.ipfimage1ctype import IPFImage1cType class RGB2Gray(ipfblock.IPFBlock): """ Convert 3 channel image to 1 channel gray block class """ type = "RGB2Gray" category = "Channel operations" is_abstract_block = False def __init__(self): super(RGB2Gray, self).__init__() self.input_ports["input_image"] = ioport.IPort(self, IPFImage3cType) self.output_ports["output_image"] = ioport.OPort(self, IPFImage1cType) self.processing_function = ipf.ipfblock.processing.rgb2gray def get_preview_image(self): return self.output_ports["output_image"]._value
// ... existing code ... def get_preview_image(self): return self.output_ports["output_image"]._value // ... rest of the code ...
791e254c6f1efed88bdc0714ee9bb264634e74a8
transunit.py
transunit.py
class TransUnit(object): "Container for XLIFF trans-unit element" def __init__(self, argument): self.origin_unit = argument self.attributes = argument.attrib self.id = '' self.ns = '' self.state = '' @staticmethod def create(xml_tu): tunit = TransUnit(xml_tu) tunit.id = tunit.attributes['id'] tunit.ns = tunit.__read_ns() tunit.state = tunit.__get_state_from_target() return tunit def __get_state_from_target(self): target = self.origin_unit.find('{}target'.format(self.ns)) if "state" in target.attrib.keys(): return target.attrib['state'] else: return '' def __has_ns(self): return '{' in self.origin_unit.tag def __read_ns(self): if self.__has_ns(): ns, tag = self.origin_unit.tag.split('}') ns = ns + '}' return ns else: return '' def has_any_state(self, list_of_states): return self.state in list_of_states
class TransUnit(object): "Container for XLIFF trans-unit element" def __init__(self, argument): self.origin_unit = argument self.attributes = argument.attrib self.id = '' self.ns = '' self.state = '' @staticmethod def create(xml_tu): tunit = TransUnit(xml_tu) tunit.id = tunit.attributes['id'] tunit.ns = tunit._read_ns() tunit.state = tunit._get_state_from_target() return tunit def _read_ns(self): if self._has_ns(): ns, tag = self.origin_unit.tag.split('}') ns = ns + '}' return ns else: return '' def _has_ns(self): return '{' in self.origin_unit.tag def _get_state_from_target(self): target = self.origin_unit.find('{}target'.format(self.ns)) if "state" in target.attrib.keys(): return target.attrib['state'] else: return '' def has_any_state(self, list_of_states): return self.state in list_of_states
Restructure transUnit class for better readibility
Restructure transUnit class for better readibility
Python
mit
jakub-szczepaniak/xliff
- - class TransUnit(object): "Container for XLIFF trans-unit element" def __init__(self, argument): self.origin_unit = argument self.attributes = argument.attrib self.id = '' self.ns = '' self.state = '' @staticmethod def create(xml_tu): tunit = TransUnit(xml_tu) tunit.id = tunit.attributes['id'] - tunit.ns = tunit.__read_ns() + tunit.ns = tunit._read_ns() - tunit.state = tunit.__get_state_from_target() + tunit.state = tunit._get_state_from_target() return tunit + def _read_ns(self): + if self._has_ns(): + ns, tag = self.origin_unit.tag.split('}') + ns = ns + '}' + return ns + else: + return '' + + def _has_ns(self): + return '{' in self.origin_unit.tag + - def __get_state_from_target(self): + def _get_state_from_target(self): target = self.origin_unit.find('{}target'.format(self.ns)) if "state" in target.attrib.keys(): return target.attrib['state'] else: return '' - def __has_ns(self): - return '{' in self.origin_unit.tag - - def __read_ns(self): - if self.__has_ns(): - ns, tag = self.origin_unit.tag.split('}') - ns = ns + '}' - return ns - else: - return '' - def has_any_state(self, list_of_states): return self.state in list_of_states
Restructure transUnit class for better readibility
## Code Before: class TransUnit(object): "Container for XLIFF trans-unit element" def __init__(self, argument): self.origin_unit = argument self.attributes = argument.attrib self.id = '' self.ns = '' self.state = '' @staticmethod def create(xml_tu): tunit = TransUnit(xml_tu) tunit.id = tunit.attributes['id'] tunit.ns = tunit.__read_ns() tunit.state = tunit.__get_state_from_target() return tunit def __get_state_from_target(self): target = self.origin_unit.find('{}target'.format(self.ns)) if "state" in target.attrib.keys(): return target.attrib['state'] else: return '' def __has_ns(self): return '{' in self.origin_unit.tag def __read_ns(self): if self.__has_ns(): ns, tag = self.origin_unit.tag.split('}') ns = ns + '}' return ns else: return '' def has_any_state(self, list_of_states): return self.state in list_of_states ## Instruction: Restructure transUnit class for better readibility ## Code After: class TransUnit(object): "Container for XLIFF trans-unit element" def __init__(self, argument): self.origin_unit = argument self.attributes = argument.attrib self.id = '' self.ns = '' self.state = '' @staticmethod def create(xml_tu): tunit = TransUnit(xml_tu) tunit.id = tunit.attributes['id'] tunit.ns = tunit._read_ns() tunit.state = tunit._get_state_from_target() return tunit def _read_ns(self): if self._has_ns(): ns, tag = self.origin_unit.tag.split('}') ns = ns + '}' return ns else: return '' def _has_ns(self): return '{' in self.origin_unit.tag def _get_state_from_target(self): target = self.origin_unit.find('{}target'.format(self.ns)) if "state" in target.attrib.keys(): return target.attrib['state'] else: return '' def has_any_state(self, list_of_states): return self.state in list_of_states
// ... existing code ... class TransUnit(object): // ... modified code ... tunit.id = tunit.attributes['id'] tunit.ns = tunit._read_ns() tunit.state = tunit._get_state_from_target() return tunit ... def _read_ns(self): if self._has_ns(): ns, tag = self.origin_unit.tag.split('}') ns = ns + '}' return ns else: return '' def _has_ns(self): return '{' in self.origin_unit.tag def _get_state_from_target(self): ... def has_any_state(self, list_of_states): // ... rest of the code ...
443874df07a3c3ed8d9e075b25e5f93c1de0128b
tests/devices_test/device_packages_test.py
tests/devices_test/device_packages_test.py
import unittest from blivet.devices import DiskDevice from blivet.devices import LUKSDevice from blivet.devices import MDRaidArrayDevice from blivet.formats import getFormat class DevicePackagesTestCase(unittest.TestCase): """Test device name validation""" def testPackages(self): dev1 = DiskDevice("name", fmt=getFormat("mdmember")) dev2 = DiskDevice("other", fmt=getFormat("mdmember")) dev = MDRaidArrayDevice("dev", level="raid1", parents=[dev1,dev2]) luks = LUKSDevice("luks", parents=[dev]) packages = luks.packages # no duplicates in list of packages self.assertListEqual(packages, list(set(packages))) # several packages that ought to be included are for package in dev1.packages + dev2.packages + dev.packages: self.assertIn(package, packages) for package in dev1.format.packages + dev2.format.packages + dev.format.packages: self.assertIn(package, packages)
import unittest from blivet.devices import DiskDevice from blivet.devices import LUKSDevice from blivet.devices import MDRaidArrayDevice from blivet.formats import getFormat class DevicePackagesTestCase(unittest.TestCase): """Test device name validation""" def testPackages(self): dev1 = DiskDevice("name", fmt=getFormat("mdmember")) dev2 = DiskDevice("other", fmt=getFormat("mdmember")) dev = MDRaidArrayDevice("dev", level="raid1", parents=[dev1,dev2]) luks = LUKSDevice("luks", parents=[dev]) packages = luks.packages # no duplicates in list of packages self.assertEqual(len(packages), len(set(packages))) # several packages that ought to be included are for package in dev1.packages + dev2.packages + dev.packages: self.assertIn(package, packages) for package in dev1.format.packages + dev2.format.packages + dev.format.packages: self.assertIn(package, packages)
Use len of set to check for duplicates in list of packages.
Use len of set to check for duplicates in list of packages. Resolves: #154. Checking for equality of the two lists was a mistake, since the order of the list generated from the set is undefined.
Python
lgpl-2.1
rhinstaller/blivet,jkonecny12/blivet,AdamWill/blivet,vojtechtrefny/blivet,jkonecny12/blivet,rvykydal/blivet,vpodzime/blivet,rhinstaller/blivet,AdamWill/blivet,rvykydal/blivet,vojtechtrefny/blivet,vpodzime/blivet
import unittest from blivet.devices import DiskDevice from blivet.devices import LUKSDevice from blivet.devices import MDRaidArrayDevice from blivet.formats import getFormat class DevicePackagesTestCase(unittest.TestCase): """Test device name validation""" def testPackages(self): dev1 = DiskDevice("name", fmt=getFormat("mdmember")) dev2 = DiskDevice("other", fmt=getFormat("mdmember")) dev = MDRaidArrayDevice("dev", level="raid1", parents=[dev1,dev2]) luks = LUKSDevice("luks", parents=[dev]) packages = luks.packages # no duplicates in list of packages - self.assertListEqual(packages, list(set(packages))) + self.assertEqual(len(packages), len(set(packages))) # several packages that ought to be included are for package in dev1.packages + dev2.packages + dev.packages: self.assertIn(package, packages) for package in dev1.format.packages + dev2.format.packages + dev.format.packages: self.assertIn(package, packages)
Use len of set to check for duplicates in list of packages.
## Code Before: import unittest from blivet.devices import DiskDevice from blivet.devices import LUKSDevice from blivet.devices import MDRaidArrayDevice from blivet.formats import getFormat class DevicePackagesTestCase(unittest.TestCase): """Test device name validation""" def testPackages(self): dev1 = DiskDevice("name", fmt=getFormat("mdmember")) dev2 = DiskDevice("other", fmt=getFormat("mdmember")) dev = MDRaidArrayDevice("dev", level="raid1", parents=[dev1,dev2]) luks = LUKSDevice("luks", parents=[dev]) packages = luks.packages # no duplicates in list of packages self.assertListEqual(packages, list(set(packages))) # several packages that ought to be included are for package in dev1.packages + dev2.packages + dev.packages: self.assertIn(package, packages) for package in dev1.format.packages + dev2.format.packages + dev.format.packages: self.assertIn(package, packages) ## Instruction: Use len of set to check for duplicates in list of packages. ## Code After: import unittest from blivet.devices import DiskDevice from blivet.devices import LUKSDevice from blivet.devices import MDRaidArrayDevice from blivet.formats import getFormat class DevicePackagesTestCase(unittest.TestCase): """Test device name validation""" def testPackages(self): dev1 = DiskDevice("name", fmt=getFormat("mdmember")) dev2 = DiskDevice("other", fmt=getFormat("mdmember")) dev = MDRaidArrayDevice("dev", level="raid1", parents=[dev1,dev2]) luks = LUKSDevice("luks", parents=[dev]) packages = luks.packages # no duplicates in list of packages self.assertEqual(len(packages), len(set(packages))) # several packages that ought to be included are for package in dev1.packages + dev2.packages + dev.packages: self.assertIn(package, packages) for package in dev1.format.packages + dev2.format.packages + dev.format.packages: self.assertIn(package, packages)
// ... existing code ... # no duplicates in list of packages self.assertEqual(len(packages), len(set(packages))) // ... rest of the code ...
151c3484da58fa02f7d2c69454be3cb4e3395d05
recipes/recipe_modules/bot_update/tests/ensure_checkout.py
recipes/recipe_modules/bot_update/tests/ensure_checkout.py
from recipe_engine import post_process DEPS = [ 'bot_update', 'gclient', 'recipe_engine/json', ] def RunSteps(api): api.gclient.set_config('depot_tools') api.bot_update.ensure_checkout() def GenTests(api): yield ( api.test('basic') + api.post_process(post_process.StatusCodeIn, 0) + api.post_process(post_process.DropExpectation) ) yield ( api.test('failure') + api.override_step_data( 'bot_update', api.json.output({'did_run': True}), retcode=1) + api.post_process(post_process.StatusCodeIn, 1) + api.post_process(post_process.DropExpectation) )
from recipe_engine import post_process DEPS = [ 'bot_update', 'gclient', 'recipe_engine/json', ] def RunSteps(api): api.gclient.set_config('depot_tools') api.bot_update.ensure_checkout() def GenTests(api): yield ( api.test('basic') + api.post_process(post_process.StatusSuccess) + api.post_process(post_process.DropExpectation) ) yield ( api.test('failure') + api.override_step_data( 'bot_update', api.json.output({'did_run': True}), retcode=1) + api.post_process(post_process.StatusAnyFailure) + api.post_process(post_process.DropExpectation) )
Replace post-process checks with ones that are not deprecated
Replace post-process checks with ones that are not deprecated [email protected] Bug: 899266 Change-Id: Ia9b1f38590d636fa2858a2bd0bbf75d6b2cfe8fa Reviewed-on: https://chromium-review.googlesource.com/c/1483033 Reviewed-by: Robbie Iannucci <[email protected]> Reviewed-by: John Budorick <[email protected]> Commit-Queue: Sergiy Belozorov <[email protected]>
Python
bsd-3-clause
CoherentLabs/depot_tools,CoherentLabs/depot_tools
from recipe_engine import post_process DEPS = [ 'bot_update', 'gclient', 'recipe_engine/json', ] def RunSteps(api): api.gclient.set_config('depot_tools') api.bot_update.ensure_checkout() def GenTests(api): yield ( api.test('basic') + - api.post_process(post_process.StatusCodeIn, 0) + + api.post_process(post_process.StatusSuccess) + api.post_process(post_process.DropExpectation) ) yield ( api.test('failure') + api.override_step_data( 'bot_update', api.json.output({'did_run': True}), retcode=1) + - api.post_process(post_process.StatusCodeIn, 1) + + api.post_process(post_process.StatusAnyFailure) + api.post_process(post_process.DropExpectation) )
Replace post-process checks with ones that are not deprecated
## Code Before: from recipe_engine import post_process DEPS = [ 'bot_update', 'gclient', 'recipe_engine/json', ] def RunSteps(api): api.gclient.set_config('depot_tools') api.bot_update.ensure_checkout() def GenTests(api): yield ( api.test('basic') + api.post_process(post_process.StatusCodeIn, 0) + api.post_process(post_process.DropExpectation) ) yield ( api.test('failure') + api.override_step_data( 'bot_update', api.json.output({'did_run': True}), retcode=1) + api.post_process(post_process.StatusCodeIn, 1) + api.post_process(post_process.DropExpectation) ) ## Instruction: Replace post-process checks with ones that are not deprecated ## Code After: from recipe_engine import post_process DEPS = [ 'bot_update', 'gclient', 'recipe_engine/json', ] def RunSteps(api): api.gclient.set_config('depot_tools') api.bot_update.ensure_checkout() def GenTests(api): yield ( api.test('basic') + api.post_process(post_process.StatusSuccess) + api.post_process(post_process.DropExpectation) ) yield ( api.test('failure') + api.override_step_data( 'bot_update', api.json.output({'did_run': True}), retcode=1) + api.post_process(post_process.StatusAnyFailure) + api.post_process(post_process.DropExpectation) )
# ... existing code ... api.test('basic') + api.post_process(post_process.StatusSuccess) + api.post_process(post_process.DropExpectation) # ... modified code ... retcode=1) + api.post_process(post_process.StatusAnyFailure) + api.post_process(post_process.DropExpectation) # ... rest of the code ...
39eea826a1f29c2bd77d5f4f5bead7011b47f0bb
sed/engine/__init__.py
sed/engine/__init__.py
from sed.engine.StreamEditor import StreamEditor from sed.engine.sed_file_util import call_main from sed.engine.match_engine import ACCEPT, REJECT, NEXT, REPEAT, CUT from sed.engine.sed_regex import ANY __all__ = [ "StreamEditor", "call_main", "ACCEPT", "REJECT", "NEXT", "REPEAT", "ANY", ]
from sed.engine.StreamEditor import StreamEditor from sed.engine.sed_file_util import call_main from sed.engine.match_engine import ( ACCEPT, REJECT, NEXT, REPEAT, CUT, ) from sed.engine.sed_regex import ANY __all__ = [ "StreamEditor", "call_main", "ACCEPT", "REJECT", "NEXT", "REPEAT", "CUT", "ANY", ]
Add CUT to list of externally visible objects
Add CUT to list of externally visible objects
Python
mit
hughdbrown/sed,hughdbrown/sed
from sed.engine.StreamEditor import StreamEditor from sed.engine.sed_file_util import call_main - from sed.engine.match_engine import ACCEPT, REJECT, NEXT, REPEAT, CUT + from sed.engine.match_engine import ( + ACCEPT, + REJECT, + NEXT, + REPEAT, + CUT, + ) from sed.engine.sed_regex import ANY __all__ = [ "StreamEditor", "call_main", - "ACCEPT", "REJECT", "NEXT", "REPEAT", + "ACCEPT", "REJECT", "NEXT", "REPEAT", "CUT", "ANY", ]
Add CUT to list of externally visible objects
## Code Before: from sed.engine.StreamEditor import StreamEditor from sed.engine.sed_file_util import call_main from sed.engine.match_engine import ACCEPT, REJECT, NEXT, REPEAT, CUT from sed.engine.sed_regex import ANY __all__ = [ "StreamEditor", "call_main", "ACCEPT", "REJECT", "NEXT", "REPEAT", "ANY", ] ## Instruction: Add CUT to list of externally visible objects ## Code After: from sed.engine.StreamEditor import StreamEditor from sed.engine.sed_file_util import call_main from sed.engine.match_engine import ( ACCEPT, REJECT, NEXT, REPEAT, CUT, ) from sed.engine.sed_regex import ANY __all__ = [ "StreamEditor", "call_main", "ACCEPT", "REJECT", "NEXT", "REPEAT", "CUT", "ANY", ]
// ... existing code ... from sed.engine.sed_file_util import call_main from sed.engine.match_engine import ( ACCEPT, REJECT, NEXT, REPEAT, CUT, ) from sed.engine.sed_regex import ANY // ... modified code ... "call_main", "ACCEPT", "REJECT", "NEXT", "REPEAT", "CUT", "ANY", // ... rest of the code ...
53ad3866b8dfbd012748e4ad7d7ed7025d491bd0
src/alexa-main.py
src/alexa-main.py
import handlers.events as events APPLICATION_ID = "amzn1.ask.skill.dd677950-cade-4805-b1f1-ce2e3a3569f0" def lambda_handler(event, context): if event['session']['new']: events.on_session_started({'requestId': event['request']['requestId']}, event['session']) request_type = event['request']['type'] if request_type == "LaunchRequest": return events.on_launch(event['request'], event['session']) elif request_type == "IntentRequest": return events.on_intent(event['request'], event['session']) elif request_type == "SessionEndedRequest": return events.on_session_ended(event['request'], event['session'])
import handlers.events as events APPLICATION_ID = "amzn1.ask.skill.dd677950-cade-4805-b1f1-ce2e3a3569f0" def lambda_handler(event, context): # Make sure only this Alexa skill can use this function if event['session']['application']['applicationId'] != APPLICATION_ID: raise ValueError("Invalid Application ID") if event['session']['new']: events.on_session_started({'requestId': event['request']['requestId']}, event['session']) request_type = event['request']['type'] if request_type == "LaunchRequest": return events.on_launch(event['request'], event['session']) elif request_type == "IntentRequest": return events.on_intent(event['request'], event['session']) elif request_type == "SessionEndedRequest": return events.on_session_ended(event['request'], event['session'])
REVERT remove application id validation
REVERT remove application id validation
Python
mit
mauriceyap/ccm-assistant
import handlers.events as events APPLICATION_ID = "amzn1.ask.skill.dd677950-cade-4805-b1f1-ce2e3a3569f0" def lambda_handler(event, context): + # Make sure only this Alexa skill can use this function + if event['session']['application']['applicationId'] != APPLICATION_ID: + raise ValueError("Invalid Application ID") + if event['session']['new']: events.on_session_started({'requestId': event['request']['requestId']}, event['session']) request_type = event['request']['type'] if request_type == "LaunchRequest": return events.on_launch(event['request'], event['session']) elif request_type == "IntentRequest": return events.on_intent(event['request'], event['session']) elif request_type == "SessionEndedRequest": return events.on_session_ended(event['request'], event['session'])
REVERT remove application id validation
## Code Before: import handlers.events as events APPLICATION_ID = "amzn1.ask.skill.dd677950-cade-4805-b1f1-ce2e3a3569f0" def lambda_handler(event, context): if event['session']['new']: events.on_session_started({'requestId': event['request']['requestId']}, event['session']) request_type = event['request']['type'] if request_type == "LaunchRequest": return events.on_launch(event['request'], event['session']) elif request_type == "IntentRequest": return events.on_intent(event['request'], event['session']) elif request_type == "SessionEndedRequest": return events.on_session_ended(event['request'], event['session']) ## Instruction: REVERT remove application id validation ## Code After: import handlers.events as events APPLICATION_ID = "amzn1.ask.skill.dd677950-cade-4805-b1f1-ce2e3a3569f0" def lambda_handler(event, context): # Make sure only this Alexa skill can use this function if event['session']['application']['applicationId'] != APPLICATION_ID: raise ValueError("Invalid Application ID") if event['session']['new']: events.on_session_started({'requestId': event['request']['requestId']}, event['session']) request_type = event['request']['type'] if request_type == "LaunchRequest": return events.on_launch(event['request'], event['session']) elif request_type == "IntentRequest": return events.on_intent(event['request'], event['session']) elif request_type == "SessionEndedRequest": return events.on_session_ended(event['request'], event['session'])
// ... existing code ... def lambda_handler(event, context): # Make sure only this Alexa skill can use this function if event['session']['application']['applicationId'] != APPLICATION_ID: raise ValueError("Invalid Application ID") if event['session']['new']: // ... rest of the code ...
0dcecfbd1e6ce9e35febc9f4ee9bcbfac1fb8f6a
hytra/util/skimage_tifffile_hack.py
hytra/util/skimage_tifffile_hack.py
from __future__ import print_function, absolute_import, nested_scopes, generators, division, with_statement, unicode_literals from skimage.external import tifffile def hack(input_tif): """ This method allows to bypass the strange faulty behaviour of skimage.external.tifffile.imread() when it gets a list of paths or a glob pattern. This function extracts the image names and the path. Then, one can os.chdir(path) and call tifffile.imread(name), what will now behave well. """ name = []; path = str() for i in input_tif: name.append(i.split('/')[-1]) path_split = list(input_tif)[0].split('/')[0:-1] for i in path_split: path += i+'/' return path, name
from __future__ import print_function, absolute_import, nested_scopes, generators, division, with_statement, unicode_literals from skimage.external import tifffile import os.path def hack(input_tif): """ This method allows to bypass the strange faulty behaviour of skimage.external.tifffile.imread() when it gets a list of paths or a glob pattern. This function extracts the image names and the path. Then, one can os.chdir(path) and call tifffile.imread(names), what will now behave well. """ assert len(input_tif) > 0 names = [] path = str() for i in input_tif: names.append(os.path.basename(i)) path = os.path.dirname(input_tif[0]) return path, names
Fix tiffile hack to use os.path
Fix tiffile hack to use os.path
Python
mit
chaubold/hytra,chaubold/hytra,chaubold/hytra
from __future__ import print_function, absolute_import, nested_scopes, generators, division, with_statement, unicode_literals from skimage.external import tifffile + import os.path def hack(input_tif): """ This method allows to bypass the strange faulty behaviour of skimage.external.tifffile.imread() when it gets a list of paths or a glob pattern. This function extracts the image names and the path. - Then, one can os.chdir(path) and call tifffile.imread(name), + Then, one can os.chdir(path) and call tifffile.imread(names), what will now behave well. """ - name = []; path = str() + assert len(input_tif) > 0 + names = [] + path = str() for i in input_tif: + names.append(os.path.basename(i)) + path = os.path.dirname(input_tif[0]) - name.append(i.split('/')[-1]) - path_split = list(input_tif)[0].split('/')[0:-1] - for i in path_split: - path += i+'/' - return path, name + return path, names
Fix tiffile hack to use os.path
## Code Before: from __future__ import print_function, absolute_import, nested_scopes, generators, division, with_statement, unicode_literals from skimage.external import tifffile def hack(input_tif): """ This method allows to bypass the strange faulty behaviour of skimage.external.tifffile.imread() when it gets a list of paths or a glob pattern. This function extracts the image names and the path. Then, one can os.chdir(path) and call tifffile.imread(name), what will now behave well. """ name = []; path = str() for i in input_tif: name.append(i.split('/')[-1]) path_split = list(input_tif)[0].split('/')[0:-1] for i in path_split: path += i+'/' return path, name ## Instruction: Fix tiffile hack to use os.path ## Code After: from __future__ import print_function, absolute_import, nested_scopes, generators, division, with_statement, unicode_literals from skimage.external import tifffile import os.path def hack(input_tif): """ This method allows to bypass the strange faulty behaviour of skimage.external.tifffile.imread() when it gets a list of paths or a glob pattern. This function extracts the image names and the path. Then, one can os.chdir(path) and call tifffile.imread(names), what will now behave well. """ assert len(input_tif) > 0 names = [] path = str() for i in input_tif: names.append(os.path.basename(i)) path = os.path.dirname(input_tif[0]) return path, names
// ... existing code ... from skimage.external import tifffile import os.path // ... modified code ... a glob pattern. This function extracts the image names and the path. Then, one can os.chdir(path) and call tifffile.imread(names), what will now behave well. ... """ assert len(input_tif) > 0 names = [] path = str() for i in input_tif: names.append(os.path.basename(i)) path = os.path.dirname(input_tif[0]) return path, names // ... rest of the code ...
e513e41dd10df009a3db7641774db1acba60a301
tensormate/graph/__init__.py
tensormate/graph/__init__.py
from tensormate.graph.base import * from tensormate.graph.data_pipeline import *
from tensormate.graph.base import * from tensormate.graph.data_pipeline import * from tensormate.graph.image_graph import *
Add an access from graph
Add an access from graph
Python
apache-2.0
songgc/tensormate
from tensormate.graph.base import * from tensormate.graph.data_pipeline import * + from tensormate.graph.image_graph import *
Add an access from graph
## Code Before: from tensormate.graph.base import * from tensormate.graph.data_pipeline import * ## Instruction: Add an access from graph ## Code After: from tensormate.graph.base import * from tensormate.graph.data_pipeline import * from tensormate.graph.image_graph import *
... from tensormate.graph.data_pipeline import * from tensormate.graph.image_graph import * ...
9ae5b882b987cd56fe20996733a828171b18aa3a
polygraph/types/tests/test_object_type.py
polygraph/types/tests/test_object_type.py
from collections import OrderedDict from unittest import TestCase from graphql.type.definition import GraphQLField, GraphQLObjectType from graphql.type.scalars import GraphQLString from polygraph.types.definitions import PolygraphNonNull from polygraph.types.fields import String from polygraph.types.object_type import ObjectType from polygraph.types.tests.helpers import graphql_objects_equal class HelloWorldObject(ObjectType): """ This is a test object """ first = String(description="First violin", nullable=True) second = String(description="Second fiddle", nullable=False) third = String(deprecation_reason="Third is dead") class ObjectTypeTest(TestCase): def test_simple_object_type(self): hello_world = HelloWorldObject() expected = GraphQLObjectType( name="HelloWorldObject", description="This is a test object", fields=OrderedDict({ "first": GraphQLField(GraphQLString, None, None, None, "First violin"), "second": GraphQLField( PolygraphNonNull(GraphQLString), None, None, None, "Second fiddle"), "third": GraphQLField( PolygraphNonNull(GraphQLString), None, None, "Third is dead", None), }) ) actual = hello_world.build_definition() self.assertTrue(graphql_objects_equal(expected, actual))
from collections import OrderedDict from unittest import TestCase from graphql.type.definition import GraphQLField, GraphQLObjectType from graphql.type.scalars import GraphQLString from polygraph.types.definitions import PolygraphNonNull from polygraph.types.fields import String, Int from polygraph.types.object_type import ObjectType from polygraph.types.tests.helpers import graphql_objects_equal class ObjectTypeTest(TestCase): def test_simple_object_type(self): class HelloWorldObject(ObjectType): """ This is a test object """ first = String(description="First violin", nullable=True) second = String(description="Second fiddle", nullable=False) third = String(deprecation_reason="Third is dead") hello_world = HelloWorldObject() expected = GraphQLObjectType( name="HelloWorldObject", description="This is a test object", fields=OrderedDict({ "first": GraphQLField(GraphQLString, None, None, None, "First violin"), "second": GraphQLField( PolygraphNonNull(GraphQLString), None, None, None, "Second fiddle"), "third": GraphQLField( PolygraphNonNull(GraphQLString), None, None, "Third is dead", None), }) ) actual = hello_world.build_definition() self.assertTrue(graphql_objects_equal(expected, actual)) def test_object_type_meta(self): class MetaObject(ObjectType): """ This docstring is _not_ the description """ count = Int() class Meta: name = "Meta" description = "Actual meta description is here" meta = MetaObject() self.assertEqual(meta.description, "Actual meta description is here") self.assertEqual(meta.name, "Meta")
Add tests around ObjectType Meta
Add tests around ObjectType Meta
Python
mit
polygraph-python/polygraph
from collections import OrderedDict from unittest import TestCase from graphql.type.definition import GraphQLField, GraphQLObjectType from graphql.type.scalars import GraphQLString from polygraph.types.definitions import PolygraphNonNull - from polygraph.types.fields import String + from polygraph.types.fields import String, Int from polygraph.types.object_type import ObjectType from polygraph.types.tests.helpers import graphql_objects_equal - class HelloWorldObject(ObjectType): - """ - This is a test object - """ - first = String(description="First violin", nullable=True) - second = String(description="Second fiddle", nullable=False) - third = String(deprecation_reason="Third is dead") - - class ObjectTypeTest(TestCase): def test_simple_object_type(self): + class HelloWorldObject(ObjectType): + """ + This is a test object + """ + first = String(description="First violin", nullable=True) + second = String(description="Second fiddle", nullable=False) + third = String(deprecation_reason="Third is dead") + hello_world = HelloWorldObject() expected = GraphQLObjectType( name="HelloWorldObject", description="This is a test object", fields=OrderedDict({ "first": GraphQLField(GraphQLString, None, None, None, "First violin"), "second": GraphQLField( PolygraphNonNull(GraphQLString), None, None, None, "Second fiddle"), "third": GraphQLField( PolygraphNonNull(GraphQLString), None, None, "Third is dead", None), }) ) actual = hello_world.build_definition() self.assertTrue(graphql_objects_equal(expected, actual)) + def test_object_type_meta(self): + class MetaObject(ObjectType): + """ + This docstring is _not_ the description + """ + count = Int() + + class Meta: + name = "Meta" + description = "Actual meta description is here" + + meta = MetaObject() + self.assertEqual(meta.description, "Actual meta description is here") + self.assertEqual(meta.name, "Meta") +
Add tests around ObjectType Meta
## Code Before: from collections import OrderedDict from unittest import TestCase from graphql.type.definition import GraphQLField, GraphQLObjectType from graphql.type.scalars import GraphQLString from polygraph.types.definitions import PolygraphNonNull from polygraph.types.fields import String from polygraph.types.object_type import ObjectType from polygraph.types.tests.helpers import graphql_objects_equal class HelloWorldObject(ObjectType): """ This is a test object """ first = String(description="First violin", nullable=True) second = String(description="Second fiddle", nullable=False) third = String(deprecation_reason="Third is dead") class ObjectTypeTest(TestCase): def test_simple_object_type(self): hello_world = HelloWorldObject() expected = GraphQLObjectType( name="HelloWorldObject", description="This is a test object", fields=OrderedDict({ "first": GraphQLField(GraphQLString, None, None, None, "First violin"), "second": GraphQLField( PolygraphNonNull(GraphQLString), None, None, None, "Second fiddle"), "third": GraphQLField( PolygraphNonNull(GraphQLString), None, None, "Third is dead", None), }) ) actual = hello_world.build_definition() self.assertTrue(graphql_objects_equal(expected, actual)) ## Instruction: Add tests around ObjectType Meta ## Code After: from collections import OrderedDict from unittest import TestCase from graphql.type.definition import GraphQLField, GraphQLObjectType from graphql.type.scalars import GraphQLString from polygraph.types.definitions import PolygraphNonNull from polygraph.types.fields import String, Int from polygraph.types.object_type import ObjectType from polygraph.types.tests.helpers import graphql_objects_equal class ObjectTypeTest(TestCase): def test_simple_object_type(self): class HelloWorldObject(ObjectType): """ This is a test object """ first = String(description="First violin", nullable=True) second = String(description="Second fiddle", nullable=False) third = String(deprecation_reason="Third is dead") hello_world = HelloWorldObject() expected = GraphQLObjectType( name="HelloWorldObject", description="This is a test object", fields=OrderedDict({ "first": GraphQLField(GraphQLString, None, None, None, "First violin"), "second": GraphQLField( PolygraphNonNull(GraphQLString), None, None, None, "Second fiddle"), "third": GraphQLField( PolygraphNonNull(GraphQLString), None, None, "Third is dead", None), }) ) actual = hello_world.build_definition() self.assertTrue(graphql_objects_equal(expected, actual)) def test_object_type_meta(self): class MetaObject(ObjectType): """ This docstring is _not_ the description """ count = Int() class Meta: name = "Meta" description = "Actual meta description is here" meta = MetaObject() self.assertEqual(meta.description, "Actual meta description is here") self.assertEqual(meta.name, "Meta")
# ... existing code ... from polygraph.types.definitions import PolygraphNonNull from polygraph.types.fields import String, Int from polygraph.types.object_type import ObjectType # ... modified code ... class ObjectTypeTest(TestCase): ... def test_simple_object_type(self): class HelloWorldObject(ObjectType): """ This is a test object """ first = String(description="First violin", nullable=True) second = String(description="Second fiddle", nullable=False) third = String(deprecation_reason="Third is dead") hello_world = HelloWorldObject() ... self.assertTrue(graphql_objects_equal(expected, actual)) def test_object_type_meta(self): class MetaObject(ObjectType): """ This docstring is _not_ the description """ count = Int() class Meta: name = "Meta" description = "Actual meta description is here" meta = MetaObject() self.assertEqual(meta.description, "Actual meta description is here") self.assertEqual(meta.name, "Meta") # ... rest of the code ...
c7a209d2c4455325f1d215ca1c12074b394ae00e
gitdir/host/__init__.py
gitdir/host/__init__.py
import abc import subprocess import gitdir class Host(abc.ABC): @abc.abstractmethod def __iter__(self): raise NotImplementedError() @abc.abstractmethod def __str__(self): raise NotImplementedError() def clone(self, repo_spec): raise NotImplementedError('Host {} does not support cloning'.format(self)) @property def dir(self): return gitdir.GITDIR / str(self) def update(self): for repo_dir in self: subprocess.check_call(['git', 'pull'], cwd=str(repo_dir / 'master')) def all(): for host_dir in gitdir.GITDIR.iterdir(): yield by_name(host_dir.name) def by_name(hostname): if hostname == 'github.com': import gitdir.host.github return gitdir.host.github.GitHub() else: raise ValueError('Unsupported hostname: {}'.format(hostname))
import abc import subprocess import gitdir class Host(abc.ABC): @abc.abstractmethod def __iter__(self): raise NotImplementedError() @abc.abstractmethod def __str__(self): raise NotImplementedError() def clone(self, repo_spec): raise NotImplementedError('Host {} does not support cloning'.format(self)) @property def dir(self): return gitdir.GITDIR / str(self) def update(self): for repo_dir in self: print('[ ** ] updating {}'.format(repo_dir)) subprocess.check_call(['git', 'pull'], cwd=str(repo_dir / 'master')) def all(): for host_dir in gitdir.GITDIR.iterdir(): yield by_name(host_dir.name) def by_name(hostname): if hostname == 'github.com': import gitdir.host.github return gitdir.host.github.GitHub() else: raise ValueError('Unsupported hostname: {}'.format(hostname))
Add status messages to `gitdir update`
Add status messages to `gitdir update`
Python
mit
fenhl/gitdir
import abc import subprocess import gitdir class Host(abc.ABC): @abc.abstractmethod def __iter__(self): raise NotImplementedError() @abc.abstractmethod def __str__(self): raise NotImplementedError() def clone(self, repo_spec): raise NotImplementedError('Host {} does not support cloning'.format(self)) @property def dir(self): return gitdir.GITDIR / str(self) def update(self): for repo_dir in self: + print('[ ** ] updating {}'.format(repo_dir)) subprocess.check_call(['git', 'pull'], cwd=str(repo_dir / 'master')) def all(): for host_dir in gitdir.GITDIR.iterdir(): yield by_name(host_dir.name) def by_name(hostname): if hostname == 'github.com': import gitdir.host.github return gitdir.host.github.GitHub() else: raise ValueError('Unsupported hostname: {}'.format(hostname))
Add status messages to `gitdir update`
## Code Before: import abc import subprocess import gitdir class Host(abc.ABC): @abc.abstractmethod def __iter__(self): raise NotImplementedError() @abc.abstractmethod def __str__(self): raise NotImplementedError() def clone(self, repo_spec): raise NotImplementedError('Host {} does not support cloning'.format(self)) @property def dir(self): return gitdir.GITDIR / str(self) def update(self): for repo_dir in self: subprocess.check_call(['git', 'pull'], cwd=str(repo_dir / 'master')) def all(): for host_dir in gitdir.GITDIR.iterdir(): yield by_name(host_dir.name) def by_name(hostname): if hostname == 'github.com': import gitdir.host.github return gitdir.host.github.GitHub() else: raise ValueError('Unsupported hostname: {}'.format(hostname)) ## Instruction: Add status messages to `gitdir update` ## Code After: import abc import subprocess import gitdir class Host(abc.ABC): @abc.abstractmethod def __iter__(self): raise NotImplementedError() @abc.abstractmethod def __str__(self): raise NotImplementedError() def clone(self, repo_spec): raise NotImplementedError('Host {} does not support cloning'.format(self)) @property def dir(self): return gitdir.GITDIR / str(self) def update(self): for repo_dir in self: print('[ ** ] updating {}'.format(repo_dir)) subprocess.check_call(['git', 'pull'], cwd=str(repo_dir / 'master')) def all(): for host_dir in gitdir.GITDIR.iterdir(): yield by_name(host_dir.name) def by_name(hostname): if hostname == 'github.com': import gitdir.host.github return gitdir.host.github.GitHub() else: raise ValueError('Unsupported hostname: {}'.format(hostname))
// ... existing code ... for repo_dir in self: print('[ ** ] updating {}'.format(repo_dir)) subprocess.check_call(['git', 'pull'], cwd=str(repo_dir / 'master')) // ... rest of the code ...
1d486d8035e918a83dce5a70c83149a06d982a9f
Instanssi/admin_calendar/models.py
Instanssi/admin_calendar/models.py
from django.db import models from django.contrib import admin from django.contrib.auth.models import User from imagekit.models import ImageSpec from imagekit.processors import resize class CalendarEvent(models.Model): user = models.ForeignKey(User, verbose_name=u'Käyttäjä') start = models.DateTimeField(u'Alku', help_text=u'Tapahtuman alkamisaika.') end = models.DateTimeField(u'Loppe', help_text=u'Tapahtuman loppumisaika.', blank=True) description = models.TextField(u'Kuvaus', help_text=u'Tapahtuman kuvaus.', blank=True) title = models.CharField(u'Otsikko', help_text=u'Lyhyt otsikko.', max_length=32) image_original = models.ImageField(u'Kuva', upload_to='calendar/images/', help_text=u"Kuva tapahtumalle.", blank=True) image_small = ImageSpec([resize.Fit(48, 48)], image_field='imagefile_original', format='PNG') EVENT_TYPES = ( (0, u'Aikaraja'), (1, u'Aikavaraus'), ) type = models.IntegerField(u'Tyyppi', help_text=u'Tapahtuman tyyppi', choices=EVENT_TYPES, default=0) try: admin.site.register(CalendarEvent) except: pass
from django.db import models from django.contrib import admin from django.contrib.auth.models import User from imagekit.models import ImageSpecField from imagekit.processors import ResizeToFill class CalendarEvent(models.Model): user = models.ForeignKey(User, verbose_name=u'Käyttäjä') start = models.DateTimeField(u'Alku', help_text=u'Tapahtuman alkamisaika.') end = models.DateTimeField(u'Loppe', help_text=u'Tapahtuman loppumisaika.', blank=True) description = models.TextField(u'Kuvaus', help_text=u'Tapahtuman kuvaus.', blank=True) title = models.CharField(u'Otsikko', help_text=u'Lyhyt otsikko.', max_length=32) image_original = models.ImageField(u'Kuva', upload_to='calendar/images/', help_text=u"Kuva tapahtumalle.", blank=True) image_small = ImageSpecField([ResizeToFill(48, 48)], image_field='imagefile_original', format='PNG') EVENT_TYPES = ( (0, u'Aikaraja'), (1, u'Aikavaraus'), ) type = models.IntegerField(u'Tyyppi', help_text=u'Tapahtuman tyyppi', choices=EVENT_TYPES, default=0) try: admin.site.register(CalendarEvent) except: pass
Fix to work on the latest django-imagekit
admin_calendar: Fix to work on the latest django-imagekit
Python
mit
Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org
from django.db import models from django.contrib import admin from django.contrib.auth.models import User - from imagekit.models import ImageSpec + from imagekit.models import ImageSpecField - from imagekit.processors import resize + from imagekit.processors import ResizeToFill class CalendarEvent(models.Model): user = models.ForeignKey(User, verbose_name=u'Käyttäjä') start = models.DateTimeField(u'Alku', help_text=u'Tapahtuman alkamisaika.') end = models.DateTimeField(u'Loppe', help_text=u'Tapahtuman loppumisaika.', blank=True) description = models.TextField(u'Kuvaus', help_text=u'Tapahtuman kuvaus.', blank=True) title = models.CharField(u'Otsikko', help_text=u'Lyhyt otsikko.', max_length=32) image_original = models.ImageField(u'Kuva', upload_to='calendar/images/', help_text=u"Kuva tapahtumalle.", blank=True) - image_small = ImageSpec([resize.Fit(48, 48)], image_field='imagefile_original', format='PNG') + image_small = ImageSpecField([ResizeToFill(48, 48)], image_field='imagefile_original', format='PNG') EVENT_TYPES = ( (0, u'Aikaraja'), (1, u'Aikavaraus'), ) type = models.IntegerField(u'Tyyppi', help_text=u'Tapahtuman tyyppi', choices=EVENT_TYPES, default=0) try: admin.site.register(CalendarEvent) except: pass
Fix to work on the latest django-imagekit
## Code Before: from django.db import models from django.contrib import admin from django.contrib.auth.models import User from imagekit.models import ImageSpec from imagekit.processors import resize class CalendarEvent(models.Model): user = models.ForeignKey(User, verbose_name=u'Käyttäjä') start = models.DateTimeField(u'Alku', help_text=u'Tapahtuman alkamisaika.') end = models.DateTimeField(u'Loppe', help_text=u'Tapahtuman loppumisaika.', blank=True) description = models.TextField(u'Kuvaus', help_text=u'Tapahtuman kuvaus.', blank=True) title = models.CharField(u'Otsikko', help_text=u'Lyhyt otsikko.', max_length=32) image_original = models.ImageField(u'Kuva', upload_to='calendar/images/', help_text=u"Kuva tapahtumalle.", blank=True) image_small = ImageSpec([resize.Fit(48, 48)], image_field='imagefile_original', format='PNG') EVENT_TYPES = ( (0, u'Aikaraja'), (1, u'Aikavaraus'), ) type = models.IntegerField(u'Tyyppi', help_text=u'Tapahtuman tyyppi', choices=EVENT_TYPES, default=0) try: admin.site.register(CalendarEvent) except: pass ## Instruction: Fix to work on the latest django-imagekit ## Code After: from django.db import models from django.contrib import admin from django.contrib.auth.models import User from imagekit.models import ImageSpecField from imagekit.processors import ResizeToFill class CalendarEvent(models.Model): user = models.ForeignKey(User, verbose_name=u'Käyttäjä') start = models.DateTimeField(u'Alku', help_text=u'Tapahtuman alkamisaika.') end = models.DateTimeField(u'Loppe', help_text=u'Tapahtuman loppumisaika.', blank=True) description = models.TextField(u'Kuvaus', help_text=u'Tapahtuman kuvaus.', blank=True) title = models.CharField(u'Otsikko', help_text=u'Lyhyt otsikko.', max_length=32) image_original = models.ImageField(u'Kuva', upload_to='calendar/images/', help_text=u"Kuva tapahtumalle.", blank=True) image_small = ImageSpecField([ResizeToFill(48, 48)], image_field='imagefile_original', format='PNG') EVENT_TYPES = ( (0, u'Aikaraja'), (1, u'Aikavaraus'), ) type = models.IntegerField(u'Tyyppi', help_text=u'Tapahtuman tyyppi', choices=EVENT_TYPES, default=0) try: admin.site.register(CalendarEvent) except: pass
... from django.contrib.auth.models import User from imagekit.models import ImageSpecField from imagekit.processors import ResizeToFill ... image_original = models.ImageField(u'Kuva', upload_to='calendar/images/', help_text=u"Kuva tapahtumalle.", blank=True) image_small = ImageSpecField([ResizeToFill(48, 48)], image_field='imagefile_original', format='PNG') EVENT_TYPES = ( ...
8d55ea0cfbafc9f6dc1044ba27c3313c36ea73c6
pombola/south_africa/templatetags/za_people_display.py
pombola/south_africa/templatetags/za_people_display.py
from django import template register = template.Library() NO_PLACE_ORGS = ('parliament', 'national-assembly', ) MEMBER_ORGS = ('parliament', 'national-assembly', ) @register.assignment_tag() def should_display_place(organisation): return organisation.slug not in NO_PLACE_ORGS @register.assignment_tag() def should_display_position(organisation, position_title): should_display = True if organisation.slug in MEMBER_ORGS and unicode(position_title) in (u'Member',): should_display = False if 'ncop' == organisation.slug and unicode(position_title) in (u'Delegate',): should_display = False return should_display
from django import template register = template.Library() NO_PLACE_ORGS = ('parliament', 'national-assembly', ) MEMBER_ORGS = ('parliament', 'national-assembly', ) @register.assignment_tag() def should_display_place(organisation): if not organisation: return True return organisation.slug not in NO_PLACE_ORGS @register.assignment_tag() def should_display_position(organisation, position_title): should_display = True if organisation.slug in MEMBER_ORGS and unicode(position_title) in (u'Member',): should_display = False if 'ncop' == organisation.slug and unicode(position_title) in (u'Delegate',): should_display = False return should_display
Fix display of people on constituency office page
[ZA] Fix display of people on constituency office page This template tag was being called without an organisation, so in production it was just silently failing, but in development it was raising an exception. This adds an extra check so that if there is no organisation then we just short circuit and return `True`.
Python
agpl-3.0
mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola
from django import template register = template.Library() NO_PLACE_ORGS = ('parliament', 'national-assembly', ) MEMBER_ORGS = ('parliament', 'national-assembly', ) @register.assignment_tag() def should_display_place(organisation): + if not organisation: + return True return organisation.slug not in NO_PLACE_ORGS @register.assignment_tag() def should_display_position(organisation, position_title): should_display = True if organisation.slug in MEMBER_ORGS and unicode(position_title) in (u'Member',): should_display = False if 'ncop' == organisation.slug and unicode(position_title) in (u'Delegate',): should_display = False return should_display
Fix display of people on constituency office page
## Code Before: from django import template register = template.Library() NO_PLACE_ORGS = ('parliament', 'national-assembly', ) MEMBER_ORGS = ('parliament', 'national-assembly', ) @register.assignment_tag() def should_display_place(organisation): return organisation.slug not in NO_PLACE_ORGS @register.assignment_tag() def should_display_position(organisation, position_title): should_display = True if organisation.slug in MEMBER_ORGS and unicode(position_title) in (u'Member',): should_display = False if 'ncop' == organisation.slug and unicode(position_title) in (u'Delegate',): should_display = False return should_display ## Instruction: Fix display of people on constituency office page ## Code After: from django import template register = template.Library() NO_PLACE_ORGS = ('parliament', 'national-assembly', ) MEMBER_ORGS = ('parliament', 'national-assembly', ) @register.assignment_tag() def should_display_place(organisation): if not organisation: return True return organisation.slug not in NO_PLACE_ORGS @register.assignment_tag() def should_display_position(organisation, position_title): should_display = True if organisation.slug in MEMBER_ORGS and unicode(position_title) in (u'Member',): should_display = False if 'ncop' == organisation.slug and unicode(position_title) in (u'Delegate',): should_display = False return should_display
# ... existing code ... def should_display_place(organisation): if not organisation: return True return organisation.slug not in NO_PLACE_ORGS # ... rest of the code ...
bd4643e35a9c75d15bb6a4bfef63774fdd8bee5b
test/regress/cbrt.cpp.py
test/regress/cbrt.cpp.py
import shtest, sys, math def cbrt(l, types=[]): return shtest.make_test([math.pow(x, 1/3.0) for x in l], [l], types) def insert_into(test): test.add_test(cbrt((0.0, 1.0, 2.0, 3.0))) test.add_test(cbrt((1.0,))) test.add_make_test((3,), [(27,)], ['i', 'i']) # Test the cube root in stream programs test = shtest.StreamTest('cbrt', 1) test.add_call(shtest.Call(shtest.Call.call, 'cbrt', 1)) insert_into(test) test.output_header(sys.stdout) test.output(sys.stdout, False) # Test the cube root in immediate mode test = shtest.ImmediateTest('cbrt_im', 1) test.add_call(shtest.Call(shtest.Call.call, 'cbrt', 1)) insert_into(test) test.output(sys.stdout, False) test.output_footer(sys.stdout)
import shtest, sys, math def cbrt(l, types=[]): return shtest.make_test([math.pow(x, 1/3.0) for x in l], [l], types) def insert_into(test): test.add_test(cbrt((0.0, 1.0, 2.0, 3.0))) test.add_test(cbrt((1.0,))) test.add_test(cbrt((4000.2, 27))) #test.add_make_test((3,), [(27,)], ['i', 'i']) # not currently working # Test the cube root in stream programs test = shtest.StreamTest('cbrt', 1) test.add_call(shtest.Call(shtest.Call.call, 'cbrt', 1)) insert_into(test) test.output_header(sys.stdout) test.output(sys.stdout, False) # Test the cube root in immediate mode test = shtest.ImmediateTest('cbrt_im', 1) test.add_call(shtest.Call(shtest.Call.call, 'cbrt', 1)) insert_into(test) test.output(sys.stdout, False) test.output_footer(sys.stdout)
Add a typical 2-component case. Comment out a case that fail until integer support is fixed.
Add a typical 2-component case. Comment out a case that fail until integer support is fixed. git-svn-id: f6f47f0a6375c1440c859a5b92b3b3fbb75bb58e@2508 afdca40c-03d6-0310-8ede-e9f093b21075
Python
lgpl-2.1
libsh-archive/sh,libsh-archive/sh,libsh-archive/sh,libsh-archive/sh,libsh-archive/sh,libsh-archive/sh
import shtest, sys, math def cbrt(l, types=[]): return shtest.make_test([math.pow(x, 1/3.0) for x in l], [l], types) def insert_into(test): test.add_test(cbrt((0.0, 1.0, 2.0, 3.0))) test.add_test(cbrt((1.0,))) + test.add_test(cbrt((4000.2, 27))) - test.add_make_test((3,), [(27,)], ['i', 'i']) + #test.add_make_test((3,), [(27,)], ['i', 'i']) # not currently working # Test the cube root in stream programs test = shtest.StreamTest('cbrt', 1) test.add_call(shtest.Call(shtest.Call.call, 'cbrt', 1)) insert_into(test) test.output_header(sys.stdout) test.output(sys.stdout, False) # Test the cube root in immediate mode test = shtest.ImmediateTest('cbrt_im', 1) test.add_call(shtest.Call(shtest.Call.call, 'cbrt', 1)) insert_into(test) test.output(sys.stdout, False) test.output_footer(sys.stdout)
Add a typical 2-component case. Comment out a case that fail until integer support is fixed.
## Code Before: import shtest, sys, math def cbrt(l, types=[]): return shtest.make_test([math.pow(x, 1/3.0) for x in l], [l], types) def insert_into(test): test.add_test(cbrt((0.0, 1.0, 2.0, 3.0))) test.add_test(cbrt((1.0,))) test.add_make_test((3,), [(27,)], ['i', 'i']) # Test the cube root in stream programs test = shtest.StreamTest('cbrt', 1) test.add_call(shtest.Call(shtest.Call.call, 'cbrt', 1)) insert_into(test) test.output_header(sys.stdout) test.output(sys.stdout, False) # Test the cube root in immediate mode test = shtest.ImmediateTest('cbrt_im', 1) test.add_call(shtest.Call(shtest.Call.call, 'cbrt', 1)) insert_into(test) test.output(sys.stdout, False) test.output_footer(sys.stdout) ## Instruction: Add a typical 2-component case. Comment out a case that fail until integer support is fixed. ## Code After: import shtest, sys, math def cbrt(l, types=[]): return shtest.make_test([math.pow(x, 1/3.0) for x in l], [l], types) def insert_into(test): test.add_test(cbrt((0.0, 1.0, 2.0, 3.0))) test.add_test(cbrt((1.0,))) test.add_test(cbrt((4000.2, 27))) #test.add_make_test((3,), [(27,)], ['i', 'i']) # not currently working # Test the cube root in stream programs test = shtest.StreamTest('cbrt', 1) test.add_call(shtest.Call(shtest.Call.call, 'cbrt', 1)) insert_into(test) test.output_header(sys.stdout) test.output(sys.stdout, False) # Test the cube root in immediate mode test = shtest.ImmediateTest('cbrt_im', 1) test.add_call(shtest.Call(shtest.Call.call, 'cbrt', 1)) insert_into(test) test.output(sys.stdout, False) test.output_footer(sys.stdout)
// ... existing code ... test.add_test(cbrt((1.0,))) test.add_test(cbrt((4000.2, 27))) #test.add_make_test((3,), [(27,)], ['i', 'i']) # not currently working // ... rest of the code ...
0a0b1087b0067259b774b91809a166d74c8c695c
spacy/lang/id/__init__.py
spacy/lang/id/__init__.py
from __future__ import unicode_literals from .stop_words import STOP_WORDS from .punctuation import TOKENIZER_SUFFIXES, TOKENIZER_PREFIXES, TOKENIZER_INFIXES from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS from .norm_exceptions import NORM_EXCEPTIONS from .lemmatizer import LOOKUP from .lex_attrs import LEX_ATTRS from .syntax_iterators import SYNTAX_ITERATORS from ..tokenizer_exceptions import BASE_EXCEPTIONS from ..norm_exceptions import BASE_NORMS from ...language import Language from ...attrs import LANG, NORM from ...util import update_exc, add_lookups class IndonesianDefaults(Language.Defaults): lex_attr_getters = dict(Language.Defaults.lex_attr_getters) lex_attr_getters[LANG] = lambda text: "id" lex_attr_getters.update(LEX_ATTRS) lex_attr_getters[NORM] = add_lookups( Language.Defaults.lex_attr_getters[NORM], BASE_NORMS, NORM_EXCEPTIONS ) tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS) stop_words = STOP_WORDS prefixes = TOKENIZER_PREFIXES suffixes = TOKENIZER_SUFFIXES infixes = TOKENIZER_INFIXES syntax_iterators = SYNTAX_ITERATORS lemma_lookup = LOOKUP class Indonesian(Language): lang = "id" Defaults = IndonesianDefaults __all__ = ["Indonesian"]
from __future__ import unicode_literals from .stop_words import STOP_WORDS from .punctuation import TOKENIZER_SUFFIXES, TOKENIZER_PREFIXES, TOKENIZER_INFIXES from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS from .norm_exceptions import NORM_EXCEPTIONS from .lemmatizer import LOOKUP from .lex_attrs import LEX_ATTRS from .syntax_iterators import SYNTAX_ITERATORS from .tag_map import TAG_MAP from ..tokenizer_exceptions import BASE_EXCEPTIONS from ..norm_exceptions import BASE_NORMS from ...language import Language from ...attrs import LANG, NORM from ...util import update_exc, add_lookups class IndonesianDefaults(Language.Defaults): lex_attr_getters = dict(Language.Defaults.lex_attr_getters) lex_attr_getters[LANG] = lambda text: "id" lex_attr_getters.update(LEX_ATTRS) lex_attr_getters[NORM] = add_lookups( Language.Defaults.lex_attr_getters[NORM], BASE_NORMS, NORM_EXCEPTIONS ) tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS) stop_words = STOP_WORDS prefixes = TOKENIZER_PREFIXES suffixes = TOKENIZER_SUFFIXES infixes = TOKENIZER_INFIXES syntax_iterators = SYNTAX_ITERATORS lemma_lookup = LOOKUP tag_map = TAG_MAP class Indonesian(Language): lang = "id" Defaults = IndonesianDefaults __all__ = ["Indonesian"]
Make tag map available in Indonesian defaults
Make tag map available in Indonesian defaults
Python
mit
spacy-io/spaCy,explosion/spaCy,spacy-io/spaCy,explosion/spaCy,honnibal/spaCy,honnibal/spaCy,spacy-io/spaCy,explosion/spaCy,honnibal/spaCy,spacy-io/spaCy,explosion/spaCy,explosion/spaCy,explosion/spaCy,spacy-io/spaCy,spacy-io/spaCy,honnibal/spaCy
from __future__ import unicode_literals from .stop_words import STOP_WORDS from .punctuation import TOKENIZER_SUFFIXES, TOKENIZER_PREFIXES, TOKENIZER_INFIXES from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS from .norm_exceptions import NORM_EXCEPTIONS from .lemmatizer import LOOKUP from .lex_attrs import LEX_ATTRS from .syntax_iterators import SYNTAX_ITERATORS + from .tag_map import TAG_MAP from ..tokenizer_exceptions import BASE_EXCEPTIONS from ..norm_exceptions import BASE_NORMS from ...language import Language from ...attrs import LANG, NORM from ...util import update_exc, add_lookups class IndonesianDefaults(Language.Defaults): lex_attr_getters = dict(Language.Defaults.lex_attr_getters) lex_attr_getters[LANG] = lambda text: "id" lex_attr_getters.update(LEX_ATTRS) lex_attr_getters[NORM] = add_lookups( Language.Defaults.lex_attr_getters[NORM], BASE_NORMS, NORM_EXCEPTIONS ) tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS) stop_words = STOP_WORDS prefixes = TOKENIZER_PREFIXES suffixes = TOKENIZER_SUFFIXES infixes = TOKENIZER_INFIXES syntax_iterators = SYNTAX_ITERATORS lemma_lookup = LOOKUP + tag_map = TAG_MAP class Indonesian(Language): lang = "id" Defaults = IndonesianDefaults __all__ = ["Indonesian"]
Make tag map available in Indonesian defaults
## Code Before: from __future__ import unicode_literals from .stop_words import STOP_WORDS from .punctuation import TOKENIZER_SUFFIXES, TOKENIZER_PREFIXES, TOKENIZER_INFIXES from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS from .norm_exceptions import NORM_EXCEPTIONS from .lemmatizer import LOOKUP from .lex_attrs import LEX_ATTRS from .syntax_iterators import SYNTAX_ITERATORS from ..tokenizer_exceptions import BASE_EXCEPTIONS from ..norm_exceptions import BASE_NORMS from ...language import Language from ...attrs import LANG, NORM from ...util import update_exc, add_lookups class IndonesianDefaults(Language.Defaults): lex_attr_getters = dict(Language.Defaults.lex_attr_getters) lex_attr_getters[LANG] = lambda text: "id" lex_attr_getters.update(LEX_ATTRS) lex_attr_getters[NORM] = add_lookups( Language.Defaults.lex_attr_getters[NORM], BASE_NORMS, NORM_EXCEPTIONS ) tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS) stop_words = STOP_WORDS prefixes = TOKENIZER_PREFIXES suffixes = TOKENIZER_SUFFIXES infixes = TOKENIZER_INFIXES syntax_iterators = SYNTAX_ITERATORS lemma_lookup = LOOKUP class Indonesian(Language): lang = "id" Defaults = IndonesianDefaults __all__ = ["Indonesian"] ## Instruction: Make tag map available in Indonesian defaults ## Code After: from __future__ import unicode_literals from .stop_words import STOP_WORDS from .punctuation import TOKENIZER_SUFFIXES, TOKENIZER_PREFIXES, TOKENIZER_INFIXES from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS from .norm_exceptions import NORM_EXCEPTIONS from .lemmatizer import LOOKUP from .lex_attrs import LEX_ATTRS from .syntax_iterators import SYNTAX_ITERATORS from .tag_map import TAG_MAP from ..tokenizer_exceptions import BASE_EXCEPTIONS from ..norm_exceptions import BASE_NORMS from ...language import Language from ...attrs import LANG, NORM from ...util import update_exc, add_lookups class IndonesianDefaults(Language.Defaults): lex_attr_getters = dict(Language.Defaults.lex_attr_getters) lex_attr_getters[LANG] = lambda text: "id" lex_attr_getters.update(LEX_ATTRS) lex_attr_getters[NORM] = add_lookups( Language.Defaults.lex_attr_getters[NORM], BASE_NORMS, NORM_EXCEPTIONS ) tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS) stop_words = STOP_WORDS prefixes = TOKENIZER_PREFIXES suffixes = TOKENIZER_SUFFIXES infixes = TOKENIZER_INFIXES syntax_iterators = SYNTAX_ITERATORS lemma_lookup = LOOKUP tag_map = TAG_MAP class Indonesian(Language): lang = "id" Defaults = IndonesianDefaults __all__ = ["Indonesian"]
# ... existing code ... from .syntax_iterators import SYNTAX_ITERATORS from .tag_map import TAG_MAP # ... modified code ... lemma_lookup = LOOKUP tag_map = TAG_MAP # ... rest of the code ...
bd5c215c1c481f3811753412bca6b509bb00591a
me_api/app.py
me_api/app.py
from __future__ import absolute_import, unicode_literals from flask import Flask from .middleware.me import me from .cache import cache def _register_module(app, module): if module == 'douban': from .middleware import douban app.register_blueprint(douban.douban_api) elif module == 'github': from .middleware import github app.register_blueprint(github.github_api) elif module == 'instagram': from .middleware import instagram app.register_blueprint(instagram.instagram_api) elif module == 'keybase': from .middleware import keybase app.register_blueprint(keybase.keybase_api) elif module == 'medium': from .middleware import medium app.register_blueprint(medium.medium_api) elif module == 'stackoverflow': from .middleware import stackoverflow app.register_blueprint(stackoverflow.stackoverflow_api) def create_app(config): app = Flask(__name__) app.config.from_object(config) cache.init_app(app) modules = config.modules['modules'] app.register_blueprint(me) for module in modules.keys(): _register_module(app, module) return app
from __future__ import absolute_import, unicode_literals from flask import Flask from werkzeug.utils import import_string from me_api.middleware.me import me from me_api.cache import cache middlewares = { 'douban': 'me_api.middleware.douban:douban_api', 'github': 'me_api.middleware.github:github_api', 'instagram': 'me_api.middleware.instagram:instagram_api', 'keybase': 'me_api.middleware.keybase:keybase_api', 'medium': 'me_api.middleware.medium:medium_api', 'stackoverflow': 'me_api.middleware.stackoverflow:stackoverflow_api', } def create_app(config): app = Flask(__name__) app.config.from_object(config) cache.init_app(app) modules = config.modules['modules'] app.register_blueprint(me) for module in modules.keys(): blueprint = import_string(middlewares[module]) app.register_blueprint(blueprint) return app
Improve the way that import middlewares
Improve the way that import middlewares
Python
mit
lord63/me-api
from __future__ import absolute_import, unicode_literals from flask import Flask + from werkzeug.utils import import_string - from .middleware.me import me + from me_api.middleware.me import me - from .cache import cache + from me_api.cache import cache + middlewares = { + 'douban': 'me_api.middleware.douban:douban_api', + 'github': 'me_api.middleware.github:github_api', + 'instagram': 'me_api.middleware.instagram:instagram_api', + 'keybase': 'me_api.middleware.keybase:keybase_api', + 'medium': 'me_api.middleware.medium:medium_api', + 'stackoverflow': 'me_api.middleware.stackoverflow:stackoverflow_api', + } - def _register_module(app, module): - if module == 'douban': - from .middleware import douban - app.register_blueprint(douban.douban_api) - elif module == 'github': - from .middleware import github - app.register_blueprint(github.github_api) - elif module == 'instagram': - from .middleware import instagram - app.register_blueprint(instagram.instagram_api) - elif module == 'keybase': - from .middleware import keybase - app.register_blueprint(keybase.keybase_api) - elif module == 'medium': - from .middleware import medium - app.register_blueprint(medium.medium_api) - elif module == 'stackoverflow': - from .middleware import stackoverflow - app.register_blueprint(stackoverflow.stackoverflow_api) def create_app(config): app = Flask(__name__) app.config.from_object(config) cache.init_app(app) modules = config.modules['modules'] app.register_blueprint(me) for module in modules.keys(): - _register_module(app, module) + blueprint = import_string(middlewares[module]) + app.register_blueprint(blueprint) return app
Improve the way that import middlewares
## Code Before: from __future__ import absolute_import, unicode_literals from flask import Flask from .middleware.me import me from .cache import cache def _register_module(app, module): if module == 'douban': from .middleware import douban app.register_blueprint(douban.douban_api) elif module == 'github': from .middleware import github app.register_blueprint(github.github_api) elif module == 'instagram': from .middleware import instagram app.register_blueprint(instagram.instagram_api) elif module == 'keybase': from .middleware import keybase app.register_blueprint(keybase.keybase_api) elif module == 'medium': from .middleware import medium app.register_blueprint(medium.medium_api) elif module == 'stackoverflow': from .middleware import stackoverflow app.register_blueprint(stackoverflow.stackoverflow_api) def create_app(config): app = Flask(__name__) app.config.from_object(config) cache.init_app(app) modules = config.modules['modules'] app.register_blueprint(me) for module in modules.keys(): _register_module(app, module) return app ## Instruction: Improve the way that import middlewares ## Code After: from __future__ import absolute_import, unicode_literals from flask import Flask from werkzeug.utils import import_string from me_api.middleware.me import me from me_api.cache import cache middlewares = { 'douban': 'me_api.middleware.douban:douban_api', 'github': 'me_api.middleware.github:github_api', 'instagram': 'me_api.middleware.instagram:instagram_api', 'keybase': 'me_api.middleware.keybase:keybase_api', 'medium': 'me_api.middleware.medium:medium_api', 'stackoverflow': 'me_api.middleware.stackoverflow:stackoverflow_api', } def create_app(config): app = Flask(__name__) app.config.from_object(config) cache.init_app(app) modules = config.modules['modules'] app.register_blueprint(me) for module in modules.keys(): blueprint = import_string(middlewares[module]) app.register_blueprint(blueprint) return app
... from flask import Flask from werkzeug.utils import import_string from me_api.middleware.me import me from me_api.cache import cache ... middlewares = { 'douban': 'me_api.middleware.douban:douban_api', 'github': 'me_api.middleware.github:github_api', 'instagram': 'me_api.middleware.instagram:instagram_api', 'keybase': 'me_api.middleware.keybase:keybase_api', 'medium': 'me_api.middleware.medium:medium_api', 'stackoverflow': 'me_api.middleware.stackoverflow:stackoverflow_api', } ... for module in modules.keys(): blueprint = import_string(middlewares[module]) app.register_blueprint(blueprint) ...
04e243aafbd08008556d83d73fbbf22e5398aab4
telostats/stations/models.py
telostats/stations/models.py
from django.db import models from django.utils import timezone class Station(models.Model): id = models.IntegerField(unique=True, primary_key=True) name = models.CharField(u'name', max_length=100) longitude = models.FloatField(u'longitude') latitude = models.FloatField(u'latitude') class Status(models.Model): station = models.ForeignKey(Station) timestamp = models.DateTimeField(default=timezone.now) actual_timestamp = models.DateTimeField(default=timezone.now) bikes = models.IntegerField(u'available bikes') docks = models.IntegerField(u'available docks')
from django.db import models from django.utils import timezone class Station(models.Model): id = models.IntegerField(unique=True, primary_key=True) name = models.CharField(u'name', max_length=100) longitude = models.FloatField(u'longitude') latitude = models.FloatField(u'latitude') def __unicode__(self): return self.name class Status(models.Model): station = models.ForeignKey(Station) timestamp = models.DateTimeField(default=timezone.now) actual_timestamp = models.DateTimeField(default=timezone.now) bikes = models.IntegerField(u'available bikes') docks = models.IntegerField(u'available docks') def __unicode__(self): return u'{}: {}/{} ({})'.format( self.station, self.bikes, self.docks, self.timestamp)
Add unicode methods to Station/Status
Add unicode methods to Station/Status
Python
bsd-3-clause
idan/telostats,idan/telostats,idan/telostats
from django.db import models from django.utils import timezone class Station(models.Model): id = models.IntegerField(unique=True, primary_key=True) name = models.CharField(u'name', max_length=100) longitude = models.FloatField(u'longitude') latitude = models.FloatField(u'latitude') + def __unicode__(self): + return self.name + class Status(models.Model): station = models.ForeignKey(Station) timestamp = models.DateTimeField(default=timezone.now) actual_timestamp = models.DateTimeField(default=timezone.now) bikes = models.IntegerField(u'available bikes') docks = models.IntegerField(u'available docks') + def __unicode__(self): + return u'{}: {}/{} ({})'.format( + self.station, + self.bikes, self.docks, + self.timestamp) +
Add unicode methods to Station/Status
## Code Before: from django.db import models from django.utils import timezone class Station(models.Model): id = models.IntegerField(unique=True, primary_key=True) name = models.CharField(u'name', max_length=100) longitude = models.FloatField(u'longitude') latitude = models.FloatField(u'latitude') class Status(models.Model): station = models.ForeignKey(Station) timestamp = models.DateTimeField(default=timezone.now) actual_timestamp = models.DateTimeField(default=timezone.now) bikes = models.IntegerField(u'available bikes') docks = models.IntegerField(u'available docks') ## Instruction: Add unicode methods to Station/Status ## Code After: from django.db import models from django.utils import timezone class Station(models.Model): id = models.IntegerField(unique=True, primary_key=True) name = models.CharField(u'name', max_length=100) longitude = models.FloatField(u'longitude') latitude = models.FloatField(u'latitude') def __unicode__(self): return self.name class Status(models.Model): station = models.ForeignKey(Station) timestamp = models.DateTimeField(default=timezone.now) actual_timestamp = models.DateTimeField(default=timezone.now) bikes = models.IntegerField(u'available bikes') docks = models.IntegerField(u'available docks') def __unicode__(self): return u'{}: {}/{} ({})'.format( self.station, self.bikes, self.docks, self.timestamp)
// ... existing code ... def __unicode__(self): return self.name // ... modified code ... docks = models.IntegerField(u'available docks') def __unicode__(self): return u'{}: {}/{} ({})'.format( self.station, self.bikes, self.docks, self.timestamp) // ... rest of the code ...
0d1e5990d55bea9530beaa49aaf5091a6434a48e
newswall/providers/base.py
newswall/providers/base.py
from newswall.models import Story class ProviderBase(object): def __init__(self, source, config): self.source = source self.config = config def update(self): raise NotImplementedError def create_story(self, object_url, **kwargs): defaults = {'source': self.source} defaults.update(kwargs) return Story.objects.get_or_create(object_url=object_url, defaults=defaults)
from datetime import date, timedelta from newswall.models import Story class ProviderBase(object): def __init__(self, source, config): self.source = source self.config = config def update(self): raise NotImplementedError def create_story(self, object_url, **kwargs): defaults = {'source': self.source} defaults.update(kwargs) if defaults.get('title'): if Story.objects.filter( title=defaults.get('title'), timestamp__gte=date.today() - timedelta(days=3), ).exists(): defaults['is_active'] = False return Story.objects.get_or_create(object_url=object_url, defaults=defaults)
Set stories to inactive if a story with the same title has been published recently
Set stories to inactive if a story with the same title has been published recently
Python
bsd-3-clause
HerraLampila/django-newswall,michaelkuty/django-newswall,matthiask/django-newswall,matthiask/django-newswall,HerraLampila/django-newswall,registerguard/django-newswall,registerguard/django-newswall,michaelkuty/django-newswall
+ from datetime import date, timedelta + from newswall.models import Story class ProviderBase(object): def __init__(self, source, config): self.source = source self.config = config def update(self): raise NotImplementedError def create_story(self, object_url, **kwargs): defaults = {'source': self.source} defaults.update(kwargs) + if defaults.get('title'): + if Story.objects.filter( + title=defaults.get('title'), + timestamp__gte=date.today() - timedelta(days=3), + ).exists(): + defaults['is_active'] = False + return Story.objects.get_or_create(object_url=object_url, defaults=defaults)
Set stories to inactive if a story with the same title has been published recently
## Code Before: from newswall.models import Story class ProviderBase(object): def __init__(self, source, config): self.source = source self.config = config def update(self): raise NotImplementedError def create_story(self, object_url, **kwargs): defaults = {'source': self.source} defaults.update(kwargs) return Story.objects.get_or_create(object_url=object_url, defaults=defaults) ## Instruction: Set stories to inactive if a story with the same title has been published recently ## Code After: from datetime import date, timedelta from newswall.models import Story class ProviderBase(object): def __init__(self, source, config): self.source = source self.config = config def update(self): raise NotImplementedError def create_story(self, object_url, **kwargs): defaults = {'source': self.source} defaults.update(kwargs) if defaults.get('title'): if Story.objects.filter( title=defaults.get('title'), timestamp__gte=date.today() - timedelta(days=3), ).exists(): defaults['is_active'] = False return Story.objects.get_or_create(object_url=object_url, defaults=defaults)
... from datetime import date, timedelta from newswall.models import Story ... if defaults.get('title'): if Story.objects.filter( title=defaults.get('title'), timestamp__gte=date.today() - timedelta(days=3), ).exists(): defaults['is_active'] = False return Story.objects.get_or_create(object_url=object_url, ...
58ae075463518e477185816094eb83f42ce5b77c
gcloud/bigquery/__init__.py
gcloud/bigquery/__init__.py
from gcloud.bigquery.client import Client from gcloud.bigquery.connection import SCOPE from gcloud.bigquery.dataset import Dataset
from gcloud.bigquery.client import Client from gcloud.bigquery.connection import SCOPE from gcloud.bigquery.dataset import Dataset from gcloud.bigquery.table import SchemaField from gcloud.bigquery.table import Table
Add public API entties from 'bigquery.table'.
Add public API entties from 'bigquery.table'.
Python
apache-2.0
CyrusBiotechnology/gcloud-python,tseaver/google-cloud-python,Fkawala/gcloud-python,waprin/gcloud-python,jonparrott/gcloud-python,EugenePig/gcloud-python,dhermes/google-cloud-python,tswast/google-cloud-python,thesandlord/gcloud-python,tswast/google-cloud-python,EugenePig/gcloud-python,jbuberel/gcloud-python,dhermes/google-cloud-python,calpeyser/google-cloud-python,tseaver/gcloud-python,dhermes/gcloud-python,dhermes/google-cloud-python,tseaver/google-cloud-python,jgeewax/gcloud-python,tswast/google-cloud-python,waprin/google-cloud-python,GoogleCloudPlatform/gcloud-python,jonparrott/google-cloud-python,tseaver/google-cloud-python,vj-ug/gcloud-python,quom/google-cloud-python,googleapis/google-cloud-python,tseaver/gcloud-python,tartavull/google-cloud-python,daspecster/google-cloud-python,quom/google-cloud-python,dhermes/gcloud-python,jonparrott/google-cloud-python,googleapis/google-cloud-python,Fkawala/gcloud-python,jbuberel/gcloud-python,elibixby/gcloud-python,VitalLabs/gcloud-python,waprin/gcloud-python,GoogleCloudPlatform/gcloud-python,CyrusBiotechnology/gcloud-python,jonparrott/gcloud-python,jgeewax/gcloud-python,vj-ug/gcloud-python,VitalLabs/gcloud-python,waprin/google-cloud-python,thesandlord/gcloud-python,daspecster/google-cloud-python,elibixby/gcloud-python,tartavull/google-cloud-python,calpeyser/google-cloud-python
from gcloud.bigquery.client import Client from gcloud.bigquery.connection import SCOPE from gcloud.bigquery.dataset import Dataset + from gcloud.bigquery.table import SchemaField + from gcloud.bigquery.table import Table
Add public API entties from 'bigquery.table'.
## Code Before: from gcloud.bigquery.client import Client from gcloud.bigquery.connection import SCOPE from gcloud.bigquery.dataset import Dataset ## Instruction: Add public API entties from 'bigquery.table'. ## Code After: from gcloud.bigquery.client import Client from gcloud.bigquery.connection import SCOPE from gcloud.bigquery.dataset import Dataset from gcloud.bigquery.table import SchemaField from gcloud.bigquery.table import Table
// ... existing code ... from gcloud.bigquery.dataset import Dataset from gcloud.bigquery.table import SchemaField from gcloud.bigquery.table import Table // ... rest of the code ...
f01921e6e2fbac76dc41e354b84f970b1591193d
nsone/rest/monitoring.py
nsone/rest/monitoring.py
from . import resource class Monitors(resource.BaseResource): ROOT = 'monitoring/jobs' PASSTHRU_FIELDS = ['name', 'config'] def list(self, callback=None, errback=None): return self._make_request('GET', '%s' % (self.ROOT), callback=callback, errback=errback) def update(self, jobid, body, callback=None, errback=None, **kwargs): self._buildStdBody(body, kwargs) return self._make_request('POST', '%s/%s' % (self.ROOT, jobid), body=body, callback=callback, errback=errback) def create(self,body, callback=None, errback=None): return self._make_request('PUT', '%s' % (self.ROOT), body=body, callback=callback, errback=errback) def retrieve(self, jobid, callback=None, errback=None): return self._make_request('GET', '%s/%s' % (self.ROOT, jobid), callback=callback, errback=errback)
from . import resource class Monitors(resource.BaseResource): ROOT = 'monitoring/jobs' PASSTHRU_FIELDS = ['name', 'config'] def list(self, callback=None, errback=None): return self._make_request('GET', '%s' % (self.ROOT), callback=callback, errback=errback) def update(self, jobid, body, callback=None, errback=None, **kwargs): self._buildStdBody(body, kwargs) return self._make_request('POST', '%s/%s' % (self.ROOT, jobid), body=body, callback=callback, errback=errback) def create(self,body, callback=None, errback=None): return self._make_request('PUT', '%s' % (self.ROOT), body=body, callback=callback, errback=errback) def retrieve(self, jobid, callback=None, errback=None): return self._make_request('GET', '%s/%s' % (self.ROOT, jobid), callback=callback, errback=errback) def delete(self, jobid, callback=None, errback=None): return self._make_request('DELETE', '%s/%s' % (self.ROOT, jobid), callback=callback, errback=errback)
Add support for monitor deletion
Add support for monitor deletion
Python
mit
nsone/nsone-python,ns1/nsone-python
from . import resource class Monitors(resource.BaseResource): ROOT = 'monitoring/jobs' PASSTHRU_FIELDS = ['name', 'config'] def list(self, callback=None, errback=None): return self._make_request('GET', '%s' % (self.ROOT), callback=callback, errback=errback) def update(self, jobid, body, callback=None, errback=None, **kwargs): self._buildStdBody(body, kwargs) return self._make_request('POST', '%s/%s' % (self.ROOT, jobid), body=body, callback=callback, - errback=errback) + errback=errback) def create(self,body, callback=None, errback=None): return self._make_request('PUT', '%s' % (self.ROOT), body=body, callback=callback, errback=errback) def retrieve(self, jobid, callback=None, errback=None): return self._make_request('GET', '%s/%s' % (self.ROOT, jobid), callback=callback, errback=errback) + def delete(self, jobid, callback=None, errback=None): + return self._make_request('DELETE', '%s/%s' % (self.ROOT, jobid), + callback=callback, + errback=errback) +
Add support for monitor deletion
## Code Before: from . import resource class Monitors(resource.BaseResource): ROOT = 'monitoring/jobs' PASSTHRU_FIELDS = ['name', 'config'] def list(self, callback=None, errback=None): return self._make_request('GET', '%s' % (self.ROOT), callback=callback, errback=errback) def update(self, jobid, body, callback=None, errback=None, **kwargs): self._buildStdBody(body, kwargs) return self._make_request('POST', '%s/%s' % (self.ROOT, jobid), body=body, callback=callback, errback=errback) def create(self,body, callback=None, errback=None): return self._make_request('PUT', '%s' % (self.ROOT), body=body, callback=callback, errback=errback) def retrieve(self, jobid, callback=None, errback=None): return self._make_request('GET', '%s/%s' % (self.ROOT, jobid), callback=callback, errback=errback) ## Instruction: Add support for monitor deletion ## Code After: from . import resource class Monitors(resource.BaseResource): ROOT = 'monitoring/jobs' PASSTHRU_FIELDS = ['name', 'config'] def list(self, callback=None, errback=None): return self._make_request('GET', '%s' % (self.ROOT), callback=callback, errback=errback) def update(self, jobid, body, callback=None, errback=None, **kwargs): self._buildStdBody(body, kwargs) return self._make_request('POST', '%s/%s' % (self.ROOT, jobid), body=body, callback=callback, errback=errback) def create(self,body, callback=None, errback=None): return self._make_request('PUT', '%s' % (self.ROOT), body=body, callback=callback, errback=errback) def retrieve(self, jobid, callback=None, errback=None): return self._make_request('GET', '%s/%s' % (self.ROOT, jobid), callback=callback, errback=errback) def delete(self, jobid, callback=None, errback=None): return self._make_request('DELETE', '%s/%s' % (self.ROOT, jobid), callback=callback, errback=errback)
// ... existing code ... callback=callback, errback=errback) // ... modified code ... errback=errback) def delete(self, jobid, callback=None, errback=None): return self._make_request('DELETE', '%s/%s' % (self.ROOT, jobid), callback=callback, errback=errback) // ... rest of the code ...
6d5edb8a5eacfb2dc83a2eef5732562024995942
api/serializers.py
api/serializers.py
from django.utils.translation import ugettext as _ from rest_framework.serializers import ModelSerializer, ValidationError from reg.models import Team class TeamSerializer(ModelSerializer): def validate(self, data): if 'is_school' in data and data['is_school']: error_dict = {} if 'school_name' not in data or not data['school_name'].strip(): error_dict['school_name'] = [_('The field is required for school teams')] if 'teacher_name' not in data or not data['teacher_name'].strip(): error_dict['teacher_name'] = [_('The field is required for school teams')] if 'teacher_email' not in data or not data['teacher_email'].strip(): error_dict['teacher_email'] = [_('The field is required for school teams')] if 'address' not in data or not data['address'].strip(): error_dict['address'] = [_('The field is required for school teams')] if len(error_dict) > 0: raise ValidationError(error_dict) return data class Meta: model = Team exclude = ('auth_string',) read_only_fields = ('id', 'created_at')
from django.utils.translation import ugettext as _ from rest_framework.serializers import ModelSerializer, ValidationError from reg.models import Team class TeamSerializer(ModelSerializer): def validate(self, data): error_dict = {} if 'is_school' in data and data['is_school']: if 'school_name' not in data or not data['school_name'].strip(): error_dict['school_name'] = [_('The field is required for school teams')] if 'teacher_name' not in data or not data['teacher_name'].strip(): error_dict['teacher_name'] = [_('The field is required for school teams')] if 'teacher_email' not in data or not data['teacher_email'].strip(): error_dict['teacher_email'] = [_('The field is required for school teams')] if 'address' not in data or not data['address'].strip(): error_dict['address'] = [_('The field is required for school teams')] if len(error_dict) > 0: raise ValidationError(error_dict) return data class Meta: model = Team exclude = ('auth_string',) read_only_fields = ('id', 'created_at')
Fix bug with registering non-school teams
Fix bug with registering non-school teams
Python
bsd-3-clause
stefantsov/blackbox3,stefantsov/blackbox3,stefantsov/blackbox3
from django.utils.translation import ugettext as _ from rest_framework.serializers import ModelSerializer, ValidationError from reg.models import Team class TeamSerializer(ModelSerializer): def validate(self, data): + error_dict = {} if 'is_school' in data and data['is_school']: - error_dict = {} if 'school_name' not in data or not data['school_name'].strip(): error_dict['school_name'] = [_('The field is required for school teams')] if 'teacher_name' not in data or not data['teacher_name'].strip(): error_dict['teacher_name'] = [_('The field is required for school teams')] if 'teacher_email' not in data or not data['teacher_email'].strip(): error_dict['teacher_email'] = [_('The field is required for school teams')] if 'address' not in data or not data['address'].strip(): error_dict['address'] = [_('The field is required for school teams')] if len(error_dict) > 0: raise ValidationError(error_dict) return data class Meta: model = Team exclude = ('auth_string',) read_only_fields = ('id', 'created_at')
Fix bug with registering non-school teams
## Code Before: from django.utils.translation import ugettext as _ from rest_framework.serializers import ModelSerializer, ValidationError from reg.models import Team class TeamSerializer(ModelSerializer): def validate(self, data): if 'is_school' in data and data['is_school']: error_dict = {} if 'school_name' not in data or not data['school_name'].strip(): error_dict['school_name'] = [_('The field is required for school teams')] if 'teacher_name' not in data or not data['teacher_name'].strip(): error_dict['teacher_name'] = [_('The field is required for school teams')] if 'teacher_email' not in data or not data['teacher_email'].strip(): error_dict['teacher_email'] = [_('The field is required for school teams')] if 'address' not in data or not data['address'].strip(): error_dict['address'] = [_('The field is required for school teams')] if len(error_dict) > 0: raise ValidationError(error_dict) return data class Meta: model = Team exclude = ('auth_string',) read_only_fields = ('id', 'created_at') ## Instruction: Fix bug with registering non-school teams ## Code After: from django.utils.translation import ugettext as _ from rest_framework.serializers import ModelSerializer, ValidationError from reg.models import Team class TeamSerializer(ModelSerializer): def validate(self, data): error_dict = {} if 'is_school' in data and data['is_school']: if 'school_name' not in data or not data['school_name'].strip(): error_dict['school_name'] = [_('The field is required for school teams')] if 'teacher_name' not in data or not data['teacher_name'].strip(): error_dict['teacher_name'] = [_('The field is required for school teams')] if 'teacher_email' not in data or not data['teacher_email'].strip(): error_dict['teacher_email'] = [_('The field is required for school teams')] if 'address' not in data or not data['address'].strip(): error_dict['address'] = [_('The field is required for school teams')] if len(error_dict) > 0: raise ValidationError(error_dict) return data class Meta: model = Team exclude = ('auth_string',) read_only_fields = ('id', 'created_at')
// ... existing code ... def validate(self, data): error_dict = {} if 'is_school' in data and data['is_school']: if 'school_name' not in data or not data['school_name'].strip(): // ... rest of the code ...
98f26daf7c2c062d3bd72352413641e0df111871
src/ansible/forms.py
src/ansible/forms.py
from django import forms from django.conf import settings from django.forms import ModelForm from ansible.models import Playbook class AnsibleForm1(ModelForm): class Meta: model = Playbook fields = ['repository', 'username'] class AnsibleForm2(ModelForm): class Meta: model = Playbook fields = ['inventory', 'user'] class LoginForm(forms.Form): username = forms.CharField(label='Username', max_length=100) password = forms.CharField(label='Password', max_length=100) class PlaybookFileForm(forms.Form): filename = forms.CharField(label='Filename', max_length=100) playbook = forms.CharField(widget=forms.Textarea(attrs={'rows':30,'cols':80}))
from django import forms from django.core.validators import ValidationError from django.conf import settings from django.forms import ModelForm from ansible.models import Playbook import utils.playbook as playbook_utils import os class AnsibleForm1(ModelForm): class Meta: model = Playbook fields = ['repository', 'username'] class AnsibleForm2(ModelForm): class Meta: model = Playbook fields = ['inventory', 'user'] class LoginForm(forms.Form): username = forms.CharField(label='Username', max_length=100) password = forms.CharField(label='Password', max_length=100) class PlaybookFileForm(forms.Form): filename = forms.CharField(label='Filename', max_length=100) playbook = forms.CharField(widget=forms.Textarea(attrs={'rows':30,'cols':80})) def __init__(self, *args, **kwargs): self.pk = kwargs.pop('pk', None) super(PlaybookFileForm, self).__init__(*args, **kwargs) def clean_filename(self): data = playbook_utils.append_extension(self.cleaned_data['filename']) playbook = Playbook.query_set.get(pk=self.pk) playbook_dir = playbook.directory playbook_file_path = os.path.join(playbook_dir, data) if os.path.exists(playbook_file_path): raise forms.ValidationError("Filename already used") return data
Use clean_filename to validate if filename is already used
Use clean_filename to validate if filename is already used
Python
bsd-3-clause
lozadaOmr/ansible-admin,lozadaOmr/ansible-admin,lozadaOmr/ansible-admin
from django import forms + from django.core.validators import ValidationError from django.conf import settings from django.forms import ModelForm from ansible.models import Playbook + import utils.playbook as playbook_utils + import os class AnsibleForm1(ModelForm): class Meta: model = Playbook fields = ['repository', 'username'] class AnsibleForm2(ModelForm): class Meta: model = Playbook fields = ['inventory', 'user'] class LoginForm(forms.Form): username = forms.CharField(label='Username', max_length=100) password = forms.CharField(label='Password', max_length=100) class PlaybookFileForm(forms.Form): filename = forms.CharField(label='Filename', max_length=100) playbook = forms.CharField(widget=forms.Textarea(attrs={'rows':30,'cols':80})) + def __init__(self, *args, **kwargs): + self.pk = kwargs.pop('pk', None) + super(PlaybookFileForm, self).__init__(*args, **kwargs) + + def clean_filename(self): + data = playbook_utils.append_extension(self.cleaned_data['filename']) + playbook = Playbook.query_set.get(pk=self.pk) + playbook_dir = playbook.directory + playbook_file_path = os.path.join(playbook_dir, data) + if os.path.exists(playbook_file_path): + raise forms.ValidationError("Filename already used") + return data +
Use clean_filename to validate if filename is already used
## Code Before: from django import forms from django.conf import settings from django.forms import ModelForm from ansible.models import Playbook class AnsibleForm1(ModelForm): class Meta: model = Playbook fields = ['repository', 'username'] class AnsibleForm2(ModelForm): class Meta: model = Playbook fields = ['inventory', 'user'] class LoginForm(forms.Form): username = forms.CharField(label='Username', max_length=100) password = forms.CharField(label='Password', max_length=100) class PlaybookFileForm(forms.Form): filename = forms.CharField(label='Filename', max_length=100) playbook = forms.CharField(widget=forms.Textarea(attrs={'rows':30,'cols':80})) ## Instruction: Use clean_filename to validate if filename is already used ## Code After: from django import forms from django.core.validators import ValidationError from django.conf import settings from django.forms import ModelForm from ansible.models import Playbook import utils.playbook as playbook_utils import os class AnsibleForm1(ModelForm): class Meta: model = Playbook fields = ['repository', 'username'] class AnsibleForm2(ModelForm): class Meta: model = Playbook fields = ['inventory', 'user'] class LoginForm(forms.Form): username = forms.CharField(label='Username', max_length=100) password = forms.CharField(label='Password', max_length=100) class PlaybookFileForm(forms.Form): filename = forms.CharField(label='Filename', max_length=100) playbook = forms.CharField(widget=forms.Textarea(attrs={'rows':30,'cols':80})) def __init__(self, *args, **kwargs): self.pk = kwargs.pop('pk', None) super(PlaybookFileForm, self).__init__(*args, **kwargs) def clean_filename(self): data = playbook_utils.append_extension(self.cleaned_data['filename']) playbook = Playbook.query_set.get(pk=self.pk) playbook_dir = playbook.directory playbook_file_path = os.path.join(playbook_dir, data) if os.path.exists(playbook_file_path): raise forms.ValidationError("Filename already used") return data
// ... existing code ... from django import forms from django.core.validators import ValidationError from django.conf import settings // ... modified code ... from ansible.models import Playbook import utils.playbook as playbook_utils import os ... playbook = forms.CharField(widget=forms.Textarea(attrs={'rows':30,'cols':80})) def __init__(self, *args, **kwargs): self.pk = kwargs.pop('pk', None) super(PlaybookFileForm, self).__init__(*args, **kwargs) def clean_filename(self): data = playbook_utils.append_extension(self.cleaned_data['filename']) playbook = Playbook.query_set.get(pk=self.pk) playbook_dir = playbook.directory playbook_file_path = os.path.join(playbook_dir, data) if os.path.exists(playbook_file_path): raise forms.ValidationError("Filename already used") return data // ... rest of the code ...
07dc719807a6d890fa33338746caca61704de0a1
src/genbank-gff-to-nquads.py
src/genbank-gff-to-nquads.py
import jargparse ################# ### CONSTANTS ### ################# metadataPrefix = '#' accessionKey = '#!genome-build-accession NCBI_Assembly:' locusTagAttributeKey = 'locus_tag' ################# ### FUNCTIONS ### ################# def parseRecord(record, locusTags): components = record.split() type = components[2] rawAttributes = components[8] if type == 'gene': attributes = rawAttributes.split(';') for a in attributes: (key, value) = a.split('=') # print a if key == locusTagAttributeKey: locusTags.append(value) parser = jargparse.ArgParser('Convert Genbank GFF into an n-quad file') parser.add_argument('gffPath', help='path to the GFF') parser.add_argument('outPath', help='path to output the n-quads') args = parser.parse_args() accessionIdentifier = 'NONE FOUND' locusTags = [] with open(args.gffPath) as f: for line in f: line = line.strip() if line.startswith(metadataPrefix): if line.startswith(accessionKey): accessionIdentifier = line[len(accessionKey):] else: parseRecord(line, locusTags) with open(args.outPath, 'w') as f: for locusTag in locusTags: f.write('<%s> <locus> "%s" .\n' % (accessionIdentifier, locusTag))
import jargparse ################# ### CONSTANTS ### ################# metadataPrefix = '#' accessionKey = '#!genome-build-accession NCBI_Assembly:' ################# ### FUNCTIONS ### ################# def parseRecord(record, locusTags): locusTagAttributeKey = 'locus_tag' components = record.split() type = components[2] rawAttributes = components[8] if type == 'gene': attributes = rawAttributes.split(';') for a in attributes: (key, value) = a.split('=') # print a if key == locusTagAttributeKey: locusTags.append(value) parser = jargparse.ArgParser('Convert Genbank GFF into an n-quad file') parser.add_argument('gffPath', help='path to the GFF') parser.add_argument('outPath', help='path to output the n-quads') args = parser.parse_args() accessionIdentifier = 'NONE FOUND' locusTags = [] with open(args.gffPath) as f: for line in f: line = line.strip() if line.startswith(metadataPrefix): if line.startswith(accessionKey): accessionIdentifier = line[len(accessionKey):] else: parseRecord(line, locusTags) with open(args.outPath, 'w') as f: for locusTag in locusTags: f.write('<%s> <locus> "%s" .\n' % (accessionIdentifier, locusTag))
Move locus tag attribute key name into the function that uses it
Move locus tag attribute key name into the function that uses it
Python
apache-2.0
justinccdev/biolta
import jargparse ################# ### CONSTANTS ### ################# metadataPrefix = '#' accessionKey = '#!genome-build-accession NCBI_Assembly:' - locusTagAttributeKey = 'locus_tag' ################# ### FUNCTIONS ### ################# def parseRecord(record, locusTags): + locusTagAttributeKey = 'locus_tag' + components = record.split() type = components[2] rawAttributes = components[8] if type == 'gene': attributes = rawAttributes.split(';') for a in attributes: (key, value) = a.split('=') # print a if key == locusTagAttributeKey: locusTags.append(value) parser = jargparse.ArgParser('Convert Genbank GFF into an n-quad file') parser.add_argument('gffPath', help='path to the GFF') parser.add_argument('outPath', help='path to output the n-quads') args = parser.parse_args() accessionIdentifier = 'NONE FOUND' locusTags = [] with open(args.gffPath) as f: for line in f: line = line.strip() if line.startswith(metadataPrefix): if line.startswith(accessionKey): accessionIdentifier = line[len(accessionKey):] else: parseRecord(line, locusTags) with open(args.outPath, 'w') as f: for locusTag in locusTags: f.write('<%s> <locus> "%s" .\n' % (accessionIdentifier, locusTag))
Move locus tag attribute key name into the function that uses it
## Code Before: import jargparse ################# ### CONSTANTS ### ################# metadataPrefix = '#' accessionKey = '#!genome-build-accession NCBI_Assembly:' locusTagAttributeKey = 'locus_tag' ################# ### FUNCTIONS ### ################# def parseRecord(record, locusTags): components = record.split() type = components[2] rawAttributes = components[8] if type == 'gene': attributes = rawAttributes.split(';') for a in attributes: (key, value) = a.split('=') # print a if key == locusTagAttributeKey: locusTags.append(value) parser = jargparse.ArgParser('Convert Genbank GFF into an n-quad file') parser.add_argument('gffPath', help='path to the GFF') parser.add_argument('outPath', help='path to output the n-quads') args = parser.parse_args() accessionIdentifier = 'NONE FOUND' locusTags = [] with open(args.gffPath) as f: for line in f: line = line.strip() if line.startswith(metadataPrefix): if line.startswith(accessionKey): accessionIdentifier = line[len(accessionKey):] else: parseRecord(line, locusTags) with open(args.outPath, 'w') as f: for locusTag in locusTags: f.write('<%s> <locus> "%s" .\n' % (accessionIdentifier, locusTag)) ## Instruction: Move locus tag attribute key name into the function that uses it ## Code After: import jargparse ################# ### CONSTANTS ### ################# metadataPrefix = '#' accessionKey = '#!genome-build-accession NCBI_Assembly:' ################# ### FUNCTIONS ### ################# def parseRecord(record, locusTags): locusTagAttributeKey = 'locus_tag' components = record.split() type = components[2] rawAttributes = components[8] if type == 'gene': attributes = rawAttributes.split(';') for a in attributes: (key, value) = a.split('=') # print a if key == locusTagAttributeKey: locusTags.append(value) parser = jargparse.ArgParser('Convert Genbank GFF into an n-quad file') parser.add_argument('gffPath', help='path to the GFF') parser.add_argument('outPath', help='path to output the n-quads') args = parser.parse_args() accessionIdentifier = 'NONE FOUND' locusTags = [] with open(args.gffPath) as f: for line in f: line = line.strip() if line.startswith(metadataPrefix): if line.startswith(accessionKey): accessionIdentifier = line[len(accessionKey):] else: parseRecord(line, locusTags) with open(args.outPath, 'w') as f: for locusTag in locusTags: f.write('<%s> <locus> "%s" .\n' % (accessionIdentifier, locusTag))
// ... existing code ... accessionKey = '#!genome-build-accession NCBI_Assembly:' // ... modified code ... def parseRecord(record, locusTags): locusTagAttributeKey = 'locus_tag' components = record.split() // ... rest of the code ...
e99c230f2bf7bdc010552c03ca657adddebaf818
chessfellows/chess/urls.py
chessfellows/chess/urls.py
from django.conf.urls import patterns, url from django.contrib import admin from chess import views admin.autodiscover() urlpatterns = patterns('', url(r'^accounts/home/', views.home_page, name='home'), url(r'^accounts/history/$', views.history_page, name='history'), url(r'^accounts/profile/$', views.profile_page, name='profile'), )
from django.conf.urls import patterns, url from django.contrib import admin from chess import views admin.autodiscover() urlpatterns = patterns('', url(r'^accounts/home/', views.home_page, name='home'), url(r'^accounts/history/$', views.history_page, name='history'), url(r'^accounts/profile/$', views.profile_page, name='profile'), url(r'^$', views.base, name='base'), )
Add url for landing page (/) that links to the base view
Add url for landing page (/) that links to the base view
Python
mit
EyuelAbebe/gamer,EyuelAbebe/gamer
from django.conf.urls import patterns, url from django.contrib import admin from chess import views admin.autodiscover() urlpatterns = patterns('', url(r'^accounts/home/', views.home_page, name='home'), url(r'^accounts/history/$', views.history_page, name='history'), url(r'^accounts/profile/$', views.profile_page, name='profile'), - + url(r'^$', views.base, name='base'), )
Add url for landing page (/) that links to the base view
## Code Before: from django.conf.urls import patterns, url from django.contrib import admin from chess import views admin.autodiscover() urlpatterns = patterns('', url(r'^accounts/home/', views.home_page, name='home'), url(r'^accounts/history/$', views.history_page, name='history'), url(r'^accounts/profile/$', views.profile_page, name='profile'), ) ## Instruction: Add url for landing page (/) that links to the base view ## Code After: from django.conf.urls import patterns, url from django.contrib import admin from chess import views admin.autodiscover() urlpatterns = patterns('', url(r'^accounts/home/', views.home_page, name='home'), url(r'^accounts/history/$', views.history_page, name='history'), url(r'^accounts/profile/$', views.profile_page, name='profile'), url(r'^$', views.base, name='base'), )
// ... existing code ... url(r'^accounts/profile/$', views.profile_page, name='profile'), url(r'^$', views.base, name='base'), ) // ... rest of the code ...
bb18029c9ca75b420aa486e393b2f79e8f2e009b
examples/echobot.py
examples/echobot.py
from linepy import * client = LineClient() #client = LineClient(authToken='AUTHTOKEN') client.log("Auth Token : " + str(client.authToken)) poll = LinePoll(client) # Receive messages from LinePoll def RECEIVE_MESSAGE(op): msg = op.message text = msg.text msg_id = msg.id receiver = msg.to sender = msg._from if msg.contentType == 0: contact = client.getContact(receiver) txt = '[%s] %s' % (contact.displayName, text) client.sendMessage(receiver, txt) client.log(txt) # Add function to LinePoll poll.addOpInterruptWithDict({ OpType.RECEIVE_MESSAGE: RECEIVE_MESSAGE }) while True: poll.trace()
from linepy import * client = LineClient() #client = LineClient(authToken='AUTHTOKEN') client.log("Auth Token : " + str(client.authToken)) poll = LinePoll(client) # Receive messages from LinePoll def RECEIVE_MESSAGE(op): msg = op.message text = msg.text msg_id = msg.id receiver = msg.to sender = msg._from # Check content only text message if msg.contentType == 0: # Check only group chat if msg.toType == 2: # Get sender contact contact = client.getContact(sender) txt = '[%s] %s' % (contact.displayName, text) # Send a message client.sendMessage(receiver, txt) # Print log client.log(txt) # Add function to LinePoll poll.addOpInterruptWithDict({ OpType.RECEIVE_MESSAGE: RECEIVE_MESSAGE }) while True: poll.trace()
Change receiver contact to sender
Change receiver contact to sender
Python
bsd-3-clause
fadhiilrachman/line-py
from linepy import * client = LineClient() #client = LineClient(authToken='AUTHTOKEN') client.log("Auth Token : " + str(client.authToken)) poll = LinePoll(client) # Receive messages from LinePoll def RECEIVE_MESSAGE(op): msg = op.message text = msg.text msg_id = msg.id receiver = msg.to sender = msg._from - + + # Check content only text message if msg.contentType == 0: + # Check only group chat + if msg.toType == 2: + # Get sender contact - contact = client.getContact(receiver) + contact = client.getContact(sender) - txt = '[%s] %s' % (contact.displayName, text) + txt = '[%s] %s' % (contact.displayName, text) + # Send a message - client.sendMessage(receiver, txt) + client.sendMessage(receiver, txt) + # Print log - client.log(txt) + client.log(txt) # Add function to LinePoll poll.addOpInterruptWithDict({ OpType.RECEIVE_MESSAGE: RECEIVE_MESSAGE }) while True: - poll.trace() + poll.trace() +
Change receiver contact to sender
## Code Before: from linepy import * client = LineClient() #client = LineClient(authToken='AUTHTOKEN') client.log("Auth Token : " + str(client.authToken)) poll = LinePoll(client) # Receive messages from LinePoll def RECEIVE_MESSAGE(op): msg = op.message text = msg.text msg_id = msg.id receiver = msg.to sender = msg._from if msg.contentType == 0: contact = client.getContact(receiver) txt = '[%s] %s' % (contact.displayName, text) client.sendMessage(receiver, txt) client.log(txt) # Add function to LinePoll poll.addOpInterruptWithDict({ OpType.RECEIVE_MESSAGE: RECEIVE_MESSAGE }) while True: poll.trace() ## Instruction: Change receiver contact to sender ## Code After: from linepy import * client = LineClient() #client = LineClient(authToken='AUTHTOKEN') client.log("Auth Token : " + str(client.authToken)) poll = LinePoll(client) # Receive messages from LinePoll def RECEIVE_MESSAGE(op): msg = op.message text = msg.text msg_id = msg.id receiver = msg.to sender = msg._from # Check content only text message if msg.contentType == 0: # Check only group chat if msg.toType == 2: # Get sender contact contact = client.getContact(sender) txt = '[%s] %s' % (contact.displayName, text) # Send a message client.sendMessage(receiver, txt) # Print log client.log(txt) # Add function to LinePoll poll.addOpInterruptWithDict({ OpType.RECEIVE_MESSAGE: RECEIVE_MESSAGE }) while True: poll.trace()
... sender = msg._from # Check content only text message if msg.contentType == 0: # Check only group chat if msg.toType == 2: # Get sender contact contact = client.getContact(sender) txt = '[%s] %s' % (contact.displayName, text) # Send a message client.sendMessage(receiver, txt) # Print log client.log(txt) ...
2a550df5d9200deb6700fca4270526633811d592
osfclient/cli.py
osfclient/cli.py
"""Command line interface to the OSF""" import os from .api import OSF CHUNK_SIZE = int(5e6) def _setup_osf(args): # command line argument overrides environment variable username = os.getenv("OSF_USERNAME") if args.username is not None: username = args.username password = os.getenv("OSF_PASSWORD") return OSF(username=username, password=password) def fetch(args): osf = _setup_osf(args) project = osf.project(args.project) output_dir = args.project if args.output is not None: output_dir = args.output for store in project.storages: prefix = os.path.join(output_dir, store.name) for file_ in store.files: path = file_.path if path.startswith('/'): path = path[1:] path = os.path.join(prefix, path) directory, _ = os.path.split(path) os.makedirs(directory, exist_ok=True) with open(path, "wb") as f: file_.write_to(f) def list_(args): osf = _setup_osf(args) project = osf.project(args.project) for store in project.storages: prefix = store.name for file_ in store.files: path = file_.path if path.startswith('/'): path = path[1:] print(os.path.join(prefix, path))
"""Command line interface to the OSF""" import os from .api import OSF CHUNK_SIZE = int(5e6) def _setup_osf(args): # command line argument overrides environment variable username = os.getenv("OSF_USERNAME") if args.username is not None: username = args.username password = None if username is not None: password = os.getenv("OSF_PASSWORD") return OSF(username=username, password=password) def fetch(args): osf = _setup_osf(args) project = osf.project(args.project) output_dir = args.project if args.output is not None: output_dir = args.output for store in project.storages: prefix = os.path.join(output_dir, store.name) for file_ in store.files: path = file_.path if path.startswith('/'): path = path[1:] path = os.path.join(prefix, path) directory, _ = os.path.split(path) os.makedirs(directory, exist_ok=True) with open(path, "wb") as f: file_.write_to(f) def list_(args): osf = _setup_osf(args) project = osf.project(args.project) for store in project.storages: prefix = store.name for file_ in store.files: path = file_.path if path.startswith('/'): path = path[1:] print(os.path.join(prefix, path))
Stop grabbing password when there is no username
Stop grabbing password when there is no username
Python
bsd-3-clause
betatim/osf-cli,betatim/osf-cli
"""Command line interface to the OSF""" import os from .api import OSF CHUNK_SIZE = int(5e6) def _setup_osf(args): # command line argument overrides environment variable username = os.getenv("OSF_USERNAME") if args.username is not None: username = args.username + password = None + if username is not None: - password = os.getenv("OSF_PASSWORD") + password = os.getenv("OSF_PASSWORD") return OSF(username=username, password=password) def fetch(args): osf = _setup_osf(args) project = osf.project(args.project) output_dir = args.project if args.output is not None: output_dir = args.output for store in project.storages: prefix = os.path.join(output_dir, store.name) for file_ in store.files: path = file_.path if path.startswith('/'): path = path[1:] path = os.path.join(prefix, path) directory, _ = os.path.split(path) os.makedirs(directory, exist_ok=True) with open(path, "wb") as f: file_.write_to(f) def list_(args): osf = _setup_osf(args) project = osf.project(args.project) for store in project.storages: prefix = store.name for file_ in store.files: path = file_.path if path.startswith('/'): path = path[1:] print(os.path.join(prefix, path))
Stop grabbing password when there is no username
## Code Before: """Command line interface to the OSF""" import os from .api import OSF CHUNK_SIZE = int(5e6) def _setup_osf(args): # command line argument overrides environment variable username = os.getenv("OSF_USERNAME") if args.username is not None: username = args.username password = os.getenv("OSF_PASSWORD") return OSF(username=username, password=password) def fetch(args): osf = _setup_osf(args) project = osf.project(args.project) output_dir = args.project if args.output is not None: output_dir = args.output for store in project.storages: prefix = os.path.join(output_dir, store.name) for file_ in store.files: path = file_.path if path.startswith('/'): path = path[1:] path = os.path.join(prefix, path) directory, _ = os.path.split(path) os.makedirs(directory, exist_ok=True) with open(path, "wb") as f: file_.write_to(f) def list_(args): osf = _setup_osf(args) project = osf.project(args.project) for store in project.storages: prefix = store.name for file_ in store.files: path = file_.path if path.startswith('/'): path = path[1:] print(os.path.join(prefix, path)) ## Instruction: Stop grabbing password when there is no username ## Code After: """Command line interface to the OSF""" import os from .api import OSF CHUNK_SIZE = int(5e6) def _setup_osf(args): # command line argument overrides environment variable username = os.getenv("OSF_USERNAME") if args.username is not None: username = args.username password = None if username is not None: password = os.getenv("OSF_PASSWORD") return OSF(username=username, password=password) def fetch(args): osf = _setup_osf(args) project = osf.project(args.project) output_dir = args.project if args.output is not None: output_dir = args.output for store in project.storages: prefix = os.path.join(output_dir, store.name) for file_ in store.files: path = file_.path if path.startswith('/'): path = path[1:] path = os.path.join(prefix, path) directory, _ = os.path.split(path) os.makedirs(directory, exist_ok=True) with open(path, "wb") as f: file_.write_to(f) def list_(args): osf = _setup_osf(args) project = osf.project(args.project) for store in project.storages: prefix = store.name for file_ in store.files: path = file_.path if path.startswith('/'): path = path[1:] print(os.path.join(prefix, path))
# ... existing code ... password = None if username is not None: password = os.getenv("OSF_PASSWORD") # ... rest of the code ...
da9058064e2a94f717abe2f97af80d2daa4fa292
likert_field/models.py
likert_field/models.py
from __future__ import unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ import likert_field.forms as forms class LikertField(models.IntegerField): """A Likert field is simply stored as an IntegerField""" description = _('Likert item field') def __init__(self, *args, **kwargs): if 'null' not in kwargs and not kwargs.get('null'): kwargs['null'] = True super(LikertField, self).__init__(*args, **kwargs) def formfield(self, **kwargs): defaults = { 'min_value': 0, 'form_class': forms.LikertField } defaults.update(kwargs) return super(LikertField, self).formfield(**defaults)
from __future__ import unicode_literals from six import string_types from django.db import models from django.utils.translation import ugettext_lazy as _ import likert_field.forms as forms class LikertField(models.IntegerField): """A Likert field is simply stored as an IntegerField""" description = _('Likert item field') def __init__(self, *args, **kwargs): if 'null' not in kwargs and not kwargs.get('null'): kwargs['null'] = True super(LikertField, self).__init__(*args, **kwargs) def get_prep_value(self, value): """The field expects a number as a string (ie. '2'). Unscored fields are empty strings and are stored as NULL """ if value is None: return None if isinstance(value, string_types) and len(value) == 0: return None return int(value) def formfield(self, **kwargs): defaults = { 'min_value': 0, 'form_class': forms.LikertField } defaults.update(kwargs) return super(LikertField, self).formfield(**defaults)
Handle empty strings from unanswered items
Handle empty strings from unanswered items
Python
bsd-3-clause
kelvinwong-ca/django-likert-field,kelvinwong-ca/django-likert-field
from __future__ import unicode_literals + + from six import string_types from django.db import models from django.utils.translation import ugettext_lazy as _ import likert_field.forms as forms class LikertField(models.IntegerField): """A Likert field is simply stored as an IntegerField""" description = _('Likert item field') def __init__(self, *args, **kwargs): if 'null' not in kwargs and not kwargs.get('null'): kwargs['null'] = True super(LikertField, self).__init__(*args, **kwargs) + def get_prep_value(self, value): + """The field expects a number as a string (ie. '2'). + Unscored fields are empty strings and are stored as NULL + """ + if value is None: + return None + if isinstance(value, string_types) and len(value) == 0: + return None + return int(value) + def formfield(self, **kwargs): defaults = { 'min_value': 0, 'form_class': forms.LikertField } defaults.update(kwargs) return super(LikertField, self).formfield(**defaults)
Handle empty strings from unanswered items
## Code Before: from __future__ import unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ import likert_field.forms as forms class LikertField(models.IntegerField): """A Likert field is simply stored as an IntegerField""" description = _('Likert item field') def __init__(self, *args, **kwargs): if 'null' not in kwargs and not kwargs.get('null'): kwargs['null'] = True super(LikertField, self).__init__(*args, **kwargs) def formfield(self, **kwargs): defaults = { 'min_value': 0, 'form_class': forms.LikertField } defaults.update(kwargs) return super(LikertField, self).formfield(**defaults) ## Instruction: Handle empty strings from unanswered items ## Code After: from __future__ import unicode_literals from six import string_types from django.db import models from django.utils.translation import ugettext_lazy as _ import likert_field.forms as forms class LikertField(models.IntegerField): """A Likert field is simply stored as an IntegerField""" description = _('Likert item field') def __init__(self, *args, **kwargs): if 'null' not in kwargs and not kwargs.get('null'): kwargs['null'] = True super(LikertField, self).__init__(*args, **kwargs) def get_prep_value(self, value): """The field expects a number as a string (ie. '2'). Unscored fields are empty strings and are stored as NULL """ if value is None: return None if isinstance(value, string_types) and len(value) == 0: return None return int(value) def formfield(self, **kwargs): defaults = { 'min_value': 0, 'form_class': forms.LikertField } defaults.update(kwargs) return super(LikertField, self).formfield(**defaults)
// ... existing code ... from __future__ import unicode_literals from six import string_types // ... modified code ... def get_prep_value(self, value): """The field expects a number as a string (ie. '2'). Unscored fields are empty strings and are stored as NULL """ if value is None: return None if isinstance(value, string_types) and len(value) == 0: return None return int(value) def formfield(self, **kwargs): // ... rest of the code ...
1285e4bcbdbcf3c28eced497c8585892f3ae1239
django_summernote/admin.py
django_summernote/admin.py
from django.contrib import admin from django.db import models from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget from django_summernote.models import Attachment from django_summernote.settings import summernote_config, get_attachment_model __widget__ = SummernoteWidget if summernote_config['iframe'] \ else SummernoteInplaceWidget class SummernoteInlineModelAdmin(admin.options.InlineModelAdmin): formfield_overrides = {models.TextField: {'widget': __widget__}} class SummernoteModelAdmin(admin.ModelAdmin): formfield_overrides = {models.TextField: {'widget': __widget__}} class AttachmentAdmin(admin.ModelAdmin): list_display = ['name', 'file', 'uploaded'] search_fields = ['name'] ordering = ('-id',) def save_model(self, request, obj, form, change): obj.name = obj.file.name if (not obj.name) else obj.name super(AttachmentAdmin, self).save_model(request, obj, form, change) admin.site.register(get_attachment_model(), AttachmentAdmin)
from django.contrib import admin from django.db import models from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget from django_summernote.settings import summernote_config, get_attachment_model __widget__ = SummernoteWidget if summernote_config['iframe'] \ else SummernoteInplaceWidget class SummernoteInlineModelAdmin(admin.options.InlineModelAdmin): formfield_overrides = {models.TextField: {'widget': __widget__}} class SummernoteModelAdmin(admin.ModelAdmin): formfield_overrides = {models.TextField: {'widget': __widget__}} class AttachmentAdmin(admin.ModelAdmin): list_display = ['name', 'file', 'uploaded'] search_fields = ['name'] ordering = ('-id',) def save_model(self, request, obj, form, change): obj.name = obj.file.name if (not obj.name) else obj.name super(AttachmentAdmin, self).save_model(request, obj, form, change) admin.site.register(get_attachment_model(), AttachmentAdmin)
Remove a non-used module importing
Remove a non-used module importing
Python
mit
lqez/django-summernote,summernote/django-summernote,lqez/django-summernote,lqez/django-summernote,summernote/django-summernote,summernote/django-summernote
from django.contrib import admin from django.db import models from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget - from django_summernote.models import Attachment from django_summernote.settings import summernote_config, get_attachment_model __widget__ = SummernoteWidget if summernote_config['iframe'] \ else SummernoteInplaceWidget class SummernoteInlineModelAdmin(admin.options.InlineModelAdmin): formfield_overrides = {models.TextField: {'widget': __widget__}} class SummernoteModelAdmin(admin.ModelAdmin): formfield_overrides = {models.TextField: {'widget': __widget__}} class AttachmentAdmin(admin.ModelAdmin): list_display = ['name', 'file', 'uploaded'] search_fields = ['name'] ordering = ('-id',) def save_model(self, request, obj, form, change): obj.name = obj.file.name if (not obj.name) else obj.name super(AttachmentAdmin, self).save_model(request, obj, form, change) admin.site.register(get_attachment_model(), AttachmentAdmin)
Remove a non-used module importing
## Code Before: from django.contrib import admin from django.db import models from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget from django_summernote.models import Attachment from django_summernote.settings import summernote_config, get_attachment_model __widget__ = SummernoteWidget if summernote_config['iframe'] \ else SummernoteInplaceWidget class SummernoteInlineModelAdmin(admin.options.InlineModelAdmin): formfield_overrides = {models.TextField: {'widget': __widget__}} class SummernoteModelAdmin(admin.ModelAdmin): formfield_overrides = {models.TextField: {'widget': __widget__}} class AttachmentAdmin(admin.ModelAdmin): list_display = ['name', 'file', 'uploaded'] search_fields = ['name'] ordering = ('-id',) def save_model(self, request, obj, form, change): obj.name = obj.file.name if (not obj.name) else obj.name super(AttachmentAdmin, self).save_model(request, obj, form, change) admin.site.register(get_attachment_model(), AttachmentAdmin) ## Instruction: Remove a non-used module importing ## Code After: from django.contrib import admin from django.db import models from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget from django_summernote.settings import summernote_config, get_attachment_model __widget__ = SummernoteWidget if summernote_config['iframe'] \ else SummernoteInplaceWidget class SummernoteInlineModelAdmin(admin.options.InlineModelAdmin): formfield_overrides = {models.TextField: {'widget': __widget__}} class SummernoteModelAdmin(admin.ModelAdmin): formfield_overrides = {models.TextField: {'widget': __widget__}} class AttachmentAdmin(admin.ModelAdmin): list_display = ['name', 'file', 'uploaded'] search_fields = ['name'] ordering = ('-id',) def save_model(self, request, obj, form, change): obj.name = obj.file.name if (not obj.name) else obj.name super(AttachmentAdmin, self).save_model(request, obj, form, change) admin.site.register(get_attachment_model(), AttachmentAdmin)
// ... existing code ... from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget from django_summernote.settings import summernote_config, get_attachment_model // ... rest of the code ...
87cfac55b14083fdb8e346b9db1a95bb0f63881a
connect/config/factories.py
connect/config/factories.py
import factory from django.contrib.sites.models import Site from connect.config.models import SiteConfig class SiteFactory(factory.django.DjangoModelFactory): class Meta: model = Site name = factory.Sequence(lambda n: "site%s" % n) domain = factory.Sequence(lambda n: "site%s.com" % n) class SiteConfigFactory(factory.django.DjangoModelFactory): class Meta: model = SiteConfig site = factory.SubFactory(Site) email = factory.Sequence(lambda n: "site.email%[email protected]" % n) tagline = 'A tagline' email_header = factory.django.ImageField(filename='my_image.png')
import factory from django.contrib.sites.models import Site from connect.config.models import SiteConfig class SiteFactory(factory.django.DjangoModelFactory): class Meta: model = Site name = factory.Sequence(lambda n: "site%s" % n) domain = factory.Sequence(lambda n: "site%s.com" % n) class SiteConfigFactory(factory.django.DjangoModelFactory): class Meta: model = SiteConfig site = factory.SubFactory(Site) logo = factory.django.ImageField(filename='my_log.png', format='PNG') email = factory.Sequence(lambda n: "site.email%[email protected]" % n) tagline = 'A tagline' email_header = factory.django.ImageField(filename='my_image.png', format='PNG')
Reconfigure SiteConfigFactory to use JPG - removes pillow's libjpeg-dev dependency
Reconfigure SiteConfigFactory to use JPG - removes pillow's libjpeg-dev dependency
Python
bsd-3-clause
nlhkabu/connect,f3r3nc/connect,f3r3nc/connect,f3r3nc/connect,nlhkabu/connect,f3r3nc/connect,nlhkabu/connect,nlhkabu/connect
import factory from django.contrib.sites.models import Site from connect.config.models import SiteConfig class SiteFactory(factory.django.DjangoModelFactory): class Meta: model = Site name = factory.Sequence(lambda n: "site%s" % n) domain = factory.Sequence(lambda n: "site%s.com" % n) class SiteConfigFactory(factory.django.DjangoModelFactory): class Meta: model = SiteConfig site = factory.SubFactory(Site) + logo = factory.django.ImageField(filename='my_log.png', format='PNG') email = factory.Sequence(lambda n: "site.email%[email protected]" % n) tagline = 'A tagline' - email_header = factory.django.ImageField(filename='my_image.png') + email_header = factory.django.ImageField(filename='my_image.png', format='PNG')
Reconfigure SiteConfigFactory to use JPG - removes pillow's libjpeg-dev dependency
## Code Before: import factory from django.contrib.sites.models import Site from connect.config.models import SiteConfig class SiteFactory(factory.django.DjangoModelFactory): class Meta: model = Site name = factory.Sequence(lambda n: "site%s" % n) domain = factory.Sequence(lambda n: "site%s.com" % n) class SiteConfigFactory(factory.django.DjangoModelFactory): class Meta: model = SiteConfig site = factory.SubFactory(Site) email = factory.Sequence(lambda n: "site.email%[email protected]" % n) tagline = 'A tagline' email_header = factory.django.ImageField(filename='my_image.png') ## Instruction: Reconfigure SiteConfigFactory to use JPG - removes pillow's libjpeg-dev dependency ## Code After: import factory from django.contrib.sites.models import Site from connect.config.models import SiteConfig class SiteFactory(factory.django.DjangoModelFactory): class Meta: model = Site name = factory.Sequence(lambda n: "site%s" % n) domain = factory.Sequence(lambda n: "site%s.com" % n) class SiteConfigFactory(factory.django.DjangoModelFactory): class Meta: model = SiteConfig site = factory.SubFactory(Site) logo = factory.django.ImageField(filename='my_log.png', format='PNG') email = factory.Sequence(lambda n: "site.email%[email protected]" % n) tagline = 'A tagline' email_header = factory.django.ImageField(filename='my_image.png', format='PNG')
# ... existing code ... site = factory.SubFactory(Site) logo = factory.django.ImageField(filename='my_log.png', format='PNG') email = factory.Sequence(lambda n: "site.email%[email protected]" % n) # ... modified code ... tagline = 'A tagline' email_header = factory.django.ImageField(filename='my_image.png', format='PNG') # ... rest of the code ...
253e4e9df1b6a6cec7c20bc34a8ccf9423c8018e
scripts/create_neurohdf.py
scripts/create_neurohdf.py
import os.path as op import h5py from contextlib import closing import numpy as np project_id = 1 stack_id = 1 filepath = '/home/stephan/dev/CATMAID/django/hdf5' with closing(h5py.File(op.join(filepath, '%s_%s.hdf' % (project_id, stack_id)), 'w')) as hfile: mesh=hfile.create_group('meshes') midline=mesh.create_group('midline') midline.create_dataset("vertices", data=np.array( [4900, 40, 0, 5230, 70, 4131, 5250,7620,4131, 4820,7630,0] , dtype = np.float32 ) ) # faces are coded according to the three.js JSONLoader standard. # See https://github.com/mrdoob/three.js/blob/master/src/extras/loaders/JSONLoader.js midline.create_dataset("faces", data=np.array( [0, 0, 1, 2, 0,2,3,0] , dtype = np.uint32 ) )
import os.path as op import h5py from contextlib import closing import numpy as np project_id = 1 stack_id = 2 filepath = '/home/stephan/dev/CATMAID/django/hdf5' with closing(h5py.File(op.join(filepath, '%s_%s.hdf' % (project_id, stack_id)), 'w')) as hfile: mesh=hfile.create_group('meshes') midline=mesh.create_group('midline') midline.create_dataset("vertices", data=np.array( [61200, 15200, 26750,63920, 26400, 76800, 66800,57600,76800, 69200,53120,26750] , dtype = np.float32 ) ) # faces are coded according to the three.js JSONLoader standard. # See https://github.com/mrdoob/three.js/blob/master/src/extras/loaders/JSONLoader.js midline.create_dataset("faces", data=np.array( [0, 0, 1, 2, 0,2,3,0] , dtype = np.uint32 ) )
Change in coordinates in the NeuroHDF create
Change in coordinates in the NeuroHDF create
Python
agpl-3.0
htem/CATMAID,htem/CATMAID,fzadow/CATMAID,htem/CATMAID,htem/CATMAID,fzadow/CATMAID,fzadow/CATMAID,fzadow/CATMAID
import os.path as op import h5py from contextlib import closing import numpy as np project_id = 1 - stack_id = 1 + stack_id = 2 filepath = '/home/stephan/dev/CATMAID/django/hdf5' with closing(h5py.File(op.join(filepath, '%s_%s.hdf' % (project_id, stack_id)), 'w')) as hfile: mesh=hfile.create_group('meshes') midline=mesh.create_group('midline') - midline.create_dataset("vertices", data=np.array( [4900, 40, 0, 5230, 70, 4131, 5250,7620,4131, 4820,7630,0] , dtype = np.float32 ) ) + midline.create_dataset("vertices", data=np.array( [61200, 15200, 26750,63920, 26400, 76800, 66800,57600,76800, 69200,53120,26750] , dtype = np.float32 ) ) # faces are coded according to the three.js JSONLoader standard. # See https://github.com/mrdoob/three.js/blob/master/src/extras/loaders/JSONLoader.js midline.create_dataset("faces", data=np.array( [0, 0, 1, 2, 0,2,3,0] , dtype = np.uint32 ) )
Change in coordinates in the NeuroHDF create
## Code Before: import os.path as op import h5py from contextlib import closing import numpy as np project_id = 1 stack_id = 1 filepath = '/home/stephan/dev/CATMAID/django/hdf5' with closing(h5py.File(op.join(filepath, '%s_%s.hdf' % (project_id, stack_id)), 'w')) as hfile: mesh=hfile.create_group('meshes') midline=mesh.create_group('midline') midline.create_dataset("vertices", data=np.array( [4900, 40, 0, 5230, 70, 4131, 5250,7620,4131, 4820,7630,0] , dtype = np.float32 ) ) # faces are coded according to the three.js JSONLoader standard. # See https://github.com/mrdoob/three.js/blob/master/src/extras/loaders/JSONLoader.js midline.create_dataset("faces", data=np.array( [0, 0, 1, 2, 0,2,3,0] , dtype = np.uint32 ) ) ## Instruction: Change in coordinates in the NeuroHDF create ## Code After: import os.path as op import h5py from contextlib import closing import numpy as np project_id = 1 stack_id = 2 filepath = '/home/stephan/dev/CATMAID/django/hdf5' with closing(h5py.File(op.join(filepath, '%s_%s.hdf' % (project_id, stack_id)), 'w')) as hfile: mesh=hfile.create_group('meshes') midline=mesh.create_group('midline') midline.create_dataset("vertices", data=np.array( [61200, 15200, 26750,63920, 26400, 76800, 66800,57600,76800, 69200,53120,26750] , dtype = np.float32 ) ) # faces are coded according to the three.js JSONLoader standard. # See https://github.com/mrdoob/three.js/blob/master/src/extras/loaders/JSONLoader.js midline.create_dataset("faces", data=np.array( [0, 0, 1, 2, 0,2,3,0] , dtype = np.uint32 ) )
// ... existing code ... project_id = 1 stack_id = 2 filepath = '/home/stephan/dev/CATMAID/django/hdf5' // ... modified code ... midline=mesh.create_group('midline') midline.create_dataset("vertices", data=np.array( [61200, 15200, 26750,63920, 26400, 76800, 66800,57600,76800, 69200,53120,26750] , dtype = np.float32 ) ) # faces are coded according to the three.js JSONLoader standard. // ... rest of the code ...
d58c04d9745f1a0af46f35fba7b3e2aef704547e
application.py
application.py
import os from flask import Flask from whitenoise import WhiteNoise from app import create_app PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'app', 'static') STATIC_URL = 'static/' app = Flask('app') create_app(app) application = WhiteNoise(app, STATIC_ROOT, STATIC_URL)
import os from flask import Flask from whitenoise import WhiteNoise from app import create_app PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'app', 'static') STATIC_URL = 'static/' app = Flask('app') create_app(app) app.wsgi_app = WhiteNoise(app.wsgi_app, STATIC_ROOT, STATIC_URL)
Make Whitenoise serve static assets
Make Whitenoise serve static assets Currently it’s not configured properly, so isn’t having any effect. This change makes it wrap the Flask app, so it intercepts any requests for static content. Follows the pattern documented in http://whitenoise.evans.io/en/stable/flask.html#enable-whitenoise
Python
mit
alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin
import os from flask import Flask from whitenoise import WhiteNoise from app import create_app PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'app', 'static') STATIC_URL = 'static/' app = Flask('app') create_app(app) - application = WhiteNoise(app, STATIC_ROOT, STATIC_URL) + app.wsgi_app = WhiteNoise(app.wsgi_app, STATIC_ROOT, STATIC_URL)
Make Whitenoise serve static assets
## Code Before: import os from flask import Flask from whitenoise import WhiteNoise from app import create_app PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'app', 'static') STATIC_URL = 'static/' app = Flask('app') create_app(app) application = WhiteNoise(app, STATIC_ROOT, STATIC_URL) ## Instruction: Make Whitenoise serve static assets ## Code After: import os from flask import Flask from whitenoise import WhiteNoise from app import create_app PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'app', 'static') STATIC_URL = 'static/' app = Flask('app') create_app(app) app.wsgi_app = WhiteNoise(app.wsgi_app, STATIC_ROOT, STATIC_URL)
... create_app(app) app.wsgi_app = WhiteNoise(app.wsgi_app, STATIC_ROOT, STATIC_URL) ...
49570c1b7dd5c62495a01db07fe070c34db18383
tests/test_BaseDataSet_uri_property.py
tests/test_BaseDataSet_uri_property.py
import os from . import tmp_dir_fixture # NOQA def test_uri_property(tmp_dir_fixture): # NOQA from dtoolcore import _BaseDataSet admin_metadata = { "name": os.path.basename(tmp_dir_fixture), "uuid": "1234", } base_ds = _BaseDataSet(tmp_dir_fixture, admin_metadata, None) expected_uri = "file://localhost{}".format(tmp_dir_fixture) assert base_ds.uri == expected_uri
import os from . import tmp_uri_fixture # NOQA def test_uri_property(tmp_uri_fixture): # NOQA from dtoolcore import _BaseDataSet admin_metadata = { "name": os.path.basename(tmp_uri_fixture), "uuid": "1234", } base_ds = _BaseDataSet(tmp_uri_fixture, admin_metadata, None) assert base_ds.uri == tmp_uri_fixture
Fix windows issue with test_uri_property
Fix windows issue with test_uri_property
Python
mit
JIC-CSB/dtoolcore
import os - from . import tmp_dir_fixture # NOQA + from . import tmp_uri_fixture # NOQA - def test_uri_property(tmp_dir_fixture): # NOQA + def test_uri_property(tmp_uri_fixture): # NOQA from dtoolcore import _BaseDataSet admin_metadata = { - "name": os.path.basename(tmp_dir_fixture), + "name": os.path.basename(tmp_uri_fixture), "uuid": "1234", } - base_ds = _BaseDataSet(tmp_dir_fixture, admin_metadata, None) + base_ds = _BaseDataSet(tmp_uri_fixture, admin_metadata, None) - expected_uri = "file://localhost{}".format(tmp_dir_fixture) - assert base_ds.uri == expected_uri + assert base_ds.uri == tmp_uri_fixture
Fix windows issue with test_uri_property
## Code Before: import os from . import tmp_dir_fixture # NOQA def test_uri_property(tmp_dir_fixture): # NOQA from dtoolcore import _BaseDataSet admin_metadata = { "name": os.path.basename(tmp_dir_fixture), "uuid": "1234", } base_ds = _BaseDataSet(tmp_dir_fixture, admin_metadata, None) expected_uri = "file://localhost{}".format(tmp_dir_fixture) assert base_ds.uri == expected_uri ## Instruction: Fix windows issue with test_uri_property ## Code After: import os from . import tmp_uri_fixture # NOQA def test_uri_property(tmp_uri_fixture): # NOQA from dtoolcore import _BaseDataSet admin_metadata = { "name": os.path.basename(tmp_uri_fixture), "uuid": "1234", } base_ds = _BaseDataSet(tmp_uri_fixture, admin_metadata, None) assert base_ds.uri == tmp_uri_fixture
// ... existing code ... from . import tmp_uri_fixture # NOQA // ... modified code ... def test_uri_property(tmp_uri_fixture): # NOQA ... admin_metadata = { "name": os.path.basename(tmp_uri_fixture), "uuid": "1234", ... } base_ds = _BaseDataSet(tmp_uri_fixture, admin_metadata, None) assert base_ds.uri == tmp_uri_fixture // ... rest of the code ...
b9cf2145097f8d1c702183a09bf2d54f669e2218
skimage/filter/__init__.py
skimage/filter/__init__.py
from .lpi_filter import inverse, wiener, LPIFilter2D from .ctmf import median_filter from ._canny import canny from .edges import (sobel, hsobel, vsobel, scharr, hscharr, vscharr, prewitt, hprewitt, vprewitt, roberts , roberts_positive_diagonal, roberts_negative_diagonal) from ._denoise import denoise_tv_chambolle, tv_denoise from ._denoise_cy import denoise_bilateral, denoise_tv_bregman from ._rank_order import rank_order from ._gabor import gabor_kernel, gabor_filter from .thresholding import threshold_otsu, threshold_adaptive __all__ = ['inverse', 'wiener', 'LPIFilter2D', 'median_filter', 'canny', 'sobel', 'hsobel', 'vsobel', 'scharr', 'hscharr', 'vscharr', 'prewitt', 'hprewitt', 'vprewitt', 'roberts', 'roberts_positive_diagonal', 'roberts_negative_diagonal', 'denoise_tv_chambolle', 'tv_denoise', 'denoise_bilateral', 'denoise_tv_bregman', 'rank_order', 'gabor_kernel', 'gabor_filter', 'threshold_otsu', 'threshold_adaptive']
from .lpi_filter import inverse, wiener, LPIFilter2D from .ctmf import median_filter from ._canny import canny from .edges import (sobel, hsobel, vsobel, scharr, hscharr, vscharr, prewitt, hprewitt, vprewitt, roberts , roberts_positive_diagonal, roberts_negative_diagonal) from ._denoise import denoise_tv_chambolle, tv_denoise from ._denoise_cy import denoise_bilateral, denoise_tv_bregman from ._rank_order import rank_order from ._gabor import gabor_kernel, gabor_filter from .thresholding import threshold_otsu, threshold_adaptive from . import rank __all__ = ['inverse', 'wiener', 'LPIFilter2D', 'median_filter', 'canny', 'sobel', 'hsobel', 'vsobel', 'scharr', 'hscharr', 'vscharr', 'prewitt', 'hprewitt', 'vprewitt', 'roberts', 'roberts_positive_diagonal', 'roberts_negative_diagonal', 'denoise_tv_chambolle', 'tv_denoise', 'denoise_bilateral', 'denoise_tv_bregman', 'rank_order', 'gabor_kernel', 'gabor_filter', 'threshold_otsu', 'threshold_adaptive', 'rank']
Add filter.rank to __all__ of filter package
Add filter.rank to __all__ of filter package
Python
bsd-3-clause
michaelpacer/scikit-image,oew1v07/scikit-image,vighneshbirodkar/scikit-image,michaelpacer/scikit-image,chriscrosscutler/scikit-image,juliusbierk/scikit-image,chintak/scikit-image,GaZ3ll3/scikit-image,warmspringwinds/scikit-image,ajaybhat/scikit-image,robintw/scikit-image,keflavich/scikit-image,chintak/scikit-image,jwiggins/scikit-image,rjeli/scikit-image,Britefury/scikit-image,bennlich/scikit-image,ofgulban/scikit-image,dpshelio/scikit-image,dpshelio/scikit-image,almarklein/scikit-image,keflavich/scikit-image,Midafi/scikit-image,pratapvardhan/scikit-image,emon10005/scikit-image,juliusbierk/scikit-image,chintak/scikit-image,pratapvardhan/scikit-image,bsipocz/scikit-image,jwiggins/scikit-image,almarklein/scikit-image,youprofit/scikit-image,SamHames/scikit-image,GaZ3ll3/scikit-image,Midafi/scikit-image,oew1v07/scikit-image,bennlich/scikit-image,SamHames/scikit-image,blink1073/scikit-image,warmspringwinds/scikit-image,Hiyorimi/scikit-image,chintak/scikit-image,newville/scikit-image,youprofit/scikit-image,Hiyorimi/scikit-image,SamHames/scikit-image,blink1073/scikit-image,rjeli/scikit-image,newville/scikit-image,paalge/scikit-image,paalge/scikit-image,almarklein/scikit-image,bsipocz/scikit-image,paalge/scikit-image,emon10005/scikit-image,ofgulban/scikit-image,michaelaye/scikit-image,ajaybhat/scikit-image,WarrenWeckesser/scikits-image,ClinicalGraphics/scikit-image,michaelaye/scikit-image,Britefury/scikit-image,vighneshbirodkar/scikit-image,SamHames/scikit-image,robintw/scikit-image,ClinicalGraphics/scikit-image,vighneshbirodkar/scikit-image,rjeli/scikit-image,almarklein/scikit-image,ofgulban/scikit-image,WarrenWeckesser/scikits-image,chriscrosscutler/scikit-image
from .lpi_filter import inverse, wiener, LPIFilter2D from .ctmf import median_filter from ._canny import canny from .edges import (sobel, hsobel, vsobel, scharr, hscharr, vscharr, prewitt, hprewitt, vprewitt, roberts , roberts_positive_diagonal, roberts_negative_diagonal) from ._denoise import denoise_tv_chambolle, tv_denoise from ._denoise_cy import denoise_bilateral, denoise_tv_bregman from ._rank_order import rank_order from ._gabor import gabor_kernel, gabor_filter from .thresholding import threshold_otsu, threshold_adaptive + from . import rank __all__ = ['inverse', 'wiener', 'LPIFilter2D', 'median_filter', 'canny', 'sobel', 'hsobel', 'vsobel', 'scharr', 'hscharr', 'vscharr', 'prewitt', 'hprewitt', 'vprewitt', 'roberts', 'roberts_positive_diagonal', 'roberts_negative_diagonal', 'denoise_tv_chambolle', 'tv_denoise', 'denoise_bilateral', 'denoise_tv_bregman', 'rank_order', 'gabor_kernel', 'gabor_filter', 'threshold_otsu', - 'threshold_adaptive'] + 'threshold_adaptive', + 'rank']
Add filter.rank to __all__ of filter package
## Code Before: from .lpi_filter import inverse, wiener, LPIFilter2D from .ctmf import median_filter from ._canny import canny from .edges import (sobel, hsobel, vsobel, scharr, hscharr, vscharr, prewitt, hprewitt, vprewitt, roberts , roberts_positive_diagonal, roberts_negative_diagonal) from ._denoise import denoise_tv_chambolle, tv_denoise from ._denoise_cy import denoise_bilateral, denoise_tv_bregman from ._rank_order import rank_order from ._gabor import gabor_kernel, gabor_filter from .thresholding import threshold_otsu, threshold_adaptive __all__ = ['inverse', 'wiener', 'LPIFilter2D', 'median_filter', 'canny', 'sobel', 'hsobel', 'vsobel', 'scharr', 'hscharr', 'vscharr', 'prewitt', 'hprewitt', 'vprewitt', 'roberts', 'roberts_positive_diagonal', 'roberts_negative_diagonal', 'denoise_tv_chambolle', 'tv_denoise', 'denoise_bilateral', 'denoise_tv_bregman', 'rank_order', 'gabor_kernel', 'gabor_filter', 'threshold_otsu', 'threshold_adaptive'] ## Instruction: Add filter.rank to __all__ of filter package ## Code After: from .lpi_filter import inverse, wiener, LPIFilter2D from .ctmf import median_filter from ._canny import canny from .edges import (sobel, hsobel, vsobel, scharr, hscharr, vscharr, prewitt, hprewitt, vprewitt, roberts , roberts_positive_diagonal, roberts_negative_diagonal) from ._denoise import denoise_tv_chambolle, tv_denoise from ._denoise_cy import denoise_bilateral, denoise_tv_bregman from ._rank_order import rank_order from ._gabor import gabor_kernel, gabor_filter from .thresholding import threshold_otsu, threshold_adaptive from . import rank __all__ = ['inverse', 'wiener', 'LPIFilter2D', 'median_filter', 'canny', 'sobel', 'hsobel', 'vsobel', 'scharr', 'hscharr', 'vscharr', 'prewitt', 'hprewitt', 'vprewitt', 'roberts', 'roberts_positive_diagonal', 'roberts_negative_diagonal', 'denoise_tv_chambolle', 'tv_denoise', 'denoise_bilateral', 'denoise_tv_bregman', 'rank_order', 'gabor_kernel', 'gabor_filter', 'threshold_otsu', 'threshold_adaptive', 'rank']
# ... existing code ... from .thresholding import threshold_otsu, threshold_adaptive from . import rank # ... modified code ... 'threshold_otsu', 'threshold_adaptive', 'rank'] # ... rest of the code ...
8774517714c8c8a7f7a2be9316a23497adfa9f59
pi_gpio/urls.py
pi_gpio/urls.py
from pi_gpio import app, socketio from flask.ext import restful from flask import render_template from handlers import PinList, PinDetail api = restful.Api(app) api.add_resource(PinList, '/api/v1/pin') api.add_resource(PinDetail, '/api/v1/pin/<string:pin_num>') import RPi.GPIO as GPIO def event_callback(pin): socketio.emit('pin:event', {"message":"woohoo!"}) @app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def index(path): GPIO.add_event_detect(23, GPIO.RISING, callback=event_callback) return render_template('index.html')
from pi_gpio import app, socketio from flask.ext import restful from flask import render_template from handlers import PinList, PinDetail from events import PinEventManager api = restful.Api(app) api.add_resource(PinList, '/api/v1/pin') api.add_resource(PinDetail, '/api/v1/pin/<string:pin_num>') @app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def index(path): PinEventManager() return render_template('index.html')
Call event manager in index route
Call event manager in index route
Python
mit
projectweekend/Pi-GPIO-Server,projectweekend/Pi-GPIO-Server,thijstriemstra/Pi-GPIO-Server,thijstriemstra/Pi-GPIO-Server,projectweekend/Pi-GPIO-Server,thijstriemstra/Pi-GPIO-Server,thijstriemstra/Pi-GPIO-Server,projectweekend/Pi-GPIO-Server
from pi_gpio import app, socketio from flask.ext import restful from flask import render_template from handlers import PinList, PinDetail + from events import PinEventManager api = restful.Api(app) api.add_resource(PinList, '/api/v1/pin') api.add_resource(PinDetail, '/api/v1/pin/<string:pin_num>') - import RPi.GPIO as GPIO - - - def event_callback(pin): - socketio.emit('pin:event', {"message":"woohoo!"}) - @app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def index(path): - GPIO.add_event_detect(23, GPIO.RISING, callback=event_callback) + PinEventManager() return render_template('index.html')
Call event manager in index route
## Code Before: from pi_gpio import app, socketio from flask.ext import restful from flask import render_template from handlers import PinList, PinDetail api = restful.Api(app) api.add_resource(PinList, '/api/v1/pin') api.add_resource(PinDetail, '/api/v1/pin/<string:pin_num>') import RPi.GPIO as GPIO def event_callback(pin): socketio.emit('pin:event', {"message":"woohoo!"}) @app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def index(path): GPIO.add_event_detect(23, GPIO.RISING, callback=event_callback) return render_template('index.html') ## Instruction: Call event manager in index route ## Code After: from pi_gpio import app, socketio from flask.ext import restful from flask import render_template from handlers import PinList, PinDetail from events import PinEventManager api = restful.Api(app) api.add_resource(PinList, '/api/v1/pin') api.add_resource(PinDetail, '/api/v1/pin/<string:pin_num>') @app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def index(path): PinEventManager() return render_template('index.html')
# ... existing code ... from handlers import PinList, PinDetail from events import PinEventManager # ... modified code ... ... def index(path): PinEventManager() return render_template('index.html') # ... rest of the code ...
b3702552ab83b7910b7972512253a829bbc56488
osgtest/tests/test_838_xrootd_tpc.py
osgtest/tests/test_838_xrootd_tpc.py
import osgtest.library.core as core import osgtest.library.files as files import osgtest.library.service as service import osgtest.library.osgunittest as osgunittest class TestStopXrootdTPC(osgunittest.OSGTestCase): @core.elrelease(7,8) def test_01_stop_xrootd(self): if core.state['xrootd.tpc.backups-exist']: files.restore(core.config['xrootd.tpc.config-1'], "xrootd") files.restore(core.config['xrootd.tpc.config-2'], "xrootd") core.skip_ok_unless_installed('xrootd', 'xrootd-scitokens', by_dependency=True) self.skip_ok_if(not core.state['xrootd.started-http-server-1'] and not core.state['xrootd.started-http-server-2'], 'did not start any of the http servers') service.check_stop(core.config['xrootd_tpc_service_1']) service.check_stop(core.config['xrootd_tpc_service_2']) def test_02_clean_test_files(self): files.remove("/tmp/test_gridftp_data_tpc.txt", force=True)
import osgtest.library.core as core import osgtest.library.files as files import osgtest.library.service as service import osgtest.library.osgunittest as osgunittest class TestStopXrootdTPC(osgunittest.OSGTestCase): @core.elrelease(7,8) def setUp(self): core.skip_ok_unless_installed("xrootd", by_dependency=True) def test_01_stop_xrootd(self): if core.state['xrootd.tpc.backups-exist']: files.restore(core.config['xrootd.tpc.config-1'], "xrootd") files.restore(core.config['xrootd.tpc.config-2'], "xrootd") core.skip_ok_unless_installed('xrootd-scitokens', by_dependency=True) self.skip_ok_if(not core.state['xrootd.started-http-server-1'] and not core.state['xrootd.started-http-server-2'], 'did not start any of the http servers') service.check_stop(core.config['xrootd_tpc_service_1']) service.check_stop(core.config['xrootd_tpc_service_2']) def test_02_clean_test_files(self): files.remove("/tmp/test_gridftp_data_tpc.txt", force=True)
Add xrootd and non-el6 check for xrootd-tpc cleanup too
Add xrootd and non-el6 check for xrootd-tpc cleanup too
Python
apache-2.0
efajardo/osg-test,efajardo/osg-test
import osgtest.library.core as core import osgtest.library.files as files import osgtest.library.service as service import osgtest.library.osgunittest as osgunittest class TestStopXrootdTPC(osgunittest.OSGTestCase): @core.elrelease(7,8) + def setUp(self): + core.skip_ok_unless_installed("xrootd", + by_dependency=True) + def test_01_stop_xrootd(self): if core.state['xrootd.tpc.backups-exist']: files.restore(core.config['xrootd.tpc.config-1'], "xrootd") files.restore(core.config['xrootd.tpc.config-2'], "xrootd") - core.skip_ok_unless_installed('xrootd', 'xrootd-scitokens', by_dependency=True) + core.skip_ok_unless_installed('xrootd-scitokens', by_dependency=True) self.skip_ok_if(not core.state['xrootd.started-http-server-1'] and not core.state['xrootd.started-http-server-2'], 'did not start any of the http servers') service.check_stop(core.config['xrootd_tpc_service_1']) service.check_stop(core.config['xrootd_tpc_service_2']) def test_02_clean_test_files(self): files.remove("/tmp/test_gridftp_data_tpc.txt", force=True)
Add xrootd and non-el6 check for xrootd-tpc cleanup too
## Code Before: import osgtest.library.core as core import osgtest.library.files as files import osgtest.library.service as service import osgtest.library.osgunittest as osgunittest class TestStopXrootdTPC(osgunittest.OSGTestCase): @core.elrelease(7,8) def test_01_stop_xrootd(self): if core.state['xrootd.tpc.backups-exist']: files.restore(core.config['xrootd.tpc.config-1'], "xrootd") files.restore(core.config['xrootd.tpc.config-2'], "xrootd") core.skip_ok_unless_installed('xrootd', 'xrootd-scitokens', by_dependency=True) self.skip_ok_if(not core.state['xrootd.started-http-server-1'] and not core.state['xrootd.started-http-server-2'], 'did not start any of the http servers') service.check_stop(core.config['xrootd_tpc_service_1']) service.check_stop(core.config['xrootd_tpc_service_2']) def test_02_clean_test_files(self): files.remove("/tmp/test_gridftp_data_tpc.txt", force=True) ## Instruction: Add xrootd and non-el6 check for xrootd-tpc cleanup too ## Code After: import osgtest.library.core as core import osgtest.library.files as files import osgtest.library.service as service import osgtest.library.osgunittest as osgunittest class TestStopXrootdTPC(osgunittest.OSGTestCase): @core.elrelease(7,8) def setUp(self): core.skip_ok_unless_installed("xrootd", by_dependency=True) def test_01_stop_xrootd(self): if core.state['xrootd.tpc.backups-exist']: files.restore(core.config['xrootd.tpc.config-1'], "xrootd") files.restore(core.config['xrootd.tpc.config-2'], "xrootd") core.skip_ok_unless_installed('xrootd-scitokens', by_dependency=True) self.skip_ok_if(not core.state['xrootd.started-http-server-1'] and not core.state['xrootd.started-http-server-2'], 'did not start any of the http servers') service.check_stop(core.config['xrootd_tpc_service_1']) service.check_stop(core.config['xrootd_tpc_service_2']) def test_02_clean_test_files(self): files.remove("/tmp/test_gridftp_data_tpc.txt", force=True)
# ... existing code ... @core.elrelease(7,8) def setUp(self): core.skip_ok_unless_installed("xrootd", by_dependency=True) def test_01_stop_xrootd(self): # ... modified code ... core.skip_ok_unless_installed('xrootd-scitokens', by_dependency=True) self.skip_ok_if(not core.state['xrootd.started-http-server-1'] and # ... rest of the code ...
95ea1d7d6564bcbb2e3b8d2ba254ccd2c1c38436
mamba/__init__.py
mamba/__init__.py
__version__ = '0.9.2' def description(message): pass def _description(message): pass def it(message): pass def _it(message): pass def context(message): pass def _context(message): pass def before(): pass def after(): pass
__version__ = '0.9.2' def description(message): pass def _description(message): pass def fdescription(message): pass def it(message): pass def _it(message): pass def fit(message): pass def context(message): pass def _context(message): pass def fcontext(message): pass def before(): pass def after(): pass
Add import for focused stuff
Add import for focused stuff
Python
mit
nestorsalceda/mamba
__version__ = '0.9.2' def description(message): pass def _description(message): pass + def fdescription(message): + pass + + def it(message): pass def _it(message): + pass + + + def fit(message): pass def context(message): pass def _context(message): pass + def fcontext(message): + pass + + def before(): pass def after(): pass
Add import for focused stuff
## Code Before: __version__ = '0.9.2' def description(message): pass def _description(message): pass def it(message): pass def _it(message): pass def context(message): pass def _context(message): pass def before(): pass def after(): pass ## Instruction: Add import for focused stuff ## Code After: __version__ = '0.9.2' def description(message): pass def _description(message): pass def fdescription(message): pass def it(message): pass def _it(message): pass def fit(message): pass def context(message): pass def _context(message): pass def fcontext(message): pass def before(): pass def after(): pass
... def fdescription(message): pass def it(message): ... def _it(message): pass def fit(message): pass ... def fcontext(message): pass def before(): ...
ceee44182b24ecdc0563a9e9a6841993d1978d0c
setup.py
setup.py
from distutils.core import setup setup( name='aJohnShots', version="1.0.0", description='Python module/library for saving Security Hash Algorithms into JSON format.', author='funilrys', author_email='[email protected]', license='GPL-3.0 https://opensource.org/licenses/GPL-3.0', url='https://github.com/funilrys/A-John-Shots', platforms=['any'], packages=['a_john_shots'], keywords=['Python', 'JSON', 'SHA 1', 'SHA-512', 'SHA-224', 'SHA-384', 'SHA'], classifiers=[ 'Environment :: Console', 'Topic :: Software Development', 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)' ], ) ''' test_suite='testsuite', entry_points=""" [console_scripts] cmd = package:main """, '''
from distutils.core import setup setup( name='a_john_shots', version="1.0.0", description='Python module/library for saving Security Hash Algorithms into JSON format.', long_description=open('README').read(), author='funilrys', author_email='[email protected]', license='GPL-3.0 https://opensource.org/licenses/GPL-3.0', url='https://github.com/funilrys/A-John-Shots', platforms=['any'], packages=['a_john_shots'], keywords=['Python', 'JSON', 'SHA-1', 'SHA-512', 'SHA-224', 'SHA-384', 'SHA', 'MD5'], classifiers=[ 'Environment :: Console', 'Topic :: Software Development', 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)' ], ) ''' test_suite='testsuite', entry_points=""" [console_scripts] cmd = package:main """, '''
Rename + add long_description + update keywords
Rename + add long_description + update keywords
Python
mit
funilrys/A-John-Shots
from distutils.core import setup setup( - name='aJohnShots', + name='a_john_shots', version="1.0.0", description='Python module/library for saving Security Hash Algorithms into JSON format.', + long_description=open('README').read(), author='funilrys', author_email='[email protected]', license='GPL-3.0 https://opensource.org/licenses/GPL-3.0', url='https://github.com/funilrys/A-John-Shots', platforms=['any'], packages=['a_john_shots'], - keywords=['Python', 'JSON', 'SHA 1', + keywords=['Python', 'JSON', 'SHA-1', - 'SHA-512', 'SHA-224', 'SHA-384', 'SHA'], + 'SHA-512', 'SHA-224', 'SHA-384', 'SHA', 'MD5'], classifiers=[ 'Environment :: Console', 'Topic :: Software Development', 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)' ], ) ''' test_suite='testsuite', entry_points=""" [console_scripts] cmd = package:main """, '''
Rename + add long_description + update keywords
## Code Before: from distutils.core import setup setup( name='aJohnShots', version="1.0.0", description='Python module/library for saving Security Hash Algorithms into JSON format.', author='funilrys', author_email='[email protected]', license='GPL-3.0 https://opensource.org/licenses/GPL-3.0', url='https://github.com/funilrys/A-John-Shots', platforms=['any'], packages=['a_john_shots'], keywords=['Python', 'JSON', 'SHA 1', 'SHA-512', 'SHA-224', 'SHA-384', 'SHA'], classifiers=[ 'Environment :: Console', 'Topic :: Software Development', 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)' ], ) ''' test_suite='testsuite', entry_points=""" [console_scripts] cmd = package:main """, ''' ## Instruction: Rename + add long_description + update keywords ## Code After: from distutils.core import setup setup( name='a_john_shots', version="1.0.0", description='Python module/library for saving Security Hash Algorithms into JSON format.', long_description=open('README').read(), author='funilrys', author_email='[email protected]', license='GPL-3.0 https://opensource.org/licenses/GPL-3.0', url='https://github.com/funilrys/A-John-Shots', platforms=['any'], packages=['a_john_shots'], keywords=['Python', 'JSON', 'SHA-1', 'SHA-512', 'SHA-224', 'SHA-384', 'SHA', 'MD5'], classifiers=[ 'Environment :: Console', 'Topic :: Software Development', 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)' ], ) ''' test_suite='testsuite', entry_points=""" [console_scripts] cmd = package:main """, '''
// ... existing code ... setup( name='a_john_shots', version="1.0.0", // ... modified code ... description='Python module/library for saving Security Hash Algorithms into JSON format.', long_description=open('README').read(), author='funilrys', ... packages=['a_john_shots'], keywords=['Python', 'JSON', 'SHA-1', 'SHA-512', 'SHA-224', 'SHA-384', 'SHA', 'MD5'], classifiers=[ // ... rest of the code ...
d0fe2fd4bc619a45d18c3e5ba911b15045366849
api/tests/test_small_scripts.py
api/tests/test_small_scripts.py
"""This module tests the small scripts - admin, model, and wsgi.""" import unittest class SmallScriptsTest(unittest.TestCase): def test_admin(self): import api.admin def test_models(self): import api.models def test_wsgi(self): import apel_rest.wsgi
"""This module tests the small scripts - admin, model, and wsgi.""" # Using unittest and not django.test as no need for overhead of database import unittest class SmallScriptsTest(unittest.TestCase): def test_admin(self): """Check that admin is importable.""" import api.admin def test_models(self): """Check that models is importable.""" import api.models def test_wsgi(self): """Check that wsgi is importable.""" import apel_rest.wsgi
Add docstrings and comment to small scripts test
Add docstrings and comment to small scripts test
Python
apache-2.0
apel/rest,apel/rest
"""This module tests the small scripts - admin, model, and wsgi.""" + # Using unittest and not django.test as no need for overhead of database import unittest class SmallScriptsTest(unittest.TestCase): def test_admin(self): + """Check that admin is importable.""" import api.admin def test_models(self): + """Check that models is importable.""" import api.models def test_wsgi(self): + """Check that wsgi is importable.""" import apel_rest.wsgi
Add docstrings and comment to small scripts test
## Code Before: """This module tests the small scripts - admin, model, and wsgi.""" import unittest class SmallScriptsTest(unittest.TestCase): def test_admin(self): import api.admin def test_models(self): import api.models def test_wsgi(self): import apel_rest.wsgi ## Instruction: Add docstrings and comment to small scripts test ## Code After: """This module tests the small scripts - admin, model, and wsgi.""" # Using unittest and not django.test as no need for overhead of database import unittest class SmallScriptsTest(unittest.TestCase): def test_admin(self): """Check that admin is importable.""" import api.admin def test_models(self): """Check that models is importable.""" import api.models def test_wsgi(self): """Check that wsgi is importable.""" import apel_rest.wsgi
# ... existing code ... # Using unittest and not django.test as no need for overhead of database import unittest # ... modified code ... def test_admin(self): """Check that admin is importable.""" import api.admin ... def test_models(self): """Check that models is importable.""" import api.models ... def test_wsgi(self): """Check that wsgi is importable.""" import apel_rest.wsgi # ... rest of the code ...