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
329e74f280537aab41d5b810f8650bfd8d6d81f5
tests/test_generate_files.py
tests/test_generate_files.py
import pytest from cookiecutter import generate from cookiecutter import exceptions @pytest.mark.usefixtures("clean_system") def test_generate_files_nontemplated_exception(): with pytest.raises(exceptions.NonTemplatedInputDirException): generate.generate_files( context={'cookiecutter': {'food': 'pizza'}}, repo_dir='tests/test-generate-files-nontemplated' )
from __future__ import unicode_literals import os import pytest from cookiecutter import generate from cookiecutter import exceptions from cookiecutter import utils @pytest.fixture(scope="function") def clean_system_remove_additional_folders(request, clean_system): def remove_additional_folders(): if os.path.exists('inputpizzä'): utils.rmtree('inputpizzä') if os.path.exists('inputgreen'): utils.rmtree('inputgreen') if os.path.exists('inputbinary_files'): utils.rmtree('inputbinary_files') if os.path.exists('tests/custom_output_dir'): utils.rmtree('tests/custom_output_dir') if os.path.exists('inputpermissions'): utils.rmtree('inputpermissions') request.addfinalizer(remove_additional_folders) @pytest.mark.usefixtures("clean_system_remove_additional_folders") def test_generate_files_nontemplated_exception(): with pytest.raises(exceptions.NonTemplatedInputDirException): generate.generate_files( context={'cookiecutter': {'food': 'pizza'}}, repo_dir='tests/test-generate-files-nontemplated' )
Add teardown specific to the former TestCase class
Add teardown specific to the former TestCase class
Python
bsd-3-clause
michaeljoseph/cookiecutter,christabor/cookiecutter,cguardia/cookiecutter,janusnic/cookiecutter,michaeljoseph/cookiecutter,cguardia/cookiecutter,vincentbernat/cookiecutter,drgarcia1986/cookiecutter,Vauxoo/cookiecutter,cichm/cookiecutter,benthomasson/cookiecutter,0k/cookiecutter,terryjbates/cookiecutter,atlassian/cookiecutter,lucius-feng/cookiecutter,Springerle/cookiecutter,hackebrot/cookiecutter,moi65/cookiecutter,0k/cookiecutter,willingc/cookiecutter,venumech/cookiecutter,jhermann/cookiecutter,ramiroluz/cookiecutter,kkujawinski/cookiecutter,agconti/cookiecutter,sp1rs/cookiecutter,lgp171188/cookiecutter,kkujawinski/cookiecutter,jhermann/cookiecutter,venumech/cookiecutter,sp1rs/cookiecutter,luzfcb/cookiecutter,janusnic/cookiecutter,vintasoftware/cookiecutter,atlassian/cookiecutter,stevepiercy/cookiecutter,pjbull/cookiecutter,ionelmc/cookiecutter,takeflight/cookiecutter,letolab/cookiecutter,letolab/cookiecutter,pjbull/cookiecutter,hackebrot/cookiecutter,luzfcb/cookiecutter,audreyr/cookiecutter,takeflight/cookiecutter,lgp171188/cookiecutter,agconti/cookiecutter,vintasoftware/cookiecutter,Springerle/cookiecutter,cichm/cookiecutter,ionelmc/cookiecutter,benthomasson/cookiecutter,lucius-feng/cookiecutter,audreyr/cookiecutter,terryjbates/cookiecutter,foodszhang/cookiecutter,foodszhang/cookiecutter,vincentbernat/cookiecutter,ramiroluz/cookiecutter,tylerdave/cookiecutter,tylerdave/cookiecutter,nhomar/cookiecutter,dajose/cookiecutter,stevepiercy/cookiecutter,nhomar/cookiecutter,willingc/cookiecutter,Vauxoo/cookiecutter,drgarcia1986/cookiecutter,moi65/cookiecutter,christabor/cookiecutter,dajose/cookiecutter
+ from __future__ import unicode_literals + import os import pytest + from cookiecutter import generate from cookiecutter import exceptions + from cookiecutter import utils + @pytest.fixture(scope="function") + def clean_system_remove_additional_folders(request, clean_system): + def remove_additional_folders(): + if os.path.exists('inputpizzä'): + utils.rmtree('inputpizzä') + if os.path.exists('inputgreen'): + utils.rmtree('inputgreen') + if os.path.exists('inputbinary_files'): + utils.rmtree('inputbinary_files') + if os.path.exists('tests/custom_output_dir'): + utils.rmtree('tests/custom_output_dir') + if os.path.exists('inputpermissions'): + utils.rmtree('inputpermissions') + request.addfinalizer(remove_additional_folders) + + - @pytest.mark.usefixtures("clean_system") + @pytest.mark.usefixtures("clean_system_remove_additional_folders") def test_generate_files_nontemplated_exception(): with pytest.raises(exceptions.NonTemplatedInputDirException): generate.generate_files( context={'cookiecutter': {'food': 'pizza'}}, repo_dir='tests/test-generate-files-nontemplated' )
Add teardown specific to the former TestCase class
## Code Before: import pytest from cookiecutter import generate from cookiecutter import exceptions @pytest.mark.usefixtures("clean_system") def test_generate_files_nontemplated_exception(): with pytest.raises(exceptions.NonTemplatedInputDirException): generate.generate_files( context={'cookiecutter': {'food': 'pizza'}}, repo_dir='tests/test-generate-files-nontemplated' ) ## Instruction: Add teardown specific to the former TestCase class ## Code After: from __future__ import unicode_literals import os import pytest from cookiecutter import generate from cookiecutter import exceptions from cookiecutter import utils @pytest.fixture(scope="function") def clean_system_remove_additional_folders(request, clean_system): def remove_additional_folders(): if os.path.exists('inputpizzä'): utils.rmtree('inputpizzä') if os.path.exists('inputgreen'): utils.rmtree('inputgreen') if os.path.exists('inputbinary_files'): utils.rmtree('inputbinary_files') if os.path.exists('tests/custom_output_dir'): utils.rmtree('tests/custom_output_dir') if os.path.exists('inputpermissions'): utils.rmtree('inputpermissions') request.addfinalizer(remove_additional_folders) @pytest.mark.usefixtures("clean_system_remove_additional_folders") def test_generate_files_nontemplated_exception(): with pytest.raises(exceptions.NonTemplatedInputDirException): generate.generate_files( context={'cookiecutter': {'food': 'pizza'}}, repo_dir='tests/test-generate-files-nontemplated' )
# ... existing code ... from __future__ import unicode_literals import os import pytest from cookiecutter import generate # ... modified code ... from cookiecutter import exceptions from cookiecutter import utils ... @pytest.fixture(scope="function") def clean_system_remove_additional_folders(request, clean_system): def remove_additional_folders(): if os.path.exists('inputpizzä'): utils.rmtree('inputpizzä') if os.path.exists('inputgreen'): utils.rmtree('inputgreen') if os.path.exists('inputbinary_files'): utils.rmtree('inputbinary_files') if os.path.exists('tests/custom_output_dir'): utils.rmtree('tests/custom_output_dir') if os.path.exists('inputpermissions'): utils.rmtree('inputpermissions') request.addfinalizer(remove_additional_folders) @pytest.mark.usefixtures("clean_system_remove_additional_folders") def test_generate_files_nontemplated_exception(): # ... rest of the code ...
3ee00fad1965dae23f83da870d7df1cb37727c7a
structlog/migrations/0001_initial.py
structlog/migrations/0001_initial.py
from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ ]
from __future__ import unicode_literals from django.db import migrations from django.contrib.postgres.operations import HStoreExtension class Migration(migrations.Migration): dependencies = [ ] operations = [ HStoreExtension(), ]
Add HStore extension to initial migration.
Add HStore extension to initial migration.
Python
bsd-2-clause
carlohamalainen/django-struct-log
from __future__ import unicode_literals from django.db import migrations - + from django.contrib.postgres.operations import HStoreExtension class Migration(migrations.Migration): dependencies = [ ] operations = [ + HStoreExtension(), ]
Add HStore extension to initial migration.
## Code Before: from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ ] ## Instruction: Add HStore extension to initial migration. ## Code After: from __future__ import unicode_literals from django.db import migrations from django.contrib.postgres.operations import HStoreExtension class Migration(migrations.Migration): dependencies = [ ] operations = [ HStoreExtension(), ]
// ... existing code ... from django.db import migrations from django.contrib.postgres.operations import HStoreExtension // ... modified code ... operations = [ HStoreExtension(), ] // ... rest of the code ...
b4b905333f8847be730f30fbc53ac7a172195cdc
src/sentry/api/endpoints/group_events.py
src/sentry/api/endpoints/group_events.py
from __future__ import absolute_import from sentry.api.base import DocSection from sentry.api.bases import GroupEndpoint from sentry.api.serializers import serialize from sentry.api.paginator import DateTimePaginator from sentry.models import Event, Group from sentry.utils.apidocs import scenario, attach_scenarios @scenario('ListAvailableSamples') def list_available_samples_scenario(runner): group = Group.objects.filter(project=runner.default_project).first() runner.request( method='GET', path='/issues/%s/events/' % group.id ) class GroupEventsEndpoint(GroupEndpoint): doc_section = DocSection.EVENTS @attach_scenarios([list_available_samples_scenario]) def get(self, request, group): """ List an Issue's Events `````````````````````` This endpoint lists an issue's events. :pparam string issue_id: the ID of the issue to retrieve. :auth: required """ events = Event.objects.filter( group=group ) return self.paginate( request=request, queryset=events, order_by='-datetime', on_results=lambda x: serialize(x, request.user), paginator_cls=DateTimePaginator, )
from __future__ import absolute_import from sentry.api.base import DocSection from sentry.api.bases import GroupEndpoint from sentry.api.serializers import serialize from sentry.api.paginator import DateTimePaginator from sentry.models import Event, Group from sentry.utils.apidocs import scenario, attach_scenarios @scenario('ListAvailableSamples') def list_available_samples_scenario(runner): group = Group.objects.filter(project=runner.default_project).first() runner.request( method='GET', path='/issues/%s/events/' % group.id ) class GroupEventsEndpoint(GroupEndpoint): doc_section = DocSection.EVENTS @attach_scenarios([list_available_samples_scenario]) def get(self, request, group): """ List an Issue's Events `````````````````````` This endpoint lists an issue's events. :pparam string issue_id: the ID of the issue to retrieve. :auth: required """ events = Event.objects.filter( group=group ) query = request.GET.get('query') if query: events = events.filter( message__iexact=query, ) return self.paginate( request=request, queryset=events, order_by='-datetime', on_results=lambda x: serialize(x, request.user), paginator_cls=DateTimePaginator, )
Add query param to event list
Add query param to event list
Python
bsd-3-clause
looker/sentry,BuildingLink/sentry,mvaled/sentry,fotinakis/sentry,zenefits/sentry,BuildingLink/sentry,gencer/sentry,gencer/sentry,JamesMura/sentry,zenefits/sentry,alexm92/sentry,ifduyue/sentry,BuildingLink/sentry,JamesMura/sentry,JackDanger/sentry,gencer/sentry,fotinakis/sentry,nicholasserra/sentry,JackDanger/sentry,mvaled/sentry,jean/sentry,mvaled/sentry,beeftornado/sentry,beeftornado/sentry,ifduyue/sentry,nicholasserra/sentry,jean/sentry,daevaorn/sentry,ifduyue/sentry,fotinakis/sentry,mitsuhiko/sentry,zenefits/sentry,looker/sentry,ifduyue/sentry,jean/sentry,alexm92/sentry,looker/sentry,BuildingLink/sentry,jean/sentry,alexm92/sentry,daevaorn/sentry,mitsuhiko/sentry,JamesMura/sentry,daevaorn/sentry,gencer/sentry,nicholasserra/sentry,daevaorn/sentry,ifduyue/sentry,looker/sentry,zenefits/sentry,JackDanger/sentry,mvaled/sentry,looker/sentry,JamesMura/sentry,mvaled/sentry,fotinakis/sentry,beeftornado/sentry,BuildingLink/sentry,gencer/sentry,jean/sentry,mvaled/sentry,JamesMura/sentry,zenefits/sentry
from __future__ import absolute_import from sentry.api.base import DocSection from sentry.api.bases import GroupEndpoint from sentry.api.serializers import serialize from sentry.api.paginator import DateTimePaginator from sentry.models import Event, Group from sentry.utils.apidocs import scenario, attach_scenarios @scenario('ListAvailableSamples') def list_available_samples_scenario(runner): group = Group.objects.filter(project=runner.default_project).first() runner.request( method='GET', path='/issues/%s/events/' % group.id ) class GroupEventsEndpoint(GroupEndpoint): doc_section = DocSection.EVENTS @attach_scenarios([list_available_samples_scenario]) def get(self, request, group): """ List an Issue's Events `````````````````````` This endpoint lists an issue's events. :pparam string issue_id: the ID of the issue to retrieve. :auth: required """ events = Event.objects.filter( group=group ) + query = request.GET.get('query') + if query: + events = events.filter( + message__iexact=query, + ) + return self.paginate( request=request, queryset=events, order_by='-datetime', on_results=lambda x: serialize(x, request.user), paginator_cls=DateTimePaginator, )
Add query param to event list
## Code Before: from __future__ import absolute_import from sentry.api.base import DocSection from sentry.api.bases import GroupEndpoint from sentry.api.serializers import serialize from sentry.api.paginator import DateTimePaginator from sentry.models import Event, Group from sentry.utils.apidocs import scenario, attach_scenarios @scenario('ListAvailableSamples') def list_available_samples_scenario(runner): group = Group.objects.filter(project=runner.default_project).first() runner.request( method='GET', path='/issues/%s/events/' % group.id ) class GroupEventsEndpoint(GroupEndpoint): doc_section = DocSection.EVENTS @attach_scenarios([list_available_samples_scenario]) def get(self, request, group): """ List an Issue's Events `````````````````````` This endpoint lists an issue's events. :pparam string issue_id: the ID of the issue to retrieve. :auth: required """ events = Event.objects.filter( group=group ) return self.paginate( request=request, queryset=events, order_by='-datetime', on_results=lambda x: serialize(x, request.user), paginator_cls=DateTimePaginator, ) ## Instruction: Add query param to event list ## Code After: from __future__ import absolute_import from sentry.api.base import DocSection from sentry.api.bases import GroupEndpoint from sentry.api.serializers import serialize from sentry.api.paginator import DateTimePaginator from sentry.models import Event, Group from sentry.utils.apidocs import scenario, attach_scenarios @scenario('ListAvailableSamples') def list_available_samples_scenario(runner): group = Group.objects.filter(project=runner.default_project).first() runner.request( method='GET', path='/issues/%s/events/' % group.id ) class GroupEventsEndpoint(GroupEndpoint): doc_section = DocSection.EVENTS @attach_scenarios([list_available_samples_scenario]) def get(self, request, group): """ List an Issue's Events `````````````````````` This endpoint lists an issue's events. :pparam string issue_id: the ID of the issue to retrieve. :auth: required """ events = Event.objects.filter( group=group ) query = request.GET.get('query') if query: events = events.filter( message__iexact=query, ) return self.paginate( request=request, queryset=events, order_by='-datetime', on_results=lambda x: serialize(x, request.user), paginator_cls=DateTimePaginator, )
# ... existing code ... query = request.GET.get('query') if query: events = events.filter( message__iexact=query, ) return self.paginate( # ... rest of the code ...
cb7170785af4bf853ff8495aaade520d3b133332
casexml/apps/stock/admin.py
casexml/apps/stock/admin.py
from django.contrib import admin from .models import * class StockReportAdmin(admin.ModelAdmin): model = StockReport list_display = ['date', 'type', 'form_id'] list_filter = ['date', 'type'] class StockTransactionAdmin(admin.ModelAdmin): model = StockTransaction list_display = ['report_date', 'section_id', 'type', 'subtype', 'case_id', 'product_id', 'quantity', 'stock_on_hand'] list_filter = ['report__date', 'section_id', 'type', 'subtype'] def report_date(self, obj): return obj.report.date report_date.admin_order_field = 'report__date' admin.site.register(StockReport, StockReportAdmin) admin.site.register(StockTransaction, StockTransactionAdmin)
from django.contrib import admin from .models import * class StockReportAdmin(admin.ModelAdmin): model = StockReport list_display = ['date', 'type', 'form_id'] list_filter = ['date', 'type'] search_fields = ['form_id'] class StockTransactionAdmin(admin.ModelAdmin): model = StockTransaction list_display = ['report_date', 'section_id', 'type', 'subtype', 'case_id', 'product_id', 'quantity', 'stock_on_hand'] list_filter = ['report__date', 'section_id', 'type', 'subtype'] search_fields = ['case_id', 'product_id'] def report_date(self, obj): return obj.report.date report_date.admin_order_field = 'report__date' admin.site.register(StockReport, StockReportAdmin) admin.site.register(StockTransaction, StockTransactionAdmin)
Add search fields to stock models
Add search fields to stock models
Python
bsd-3-clause
dimagi/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,SEL-Columbia/commcare-hq,SEL-Columbia/commcare-hq,dimagi/commcare-hq,SEL-Columbia/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,puttarajubr/commcare-hq
from django.contrib import admin from .models import * + class StockReportAdmin(admin.ModelAdmin): model = StockReport list_display = ['date', 'type', 'form_id'] list_filter = ['date', 'type'] + search_fields = ['form_id'] + class StockTransactionAdmin(admin.ModelAdmin): model = StockTransaction list_display = ['report_date', 'section_id', 'type', 'subtype', 'case_id', 'product_id', 'quantity', 'stock_on_hand'] list_filter = ['report__date', 'section_id', 'type', 'subtype'] + search_fields = ['case_id', 'product_id'] def report_date(self, obj): return obj.report.date report_date.admin_order_field = 'report__date' admin.site.register(StockReport, StockReportAdmin) admin.site.register(StockTransaction, StockTransactionAdmin)
Add search fields to stock models
## Code Before: from django.contrib import admin from .models import * class StockReportAdmin(admin.ModelAdmin): model = StockReport list_display = ['date', 'type', 'form_id'] list_filter = ['date', 'type'] class StockTransactionAdmin(admin.ModelAdmin): model = StockTransaction list_display = ['report_date', 'section_id', 'type', 'subtype', 'case_id', 'product_id', 'quantity', 'stock_on_hand'] list_filter = ['report__date', 'section_id', 'type', 'subtype'] def report_date(self, obj): return obj.report.date report_date.admin_order_field = 'report__date' admin.site.register(StockReport, StockReportAdmin) admin.site.register(StockTransaction, StockTransactionAdmin) ## Instruction: Add search fields to stock models ## Code After: from django.contrib import admin from .models import * class StockReportAdmin(admin.ModelAdmin): model = StockReport list_display = ['date', 'type', 'form_id'] list_filter = ['date', 'type'] search_fields = ['form_id'] class StockTransactionAdmin(admin.ModelAdmin): model = StockTransaction list_display = ['report_date', 'section_id', 'type', 'subtype', 'case_id', 'product_id', 'quantity', 'stock_on_hand'] list_filter = ['report__date', 'section_id', 'type', 'subtype'] search_fields = ['case_id', 'product_id'] def report_date(self, obj): return obj.report.date report_date.admin_order_field = 'report__date' admin.site.register(StockReport, StockReportAdmin) admin.site.register(StockTransaction, StockTransactionAdmin)
... from .models import * ... list_filter = ['date', 'type'] search_fields = ['form_id'] ... list_filter = ['report__date', 'section_id', 'type', 'subtype'] search_fields = ['case_id', 'product_id'] ...
52584725e462ab304bc2e976fa691f0d830e7efb
Speech/processor.py
Speech/processor.py
import urllib, convert, re, os # from speech_py import speech_to_text_offline as STT_o # from speech_py import speech_to_text_google as STT from speech_py import speech_to_text_ibm_rest as STT def transcribe(audio_url): if not os.path.isdir('./audio/retrieved_audio'): os.makedirs('./audio/retrieved_audio') reg_ex = '\w+.mp4' file_name = re.search(reg_ex, audio_url).group(0) urllib.urlretrieve(audio_url, './audio/retrieved_audio/{}'.format(file_name)) convert.convert('./audio/retrieved_audio/{}'.format(file_name)) # Converted in: ./converted/{name}.wav return STT('./audio/converted/{}'.format(file_name[:-4]+".wav"))
import urllib, convert, re, os # from speech_py import speech_to_text_google as STT from speech_py import speech_to_text_ibm_rest as STT def transcribe(audio_url): if not os.path.isdir('./audio/retrieved_audio'): os.makedirs('./audio/retrieved_audio') reg_ex = '\w+.mp4' file_name = re.search(reg_ex, audio_url).group(0) urllib.urlretrieve(audio_url, './audio/retrieved_audio/{}'.format(file_name)) convert.convert('./audio/retrieved_audio/{}'.format(file_name)) # Converted in: ./converted/{name}.wav return STT('./audio/converted/{}'.format(file_name[:-4]+".wav"))
Modify ffmpeg path heroku 3
Modify ffmpeg path heroku 3
Python
mit
hungtraan/FacebookBot,hungtraan/FacebookBot,hungtraan/FacebookBot
import urllib, convert, re, os - # from speech_py import speech_to_text_offline as STT_o # from speech_py import speech_to_text_google as STT from speech_py import speech_to_text_ibm_rest as STT def transcribe(audio_url): if not os.path.isdir('./audio/retrieved_audio'): os.makedirs('./audio/retrieved_audio') reg_ex = '\w+.mp4' file_name = re.search(reg_ex, audio_url).group(0) urllib.urlretrieve(audio_url, './audio/retrieved_audio/{}'.format(file_name)) convert.convert('./audio/retrieved_audio/{}'.format(file_name)) # Converted in: ./converted/{name}.wav return STT('./audio/converted/{}'.format(file_name[:-4]+".wav"))
Modify ffmpeg path heroku 3
## Code Before: import urllib, convert, re, os # from speech_py import speech_to_text_offline as STT_o # from speech_py import speech_to_text_google as STT from speech_py import speech_to_text_ibm_rest as STT def transcribe(audio_url): if not os.path.isdir('./audio/retrieved_audio'): os.makedirs('./audio/retrieved_audio') reg_ex = '\w+.mp4' file_name = re.search(reg_ex, audio_url).group(0) urllib.urlretrieve(audio_url, './audio/retrieved_audio/{}'.format(file_name)) convert.convert('./audio/retrieved_audio/{}'.format(file_name)) # Converted in: ./converted/{name}.wav return STT('./audio/converted/{}'.format(file_name[:-4]+".wav")) ## Instruction: Modify ffmpeg path heroku 3 ## Code After: import urllib, convert, re, os # from speech_py import speech_to_text_google as STT from speech_py import speech_to_text_ibm_rest as STT def transcribe(audio_url): if not os.path.isdir('./audio/retrieved_audio'): os.makedirs('./audio/retrieved_audio') reg_ex = '\w+.mp4' file_name = re.search(reg_ex, audio_url).group(0) urllib.urlretrieve(audio_url, './audio/retrieved_audio/{}'.format(file_name)) convert.convert('./audio/retrieved_audio/{}'.format(file_name)) # Converted in: ./converted/{name}.wav return STT('./audio/converted/{}'.format(file_name[:-4]+".wav"))
// ... existing code ... import urllib, convert, re, os # from speech_py import speech_to_text_google as STT // ... rest of the code ...
8df3076b6315a74e57ee27fe3478d36737be0ff9
roche/scripts/xml-load.py
roche/scripts/xml-load.py
import sys import os sys.path.append('.') import roche.settings from os import walk from eulexistdb.db import ExistDB from roche.settings import EXISTDB_SERVER_URL # # Timeout higher? # xmldb = ExistDB(timeout=30) xmldb.createCollection('docker', True) xmldb.createCollection('docker/texts', True) os.chdir('../dublin-store') for (dirpath, dirnames, filenames) in walk('浙江大學圖書館'): xmldb.createCollection('docker/texts' + '/' + dirpath, True) if filenames: for filename in filenames: with open(dirpath + '/' + filename) as f: xmldb.load(f, 'docker/texts' + '/' + dirpath + '/' + filename, True)
import sys import os sys.path.append('.') import roche.settings from os import walk from eulexistdb.db import ExistDB from roche.settings import EXISTDB_SERVER_URL # # Timeout higher? # xmldb = ExistDB(timeout=30) xmldb.createCollection('docker', True) xmldb.createCollection('docker/texts', True) os.chdir('../dublin-store') for (dirpath, dirnames, filenames) in walk('浙江大學圖書館'): xmldb.createCollection('docker/texts' + '/' + dirpath, True) if filenames: for filename in filenames: with open(dirpath + '/' + filename) as f: xmldb.load(f, 'docker/texts' + '/' + dirpath + '/' + filename, True) # # Load resources # for (dirpath, dirnames, filenames) in walk('resources'): xmldb.createCollection('docker' + '/' + dirpath, True) if filenames: for filename in filenames: with open(dirpath + '/' + filename) as f: xmldb.load(f, 'docker' + '/' + dirpath + '/' + filename, True)
Load other resources into exist-db
Load other resources into exist-db
Python
mit
beijingren/roche-website,beijingren/roche-website,beijingren/roche-website,beijingren/roche-website
import sys import os sys.path.append('.') import roche.settings from os import walk from eulexistdb.db import ExistDB from roche.settings import EXISTDB_SERVER_URL # # Timeout higher? # xmldb = ExistDB(timeout=30) xmldb.createCollection('docker', True) xmldb.createCollection('docker/texts', True) os.chdir('../dublin-store') for (dirpath, dirnames, filenames) in walk('浙江大學圖書館'): xmldb.createCollection('docker/texts' + '/' + dirpath, True) if filenames: for filename in filenames: with open(dirpath + '/' + filename) as f: xmldb.load(f, 'docker/texts' + '/' + dirpath + '/' + filename, True) + # + # Load resources + # + for (dirpath, dirnames, filenames) in walk('resources'): + xmldb.createCollection('docker' + '/' + dirpath, True) + if filenames: + for filename in filenames: + with open(dirpath + '/' + filename) as f: + xmldb.load(f, 'docker' + '/' + dirpath + '/' + filename, True) +
Load other resources into exist-db
## Code Before: import sys import os sys.path.append('.') import roche.settings from os import walk from eulexistdb.db import ExistDB from roche.settings import EXISTDB_SERVER_URL # # Timeout higher? # xmldb = ExistDB(timeout=30) xmldb.createCollection('docker', True) xmldb.createCollection('docker/texts', True) os.chdir('../dublin-store') for (dirpath, dirnames, filenames) in walk('浙江大學圖書館'): xmldb.createCollection('docker/texts' + '/' + dirpath, True) if filenames: for filename in filenames: with open(dirpath + '/' + filename) as f: xmldb.load(f, 'docker/texts' + '/' + dirpath + '/' + filename, True) ## Instruction: Load other resources into exist-db ## Code After: import sys import os sys.path.append('.') import roche.settings from os import walk from eulexistdb.db import ExistDB from roche.settings import EXISTDB_SERVER_URL # # Timeout higher? # xmldb = ExistDB(timeout=30) xmldb.createCollection('docker', True) xmldb.createCollection('docker/texts', True) os.chdir('../dublin-store') for (dirpath, dirnames, filenames) in walk('浙江大學圖書館'): xmldb.createCollection('docker/texts' + '/' + dirpath, True) if filenames: for filename in filenames: with open(dirpath + '/' + filename) as f: xmldb.load(f, 'docker/texts' + '/' + dirpath + '/' + filename, True) # # Load resources # for (dirpath, dirnames, filenames) in walk('resources'): xmldb.createCollection('docker' + '/' + dirpath, True) if filenames: for filename in filenames: with open(dirpath + '/' + filename) as f: xmldb.load(f, 'docker' + '/' + dirpath + '/' + filename, True)
... xmldb.load(f, 'docker/texts' + '/' + dirpath + '/' + filename, True) # # Load resources # for (dirpath, dirnames, filenames) in walk('resources'): xmldb.createCollection('docker' + '/' + dirpath, True) if filenames: for filename in filenames: with open(dirpath + '/' + filename) as f: xmldb.load(f, 'docker' + '/' + dirpath + '/' + filename, True) ...
c4eef5919fa60c87b59d60c1bd005f97183ce057
aiozk/test/test_connection.py
aiozk/test/test_connection.py
from unittest import mock import pytest import aiozk.connection @pytest.fixture def connection(event_loop): connection = aiozk.connection.Connection( host='zookeeper.test', port=2181, watch_handler=mock.MagicMock(), read_timeout=30, loop=mock.MagicMock(wraps=event_loop)) connection.writer = mock.MagicMock() return connection @pytest.mark.asyncio async def test_close_connection_in_state_closing_do_not_performs_abort(connection): connection.abort = mock.AsyncMock() connection.closing = True await connection.close(mock.ANY) connection.abort.assert_not_awaited() @pytest.mark.asyncio async def test_close_cancels_read_loop_task(connection): connection.start_read_loop() connection.read_response = mock.AsyncMock(return_value=(0, mock.ANY, mock.ANY)) task_cancelled_future = connection.loop.create_future() def set_result(task): task_cancelled_future.set_result(task.cancelled()) connection.read_loop_task.add_done_callback(set_result) await connection.close(mock.ANY) assert await task_cancelled_future
from unittest import mock import pytest import aiozk.connection @pytest.fixture def connection(event_loop): connection = aiozk.connection.Connection( host='zookeeper.test', port=2181, watch_handler=mock.MagicMock(), read_timeout=30, loop=event_loop) connection.writer = mock.MagicMock() return connection @pytest.mark.asyncio async def test_close_connection_in_state_closing_do_not_performs_abort(connection): connection.abort = mock.AsyncMock() connection.closing = True await connection.close(0.1) connection.abort.assert_not_awaited() @pytest.mark.asyncio async def test_close_cancels_read_loop_task(connection): connection.read_loop_task = connection.loop.create_future() connection.read_loop_task.done = mock.MagicMock(return_value=False) connection.read_loop_task.cancel = mock.MagicMock( wraps=connection.read_loop_task.cancel) await connection.close(0.1) connection.read_loop_task.cancel.assert_called_once() @pytest.mark.asyncio async def test_connection_abort(connection): connection.pending_count = mock.MagicMock(return_value=1) connection.abort = mock.MagicMock() await connection.close(0.1) connection.abort.assert_called_once()
Modify and add tests for the revised connection.close
Modify and add tests for the revised connection.close
Python
mit
tipsi/aiozk,tipsi/aiozk
from unittest import mock import pytest import aiozk.connection @pytest.fixture def connection(event_loop): connection = aiozk.connection.Connection( host='zookeeper.test', port=2181, watch_handler=mock.MagicMock(), read_timeout=30, - loop=mock.MagicMock(wraps=event_loop)) + loop=event_loop) connection.writer = mock.MagicMock() return connection @pytest.mark.asyncio async def test_close_connection_in_state_closing_do_not_performs_abort(connection): connection.abort = mock.AsyncMock() connection.closing = True - await connection.close(mock.ANY) + await connection.close(0.1) connection.abort.assert_not_awaited() @pytest.mark.asyncio async def test_close_cancels_read_loop_task(connection): - connection.start_read_loop() - connection.read_response = mock.AsyncMock(return_value=(0, mock.ANY, mock.ANY)) + connection.read_loop_task = connection.loop.create_future() + connection.read_loop_task.done = mock.MagicMock(return_value=False) + connection.read_loop_task.cancel = mock.MagicMock( + wraps=connection.read_loop_task.cancel) + await connection.close(0.1) + connection.read_loop_task.cancel.assert_called_once() - task_cancelled_future = connection.loop.create_future() - def set_result(task): - task_cancelled_future.set_result(task.cancelled()) + @pytest.mark.asyncio + async def test_connection_abort(connection): + connection.pending_count = mock.MagicMock(return_value=1) + connection.abort = mock.MagicMock() + await connection.close(0.1) + connection.abort.assert_called_once() - connection.read_loop_task.add_done_callback(set_result) - - await connection.close(mock.ANY) - assert await task_cancelled_future -
Modify and add tests for the revised connection.close
## Code Before: from unittest import mock import pytest import aiozk.connection @pytest.fixture def connection(event_loop): connection = aiozk.connection.Connection( host='zookeeper.test', port=2181, watch_handler=mock.MagicMock(), read_timeout=30, loop=mock.MagicMock(wraps=event_loop)) connection.writer = mock.MagicMock() return connection @pytest.mark.asyncio async def test_close_connection_in_state_closing_do_not_performs_abort(connection): connection.abort = mock.AsyncMock() connection.closing = True await connection.close(mock.ANY) connection.abort.assert_not_awaited() @pytest.mark.asyncio async def test_close_cancels_read_loop_task(connection): connection.start_read_loop() connection.read_response = mock.AsyncMock(return_value=(0, mock.ANY, mock.ANY)) task_cancelled_future = connection.loop.create_future() def set_result(task): task_cancelled_future.set_result(task.cancelled()) connection.read_loop_task.add_done_callback(set_result) await connection.close(mock.ANY) assert await task_cancelled_future ## Instruction: Modify and add tests for the revised connection.close ## Code After: from unittest import mock import pytest import aiozk.connection @pytest.fixture def connection(event_loop): connection = aiozk.connection.Connection( host='zookeeper.test', port=2181, watch_handler=mock.MagicMock(), read_timeout=30, loop=event_loop) connection.writer = mock.MagicMock() return connection @pytest.mark.asyncio async def test_close_connection_in_state_closing_do_not_performs_abort(connection): connection.abort = mock.AsyncMock() connection.closing = True await connection.close(0.1) connection.abort.assert_not_awaited() @pytest.mark.asyncio async def test_close_cancels_read_loop_task(connection): connection.read_loop_task = connection.loop.create_future() connection.read_loop_task.done = mock.MagicMock(return_value=False) connection.read_loop_task.cancel = mock.MagicMock( wraps=connection.read_loop_task.cancel) await connection.close(0.1) connection.read_loop_task.cancel.assert_called_once() @pytest.mark.asyncio async def test_connection_abort(connection): connection.pending_count = mock.MagicMock(return_value=1) connection.abort = mock.MagicMock() await connection.close(0.1) connection.abort.assert_called_once()
// ... existing code ... read_timeout=30, loop=event_loop) // ... modified code ... await connection.close(0.1) ... async def test_close_cancels_read_loop_task(connection): connection.read_loop_task = connection.loop.create_future() connection.read_loop_task.done = mock.MagicMock(return_value=False) connection.read_loop_task.cancel = mock.MagicMock( wraps=connection.read_loop_task.cancel) await connection.close(0.1) connection.read_loop_task.cancel.assert_called_once() @pytest.mark.asyncio async def test_connection_abort(connection): connection.pending_count = mock.MagicMock(return_value=1) connection.abort = mock.MagicMock() await connection.close(0.1) connection.abort.assert_called_once() // ... rest of the code ...
c39a64c5dc83d55632ffc19a96196aef07474114
pylab/accounts/tests/test_settings.py
pylab/accounts/tests/test_settings.py
import django_webtest import django.contrib.auth.models as auth_models import pylab.accounts.models as accounts_models class SettingsTests(django_webtest.WebTest): def setUp(self): super().setUp() auth_models.User.objects.create_user('u1') def test_settings(self): resp = self.app.get('/accounts/settings/', user='u1') resp.form['first_name'] = 'My' resp.form['last_name'] = 'Name' resp.form['email'] = '' resp.form['language'] = 'en' resp = resp.form.submit() self.assertEqual(resp.status_int, 302) self.assertEqual(list(auth_models.User.objects.values_list('first_name', 'last_name', 'email')), [ ('My', 'Name', ''), ]) self.assertEqual(list(accounts_models.UserProfile.objects.values_list('language')), [('en',),])
import django_webtest import django.contrib.auth.models as auth_models import pylab.accounts.models as accounts_models class SettingsTests(django_webtest.WebTest): def setUp(self): super().setUp() auth_models.User.objects.create_user('u1') def test_user_settings(self): resp = self.app.get('/accounts/settings/', user='u1') resp.form['first_name'] = 'My' resp.form['last_name'] = 'Name' resp.form['email'] = '' resp = resp.form.submit() self.assertEqual(resp.status_int, 302) self.assertEqual(list(auth_models.User.objects.values_list('first_name', 'last_name', 'email')), [ ('My', 'Name', ''), ]) def test_userprofile_settings(self): resp = self.app.get('/accounts/settings/', user='u1') resp.form['language'] = 'en' resp = resp.form.submit() self.assertEqual(resp.status_int, 302) self.assertEqual(list(accounts_models.UserProfile.objects.values_list('language')), [('en',),])
Split user settings test into two tests
Split user settings test into two tests
Python
agpl-3.0
python-dirbtuves/website,python-dirbtuves/website,python-dirbtuves/website
import django_webtest import django.contrib.auth.models as auth_models import pylab.accounts.models as accounts_models class SettingsTests(django_webtest.WebTest): def setUp(self): super().setUp() auth_models.User.objects.create_user('u1') - def test_settings(self): + def test_user_settings(self): resp = self.app.get('/accounts/settings/', user='u1') resp.form['first_name'] = 'My' resp.form['last_name'] = 'Name' resp.form['email'] = '' - resp.form['language'] = 'en' resp = resp.form.submit() self.assertEqual(resp.status_int, 302) self.assertEqual(list(auth_models.User.objects.values_list('first_name', 'last_name', 'email')), [ ('My', 'Name', ''), ]) + + def test_userprofile_settings(self): + resp = self.app.get('/accounts/settings/', user='u1') + resp.form['language'] = 'en' + resp = resp.form.submit() + self.assertEqual(resp.status_int, 302) self.assertEqual(list(accounts_models.UserProfile.objects.values_list('language')), [('en',),])
Split user settings test into two tests
## Code Before: import django_webtest import django.contrib.auth.models as auth_models import pylab.accounts.models as accounts_models class SettingsTests(django_webtest.WebTest): def setUp(self): super().setUp() auth_models.User.objects.create_user('u1') def test_settings(self): resp = self.app.get('/accounts/settings/', user='u1') resp.form['first_name'] = 'My' resp.form['last_name'] = 'Name' resp.form['email'] = '' resp.form['language'] = 'en' resp = resp.form.submit() self.assertEqual(resp.status_int, 302) self.assertEqual(list(auth_models.User.objects.values_list('first_name', 'last_name', 'email')), [ ('My', 'Name', ''), ]) self.assertEqual(list(accounts_models.UserProfile.objects.values_list('language')), [('en',),]) ## Instruction: Split user settings test into two tests ## Code After: import django_webtest import django.contrib.auth.models as auth_models import pylab.accounts.models as accounts_models class SettingsTests(django_webtest.WebTest): def setUp(self): super().setUp() auth_models.User.objects.create_user('u1') def test_user_settings(self): resp = self.app.get('/accounts/settings/', user='u1') resp.form['first_name'] = 'My' resp.form['last_name'] = 'Name' resp.form['email'] = '' resp = resp.form.submit() self.assertEqual(resp.status_int, 302) self.assertEqual(list(auth_models.User.objects.values_list('first_name', 'last_name', 'email')), [ ('My', 'Name', ''), ]) def test_userprofile_settings(self): resp = self.app.get('/accounts/settings/', user='u1') resp.form['language'] = 'en' resp = resp.form.submit() self.assertEqual(resp.status_int, 302) self.assertEqual(list(accounts_models.UserProfile.objects.values_list('language')), [('en',),])
... def test_user_settings(self): resp = self.app.get('/accounts/settings/', user='u1') ... resp.form['email'] = '' resp = resp.form.submit() ... ]) def test_userprofile_settings(self): resp = self.app.get('/accounts/settings/', user='u1') resp.form['language'] = 'en' resp = resp.form.submit() self.assertEqual(resp.status_int, 302) self.assertEqual(list(accounts_models.UserProfile.objects.values_list('language')), [('en',),]) ...
9660fb734ecf2ad2c181eba790cdd2ddc9ed423e
cyder/core/system/forms.py
cyder/core/system/forms.py
from django import forms from cyder.base.eav.forms import get_eav_form from cyder.base.mixins import UsabilityFormMixin from cyder.core.system.models import System, SystemAV class SystemForm(forms.ModelForm): class Meta: model = System class ExtendedSystemForm(forms.ModelForm, UsabilityFormMixin): interface_type = forms.ChoiceField( widget=forms.RadioSelect, choices=( ('Static', 'Static Interface'), ('Dynamic', 'Dynamic Interface'))) class Meta: model = System SystemAVForm = get_eav_form(SystemAV, System)
from django import forms from cyder.base.eav.forms import get_eav_form from cyder.base.mixins import UsabilityFormMixin from cyder.core.system.models import System, SystemAV class SystemForm(forms.ModelForm): class Meta: model = System class ExtendedSystemForm(forms.ModelForm, UsabilityFormMixin): interface_type = forms.ChoiceField( widget=forms.RadioSelect, choices=( ('static_interface', 'Static Interface'), ('dynamic_interface', 'Dynamic Interface'))) class Meta: model = System SystemAVForm = get_eav_form(SystemAV, System)
Fix system form interface_type choices
Fix system form interface_type choices
Python
bsd-3-clause
murrown/cyder,drkitty/cyder,OSU-Net/cyder,akeym/cyder,murrown/cyder,OSU-Net/cyder,murrown/cyder,akeym/cyder,murrown/cyder,drkitty/cyder,zeeman/cyder,zeeman/cyder,OSU-Net/cyder,akeym/cyder,zeeman/cyder,OSU-Net/cyder,drkitty/cyder,akeym/cyder,drkitty/cyder,zeeman/cyder
from django import forms from cyder.base.eav.forms import get_eav_form from cyder.base.mixins import UsabilityFormMixin from cyder.core.system.models import System, SystemAV class SystemForm(forms.ModelForm): class Meta: model = System class ExtendedSystemForm(forms.ModelForm, UsabilityFormMixin): interface_type = forms.ChoiceField( widget=forms.RadioSelect, choices=( - ('Static', 'Static Interface'), - ('Dynamic', 'Dynamic Interface'))) + ('static_interface', 'Static Interface'), + ('dynamic_interface', 'Dynamic Interface'))) class Meta: model = System SystemAVForm = get_eav_form(SystemAV, System)
Fix system form interface_type choices
## Code Before: from django import forms from cyder.base.eav.forms import get_eav_form from cyder.base.mixins import UsabilityFormMixin from cyder.core.system.models import System, SystemAV class SystemForm(forms.ModelForm): class Meta: model = System class ExtendedSystemForm(forms.ModelForm, UsabilityFormMixin): interface_type = forms.ChoiceField( widget=forms.RadioSelect, choices=( ('Static', 'Static Interface'), ('Dynamic', 'Dynamic Interface'))) class Meta: model = System SystemAVForm = get_eav_form(SystemAV, System) ## Instruction: Fix system form interface_type choices ## Code After: from django import forms from cyder.base.eav.forms import get_eav_form from cyder.base.mixins import UsabilityFormMixin from cyder.core.system.models import System, SystemAV class SystemForm(forms.ModelForm): class Meta: model = System class ExtendedSystemForm(forms.ModelForm, UsabilityFormMixin): interface_type = forms.ChoiceField( widget=forms.RadioSelect, choices=( ('static_interface', 'Static Interface'), ('dynamic_interface', 'Dynamic Interface'))) class Meta: model = System SystemAVForm = get_eav_form(SystemAV, System)
// ... existing code ... widget=forms.RadioSelect, choices=( ('static_interface', 'Static Interface'), ('dynamic_interface', 'Dynamic Interface'))) // ... rest of the code ...
da50d1b66f662f5e3e1b89fd88632f7076c32084
apps/careers/models.py
apps/careers/models.py
from cms import sitemaps from cms.apps.pages.models import ContentBase from cms.models import HtmlField, PageBase from django.db import models from historylinks import shortcuts as historylinks class Careers(ContentBase): classifier = 'apps' urlconf = '{{ project_name }}.apps.careers.urls' per_page = models.PositiveIntegerField( 'careers per page', default=10, blank=True, null=True ) def __str__(self): return self.page.title class Career(PageBase): page = models.ForeignKey( Careers ) title = models.CharField( max_length=256, ) slug = models.CharField( max_length=256, unique=True ) location = models.CharField( max_length=256, blank=True, null=True ) summary = models.TextField( blank=True, null=True ) description = HtmlField() email_address = models.EmailField() order = models.PositiveIntegerField( default=0 ) class Meta: ordering = ['order'] def __str__(self): return self.title def get_absolute_url(self): return self.page.page.reverse('career_detail', kwargs={ 'slug': self.slug, }) historylinks.register(Career) sitemaps.register(Career)
from cms import sitemaps from cms.apps.pages.models import ContentBase from cms.models import HtmlField, PageBase from django.db import models from historylinks import shortcuts as historylinks class Careers(ContentBase): classifier = 'apps' urlconf = '{{ project_name }}.apps.careers.urls' per_page = models.PositiveIntegerField( 'careers per page', default=10, blank=True, null=True ) def __str__(self): return self.page.title class Career(PageBase): page = models.ForeignKey( Careers ) location = models.CharField( max_length=256, blank=True, null=True ) summary = models.TextField( blank=True, null=True ) description = HtmlField() email_address = models.EmailField() order = models.PositiveIntegerField( default=0 ) class Meta: ordering = ['order'] def __str__(self): return self.title def get_absolute_url(self): return self.page.page.reverse('career_detail', kwargs={ 'slug': self.slug, }) historylinks.register(Career) sitemaps.register(Career)
Remove duplicate fields from Career
Remove duplicate fields from Career
Python
mit
onespacemedia/cms-jobs,onespacemedia/cms-jobs
from cms import sitemaps from cms.apps.pages.models import ContentBase from cms.models import HtmlField, PageBase from django.db import models from historylinks import shortcuts as historylinks class Careers(ContentBase): classifier = 'apps' urlconf = '{{ project_name }}.apps.careers.urls' per_page = models.PositiveIntegerField( 'careers per page', default=10, blank=True, null=True ) def __str__(self): return self.page.title class Career(PageBase): page = models.ForeignKey( Careers - ) - - title = models.CharField( - max_length=256, - ) - - slug = models.CharField( - max_length=256, - unique=True ) location = models.CharField( max_length=256, blank=True, null=True ) summary = models.TextField( blank=True, null=True ) description = HtmlField() email_address = models.EmailField() order = models.PositiveIntegerField( default=0 ) class Meta: ordering = ['order'] def __str__(self): return self.title def get_absolute_url(self): return self.page.page.reverse('career_detail', kwargs={ 'slug': self.slug, }) historylinks.register(Career) sitemaps.register(Career)
Remove duplicate fields from Career
## Code Before: from cms import sitemaps from cms.apps.pages.models import ContentBase from cms.models import HtmlField, PageBase from django.db import models from historylinks import shortcuts as historylinks class Careers(ContentBase): classifier = 'apps' urlconf = '{{ project_name }}.apps.careers.urls' per_page = models.PositiveIntegerField( 'careers per page', default=10, blank=True, null=True ) def __str__(self): return self.page.title class Career(PageBase): page = models.ForeignKey( Careers ) title = models.CharField( max_length=256, ) slug = models.CharField( max_length=256, unique=True ) location = models.CharField( max_length=256, blank=True, null=True ) summary = models.TextField( blank=True, null=True ) description = HtmlField() email_address = models.EmailField() order = models.PositiveIntegerField( default=0 ) class Meta: ordering = ['order'] def __str__(self): return self.title def get_absolute_url(self): return self.page.page.reverse('career_detail', kwargs={ 'slug': self.slug, }) historylinks.register(Career) sitemaps.register(Career) ## Instruction: Remove duplicate fields from Career ## Code After: from cms import sitemaps from cms.apps.pages.models import ContentBase from cms.models import HtmlField, PageBase from django.db import models from historylinks import shortcuts as historylinks class Careers(ContentBase): classifier = 'apps' urlconf = '{{ project_name }}.apps.careers.urls' per_page = models.PositiveIntegerField( 'careers per page', default=10, blank=True, null=True ) def __str__(self): return self.page.title class Career(PageBase): page = models.ForeignKey( Careers ) location = models.CharField( max_length=256, blank=True, null=True ) summary = models.TextField( blank=True, null=True ) description = HtmlField() email_address = models.EmailField() order = models.PositiveIntegerField( default=0 ) class Meta: ordering = ['order'] def __str__(self): return self.title def get_absolute_url(self): return self.page.page.reverse('career_detail', kwargs={ 'slug': self.slug, }) historylinks.register(Career) sitemaps.register(Career)
... Careers ) ...
77ff64c858aa21c9651ccf58c95b739db45cd97b
Instanssi/kompomaatti/templatetags/kompomaatti_base_tags.py
Instanssi/kompomaatti/templatetags/kompomaatti_base_tags.py
from django import template from Instanssi.kompomaatti.models import Compo, Competition register = template.Library() @register.inclusion_tag('kompomaatti/compo_nav_items.html') def render_base_compos_nav(event_id): return { 'event_id': event_id, 'compos': Compo.objects.filter(active=True, event_id=event_id) } @register.inclusion_tag('kompomaatti/competition_nav_items.html') def render_base_competitions_nav(event_id): return { 'event_id': event_id, 'competitions': Competition.objects.filter(active=True, event_id=event_id) }
from django import template from Instanssi.kompomaatti.models import Compo, Competition register = template.Library() @register.inclusion_tag('kompomaatti/tags/compo_nav_items.html') def render_base_compos_nav(event_id): return { 'event_id': event_id, 'compos': Compo.objects.filter(active=True, event_id=event_id) } @register.inclusion_tag('kompomaatti/tags/competition_nav_items.html') def render_base_competitions_nav(event_id): return { 'event_id': event_id, 'competitions': Competition.objects.filter(active=True, event_id=event_id) }
Update tags to use new template subdirectory.
kompomaatti: Update tags to use new template subdirectory.
Python
mit
Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org
from django import template from Instanssi.kompomaatti.models import Compo, Competition register = template.Library() - @register.inclusion_tag('kompomaatti/compo_nav_items.html') + @register.inclusion_tag('kompomaatti/tags/compo_nav_items.html') def render_base_compos_nav(event_id): return { 'event_id': event_id, 'compos': Compo.objects.filter(active=True, event_id=event_id) } - @register.inclusion_tag('kompomaatti/competition_nav_items.html') + @register.inclusion_tag('kompomaatti/tags/competition_nav_items.html') def render_base_competitions_nav(event_id): return { 'event_id': event_id, 'competitions': Competition.objects.filter(active=True, event_id=event_id) }
Update tags to use new template subdirectory.
## Code Before: from django import template from Instanssi.kompomaatti.models import Compo, Competition register = template.Library() @register.inclusion_tag('kompomaatti/compo_nav_items.html') def render_base_compos_nav(event_id): return { 'event_id': event_id, 'compos': Compo.objects.filter(active=True, event_id=event_id) } @register.inclusion_tag('kompomaatti/competition_nav_items.html') def render_base_competitions_nav(event_id): return { 'event_id': event_id, 'competitions': Competition.objects.filter(active=True, event_id=event_id) } ## Instruction: Update tags to use new template subdirectory. ## Code After: from django import template from Instanssi.kompomaatti.models import Compo, Competition register = template.Library() @register.inclusion_tag('kompomaatti/tags/compo_nav_items.html') def render_base_compos_nav(event_id): return { 'event_id': event_id, 'compos': Compo.objects.filter(active=True, event_id=event_id) } @register.inclusion_tag('kompomaatti/tags/competition_nav_items.html') def render_base_competitions_nav(event_id): return { 'event_id': event_id, 'competitions': Competition.objects.filter(active=True, event_id=event_id) }
// ... existing code ... @register.inclusion_tag('kompomaatti/tags/compo_nav_items.html') def render_base_compos_nav(event_id): // ... modified code ... @register.inclusion_tag('kompomaatti/tags/competition_nav_items.html') def render_base_competitions_nav(event_id): // ... rest of the code ...
c7b7e62cb2585f6109d70b27564617b0be4c8c33
tests/test_daterange.py
tests/test_daterange.py
import os import time try: import unittest2 as unittest except ImportError: import unittest class DateRangeTest(unittest.TestCase): def setUp(self): self.openlicensefile = os.path.join(os.path.dirname(__file__), '../LICENSE.txt') self.pattern = 'Copyright (c) 2012 - %s SendGrid, Inc.' % (time.strftime("%Y")) self.licensefile = open(self.openlicensefile).read() def test__daterange(self): self.assertTrue(self.pattern in self.licensefile)
import os import time try: import unittest2 as unittest except ImportError: import unittest class DateRangeTest(unittest.TestCase): def setUp(self): self.openlicensefile = os.path.join( os.path.dirname(__file__), '../LICENSE.txt') self.pattern = 'Copyright (c) 2012 - %s SendGrid, Inc.' % ( time.strftime("%Y")) self.licensefile = open(self.openlicensefile).read() def test__daterange(self): self.assertTrue(self.pattern in self.licensefile)
Update code for PEP8 compliance
Update code for PEP8 compliance
Python
mit
sendgrid/python-http-client,sendgrid/python-http-client
import os import time try: import unittest2 as unittest except ImportError: import unittest + class DateRangeTest(unittest.TestCase): def setUp(self): - self.openlicensefile = os.path.join(os.path.dirname(__file__), '../LICENSE.txt') + self.openlicensefile = os.path.join( + os.path.dirname(__file__), + '../LICENSE.txt') - self.pattern = 'Copyright (c) 2012 - %s SendGrid, Inc.' % (time.strftime("%Y")) + self.pattern = 'Copyright (c) 2012 - %s SendGrid, Inc.' % ( + time.strftime("%Y")) self.licensefile = open(self.openlicensefile).read() def test__daterange(self): self.assertTrue(self.pattern in self.licensefile)
Update code for PEP8 compliance
## Code Before: import os import time try: import unittest2 as unittest except ImportError: import unittest class DateRangeTest(unittest.TestCase): def setUp(self): self.openlicensefile = os.path.join(os.path.dirname(__file__), '../LICENSE.txt') self.pattern = 'Copyright (c) 2012 - %s SendGrid, Inc.' % (time.strftime("%Y")) self.licensefile = open(self.openlicensefile).read() def test__daterange(self): self.assertTrue(self.pattern in self.licensefile) ## Instruction: Update code for PEP8 compliance ## Code After: import os import time try: import unittest2 as unittest except ImportError: import unittest class DateRangeTest(unittest.TestCase): def setUp(self): self.openlicensefile = os.path.join( os.path.dirname(__file__), '../LICENSE.txt') self.pattern = 'Copyright (c) 2012 - %s SendGrid, Inc.' % ( time.strftime("%Y")) self.licensefile = open(self.openlicensefile).read() def test__daterange(self): self.assertTrue(self.pattern in self.licensefile)
# ... existing code ... class DateRangeTest(unittest.TestCase): # ... modified code ... def setUp(self): self.openlicensefile = os.path.join( os.path.dirname(__file__), '../LICENSE.txt') self.pattern = 'Copyright (c) 2012 - %s SendGrid, Inc.' % ( time.strftime("%Y")) self.licensefile = open(self.openlicensefile).read() # ... rest of the code ...
0c186d8e0fb5bd7170ec55943e546f1e4e335839
masters/master.tryserver.chromium/master_site_config.py
masters/master.tryserver.chromium/master_site_config.py
"""ActiveMaster definition.""" from config_bootstrap import Master class TryServer(Master.Master4): project_name = 'Chromium Try Server' master_port = 8028 slave_port = 8128 master_port_alt = 8228 try_job_port = 8328 # Select tree status urls and codereview location. reply_to = '[email protected]' base_app_url = 'https://chromium-status.appspot.com' tree_status_url = base_app_url + '/status' store_revisions_url = base_app_url + '/revisions' last_good_url = base_app_url + '/lkgr' last_good_blink_url = 'http://blink-status.appspot.com/lkgr' svn_url = 'svn://svn-mirror.golo.chromium.org/chrome-try/try' buildbot_url = 'http://build.chromium.org/p/tryserver.chromium/'
"""ActiveMaster definition.""" from config_bootstrap import Master class TryServer(Master.Master4): project_name = 'Chromium Try Server' master_port = 8028 slave_port = 8128 master_port_alt = 8228 try_job_port = 8328 # Select tree status urls and codereview location. reply_to = '[email protected]' base_app_url = 'https://chromium-status.appspot.com' tree_status_url = base_app_url + '/status' store_revisions_url = base_app_url + '/revisions' last_good_url = None last_good_blink_url = None svn_url = 'svn://svn-mirror.golo.chromium.org/chrome-try/try' buildbot_url = 'http://build.chromium.org/p/tryserver.chromium/'
Remove last good URL for tryserver.chromium
Remove last good URL for tryserver.chromium The expected behavior of this change is that the tryserver master no longer tries to resolve revisions to LKGR when trying jobs. BUG=372499, 386667 Review URL: https://codereview.chromium.org/394653002 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@283469 0039d316-1c4b-4281-b951-d872f2087c98
Python
bsd-3-clause
eunchong/build,eunchong/build,eunchong/build,eunchong/build
"""ActiveMaster definition.""" from config_bootstrap import Master class TryServer(Master.Master4): project_name = 'Chromium Try Server' master_port = 8028 slave_port = 8128 master_port_alt = 8228 try_job_port = 8328 # Select tree status urls and codereview location. reply_to = '[email protected]' base_app_url = 'https://chromium-status.appspot.com' tree_status_url = base_app_url + '/status' store_revisions_url = base_app_url + '/revisions' - last_good_url = base_app_url + '/lkgr' - last_good_blink_url = 'http://blink-status.appspot.com/lkgr' + last_good_url = None + last_good_blink_url = None svn_url = 'svn://svn-mirror.golo.chromium.org/chrome-try/try' buildbot_url = 'http://build.chromium.org/p/tryserver.chromium/'
Remove last good URL for tryserver.chromium
## Code Before: """ActiveMaster definition.""" from config_bootstrap import Master class TryServer(Master.Master4): project_name = 'Chromium Try Server' master_port = 8028 slave_port = 8128 master_port_alt = 8228 try_job_port = 8328 # Select tree status urls and codereview location. reply_to = '[email protected]' base_app_url = 'https://chromium-status.appspot.com' tree_status_url = base_app_url + '/status' store_revisions_url = base_app_url + '/revisions' last_good_url = base_app_url + '/lkgr' last_good_blink_url = 'http://blink-status.appspot.com/lkgr' svn_url = 'svn://svn-mirror.golo.chromium.org/chrome-try/try' buildbot_url = 'http://build.chromium.org/p/tryserver.chromium/' ## Instruction: Remove last good URL for tryserver.chromium ## Code After: """ActiveMaster definition.""" from config_bootstrap import Master class TryServer(Master.Master4): project_name = 'Chromium Try Server' master_port = 8028 slave_port = 8128 master_port_alt = 8228 try_job_port = 8328 # Select tree status urls and codereview location. reply_to = '[email protected]' base_app_url = 'https://chromium-status.appspot.com' tree_status_url = base_app_url + '/status' store_revisions_url = base_app_url + '/revisions' last_good_url = None last_good_blink_url = None svn_url = 'svn://svn-mirror.golo.chromium.org/chrome-try/try' buildbot_url = 'http://build.chromium.org/p/tryserver.chromium/'
# ... existing code ... store_revisions_url = base_app_url + '/revisions' last_good_url = None last_good_blink_url = None svn_url = 'svn://svn-mirror.golo.chromium.org/chrome-try/try' # ... rest of the code ...
7e2835f76474f6153d8972a983c5d45f9c4f11ee
tests/Physics/TestLight.py
tests/Physics/TestLight.py
from numpy.testing import assert_approx_equal from UliEngineering.Physics.Light import * from UliEngineering.EngineerIO import auto_format import unittest class TestJohnsonNyquistNoise(unittest.TestCase): def test_lumen_to_candela_by_apex_angle(self): v = lumen_to_candela_by_apex_angle("25 lm", "120°") assert_approx_equal(v, 7.9577471546, significant=5) self.assertEqual(auto_format(lumen_to_candela_by_apex_angle, "25 lm", "120°"), "7.96 cd")
from numpy.testing import assert_approx_equal from UliEngineering.Physics.Light import * from UliEngineering.EngineerIO import auto_format import unittest class TestLight(unittest.TestCase): def test_lumen_to_candela_by_apex_angle(self): v = lumen_to_candela_by_apex_angle("25 lm", "120°") assert_approx_equal(v, 7.9577471546, significant=5) self.assertEqual(auto_format(lumen_to_candela_by_apex_angle, "25 lm", "120°"), "7.96 cd")
Fix badly named test class
Fix badly named test class
Python
apache-2.0
ulikoehler/UliEngineering
from numpy.testing import assert_approx_equal from UliEngineering.Physics.Light import * from UliEngineering.EngineerIO import auto_format import unittest - class TestJohnsonNyquistNoise(unittest.TestCase): + class TestLight(unittest.TestCase): def test_lumen_to_candela_by_apex_angle(self): v = lumen_to_candela_by_apex_angle("25 lm", "120°") assert_approx_equal(v, 7.9577471546, significant=5) self.assertEqual(auto_format(lumen_to_candela_by_apex_angle, "25 lm", "120°"), "7.96 cd")
Fix badly named test class
## Code Before: from numpy.testing import assert_approx_equal from UliEngineering.Physics.Light import * from UliEngineering.EngineerIO import auto_format import unittest class TestJohnsonNyquistNoise(unittest.TestCase): def test_lumen_to_candela_by_apex_angle(self): v = lumen_to_candela_by_apex_angle("25 lm", "120°") assert_approx_equal(v, 7.9577471546, significant=5) self.assertEqual(auto_format(lumen_to_candela_by_apex_angle, "25 lm", "120°"), "7.96 cd") ## Instruction: Fix badly named test class ## Code After: from numpy.testing import assert_approx_equal from UliEngineering.Physics.Light import * from UliEngineering.EngineerIO import auto_format import unittest class TestLight(unittest.TestCase): def test_lumen_to_candela_by_apex_angle(self): v = lumen_to_candela_by_apex_angle("25 lm", "120°") assert_approx_equal(v, 7.9577471546, significant=5) self.assertEqual(auto_format(lumen_to_candela_by_apex_angle, "25 lm", "120°"), "7.96 cd")
// ... existing code ... class TestLight(unittest.TestCase): def test_lumen_to_candela_by_apex_angle(self): // ... rest of the code ...
9bf6aec99ac490fce1af2ea92bea57b7d1e9acd9
heat/common/environment_format.py
heat/common/environment_format.py
from heat.common.template_format import yaml SECTIONS = (PARAMETERS, RESOURCE_REGISTRY) = \ ('parameters', 'resource_registry') def parse(env_str): ''' Takes a string and returns a dict containing the parsed structure. This includes determination of whether the string is using the JSON or YAML format. ''' try: env = yaml.safe_load(env_str) except (yaml.scanner.ScannerError, yaml.parser.ParserError) as e: raise ValueError(e) else: if env is None: env = {} for param in env: if param not in SECTIONS: raise ValueError(_('environment has wrong section "%s"') % param) return env def default_for_missing(env): ''' Checks a parsed environment for missing sections. ''' for param in SECTIONS: if param not in env: env[param] = {}
from heat.common.template_format import yaml from heat.common.template_format import yaml_loader SECTIONS = (PARAMETERS, RESOURCE_REGISTRY) = \ ('parameters', 'resource_registry') def parse(env_str): ''' Takes a string and returns a dict containing the parsed structure. This includes determination of whether the string is using the JSON or YAML format. ''' try: env = yaml.load(env_str, Loader=yaml_loader) except (yaml.scanner.ScannerError, yaml.parser.ParserError) as e: raise ValueError(e) else: if env is None: env = {} for param in env: if param not in SECTIONS: raise ValueError(_('environment has wrong section "%s"') % param) return env def default_for_missing(env): ''' Checks a parsed environment for missing sections. ''' for param in SECTIONS: if param not in env: env[param] = {}
Make the template and env yaml parsing more consistent
Make the template and env yaml parsing more consistent in the environment_format.py use the same yaml_loader Partial-bug: #1242155 Change-Id: I66b08415d450bd4758af648eaff0f20dd934a9cc
Python
apache-2.0
noironetworks/heat,ntt-sic/heat,openstack/heat,srznew/heat,dragorosson/heat,steveb/heat,gonzolino/heat,pratikmallya/heat,srznew/heat,redhat-openstack/heat,cryptickp/heat,pratikmallya/heat,cwolferh/heat-scratch,pshchelo/heat,NeCTAR-RC/heat,miguelgrinberg/heat,pshchelo/heat,dragorosson/heat,maestro-hybrid-cloud/heat,takeshineshiro/heat,jasondunsmore/heat,ntt-sic/heat,maestro-hybrid-cloud/heat,miguelgrinberg/heat,rh-s/heat,rdo-management/heat,jasondunsmore/heat,cryptickp/heat,dims/heat,steveb/heat,NeCTAR-RC/heat,noironetworks/heat,gonzolino/heat,rdo-management/heat,redhat-openstack/heat,rh-s/heat,cwolferh/heat-scratch,dims/heat,takeshineshiro/heat,openstack/heat
from heat.common.template_format import yaml + from heat.common.template_format import yaml_loader SECTIONS = (PARAMETERS, RESOURCE_REGISTRY) = \ ('parameters', 'resource_registry') def parse(env_str): ''' Takes a string and returns a dict containing the parsed structure. This includes determination of whether the string is using the JSON or YAML format. ''' try: - env = yaml.safe_load(env_str) + env = yaml.load(env_str, Loader=yaml_loader) except (yaml.scanner.ScannerError, yaml.parser.ParserError) as e: raise ValueError(e) else: if env is None: env = {} for param in env: if param not in SECTIONS: raise ValueError(_('environment has wrong section "%s"') % param) return env def default_for_missing(env): ''' Checks a parsed environment for missing sections. ''' for param in SECTIONS: if param not in env: env[param] = {}
Make the template and env yaml parsing more consistent
## Code Before: from heat.common.template_format import yaml SECTIONS = (PARAMETERS, RESOURCE_REGISTRY) = \ ('parameters', 'resource_registry') def parse(env_str): ''' Takes a string and returns a dict containing the parsed structure. This includes determination of whether the string is using the JSON or YAML format. ''' try: env = yaml.safe_load(env_str) except (yaml.scanner.ScannerError, yaml.parser.ParserError) as e: raise ValueError(e) else: if env is None: env = {} for param in env: if param not in SECTIONS: raise ValueError(_('environment has wrong section "%s"') % param) return env def default_for_missing(env): ''' Checks a parsed environment for missing sections. ''' for param in SECTIONS: if param not in env: env[param] = {} ## Instruction: Make the template and env yaml parsing more consistent ## Code After: from heat.common.template_format import yaml from heat.common.template_format import yaml_loader SECTIONS = (PARAMETERS, RESOURCE_REGISTRY) = \ ('parameters', 'resource_registry') def parse(env_str): ''' Takes a string and returns a dict containing the parsed structure. This includes determination of whether the string is using the JSON or YAML format. ''' try: env = yaml.load(env_str, Loader=yaml_loader) except (yaml.scanner.ScannerError, yaml.parser.ParserError) as e: raise ValueError(e) else: if env is None: env = {} for param in env: if param not in SECTIONS: raise ValueError(_('environment has wrong section "%s"') % param) return env def default_for_missing(env): ''' Checks a parsed environment for missing sections. ''' for param in SECTIONS: if param not in env: env[param] = {}
# ... existing code ... from heat.common.template_format import yaml from heat.common.template_format import yaml_loader # ... modified code ... try: env = yaml.load(env_str, Loader=yaml_loader) except (yaml.scanner.ScannerError, yaml.parser.ParserError) as e: # ... rest of the code ...
eeac557b77a3a63a3497791a2716706801b20e37
kodos/main.py
kodos/main.py
def run(args=None): """Main entry point of the application.""" pass
import sys from PyQt4.QtGui import QApplication, QMainWindow from kodos.ui.ui_main import Ui_MainWindow class KodosMainWindow(QMainWindow, Ui_MainWindow): def __init__(self, parent=None): super(KodosMainWindow, self).__init__(parent) self.setupUi(self) self.connectActions() # Trigger the textChanged signal for widget in [self.regexText, self.searchText, self.replaceText]: widget.setPlainText('') def connectActions(self): # Connect input widgets to update the GUI when their text change for widget in [self.regexText, self.searchText, self.replaceText]: widget.textChanged.connect(self.on_compute_regex) def on_compute_regex(self): regex = self.regexText.toPlainText() search = self.searchText.toPlainText() replace = self.replaceText.toPlainText() if regex == "" or search == "": self.statusbar.showMessage( "Please enter a regex and a search to work on") else: self.statusbar.clearMessage() def run(args=None): """Main entry point of the application.""" app = QApplication(sys.argv) kodos = KodosMainWindow() kodos.show() app.exec_()
Connect the UI to the code and start to connect slots to actions.
Connect the UI to the code and start to connect slots to actions.
Python
bsd-2-clause
multani/kodos-qt4
+ import sys + from PyQt4.QtGui import QApplication, QMainWindow + + from kodos.ui.ui_main import Ui_MainWindow + + + class KodosMainWindow(QMainWindow, Ui_MainWindow): + def __init__(self, parent=None): + super(KodosMainWindow, self).__init__(parent) + self.setupUi(self) + self.connectActions() + + # Trigger the textChanged signal + for widget in [self.regexText, self.searchText, self.replaceText]: + widget.setPlainText('') + + def connectActions(self): + # Connect input widgets to update the GUI when their text change + for widget in [self.regexText, self.searchText, self.replaceText]: + widget.textChanged.connect(self.on_compute_regex) + + def on_compute_regex(self): + regex = self.regexText.toPlainText() + search = self.searchText.toPlainText() + replace = self.replaceText.toPlainText() + + if regex == "" or search == "": + self.statusbar.showMessage( + "Please enter a regex and a search to work on") + else: + self.statusbar.clearMessage() def run(args=None): """Main entry point of the application.""" - pass + app = QApplication(sys.argv) + kodos = KodosMainWindow() + kodos.show() + app.exec_() +
Connect the UI to the code and start to connect slots to actions.
## Code Before: def run(args=None): """Main entry point of the application.""" pass ## Instruction: Connect the UI to the code and start to connect slots to actions. ## Code After: import sys from PyQt4.QtGui import QApplication, QMainWindow from kodos.ui.ui_main import Ui_MainWindow class KodosMainWindow(QMainWindow, Ui_MainWindow): def __init__(self, parent=None): super(KodosMainWindow, self).__init__(parent) self.setupUi(self) self.connectActions() # Trigger the textChanged signal for widget in [self.regexText, self.searchText, self.replaceText]: widget.setPlainText('') def connectActions(self): # Connect input widgets to update the GUI when their text change for widget in [self.regexText, self.searchText, self.replaceText]: widget.textChanged.connect(self.on_compute_regex) def on_compute_regex(self): regex = self.regexText.toPlainText() search = self.searchText.toPlainText() replace = self.replaceText.toPlainText() if regex == "" or search == "": self.statusbar.showMessage( "Please enter a regex and a search to work on") else: self.statusbar.clearMessage() def run(args=None): """Main entry point of the application.""" app = QApplication(sys.argv) kodos = KodosMainWindow() kodos.show() app.exec_()
... import sys from PyQt4.QtGui import QApplication, QMainWindow from kodos.ui.ui_main import Ui_MainWindow class KodosMainWindow(QMainWindow, Ui_MainWindow): def __init__(self, parent=None): super(KodosMainWindow, self).__init__(parent) self.setupUi(self) self.connectActions() # Trigger the textChanged signal for widget in [self.regexText, self.searchText, self.replaceText]: widget.setPlainText('') def connectActions(self): # Connect input widgets to update the GUI when their text change for widget in [self.regexText, self.searchText, self.replaceText]: widget.textChanged.connect(self.on_compute_regex) def on_compute_regex(self): regex = self.regexText.toPlainText() search = self.searchText.toPlainText() replace = self.replaceText.toPlainText() if regex == "" or search == "": self.statusbar.showMessage( "Please enter a regex and a search to work on") else: self.statusbar.clearMessage() ... """Main entry point of the application.""" app = QApplication(sys.argv) kodos = KodosMainWindow() kodos.show() app.exec_() ...
46cfd25a4acf075650a5471c388457cb04cd9a15
invenio_mail/api.py
invenio_mail/api.py
"""Template based messages.""" from __future__ import absolute_import, print_function from flask import render_template from flask_mail import Message class TemplatedMessage(Message): """Siplify creation of templated messages.""" def __init__(self, template_body=None, template_html=None, ctx={}, **kwargs): r"""Build message body and HTML based on provided templates. Provided templates can use keyword arguments ``body`` and ``html`` respectively. :param template_body: Path to the text template. :param template_html: Path to the html template. :param ctx: A mapping containing additional information passed to the template. :param \*\*kwargs: Keyword arguments as defined in :class:`flask_mail.Message`. """ if template_body: kwargs['body'] = render_template( template_body, body=kwargs.get('body'), **ctx ) if template_html: kwargs['html'] = render_template( template_html, html=kwargs.get('html'), **ctx ) super(TemplatedMessage, self).__init__(**kwargs)
"""Template based messages.""" from __future__ import absolute_import, print_function from flask import render_template from flask_mail import Message class TemplatedMessage(Message): """Siplify creation of templated messages.""" def __init__(self, template_body=None, template_html=None, ctx=None, **kwargs): r"""Build message body and HTML based on provided templates. Provided templates can use keyword arguments ``body`` and ``html`` respectively. :param template_body: Path to the text template. :param template_html: Path to the html template. :param ctx: A mapping containing additional information passed to the template. :param \*\*kwargs: Keyword arguments as defined in :class:`flask_mail.Message`. """ ctx = ctx if ctx else {} if template_body: kwargs['body'] = render_template( template_body, body=kwargs.get('body'), **ctx ) if template_html: kwargs['html'] = render_template( template_html, html=kwargs.get('html'), **ctx ) super(TemplatedMessage, self).__init__(**kwargs)
Use sentinel value for ctx
Use sentinel value for ctx
Python
mit
inveniosoftware/invenio-mail,inveniosoftware/invenio-mail,inveniosoftware/invenio-mail
"""Template based messages.""" from __future__ import absolute_import, print_function from flask import render_template from flask_mail import Message class TemplatedMessage(Message): """Siplify creation of templated messages.""" - def __init__(self, template_body=None, template_html=None, ctx={}, + def __init__(self, template_body=None, template_html=None, ctx=None, **kwargs): r"""Build message body and HTML based on provided templates. Provided templates can use keyword arguments ``body`` and ``html`` respectively. :param template_body: Path to the text template. :param template_html: Path to the html template. :param ctx: A mapping containing additional information passed to the template. :param \*\*kwargs: Keyword arguments as defined in :class:`flask_mail.Message`. """ + ctx = ctx if ctx else {} if template_body: kwargs['body'] = render_template( template_body, body=kwargs.get('body'), **ctx ) if template_html: kwargs['html'] = render_template( template_html, html=kwargs.get('html'), **ctx ) super(TemplatedMessage, self).__init__(**kwargs)
Use sentinel value for ctx
## Code Before: """Template based messages.""" from __future__ import absolute_import, print_function from flask import render_template from flask_mail import Message class TemplatedMessage(Message): """Siplify creation of templated messages.""" def __init__(self, template_body=None, template_html=None, ctx={}, **kwargs): r"""Build message body and HTML based on provided templates. Provided templates can use keyword arguments ``body`` and ``html`` respectively. :param template_body: Path to the text template. :param template_html: Path to the html template. :param ctx: A mapping containing additional information passed to the template. :param \*\*kwargs: Keyword arguments as defined in :class:`flask_mail.Message`. """ if template_body: kwargs['body'] = render_template( template_body, body=kwargs.get('body'), **ctx ) if template_html: kwargs['html'] = render_template( template_html, html=kwargs.get('html'), **ctx ) super(TemplatedMessage, self).__init__(**kwargs) ## Instruction: Use sentinel value for ctx ## Code After: """Template based messages.""" from __future__ import absolute_import, print_function from flask import render_template from flask_mail import Message class TemplatedMessage(Message): """Siplify creation of templated messages.""" def __init__(self, template_body=None, template_html=None, ctx=None, **kwargs): r"""Build message body and HTML based on provided templates. Provided templates can use keyword arguments ``body`` and ``html`` respectively. :param template_body: Path to the text template. :param template_html: Path to the html template. :param ctx: A mapping containing additional information passed to the template. :param \*\*kwargs: Keyword arguments as defined in :class:`flask_mail.Message`. """ ctx = ctx if ctx else {} if template_body: kwargs['body'] = render_template( template_body, body=kwargs.get('body'), **ctx ) if template_html: kwargs['html'] = render_template( template_html, html=kwargs.get('html'), **ctx ) super(TemplatedMessage, self).__init__(**kwargs)
... def __init__(self, template_body=None, template_html=None, ctx=None, **kwargs): ... """ ctx = ctx if ctx else {} if template_body: ...
f5369b9b0175e221743101abb936b5a2947a3808
polyaxon/libs/paths.py
polyaxon/libs/paths.py
from __future__ import absolute_import, division, print_function import logging import os import shutil logger = logging.getLogger('polyaxon.libs.paths') def delete_path(path): if not os.path.exists(path): return try: shutil.rmtree(path) except OSError: logger.warning('Could not delete path `{}`'.format(path)) def create_path(path): os.mkdir(path) os.chmod(path, 0o777)
from __future__ import absolute_import, division, print_function import logging import os import shutil logger = logging.getLogger('polyaxon.libs.paths') def delete_path(path): if not os.path.exists(path): return try: if os.path.isfile(path): os.remove(path) else: shutil.rmtree(path) except OSError: logger.warning('Could not delete path `{}`'.format(path)) def create_path(path): os.mkdir(path) os.chmod(path, 0o777)
Check if file or dir before deleting
Check if file or dir before deleting
Python
apache-2.0
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
from __future__ import absolute_import, division, print_function import logging import os import shutil logger = logging.getLogger('polyaxon.libs.paths') def delete_path(path): if not os.path.exists(path): return try: + if os.path.isfile(path): + os.remove(path) + else: - shutil.rmtree(path) + shutil.rmtree(path) except OSError: logger.warning('Could not delete path `{}`'.format(path)) def create_path(path): os.mkdir(path) os.chmod(path, 0o777)
Check if file or dir before deleting
## Code Before: from __future__ import absolute_import, division, print_function import logging import os import shutil logger = logging.getLogger('polyaxon.libs.paths') def delete_path(path): if not os.path.exists(path): return try: shutil.rmtree(path) except OSError: logger.warning('Could not delete path `{}`'.format(path)) def create_path(path): os.mkdir(path) os.chmod(path, 0o777) ## Instruction: Check if file or dir before deleting ## Code After: from __future__ import absolute_import, division, print_function import logging import os import shutil logger = logging.getLogger('polyaxon.libs.paths') def delete_path(path): if not os.path.exists(path): return try: if os.path.isfile(path): os.remove(path) else: shutil.rmtree(path) except OSError: logger.warning('Could not delete path `{}`'.format(path)) def create_path(path): os.mkdir(path) os.chmod(path, 0o777)
// ... existing code ... try: if os.path.isfile(path): os.remove(path) else: shutil.rmtree(path) except OSError: // ... rest of the code ...
d6e4aa32b7b79adc734dfc2b058509cedf771944
munigeo/migrations/0004_building.py
munigeo/migrations/0004_building.py
from __future__ import unicode_literals import django.contrib.gis.db.models.fields from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('munigeo', '0003_add_modified_time_to_address_and_street'), ] operations = [ migrations.CreateModel( name='Building', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('origin_id', models.CharField(db_index=True, max_length=40)), ('geometry', django.contrib.gis.db.models.fields.MultiPolygonField(srid=4326)), ('modified_at', models.DateTimeField(auto_now=True, help_text='Time when the information was last changed')), ('addresses', models.ManyToManyField(blank=True, to='munigeo.Address')), ('municipality', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='munigeo.Municipality')), ], options={ 'ordering': ['municipality', 'origin_id'], }, ), ]
from __future__ import unicode_literals import django.contrib.gis.db.models.fields from django.db import migrations, models import django.db.models.deletion from munigeo.utils import get_default_srid DEFAULT_SRID = get_default_srid() class Migration(migrations.Migration): dependencies = [ ('munigeo', '0003_add_modified_time_to_address_and_street'), ] operations = [ migrations.CreateModel( name='Building', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('origin_id', models.CharField(db_index=True, max_length=40)), ('geometry', django.contrib.gis.db.models.fields.MultiPolygonField(srid=DEFAULT_SRID)), ('modified_at', models.DateTimeField(auto_now=True, help_text='Time when the information was last changed')), ('addresses', models.ManyToManyField(blank=True, to='munigeo.Address')), ('municipality', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='munigeo.Municipality')), ], options={ 'ordering': ['municipality', 'origin_id'], }, ), ]
Fix building migration SRID logic
Fix building migration SRID logic Hardcoding the SRID in the migration could result in a mismatch between the model srid and the migration srid.
Python
agpl-3.0
City-of-Helsinki/munigeo
from __future__ import unicode_literals import django.contrib.gis.db.models.fields from django.db import migrations, models import django.db.models.deletion + + from munigeo.utils import get_default_srid + DEFAULT_SRID = get_default_srid() class Migration(migrations.Migration): dependencies = [ ('munigeo', '0003_add_modified_time_to_address_and_street'), ] operations = [ migrations.CreateModel( name='Building', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('origin_id', models.CharField(db_index=True, max_length=40)), - ('geometry', django.contrib.gis.db.models.fields.MultiPolygonField(srid=4326)), + ('geometry', django.contrib.gis.db.models.fields.MultiPolygonField(srid=DEFAULT_SRID)), ('modified_at', models.DateTimeField(auto_now=True, help_text='Time when the information was last changed')), ('addresses', models.ManyToManyField(blank=True, to='munigeo.Address')), ('municipality', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='munigeo.Municipality')), ], options={ 'ordering': ['municipality', 'origin_id'], }, ), ]
Fix building migration SRID logic
## Code Before: from __future__ import unicode_literals import django.contrib.gis.db.models.fields from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('munigeo', '0003_add_modified_time_to_address_and_street'), ] operations = [ migrations.CreateModel( name='Building', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('origin_id', models.CharField(db_index=True, max_length=40)), ('geometry', django.contrib.gis.db.models.fields.MultiPolygonField(srid=4326)), ('modified_at', models.DateTimeField(auto_now=True, help_text='Time when the information was last changed')), ('addresses', models.ManyToManyField(blank=True, to='munigeo.Address')), ('municipality', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='munigeo.Municipality')), ], options={ 'ordering': ['municipality', 'origin_id'], }, ), ] ## Instruction: Fix building migration SRID logic ## Code After: from __future__ import unicode_literals import django.contrib.gis.db.models.fields from django.db import migrations, models import django.db.models.deletion from munigeo.utils import get_default_srid DEFAULT_SRID = get_default_srid() class Migration(migrations.Migration): dependencies = [ ('munigeo', '0003_add_modified_time_to_address_and_street'), ] operations = [ migrations.CreateModel( name='Building', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('origin_id', models.CharField(db_index=True, max_length=40)), ('geometry', django.contrib.gis.db.models.fields.MultiPolygonField(srid=DEFAULT_SRID)), ('modified_at', models.DateTimeField(auto_now=True, help_text='Time when the information was last changed')), ('addresses', models.ManyToManyField(blank=True, to='munigeo.Address')), ('municipality', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='munigeo.Municipality')), ], options={ 'ordering': ['municipality', 'origin_id'], }, ), ]
... import django.db.models.deletion from munigeo.utils import get_default_srid DEFAULT_SRID = get_default_srid() ... ('origin_id', models.CharField(db_index=True, max_length=40)), ('geometry', django.contrib.gis.db.models.fields.MultiPolygonField(srid=DEFAULT_SRID)), ('modified_at', models.DateTimeField(auto_now=True, help_text='Time when the information was last changed')), ...
2833e2296cff6a52ab75c2c88563e81372902035
src/heartbeat/checkers/build.py
src/heartbeat/checkers/build.py
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from pkg_resources import get_distribution, DistributionNotFound def check(request): package_name = settings.HEARTBEAT.get('package_name') if not package_name: raise ImproperlyConfigured( 'Missing package_name key from heartbeat configuration') try: distro = get_distribution(package_name) except DistributionNotFound: return dict(error='no distribution found for {}'.format(package_name)) return dict(name=distro.project_name, version=distro.version)
from pkg_resources import Requirement, WorkingSet from django.conf import settings from django.core.exceptions import ImproperlyConfigured def check(request): package_name = settings.HEARTBEAT.get('package_name') if not package_name: raise ImproperlyConfigured( 'Missing package_name key from heartbeat configuration') sys_path_distros = WorkingSet() package_req = Requirement.parse(package_name) distro = sys_path_distros.find(package_req) if not distro: return dict(error='no distribution found for {}'.format(package_name)) return dict(name=distro.project_name, version=distro.version)
Package name should be searched through the same distros list we use for listing installed packages. get_distribution is using the global working_set which may not contain the requested package if the initialization(pkg_resources import time) happened before the project name to appear in the sys.path.
Package name should be searched through the same distros list we use for listing installed packages. get_distribution is using the global working_set which may not contain the requested package if the initialization(pkg_resources import time) happened before the project name to appear in the sys.path.
Python
mit
pbs/django-heartbeat
+ from pkg_resources import Requirement, WorkingSet + from django.conf import settings from django.core.exceptions import ImproperlyConfigured - from pkg_resources import get_distribution, DistributionNotFound def check(request): package_name = settings.HEARTBEAT.get('package_name') if not package_name: raise ImproperlyConfigured( 'Missing package_name key from heartbeat configuration') - try: - distro = get_distribution(package_name) - except DistributionNotFound: + sys_path_distros = WorkingSet() + package_req = Requirement.parse(package_name) + + distro = sys_path_distros.find(package_req) + if not distro: return dict(error='no distribution found for {}'.format(package_name)) return dict(name=distro.project_name, version=distro.version)
Package name should be searched through the same distros list we use for listing installed packages. get_distribution is using the global working_set which may not contain the requested package if the initialization(pkg_resources import time) happened before the project name to appear in the sys.path.
## Code Before: from django.conf import settings from django.core.exceptions import ImproperlyConfigured from pkg_resources import get_distribution, DistributionNotFound def check(request): package_name = settings.HEARTBEAT.get('package_name') if not package_name: raise ImproperlyConfigured( 'Missing package_name key from heartbeat configuration') try: distro = get_distribution(package_name) except DistributionNotFound: return dict(error='no distribution found for {}'.format(package_name)) return dict(name=distro.project_name, version=distro.version) ## Instruction: Package name should be searched through the same distros list we use for listing installed packages. get_distribution is using the global working_set which may not contain the requested package if the initialization(pkg_resources import time) happened before the project name to appear in the sys.path. ## Code After: from pkg_resources import Requirement, WorkingSet from django.conf import settings from django.core.exceptions import ImproperlyConfigured def check(request): package_name = settings.HEARTBEAT.get('package_name') if not package_name: raise ImproperlyConfigured( 'Missing package_name key from heartbeat configuration') sys_path_distros = WorkingSet() package_req = Requirement.parse(package_name) distro = sys_path_distros.find(package_req) if not distro: return dict(error='no distribution found for {}'.format(package_name)) return dict(name=distro.project_name, version=distro.version)
# ... existing code ... from pkg_resources import Requirement, WorkingSet from django.conf import settings # ... modified code ... from django.core.exceptions import ImproperlyConfigured ... sys_path_distros = WorkingSet() package_req = Requirement.parse(package_name) distro = sys_path_distros.find(package_req) if not distro: return dict(error='no distribution found for {}'.format(package_name)) # ... rest of the code ...
e4b1fcf017494c22744f44bd93381b8063b30e34
eadred/tests/test_generate.py
eadred/tests/test_generate.py
import unittest from eadred.management.commands import generatedata def test_generatedata(): """Basic test to make sure function gets called.""" from testproject.testapp import sampledata assert sampledata.called == False cmd = generatedata.Command() cmd.execute() assert sampledata.called == True
from eadred.management.commands import generatedata def test_generatedata(): """Basic test to make sure function gets called.""" from testproject.testapp import sampledata assert sampledata.called == False cmd = generatedata.Command() cmd.run_from_argv(['manage.py', '']) assert sampledata.called == True
Fix test to catch options issues
Fix test to catch options issues The test should now catch the issue that was fixed in 79a453f.
Python
bsd-3-clause
willkg/django-eadred
- import unittest - from eadred.management.commands import generatedata def test_generatedata(): """Basic test to make sure function gets called.""" from testproject.testapp import sampledata assert sampledata.called == False cmd = generatedata.Command() - cmd.execute() + cmd.run_from_argv(['manage.py', '']) assert sampledata.called == True
Fix test to catch options issues
## Code Before: import unittest from eadred.management.commands import generatedata def test_generatedata(): """Basic test to make sure function gets called.""" from testproject.testapp import sampledata assert sampledata.called == False cmd = generatedata.Command() cmd.execute() assert sampledata.called == True ## Instruction: Fix test to catch options issues ## Code After: from eadred.management.commands import generatedata def test_generatedata(): """Basic test to make sure function gets called.""" from testproject.testapp import sampledata assert sampledata.called == False cmd = generatedata.Command() cmd.run_from_argv(['manage.py', '']) assert sampledata.called == True
// ... existing code ... from eadred.management.commands import generatedata // ... modified code ... cmd = generatedata.Command() cmd.run_from_argv(['manage.py', '']) assert sampledata.called == True // ... rest of the code ...
6631906fc126eadc114a7ee673194da4880dc960
flask_admin/contrib/geoa/typefmt.py
flask_admin/contrib/geoa/typefmt.py
from flask_admin.contrib.sqla.typefmt import DEFAULT_FORMATTERS as BASE_FORMATTERS import json from jinja2 import Markup from wtforms.widgets import html_params from geoalchemy2.shape import to_shape from geoalchemy2.elements import WKBElement from sqlalchemy import func from flask import current_app def geom_formatter(view, value): params = html_params(**{ "data-role": "leaflet", "disabled": "disabled", "data-width": 100, "data-height": 70, "data-geometry-type": to_shape(value).geom_type, "data-zoom": 15, }) if value.srid is -1: geojson = current_app.extensions['sqlalchemy'].db.session.scalar(func.ST_AsGeoJson(value)) else: geojson = current_app.extensions['sqlalchemy'].db.session.scalar(func.ST_AsGeoJson(value.ST_Transform( 4326))) return Markup('<textarea %s>%s</textarea>' % (params, geojson)) DEFAULT_FORMATTERS = BASE_FORMATTERS.copy() DEFAULT_FORMATTERS[WKBElement] = geom_formatter
from flask_admin.contrib.sqla.typefmt import DEFAULT_FORMATTERS as BASE_FORMATTERS from jinja2 import Markup from wtforms.widgets import html_params from geoalchemy2.shape import to_shape from geoalchemy2.elements import WKBElement from sqlalchemy import func def geom_formatter(view, value): params = html_params(**{ "data-role": "leaflet", "disabled": "disabled", "data-width": 100, "data-height": 70, "data-geometry-type": to_shape(value).geom_type, "data-zoom": 15, }) if value.srid is -1: value.srid = 4326 geojson = view.model.query.with_entities(func.ST_AsGeoJSON(value)).scalar() return Markup('<textarea %s>%s</textarea>' % (params, geojson)) DEFAULT_FORMATTERS = BASE_FORMATTERS.copy() DEFAULT_FORMATTERS[WKBElement] = geom_formatter
Remove Flask-SQLAlchemy dependency It should be noted that the declarative base still has to be configured like this:
Remove Flask-SQLAlchemy dependency It should be noted that the declarative base still has to be configured like this: ```python MyBase: query = session.query_property() ``` Also decreased code duplication and removed unused imports.
Python
bsd-3-clause
torotil/flask-admin,likaiguo/flask-admin,iurisilvio/flask-admin,toddetzel/flask-admin,mikelambert/flask-admin,lifei/flask-admin,likaiguo/flask-admin,rochacbruno/flask-admin,ArtemSerga/flask-admin,closeio/flask-admin,betterlife/flask-admin,jschneier/flask-admin,torotil/flask-admin,toddetzel/flask-admin,closeio/flask-admin,jmagnusson/flask-admin,toddetzel/flask-admin,iurisilvio/flask-admin,quokkaproject/flask-admin,torotil/flask-admin,flask-admin/flask-admin,quokkaproject/flask-admin,betterlife/flask-admin,jschneier/flask-admin,quokkaproject/flask-admin,mikelambert/flask-admin,jmagnusson/flask-admin,flask-admin/flask-admin,mikelambert/flask-admin,iurisilvio/flask-admin,likaiguo/flask-admin,jschneier/flask-admin,flask-admin/flask-admin,rochacbruno/flask-admin,mikelambert/flask-admin,lifei/flask-admin,jschneier/flask-admin,betterlife/flask-admin,rochacbruno/flask-admin,jmagnusson/flask-admin,rochacbruno/flask-admin,jmagnusson/flask-admin,toddetzel/flask-admin,ArtemSerga/flask-admin,flask-admin/flask-admin,iurisilvio/flask-admin,betterlife/flask-admin,ArtemSerga/flask-admin,quokkaproject/flask-admin,closeio/flask-admin,likaiguo/flask-admin,closeio/flask-admin,lifei/flask-admin,lifei/flask-admin,torotil/flask-admin,ArtemSerga/flask-admin
from flask_admin.contrib.sqla.typefmt import DEFAULT_FORMATTERS as BASE_FORMATTERS - import json from jinja2 import Markup from wtforms.widgets import html_params from geoalchemy2.shape import to_shape from geoalchemy2.elements import WKBElement from sqlalchemy import func - from flask import current_app def geom_formatter(view, value): params = html_params(**{ "data-role": "leaflet", "disabled": "disabled", "data-width": 100, "data-height": 70, "data-geometry-type": to_shape(value).geom_type, "data-zoom": 15, }) if value.srid is -1: + value.srid = 4326 + geojson = view.model.query.with_entities(func.ST_AsGeoJSON(value)).scalar() - geojson = current_app.extensions['sqlalchemy'].db.session.scalar(func.ST_AsGeoJson(value)) - else: - geojson = current_app.extensions['sqlalchemy'].db.session.scalar(func.ST_AsGeoJson(value.ST_Transform( 4326))) return Markup('<textarea %s>%s</textarea>' % (params, geojson)) DEFAULT_FORMATTERS = BASE_FORMATTERS.copy() DEFAULT_FORMATTERS[WKBElement] = geom_formatter
Remove Flask-SQLAlchemy dependency It should be noted that the declarative base still has to be configured like this:
## Code Before: from flask_admin.contrib.sqla.typefmt import DEFAULT_FORMATTERS as BASE_FORMATTERS import json from jinja2 import Markup from wtforms.widgets import html_params from geoalchemy2.shape import to_shape from geoalchemy2.elements import WKBElement from sqlalchemy import func from flask import current_app def geom_formatter(view, value): params = html_params(**{ "data-role": "leaflet", "disabled": "disabled", "data-width": 100, "data-height": 70, "data-geometry-type": to_shape(value).geom_type, "data-zoom": 15, }) if value.srid is -1: geojson = current_app.extensions['sqlalchemy'].db.session.scalar(func.ST_AsGeoJson(value)) else: geojson = current_app.extensions['sqlalchemy'].db.session.scalar(func.ST_AsGeoJson(value.ST_Transform( 4326))) return Markup('<textarea %s>%s</textarea>' % (params, geojson)) DEFAULT_FORMATTERS = BASE_FORMATTERS.copy() DEFAULT_FORMATTERS[WKBElement] = geom_formatter ## Instruction: Remove Flask-SQLAlchemy dependency It should be noted that the declarative base still has to be configured like this: ## Code After: from flask_admin.contrib.sqla.typefmt import DEFAULT_FORMATTERS as BASE_FORMATTERS from jinja2 import Markup from wtforms.widgets import html_params from geoalchemy2.shape import to_shape from geoalchemy2.elements import WKBElement from sqlalchemy import func def geom_formatter(view, value): params = html_params(**{ "data-role": "leaflet", "disabled": "disabled", "data-width": 100, "data-height": 70, "data-geometry-type": to_shape(value).geom_type, "data-zoom": 15, }) if value.srid is -1: value.srid = 4326 geojson = view.model.query.with_entities(func.ST_AsGeoJSON(value)).scalar() return Markup('<textarea %s>%s</textarea>' % (params, geojson)) DEFAULT_FORMATTERS = BASE_FORMATTERS.copy() DEFAULT_FORMATTERS[WKBElement] = geom_formatter
# ... existing code ... from flask_admin.contrib.sqla.typefmt import DEFAULT_FORMATTERS as BASE_FORMATTERS from jinja2 import Markup # ... modified code ... from sqlalchemy import func ... if value.srid is -1: value.srid = 4326 geojson = view.model.query.with_entities(func.ST_AsGeoJSON(value)).scalar() return Markup('<textarea %s>%s</textarea>' % (params, geojson)) # ... rest of the code ...
0887e200f31edd8d61e0dd1d3fefae7e828c9269
mindbender/maya/plugins/validate_single_assembly.py
mindbender/maya/plugins/validate_single_assembly.py
import pyblish.api class ValidateMindbenderSingleAssembly(pyblish.api.InstancePlugin): """Each asset must have a single top-level group The given instance is test-exported, along with construction history to test whether more than 1 top-level DAG node would be included in the exported file. """ label = "Validate Single Assembly" order = pyblish.api.ValidatorOrder hosts = ["maya"] families = ["mindbender.model", "mindbender.rig"] def process(self, instance): from maya import cmds from mindbender import maya with maya.maintained_selection(): cmds.select(instance, replace=True) nodes = cmds.file( constructionHistory=True, exportSelected=True, preview=True, force=True, ) assemblies = cmds.ls(nodes, assemblies=True) if not assemblies: raise Exception("No assembly found.") if len(assemblies) != 1: assemblies = '"%s"' % '", "'.join(assemblies) raise Exception( "Multiple assemblies found: %s" % assemblies )
import pyblish.api class SelectAssemblies(pyblish.api.Action): label = "Select Assemblies" on = "failed" def process(self, context, plugin): from maya import cmds cmds.select(plugin.assemblies) class ValidateMindbenderSingleAssembly(pyblish.api.InstancePlugin): """Each asset must have a single top-level group The given instance is test-exported, along with construction history to test whether more than 1 top-level DAG node would be included in the exported file. """ label = "Validate Single Assembly" order = pyblish.api.ValidatorOrder hosts = ["maya"] families = ["mindbender.model", "mindbender.rig"] actions = [ pyblish.api.Category("Actions"), SelectAssemblies, ] assemblies = [] def process(self, instance): from maya import cmds from mindbender import maya with maya.maintained_selection(): cmds.select(instance, replace=True) nodes = cmds.file( constructionHistory=True, exportSelected=True, preview=True, force=True, ) self.assemblies[:] = cmds.ls(nodes, assemblies=True) if not self.assemblies: raise Exception("No assembly found.") if len(self.assemblies) != 1: self.assemblies = '"%s"' % '", "'.join(self.assemblies) raise Exception( "Multiple assemblies found: %s" % self.assemblies )
Add action to select the multiple assemblies.
Add action to select the multiple assemblies.
Python
mit
getavalon/core,MoonShineVFX/core,MoonShineVFX/core,mindbender-studio/core,mindbender-studio/core,getavalon/core
import pyblish.api + + + class SelectAssemblies(pyblish.api.Action): + label = "Select Assemblies" + on = "failed" + + def process(self, context, plugin): + from maya import cmds + cmds.select(plugin.assemblies) class ValidateMindbenderSingleAssembly(pyblish.api.InstancePlugin): """Each asset must have a single top-level group The given instance is test-exported, along with construction history to test whether more than 1 top-level DAG node would be included in the exported file. """ label = "Validate Single Assembly" order = pyblish.api.ValidatorOrder hosts = ["maya"] families = ["mindbender.model", "mindbender.rig"] + actions = [ + pyblish.api.Category("Actions"), + SelectAssemblies, + ] + + assemblies = [] def process(self, instance): from maya import cmds from mindbender import maya with maya.maintained_selection(): cmds.select(instance, replace=True) nodes = cmds.file( constructionHistory=True, exportSelected=True, preview=True, force=True, ) - assemblies = cmds.ls(nodes, assemblies=True) + self.assemblies[:] = cmds.ls(nodes, assemblies=True) - if not assemblies: + if not self.assemblies: raise Exception("No assembly found.") - if len(assemblies) != 1: + if len(self.assemblies) != 1: - assemblies = '"%s"' % '", "'.join(assemblies) + self.assemblies = '"%s"' % '", "'.join(self.assemblies) raise Exception( - "Multiple assemblies found: %s" % assemblies + "Multiple assemblies found: %s" % self.assemblies )
Add action to select the multiple assemblies.
## Code Before: import pyblish.api class ValidateMindbenderSingleAssembly(pyblish.api.InstancePlugin): """Each asset must have a single top-level group The given instance is test-exported, along with construction history to test whether more than 1 top-level DAG node would be included in the exported file. """ label = "Validate Single Assembly" order = pyblish.api.ValidatorOrder hosts = ["maya"] families = ["mindbender.model", "mindbender.rig"] def process(self, instance): from maya import cmds from mindbender import maya with maya.maintained_selection(): cmds.select(instance, replace=True) nodes = cmds.file( constructionHistory=True, exportSelected=True, preview=True, force=True, ) assemblies = cmds.ls(nodes, assemblies=True) if not assemblies: raise Exception("No assembly found.") if len(assemblies) != 1: assemblies = '"%s"' % '", "'.join(assemblies) raise Exception( "Multiple assemblies found: %s" % assemblies ) ## Instruction: Add action to select the multiple assemblies. ## Code After: import pyblish.api class SelectAssemblies(pyblish.api.Action): label = "Select Assemblies" on = "failed" def process(self, context, plugin): from maya import cmds cmds.select(plugin.assemblies) class ValidateMindbenderSingleAssembly(pyblish.api.InstancePlugin): """Each asset must have a single top-level group The given instance is test-exported, along with construction history to test whether more than 1 top-level DAG node would be included in the exported file. """ label = "Validate Single Assembly" order = pyblish.api.ValidatorOrder hosts = ["maya"] families = ["mindbender.model", "mindbender.rig"] actions = [ pyblish.api.Category("Actions"), SelectAssemblies, ] assemblies = [] def process(self, instance): from maya import cmds from mindbender import maya with maya.maintained_selection(): cmds.select(instance, replace=True) nodes = cmds.file( constructionHistory=True, exportSelected=True, preview=True, force=True, ) self.assemblies[:] = cmds.ls(nodes, assemblies=True) if not self.assemblies: raise Exception("No assembly found.") if len(self.assemblies) != 1: self.assemblies = '"%s"' % '", "'.join(self.assemblies) raise Exception( "Multiple assemblies found: %s" % self.assemblies )
// ... existing code ... import pyblish.api class SelectAssemblies(pyblish.api.Action): label = "Select Assemblies" on = "failed" def process(self, context, plugin): from maya import cmds cmds.select(plugin.assemblies) // ... modified code ... families = ["mindbender.model", "mindbender.rig"] actions = [ pyblish.api.Category("Actions"), SelectAssemblies, ] assemblies = [] ... self.assemblies[:] = cmds.ls(nodes, assemblies=True) if not self.assemblies: raise Exception("No assembly found.") ... if len(self.assemblies) != 1: self.assemblies = '"%s"' % '", "'.join(self.assemblies) raise Exception( "Multiple assemblies found: %s" % self.assemblies ) // ... rest of the code ...
39f44c926eb16f2cd57fa344318bce652b158a3a
tests/shape/test_basic.py
tests/shape/test_basic.py
import pytest from unittest import TestCase from stylo.shape import Ellipse, Circle, Rectangle, Square from stylo.testing.shape import BaseShapeTest @pytest.mark.shape class TestEllipse(TestCase, BaseShapeTest): """Tests for the :code:`Ellipse` shape.""" def setUp(self): self.shape = Ellipse(0, 0, 1 / 2, 1 / 3, 0.6) @pytest.mark.shape class TestCircle(TestCase, BaseShapeTest): """Tests for the :code:`Circle` shape.""" def setUp(self): self.shape = Circle(0, 0, 0.5) @pytest.mark.shape class TestRectangle(TestCase, BaseShapeTest): """Tests for the :code:`Rectangle` shape.""" def setUp(self): self.shape = Rectangle(0, 0, 0.6, 0.3) @pytest.mark.shape class TestSquare(TestCase, BaseShapeTest): """Tests for the :code:`Square` shape.""" def setUp(self): self.shape = Square(0, 0, 0.75)
import pytest from unittest import TestCase from stylo.shape import Ellipse, Circle, Rectangle, Square, Triangle from stylo.testing.shape import BaseShapeTest @pytest.mark.shape class TestEllipse(TestCase, BaseShapeTest): """Tests for the :code:`Ellipse` shape.""" def setUp(self): self.shape = Ellipse(0, 0, 1 / 2, 1 / 3, 0.6) @pytest.mark.shape class TestCircle(TestCase, BaseShapeTest): """Tests for the :code:`Circle` shape.""" def setUp(self): self.shape = Circle(0, 0, 0.5) @pytest.mark.shape class TestRectangle(TestCase, BaseShapeTest): """Tests for the :code:`Rectangle` shape.""" def setUp(self): self.shape = Rectangle(0, 0, 0.6, 0.3) @pytest.mark.shape class TestSquare(TestCase, BaseShapeTest): """Tests for the :code:`Square` shape.""" def setUp(self): self.shape = Square(0, 0, 0.75) @pytest.mark.shape class TestTriangle(TestCase, BaseShapeTest): """Tests for the :code:`Triangle` shape.""" def setUp(self): self.shape = Triangle((1,.5),(.2,1),(.4,.5))
Add Triangle to shape tests
Add Triangle to shape tests
Python
mit
alcarney/stylo,alcarney/stylo
import pytest from unittest import TestCase - from stylo.shape import Ellipse, Circle, Rectangle, Square + from stylo.shape import Ellipse, Circle, Rectangle, Square, Triangle from stylo.testing.shape import BaseShapeTest @pytest.mark.shape class TestEllipse(TestCase, BaseShapeTest): """Tests for the :code:`Ellipse` shape.""" def setUp(self): self.shape = Ellipse(0, 0, 1 / 2, 1 / 3, 0.6) @pytest.mark.shape class TestCircle(TestCase, BaseShapeTest): """Tests for the :code:`Circle` shape.""" def setUp(self): self.shape = Circle(0, 0, 0.5) @pytest.mark.shape class TestRectangle(TestCase, BaseShapeTest): """Tests for the :code:`Rectangle` shape.""" def setUp(self): self.shape = Rectangle(0, 0, 0.6, 0.3) @pytest.mark.shape class TestSquare(TestCase, BaseShapeTest): """Tests for the :code:`Square` shape.""" def setUp(self): self.shape = Square(0, 0, 0.75) + @pytest.mark.shape + class TestTriangle(TestCase, BaseShapeTest): + """Tests for the :code:`Triangle` shape.""" + + def setUp(self): + self.shape = Triangle((1,.5),(.2,1),(.4,.5)) +
Add Triangle to shape tests
## Code Before: import pytest from unittest import TestCase from stylo.shape import Ellipse, Circle, Rectangle, Square from stylo.testing.shape import BaseShapeTest @pytest.mark.shape class TestEllipse(TestCase, BaseShapeTest): """Tests for the :code:`Ellipse` shape.""" def setUp(self): self.shape = Ellipse(0, 0, 1 / 2, 1 / 3, 0.6) @pytest.mark.shape class TestCircle(TestCase, BaseShapeTest): """Tests for the :code:`Circle` shape.""" def setUp(self): self.shape = Circle(0, 0, 0.5) @pytest.mark.shape class TestRectangle(TestCase, BaseShapeTest): """Tests for the :code:`Rectangle` shape.""" def setUp(self): self.shape = Rectangle(0, 0, 0.6, 0.3) @pytest.mark.shape class TestSquare(TestCase, BaseShapeTest): """Tests for the :code:`Square` shape.""" def setUp(self): self.shape = Square(0, 0, 0.75) ## Instruction: Add Triangle to shape tests ## Code After: import pytest from unittest import TestCase from stylo.shape import Ellipse, Circle, Rectangle, Square, Triangle from stylo.testing.shape import BaseShapeTest @pytest.mark.shape class TestEllipse(TestCase, BaseShapeTest): """Tests for the :code:`Ellipse` shape.""" def setUp(self): self.shape = Ellipse(0, 0, 1 / 2, 1 / 3, 0.6) @pytest.mark.shape class TestCircle(TestCase, BaseShapeTest): """Tests for the :code:`Circle` shape.""" def setUp(self): self.shape = Circle(0, 0, 0.5) @pytest.mark.shape class TestRectangle(TestCase, BaseShapeTest): """Tests for the :code:`Rectangle` shape.""" def setUp(self): self.shape = Rectangle(0, 0, 0.6, 0.3) @pytest.mark.shape class TestSquare(TestCase, BaseShapeTest): """Tests for the :code:`Square` shape.""" def setUp(self): self.shape = Square(0, 0, 0.75) @pytest.mark.shape class TestTriangle(TestCase, BaseShapeTest): """Tests for the :code:`Triangle` shape.""" def setUp(self): self.shape = Triangle((1,.5),(.2,1),(.4,.5))
# ... existing code ... from stylo.shape import Ellipse, Circle, Rectangle, Square, Triangle from stylo.testing.shape import BaseShapeTest # ... modified code ... self.shape = Square(0, 0, 0.75) @pytest.mark.shape class TestTriangle(TestCase, BaseShapeTest): """Tests for the :code:`Triangle` shape.""" def setUp(self): self.shape = Triangle((1,.5),(.2,1),(.4,.5)) # ... rest of the code ...
dfdeaf536466cfa8003af4cd5341d1d7127ea6b7
py/_test_py2go.py
py/_test_py2go.py
import datetime def return_true(): return True def return_false(): return False def return_int(): return 123 def return_float(): return 1.0 def return_string(): return "ABC" def return_bytearray(): return bytearray('abcdefg') def return_array(): return [1, 2, {"key": 3}] def return_map(): return {"key1": 123, "key2": "str"} def return_nested_map(): return {"key1": {"key2": 123}} def return_none(): return None def return_timestamp(): return datetime.datetime(2015, 4, 1, 14, 27, 0, 500*1000, None)
import datetime def return_true(): return True def return_false(): return False def return_int(): return 123 def return_float(): return 1.0 def return_string(): return "ABC" def return_bytearray(): return bytearray('abcdefg') def return_array(): return [1, 2, {"key": 3}] def return_map(): return {"key1": 123, "key2": "str"} def return_nested_map(): return {"key1": {"key2": 123}} def return_none(): return None def return_timestamp(): return datetime.datetime(2015, 4, 1, 14, 27, 0, 500*1000, None)
Update python script for pep8 style
Update python script for pep8 style
Python
mit
sensorbee/py,sensorbee/py
import datetime + def return_true(): return True + def return_false(): return False + def return_int(): return 123 + def return_float(): return 1.0 + def return_string(): return "ABC" + def return_bytearray(): return bytearray('abcdefg') + def return_array(): return [1, 2, {"key": 3}] + def return_map(): return {"key1": 123, "key2": "str"} + def return_nested_map(): return {"key1": {"key2": 123}} + def return_none(): return None + def return_timestamp(): return datetime.datetime(2015, 4, 1, 14, 27, 0, 500*1000, None)
Update python script for pep8 style
## Code Before: import datetime def return_true(): return True def return_false(): return False def return_int(): return 123 def return_float(): return 1.0 def return_string(): return "ABC" def return_bytearray(): return bytearray('abcdefg') def return_array(): return [1, 2, {"key": 3}] def return_map(): return {"key1": 123, "key2": "str"} def return_nested_map(): return {"key1": {"key2": 123}} def return_none(): return None def return_timestamp(): return datetime.datetime(2015, 4, 1, 14, 27, 0, 500*1000, None) ## Instruction: Update python script for pep8 style ## Code After: import datetime def return_true(): return True def return_false(): return False def return_int(): return 123 def return_float(): return 1.0 def return_string(): return "ABC" def return_bytearray(): return bytearray('abcdefg') def return_array(): return [1, 2, {"key": 3}] def return_map(): return {"key1": 123, "key2": "str"} def return_nested_map(): return {"key1": {"key2": 123}} def return_none(): return None def return_timestamp(): return datetime.datetime(2015, 4, 1, 14, 27, 0, 500*1000, None)
// ... existing code ... import datetime // ... modified code ... def return_false(): ... return False ... def return_float(): ... return 1.0 ... def return_bytearray(): ... return bytearray('abcdefg') ... def return_map(): ... return {"key1": 123, "key2": "str"} ... def return_none(): ... def return_timestamp(): // ... rest of the code ...
4f6400e9ecf9bbc1cee62567673c619f9a975f95
lib/python/opendiamond/bundle.py
lib/python/opendiamond/bundle.py
import os import subprocess import zipfile def make_zipfile(path, manifest, files): '''manifest is a string, files is a dict of filename => path pairs''' if os.path.exists(path): raise Exception("Refusing to clobber destination file") zip = zipfile.ZipFile(path, mode = 'w', compression = zipfile.ZIP_DEFLATED) zip.writestr('opendiamond-manifest.txt', manifest) for name, path in files.items(): zip.write(path, name) zip.close() def bundle_python(out, filter, blob = None): try: proc = subprocess.Popen(['python', os.path.realpath(filter), '--get-manifest'], stdout = subprocess.PIPE) except OSError: raise Exception("Couldn't execute filter program") manifest = proc.communicate()[0] if proc.returncode != 0: raise Exception("Couldn't generate filter manifest") files = {'filter': filter} if blob is not None: files['blob'] = blob make_zipfile(out, manifest, files)
import os import subprocess import zipfile def make_zipfile(path, manifest, files): '''manifest is a string, files is a dict of filename => path pairs''' zip = zipfile.ZipFile(path, mode = 'w', compression = zipfile.ZIP_DEFLATED) zip.writestr('opendiamond-manifest.txt', manifest) for name, path in files.items(): zip.write(path, name) zip.close() def bundle_python(out, filter, blob = None): try: proc = subprocess.Popen(['python', os.path.realpath(filter), '--get-manifest'], stdout = subprocess.PIPE) except OSError: raise Exception("Couldn't execute filter program") manifest = proc.communicate()[0] if proc.returncode != 0: raise Exception("Couldn't generate filter manifest") files = {'filter': filter} if blob is not None: files['blob'] = blob make_zipfile(out, manifest, files)
Allow make_zipfile() to clobber the destination file
Allow make_zipfile() to clobber the destination file
Python
epl-1.0
cmusatyalab/opendiamond,cmusatyalab/opendiamond,cmusatyalab/opendiamond,cmusatyalab/opendiamond,cmusatyalab/opendiamond
import os import subprocess import zipfile def make_zipfile(path, manifest, files): '''manifest is a string, files is a dict of filename => path pairs''' - if os.path.exists(path): - raise Exception("Refusing to clobber destination file") zip = zipfile.ZipFile(path, mode = 'w', compression = zipfile.ZIP_DEFLATED) zip.writestr('opendiamond-manifest.txt', manifest) for name, path in files.items(): zip.write(path, name) zip.close() def bundle_python(out, filter, blob = None): try: proc = subprocess.Popen(['python', os.path.realpath(filter), '--get-manifest'], stdout = subprocess.PIPE) except OSError: raise Exception("Couldn't execute filter program") manifest = proc.communicate()[0] if proc.returncode != 0: raise Exception("Couldn't generate filter manifest") files = {'filter': filter} if blob is not None: files['blob'] = blob make_zipfile(out, manifest, files)
Allow make_zipfile() to clobber the destination file
## Code Before: import os import subprocess import zipfile def make_zipfile(path, manifest, files): '''manifest is a string, files is a dict of filename => path pairs''' if os.path.exists(path): raise Exception("Refusing to clobber destination file") zip = zipfile.ZipFile(path, mode = 'w', compression = zipfile.ZIP_DEFLATED) zip.writestr('opendiamond-manifest.txt', manifest) for name, path in files.items(): zip.write(path, name) zip.close() def bundle_python(out, filter, blob = None): try: proc = subprocess.Popen(['python', os.path.realpath(filter), '--get-manifest'], stdout = subprocess.PIPE) except OSError: raise Exception("Couldn't execute filter program") manifest = proc.communicate()[0] if proc.returncode != 0: raise Exception("Couldn't generate filter manifest") files = {'filter': filter} if blob is not None: files['blob'] = blob make_zipfile(out, manifest, files) ## Instruction: Allow make_zipfile() to clobber the destination file ## Code After: import os import subprocess import zipfile def make_zipfile(path, manifest, files): '''manifest is a string, files is a dict of filename => path pairs''' zip = zipfile.ZipFile(path, mode = 'w', compression = zipfile.ZIP_DEFLATED) zip.writestr('opendiamond-manifest.txt', manifest) for name, path in files.items(): zip.write(path, name) zip.close() def bundle_python(out, filter, blob = None): try: proc = subprocess.Popen(['python', os.path.realpath(filter), '--get-manifest'], stdout = subprocess.PIPE) except OSError: raise Exception("Couldn't execute filter program") manifest = proc.communicate()[0] if proc.returncode != 0: raise Exception("Couldn't generate filter manifest") files = {'filter': filter} if blob is not None: files['blob'] = blob make_zipfile(out, manifest, files)
... '''manifest is a string, files is a dict of filename => path pairs''' zip = zipfile.ZipFile(path, mode = 'w', compression = zipfile.ZIP_DEFLATED) ...
eda7125f28a9da3c5ccefb3ec5c604ddd23d3034
plantcv/plantcv/plot_image.py
plantcv/plantcv/plot_image.py
import cv2 import numpy import matplotlib from plantcv.plantcv import params from matplotlib import pyplot as plt from plantcv.plantcv import fatal_error def plot_image(img, cmap=None): """Plot an image to the screen. :param img: numpy.ndarray :param cmap: str :return: """ image_type = type(img) dimensions = numpy.shape(img) if image_type == numpy.ndarray: matplotlib.rcParams['figure.dpi'] = params.dpi # If the image is color then OpenCV stores it as BGR, we plot it as RGB if len(dimensions) == 3: plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) plt.show() elif cmap is None and len(dimensions) == 2: plt.imshow(img, cmap="gray") plt.show() elif cmap is not None and len(dimensions) == 2: plt.imshow(img, cmap=cmap) plt.show() elif image_type == matplotlib.figure.Figure: fatal_error("Error, matplotlib Figure not supported. Instead try running without plot_image.") # Plot if the image is a plotnine ggplot image elif str(image_type) == "<class 'plotnine.ggplot.ggplot'>": print(img)
import cv2 import numpy import matplotlib from plantcv.plantcv import params from matplotlib import pyplot as plt from plantcv.plantcv import fatal_error def plot_image(img, cmap=None): """Plot an image to the screen. :param img: numpy.ndarray :param cmap: str :return: """ image_type = type(img) dimensions = numpy.shape(img) if image_type == numpy.ndarray: matplotlib.rcParams['figure.dpi'] = params.dpi # If the image is color then OpenCV stores it as BGR, we plot it as RGB if len(dimensions) == 3: fig = plt.figure() plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) plt.show() elif cmap is None and len(dimensions) == 2: fig = plt.figure() plt.imshow(img, cmap="gray") plt.show() elif cmap is not None and len(dimensions) == 2: fig = plt.figure() plt.imshow(img, cmap=cmap) plt.show() elif image_type == matplotlib.figure.Figure: fatal_error("Error, matplotlib Figure not supported. Instead try running without plot_image.") # Plot if the image is a plotnine ggplot image elif str(image_type) == "<class 'plotnine.ggplot.ggplot'>": print(img)
Create a new figure for each plot
Create a new figure for each plot
Python
mit
danforthcenter/plantcv,stiphyMT/plantcv,danforthcenter/plantcv,danforthcenter/plantcv,stiphyMT/plantcv,stiphyMT/plantcv
import cv2 import numpy import matplotlib from plantcv.plantcv import params from matplotlib import pyplot as plt from plantcv.plantcv import fatal_error def plot_image(img, cmap=None): """Plot an image to the screen. :param img: numpy.ndarray :param cmap: str :return: """ image_type = type(img) dimensions = numpy.shape(img) if image_type == numpy.ndarray: matplotlib.rcParams['figure.dpi'] = params.dpi # If the image is color then OpenCV stores it as BGR, we plot it as RGB if len(dimensions) == 3: + fig = plt.figure() plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) plt.show() elif cmap is None and len(dimensions) == 2: + fig = plt.figure() plt.imshow(img, cmap="gray") plt.show() elif cmap is not None and len(dimensions) == 2: + fig = plt.figure() plt.imshow(img, cmap=cmap) plt.show() elif image_type == matplotlib.figure.Figure: fatal_error("Error, matplotlib Figure not supported. Instead try running without plot_image.") # Plot if the image is a plotnine ggplot image elif str(image_type) == "<class 'plotnine.ggplot.ggplot'>": print(img)
Create a new figure for each plot
## Code Before: import cv2 import numpy import matplotlib from plantcv.plantcv import params from matplotlib import pyplot as plt from plantcv.plantcv import fatal_error def plot_image(img, cmap=None): """Plot an image to the screen. :param img: numpy.ndarray :param cmap: str :return: """ image_type = type(img) dimensions = numpy.shape(img) if image_type == numpy.ndarray: matplotlib.rcParams['figure.dpi'] = params.dpi # If the image is color then OpenCV stores it as BGR, we plot it as RGB if len(dimensions) == 3: plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) plt.show() elif cmap is None and len(dimensions) == 2: plt.imshow(img, cmap="gray") plt.show() elif cmap is not None and len(dimensions) == 2: plt.imshow(img, cmap=cmap) plt.show() elif image_type == matplotlib.figure.Figure: fatal_error("Error, matplotlib Figure not supported. Instead try running without plot_image.") # Plot if the image is a plotnine ggplot image elif str(image_type) == "<class 'plotnine.ggplot.ggplot'>": print(img) ## Instruction: Create a new figure for each plot ## Code After: import cv2 import numpy import matplotlib from plantcv.plantcv import params from matplotlib import pyplot as plt from plantcv.plantcv import fatal_error def plot_image(img, cmap=None): """Plot an image to the screen. :param img: numpy.ndarray :param cmap: str :return: """ image_type = type(img) dimensions = numpy.shape(img) if image_type == numpy.ndarray: matplotlib.rcParams['figure.dpi'] = params.dpi # If the image is color then OpenCV stores it as BGR, we plot it as RGB if len(dimensions) == 3: fig = plt.figure() plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) plt.show() elif cmap is None and len(dimensions) == 2: fig = plt.figure() plt.imshow(img, cmap="gray") plt.show() elif cmap is not None and len(dimensions) == 2: fig = plt.figure() plt.imshow(img, cmap=cmap) plt.show() elif image_type == matplotlib.figure.Figure: fatal_error("Error, matplotlib Figure not supported. Instead try running without plot_image.") # Plot if the image is a plotnine ggplot image elif str(image_type) == "<class 'plotnine.ggplot.ggplot'>": print(img)
// ... existing code ... if len(dimensions) == 3: fig = plt.figure() plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) // ... modified code ... elif cmap is None and len(dimensions) == 2: fig = plt.figure() plt.imshow(img, cmap="gray") ... elif cmap is not None and len(dimensions) == 2: fig = plt.figure() plt.imshow(img, cmap=cmap) // ... rest of the code ...
b2ffa1616c1ca31916047e1524e73395f0f45936
bokeh/charts/tests/test_stats.py
bokeh/charts/tests/test_stats.py
import pytest from bokeh.charts.stats import Bins from bokeh.models import ColumnDataSource @pytest.fixture def ds(test_data): return ColumnDataSource(test_data.auto_data) def test_explicit_bin_count(ds): b = Bins(source=ds, column='mpg', bin_count=2) assert len(b.bins) == 2 def test_auto_bin_count(ds): b = Bins(source=ds, column='mpg', bin_count=2) assert len(b.bins) == 2
import pytest from bokeh.charts.stats import Bins from bokeh.models import ColumnDataSource @pytest.fixture def ds(test_data): return ColumnDataSource(test_data.auto_data) def test_explicit_bin_count(ds): b = Bins(source=ds, column='mpg', bin_count=2) assert len(b.bins) == 2 def test_auto_bin_count(ds): b = Bins(source=ds, column='mpg') assert len(b.bins) == 12
Add auto binning test to stats.
Add auto binning test to stats.
Python
bsd-3-clause
percyfal/bokeh,msarahan/bokeh,schoolie/bokeh,mindriot101/bokeh,Karel-van-de-Plassche/bokeh,timsnyder/bokeh,dennisobrien/bokeh,aiguofer/bokeh,phobson/bokeh,ericmjl/bokeh,phobson/bokeh,draperjames/bokeh,timsnyder/bokeh,stonebig/bokeh,timsnyder/bokeh,stonebig/bokeh,ptitjano/bokeh,maxalbert/bokeh,jakirkham/bokeh,DuCorey/bokeh,draperjames/bokeh,bokeh/bokeh,draperjames/bokeh,schoolie/bokeh,DuCorey/bokeh,schoolie/bokeh,philippjfr/bokeh,DuCorey/bokeh,percyfal/bokeh,philippjfr/bokeh,maxalbert/bokeh,msarahan/bokeh,jakirkham/bokeh,htygithub/bokeh,dennisobrien/bokeh,jakirkham/bokeh,KasperPRasmussen/bokeh,bokeh/bokeh,aiguofer/bokeh,schoolie/bokeh,schoolie/bokeh,dennisobrien/bokeh,DuCorey/bokeh,quasiben/bokeh,ericmjl/bokeh,Karel-van-de-Plassche/bokeh,timsnyder/bokeh,azjps/bokeh,ericmjl/bokeh,bokeh/bokeh,aiguofer/bokeh,bokeh/bokeh,mindriot101/bokeh,htygithub/bokeh,maxalbert/bokeh,quasiben/bokeh,Karel-van-de-Plassche/bokeh,dennisobrien/bokeh,justacec/bokeh,htygithub/bokeh,clairetang6/bokeh,azjps/bokeh,ptitjano/bokeh,justacec/bokeh,aavanian/bokeh,ptitjano/bokeh,ptitjano/bokeh,aiguofer/bokeh,ptitjano/bokeh,bokeh/bokeh,dennisobrien/bokeh,percyfal/bokeh,draperjames/bokeh,KasperPRasmussen/bokeh,aavanian/bokeh,justacec/bokeh,phobson/bokeh,rs2/bokeh,philippjfr/bokeh,maxalbert/bokeh,stonebig/bokeh,rs2/bokeh,azjps/bokeh,phobson/bokeh,rs2/bokeh,Karel-van-de-Plassche/bokeh,msarahan/bokeh,philippjfr/bokeh,aavanian/bokeh,htygithub/bokeh,azjps/bokeh,draperjames/bokeh,jakirkham/bokeh,KasperPRasmussen/bokeh,DuCorey/bokeh,rs2/bokeh,azjps/bokeh,mindriot101/bokeh,justacec/bokeh,percyfal/bokeh,clairetang6/bokeh,KasperPRasmussen/bokeh,jakirkham/bokeh,percyfal/bokeh,stonebig/bokeh,msarahan/bokeh,ericmjl/bokeh,aavanian/bokeh,KasperPRasmussen/bokeh,clairetang6/bokeh,rs2/bokeh,aavanian/bokeh,clairetang6/bokeh,mindriot101/bokeh,ericmjl/bokeh,quasiben/bokeh,phobson/bokeh,philippjfr/bokeh,timsnyder/bokeh,aiguofer/bokeh,Karel-van-de-Plassche/bokeh
import pytest from bokeh.charts.stats import Bins from bokeh.models import ColumnDataSource @pytest.fixture def ds(test_data): return ColumnDataSource(test_data.auto_data) def test_explicit_bin_count(ds): b = Bins(source=ds, column='mpg', bin_count=2) assert len(b.bins) == 2 def test_auto_bin_count(ds): - b = Bins(source=ds, column='mpg', bin_count=2) + b = Bins(source=ds, column='mpg') - assert len(b.bins) == 2 + assert len(b.bins) == 12 +
Add auto binning test to stats.
## Code Before: import pytest from bokeh.charts.stats import Bins from bokeh.models import ColumnDataSource @pytest.fixture def ds(test_data): return ColumnDataSource(test_data.auto_data) def test_explicit_bin_count(ds): b = Bins(source=ds, column='mpg', bin_count=2) assert len(b.bins) == 2 def test_auto_bin_count(ds): b = Bins(source=ds, column='mpg', bin_count=2) assert len(b.bins) == 2 ## Instruction: Add auto binning test to stats. ## Code After: import pytest from bokeh.charts.stats import Bins from bokeh.models import ColumnDataSource @pytest.fixture def ds(test_data): return ColumnDataSource(test_data.auto_data) def test_explicit_bin_count(ds): b = Bins(source=ds, column='mpg', bin_count=2) assert len(b.bins) == 2 def test_auto_bin_count(ds): b = Bins(source=ds, column='mpg') assert len(b.bins) == 12
// ... existing code ... def test_auto_bin_count(ds): b = Bins(source=ds, column='mpg') assert len(b.bins) == 12 // ... rest of the code ...
b2d06e068fbc7bad9ed0c8f22e751b6bb46d353d
dependencies/contrib/_django.py
dependencies/contrib/_django.py
from __future__ import absolute_import from collections import OrderedDict from dependencies import this from django.views.generic import View def view(injector): """Create Django class-based view from injector class.""" handler = create_handler(View) apply_http_methods(handler, injector) handler.http_method_names = list(handler.http_method_names.keys()) return injector.let(as_view=handler.as_view) def create_handler(from_class): class Handler(from_class): http_method_names = OrderedDict.fromkeys(["head", "options"]) return Handler def apply_http_methods(handler, injector): for method in ["get", "post", "put", "patch", "delete", "head", "options", "trace"]: if method in injector: def __view(self, request, *args, **kwargs): return injector.let( view=self, request=request, args=args, kwargs=kwargs, user=this.request.user, ).trace() handler.http_method_names[method] = None setattr(handler, method, __view)
from __future__ import absolute_import from collections import OrderedDict from dependencies import this from django.views.generic import View def view(injector): """Create Django class-based view from injector class.""" handler = create_handler(View) apply_http_methods(handler, injector) finalize_http_methods(handler) return injector.let(as_view=handler.as_view) def create_handler(from_class): class Handler(from_class): http_method_names = OrderedDict.fromkeys(["head", "options"]) return Handler def apply_http_methods(handler, injector): for method in ["get", "post", "put", "patch", "delete", "head", "options", "trace"]: if method in injector: def __view(self, request, *args, **kwargs): ns = injector.let( view=self, request=request, args=args, kwargs=kwargs, user=this.request.user, ) return getattr(ns, __view.method)() __view.method = method handler.http_method_names[method] = None setattr(handler, method, __view) def finalize_http_methods(handler): handler.http_method_names = list(handler.http_method_names.keys())
Fix django view closure issue.
Fix django view closure issue.
Python
bsd-2-clause
proofit404/dependencies,proofit404/dependencies,proofit404/dependencies,proofit404/dependencies
from __future__ import absolute_import from collections import OrderedDict from dependencies import this from django.views.generic import View def view(injector): """Create Django class-based view from injector class.""" handler = create_handler(View) apply_http_methods(handler, injector) + finalize_http_methods(handler) - handler.http_method_names = list(handler.http_method_names.keys()) - return injector.let(as_view=handler.as_view) def create_handler(from_class): class Handler(from_class): http_method_names = OrderedDict.fromkeys(["head", "options"]) return Handler def apply_http_methods(handler, injector): for method in ["get", "post", "put", "patch", "delete", "head", "options", "trace"]: - if method in injector: def __view(self, request, *args, **kwargs): - return injector.let( + ns = injector.let( view=self, request=request, args=args, kwargs=kwargs, user=this.request.user, - ).trace() + ) + return getattr(ns, __view.method)() + __view.method = method handler.http_method_names[method] = None setattr(handler, method, __view) + + def finalize_http_methods(handler): + + handler.http_method_names = list(handler.http_method_names.keys()) +
Fix django view closure issue.
## Code Before: from __future__ import absolute_import from collections import OrderedDict from dependencies import this from django.views.generic import View def view(injector): """Create Django class-based view from injector class.""" handler = create_handler(View) apply_http_methods(handler, injector) handler.http_method_names = list(handler.http_method_names.keys()) return injector.let(as_view=handler.as_view) def create_handler(from_class): class Handler(from_class): http_method_names = OrderedDict.fromkeys(["head", "options"]) return Handler def apply_http_methods(handler, injector): for method in ["get", "post", "put", "patch", "delete", "head", "options", "trace"]: if method in injector: def __view(self, request, *args, **kwargs): return injector.let( view=self, request=request, args=args, kwargs=kwargs, user=this.request.user, ).trace() handler.http_method_names[method] = None setattr(handler, method, __view) ## Instruction: Fix django view closure issue. ## Code After: from __future__ import absolute_import from collections import OrderedDict from dependencies import this from django.views.generic import View def view(injector): """Create Django class-based view from injector class.""" handler = create_handler(View) apply_http_methods(handler, injector) finalize_http_methods(handler) return injector.let(as_view=handler.as_view) def create_handler(from_class): class Handler(from_class): http_method_names = OrderedDict.fromkeys(["head", "options"]) return Handler def apply_http_methods(handler, injector): for method in ["get", "post", "put", "patch", "delete", "head", "options", "trace"]: if method in injector: def __view(self, request, *args, **kwargs): ns = injector.let( view=self, request=request, args=args, kwargs=kwargs, user=this.request.user, ) return getattr(ns, __view.method)() __view.method = method handler.http_method_names[method] = None setattr(handler, method, __view) def finalize_http_methods(handler): handler.http_method_names = list(handler.http_method_names.keys())
// ... existing code ... apply_http_methods(handler, injector) finalize_http_methods(handler) return injector.let(as_view=handler.as_view) // ... modified code ... for method in ["get", "post", "put", "patch", "delete", "head", "options", "trace"]: if method in injector: ... def __view(self, request, *args, **kwargs): ns = injector.let( view=self, ... user=this.request.user, ) return getattr(ns, __view.method)() __view.method = method handler.http_method_names[method] = None ... setattr(handler, method, __view) def finalize_http_methods(handler): handler.http_method_names = list(handler.http_method_names.keys()) // ... rest of the code ...
792e073317f75f4b9a687c4a647a2b7f9f5656c1
test_project/runtests.py
test_project/runtests.py
import os, sys os.environ['DJANGO_SETTINGS_MODULE'] = 'test_project.settings' test_dir = os.path.dirname(__file__) sys.path.insert(0, test_dir) from django.test.utils import get_runner from django.conf import settings def runtests(): test_runner = get_runner(settings) failures = test_runner().run_tests([]) sys.exit(failures) if __name__ == '__main__': runtests()
import os, sys os.environ['DJANGO_SETTINGS_MODULE'] = 'test_project.settings' test_dir = os.path.dirname(__file__) sys.path.insert(0, test_dir) from django.test.utils import get_runner from django.conf import settings def runtests(): test_runner = get_runner(settings) failures = test_runner([]) sys.exit(failures) if __name__ == '__main__': runtests()
Fix the running of tests. Wonder if this is a django regression.
Fix the running of tests. Wonder if this is a django regression.
Python
mit
ericholscher/django-test-utils,frac/django-test-utils,ericholscher/django-test-utils,acdha/django-test-utils,frac/django-test-utils,acdha/django-test-utils
import os, sys os.environ['DJANGO_SETTINGS_MODULE'] = 'test_project.settings' test_dir = os.path.dirname(__file__) sys.path.insert(0, test_dir) from django.test.utils import get_runner from django.conf import settings def runtests(): test_runner = get_runner(settings) - failures = test_runner().run_tests([]) + failures = test_runner([]) sys.exit(failures) if __name__ == '__main__': runtests()
Fix the running of tests. Wonder if this is a django regression.
## Code Before: import os, sys os.environ['DJANGO_SETTINGS_MODULE'] = 'test_project.settings' test_dir = os.path.dirname(__file__) sys.path.insert(0, test_dir) from django.test.utils import get_runner from django.conf import settings def runtests(): test_runner = get_runner(settings) failures = test_runner().run_tests([]) sys.exit(failures) if __name__ == '__main__': runtests() ## Instruction: Fix the running of tests. Wonder if this is a django regression. ## Code After: import os, sys os.environ['DJANGO_SETTINGS_MODULE'] = 'test_project.settings' test_dir = os.path.dirname(__file__) sys.path.insert(0, test_dir) from django.test.utils import get_runner from django.conf import settings def runtests(): test_runner = get_runner(settings) failures = test_runner([]) sys.exit(failures) if __name__ == '__main__': runtests()
// ... existing code ... test_runner = get_runner(settings) failures = test_runner([]) sys.exit(failures) // ... rest of the code ...
4cb1b6b8656d4e3893b3aa8fe5766b507afa6d24
cmsplugin_rt/button/cms_plugins.py
cmsplugin_rt/button/cms_plugins.py
from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from cms.models.pluginmodel import CMSPlugin from django.utils.translation import ugettext_lazy as _ from django.conf import settings from models import * bootstrap_module_name = _("Widgets") layout_module_name = _("Layout elements") generic_module_name = _("Generic") meta_module_name = _("Meta elements") class ButtonPlugin(CMSPluginBase): model = ButtonPluginModel name = _("Button") #module = bootstrap_module_name render_template = "button_plugin.html" def render(self, context, instance, placeholder): context['instance'] = instance if instance.page_link: context['link'] = instance.page_link.get_absolute_url() else: context['link'] = instance.button_link return context plugin_pool.register_plugin(ButtonPlugin)
from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from cms.models.pluginmodel import CMSPlugin from django.utils.translation import ugettext_lazy as _ from django.conf import settings from models import * bootstrap_module_name = _("Widgets") layout_module_name = _("Layout elements") generic_module_name = _("Generic") meta_module_name = _("Meta elements") class ButtonPlugin(CMSPluginBase): model = ButtonPluginModel name = _("Button") #module = bootstrap_module_name render_template = "button_plugin.html" text_enabled = True def render(self, context, instance, placeholder): context['instance'] = instance if instance.page_link: context['link'] = instance.page_link.get_absolute_url() else: context['link'] = instance.button_link return context plugin_pool.register_plugin(ButtonPlugin)
Make Button plugin usable inside Text plugin
Make Button plugin usable inside Text plugin
Python
bsd-3-clause
RacingTadpole/cmsplugin-rt
from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from cms.models.pluginmodel import CMSPlugin from django.utils.translation import ugettext_lazy as _ from django.conf import settings from models import * bootstrap_module_name = _("Widgets") layout_module_name = _("Layout elements") generic_module_name = _("Generic") meta_module_name = _("Meta elements") class ButtonPlugin(CMSPluginBase): model = ButtonPluginModel name = _("Button") #module = bootstrap_module_name render_template = "button_plugin.html" + text_enabled = True def render(self, context, instance, placeholder): context['instance'] = instance if instance.page_link: context['link'] = instance.page_link.get_absolute_url() else: context['link'] = instance.button_link return context plugin_pool.register_plugin(ButtonPlugin)
Make Button plugin usable inside Text plugin
## Code Before: from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from cms.models.pluginmodel import CMSPlugin from django.utils.translation import ugettext_lazy as _ from django.conf import settings from models import * bootstrap_module_name = _("Widgets") layout_module_name = _("Layout elements") generic_module_name = _("Generic") meta_module_name = _("Meta elements") class ButtonPlugin(CMSPluginBase): model = ButtonPluginModel name = _("Button") #module = bootstrap_module_name render_template = "button_plugin.html" def render(self, context, instance, placeholder): context['instance'] = instance if instance.page_link: context['link'] = instance.page_link.get_absolute_url() else: context['link'] = instance.button_link return context plugin_pool.register_plugin(ButtonPlugin) ## Instruction: Make Button plugin usable inside Text plugin ## Code After: from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from cms.models.pluginmodel import CMSPlugin from django.utils.translation import ugettext_lazy as _ from django.conf import settings from models import * bootstrap_module_name = _("Widgets") layout_module_name = _("Layout elements") generic_module_name = _("Generic") meta_module_name = _("Meta elements") class ButtonPlugin(CMSPluginBase): model = ButtonPluginModel name = _("Button") #module = bootstrap_module_name render_template = "button_plugin.html" text_enabled = True def render(self, context, instance, placeholder): context['instance'] = instance if instance.page_link: context['link'] = instance.page_link.get_absolute_url() else: context['link'] = instance.button_link return context plugin_pool.register_plugin(ButtonPlugin)
... render_template = "button_plugin.html" text_enabled = True ...
164c70386191f0761923c1344447b8fac0e0795c
pelican/settings.py
pelican/settings.py
import os _DEFAULT_THEME = os.sep.join([os.path.dirname(os.path.abspath(__file__)), "themes/notmyidea"]) _DEFAULT_CONFIG = {'PATH': None, 'THEME': _DEFAULT_THEME, 'OUTPUT_PATH': 'output/', 'MARKUP': ('rst', 'md'), 'STATIC_PATHS': ['images',], 'THEME_STATIC_PATHS': ['static',], 'FEED': 'feeds/all.atom.xml', 'CATEGORY_FEED': 'feeds/%s.atom.xml', 'TRANSLATION_FEED': 'feeds/all-%s.atom.xml', 'SITENAME': 'A Pelican Blog', 'DISPLAY_PAGES_ON_MENU': True, 'PDF_GENERATOR': False, 'DEFAULT_CATEGORY': 'misc', 'FALLBACK_ON_FS_DATE': True, 'CSS_FILE': 'main.css', 'REVERSE_ARCHIVE_ORDER': False, 'KEEP_OUTPUT_DIRECTORY': False, 'CLEAN_URLS': False, # use /blah/ instead /blah.html in urls 'RELATIVE_URLS': True, 'DEFAULT_LANG': 'en', } def read_settings(filename): """Load a Python file into a dictionary. """ context = _DEFAULT_CONFIG.copy() if filename: tempdict = {} execfile(filename, tempdict) for key in tempdict: if key.isupper(): context[key] = tempdict[key] return context
import os _DEFAULT_THEME = os.sep.join([os.path.dirname(os.path.abspath(__file__)), "themes/notmyidea"]) _DEFAULT_CONFIG = {'PATH': None, 'THEME': _DEFAULT_THEME, 'OUTPUT_PATH': 'output/', 'MARKUP': ('rst', 'md'), 'STATIC_PATHS': ['images',], 'THEME_STATIC_PATHS': ['static',], 'FEED': 'feeds/all.atom.xml', 'CATEGORY_FEED': 'feeds/%s.atom.xml', 'TRANSLATION_FEED': 'feeds/all-%s.atom.xml', 'SITENAME': 'A Pelican Blog', 'DISPLAY_PAGES_ON_MENU': True, 'PDF_GENERATOR': False, 'DEFAULT_CATEGORY': 'misc', 'FALLBACK_ON_FS_DATE': True, 'CSS_FILE': 'main.css', 'REVERSE_ARCHIVE_ORDER': False, 'KEEP_OUTPUT_DIRECTORY': False, 'CLEAN_URLS': False, # use /blah/ instead /blah.html in urls 'RELATIVE_URLS': True, 'DEFAULT_LANG': 'en', 'JINJA_EXTENSIONS': [], } def read_settings(filename): """Load a Python file into a dictionary. """ context = _DEFAULT_CONFIG.copy() if filename: tempdict = {} execfile(filename, tempdict) for key in tempdict: if key.isupper(): context[key] = tempdict[key] return context
Add a default for JINJA_EXTENSIONS (default is no extensions)
Add a default for JINJA_EXTENSIONS (default is no extensions)
Python
agpl-3.0
treyhunner/pelican,joetboole/pelican,janaurka/git-debug-presentiation,goerz/pelican,JeremyMorgan/pelican,Polyconseil/pelican,deved69/pelican-1,JeremyMorgan/pelican,douglaskastle/pelican,farseerfc/pelican,51itclub/pelican,florianjacob/pelican,liyonghelpme/myBlog,levanhien8/pelican,lucasplus/pelican,btnpushnmunky/pelican,gymglish/pelican,catdog2/pelican,liyonghelpme/myBlog,ehashman/pelican,lazycoder-ru/pelican,koobs/pelican,douglaskastle/pelican,jimperio/pelican,Scheirle/pelican,sunzhongwei/pelican,koobs/pelican,GiovanniMoretti/pelican,liyonghelpme/myBlog,janaurka/git-debug-presentiation,lazycoder-ru/pelican,karlcow/pelican,51itclub/pelican,lucasplus/pelican,jimperio/pelican,garbas/pelican,simonjj/pelican,jvehent/pelican,kernc/pelican,GiovanniMoretti/pelican,karlcow/pelican,abrahamvarricatt/pelican,eevee/pelican,iKevinY/pelican,Natim/pelican,ehashman/pelican,jimperio/pelican,iurisilvio/pelican,number5/pelican,jo-tham/pelican,sunzhongwei/pelican,avaris/pelican,joetboole/pelican,iurisilvio/pelican,rbarraud/pelican,catdog2/pelican,11craft/pelican,eevee/pelican,goerz/pelican,catdog2/pelican,kennethlyn/pelican,btnpushnmunky/pelican,alexras/pelican,levanhien8/pelican,HyperGroups/pelican,fbs/pelican,treyhunner/pelican,iurisilvio/pelican,kernc/pelican,alexras/pelican,liyonghelpme/myBlog,ingwinlu/pelican,ls2uper/pelican,goerz/pelican,GiovanniMoretti/pelican,11craft/pelican,alexras/pelican,kennethlyn/pelican,gymglish/pelican,Summonee/pelican,ehashman/pelican,Summonee/pelican,TC01/pelican,Scheirle/pelican,deved69/pelican-1,jo-tham/pelican,arty-name/pelican,treyhunner/pelican,garbas/pelican,koobs/pelican,simonjj/pelican,UdeskDeveloper/pelican,UdeskDeveloper/pelican,ls2uper/pelican,TC01/pelican,number5/pelican,0xMF/pelican,kennethlyn/pelican,51itclub/pelican,crmackay/pelican,zackw/pelican,Rogdham/pelican,rbarraud/pelican,janaurka/git-debug-presentiation,ionelmc/pelican,JeremyMorgan/pelican,getpelican/pelican,zackw/pelican,lucasplus/pelican,florianjacob/pelican,btnpushnmunky/pelican,abrahamvarricatt/pelican,talha131/pelican,ls2uper/pelican,jvehent/pelican,florianjacob/pelican,eevee/pelican,gymglish/pelican,liyonghelpme/myBlog,simonjj/pelican,Polyconseil/pelican,joetboole/pelican,crmackay/pelican,farseerfc/pelican,Summonee/pelican,ingwinlu/pelican,sunzhongwei/pelican,sunzhongwei/pelican,Scheirle/pelican,karlcow/pelican,11craft/pelican,crmackay/pelican,getpelican/pelican,HyperGroups/pelican,lazycoder-ru/pelican,Rogdham/pelican,talha131/pelican,zackw/pelican,TC01/pelican,levanhien8/pelican,Rogdham/pelican,deved69/pelican-1,jvehent/pelican,number5/pelican,HyperGroups/pelican,justinmayer/pelican,deanishe/pelican,garbas/pelican,iKevinY/pelican,avaris/pelican,deanishe/pelican,rbarraud/pelican,UdeskDeveloper/pelican,douglaskastle/pelican,abrahamvarricatt/pelican,deanishe/pelican,kernc/pelican
import os _DEFAULT_THEME = os.sep.join([os.path.dirname(os.path.abspath(__file__)), "themes/notmyidea"]) _DEFAULT_CONFIG = {'PATH': None, 'THEME': _DEFAULT_THEME, 'OUTPUT_PATH': 'output/', 'MARKUP': ('rst', 'md'), 'STATIC_PATHS': ['images',], 'THEME_STATIC_PATHS': ['static',], 'FEED': 'feeds/all.atom.xml', 'CATEGORY_FEED': 'feeds/%s.atom.xml', 'TRANSLATION_FEED': 'feeds/all-%s.atom.xml', 'SITENAME': 'A Pelican Blog', 'DISPLAY_PAGES_ON_MENU': True, 'PDF_GENERATOR': False, 'DEFAULT_CATEGORY': 'misc', 'FALLBACK_ON_FS_DATE': True, 'CSS_FILE': 'main.css', 'REVERSE_ARCHIVE_ORDER': False, 'KEEP_OUTPUT_DIRECTORY': False, 'CLEAN_URLS': False, # use /blah/ instead /blah.html in urls 'RELATIVE_URLS': True, 'DEFAULT_LANG': 'en', + 'JINJA_EXTENSIONS': [], } def read_settings(filename): """Load a Python file into a dictionary. """ context = _DEFAULT_CONFIG.copy() if filename: tempdict = {} execfile(filename, tempdict) for key in tempdict: if key.isupper(): context[key] = tempdict[key] return context
Add a default for JINJA_EXTENSIONS (default is no extensions)
## Code Before: import os _DEFAULT_THEME = os.sep.join([os.path.dirname(os.path.abspath(__file__)), "themes/notmyidea"]) _DEFAULT_CONFIG = {'PATH': None, 'THEME': _DEFAULT_THEME, 'OUTPUT_PATH': 'output/', 'MARKUP': ('rst', 'md'), 'STATIC_PATHS': ['images',], 'THEME_STATIC_PATHS': ['static',], 'FEED': 'feeds/all.atom.xml', 'CATEGORY_FEED': 'feeds/%s.atom.xml', 'TRANSLATION_FEED': 'feeds/all-%s.atom.xml', 'SITENAME': 'A Pelican Blog', 'DISPLAY_PAGES_ON_MENU': True, 'PDF_GENERATOR': False, 'DEFAULT_CATEGORY': 'misc', 'FALLBACK_ON_FS_DATE': True, 'CSS_FILE': 'main.css', 'REVERSE_ARCHIVE_ORDER': False, 'KEEP_OUTPUT_DIRECTORY': False, 'CLEAN_URLS': False, # use /blah/ instead /blah.html in urls 'RELATIVE_URLS': True, 'DEFAULT_LANG': 'en', } def read_settings(filename): """Load a Python file into a dictionary. """ context = _DEFAULT_CONFIG.copy() if filename: tempdict = {} execfile(filename, tempdict) for key in tempdict: if key.isupper(): context[key] = tempdict[key] return context ## Instruction: Add a default for JINJA_EXTENSIONS (default is no extensions) ## Code After: import os _DEFAULT_THEME = os.sep.join([os.path.dirname(os.path.abspath(__file__)), "themes/notmyidea"]) _DEFAULT_CONFIG = {'PATH': None, 'THEME': _DEFAULT_THEME, 'OUTPUT_PATH': 'output/', 'MARKUP': ('rst', 'md'), 'STATIC_PATHS': ['images',], 'THEME_STATIC_PATHS': ['static',], 'FEED': 'feeds/all.atom.xml', 'CATEGORY_FEED': 'feeds/%s.atom.xml', 'TRANSLATION_FEED': 'feeds/all-%s.atom.xml', 'SITENAME': 'A Pelican Blog', 'DISPLAY_PAGES_ON_MENU': True, 'PDF_GENERATOR': False, 'DEFAULT_CATEGORY': 'misc', 'FALLBACK_ON_FS_DATE': True, 'CSS_FILE': 'main.css', 'REVERSE_ARCHIVE_ORDER': False, 'KEEP_OUTPUT_DIRECTORY': False, 'CLEAN_URLS': False, # use /blah/ instead /blah.html in urls 'RELATIVE_URLS': True, 'DEFAULT_LANG': 'en', 'JINJA_EXTENSIONS': [], } def read_settings(filename): """Load a Python file into a dictionary. """ context = _DEFAULT_CONFIG.copy() if filename: tempdict = {} execfile(filename, tempdict) for key in tempdict: if key.isupper(): context[key] = tempdict[key] return context
// ... existing code ... 'DEFAULT_LANG': 'en', 'JINJA_EXTENSIONS': [], } // ... rest of the code ...
e62e090f2282426d14dad52a06eeca788789846f
kpi/serializers/v2/user_asset_subscription.py
kpi/serializers/v2/user_asset_subscription.py
from django.utils.translation import ugettext as _ from rest_framework import serializers from kpi.constants import ( ASSET_TYPE_COLLECTION, PERM_DISCOVER_ASSET, PERM_VIEW_ASSET ) from kpi.fields import RelativePrefixHyperlinkedRelatedField from kpi.models import Asset from kpi.models import UserAssetSubscription from kpi.models.object_permission import get_anonymous_user, get_objects_for_user class UserAssetSubscriptionSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField( lookup_field='uid', view_name='userassetsubscription-detail' ) asset = RelativePrefixHyperlinkedRelatedField( lookup_field='uid', view_name='asset-detail', queryset=Asset.objects.none() # will be set in __init__() ) uid = serializers.ReadOnlyField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['asset'].queryset = get_objects_for_user( get_anonymous_user(), [PERM_VIEW_ASSET, PERM_DISCOVER_ASSET], Asset ) class Meta: model = UserAssetSubscription lookup_field = 'uid' fields = ('url', 'asset', 'uid') def validate_asset(self, asset): if asset.asset_type != ASSET_TYPE_COLLECTION: raise serializers.ValidationError( _('Invalid asset type. Only `{asset_type}`').format( asset_type=ASSET_TYPE_COLLECTION ) ) return asset
from django.utils.translation import ugettext as _ from rest_framework import serializers from kpi.constants import ( ASSET_TYPE_COLLECTION, PERM_DISCOVER_ASSET, PERM_VIEW_ASSET ) from kpi.fields import RelativePrefixHyperlinkedRelatedField from kpi.models import Asset from kpi.models import UserAssetSubscription from kpi.models.object_permission import get_anonymous_user, get_objects_for_user class UserAssetSubscriptionSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField( lookup_field='uid', view_name='userassetsubscription-detail' ) asset = RelativePrefixHyperlinkedRelatedField( lookup_field='uid', view_name='asset-detail', queryset=Asset.objects.none() # will be set in __init__() ) uid = serializers.ReadOnlyField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['asset'].queryset = get_objects_for_user( get_anonymous_user(), [PERM_VIEW_ASSET, PERM_DISCOVER_ASSET], Asset ) class Meta: model = UserAssetSubscription lookup_field = 'uid' fields = ('url', 'asset', 'uid') def validate_asset(self, asset): if asset.asset_type != ASSET_TYPE_COLLECTION: raise serializers.ValidationError( _('Invalid asset type. Only `{asset_type}` is allowed').format( asset_type=ASSET_TYPE_COLLECTION ) ) return asset
Improve (a tiny bit) validation error message
Improve (a tiny bit) validation error message
Python
agpl-3.0
kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi
from django.utils.translation import ugettext as _ from rest_framework import serializers from kpi.constants import ( ASSET_TYPE_COLLECTION, PERM_DISCOVER_ASSET, PERM_VIEW_ASSET ) from kpi.fields import RelativePrefixHyperlinkedRelatedField from kpi.models import Asset from kpi.models import UserAssetSubscription from kpi.models.object_permission import get_anonymous_user, get_objects_for_user class UserAssetSubscriptionSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField( lookup_field='uid', view_name='userassetsubscription-detail' ) asset = RelativePrefixHyperlinkedRelatedField( lookup_field='uid', view_name='asset-detail', queryset=Asset.objects.none() # will be set in __init__() ) uid = serializers.ReadOnlyField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['asset'].queryset = get_objects_for_user( get_anonymous_user(), [PERM_VIEW_ASSET, PERM_DISCOVER_ASSET], Asset ) class Meta: model = UserAssetSubscription lookup_field = 'uid' fields = ('url', 'asset', 'uid') def validate_asset(self, asset): if asset.asset_type != ASSET_TYPE_COLLECTION: raise serializers.ValidationError( - _('Invalid asset type. Only `{asset_type}`').format( + _('Invalid asset type. Only `{asset_type}` is allowed').format( asset_type=ASSET_TYPE_COLLECTION ) ) return asset
Improve (a tiny bit) validation error message
## Code Before: from django.utils.translation import ugettext as _ from rest_framework import serializers from kpi.constants import ( ASSET_TYPE_COLLECTION, PERM_DISCOVER_ASSET, PERM_VIEW_ASSET ) from kpi.fields import RelativePrefixHyperlinkedRelatedField from kpi.models import Asset from kpi.models import UserAssetSubscription from kpi.models.object_permission import get_anonymous_user, get_objects_for_user class UserAssetSubscriptionSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField( lookup_field='uid', view_name='userassetsubscription-detail' ) asset = RelativePrefixHyperlinkedRelatedField( lookup_field='uid', view_name='asset-detail', queryset=Asset.objects.none() # will be set in __init__() ) uid = serializers.ReadOnlyField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['asset'].queryset = get_objects_for_user( get_anonymous_user(), [PERM_VIEW_ASSET, PERM_DISCOVER_ASSET], Asset ) class Meta: model = UserAssetSubscription lookup_field = 'uid' fields = ('url', 'asset', 'uid') def validate_asset(self, asset): if asset.asset_type != ASSET_TYPE_COLLECTION: raise serializers.ValidationError( _('Invalid asset type. Only `{asset_type}`').format( asset_type=ASSET_TYPE_COLLECTION ) ) return asset ## Instruction: Improve (a tiny bit) validation error message ## Code After: from django.utils.translation import ugettext as _ from rest_framework import serializers from kpi.constants import ( ASSET_TYPE_COLLECTION, PERM_DISCOVER_ASSET, PERM_VIEW_ASSET ) from kpi.fields import RelativePrefixHyperlinkedRelatedField from kpi.models import Asset from kpi.models import UserAssetSubscription from kpi.models.object_permission import get_anonymous_user, get_objects_for_user class UserAssetSubscriptionSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField( lookup_field='uid', view_name='userassetsubscription-detail' ) asset = RelativePrefixHyperlinkedRelatedField( lookup_field='uid', view_name='asset-detail', queryset=Asset.objects.none() # will be set in __init__() ) uid = serializers.ReadOnlyField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['asset'].queryset = get_objects_for_user( get_anonymous_user(), [PERM_VIEW_ASSET, PERM_DISCOVER_ASSET], Asset ) class Meta: model = UserAssetSubscription lookup_field = 'uid' fields = ('url', 'asset', 'uid') def validate_asset(self, asset): if asset.asset_type != ASSET_TYPE_COLLECTION: raise serializers.ValidationError( _('Invalid asset type. Only `{asset_type}` is allowed').format( asset_type=ASSET_TYPE_COLLECTION ) ) return asset
// ... existing code ... raise serializers.ValidationError( _('Invalid asset type. Only `{asset_type}` is allowed').format( asset_type=ASSET_TYPE_COLLECTION // ... rest of the code ...
4c080197dce0d452047203dbf06dd160086fcbdf
website/snat/forms.py
website/snat/forms.py
from flask_wtf import Form from wtforms import TextField from wtforms.validators import Required, IPAddress class SnatForm(Form): source = TextField(u'SNAT源IP(段)', validators=[Required(message=u'这是一个必选项!')]) gateway = TextField(u'SNAT转发IP', validators=[Required(message=u'这是一个必选项!'), IPAddress(message=u'无效的ip 地址!')])
from flask_wtf import Form from wtforms import TextField, ValidationError from wtforms.validators import Required, IPAddress def IPorNet(message=u"无效的IP 或网段!"): def _ipornet(form, field): value = field.data ip = value.split('/')[0] if '/' in value: try: mask = int(value.split('/')[1]) except: raise ValidationError(message) if mask < 0 or mask > 32: raise ValidationError(message) parts = ip.split('.') if len(parts) == 4 and all(x.isdigit() for x in parts): numbers = list(int(x) for x in parts) if not all(num >= 0 and num < 256 for num in numbers): raise ValidationError(message) return True raise ValidationError(message) return _ipornet class SnatForm(Form): source = TextField(u'SNAT源IP(段)', validators=[Required(message=u'这是一个必选项!'), IPorNet(message=u"无效的IP 或网段!")]) gateway = TextField(u'SNAT转发IP', validators=[Required(message=u'这是一个必选项!'), IPAddress(message=u'无效的IP 地址!')])
Add snat ip or net validator.
Add snat ip or net validator.
Python
bsd-3-clause
sdgdsffdsfff/FlexGW,sdgdsffdsfff/FlexGW,alibaba/FlexGW,alibaba/FlexGW,sdgdsffdsfff/FlexGW,sdgdsffdsfff/FlexGW,alibaba/FlexGW,alibaba/FlexGW
from flask_wtf import Form - from wtforms import TextField + from wtforms import TextField, ValidationError from wtforms.validators import Required, IPAddress + + + def IPorNet(message=u"无效的IP 或网段!"): + def _ipornet(form, field): + value = field.data + ip = value.split('/')[0] + if '/' in value: + try: + mask = int(value.split('/')[1]) + except: + raise ValidationError(message) + if mask < 0 or mask > 32: + raise ValidationError(message) + parts = ip.split('.') + if len(parts) == 4 and all(x.isdigit() for x in parts): + numbers = list(int(x) for x in parts) + if not all(num >= 0 and num < 256 for num in numbers): + raise ValidationError(message) + return True + raise ValidationError(message) + return _ipornet class SnatForm(Form): source = TextField(u'SNAT源IP(段)', - validators=[Required(message=u'这是一个必选项!')]) + validators=[Required(message=u'这是一个必选项!'), + IPorNet(message=u"无效的IP 或网段!")]) gateway = TextField(u'SNAT转发IP', validators=[Required(message=u'这是一个必选项!'), - IPAddress(message=u'无效的ip 地址!')]) + IPAddress(message=u'无效的IP 地址!')])
Add snat ip or net validator.
## Code Before: from flask_wtf import Form from wtforms import TextField from wtforms.validators import Required, IPAddress class SnatForm(Form): source = TextField(u'SNAT源IP(段)', validators=[Required(message=u'这是一个必选项!')]) gateway = TextField(u'SNAT转发IP', validators=[Required(message=u'这是一个必选项!'), IPAddress(message=u'无效的ip 地址!')]) ## Instruction: Add snat ip or net validator. ## Code After: from flask_wtf import Form from wtforms import TextField, ValidationError from wtforms.validators import Required, IPAddress def IPorNet(message=u"无效的IP 或网段!"): def _ipornet(form, field): value = field.data ip = value.split('/')[0] if '/' in value: try: mask = int(value.split('/')[1]) except: raise ValidationError(message) if mask < 0 or mask > 32: raise ValidationError(message) parts = ip.split('.') if len(parts) == 4 and all(x.isdigit() for x in parts): numbers = list(int(x) for x in parts) if not all(num >= 0 and num < 256 for num in numbers): raise ValidationError(message) return True raise ValidationError(message) return _ipornet class SnatForm(Form): source = TextField(u'SNAT源IP(段)', validators=[Required(message=u'这是一个必选项!'), IPorNet(message=u"无效的IP 或网段!")]) gateway = TextField(u'SNAT转发IP', validators=[Required(message=u'这是一个必选项!'), IPAddress(message=u'无效的IP 地址!')])
// ... existing code ... from flask_wtf import Form from wtforms import TextField, ValidationError from wtforms.validators import Required, IPAddress def IPorNet(message=u"无效的IP 或网段!"): def _ipornet(form, field): value = field.data ip = value.split('/')[0] if '/' in value: try: mask = int(value.split('/')[1]) except: raise ValidationError(message) if mask < 0 or mask > 32: raise ValidationError(message) parts = ip.split('.') if len(parts) == 4 and all(x.isdigit() for x in parts): numbers = list(int(x) for x in parts) if not all(num >= 0 and num < 256 for num in numbers): raise ValidationError(message) return True raise ValidationError(message) return _ipornet // ... modified code ... source = TextField(u'SNAT源IP(段)', validators=[Required(message=u'这是一个必选项!'), IPorNet(message=u"无效的IP 或网段!")]) gateway = TextField(u'SNAT转发IP', ... validators=[Required(message=u'这是一个必选项!'), IPAddress(message=u'无效的IP 地址!')]) // ... rest of the code ...
b35d4292e50e8a8dc56635bddeac5a1fc42a5d19
tveebot_tracker/source.py
tveebot_tracker/source.py
from abc import ABC, abstractmethod class TVShowNotFound(Exception): """ Raised when a reference does not match any TV Show available """ class EpisodeSource(ABC): """ Abstract base class to define the interface for and episode source. An episode source is used by the tracker to obtain episode files. A source is usually based on a feed that provides links to TV Show's episodes. Every source has its own protocol to obtain the information and it uses its own format to present that information. Implementations of this interface are responsible for implementing the details of how to obtain the episode files' information and present them to the tracker. """ # Called by the tracker when it wants to get the episodes available for # a specific TVShow @abstractmethod def get_episodes_for(self, tvshow_reference: str) -> list: """ Retrieve all available episode files corresponding to the specified TV show. Multiple files for the same episode may be retrieved. The TV show to obtain the episodes from is identified by some reference that uniquely identifies it within the episode source in question. :param tvshow_reference: reference that uniquely identifies the TV show to get the episodes for :return: a list containing all episode files available for the specified TV Show. An empty list if none is found. :raise TVShowNotFound: if the specified reference does not match to any TV show available """
from abc import ABC, abstractmethod class TVShowNotFound(Exception): """ Raised when a reference does not match any TV Show available """ class EpisodeSource(ABC): """ Abstract base class to define the interface for and episode source. An episode source is used by the tracker to obtain episode files. A source is usually based on a feed that provides links to TV Show's episodes. Every source has its own protocol to obtain the information and it uses its own format to present that information. Implementations of this interface are responsible for implementing the details of how to obtain the episode files' information and present them to the tracker. """ # Called by the tracker when it wants to get the episodes available for # a specific TVShow @abstractmethod def fetch(self, tvshow_reference: str) -> list: """ Fetches all available episode files, corresponding to the specified TV show. Multiple files for the same episode may be retrieved. The TV show to obtain the episodes from is identified by some reference that uniquely identifies it within the episode source in question. :param tvshow_reference: reference that uniquely identifies the TV show to get the episodes for :return: a list containing all episode files available for the specified TV Show. An empty list if none is found. :raise TVShowNotFound: if the specified reference does not match to any TV show available """
Rename Source's get_episodes_for() method to fetch()
Rename Source's get_episodes_for() method to fetch()
Python
mit
tveebot/tracker
from abc import ABC, abstractmethod class TVShowNotFound(Exception): """ Raised when a reference does not match any TV Show available """ class EpisodeSource(ABC): """ Abstract base class to define the interface for and episode source. An episode source is used by the tracker to obtain episode files. A source is usually based on a feed that provides links to TV Show's episodes. Every source has its own protocol to obtain the information and it uses its own format to present that information. Implementations of this interface are responsible for implementing the details of how to obtain the episode files' information and present them to the tracker. """ # Called by the tracker when it wants to get the episodes available for # a specific TVShow @abstractmethod - def get_episodes_for(self, tvshow_reference: str) -> list: + def fetch(self, tvshow_reference: str) -> list: """ - Retrieve all available episode files corresponding to the specified + Fetches all available episode files, corresponding to the specified TV show. Multiple files for the same episode may be retrieved. The TV show to obtain the episodes from is identified by some reference that uniquely identifies it within the episode source in question. :param tvshow_reference: reference that uniquely identifies the TV show to get the episodes for :return: a list containing all episode files available for the specified TV Show. An empty list if none is found. :raise TVShowNotFound: if the specified reference does not match to any TV show available """
Rename Source's get_episodes_for() method to fetch()
## Code Before: from abc import ABC, abstractmethod class TVShowNotFound(Exception): """ Raised when a reference does not match any TV Show available """ class EpisodeSource(ABC): """ Abstract base class to define the interface for and episode source. An episode source is used by the tracker to obtain episode files. A source is usually based on a feed that provides links to TV Show's episodes. Every source has its own protocol to obtain the information and it uses its own format to present that information. Implementations of this interface are responsible for implementing the details of how to obtain the episode files' information and present them to the tracker. """ # Called by the tracker when it wants to get the episodes available for # a specific TVShow @abstractmethod def get_episodes_for(self, tvshow_reference: str) -> list: """ Retrieve all available episode files corresponding to the specified TV show. Multiple files for the same episode may be retrieved. The TV show to obtain the episodes from is identified by some reference that uniquely identifies it within the episode source in question. :param tvshow_reference: reference that uniquely identifies the TV show to get the episodes for :return: a list containing all episode files available for the specified TV Show. An empty list if none is found. :raise TVShowNotFound: if the specified reference does not match to any TV show available """ ## Instruction: Rename Source's get_episodes_for() method to fetch() ## Code After: from abc import ABC, abstractmethod class TVShowNotFound(Exception): """ Raised when a reference does not match any TV Show available """ class EpisodeSource(ABC): """ Abstract base class to define the interface for and episode source. An episode source is used by the tracker to obtain episode files. A source is usually based on a feed that provides links to TV Show's episodes. Every source has its own protocol to obtain the information and it uses its own format to present that information. Implementations of this interface are responsible for implementing the details of how to obtain the episode files' information and present them to the tracker. """ # Called by the tracker when it wants to get the episodes available for # a specific TVShow @abstractmethod def fetch(self, tvshow_reference: str) -> list: """ Fetches all available episode files, corresponding to the specified TV show. Multiple files for the same episode may be retrieved. The TV show to obtain the episodes from is identified by some reference that uniquely identifies it within the episode source in question. :param tvshow_reference: reference that uniquely identifies the TV show to get the episodes for :return: a list containing all episode files available for the specified TV Show. An empty list if none is found. :raise TVShowNotFound: if the specified reference does not match to any TV show available """
... @abstractmethod def fetch(self, tvshow_reference: str) -> list: """ Fetches all available episode files, corresponding to the specified TV show. Multiple files for the same episode may be retrieved. ...
763073bc71e59953b7010840fc7923fc15881265
tests/scoring_engine/models/test_settings.py
tests/scoring_engine/models/test_settings.py
from scoring_engine.models.setting import Setting from tests.scoring_engine.unit_test import UnitTest class TestSetting(UnitTest): def test_init_setting(self): setting = Setting(name='test_setting', value='test value example') assert setting.id is None assert setting.name == 'test_setting' assert setting.value == 'test value example' self.session.add(setting) self.session.commit() assert setting.id is not None def test_get_setting(self): setting_old = Setting(name='test_setting', value='test value example') self.session.add(setting_old) setting_new = Setting(name='test_setting', value='updated example') self.session.add(setting_new) self.session.commit() assert Setting.get_setting('test_setting', self.session).value == 'updated example'
from scoring_engine.models.setting import Setting from tests.scoring_engine.unit_test import UnitTest class TestSetting(UnitTest): def test_init_setting(self): setting = Setting(name='test_setting', value='test value example') assert setting.id is None assert setting.name == 'test_setting' assert setting.value == 'test value example' self.session.add(setting) self.session.commit() assert setting.id is not None def test_get_setting(self): setting_old = Setting(name='test_setting', value='test value example') self.session.add(setting_old) setting_new = Setting(name='test_setting', value='updated example') self.session.add(setting_new) self.session.commit() assert Setting.get_setting('test_setting').value == 'updated example'
Remove leftover parameter in settings tests
Remove leftover parameter in settings tests
Python
mit
pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine
from scoring_engine.models.setting import Setting from tests.scoring_engine.unit_test import UnitTest class TestSetting(UnitTest): def test_init_setting(self): setting = Setting(name='test_setting', value='test value example') assert setting.id is None assert setting.name == 'test_setting' assert setting.value == 'test value example' self.session.add(setting) self.session.commit() assert setting.id is not None def test_get_setting(self): setting_old = Setting(name='test_setting', value='test value example') self.session.add(setting_old) setting_new = Setting(name='test_setting', value='updated example') self.session.add(setting_new) self.session.commit() - assert Setting.get_setting('test_setting', self.session).value == 'updated example' + assert Setting.get_setting('test_setting').value == 'updated example'
Remove leftover parameter in settings tests
## Code Before: from scoring_engine.models.setting import Setting from tests.scoring_engine.unit_test import UnitTest class TestSetting(UnitTest): def test_init_setting(self): setting = Setting(name='test_setting', value='test value example') assert setting.id is None assert setting.name == 'test_setting' assert setting.value == 'test value example' self.session.add(setting) self.session.commit() assert setting.id is not None def test_get_setting(self): setting_old = Setting(name='test_setting', value='test value example') self.session.add(setting_old) setting_new = Setting(name='test_setting', value='updated example') self.session.add(setting_new) self.session.commit() assert Setting.get_setting('test_setting', self.session).value == 'updated example' ## Instruction: Remove leftover parameter in settings tests ## Code After: from scoring_engine.models.setting import Setting from tests.scoring_engine.unit_test import UnitTest class TestSetting(UnitTest): def test_init_setting(self): setting = Setting(name='test_setting', value='test value example') assert setting.id is None assert setting.name == 'test_setting' assert setting.value == 'test value example' self.session.add(setting) self.session.commit() assert setting.id is not None def test_get_setting(self): setting_old = Setting(name='test_setting', value='test value example') self.session.add(setting_old) setting_new = Setting(name='test_setting', value='updated example') self.session.add(setting_new) self.session.commit() assert Setting.get_setting('test_setting').value == 'updated example'
# ... existing code ... self.session.commit() assert Setting.get_setting('test_setting').value == 'updated example' # ... rest of the code ...
1bc95e2e2a2d4d0daf6cfcdbf7e4803b13262a49
etcd3/__init__.py
etcd3/__init__.py
from __future__ import absolute_import __author__ = 'Louis Taylor' __email__ = '[email protected]' __version__ = '0.1.0' import grpc from etcdrpc import rpc_pb2 as etcdrpc channel = grpc.insecure_channel('localhost:2379') stub = etcdrpc.KVStub(channel) put_request = etcdrpc.PutRequest() put_request.key = 'doot'.encode('utf-8') put_request.value = 'toottoot'.encode('utf-8') print(stub.Put(put_request)) class Etcd3Client(object): def __init__(self): pass def get(self, key): pass def put(self, key, value): pass
from __future__ import absolute_import __author__ = 'Louis Taylor' __email__ = '[email protected]' __version__ = '0.1.0' import grpc from etcdrpc import rpc_pb2 as etcdrpc class Etcd3Client(object): def __init__(self): self.channel = grpc.insecure_channel('localhost:2379') self.kvstub = etcdrpc.KVStub(channel) def get(self, key): pass def put(self, key, value): put_request = etcdrpc.PutRequest() put_request.key = key.encode('utf-8') put_request.value = value.encode('utf-8') self.kvstub.Put(put_request)
Move put code into method
Move put code into method
Python
apache-2.0
kragniz/python-etcd3
from __future__ import absolute_import __author__ = 'Louis Taylor' __email__ = '[email protected]' __version__ = '0.1.0' import grpc from etcdrpc import rpc_pb2 as etcdrpc - channel = grpc.insecure_channel('localhost:2379') - stub = etcdrpc.KVStub(channel) - - put_request = etcdrpc.PutRequest() - put_request.key = 'doot'.encode('utf-8') - put_request.value = 'toottoot'.encode('utf-8') - print(stub.Put(put_request)) - class Etcd3Client(object): def __init__(self): - pass + self.channel = grpc.insecure_channel('localhost:2379') + self.kvstub = etcdrpc.KVStub(channel) def get(self, key): pass def put(self, key, value): - pass + put_request = etcdrpc.PutRequest() + put_request.key = key.encode('utf-8') + put_request.value = value.encode('utf-8') + self.kvstub.Put(put_request)
Move put code into method
## Code Before: from __future__ import absolute_import __author__ = 'Louis Taylor' __email__ = '[email protected]' __version__ = '0.1.0' import grpc from etcdrpc import rpc_pb2 as etcdrpc channel = grpc.insecure_channel('localhost:2379') stub = etcdrpc.KVStub(channel) put_request = etcdrpc.PutRequest() put_request.key = 'doot'.encode('utf-8') put_request.value = 'toottoot'.encode('utf-8') print(stub.Put(put_request)) class Etcd3Client(object): def __init__(self): pass def get(self, key): pass def put(self, key, value): pass ## Instruction: Move put code into method ## Code After: from __future__ import absolute_import __author__ = 'Louis Taylor' __email__ = '[email protected]' __version__ = '0.1.0' import grpc from etcdrpc import rpc_pb2 as etcdrpc class Etcd3Client(object): def __init__(self): self.channel = grpc.insecure_channel('localhost:2379') self.kvstub = etcdrpc.KVStub(channel) def get(self, key): pass def put(self, key, value): put_request = etcdrpc.PutRequest() put_request.key = key.encode('utf-8') put_request.value = value.encode('utf-8') self.kvstub.Put(put_request)
... ... def __init__(self): self.channel = grpc.insecure_channel('localhost:2379') self.kvstub = etcdrpc.KVStub(channel) ... def put(self, key, value): put_request = etcdrpc.PutRequest() put_request.key = key.encode('utf-8') put_request.value = value.encode('utf-8') self.kvstub.Put(put_request) ...
cfde8a339c52c1875cb3b863ace3cad6174eb54c
account_cost_spread/models/account_invoice.py
account_cost_spread/models/account_invoice.py
from odoo import api, models class AccountInvoice(models.Model): _inherit = 'account.invoice' @api.multi def action_move_create(self): """Override, button Validate on invoices.""" res = super(AccountInvoice, self).action_move_create() for rec in self: rec.invoice_line_ids.compute_spread_board() return res @api.multi def invoice_line_move_line_get(self): res = super(AccountInvoice, self).invoice_line_move_line_get() for line in res: invl_id = line.get('invl_id') invl = self.env['account.invoice.line'].browse(invl_id) if invl.spread_account_id: line['account_id'] = invl.spread_account_id.id return res @api.multi def action_invoice_cancel(self): res = self.action_cancel() for invoice in self: for invoice_line in invoice.invoice_line_ids: for spread_line in invoice_line.spread_line_ids: if spread_line.move_id: spread_line.move_id.button_cancel() spread_line.move_id.unlink() spread_line.unlink() return res
from odoo import api, models class AccountInvoice(models.Model): _inherit = 'account.invoice' @api.multi def action_move_create(self): """Invoked when validating the invoices.""" res = super(AccountInvoice, self).action_move_create() for rec in self: rec.invoice_line_ids.compute_spread_board() return res @api.multi def invoice_line_move_line_get(self): res = super(AccountInvoice, self).invoice_line_move_line_get() for line in res: invl_id = line.get('invl_id') invl = self.env['account.invoice.line'].browse(invl_id) if invl.spread_account_id: line['account_id'] = invl.spread_account_id.id return res @api.multi def action_invoice_cancel(self): res = self.action_cancel() for invoice in self: for invoice_line in invoice.invoice_line_ids: for spread_line in invoice_line.spread_line_ids: if spread_line.move_id: spread_line.move_id.button_cancel() spread_line.move_id.unlink() spread_line.unlink() return res
Fix method description in account_cost_spread
Fix method description in account_cost_spread
Python
agpl-3.0
onesteinbv/addons-onestein,onesteinbv/addons-onestein,onesteinbv/addons-onestein
from odoo import api, models class AccountInvoice(models.Model): _inherit = 'account.invoice' @api.multi def action_move_create(self): - """Override, button Validate on invoices.""" + """Invoked when validating the invoices.""" res = super(AccountInvoice, self).action_move_create() for rec in self: rec.invoice_line_ids.compute_spread_board() return res @api.multi def invoice_line_move_line_get(self): res = super(AccountInvoice, self).invoice_line_move_line_get() for line in res: invl_id = line.get('invl_id') invl = self.env['account.invoice.line'].browse(invl_id) if invl.spread_account_id: line['account_id'] = invl.spread_account_id.id return res @api.multi def action_invoice_cancel(self): res = self.action_cancel() for invoice in self: for invoice_line in invoice.invoice_line_ids: for spread_line in invoice_line.spread_line_ids: if spread_line.move_id: spread_line.move_id.button_cancel() spread_line.move_id.unlink() spread_line.unlink() return res
Fix method description in account_cost_spread
## Code Before: from odoo import api, models class AccountInvoice(models.Model): _inherit = 'account.invoice' @api.multi def action_move_create(self): """Override, button Validate on invoices.""" res = super(AccountInvoice, self).action_move_create() for rec in self: rec.invoice_line_ids.compute_spread_board() return res @api.multi def invoice_line_move_line_get(self): res = super(AccountInvoice, self).invoice_line_move_line_get() for line in res: invl_id = line.get('invl_id') invl = self.env['account.invoice.line'].browse(invl_id) if invl.spread_account_id: line['account_id'] = invl.spread_account_id.id return res @api.multi def action_invoice_cancel(self): res = self.action_cancel() for invoice in self: for invoice_line in invoice.invoice_line_ids: for spread_line in invoice_line.spread_line_ids: if spread_line.move_id: spread_line.move_id.button_cancel() spread_line.move_id.unlink() spread_line.unlink() return res ## Instruction: Fix method description in account_cost_spread ## Code After: from odoo import api, models class AccountInvoice(models.Model): _inherit = 'account.invoice' @api.multi def action_move_create(self): """Invoked when validating the invoices.""" res = super(AccountInvoice, self).action_move_create() for rec in self: rec.invoice_line_ids.compute_spread_board() return res @api.multi def invoice_line_move_line_get(self): res = super(AccountInvoice, self).invoice_line_move_line_get() for line in res: invl_id = line.get('invl_id') invl = self.env['account.invoice.line'].browse(invl_id) if invl.spread_account_id: line['account_id'] = invl.spread_account_id.id return res @api.multi def action_invoice_cancel(self): res = self.action_cancel() for invoice in self: for invoice_line in invoice.invoice_line_ids: for spread_line in invoice_line.spread_line_ids: if spread_line.move_id: spread_line.move_id.button_cancel() spread_line.move_id.unlink() spread_line.unlink() return res
... def action_move_create(self): """Invoked when validating the invoices.""" res = super(AccountInvoice, self).action_move_create() ...
55d22f95301c4c96c42e30fa037df5bc957dc7b4
incunafein/module/page/extensions/prepared_date.py
incunafein/module/page/extensions/prepared_date.py
from django.db import models def register(cls, admin_cls): cls.add_to_class('prepared_date', models.TextField('Date of Preparation', blank=True, null=True))
from django.db import models def get_prepared_date(cls): return cls.prepared_date or cls.parent.prepared_date def register(cls, admin_cls): cls.add_to_class('prepared_date', models.TextField('Date of Preparation', blank=True, null=True)) cls.add_to_class('get_prepared_date', get_prepared_date)
Add a get prepared date method
Add a get prepared date method Child pages won't necessarily have a prepared date and it makes sense to use the parent date to avoid repetition.
Python
bsd-2-clause
incuna/incuna-feincms,incuna/incuna-feincms,incuna/incuna-feincms
from django.db import models + + def get_prepared_date(cls): + return cls.prepared_date or cls.parent.prepared_date def register(cls, admin_cls): cls.add_to_class('prepared_date', models.TextField('Date of Preparation', blank=True, null=True)) + cls.add_to_class('get_prepared_date', get_prepared_date)
Add a get prepared date method
## Code Before: from django.db import models def register(cls, admin_cls): cls.add_to_class('prepared_date', models.TextField('Date of Preparation', blank=True, null=True)) ## Instruction: Add a get prepared date method ## Code After: from django.db import models def get_prepared_date(cls): return cls.prepared_date or cls.parent.prepared_date def register(cls, admin_cls): cls.add_to_class('prepared_date', models.TextField('Date of Preparation', blank=True, null=True)) cls.add_to_class('get_prepared_date', get_prepared_date)
// ... existing code ... from django.db import models def get_prepared_date(cls): return cls.prepared_date or cls.parent.prepared_date // ... modified code ... cls.add_to_class('prepared_date', models.TextField('Date of Preparation', blank=True, null=True)) cls.add_to_class('get_prepared_date', get_prepared_date) // ... rest of the code ...
237faf53129e575faafad6cfeecf96c707d50c4b
examples/common.py
examples/common.py
def print_devices(b): for device in sorted(b.devices, key=lambda d: len(d.ancestors)): print(device) # this is a blivet.devices.StorageDevice instance print()
def print_devices(b): print(b.devicetree)
Use DeviceTree.__str__ when printing devices in examples.
Use DeviceTree.__str__ when printing devices in examples.
Python
lgpl-2.1
AdamWill/blivet,vojtechtrefny/blivet,rhinstaller/blivet,vpodzime/blivet,vojtechtrefny/blivet,AdamWill/blivet,rvykydal/blivet,rvykydal/blivet,jkonecny12/blivet,rhinstaller/blivet,jkonecny12/blivet,vpodzime/blivet
def print_devices(b): + print(b.devicetree) - for device in sorted(b.devices, key=lambda d: len(d.ancestors)): - print(device) # this is a blivet.devices.StorageDevice instance - print() -
Use DeviceTree.__str__ when printing devices in examples.
## Code Before: def print_devices(b): for device in sorted(b.devices, key=lambda d: len(d.ancestors)): print(device) # this is a blivet.devices.StorageDevice instance print() ## Instruction: Use DeviceTree.__str__ when printing devices in examples. ## Code After: def print_devices(b): print(b.devicetree)
... def print_devices(b): print(b.devicetree) ...
978b9450346f4de687ed3c23bc11c970538e948b
mosecom_air/api/parser.py
mosecom_air/api/parser.py
from collections import namedtuple Substance = namedtuple('Substance', 'name alias') Measurement = namedtuple('Measurement', 'substance unit performed value') Result = namedtuple('Result', 'measurements substances units station_alias')
from collections import namedtuple Substance = namedtuple('Substance', ('name', 'alias')) Measurement = namedtuple('Measurement', ('substance', 'unit', 'performed', 'value')) Result = namedtuple('Result', ('measurements', 'substances', 'units', 'station_alias'))
Use tuple in namedtuples initization
Use tuple in namedtuples initization
Python
mit
elsid/mosecom-air,elsid/mosecom-air,elsid/mosecom-air
from collections import namedtuple - Substance = namedtuple('Substance', 'name alias') + Substance = namedtuple('Substance', ('name', 'alias')) - Measurement = namedtuple('Measurement', 'substance unit performed value') + Measurement = namedtuple('Measurement', ('substance', 'unit', 'performed', + 'value')) - Result = namedtuple('Result', 'measurements substances units station_alias') + Result = namedtuple('Result', ('measurements', 'substances', 'units', + 'station_alias'))
Use tuple in namedtuples initization
## Code Before: from collections import namedtuple Substance = namedtuple('Substance', 'name alias') Measurement = namedtuple('Measurement', 'substance unit performed value') Result = namedtuple('Result', 'measurements substances units station_alias') ## Instruction: Use tuple in namedtuples initization ## Code After: from collections import namedtuple Substance = namedtuple('Substance', ('name', 'alias')) Measurement = namedtuple('Measurement', ('substance', 'unit', 'performed', 'value')) Result = namedtuple('Result', ('measurements', 'substances', 'units', 'station_alias'))
... Substance = namedtuple('Substance', ('name', 'alias')) Measurement = namedtuple('Measurement', ('substance', 'unit', 'performed', 'value')) Result = namedtuple('Result', ('measurements', 'substances', 'units', 'station_alias')) ...
8ad4627973db344e228a9170aef030ab58efdeb9
src/ggrc/converters/__init__.py
src/ggrc/converters/__init__.py
from ggrc.converters.sections import SectionsConverter all_converters = [('sections', SectionsConverter)] HANDLERS = {} def get_converter(name): return all_converters(name)
from ggrc.converters.sections import SectionsConverter from ggrc.models import ( Audit, Control, ControlAssessment, DataAsset, Directive, Contract, Policy, Regulation, Standard, Facility, Market, Objective, Option, OrgGroup, Vendor, Person, Product, Program, Project, Request, Response, Section, Clause, System, Process, Issue, ) all_converters = [('sections', SectionsConverter)] HANDLERS = {} def get_converter(name): return all_converters(name) COLUMN_ORDER = ( "slug", "title", "description", "notes", "owners", ) IMPORTABLE = { "audit": Audit, "control": Control, "control assessment": ControlAssessment, "control_assessment": ControlAssessment, "data asset": DataAsset, "data_asset": DataAsset, "directive": Directive, "contract": Contract, "policy": Policy, "regulation": Regulation, "standard": Standard, "facility": Facility, "market": Market, "objective": Objective, "option": Option, "org group": OrgGroup, "org_group": OrgGroup, "vendor": Vendor, "person": Person, "product": Product, "program": Program, "project": Project, "request": Request, "response": Response, "section": Section, "clause": Clause, "system": System, "process": Process, "issue": Issue, }
Add column order and importable objects lists
Add column order and importable objects lists
Python
apache-2.0
edofic/ggrc-core,hasanalom/ggrc-core,AleksNeStu/ggrc-core,AleksNeStu/ggrc-core,plamut/ggrc-core,NejcZupec/ggrc-core,selahssea/ggrc-core,jmakov/ggrc-core,j0gurt/ggrc-core,NejcZupec/ggrc-core,NejcZupec/ggrc-core,josthkko/ggrc-core,jmakov/ggrc-core,VinnieJohns/ggrc-core,edofic/ggrc-core,selahssea/ggrc-core,hyperNURb/ggrc-core,jmakov/ggrc-core,hasanalom/ggrc-core,andrei-karalionak/ggrc-core,hasanalom/ggrc-core,AleksNeStu/ggrc-core,kr41/ggrc-core,VinnieJohns/ggrc-core,hyperNURb/ggrc-core,edofic/ggrc-core,uskudnik/ggrc-core,plamut/ggrc-core,hyperNURb/ggrc-core,prasannav7/ggrc-core,andrei-karalionak/ggrc-core,uskudnik/ggrc-core,VinnieJohns/ggrc-core,andrei-karalionak/ggrc-core,selahssea/ggrc-core,hasanalom/ggrc-core,AleksNeStu/ggrc-core,kr41/ggrc-core,josthkko/ggrc-core,NejcZupec/ggrc-core,uskudnik/ggrc-core,prasannav7/ggrc-core,jmakov/ggrc-core,hyperNURb/ggrc-core,j0gurt/ggrc-core,hyperNURb/ggrc-core,josthkko/ggrc-core,josthkko/ggrc-core,kr41/ggrc-core,edofic/ggrc-core,hasanalom/ggrc-core,kr41/ggrc-core,uskudnik/ggrc-core,andrei-karalionak/ggrc-core,selahssea/ggrc-core,prasannav7/ggrc-core,jmakov/ggrc-core,j0gurt/ggrc-core,uskudnik/ggrc-core,plamut/ggrc-core,plamut/ggrc-core,prasannav7/ggrc-core,VinnieJohns/ggrc-core,j0gurt/ggrc-core
from ggrc.converters.sections import SectionsConverter + from ggrc.models import ( + Audit, Control, ControlAssessment, DataAsset, Directive, Contract, + Policy, Regulation, Standard, Facility, Market, Objective, Option, + OrgGroup, Vendor, Person, Product, Program, Project, Request, Response, + Section, Clause, System, Process, Issue, + ) + all_converters = [('sections', SectionsConverter)] HANDLERS = {} + def get_converter(name): return all_converters(name) + COLUMN_ORDER = ( + "slug", + "title", + "description", + "notes", + "owners", + ) + + IMPORTABLE = { + "audit": Audit, + "control": Control, + "control assessment": ControlAssessment, + "control_assessment": ControlAssessment, + "data asset": DataAsset, + "data_asset": DataAsset, + "directive": Directive, + "contract": Contract, + "policy": Policy, + "regulation": Regulation, + "standard": Standard, + "facility": Facility, + "market": Market, + "objective": Objective, + "option": Option, + "org group": OrgGroup, + "org_group": OrgGroup, + "vendor": Vendor, + "person": Person, + "product": Product, + "program": Program, + "project": Project, + "request": Request, + "response": Response, + "section": Section, + "clause": Clause, + "system": System, + "process": Process, + "issue": Issue, + } +
Add column order and importable objects lists
## Code Before: from ggrc.converters.sections import SectionsConverter all_converters = [('sections', SectionsConverter)] HANDLERS = {} def get_converter(name): return all_converters(name) ## Instruction: Add column order and importable objects lists ## Code After: from ggrc.converters.sections import SectionsConverter from ggrc.models import ( Audit, Control, ControlAssessment, DataAsset, Directive, Contract, Policy, Regulation, Standard, Facility, Market, Objective, Option, OrgGroup, Vendor, Person, Product, Program, Project, Request, Response, Section, Clause, System, Process, Issue, ) all_converters = [('sections', SectionsConverter)] HANDLERS = {} def get_converter(name): return all_converters(name) COLUMN_ORDER = ( "slug", "title", "description", "notes", "owners", ) IMPORTABLE = { "audit": Audit, "control": Control, "control assessment": ControlAssessment, "control_assessment": ControlAssessment, "data asset": DataAsset, "data_asset": DataAsset, "directive": Directive, "contract": Contract, "policy": Policy, "regulation": Regulation, "standard": Standard, "facility": Facility, "market": Market, "objective": Objective, "option": Option, "org group": OrgGroup, "org_group": OrgGroup, "vendor": Vendor, "person": Person, "product": Product, "program": Program, "project": Project, "request": Request, "response": Response, "section": Section, "clause": Clause, "system": System, "process": Process, "issue": Issue, }
// ... existing code ... from ggrc.converters.sections import SectionsConverter from ggrc.models import ( Audit, Control, ControlAssessment, DataAsset, Directive, Contract, Policy, Regulation, Standard, Facility, Market, Objective, Option, OrgGroup, Vendor, Person, Product, Program, Project, Request, Response, Section, Clause, System, Process, Issue, ) // ... modified code ... def get_converter(name): ... return all_converters(name) COLUMN_ORDER = ( "slug", "title", "description", "notes", "owners", ) IMPORTABLE = { "audit": Audit, "control": Control, "control assessment": ControlAssessment, "control_assessment": ControlAssessment, "data asset": DataAsset, "data_asset": DataAsset, "directive": Directive, "contract": Contract, "policy": Policy, "regulation": Regulation, "standard": Standard, "facility": Facility, "market": Market, "objective": Objective, "option": Option, "org group": OrgGroup, "org_group": OrgGroup, "vendor": Vendor, "person": Person, "product": Product, "program": Program, "project": Project, "request": Request, "response": Response, "section": Section, "clause": Clause, "system": System, "process": Process, "issue": Issue, } // ... rest of the code ...
d08973c3854d10755e156b1457972a8aaebb251b
bottle_utils/form/__init__.py
bottle_utils/form/__init__.py
from .exceptions import ValidationError from .fields import (DormantField, Field, StringField, PasswordField, HiddenField, EmailField, TextAreaField, DateField, FileField, IntegerField, FloatField, BooleanField, SelectField) from .forms import Form from .validators import Validator, Required, DateValidator, InRangeValidator __all__ = ['ValidationError', 'DormantField', 'Field', 'StringField', 'PasswordField', 'HiddenField', 'EmailField', 'TextAreaField', 'DateField', 'FileField', 'IntegerField', 'FloatField', 'BooleanField', 'SelectField', 'Form', 'Validator', 'Required', 'DateValidator', 'InRangeValidator']
from .exceptions import ValidationError from .fields import (DormantField, Field, StringField, PasswordField, HiddenField, EmailField, TextAreaField, DateField, FileField, IntegerField, FloatField, BooleanField, SelectField) from .forms import Form from .validators import (Validator, Required, DateValidator, InRangeValidator, LengthValidator) __all__ = ['ValidationError', 'DormantField', 'Field', 'StringField', 'PasswordField', 'HiddenField', 'EmailField', 'TextAreaField', 'DateField', 'FileField', 'IntegerField', 'FloatField', 'BooleanField', 'SelectField', 'Form', 'Validator', 'Required', 'DateValidator', 'InRangeValidator']
Include LengthValidator in list of exporeted objects
Include LengthValidator in list of exporeted objects Signed-off-by: Branko Vukelic <[email protected]>
Python
bsd-2-clause
Outernet-Project/bottle-utils
from .exceptions import ValidationError from .fields import (DormantField, Field, StringField, PasswordField, HiddenField, EmailField, TextAreaField, DateField, FileField, IntegerField, FloatField, BooleanField, SelectField) from .forms import Form - from .validators import Validator, Required, DateValidator, InRangeValidator + from .validators import (Validator, Required, DateValidator, InRangeValidator, + LengthValidator) __all__ = ['ValidationError', 'DormantField', 'Field', 'StringField', 'PasswordField', 'HiddenField', 'EmailField', 'TextAreaField', 'DateField', 'FileField', 'IntegerField', 'FloatField', 'BooleanField', 'SelectField', 'Form', 'Validator', 'Required', 'DateValidator', 'InRangeValidator']
Include LengthValidator in list of exporeted objects
## Code Before: from .exceptions import ValidationError from .fields import (DormantField, Field, StringField, PasswordField, HiddenField, EmailField, TextAreaField, DateField, FileField, IntegerField, FloatField, BooleanField, SelectField) from .forms import Form from .validators import Validator, Required, DateValidator, InRangeValidator __all__ = ['ValidationError', 'DormantField', 'Field', 'StringField', 'PasswordField', 'HiddenField', 'EmailField', 'TextAreaField', 'DateField', 'FileField', 'IntegerField', 'FloatField', 'BooleanField', 'SelectField', 'Form', 'Validator', 'Required', 'DateValidator', 'InRangeValidator'] ## Instruction: Include LengthValidator in list of exporeted objects ## Code After: from .exceptions import ValidationError from .fields import (DormantField, Field, StringField, PasswordField, HiddenField, EmailField, TextAreaField, DateField, FileField, IntegerField, FloatField, BooleanField, SelectField) from .forms import Form from .validators import (Validator, Required, DateValidator, InRangeValidator, LengthValidator) __all__ = ['ValidationError', 'DormantField', 'Field', 'StringField', 'PasswordField', 'HiddenField', 'EmailField', 'TextAreaField', 'DateField', 'FileField', 'IntegerField', 'FloatField', 'BooleanField', 'SelectField', 'Form', 'Validator', 'Required', 'DateValidator', 'InRangeValidator']
// ... existing code ... from .forms import Form from .validators import (Validator, Required, DateValidator, InRangeValidator, LengthValidator) // ... rest of the code ...
d4da069b43174482f3a75e9553e8283be905fa16
cla_public/apps/base/filters.py
cla_public/apps/base/filters.py
"Jinja custom filters" import re from cla_public.apps.base import base from babel.dates import format_datetime @base.app_template_filter() def datetime(dt, format='medium', locale='en_GB'): if format == 'full': format = "EEEE, d MMMM y 'at' HH:mm" elif format == 'medium': format = "EE, dd/MM/y 'at' h:mma" elif format == 'short': format = "dd/MM/y, h:mma" return format_datetime(dt, format, locale=locale) @base.app_template_filter() def url_to_human(value): return re.sub(r'(^https?://)|(/$)', '', value) @base.app_template_filter() def human_to_url(value): return re.sub(r'^((?!https?://).*)', r'http://\1', value) @base.app_template_filter() def query_to_dict(value, prop=None): result = parse_qs(urlparse(value).query) if prop: result = result[prop] return result
"Jinja custom filters" import re from urlparse import urlparse, parse_qs from cla_public.apps.base import base from babel.dates import format_datetime @base.app_template_filter() def datetime(dt, format='medium', locale='en_GB'): if format == 'full': format = "EEEE, d MMMM y 'at' HH:mm" elif format == 'medium': format = "EE, dd/MM/y 'at' h:mma" elif format == 'short': format = "dd/MM/y, h:mma" return format_datetime(dt, format, locale=locale) @base.app_template_filter() def url_to_human(value): return re.sub(r'(^https?://)|(/$)', '', value) @base.app_template_filter() def human_to_url(value): return re.sub(r'^((?!https?://).*)', r'http://\1', value) @base.app_template_filter() def query_to_dict(value, prop=None): result = parse_qs(urlparse(value).query) if prop: result = result[prop] return result
Add Jinja filter to convert URL params to dict
BE: Add Jinja filter to convert URL params to dict
Python
mit
ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public
"Jinja custom filters" import re + from urlparse import urlparse, parse_qs from cla_public.apps.base import base from babel.dates import format_datetime @base.app_template_filter() def datetime(dt, format='medium', locale='en_GB'): if format == 'full': format = "EEEE, d MMMM y 'at' HH:mm" elif format == 'medium': format = "EE, dd/MM/y 'at' h:mma" elif format == 'short': format = "dd/MM/y, h:mma" return format_datetime(dt, format, locale=locale) @base.app_template_filter() def url_to_human(value): return re.sub(r'(^https?://)|(/$)', '', value) @base.app_template_filter() def human_to_url(value): return re.sub(r'^((?!https?://).*)', r'http://\1', value) @base.app_template_filter() def query_to_dict(value, prop=None): result = parse_qs(urlparse(value).query) if prop: result = result[prop] return result
Add Jinja filter to convert URL params to dict
## Code Before: "Jinja custom filters" import re from cla_public.apps.base import base from babel.dates import format_datetime @base.app_template_filter() def datetime(dt, format='medium', locale='en_GB'): if format == 'full': format = "EEEE, d MMMM y 'at' HH:mm" elif format == 'medium': format = "EE, dd/MM/y 'at' h:mma" elif format == 'short': format = "dd/MM/y, h:mma" return format_datetime(dt, format, locale=locale) @base.app_template_filter() def url_to_human(value): return re.sub(r'(^https?://)|(/$)', '', value) @base.app_template_filter() def human_to_url(value): return re.sub(r'^((?!https?://).*)', r'http://\1', value) @base.app_template_filter() def query_to_dict(value, prop=None): result = parse_qs(urlparse(value).query) if prop: result = result[prop] return result ## Instruction: Add Jinja filter to convert URL params to dict ## Code After: "Jinja custom filters" import re from urlparse import urlparse, parse_qs from cla_public.apps.base import base from babel.dates import format_datetime @base.app_template_filter() def datetime(dt, format='medium', locale='en_GB'): if format == 'full': format = "EEEE, d MMMM y 'at' HH:mm" elif format == 'medium': format = "EE, dd/MM/y 'at' h:mma" elif format == 'short': format = "dd/MM/y, h:mma" return format_datetime(dt, format, locale=locale) @base.app_template_filter() def url_to_human(value): return re.sub(r'(^https?://)|(/$)', '', value) @base.app_template_filter() def human_to_url(value): return re.sub(r'^((?!https?://).*)', r'http://\1', value) @base.app_template_filter() def query_to_dict(value, prop=None): result = parse_qs(urlparse(value).query) if prop: result = result[prop] return result
# ... existing code ... import re from urlparse import urlparse, parse_qs from cla_public.apps.base import base # ... rest of the code ...
27ee536137a98a317f2cfbb2010fa5fe31037e99
txircd/modules/cmd_user.py
txircd/modules/cmd_user.py
from twisted.words.protocols import irc from txircd.modbase import Command class UserCommand(Command): def onUse(self, user, params): if user.registered == 0: self.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)") return if params and len(params) < 4: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Not enough parameters") if not user.username: user.registered -= 1 user.username = filter(lambda x: x in string.ascii_letters + string.digits + "-_", params[0])[:12] if not user.username: user.registered += 1 user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Your username is not valid") return user.realname = params[3] if user.registered == 0: user.register() def Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(): return { "commands": { "USER": UserCommand() } } def cleanup(): del self.ircd.commands["USER"]
from twisted.words.protocols import irc from txircd.modbase import Command class UserCommand(Command): def onUse(self, user, data): if not user.username: user.registered -= 1 user.username = data["ident"] user.realname = data["gecos"] if user.registered == 0: user.register() def processParams(self, user, params): if user.registered == 0: user.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)") return {} if params and len(params) < 4: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Not enough parameters") return {} ident = filter(lambda x: x in string.ascii_letters + string.digits + "-_", params[0])[:12] if not ident: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Your username is not valid") return {} return { "user": user, "ident": ident, "gecos": params[3] } def Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(): return { "commands": { "USER": UserCommand() } } def cleanup(): del self.ircd.commands["USER"]
Update the USER command to take advantage of core capabilities as well
Update the USER command to take advantage of core capabilities as well
Python
bsd-3-clause
DesertBus/txircd,Heufneutje/txircd,ElementalAlchemist/txircd
from twisted.words.protocols import irc from txircd.modbase import Command class UserCommand(Command): - def onUse(self, user, params): + def onUse(self, user, data): + if not user.username: + user.registered -= 1 + user.username = data["ident"] + user.realname = data["gecos"] if user.registered == 0: + user.register() + + def processParams(self, user, params): + if user.registered == 0: - self.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)") + user.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)") - return + return {} if params and len(params) < 4: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Not enough parameters") + return {} - if not user.username: - user.registered -= 1 - user.username = filter(lambda x: x in string.ascii_letters + string.digits + "-_", params[0])[:12] + ident = filter(lambda x: x in string.ascii_letters + string.digits + "-_", params[0])[:12] + if not ident: - if not user.username: - user.registered += 1 user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Your username is not valid") - return + return {} - user.realname = params[3] - if user.registered == 0: - user.register() + return { + "user": user, + "ident": ident, + "gecos": params[3] + } def Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(): return { "commands": { "USER": UserCommand() } } def cleanup(): del self.ircd.commands["USER"]
Update the USER command to take advantage of core capabilities as well
## Code Before: from twisted.words.protocols import irc from txircd.modbase import Command class UserCommand(Command): def onUse(self, user, params): if user.registered == 0: self.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)") return if params and len(params) < 4: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Not enough parameters") if not user.username: user.registered -= 1 user.username = filter(lambda x: x in string.ascii_letters + string.digits + "-_", params[0])[:12] if not user.username: user.registered += 1 user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Your username is not valid") return user.realname = params[3] if user.registered == 0: user.register() def Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(): return { "commands": { "USER": UserCommand() } } def cleanup(): del self.ircd.commands["USER"] ## Instruction: Update the USER command to take advantage of core capabilities as well ## Code After: from twisted.words.protocols import irc from txircd.modbase import Command class UserCommand(Command): def onUse(self, user, data): if not user.username: user.registered -= 1 user.username = data["ident"] user.realname = data["gecos"] if user.registered == 0: user.register() def processParams(self, user, params): if user.registered == 0: user.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)") return {} if params and len(params) < 4: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Not enough parameters") return {} ident = filter(lambda x: x in string.ascii_letters + string.digits + "-_", params[0])[:12] if not ident: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Your username is not valid") return {} return { "user": user, "ident": ident, "gecos": params[3] } def Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(): return { "commands": { "USER": UserCommand() } } def cleanup(): del self.ircd.commands["USER"]
// ... existing code ... class UserCommand(Command): def onUse(self, user, data): if not user.username: user.registered -= 1 user.username = data["ident"] user.realname = data["gecos"] if user.registered == 0: user.register() def processParams(self, user, params): if user.registered == 0: user.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)") return {} if params and len(params) < 4: // ... modified code ... user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Not enough parameters") return {} ident = filter(lambda x: x in string.ascii_letters + string.digits + "-_", params[0])[:12] if not ident: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Your username is not valid") return {} return { "user": user, "ident": ident, "gecos": params[3] } // ... rest of the code ...
d101b7f023db1583ca7b65899bfdef296f838ad2
openspending/ui/validation/source.py
openspending/ui/validation/source.py
from urlparse import urlparse from openspending.validation.model.common import mapping from openspending.validation.model.common import key from openspending.validation.model.predicates import chained, \ nonempty_string def valid_url(url): parsed = urlparse(url) if parsed.scheme.lower() not in ('http', 'https'): return "Only HTTP/HTTPS web addresses are supported " \ "at the moment." return True def source_schema(): schema = mapping('source') schema.add(key('url', validator=chained( nonempty_string, valid_url ))) return schema
from urlparse import urlparse from openspending.validation.model.common import mapping from openspending.validation.model.common import key from openspending.validation.model.predicates import chained, \ nonempty_string def valid_url(url): parsed = urlparse(url) if parsed.scheme.lower() not in ('http', 'https'): return "Only HTTP/HTTPS web addresses are supported " \ "at the moment." return True def source_schema(): schema = mapping('source') schema.add(key('url', validator=chained( nonempty_string, valid_url ))) return schema
Fix PEP8 issues in openspending/ui/validation.
Fix PEP8 issues in openspending/ui/validation.
Python
agpl-3.0
CivicVision/datahub,openspending/spendb,CivicVision/datahub,spendb/spendb,spendb/spendb,johnjohndoe/spendb,USStateDept/FPA_Core,nathanhilbert/FPA_Core,openspending/spendb,spendb/spendb,USStateDept/FPA_Core,USStateDept/FPA_Core,johnjohndoe/spendb,openspending/spendb,nathanhilbert/FPA_Core,johnjohndoe/spendb,pudo/spendb,nathanhilbert/FPA_Core,CivicVision/datahub,pudo/spendb,pudo/spendb
from urlparse import urlparse from openspending.validation.model.common import mapping from openspending.validation.model.common import key from openspending.validation.model.predicates import chained, \ nonempty_string + def valid_url(url): parsed = urlparse(url) if parsed.scheme.lower() not in ('http', 'https'): return "Only HTTP/HTTPS web addresses are supported " \ - "at the moment." + "at the moment." return True + def source_schema(): schema = mapping('source') schema.add(key('url', validator=chained( - nonempty_string, + nonempty_string, - valid_url + valid_url - ))) + ))) return schema - - - -
Fix PEP8 issues in openspending/ui/validation.
## Code Before: from urlparse import urlparse from openspending.validation.model.common import mapping from openspending.validation.model.common import key from openspending.validation.model.predicates import chained, \ nonempty_string def valid_url(url): parsed = urlparse(url) if parsed.scheme.lower() not in ('http', 'https'): return "Only HTTP/HTTPS web addresses are supported " \ "at the moment." return True def source_schema(): schema = mapping('source') schema.add(key('url', validator=chained( nonempty_string, valid_url ))) return schema ## Instruction: Fix PEP8 issues in openspending/ui/validation. ## Code After: from urlparse import urlparse from openspending.validation.model.common import mapping from openspending.validation.model.common import key from openspending.validation.model.predicates import chained, \ nonempty_string def valid_url(url): parsed = urlparse(url) if parsed.scheme.lower() not in ('http', 'https'): return "Only HTTP/HTTPS web addresses are supported " \ "at the moment." return True def source_schema(): schema = mapping('source') schema.add(key('url', validator=chained( nonempty_string, valid_url ))) return schema
# ... existing code ... def valid_url(url): # ... modified code ... return "Only HTTP/HTTPS web addresses are supported " \ "at the moment." return True ... schema.add(key('url', validator=chained( nonempty_string, valid_url ))) return schema # ... rest of the code ...
7cf37b966049cfc47ef200ad8ae69763d98185c5
collector/description/normal/L2.py
collector/description/normal/L2.py
from __future__ import absolute_import import math, utilities.operator from ...weight import WeightDict, normalize_exp from .L1 import phase_description # Normalised distances and L2-normalised (Euclidean norm) collector sets collector_weights = \ WeightDict(normalize_exp, (utilities.operator.square, math.sqrt), tags=('normalized'))
from __future__ import absolute_import import math, utilities.operator from ...weight import WeightDict, normalize_exp from .L1 import descriptions # Normalised distances and L2-normalised (Euclidean norm) collector sets weights = \ WeightDict(normalize_exp, (utilities.operator.square, math.sqrt), tags=('normalized'))
Update secondary collector description module
Update secondary collector description module
Python
mit
davidfoerster/schema-matching
from __future__ import absolute_import import math, utilities.operator from ...weight import WeightDict, normalize_exp - from .L1 import phase_description + from .L1 import descriptions # Normalised distances and L2-normalised (Euclidean norm) collector sets - collector_weights = \ + weights = \ WeightDict(normalize_exp, (utilities.operator.square, math.sqrt), tags=('normalized'))
Update secondary collector description module
## Code Before: from __future__ import absolute_import import math, utilities.operator from ...weight import WeightDict, normalize_exp from .L1 import phase_description # Normalised distances and L2-normalised (Euclidean norm) collector sets collector_weights = \ WeightDict(normalize_exp, (utilities.operator.square, math.sqrt), tags=('normalized')) ## Instruction: Update secondary collector description module ## Code After: from __future__ import absolute_import import math, utilities.operator from ...weight import WeightDict, normalize_exp from .L1 import descriptions # Normalised distances and L2-normalised (Euclidean norm) collector sets weights = \ WeightDict(normalize_exp, (utilities.operator.square, math.sqrt), tags=('normalized'))
// ... existing code ... from ...weight import WeightDict, normalize_exp from .L1 import descriptions // ... modified code ... # Normalised distances and L2-normalised (Euclidean norm) collector sets weights = \ WeightDict(normalize_exp, (utilities.operator.square, math.sqrt), // ... rest of the code ...
343524ddeac29e59d7c214a62a721c2065583503
setuptools_extversion/__init__.py
setuptools_extversion/__init__.py
VERSION_PROVIDER_KEY = 'extversion' def version_calc(dist, attr, value): """ Handler for parameter to setup(extversion=value) """ if attr == VERSION_PROVIDER_KEY: extversion = value dist.metadata.version = extversion(dist) class command(object): def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs def __call__(self, distribution, metadata, command): return subprocess.check_output(*self.args, **self.kwargs).strip() class function(object): def __init__(self, func, *args, **kwargs): self.func = func self.args = args self.kwargs = kwargs def __call__(self, *args, **kwargs): if isinstance(self.func, basestring): ep = pkg_resources.EntryPoint.parse('x=' + self.func) self.func = ep.load(False) args = list(self.args + args) kwargs = dict(self.kwargs) kwargs.update(kwargs) return self.func(*args, **kwargs)
import subprocess VERSION_PROVIDER_KEY = 'extversion' def version_calc(dist, attr, value): """ Handler for parameter to setup(extversion=value) """ if attr == VERSION_PROVIDER_KEY: if callable(value): extversion = value elif hasattr(value, 'get'): if value.get('command'): extversion = command(value.get('command'), shell=True) else: raise Exception('Unknown type for %s = %r' % (attr, value)) dist.metadata.version = extversion(dist) class command(object): def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs def __call__(self, distribution): return subprocess.check_output(*self.args, **self.kwargs).strip() class function(object): def __init__(self, func, *args, **kwargs): self.func = func self.args = args self.kwargs = kwargs def __call__(self, *args, **kwargs): if isinstance(self.func, basestring): ep = pkg_resources.EntryPoint.parse('x=' + self.func) self.func = ep.load(False) args = list(self.args + args) kwargs = dict(self.kwargs) kwargs.update(kwargs) return self.func(*args, **kwargs)
Add support for providing command string
Add support for providing command string User can provide a command string in a 'command' key -- e.g.: setup( ... setup_requires='setuptools_extversion', extversion={ 'command': 'git describe --tags --dirty', } ... )
Python
mit
msabramo/python_setuptools_extversion
+ + import subprocess + VERSION_PROVIDER_KEY = 'extversion' def version_calc(dist, attr, value): """ Handler for parameter to setup(extversion=value) """ if attr == VERSION_PROVIDER_KEY: + if callable(value): - extversion = value + extversion = value + elif hasattr(value, 'get'): + if value.get('command'): + extversion = command(value.get('command'), shell=True) + else: + raise Exception('Unknown type for %s = %r' % (attr, value)) dist.metadata.version = extversion(dist) class command(object): def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs - def __call__(self, distribution, metadata, command): + def __call__(self, distribution): return subprocess.check_output(*self.args, **self.kwargs).strip() class function(object): def __init__(self, func, *args, **kwargs): self.func = func self.args = args self.kwargs = kwargs def __call__(self, *args, **kwargs): if isinstance(self.func, basestring): ep = pkg_resources.EntryPoint.parse('x=' + self.func) self.func = ep.load(False) args = list(self.args + args) kwargs = dict(self.kwargs) kwargs.update(kwargs) return self.func(*args, **kwargs)
Add support for providing command string
## Code Before: VERSION_PROVIDER_KEY = 'extversion' def version_calc(dist, attr, value): """ Handler for parameter to setup(extversion=value) """ if attr == VERSION_PROVIDER_KEY: extversion = value dist.metadata.version = extversion(dist) class command(object): def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs def __call__(self, distribution, metadata, command): return subprocess.check_output(*self.args, **self.kwargs).strip() class function(object): def __init__(self, func, *args, **kwargs): self.func = func self.args = args self.kwargs = kwargs def __call__(self, *args, **kwargs): if isinstance(self.func, basestring): ep = pkg_resources.EntryPoint.parse('x=' + self.func) self.func = ep.load(False) args = list(self.args + args) kwargs = dict(self.kwargs) kwargs.update(kwargs) return self.func(*args, **kwargs) ## Instruction: Add support for providing command string ## Code After: import subprocess VERSION_PROVIDER_KEY = 'extversion' def version_calc(dist, attr, value): """ Handler for parameter to setup(extversion=value) """ if attr == VERSION_PROVIDER_KEY: if callable(value): extversion = value elif hasattr(value, 'get'): if value.get('command'): extversion = command(value.get('command'), shell=True) else: raise Exception('Unknown type for %s = %r' % (attr, value)) dist.metadata.version = extversion(dist) class command(object): def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs def __call__(self, distribution): return subprocess.check_output(*self.args, **self.kwargs).strip() class function(object): def __init__(self, func, *args, **kwargs): self.func = func self.args = args self.kwargs = kwargs def __call__(self, *args, **kwargs): if isinstance(self.func, basestring): ep = pkg_resources.EntryPoint.parse('x=' + self.func) self.func = ep.load(False) args = list(self.args + args) kwargs = dict(self.kwargs) kwargs.update(kwargs) return self.func(*args, **kwargs)
// ... existing code ... import subprocess // ... modified code ... if attr == VERSION_PROVIDER_KEY: if callable(value): extversion = value elif hasattr(value, 'get'): if value.get('command'): extversion = command(value.get('command'), shell=True) else: raise Exception('Unknown type for %s = %r' % (attr, value)) dist.metadata.version = extversion(dist) ... def __call__(self, distribution): return subprocess.check_output(*self.args, **self.kwargs).strip() // ... rest of the code ...
ec2d3feff6a1677457dfeb5b948b2013bc03df2a
classes/admin.py
classes/admin.py
from django.contrib import admin from classes.models import Attendee from classes.models import Attendance from classes.models import Session from classes.models import WalkinClass class AttendanceInline(admin.TabularInline): model = Attendance extra = 1 verbose_name = 'Attendee' verbose_name_plural = 'Attendees' fields = ('attendee', 'start_date_time', "stop_date_time", 'notes') # fieldsets = ( # ("Attendee", {'fields': ('name'),}), # ("Start Date Time", {"fields": ('start_date_time'),}), # ("Stop Date Time", {"fields": ('stop_date_time'),}), # ('Notes', {'fields': ('notes'),}), # ) class AttendeeAdmin(admin.ModelAdmin): pass class SessionAdmin(admin.ModelAdmin): inlines = [ AttendanceInline, ] fields = ('walk_in_class','teacher', 'start_date_time', "stop_date_time", ) list_display= ('walk_in_class', 'start_date_time',) class WalkinClassAdmin(admin.ModelAdmin): pass admin.site.register(Attendee, AttendeeAdmin) admin.site.register(Session, SessionAdmin) admin.site.register(WalkinClass, WalkinClassAdmin)
from django.contrib import admin from classes.models import Attendee from classes.models import Attendance from classes.models import Session from classes.models import WalkinClass class AttendanceInline(admin.TabularInline): model = Attendance extra = 1 verbose_name = 'Attendee' verbose_name_plural = 'Attendees' fields = ('attendee', 'start_date_time', "stop_date_time", 'notes') class SessionInline(admin.TabularInline): model = Session extra = 1 fields = ('start_date_time', 'stop_date_time', 'teacher') class AttendeeAdmin(admin.ModelAdmin): pass class SessionAdmin(admin.ModelAdmin): inlines = [ AttendanceInline, ] fields = ('walk_in_class','teacher', 'start_date_time', "stop_date_time", ) list_display= ('walk_in_class', 'start_date_time',) class WalkinClassAdmin(admin.ModelAdmin): inlines = [ SessionInline, ] admin.site.register(Attendee, AttendeeAdmin) admin.site.register(Session, SessionAdmin) admin.site.register(WalkinClass, WalkinClassAdmin)
Add sessions inline to classes
Add sessions inline to classes
Python
mit
thrive-refugee/thrive-refugee,thrive-refugee/thrive-refugee,thrive-refugee/thrive-refugee
from django.contrib import admin from classes.models import Attendee from classes.models import Attendance from classes.models import Session from classes.models import WalkinClass class AttendanceInline(admin.TabularInline): model = Attendance extra = 1 verbose_name = 'Attendee' verbose_name_plural = 'Attendees' fields = ('attendee', 'start_date_time', "stop_date_time", 'notes') - # fieldsets = ( - # ("Attendee", {'fields': ('name'),}), - # ("Start Date Time", {"fields": ('start_date_time'),}), - # ("Stop Date Time", {"fields": ('stop_date_time'),}), - # ('Notes', {'fields': ('notes'),}), - # ) + + + class SessionInline(admin.TabularInline): + model = Session + extra = 1 + fields = ('start_date_time', 'stop_date_time', 'teacher') class AttendeeAdmin(admin.ModelAdmin): pass class SessionAdmin(admin.ModelAdmin): inlines = [ AttendanceInline, ] fields = ('walk_in_class','teacher', 'start_date_time', "stop_date_time", ) list_display= ('walk_in_class', 'start_date_time',) class WalkinClassAdmin(admin.ModelAdmin): - pass + inlines = [ + SessionInline, + ] admin.site.register(Attendee, AttendeeAdmin) admin.site.register(Session, SessionAdmin) admin.site.register(WalkinClass, WalkinClassAdmin)
Add sessions inline to classes
## Code Before: from django.contrib import admin from classes.models import Attendee from classes.models import Attendance from classes.models import Session from classes.models import WalkinClass class AttendanceInline(admin.TabularInline): model = Attendance extra = 1 verbose_name = 'Attendee' verbose_name_plural = 'Attendees' fields = ('attendee', 'start_date_time', "stop_date_time", 'notes') # fieldsets = ( # ("Attendee", {'fields': ('name'),}), # ("Start Date Time", {"fields": ('start_date_time'),}), # ("Stop Date Time", {"fields": ('stop_date_time'),}), # ('Notes', {'fields': ('notes'),}), # ) class AttendeeAdmin(admin.ModelAdmin): pass class SessionAdmin(admin.ModelAdmin): inlines = [ AttendanceInline, ] fields = ('walk_in_class','teacher', 'start_date_time', "stop_date_time", ) list_display= ('walk_in_class', 'start_date_time',) class WalkinClassAdmin(admin.ModelAdmin): pass admin.site.register(Attendee, AttendeeAdmin) admin.site.register(Session, SessionAdmin) admin.site.register(WalkinClass, WalkinClassAdmin) ## Instruction: Add sessions inline to classes ## Code After: from django.contrib import admin from classes.models import Attendee from classes.models import Attendance from classes.models import Session from classes.models import WalkinClass class AttendanceInline(admin.TabularInline): model = Attendance extra = 1 verbose_name = 'Attendee' verbose_name_plural = 'Attendees' fields = ('attendee', 'start_date_time', "stop_date_time", 'notes') class SessionInline(admin.TabularInline): model = Session extra = 1 fields = ('start_date_time', 'stop_date_time', 'teacher') class AttendeeAdmin(admin.ModelAdmin): pass class SessionAdmin(admin.ModelAdmin): inlines = [ AttendanceInline, ] fields = ('walk_in_class','teacher', 'start_date_time', "stop_date_time", ) list_display= ('walk_in_class', 'start_date_time',) class WalkinClassAdmin(admin.ModelAdmin): inlines = [ SessionInline, ] admin.site.register(Attendee, AttendeeAdmin) admin.site.register(Session, SessionAdmin) admin.site.register(WalkinClass, WalkinClassAdmin)
... fields = ('attendee', 'start_date_time', "stop_date_time", 'notes') class SessionInline(admin.TabularInline): model = Session extra = 1 fields = ('start_date_time', 'stop_date_time', 'teacher') ... class WalkinClassAdmin(admin.ModelAdmin): inlines = [ SessionInline, ] ...
f4b92c2212ce2533860764fccdb5ff05df8b8059
die_bag.py
die_bag.py
import random class die_bag():#Class for rolling die/dices def __init__(self): self.data = [] def die(self, x, y = 1):#Roll a die and returns result result = [] for i in range(y): result.append(random.randint(1, x)) return result print result def take_input_die(self):#Take input from user eyes = int(raw_input('Number of eyes? ')) times = int(raw_input('Number of times? ')) #Call die dieRoll = die_bag.die(self, eyes, times) print dieRoll d_class = die_bag()#Create a instance of die_bag die_bag.take_input_die(d_class)#Call take_input_die #Why does this not work? die_bag.die(d_class, 20, 1)#Call die with parameters
import random """In this module, die or dices are rolled""" def die(x, y = 1): """Function for rolling a die or several dice, returns an array with results of dice rolls. Parameter x is number of eyes on a die. Parameter y = 1 is the times to a die is rolled. """ result = [] for i in range(y): result.append(random.randint(1, x)) return result
Remove test functions and, clean code in preperation for posting a pull request
Remove test functions and, clean code in preperation for posting a pull request
Python
mit
Eanilsen/RPGHelper
import random - class die_bag():#Class for rolling die/dices - - def __init__(self): - self.data = [] - - - def die(self, x, y = 1):#Roll a die and returns result - result = [] - for i in range(y): - result.append(random.randint(1, x)) - return result - print result + """In this module, die or dices are rolled""" - - + def die(x, y = 1): + """Function for rolling a die or several dice, + returns an array with results of dice rolls. + Parameter x is number of eyes on a die. + Parameter y = 1 is the times to a die is rolled. + """ + + result = [] + for i in range(y): + result.append(random.randint(1, x)) + return result - def take_input_die(self):#Take input from user - - eyes = int(raw_input('Number of eyes? ')) - times = int(raw_input('Number of times? ')) - - #Call die - dieRoll = die_bag.die(self, eyes, times) - print dieRoll - - d_class = die_bag()#Create a instance of die_bag - - die_bag.take_input_die(d_class)#Call take_input_die - - #Why does this not work? - die_bag.die(d_class, 20, 1)#Call die with parameters
Remove test functions and, clean code in preperation for posting a pull request
## Code Before: import random class die_bag():#Class for rolling die/dices def __init__(self): self.data = [] def die(self, x, y = 1):#Roll a die and returns result result = [] for i in range(y): result.append(random.randint(1, x)) return result print result def take_input_die(self):#Take input from user eyes = int(raw_input('Number of eyes? ')) times = int(raw_input('Number of times? ')) #Call die dieRoll = die_bag.die(self, eyes, times) print dieRoll d_class = die_bag()#Create a instance of die_bag die_bag.take_input_die(d_class)#Call take_input_die #Why does this not work? die_bag.die(d_class, 20, 1)#Call die with parameters ## Instruction: Remove test functions and, clean code in preperation for posting a pull request ## Code After: import random """In this module, die or dices are rolled""" def die(x, y = 1): """Function for rolling a die or several dice, returns an array with results of dice rolls. Parameter x is number of eyes on a die. Parameter y = 1 is the times to a die is rolled. """ result = [] for i in range(y): result.append(random.randint(1, x)) return result
// ... existing code ... import random """In this module, die or dices are rolled""" def die(x, y = 1): """Function for rolling a die or several dice, returns an array with results of dice rolls. Parameter x is number of eyes on a die. Parameter y = 1 is the times to a die is rolled. """ result = [] for i in range(y): result.append(random.randint(1, x)) return result // ... rest of the code ...
5bc3e6a3fb112b529f738142850860dd98a9d428
tests/runtests.py
tests/runtests.py
import glob import os import unittest def build_test_suite(): suite = unittest.TestSuite() for test_case in glob.glob('tests/test_*.py'): modname = os.path.splitext(test_case)[0] modname = modname.replace('/', '.') module = __import__(modname, {}, {}, ['1']) suite.addTest(unittest.TestLoader().loadTestsFromModule(module)) return suite if __name__ == "__main__": suite = build_test_suite() runner = unittest.TextTestRunner() runner.run(suite)
import glob import os import unittest import sys def build_test_suite(): suite = unittest.TestSuite() for test_case in glob.glob('tests/test_*.py'): modname = os.path.splitext(test_case)[0] modname = modname.replace('/', '.') module = __import__(modname, {}, {}, ['1']) suite.addTest(unittest.TestLoader().loadTestsFromModule(module)) return suite if __name__ == "__main__": suite = build_test_suite() runner = unittest.TextTestRunner() result = runner.run(suite) sys.exit(not result.wasSuccessful())
Make unittest return exit code 1 on failure
Make unittest return exit code 1 on failure This is to allow travis to catch test failures
Python
bsd-3-clause
jorgecarleitao/pyglet-gui
import glob import os import unittest - + import sys def build_test_suite(): suite = unittest.TestSuite() for test_case in glob.glob('tests/test_*.py'): modname = os.path.splitext(test_case)[0] modname = modname.replace('/', '.') module = __import__(modname, {}, {}, ['1']) suite.addTest(unittest.TestLoader().loadTestsFromModule(module)) return suite if __name__ == "__main__": suite = build_test_suite() runner = unittest.TextTestRunner() - runner.run(suite) + result = runner.run(suite) + sys.exit(not result.wasSuccessful())
Make unittest return exit code 1 on failure
## Code Before: import glob import os import unittest def build_test_suite(): suite = unittest.TestSuite() for test_case in glob.glob('tests/test_*.py'): modname = os.path.splitext(test_case)[0] modname = modname.replace('/', '.') module = __import__(modname, {}, {}, ['1']) suite.addTest(unittest.TestLoader().loadTestsFromModule(module)) return suite if __name__ == "__main__": suite = build_test_suite() runner = unittest.TextTestRunner() runner.run(suite) ## Instruction: Make unittest return exit code 1 on failure ## Code After: import glob import os import unittest import sys def build_test_suite(): suite = unittest.TestSuite() for test_case in glob.glob('tests/test_*.py'): modname = os.path.splitext(test_case)[0] modname = modname.replace('/', '.') module = __import__(modname, {}, {}, ['1']) suite.addTest(unittest.TestLoader().loadTestsFromModule(module)) return suite if __name__ == "__main__": suite = build_test_suite() runner = unittest.TextTestRunner() result = runner.run(suite) sys.exit(not result.wasSuccessful())
# ... existing code ... import unittest import sys # ... modified code ... result = runner.run(suite) sys.exit(not result.wasSuccessful()) # ... rest of the code ...
424a5da1e867b5b77fe5f241ef0a825988157811
moksha/config/app_cfg.py
moksha/config/app_cfg.py
from tg.configuration import AppConfig, Bunch import moksha from moksha import model from moksha.lib import app_globals, helpers base_config = AppConfig() base_config.package = moksha # Set the default renderer base_config.default_renderer = 'mako' base_config.renderers = [] base_config.renderers.append('mako') # @@ This is necessary at the moment. base_config.use_legacy_renderer = True # Configure the base SQLALchemy Setup base_config.use_sqlalchemy = True base_config.model = moksha.model base_config.DBSession = moksha.model.DBSession # Configure the authentication backend base_config.auth_backend = 'sqlalchemy' base_config.sa_auth.dbsession = model.DBSession base_config.sa_auth.user_class = model.User base_config.sa_auth.group_class = model.Group base_config.sa_auth.permission_class = model.Permission # override this if you would like to provide a different who plugin for # managing login and logout of your application base_config.sa_auth.form_plugin = None
from tg.configuration import AppConfig, Bunch import moksha from moksha import model from moksha.lib import app_globals, helpers base_config = AppConfig() base_config.package = moksha # Set the default renderer base_config.default_renderer = 'mako' base_config.renderers = [] base_config.renderers.append('genshi') base_config.renderers.append('mako') # @@ This is necessary at the moment. base_config.use_legacy_renderer = True # Configure the base SQLALchemy Setup base_config.use_sqlalchemy = True base_config.model = moksha.model base_config.DBSession = moksha.model.DBSession # Configure the authentication backend base_config.auth_backend = 'sqlalchemy' base_config.sa_auth.dbsession = model.DBSession base_config.sa_auth.user_class = model.User base_config.sa_auth.group_class = model.Group base_config.sa_auth.permission_class = model.Permission # override this if you would like to provide a different who plugin for # managing login and logout of your application base_config.sa_auth.form_plugin = None
Load up the genshi renderer
Load up the genshi renderer
Python
apache-2.0
lmacken/moksha,ralphbean/moksha,pombredanne/moksha,pombredanne/moksha,mokshaproject/moksha,lmacken/moksha,ralphbean/moksha,lmacken/moksha,pombredanne/moksha,mokshaproject/moksha,mokshaproject/moksha,ralphbean/moksha,mokshaproject/moksha,pombredanne/moksha
from tg.configuration import AppConfig, Bunch import moksha from moksha import model from moksha.lib import app_globals, helpers base_config = AppConfig() base_config.package = moksha # Set the default renderer base_config.default_renderer = 'mako' base_config.renderers = [] + base_config.renderers.append('genshi') base_config.renderers.append('mako') # @@ This is necessary at the moment. base_config.use_legacy_renderer = True # Configure the base SQLALchemy Setup base_config.use_sqlalchemy = True base_config.model = moksha.model base_config.DBSession = moksha.model.DBSession # Configure the authentication backend base_config.auth_backend = 'sqlalchemy' base_config.sa_auth.dbsession = model.DBSession base_config.sa_auth.user_class = model.User base_config.sa_auth.group_class = model.Group base_config.sa_auth.permission_class = model.Permission # override this if you would like to provide a different who plugin for # managing login and logout of your application base_config.sa_auth.form_plugin = None
Load up the genshi renderer
## Code Before: from tg.configuration import AppConfig, Bunch import moksha from moksha import model from moksha.lib import app_globals, helpers base_config = AppConfig() base_config.package = moksha # Set the default renderer base_config.default_renderer = 'mako' base_config.renderers = [] base_config.renderers.append('mako') # @@ This is necessary at the moment. base_config.use_legacy_renderer = True # Configure the base SQLALchemy Setup base_config.use_sqlalchemy = True base_config.model = moksha.model base_config.DBSession = moksha.model.DBSession # Configure the authentication backend base_config.auth_backend = 'sqlalchemy' base_config.sa_auth.dbsession = model.DBSession base_config.sa_auth.user_class = model.User base_config.sa_auth.group_class = model.Group base_config.sa_auth.permission_class = model.Permission # override this if you would like to provide a different who plugin for # managing login and logout of your application base_config.sa_auth.form_plugin = None ## Instruction: Load up the genshi renderer ## Code After: from tg.configuration import AppConfig, Bunch import moksha from moksha import model from moksha.lib import app_globals, helpers base_config = AppConfig() base_config.package = moksha # Set the default renderer base_config.default_renderer = 'mako' base_config.renderers = [] base_config.renderers.append('genshi') base_config.renderers.append('mako') # @@ This is necessary at the moment. base_config.use_legacy_renderer = True # Configure the base SQLALchemy Setup base_config.use_sqlalchemy = True base_config.model = moksha.model base_config.DBSession = moksha.model.DBSession # Configure the authentication backend base_config.auth_backend = 'sqlalchemy' base_config.sa_auth.dbsession = model.DBSession base_config.sa_auth.user_class = model.User base_config.sa_auth.group_class = model.Group base_config.sa_auth.permission_class = model.Permission # override this if you would like to provide a different who plugin for # managing login and logout of your application base_config.sa_auth.form_plugin = None
# ... existing code ... base_config.renderers = [] base_config.renderers.append('genshi') base_config.renderers.append('mako') # ... rest of the code ...
42804d3182b9b7489583250856e31a8daaef5fa3
protolint/__init__.py
protolint/__init__.py
from . import cli from . import linter from . import output __version__ = (1, 0, 0)
__version__ = (1, 0, 0) from . import cli from . import linter from . import output
Fix CLI module during build
Fix CLI module during build
Python
mit
sgammon/codeclimate-protobuf,sgammon/codeclimate-protobuf
+ + __version__ = (1, 0, 0) from . import cli from . import linter from . import output - __version__ = (1, 0, 0) -
Fix CLI module during build
## Code Before: from . import cli from . import linter from . import output __version__ = (1, 0, 0) ## Instruction: Fix CLI module during build ## Code After: __version__ = (1, 0, 0) from . import cli from . import linter from . import output
# ... existing code ... __version__ = (1, 0, 0) # ... modified code ... from . import output # ... rest of the code ...
7b9206d7c3fcf91c6ac16b54b9e1d13b92f7802a
tests/test_testing.py
tests/test_testing.py
"""Test MetPy's testing utilities.""" import numpy as np import pytest from metpy.testing import assert_array_almost_equal # Test #1183: numpy.testing.assert_array* ignores any masked value, so work-around def test_masked_arrays(): """Test that we catch masked arrays with different masks.""" with pytest.raises(AssertionError): assert_array_almost_equal(np.array([10, 20]), np.ma.array([10, np.nan], mask=[False, True]), 2) def test_masked_and_no_mask(): """Test that we can compare a masked array with no masked values and a regular array.""" a = np.array([10, 20]) b = np.ma.array([10, 20], mask=[False, False]) assert_array_almost_equal(a, b)
"""Test MetPy's testing utilities.""" import warnings import numpy as np import pytest from metpy.deprecation import MetpyDeprecationWarning from metpy.testing import assert_array_almost_equal, check_and_silence_deprecation # Test #1183: numpy.testing.assert_array* ignores any masked value, so work-around def test_masked_arrays(): """Test that we catch masked arrays with different masks.""" with pytest.raises(AssertionError): assert_array_almost_equal(np.array([10, 20]), np.ma.array([10, np.nan], mask=[False, True]), 2) def test_masked_and_no_mask(): """Test that we can compare a masked array with no masked values and a regular array.""" a = np.array([10, 20]) b = np.ma.array([10, 20], mask=[False, False]) assert_array_almost_equal(a, b) @check_and_silence_deprecation def test_deprecation_decorator(): """Make sure the deprecation checker works.""" warnings.warn('Testing warning.', MetpyDeprecationWarning)
Add explicit test for deprecation decorator
MNT: Add explicit test for deprecation decorator
Python
bsd-3-clause
dopplershift/MetPy,ShawnMurd/MetPy,ahaberlie/MetPy,Unidata/MetPy,Unidata/MetPy,ahaberlie/MetPy,dopplershift/MetPy
"""Test MetPy's testing utilities.""" + import warnings import numpy as np import pytest + from metpy.deprecation import MetpyDeprecationWarning - from metpy.testing import assert_array_almost_equal + from metpy.testing import assert_array_almost_equal, check_and_silence_deprecation # Test #1183: numpy.testing.assert_array* ignores any masked value, so work-around def test_masked_arrays(): """Test that we catch masked arrays with different masks.""" with pytest.raises(AssertionError): assert_array_almost_equal(np.array([10, 20]), np.ma.array([10, np.nan], mask=[False, True]), 2) def test_masked_and_no_mask(): """Test that we can compare a masked array with no masked values and a regular array.""" a = np.array([10, 20]) b = np.ma.array([10, 20], mask=[False, False]) assert_array_almost_equal(a, b) + + @check_and_silence_deprecation + def test_deprecation_decorator(): + """Make sure the deprecation checker works.""" + warnings.warn('Testing warning.', MetpyDeprecationWarning) +
Add explicit test for deprecation decorator
## Code Before: """Test MetPy's testing utilities.""" import numpy as np import pytest from metpy.testing import assert_array_almost_equal # Test #1183: numpy.testing.assert_array* ignores any masked value, so work-around def test_masked_arrays(): """Test that we catch masked arrays with different masks.""" with pytest.raises(AssertionError): assert_array_almost_equal(np.array([10, 20]), np.ma.array([10, np.nan], mask=[False, True]), 2) def test_masked_and_no_mask(): """Test that we can compare a masked array with no masked values and a regular array.""" a = np.array([10, 20]) b = np.ma.array([10, 20], mask=[False, False]) assert_array_almost_equal(a, b) ## Instruction: Add explicit test for deprecation decorator ## Code After: """Test MetPy's testing utilities.""" import warnings import numpy as np import pytest from metpy.deprecation import MetpyDeprecationWarning from metpy.testing import assert_array_almost_equal, check_and_silence_deprecation # Test #1183: numpy.testing.assert_array* ignores any masked value, so work-around def test_masked_arrays(): """Test that we catch masked arrays with different masks.""" with pytest.raises(AssertionError): assert_array_almost_equal(np.array([10, 20]), np.ma.array([10, np.nan], mask=[False, True]), 2) def test_masked_and_no_mask(): """Test that we can compare a masked array with no masked values and a regular array.""" a = np.array([10, 20]) b = np.ma.array([10, 20], mask=[False, False]) assert_array_almost_equal(a, b) @check_and_silence_deprecation def test_deprecation_decorator(): """Make sure the deprecation checker works.""" warnings.warn('Testing warning.', MetpyDeprecationWarning)
# ... existing code ... """Test MetPy's testing utilities.""" import warnings # ... modified code ... from metpy.deprecation import MetpyDeprecationWarning from metpy.testing import assert_array_almost_equal, check_and_silence_deprecation ... assert_array_almost_equal(a, b) @check_and_silence_deprecation def test_deprecation_decorator(): """Make sure the deprecation checker works.""" warnings.warn('Testing warning.', MetpyDeprecationWarning) # ... rest of the code ...
0ee0650dfacf648982615be49cefd57f928a73ee
holonet/core/list_access.py
holonet/core/list_access.py
from django.conf import settings from holonet.mappings.helpers import clean_address, split_address from .models import DomainBlacklist, DomainWhitelist, SenderBlacklist, SenderWhitelist def is_blacklisted(sender): sender = clean_address(sender) prefix, domain = split_address(sender) try: DomainBlacklist.objects.get(domain=domain) return True except DomainBlacklist.DoesNotExist: pass try: SenderBlacklist.objects.get(sender=sender) return True except SenderBlacklist.DoesNotExist: pass return False def is_not_whitelisted(sender): sender = clean_address(sender) prefix, domain = split_address(sender) if settings.SENDER_WHITELIST_ENABLED: try: SenderWhitelist.objects.get(sender=sender) return False except SenderWhitelist.DoesNotExist: pass if settings.DOMAIN_WHITELIST_ENABLED: try: DomainWhitelist.objects.get(domain=domain) return False except DomainWhitelist.DoesNotExist: pass return bool(settings.SENDER_WHITELIST_ENABLED or settings.DOMAIN_WHITELIST_ENABLED)
from django.conf import settings from holonet.mappings.helpers import clean_address, split_address from .models import DomainBlacklist, DomainWhitelist, SenderBlacklist, SenderWhitelist def is_blacklisted(sender): sender = clean_address(sender) prefix, domain = split_address(sender) if DomainBlacklist.objects.filter(domain=domain).exists(): return True if SenderBlacklist.objects.filter(sender=sender).exists(): return True return False def is_not_whitelisted(sender): sender = clean_address(sender) prefix, domain = split_address(sender) if settings.SENDER_WHITELIST_ENABLED: if SenderWhitelist.objects.filter(sender=sender).exists(): return False if settings.DOMAIN_WHITELIST_ENABLED: if DomainWhitelist.objects.filter(domain=domain).exists(): return False return bool(settings.SENDER_WHITELIST_ENABLED or settings.DOMAIN_WHITELIST_ENABLED)
Change to exists instead of catching DoesNotExist exception.
Change to exists instead of catching DoesNotExist exception.
Python
mit
webkom/holonet,webkom/holonet,webkom/holonet
from django.conf import settings from holonet.mappings.helpers import clean_address, split_address from .models import DomainBlacklist, DomainWhitelist, SenderBlacklist, SenderWhitelist def is_blacklisted(sender): sender = clean_address(sender) prefix, domain = split_address(sender) - try: - DomainBlacklist.objects.get(domain=domain) + if DomainBlacklist.objects.filter(domain=domain).exists(): return True - except DomainBlacklist.DoesNotExist: - pass - try: - SenderBlacklist.objects.get(sender=sender) + if SenderBlacklist.objects.filter(sender=sender).exists(): return True - except SenderBlacklist.DoesNotExist: - pass return False def is_not_whitelisted(sender): sender = clean_address(sender) prefix, domain = split_address(sender) if settings.SENDER_WHITELIST_ENABLED: - try: - SenderWhitelist.objects.get(sender=sender) + if SenderWhitelist.objects.filter(sender=sender).exists(): return False - except SenderWhitelist.DoesNotExist: - pass if settings.DOMAIN_WHITELIST_ENABLED: - try: - DomainWhitelist.objects.get(domain=domain) + if DomainWhitelist.objects.filter(domain=domain).exists(): return False - except DomainWhitelist.DoesNotExist: - pass return bool(settings.SENDER_WHITELIST_ENABLED or settings.DOMAIN_WHITELIST_ENABLED)
Change to exists instead of catching DoesNotExist exception.
## Code Before: from django.conf import settings from holonet.mappings.helpers import clean_address, split_address from .models import DomainBlacklist, DomainWhitelist, SenderBlacklist, SenderWhitelist def is_blacklisted(sender): sender = clean_address(sender) prefix, domain = split_address(sender) try: DomainBlacklist.objects.get(domain=domain) return True except DomainBlacklist.DoesNotExist: pass try: SenderBlacklist.objects.get(sender=sender) return True except SenderBlacklist.DoesNotExist: pass return False def is_not_whitelisted(sender): sender = clean_address(sender) prefix, domain = split_address(sender) if settings.SENDER_WHITELIST_ENABLED: try: SenderWhitelist.objects.get(sender=sender) return False except SenderWhitelist.DoesNotExist: pass if settings.DOMAIN_WHITELIST_ENABLED: try: DomainWhitelist.objects.get(domain=domain) return False except DomainWhitelist.DoesNotExist: pass return bool(settings.SENDER_WHITELIST_ENABLED or settings.DOMAIN_WHITELIST_ENABLED) ## Instruction: Change to exists instead of catching DoesNotExist exception. ## Code After: from django.conf import settings from holonet.mappings.helpers import clean_address, split_address from .models import DomainBlacklist, DomainWhitelist, SenderBlacklist, SenderWhitelist def is_blacklisted(sender): sender = clean_address(sender) prefix, domain = split_address(sender) if DomainBlacklist.objects.filter(domain=domain).exists(): return True if SenderBlacklist.objects.filter(sender=sender).exists(): return True return False def is_not_whitelisted(sender): sender = clean_address(sender) prefix, domain = split_address(sender) if settings.SENDER_WHITELIST_ENABLED: if SenderWhitelist.objects.filter(sender=sender).exists(): return False if settings.DOMAIN_WHITELIST_ENABLED: if DomainWhitelist.objects.filter(domain=domain).exists(): return False return bool(settings.SENDER_WHITELIST_ENABLED or settings.DOMAIN_WHITELIST_ENABLED)
// ... existing code ... if DomainBlacklist.objects.filter(domain=domain).exists(): return True if SenderBlacklist.objects.filter(sender=sender).exists(): return True // ... modified code ... if settings.SENDER_WHITELIST_ENABLED: if SenderWhitelist.objects.filter(sender=sender).exists(): return False ... if settings.DOMAIN_WHITELIST_ENABLED: if DomainWhitelist.objects.filter(domain=domain).exists(): return False // ... rest of the code ...
9f9d36025db87b7326b235131063ef852f43cef8
euxfel_h5tools/h5index.py
euxfel_h5tools/h5index.py
import csv import h5py import sys def hdf5_datasets(grp): """Print CSV data of all datasets in an HDF5 file. path, shape, dtype """ writer = csv.writer(sys.stdout) writer.writerow(['path', 'shape', 'dtype']) def visitor(path, item): if isinstance(item, h5py.Dataset): writer.writerow([path, item.shape, item.dtype.str]) grp.visititems(visitor) def main(): file = h5py.File(sys.argv[1]) hdf5_datasets(file) if __name__ == '__main__': main()
import csv import h5py import sys def hdf5_datasets(grp): """Print CSV data of all datasets in an HDF5 file. path, shape, dtype """ all_datasets = [] def visitor(path, item): if isinstance(item, h5py.Dataset): all_datasets.append([path, item.shape, item.dtype.str]) grp.visititems(visitor) writer = csv.writer(sys.stdout) writer.writerow(['path', 'shape', 'dtype']) for row in sorted(all_datasets): writer.writerow(row) def main(): file = h5py.File(sys.argv[1]) hdf5_datasets(file) if __name__ == '__main__': main()
Sort datasets for index of HDF5 files
Sort datasets for index of HDF5 files
Python
bsd-3-clause
European-XFEL/h5tools-py
import csv import h5py import sys def hdf5_datasets(grp): """Print CSV data of all datasets in an HDF5 file. path, shape, dtype """ + all_datasets = [] - writer = csv.writer(sys.stdout) - writer.writerow(['path', 'shape', 'dtype']) def visitor(path, item): if isinstance(item, h5py.Dataset): - writer.writerow([path, item.shape, item.dtype.str]) + all_datasets.append([path, item.shape, item.dtype.str]) grp.visititems(visitor) + + writer = csv.writer(sys.stdout) + writer.writerow(['path', 'shape', 'dtype']) + for row in sorted(all_datasets): + writer.writerow(row) def main(): file = h5py.File(sys.argv[1]) hdf5_datasets(file) if __name__ == '__main__': main()
Sort datasets for index of HDF5 files
## Code Before: import csv import h5py import sys def hdf5_datasets(grp): """Print CSV data of all datasets in an HDF5 file. path, shape, dtype """ writer = csv.writer(sys.stdout) writer.writerow(['path', 'shape', 'dtype']) def visitor(path, item): if isinstance(item, h5py.Dataset): writer.writerow([path, item.shape, item.dtype.str]) grp.visititems(visitor) def main(): file = h5py.File(sys.argv[1]) hdf5_datasets(file) if __name__ == '__main__': main() ## Instruction: Sort datasets for index of HDF5 files ## Code After: import csv import h5py import sys def hdf5_datasets(grp): """Print CSV data of all datasets in an HDF5 file. path, shape, dtype """ all_datasets = [] def visitor(path, item): if isinstance(item, h5py.Dataset): all_datasets.append([path, item.shape, item.dtype.str]) grp.visititems(visitor) writer = csv.writer(sys.stdout) writer.writerow(['path', 'shape', 'dtype']) for row in sorted(all_datasets): writer.writerow(row) def main(): file = h5py.File(sys.argv[1]) hdf5_datasets(file) if __name__ == '__main__': main()
// ... existing code ... """ all_datasets = [] // ... modified code ... if isinstance(item, h5py.Dataset): all_datasets.append([path, item.shape, item.dtype.str]) grp.visititems(visitor) writer = csv.writer(sys.stdout) writer.writerow(['path', 'shape', 'dtype']) for row in sorted(all_datasets): writer.writerow(row) // ... rest of the code ...
3421fe2542a5b71f6b604e30f2c800400b5e40d8
datawire/store/common.py
datawire/store/common.py
import json from datawire.views.util import JSONEncoder class Store(object): def __init__(self, url): self.url = url def store(self, frame): urn = frame.get('urn') data = json.dumps(frame, cls=JSONEncoder) return self._store(urn, data) def load(self, urn): data = self._load(urn) if data is not None: data = json.loads(data) return data
import json from datawire.views.util import JSONEncoder class Store(object): def __init__(self, url): self.url = url def store(self, frame): urn = frame.get('urn') data = JSONEncoder().encode(frame) return self._store(urn, data) def load(self, urn): data = self._load(urn) if data is not None: data = json.loads(data) return data
Fix encoding of store serialisation.
Fix encoding of store serialisation.
Python
mit
arc64/datawi.re,arc64/datawi.re,arc64/datawi.re
import json from datawire.views.util import JSONEncoder class Store(object): def __init__(self, url): self.url = url def store(self, frame): urn = frame.get('urn') - data = json.dumps(frame, cls=JSONEncoder) + data = JSONEncoder().encode(frame) return self._store(urn, data) def load(self, urn): data = self._load(urn) if data is not None: data = json.loads(data) return data
Fix encoding of store serialisation.
## Code Before: import json from datawire.views.util import JSONEncoder class Store(object): def __init__(self, url): self.url = url def store(self, frame): urn = frame.get('urn') data = json.dumps(frame, cls=JSONEncoder) return self._store(urn, data) def load(self, urn): data = self._load(urn) if data is not None: data = json.loads(data) return data ## Instruction: Fix encoding of store serialisation. ## Code After: import json from datawire.views.util import JSONEncoder class Store(object): def __init__(self, url): self.url = url def store(self, frame): urn = frame.get('urn') data = JSONEncoder().encode(frame) return self._store(urn, data) def load(self, urn): data = self._load(urn) if data is not None: data = json.loads(data) return data
... urn = frame.get('urn') data = JSONEncoder().encode(frame) return self._store(urn, data) ...
03b19d542a50f9f897aa759c5921933cba8bf501
sim_services_local/dispatcher.py
sim_services_local/dispatcher.py
from django.utils import timezone import subprocess import sys import os from data_services import models as data_models def submit(simulation_group): """ Run a simulation group on a local machine in background. Raises RuntimeError if the submission fails for some reason. """ assert isinstance(simulation_group, data_models.SimulationGroup) base_dir = os.path.dirname(os.path.abspath(__file__)) run_script_filename = os.path.join(base_dir, "run.py") for simulation in simulation_group.simulations.all(): subprocess.Popen(sys.executable + " " + "%s" % run_script_filename + " " + str(simulation.id), shell=True) simulation_group.submitted_when = timezone.now() simulation_group.save()
from django.utils import timezone from django.conf import settings import subprocess import sys import os from data_services import models as data_models def submit(simulation_group): """ Run a simulation group on a local machine in background. Raises RuntimeError if the submission fails for some reason. """ assert isinstance(simulation_group, data_models.SimulationGroup) base_dir = os.path.dirname(os.path.abspath(__file__)) run_script_filename = os.path.join(base_dir, "run.py") for simulation in simulation_group.simulations.all(): executable = sys.executable if hasattr(settings, "PYTHON_EXECUTABLE"): executable = settings.PYTHON_EXECUTABLE subprocess.Popen(executable + " " + "%s" % run_script_filename + " " + str(simulation.id), shell=True) simulation_group.submitted_when = timezone.now() simulation_group.save()
Fix for broken job submission in apache
Fix for broken job submission in apache
Python
mpl-2.0
vecnet/om,vecnet/om,vecnet/om,vecnet/om,vecnet/om
from django.utils import timezone + from django.conf import settings import subprocess import sys import os from data_services import models as data_models def submit(simulation_group): """ Run a simulation group on a local machine in background. Raises RuntimeError if the submission fails for some reason. """ assert isinstance(simulation_group, data_models.SimulationGroup) base_dir = os.path.dirname(os.path.abspath(__file__)) run_script_filename = os.path.join(base_dir, "run.py") for simulation in simulation_group.simulations.all(): + executable = sys.executable + if hasattr(settings, "PYTHON_EXECUTABLE"): + executable = settings.PYTHON_EXECUTABLE - subprocess.Popen(sys.executable + " " + "%s" % run_script_filename + " " + str(simulation.id), shell=True) + subprocess.Popen(executable + " " + "%s" % run_script_filename + " " + str(simulation.id), shell=True) simulation_group.submitted_when = timezone.now() simulation_group.save()
Fix for broken job submission in apache
## Code Before: from django.utils import timezone import subprocess import sys import os from data_services import models as data_models def submit(simulation_group): """ Run a simulation group on a local machine in background. Raises RuntimeError if the submission fails for some reason. """ assert isinstance(simulation_group, data_models.SimulationGroup) base_dir = os.path.dirname(os.path.abspath(__file__)) run_script_filename = os.path.join(base_dir, "run.py") for simulation in simulation_group.simulations.all(): subprocess.Popen(sys.executable + " " + "%s" % run_script_filename + " " + str(simulation.id), shell=True) simulation_group.submitted_when = timezone.now() simulation_group.save() ## Instruction: Fix for broken job submission in apache ## Code After: from django.utils import timezone from django.conf import settings import subprocess import sys import os from data_services import models as data_models def submit(simulation_group): """ Run a simulation group on a local machine in background. Raises RuntimeError if the submission fails for some reason. """ assert isinstance(simulation_group, data_models.SimulationGroup) base_dir = os.path.dirname(os.path.abspath(__file__)) run_script_filename = os.path.join(base_dir, "run.py") for simulation in simulation_group.simulations.all(): executable = sys.executable if hasattr(settings, "PYTHON_EXECUTABLE"): executable = settings.PYTHON_EXECUTABLE subprocess.Popen(executable + " " + "%s" % run_script_filename + " " + str(simulation.id), shell=True) simulation_group.submitted_when = timezone.now() simulation_group.save()
# ... existing code ... from django.utils import timezone from django.conf import settings import subprocess # ... modified code ... for simulation in simulation_group.simulations.all(): executable = sys.executable if hasattr(settings, "PYTHON_EXECUTABLE"): executable = settings.PYTHON_EXECUTABLE subprocess.Popen(executable + " " + "%s" % run_script_filename + " " + str(simulation.id), shell=True) # ... rest of the code ...
70259a9f9ce5647f9c36b70c2eb20b51ba447eda
middleware.py
middleware.py
class Routes: '''Define the feature of route for URIs.''' def __init__(self): self._Routes = [] def AddRoute(self, uri, callback): '''Add an URI into the route table.''' self._Routes.append([uri, callback]) def Dispatch(self, req, res): '''Dispatch an URI according to the route table.''' uri = "" for fv in req.Header: if fv[0] == "URI": uri = fv[1] found = 1 break found = 0 for r in self._Routes: if r[0] == uri: r[1](req, res) found = 1 break if found != 1: self._NotFound(req, res) def _NotFound(self, req, res): '''Define the default error page for not found URI.''' res.Header.append(["Status", "404 Not Found"])
class Routes: '''Define the feature of route for URIs.''' def __init__(self): self._Routes = [] def AddRoute(self, uri, callback): '''Add an URI into the route table.''' self._Routes.append([uri, callback]) def Dispatch(self, req, res): '''Dispatch an URI according to the route table.''' uri = "" for fv in req.Header: if fv[0] == "URI": uri = fv[1] found = 1 break found = 0 # Check the route for r in self._Routes: if r[0] == uri: r[1](req, res) found = 1 break # Check static files if found != 1: found = self._ReadStaticFiles(uri, res) # It is really not found if found != 1: self._NotFound(req, res) def _ReadStaticFiles(self, uri, res): found = 0 try: f = open("static/{}".format(uri), "r") res.Body = f.read() f.close() found = 1 except: pass return found def _NotFound(self, req, res): '''Define the default error page for not found URI.''' res.Header.append(["Status", "404 Not Found"])
Add read static files feature.
Add read static files feature.
Python
bsd-3-clause
starnight/MicroHttpServer,starnight/MicroHttpServer,starnight/MicroHttpServer,starnight/MicroHttpServer
class Routes: '''Define the feature of route for URIs.''' def __init__(self): self._Routes = [] def AddRoute(self, uri, callback): '''Add an URI into the route table.''' self._Routes.append([uri, callback]) def Dispatch(self, req, res): '''Dispatch an URI according to the route table.''' uri = "" for fv in req.Header: if fv[0] == "URI": uri = fv[1] found = 1 break found = 0 + # Check the route for r in self._Routes: if r[0] == uri: r[1](req, res) found = 1 break + # Check static files + if found != 1: + found = self._ReadStaticFiles(uri, res) + # It is really not found if found != 1: self._NotFound(req, res) + + def _ReadStaticFiles(self, uri, res): + found = 0 + try: + f = open("static/{}".format(uri), "r") + res.Body = f.read() + f.close() + found = 1 + except: + pass + + return found def _NotFound(self, req, res): '''Define the default error page for not found URI.''' res.Header.append(["Status", "404 Not Found"])
Add read static files feature.
## Code Before: class Routes: '''Define the feature of route for URIs.''' def __init__(self): self._Routes = [] def AddRoute(self, uri, callback): '''Add an URI into the route table.''' self._Routes.append([uri, callback]) def Dispatch(self, req, res): '''Dispatch an URI according to the route table.''' uri = "" for fv in req.Header: if fv[0] == "URI": uri = fv[1] found = 1 break found = 0 for r in self._Routes: if r[0] == uri: r[1](req, res) found = 1 break if found != 1: self._NotFound(req, res) def _NotFound(self, req, res): '''Define the default error page for not found URI.''' res.Header.append(["Status", "404 Not Found"]) ## Instruction: Add read static files feature. ## Code After: class Routes: '''Define the feature of route for URIs.''' def __init__(self): self._Routes = [] def AddRoute(self, uri, callback): '''Add an URI into the route table.''' self._Routes.append([uri, callback]) def Dispatch(self, req, res): '''Dispatch an URI according to the route table.''' uri = "" for fv in req.Header: if fv[0] == "URI": uri = fv[1] found = 1 break found = 0 # Check the route for r in self._Routes: if r[0] == uri: r[1](req, res) found = 1 break # Check static files if found != 1: found = self._ReadStaticFiles(uri, res) # It is really not found if found != 1: self._NotFound(req, res) def _ReadStaticFiles(self, uri, res): found = 0 try: f = open("static/{}".format(uri), "r") res.Body = f.read() f.close() found = 1 except: pass return found def _NotFound(self, req, res): '''Define the default error page for not found URI.''' res.Header.append(["Status", "404 Not Found"])
... found = 0 # Check the route for r in self._Routes: ... break # Check static files if found != 1: found = self._ReadStaticFiles(uri, res) # It is really not found if found != 1: ... self._NotFound(req, res) def _ReadStaticFiles(self, uri, res): found = 0 try: f = open("static/{}".format(uri), "r") res.Body = f.read() f.close() found = 1 except: pass return found ...
daf68a1475530f4f0cb2e78e2ccf6ecbca821a8e
rfb_utils/prefs_utils.py
rfb_utils/prefs_utils.py
from ..rman_constants import RFB_PREFS_NAME import bpy def get_addon_prefs(): try: addon = bpy.context.preferences.addons[RFB_PREFS_NAME] return addon.preferences except: return None def get_pref(pref_name='', default=None): """ Return the value of a preference Args: pref_name (str) - name of the preference to look up default (AnyType) - default to return, if pref_name doesn't exist Returns: (AnyType) - preference value. """ prefs = get_addon_prefs() if not prefs: return default return getattr(prefs, pref_name, default) def get_bl_temp_dir(): return bpy.context.preferences.filepaths.temporary_directory
from ..rman_constants import RFB_PREFS_NAME import bpy def get_addon_prefs(): try: addon = bpy.context.preferences.addons[RFB_PREFS_NAME] return addon.preferences except: # try looking for all variants of RFB_PREFS_NAME for k, v in bpy.context.preferences.addons.items(): if RFB_PREFS_NAME in k: return v return None def get_pref(pref_name='', default=None): """ Return the value of a preference Args: pref_name (str) - name of the preference to look up default (AnyType) - default to return, if pref_name doesn't exist Returns: (AnyType) - preference value. """ prefs = get_addon_prefs() if not prefs: return default return getattr(prefs, pref_name, default) def get_bl_temp_dir(): return bpy.context.preferences.filepaths.temporary_directory
Add some fallback code when looking for our prefs object.
Add some fallback code when looking for our prefs object.
Python
mit
prman-pixar/RenderManForBlender,adminradio/RenderManForBlender,prman-pixar/RenderManForBlender
from ..rman_constants import RFB_PREFS_NAME import bpy def get_addon_prefs(): try: addon = bpy.context.preferences.addons[RFB_PREFS_NAME] return addon.preferences except: + # try looking for all variants of RFB_PREFS_NAME + for k, v in bpy.context.preferences.addons.items(): + if RFB_PREFS_NAME in k: + return v return None def get_pref(pref_name='', default=None): """ Return the value of a preference Args: pref_name (str) - name of the preference to look up default (AnyType) - default to return, if pref_name doesn't exist Returns: (AnyType) - preference value. """ prefs = get_addon_prefs() if not prefs: return default return getattr(prefs, pref_name, default) def get_bl_temp_dir(): return bpy.context.preferences.filepaths.temporary_directory
Add some fallback code when looking for our prefs object.
## Code Before: from ..rman_constants import RFB_PREFS_NAME import bpy def get_addon_prefs(): try: addon = bpy.context.preferences.addons[RFB_PREFS_NAME] return addon.preferences except: return None def get_pref(pref_name='', default=None): """ Return the value of a preference Args: pref_name (str) - name of the preference to look up default (AnyType) - default to return, if pref_name doesn't exist Returns: (AnyType) - preference value. """ prefs = get_addon_prefs() if not prefs: return default return getattr(prefs, pref_name, default) def get_bl_temp_dir(): return bpy.context.preferences.filepaths.temporary_directory ## Instruction: Add some fallback code when looking for our prefs object. ## Code After: from ..rman_constants import RFB_PREFS_NAME import bpy def get_addon_prefs(): try: addon = bpy.context.preferences.addons[RFB_PREFS_NAME] return addon.preferences except: # try looking for all variants of RFB_PREFS_NAME for k, v in bpy.context.preferences.addons.items(): if RFB_PREFS_NAME in k: return v return None def get_pref(pref_name='', default=None): """ Return the value of a preference Args: pref_name (str) - name of the preference to look up default (AnyType) - default to return, if pref_name doesn't exist Returns: (AnyType) - preference value. """ prefs = get_addon_prefs() if not prefs: return default return getattr(prefs, pref_name, default) def get_bl_temp_dir(): return bpy.context.preferences.filepaths.temporary_directory
# ... existing code ... except: # try looking for all variants of RFB_PREFS_NAME for k, v in bpy.context.preferences.addons.items(): if RFB_PREFS_NAME in k: return v return None # ... rest of the code ...
c0e68d9e4fe18154deb412d5897702603883cc06
statsd/__init__.py
statsd/__init__.py
try: from django.conf import settings except ImportError: settings = None from client import StatsClient __all__ = ['StatsClient', 'statsd', 'VERSION'] VERSION = (0, 1) if settings: host = getattr(settings, 'STATSD_HOST', 'localhost') port = getattr(settings, 'STATSD_PORT', 8125) statsd = StatsClient(host, port)
try: from django.conf import settings except ImportError: settings = None from client import StatsClient __all__ = ['StatsClient', 'statsd', 'VERSION'] VERSION = (0, 1) if settings: try: host = getattr(settings, 'STATSD_HOST', 'localhost') port = getattr(settings, 'STATSD_PORT', 8125) statsd = StatsClient(host, port) except ImportError: statsd = None
Support Django being on the path but unused.
Support Django being on the path but unused.
Python
mit
Khan/pystatsd,wujuguang/pystatsd,deathowl/pystatsd,lyft/pystatsd,lyft/pystatsd,smarkets/pystatsd,jsocol/pystatsd,Khan/pystatsd
try: from django.conf import settings except ImportError: settings = None from client import StatsClient __all__ = ['StatsClient', 'statsd', 'VERSION'] VERSION = (0, 1) if settings: + try: - host = getattr(settings, 'STATSD_HOST', 'localhost') + host = getattr(settings, 'STATSD_HOST', 'localhost') - port = getattr(settings, 'STATSD_PORT', 8125) + port = getattr(settings, 'STATSD_PORT', 8125) - statsd = StatsClient(host, port) + statsd = StatsClient(host, port) + except ImportError: + statsd = None
Support Django being on the path but unused.
## Code Before: try: from django.conf import settings except ImportError: settings = None from client import StatsClient __all__ = ['StatsClient', 'statsd', 'VERSION'] VERSION = (0, 1) if settings: host = getattr(settings, 'STATSD_HOST', 'localhost') port = getattr(settings, 'STATSD_PORT', 8125) statsd = StatsClient(host, port) ## Instruction: Support Django being on the path but unused. ## Code After: try: from django.conf import settings except ImportError: settings = None from client import StatsClient __all__ = ['StatsClient', 'statsd', 'VERSION'] VERSION = (0, 1) if settings: try: host = getattr(settings, 'STATSD_HOST', 'localhost') port = getattr(settings, 'STATSD_PORT', 8125) statsd = StatsClient(host, port) except ImportError: statsd = None
// ... existing code ... if settings: try: host = getattr(settings, 'STATSD_HOST', 'localhost') port = getattr(settings, 'STATSD_PORT', 8125) statsd = StatsClient(host, port) except ImportError: statsd = None // ... rest of the code ...
715098531f823c3b2932e6a03d2e4b113bd53ed9
tests/test_grammar.py
tests/test_grammar.py
import viper.grammar as vg import viper.grammar.languages as vgl import viper.lexer as vl import pytest @pytest.mark.parametrize('line,sppf', [ ('foo', vgl.SPPF(vgl.ParseTreeChar(vl.Name('foo')))), ('2', vgl.SPPF(vgl.ParseTreeChar(vl.Number('2')))), ('...', vgl.SPPF(vgl.ParseTreeChar(vl.Operator('...')))), ('Zilch', vgl.SPPF(vgl.ParseTreeChar(vl.Class('Zilch')))), ('True', vgl.SPPF(vgl.ParseTreeChar(vl.Class('True')))), ('False', vgl.SPPF(vgl.ParseTreeChar(vl.Class('False')))), ]) def test_atom(line: str, sppf: vgl.SPPF): atom = vg.GRAMMAR.get_rule('atom') lexemes = vl.lex_line(line) assert sppf == vg.make_sppf(atom, lexemes)
import viper.grammar as vg import viper.lexer as vl from viper.grammar.languages import ( SPPF, ParseTreeEmpty as PTE, ParseTreeChar as PTC, ParseTreePair as PTP, ParseTreeRep as PTR ) import pytest @pytest.mark.parametrize('line,sppf', [ ('foo', SPPF(PTC(vl.Name('foo')))), ('42', SPPF(PTC(vl.Number('42')))), ('...', SPPF(PTC(vl.Operator('...')))), ('Zilch', SPPF(PTC(vl.Class('Zilch')))), ('True', SPPF(PTC(vl.Class('True')))), ('False', SPPF(PTC(vl.Class('False')))), ('()', SPPF(PTP(SPPF(PTC(vl.OpenParen())), SPPF(PTC(vl.CloseParen()))))), ('(foo)', SPPF(PTP(SPPF(PTC(vl.OpenParen())), SPPF(PTP(SPPF(PTP(SPPF(PTC(vl.Name('foo'))), SPPF(PTR(SPPF())))), SPPF(PTC(vl.CloseParen()))))))), ]) def test_atom(line: str, sppf: SPPF): atom = vg.GRAMMAR.get_rule('atom') lexemes = vl.lex_line(line) assert sppf == vg.make_sppf(atom, lexemes)
Revise grammar tests for atom
Revise grammar tests for atom
Python
apache-2.0
pdarragh/Viper
import viper.grammar as vg - import viper.grammar.languages as vgl import viper.lexer as vl + + from viper.grammar.languages import ( + SPPF, + ParseTreeEmpty as PTE, ParseTreeChar as PTC, ParseTreePair as PTP, ParseTreeRep as PTR + ) import pytest @pytest.mark.parametrize('line,sppf', [ ('foo', - vgl.SPPF(vgl.ParseTreeChar(vl.Name('foo')))), + SPPF(PTC(vl.Name('foo')))), - ('2', + ('42', - vgl.SPPF(vgl.ParseTreeChar(vl.Number('2')))), + SPPF(PTC(vl.Number('42')))), ('...', - vgl.SPPF(vgl.ParseTreeChar(vl.Operator('...')))), + SPPF(PTC(vl.Operator('...')))), ('Zilch', - vgl.SPPF(vgl.ParseTreeChar(vl.Class('Zilch')))), + SPPF(PTC(vl.Class('Zilch')))), ('True', - vgl.SPPF(vgl.ParseTreeChar(vl.Class('True')))), + SPPF(PTC(vl.Class('True')))), ('False', - vgl.SPPF(vgl.ParseTreeChar(vl.Class('False')))), + SPPF(PTC(vl.Class('False')))), + ('()', + SPPF(PTP(SPPF(PTC(vl.OpenParen())), + SPPF(PTC(vl.CloseParen()))))), + ('(foo)', + SPPF(PTP(SPPF(PTC(vl.OpenParen())), + SPPF(PTP(SPPF(PTP(SPPF(PTC(vl.Name('foo'))), + SPPF(PTR(SPPF())))), + SPPF(PTC(vl.CloseParen()))))))), ]) - def test_atom(line: str, sppf: vgl.SPPF): + def test_atom(line: str, sppf: SPPF): atom = vg.GRAMMAR.get_rule('atom') lexemes = vl.lex_line(line) assert sppf == vg.make_sppf(atom, lexemes)
Revise grammar tests for atom
## Code Before: import viper.grammar as vg import viper.grammar.languages as vgl import viper.lexer as vl import pytest @pytest.mark.parametrize('line,sppf', [ ('foo', vgl.SPPF(vgl.ParseTreeChar(vl.Name('foo')))), ('2', vgl.SPPF(vgl.ParseTreeChar(vl.Number('2')))), ('...', vgl.SPPF(vgl.ParseTreeChar(vl.Operator('...')))), ('Zilch', vgl.SPPF(vgl.ParseTreeChar(vl.Class('Zilch')))), ('True', vgl.SPPF(vgl.ParseTreeChar(vl.Class('True')))), ('False', vgl.SPPF(vgl.ParseTreeChar(vl.Class('False')))), ]) def test_atom(line: str, sppf: vgl.SPPF): atom = vg.GRAMMAR.get_rule('atom') lexemes = vl.lex_line(line) assert sppf == vg.make_sppf(atom, lexemes) ## Instruction: Revise grammar tests for atom ## Code After: import viper.grammar as vg import viper.lexer as vl from viper.grammar.languages import ( SPPF, ParseTreeEmpty as PTE, ParseTreeChar as PTC, ParseTreePair as PTP, ParseTreeRep as PTR ) import pytest @pytest.mark.parametrize('line,sppf', [ ('foo', SPPF(PTC(vl.Name('foo')))), ('42', SPPF(PTC(vl.Number('42')))), ('...', SPPF(PTC(vl.Operator('...')))), ('Zilch', SPPF(PTC(vl.Class('Zilch')))), ('True', SPPF(PTC(vl.Class('True')))), ('False', SPPF(PTC(vl.Class('False')))), ('()', SPPF(PTP(SPPF(PTC(vl.OpenParen())), SPPF(PTC(vl.CloseParen()))))), ('(foo)', SPPF(PTP(SPPF(PTC(vl.OpenParen())), SPPF(PTP(SPPF(PTP(SPPF(PTC(vl.Name('foo'))), SPPF(PTR(SPPF())))), SPPF(PTC(vl.CloseParen()))))))), ]) def test_atom(line: str, sppf: SPPF): atom = vg.GRAMMAR.get_rule('atom') lexemes = vl.lex_line(line) assert sppf == vg.make_sppf(atom, lexemes)
// ... existing code ... import viper.grammar as vg import viper.lexer as vl from viper.grammar.languages import ( SPPF, ParseTreeEmpty as PTE, ParseTreeChar as PTC, ParseTreePair as PTP, ParseTreeRep as PTR ) // ... modified code ... ('foo', SPPF(PTC(vl.Name('foo')))), ('42', SPPF(PTC(vl.Number('42')))), ('...', SPPF(PTC(vl.Operator('...')))), ('Zilch', SPPF(PTC(vl.Class('Zilch')))), ('True', SPPF(PTC(vl.Class('True')))), ('False', SPPF(PTC(vl.Class('False')))), ('()', SPPF(PTP(SPPF(PTC(vl.OpenParen())), SPPF(PTC(vl.CloseParen()))))), ('(foo)', SPPF(PTP(SPPF(PTC(vl.OpenParen())), SPPF(PTP(SPPF(PTP(SPPF(PTC(vl.Name('foo'))), SPPF(PTR(SPPF())))), SPPF(PTC(vl.CloseParen()))))))), ]) def test_atom(line: str, sppf: SPPF): atom = vg.GRAMMAR.get_rule('atom') // ... rest of the code ...
b04afdc4a6808029443e8107c651a24ba5f9842a
gitman/__init__.py
gitman/__init__.py
"""Package for GitMan.""" from pkg_resources import get_distribution from .commands import delete as uninstall # pylint: disable=redefined-builtin from .commands import display as list from .commands import init, install, lock, update __version__ = get_distribution("gitman").version
"""Package for GitMan.""" from pkg_resources import DistributionNotFound, get_distribution from .commands import delete as uninstall # pylint: disable=redefined-builtin from .commands import display as list from .commands import init, install, lock, update try: __version__ = get_distribution("gitman").version except DistributionNotFound: __version__ = "???"
Handle missing distribution on ReadTheDocs
Handle missing distribution on ReadTheDocs
Python
mit
jacebrowning/gitman
"""Package for GitMan.""" - from pkg_resources import get_distribution + from pkg_resources import DistributionNotFound, get_distribution from .commands import delete as uninstall # pylint: disable=redefined-builtin from .commands import display as list from .commands import init, install, lock, update + try: - __version__ = get_distribution("gitman").version + __version__ = get_distribution("gitman").version + except DistributionNotFound: + __version__ = "???"
Handle missing distribution on ReadTheDocs
## Code Before: """Package for GitMan.""" from pkg_resources import get_distribution from .commands import delete as uninstall # pylint: disable=redefined-builtin from .commands import display as list from .commands import init, install, lock, update __version__ = get_distribution("gitman").version ## Instruction: Handle missing distribution on ReadTheDocs ## Code After: """Package for GitMan.""" from pkg_resources import DistributionNotFound, get_distribution from .commands import delete as uninstall # pylint: disable=redefined-builtin from .commands import display as list from .commands import init, install, lock, update try: __version__ = get_distribution("gitman").version except DistributionNotFound: __version__ = "???"
... from pkg_resources import DistributionNotFound, get_distribution ... try: __version__ = get_distribution("gitman").version except DistributionNotFound: __version__ = "???" ...
bce0d37239f3d054274c0a1c90402e03d6e48b69
climate/data/montecarlo.py
climate/data/montecarlo.py
import numpy class dist: normal, random = range(2) # Monte carlo simulation data def montecarlo(callback, samples, **kwargs): """ generate random samples based on values """ vals = {} for var in kwargs: if isinstance(kwargs[var], tuple): (minVal, maxVal, distribution) = kwargs[var] if distribution == dist.normal: vals[var] = normal(samples, minVal, maxVal) elif distribution == dist.random: if isinstance(minVal, float) or isinstance(maxVal, float): vals[var] = randomFloat(samples, minVal, maxVal) else: vals[var] = randomInt(samples, minVal, maxVal) else: vals[var] = kwargs[var] for i in xrange(samples): callVals = {} for var in vals: if isinstance(vals[var], numpy.ndarray): callVals[var] = vals[var][i] else: callVals[var] = vals[var] callback(**callVals) def normal(samples, minVal, maxVal): mean = (maxVal + minVal) / 2. deviation = (mean - minVal) / 3. return numpy.random.normal(mean, deviation, samples) def randomFloat(samples, minVal, maxVal): return numpy.random.uniform(minVal, maxVal, samples) def randomInt(samples, minVal, maxVal): return numpy.random.randint(minVal, maxVal, samples)
import numpy class dist: normal, random = range(2) # Monte carlo simulation data def montecarlo(callback, samples, **kwargs): """ generate random samples based on values """ vals = {} for var in kwargs: if isinstance(kwargs[var], tuple): (minVal, maxVal, distribution) = kwargs[var] if distribution == dist.normal: vals[var] = normal(samples, minVal, maxVal) elif distribution == dist.random: if isinstance(minVal, float) or isinstance(maxVal, float): vals[var] = randomFloat(samples, minVal, maxVal) else: vals[var] = randomInt(samples, minVal, maxVal) else: vals[var] = kwargs[var] for i in xrange(samples): callVals = {} for var in vals: if isinstance(vals[var], numpy.ndarray): callVals[var] = vals[var][i] else: callVals[var] = vals[var] callback(**callVals) def normal(samples, minVal, maxVal): # Normal distribution from 0 to 2 distribution = numpy.random.standard_normal(samples) + 1 # From 0 to (maxVal - minVal) distribution *= (maxVal - minVal) / 2. # From minVal to maxVal distribution += minVal return distribution def randomFloat(samples, minVal, maxVal): return numpy.random.uniform(minVal, maxVal, samples) def randomInt(samples, minVal, maxVal): return numpy.random.randint(minVal, maxVal, samples)
Change in the implementation of normal distribution
Change in the implementation of normal distribution
Python
mit
dionhaefner/veros,dionhaefner/veros
import numpy class dist: normal, random = range(2) # Monte carlo simulation data def montecarlo(callback, samples, **kwargs): """ generate random samples based on values """ vals = {} for var in kwargs: if isinstance(kwargs[var], tuple): (minVal, maxVal, distribution) = kwargs[var] if distribution == dist.normal: vals[var] = normal(samples, minVal, maxVal) elif distribution == dist.random: if isinstance(minVal, float) or isinstance(maxVal, float): vals[var] = randomFloat(samples, minVal, maxVal) else: vals[var] = randomInt(samples, minVal, maxVal) else: vals[var] = kwargs[var] for i in xrange(samples): callVals = {} for var in vals: if isinstance(vals[var], numpy.ndarray): callVals[var] = vals[var][i] else: callVals[var] = vals[var] callback(**callVals) def normal(samples, minVal, maxVal): + # Normal distribution from 0 to 2 + distribution = numpy.random.standard_normal(samples) + 1 + # From 0 to (maxVal - minVal) - mean = (maxVal + minVal) / 2. + distribution *= (maxVal - minVal) / 2. - deviation = (mean - minVal) / 3. - return numpy.random.normal(mean, deviation, samples) + # From minVal to maxVal + distribution += minVal + return distribution def randomFloat(samples, minVal, maxVal): return numpy.random.uniform(minVal, maxVal, samples) def randomInt(samples, minVal, maxVal): return numpy.random.randint(minVal, maxVal, samples)
Change in the implementation of normal distribution
## Code Before: import numpy class dist: normal, random = range(2) # Monte carlo simulation data def montecarlo(callback, samples, **kwargs): """ generate random samples based on values """ vals = {} for var in kwargs: if isinstance(kwargs[var], tuple): (minVal, maxVal, distribution) = kwargs[var] if distribution == dist.normal: vals[var] = normal(samples, minVal, maxVal) elif distribution == dist.random: if isinstance(minVal, float) or isinstance(maxVal, float): vals[var] = randomFloat(samples, minVal, maxVal) else: vals[var] = randomInt(samples, minVal, maxVal) else: vals[var] = kwargs[var] for i in xrange(samples): callVals = {} for var in vals: if isinstance(vals[var], numpy.ndarray): callVals[var] = vals[var][i] else: callVals[var] = vals[var] callback(**callVals) def normal(samples, minVal, maxVal): mean = (maxVal + minVal) / 2. deviation = (mean - minVal) / 3. return numpy.random.normal(mean, deviation, samples) def randomFloat(samples, minVal, maxVal): return numpy.random.uniform(minVal, maxVal, samples) def randomInt(samples, minVal, maxVal): return numpy.random.randint(minVal, maxVal, samples) ## Instruction: Change in the implementation of normal distribution ## Code After: import numpy class dist: normal, random = range(2) # Monte carlo simulation data def montecarlo(callback, samples, **kwargs): """ generate random samples based on values """ vals = {} for var in kwargs: if isinstance(kwargs[var], tuple): (minVal, maxVal, distribution) = kwargs[var] if distribution == dist.normal: vals[var] = normal(samples, minVal, maxVal) elif distribution == dist.random: if isinstance(minVal, float) or isinstance(maxVal, float): vals[var] = randomFloat(samples, minVal, maxVal) else: vals[var] = randomInt(samples, minVal, maxVal) else: vals[var] = kwargs[var] for i in xrange(samples): callVals = {} for var in vals: if isinstance(vals[var], numpy.ndarray): callVals[var] = vals[var][i] else: callVals[var] = vals[var] callback(**callVals) def normal(samples, minVal, maxVal): # Normal distribution from 0 to 2 distribution = numpy.random.standard_normal(samples) + 1 # From 0 to (maxVal - minVal) distribution *= (maxVal - minVal) / 2. # From minVal to maxVal distribution += minVal return distribution def randomFloat(samples, minVal, maxVal): return numpy.random.uniform(minVal, maxVal, samples) def randomInt(samples, minVal, maxVal): return numpy.random.randint(minVal, maxVal, samples)
// ... existing code ... def normal(samples, minVal, maxVal): # Normal distribution from 0 to 2 distribution = numpy.random.standard_normal(samples) + 1 # From 0 to (maxVal - minVal) distribution *= (maxVal - minVal) / 2. # From minVal to maxVal distribution += minVal return distribution // ... rest of the code ...
8db252d2980451a3c2107df64c4438de44781eea
frigg/projects/urls.py
frigg/projects/urls.py
from django.conf.urls import url from . import views urlpatterns = [ url(r'^projects/approve/$', views.approve_projects, name='approve_projects_overview'), url(r'^projects/approve/(?P<project_id>\d+)/$', views.approve_projects, name='approve_project'), url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+).svg$', views.build_badge, name='build_badge'), url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+)/coverage.svg$', views.coverage_badge, name='coverage_badge'), ]
from django.conf.urls import url from . import views urlpatterns = [ url(r'^projects/approve/$', views.approve_projects, name='approve_projects_overview'), url(r'^projects/approve/(?P<project_id>\d+)/$', views.approve_projects, name='approve_project'), url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+).svg$', views.build_badge, name='build_badge'), url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+)/(?P<branch>[^/]+).svg$', views.build_badge, name='build_branch_badge'), url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+)/coverage.svg$', views.coverage_badge, name='coverage_badge'), url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+)/(?P<branch>[^/]+)/coverage.svg$', views.coverage_badge, name='coverage_branch_badge'), ]
Add support for specifying branch name to svg badges
Add support for specifying branch name to svg badges
Python
mit
frigg/frigg-hq,frigg/frigg-hq,frigg/frigg-hq
from django.conf.urls import url from . import views urlpatterns = [ url(r'^projects/approve/$', views.approve_projects, name='approve_projects_overview'), url(r'^projects/approve/(?P<project_id>\d+)/$', views.approve_projects, name='approve_project'), url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+).svg$', views.build_badge, name='build_badge'), + url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+)/(?P<branch>[^/]+).svg$', views.build_badge, + name='build_branch_badge'), url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+)/coverage.svg$', views.coverage_badge, name='coverage_badge'), + url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+)/(?P<branch>[^/]+)/coverage.svg$', views.coverage_badge, + name='coverage_branch_badge'), ]
Add support for specifying branch name to svg badges
## Code Before: from django.conf.urls import url from . import views urlpatterns = [ url(r'^projects/approve/$', views.approve_projects, name='approve_projects_overview'), url(r'^projects/approve/(?P<project_id>\d+)/$', views.approve_projects, name='approve_project'), url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+).svg$', views.build_badge, name='build_badge'), url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+)/coverage.svg$', views.coverage_badge, name='coverage_badge'), ] ## Instruction: Add support for specifying branch name to svg badges ## Code After: from django.conf.urls import url from . import views urlpatterns = [ url(r'^projects/approve/$', views.approve_projects, name='approve_projects_overview'), url(r'^projects/approve/(?P<project_id>\d+)/$', views.approve_projects, name='approve_project'), url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+).svg$', views.build_badge, name='build_badge'), url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+)/(?P<branch>[^/]+).svg$', views.build_badge, name='build_branch_badge'), url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+)/coverage.svg$', views.coverage_badge, name='coverage_badge'), url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+)/(?P<branch>[^/]+)/coverage.svg$', views.coverage_badge, name='coverage_branch_badge'), ]
... url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+).svg$', views.build_badge, name='build_badge'), url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+)/(?P<branch>[^/]+).svg$', views.build_badge, name='build_branch_badge'), url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+)/coverage.svg$', views.coverage_badge, ... name='coverage_badge'), url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+)/(?P<branch>[^/]+)/coverage.svg$', views.coverage_badge, name='coverage_branch_badge'), ] ...
2367a5454660ffec6b4bab11939edc52197be791
guv/__init__.py
guv/__init__.py
version_info = (0, 20, 0) __version__ = '.'.join(map(str, version_info)) try: from . import greenthread from . import greenpool from . import queue from . import timeout from . import patcher from . import server from .hubs.trampoline import gyield import greenlet import pyuv_cffi # only to compile the shared library before monkey-patching sleep = greenthread.sleep spawn = greenthread.spawn spawn_n = greenthread.spawn_n spawn_after = greenthread.spawn_after kill = greenthread.kill Timeout = timeout.Timeout with_timeout = timeout.with_timeout GreenPool = greenpool.GreenPool GreenPile = greenpool.GreenPile Queue = queue.Queue import_patched = patcher.import_patched monkey_patch = patcher.monkey_patch serve = server.serve listen = server.listen connect = server.connect StopServe = server.StopServe wrap_ssl = server.wrap_ssl getcurrent = greenlet.greenlet.getcurrent except ImportError as e: # This is to make Debian packaging easier, it ignores import errors of greenlet so that the # packager can still at least access the version. Also this makes easy_install a little quieter if 'greenlet' not in str(e): # any other exception should be printed import traceback traceback.print_exc()
version_info = (0, 21, 0) __version__ = '.'.join(map(str, version_info)) try: from . import greenpool from . import queue from .hubs.trampoline import gyield from .greenthread import sleep, spawn, spawn_n, spawn_after, kill from .greenpool import GreenPool, GreenPile from .timeout import Timeout, with_timeout from .patcher import import_patched, monkey_patch from .server import serve, listen, connect, StopServe, wrap_ssl import pyuv_cffi # only to compile the shared library before monkey-patching except ImportError as e: # This is to make Debian packaging easier, it ignores import errors of greenlet so that the # packager can still at least access the version. Also this makes easy_install a little quieter if 'greenlet' not in str(e): # any other exception should be printed import traceback traceback.print_exc()
Reorganize imports (and bump version)
Reorganize imports (and bump version)
Python
mit
veegee/guv,veegee/guv
- version_info = (0, 20, 0) + version_info = (0, 21, 0) __version__ = '.'.join(map(str, version_info)) try: - from . import greenthread from . import greenpool from . import queue - from . import timeout - from . import patcher - from . import server from .hubs.trampoline import gyield - import greenlet + from .greenthread import sleep, spawn, spawn_n, spawn_after, kill + from .greenpool import GreenPool, GreenPile + from .timeout import Timeout, with_timeout + from .patcher import import_patched, monkey_patch + from .server import serve, listen, connect, StopServe, wrap_ssl + import pyuv_cffi # only to compile the shared library before monkey-patching - sleep = greenthread.sleep - spawn = greenthread.spawn - spawn_n = greenthread.spawn_n - spawn_after = greenthread.spawn_after - kill = greenthread.kill - - Timeout = timeout.Timeout - with_timeout = timeout.with_timeout - - GreenPool = greenpool.GreenPool - GreenPile = greenpool.GreenPile - - Queue = queue.Queue - - import_patched = patcher.import_patched - monkey_patch = patcher.monkey_patch - - serve = server.serve - listen = server.listen - connect = server.connect - StopServe = server.StopServe - wrap_ssl = server.wrap_ssl - - getcurrent = greenlet.greenlet.getcurrent except ImportError as e: # This is to make Debian packaging easier, it ignores import errors of greenlet so that the # packager can still at least access the version. Also this makes easy_install a little quieter if 'greenlet' not in str(e): # any other exception should be printed import traceback traceback.print_exc()
Reorganize imports (and bump version)
## Code Before: version_info = (0, 20, 0) __version__ = '.'.join(map(str, version_info)) try: from . import greenthread from . import greenpool from . import queue from . import timeout from . import patcher from . import server from .hubs.trampoline import gyield import greenlet import pyuv_cffi # only to compile the shared library before monkey-patching sleep = greenthread.sleep spawn = greenthread.spawn spawn_n = greenthread.spawn_n spawn_after = greenthread.spawn_after kill = greenthread.kill Timeout = timeout.Timeout with_timeout = timeout.with_timeout GreenPool = greenpool.GreenPool GreenPile = greenpool.GreenPile Queue = queue.Queue import_patched = patcher.import_patched monkey_patch = patcher.monkey_patch serve = server.serve listen = server.listen connect = server.connect StopServe = server.StopServe wrap_ssl = server.wrap_ssl getcurrent = greenlet.greenlet.getcurrent except ImportError as e: # This is to make Debian packaging easier, it ignores import errors of greenlet so that the # packager can still at least access the version. Also this makes easy_install a little quieter if 'greenlet' not in str(e): # any other exception should be printed import traceback traceback.print_exc() ## Instruction: Reorganize imports (and bump version) ## Code After: version_info = (0, 21, 0) __version__ = '.'.join(map(str, version_info)) try: from . import greenpool from . import queue from .hubs.trampoline import gyield from .greenthread import sleep, spawn, spawn_n, spawn_after, kill from .greenpool import GreenPool, GreenPile from .timeout import Timeout, with_timeout from .patcher import import_patched, monkey_patch from .server import serve, listen, connect, StopServe, wrap_ssl import pyuv_cffi # only to compile the shared library before monkey-patching except ImportError as e: # This is to make Debian packaging easier, it ignores import errors of greenlet so that the # packager can still at least access the version. Also this makes easy_install a little quieter if 'greenlet' not in str(e): # any other exception should be printed import traceback traceback.print_exc()
... version_info = (0, 21, 0) __version__ = '.'.join(map(str, version_info)) ... try: from . import greenpool ... from . import queue from .hubs.trampoline import gyield from .greenthread import sleep, spawn, spawn_n, spawn_after, kill from .greenpool import GreenPool, GreenPile from .timeout import Timeout, with_timeout from .patcher import import_patched, monkey_patch from .server import serve, listen, connect, StopServe, wrap_ssl import pyuv_cffi # only to compile the shared library before monkey-patching ... except ImportError as e: ...
25da28f685b9cffa86b9400957089bdd7b5513de
kaptan/handlers/yaml_handler.py
kaptan/handlers/yaml_handler.py
from __future__ import print_function, unicode_literals import yaml from . import BaseHandler class YamlHandler(BaseHandler): def load(self, data): return yaml.load(data) def dump(self, data, safe=False, **kwargs): if not safe: return yaml.dump(data, **kwargs) else: return yaml.safe_dump(data, **kwargs)
from __future__ import print_function, unicode_literals import yaml from . import BaseHandler class YamlHandler(BaseHandler): def load(self, data, safe=True): if safe: func = yaml.safe_load else: func = yaml.load return func(data) def dump(self, data, safe=True, **kwargs): if safe: func = yaml.safe_dump else: func = yaml.dump return func(data, **kwargs)
Make YAML handler safe by default
Make YAML handler safe by default Fixes #43
Python
bsd-3-clause
emre/kaptan
from __future__ import print_function, unicode_literals import yaml from . import BaseHandler class YamlHandler(BaseHandler): - def load(self, data): + def load(self, data, safe=True): + if safe: + func = yaml.safe_load + else: + func = yaml.load - return yaml.load(data) + return func(data) - def dump(self, data, safe=False, **kwargs): + def dump(self, data, safe=True, **kwargs): - if not safe: + if safe: - return yaml.dump(data, **kwargs) + func = yaml.safe_dump else: + func = yaml.dump - return yaml.safe_dump(data, **kwargs) + return func(data, **kwargs)
Make YAML handler safe by default
## Code Before: from __future__ import print_function, unicode_literals import yaml from . import BaseHandler class YamlHandler(BaseHandler): def load(self, data): return yaml.load(data) def dump(self, data, safe=False, **kwargs): if not safe: return yaml.dump(data, **kwargs) else: return yaml.safe_dump(data, **kwargs) ## Instruction: Make YAML handler safe by default ## Code After: from __future__ import print_function, unicode_literals import yaml from . import BaseHandler class YamlHandler(BaseHandler): def load(self, data, safe=True): if safe: func = yaml.safe_load else: func = yaml.load return func(data) def dump(self, data, safe=True, **kwargs): if safe: func = yaml.safe_dump else: func = yaml.dump return func(data, **kwargs)
# ... existing code ... def load(self, data, safe=True): if safe: func = yaml.safe_load else: func = yaml.load return func(data) def dump(self, data, safe=True, **kwargs): if safe: func = yaml.safe_dump else: func = yaml.dump return func(data, **kwargs) # ... rest of the code ...
78d520b88e13a35ac20a0eeea1385f35b17383d2
sieve/sieve.py
sieve/sieve.py
def sieve(n): return list(primes(n)) def primes(n): if n < 2: raise StopIteration yield 2 not_prime = set() for i in range(3, n+1, 2): if i not in not_prime: yield i not_prime.update(range(i*i, n, i))
def sieve(n): if n < 2: return [] not_prime = set() prime = [2] for i in range(3, n+1, 2): if i not in not_prime: prime.append(i) not_prime.update(range(i*i, n, i)) return prime
Switch to more optimal non-generator solution
Switch to more optimal non-generator solution
Python
agpl-3.0
CubicComet/exercism-python-solutions
def sieve(n): - return list(primes(n)) - - - def primes(n): if n < 2: + return [] - raise StopIteration - yield 2 not_prime = set() + prime = [2] for i in range(3, n+1, 2): if i not in not_prime: - yield i + prime.append(i) - not_prime.update(range(i*i, n, i)) + not_prime.update(range(i*i, n, i)) + return prime
Switch to more optimal non-generator solution
## Code Before: def sieve(n): return list(primes(n)) def primes(n): if n < 2: raise StopIteration yield 2 not_prime = set() for i in range(3, n+1, 2): if i not in not_prime: yield i not_prime.update(range(i*i, n, i)) ## Instruction: Switch to more optimal non-generator solution ## Code After: def sieve(n): if n < 2: return [] not_prime = set() prime = [2] for i in range(3, n+1, 2): if i not in not_prime: prime.append(i) not_prime.update(range(i*i, n, i)) return prime
# ... existing code ... def sieve(n): if n < 2: return [] not_prime = set() prime = [2] for i in range(3, n+1, 2): # ... modified code ... if i not in not_prime: prime.append(i) not_prime.update(range(i*i, n, i)) return prime # ... rest of the code ...
091b1f5eb7c999a8d9b2448c1ca75941d2efb926
opentaxii/auth/sqldb/models.py
opentaxii/auth/sqldb/models.py
import bcrypt from sqlalchemy.schema import Column from sqlalchemy.types import Integer, String from sqlalchemy.ext.declarative import declarative_base __all__ = ['Base', 'Account'] Base = declarative_base() MAX_STR_LEN = 256 class Account(Base): __tablename__ = 'accounts' id = Column(Integer, primary_key=True) username = Column(String(MAX_STR_LEN), unique=True) password_hash = Column(String(MAX_STR_LEN)) def set_password(self, password): if isinstance(password, unicode): password = password.encode('utf-8') self.password_hash = bcrypt.hashpw(password, bcrypt.gensalt()) def is_password_valid(self, password): if isinstance(password, unicode): password = password.encode('utf-8') hashed = self.password_hash.encode('utf-8') return bcrypt.hashpw(password, hashed) == hashed
import hmac import bcrypt from sqlalchemy.schema import Column from sqlalchemy.types import Integer, String from sqlalchemy.ext.declarative import declarative_base __all__ = ['Base', 'Account'] Base = declarative_base() MAX_STR_LEN = 256 class Account(Base): __tablename__ = 'accounts' id = Column(Integer, primary_key=True) username = Column(String(MAX_STR_LEN), unique=True) password_hash = Column(String(MAX_STR_LEN)) def set_password(self, password): if isinstance(password, unicode): password = password.encode('utf-8') self.password_hash = bcrypt.hashpw(password, bcrypt.gensalt()) def is_password_valid(self, password): if isinstance(password, unicode): password = password.encode('utf-8') hashed = self.password_hash.encode('utf-8') return hmac.compare_digest(bcrypt.hashpw(password, hashed), hashed)
Use constant time string comparison for password checking
Use constant time string comparison for password checking
Python
bsd-3-clause
EclecticIQ/OpenTAXII,Intelworks/OpenTAXII,EclecticIQ/OpenTAXII,Intelworks/OpenTAXII
+ import hmac + import bcrypt from sqlalchemy.schema import Column from sqlalchemy.types import Integer, String from sqlalchemy.ext.declarative import declarative_base __all__ = ['Base', 'Account'] Base = declarative_base() MAX_STR_LEN = 256 + class Account(Base): __tablename__ = 'accounts' id = Column(Integer, primary_key=True) username = Column(String(MAX_STR_LEN), unique=True) password_hash = Column(String(MAX_STR_LEN)) - def set_password(self, password): if isinstance(password, unicode): password = password.encode('utf-8') self.password_hash = bcrypt.hashpw(password, bcrypt.gensalt()) def is_password_valid(self, password): if isinstance(password, unicode): password = password.encode('utf-8') hashed = self.password_hash.encode('utf-8') - return bcrypt.hashpw(password, hashed) == hashed + return hmac.compare_digest(bcrypt.hashpw(password, hashed), hashed) - -
Use constant time string comparison for password checking
## Code Before: import bcrypt from sqlalchemy.schema import Column from sqlalchemy.types import Integer, String from sqlalchemy.ext.declarative import declarative_base __all__ = ['Base', 'Account'] Base = declarative_base() MAX_STR_LEN = 256 class Account(Base): __tablename__ = 'accounts' id = Column(Integer, primary_key=True) username = Column(String(MAX_STR_LEN), unique=True) password_hash = Column(String(MAX_STR_LEN)) def set_password(self, password): if isinstance(password, unicode): password = password.encode('utf-8') self.password_hash = bcrypt.hashpw(password, bcrypt.gensalt()) def is_password_valid(self, password): if isinstance(password, unicode): password = password.encode('utf-8') hashed = self.password_hash.encode('utf-8') return bcrypt.hashpw(password, hashed) == hashed ## Instruction: Use constant time string comparison for password checking ## Code After: import hmac import bcrypt from sqlalchemy.schema import Column from sqlalchemy.types import Integer, String from sqlalchemy.ext.declarative import declarative_base __all__ = ['Base', 'Account'] Base = declarative_base() MAX_STR_LEN = 256 class Account(Base): __tablename__ = 'accounts' id = Column(Integer, primary_key=True) username = Column(String(MAX_STR_LEN), unique=True) password_hash = Column(String(MAX_STR_LEN)) def set_password(self, password): if isinstance(password, unicode): password = password.encode('utf-8') self.password_hash = bcrypt.hashpw(password, bcrypt.gensalt()) def is_password_valid(self, password): if isinstance(password, unicode): password = password.encode('utf-8') hashed = self.password_hash.encode('utf-8') return hmac.compare_digest(bcrypt.hashpw(password, hashed), hashed)
# ... existing code ... import hmac import bcrypt # ... modified code ... class Account(Base): ... password_hash = Column(String(MAX_STR_LEN)) ... hashed = self.password_hash.encode('utf-8') return hmac.compare_digest(bcrypt.hashpw(password, hashed), hashed) # ... rest of the code ...
bb3ec131261f0619a86f21f549d6b1cb47f2c9ad
graph/serializers.py
graph/serializers.py
from rest_framework import serializers from measurement.models import Measurement from threshold_value.models import ThresholdValue from calendar import timegm from alarm.models import Alarm class GraphSeriesSerializer(serializers.ModelSerializer): x = serializers.SerializerMethodField('get_time') y = serializers.SerializerMethodField('get_value') class Meta: fields = ['x', 'y'] def get_time(self, obj): return int(timegm(obj.time.utctimetuple())) * 1000 # Milliseconds since epoch, UTC def get_value(self, obj): return obj.value class MeasurementGraphSeriesSerializer(GraphSeriesSerializer): alarm = serializers.SerializerMethodField('get_alarm') def __init__(self, *args, **kwargs): self.alarm_dict = kwargs.pop('alarm_dict', None) super(MeasurementGraphSeriesSerializer, self).__init__(*args, **kwargs) if not self.alarm_dict: self.fields.pop('alarm') def get_alarm(self, obj): if obj.id in self.alarm_dict: alarm = self.alarm_dict[obj.id] serializer = SimpleAlarmSerializer(alarm) return serializer.data return None class Meta(GraphSeriesSerializer.Meta): model = Measurement fields = GraphSeriesSerializer.Meta.fields + ['alarm'] class ThresholdValueGraphSeriesSerializer(GraphSeriesSerializer): class Meta(GraphSeriesSerializer.Meta): model = ThresholdValue class SimpleAlarmSerializer(serializers.ModelSerializer): class Meta: model = Alarm fields = ('id', 'time_created', 'is_treated', 'treated_text')
from rest_framework import serializers from measurement.models import Measurement from threshold_value.models import ThresholdValue from calendar import timegm from alarm.models import Alarm class GraphSeriesSerializer(serializers.ModelSerializer): x = serializers.SerializerMethodField('get_time') y = serializers.SerializerMethodField('get_value') class Meta: fields = ['x', 'y'] def get_time(self, obj): return int(timegm(obj.time.utctimetuple())) * 1000 # Milliseconds since epoch, UTC def get_value(self, obj): return obj.value class MeasurementGraphSeriesSerializer(GraphSeriesSerializer): alarm = serializers.SerializerMethodField('get_alarm') def __init__(self, *args, **kwargs): self.alarm_dict = kwargs.pop('alarm_dict', None) super(MeasurementGraphSeriesSerializer, self).__init__(*args, **kwargs) if not self.alarm_dict: self.fields.pop('alarm') def get_alarm(self, obj): if obj.id in self.alarm_dict: alarm = self.alarm_dict[obj.id] serializer = SimpleAlarmSerializer(alarm) return serializer.data return None class Meta(GraphSeriesSerializer.Meta): model = Measurement fields = GraphSeriesSerializer.Meta.fields + ['alarm'] class ThresholdValueGraphSeriesSerializer(GraphSeriesSerializer): class Meta(GraphSeriesSerializer.Meta): model = ThresholdValue class SimpleAlarmSerializer(serializers.ModelSerializer): class Meta: model = Alarm fields = ['is_treated']
Simplify SimpleAlarmSerializer to improve the performance of the graph_data endpoint
Simplify SimpleAlarmSerializer to improve the performance of the graph_data endpoint
Python
mit
sigurdsa/angelika-api
from rest_framework import serializers from measurement.models import Measurement from threshold_value.models import ThresholdValue from calendar import timegm from alarm.models import Alarm class GraphSeriesSerializer(serializers.ModelSerializer): x = serializers.SerializerMethodField('get_time') y = serializers.SerializerMethodField('get_value') class Meta: fields = ['x', 'y'] def get_time(self, obj): return int(timegm(obj.time.utctimetuple())) * 1000 # Milliseconds since epoch, UTC def get_value(self, obj): return obj.value class MeasurementGraphSeriesSerializer(GraphSeriesSerializer): alarm = serializers.SerializerMethodField('get_alarm') def __init__(self, *args, **kwargs): self.alarm_dict = kwargs.pop('alarm_dict', None) super(MeasurementGraphSeriesSerializer, self).__init__(*args, **kwargs) if not self.alarm_dict: self.fields.pop('alarm') def get_alarm(self, obj): if obj.id in self.alarm_dict: alarm = self.alarm_dict[obj.id] serializer = SimpleAlarmSerializer(alarm) return serializer.data return None class Meta(GraphSeriesSerializer.Meta): model = Measurement fields = GraphSeriesSerializer.Meta.fields + ['alarm'] class ThresholdValueGraphSeriesSerializer(GraphSeriesSerializer): class Meta(GraphSeriesSerializer.Meta): model = ThresholdValue class SimpleAlarmSerializer(serializers.ModelSerializer): class Meta: model = Alarm - fields = ('id', 'time_created', 'is_treated', 'treated_text') + fields = ['is_treated']
Simplify SimpleAlarmSerializer to improve the performance of the graph_data endpoint
## Code Before: from rest_framework import serializers from measurement.models import Measurement from threshold_value.models import ThresholdValue from calendar import timegm from alarm.models import Alarm class GraphSeriesSerializer(serializers.ModelSerializer): x = serializers.SerializerMethodField('get_time') y = serializers.SerializerMethodField('get_value') class Meta: fields = ['x', 'y'] def get_time(self, obj): return int(timegm(obj.time.utctimetuple())) * 1000 # Milliseconds since epoch, UTC def get_value(self, obj): return obj.value class MeasurementGraphSeriesSerializer(GraphSeriesSerializer): alarm = serializers.SerializerMethodField('get_alarm') def __init__(self, *args, **kwargs): self.alarm_dict = kwargs.pop('alarm_dict', None) super(MeasurementGraphSeriesSerializer, self).__init__(*args, **kwargs) if not self.alarm_dict: self.fields.pop('alarm') def get_alarm(self, obj): if obj.id in self.alarm_dict: alarm = self.alarm_dict[obj.id] serializer = SimpleAlarmSerializer(alarm) return serializer.data return None class Meta(GraphSeriesSerializer.Meta): model = Measurement fields = GraphSeriesSerializer.Meta.fields + ['alarm'] class ThresholdValueGraphSeriesSerializer(GraphSeriesSerializer): class Meta(GraphSeriesSerializer.Meta): model = ThresholdValue class SimpleAlarmSerializer(serializers.ModelSerializer): class Meta: model = Alarm fields = ('id', 'time_created', 'is_treated', 'treated_text') ## Instruction: Simplify SimpleAlarmSerializer to improve the performance of the graph_data endpoint ## Code After: from rest_framework import serializers from measurement.models import Measurement from threshold_value.models import ThresholdValue from calendar import timegm from alarm.models import Alarm class GraphSeriesSerializer(serializers.ModelSerializer): x = serializers.SerializerMethodField('get_time') y = serializers.SerializerMethodField('get_value') class Meta: fields = ['x', 'y'] def get_time(self, obj): return int(timegm(obj.time.utctimetuple())) * 1000 # Milliseconds since epoch, UTC def get_value(self, obj): return obj.value class MeasurementGraphSeriesSerializer(GraphSeriesSerializer): alarm = serializers.SerializerMethodField('get_alarm') def __init__(self, *args, **kwargs): self.alarm_dict = kwargs.pop('alarm_dict', None) super(MeasurementGraphSeriesSerializer, self).__init__(*args, **kwargs) if not self.alarm_dict: self.fields.pop('alarm') def get_alarm(self, obj): if obj.id in self.alarm_dict: alarm = self.alarm_dict[obj.id] serializer = SimpleAlarmSerializer(alarm) return serializer.data return None class Meta(GraphSeriesSerializer.Meta): model = Measurement fields = GraphSeriesSerializer.Meta.fields + ['alarm'] class ThresholdValueGraphSeriesSerializer(GraphSeriesSerializer): class Meta(GraphSeriesSerializer.Meta): model = ThresholdValue class SimpleAlarmSerializer(serializers.ModelSerializer): class Meta: model = Alarm fields = ['is_treated']
# ... existing code ... model = Alarm fields = ['is_treated'] # ... rest of the code ...
7bf477f2ce728ed4af4163a0a96f9ec1b3b76d8d
tests/cyclus_tools.py
tests/cyclus_tools.py
import os from tools import check_cmd def run_cyclus(cyclus, cwd, sim_files): """Runs cyclus with various inputs and creates output databases """ for sim_input, sim_output in sim_files: holdsrtn = [1] # needed because nose does not send() to test generator # make sure the output target directory exists if not os.path.exists(sim_output): os.makedirs(sim_output) cmd = [cyclus, "-o", sim_output, "--input-file", sim_input] check_cmd(cmd, cwd, holdsrtn) rtn = holdsrtn[0] if rtn != 0: return # don"t execute further commands
import os from tools import check_cmd def run_cyclus(cyclus, cwd, sim_files): """Runs cyclus with various inputs and creates output databases """ for sim_input, sim_output in sim_files: holdsrtn = [1] # needed because nose does not send() to test generator # make sure the output target directory exists if not os.path.exists(os.path.dirname(sim_output)): os.makedirs(os.path.dirname(sim_output)) cmd = [cyclus, "-o", sim_output, "--input-file", sim_input] check_cmd(cmd, cwd, holdsrtn) rtn = holdsrtn[0] if rtn != 0: return # don"t execute further commands
Correct a bug in creating directories as needed for output.
Correct a bug in creating directories as needed for output.
Python
bsd-3-clause
Baaaaam/cyBaM,Baaaaam/cyBaM,Baaaaam/cyBaM,rwcarlsen/cycamore,rwcarlsen/cycamore,gonuke/cycamore,Baaaaam/cycamore,Baaaaam/cyBaM,jlittell/cycamore,rwcarlsen/cycamore,jlittell/cycamore,cyclus/cycaless,gonuke/cycamore,Baaaaam/cyCLASS,jlittell/cycamore,gonuke/cycamore,jlittell/cycamore,Baaaaam/cycamore,gonuke/cycamore,cyclus/cycaless,Baaaaam/cyCLASS,rwcarlsen/cycamore,Baaaaam/cycamore
import os from tools import check_cmd def run_cyclus(cyclus, cwd, sim_files): """Runs cyclus with various inputs and creates output databases """ for sim_input, sim_output in sim_files: holdsrtn = [1] # needed because nose does not send() to test generator # make sure the output target directory exists - if not os.path.exists(sim_output): + if not os.path.exists(os.path.dirname(sim_output)): - os.makedirs(sim_output) + os.makedirs(os.path.dirname(sim_output)) cmd = [cyclus, "-o", sim_output, "--input-file", sim_input] check_cmd(cmd, cwd, holdsrtn) rtn = holdsrtn[0] if rtn != 0: return # don"t execute further commands
Correct a bug in creating directories as needed for output.
## Code Before: import os from tools import check_cmd def run_cyclus(cyclus, cwd, sim_files): """Runs cyclus with various inputs and creates output databases """ for sim_input, sim_output in sim_files: holdsrtn = [1] # needed because nose does not send() to test generator # make sure the output target directory exists if not os.path.exists(sim_output): os.makedirs(sim_output) cmd = [cyclus, "-o", sim_output, "--input-file", sim_input] check_cmd(cmd, cwd, holdsrtn) rtn = holdsrtn[0] if rtn != 0: return # don"t execute further commands ## Instruction: Correct a bug in creating directories as needed for output. ## Code After: import os from tools import check_cmd def run_cyclus(cyclus, cwd, sim_files): """Runs cyclus with various inputs and creates output databases """ for sim_input, sim_output in sim_files: holdsrtn = [1] # needed because nose does not send() to test generator # make sure the output target directory exists if not os.path.exists(os.path.dirname(sim_output)): os.makedirs(os.path.dirname(sim_output)) cmd = [cyclus, "-o", sim_output, "--input-file", sim_input] check_cmd(cmd, cwd, holdsrtn) rtn = holdsrtn[0] if rtn != 0: return # don"t execute further commands
// ... existing code ... # make sure the output target directory exists if not os.path.exists(os.path.dirname(sim_output)): os.makedirs(os.path.dirname(sim_output)) // ... rest of the code ...
548cfea821bf1b0b92ce09c54405554d264b5395
tests/integration/session/test_timeout.py
tests/integration/session/test_timeout.py
import time from app import settings from tests.integration.integration_test_case import IntegrationTestCase class TestTimeout(IntegrationTestCase): def setUp(self): settings.EQ_SESSION_TIMEOUT_SECONDS = 1 settings.EQ_SESSION_TIMEOUT_GRACE_PERIOD_SECONDS = 0 super().setUp() def test_timeout_continue_returns_200(self): self.launchSurvey('test', 'timeout') self.get('/timeout-continue') self.assertStatusOK() def test_when_session_times_out_server_side_401_is_returned(self): self.launchSurvey('test', 'timeout') time.sleep(2) self.get(self.last_url) self.assertStatusUnauthorised() def test_schema_defined_timeout_is_used(self): self.launchSurvey('test', 'timeout') self.assertInPage('window.__EQ_SESSION_TIMEOUT__ = 1') def test_schema_defined_timeout_cant_be_higher_than_server(self): self._application.config['EQ_SESSION_TIMEOUT_SECONDS'] = 10 self.launchSurvey('test', 'timeout') self.assertInPage('window.__EQ_SESSION_TIMEOUT__ = 6')
import time from app import settings from tests.integration.integration_test_case import IntegrationTestCase class TestTimeout(IntegrationTestCase): def setUp(self): settings.EQ_SESSION_TIMEOUT_SECONDS = 1 settings.EQ_SESSION_TIMEOUT_GRACE_PERIOD_SECONDS = 0 super().setUp() def tearDown(self): settings.EQ_SESSION_TIMEOUT_SECONDS = 45 * 60 settings.EQ_SESSION_TIMEOUT_GRACE_PERIOD_SECONDS = 30 super().tearDown() def test_timeout_continue_returns_200(self): self.launchSurvey('test', 'timeout') self.get('/timeout-continue') self.assertStatusOK() def test_when_session_times_out_server_side_401_is_returned(self): self.launchSurvey('test', 'timeout') time.sleep(2) self.get(self.last_url) self.assertStatusUnauthorised() def test_schema_defined_timeout_is_used(self): self.launchSurvey('test', 'timeout') self.assertInPage('window.__EQ_SESSION_TIMEOUT__ = 1') def test_schema_defined_timeout_cant_be_higher_than_server(self): self._application.config['EQ_SESSION_TIMEOUT_SECONDS'] = 10 self.launchSurvey('test', 'timeout') self.assertInPage('window.__EQ_SESSION_TIMEOUT__ = 6')
Fix CSRF missing errors that happen occasionally in tests
Fix CSRF missing errors that happen occasionally in tests
Python
mit
ONSdigital/eq-survey-runner,ONSdigital/eq-survey-runner,ONSdigital/eq-survey-runner,ONSdigital/eq-survey-runner
import time from app import settings from tests.integration.integration_test_case import IntegrationTestCase class TestTimeout(IntegrationTestCase): def setUp(self): settings.EQ_SESSION_TIMEOUT_SECONDS = 1 settings.EQ_SESSION_TIMEOUT_GRACE_PERIOD_SECONDS = 0 super().setUp() + + def tearDown(self): + settings.EQ_SESSION_TIMEOUT_SECONDS = 45 * 60 + settings.EQ_SESSION_TIMEOUT_GRACE_PERIOD_SECONDS = 30 + super().tearDown() def test_timeout_continue_returns_200(self): self.launchSurvey('test', 'timeout') self.get('/timeout-continue') self.assertStatusOK() def test_when_session_times_out_server_side_401_is_returned(self): self.launchSurvey('test', 'timeout') time.sleep(2) self.get(self.last_url) self.assertStatusUnauthorised() def test_schema_defined_timeout_is_used(self): self.launchSurvey('test', 'timeout') self.assertInPage('window.__EQ_SESSION_TIMEOUT__ = 1') def test_schema_defined_timeout_cant_be_higher_than_server(self): self._application.config['EQ_SESSION_TIMEOUT_SECONDS'] = 10 self.launchSurvey('test', 'timeout') self.assertInPage('window.__EQ_SESSION_TIMEOUT__ = 6')
Fix CSRF missing errors that happen occasionally in tests
## Code Before: import time from app import settings from tests.integration.integration_test_case import IntegrationTestCase class TestTimeout(IntegrationTestCase): def setUp(self): settings.EQ_SESSION_TIMEOUT_SECONDS = 1 settings.EQ_SESSION_TIMEOUT_GRACE_PERIOD_SECONDS = 0 super().setUp() def test_timeout_continue_returns_200(self): self.launchSurvey('test', 'timeout') self.get('/timeout-continue') self.assertStatusOK() def test_when_session_times_out_server_side_401_is_returned(self): self.launchSurvey('test', 'timeout') time.sleep(2) self.get(self.last_url) self.assertStatusUnauthorised() def test_schema_defined_timeout_is_used(self): self.launchSurvey('test', 'timeout') self.assertInPage('window.__EQ_SESSION_TIMEOUT__ = 1') def test_schema_defined_timeout_cant_be_higher_than_server(self): self._application.config['EQ_SESSION_TIMEOUT_SECONDS'] = 10 self.launchSurvey('test', 'timeout') self.assertInPage('window.__EQ_SESSION_TIMEOUT__ = 6') ## Instruction: Fix CSRF missing errors that happen occasionally in tests ## Code After: import time from app import settings from tests.integration.integration_test_case import IntegrationTestCase class TestTimeout(IntegrationTestCase): def setUp(self): settings.EQ_SESSION_TIMEOUT_SECONDS = 1 settings.EQ_SESSION_TIMEOUT_GRACE_PERIOD_SECONDS = 0 super().setUp() def tearDown(self): settings.EQ_SESSION_TIMEOUT_SECONDS = 45 * 60 settings.EQ_SESSION_TIMEOUT_GRACE_PERIOD_SECONDS = 30 super().tearDown() def test_timeout_continue_returns_200(self): self.launchSurvey('test', 'timeout') self.get('/timeout-continue') self.assertStatusOK() def test_when_session_times_out_server_side_401_is_returned(self): self.launchSurvey('test', 'timeout') time.sleep(2) self.get(self.last_url) self.assertStatusUnauthorised() def test_schema_defined_timeout_is_used(self): self.launchSurvey('test', 'timeout') self.assertInPage('window.__EQ_SESSION_TIMEOUT__ = 1') def test_schema_defined_timeout_cant_be_higher_than_server(self): self._application.config['EQ_SESSION_TIMEOUT_SECONDS'] = 10 self.launchSurvey('test', 'timeout') self.assertInPage('window.__EQ_SESSION_TIMEOUT__ = 6')
// ... existing code ... super().setUp() def tearDown(self): settings.EQ_SESSION_TIMEOUT_SECONDS = 45 * 60 settings.EQ_SESSION_TIMEOUT_GRACE_PERIOD_SECONDS = 30 super().tearDown() // ... rest of the code ...
631a096eb8b369258c85b5c014460166787abf6c
owid_grapher/various_scripts/extract_short_units_from_existing_vars.py
owid_grapher/various_scripts/extract_short_units_from_existing_vars.py
import os import sys sys.path.insert(1, os.path.join(sys.path[0], '../..')) import owid_grapher.wsgi from grapher_admin.models import Variable # use this script to extract and write short forms of unit of measurement for all variables that already exit in the db common_short_units = ['$', '£', '€', '%'] all_variables = Variable.objects.filter(fk_dst_id__namespace='wdi') for each in all_variables: if each.unit: if ' per ' in each.unit: short_form = each.unit.split(' per ')[0] if any(w in short_form for w in common_short_units): for x in common_short_units: if x in short_form: each.short_unit = x each.save() break else: each.short_unit = short_form each.save() elif any(x in each.unit for x in common_short_units): for y in common_short_units: if y in each.unit: each.short_unit = y each.save() break elif len(each.unit) < 9: # this length is sort of arbitrary at this point, taken from the unit 'hectares' each.short_unit = each.unit each.save()
import os import sys sys.path.insert(1, os.path.join(sys.path[0], '../..')) import owid_grapher.wsgi from grapher_admin.models import Variable # use this script to extract and write short forms of unit of measurement for all variables that already exit in the db common_short_units = ['$', '£', '€', '%'] all_variables = Variable.objects.filter(fk_dst_id__namespace='wdi') for each in all_variables: if each.unit and not each.short_unit: if ' per ' in each.unit: short_form = each.unit.split(' per ')[0] if any(w in short_form for w in common_short_units): for x in common_short_units: if x in short_form: each.short_unit = x each.save() break else: each.short_unit = short_form each.save() elif any(x in each.unit for x in common_short_units): for y in common_short_units: if y in each.unit: each.short_unit = y each.save() break elif len(each.unit) < 9: # this length is sort of arbitrary at this point, taken from the unit 'hectares' each.short_unit = each.unit each.save()
Make short unit extraction script idempotent
Make short unit extraction script idempotent
Python
mit
OurWorldInData/owid-grapher,owid/owid-grapher,aaldaber/owid-grapher,aaldaber/owid-grapher,owid/owid-grapher,owid/owid-grapher,owid/owid-grapher,OurWorldInData/our-world-in-data-grapher,OurWorldInData/owid-grapher,OurWorldInData/owid-grapher,aaldaber/owid-grapher,owid/owid-grapher,OurWorldInData/our-world-in-data-grapher,OurWorldInData/owid-grapher,OurWorldInData/our-world-in-data-grapher,aaldaber/owid-grapher,OurWorldInData/owid-grapher,aaldaber/owid-grapher,OurWorldInData/our-world-in-data-grapher
import os import sys sys.path.insert(1, os.path.join(sys.path[0], '../..')) import owid_grapher.wsgi from grapher_admin.models import Variable # use this script to extract and write short forms of unit of measurement for all variables that already exit in the db common_short_units = ['$', '£', '€', '%'] all_variables = Variable.objects.filter(fk_dst_id__namespace='wdi') for each in all_variables: - if each.unit: + if each.unit and not each.short_unit: if ' per ' in each.unit: short_form = each.unit.split(' per ')[0] if any(w in short_form for w in common_short_units): for x in common_short_units: if x in short_form: each.short_unit = x each.save() break else: each.short_unit = short_form each.save() elif any(x in each.unit for x in common_short_units): for y in common_short_units: if y in each.unit: each.short_unit = y each.save() break elif len(each.unit) < 9: # this length is sort of arbitrary at this point, taken from the unit 'hectares' each.short_unit = each.unit each.save()
Make short unit extraction script idempotent
## Code Before: import os import sys sys.path.insert(1, os.path.join(sys.path[0], '../..')) import owid_grapher.wsgi from grapher_admin.models import Variable # use this script to extract and write short forms of unit of measurement for all variables that already exit in the db common_short_units = ['$', '£', '€', '%'] all_variables = Variable.objects.filter(fk_dst_id__namespace='wdi') for each in all_variables: if each.unit: if ' per ' in each.unit: short_form = each.unit.split(' per ')[0] if any(w in short_form for w in common_short_units): for x in common_short_units: if x in short_form: each.short_unit = x each.save() break else: each.short_unit = short_form each.save() elif any(x in each.unit for x in common_short_units): for y in common_short_units: if y in each.unit: each.short_unit = y each.save() break elif len(each.unit) < 9: # this length is sort of arbitrary at this point, taken from the unit 'hectares' each.short_unit = each.unit each.save() ## Instruction: Make short unit extraction script idempotent ## Code After: import os import sys sys.path.insert(1, os.path.join(sys.path[0], '../..')) import owid_grapher.wsgi from grapher_admin.models import Variable # use this script to extract and write short forms of unit of measurement for all variables that already exit in the db common_short_units = ['$', '£', '€', '%'] all_variables = Variable.objects.filter(fk_dst_id__namespace='wdi') for each in all_variables: if each.unit and not each.short_unit: if ' per ' in each.unit: short_form = each.unit.split(' per ')[0] if any(w in short_form for w in common_short_units): for x in common_short_units: if x in short_form: each.short_unit = x each.save() break else: each.short_unit = short_form each.save() elif any(x in each.unit for x in common_short_units): for y in common_short_units: if y in each.unit: each.short_unit = y each.save() break elif len(each.unit) < 9: # this length is sort of arbitrary at this point, taken from the unit 'hectares' each.short_unit = each.unit each.save()
// ... existing code ... for each in all_variables: if each.unit and not each.short_unit: if ' per ' in each.unit: // ... rest of the code ...
6ce6f22837b9e6a1dc8423038b6e2eb3d0a8de89
rxet/helper.py
rxet/helper.py
from struct import unpack def read_uint32(fileobj): return unpack("I", fileobj.read(4))[0]
from struct import unpack def read_uint32(fileobj): return unpack("I", fileobj.read(4))[0] # read int as a big endian number def read_uint32_BE(fileobj): return unpack(">I", fileobj.read(4))[0]
Add big endian integer reading
Add big endian integer reading
Python
mit
RenolY2/battalion-tools
from struct import unpack def read_uint32(fileobj): return unpack("I", fileobj.read(4))[0] + + # read int as a big endian number + def read_uint32_BE(fileobj): + return unpack(">I", fileobj.read(4))[0]
Add big endian integer reading
## Code Before: from struct import unpack def read_uint32(fileobj): return unpack("I", fileobj.read(4))[0] ## Instruction: Add big endian integer reading ## Code After: from struct import unpack def read_uint32(fileobj): return unpack("I", fileobj.read(4))[0] # read int as a big endian number def read_uint32_BE(fileobj): return unpack(">I", fileobj.read(4))[0]
... return unpack("I", fileobj.read(4))[0] # read int as a big endian number def read_uint32_BE(fileobj): return unpack(">I", fileobj.read(4))[0] ...
8f4c376a57c68636188880cd92c64b4640b1c8cc
sheared/web/entwine.py
sheared/web/entwine.py
import warnings from dtml import tal, metal, tales, context from sheared.python import io class Entwiner: def __init__(self): self.builtins = context.BuiltIns({}) #self.context = context.Context() #self.context.setDefaults(self.builtins) def handle(self, request, reply, subpath): self.context = {} self.entwine(request, reply, subpath) r = self.execute(self.page_path, throwaway=0) reply.send(r) def execute(self, path, throwaway=1): r = io.readfile(path) c = tal.compile(r, tales) r = tal.execute(c, self.context, self.builtins, tales) c = metal.compile(r, tales) r = metal.execute(c, self.context, self.builtins, tales) if throwaway and r.strip(): warnings.warn('%s: ignored non-macro content' % path) return r
import warnings from dtml import tal, metal, tales from sheared.python import io class Entwiner: def handle(self, request, reply, subpath): self.context = {} self.entwine(request, reply, subpath) r = self.execute(self.page_path, throwaway=0) reply.send(r) def execute(self, path, throwaway=1): r = io.readfile(path) c = tal.compile(r, tales) r = tal.execute(c, self.context, tales) c = metal.compile(r, tales) r = metal.execute(c, self.context, tales) if throwaway and r.strip(): warnings.warn('%s: ignored non-macro content' % path) return r
Remove the builtins arguments to the {tal,metal}.execute calls.
Remove the builtins arguments to the {tal,metal}.execute calls. git-svn-id: 8b0eea19d26e20ec80f5c0ea247ec202fbcc1090@107 5646265b-94b7-0310-9681-9501d24b2df7
Python
mit
kirkeby/sheared
import warnings - from dtml import tal, metal, tales, context + from dtml import tal, metal, tales from sheared.python import io class Entwiner: - def __init__(self): - self.builtins = context.BuiltIns({}) - #self.context = context.Context() - #self.context.setDefaults(self.builtins) - def handle(self, request, reply, subpath): self.context = {} self.entwine(request, reply, subpath) r = self.execute(self.page_path, throwaway=0) - reply.send(r) def execute(self, path, throwaway=1): r = io.readfile(path) c = tal.compile(r, tales) - r = tal.execute(c, self.context, self.builtins, tales) + r = tal.execute(c, self.context, tales) c = metal.compile(r, tales) - r = metal.execute(c, self.context, self.builtins, tales) + r = metal.execute(c, self.context, tales) if throwaway and r.strip(): warnings.warn('%s: ignored non-macro content' % path) return r
Remove the builtins arguments to the {tal,metal}.execute calls.
## Code Before: import warnings from dtml import tal, metal, tales, context from sheared.python import io class Entwiner: def __init__(self): self.builtins = context.BuiltIns({}) #self.context = context.Context() #self.context.setDefaults(self.builtins) def handle(self, request, reply, subpath): self.context = {} self.entwine(request, reply, subpath) r = self.execute(self.page_path, throwaway=0) reply.send(r) def execute(self, path, throwaway=1): r = io.readfile(path) c = tal.compile(r, tales) r = tal.execute(c, self.context, self.builtins, tales) c = metal.compile(r, tales) r = metal.execute(c, self.context, self.builtins, tales) if throwaway and r.strip(): warnings.warn('%s: ignored non-macro content' % path) return r ## Instruction: Remove the builtins arguments to the {tal,metal}.execute calls. ## Code After: import warnings from dtml import tal, metal, tales from sheared.python import io class Entwiner: def handle(self, request, reply, subpath): self.context = {} self.entwine(request, reply, subpath) r = self.execute(self.page_path, throwaway=0) reply.send(r) def execute(self, path, throwaway=1): r = io.readfile(path) c = tal.compile(r, tales) r = tal.execute(c, self.context, tales) c = metal.compile(r, tales) r = metal.execute(c, self.context, tales) if throwaway and r.strip(): warnings.warn('%s: ignored non-macro content' % path) return r
// ... existing code ... from dtml import tal, metal, tales // ... modified code ... class Entwiner: def handle(self, request, reply, subpath): ... r = self.execute(self.page_path, throwaway=0) reply.send(r) ... c = tal.compile(r, tales) r = tal.execute(c, self.context, tales) c = metal.compile(r, tales) r = metal.execute(c, self.context, tales) // ... rest of the code ...
30a982448b4f0baa2abe02ea0d9ef0d4d21c8414
Main.py
Main.py
from App import App #try: app = App() app.run() #except: # print('')
from App import App try: app = App() app.run() except KeyboardInterrupt: print('')
Add try except for keyboard interrupts
Add try except for keyboard interrupts
Python
mit
Rookfighter/TextAdventure
from App import App - #try: + try: - app = App() + app = App() - app.run() + app.run() - #except: + except KeyboardInterrupt: - # print('') + print('')
Add try except for keyboard interrupts
## Code Before: from App import App #try: app = App() app.run() #except: # print('') ## Instruction: Add try except for keyboard interrupts ## Code After: from App import App try: app = App() app.run() except KeyboardInterrupt: print('')
# ... existing code ... try: app = App() app.run() except KeyboardInterrupt: print('') # ... rest of the code ...
3035521c5a8e04b8eeb6874d8769dd5859747d53
devpi_builder/cli.py
devpi_builder/cli.py
import argparse from devpi_builder import requirements, wheeler, devpi def main(args=None): parser = argparse.ArgumentParser(description='Create wheels for all given project versions and upload them to the given index.') parser.add_argument('requirements', help='requirements.txt style file specifying which project versions to package.') parser.add_argument('index', help='The index to upload the packaged software to.') parser.add_argument('user', help='The user to log in as.') parser.add_argument('password', help='Password of the user.') parser.add_argument('--blacklist', help='Packages matched by this requirements.txt style file will never be build.') args = parser.parse_args(args=args) with wheeler.Builder() as builder, devpi.Client(args.index, args.user, args.password) as devpi_client: for package, version in requirements.read(args.requirements): if devpi_client.package_version_exists(package, version): continue if args.blacklist and requirements.matched_by_file(package, version, args.blacklist): print('Skipping {} {} as it is matched by the blacklist.'.format(package, version)) else: print('Building {} {}.'.format(package, version)) try: wheel_file = builder(package, version) devpi_client.upload(wheel_file) except wheeler.BuildError as e: print(e)
import argparse import logging from devpi_builder import requirements, wheeler, devpi logging.basicConfig() logger = logging.getLogger(__name__) def main(args=None): parser = argparse.ArgumentParser(description='Create wheels for all given project versions and upload them to the given index.') parser.add_argument('requirements', help='requirements.txt style file specifying which project versions to package.') parser.add_argument('index', help='The index to upload the packaged software to.') parser.add_argument('user', help='The user to log in as.') parser.add_argument('password', help='Password of the user.') parser.add_argument('--blacklist', help='Packages matched by this requirements.txt style file will never be build.') args = parser.parse_args(args=args) with wheeler.Builder() as builder, devpi.Client(args.index, args.user, args.password) as devpi_client: for package, version in requirements.read(args.requirements): if devpi_client.package_version_exists(package, version): continue if args.blacklist and requirements.matched_by_file(package, version, args.blacklist): logger.info('Skipping %s %s as it is matched by the blacklist.', package, version) else: logger.info('Building %s %s', package, version) try: wheel_file = builder(package, version) devpi_client.upload(wheel_file) except wheeler.BuildError as e: logger.exception(e)
Use a logger instead of printing to stdout
Use a logger instead of printing to stdout
Python
bsd-3-clause
tylerdave/devpi-builder
import argparse + import logging from devpi_builder import requirements, wheeler, devpi + + logging.basicConfig() + logger = logging.getLogger(__name__) def main(args=None): parser = argparse.ArgumentParser(description='Create wheels for all given project versions and upload them to the given index.') parser.add_argument('requirements', help='requirements.txt style file specifying which project versions to package.') parser.add_argument('index', help='The index to upload the packaged software to.') parser.add_argument('user', help='The user to log in as.') parser.add_argument('password', help='Password of the user.') parser.add_argument('--blacklist', help='Packages matched by this requirements.txt style file will never be build.') args = parser.parse_args(args=args) with wheeler.Builder() as builder, devpi.Client(args.index, args.user, args.password) as devpi_client: for package, version in requirements.read(args.requirements): if devpi_client.package_version_exists(package, version): continue if args.blacklist and requirements.matched_by_file(package, version, args.blacklist): - print('Skipping {} {} as it is matched by the blacklist.'.format(package, version)) + logger.info('Skipping %s %s as it is matched by the blacklist.', package, version) else: - print('Building {} {}.'.format(package, version)) + logger.info('Building %s %s', package, version) try: wheel_file = builder(package, version) devpi_client.upload(wheel_file) except wheeler.BuildError as e: - print(e) + logger.exception(e)
Use a logger instead of printing to stdout
## Code Before: import argparse from devpi_builder import requirements, wheeler, devpi def main(args=None): parser = argparse.ArgumentParser(description='Create wheels for all given project versions and upload them to the given index.') parser.add_argument('requirements', help='requirements.txt style file specifying which project versions to package.') parser.add_argument('index', help='The index to upload the packaged software to.') parser.add_argument('user', help='The user to log in as.') parser.add_argument('password', help='Password of the user.') parser.add_argument('--blacklist', help='Packages matched by this requirements.txt style file will never be build.') args = parser.parse_args(args=args) with wheeler.Builder() as builder, devpi.Client(args.index, args.user, args.password) as devpi_client: for package, version in requirements.read(args.requirements): if devpi_client.package_version_exists(package, version): continue if args.blacklist and requirements.matched_by_file(package, version, args.blacklist): print('Skipping {} {} as it is matched by the blacklist.'.format(package, version)) else: print('Building {} {}.'.format(package, version)) try: wheel_file = builder(package, version) devpi_client.upload(wheel_file) except wheeler.BuildError as e: print(e) ## Instruction: Use a logger instead of printing to stdout ## Code After: import argparse import logging from devpi_builder import requirements, wheeler, devpi logging.basicConfig() logger = logging.getLogger(__name__) def main(args=None): parser = argparse.ArgumentParser(description='Create wheels for all given project versions and upload them to the given index.') parser.add_argument('requirements', help='requirements.txt style file specifying which project versions to package.') parser.add_argument('index', help='The index to upload the packaged software to.') parser.add_argument('user', help='The user to log in as.') parser.add_argument('password', help='Password of the user.') parser.add_argument('--blacklist', help='Packages matched by this requirements.txt style file will never be build.') args = parser.parse_args(args=args) with wheeler.Builder() as builder, devpi.Client(args.index, args.user, args.password) as devpi_client: for package, version in requirements.read(args.requirements): if devpi_client.package_version_exists(package, version): continue if args.blacklist and requirements.matched_by_file(package, version, args.blacklist): logger.info('Skipping %s %s as it is matched by the blacklist.', package, version) else: logger.info('Building %s %s', package, version) try: wheel_file = builder(package, version) devpi_client.upload(wheel_file) except wheeler.BuildError as e: logger.exception(e)
# ... existing code ... import argparse import logging # ... modified code ... from devpi_builder import requirements, wheeler, devpi logging.basicConfig() logger = logging.getLogger(__name__) ... if args.blacklist and requirements.matched_by_file(package, version, args.blacklist): logger.info('Skipping %s %s as it is matched by the blacklist.', package, version) else: logger.info('Building %s %s', package, version) try: ... except wheeler.BuildError as e: logger.exception(e) # ... rest of the code ...
8af349128b725e47b89f28ddc005d142a44c5765
openarc/env.py
openarc/env.py
import os import json class OAEnv(object): @property def static_http_root(self): if self.envcfg['httpinfo']['secure'] is True: security = "https://" else: security = "http://" return "%s%s" % ( security, self.envcfg['httpinfo']['httproot'] ) @property def dbinfo(self): return self.envcfg['dbinfo'] @property def crypto(self): return self.envcfg['crypto'] def __init__(self, requested_env): cfg_file = "%s/envcfg.json" % ( os.environ.get("OPENARC_CFG_DIR") ) with open( cfg_file ) as f: self.envcfg = json.loads( f.read() )[requested_env] #This is where we hold library state. #You will get cut if you don't manipulate the p_* variables #via getenv() and initenv() p_refcount_env = 0 p_env = None def initenv(envstr): """envstr: one of local, dev, qa, prod. Does not return OAEnv variable; for that, you must call getenv""" global p_env global p_refcount_env if p_refcount_env == 0: p_env = OAEnv(envstr) p_refcount_env += 1 def getenv(): """Accessor method for global state""" global p_env return p_env
import os import json class OAEnv(object): @property def static_http_root(self): if self.envcfg['httpinfo']['secure'] is True: security = "https://" else: security = "http://" return "%s%s" % ( security, self.envcfg['httpinfo']['httproot'] ) @property def dbinfo(self): return self.envcfg['dbinfo'] @property def crypto(self): return self.envcfg['crypto'] @property def extcreds(self): return self.envcfg['extcreds'] def __init__(self, requested_env): cfg_file = "%s/envcfg.json" % ( os.environ.get("OPENARC_CFG_DIR") ) with open( cfg_file ) as f: self.envcfg = json.loads( f.read() )[requested_env] #This is where we hold library state. #You will get cut if you don't manipulate the p_* variables #via getenv() and initenv() p_refcount_env = 0 p_env = None def initenv(envstr): """envstr: one of local, dev, qa, prod. Does not return OAEnv variable; for that, you must call getenv""" global p_env global p_refcount_env if p_refcount_env == 0: p_env = OAEnv(envstr) p_refcount_env += 1 def getenv(): """Accessor method for global state""" global p_env return p_env
Allow retrieval of external api credentials
Allow retrieval of external api credentials
Python
bsd-3-clause
kchoudhu/openarc
import os import json class OAEnv(object): @property def static_http_root(self): if self.envcfg['httpinfo']['secure'] is True: security = "https://" else: security = "http://" return "%s%s" % ( security, self.envcfg['httpinfo']['httproot'] ) @property def dbinfo(self): return self.envcfg['dbinfo'] @property def crypto(self): return self.envcfg['crypto'] + + @property + def extcreds(self): + return self.envcfg['extcreds'] def __init__(self, requested_env): cfg_file = "%s/envcfg.json" % ( os.environ.get("OPENARC_CFG_DIR") ) with open( cfg_file ) as f: self.envcfg = json.loads( f.read() )[requested_env] #This is where we hold library state. #You will get cut if you don't manipulate the p_* variables #via getenv() and initenv() p_refcount_env = 0 p_env = None def initenv(envstr): """envstr: one of local, dev, qa, prod. Does not return OAEnv variable; for that, you must call getenv""" global p_env global p_refcount_env if p_refcount_env == 0: p_env = OAEnv(envstr) p_refcount_env += 1 def getenv(): """Accessor method for global state""" global p_env return p_env
Allow retrieval of external api credentials
## Code Before: import os import json class OAEnv(object): @property def static_http_root(self): if self.envcfg['httpinfo']['secure'] is True: security = "https://" else: security = "http://" return "%s%s" % ( security, self.envcfg['httpinfo']['httproot'] ) @property def dbinfo(self): return self.envcfg['dbinfo'] @property def crypto(self): return self.envcfg['crypto'] def __init__(self, requested_env): cfg_file = "%s/envcfg.json" % ( os.environ.get("OPENARC_CFG_DIR") ) with open( cfg_file ) as f: self.envcfg = json.loads( f.read() )[requested_env] #This is where we hold library state. #You will get cut if you don't manipulate the p_* variables #via getenv() and initenv() p_refcount_env = 0 p_env = None def initenv(envstr): """envstr: one of local, dev, qa, prod. Does not return OAEnv variable; for that, you must call getenv""" global p_env global p_refcount_env if p_refcount_env == 0: p_env = OAEnv(envstr) p_refcount_env += 1 def getenv(): """Accessor method for global state""" global p_env return p_env ## Instruction: Allow retrieval of external api credentials ## Code After: import os import json class OAEnv(object): @property def static_http_root(self): if self.envcfg['httpinfo']['secure'] is True: security = "https://" else: security = "http://" return "%s%s" % ( security, self.envcfg['httpinfo']['httproot'] ) @property def dbinfo(self): return self.envcfg['dbinfo'] @property def crypto(self): return self.envcfg['crypto'] @property def extcreds(self): return self.envcfg['extcreds'] def __init__(self, requested_env): cfg_file = "%s/envcfg.json" % ( os.environ.get("OPENARC_CFG_DIR") ) with open( cfg_file ) as f: self.envcfg = json.loads( f.read() )[requested_env] #This is where we hold library state. #You will get cut if you don't manipulate the p_* variables #via getenv() and initenv() p_refcount_env = 0 p_env = None def initenv(envstr): """envstr: one of local, dev, qa, prod. Does not return OAEnv variable; for that, you must call getenv""" global p_env global p_refcount_env if p_refcount_env == 0: p_env = OAEnv(envstr) p_refcount_env += 1 def getenv(): """Accessor method for global state""" global p_env return p_env
// ... existing code ... return self.envcfg['crypto'] @property def extcreds(self): return self.envcfg['extcreds'] // ... rest of the code ...
2537cdf45650eb2d7d57d5e108a11658b4d64898
saleor/product/urls.py
saleor/product/urls.py
from django.conf.urls import patterns, url from . import views urlpatterns = [ url(r'^(?P<slug>[a-z0-9-]+?)-(?P<product_id>[0-9]+)/$', views.product_details, name='details'), url(r'^category/(?P<slug>[a-z0-9-]+?)/$', views.category_index, name='category') ]
from django.conf.urls import url from . import views urlpatterns = [ url(r'^(?P<slug>[a-z0-9-]+?)-(?P<product_id>[0-9]+)/$', views.product_details, name='details'), url(r'^category/(?P<slug>[\w-]+?)/$', views.category_index, name='category') ]
Fix url pattern for category's slug
Fix url pattern for category's slug
Python
bsd-3-clause
arth-co/saleor,HyperManTT/ECommerceSaleor,HyperManTT/ECommerceSaleor,rchav/vinerack,paweltin/saleor,avorio/saleor,arth-co/saleor,tfroehlich82/saleor,dashmug/saleor,maferelo/saleor,avorio/saleor,laosunhust/saleor,itbabu/saleor,KenMutemi/saleor,car3oon/saleor,Drekscott/Motlaesaleor,maferelo/saleor,taedori81/saleor,Drekscott/Motlaesaleor,UITools/saleor,itbabu/saleor,dashmug/saleor,taedori81/saleor,avorio/saleor,paweltin/saleor,spartonia/saleor,rodrigozn/CW-Shop,UITools/saleor,Drekscott/Motlaesaleor,jreigel/saleor,KenMutemi/saleor,mociepka/saleor,rodrigozn/CW-Shop,UITools/saleor,HyperManTT/ECommerceSaleor,arth-co/saleor,josesanch/saleor,laosunhust/saleor,paweltin/saleor,mociepka/saleor,Drekscott/Motlaesaleor,KenMutemi/saleor,josesanch/saleor,rodrigozn/CW-Shop,taedori81/saleor,josesanch/saleor,UITools/saleor,paweltin/saleor,car3oon/saleor,UITools/saleor,tfroehlich82/saleor,rchav/vinerack,laosunhust/saleor,car3oon/saleor,maferelo/saleor,laosunhust/saleor,spartonia/saleor,jreigel/saleor,rchav/vinerack,tfroehlich82/saleor,avorio/saleor,spartonia/saleor,taedori81/saleor,spartonia/saleor,dashmug/saleor,mociepka/saleor,itbabu/saleor,jreigel/saleor,arth-co/saleor
- from django.conf.urls import patterns, url + from django.conf.urls import url from . import views urlpatterns = [ url(r'^(?P<slug>[a-z0-9-]+?)-(?P<product_id>[0-9]+)/$', views.product_details, name='details'), - url(r'^category/(?P<slug>[a-z0-9-]+?)/$', views.category_index, + url(r'^category/(?P<slug>[\w-]+?)/$', views.category_index, name='category') ]
Fix url pattern for category's slug
## Code Before: from django.conf.urls import patterns, url from . import views urlpatterns = [ url(r'^(?P<slug>[a-z0-9-]+?)-(?P<product_id>[0-9]+)/$', views.product_details, name='details'), url(r'^category/(?P<slug>[a-z0-9-]+?)/$', views.category_index, name='category') ] ## Instruction: Fix url pattern for category's slug ## Code After: from django.conf.urls import url from . import views urlpatterns = [ url(r'^(?P<slug>[a-z0-9-]+?)-(?P<product_id>[0-9]+)/$', views.product_details, name='details'), url(r'^category/(?P<slug>[\w-]+?)/$', views.category_index, name='category') ]
... from django.conf.urls import url ... views.product_details, name='details'), url(r'^category/(?P<slug>[\w-]+?)/$', views.category_index, name='category') ...
8e41709078885313b12f3b6e619573851a21be19
scripts/check_env.py
scripts/check_env.py
import sys import subprocess return_value = 0 required_packages = ['numpy', 'scipy', 'matplotlib', 'SimpleITK'] for package in required_packages: print('Importing ' + package + ' ...') try: __import__(package, globals(), locals(), [], 0) except ImportError: print('Error: could not import ' + package) return_value += 1 required_executables = ['git', 'dexy', 'ipython', 'nosetests'] for executable in required_executables: print('Executing ' + executable + ' ...') try: output = subprocess.check_output([executable, '--help']) except OSError: print('Error: could not execute ' + executable) return_value += 1 if return_value is 0: print('\nSuccess.') else: print('\nAn error was found in your environment, please see the messages ' + 'above.') sys.exit(return_value)
import sys import subprocess return_value = 0 required_packages = ['numpy', 'scipy', 'matplotlib', 'SimpleITK'] for package in required_packages: print('Importing ' + package + ' ...') try: __import__(package, globals(), locals(), [], 0) except ImportError: print('Error: could not import ' + package) return_value += 1 print('') required_executables = ['git', 'dexy', 'ipython', 'nosetests', 'ffmpeg'] for executable in required_executables: print('Executing ' + executable + ' ...') try: output = subprocess.check_output([executable, '--help'], stderr=subprocess.STDOUT) except OSError: print('Error: could not execute ' + executable) return_value += 1 if return_value is 0: print('\nSuccess.') else: print('\nAn defect was found in your environment, please see the messages ' + 'above.') sys.exit(return_value)
Add ffmpeg to the required environment.
Add ffmpeg to the required environment.
Python
apache-2.0
5x5x5x5/ReproTutorial,5x5x5x5/ReproTutorial,reproducible-research/scipy-tutorial-2014,reproducible-research/scipy-tutorial-2014,5x5x5x5/ReproTutorial,reproducible-research/scipy-tutorial-2014
import sys import subprocess return_value = 0 required_packages = ['numpy', 'scipy', 'matplotlib', 'SimpleITK'] for package in required_packages: print('Importing ' + package + ' ...') try: __import__(package, globals(), locals(), [], 0) except ImportError: print('Error: could not import ' + package) return_value += 1 + print('') - required_executables = ['git', 'dexy', 'ipython', 'nosetests'] + required_executables = ['git', 'dexy', 'ipython', 'nosetests', 'ffmpeg'] for executable in required_executables: print('Executing ' + executable + ' ...') try: - output = subprocess.check_output([executable, '--help']) + output = subprocess.check_output([executable, '--help'], + stderr=subprocess.STDOUT) except OSError: print('Error: could not execute ' + executable) return_value += 1 if return_value is 0: print('\nSuccess.') else: - print('\nAn error was found in your environment, please see the messages ' + + print('\nAn defect was found in your environment, please see the messages ' + 'above.') sys.exit(return_value)
Add ffmpeg to the required environment.
## Code Before: import sys import subprocess return_value = 0 required_packages = ['numpy', 'scipy', 'matplotlib', 'SimpleITK'] for package in required_packages: print('Importing ' + package + ' ...') try: __import__(package, globals(), locals(), [], 0) except ImportError: print('Error: could not import ' + package) return_value += 1 required_executables = ['git', 'dexy', 'ipython', 'nosetests'] for executable in required_executables: print('Executing ' + executable + ' ...') try: output = subprocess.check_output([executable, '--help']) except OSError: print('Error: could not execute ' + executable) return_value += 1 if return_value is 0: print('\nSuccess.') else: print('\nAn error was found in your environment, please see the messages ' + 'above.') sys.exit(return_value) ## Instruction: Add ffmpeg to the required environment. ## Code After: import sys import subprocess return_value = 0 required_packages = ['numpy', 'scipy', 'matplotlib', 'SimpleITK'] for package in required_packages: print('Importing ' + package + ' ...') try: __import__(package, globals(), locals(), [], 0) except ImportError: print('Error: could not import ' + package) return_value += 1 print('') required_executables = ['git', 'dexy', 'ipython', 'nosetests', 'ffmpeg'] for executable in required_executables: print('Executing ' + executable + ' ...') try: output = subprocess.check_output([executable, '--help'], stderr=subprocess.STDOUT) except OSError: print('Error: could not execute ' + executable) return_value += 1 if return_value is 0: print('\nSuccess.') else: print('\nAn defect was found in your environment, please see the messages ' + 'above.') sys.exit(return_value)
// ... existing code ... print('') required_executables = ['git', 'dexy', 'ipython', 'nosetests', 'ffmpeg'] for executable in required_executables: // ... modified code ... try: output = subprocess.check_output([executable, '--help'], stderr=subprocess.STDOUT) except OSError: ... else: print('\nAn defect was found in your environment, please see the messages ' + 'above.') // ... rest of the code ...
76ae7716090fde2dfad03de1635082644ac8fbb4
account_wallet_sale/hooks.py
account_wallet_sale/hooks.py
from odoo import api, SUPERUSER_ID from openupgradelib import openupgrade def _rename_cagnotte(env): columns = { "sale_order_line": [ ("account_cagnotte_id", "account_wallet_id"), ], } openupgrade.rename_columns(env.cr, columns) def pre_init_hook(cr): with api.Environment.manage(): env = api.Environment(cr, SUPERUSER_ID, {}) _rename_cagnotte(env)
from odoo import api, SUPERUSER_ID from openupgradelib import openupgrade def _rename_cagnotte(env): if not openupgrade.column_exists( env.cr, "sale_order_line", "account_cagnotte_id"): return columns = { "sale_order_line": [ ("account_cagnotte_id", "account_wallet_id"), ], } openupgrade.rename_columns(env.cr, columns) def pre_init_hook(cr): with api.Environment.manage(): env = api.Environment(cr, SUPERUSER_ID, {}) _rename_cagnotte(env)
Migrate only if former column exist
[14.0][IMP] account_wallet_sale: Migrate only if former column exist
Python
agpl-3.0
acsone/acsone-addons,acsone/acsone-addons,acsone/acsone-addons
from odoo import api, SUPERUSER_ID from openupgradelib import openupgrade def _rename_cagnotte(env): + if not openupgrade.column_exists( + env.cr, "sale_order_line", "account_cagnotte_id"): + return columns = { "sale_order_line": [ ("account_cagnotte_id", "account_wallet_id"), ], } openupgrade.rename_columns(env.cr, columns) def pre_init_hook(cr): with api.Environment.manage(): env = api.Environment(cr, SUPERUSER_ID, {}) _rename_cagnotte(env)
Migrate only if former column exist
## Code Before: from odoo import api, SUPERUSER_ID from openupgradelib import openupgrade def _rename_cagnotte(env): columns = { "sale_order_line": [ ("account_cagnotte_id", "account_wallet_id"), ], } openupgrade.rename_columns(env.cr, columns) def pre_init_hook(cr): with api.Environment.manage(): env = api.Environment(cr, SUPERUSER_ID, {}) _rename_cagnotte(env) ## Instruction: Migrate only if former column exist ## Code After: from odoo import api, SUPERUSER_ID from openupgradelib import openupgrade def _rename_cagnotte(env): if not openupgrade.column_exists( env.cr, "sale_order_line", "account_cagnotte_id"): return columns = { "sale_order_line": [ ("account_cagnotte_id", "account_wallet_id"), ], } openupgrade.rename_columns(env.cr, columns) def pre_init_hook(cr): with api.Environment.manage(): env = api.Environment(cr, SUPERUSER_ID, {}) _rename_cagnotte(env)
// ... existing code ... def _rename_cagnotte(env): if not openupgrade.column_exists( env.cr, "sale_order_line", "account_cagnotte_id"): return columns = { // ... rest of the code ...
0f71f39a8634927b532c3f5b258720761f1d9c5c
mentorup/users/models.py
mentorup/users/models.py
from chosen import forms as chosenforms # Import the AbstractUser model from django.contrib.auth.models import AbstractUser # Import the basic Django ORM models and forms library from django.db import models from django import forms # Import tags for searching from taggit.models import Tag from taggit.models import TagBase from taggit.managers import TaggableManager from django.utils.translation import ugettext_lazy as _ # Create seperate classes for each tag type that will be a foreign key reference from User class TeachSkills(models.Model): skills = TaggableManager() class LearnSkills(models.Model): skills = TaggableManager() # Subclass AbstractUser class User(AbstractUser): def __unicode__(self): return self.username teach = models.ForeignKey(TeachSkills, null=True) learn = models.ForeignKey(LearnSkills, null=True) short_bio = models.TextField() location = models.CharField(max_length=50)
from chosen import forms as chosenforms # Import the AbstractUser model from django.contrib.auth.models import AbstractUser # Import the basic Django ORM models and forms library from django.db import models from django import forms # Import tags for searching from taggit.models import Tag from taggit.models import TagBase from taggit.managers import TaggableManager from django.utils.translation import ugettext_lazy as _ # Create seperate classes for each tag type that will be a foreign key reference from User class TeachSkills(models.Model): skills = TaggableManager() class LearnSkills(models.Model): skills = TaggableManager() class UserManager(models.Manager): def create(self, name): new_user = Food() new_user.name = name new_user.teach = TeachSkills() new_user.teach.save() new_user.learn = LearnSkills() new_user.learn.save() new_user.save() return new_user # Subclass AbstractUser class User(AbstractUser): def __unicode__(self): return self.username objects = UserManager() teach = models.ForeignKey(TeachSkills, null=True) learn = models.ForeignKey(LearnSkills, null=True) short_bio = models.TextField() location = models.CharField(max_length=50)
Create UserManager to ensure ForeignKey relation is saved and associated with User upon creation
Create UserManager to ensure ForeignKey relation is saved and associated with User upon creation
Python
bsd-3-clause
briandant/mentor_up,briandant/mentor_up,briandant/mentor_up,briandant/mentor_up
from chosen import forms as chosenforms # Import the AbstractUser model from django.contrib.auth.models import AbstractUser # Import the basic Django ORM models and forms library from django.db import models from django import forms # Import tags for searching from taggit.models import Tag from taggit.models import TagBase from taggit.managers import TaggableManager from django.utils.translation import ugettext_lazy as _ # Create seperate classes for each tag type that will be a foreign key reference from User class TeachSkills(models.Model): skills = TaggableManager() class LearnSkills(models.Model): skills = TaggableManager() + class UserManager(models.Manager): + def create(self, name): + new_user = Food() + new_user.name = name + new_user.teach = TeachSkills() + new_user.teach.save() + new_user.learn = LearnSkills() + new_user.learn.save() + new_user.save() + return new_user + # Subclass AbstractUser class User(AbstractUser): def __unicode__(self): return self.username - + + objects = UserManager() teach = models.ForeignKey(TeachSkills, null=True) learn = models.ForeignKey(LearnSkills, null=True) short_bio = models.TextField() location = models.CharField(max_length=50)
Create UserManager to ensure ForeignKey relation is saved and associated with User upon creation
## Code Before: from chosen import forms as chosenforms # Import the AbstractUser model from django.contrib.auth.models import AbstractUser # Import the basic Django ORM models and forms library from django.db import models from django import forms # Import tags for searching from taggit.models import Tag from taggit.models import TagBase from taggit.managers import TaggableManager from django.utils.translation import ugettext_lazy as _ # Create seperate classes for each tag type that will be a foreign key reference from User class TeachSkills(models.Model): skills = TaggableManager() class LearnSkills(models.Model): skills = TaggableManager() # Subclass AbstractUser class User(AbstractUser): def __unicode__(self): return self.username teach = models.ForeignKey(TeachSkills, null=True) learn = models.ForeignKey(LearnSkills, null=True) short_bio = models.TextField() location = models.CharField(max_length=50) ## Instruction: Create UserManager to ensure ForeignKey relation is saved and associated with User upon creation ## Code After: from chosen import forms as chosenforms # Import the AbstractUser model from django.contrib.auth.models import AbstractUser # Import the basic Django ORM models and forms library from django.db import models from django import forms # Import tags for searching from taggit.models import Tag from taggit.models import TagBase from taggit.managers import TaggableManager from django.utils.translation import ugettext_lazy as _ # Create seperate classes for each tag type that will be a foreign key reference from User class TeachSkills(models.Model): skills = TaggableManager() class LearnSkills(models.Model): skills = TaggableManager() class UserManager(models.Manager): def create(self, name): new_user = Food() new_user.name = name new_user.teach = TeachSkills() new_user.teach.save() new_user.learn = LearnSkills() new_user.learn.save() new_user.save() return new_user # Subclass AbstractUser class User(AbstractUser): def __unicode__(self): return self.username objects = UserManager() teach = models.ForeignKey(TeachSkills, null=True) learn = models.ForeignKey(LearnSkills, null=True) short_bio = models.TextField() location = models.CharField(max_length=50)
... class UserManager(models.Manager): def create(self, name): new_user = Food() new_user.name = name new_user.teach = TeachSkills() new_user.teach.save() new_user.learn = LearnSkills() new_user.learn.save() new_user.save() return new_user # Subclass AbstractUser ... return self.username objects = UserManager() teach = models.ForeignKey(TeachSkills, null=True) ...
79d1ab43d187d8ba1350965673b930fa0b3879b6
rosbridge_suite/rosbridge_library/src/rosbridge_library/internal/pngcompression.py
rosbridge_suite/rosbridge_library/src/rosbridge_library/internal/pngcompression.py
from pypng.code import png from base64 import standard_b64encode, standard_b64decode from StringIO import StringIO def encode(string): """ PNG-compress the string, return the b64 encoded bytes """ bytes = list(bytearray(string)) png_image = png.from_array([bytes], 'L') buff = StringIO() png_image.save(buff) encoded = standard_b64encode(buff.getvalue()) return encoded def decode(string): """ b64 decode the string, then PNG-decompress """ decoded = standard_b64decode(string) reader = png.Reader(bytes=decoded) width, height, rawpixels, metadata = reader.read() pixels = list(rawpixels)[0] return str(bytearray(pixels))
from pypng.code import png from PIL import Image from base64 import standard_b64encode, standard_b64decode from StringIO import StringIO def encode(string): """ PNG-compress the string, return the b64 encoded bytes """ i = Image.fromstring('L', (len(string), 1), string) buff = StringIO() i.save(buff, "png") encoded = standard_b64encode(buff.getvalue()) return encoded def decode(string): """ b64 decode the string, then PNG-decompress """ decoded = standard_b64decode(string) reader = png.Reader(bytes=decoded) width, height, rawpixels, metadata = reader.read() pixels = list(rawpixels)[0] return str(bytearray(pixels))
Use python imaging library to encode PNG instead of pypng
Use python imaging library to encode PNG instead of pypng
Python
bsd-3-clause
WangRobo/rosbridge_suite,vladrotea/rosbridge_suite,kbendick/rosbridge_suite,vladrotea/rosbridge_suite,RobotWebTools/rosbridge_suite,DLu/rosbridge_suite,SNU-Sigma/rosbridge_suite,DLu/rosbridge_suite,DLu/rosbridge_suite,mayfieldrobotics/rosbridge_suite,mayfieldrobotics/rosbridge_suite,WangRobo/rosbridge_suite,SNU-Sigma/rosbridge_suite,WangRobo/rosbridge_suite,kbendick/rosbridge_suite,SNU-Sigma/rosbridge_suite,kbendick/rosbridge_suite,SNU-Sigma/rosbridge_suite,vladrotea/rosbridge_suite,mayfieldrobotics/rosbridge_suite
from pypng.code import png + from PIL import Image from base64 import standard_b64encode, standard_b64decode from StringIO import StringIO def encode(string): """ PNG-compress the string, return the b64 encoded bytes """ + i = Image.fromstring('L', (len(string), 1), string) - bytes = list(bytearray(string)) - png_image = png.from_array([bytes], 'L') buff = StringIO() - png_image.save(buff) + i.save(buff, "png") encoded = standard_b64encode(buff.getvalue()) return encoded def decode(string): """ b64 decode the string, then PNG-decompress """ decoded = standard_b64decode(string) reader = png.Reader(bytes=decoded) width, height, rawpixels, metadata = reader.read() pixels = list(rawpixels)[0] return str(bytearray(pixels))
Use python imaging library to encode PNG instead of pypng
## Code Before: from pypng.code import png from base64 import standard_b64encode, standard_b64decode from StringIO import StringIO def encode(string): """ PNG-compress the string, return the b64 encoded bytes """ bytes = list(bytearray(string)) png_image = png.from_array([bytes], 'L') buff = StringIO() png_image.save(buff) encoded = standard_b64encode(buff.getvalue()) return encoded def decode(string): """ b64 decode the string, then PNG-decompress """ decoded = standard_b64decode(string) reader = png.Reader(bytes=decoded) width, height, rawpixels, metadata = reader.read() pixels = list(rawpixels)[0] return str(bytearray(pixels)) ## Instruction: Use python imaging library to encode PNG instead of pypng ## Code After: from pypng.code import png from PIL import Image from base64 import standard_b64encode, standard_b64decode from StringIO import StringIO def encode(string): """ PNG-compress the string, return the b64 encoded bytes """ i = Image.fromstring('L', (len(string), 1), string) buff = StringIO() i.save(buff, "png") encoded = standard_b64encode(buff.getvalue()) return encoded def decode(string): """ b64 decode the string, then PNG-decompress """ decoded = standard_b64decode(string) reader = png.Reader(bytes=decoded) width, height, rawpixels, metadata = reader.read() pixels = list(rawpixels)[0] return str(bytearray(pixels))
... from pypng.code import png from PIL import Image from base64 import standard_b64encode, standard_b64decode ... """ PNG-compress the string, return the b64 encoded bytes """ i = Image.fromstring('L', (len(string), 1), string) buff = StringIO() i.save(buff, "png") encoded = standard_b64encode(buff.getvalue()) ...
1b103d314e94e3c1dba9d9d08a2655c62f26d18c
ibmcnx/doc/DataSources.py
ibmcnx/doc/DataSources.py
import ibmcnx.functions dbs = AdminConfig.list( 'DataSource', AdminControl.getCell()) for db in dbs: t1 = ibmcnx.functions.getDSId( db ) AdminConfig.list( t1 )
import ibmcnx.functions cell = '/' + AdminControl.getCell() + '/' dbs = AdminConfig.list( 'DataSource', cell ) for db in dbs: t1 = ibmcnx.functions.getDSId( db ) AdminConfig.list( t1 )
Create script to save documentation to a file
4: Create script to save documentation to a file Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/4
Python
apache-2.0
stoeps13/ibmcnx2,stoeps13/ibmcnx2
import ibmcnx.functions + cell = '/' + AdminControl.getCell() + '/' - dbs = AdminConfig.list( 'DataSource', AdminControl.getCell()) + dbs = AdminConfig.list( 'DataSource', cell ) for db in dbs: t1 = ibmcnx.functions.getDSId( db ) AdminConfig.list( t1 )
Create script to save documentation to a file
## Code Before: import ibmcnx.functions dbs = AdminConfig.list( 'DataSource', AdminControl.getCell()) for db in dbs: t1 = ibmcnx.functions.getDSId( db ) AdminConfig.list( t1 ) ## Instruction: Create script to save documentation to a file ## Code After: import ibmcnx.functions cell = '/' + AdminControl.getCell() + '/' dbs = AdminConfig.list( 'DataSource', cell ) for db in dbs: t1 = ibmcnx.functions.getDSId( db ) AdminConfig.list( t1 )
# ... existing code ... cell = '/' + AdminControl.getCell() + '/' dbs = AdminConfig.list( 'DataSource', cell ) # ... rest of the code ...
e9fe645af28bd93a6ee2b38184254c8295b70d3d
sn.py
sn.py
import tables as tb hdf5_filename = 'hdf5/sn_data.h5' class SN(object): """A supernova is the explosion that ends the life of a star The SN needs to be conatained within the HDF5 database before it is used by SNoBoL. Once there, simply create a supernova by calling the constructor with the name of the SN as a string of the form "sn[YEAR][Letter(s)]" For example: sn1987A = SN('sn1987a') sn1999em = SN('sn1999em') Attributes ---------- name : Name of the supernova, "SN" followed by the year of first observation along with a letter designating the order of observation in that year. "SN1987A" was the first SN observed in 1987. "SN2000cb" was the eightieth SN observed in 2000. """ def __init__(self, name): """Initializes the SN with supplied value for [name]""" self.name = name # Load SN data from HDF5 file self.read_hdf5() def read_hdf5(self): h5file = tb.open_file(hdf5_filename) # Check that the desired SN is in the HDF5 file if self.name in h5file.list_nodes('/sn')._v_name: print "Yay!" else: print "Boo!"
import tables as tb hdf5_filename = 'hdf5/sn_data.h5' class SN(object): """A supernova is the explosion that ends the life of a star The SN needs to be conatained within the HDF5 database before it is used by SNoBoL. Once there, simply create a supernova by calling the constructor with the name of the SN as a string of the form "sn[YEAR][Letter(s)]" For example: sn1987A = SN('sn1987a') sn1999em = SN('sn1999em') Attributes ---------- name : Name of the supernova, "SN" followed by the year of first observation along with a letter designating the order of observation in that year. "SN1987A" was the first SN observed in 1987. "SN2000cb" was the eightieth SN observed in 2000. """ def __init__(self, name): """Initializes the SN with supplied value for [name]""" self.name = name # Load SN data from HDF5 file self.read_hdf5() def read_hdf5(self): h5file = tb.open_file(hdf5_filename) # Get the desired node from the HDF5 file sn_node = h5file.get_node('/sn', self.name)
Add method to check for the SN in the HDF5 file
Add method to check for the SN in the HDF5 file
Python
mit
JALusk/SuperBoL,JALusk/SNoBoL,JALusk/SNoBoL
import tables as tb hdf5_filename = 'hdf5/sn_data.h5' class SN(object): """A supernova is the explosion that ends the life of a star The SN needs to be conatained within the HDF5 database before it is used by SNoBoL. Once there, simply create a supernova by calling the constructor with the name of the SN as a string of the form "sn[YEAR][Letter(s)]" For example: sn1987A = SN('sn1987a') sn1999em = SN('sn1999em') Attributes ---------- name : Name of the supernova, "SN" followed by the year of first observation along with a letter designating the order of observation in that year. "SN1987A" was the first SN observed in 1987. "SN2000cb" was the eightieth SN observed in 2000. """ def __init__(self, name): """Initializes the SN with supplied value for [name]""" self.name = name # Load SN data from HDF5 file self.read_hdf5() def read_hdf5(self): h5file = tb.open_file(hdf5_filename) - # Check that the desired SN is in the HDF5 file + # Get the desired node from the HDF5 file + sn_node = h5file.get_node('/sn', self.name) - if self.name in h5file.list_nodes('/sn')._v_name: - print "Yay!" - else: - print "Boo!"
Add method to check for the SN in the HDF5 file
## Code Before: import tables as tb hdf5_filename = 'hdf5/sn_data.h5' class SN(object): """A supernova is the explosion that ends the life of a star The SN needs to be conatained within the HDF5 database before it is used by SNoBoL. Once there, simply create a supernova by calling the constructor with the name of the SN as a string of the form "sn[YEAR][Letter(s)]" For example: sn1987A = SN('sn1987a') sn1999em = SN('sn1999em') Attributes ---------- name : Name of the supernova, "SN" followed by the year of first observation along with a letter designating the order of observation in that year. "SN1987A" was the first SN observed in 1987. "SN2000cb" was the eightieth SN observed in 2000. """ def __init__(self, name): """Initializes the SN with supplied value for [name]""" self.name = name # Load SN data from HDF5 file self.read_hdf5() def read_hdf5(self): h5file = tb.open_file(hdf5_filename) # Check that the desired SN is in the HDF5 file if self.name in h5file.list_nodes('/sn')._v_name: print "Yay!" else: print "Boo!" ## Instruction: Add method to check for the SN in the HDF5 file ## Code After: import tables as tb hdf5_filename = 'hdf5/sn_data.h5' class SN(object): """A supernova is the explosion that ends the life of a star The SN needs to be conatained within the HDF5 database before it is used by SNoBoL. Once there, simply create a supernova by calling the constructor with the name of the SN as a string of the form "sn[YEAR][Letter(s)]" For example: sn1987A = SN('sn1987a') sn1999em = SN('sn1999em') Attributes ---------- name : Name of the supernova, "SN" followed by the year of first observation along with a letter designating the order of observation in that year. "SN1987A" was the first SN observed in 1987. "SN2000cb" was the eightieth SN observed in 2000. """ def __init__(self, name): """Initializes the SN with supplied value for [name]""" self.name = name # Load SN data from HDF5 file self.read_hdf5() def read_hdf5(self): h5file = tb.open_file(hdf5_filename) # Get the desired node from the HDF5 file sn_node = h5file.get_node('/sn', self.name)
# ... existing code ... # Get the desired node from the HDF5 file sn_node = h5file.get_node('/sn', self.name) # ... rest of the code ...
418357ead146a98f2318af6c76323e2705b79cec
cvloop/__init__.py
cvloop/__init__.py
"""Provides cvloop, a ready to use OpenCV VideoCapture mapper, designed for jupyter notebooks.""" import sys OPENCV_FOUND = False OPENCV_VERSION_COMPATIBLE = False try: import cv2 OPENCV_FOUND = True except Exception as e: # print ("Error:", e) print('OpenCV is not found (tried importing cv2).', file=sys.stderr) print(''' Is OpenCV installed and properly added to your path? you are using a virtual environment, make sure to add the path to the OpenCV bindings to the environment\'s site-packages. For example (MacOSX with brew): echo /usr/local/Cellar/opencv3/HEAD-8d662a1_4/lib/python3.6/site-packages > ./.venv/lib/python3.6/site-packages/opencv.pth Make sure that the first path contains your cv2.so! See https://docs.python.org/3/library/site.html ''') if OPENCV_FOUND: MAJOR, MINOR, PATCH = cv2.__version__.split('.') OPENCV_VERSION_COMPATIBLE = int(MAJOR) >= 3 and int(MINOR) >= 1 if not OPENCV_VERSION_COMPATIBLE: print('OpenCV version {} is lower than 3.1!'.format(cv2.__version__), file=sys.stderr) if OPENCV_FOUND and OPENCV_VERSION_COMPATIBLE: from .cvloop import cvloop from .functions import *
"""Provides cvloop, a ready to use OpenCV VideoCapture mapper, designed for jupyter notebooks.""" import sys OPENCV_FOUND = False OPENCV_VERSION_COMPATIBLE = False try: import cv2 OPENCV_FOUND = True except ModuleNotFoundError: print('OpenCV is not found (tried importing cv2).', file=sys.stderr) print(''' Is OpenCV installed and properly added to your path? you are using a virtual environment, make sure to add the path to the OpenCV bindings to the environment\'s site-packages. For example (MacOSX with brew): echo /usr/local/Cellar/opencv3/HEAD-8d662a1_4/lib/python3.6/site-packages > ./.venv/lib/python3.6/site-packages/opencv.pth Make sure that the first path contains your cv2.so! See https://docs.python.org/3/library/site.html ''') if OPENCV_FOUND: MAJOR, MINOR, PATCH = cv2.__version__.split('.') OPENCV_VERSION_COMPATIBLE = int(MAJOR) >= 3 and int(MINOR) >= 1 if not OPENCV_VERSION_COMPATIBLE: print('OpenCV version {} is lower than 3.1!'.format(cv2.__version__), file=sys.stderr) if OPENCV_FOUND and OPENCV_VERSION_COMPATIBLE: from .cvloop import cvloop from .functions import *
Revert unnecessary change to original
Revert unnecessary change to original
Python
mit
shoeffner/cvloop
"""Provides cvloop, a ready to use OpenCV VideoCapture mapper, designed for jupyter notebooks.""" import sys OPENCV_FOUND = False OPENCV_VERSION_COMPATIBLE = False try: import cv2 OPENCV_FOUND = True + except ModuleNotFoundError: - except Exception as e: - # print ("Error:", e) print('OpenCV is not found (tried importing cv2).', file=sys.stderr) print(''' Is OpenCV installed and properly added to your path? you are using a virtual environment, make sure to add the path to the OpenCV bindings to the environment\'s site-packages. For example (MacOSX with brew): echo /usr/local/Cellar/opencv3/HEAD-8d662a1_4/lib/python3.6/site-packages > ./.venv/lib/python3.6/site-packages/opencv.pth Make sure that the first path contains your cv2.so! See https://docs.python.org/3/library/site.html ''') if OPENCV_FOUND: MAJOR, MINOR, PATCH = cv2.__version__.split('.') OPENCV_VERSION_COMPATIBLE = int(MAJOR) >= 3 and int(MINOR) >= 1 if not OPENCV_VERSION_COMPATIBLE: print('OpenCV version {} is lower than 3.1!'.format(cv2.__version__), file=sys.stderr) if OPENCV_FOUND and OPENCV_VERSION_COMPATIBLE: from .cvloop import cvloop from .functions import *
Revert unnecessary change to original
## Code Before: """Provides cvloop, a ready to use OpenCV VideoCapture mapper, designed for jupyter notebooks.""" import sys OPENCV_FOUND = False OPENCV_VERSION_COMPATIBLE = False try: import cv2 OPENCV_FOUND = True except Exception as e: # print ("Error:", e) print('OpenCV is not found (tried importing cv2).', file=sys.stderr) print(''' Is OpenCV installed and properly added to your path? you are using a virtual environment, make sure to add the path to the OpenCV bindings to the environment\'s site-packages. For example (MacOSX with brew): echo /usr/local/Cellar/opencv3/HEAD-8d662a1_4/lib/python3.6/site-packages > ./.venv/lib/python3.6/site-packages/opencv.pth Make sure that the first path contains your cv2.so! See https://docs.python.org/3/library/site.html ''') if OPENCV_FOUND: MAJOR, MINOR, PATCH = cv2.__version__.split('.') OPENCV_VERSION_COMPATIBLE = int(MAJOR) >= 3 and int(MINOR) >= 1 if not OPENCV_VERSION_COMPATIBLE: print('OpenCV version {} is lower than 3.1!'.format(cv2.__version__), file=sys.stderr) if OPENCV_FOUND and OPENCV_VERSION_COMPATIBLE: from .cvloop import cvloop from .functions import * ## Instruction: Revert unnecessary change to original ## Code After: """Provides cvloop, a ready to use OpenCV VideoCapture mapper, designed for jupyter notebooks.""" import sys OPENCV_FOUND = False OPENCV_VERSION_COMPATIBLE = False try: import cv2 OPENCV_FOUND = True except ModuleNotFoundError: print('OpenCV is not found (tried importing cv2).', file=sys.stderr) print(''' Is OpenCV installed and properly added to your path? you are using a virtual environment, make sure to add the path to the OpenCV bindings to the environment\'s site-packages. For example (MacOSX with brew): echo /usr/local/Cellar/opencv3/HEAD-8d662a1_4/lib/python3.6/site-packages > ./.venv/lib/python3.6/site-packages/opencv.pth Make sure that the first path contains your cv2.so! See https://docs.python.org/3/library/site.html ''') if OPENCV_FOUND: MAJOR, MINOR, PATCH = cv2.__version__.split('.') OPENCV_VERSION_COMPATIBLE = int(MAJOR) >= 3 and int(MINOR) >= 1 if not OPENCV_VERSION_COMPATIBLE: print('OpenCV version {} is lower than 3.1!'.format(cv2.__version__), file=sys.stderr) if OPENCV_FOUND and OPENCV_VERSION_COMPATIBLE: from .cvloop import cvloop from .functions import *
... OPENCV_FOUND = True except ModuleNotFoundError: print('OpenCV is not found (tried importing cv2).', file=sys.stderr) ...
32d4ea22c1bca4a96a8d826f0225dfee2a4c21d2
django_tenants/tests/__init__.py
django_tenants/tests/__init__.py
from .test_routes import * from .test_tenants import * from .test_cache import *
from .files import * from .staticfiles import * from .template import * from .test_routes import * from .test_tenants import * from .test_cache import *
Include static file-related tests in 'test' package.
fix(tests): Include static file-related tests in 'test' package.
Python
mit
tomturner/django-tenants,tomturner/django-tenants,tomturner/django-tenants
+ from .files import * + from .staticfiles import * + from .template import * from .test_routes import * from .test_tenants import * from .test_cache import *
Include static file-related tests in 'test' package.
## Code Before: from .test_routes import * from .test_tenants import * from .test_cache import * ## Instruction: Include static file-related tests in 'test' package. ## Code After: from .files import * from .staticfiles import * from .template import * from .test_routes import * from .test_tenants import * from .test_cache import *
# ... existing code ... from .files import * from .staticfiles import * from .template import * from .test_routes import * # ... rest of the code ...
1090ecf891dd7c0928cdaae385464d3be660fdbf
penn/base.py
penn/base.py
from requests import get class WrapperBase(object): def __init__(self, bearer, token): self.bearer = bearer self.token = token @property def headers(self): """The HTTP headers needed for signed requests""" return { "Authorization-Bearer": self.bearer, "Authorization-Token": self.token, } def _request(self, url, params=None): """Make a signed request to the API, raise any API errors, and returning a tuple of (data, metadata)""" response = get(url, params=params, headers=self.headers).json() if response['service_meta']['error_text']: raise ValueError(response['service_meta']['error_text']) return response
from requests import get class WrapperBase(object): def __init__(self, bearer, token): self.bearer = bearer self.token = token @property def headers(self): """The HTTP headers needed for signed requests""" return { "Authorization-Bearer": self.bearer, "Authorization-Token": self.token, } def _request(self, url, params=None): """Make a signed request to the API, raise any API errors, and returning a tuple of (data, metadata)""" response = get(url, params=params, headers=self.headers) if response.status_code != 200: raise ValueError('Request to {} returned {}'.format(response.url, response.status_code)) response = response.json() if response['service_meta']['error_text']: raise ValueError(response['service_meta']['error_text']) return response
Add better error handling for non-200 responses
Add better error handling for non-200 responses
Python
mit
pennlabs/penn-sdk-python,pennlabs/penn-sdk-python
from requests import get class WrapperBase(object): def __init__(self, bearer, token): self.bearer = bearer self.token = token @property def headers(self): """The HTTP headers needed for signed requests""" return { "Authorization-Bearer": self.bearer, "Authorization-Token": self.token, } def _request(self, url, params=None): """Make a signed request to the API, raise any API errors, and returning a tuple of (data, metadata)""" - response = get(url, params=params, headers=self.headers).json() + response = get(url, params=params, headers=self.headers) + if response.status_code != 200: + raise ValueError('Request to {} returned {}'.format(response.url, response.status_code)) + + response = response.json() if response['service_meta']['error_text']: raise ValueError(response['service_meta']['error_text']) return response
Add better error handling for non-200 responses
## Code Before: from requests import get class WrapperBase(object): def __init__(self, bearer, token): self.bearer = bearer self.token = token @property def headers(self): """The HTTP headers needed for signed requests""" return { "Authorization-Bearer": self.bearer, "Authorization-Token": self.token, } def _request(self, url, params=None): """Make a signed request to the API, raise any API errors, and returning a tuple of (data, metadata)""" response = get(url, params=params, headers=self.headers).json() if response['service_meta']['error_text']: raise ValueError(response['service_meta']['error_text']) return response ## Instruction: Add better error handling for non-200 responses ## Code After: from requests import get class WrapperBase(object): def __init__(self, bearer, token): self.bearer = bearer self.token = token @property def headers(self): """The HTTP headers needed for signed requests""" return { "Authorization-Bearer": self.bearer, "Authorization-Token": self.token, } def _request(self, url, params=None): """Make a signed request to the API, raise any API errors, and returning a tuple of (data, metadata)""" response = get(url, params=params, headers=self.headers) if response.status_code != 200: raise ValueError('Request to {} returned {}'.format(response.url, response.status_code)) response = response.json() if response['service_meta']['error_text']: raise ValueError(response['service_meta']['error_text']) return response
# ... existing code ... of (data, metadata)""" response = get(url, params=params, headers=self.headers) if response.status_code != 200: raise ValueError('Request to {} returned {}'.format(response.url, response.status_code)) response = response.json() # ... rest of the code ...
df03a2d9543b392fb9ea9c027b93f4ed736e6788
pyked/_version.py
pyked/_version.py
__version_info__ = (0, 1, 1) __version__ = '.'.join(map(str, __version_info__))
__version_info__ = (0, 1, 1, 'a1') __version__ = '.'.join(map(str, __version_info__[:3])) if len(__version_info__) == 4: __version__ += __version_info__[-1]
Allow alpha versions in the versioning string
Allow alpha versions in the versioning string
Python
bsd-3-clause
bryanwweber/PyKED,pr-omethe-us/PyKED
- __version_info__ = (0, 1, 1) + __version_info__ = (0, 1, 1, 'a1') - __version__ = '.'.join(map(str, __version_info__)) + __version__ = '.'.join(map(str, __version_info__[:3])) + if len(__version_info__) == 4: + __version__ += __version_info__[-1]
Allow alpha versions in the versioning string
## Code Before: __version_info__ = (0, 1, 1) __version__ = '.'.join(map(str, __version_info__)) ## Instruction: Allow alpha versions in the versioning string ## Code After: __version_info__ = (0, 1, 1, 'a1') __version__ = '.'.join(map(str, __version_info__[:3])) if len(__version_info__) == 4: __version__ += __version_info__[-1]
... __version_info__ = (0, 1, 1, 'a1') __version__ = '.'.join(map(str, __version_info__[:3])) if len(__version_info__) == 4: __version__ += __version_info__[-1] ...
8c75327dfc6f6d6bc3097813db9dc4ae0e46489a
private_storage/permissions.py
private_storage/permissions.py
def allow_authenticated(private_file): try: return private_file.request.user.is_authenticated() except AttributeError: # Using user.is_authenticated() and user.is_anonymous() as a method is deprecated since Django 2.0 return private_file.request.user.is_authenticated def allow_staff(private_file): request = private_file.request try: return request.user.is_authenticated() and request.user.is_staff except AttributeError: # Using user.is_authenticated() and user.is_anonymous() as a method is deprecated since Django 2.0 return request.user.is_authenticated and request.user.is_staff def allow_superuser(private_file): request = private_file.request try: return request.user.is_authenticated() and request.user.is_superuser except AttributeError: # Using user.is_authenticated() and user.is_anonymous() as a method is deprecated since Django 2.0 return request.user.is_authenticated and request.user.is_superuser
import django if django.VERSION >= (1, 10): def allow_authenticated(private_file): return private_file.request.user.is_authenticated def allow_staff(private_file): request = private_file.request return request.user.is_authenticated and request.user.is_staff def allow_superuser(private_file): request = private_file.request return request.user.is_authenticated and request.user.is_superuser else: def allow_authenticated(private_file): return private_file.request.user.is_authenticated() def allow_staff(private_file): request = private_file.request return request.user.is_authenticated() and request.user.is_staff def allow_superuser(private_file): request = private_file.request return request.user.is_authenticated() and request.user.is_superuser
Change the permission checks, provide distinct versions for Django 1.10+
Change the permission checks, provide distinct versions for Django 1.10+
Python
apache-2.0
edoburu/django-private-storage
+ import django + if django.VERSION >= (1, 10): + def allow_authenticated(private_file): + return private_file.request.user.is_authenticated - def allow_authenticated(private_file): - try: - return private_file.request.user.is_authenticated() - except AttributeError: - # Using user.is_authenticated() and user.is_anonymous() as a method is deprecated since Django 2.0 - return private_file.request.user.is_authenticated - - - def allow_staff(private_file): + def allow_staff(private_file): - request = private_file.request + request = private_file.request - try: - return request.user.is_authenticated() and request.user.is_staff - except AttributeError: - # Using user.is_authenticated() and user.is_anonymous() as a method is deprecated since Django 2.0 return request.user.is_authenticated and request.user.is_staff + def allow_superuser(private_file): + request = private_file.request + return request.user.is_authenticated and request.user.is_superuser + else: + def allow_authenticated(private_file): + return private_file.request.user.is_authenticated() - def allow_superuser(private_file): + def allow_staff(private_file): - request = private_file.request + request = private_file.request - try: + return request.user.is_authenticated() and request.user.is_staff + + def allow_superuser(private_file): + request = private_file.request return request.user.is_authenticated() and request.user.is_superuser - except AttributeError: - # Using user.is_authenticated() and user.is_anonymous() as a method is deprecated since Django 2.0 - return request.user.is_authenticated and request.user.is_superuser
Change the permission checks, provide distinct versions for Django 1.10+
## Code Before: def allow_authenticated(private_file): try: return private_file.request.user.is_authenticated() except AttributeError: # Using user.is_authenticated() and user.is_anonymous() as a method is deprecated since Django 2.0 return private_file.request.user.is_authenticated def allow_staff(private_file): request = private_file.request try: return request.user.is_authenticated() and request.user.is_staff except AttributeError: # Using user.is_authenticated() and user.is_anonymous() as a method is deprecated since Django 2.0 return request.user.is_authenticated and request.user.is_staff def allow_superuser(private_file): request = private_file.request try: return request.user.is_authenticated() and request.user.is_superuser except AttributeError: # Using user.is_authenticated() and user.is_anonymous() as a method is deprecated since Django 2.0 return request.user.is_authenticated and request.user.is_superuser ## Instruction: Change the permission checks, provide distinct versions for Django 1.10+ ## Code After: import django if django.VERSION >= (1, 10): def allow_authenticated(private_file): return private_file.request.user.is_authenticated def allow_staff(private_file): request = private_file.request return request.user.is_authenticated and request.user.is_staff def allow_superuser(private_file): request = private_file.request return request.user.is_authenticated and request.user.is_superuser else: def allow_authenticated(private_file): return private_file.request.user.is_authenticated() def allow_staff(private_file): request = private_file.request return request.user.is_authenticated() and request.user.is_staff def allow_superuser(private_file): request = private_file.request return request.user.is_authenticated() and request.user.is_superuser
// ... existing code ... import django if django.VERSION >= (1, 10): def allow_authenticated(private_file): return private_file.request.user.is_authenticated def allow_staff(private_file): request = private_file.request return request.user.is_authenticated and request.user.is_staff // ... modified code ... def allow_superuser(private_file): request = private_file.request return request.user.is_authenticated and request.user.is_superuser else: def allow_authenticated(private_file): return private_file.request.user.is_authenticated() def allow_staff(private_file): request = private_file.request return request.user.is_authenticated() and request.user.is_staff def allow_superuser(private_file): request = private_file.request return request.user.is_authenticated() and request.user.is_superuser // ... rest of the code ...
4467ffe669eec09bab16f4e5a3256ed333c5d3d5
rcamp/lib/ldap_utils.py
rcamp/lib/ldap_utils.py
from django.conf import settings from ldapdb import escape_ldap_filter import ldap def authenticate(dn,pwd,ldap_conf_key): # Setup connection ldap_conf = settings.LDAPCONFS[ldap_conf_key] server = ldap_conf['server'] ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW) conn = ldap.initialize(server) # Authenticate try: conn.simple_bind_s(dn, pwd) return True except ldap.INVALID_CREDENTIALS: return False def get_suffixed_username(username,organization): try: suffix = settings.ORGANIZATION_INFO[organization]['suffix'] except KeyError: suffix = None suffixed_username = username if suffix: suffixed_username = '{0}@{1}'.format(username,suffix) return suffixed_username def get_ldap_username_and_org(suffixed_username): username = suffixed_username org = 'ucb' if '@' in suffixed_username: username, suffix = suffixed_username.rsplit('@',1) for k,v in settings.ORGANIZATION_INFO.iteritems(): if v['suffix'] == suffix: org = k break return username, org
from django.conf import settings from ldapdb import escape_ldap_filter import ldap def authenticate(dn,pwd,ldap_conf_key): # Setup connection ldap_conf = settings.LDAPCONFS[ldap_conf_key] server = ldap_conf['server'] ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW) conn = ldap.initialize(server, bytes_mode=False) # Authenticate try: conn.simple_bind_s(dn, pwd) return True except ldap.INVALID_CREDENTIALS: return False def get_suffixed_username(username,organization): try: suffix = settings.ORGANIZATION_INFO[organization]['suffix'] except KeyError: suffix = None suffixed_username = username if suffix: suffixed_username = '{0}@{1}'.format(username,suffix) return suffixed_username def get_ldap_username_and_org(suffixed_username): username = suffixed_username org = 'ucb' if '@' in suffixed_username: username, suffix = suffixed_username.rsplit('@',1) for k,v in settings.ORGANIZATION_INFO.iteritems(): if v['suffix'] == suffix: org = k break return username, org
Set bytes_mode=False for future compatability with Python3
Set bytes_mode=False for future compatability with Python3
Python
mit
ResearchComputing/RCAMP,ResearchComputing/RCAMP,ResearchComputing/RCAMP,ResearchComputing/RCAMP
from django.conf import settings from ldapdb import escape_ldap_filter import ldap def authenticate(dn,pwd,ldap_conf_key): # Setup connection ldap_conf = settings.LDAPCONFS[ldap_conf_key] server = ldap_conf['server'] ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW) - conn = ldap.initialize(server) + conn = ldap.initialize(server, bytes_mode=False) # Authenticate try: conn.simple_bind_s(dn, pwd) return True except ldap.INVALID_CREDENTIALS: return False def get_suffixed_username(username,organization): try: suffix = settings.ORGANIZATION_INFO[organization]['suffix'] except KeyError: suffix = None suffixed_username = username if suffix: suffixed_username = '{0}@{1}'.format(username,suffix) return suffixed_username def get_ldap_username_and_org(suffixed_username): username = suffixed_username org = 'ucb' if '@' in suffixed_username: username, suffix = suffixed_username.rsplit('@',1) for k,v in settings.ORGANIZATION_INFO.iteritems(): if v['suffix'] == suffix: org = k break return username, org
Set bytes_mode=False for future compatability with Python3
## Code Before: from django.conf import settings from ldapdb import escape_ldap_filter import ldap def authenticate(dn,pwd,ldap_conf_key): # Setup connection ldap_conf = settings.LDAPCONFS[ldap_conf_key] server = ldap_conf['server'] ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW) conn = ldap.initialize(server) # Authenticate try: conn.simple_bind_s(dn, pwd) return True except ldap.INVALID_CREDENTIALS: return False def get_suffixed_username(username,organization): try: suffix = settings.ORGANIZATION_INFO[organization]['suffix'] except KeyError: suffix = None suffixed_username = username if suffix: suffixed_username = '{0}@{1}'.format(username,suffix) return suffixed_username def get_ldap_username_and_org(suffixed_username): username = suffixed_username org = 'ucb' if '@' in suffixed_username: username, suffix = suffixed_username.rsplit('@',1) for k,v in settings.ORGANIZATION_INFO.iteritems(): if v['suffix'] == suffix: org = k break return username, org ## Instruction: Set bytes_mode=False for future compatability with Python3 ## Code After: from django.conf import settings from ldapdb import escape_ldap_filter import ldap def authenticate(dn,pwd,ldap_conf_key): # Setup connection ldap_conf = settings.LDAPCONFS[ldap_conf_key] server = ldap_conf['server'] ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW) conn = ldap.initialize(server, bytes_mode=False) # Authenticate try: conn.simple_bind_s(dn, pwd) return True except ldap.INVALID_CREDENTIALS: return False def get_suffixed_username(username,organization): try: suffix = settings.ORGANIZATION_INFO[organization]['suffix'] except KeyError: suffix = None suffixed_username = username if suffix: suffixed_username = '{0}@{1}'.format(username,suffix) return suffixed_username def get_ldap_username_and_org(suffixed_username): username = suffixed_username org = 'ucb' if '@' in suffixed_username: username, suffix = suffixed_username.rsplit('@',1) for k,v in settings.ORGANIZATION_INFO.iteritems(): if v['suffix'] == suffix: org = k break return username, org
... ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW) conn = ldap.initialize(server, bytes_mode=False) # Authenticate ...
ef98ba0f2aa660b85a4116d46679bf30321f2a05
scipy/spatial/transform/__init__.py
scipy/spatial/transform/__init__.py
from __future__ import division, print_function, absolute_import from .rotation import Rotation, Slerp from ._rotation_spline import RotationSpline __all__ = ['Rotation', 'Slerp'] from scipy._lib._testutils import PytestTester test = PytestTester(__name__) del PytestTester
from __future__ import division, print_function, absolute_import from .rotation import Rotation, Slerp from ._rotation_spline import RotationSpline __all__ = ['Rotation', 'Slerp', 'RotationSpline'] from scipy._lib._testutils import PytestTester test = PytestTester(__name__) del PytestTester
Add RotationSpline into __all__ of spatial.transform
MAINT: Add RotationSpline into __all__ of spatial.transform
Python
bsd-3-clause
grlee77/scipy,pizzathief/scipy,endolith/scipy,Eric89GXL/scipy,gertingold/scipy,aeklant/scipy,anntzer/scipy,tylerjereddy/scipy,ilayn/scipy,scipy/scipy,matthew-brett/scipy,jor-/scipy,endolith/scipy,ilayn/scipy,person142/scipy,Eric89GXL/scipy,nmayorov/scipy,lhilt/scipy,arokem/scipy,endolith/scipy,ilayn/scipy,WarrenWeckesser/scipy,gertingold/scipy,e-q/scipy,vigna/scipy,arokem/scipy,perimosocordiae/scipy,Eric89GXL/scipy,jor-/scipy,zerothi/scipy,anntzer/scipy,lhilt/scipy,zerothi/scipy,jor-/scipy,anntzer/scipy,Stefan-Endres/scipy,tylerjereddy/scipy,arokem/scipy,zerothi/scipy,gertingold/scipy,aarchiba/scipy,Eric89GXL/scipy,WarrenWeckesser/scipy,ilayn/scipy,lhilt/scipy,vigna/scipy,e-q/scipy,arokem/scipy,perimosocordiae/scipy,lhilt/scipy,mdhaber/scipy,e-q/scipy,grlee77/scipy,nmayorov/scipy,rgommers/scipy,mdhaber/scipy,person142/scipy,aeklant/scipy,endolith/scipy,anntzer/scipy,Stefan-Endres/scipy,matthew-brett/scipy,WarrenWeckesser/scipy,jor-/scipy,aeklant/scipy,scipy/scipy,tylerjereddy/scipy,Eric89GXL/scipy,andyfaff/scipy,scipy/scipy,perimosocordiae/scipy,aeklant/scipy,mdhaber/scipy,WarrenWeckesser/scipy,scipy/scipy,jamestwebber/scipy,jamestwebber/scipy,Stefan-Endres/scipy,jamestwebber/scipy,aarchiba/scipy,pizzathief/scipy,person142/scipy,mdhaber/scipy,matthew-brett/scipy,lhilt/scipy,rgommers/scipy,e-q/scipy,pizzathief/scipy,zerothi/scipy,rgommers/scipy,andyfaff/scipy,vigna/scipy,rgommers/scipy,anntzer/scipy,matthew-brett/scipy,WarrenWeckesser/scipy,aarchiba/scipy,aarchiba/scipy,Stefan-Endres/scipy,arokem/scipy,rgommers/scipy,tylerjereddy/scipy,jamestwebber/scipy,e-q/scipy,person142/scipy,ilayn/scipy,ilayn/scipy,jamestwebber/scipy,aeklant/scipy,andyfaff/scipy,scipy/scipy,Stefan-Endres/scipy,scipy/scipy,vigna/scipy,Eric89GXL/scipy,grlee77/scipy,pizzathief/scipy,andyfaff/scipy,gertingold/scipy,andyfaff/scipy,anntzer/scipy,vigna/scipy,perimosocordiae/scipy,grlee77/scipy,grlee77/scipy,andyfaff/scipy,WarrenWeckesser/scipy,perimosocordiae/scipy,aarchiba/scipy,endolith/scipy,zerothi/scipy,zerothi/scipy,nmayorov/scipy,gertingold/scipy,mdhaber/scipy,Stefan-Endres/scipy,matthew-brett/scipy,jor-/scipy,pizzathief/scipy,tylerjereddy/scipy,perimosocordiae/scipy,mdhaber/scipy,nmayorov/scipy,nmayorov/scipy,endolith/scipy,person142/scipy
from __future__ import division, print_function, absolute_import from .rotation import Rotation, Slerp from ._rotation_spline import RotationSpline - __all__ = ['Rotation', 'Slerp'] + __all__ = ['Rotation', 'Slerp', 'RotationSpline'] from scipy._lib._testutils import PytestTester test = PytestTester(__name__) del PytestTester
Add RotationSpline into __all__ of spatial.transform
## Code Before: from __future__ import division, print_function, absolute_import from .rotation import Rotation, Slerp from ._rotation_spline import RotationSpline __all__ = ['Rotation', 'Slerp'] from scipy._lib._testutils import PytestTester test = PytestTester(__name__) del PytestTester ## Instruction: Add RotationSpline into __all__ of spatial.transform ## Code After: from __future__ import division, print_function, absolute_import from .rotation import Rotation, Slerp from ._rotation_spline import RotationSpline __all__ = ['Rotation', 'Slerp', 'RotationSpline'] from scipy._lib._testutils import PytestTester test = PytestTester(__name__) del PytestTester
// ... existing code ... __all__ = ['Rotation', 'Slerp', 'RotationSpline'] // ... rest of the code ...
e192a0d29c0b082458bf0a6f37df86978bfa0032
setup.py
setup.py
from distutils.core import setup setup( name='cstypo', version='0.1.1', author='Juda Kaleta', author_email='[email protected]', packages=['cstypo', 'cstypo.templatetags', 'cstypo.tests'], scripts=['bin/cstypo'], url='https://github.com/yetty/cstypo', license=open('LICENSE').read(), description='Package to apply Czech typography easily', long_description=open('README').read(), )
from distutils.core import setup setup( name='cstypo', version='0.1.1', author='Juda Kaleta', author_email='[email protected]', packages=['cstypo', 'cstypo.templatetags', 'cstypo.tests'], scripts=['bin/cstypo'], url='https://github.com/yetty/cstypo', license=open('LICENSE').read(), description='Package to apply Czech typography easily', long_description=open('README').read(), requires=['docopt (>=0.5.0)'], )
Add docopt to required packages
Add docopt to required packages
Python
mit
yetty/cstypo
from distutils.core import setup setup( name='cstypo', version='0.1.1', author='Juda Kaleta', author_email='[email protected]', packages=['cstypo', 'cstypo.templatetags', 'cstypo.tests'], scripts=['bin/cstypo'], url='https://github.com/yetty/cstypo', license=open('LICENSE').read(), description='Package to apply Czech typography easily', long_description=open('README').read(), + requires=['docopt (>=0.5.0)'], )
Add docopt to required packages
## Code Before: from distutils.core import setup setup( name='cstypo', version='0.1.1', author='Juda Kaleta', author_email='[email protected]', packages=['cstypo', 'cstypo.templatetags', 'cstypo.tests'], scripts=['bin/cstypo'], url='https://github.com/yetty/cstypo', license=open('LICENSE').read(), description='Package to apply Czech typography easily', long_description=open('README').read(), ) ## Instruction: Add docopt to required packages ## Code After: from distutils.core import setup setup( name='cstypo', version='0.1.1', author='Juda Kaleta', author_email='[email protected]', packages=['cstypo', 'cstypo.templatetags', 'cstypo.tests'], scripts=['bin/cstypo'], url='https://github.com/yetty/cstypo', license=open('LICENSE').read(), description='Package to apply Czech typography easily', long_description=open('README').read(), requires=['docopt (>=0.5.0)'], )
// ... existing code ... long_description=open('README').read(), requires=['docopt (>=0.5.0)'], ) // ... rest of the code ...
8f03f51c89aeea44943f9cb0b39330e676ae0089
utils.py
utils.py
import vx from contextlib import contextmanager from functools import partial import sys from io import StringIO def _expose(f=None, name=None): if f is None: return partial(_expose, name=name) if name is None: name = f.__name__.lstrip('_') if getattr(vx, name, None) is not None: raise AttributeError("Cannot expose duplicate name: '{}'".format(name)) setattr(vx, name, f) return f vx.expose = _expose @vx.expose def _repeat(c, times=4): for _ in range(times): c() @vx.expose @contextmanager def _cursor_wander(command=None, window=None): if window is None: window = vx.window.focused_window y, x = vx.get_linecol_window(window) if command is not None: command() yp, xp = vx.get_linecol_window(window) yield (yp, xp) vx.set_linecol_window(window, y, x) @contextmanager def stdoutIO(stdout=None): old = sys.stdout if stdout is None: stdout = StringIO() sys.stdout = stdout yield stdout sys.stdout = old
import vx from contextlib import contextmanager from functools import partial import sys from io import StringIO def _expose(f=None, name=None): if f is None: return partial(_expose, name=name) if name is None: name = f.__name__.lstrip('_') if getattr(vx, name, None) is not None: raise AttributeError("Cannot expose duplicate name: '{}'".format(name)) setattr(vx, name, f) return f vx.expose = _expose @vx.expose def _repeat(c, times=4): res = [] for _ in range(times): res.append(c()) return res @vx.expose @contextmanager def _cursor_wander(command=None, window=None): if window is None: window = vx.window.focused_window y, x = vx.get_linecol_window(window) if command is not None: command() yp, xp = vx.get_linecol_window(window) yield (yp, xp) vx.set_linecol_window(window, y, x) @contextmanager def stdoutIO(stdout=None): old = sys.stdout if stdout is None: stdout = StringIO() sys.stdout = stdout yield stdout sys.stdout = old
Change repeat command to return a list of the results of the repeated commands
Change repeat command to return a list of the results of the repeated commands
Python
mit
philipdexter/vx,philipdexter/vx
import vx from contextlib import contextmanager from functools import partial import sys from io import StringIO def _expose(f=None, name=None): if f is None: return partial(_expose, name=name) if name is None: name = f.__name__.lstrip('_') if getattr(vx, name, None) is not None: raise AttributeError("Cannot expose duplicate name: '{}'".format(name)) setattr(vx, name, f) return f vx.expose = _expose @vx.expose def _repeat(c, times=4): + res = [] for _ in range(times): - c() + res.append(c()) + return res @vx.expose @contextmanager def _cursor_wander(command=None, window=None): if window is None: window = vx.window.focused_window y, x = vx.get_linecol_window(window) if command is not None: command() yp, xp = vx.get_linecol_window(window) yield (yp, xp) vx.set_linecol_window(window, y, x) @contextmanager def stdoutIO(stdout=None): old = sys.stdout if stdout is None: stdout = StringIO() sys.stdout = stdout yield stdout sys.stdout = old
Change repeat command to return a list of the results of the repeated commands
## Code Before: import vx from contextlib import contextmanager from functools import partial import sys from io import StringIO def _expose(f=None, name=None): if f is None: return partial(_expose, name=name) if name is None: name = f.__name__.lstrip('_') if getattr(vx, name, None) is not None: raise AttributeError("Cannot expose duplicate name: '{}'".format(name)) setattr(vx, name, f) return f vx.expose = _expose @vx.expose def _repeat(c, times=4): for _ in range(times): c() @vx.expose @contextmanager def _cursor_wander(command=None, window=None): if window is None: window = vx.window.focused_window y, x = vx.get_linecol_window(window) if command is not None: command() yp, xp = vx.get_linecol_window(window) yield (yp, xp) vx.set_linecol_window(window, y, x) @contextmanager def stdoutIO(stdout=None): old = sys.stdout if stdout is None: stdout = StringIO() sys.stdout = stdout yield stdout sys.stdout = old ## Instruction: Change repeat command to return a list of the results of the repeated commands ## Code After: import vx from contextlib import contextmanager from functools import partial import sys from io import StringIO def _expose(f=None, name=None): if f is None: return partial(_expose, name=name) if name is None: name = f.__name__.lstrip('_') if getattr(vx, name, None) is not None: raise AttributeError("Cannot expose duplicate name: '{}'".format(name)) setattr(vx, name, f) return f vx.expose = _expose @vx.expose def _repeat(c, times=4): res = [] for _ in range(times): res.append(c()) return res @vx.expose @contextmanager def _cursor_wander(command=None, window=None): if window is None: window = vx.window.focused_window y, x = vx.get_linecol_window(window) if command is not None: command() yp, xp = vx.get_linecol_window(window) yield (yp, xp) vx.set_linecol_window(window, y, x) @contextmanager def stdoutIO(stdout=None): old = sys.stdout if stdout is None: stdout = StringIO() sys.stdout = stdout yield stdout sys.stdout = old
... def _repeat(c, times=4): res = [] for _ in range(times): res.append(c()) return res ...
117c3e6c1f301c4e5c07e22b3c76f330b18ea36e
bin/create_contour_data.py
bin/create_contour_data.py
import sys import os sys.path.append('../nsmaps') import nsmaps DATA_DIR = './website/nsmaps-data' def test(): stations = nsmaps.station.Stations(DATA_DIR) departure_station_name = 'Utrecht Centraal' departure_station = stations.find_station(departure_station_name) filepath_out = os.path.join(DATA_DIR, 'contours_' + departure_station.get_code() + '.geojson') test_config = nsmaps.contourmap.ContourPlotConfig() contourmap = nsmaps.contourmap.Contour(departure_station, stations, test_config, DATA_DIR) contourmap.create_contour_data(filepath_out) def create_all(): stations = nsmaps.station.Stations(DATA_DIR) # test_config = nsmaps.contourmap.TestConfig() config = nsmaps.contourmap.ContourPlotConfig() for station in stations: if station.has_travel_time_data(): contourmap = nsmaps.contourmap.Contour(station, stations, config, DATA_DIR) contourmap.create_contour_data(filepath_out) if __name__ == "__main__": test() # create_all()
import sys import os sys.path.append('../nsmaps') import nsmaps DATA_DIR = './website/nsmaps-data' def test(): stations = nsmaps.station.Stations(DATA_DIR) departure_station_name = 'Utrecht Centraal' departure_station = stations.find_station(departure_station_name) assert os.path.exists(os.path.join(DATA_DIR, 'contours/')) filepath_out = os.path.join(DATA_DIR, 'contours/' + departure_station.get_code() + '.geojson') test_config = nsmaps.contourmap.ContourPlotConfig() test_config.print_bounding_box() contourmap = nsmaps.contourmap.Contour(departure_station, stations, test_config, DATA_DIR) # contourmap.create_contour_data(filepath_out) contourmap.create_geojson_tiles(filepath_out) def create_all(): stations = nsmaps.station.Stations(DATA_DIR) # test_config = nsmaps.contourmap.TestConfig() config = nsmaps.contourmap.ContourPlotConfig() for station in stations: if station.has_travel_time_data(): contourmap = nsmaps.contourmap.Contour(station, stations, config, DATA_DIR) contourmap.create_contour_data(filepath_out) contourmap.create_geojson_tiles(filepath_out) if __name__ == "__main__": test() # create_all()
Create tiles in create contour command
Create tiles in create contour command
Python
mit
bartromgens/nsmaps,bartromgens/nsmaps,bartromgens/nsmaps
import sys import os sys.path.append('../nsmaps') import nsmaps DATA_DIR = './website/nsmaps-data' def test(): stations = nsmaps.station.Stations(DATA_DIR) departure_station_name = 'Utrecht Centraal' departure_station = stations.find_station(departure_station_name) + assert os.path.exists(os.path.join(DATA_DIR, 'contours/')) - filepath_out = os.path.join(DATA_DIR, 'contours_' + departure_station.get_code() + '.geojson') + filepath_out = os.path.join(DATA_DIR, 'contours/' + departure_station.get_code() + '.geojson') test_config = nsmaps.contourmap.ContourPlotConfig() + test_config.print_bounding_box() contourmap = nsmaps.contourmap.Contour(departure_station, stations, test_config, DATA_DIR) - contourmap.create_contour_data(filepath_out) + # contourmap.create_contour_data(filepath_out) - + contourmap.create_geojson_tiles(filepath_out) def create_all(): stations = nsmaps.station.Stations(DATA_DIR) # test_config = nsmaps.contourmap.TestConfig() config = nsmaps.contourmap.ContourPlotConfig() for station in stations: if station.has_travel_time_data(): contourmap = nsmaps.contourmap.Contour(station, stations, config, DATA_DIR) contourmap.create_contour_data(filepath_out) + contourmap.create_geojson_tiles(filepath_out) if __name__ == "__main__": test() # create_all()
Create tiles in create contour command
## Code Before: import sys import os sys.path.append('../nsmaps') import nsmaps DATA_DIR = './website/nsmaps-data' def test(): stations = nsmaps.station.Stations(DATA_DIR) departure_station_name = 'Utrecht Centraal' departure_station = stations.find_station(departure_station_name) filepath_out = os.path.join(DATA_DIR, 'contours_' + departure_station.get_code() + '.geojson') test_config = nsmaps.contourmap.ContourPlotConfig() contourmap = nsmaps.contourmap.Contour(departure_station, stations, test_config, DATA_DIR) contourmap.create_contour_data(filepath_out) def create_all(): stations = nsmaps.station.Stations(DATA_DIR) # test_config = nsmaps.contourmap.TestConfig() config = nsmaps.contourmap.ContourPlotConfig() for station in stations: if station.has_travel_time_data(): contourmap = nsmaps.contourmap.Contour(station, stations, config, DATA_DIR) contourmap.create_contour_data(filepath_out) if __name__ == "__main__": test() # create_all() ## Instruction: Create tiles in create contour command ## Code After: import sys import os sys.path.append('../nsmaps') import nsmaps DATA_DIR = './website/nsmaps-data' def test(): stations = nsmaps.station.Stations(DATA_DIR) departure_station_name = 'Utrecht Centraal' departure_station = stations.find_station(departure_station_name) assert os.path.exists(os.path.join(DATA_DIR, 'contours/')) filepath_out = os.path.join(DATA_DIR, 'contours/' + departure_station.get_code() + '.geojson') test_config = nsmaps.contourmap.ContourPlotConfig() test_config.print_bounding_box() contourmap = nsmaps.contourmap.Contour(departure_station, stations, test_config, DATA_DIR) # contourmap.create_contour_data(filepath_out) contourmap.create_geojson_tiles(filepath_out) def create_all(): stations = nsmaps.station.Stations(DATA_DIR) # test_config = nsmaps.contourmap.TestConfig() config = nsmaps.contourmap.ContourPlotConfig() for station in stations: if station.has_travel_time_data(): contourmap = nsmaps.contourmap.Contour(station, stations, config, DATA_DIR) contourmap.create_contour_data(filepath_out) contourmap.create_geojson_tiles(filepath_out) if __name__ == "__main__": test() # create_all()
# ... existing code ... departure_station = stations.find_station(departure_station_name) assert os.path.exists(os.path.join(DATA_DIR, 'contours/')) filepath_out = os.path.join(DATA_DIR, 'contours/' + departure_station.get_code() + '.geojson') test_config = nsmaps.contourmap.ContourPlotConfig() test_config.print_bounding_box() # ... modified code ... contourmap = nsmaps.contourmap.Contour(departure_station, stations, test_config, DATA_DIR) # contourmap.create_contour_data(filepath_out) contourmap.create_geojson_tiles(filepath_out) ... contourmap.create_contour_data(filepath_out) contourmap.create_geojson_tiles(filepath_out) # ... rest of the code ...
23d12b1c4b755c7d35406bf2428eefbd682ef68f
examples/xor-classifier.py
examples/xor-classifier.py
'''Example using the theanets package for learning the XOR relation.''' import climate import logging import numpy as np import theanets climate.enable_default_logging() X = np.array([[0.0, 0.0], [0.0, 1.0], [1.0, 0.0], [1.0, 1.0]]) Y = np.array([0, 1, 1, 0, ]) Xi = np.random.randint(0, 2, size=(256, 2)) train = [ (Xi + 0.1 * np.random.randn(*Xi.shape)).astype('f'), (Xi[:, 0] ^ Xi[:, 1]).astype('f')[:, None], ] e = theanets.Experiment(theanets.Regressor, layers=(2, 2, 1), learning_rate=0.1, momentum=0.5, patience=300) e.run(train, train) logging.info("Input:\n%s", X) logging.info("XOR output:\n%s", Y) logging.info("NN XOR predictions:\n%s", e.network(X.astype('f')))
'''Example using the theanets package for learning the XOR relation.''' import climate import logging import numpy as np import theanets climate.enable_default_logging() X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype='f') Y = np.array([[0], [1], [1], [0]], dtype='f') e = theanets.Experiment(theanets.Regressor, layers=(2, 2, 1)) e.train([X, Y], optimize='rprop', min_improvement=0.2, patience=500) logging.info("Input:\n%s", X) logging.info("XOR output:\n%s", Y) logging.info("NN XOR predictions:\n%s", e.network(X.astype('f')).round(2))
Use rprop for xor example.
Use rprop for xor example.
Python
mit
lmjohns3/theanets,devdoer/theanets,chrinide/theanets
'''Example using the theanets package for learning the XOR relation.''' import climate import logging import numpy as np import theanets climate.enable_default_logging() - X = np.array([[0.0, 0.0], [0.0, 1.0], [1.0, 0.0], [1.0, 1.0]]) - Y = np.array([0, 1, 1, 0, ]) + X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype='f') + Y = np.array([[0], [1], [1], [0]], dtype='f') - Xi = np.random.randint(0, 2, size=(256, 2)) - train = [ - (Xi + 0.1 * np.random.randn(*Xi.shape)).astype('f'), - (Xi[:, 0] ^ Xi[:, 1]).astype('f')[:, None], - ] - - e = theanets.Experiment(theanets.Regressor, + e = theanets.Experiment(theanets.Regressor, layers=(2, 2, 1)) + e.train([X, Y], optimize='rprop', min_improvement=0.2, patience=500) - layers=(2, 2, 1), - learning_rate=0.1, - momentum=0.5, - patience=300) - e.run(train, train) logging.info("Input:\n%s", X) logging.info("XOR output:\n%s", Y) - logging.info("NN XOR predictions:\n%s", e.network(X.astype('f'))) + logging.info("NN XOR predictions:\n%s", e.network(X.astype('f')).round(2))
Use rprop for xor example.
## Code Before: '''Example using the theanets package for learning the XOR relation.''' import climate import logging import numpy as np import theanets climate.enable_default_logging() X = np.array([[0.0, 0.0], [0.0, 1.0], [1.0, 0.0], [1.0, 1.0]]) Y = np.array([0, 1, 1, 0, ]) Xi = np.random.randint(0, 2, size=(256, 2)) train = [ (Xi + 0.1 * np.random.randn(*Xi.shape)).astype('f'), (Xi[:, 0] ^ Xi[:, 1]).astype('f')[:, None], ] e = theanets.Experiment(theanets.Regressor, layers=(2, 2, 1), learning_rate=0.1, momentum=0.5, patience=300) e.run(train, train) logging.info("Input:\n%s", X) logging.info("XOR output:\n%s", Y) logging.info("NN XOR predictions:\n%s", e.network(X.astype('f'))) ## Instruction: Use rprop for xor example. ## Code After: '''Example using the theanets package for learning the XOR relation.''' import climate import logging import numpy as np import theanets climate.enable_default_logging() X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype='f') Y = np.array([[0], [1], [1], [0]], dtype='f') e = theanets.Experiment(theanets.Regressor, layers=(2, 2, 1)) e.train([X, Y], optimize='rprop', min_improvement=0.2, patience=500) logging.info("Input:\n%s", X) logging.info("XOR output:\n%s", Y) logging.info("NN XOR predictions:\n%s", e.network(X.astype('f')).round(2))
// ... existing code ... X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype='f') Y = np.array([[0], [1], [1], [0]], dtype='f') e = theanets.Experiment(theanets.Regressor, layers=(2, 2, 1)) e.train([X, Y], optimize='rprop', min_improvement=0.2, patience=500) // ... modified code ... logging.info("XOR output:\n%s", Y) logging.info("NN XOR predictions:\n%s", e.network(X.astype('f')).round(2)) // ... rest of the code ...
151e94d2d0208ac1984da105c6c7966b2a76c697
pymodels/TS_V04_01/__init__.py
pymodels/TS_V04_01/__init__.py
from .lattice import default_optics_mode from .lattice import energy from .accelerator import default_vchamber_on from .accelerator import default_radiation_on from .accelerator import accelerator_data from .accelerator import create_accelerator from .families import get_family_data from .families import family_mapping from .families import get_section_name_mapping # -- default accelerator values for TS_V04_01-- lattice_version = accelerator_data['lattice_version']
from .lattice import default_optics_mode from .lattice import energy from .accelerator import default_vchamber_on from .accelerator import default_radiation_on from .accelerator import accelerator_data from .accelerator import create_accelerator from .families import get_family_data from .families import family_mapping from .families import get_section_name_mapping from .control_system import get_control_system_data # -- default accelerator values for TS_V04_01-- lattice_version = accelerator_data['lattice_version']
Add control system data to init.
TS.ENH: Add control system data to init.
Python
mit
lnls-fac/sirius
from .lattice import default_optics_mode from .lattice import energy from .accelerator import default_vchamber_on from .accelerator import default_radiation_on from .accelerator import accelerator_data from .accelerator import create_accelerator from .families import get_family_data from .families import family_mapping from .families import get_section_name_mapping + from .control_system import get_control_system_data + # -- default accelerator values for TS_V04_01-- lattice_version = accelerator_data['lattice_version']
Add control system data to init.
## Code Before: from .lattice import default_optics_mode from .lattice import energy from .accelerator import default_vchamber_on from .accelerator import default_radiation_on from .accelerator import accelerator_data from .accelerator import create_accelerator from .families import get_family_data from .families import family_mapping from .families import get_section_name_mapping # -- default accelerator values for TS_V04_01-- lattice_version = accelerator_data['lattice_version'] ## Instruction: Add control system data to init. ## Code After: from .lattice import default_optics_mode from .lattice import energy from .accelerator import default_vchamber_on from .accelerator import default_radiation_on from .accelerator import accelerator_data from .accelerator import create_accelerator from .families import get_family_data from .families import family_mapping from .families import get_section_name_mapping from .control_system import get_control_system_data # -- default accelerator values for TS_V04_01-- lattice_version = accelerator_data['lattice_version']
# ... existing code ... from .control_system import get_control_system_data # -- default accelerator values for TS_V04_01-- # ... rest of the code ...
f14329dd4449c352cdf82ff2ffab0bfb9bcff882
parser.py
parser.py
from collections import namedtuple IRCMsg = namedtuple('IRCMsg', 'prefix cmd params postfix') def parse(line): """ Parses line and returns a named tuple IRCMsg with fields (prefix, cmd, params, postfix). - prefix is the first part starting with : (colon), without the : - cmd is the command - params are the parameters for the command, not including the possible postfix - postfix is the part of the parameters starting with :, without the : """ if not line: return None prefix = '' command = '' params = '' postfix = '' # prefix is present is line starts with ':' if line[0] == ':': prefix, line = line.split(' ', 1) # there might be more than one space between # the possible prefix and command, so we'll strip them command, line = line.lstrip().split(' ', 1) # postfix is present is line has ':' index = line.find(':') if index != -1: params = line[:index] postfix = line[index:] else: params = line # command and params must be non-empty if len(command) == 0 or len(params) == 0: return None return IRCMsg(prefix=prefix[1:], cmd=command, params=params, postfix=postfix[1:])
from collections import namedtuple IRCMsg = namedtuple('IRCMsg', 'prefix cmd params postfix') def parse(line): """ Parses line and returns a named tuple IRCMsg with fields (prefix, cmd, params, postfix). - prefix is the first part starting with : (colon), without the : - cmd is the command - params are the parameters for the command, not including the possible postfix - postfix is the part of the parameters starting with :, without the : """ if not line: return None prefix = '' command = '' params = '' postfix = '' # prefix is present is line starts with ':' if line[0] == ':': prefix, line = line.split(' ', 1) # there might be more than one space between # the possible prefix and command, so we'll strip them command, line = line.lstrip().split(' ', 1) # postfix is present is line has ':' index = line.find(':') if index != -1: params = line[:index] postfix = line[index:] else: params = line # command must be non-empty if len(command) == 0: return None return IRCMsg(prefix=prefix[1:], cmd=command, params=params, postfix=postfix[1:])
Fix parsing irc messages with empty list of parameters
Fix parsing irc messages with empty list of parameters
Python
mit
aalien/mib
from collections import namedtuple IRCMsg = namedtuple('IRCMsg', 'prefix cmd params postfix') def parse(line): """ Parses line and returns a named tuple IRCMsg with fields (prefix, cmd, params, postfix). - prefix is the first part starting with : (colon), without the : - cmd is the command - params are the parameters for the command, not including the possible postfix - postfix is the part of the parameters starting with :, without the : """ if not line: return None prefix = '' command = '' params = '' postfix = '' # prefix is present is line starts with ':' if line[0] == ':': prefix, line = line.split(' ', 1) # there might be more than one space between # the possible prefix and command, so we'll strip them command, line = line.lstrip().split(' ', 1) # postfix is present is line has ':' index = line.find(':') if index != -1: params = line[:index] postfix = line[index:] else: params = line - # command and params must be non-empty + # command must be non-empty - if len(command) == 0 or len(params) == 0: + if len(command) == 0: return None return IRCMsg(prefix=prefix[1:], cmd=command, params=params, postfix=postfix[1:])
Fix parsing irc messages with empty list of parameters
## Code Before: from collections import namedtuple IRCMsg = namedtuple('IRCMsg', 'prefix cmd params postfix') def parse(line): """ Parses line and returns a named tuple IRCMsg with fields (prefix, cmd, params, postfix). - prefix is the first part starting with : (colon), without the : - cmd is the command - params are the parameters for the command, not including the possible postfix - postfix is the part of the parameters starting with :, without the : """ if not line: return None prefix = '' command = '' params = '' postfix = '' # prefix is present is line starts with ':' if line[0] == ':': prefix, line = line.split(' ', 1) # there might be more than one space between # the possible prefix and command, so we'll strip them command, line = line.lstrip().split(' ', 1) # postfix is present is line has ':' index = line.find(':') if index != -1: params = line[:index] postfix = line[index:] else: params = line # command and params must be non-empty if len(command) == 0 or len(params) == 0: return None return IRCMsg(prefix=prefix[1:], cmd=command, params=params, postfix=postfix[1:]) ## Instruction: Fix parsing irc messages with empty list of parameters ## Code After: from collections import namedtuple IRCMsg = namedtuple('IRCMsg', 'prefix cmd params postfix') def parse(line): """ Parses line and returns a named tuple IRCMsg with fields (prefix, cmd, params, postfix). - prefix is the first part starting with : (colon), without the : - cmd is the command - params are the parameters for the command, not including the possible postfix - postfix is the part of the parameters starting with :, without the : """ if not line: return None prefix = '' command = '' params = '' postfix = '' # prefix is present is line starts with ':' if line[0] == ':': prefix, line = line.split(' ', 1) # there might be more than one space between # the possible prefix and command, so we'll strip them command, line = line.lstrip().split(' ', 1) # postfix is present is line has ':' index = line.find(':') if index != -1: params = line[:index] postfix = line[index:] else: params = line # command must be non-empty if len(command) == 0: return None return IRCMsg(prefix=prefix[1:], cmd=command, params=params, postfix=postfix[1:])
... # command must be non-empty if len(command) == 0: return None ...
b3b67fe0e68423fc2f85bccf1f20acdb779a38ba
pylxd/deprecated/tests/utils.py
pylxd/deprecated/tests/utils.py
from pylxd import api from pylxd import exceptions as lxd_exceptions def upload_image(image): alias = "{}/{}/{}/{}".format( image["os"], image["release"], image["arch"], image["variant"] ) lxd = api.API() imgs = api.API(host="images.linuxcontainers.org") d = imgs.alias_show(alias) meta = d[1]["metadata"] tgt = meta["target"] try: lxd.alias_update(meta) except lxd_exceptions.APIError as ex: if ex.status_code == 404: lxd.alias_create(meta) return tgt def delete_image(image): lxd = api.API() lxd.image_delete(image)
from pylxd import api def delete_image(image): lxd = api.API() lxd.image_delete(image)
Remove unused testing utility function
Remove unused testing utility function Signed-off-by: Dougal Matthews <[email protected]>
Python
apache-2.0
lxc/pylxd,lxc/pylxd
from pylxd import api - from pylxd import exceptions as lxd_exceptions - - - def upload_image(image): - alias = "{}/{}/{}/{}".format( - image["os"], image["release"], image["arch"], image["variant"] - ) - lxd = api.API() - imgs = api.API(host="images.linuxcontainers.org") - d = imgs.alias_show(alias) - - meta = d[1]["metadata"] - tgt = meta["target"] - - try: - lxd.alias_update(meta) - except lxd_exceptions.APIError as ex: - if ex.status_code == 404: - lxd.alias_create(meta) - - return tgt def delete_image(image): lxd = api.API() lxd.image_delete(image)
Remove unused testing utility function
## Code Before: from pylxd import api from pylxd import exceptions as lxd_exceptions def upload_image(image): alias = "{}/{}/{}/{}".format( image["os"], image["release"], image["arch"], image["variant"] ) lxd = api.API() imgs = api.API(host="images.linuxcontainers.org") d = imgs.alias_show(alias) meta = d[1]["metadata"] tgt = meta["target"] try: lxd.alias_update(meta) except lxd_exceptions.APIError as ex: if ex.status_code == 404: lxd.alias_create(meta) return tgt def delete_image(image): lxd = api.API() lxd.image_delete(image) ## Instruction: Remove unused testing utility function ## Code After: from pylxd import api def delete_image(image): lxd = api.API() lxd.image_delete(image)
# ... existing code ... from pylxd import api # ... rest of the code ...
c6346fa2c026318b530dbbdc90dbaee8310b6b05
robot/Cumulus/resources/locators_50.py
robot/Cumulus/resources/locators_50.py
from locators_51 import * import copy npsp_lex_locators = copy.deepcopy(npsp_lex_locators) npsp_lex_locators['delete_icon']='//span[contains(text() ,"{}")]/following::span[. = "{}"]/following-sibling::a/child::span[@class = "deleteIcon"]' npsp_lex_locators['object']['field']= "//div[contains(@class, 'uiInput')][.//label[contains(@class, 'uiLabel')][.//span[text()='{}']]]//*[self::input or self::textarea]" npsp_lex_locators["record"]["related"]["dd-link"]='//div[contains(@class,"actionMenu")]//a[@title="{}"]' npsp_lex_locators["record"]["related"]["button"]="//article[contains(@class, 'slds-card slds-card_boundary')][.//img][.//span[@title='{}']]//a[@title='{}']"
from locators_51 import * import copy npsp_lex_locators = copy.deepcopy(npsp_lex_locators) # current version (Sravani's ) npsp_lex_locators['delete_icon']='//span[contains(text() ,"{}")]/following::span[. = "{}"]/following-sibling::a/child::span[@class = "deleteIcon"]' npsp_lex_locators['object']['field']= "//div[contains(@class, 'uiInput')][.//label[contains(@class, 'uiLabel')][.//span[text()='{}']]]//*[self::input or self::textarea]" npsp_lex_locators["record"]["related"]["dd-link"]='//div[contains(@class,"actionMenu")]//a[@title="{}"]' npsp_lex_locators["record"]["related"]["button"]="//article[contains(@class, 'slds-card slds-card_boundary')][.//img][.//span[@title='{}']]//a[@title='{}']" # stashed (Noah's version) # npsp_lex_locators["delete_icon"]= "//span[contains(text(),'{}')]/../following::div//span[text() = '{}']/following-sibling::a/child::span[@class = 'deleteIcon']" # npsp_lex_locators['object']['field']= "//div[contains(@class, 'uiInput')][.//label[contains(@class, 'uiLabel')][.//span[text()='{}']]]//*[self::input or self::textarea]" # npsp_lex_locators["record"]["related"]["dd-link"]='//div[contains(@class,"actionMenu")]//a[@title="{}"]'
Revert "Revert "changes in locator_50 file (current and old versions)""
Revert "Revert "changes in locator_50 file (current and old versions)"" This reverts commit 7537387aa80109877d6659cc54ec0ee7aa6496bd.
Python
bsd-3-clause
SalesforceFoundation/Cumulus,SalesforceFoundation/Cumulus,SalesforceFoundation/Cumulus,SalesforceFoundation/Cumulus
from locators_51 import * import copy npsp_lex_locators = copy.deepcopy(npsp_lex_locators) + + # current version (Sravani's ) npsp_lex_locators['delete_icon']='//span[contains(text() ,"{}")]/following::span[. = "{}"]/following-sibling::a/child::span[@class = "deleteIcon"]' npsp_lex_locators['object']['field']= "//div[contains(@class, 'uiInput')][.//label[contains(@class, 'uiLabel')][.//span[text()='{}']]]//*[self::input or self::textarea]" npsp_lex_locators["record"]["related"]["dd-link"]='//div[contains(@class,"actionMenu")]//a[@title="{}"]' npsp_lex_locators["record"]["related"]["button"]="//article[contains(@class, 'slds-card slds-card_boundary')][.//img][.//span[@title='{}']]//a[@title='{}']" + + # stashed (Noah's version) + + # npsp_lex_locators["delete_icon"]= "//span[contains(text(),'{}')]/../following::div//span[text() = '{}']/following-sibling::a/child::span[@class = 'deleteIcon']" + # npsp_lex_locators['object']['field']= "//div[contains(@class, 'uiInput')][.//label[contains(@class, 'uiLabel')][.//span[text()='{}']]]//*[self::input or self::textarea]" + # npsp_lex_locators["record"]["related"]["dd-link"]='//div[contains(@class,"actionMenu")]//a[@title="{}"]' + +
Revert "Revert "changes in locator_50 file (current and old versions)""
## Code Before: from locators_51 import * import copy npsp_lex_locators = copy.deepcopy(npsp_lex_locators) npsp_lex_locators['delete_icon']='//span[contains(text() ,"{}")]/following::span[. = "{}"]/following-sibling::a/child::span[@class = "deleteIcon"]' npsp_lex_locators['object']['field']= "//div[contains(@class, 'uiInput')][.//label[contains(@class, 'uiLabel')][.//span[text()='{}']]]//*[self::input or self::textarea]" npsp_lex_locators["record"]["related"]["dd-link"]='//div[contains(@class,"actionMenu")]//a[@title="{}"]' npsp_lex_locators["record"]["related"]["button"]="//article[contains(@class, 'slds-card slds-card_boundary')][.//img][.//span[@title='{}']]//a[@title='{}']" ## Instruction: Revert "Revert "changes in locator_50 file (current and old versions)"" ## Code After: from locators_51 import * import copy npsp_lex_locators = copy.deepcopy(npsp_lex_locators) # current version (Sravani's ) npsp_lex_locators['delete_icon']='//span[contains(text() ,"{}")]/following::span[. = "{}"]/following-sibling::a/child::span[@class = "deleteIcon"]' npsp_lex_locators['object']['field']= "//div[contains(@class, 'uiInput')][.//label[contains(@class, 'uiLabel')][.//span[text()='{}']]]//*[self::input or self::textarea]" npsp_lex_locators["record"]["related"]["dd-link"]='//div[contains(@class,"actionMenu")]//a[@title="{}"]' npsp_lex_locators["record"]["related"]["button"]="//article[contains(@class, 'slds-card slds-card_boundary')][.//img][.//span[@title='{}']]//a[@title='{}']" # stashed (Noah's version) # npsp_lex_locators["delete_icon"]= "//span[contains(text(),'{}')]/../following::div//span[text() = '{}']/following-sibling::a/child::span[@class = 'deleteIcon']" # npsp_lex_locators['object']['field']= "//div[contains(@class, 'uiInput')][.//label[contains(@class, 'uiLabel')][.//span[text()='{}']]]//*[self::input or self::textarea]" # npsp_lex_locators["record"]["related"]["dd-link"]='//div[contains(@class,"actionMenu")]//a[@title="{}"]'
// ... existing code ... npsp_lex_locators = copy.deepcopy(npsp_lex_locators) # current version (Sravani's ) npsp_lex_locators['delete_icon']='//span[contains(text() ,"{}")]/following::span[. = "{}"]/following-sibling::a/child::span[@class = "deleteIcon"]' // ... modified code ... npsp_lex_locators["record"]["related"]["button"]="//article[contains(@class, 'slds-card slds-card_boundary')][.//img][.//span[@title='{}']]//a[@title='{}']" # stashed (Noah's version) # npsp_lex_locators["delete_icon"]= "//span[contains(text(),'{}')]/../following::div//span[text() = '{}']/following-sibling::a/child::span[@class = 'deleteIcon']" # npsp_lex_locators['object']['field']= "//div[contains(@class, 'uiInput')][.//label[contains(@class, 'uiLabel')][.//span[text()='{}']]]//*[self::input or self::textarea]" # npsp_lex_locators["record"]["related"]["dd-link"]='//div[contains(@class,"actionMenu")]//a[@title="{}"]' // ... rest of the code ...