commit
stringlengths
40
40
old_file
stringlengths
4
106
new_file
stringlengths
4
106
old_contents
stringlengths
10
2.94k
new_contents
stringlengths
21
2.95k
subject
stringlengths
16
444
message
stringlengths
17
2.63k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
7
43k
ndiff
stringlengths
52
3.31k
instruction
stringlengths
16
444
content
stringlengths
133
4.32k
diff
stringlengths
49
3.61k
b3c2a47b049f97de0367f012fb35d247f2f1510b
oscar/apps/offer/managers.py
oscar/apps/offer/managers.py
from django.utils.timezone import now from django.db import models class ActiveOfferManager(models.Manager): """ For searching/creating offers within their date range """ def get_query_set(self): cutoff = now() return super(ActiveOfferManager, self).get_query_set().filter( models.Q(end_date__gte=today) | models.Q(end_date=None), start_date__lte=today)
from django.utils.timezone import now from django.db import models class ActiveOfferManager(models.Manager): """ For searching/creating offers within their date range """ def get_query_set(self): cutoff = now() return super(ActiveOfferManager, self).get_query_set().filter( models.Q(end_datetime__gte=cutoff) | models.Q(end_datetime=None), start_datetime__lte=cutoff)
Fix bug in offer manager with new datetimes
Fix bug in offer manager with new datetimes
Python
bsd-3-clause
rocopartners/django-oscar,WadeYuChen/django-oscar,sonofatailor/django-oscar,josesanch/django-oscar,mexeniz/django-oscar,faratro/django-oscar,michaelkuty/django-oscar,anentropic/django-oscar,jinnykoo/wuyisj,MatthewWilkes/django-oscar,sasha0/django-oscar,jlmadurga/django-oscar,Idematica/django-oscar,okfish/django-oscar,bschuon/django-oscar,django-oscar/django-oscar,taedori81/django-oscar,bnprk/django-oscar,ka7eh/django-oscar,pasqualguerrero/django-oscar,Bogh/django-oscar,DrOctogon/unwash_ecom,MatthewWilkes/django-oscar,QLGu/django-oscar,jinnykoo/christmas,saadatqadri/django-oscar,kapari/django-oscar,taedori81/django-oscar,ka7eh/django-oscar,spartonia/django-oscar,ka7eh/django-oscar,nickpack/django-oscar,john-parton/django-oscar,monikasulik/django-oscar,rocopartners/django-oscar,jinnykoo/wuyisj,kapt/django-oscar,pasqualguerrero/django-oscar,rocopartners/django-oscar,amirrpp/django-oscar,DrOctogon/unwash_ecom,john-parton/django-oscar,WillisXChen/django-oscar,dongguangming/django-oscar,pdonadeo/django-oscar,nfletton/django-oscar,manevant/django-oscar,nickpack/django-oscar,itbabu/django-oscar,nickpack/django-oscar,machtfit/django-oscar,nfletton/django-oscar,thechampanurag/django-oscar,adamend/django-oscar,thechampanurag/django-oscar,Jannes123/django-oscar,saadatqadri/django-oscar,WadeYuChen/django-oscar,anentropic/django-oscar,makielab/django-oscar,vovanbo/django-oscar,ademuk/django-oscar,vovanbo/django-oscar,vovanbo/django-oscar,sasha0/django-oscar,QLGu/django-oscar,makielab/django-oscar,solarissmoke/django-oscar,amirrpp/django-oscar,django-oscar/django-oscar,Jannes123/django-oscar,WadeYuChen/django-oscar,josesanch/django-oscar,mexeniz/django-oscar,josesanch/django-oscar,ademuk/django-oscar,manevant/django-oscar,itbabu/django-oscar,Idematica/django-oscar,mexeniz/django-oscar,WillisXChen/django-oscar,manevant/django-oscar,rocopartners/django-oscar,jmt4/django-oscar,kapt/django-oscar,pdonadeo/django-oscar,spartonia/django-oscar,Bogh/django-oscar,jmt4/django-oscar,taedori81/django-oscar,marcoantoniooliveira/labweb,ahmetdaglarbas/e-commerce,ahmetdaglarbas/e-commerce,MatthewWilkes/django-oscar,spartonia/django-oscar,adamend/django-oscar,makielab/django-oscar,solarissmoke/django-oscar,kapt/django-oscar,john-parton/django-oscar,bschuon/django-oscar,Bogh/django-oscar,django-oscar/django-oscar,jlmadurga/django-oscar,sasha0/django-oscar,pdonadeo/django-oscar,QLGu/django-oscar,thechampanurag/django-oscar,bnprk/django-oscar,jlmadurga/django-oscar,WillisXChen/django-oscar,bschuon/django-oscar,marcoantoniooliveira/labweb,eddiep1101/django-oscar,machtfit/django-oscar,lijoantony/django-oscar,ka7eh/django-oscar,jinnykoo/wuyisj.com,okfish/django-oscar,manevant/django-oscar,WillisXChen/django-oscar,marcoantoniooliveira/labweb,nfletton/django-oscar,elliotthill/django-oscar,spartonia/django-oscar,john-parton/django-oscar,WillisXChen/django-oscar,taedori81/django-oscar,binarydud/django-oscar,binarydud/django-oscar,jinnykoo/christmas,sonofatailor/django-oscar,nfletton/django-oscar,elliotthill/django-oscar,elliotthill/django-oscar,solarissmoke/django-oscar,Jannes123/django-oscar,bnprk/django-oscar,adamend/django-oscar,michaelkuty/django-oscar,okfish/django-oscar,saadatqadri/django-oscar,ahmetdaglarbas/e-commerce,itbabu/django-oscar,jinnykoo/wuyisj,jinnykoo/wuyisj.com,binarydud/django-oscar,marcoantoniooliveira/labweb,jinnykoo/wuyisj,pasqualguerrero/django-oscar,binarydud/django-oscar,Jannes123/django-oscar,jinnykoo/wuyisj.com,bnprk/django-oscar,eddiep1101/django-oscar,kapari/django-oscar,adamend/django-oscar,eddiep1101/django-oscar,dongguangming/django-oscar,Idematica/django-oscar,sasha0/django-oscar,pdonadeo/django-oscar,eddiep1101/django-oscar,thechampanurag/django-oscar,nickpack/django-oscar,lijoantony/django-oscar,monikasulik/django-oscar,bschuon/django-oscar,machtfit/django-oscar,QLGu/django-oscar,amirrpp/django-oscar,jmt4/django-oscar,anentropic/django-oscar,monikasulik/django-oscar,faratro/django-oscar,jinnykoo/wuyisj.com,anentropic/django-oscar,DrOctogon/unwash_ecom,MatthewWilkes/django-oscar,saadatqadri/django-oscar,faratro/django-oscar,jmt4/django-oscar,mexeniz/django-oscar,michaelkuty/django-oscar,michaelkuty/django-oscar,itbabu/django-oscar,jinnykoo/christmas,kapari/django-oscar,monikasulik/django-oscar,ademuk/django-oscar,makielab/django-oscar,dongguangming/django-oscar,WadeYuChen/django-oscar,solarissmoke/django-oscar,faratro/django-oscar,sonofatailor/django-oscar,ahmetdaglarbas/e-commerce,vovanbo/django-oscar,kapari/django-oscar,dongguangming/django-oscar,sonofatailor/django-oscar,django-oscar/django-oscar,okfish/django-oscar,WillisXChen/django-oscar,amirrpp/django-oscar,lijoantony/django-oscar,pasqualguerrero/django-oscar,ademuk/django-oscar,Bogh/django-oscar,jlmadurga/django-oscar,lijoantony/django-oscar
from django.utils.timezone import now from django.db import models class ActiveOfferManager(models.Manager): """ For searching/creating offers within their date range """ def get_query_set(self): cutoff = now() return super(ActiveOfferManager, self).get_query_set().filter( - models.Q(end_date__gte=today) | models.Q(end_date=None), + models.Q(end_datetime__gte=cutoff) | models.Q(end_datetime=None), - start_date__lte=today) + start_datetime__lte=cutoff)
Fix bug in offer manager with new datetimes
## Code Before: from django.utils.timezone import now from django.db import models class ActiveOfferManager(models.Manager): """ For searching/creating offers within their date range """ def get_query_set(self): cutoff = now() return super(ActiveOfferManager, self).get_query_set().filter( models.Q(end_date__gte=today) | models.Q(end_date=None), start_date__lte=today) ## Instruction: Fix bug in offer manager with new datetimes ## Code After: from django.utils.timezone import now from django.db import models class ActiveOfferManager(models.Manager): """ For searching/creating offers within their date range """ def get_query_set(self): cutoff = now() return super(ActiveOfferManager, self).get_query_set().filter( models.Q(end_datetime__gte=cutoff) | models.Q(end_datetime=None), start_datetime__lte=cutoff)
from django.utils.timezone import now from django.db import models class ActiveOfferManager(models.Manager): """ For searching/creating offers within their date range """ def get_query_set(self): cutoff = now() return super(ActiveOfferManager, self).get_query_set().filter( - models.Q(end_date__gte=today) | models.Q(end_date=None), ? ^^^ + models.Q(end_datetime__gte=cutoff) | models.Q(end_datetime=None), ? ++++ ++ ^^ ++++ - start_date__lte=today) ? ^^^ + start_datetime__lte=cutoff) ? ++++ ++ ^^
ce0b30775aedce3be7f25e61ec751116bb192cdc
src/hamcrest/core/core/__init__.py
src/hamcrest/core/core/__init__.py
from __future__ import absolute_import """Fundamental matchers of objects and values, and composite matchers.""" from hamcrest.core.core.allof import all_of from hamcrest.core.core.anyof import any_of from hamcrest.core.core.described_as import described_as from hamcrest.core.core.is_ import is_ from hamcrest.core.core.isanything import anything from hamcrest.core.core.isequal import equal_to from hamcrest.core.core.isinstanceof import instance_of from hamcrest.core.core.isnone import none, not_none from hamcrest.core.core.isnot import is_not from hamcrest.core.core.issame import same_instance from hamcrest.core.core.raises import calling, raises __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt"
from __future__ import absolute_import """Fundamental matchers of objects and values, and composite matchers.""" from hamcrest.core.core.allof import all_of from hamcrest.core.core.anyof import any_of from hamcrest.core.core.described_as import described_as from hamcrest.core.core.is_ import is_ from hamcrest.core.core.isanything import anything from hamcrest.core.core.isequal import equal_to from hamcrest.core.core.isinstanceof import instance_of from hamcrest.core.core.isnone import none, not_none from hamcrest.core.core.isnot import is_not not_ = is_not from hamcrest.core.core.issame import same_instance from hamcrest.core.core.raises import calling, raises __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt"
Add not_ alias of is_not for better readability of negations
Add not_ alias of is_not for better readability of negations Example: >> assert_that(alist, is_not(has_item(item))) can be >>assert_that(alist, not_(has_item(item)))
Python
bsd-3-clause
nitishr/PyHamcrest,msabramo/PyHamcrest,msabramo/PyHamcrest,nitishr/PyHamcrest
from __future__ import absolute_import """Fundamental matchers of objects and values, and composite matchers.""" from hamcrest.core.core.allof import all_of from hamcrest.core.core.anyof import any_of from hamcrest.core.core.described_as import described_as from hamcrest.core.core.is_ import is_ from hamcrest.core.core.isanything import anything from hamcrest.core.core.isequal import equal_to from hamcrest.core.core.isinstanceof import instance_of from hamcrest.core.core.isnone import none, not_none from hamcrest.core.core.isnot import is_not + not_ = is_not from hamcrest.core.core.issame import same_instance from hamcrest.core.core.raises import calling, raises __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt"
Add not_ alias of is_not for better readability of negations
## Code Before: from __future__ import absolute_import """Fundamental matchers of objects and values, and composite matchers.""" from hamcrest.core.core.allof import all_of from hamcrest.core.core.anyof import any_of from hamcrest.core.core.described_as import described_as from hamcrest.core.core.is_ import is_ from hamcrest.core.core.isanything import anything from hamcrest.core.core.isequal import equal_to from hamcrest.core.core.isinstanceof import instance_of from hamcrest.core.core.isnone import none, not_none from hamcrest.core.core.isnot import is_not from hamcrest.core.core.issame import same_instance from hamcrest.core.core.raises import calling, raises __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" ## Instruction: Add not_ alias of is_not for better readability of negations ## Code After: from __future__ import absolute_import """Fundamental matchers of objects and values, and composite matchers.""" from hamcrest.core.core.allof import all_of from hamcrest.core.core.anyof import any_of from hamcrest.core.core.described_as import described_as from hamcrest.core.core.is_ import is_ from hamcrest.core.core.isanything import anything from hamcrest.core.core.isequal import equal_to from hamcrest.core.core.isinstanceof import instance_of from hamcrest.core.core.isnone import none, not_none from hamcrest.core.core.isnot import is_not not_ = is_not from hamcrest.core.core.issame import same_instance from hamcrest.core.core.raises import calling, raises __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt"
from __future__ import absolute_import """Fundamental matchers of objects and values, and composite matchers.""" from hamcrest.core.core.allof import all_of from hamcrest.core.core.anyof import any_of from hamcrest.core.core.described_as import described_as from hamcrest.core.core.is_ import is_ from hamcrest.core.core.isanything import anything from hamcrest.core.core.isequal import equal_to from hamcrest.core.core.isinstanceof import instance_of from hamcrest.core.core.isnone import none, not_none from hamcrest.core.core.isnot import is_not + not_ = is_not from hamcrest.core.core.issame import same_instance from hamcrest.core.core.raises import calling, raises __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt"
ffd429281ed6695457304646467a6d9e0a0301a4
src/nyc_trees/apps/core/tasks.py
src/nyc_trees/apps/core/tasks.py
from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from celery import task from django.core.files.storage import default_storage @task(bind=True, max_retries=15, default_retry_delay=2) def wait_for_default_storage_file(self, filename): if default_storage.exists(filename): return filename else: self.retry()
from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from celery import task from django.core.files.storage import default_storage @task(bind=True, max_retries=15, default_retry_delay=2) def wait_for_default_storage_file(self, filename): if default_storage.exists(filename): return filename elif self.request.retries < self.max_retries: self.retry() else: return None
Send RSVP email even if PDF doesn't exist
Send RSVP email even if PDF doesn't exist If the PDF can't be found on the disk after the maximum number of retries, return None, instead of raising an exception. This ensures that the RSVP email notification still sends even without the PDF attachment. Refs #1655
Python
agpl-3.0
azavea/nyc-trees,maurizi/nyc-trees,kdeloach/nyc-trees,azavea/nyc-trees,kdeloach/nyc-trees,azavea/nyc-trees,maurizi/nyc-trees,kdeloach/nyc-trees,kdeloach/nyc-trees,maurizi/nyc-trees,azavea/nyc-trees,kdeloach/nyc-trees,maurizi/nyc-trees,azavea/nyc-trees
from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from celery import task from django.core.files.storage import default_storage @task(bind=True, max_retries=15, default_retry_delay=2) def wait_for_default_storage_file(self, filename): if default_storage.exists(filename): return filename + elif self.request.retries < self.max_retries: + self.retry() else: - self.retry() + return None
Send RSVP email even if PDF doesn't exist
## Code Before: from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from celery import task from django.core.files.storage import default_storage @task(bind=True, max_retries=15, default_retry_delay=2) def wait_for_default_storage_file(self, filename): if default_storage.exists(filename): return filename else: self.retry() ## Instruction: Send RSVP email even if PDF doesn't exist ## Code After: from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from celery import task from django.core.files.storage import default_storage @task(bind=True, max_retries=15, default_retry_delay=2) def wait_for_default_storage_file(self, filename): if default_storage.exists(filename): return filename elif self.request.retries < self.max_retries: self.retry() else: return None
from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from celery import task from django.core.files.storage import default_storage @task(bind=True, max_retries=15, default_retry_delay=2) def wait_for_default_storage_file(self, filename): if default_storage.exists(filename): return filename + elif self.request.retries < self.max_retries: + self.retry() else: - self.retry() + return None
8aea526176592511581ddbeb6f3bb96ce072cc91
wukong/__init__.py
wukong/__init__.py
import logging try: # Python 2.7+ from logging import NullHandler except ImportError: class NullHandler(logging.Handler): def emit(self, record): pass logging.getLogger(__name__).addHandler(NullHandler())
import logging from logging import NullHandler logging.getLogger(__name__).addHandler(NullHandler())
Remove the NullHandler patch because we don't support any python versions that need it
Remove the NullHandler patch because we don't support any python versions that need it
Python
mit
SurveyMonkey/wukong
import logging - try: # Python 2.7+ - from logging import NullHandler + from logging import NullHandler - except ImportError: - class NullHandler(logging.Handler): - def emit(self, record): - pass - logging.getLogger(__name__).addHandler(NullHandler())
Remove the NullHandler patch because we don't support any python versions that need it
## Code Before: import logging try: # Python 2.7+ from logging import NullHandler except ImportError: class NullHandler(logging.Handler): def emit(self, record): pass logging.getLogger(__name__).addHandler(NullHandler()) ## Instruction: Remove the NullHandler patch because we don't support any python versions that need it ## Code After: import logging from logging import NullHandler logging.getLogger(__name__).addHandler(NullHandler())
import logging - try: # Python 2.7+ - from logging import NullHandler ? ---- + from logging import NullHandler - except ImportError: - class NullHandler(logging.Handler): - def emit(self, record): - pass - logging.getLogger(__name__).addHandler(NullHandler())
3a3997b19966560b828efb1699ee29a58cacbfc8
spriteworld/configs/cobra/common.py
spriteworld/configs/cobra/common.py
"""Shared definitions and methods across all COBRA tasks.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from spriteworld import action_spaces from spriteworld import renderers as spriteworld_renderers def action_space(): return action_spaces.SelectMove(scale=0.25, noise_scale=0.05) def renderers(): return { 'image': spriteworld_renderers.PILRenderer( image_size=(64, 64), anti_aliasing=5, color_to_rgb=spriteworld_renderers.color_maps.hsv_to_rgb, ) }
"""Shared definitions and methods across all COBRA tasks.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from spriteworld import action_spaces from spriteworld import renderers as spriteworld_renderers def action_space(): return action_spaces.SelectMove(scale=0.25) def renderers(): return { 'image': spriteworld_renderers.PILRenderer( image_size=(64, 64), anti_aliasing=5, color_to_rgb=spriteworld_renderers.color_maps.hsv_to_rgb, ) }
Remove noise from default COBRA configs.
Remove noise from default COBRA configs. PiperOrigin-RevId: 265733849 Change-Id: Ie0e7c0385497852fd85c769ee85c951542c14463
Python
apache-2.0
deepmind/spriteworld
"""Shared definitions and methods across all COBRA tasks.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from spriteworld import action_spaces from spriteworld import renderers as spriteworld_renderers def action_space(): - return action_spaces.SelectMove(scale=0.25, noise_scale=0.05) + return action_spaces.SelectMove(scale=0.25) def renderers(): return { 'image': spriteworld_renderers.PILRenderer( image_size=(64, 64), anti_aliasing=5, color_to_rgb=spriteworld_renderers.color_maps.hsv_to_rgb, ) }
Remove noise from default COBRA configs.
## Code Before: """Shared definitions and methods across all COBRA tasks.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from spriteworld import action_spaces from spriteworld import renderers as spriteworld_renderers def action_space(): return action_spaces.SelectMove(scale=0.25, noise_scale=0.05) def renderers(): return { 'image': spriteworld_renderers.PILRenderer( image_size=(64, 64), anti_aliasing=5, color_to_rgb=spriteworld_renderers.color_maps.hsv_to_rgb, ) } ## Instruction: Remove noise from default COBRA configs. ## Code After: """Shared definitions and methods across all COBRA tasks.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from spriteworld import action_spaces from spriteworld import renderers as spriteworld_renderers def action_space(): return action_spaces.SelectMove(scale=0.25) def renderers(): return { 'image': spriteworld_renderers.PILRenderer( image_size=(64, 64), anti_aliasing=5, color_to_rgb=spriteworld_renderers.color_maps.hsv_to_rgb, ) }
"""Shared definitions and methods across all COBRA tasks.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from spriteworld import action_spaces from spriteworld import renderers as spriteworld_renderers def action_space(): - return action_spaces.SelectMove(scale=0.25, noise_scale=0.05) ? ------------------ + return action_spaces.SelectMove(scale=0.25) def renderers(): return { 'image': spriteworld_renderers.PILRenderer( image_size=(64, 64), anti_aliasing=5, color_to_rgb=spriteworld_renderers.color_maps.hsv_to_rgb, ) }
5dcdfa510e62d754bce6270286e42a76b37c23c4
inpassing/worker/util.py
inpassing/worker/util.py
from datetime import datetime, timezone DATE_FMT = '%Y-%m-%d' def date_to_str(day): return day.strftime(DATE_FMT) def str_to_date(s): return datetime.strptime(s, DATE_FMT).replace(tzinfo=timezone.utc)
from datetime import datetime, timezone DATE_FMT = '%Y-%m-%d' def date_to_str(day): return day.strftime(DATE_FMT) def str_to_date(s, tz=None): ret = datetime.strptime(s, DATE_FMT) if tz: return tz.localize(ret) else: return ret
Support use of local timezones when parsing date strings
Support use of local timezones when parsing date strings
Python
mit
lukesanantonio/inpassing-backend,lukesanantonio/inpassing-backend
from datetime import datetime, timezone DATE_FMT = '%Y-%m-%d' def date_to_str(day): return day.strftime(DATE_FMT) - def str_to_date(s): + def str_to_date(s, tz=None): - return datetime.strptime(s, DATE_FMT).replace(tzinfo=timezone.utc) + ret = datetime.strptime(s, DATE_FMT) + if tz: + return tz.localize(ret) + else: + return ret
Support use of local timezones when parsing date strings
## Code Before: from datetime import datetime, timezone DATE_FMT = '%Y-%m-%d' def date_to_str(day): return day.strftime(DATE_FMT) def str_to_date(s): return datetime.strptime(s, DATE_FMT).replace(tzinfo=timezone.utc) ## Instruction: Support use of local timezones when parsing date strings ## Code After: from datetime import datetime, timezone DATE_FMT = '%Y-%m-%d' def date_to_str(day): return day.strftime(DATE_FMT) def str_to_date(s, tz=None): ret = datetime.strptime(s, DATE_FMT) if tz: return tz.localize(ret) else: return ret
from datetime import datetime, timezone DATE_FMT = '%Y-%m-%d' def date_to_str(day): return day.strftime(DATE_FMT) - def str_to_date(s): + def str_to_date(s, tz=None): ? +++++++++ - return datetime.strptime(s, DATE_FMT).replace(tzinfo=timezone.utc) + ret = datetime.strptime(s, DATE_FMT) + if tz: + return tz.localize(ret) + else: + return ret
0078bb14b85df519744371df89e243822a86ed4c
generate.py
generate.py
import random import sys population = bytes([i for i in range(256)]) if sys.argv[1] == 'reflector': popset = set(population) buffer = [None for i in range(256)] for i in range(128): x, y = random.sample(popset, 2) popset.remove(x) popset.remove(y) buffer[x] = y buffer[y] = x print(bytes(buffer)) elif sys.argv[1] == 'rotor': print(bytes(random.sample(population, 256)))
import random import sys population = bytes([i for i in range(256)]) if sys.argv[1] == 'reflector': print('WIRING') popset = set(population) buffer = [None for i in range(256)] for i in range(128): x, y = random.sample(popset, 2) popset.remove(x) popset.remove(y) buffer[x] = y buffer[y] = x print(bytes(buffer)) elif sys.argv[1] == 'rotor': print('WIRING') print(bytes(random.sample(population, 256))) print('NOTCHES') print(random.sample(population, 3))
Add a little more detail to the generator
Add a little more detail to the generator
Python
mit
spgill/bitnigma
import random import sys population = bytes([i for i in range(256)]) if sys.argv[1] == 'reflector': + print('WIRING') popset = set(population) buffer = [None for i in range(256)] for i in range(128): x, y = random.sample(popset, 2) popset.remove(x) popset.remove(y) buffer[x] = y buffer[y] = x print(bytes(buffer)) elif sys.argv[1] == 'rotor': + print('WIRING') print(bytes(random.sample(population, 256))) + print('NOTCHES') + print(random.sample(population, 3))
Add a little more detail to the generator
## Code Before: import random import sys population = bytes([i for i in range(256)]) if sys.argv[1] == 'reflector': popset = set(population) buffer = [None for i in range(256)] for i in range(128): x, y = random.sample(popset, 2) popset.remove(x) popset.remove(y) buffer[x] = y buffer[y] = x print(bytes(buffer)) elif sys.argv[1] == 'rotor': print(bytes(random.sample(population, 256))) ## Instruction: Add a little more detail to the generator ## Code After: import random import sys population = bytes([i for i in range(256)]) if sys.argv[1] == 'reflector': print('WIRING') popset = set(population) buffer = [None for i in range(256)] for i in range(128): x, y = random.sample(popset, 2) popset.remove(x) popset.remove(y) buffer[x] = y buffer[y] = x print(bytes(buffer)) elif sys.argv[1] == 'rotor': print('WIRING') print(bytes(random.sample(population, 256))) print('NOTCHES') print(random.sample(population, 3))
import random import sys population = bytes([i for i in range(256)]) if sys.argv[1] == 'reflector': + print('WIRING') popset = set(population) buffer = [None for i in range(256)] for i in range(128): x, y = random.sample(popset, 2) popset.remove(x) popset.remove(y) buffer[x] = y buffer[y] = x print(bytes(buffer)) elif sys.argv[1] == 'rotor': + print('WIRING') print(bytes(random.sample(population, 256))) + print('NOTCHES') + print(random.sample(population, 3))
a02ed17f79bba6e948c3b38d70ed6c2adbf1d0eb
py/tables.py
py/tables.py
import sqlalchemy import sqlalchemy.ext.declarative Base = sqlalchemy.ext.declarative.declarative_base() class Post(Base): __tablename__ = "posts" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) title = sqlalchemy.Column(sqlalchemy.String) body = sqlalchemy.Column(sqlalchemy.Text,) #Should be text to avoid length problems time_posted = sqlalchemy.Column(sqlalchemy.Time) class Tag(Base): __tablename__ = "tags" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) name = sqlalchemy.Column(sqlalchemy.Text) #Used to relate tags to posts. class TagRelation(Base): __tablename__ = "tag_relation" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) post_id = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey(Post.__table__.columns.id)) tag_id = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey(Tag.__table__.columns.id)) #The Following tables will only be the ones added to the database ALL_TABLES = [Post, Tag, TagRelation]
import sqlalchemy import sqlalchemy.ext.declarative Base = sqlalchemy.ext.declarative.declarative_base() class Post(Base): __tablename__ = "posts" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) title = sqlalchemy.Column(sqlalchemy.String) body = sqlalchemy.Column(sqlalchemy.Text,) #Should be text to avoid length problems time_posted = sqlalchemy.Column(sqlalchemy.DateTime) author = sqlalchemy.Column(sqlalchemy.String) class Tag(Base): __tablename__ = "tags" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) name = sqlalchemy.Column(sqlalchemy.Text) #Used to relate tags to posts. class TagRelation(Base): __tablename__ = "tag_relation" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) post_id = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey(Post.__table__.columns.id)) tag_id = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey(Tag.__table__.columns.id)) #The Following tables will only be the ones added to the database ALL_TABLES = [Post, Tag, TagRelation]
Change type of time_posted to DATETIME and add author column
Change type of time_posted to DATETIME and add author column
Python
mit
ollien/Timpani,ollien/Timpani,ollien/Timpani
import sqlalchemy import sqlalchemy.ext.declarative Base = sqlalchemy.ext.declarative.declarative_base() class Post(Base): __tablename__ = "posts" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) title = sqlalchemy.Column(sqlalchemy.String) body = sqlalchemy.Column(sqlalchemy.Text,) #Should be text to avoid length problems - time_posted = sqlalchemy.Column(sqlalchemy.Time) + time_posted = sqlalchemy.Column(sqlalchemy.DateTime) + author = sqlalchemy.Column(sqlalchemy.String) class Tag(Base): __tablename__ = "tags" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) name = sqlalchemy.Column(sqlalchemy.Text) #Used to relate tags to posts. class TagRelation(Base): __tablename__ = "tag_relation" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) post_id = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey(Post.__table__.columns.id)) tag_id = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey(Tag.__table__.columns.id)) #The Following tables will only be the ones added to the database ALL_TABLES = [Post, Tag, TagRelation]
Change type of time_posted to DATETIME and add author column
## Code Before: import sqlalchemy import sqlalchemy.ext.declarative Base = sqlalchemy.ext.declarative.declarative_base() class Post(Base): __tablename__ = "posts" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) title = sqlalchemy.Column(sqlalchemy.String) body = sqlalchemy.Column(sqlalchemy.Text,) #Should be text to avoid length problems time_posted = sqlalchemy.Column(sqlalchemy.Time) class Tag(Base): __tablename__ = "tags" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) name = sqlalchemy.Column(sqlalchemy.Text) #Used to relate tags to posts. class TagRelation(Base): __tablename__ = "tag_relation" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) post_id = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey(Post.__table__.columns.id)) tag_id = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey(Tag.__table__.columns.id)) #The Following tables will only be the ones added to the database ALL_TABLES = [Post, Tag, TagRelation] ## Instruction: Change type of time_posted to DATETIME and add author column ## Code After: import sqlalchemy import sqlalchemy.ext.declarative Base = sqlalchemy.ext.declarative.declarative_base() class Post(Base): __tablename__ = "posts" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) title = sqlalchemy.Column(sqlalchemy.String) body = sqlalchemy.Column(sqlalchemy.Text,) #Should be text to avoid length problems time_posted = sqlalchemy.Column(sqlalchemy.DateTime) author = sqlalchemy.Column(sqlalchemy.String) class Tag(Base): __tablename__ = "tags" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) name = sqlalchemy.Column(sqlalchemy.Text) #Used to relate tags to posts. class TagRelation(Base): __tablename__ = "tag_relation" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) post_id = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey(Post.__table__.columns.id)) tag_id = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey(Tag.__table__.columns.id)) #The Following tables will only be the ones added to the database ALL_TABLES = [Post, Tag, TagRelation]
import sqlalchemy import sqlalchemy.ext.declarative Base = sqlalchemy.ext.declarative.declarative_base() class Post(Base): __tablename__ = "posts" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) title = sqlalchemy.Column(sqlalchemy.String) body = sqlalchemy.Column(sqlalchemy.Text,) #Should be text to avoid length problems - time_posted = sqlalchemy.Column(sqlalchemy.Time) + time_posted = sqlalchemy.Column(sqlalchemy.DateTime) ? ++++ + author = sqlalchemy.Column(sqlalchemy.String) class Tag(Base): __tablename__ = "tags" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) name = sqlalchemy.Column(sqlalchemy.Text) #Used to relate tags to posts. class TagRelation(Base): __tablename__ = "tag_relation" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) post_id = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey(Post.__table__.columns.id)) tag_id = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey(Tag.__table__.columns.id)) #The Following tables will only be the ones added to the database ALL_TABLES = [Post, Tag, TagRelation]
b2cac05be3f6c510edfaf1ae478fabdcf06fd19a
mgsv_names.py
mgsv_names.py
import random global adjectives, animals, rares with open('adjectives.txt') as f: adjectives = f.readlines() with open('animals.txt') as f: animals = f.readlines() with open('rares.txt') as f: rares = f.readlines() uncommons = { # Adjectives: 'master': 'miller', 'raging': 'bull', 'hidden': 'dragon', 'humming': 'bird', 'spicy': 'sandworm', # Animals: 'ocelot': 'revolver', 'lion': 'snooping', 'tiger': 'crouching', 'hippo': 'hungry', 'falcon': 'punching', } def get_name(): adj = random.choice(adjectives).strip() anim = random.choice(animals).strip() r = random.random() if r < 0.001 or r >= 0.999: return random.choice(rares).strip() elif r < 0.3 and adj in uncommons: return ' '.join((adj, uncommons[adj])) elif r >= 0.7 and anim in uncommons: return ' '.join((uncommons[anim], anim)) return ' '.join((adj, anim)) if __name__ == '__main__': print(get_name())
import random, os global adjectives, animals, rares with open(os.path.join(os.path.dirname(__file__), 'adjectives.txt')) as f: adjectives = f.readlines() with open(os.path.join(os.path.dirname(__file__), 'animals.txt')) as f: animals = f.readlines() with open(os.path.join(os.path.dirname(__file__), 'rares.txt')) as f: rares = f.readlines() uncommons = { # Adjectives: 'master': 'miller', 'raging': 'bull', 'hidden': 'dragon', 'humming': 'bird', 'spicy': 'sandworm', # Animals: 'ocelot': 'revolver', 'lion': 'snooping', 'tiger': 'crouching', 'hippo': 'hungry', 'falcon': 'punching', } def generate_name(): adj = random.choice(adjectives).strip() anim = random.choice(animals).strip() r = random.random() if r < 0.001 or r >= 0.999: return random.choice(rares).strip() elif r < 0.3 and adj in uncommons: return ' '.join((adj, uncommons[adj])) elif r >= 0.7 and anim in uncommons: return ' '.join((uncommons[anim], anim)) return ' '.join((adj, anim)) if __name__ == '__main__': print(generate_name())
Load text files from the same dir as the script.
Load text files from the same dir as the script. Also renamed our name generator.
Python
unlicense
rotated8/mgsv_names
- import random + import random, os global adjectives, animals, rares - with open('adjectives.txt') as f: + with open(os.path.join(os.path.dirname(__file__), 'adjectives.txt')) as f: adjectives = f.readlines() - with open('animals.txt') as f: + with open(os.path.join(os.path.dirname(__file__), 'animals.txt')) as f: animals = f.readlines() - with open('rares.txt') as f: + with open(os.path.join(os.path.dirname(__file__), 'rares.txt')) as f: rares = f.readlines() uncommons = { # Adjectives: 'master': 'miller', 'raging': 'bull', 'hidden': 'dragon', 'humming': 'bird', 'spicy': 'sandworm', # Animals: 'ocelot': 'revolver', 'lion': 'snooping', 'tiger': 'crouching', 'hippo': 'hungry', 'falcon': 'punching', } - def get_name(): + def generate_name(): adj = random.choice(adjectives).strip() anim = random.choice(animals).strip() r = random.random() if r < 0.001 or r >= 0.999: return random.choice(rares).strip() elif r < 0.3 and adj in uncommons: return ' '.join((adj, uncommons[adj])) elif r >= 0.7 and anim in uncommons: return ' '.join((uncommons[anim], anim)) return ' '.join((adj, anim)) if __name__ == '__main__': - print(get_name()) + print(generate_name())
Load text files from the same dir as the script.
## Code Before: import random global adjectives, animals, rares with open('adjectives.txt') as f: adjectives = f.readlines() with open('animals.txt') as f: animals = f.readlines() with open('rares.txt') as f: rares = f.readlines() uncommons = { # Adjectives: 'master': 'miller', 'raging': 'bull', 'hidden': 'dragon', 'humming': 'bird', 'spicy': 'sandworm', # Animals: 'ocelot': 'revolver', 'lion': 'snooping', 'tiger': 'crouching', 'hippo': 'hungry', 'falcon': 'punching', } def get_name(): adj = random.choice(adjectives).strip() anim = random.choice(animals).strip() r = random.random() if r < 0.001 or r >= 0.999: return random.choice(rares).strip() elif r < 0.3 and adj in uncommons: return ' '.join((adj, uncommons[adj])) elif r >= 0.7 and anim in uncommons: return ' '.join((uncommons[anim], anim)) return ' '.join((adj, anim)) if __name__ == '__main__': print(get_name()) ## Instruction: Load text files from the same dir as the script. ## Code After: import random, os global adjectives, animals, rares with open(os.path.join(os.path.dirname(__file__), 'adjectives.txt')) as f: adjectives = f.readlines() with open(os.path.join(os.path.dirname(__file__), 'animals.txt')) as f: animals = f.readlines() with open(os.path.join(os.path.dirname(__file__), 'rares.txt')) as f: rares = f.readlines() uncommons = { # Adjectives: 'master': 'miller', 'raging': 'bull', 'hidden': 'dragon', 'humming': 'bird', 'spicy': 'sandworm', # Animals: 'ocelot': 'revolver', 'lion': 'snooping', 'tiger': 'crouching', 'hippo': 'hungry', 'falcon': 'punching', } def generate_name(): adj = random.choice(adjectives).strip() anim = random.choice(animals).strip() r = random.random() if r < 0.001 or r >= 0.999: return random.choice(rares).strip() elif r < 0.3 and adj in uncommons: return ' '.join((adj, uncommons[adj])) elif r >= 0.7 and anim in uncommons: return ' '.join((uncommons[anim], anim)) return ' '.join((adj, anim)) if __name__ == '__main__': print(generate_name())
- import random + import random, os ? ++++ global adjectives, animals, rares - with open('adjectives.txt') as f: + with open(os.path.join(os.path.dirname(__file__), 'adjectives.txt')) as f: adjectives = f.readlines() - with open('animals.txt') as f: + with open(os.path.join(os.path.dirname(__file__), 'animals.txt')) as f: animals = f.readlines() - with open('rares.txt') as f: + with open(os.path.join(os.path.dirname(__file__), 'rares.txt')) as f: rares = f.readlines() uncommons = { # Adjectives: 'master': 'miller', 'raging': 'bull', 'hidden': 'dragon', 'humming': 'bird', 'spicy': 'sandworm', # Animals: 'ocelot': 'revolver', 'lion': 'snooping', 'tiger': 'crouching', 'hippo': 'hungry', 'falcon': 'punching', } - def get_name(): + def generate_name(): ? ++++ + adj = random.choice(adjectives).strip() anim = random.choice(animals).strip() r = random.random() if r < 0.001 or r >= 0.999: return random.choice(rares).strip() elif r < 0.3 and adj in uncommons: return ' '.join((adj, uncommons[adj])) elif r >= 0.7 and anim in uncommons: return ' '.join((uncommons[anim], anim)) return ' '.join((adj, anim)) if __name__ == '__main__': - print(get_name()) + print(generate_name()) ? ++++ +
0101bdc12b00ecb0a1a208f6a1f49e670a5362a6
user_profile/models.py
user_profile/models.py
from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User) description = models.TextField(max_length=3000) picture = models.ImageField(blank=True, upload_to='media/profiles/') thumbnail = models.ImageField( upload_to='media/profiles/thumb/', max_length=500, null=True, blank=True ) follows = models.ManyToManyField("self", blank=True)
from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User) description = models.TextField(max_length=3000) picture = models.ImageField(blank=True, upload_to='media/profiles/') thumbnail = models.ImageField( upload_to='media/profiles/thumb/', max_length=500, null=True, blank=True ) follows = models.ManyToManyField("self", blank=True) # Create UserProfile when user is created @receiver(post_save, sender=User) def create_profile(sender, **kwargs): user = kwargs["instance"] if kwargs["created"]: profile = UserProfile(user=user) profile.save()
Create user_profile automatically after user creation
Create user_profile automatically after user creation
Python
mit
DeWaster/Tviserrys,DeWaster/Tviserrys
from django.db import models from django.contrib.auth.models import User + from django.db.models.signals import post_save + from django.dispatch import receiver + from django.contrib.auth.models import User + class UserProfile(models.Model): user = models.OneToOneField(User) description = models.TextField(max_length=3000) picture = models.ImageField(blank=True, upload_to='media/profiles/') thumbnail = models.ImageField( upload_to='media/profiles/thumb/', max_length=500, null=True, blank=True ) follows = models.ManyToManyField("self", blank=True) - - + # Create UserProfile when user is created + @receiver(post_save, sender=User) + def create_profile(sender, **kwargs): + user = kwargs["instance"] + if kwargs["created"]: + profile = UserProfile(user=user) + profile.save()
Create user_profile automatically after user creation
## Code Before: from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User) description = models.TextField(max_length=3000) picture = models.ImageField(blank=True, upload_to='media/profiles/') thumbnail = models.ImageField( upload_to='media/profiles/thumb/', max_length=500, null=True, blank=True ) follows = models.ManyToManyField("self", blank=True) ## Instruction: Create user_profile automatically after user creation ## Code After: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User) description = models.TextField(max_length=3000) picture = models.ImageField(blank=True, upload_to='media/profiles/') thumbnail = models.ImageField( upload_to='media/profiles/thumb/', max_length=500, null=True, blank=True ) follows = models.ManyToManyField("self", blank=True) # Create UserProfile when user is created @receiver(post_save, sender=User) def create_profile(sender, **kwargs): user = kwargs["instance"] if kwargs["created"]: profile = UserProfile(user=user) profile.save()
from django.db import models from django.contrib.auth.models import User + from django.db.models.signals import post_save + from django.dispatch import receiver + from django.contrib.auth.models import User + class UserProfile(models.Model): user = models.OneToOneField(User) description = models.TextField(max_length=3000) picture = models.ImageField(blank=True, upload_to='media/profiles/') thumbnail = models.ImageField( upload_to='media/profiles/thumb/', max_length=500, null=True, blank=True ) follows = models.ManyToManyField("self", blank=True) - + # Create UserProfile when user is created + @receiver(post_save, sender=User) + def create_profile(sender, **kwargs): + user = kwargs["instance"] + if kwargs["created"]: + profile = UserProfile(user=user) + profile.save()
111019266e15f59a358c0842815cd7368d89982f
rbm2m/views/public.py
rbm2m/views/public.py
import logging from flask import Blueprint, render_template, request, send_from_directory, current_app from ..webapp import db from ..action import export_manager, genre_manager, exporter bp = Blueprint('public', __name__) logger = logging.getLogger(__name__) @bp.route('/yml') def yml(): """ YML export endpoint """ exp = exporter.YMLExporter(db.session) exp.log_export(request.remote_addr, request.user_agent) ctx = { 'generation_date': exp.generation_date(), 'genres': exp.category_list(), 'offers': exp.offers() } return render_template('yml.xml', **ctx) @bp.route('/table') def table(): """ Table export endpoint """ exp = exporter.TableExporter(db.session) exp.log_export(request.remote_addr, request.user_agent) ctx = { 'genres': exp.category_list(), 'rows': exp.rows() } return render_template('table.html', **ctx) @bp.route('/media/<path:path>') def serve_media(path): return send_from_directory(current_app.config['MEDIA_DIR'], path)
import logging from flask import Blueprint, render_template, request, send_from_directory, current_app from ..webapp import db from ..action import export_manager, genre_manager, exporter bp = Blueprint('public', __name__) logger = logging.getLogger(__name__) @bp.route('/yml') def yml(): """ YML export endpoint """ exp = exporter.YMLExporter(db.session) exp.log_export(client_ip(), request.user_agent) ctx = { 'generation_date': exp.generation_date(), 'genres': exp.category_list(), 'offers': exp.offers() } return render_template('yml.xml', **ctx) @bp.route('/table') def table(): """ Table export endpoint """ exp = exporter.TableExporter(db.session) exp.log_export(request.remote_addr, request.user_agent) ctx = { 'genres': exp.category_list(), 'rows': exp.rows() } return render_template('table.html', **ctx) @bp.route('/media/<path:path>') def serve_media(path): return send_from_directory(current_app.config['MEDIA_DIR'], path) def client_ip(): """ Returns client ip address """ if 'HTTP_X_REAL_IP' in request.environ: return request.environ['HTTP_X_REAL_IP'] return request.remote_addr
Use HTTP_X_REAL_IP to determine client ip address
Use HTTP_X_REAL_IP to determine client ip address
Python
apache-2.0
notapresent/rbm2m,notapresent/rbm2m
import logging from flask import Blueprint, render_template, request, send_from_directory, current_app from ..webapp import db from ..action import export_manager, genre_manager, exporter bp = Blueprint('public', __name__) logger = logging.getLogger(__name__) @bp.route('/yml') def yml(): """ YML export endpoint """ exp = exporter.YMLExporter(db.session) - exp.log_export(request.remote_addr, request.user_agent) + exp.log_export(client_ip(), request.user_agent) ctx = { 'generation_date': exp.generation_date(), 'genres': exp.category_list(), 'offers': exp.offers() } return render_template('yml.xml', **ctx) @bp.route('/table') def table(): """ Table export endpoint """ exp = exporter.TableExporter(db.session) exp.log_export(request.remote_addr, request.user_agent) ctx = { 'genres': exp.category_list(), 'rows': exp.rows() } return render_template('table.html', **ctx) @bp.route('/media/<path:path>') def serve_media(path): return send_from_directory(current_app.config['MEDIA_DIR'], path) + + def client_ip(): + """ + Returns client ip address + """ + if 'HTTP_X_REAL_IP' in request.environ: + return request.environ['HTTP_X_REAL_IP'] + + return request.remote_addr +
Use HTTP_X_REAL_IP to determine client ip address
## Code Before: import logging from flask import Blueprint, render_template, request, send_from_directory, current_app from ..webapp import db from ..action import export_manager, genre_manager, exporter bp = Blueprint('public', __name__) logger = logging.getLogger(__name__) @bp.route('/yml') def yml(): """ YML export endpoint """ exp = exporter.YMLExporter(db.session) exp.log_export(request.remote_addr, request.user_agent) ctx = { 'generation_date': exp.generation_date(), 'genres': exp.category_list(), 'offers': exp.offers() } return render_template('yml.xml', **ctx) @bp.route('/table') def table(): """ Table export endpoint """ exp = exporter.TableExporter(db.session) exp.log_export(request.remote_addr, request.user_agent) ctx = { 'genres': exp.category_list(), 'rows': exp.rows() } return render_template('table.html', **ctx) @bp.route('/media/<path:path>') def serve_media(path): return send_from_directory(current_app.config['MEDIA_DIR'], path) ## Instruction: Use HTTP_X_REAL_IP to determine client ip address ## Code After: import logging from flask import Blueprint, render_template, request, send_from_directory, current_app from ..webapp import db from ..action import export_manager, genre_manager, exporter bp = Blueprint('public', __name__) logger = logging.getLogger(__name__) @bp.route('/yml') def yml(): """ YML export endpoint """ exp = exporter.YMLExporter(db.session) exp.log_export(client_ip(), request.user_agent) ctx = { 'generation_date': exp.generation_date(), 'genres': exp.category_list(), 'offers': exp.offers() } return render_template('yml.xml', **ctx) @bp.route('/table') def table(): """ Table export endpoint """ exp = exporter.TableExporter(db.session) exp.log_export(request.remote_addr, request.user_agent) ctx = { 'genres': exp.category_list(), 'rows': exp.rows() } return render_template('table.html', **ctx) @bp.route('/media/<path:path>') def serve_media(path): return send_from_directory(current_app.config['MEDIA_DIR'], path) def client_ip(): """ Returns client ip address """ if 'HTTP_X_REAL_IP' in request.environ: return request.environ['HTTP_X_REAL_IP'] return request.remote_addr
import logging from flask import Blueprint, render_template, request, send_from_directory, current_app from ..webapp import db from ..action import export_manager, genre_manager, exporter bp = Blueprint('public', __name__) logger = logging.getLogger(__name__) @bp.route('/yml') def yml(): """ YML export endpoint """ exp = exporter.YMLExporter(db.session) - exp.log_export(request.remote_addr, request.user_agent) ? ^ ^^^^ ------- ^^^^ + exp.log_export(client_ip(), request.user_agent) ? ^^^ ^ ^^^^ ctx = { 'generation_date': exp.generation_date(), 'genres': exp.category_list(), 'offers': exp.offers() } return render_template('yml.xml', **ctx) @bp.route('/table') def table(): """ Table export endpoint """ exp = exporter.TableExporter(db.session) exp.log_export(request.remote_addr, request.user_agent) ctx = { 'genres': exp.category_list(), 'rows': exp.rows() } return render_template('table.html', **ctx) @bp.route('/media/<path:path>') def serve_media(path): return send_from_directory(current_app.config['MEDIA_DIR'], path) + + + def client_ip(): + """ + Returns client ip address + """ + if 'HTTP_X_REAL_IP' in request.environ: + return request.environ['HTTP_X_REAL_IP'] + + return request.remote_addr
c1ae43fd33cd0f8eb3e270907a8ed7e728d1e268
server.py
server.py
import evdev import requests import json import datetime import yaml def main(): config = load_config() dev = evdev.InputDevice(config['device_path']) output_line('Initialized - Capturing device: ' + str(dev)) for event in dev.read_loop(): if event.type == evdev.ecodes.EV_KEY: event = evdev.categorize(event) output_line(event) payload = build_payload(event) output_line('Sending ' + str(payload) + ' to ' + config['post_url']) response = requests.post(config['post_url'], json.dumps(payload)) output_line(response) def build_payload(event): return { 'code': event.scancode, 'key': event.keycode[0] if type(event.keycode) == list else event.keycode, 'state': {0: 'UP', 1: 'DOWN', 2: 'HOLD'}[event.keystate] } def load_config(): with open('config.yml', 'r') as f: return yaml.safe_load(f.read()) def timestamp_s(): return '[' + str(datetime.datetime.now()) + ']' def output_line(string): print(timestamp_s() + ' ' + str(string)) if __name__ == '__main__': main()
import evdev import requests import json import datetime import yaml def main(): config = load_config() dev = evdev.InputDevice(config['device_path']) output_line('Initialized - Capturing device: ' + str(dev)) for event in dev.read_loop(): if event.type == evdev.ecodes.EV_KEY: output_line(event) payload = build_payload(event) output_line('Sending ' + str(payload) + ' to ' + config['post_url']) response = requests.post(config['post_url'], json.dumps(payload)) output_line(response) def build_payload(event): event = evdev.categorize(event) return { 'code': event.scancode, 'key': event.keycode[0] if type(event.keycode) == list else event.keycode, 'state': {0: 'UP', 1: 'DOWN', 2: 'HOLD'}[event.keystate], 'captured_at': datetime.datetime.fromtimestamp(event.event.timestamp()).isoformat() } def load_config(): with open('config.yml', 'r') as f: return yaml.safe_load(f.read()) def timestamp_s(): return '[' + str(datetime.datetime.now()) + ']' def output_line(string): print(timestamp_s() + ' ' + str(string)) if __name__ == '__main__': main()
Add captured_at timestamp to POST payload
Add captured_at timestamp to POST payload Timestamp is in ISO 8601 format
Python
mit
nicolas-fricke/keypost
import evdev import requests import json import datetime import yaml def main(): config = load_config() dev = evdev.InputDevice(config['device_path']) output_line('Initialized - Capturing device: ' + str(dev)) for event in dev.read_loop(): if event.type == evdev.ecodes.EV_KEY: - event = evdev.categorize(event) output_line(event) payload = build_payload(event) output_line('Sending ' + str(payload) + ' to ' + config['post_url']) response = requests.post(config['post_url'], json.dumps(payload)) output_line(response) def build_payload(event): + event = evdev.categorize(event) return { 'code': event.scancode, 'key': event.keycode[0] if type(event.keycode) == list else event.keycode, - 'state': {0: 'UP', 1: 'DOWN', 2: 'HOLD'}[event.keystate] + 'state': {0: 'UP', 1: 'DOWN', 2: 'HOLD'}[event.keystate], + 'captured_at': datetime.datetime.fromtimestamp(event.event.timestamp()).isoformat() } def load_config(): with open('config.yml', 'r') as f: return yaml.safe_load(f.read()) def timestamp_s(): return '[' + str(datetime.datetime.now()) + ']' def output_line(string): print(timestamp_s() + ' ' + str(string)) if __name__ == '__main__': main()
Add captured_at timestamp to POST payload
## Code Before: import evdev import requests import json import datetime import yaml def main(): config = load_config() dev = evdev.InputDevice(config['device_path']) output_line('Initialized - Capturing device: ' + str(dev)) for event in dev.read_loop(): if event.type == evdev.ecodes.EV_KEY: event = evdev.categorize(event) output_line(event) payload = build_payload(event) output_line('Sending ' + str(payload) + ' to ' + config['post_url']) response = requests.post(config['post_url'], json.dumps(payload)) output_line(response) def build_payload(event): return { 'code': event.scancode, 'key': event.keycode[0] if type(event.keycode) == list else event.keycode, 'state': {0: 'UP', 1: 'DOWN', 2: 'HOLD'}[event.keystate] } def load_config(): with open('config.yml', 'r') as f: return yaml.safe_load(f.read()) def timestamp_s(): return '[' + str(datetime.datetime.now()) + ']' def output_line(string): print(timestamp_s() + ' ' + str(string)) if __name__ == '__main__': main() ## Instruction: Add captured_at timestamp to POST payload ## Code After: import evdev import requests import json import datetime import yaml def main(): config = load_config() dev = evdev.InputDevice(config['device_path']) output_line('Initialized - Capturing device: ' + str(dev)) for event in dev.read_loop(): if event.type == evdev.ecodes.EV_KEY: output_line(event) payload = build_payload(event) output_line('Sending ' + str(payload) + ' to ' + config['post_url']) response = requests.post(config['post_url'], json.dumps(payload)) output_line(response) def build_payload(event): event = evdev.categorize(event) return { 'code': event.scancode, 'key': event.keycode[0] if type(event.keycode) == list else event.keycode, 'state': {0: 'UP', 1: 'DOWN', 2: 'HOLD'}[event.keystate], 'captured_at': datetime.datetime.fromtimestamp(event.event.timestamp()).isoformat() } def load_config(): with open('config.yml', 'r') as f: return yaml.safe_load(f.read()) def timestamp_s(): return '[' + str(datetime.datetime.now()) + ']' def output_line(string): print(timestamp_s() + ' ' + str(string)) if __name__ == '__main__': main()
import evdev import requests import json import datetime import yaml def main(): config = load_config() dev = evdev.InputDevice(config['device_path']) output_line('Initialized - Capturing device: ' + str(dev)) for event in dev.read_loop(): if event.type == evdev.ecodes.EV_KEY: - event = evdev.categorize(event) output_line(event) payload = build_payload(event) output_line('Sending ' + str(payload) + ' to ' + config['post_url']) response = requests.post(config['post_url'], json.dumps(payload)) output_line(response) def build_payload(event): + event = evdev.categorize(event) return { 'code': event.scancode, 'key': event.keycode[0] if type(event.keycode) == list else event.keycode, - 'state': {0: 'UP', 1: 'DOWN', 2: 'HOLD'}[event.keystate] + 'state': {0: 'UP', 1: 'DOWN', 2: 'HOLD'}[event.keystate], ? + + 'captured_at': datetime.datetime.fromtimestamp(event.event.timestamp()).isoformat() } def load_config(): with open('config.yml', 'r') as f: return yaml.safe_load(f.read()) def timestamp_s(): return '[' + str(datetime.datetime.now()) + ']' def output_line(string): print(timestamp_s() + ' ' + str(string)) if __name__ == '__main__': main()
5bfc42e4f7c948b1cb895ebec523426be6908829
dockorm/tests/utils.py
dockorm/tests/utils.py
# encoding: utf-8 from __future__ import unicode_literals from os.path import ( dirname, join, ) from six import iteritems from ..container import ( Container, scalar, ) TEST_ORG = 'dockorm_testing' TEST_TAG = 'test' def assert_in_logs(container, line): """ Assert that the given lines are in the container's logs. """ logs = scalar(container.logs(all=True)) validate_dict(logs, {'Logs': line}) def dockerfile_root(path): """ Path to a directory Dockerfile for testing. """ return join( dirname(__file__), 'dockerfiles', path, ) def make_container(image, **kwargs): return Container( image=image, build_path=dockerfile_root(image), organization=TEST_ORG, tag=TEST_TAG, **kwargs ) def volume(path): """ Path to a file relative to the test volumes directory. """ return join( dirname(__file__), 'volumes', path, ) def validate_dict(to_test, expected): """ Recursively validate a dictionary of expectations against another input. Like TestCase.assertDictContainsSubset, but recursive. """ for key, value in iteritems(expected): if isinstance(value, dict): validate_dict(to_test[key], value) else: assert to_test[key] == value
# encoding: utf-8 from __future__ import unicode_literals from os import getenv from os.path import ( dirname, join, ) from six import iteritems from ..container import ( Container, scalar, ) TEST_ORG = 'dockorm_testing' TEST_TAG = 'test' def assert_in_logs(container, line): """ Assert that the given lines are in the container's logs. """ logs = scalar(container.logs(all=True)) validate_dict(logs, {'Logs': line}) def dockerfile_root(path): """ Path to a directory Dockerfile for testing. """ return join( dirname(__file__), 'dockerfiles', path, ) def make_container(image, **kwargs): return Container( image=image, build_path=dockerfile_root(image), organization=TEST_ORG, tag=TEST_TAG, **kwargs ) def volume(path): """ Path to a file relative to the test volumes directory. """ return join( getenv('DOCKORM_TESTS_DIR') or dirname(__file__), 'volumes', path, ) def validate_dict(to_test, expected): """ Recursively validate a dictionary of expectations against another input. Like TestCase.assertDictContainsSubset, but recursive. """ for key, value in iteritems(expected): if isinstance(value, dict): validate_dict(to_test[key], value) else: assert to_test[key] == value
Enable running tests from inside a container
TST: Enable running tests from inside a container by setting an env var for the path to the test volume data on the host
Python
apache-2.0
quantopian/DockORM
# encoding: utf-8 from __future__ import unicode_literals + from os import getenv from os.path import ( dirname, join, ) from six import iteritems from ..container import ( Container, scalar, ) TEST_ORG = 'dockorm_testing' TEST_TAG = 'test' def assert_in_logs(container, line): """ Assert that the given lines are in the container's logs. """ logs = scalar(container.logs(all=True)) validate_dict(logs, {'Logs': line}) def dockerfile_root(path): """ Path to a directory Dockerfile for testing. """ return join( dirname(__file__), 'dockerfiles', path, ) def make_container(image, **kwargs): return Container( image=image, build_path=dockerfile_root(image), organization=TEST_ORG, tag=TEST_TAG, **kwargs ) def volume(path): """ Path to a file relative to the test volumes directory. """ return join( - dirname(__file__), + getenv('DOCKORM_TESTS_DIR') or dirname(__file__), 'volumes', path, ) def validate_dict(to_test, expected): """ Recursively validate a dictionary of expectations against another input. Like TestCase.assertDictContainsSubset, but recursive. """ for key, value in iteritems(expected): if isinstance(value, dict): validate_dict(to_test[key], value) else: assert to_test[key] == value
Enable running tests from inside a container
## Code Before: # encoding: utf-8 from __future__ import unicode_literals from os.path import ( dirname, join, ) from six import iteritems from ..container import ( Container, scalar, ) TEST_ORG = 'dockorm_testing' TEST_TAG = 'test' def assert_in_logs(container, line): """ Assert that the given lines are in the container's logs. """ logs = scalar(container.logs(all=True)) validate_dict(logs, {'Logs': line}) def dockerfile_root(path): """ Path to a directory Dockerfile for testing. """ return join( dirname(__file__), 'dockerfiles', path, ) def make_container(image, **kwargs): return Container( image=image, build_path=dockerfile_root(image), organization=TEST_ORG, tag=TEST_TAG, **kwargs ) def volume(path): """ Path to a file relative to the test volumes directory. """ return join( dirname(__file__), 'volumes', path, ) def validate_dict(to_test, expected): """ Recursively validate a dictionary of expectations against another input. Like TestCase.assertDictContainsSubset, but recursive. """ for key, value in iteritems(expected): if isinstance(value, dict): validate_dict(to_test[key], value) else: assert to_test[key] == value ## Instruction: Enable running tests from inside a container ## Code After: # encoding: utf-8 from __future__ import unicode_literals from os import getenv from os.path import ( dirname, join, ) from six import iteritems from ..container import ( Container, scalar, ) TEST_ORG = 'dockorm_testing' TEST_TAG = 'test' def assert_in_logs(container, line): """ Assert that the given lines are in the container's logs. """ logs = scalar(container.logs(all=True)) validate_dict(logs, {'Logs': line}) def dockerfile_root(path): """ Path to a directory Dockerfile for testing. """ return join( dirname(__file__), 'dockerfiles', path, ) def make_container(image, **kwargs): return Container( image=image, build_path=dockerfile_root(image), organization=TEST_ORG, tag=TEST_TAG, **kwargs ) def volume(path): """ Path to a file relative to the test volumes directory. """ return join( getenv('DOCKORM_TESTS_DIR') or dirname(__file__), 'volumes', path, ) def validate_dict(to_test, expected): """ Recursively validate a dictionary of expectations against another input. Like TestCase.assertDictContainsSubset, but recursive. """ for key, value in iteritems(expected): if isinstance(value, dict): validate_dict(to_test[key], value) else: assert to_test[key] == value
# encoding: utf-8 from __future__ import unicode_literals + from os import getenv from os.path import ( dirname, join, ) from six import iteritems from ..container import ( Container, scalar, ) TEST_ORG = 'dockorm_testing' TEST_TAG = 'test' def assert_in_logs(container, line): """ Assert that the given lines are in the container's logs. """ logs = scalar(container.logs(all=True)) validate_dict(logs, {'Logs': line}) def dockerfile_root(path): """ Path to a directory Dockerfile for testing. """ return join( dirname(__file__), 'dockerfiles', path, ) def make_container(image, **kwargs): return Container( image=image, build_path=dockerfile_root(image), organization=TEST_ORG, tag=TEST_TAG, **kwargs ) def volume(path): """ Path to a file relative to the test volumes directory. """ return join( - dirname(__file__), + getenv('DOCKORM_TESTS_DIR') or dirname(__file__), 'volumes', path, ) def validate_dict(to_test, expected): """ Recursively validate a dictionary of expectations against another input. Like TestCase.assertDictContainsSubset, but recursive. """ for key, value in iteritems(expected): if isinstance(value, dict): validate_dict(to_test[key], value) else: assert to_test[key] == value
d409594c01e11e05a59f5614722dd3035855e399
salt/returners/redis_return.py
salt/returners/redis_return.py
''' Return data to a redis server This is a VERY simple example for pushing data to a redis server and is not nessisarily intended as a usable interface. ''' import redis import json __opts__ = { 'redis.host': 'mcp', 'redis.port': 6379, 'redis.db': '0', } def returner(ret): ''' Return data to a redis data store ''' serv = redis.Redis( host=__opts__['redis.host'], port=__opts__['redis.port'], db=__opts__['redis.db']) serv.set(ret['id'] + ':' + ret['jid'], json.dumps(ret['return']))
''' Return data to a redis server This is a VERY simple example for pushing data to a redis server and is not nessisarily intended as a usable interface. ''' import redis import json __opts__ = { 'redis.host': 'mcp', 'redis.port': 6379, 'redis.db': '0', } def returner(ret): ''' Return data to a redis data store ''' serv = redis.Redis( host=__opts__['redis.host'], port=__opts__['redis.port'], db=__opts__['redis.db']) serv.sadd(ret['id'] + 'jobs', ret['jid']) serv.set(ret['jid'] + ':' + ret['id'], json.dumps(ret['return'])) serv.sadd('jobs', ret['jid']) serv.sadd(ret['jid'], ret['id'])
Change the redis returner to better use data structures
Change the redis returner to better use data structures
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
''' Return data to a redis server This is a VERY simple example for pushing data to a redis server and is not nessisarily intended as a usable interface. ''' import redis import json __opts__ = { 'redis.host': 'mcp', 'redis.port': 6379, 'redis.db': '0', } def returner(ret): ''' Return data to a redis data store ''' serv = redis.Redis( host=__opts__['redis.host'], port=__opts__['redis.port'], db=__opts__['redis.db']) + serv.sadd(ret['id'] + 'jobs', ret['jid']) - serv.set(ret['id'] + ':' + ret['jid'], json.dumps(ret['return'])) + serv.set(ret['jid'] + ':' + ret['id'], json.dumps(ret['return'])) + serv.sadd('jobs', ret['jid']) + serv.sadd(ret['jid'], ret['id'])
Change the redis returner to better use data structures
## Code Before: ''' Return data to a redis server This is a VERY simple example for pushing data to a redis server and is not nessisarily intended as a usable interface. ''' import redis import json __opts__ = { 'redis.host': 'mcp', 'redis.port': 6379, 'redis.db': '0', } def returner(ret): ''' Return data to a redis data store ''' serv = redis.Redis( host=__opts__['redis.host'], port=__opts__['redis.port'], db=__opts__['redis.db']) serv.set(ret['id'] + ':' + ret['jid'], json.dumps(ret['return'])) ## Instruction: Change the redis returner to better use data structures ## Code After: ''' Return data to a redis server This is a VERY simple example for pushing data to a redis server and is not nessisarily intended as a usable interface. ''' import redis import json __opts__ = { 'redis.host': 'mcp', 'redis.port': 6379, 'redis.db': '0', } def returner(ret): ''' Return data to a redis data store ''' serv = redis.Redis( host=__opts__['redis.host'], port=__opts__['redis.port'], db=__opts__['redis.db']) serv.sadd(ret['id'] + 'jobs', ret['jid']) serv.set(ret['jid'] + ':' + ret['id'], json.dumps(ret['return'])) serv.sadd('jobs', ret['jid']) serv.sadd(ret['jid'], ret['id'])
''' Return data to a redis server This is a VERY simple example for pushing data to a redis server and is not nessisarily intended as a usable interface. ''' import redis import json __opts__ = { 'redis.host': 'mcp', 'redis.port': 6379, 'redis.db': '0', } def returner(ret): ''' Return data to a redis data store ''' serv = redis.Redis( host=__opts__['redis.host'], port=__opts__['redis.port'], db=__opts__['redis.db']) + serv.sadd(ret['id'] + 'jobs', ret['jid']) - serv.set(ret['id'] + ':' + ret['jid'], json.dumps(ret['return'])) ? - + serv.set(ret['jid'] + ':' + ret['id'], json.dumps(ret['return'])) ? + + serv.sadd('jobs', ret['jid']) + serv.sadd(ret['jid'], ret['id'])
9f6d6509b1f3f4a5f3fd20919bcc465475fc1ce3
app/composer.py
app/composer.py
import os from app.configuration import get_value from app.helper import php def initialization(): checker_dir = get_value('checker-dir') if not os.path.isfile(checker_dir+'bin/composer'): download(checker_dir) if not os.path.isfile(checker_dir+'bin/phpcs'): php('bin/composer install') def download(checker_dir): php_bin = get_value('php') if not os.path.exists(checker_dir+'bin'): os.makedirs(checker_dir+'bin') print('>>> Download composer') os.system('curl -sS https://getcomposer.org/installer | '+php_bin+' -- --install-dir='+checker_dir+'bin --filename=composer') def update(): php('bin/composer self-update') php('bin/composer update') def project_installation(): code = php('bin/composer install --optimize-autoloader') if code != 0: raise SystemExit('The composer install command for the project failed with the code '+str(code))
import os from app.configuration import get_value from app.helper import php def initialization(): checker_dir = get_value('checker-dir') if not os.path.isfile(checker_dir+'bin/composer'): download(checker_dir) if not os.path.isfile(checker_dir+'bin/phpcs'): composer('install') def download(checker_dir): php_bin = get_value('php') if not os.path.exists(checker_dir+'bin'): os.makedirs(checker_dir+'bin') print('>>> Download composer') os.system('curl -sS https://getcomposer.org/installer | '+php_bin+' -- --install-dir='+checker_dir+'bin --filename=composer') def update(): composer('self-update') composer('update') def project_installation(): code = php('bin/composer install --optimize-autoloader') if code != 0: raise SystemExit('The composer install command for the project failed with the code '+str(code)) def composer(command): base_dir = os.getcwd() os.chdir(get_value('checker-dir')) php('bin/composer '+command) os.chdir(base_dir)
Add execution path for internal update
Add execution path for internal update
Python
mit
mi-schi/php-code-checker
import os from app.configuration import get_value from app.helper import php def initialization(): checker_dir = get_value('checker-dir') if not os.path.isfile(checker_dir+'bin/composer'): download(checker_dir) if not os.path.isfile(checker_dir+'bin/phpcs'): - php('bin/composer install') + composer('install') def download(checker_dir): php_bin = get_value('php') if not os.path.exists(checker_dir+'bin'): os.makedirs(checker_dir+'bin') print('>>> Download composer') os.system('curl -sS https://getcomposer.org/installer | '+php_bin+' -- --install-dir='+checker_dir+'bin --filename=composer') def update(): - php('bin/composer self-update') + composer('self-update') - php('bin/composer update') + composer('update') def project_installation(): code = php('bin/composer install --optimize-autoloader') if code != 0: raise SystemExit('The composer install command for the project failed with the code '+str(code)) + + def composer(command): + base_dir = os.getcwd() + os.chdir(get_value('checker-dir')) + + php('bin/composer '+command) + + os.chdir(base_dir) +
Add execution path for internal update
## Code Before: import os from app.configuration import get_value from app.helper import php def initialization(): checker_dir = get_value('checker-dir') if not os.path.isfile(checker_dir+'bin/composer'): download(checker_dir) if not os.path.isfile(checker_dir+'bin/phpcs'): php('bin/composer install') def download(checker_dir): php_bin = get_value('php') if not os.path.exists(checker_dir+'bin'): os.makedirs(checker_dir+'bin') print('>>> Download composer') os.system('curl -sS https://getcomposer.org/installer | '+php_bin+' -- --install-dir='+checker_dir+'bin --filename=composer') def update(): php('bin/composer self-update') php('bin/composer update') def project_installation(): code = php('bin/composer install --optimize-autoloader') if code != 0: raise SystemExit('The composer install command for the project failed with the code '+str(code)) ## Instruction: Add execution path for internal update ## Code After: import os from app.configuration import get_value from app.helper import php def initialization(): checker_dir = get_value('checker-dir') if not os.path.isfile(checker_dir+'bin/composer'): download(checker_dir) if not os.path.isfile(checker_dir+'bin/phpcs'): composer('install') def download(checker_dir): php_bin = get_value('php') if not os.path.exists(checker_dir+'bin'): os.makedirs(checker_dir+'bin') print('>>> Download composer') os.system('curl -sS https://getcomposer.org/installer | '+php_bin+' -- --install-dir='+checker_dir+'bin --filename=composer') def update(): composer('self-update') composer('update') def project_installation(): code = php('bin/composer install --optimize-autoloader') if code != 0: raise SystemExit('The composer install command for the project failed with the code '+str(code)) def composer(command): base_dir = os.getcwd() os.chdir(get_value('checker-dir')) php('bin/composer '+command) os.chdir(base_dir)
import os from app.configuration import get_value from app.helper import php def initialization(): checker_dir = get_value('checker-dir') if not os.path.isfile(checker_dir+'bin/composer'): download(checker_dir) if not os.path.isfile(checker_dir+'bin/phpcs'): - php('bin/composer install') ? --------- ^ + composer('install') ? ^^ def download(checker_dir): php_bin = get_value('php') if not os.path.exists(checker_dir+'bin'): os.makedirs(checker_dir+'bin') print('>>> Download composer') os.system('curl -sS https://getcomposer.org/installer | '+php_bin+' -- --install-dir='+checker_dir+'bin --filename=composer') def update(): - php('bin/composer self-update') ? --------- ^ + composer('self-update') ? ^^ - php('bin/composer update') ? --------- ^ + composer('update') ? ^^ def project_installation(): code = php('bin/composer install --optimize-autoloader') if code != 0: raise SystemExit('The composer install command for the project failed with the code '+str(code)) + + + def composer(command): + base_dir = os.getcwd() + os.chdir(get_value('checker-dir')) + + php('bin/composer '+command) + + os.chdir(base_dir)
bea83c533f65eeedae983b70fd41350e57df6908
cms/djangoapps/contentstore/features/video-editor.py
cms/djangoapps/contentstore/features/video-editor.py
from lettuce import world, step @step('I see the correct settings and default values$') def i_see_the_correct_settings_and_values(step): world.verify_all_setting_entries([['.75x', '', False], ['1.25x', '', False], ['1.5x', '', False], ['Display Name', 'default', True], ['Normal Speed', '', False], ['Show Captions', 'True', False], ['Source', '', False], ['Track', '', False]])
from lettuce import world, step @step('I see the correct settings and default values$') def i_see_the_correct_settings_and_values(step): world.verify_all_setting_entries([['Default Speed', '', False], ['Display Name', 'default', True], ['Download Track', '', False], ['Download Video', '', False], ['Show Captions', 'True', False], ['Speed: .75x', '', False], ['Speed: 1.25x', '', False], ['Speed: 1.5x', '', False]])
Update failing metadata settings acceptance test.
Update failing metadata settings acceptance test.
Python
agpl-3.0
bitifirefly/edx-platform,jonathan-beard/edx-platform,arbrandes/edx-platform,xuxiao19910803/edx-platform,zhenzhai/edx-platform,jazztpt/edx-platform,doismellburning/edx-platform,apigee/edx-platform,jbassen/edx-platform,inares/edx-platform,stvstnfrd/edx-platform,Edraak/edx-platform,a-parhom/edx-platform,etzhou/edx-platform,nanolearningllc/edx-platform-cypress-2,kxliugang/edx-platform,jelugbo/tundex,synergeticsedx/deployment-wipro,dcosentino/edx-platform,chudaol/edx-platform,prarthitm/edxplatform,defance/edx-platform,Stanford-Online/edx-platform,gsehub/edx-platform,appsembler/edx-platform,torchingloom/edx-platform,zofuthan/edx-platform,hamzehd/edx-platform,pepeportela/edx-platform,philanthropy-u/edx-platform,rhndg/openedx,ZLLab-Mooc/edx-platform,EduPepperPDTesting/pepper2013-testing,pelikanchik/edx-platform,BehavioralInsightsTeam/edx-platform,xinjiguaike/edx-platform,bitifirefly/edx-platform,sameetb-cuelogic/edx-platform-test,hamzehd/edx-platform,motion2015/edx-platform,wwj718/edx-platform,B-MOOC/edx-platform,wwj718/edx-platform,DNFcode/edx-platform,shabab12/edx-platform,jbzdak/edx-platform,jzoldak/edx-platform,hkawasaki/kawasaki-aio8-0,kalebhartje/schoolboost,Endika/edx-platform,ahmadiga/min_edx,jzoldak/edx-platform,motion2015/edx-platform,cyanna/edx-platform,procangroup/edx-platform,Unow/edx-platform,jelugbo/tundex,jruiperezv/ANALYSE,beacloudgenius/edx-platform,DefyVentures/edx-platform,franosincic/edx-platform,nanolearning/edx-platform,ahmadiga/min_edx,jswope00/GAI,shubhdev/edx-platform,SravanthiSinha/edx-platform,pabloborrego93/edx-platform,zadgroup/edx-platform,beni55/edx-platform,rismalrv/edx-platform,longmen21/edx-platform,EduPepperPD/pepper2013,morpheby/levelup-by,ahmedaljazzar/edx-platform,polimediaupv/edx-platform,abdoosh00/edraak,EDUlib/edx-platform,mjirayu/sit_academy,EduPepperPD/pepper2013,ovnicraft/edx-platform,tiagochiavericosta/edx-platform,yokose-ks/edx-platform,fly19890211/edx-platform,antonve/s4-project-mooc,lduarte1991/edx-platform,motion2015/edx-platform,CourseTalk/edx-platform,wwj718/ANALYSE,angelapper/edx-platform,shabab12/edx-platform,waheedahmed/edx-platform,solashirai/edx-platform,kamalx/edx-platform,iivic/BoiseStateX,shashank971/edx-platform,shashank971/edx-platform,hkawasaki/kawasaki-aio8-1,nikolas/edx-platform,MSOpenTech/edx-platform,rismalrv/edx-platform,a-parhom/edx-platform,beacloudgenius/edx-platform,jamesblunt/edx-platform,devs1991/test_edx_docmode,mushtaqak/edx-platform,chrisndodge/edx-platform,jamesblunt/edx-platform,olexiim/edx-platform,raccoongang/edx-platform,martynovp/edx-platform,peterm-itr/edx-platform,stvstnfrd/edx-platform,sudheerchintala/LearnEraPlatForm,Semi-global/edx-platform,zubair-arbi/edx-platform,nanolearningllc/edx-platform-cypress,ovnicraft/edx-platform,ferabra/edx-platform,ak2703/edx-platform,etzhou/edx-platform,dsajkl/reqiop,OmarIthawi/edx-platform,edry/edx-platform,jolyonb/edx-platform,kalebhartje/schoolboost,RPI-OPENEDX/edx-platform,eemirtekin/edx-platform,Kalyzee/edx-platform,nttks/jenkins-test,appliedx/edx-platform,zubair-arbi/edx-platform,mahendra-r/edx-platform,xinjiguaike/edx-platform,Kalyzee/edx-platform,ahmedaljazzar/edx-platform,tanmaykm/edx-platform,alexthered/kienhoc-platform,ZLLab-Mooc/edx-platform,Kalyzee/edx-platform,syjeon/new_edx,jelugbo/tundex,martynovp/edx-platform,EduPepperPD/pepper2013,kmoocdev/edx-platform,tiagochiavericosta/edx-platform,halvertoluke/edx-platform,cpennington/edx-platform,shubhdev/edxOnBaadal,10clouds/edx-platform,RPI-OPENEDX/edx-platform,Edraak/edraak-platform,zhenzhai/edx-platform,angelapper/edx-platform,teltek/edx-platform,leansoft/edx-platform,jbassen/edx-platform,caesar2164/edx-platform,tiagochiavericosta/edx-platform,morenopc/edx-platform,chauhanhardik/populo,cselis86/edx-platform,zerobatu/edx-platform,vikas1885/test1,utecuy/edx-platform,amir-qayyum-khan/edx-platform,sudheerchintala/LearnEraPlatForm,andyzsf/edx,LearnEra/LearnEraPlaftform,simbs/edx-platform,jamiefolsom/edx-platform,jjmiranda/edx-platform,eemirtekin/edx-platform,kmoocdev2/edx-platform,hkawasaki/kawasaki-aio8-0,TeachAtTUM/edx-platform,zofuthan/edx-platform,rationalAgent/edx-platform-custom,olexiim/edx-platform,Shrhawk/edx-platform,fly19890211/edx-platform,shubhdev/openedx,EduPepperPDTesting/pepper2013-testing,jswope00/griffinx,cecep-edu/edx-platform,benpatterson/edx-platform,peterm-itr/edx-platform,bitifirefly/edx-platform,ubc/edx-platform,IndonesiaX/edx-platform,jazztpt/edx-platform,xinjiguaike/edx-platform,unicri/edx-platform,fly19890211/edx-platform,ampax/edx-platform,gymnasium/edx-platform,knehez/edx-platform,franosincic/edx-platform,bitifirefly/edx-platform,UXE/local-edx,knehez/edx-platform,ubc/edx-platform,RPI-OPENEDX/edx-platform,itsjeyd/edx-platform,motion2015/a3,eduNEXT/edunext-platform,kamalx/edx-platform,dcosentino/edx-platform,hkawasaki/kawasaki-aio8-2,olexiim/edx-platform,pku9104038/edx-platform,appliedx/edx-platform,UOMx/edx-platform,kmoocdev2/edx-platform,vasyarv/edx-platform,vasyarv/edx-platform,TsinghuaX/edx-platform,jazztpt/edx-platform,UOMx/edx-platform,openfun/edx-platform,dkarakats/edx-platform,antonve/s4-project-mooc,jonathan-beard/edx-platform,jonathan-beard/edx-platform,torchingloom/edx-platform,playm2mboy/edx-platform,eestay/edx-platform,xingyepei/edx-platform,zerobatu/edx-platform,Ayub-Khan/edx-platform,atsolakid/edx-platform,jazkarta/edx-platform-for-isc,jbassen/edx-platform,chauhanhardik/populo_2,pabloborrego93/edx-platform,amir-qayyum-khan/edx-platform,naresh21/synergetics-edx-platform,cselis86/edx-platform,edry/edx-platform,utecuy/edx-platform,EduPepperPDTesting/pepper2013-testing,jamesblunt/edx-platform,TeachAtTUM/edx-platform,adoosii/edx-platform,longmen21/edx-platform,eemirtekin/edx-platform,ahmadio/edx-platform,TeachAtTUM/edx-platform,olexiim/edx-platform,mitocw/edx-platform,shubhdev/openedx,fintech-circle/edx-platform,dcosentino/edx-platform,OmarIthawi/edx-platform,dcosentino/edx-platform,vasyarv/edx-platform,zerobatu/edx-platform,abdoosh00/edx-rtl-final,vismartltd/edx-platform,kalebhartje/schoolboost,kamalx/edx-platform,beacloudgenius/edx-platform,chauhanhardik/populo_2,J861449197/edx-platform,hkawasaki/kawasaki-aio8-1,simbs/edx-platform,Unow/edx-platform,rhndg/openedx,WatanabeYasumasa/edx-platform,chauhanhardik/populo,Edraak/circleci-edx-platform,ahmadio/edx-platform,Lektorium-LLC/edx-platform,praveen-pal/edx-platform,jamiefolsom/edx-platform,antonve/s4-project-mooc,DNFcode/edx-platform,arifsetiawan/edx-platform,cognitiveclass/edx-platform,naresh21/synergetics-edx-platform,zadgroup/edx-platform,dkarakats/edx-platform,carsongee/edx-platform,doganov/edx-platform,defance/edx-platform,devs1991/test_edx_docmode,etzhou/edx-platform,shubhdev/edx-platform,solashirai/edx-platform,romain-li/edx-platform,IONISx/edx-platform,xinjiguaike/edx-platform,morenopc/edx-platform,eemirtekin/edx-platform,mjirayu/sit_academy,chudaol/edx-platform,hkawasaki/kawasaki-aio8-0,shubhdev/openedx,mcgachey/edx-platform,vismartltd/edx-platform,JCBarahona/edX,rue89-tech/edx-platform,morenopc/edx-platform,PepperPD/edx-pepper-platform,rationalAgent/edx-platform-custom,kalebhartje/schoolboost,jolyonb/edx-platform,deepsrijit1105/edx-platform,CourseTalk/edx-platform,IITBinterns13/edx-platform-dev,martynovp/edx-platform,shubhdev/edxOnBaadal,TsinghuaX/edx-platform,jruiperezv/ANALYSE,Lektorium-LLC/edx-platform,adoosii/edx-platform,atsolakid/edx-platform,prarthitm/edxplatform,itsjeyd/edx-platform,IndonesiaX/edx-platform,analyseuc3m/ANALYSE-v1,xuxiao19910803/edx,utecuy/edx-platform,vasyarv/edx-platform,utecuy/edx-platform,leansoft/edx-platform,rismalrv/edx-platform,torchingloom/edx-platform,halvertoluke/edx-platform,cpennington/edx-platform,adoosii/edx-platform,abdoosh00/edraak,Shrhawk/edx-platform,bdero/edx-platform,eduNEXT/edunext-platform,inares/edx-platform,vasyarv/edx-platform,Kalyzee/edx-platform,chand3040/cloud_that,J861449197/edx-platform,auferack08/edx-platform,rue89-tech/edx-platform,zofuthan/edx-platform,hkawasaki/kawasaki-aio8-0,mjg2203/edx-platform-seas,hkawasaki/kawasaki-aio8-2,AkA84/edx-platform,mjg2203/edx-platform-seas,jruiperezv/ANALYSE,mtlchun/edx,rue89-tech/edx-platform,BehavioralInsightsTeam/edx-platform,MSOpenTech/edx-platform,pabloborrego93/edx-platform,arbrandes/edx-platform,syjeon/new_edx,marcore/edx-platform,zubair-arbi/edx-platform,eduNEXT/edx-platform,LearnEra/LearnEraPlaftform,valtech-mooc/edx-platform,pelikanchik/edx-platform,IONISx/edx-platform,devs1991/test_edx_docmode,unicri/edx-platform,Lektorium-LLC/edx-platform,alexthered/kienhoc-platform,vikas1885/test1,cecep-edu/edx-platform,romain-li/edx-platform,deepsrijit1105/edx-platform,don-github/edx-platform,pdehaye/theming-edx-platform,pepeportela/edx-platform,hkawasaki/kawasaki-aio8-1,vismartltd/edx-platform,abdoosh00/edraak,cpennington/edx-platform,Edraak/circleci-edx-platform,hastexo/edx-platform,IndonesiaX/edx-platform,ovnicraft/edx-platform,appliedx/edx-platform,dcosentino/edx-platform,nagyistoce/edx-platform,chauhanhardik/populo_2,rhndg/openedx,arbrandes/edx-platform,pomegranited/edx-platform,waheedahmed/edx-platform,SivilTaram/edx-platform,romain-li/edx-platform,UXE/local-edx,alu042/edx-platform,msegado/edx-platform,jruiperezv/ANALYSE,shabab12/edx-platform,philanthropy-u/edx-platform,beni55/edx-platform,DefyVentures/edx-platform,UOMx/edx-platform,synergeticsedx/deployment-wipro,ampax/edx-platform,nagyistoce/edx-platform,franosincic/edx-platform,SravanthiSinha/edx-platform,fly19890211/edx-platform,antonve/s4-project-mooc,10clouds/edx-platform,tanmaykm/edx-platform,edx/edx-platform,MakeHer/edx-platform,devs1991/test_edx_docmode,bigdatauniversity/edx-platform,a-parhom/edx-platform,fintech-circle/edx-platform,pepeportela/edx-platform,TsinghuaX/edx-platform,dsajkl/reqiop,jazztpt/edx-platform,cpennington/edx-platform,jzoldak/edx-platform,rhndg/openedx,eduNEXT/edunext-platform,doganov/edx-platform,eduNEXT/edx-platform,arifsetiawan/edx-platform,MakeHer/edx-platform,rationalAgent/edx-platform-custom,devs1991/test_edx_docmode,ovnicraft/edx-platform,edx-solutions/edx-platform,shubhdev/edx-platform,halvertoluke/edx-platform,MakeHer/edx-platform,mjirayu/sit_academy,defance/edx-platform,zhenzhai/edx-platform,kamalx/edx-platform,alexthered/kienhoc-platform,ESOedX/edx-platform,knehez/edx-platform,Livit/Livit.Learn.EdX,philanthropy-u/edx-platform,jazkarta/edx-platform-for-isc,sameetb-cuelogic/edx-platform-test,shabab12/edx-platform,jswope00/griffinx,shubhdev/openedx,LICEF/edx-platform,xingyepei/edx-platform,morpheby/levelup-by,Softmotions/edx-platform,ampax/edx-platform,Semi-global/edx-platform,jjmiranda/edx-platform,yokose-ks/edx-platform,benpatterson/edx-platform,teltek/edx-platform,kxliugang/edx-platform,SravanthiSinha/edx-platform,mtlchun/edx,4eek/edx-platform,LICEF/edx-platform,jjmiranda/edx-platform,Edraak/edx-platform,bigdatauniversity/edx-platform,polimediaupv/edx-platform,appliedx/edx-platform,ak2703/edx-platform,Shrhawk/edx-platform,shubhdev/edxOnBaadal,CourseTalk/edx-platform,cecep-edu/edx-platform,SravanthiSinha/edx-platform,kxliugang/edx-platform,Endika/edx-platform,Kalyzee/edx-platform,y12uc231/edx-platform,chrisndodge/edx-platform,zadgroup/edx-platform,arifsetiawan/edx-platform,edx-solutions/edx-platform,ahmadio/edx-platform,devs1991/test_edx_docmode,defance/edx-platform,bigdatauniversity/edx-platform,yokose-ks/edx-platform,nanolearning/edx-platform,Shrhawk/edx-platform,valtech-mooc/edx-platform,syjeon/new_edx,pabloborrego93/edx-platform,WatanabeYasumasa/edx-platform,nttks/edx-platform,AkA84/edx-platform,louyihua/edx-platform,Ayub-Khan/edx-platform,jswope00/GAI,cecep-edu/edx-platform,Stanford-Online/edx-platform,halvertoluke/edx-platform,bigdatauniversity/edx-platform,etzhou/edx-platform,JioEducation/edx-platform,DNFcode/edx-platform,cognitiveclass/edx-platform,jzoldak/edx-platform,ahmedaljazzar/edx-platform,arifsetiawan/edx-platform,4eek/edx-platform,iivic/BoiseStateX,kursitet/edx-platform,chand3040/cloud_that,hmcmooc/muddx-platform,mcgachey/edx-platform,Shrhawk/edx-platform,nanolearningllc/edx-platform-cypress-2,edx-solutions/edx-platform,jazkarta/edx-platform,IONISx/edx-platform,J861449197/edx-platform,ferabra/edx-platform,DefyVentures/edx-platform,waheedahmed/edx-platform,shubhdev/edx-platform,gsehub/edx-platform,y12uc231/edx-platform,apigee/edx-platform,Semi-global/edx-platform,ferabra/edx-platform,auferack08/edx-platform,pdehaye/theming-edx-platform,jelugbo/tundex,jswope00/GAI,tanmaykm/edx-platform,IITBinterns13/edx-platform-dev,kmoocdev/edx-platform,teltek/edx-platform,romain-li/edx-platform,RPI-OPENEDX/edx-platform,andyzsf/edx,cselis86/edx-platform,atsolakid/edx-platform,morpheby/levelup-by,naresh21/synergetics-edx-platform,Edraak/circleci-edx-platform,fly19890211/edx-platform,marcore/edx-platform,atsolakid/edx-platform,mcgachey/edx-platform,angelapper/edx-platform,rismalrv/edx-platform,adoosii/edx-platform,xinjiguaike/edx-platform,bdero/edx-platform,edx/edx-platform,chudaol/edx-platform,wwj718/ANALYSE,MakeHer/edx-platform,valtech-mooc/edx-platform,SravanthiSinha/edx-platform,MSOpenTech/edx-platform,rismalrv/edx-platform,synergeticsedx/deployment-wipro,eestay/edx-platform,proversity-org/edx-platform,benpatterson/edx-platform,B-MOOC/edx-platform,cyanna/edx-platform,vismartltd/edx-platform,lduarte1991/edx-platform,antoviaque/edx-platform,waheedahmed/edx-platform,tiagochiavericosta/edx-platform,chauhanhardik/populo,nikolas/edx-platform,vikas1885/test1,xuxiao19910803/edx-platform,antonve/s4-project-mooc,jazkarta/edx-platform,cyanna/edx-platform,TsinghuaX/edx-platform,10clouds/edx-platform,mushtaqak/edx-platform,dsajkl/123,jruiperezv/ANALYSE,marcore/edx-platform,ahmadiga/min_edx,Endika/edx-platform,ESOedX/edx-platform,xuxiao19910803/edx,gymnasium/edx-platform,pdehaye/theming-edx-platform,ak2703/edx-platform,AkA84/edx-platform,B-MOOC/edx-platform,jjmiranda/edx-platform,inares/edx-platform,DNFcode/edx-platform,doganov/edx-platform,carsongee/edx-platform,SivilTaram/edx-platform,abdoosh00/edx-rtl-final,marcore/edx-platform,jbassen/edx-platform,IndonesiaX/edx-platform,morpheby/levelup-by,zadgroup/edx-platform,unicri/edx-platform,ahmadiga/min_edx,don-github/edx-platform,UOMx/edx-platform,vismartltd/edx-platform,Livit/Livit.Learn.EdX,pdehaye/theming-edx-platform,JioEducation/edx-platform,ZLLab-Mooc/edx-platform,antoviaque/edx-platform,cselis86/edx-platform,LICEF/edx-platform,etzhou/edx-platform,devs1991/test_edx_docmode,BehavioralInsightsTeam/edx-platform,openfun/edx-platform,chand3040/cloud_that,deepsrijit1105/edx-platform,alu042/edx-platform,kmoocdev2/edx-platform,doganov/edx-platform,franosincic/edx-platform,dsajkl/123,atsolakid/edx-platform,msegado/edx-platform,bdero/edx-platform,eestay/edx-platform,msegado/edx-platform,shurihell/testasia,kursitet/edx-platform,xingyepei/edx-platform,ESOedX/edx-platform,jolyonb/edx-platform,jazkarta/edx-platform,JCBarahona/edX,jonathan-beard/edx-platform,jazztpt/edx-platform,alexthered/kienhoc-platform,mbareta/edx-platform-ft,CredoReference/edx-platform,cyanna/edx-platform,Softmotions/edx-platform,fintech-circle/edx-platform,antoviaque/edx-platform,hmcmooc/muddx-platform,inares/edx-platform,jonathan-beard/edx-platform,IITBinterns13/edx-platform-dev,zofuthan/edx-platform,xuxiao19910803/edx-platform,caesar2164/edx-platform,OmarIthawi/edx-platform,PepperPD/edx-pepper-platform,sameetb-cuelogic/edx-platform-test,don-github/edx-platform,nanolearningllc/edx-platform-cypress,kxliugang/edx-platform,utecuy/edx-platform,bitifirefly/edx-platform,auferack08/edx-platform,sudheerchintala/LearnEraPlatForm,ahmedaljazzar/edx-platform,nikolas/edx-platform,nttks/edx-platform,playm2mboy/edx-platform,chand3040/cloud_that,mcgachey/edx-platform,motion2015/edx-platform,caesar2164/edx-platform,xuxiao19910803/edx-platform,abdoosh00/edraak,kursitet/edx-platform,tiagochiavericosta/edx-platform,alu042/edx-platform,zhenzhai/edx-platform,xuxiao19910803/edx-platform,ubc/edx-platform,LearnEra/LearnEraPlaftform,hastexo/edx-platform,ampax/edx-platform-backup,kamalx/edx-platform,Stanford-Online/edx-platform,morenopc/edx-platform,dsajkl/123,EDUlib/edx-platform,UXE/local-edx,TeachAtTUM/edx-platform,don-github/edx-platform,beni55/edx-platform,eduNEXT/edunext-platform,xuxiao19910803/edx,shubhdev/openedx,hamzehd/edx-platform,doismellburning/edx-platform,openfun/edx-platform,peterm-itr/edx-platform,doismellburning/edx-platform,shurihell/testasia,ubc/edx-platform,solashirai/edx-platform,motion2015/a3,nagyistoce/edx-platform,jswope00/griffinx,cecep-edu/edx-platform,shurihell/testasia,y12uc231/edx-platform,nanolearningllc/edx-platform-cypress-2,yokose-ks/edx-platform,WatanabeYasumasa/edx-platform,valtech-mooc/edx-platform,nttks/edx-platform,halvertoluke/edx-platform,analyseuc3m/ANALYSE-v1,jamesblunt/edx-platform,chand3040/cloud_that,playm2mboy/edx-platform,leansoft/edx-platform,procangroup/edx-platform,appsembler/edx-platform,nttks/jenkins-test,proversity-org/edx-platform,torchingloom/edx-platform,edry/edx-platform,carsongee/edx-platform,hmcmooc/muddx-platform,DNFcode/edx-platform,ZLLab-Mooc/edx-platform,auferack08/edx-platform,cognitiveclass/edx-platform,motion2015/a3,jamesblunt/edx-platform,CredoReference/edx-platform,nttks/edx-platform,fintech-circle/edx-platform,CredoReference/edx-platform,J861449197/edx-platform,mitocw/edx-platform,mbareta/edx-platform-ft,jelugbo/tundex,doismellburning/edx-platform,JioEducation/edx-platform,kmoocdev/edx-platform,martynovp/edx-platform,SivilTaram/edx-platform,chrisndodge/edx-platform,motion2015/a3,vikas1885/test1,benpatterson/edx-platform,LICEF/edx-platform,wwj718/edx-platform,beni55/edx-platform,itsjeyd/edx-platform,apigee/edx-platform,eestay/edx-platform,inares/edx-platform,jamiefolsom/edx-platform,mbareta/edx-platform-ft,kmoocdev/edx-platform,gsehub/edx-platform,jamiefolsom/edx-platform,pomegranited/edx-platform,LICEF/edx-platform,synergeticsedx/deployment-wipro,JCBarahona/edX,louyihua/edx-platform,jswope00/griffinx,iivic/BoiseStateX,iivic/BoiseStateX,nanolearning/edx-platform,analyseuc3m/ANALYSE-v1,pku9104038/edx-platform,a-parhom/edx-platform,appsembler/edx-platform,jbassen/edx-platform,nttks/edx-platform,abdoosh00/edx-rtl-final,jbzdak/edx-platform,apigee/edx-platform,longmen21/edx-platform,lduarte1991/edx-platform,longmen21/edx-platform,hastexo/edx-platform,lduarte1991/edx-platform,deepsrijit1105/edx-platform,eduNEXT/edx-platform,ubc/edx-platform,nanolearningllc/edx-platform-cypress,hamzehd/edx-platform,ampax/edx-platform-backup,jazkarta/edx-platform-for-isc,WatanabeYasumasa/edx-platform,edry/edx-platform,beni55/edx-platform,pomegranited/edx-platform,proversity-org/edx-platform,solashirai/edx-platform,jswope00/griffinx,ahmadio/edx-platform,y12uc231/edx-platform,EduPepperPDTesting/pepper2013-testing,PepperPD/edx-pepper-platform,mahendra-r/edx-platform,doganov/edx-platform,jbzdak/edx-platform,mbareta/edx-platform-ft,morenopc/edx-platform,kalebhartje/schoolboost,jazkarta/edx-platform-for-isc,mitocw/edx-platform,rhndg/openedx,cyanna/edx-platform,ak2703/edx-platform,LearnEra/LearnEraPlaftform,jazkarta/edx-platform,PepperPD/edx-pepper-platform,praveen-pal/edx-platform,nikolas/edx-platform,IndonesiaX/edx-platform,msegado/edx-platform,4eek/edx-platform,gymnasium/edx-platform,proversity-org/edx-platform,cselis86/edx-platform,miptliot/edx-platform,nttks/jenkins-test,antoviaque/edx-platform,Edraak/edx-platform,beacloudgenius/edx-platform,UXE/local-edx,peterm-itr/edx-platform,amir-qayyum-khan/edx-platform,J861449197/edx-platform,louyihua/edx-platform,mushtaqak/edx-platform,xuxiao19910803/edx,zubair-arbi/edx-platform,unicri/edx-platform,mjirayu/sit_academy,kursitet/edx-platform,Edraak/edraak-platform,olexiim/edx-platform,jswope00/GAI,hkawasaki/kawasaki-aio8-1,mcgachey/edx-platform,gymnasium/edx-platform,eestay/edx-platform,edx-solutions/edx-platform,ampax/edx-platform-backup,polimediaupv/edx-platform,rue89-tech/edx-platform,pku9104038/edx-platform,nagyistoce/edx-platform,Endika/edx-platform,jazkarta/edx-platform-for-isc,martynovp/edx-platform,eduNEXT/edx-platform,mjg2203/edx-platform-seas,Edraak/edraak-platform,edx/edx-platform,vikas1885/test1,dkarakats/edx-platform,unicri/edx-platform,shubhdev/edxOnBaadal,shubhdev/edxOnBaadal,nagyistoce/edx-platform,playm2mboy/edx-platform,andyzsf/edx,hamzehd/edx-platform,OmarIthawi/edx-platform,sameetb-cuelogic/edx-platform-test,JCBarahona/edX,jbzdak/edx-platform,xingyepei/edx-platform,shashank971/edx-platform,zadgroup/edx-platform,prarthitm/edxplatform,Semi-global/edx-platform,Softmotions/edx-platform,ak2703/edx-platform,pku9104038/edx-platform,mjirayu/sit_academy,teltek/edx-platform,bigdatauniversity/edx-platform,AkA84/edx-platform,chauhanhardik/populo_2,Stanford-Online/edx-platform,Edraak/edx-platform,4eek/edx-platform,shashank971/edx-platform,IONISx/edx-platform,ahmadiga/min_edx,EduPepperPDTesting/pepper2013-testing,dsajkl/123,dkarakats/edx-platform,kxliugang/edx-platform,ESOedX/edx-platform,miptliot/edx-platform,nanolearningllc/edx-platform-cypress,ZLLab-Mooc/edx-platform,raccoongang/edx-platform,eemirtekin/edx-platform,bdero/edx-platform,alu042/edx-platform,dsajkl/reqiop,DefyVentures/edx-platform,Ayub-Khan/edx-platform,y12uc231/edx-platform,Ayub-Khan/edx-platform,Edraak/circleci-edx-platform,knehez/edx-platform,franosincic/edx-platform,EDUlib/edx-platform,doismellburning/edx-platform,chudaol/edx-platform,wwj718/edx-platform,BehavioralInsightsTeam/edx-platform,wwj718/edx-platform,motion2015/a3,stvstnfrd/edx-platform,devs1991/test_edx_docmode,zubair-arbi/edx-platform,rationalAgent/edx-platform-custom,leansoft/edx-platform,nanolearningllc/edx-platform-cypress-2,hmcmooc/muddx-platform,jbzdak/edx-platform,pomegranited/edx-platform,Edraak/edraak-platform,kmoocdev2/edx-platform,amir-qayyum-khan/edx-platform,simbs/edx-platform,torchingloom/edx-platform,edx/edx-platform,EduPepperPD/pepper2013,mtlchun/edx,knehez/edx-platform,chudaol/edx-platform,AkA84/edx-platform,EduPepperPD/pepper2013,MSOpenTech/edx-platform,pelikanchik/edx-platform,philanthropy-u/edx-platform,pepeportela/edx-platform,jolyonb/edx-platform,SivilTaram/edx-platform,louyihua/edx-platform,CredoReference/edx-platform,Unow/edx-platform,gsehub/edx-platform,beacloudgenius/edx-platform,hastexo/edx-platform,nanolearning/edx-platform,chauhanhardik/populo_2,shurihell/testasia,10clouds/edx-platform,Edraak/circleci-edx-platform,JCBarahona/edX,procangroup/edx-platform,ahmadio/edx-platform,wwj718/ANALYSE,kmoocdev/edx-platform,xuxiao19910803/edx,hkawasaki/kawasaki-aio8-2,nanolearningllc/edx-platform-cypress,hkawasaki/kawasaki-aio8-2,solashirai/edx-platform,Edraak/edx-platform,pomegranited/edx-platform,mushtaqak/edx-platform,procangroup/edx-platform,ampax/edx-platform-backup,IITBinterns13/edx-platform-dev,andyzsf/edx,miptliot/edx-platform,openfun/edx-platform,Unow/edx-platform,B-MOOC/edx-platform,syjeon/new_edx,chauhanhardik/populo,adoosii/edx-platform,EduPepperPDTesting/pepper2013-testing,zofuthan/edx-platform,mahendra-r/edx-platform,xingyepei/edx-platform,DefyVentures/edx-platform,rationalAgent/edx-platform-custom,chauhanhardik/populo,Livit/Livit.Learn.EdX,wwj718/ANALYSE,prarthitm/edxplatform,mahendra-r/edx-platform,zerobatu/edx-platform,IONISx/edx-platform,miptliot/edx-platform,cognitiveclass/edx-platform,jazkarta/edx-platform,benpatterson/edx-platform,mitocw/edx-platform,edry/edx-platform,JioEducation/edx-platform,MakeHer/edx-platform,EDUlib/edx-platform,alexthered/kienhoc-platform,angelapper/edx-platform,raccoongang/edx-platform,nttks/jenkins-test,arifsetiawan/edx-platform,4eek/edx-platform,waheedahmed/edx-platform,openfun/edx-platform,appsembler/edx-platform,mtlchun/edx,shubhdev/edx-platform,ferabra/edx-platform,arbrandes/edx-platform,Lektorium-LLC/edx-platform,nanolearningllc/edx-platform-cypress-2,zerobatu/edx-platform,Softmotions/edx-platform,mushtaqak/edx-platform,PepperPD/edx-pepper-platform,Ayub-Khan/edx-platform,analyseuc3m/ANALYSE-v1,simbs/edx-platform,cognitiveclass/edx-platform,mjg2203/edx-platform-seas,SivilTaram/edx-platform,leansoft/edx-platform,shurihell/testasia,abdoosh00/edx-rtl-final,dkarakats/edx-platform,CourseTalk/edx-platform,ferabra/edx-platform,appliedx/edx-platform,praveen-pal/edx-platform,shashank971/edx-platform,caesar2164/edx-platform,simbs/edx-platform,valtech-mooc/edx-platform,pelikanchik/edx-platform,naresh21/synergetics-edx-platform,mtlchun/edx,itsjeyd/edx-platform,polimediaupv/edx-platform,polimediaupv/edx-platform,nanolearning/edx-platform,tanmaykm/edx-platform,ampax/edx-platform-backup,yokose-ks/edx-platform,don-github/edx-platform,Semi-global/edx-platform,msegado/edx-platform,iivic/BoiseStateX,longmen21/edx-platform,ampax/edx-platform,stvstnfrd/edx-platform,wwj718/ANALYSE,romain-li/edx-platform,MSOpenTech/edx-platform,motion2015/edx-platform,zhenzhai/edx-platform,dsajkl/123,raccoongang/edx-platform,kursitet/edx-platform,Softmotions/edx-platform,carsongee/edx-platform,dsajkl/reqiop,jamiefolsom/edx-platform,Livit/Livit.Learn.EdX,mahendra-r/edx-platform,rue89-tech/edx-platform,sameetb-cuelogic/edx-platform-test,playm2mboy/edx-platform,RPI-OPENEDX/edx-platform,sudheerchintala/LearnEraPlatForm,kmoocdev2/edx-platform,ovnicraft/edx-platform,B-MOOC/edx-platform,nikolas/edx-platform,nttks/jenkins-test,chrisndodge/edx-platform,praveen-pal/edx-platform
from lettuce import world, step @step('I see the correct settings and default values$') def i_see_the_correct_settings_and_values(step): - world.verify_all_setting_entries([['.75x', '', False], + world.verify_all_setting_entries([['Default Speed', '', False], - ['1.25x', '', False], - ['1.5x', '', False], ['Display Name', 'default', True], - ['Normal Speed', '', False], + ['Download Track', '', False], + ['Download Video', '', False], ['Show Captions', 'True', False], - ['Source', '', False], + ['Speed: .75x', '', False], + ['Speed: 1.25x', '', False], - ['Track', '', False]]) + ['Speed: 1.5x', '', False]])
Update failing metadata settings acceptance test.
## Code Before: from lettuce import world, step @step('I see the correct settings and default values$') def i_see_the_correct_settings_and_values(step): world.verify_all_setting_entries([['.75x', '', False], ['1.25x', '', False], ['1.5x', '', False], ['Display Name', 'default', True], ['Normal Speed', '', False], ['Show Captions', 'True', False], ['Source', '', False], ['Track', '', False]]) ## Instruction: Update failing metadata settings acceptance test. ## Code After: from lettuce import world, step @step('I see the correct settings and default values$') def i_see_the_correct_settings_and_values(step): world.verify_all_setting_entries([['Default Speed', '', False], ['Display Name', 'default', True], ['Download Track', '', False], ['Download Video', '', False], ['Show Captions', 'True', False], ['Speed: .75x', '', False], ['Speed: 1.25x', '', False], ['Speed: 1.5x', '', False]])
from lettuce import world, step @step('I see the correct settings and default values$') def i_see_the_correct_settings_and_values(step): - world.verify_all_setting_entries([['.75x', '', False], ? ^^^^ + world.verify_all_setting_entries([['Default Speed', '', False], ? ^^^^^^^^^^^^^ - ['1.25x', '', False], - ['1.5x', '', False], ['Display Name', 'default', True], + ['Download Track', '', False], - ['Normal Speed', '', False], ? ^ ^^ ^ ^^ ^^ + ['Download Video', '', False], ? ^ ^^^^ ^ ^^^ ^ ['Show Captions', 'True', False], - ['Source', '', False], ? ^^^^ + ['Speed: .75x', '', False], ? ^ ++++++++ + ['Speed: 1.25x', '', False], - ['Track', '', False]]) ? ^^^^^ + ['Speed: 1.5x', '', False]]) ? ^^^^^^^^^^^
aff5a09eb3d61f77cb277b076820481b8ba145d5
tests/test_coroutine.py
tests/test_coroutine.py
import tests try: import asyncio exec('''if 1: def hello_world(result, delay): result.append("Hello") # retrieve the event loop from the policy yield from asyncio.sleep(delay) result.append('World') ''') except ImportError: import trollius as asyncio from trollius import From def hello_world(result, delay): result.append("Hello") # retrieve the event loop from the policy yield From(asyncio.sleep(delay)) result.append('World') class CallbackTests(tests.TestCase): def test_hello_world(self): result = [] self.loop.run_until_complete(hello_world(result, 0.001)) self.assertEqual(result, ['Hello', 'World']) if __name__ == '__main__': import unittest unittest.main()
import tests try: import asyncio exec('''if 1: def hello_world(result, delay): result.append("Hello") # retrieve the event loop from the policy yield from asyncio.sleep(delay) result.append('World') return "." def waiter(result): loop = asyncio.get_event_loop() fut = asyncio.Future(loop=loop) loop.call_soon(fut.set_result, "Future") value = yield from fut result.append(value) value = yield from hello_world(result, 0.001) result.append(value) ''') except ImportError: import trollius as asyncio from trollius import From, Return def hello_world(result, delay): result.append("Hello") # retrieve the event loop from the policy yield From(asyncio.sleep(delay)) result.append('World') raise Return(".") def waiter(result): loop = asyncio.get_event_loop() fut = asyncio.Future(loop=loop) loop.call_soon(fut.set_result, "Future") value = yield From(fut) result.append(value) value = yield From(hello_world(result, 0.001)) result.append(value) class CallbackTests(tests.TestCase): def test_hello_world(self): result = [] self.loop.run_until_complete(hello_world(result, 0.001)) self.assertEqual(result, ['Hello', 'World']) def test_waiter(self): result = [] self.loop.run_until_complete(waiter(result)) self.assertEqual(result, ['Future', 'Hello', 'World', '.']) if __name__ == '__main__': import unittest unittest.main()
Add more complex coroutine example
Add more complex coroutine example
Python
apache-2.0
overcastcloud/aioeventlet
import tests try: import asyncio exec('''if 1: def hello_world(result, delay): result.append("Hello") # retrieve the event loop from the policy yield from asyncio.sleep(delay) result.append('World') + return "." + + def waiter(result): + loop = asyncio.get_event_loop() + fut = asyncio.Future(loop=loop) + loop.call_soon(fut.set_result, "Future") + + value = yield from fut + result.append(value) + + value = yield from hello_world(result, 0.001) + result.append(value) ''') except ImportError: import trollius as asyncio - from trollius import From + from trollius import From, Return def hello_world(result, delay): result.append("Hello") # retrieve the event loop from the policy yield From(asyncio.sleep(delay)) result.append('World') + raise Return(".") + + def waiter(result): + loop = asyncio.get_event_loop() + fut = asyncio.Future(loop=loop) + loop.call_soon(fut.set_result, "Future") + + value = yield From(fut) + result.append(value) + + value = yield From(hello_world(result, 0.001)) + result.append(value) + class CallbackTests(tests.TestCase): def test_hello_world(self): result = [] self.loop.run_until_complete(hello_world(result, 0.001)) self.assertEqual(result, ['Hello', 'World']) + def test_waiter(self): + result = [] + self.loop.run_until_complete(waiter(result)) + self.assertEqual(result, ['Future', 'Hello', 'World', '.']) + if __name__ == '__main__': import unittest unittest.main()
Add more complex coroutine example
## Code Before: import tests try: import asyncio exec('''if 1: def hello_world(result, delay): result.append("Hello") # retrieve the event loop from the policy yield from asyncio.sleep(delay) result.append('World') ''') except ImportError: import trollius as asyncio from trollius import From def hello_world(result, delay): result.append("Hello") # retrieve the event loop from the policy yield From(asyncio.sleep(delay)) result.append('World') class CallbackTests(tests.TestCase): def test_hello_world(self): result = [] self.loop.run_until_complete(hello_world(result, 0.001)) self.assertEqual(result, ['Hello', 'World']) if __name__ == '__main__': import unittest unittest.main() ## Instruction: Add more complex coroutine example ## Code After: import tests try: import asyncio exec('''if 1: def hello_world(result, delay): result.append("Hello") # retrieve the event loop from the policy yield from asyncio.sleep(delay) result.append('World') return "." def waiter(result): loop = asyncio.get_event_loop() fut = asyncio.Future(loop=loop) loop.call_soon(fut.set_result, "Future") value = yield from fut result.append(value) value = yield from hello_world(result, 0.001) result.append(value) ''') except ImportError: import trollius as asyncio from trollius import From, Return def hello_world(result, delay): result.append("Hello") # retrieve the event loop from the policy yield From(asyncio.sleep(delay)) result.append('World') raise Return(".") def waiter(result): loop = asyncio.get_event_loop() fut = asyncio.Future(loop=loop) loop.call_soon(fut.set_result, "Future") value = yield From(fut) result.append(value) value = yield From(hello_world(result, 0.001)) result.append(value) class CallbackTests(tests.TestCase): def test_hello_world(self): result = [] self.loop.run_until_complete(hello_world(result, 0.001)) self.assertEqual(result, ['Hello', 'World']) def test_waiter(self): result = [] self.loop.run_until_complete(waiter(result)) self.assertEqual(result, ['Future', 'Hello', 'World', '.']) if __name__ == '__main__': import unittest unittest.main()
import tests try: import asyncio exec('''if 1: def hello_world(result, delay): result.append("Hello") # retrieve the event loop from the policy yield from asyncio.sleep(delay) result.append('World') + return "." + + def waiter(result): + loop = asyncio.get_event_loop() + fut = asyncio.Future(loop=loop) + loop.call_soon(fut.set_result, "Future") + + value = yield from fut + result.append(value) + + value = yield from hello_world(result, 0.001) + result.append(value) ''') except ImportError: import trollius as asyncio - from trollius import From + from trollius import From, Return ? ++++++++ def hello_world(result, delay): result.append("Hello") # retrieve the event loop from the policy yield From(asyncio.sleep(delay)) result.append('World') + raise Return(".") + + def waiter(result): + loop = asyncio.get_event_loop() + fut = asyncio.Future(loop=loop) + loop.call_soon(fut.set_result, "Future") + + value = yield From(fut) + result.append(value) + + value = yield From(hello_world(result, 0.001)) + result.append(value) + class CallbackTests(tests.TestCase): def test_hello_world(self): result = [] self.loop.run_until_complete(hello_world(result, 0.001)) self.assertEqual(result, ['Hello', 'World']) + def test_waiter(self): + result = [] + self.loop.run_until_complete(waiter(result)) + self.assertEqual(result, ['Future', 'Hello', 'World', '.']) + if __name__ == '__main__': import unittest unittest.main()
46344032e016b51e9d34b2620b72e418533374e2
hyper/http20/frame.py
hyper/http20/frame.py
class Frame(object): """ The base class for all HTTP/2.0 frames. """ # The flags defined on this type of frame. defined_flags = [] # The type of the frame. type = 0 def __init__(self, stream_id): self.stream_id = stream_id self.flags = set() def parse_flags(self, flag_byte): for flag, flag_bit in self.defined_flags: if flag_byte & flag_bit: self.flags.add(flag) return self.flags def serialize(self): raise NotImplementedError() def _get_len(self): raise NotImplementedError()
# A map of type byte to frame class. FRAMES = { 0x00: DataFrame } class Frame(object): """ The base class for all HTTP/2.0 frames. """ # The flags defined on this type of frame. defined_flags = [] # The type of the frame. type = 0 def __init__(self, stream_id): self.stream_id = stream_id self.flags = set() def parse_flags(self, flag_byte): for flag, flag_bit in self.defined_flags: if flag_byte & flag_bit: self.flags.add(flag) return self.flags def serialize(self): raise NotImplementedError() def _get_len(self): raise NotImplementedError()
Define a mapping between byte and class.
Define a mapping between byte and class.
Python
mit
Lukasa/hyper,fredthomsen/hyper,Lukasa/hyper,masaori335/hyper,lawnmowerlatte/hyper,jdecuyper/hyper,irvind/hyper,jdecuyper/hyper,lawnmowerlatte/hyper,irvind/hyper,masaori335/hyper,plucury/hyper,plucury/hyper,fredthomsen/hyper
+ # A map of type byte to frame class. + FRAMES = { + 0x00: DataFrame + } + + class Frame(object): """ The base class for all HTTP/2.0 frames. """ # The flags defined on this type of frame. defined_flags = [] # The type of the frame. type = 0 def __init__(self, stream_id): self.stream_id = stream_id self.flags = set() def parse_flags(self, flag_byte): for flag, flag_bit in self.defined_flags: if flag_byte & flag_bit: self.flags.add(flag) return self.flags def serialize(self): raise NotImplementedError() def _get_len(self): raise NotImplementedError()
Define a mapping between byte and class.
## Code Before: class Frame(object): """ The base class for all HTTP/2.0 frames. """ # The flags defined on this type of frame. defined_flags = [] # The type of the frame. type = 0 def __init__(self, stream_id): self.stream_id = stream_id self.flags = set() def parse_flags(self, flag_byte): for flag, flag_bit in self.defined_flags: if flag_byte & flag_bit: self.flags.add(flag) return self.flags def serialize(self): raise NotImplementedError() def _get_len(self): raise NotImplementedError() ## Instruction: Define a mapping between byte and class. ## Code After: # A map of type byte to frame class. FRAMES = { 0x00: DataFrame } class Frame(object): """ The base class for all HTTP/2.0 frames. """ # The flags defined on this type of frame. defined_flags = [] # The type of the frame. type = 0 def __init__(self, stream_id): self.stream_id = stream_id self.flags = set() def parse_flags(self, flag_byte): for flag, flag_bit in self.defined_flags: if flag_byte & flag_bit: self.flags.add(flag) return self.flags def serialize(self): raise NotImplementedError() def _get_len(self): raise NotImplementedError()
+ # A map of type byte to frame class. + FRAMES = { + 0x00: DataFrame + } + + class Frame(object): """ The base class for all HTTP/2.0 frames. """ # The flags defined on this type of frame. defined_flags = [] # The type of the frame. type = 0 def __init__(self, stream_id): self.stream_id = stream_id self.flags = set() def parse_flags(self, flag_byte): for flag, flag_bit in self.defined_flags: if flag_byte & flag_bit: self.flags.add(flag) return self.flags def serialize(self): raise NotImplementedError() def _get_len(self): raise NotImplementedError()
dafd7689eaca4705ace7b462a1f039982d47cd71
panoply/errors.py
panoply/errors.py
class PanoplyException(Exception): def __init__(self, args=None, retryable=True): super(PanoplyException, self).__init__(args) self.retryable = retryable
class PanoplyException(Exception): def __init__(self, args=None, retryable=True): super(PanoplyException, self).__init__(args) self.retryable = retryable class IncorrectParamError(Exception): def __init__(self, msg: str = "Incorrect input parametr"): super().__init__(msg)
Add new exception class for ssh tunnel logic
Add new exception class for ssh tunnel logic
Python
mit
panoplyio/panoply-python-sdk
class PanoplyException(Exception): def __init__(self, args=None, retryable=True): super(PanoplyException, self).__init__(args) self.retryable = retryable + + class IncorrectParamError(Exception): + def __init__(self, msg: str = "Incorrect input parametr"): + super().__init__(msg) +
Add new exception class for ssh tunnel logic
## Code Before: class PanoplyException(Exception): def __init__(self, args=None, retryable=True): super(PanoplyException, self).__init__(args) self.retryable = retryable ## Instruction: Add new exception class for ssh tunnel logic ## Code After: class PanoplyException(Exception): def __init__(self, args=None, retryable=True): super(PanoplyException, self).__init__(args) self.retryable = retryable class IncorrectParamError(Exception): def __init__(self, msg: str = "Incorrect input parametr"): super().__init__(msg)
class PanoplyException(Exception): def __init__(self, args=None, retryable=True): super(PanoplyException, self).__init__(args) self.retryable = retryable + + + class IncorrectParamError(Exception): + def __init__(self, msg: str = "Incorrect input parametr"): + super().__init__(msg)
6eeecb5e36e5551ba3a3c35a9c7f52393d2f9d14
src/puzzle/problems/problem.py
src/puzzle/problems/problem.py
from src.data import meta class Problem(object): def __init__(self, name, lines): self.name = name self.lines = lines self._solutions = None self._constraints = [] def constrain(self, fn): self._constraints.append(fn) # Invalidate solutions. self._solutions = None def solutions(self): if self._solutions is None: self._solutions = meta.Meta( (k, v) for k, v in self._solve().items() if all( [fn(k, v) for fn in self._constraints] ) ) return self._solutions def _solve(self): """Solves Problem. Returns: dict Dict mapping solution to score. """ raise NotImplementedError()
from src.data import meta class Problem(object): def __init__(self, name, lines): self.name = name self.lines = lines self._solutions = None self._constraints = [] @property def kind(self): return str(type(self)).strip("'<>").split('.').pop() @property def solution(self): return self.solutions().peek() def constrain(self, fn): self._constraints.append(fn) # Invalidate solutions. self._solutions = None def solutions(self): if self._solutions is None: self._solutions = meta.Meta( (k, v) for k, v in self._solve().items() if all( [fn(k, v) for fn in self._constraints] ) ) return self._solutions def _solve(self): """Solves Problem. Returns: dict Dict mapping solution to score. """ raise NotImplementedError()
Add simple helper properties to Problem.
Add simple helper properties to Problem.
Python
mit
PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge
from src.data import meta class Problem(object): def __init__(self, name, lines): self.name = name self.lines = lines self._solutions = None self._constraints = [] + + @property + def kind(self): + return str(type(self)).strip("'<>").split('.').pop() + + @property + def solution(self): + return self.solutions().peek() def constrain(self, fn): self._constraints.append(fn) # Invalidate solutions. self._solutions = None def solutions(self): if self._solutions is None: self._solutions = meta.Meta( (k, v) for k, v in self._solve().items() if all( [fn(k, v) for fn in self._constraints] ) ) return self._solutions def _solve(self): """Solves Problem. Returns: dict Dict mapping solution to score. """ raise NotImplementedError()
Add simple helper properties to Problem.
## Code Before: from src.data import meta class Problem(object): def __init__(self, name, lines): self.name = name self.lines = lines self._solutions = None self._constraints = [] def constrain(self, fn): self._constraints.append(fn) # Invalidate solutions. self._solutions = None def solutions(self): if self._solutions is None: self._solutions = meta.Meta( (k, v) for k, v in self._solve().items() if all( [fn(k, v) for fn in self._constraints] ) ) return self._solutions def _solve(self): """Solves Problem. Returns: dict Dict mapping solution to score. """ raise NotImplementedError() ## Instruction: Add simple helper properties to Problem. ## Code After: from src.data import meta class Problem(object): def __init__(self, name, lines): self.name = name self.lines = lines self._solutions = None self._constraints = [] @property def kind(self): return str(type(self)).strip("'<>").split('.').pop() @property def solution(self): return self.solutions().peek() def constrain(self, fn): self._constraints.append(fn) # Invalidate solutions. self._solutions = None def solutions(self): if self._solutions is None: self._solutions = meta.Meta( (k, v) for k, v in self._solve().items() if all( [fn(k, v) for fn in self._constraints] ) ) return self._solutions def _solve(self): """Solves Problem. Returns: dict Dict mapping solution to score. """ raise NotImplementedError()
from src.data import meta class Problem(object): def __init__(self, name, lines): self.name = name self.lines = lines self._solutions = None self._constraints = [] + + @property + def kind(self): + return str(type(self)).strip("'<>").split('.').pop() + + @property + def solution(self): + return self.solutions().peek() def constrain(self, fn): self._constraints.append(fn) # Invalidate solutions. self._solutions = None def solutions(self): if self._solutions is None: self._solutions = meta.Meta( (k, v) for k, v in self._solve().items() if all( [fn(k, v) for fn in self._constraints] ) ) return self._solutions def _solve(self): """Solves Problem. Returns: dict Dict mapping solution to score. """ raise NotImplementedError()
1c19d7fb5914554b470a6d067902a9c61882ff4a
packs/softlayer/actions/destroy_instance.py
packs/softlayer/actions/destroy_instance.py
from lib.softlayer import SoftlayerBaseAction class SoftlayerDeleteInstance(SoftlayerBaseAction): def run(self, name): driver = self._get_driver() # go from name to Node Object node = [n for n in driver.list_nodes() if n.extra['hostname'] == name][0] # destroy the node self.logger.info('Destroying node...') node = driver.destroy_node(node) self.logger.info('Node successfully destroyed: {}'.format(node)) return
from lib.softlayer import SoftlayerBaseAction class SoftlayerDeleteInstance(SoftlayerBaseAction): def run(self, name): driver = self._get_driver() # go from name to Node Object try: node = [n for n in driver.list_nodes() if n.extra['hostname'] == name][0] except IndexError: raise Exception("Node with name {} not found in Softlayer".format(name)) # destroy the node self.logger.info('Destroying node...') node = driver.destroy_node(node) self.logger.info('Node successfully destroyed: {}'.format(node)) return
Return a sane error if there is no Nodes with that name instead of IndexError
Return a sane error if there is no Nodes with that name instead of IndexError
Python
apache-2.0
tonybaloney/st2contrib,StackStorm/st2contrib,tonybaloney/st2contrib,pearsontechnology/st2contrib,meirwah/st2contrib,psychopenguin/st2contrib,pidah/st2contrib,digideskio/st2contrib,digideskio/st2contrib,psychopenguin/st2contrib,meirwah/st2contrib,lmEshoo/st2contrib,pinterb/st2contrib,tonybaloney/st2contrib,pidah/st2contrib,lmEshoo/st2contrib,armab/st2contrib,pidah/st2contrib,dennybaa/st2contrib,StackStorm/st2contrib,dennybaa/st2contrib,pearsontechnology/st2contrib,StackStorm/st2contrib,armab/st2contrib,armab/st2contrib,pearsontechnology/st2contrib,pinterb/st2contrib,pearsontechnology/st2contrib
from lib.softlayer import SoftlayerBaseAction class SoftlayerDeleteInstance(SoftlayerBaseAction): def run(self, name): driver = self._get_driver() # go from name to Node Object + try: - node = [n for n in driver.list_nodes() if n.extra['hostname'] == name][0] + node = [n for n in driver.list_nodes() if n.extra['hostname'] == name][0] + except IndexError: + raise Exception("Node with name {} not found in Softlayer".format(name)) # destroy the node self.logger.info('Destroying node...') node = driver.destroy_node(node) self.logger.info('Node successfully destroyed: {}'.format(node)) return
Return a sane error if there is no Nodes with that name instead of IndexError
## Code Before: from lib.softlayer import SoftlayerBaseAction class SoftlayerDeleteInstance(SoftlayerBaseAction): def run(self, name): driver = self._get_driver() # go from name to Node Object node = [n for n in driver.list_nodes() if n.extra['hostname'] == name][0] # destroy the node self.logger.info('Destroying node...') node = driver.destroy_node(node) self.logger.info('Node successfully destroyed: {}'.format(node)) return ## Instruction: Return a sane error if there is no Nodes with that name instead of IndexError ## Code After: from lib.softlayer import SoftlayerBaseAction class SoftlayerDeleteInstance(SoftlayerBaseAction): def run(self, name): driver = self._get_driver() # go from name to Node Object try: node = [n for n in driver.list_nodes() if n.extra['hostname'] == name][0] except IndexError: raise Exception("Node with name {} not found in Softlayer".format(name)) # destroy the node self.logger.info('Destroying node...') node = driver.destroy_node(node) self.logger.info('Node successfully destroyed: {}'.format(node)) return
from lib.softlayer import SoftlayerBaseAction class SoftlayerDeleteInstance(SoftlayerBaseAction): def run(self, name): driver = self._get_driver() # go from name to Node Object + try: - node = [n for n in driver.list_nodes() if n.extra['hostname'] == name][0] + node = [n for n in driver.list_nodes() if n.extra['hostname'] == name][0] ? ++++ + except IndexError: + raise Exception("Node with name {} not found in Softlayer".format(name)) # destroy the node self.logger.info('Destroying node...') node = driver.destroy_node(node) self.logger.info('Node successfully destroyed: {}'.format(node)) return
7ec92591324717cfdefc8531549654f146e8b15c
test/unit/test_id_iterators.py
test/unit/test_id_iterators.py
from unittest import TestCase, main import re from uuid import UUID from jsonrpcclient.id_iterators import hex_iterator, uuid_iterator, \ random_iterator class TestHexIterator(TestCase): def test(self): i = hex_iterator() self.assertEqual('1', next(i)) i = hex_iterator(9) self.assertEqual('9', next(i)) self.assertEqual('a', next(i)) class TestUUIDIterator(TestCase): def test(self): i = uuid_iterator() # Raise ValueError if badly formed hexadecimal UUID string UUID(next(i), version=4) class TestRandomIterator(TestCase): def test(self): i = random_iterator() self.assertTrue(re.match('^[0-9,a-z]{8}$', next(i)))
from unittest import TestCase, main import re from uuid import UUID from jsonrpcclient.id_iterators import hex_iterator, uuid_iterator, \ random_iterator class TestHexIterator(TestCase): def test(self): i = hex_iterator() self.assertEqual('1', next(i)) i = hex_iterator(9) self.assertEqual('9', next(i)) self.assertEqual('a', next(i)) class TestUUIDIterator(TestCase): def test(self): i = uuid_iterator() # Raise ValueError if badly formed hexadecimal UUID string UUID(next(i), version=4) class TestRandomIterator(TestCase): def test(self): i = random_iterator() self.assertTrue(re.match('^[0-9,a-z]{8}$', next(i))) if __name__ == '__main__': main()
Add statements to run id_iterators tests
Add statements to run id_iterators tests Closes #8
Python
mit
bcb/jsonrpcclient
from unittest import TestCase, main import re from uuid import UUID from jsonrpcclient.id_iterators import hex_iterator, uuid_iterator, \ random_iterator class TestHexIterator(TestCase): def test(self): i = hex_iterator() self.assertEqual('1', next(i)) i = hex_iterator(9) self.assertEqual('9', next(i)) self.assertEqual('a', next(i)) class TestUUIDIterator(TestCase): def test(self): i = uuid_iterator() # Raise ValueError if badly formed hexadecimal UUID string UUID(next(i), version=4) class TestRandomIterator(TestCase): def test(self): i = random_iterator() self.assertTrue(re.match('^[0-9,a-z]{8}$', next(i))) + + if __name__ == '__main__': + main() +
Add statements to run id_iterators tests
## Code Before: from unittest import TestCase, main import re from uuid import UUID from jsonrpcclient.id_iterators import hex_iterator, uuid_iterator, \ random_iterator class TestHexIterator(TestCase): def test(self): i = hex_iterator() self.assertEqual('1', next(i)) i = hex_iterator(9) self.assertEqual('9', next(i)) self.assertEqual('a', next(i)) class TestUUIDIterator(TestCase): def test(self): i = uuid_iterator() # Raise ValueError if badly formed hexadecimal UUID string UUID(next(i), version=4) class TestRandomIterator(TestCase): def test(self): i = random_iterator() self.assertTrue(re.match('^[0-9,a-z]{8}$', next(i))) ## Instruction: Add statements to run id_iterators tests ## Code After: from unittest import TestCase, main import re from uuid import UUID from jsonrpcclient.id_iterators import hex_iterator, uuid_iterator, \ random_iterator class TestHexIterator(TestCase): def test(self): i = hex_iterator() self.assertEqual('1', next(i)) i = hex_iterator(9) self.assertEqual('9', next(i)) self.assertEqual('a', next(i)) class TestUUIDIterator(TestCase): def test(self): i = uuid_iterator() # Raise ValueError if badly formed hexadecimal UUID string UUID(next(i), version=4) class TestRandomIterator(TestCase): def test(self): i = random_iterator() self.assertTrue(re.match('^[0-9,a-z]{8}$', next(i))) if __name__ == '__main__': main()
from unittest import TestCase, main import re from uuid import UUID from jsonrpcclient.id_iterators import hex_iterator, uuid_iterator, \ random_iterator class TestHexIterator(TestCase): def test(self): i = hex_iterator() self.assertEqual('1', next(i)) i = hex_iterator(9) self.assertEqual('9', next(i)) self.assertEqual('a', next(i)) class TestUUIDIterator(TestCase): def test(self): i = uuid_iterator() # Raise ValueError if badly formed hexadecimal UUID string UUID(next(i), version=4) class TestRandomIterator(TestCase): def test(self): i = random_iterator() self.assertTrue(re.match('^[0-9,a-z]{8}$', next(i))) + + + if __name__ == '__main__': + main()
0337d51dc2c65c376f30046a0869c6fabf012cd0
webfinger/__init__.py
webfinger/__init__.py
__version__ = "3.0.0.dev0" # Backwards compatibility stubs from webfinger.client.requests import WebFingerClient from webfinger.objects import WebFingerResponse from webfinger.exceptions import * _client = WebFingerClient() def finger(resource, rel=None): """Invoke finger without creating a WebFingerClient instance. args: resource - resource to look up rel - relation to request from the server """ return _client.finger(resource, rel=rel)
__version__ = "3.0.0.dev1" from webfinger.client import BaseWebFingerClient from webfinger.client.requests import WebFingerClient from webfinger.objects import WebFingerResponse, WebFingerBuilder from webfinger.exceptions import * _client = WebFingerClient() def finger(resource, rel=None): """Invoke finger without creating a WebFingerClient instance. args: resource - resource to look up rel - relation to request from the server """ return _client.finger(resource, rel=rel)
Improve docs and import WebFingerBuilder
Improve docs and import WebFingerBuilder
Python
bsd-3-clause
Elizafox/python-webfinger
- __version__ = "3.0.0.dev0" + __version__ = "3.0.0.dev1" - # Backwards compatibility stubs + from webfinger.client import BaseWebFingerClient from webfinger.client.requests import WebFingerClient - from webfinger.objects import WebFingerResponse + from webfinger.objects import WebFingerResponse, WebFingerBuilder from webfinger.exceptions import * _client = WebFingerClient() def finger(resource, rel=None): """Invoke finger without creating a WebFingerClient instance. args: resource - resource to look up rel - relation to request from the server """ return _client.finger(resource, rel=rel)
Improve docs and import WebFingerBuilder
## Code Before: __version__ = "3.0.0.dev0" # Backwards compatibility stubs from webfinger.client.requests import WebFingerClient from webfinger.objects import WebFingerResponse from webfinger.exceptions import * _client = WebFingerClient() def finger(resource, rel=None): """Invoke finger without creating a WebFingerClient instance. args: resource - resource to look up rel - relation to request from the server """ return _client.finger(resource, rel=rel) ## Instruction: Improve docs and import WebFingerBuilder ## Code After: __version__ = "3.0.0.dev1" from webfinger.client import BaseWebFingerClient from webfinger.client.requests import WebFingerClient from webfinger.objects import WebFingerResponse, WebFingerBuilder from webfinger.exceptions import * _client = WebFingerClient() def finger(resource, rel=None): """Invoke finger without creating a WebFingerClient instance. args: resource - resource to look up rel - relation to request from the server """ return _client.finger(resource, rel=rel)
- __version__ = "3.0.0.dev0" ? ^ + __version__ = "3.0.0.dev1" ? ^ - # Backwards compatibility stubs + from webfinger.client import BaseWebFingerClient from webfinger.client.requests import WebFingerClient - from webfinger.objects import WebFingerResponse + from webfinger.objects import WebFingerResponse, WebFingerBuilder ? ++++++++++++++++++ from webfinger.exceptions import * _client = WebFingerClient() def finger(resource, rel=None): """Invoke finger without creating a WebFingerClient instance. args: resource - resource to look up rel - relation to request from the server """ return _client.finger(resource, rel=rel)
01eb74ebca81f79ab829073f163b028d3e98f055
setup.py
setup.py
''' cd dropbox/codes/check_forbidden py -3.4 setup.py py2exe Libraries used: import tkinter import tkinter.filedialog import csv import os import re from time import sleep import zipfile ''' from distutils.core import setup import py2exe setup( console=[{'author': 'Shun Sakurai', 'script': 'check_forbidden.py', 'version': '1.4.0', }], options={'py2exe': { 'bundle_files': 2, 'compressed': True, 'excludes': ['_hashlib', '_frozen_importlib', 'argparse', '_lzma', '_bz2', '_ssl', 'calendar', 'datetime', 'difflib', 'doctest', 'inspect', 'locale', 'optparse', 'pdb', 'pickle', 'pydoc', 'pyexpat', 'pyreadline'], }} )
''' cd dropbox/codes/check_forbidden py -3.4 setup.py py2exe Libraries used: import tkinter import tkinter.filedialog import csv import os import re from time import sleep import zipfile ''' from distutils.core import setup import py2exe setup( console=[{'author': 'Shun Sakurai', 'dest_base': 'Check Forbidden', 'script': 'check_forbidden.py', 'version': '1.4.0', }], options={'py2exe': { 'bundle_files': 2, 'compressed': True, 'excludes': ['_hashlib', '_frozen_importlib', 'argparse', '_lzma', '_bz2', '_ssl', 'calendar', 'datetime', 'difflib', 'doctest', 'inspect', 'locale', 'optparse', 'pdb', 'pickle', 'pydoc', 'pyexpat', 'pyreadline'], }} )
Change the application name to 'Check Forbidden'
Change the application name to 'Check Forbidden'
Python
mit
ShunSakurai/check_forbidden,ShunSakurai/check_forbidden
''' cd dropbox/codes/check_forbidden py -3.4 setup.py py2exe Libraries used: import tkinter import tkinter.filedialog import csv import os import re from time import sleep import zipfile ''' from distutils.core import setup import py2exe setup( console=[{'author': 'Shun Sakurai', + 'dest_base': 'Check Forbidden', 'script': 'check_forbidden.py', 'version': '1.4.0', }], options={'py2exe': { 'bundle_files': 2, 'compressed': True, 'excludes': ['_hashlib', '_frozen_importlib', 'argparse', '_lzma', '_bz2', '_ssl', 'calendar', 'datetime', 'difflib', 'doctest', 'inspect', 'locale', 'optparse', 'pdb', 'pickle', 'pydoc', 'pyexpat', 'pyreadline'], }} )
Change the application name to 'Check Forbidden'
## Code Before: ''' cd dropbox/codes/check_forbidden py -3.4 setup.py py2exe Libraries used: import tkinter import tkinter.filedialog import csv import os import re from time import sleep import zipfile ''' from distutils.core import setup import py2exe setup( console=[{'author': 'Shun Sakurai', 'script': 'check_forbidden.py', 'version': '1.4.0', }], options={'py2exe': { 'bundle_files': 2, 'compressed': True, 'excludes': ['_hashlib', '_frozen_importlib', 'argparse', '_lzma', '_bz2', '_ssl', 'calendar', 'datetime', 'difflib', 'doctest', 'inspect', 'locale', 'optparse', 'pdb', 'pickle', 'pydoc', 'pyexpat', 'pyreadline'], }} ) ## Instruction: Change the application name to 'Check Forbidden' ## Code After: ''' cd dropbox/codes/check_forbidden py -3.4 setup.py py2exe Libraries used: import tkinter import tkinter.filedialog import csv import os import re from time import sleep import zipfile ''' from distutils.core import setup import py2exe setup( console=[{'author': 'Shun Sakurai', 'dest_base': 'Check Forbidden', 'script': 'check_forbidden.py', 'version': '1.4.0', }], options={'py2exe': { 'bundle_files': 2, 'compressed': True, 'excludes': ['_hashlib', '_frozen_importlib', 'argparse', '_lzma', '_bz2', '_ssl', 'calendar', 'datetime', 'difflib', 'doctest', 'inspect', 'locale', 'optparse', 'pdb', 'pickle', 'pydoc', 'pyexpat', 'pyreadline'], }} )
''' cd dropbox/codes/check_forbidden py -3.4 setup.py py2exe Libraries used: import tkinter import tkinter.filedialog import csv import os import re from time import sleep import zipfile ''' from distutils.core import setup import py2exe setup( console=[{'author': 'Shun Sakurai', + 'dest_base': 'Check Forbidden', 'script': 'check_forbidden.py', 'version': '1.4.0', }], options={'py2exe': { 'bundle_files': 2, 'compressed': True, 'excludes': ['_hashlib', '_frozen_importlib', 'argparse', '_lzma', '_bz2', '_ssl', 'calendar', 'datetime', 'difflib', 'doctest', 'inspect', 'locale', 'optparse', 'pdb', 'pickle', 'pydoc', 'pyexpat', 'pyreadline'], }} )
2f039066530533b1a8ae82076ed745c1f2e03688
app-tasks/rf/src/rf/uploads/geotiff/create_images.py
app-tasks/rf/src/rf/uploads/geotiff/create_images.py
import os from rf.models import Image from rf.utils.io import Visibility from .io import get_geotiff_size_bytes, get_geotiff_resolution from .create_bands import create_geotiff_bands def create_geotiff_image(organizationId, tif_path, sourceuri, filename=None, visibility=Visibility.PRIVATE, imageMetadata={}, scene=None, owner=None): """Create an Image object from a GeoTIFF. Args: orgnizationId (str): UUID of organization that this image belongs to tif_path (str): Local path to tif file sourceuri (str): remote source of image visibility (str): accessibility level for object imageMetadata (dict): Optional dict of metadata about the image scene (Scene): Optional Scene object holding this image owner (str): Optional owner of an image """ filename = filename if filename else os.path.basename(tif_path) return Image( organizationId, get_geotiff_size_bytes(tif_path), visibility, filename, sourceuri, create_geotiff_bands(tif_path), imageMetadata, # TIFFs can have a different resolution in the X and Y directions, that is, pixels can be # rectangular with respect to the ground. The RF API doesn't currently support this, so just # select the X resolution. get_geotiff_resolution(tif_path)[0], [], scene=scene, owner=owner )
import os from rf.models import Image from rf.utils.io import Visibility from .io import get_geotiff_size_bytes, get_geotiff_resolution from .create_bands import create_geotiff_bands def create_geotiff_image(organizationId, tif_path, sourceuri, filename=None, visibility=Visibility.PRIVATE, imageMetadata={}, scene=None, owner=None, band_create_function=create_geotiff_bands): """Create an Image object from a GeoTIFF. Args: orgnizationId (str): UUID of organization that this image belongs to tif_path (str): Local path to tif file sourceuri (str): remote source of image visibility (str): accessibility level for object imageMetadata (dict): Optional dict of metadata about the image scene (Scene): Optional Scene object holding this image owner (str): Optional owner of an image band_create_function (function): function to aid in creating bands for a geotiff """ filename = filename if filename else os.path.basename(tif_path) return Image( organizationId, get_geotiff_size_bytes(tif_path), visibility, filename, sourceuri, band_create_function(tif_path), imageMetadata, # TIFFs can have a different resolution in the X and Y directions, that is, pixels can be # rectangular with respect to the ground. The RF API doesn't currently support this, so just # select the X resolution. get_geotiff_resolution(tif_path)[0], [], scene=scene, owner=owner )
Add ability to define band create function for geotiff images
Add ability to define band create function for geotiff images This commit makes defining bands for custom geotiffs more flexible by allowing passing custom functions for defining bands for different datasources or other variables - subsequent commits for MODIS take advantage of this
Python
apache-2.0
raster-foundry/raster-foundry,aaronxsu/raster-foundry,azavea/raster-foundry,azavea/raster-foundry,aaronxsu/raster-foundry,aaronxsu/raster-foundry,azavea/raster-foundry,azavea/raster-foundry,azavea/raster-foundry,raster-foundry/raster-foundry,raster-foundry/raster-foundry,aaronxsu/raster-foundry
import os from rf.models import Image from rf.utils.io import Visibility from .io import get_geotiff_size_bytes, get_geotiff_resolution from .create_bands import create_geotiff_bands def create_geotiff_image(organizationId, tif_path, sourceuri, filename=None, visibility=Visibility.PRIVATE, imageMetadata={}, scene=None, - owner=None): + owner=None, band_create_function=create_geotiff_bands): """Create an Image object from a GeoTIFF. Args: orgnizationId (str): UUID of organization that this image belongs to tif_path (str): Local path to tif file sourceuri (str): remote source of image visibility (str): accessibility level for object imageMetadata (dict): Optional dict of metadata about the image scene (Scene): Optional Scene object holding this image owner (str): Optional owner of an image + band_create_function (function): function to aid in creating bands for a geotiff """ filename = filename if filename else os.path.basename(tif_path) return Image( organizationId, get_geotiff_size_bytes(tif_path), visibility, filename, sourceuri, - create_geotiff_bands(tif_path), + band_create_function(tif_path), imageMetadata, # TIFFs can have a different resolution in the X and Y directions, that is, pixels can be # rectangular with respect to the ground. The RF API doesn't currently support this, so just # select the X resolution. get_geotiff_resolution(tif_path)[0], [], scene=scene, owner=owner )
Add ability to define band create function for geotiff images
## Code Before: import os from rf.models import Image from rf.utils.io import Visibility from .io import get_geotiff_size_bytes, get_geotiff_resolution from .create_bands import create_geotiff_bands def create_geotiff_image(organizationId, tif_path, sourceuri, filename=None, visibility=Visibility.PRIVATE, imageMetadata={}, scene=None, owner=None): """Create an Image object from a GeoTIFF. Args: orgnizationId (str): UUID of organization that this image belongs to tif_path (str): Local path to tif file sourceuri (str): remote source of image visibility (str): accessibility level for object imageMetadata (dict): Optional dict of metadata about the image scene (Scene): Optional Scene object holding this image owner (str): Optional owner of an image """ filename = filename if filename else os.path.basename(tif_path) return Image( organizationId, get_geotiff_size_bytes(tif_path), visibility, filename, sourceuri, create_geotiff_bands(tif_path), imageMetadata, # TIFFs can have a different resolution in the X and Y directions, that is, pixels can be # rectangular with respect to the ground. The RF API doesn't currently support this, so just # select the X resolution. get_geotiff_resolution(tif_path)[0], [], scene=scene, owner=owner ) ## Instruction: Add ability to define band create function for geotiff images ## Code After: import os from rf.models import Image from rf.utils.io import Visibility from .io import get_geotiff_size_bytes, get_geotiff_resolution from .create_bands import create_geotiff_bands def create_geotiff_image(organizationId, tif_path, sourceuri, filename=None, visibility=Visibility.PRIVATE, imageMetadata={}, scene=None, owner=None, band_create_function=create_geotiff_bands): """Create an Image object from a GeoTIFF. Args: orgnizationId (str): UUID of organization that this image belongs to tif_path (str): Local path to tif file sourceuri (str): remote source of image visibility (str): accessibility level for object imageMetadata (dict): Optional dict of metadata about the image scene (Scene): Optional Scene object holding this image owner (str): Optional owner of an image band_create_function (function): function to aid in creating bands for a geotiff """ filename = filename if filename else os.path.basename(tif_path) return Image( organizationId, get_geotiff_size_bytes(tif_path), visibility, filename, sourceuri, band_create_function(tif_path), imageMetadata, # TIFFs can have a different resolution in the X and Y directions, that is, pixels can be # rectangular with respect to the ground. The RF API doesn't currently support this, so just # select the X resolution. get_geotiff_resolution(tif_path)[0], [], scene=scene, owner=owner )
import os from rf.models import Image from rf.utils.io import Visibility from .io import get_geotiff_size_bytes, get_geotiff_resolution from .create_bands import create_geotiff_bands def create_geotiff_image(organizationId, tif_path, sourceuri, filename=None, visibility=Visibility.PRIVATE, imageMetadata={}, scene=None, - owner=None): + owner=None, band_create_function=create_geotiff_bands): """Create an Image object from a GeoTIFF. Args: orgnizationId (str): UUID of organization that this image belongs to tif_path (str): Local path to tif file sourceuri (str): remote source of image visibility (str): accessibility level for object imageMetadata (dict): Optional dict of metadata about the image scene (Scene): Optional Scene object holding this image owner (str): Optional owner of an image + band_create_function (function): function to aid in creating bands for a geotiff """ filename = filename if filename else os.path.basename(tif_path) return Image( organizationId, get_geotiff_size_bytes(tif_path), visibility, filename, sourceuri, - create_geotiff_bands(tif_path), + band_create_function(tif_path), imageMetadata, # TIFFs can have a different resolution in the X and Y directions, that is, pixels can be # rectangular with respect to the ground. The RF API doesn't currently support this, so just # select the X resolution. get_geotiff_resolution(tif_path)[0], [], scene=scene, owner=owner )
464bc1b511415459e99700b94101776d00b23796
indra/pre_assemble_for_db/pre_assemble_script.py
indra/pre_assemble_for_db/pre_assemble_script.py
import indra.tools.assemble_corpus as ac def process_statements(stmts): stmts = ac.map_grounding(stmts) stmts = ac.map_sequence(stmts) stmts = ac.run_preassembly(stmts, return_toplevel=False) return stmts
import indra.tools.assemble_corpus as ac from indra.db.util import get_statements, insert_pa_stmts def process_statements(stmts, num_procs=1): stmts = ac.map_grounding(stmts) stmts = ac.map_sequence(stmts) stmts = ac.run_preassembly(stmts, return_toplevel=False, poolsize=num_procs) return stmts def preassemble_db_stmts(db, num_procs, *clauses): """Run pre-assembly on a set of statements in the database.""" stmts = get_statements(clauses, db=db, do_stmt_count=False) pa_stmts = process_statements(stmts, num_procs) insert_pa_stmts(db, pa_stmts) return pa_stmts
Create function to handle full pipeline.
Create function to handle full pipeline.
Python
bsd-2-clause
bgyori/indra,johnbachman/indra,bgyori/indra,sorgerlab/belpy,pvtodorov/indra,johnbachman/indra,sorgerlab/indra,bgyori/indra,johnbachman/belpy,pvtodorov/indra,sorgerlab/belpy,johnbachman/belpy,sorgerlab/indra,sorgerlab/belpy,johnbachman/indra,johnbachman/belpy,sorgerlab/indra,pvtodorov/indra,pvtodorov/indra
import indra.tools.assemble_corpus as ac + from indra.db.util import get_statements, insert_pa_stmts + - def process_statements(stmts): + def process_statements(stmts, num_procs=1): stmts = ac.map_grounding(stmts) stmts = ac.map_sequence(stmts) - stmts = ac.run_preassembly(stmts, return_toplevel=False) + stmts = ac.run_preassembly(stmts, return_toplevel=False, + poolsize=num_procs) return stmts + + def preassemble_db_stmts(db, num_procs, *clauses): + """Run pre-assembly on a set of statements in the database.""" + stmts = get_statements(clauses, db=db, do_stmt_count=False) + pa_stmts = process_statements(stmts, num_procs) + insert_pa_stmts(db, pa_stmts) + return pa_stmts +
Create function to handle full pipeline.
## Code Before: import indra.tools.assemble_corpus as ac def process_statements(stmts): stmts = ac.map_grounding(stmts) stmts = ac.map_sequence(stmts) stmts = ac.run_preassembly(stmts, return_toplevel=False) return stmts ## Instruction: Create function to handle full pipeline. ## Code After: import indra.tools.assemble_corpus as ac from indra.db.util import get_statements, insert_pa_stmts def process_statements(stmts, num_procs=1): stmts = ac.map_grounding(stmts) stmts = ac.map_sequence(stmts) stmts = ac.run_preassembly(stmts, return_toplevel=False, poolsize=num_procs) return stmts def preassemble_db_stmts(db, num_procs, *clauses): """Run pre-assembly on a set of statements in the database.""" stmts = get_statements(clauses, db=db, do_stmt_count=False) pa_stmts = process_statements(stmts, num_procs) insert_pa_stmts(db, pa_stmts) return pa_stmts
import indra.tools.assemble_corpus as ac + from indra.db.util import get_statements, insert_pa_stmts + - def process_statements(stmts): + def process_statements(stmts, num_procs=1): ? +++++++++++++ stmts = ac.map_grounding(stmts) stmts = ac.map_sequence(stmts) - stmts = ac.run_preassembly(stmts, return_toplevel=False) ? ^ + stmts = ac.run_preassembly(stmts, return_toplevel=False, ? ^ + poolsize=num_procs) return stmts + + + def preassemble_db_stmts(db, num_procs, *clauses): + """Run pre-assembly on a set of statements in the database.""" + stmts = get_statements(clauses, db=db, do_stmt_count=False) + pa_stmts = process_statements(stmts, num_procs) + insert_pa_stmts(db, pa_stmts) + return pa_stmts
d814c9c131f2c2957173302f7c4c1cbf2b719b45
check_rfc_header.py
check_rfc_header.py
import os from travistooling import ROOT def get_rfc_readmes(repo): rfcs_dir = os.path.join(repo, 'docs', 'rfcs') for root, _, filenames in os.walk(rfcs_dir): for f in filenames: if f == 'README.md': yield os.path.join(root, f) print('*** Checking RFC headers') for f in get_rfc_readmes(ROOT): print('*** Checking header for %s' % os.path.relpath(f, start=ROOT)) filename = os.path.basename(os.path.dirname(f)) number, name = filename.split('-', 1) contents = open(f).read() header = contents.splitlines()[:3] assert header[0].startswith('# RFC %03d: ' % int(number)) assert header[1] == '' print(f, name) print(header)
import datetime as dt import os from travistooling import git, ROOT def get_rfc_readmes(repo): rfcs_dir = os.path.join(repo, 'docs', 'rfcs') for root, _, filenames in os.walk(rfcs_dir): for f in filenames: if f == 'README.md': yield os.path.join(root, f) if __name__ == '__main__': print('*** Checking RFC headers') for f in get_rfc_readmes(ROOT): print('*** Checking header for %s' % os.path.relpath(f, start=ROOT)) filename = os.path.basename(os.path.dirname(f)) number, name = filename.split('-', 1) contents = open(f).read() header = contents.splitlines()[:3] update_timestamp = git('log', '-1', '--format=%ct', f) last_updated = dt.datetime.fromtimestamp(int(update_timestamp)) assert header[0].startswith('# RFC %03d: ' % int(number)) assert header[1] == '' expected_date_str = '**Last updated: %s.**' % last_updated.strftime('%d %B %Y') assert header[2] == expected_date_str, (header[2], expected_date_str)
Check update dates in the RFC headers
Check update dates in the RFC headers
Python
mit
wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api
+ import datetime as dt import os - from travistooling import ROOT + from travistooling import git, ROOT def get_rfc_readmes(repo): rfcs_dir = os.path.join(repo, 'docs', 'rfcs') for root, _, filenames in os.walk(rfcs_dir): for f in filenames: if f == 'README.md': yield os.path.join(root, f) + if __name__ == '__main__': - print('*** Checking RFC headers') + print('*** Checking RFC headers') - for f in get_rfc_readmes(ROOT): + for f in get_rfc_readmes(ROOT): - print('*** Checking header for %s' % os.path.relpath(f, start=ROOT)) + print('*** Checking header for %s' % os.path.relpath(f, start=ROOT)) - filename = os.path.basename(os.path.dirname(f)) + filename = os.path.basename(os.path.dirname(f)) - number, name = filename.split('-', 1) + number, name = filename.split('-', 1) - contents = open(f).read() + contents = open(f).read() - header = contents.splitlines()[:3] + header = contents.splitlines()[:3] - assert header[0].startswith('# RFC %03d: ' % int(number)) - assert header[1] == '' + update_timestamp = git('log', '-1', '--format=%ct', f) + last_updated = dt.datetime.fromtimestamp(int(update_timestamp)) - print(f, name) - print(header) + assert header[0].startswith('# RFC %03d: ' % int(number)) + assert header[1] == '' + expected_date_str = '**Last updated: %s.**' % last_updated.strftime('%d %B %Y') + assert header[2] == expected_date_str, (header[2], expected_date_str)
Check update dates in the RFC headers
## Code Before: import os from travistooling import ROOT def get_rfc_readmes(repo): rfcs_dir = os.path.join(repo, 'docs', 'rfcs') for root, _, filenames in os.walk(rfcs_dir): for f in filenames: if f == 'README.md': yield os.path.join(root, f) print('*** Checking RFC headers') for f in get_rfc_readmes(ROOT): print('*** Checking header for %s' % os.path.relpath(f, start=ROOT)) filename = os.path.basename(os.path.dirname(f)) number, name = filename.split('-', 1) contents = open(f).read() header = contents.splitlines()[:3] assert header[0].startswith('# RFC %03d: ' % int(number)) assert header[1] == '' print(f, name) print(header) ## Instruction: Check update dates in the RFC headers ## Code After: import datetime as dt import os from travistooling import git, ROOT def get_rfc_readmes(repo): rfcs_dir = os.path.join(repo, 'docs', 'rfcs') for root, _, filenames in os.walk(rfcs_dir): for f in filenames: if f == 'README.md': yield os.path.join(root, f) if __name__ == '__main__': print('*** Checking RFC headers') for f in get_rfc_readmes(ROOT): print('*** Checking header for %s' % os.path.relpath(f, start=ROOT)) filename = os.path.basename(os.path.dirname(f)) number, name = filename.split('-', 1) contents = open(f).read() header = contents.splitlines()[:3] update_timestamp = git('log', '-1', '--format=%ct', f) last_updated = dt.datetime.fromtimestamp(int(update_timestamp)) assert header[0].startswith('# RFC %03d: ' % int(number)) assert header[1] == '' expected_date_str = '**Last updated: %s.**' % last_updated.strftime('%d %B %Y') assert header[2] == expected_date_str, (header[2], expected_date_str)
+ import datetime as dt import os - from travistooling import ROOT + from travistooling import git, ROOT ? +++++ def get_rfc_readmes(repo): rfcs_dir = os.path.join(repo, 'docs', 'rfcs') for root, _, filenames in os.walk(rfcs_dir): for f in filenames: if f == 'README.md': yield os.path.join(root, f) + if __name__ == '__main__': - print('*** Checking RFC headers') + print('*** Checking RFC headers') ? ++++ - for f in get_rfc_readmes(ROOT): + for f in get_rfc_readmes(ROOT): ? ++++ - print('*** Checking header for %s' % os.path.relpath(f, start=ROOT)) + print('*** Checking header for %s' % os.path.relpath(f, start=ROOT)) ? ++++ - filename = os.path.basename(os.path.dirname(f)) + filename = os.path.basename(os.path.dirname(f)) ? ++++ - number, name = filename.split('-', 1) + number, name = filename.split('-', 1) ? ++++ - contents = open(f).read() + contents = open(f).read() ? ++++ - header = contents.splitlines()[:3] + header = contents.splitlines()[:3] ? ++++ - assert header[0].startswith('# RFC %03d: ' % int(number)) - assert header[1] == '' + update_timestamp = git('log', '-1', '--format=%ct', f) + last_updated = dt.datetime.fromtimestamp(int(update_timestamp)) - print(f, name) - print(header) + assert header[0].startswith('# RFC %03d: ' % int(number)) + assert header[1] == '' + expected_date_str = '**Last updated: %s.**' % last_updated.strftime('%d %B %Y') + assert header[2] == expected_date_str, (header[2], expected_date_str)
109fc84cb307083f6a01317bb5b5bea0578088d3
bloop/__init__.py
bloop/__init__.py
from bloop.engine import Engine, ObjectsNotFound, ConstraintViolation from bloop.column import Column, GlobalSecondaryIndex, LocalSecondaryIndex from bloop.types import ( String, Float, Integer, Binary, StringSet, FloatSet, IntegerSet, BinarySet, Null, Boolean, Map, List ) __all__ = [ "Engine", "ObjectsNotFound", "ConstraintViolation", "Column", "GlobalSecondaryIndex", "LocalSecondaryIndex", "String", "Float", "Integer", "Binary", "StringSet", "FloatSet", "IntegerSet", "BinarySet", "Null", "Boolean", "Map", "List" ]
from bloop.engine import Engine, ObjectsNotFound, ConstraintViolation from bloop.column import Column, GlobalSecondaryIndex, LocalSecondaryIndex from bloop.types import ( String, UUID, Float, Integer, Binary, StringSet, FloatSet, IntegerSet, BinarySet, Null, Boolean, Map, List ) __all__ = [ "Engine", "ObjectsNotFound", "ConstraintViolation", "Column", "GlobalSecondaryIndex", "LocalSecondaryIndex", "String", "UUID", "Float", "Integer", "Binary", "StringSet", "FloatSet", "IntegerSet", "BinarySet", "Null", "Boolean", "Map", "List" ]
Add UUID to bloop __all__
Add UUID to bloop __all__
Python
mit
numberoverzero/bloop,numberoverzero/bloop
from bloop.engine import Engine, ObjectsNotFound, ConstraintViolation from bloop.column import Column, GlobalSecondaryIndex, LocalSecondaryIndex from bloop.types import ( - String, Float, Integer, Binary, StringSet, FloatSet, + String, UUID, Float, Integer, Binary, StringSet, FloatSet, IntegerSet, BinarySet, Null, Boolean, Map, List ) __all__ = [ "Engine", "ObjectsNotFound", "ConstraintViolation", "Column", "GlobalSecondaryIndex", "LocalSecondaryIndex", - "String", "Float", "Integer", "Binary", "StringSet", "FloatSet", + "String", "UUID", "Float", "Integer", "Binary", "StringSet", "FloatSet", "IntegerSet", "BinarySet", "Null", "Boolean", "Map", "List" ]
Add UUID to bloop __all__
## Code Before: from bloop.engine import Engine, ObjectsNotFound, ConstraintViolation from bloop.column import Column, GlobalSecondaryIndex, LocalSecondaryIndex from bloop.types import ( String, Float, Integer, Binary, StringSet, FloatSet, IntegerSet, BinarySet, Null, Boolean, Map, List ) __all__ = [ "Engine", "ObjectsNotFound", "ConstraintViolation", "Column", "GlobalSecondaryIndex", "LocalSecondaryIndex", "String", "Float", "Integer", "Binary", "StringSet", "FloatSet", "IntegerSet", "BinarySet", "Null", "Boolean", "Map", "List" ] ## Instruction: Add UUID to bloop __all__ ## Code After: from bloop.engine import Engine, ObjectsNotFound, ConstraintViolation from bloop.column import Column, GlobalSecondaryIndex, LocalSecondaryIndex from bloop.types import ( String, UUID, Float, Integer, Binary, StringSet, FloatSet, IntegerSet, BinarySet, Null, Boolean, Map, List ) __all__ = [ "Engine", "ObjectsNotFound", "ConstraintViolation", "Column", "GlobalSecondaryIndex", "LocalSecondaryIndex", "String", "UUID", "Float", "Integer", "Binary", "StringSet", "FloatSet", "IntegerSet", "BinarySet", "Null", "Boolean", "Map", "List" ]
from bloop.engine import Engine, ObjectsNotFound, ConstraintViolation from bloop.column import Column, GlobalSecondaryIndex, LocalSecondaryIndex from bloop.types import ( - String, Float, Integer, Binary, StringSet, FloatSet, + String, UUID, Float, Integer, Binary, StringSet, FloatSet, ? ++++++ IntegerSet, BinarySet, Null, Boolean, Map, List ) __all__ = [ "Engine", "ObjectsNotFound", "ConstraintViolation", "Column", "GlobalSecondaryIndex", "LocalSecondaryIndex", - "String", "Float", "Integer", "Binary", "StringSet", "FloatSet", + "String", "UUID", "Float", "Integer", "Binary", "StringSet", "FloatSet", ? ++++++++ "IntegerSet", "BinarySet", "Null", "Boolean", "Map", "List" ]
b90f01bb8e10751ccfa51872dc32054b5be31d1b
vishwin_http/__init__.py
vishwin_http/__init__.py
from flask import Flask from werkzeug.contrib.cache import FileSystemCache import pkg_resources app=Flask(__name__) #app.config.from_object('config') cache=FileSystemCache(pkg_resources.resource_filename('vishwin_http', 'cache'), default_timeout=60 * 60) # one hour timeout import vishwin_http.views
from flask import Flask from werkzeug.contrib.cache import MemcachedCache import pkg_resources app=Flask(__name__) app.config.from_object('config') # set up a memcached Werkzeug cache, prefixing each key, with default timeout of one hour cache=MemcachedCache(servers=app.config['MEMCACHED_SERVERS'], key_prefix=app.config['MEMCACHED_KEYPREFIX'], default_timeout=60 * 60) import vishwin_http.views
Switch to memcached cache backend
Switch to memcached cache backend - Reinstate config file - Read server locations and key prefix from config
Python
mpl-2.0
vishwin/vishwin.info-http,vishwin/vishwin.info-http,vishwin/vishwin.info-http
from flask import Flask - from werkzeug.contrib.cache import FileSystemCache + from werkzeug.contrib.cache import MemcachedCache import pkg_resources app=Flask(__name__) - #app.config.from_object('config') + app.config.from_object('config') - cache=FileSystemCache(pkg_resources.resource_filename('vishwin_http', 'cache'), default_timeout=60 * 60) # one hour timeout + # set up a memcached Werkzeug cache, prefixing each key, with default timeout of one hour + cache=MemcachedCache(servers=app.config['MEMCACHED_SERVERS'], key_prefix=app.config['MEMCACHED_KEYPREFIX'], default_timeout=60 * 60) import vishwin_http.views
Switch to memcached cache backend
## Code Before: from flask import Flask from werkzeug.contrib.cache import FileSystemCache import pkg_resources app=Flask(__name__) #app.config.from_object('config') cache=FileSystemCache(pkg_resources.resource_filename('vishwin_http', 'cache'), default_timeout=60 * 60) # one hour timeout import vishwin_http.views ## Instruction: Switch to memcached cache backend ## Code After: from flask import Flask from werkzeug.contrib.cache import MemcachedCache import pkg_resources app=Flask(__name__) app.config.from_object('config') # set up a memcached Werkzeug cache, prefixing each key, with default timeout of one hour cache=MemcachedCache(servers=app.config['MEMCACHED_SERVERS'], key_prefix=app.config['MEMCACHED_KEYPREFIX'], default_timeout=60 * 60) import vishwin_http.views
from flask import Flask - from werkzeug.contrib.cache import FileSystemCache ? ^^^^^^^^ + from werkzeug.contrib.cache import MemcachedCache ? ^ ++++++ import pkg_resources app=Flask(__name__) - #app.config.from_object('config') ? - + app.config.from_object('config') - cache=FileSystemCache(pkg_resources.resource_filename('vishwin_http', 'cache'), default_timeout=60 * 60) # one hour timeout + # set up a memcached Werkzeug cache, prefixing each key, with default timeout of one hour + cache=MemcachedCache(servers=app.config['MEMCACHED_SERVERS'], key_prefix=app.config['MEMCACHED_KEYPREFIX'], default_timeout=60 * 60) import vishwin_http.views
853eb4896315c7fc60b1cbd7c87be9f7674f01ba
urls.py
urls.py
from django.conf.urls.defaults import * from django.contrib import admin from django.contrib.auth.decorators import login_required from django.views.generic.simple import direct_to_template import settings admin.autodiscover() urlpatterns = patterns('', (r'^admin/', include(admin.site.urls)), (r'^idp/', include('authentic.idp.urls')), (r'^accounts/', include('registration.urls')), (r'^$', login_required(direct_to_template), { 'template': 'index.html' }, 'index'), ) if settings.AUTH_OPENID: urlpatterns += patterns('', (r'^openid/', include('django_authopenid.urls')), ) if settings.AUTH_SSL: urlpatterns += patterns('', url(r'^sslauth/$', 'authentic.sslauth.login_ssl.process_request', name='user_signin_ssl'), url(r'^error_ssl/$', direct_to_template, {'template': 'error_ssl.html'}, 'error_ssl'), ) if settings.STATIC_SERVE: urlpatterns += patterns('', url( regex = r'^media/(?P<path>.*)$', view = 'django.views.static.serve', kwargs = {'document_root': settings.MEDIA_ROOT}), )
from django.conf.urls.defaults import * from django.contrib import admin from django.contrib.auth.decorators import login_required from django.views.generic.simple import direct_to_template import settings admin.autodiscover() urlpatterns = patterns('', (r'^admin/', include(admin.site.urls)), (r'^idp/', include('authentic.idp.urls')), (r'^$', login_required(direct_to_template), { 'template': 'index.html' }, 'index'), ) if settings.AUTH_OPENID: urlpatterns += patterns('', (r'^accounts/openid/', include('django_authopenid.urls')), ) urlpatterns += patterns('', (r'^accounts/', include('registration.urls')), ) if settings.AUTH_SSL: urlpatterns += patterns('', url(r'^sslauth/$', 'authentic.sslauth.login_ssl.process_request', name='user_signin_ssl'), url(r'^error_ssl/$', direct_to_template, {'template': 'error_ssl.html'}, 'error_ssl'), ) if settings.STATIC_SERVE: urlpatterns += patterns('', url( regex = r'^media/(?P<path>.*)$', view = 'django.views.static.serve', kwargs = {'document_root': settings.MEDIA_ROOT}), )
Move OpenID stuff under /accounts/openid/
Move OpenID stuff under /accounts/openid/
Python
agpl-3.0
adieu/authentic2,adieu/authentic2,pu239ppy/authentic2,incuna/authentic,incuna/authentic,BryceLohr/authentic,BryceLohr/authentic,pu239ppy/authentic2,incuna/authentic,adieu/authentic2,adieu/authentic2,BryceLohr/authentic,BryceLohr/authentic,incuna/authentic,incuna/authentic,pu239ppy/authentic2,pu239ppy/authentic2
from django.conf.urls.defaults import * from django.contrib import admin from django.contrib.auth.decorators import login_required from django.views.generic.simple import direct_to_template import settings admin.autodiscover() urlpatterns = patterns('', (r'^admin/', include(admin.site.urls)), (r'^idp/', include('authentic.idp.urls')), - (r'^accounts/', include('registration.urls')), (r'^$', login_required(direct_to_template), { 'template': 'index.html' }, 'index'), ) if settings.AUTH_OPENID: urlpatterns += patterns('', - (r'^openid/', include('django_authopenid.urls')), + (r'^accounts/openid/', include('django_authopenid.urls')), ) + + urlpatterns += patterns('', + (r'^accounts/', include('registration.urls')), + ) if settings.AUTH_SSL: urlpatterns += patterns('', url(r'^sslauth/$', 'authentic.sslauth.login_ssl.process_request', name='user_signin_ssl'), url(r'^error_ssl/$', direct_to_template, {'template': 'error_ssl.html'}, 'error_ssl'), ) if settings.STATIC_SERVE: urlpatterns += patterns('', url( regex = r'^media/(?P<path>.*)$', view = 'django.views.static.serve', kwargs = {'document_root': settings.MEDIA_ROOT}), )
Move OpenID stuff under /accounts/openid/
## Code Before: from django.conf.urls.defaults import * from django.contrib import admin from django.contrib.auth.decorators import login_required from django.views.generic.simple import direct_to_template import settings admin.autodiscover() urlpatterns = patterns('', (r'^admin/', include(admin.site.urls)), (r'^idp/', include('authentic.idp.urls')), (r'^accounts/', include('registration.urls')), (r'^$', login_required(direct_to_template), { 'template': 'index.html' }, 'index'), ) if settings.AUTH_OPENID: urlpatterns += patterns('', (r'^openid/', include('django_authopenid.urls')), ) if settings.AUTH_SSL: urlpatterns += patterns('', url(r'^sslauth/$', 'authentic.sslauth.login_ssl.process_request', name='user_signin_ssl'), url(r'^error_ssl/$', direct_to_template, {'template': 'error_ssl.html'}, 'error_ssl'), ) if settings.STATIC_SERVE: urlpatterns += patterns('', url( regex = r'^media/(?P<path>.*)$', view = 'django.views.static.serve', kwargs = {'document_root': settings.MEDIA_ROOT}), ) ## Instruction: Move OpenID stuff under /accounts/openid/ ## Code After: from django.conf.urls.defaults import * from django.contrib import admin from django.contrib.auth.decorators import login_required from django.views.generic.simple import direct_to_template import settings admin.autodiscover() urlpatterns = patterns('', (r'^admin/', include(admin.site.urls)), (r'^idp/', include('authentic.idp.urls')), (r'^$', login_required(direct_to_template), { 'template': 'index.html' }, 'index'), ) if settings.AUTH_OPENID: urlpatterns += patterns('', (r'^accounts/openid/', include('django_authopenid.urls')), ) urlpatterns += patterns('', (r'^accounts/', include('registration.urls')), ) if settings.AUTH_SSL: urlpatterns += patterns('', url(r'^sslauth/$', 'authentic.sslauth.login_ssl.process_request', name='user_signin_ssl'), url(r'^error_ssl/$', direct_to_template, {'template': 'error_ssl.html'}, 'error_ssl'), ) if settings.STATIC_SERVE: urlpatterns += patterns('', url( regex = r'^media/(?P<path>.*)$', view = 'django.views.static.serve', kwargs = {'document_root': settings.MEDIA_ROOT}), )
from django.conf.urls.defaults import * from django.contrib import admin from django.contrib.auth.decorators import login_required from django.views.generic.simple import direct_to_template import settings admin.autodiscover() urlpatterns = patterns('', (r'^admin/', include(admin.site.urls)), (r'^idp/', include('authentic.idp.urls')), - (r'^accounts/', include('registration.urls')), (r'^$', login_required(direct_to_template), { 'template': 'index.html' }, 'index'), ) if settings.AUTH_OPENID: urlpatterns += patterns('', - (r'^openid/', include('django_authopenid.urls')), + (r'^accounts/openid/', include('django_authopenid.urls')), ? +++++++++ ) + + urlpatterns += patterns('', + (r'^accounts/', include('registration.urls')), + ) if settings.AUTH_SSL: urlpatterns += patterns('', url(r'^sslauth/$', 'authentic.sslauth.login_ssl.process_request', name='user_signin_ssl'), url(r'^error_ssl/$', direct_to_template, {'template': 'error_ssl.html'}, 'error_ssl'), ) if settings.STATIC_SERVE: urlpatterns += patterns('', url( regex = r'^media/(?P<path>.*)$', view = 'django.views.static.serve', kwargs = {'document_root': settings.MEDIA_ROOT}), )
187026ce695dee79c4897c0e8e014bb208de5a83
gaia_tools/load/__init__.py
gaia_tools/load/__init__.py
import os, os.path import astropy.io.ascii from gaia_tools.load import path, download def galah(dr=1): filePath, ReadMePath= path.galahPath(dr=dr) if not os.path.exists(filePath): download.galah(dr=dr) data= astropy.io.ascii.read(filePath,readme=ReadMePath) return data
import os, os.path import numpy import astropy.io.ascii from gaia_tools.load import path, download def galah(dr=1): filePath, ReadMePath= path.galahPath(dr=dr) if not os.path.exists(filePath): download.galah(dr=dr) data= astropy.io.ascii.read(filePath,readme=ReadMePath) data['RA']._fill_value= numpy.array([-9999.99]) data['dec']._fill_value= numpy.array([-9999.99]) return data
Set fill value of GALAH RA and Dec explicitly
Set fill value of GALAH RA and Dec explicitly
Python
mit
jobovy/gaia_tools
import os, os.path + import numpy import astropy.io.ascii from gaia_tools.load import path, download def galah(dr=1): filePath, ReadMePath= path.galahPath(dr=dr) if not os.path.exists(filePath): download.galah(dr=dr) data= astropy.io.ascii.read(filePath,readme=ReadMePath) + data['RA']._fill_value= numpy.array([-9999.99]) + data['dec']._fill_value= numpy.array([-9999.99]) return data
Set fill value of GALAH RA and Dec explicitly
## Code Before: import os, os.path import astropy.io.ascii from gaia_tools.load import path, download def galah(dr=1): filePath, ReadMePath= path.galahPath(dr=dr) if not os.path.exists(filePath): download.galah(dr=dr) data= astropy.io.ascii.read(filePath,readme=ReadMePath) return data ## Instruction: Set fill value of GALAH RA and Dec explicitly ## Code After: import os, os.path import numpy import astropy.io.ascii from gaia_tools.load import path, download def galah(dr=1): filePath, ReadMePath= path.galahPath(dr=dr) if not os.path.exists(filePath): download.galah(dr=dr) data= astropy.io.ascii.read(filePath,readme=ReadMePath) data['RA']._fill_value= numpy.array([-9999.99]) data['dec']._fill_value= numpy.array([-9999.99]) return data
import os, os.path + import numpy import astropy.io.ascii from gaia_tools.load import path, download def galah(dr=1): filePath, ReadMePath= path.galahPath(dr=dr) if not os.path.exists(filePath): download.galah(dr=dr) data= astropy.io.ascii.read(filePath,readme=ReadMePath) + data['RA']._fill_value= numpy.array([-9999.99]) + data['dec']._fill_value= numpy.array([-9999.99]) return data
07225cc0d019bb47e9d250f17639804242efcaa8
sea/contrib/extensions/celery/cmd.py
sea/contrib/extensions/celery/cmd.py
import sys from celery.__main__ import main as celerymain from sea import create_app from sea.cli import jobm def celery(argv, app): if argv[0] == "inspect": from sea.contrib.extensions.celery import empty_celeryapp empty_celeryapp.load_config(app) sys.argv = ( ["celery"] + argv + ["-A", "sea.contrib.extensions.celery.empty_celeryapp.capp"] ) else: create_app() sys.argv = ( ["celery"] + argv + ["-A", "app.extensions:{app}".format(app=app)] ) return celerymain() @jobm.job("async_task", proxy=True, inapp=False, help="invoke celery cmds for async tasks") def async_task(argv): return celery(argv, "async_task") @jobm.job("bus", proxy=True, inapp=False, help="invoke celery cmds for bus") def bus(argv): return celery(argv, "bus")
import sys from celery.__main__ import main as celerymain from sea import create_app from sea.cli import jobm def celery(argv, app): if argv[0] == "inspect": from sea.contrib.extensions.celery import empty_celeryapp empty_celeryapp.load_config(app) sys.argv = ( ["celery"] + ["-A", "sea.contrib.extensions.celery.empty_celeryapp.capp"] + argv ) else: create_app() sys.argv = ( ["celery"] + ["-A", "app.extensions:{app}".format(app=app)] + argv ) return celerymain() @jobm.job("async_task", proxy=True, inapp=False, help="invoke celery cmds for async tasks") def async_task(argv): return celery(argv, "async_task") @jobm.job("bus", proxy=True, inapp=False, help="invoke celery cmds for bus") def bus(argv): return celery(argv, "bus")
Change the ordering of celery global options
Change the ordering of celery global options
Python
mit
shanbay/sea,yandy/sea,yandy/sea
import sys from celery.__main__ import main as celerymain from sea import create_app from sea.cli import jobm def celery(argv, app): if argv[0] == "inspect": from sea.contrib.extensions.celery import empty_celeryapp empty_celeryapp.load_config(app) sys.argv = ( - ["celery"] + argv + ["celery"] + ["-A", "sea.contrib.extensions.celery.empty_celeryapp.capp"] + + argv ) else: create_app() sys.argv = ( + ["celery"] - ["celery"] + argv + ["-A", "app.extensions:{app}".format(app=app)] + + ["-A", "app.extensions:{app}".format(app=app)] + + argv ) return celerymain() @jobm.job("async_task", proxy=True, inapp=False, help="invoke celery cmds for async tasks") def async_task(argv): return celery(argv, "async_task") @jobm.job("bus", proxy=True, inapp=False, help="invoke celery cmds for bus") def bus(argv): return celery(argv, "bus")
Change the ordering of celery global options
## Code Before: import sys from celery.__main__ import main as celerymain from sea import create_app from sea.cli import jobm def celery(argv, app): if argv[0] == "inspect": from sea.contrib.extensions.celery import empty_celeryapp empty_celeryapp.load_config(app) sys.argv = ( ["celery"] + argv + ["-A", "sea.contrib.extensions.celery.empty_celeryapp.capp"] ) else: create_app() sys.argv = ( ["celery"] + argv + ["-A", "app.extensions:{app}".format(app=app)] ) return celerymain() @jobm.job("async_task", proxy=True, inapp=False, help="invoke celery cmds for async tasks") def async_task(argv): return celery(argv, "async_task") @jobm.job("bus", proxy=True, inapp=False, help="invoke celery cmds for bus") def bus(argv): return celery(argv, "bus") ## Instruction: Change the ordering of celery global options ## Code After: import sys from celery.__main__ import main as celerymain from sea import create_app from sea.cli import jobm def celery(argv, app): if argv[0] == "inspect": from sea.contrib.extensions.celery import empty_celeryapp empty_celeryapp.load_config(app) sys.argv = ( ["celery"] + ["-A", "sea.contrib.extensions.celery.empty_celeryapp.capp"] + argv ) else: create_app() sys.argv = ( ["celery"] + ["-A", "app.extensions:{app}".format(app=app)] + argv ) return celerymain() @jobm.job("async_task", proxy=True, inapp=False, help="invoke celery cmds for async tasks") def async_task(argv): return celery(argv, "async_task") @jobm.job("bus", proxy=True, inapp=False, help="invoke celery cmds for bus") def bus(argv): return celery(argv, "bus")
import sys from celery.__main__ import main as celerymain from sea import create_app from sea.cli import jobm def celery(argv, app): if argv[0] == "inspect": from sea.contrib.extensions.celery import empty_celeryapp empty_celeryapp.load_config(app) sys.argv = ( - ["celery"] + argv ? ------- + ["celery"] + ["-A", "sea.contrib.extensions.celery.empty_celeryapp.capp"] + + argv ) else: create_app() sys.argv = ( + ["celery"] - ["celery"] + argv + ["-A", "app.extensions:{app}".format(app=app)] ? ------------------ + + ["-A", "app.extensions:{app}".format(app=app)] + + argv ) return celerymain() @jobm.job("async_task", proxy=True, inapp=False, help="invoke celery cmds for async tasks") def async_task(argv): return celery(argv, "async_task") @jobm.job("bus", proxy=True, inapp=False, help="invoke celery cmds for bus") def bus(argv): return celery(argv, "bus")
f313c9c476f6ae441f65567552ed835e96c62cb3
avocado/tests/settings.py
avocado/tests/settings.py
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', } } MODELTREES = { 'default': { 'model': 'tests.Employee' } } INSTALLED_APPS = ( 'avocado', 'avocado.meta', 'avocado.tests', ) COVERAGE_MODULES = ( 'avocado.meta.formatters', 'avocado.meta.exporters._base', 'avocado.meta.exporters._csv', 'avocado.meta.exporters._excel', 'avocado.meta.exporters._sas', 'avocado.meta.exporters._r', # 'avocado.meta.logictree', 'avocado.meta.managers', 'avocado.meta.mixins', 'avocado.meta.models', 'avocado.meta.operators', 'avocado.meta.translators', 'avocado.meta.utils', ) TEST_RUNNER = 'avocado.tests.coverage_test.CoverageTestRunner'
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', } } MODELTREES = { 'default': { 'model': 'tests.Employee' } } INSTALLED_APPS = ( 'avocado', 'avocado.meta', 'avocado.tests', ) COVERAGE_MODULES = ( 'avocado.meta.formatters', 'avocado.meta.exporters._base', 'avocado.meta.exporters._csv', 'avocado.meta.exporters._excel', 'avocado.meta.exporters._sas', 'avocado.meta.exporters._r', 'avocado.meta.exporters._json', # 'avocado.meta.logictree', 'avocado.meta.managers', 'avocado.meta.mixins', 'avocado.meta.models', 'avocado.meta.operators', 'avocado.meta.translators', 'avocado.meta.utils', ) TEST_RUNNER = 'avocado.tests.coverage_test.CoverageTestRunner'
Add json exporter module to modules coveraged
Add json exporter module to modules coveraged
Python
bsd-2-clause
murphyke/avocado,murphyke/avocado,murphyke/avocado,murphyke/avocado
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', } } MODELTREES = { 'default': { 'model': 'tests.Employee' } } INSTALLED_APPS = ( 'avocado', 'avocado.meta', 'avocado.tests', ) COVERAGE_MODULES = ( 'avocado.meta.formatters', 'avocado.meta.exporters._base', 'avocado.meta.exporters._csv', 'avocado.meta.exporters._excel', 'avocado.meta.exporters._sas', 'avocado.meta.exporters._r', + 'avocado.meta.exporters._json', # 'avocado.meta.logictree', 'avocado.meta.managers', 'avocado.meta.mixins', 'avocado.meta.models', 'avocado.meta.operators', 'avocado.meta.translators', 'avocado.meta.utils', ) TEST_RUNNER = 'avocado.tests.coverage_test.CoverageTestRunner' +
Add json exporter module to modules coveraged
## Code Before: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', } } MODELTREES = { 'default': { 'model': 'tests.Employee' } } INSTALLED_APPS = ( 'avocado', 'avocado.meta', 'avocado.tests', ) COVERAGE_MODULES = ( 'avocado.meta.formatters', 'avocado.meta.exporters._base', 'avocado.meta.exporters._csv', 'avocado.meta.exporters._excel', 'avocado.meta.exporters._sas', 'avocado.meta.exporters._r', # 'avocado.meta.logictree', 'avocado.meta.managers', 'avocado.meta.mixins', 'avocado.meta.models', 'avocado.meta.operators', 'avocado.meta.translators', 'avocado.meta.utils', ) TEST_RUNNER = 'avocado.tests.coverage_test.CoverageTestRunner' ## Instruction: Add json exporter module to modules coveraged ## Code After: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', } } MODELTREES = { 'default': { 'model': 'tests.Employee' } } INSTALLED_APPS = ( 'avocado', 'avocado.meta', 'avocado.tests', ) COVERAGE_MODULES = ( 'avocado.meta.formatters', 'avocado.meta.exporters._base', 'avocado.meta.exporters._csv', 'avocado.meta.exporters._excel', 'avocado.meta.exporters._sas', 'avocado.meta.exporters._r', 'avocado.meta.exporters._json', # 'avocado.meta.logictree', 'avocado.meta.managers', 'avocado.meta.mixins', 'avocado.meta.models', 'avocado.meta.operators', 'avocado.meta.translators', 'avocado.meta.utils', ) TEST_RUNNER = 'avocado.tests.coverage_test.CoverageTestRunner'
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', } } MODELTREES = { 'default': { 'model': 'tests.Employee' } } INSTALLED_APPS = ( 'avocado', 'avocado.meta', 'avocado.tests', ) COVERAGE_MODULES = ( 'avocado.meta.formatters', 'avocado.meta.exporters._base', 'avocado.meta.exporters._csv', 'avocado.meta.exporters._excel', 'avocado.meta.exporters._sas', 'avocado.meta.exporters._r', + 'avocado.meta.exporters._json', # 'avocado.meta.logictree', 'avocado.meta.managers', 'avocado.meta.mixins', 'avocado.meta.models', 'avocado.meta.operators', 'avocado.meta.translators', 'avocado.meta.utils', ) TEST_RUNNER = 'avocado.tests.coverage_test.CoverageTestRunner'
a2ad75b8dac515d1bbc49c32257c62a7da59e2e1
semantic_release/helpers.py
semantic_release/helpers.py
import configparser import semver from invoke import run def get_current_version(): return run('python setup.py --version', hide=True).stdout.strip() def evaluate_version_bump(force=None): if force: return force return 'patch' def get_new_version(current_version, level_bump): return getattr(semver, 'bump_{0}'.format(level_bump))(current_version) def set_new_version(current_version): return True def load_config(): config = configparser.ConfigParser() with open(os.path.join(os.getcwd(), 'setup.cfg')) as f: config.read_file(f) return config._sections['semantic_release']
import configparser import os import re import semver from invoke import run def get_current_version(): return run('python setup.py --version', hide=True).stdout.strip() def evaluate_version_bump(force=None): if force: return force return 'patch' def get_new_version(current_version, level_bump): return getattr(semver, 'bump_{0}'.format(level_bump))(current_version) def set_new_version(new_version): filename, variable = load_config().get('version_variable').split(':') variable = variable.strip() with open(filename, mode='r') as fr: content = fr.read() content = re.sub( r'{} ?= ?["\']\d+\.\d+(?:\.\d+)?["\']'.format(variable), '{} = \'{}\''.format(variable, new_version), content ) with open(filename, mode='w') as fw: fw.write(content) return True def load_config(): config = configparser.ConfigParser() with open(os.path.join(os.getcwd(), 'setup.cfg')) as f: config.read_file(f) return config._sections['semantic_release']
Implement setting of new version
:sparkles: Implement setting of new version
Python
mit
riddlesio/python-semantic-release,relekang/python-semantic-release,relekang/python-semantic-release,wlonk/python-semantic-release,jvrsantacruz/python-semantic-release
import configparser + import os + import re import semver from invoke import run def get_current_version(): return run('python setup.py --version', hide=True).stdout.strip() def evaluate_version_bump(force=None): if force: return force return 'patch' def get_new_version(current_version, level_bump): return getattr(semver, 'bump_{0}'.format(level_bump))(current_version) - def set_new_version(current_version): + def set_new_version(new_version): + filename, variable = load_config().get('version_variable').split(':') + variable = variable.strip() + with open(filename, mode='r') as fr: + content = fr.read() + + content = re.sub( + r'{} ?= ?["\']\d+\.\d+(?:\.\d+)?["\']'.format(variable), + '{} = \'{}\''.format(variable, new_version), + content + ) + + with open(filename, mode='w') as fw: + fw.write(content) return True def load_config(): config = configparser.ConfigParser() with open(os.path.join(os.getcwd(), 'setup.cfg')) as f: config.read_file(f) return config._sections['semantic_release']
Implement setting of new version
## Code Before: import configparser import semver from invoke import run def get_current_version(): return run('python setup.py --version', hide=True).stdout.strip() def evaluate_version_bump(force=None): if force: return force return 'patch' def get_new_version(current_version, level_bump): return getattr(semver, 'bump_{0}'.format(level_bump))(current_version) def set_new_version(current_version): return True def load_config(): config = configparser.ConfigParser() with open(os.path.join(os.getcwd(), 'setup.cfg')) as f: config.read_file(f) return config._sections['semantic_release'] ## Instruction: Implement setting of new version ## Code After: import configparser import os import re import semver from invoke import run def get_current_version(): return run('python setup.py --version', hide=True).stdout.strip() def evaluate_version_bump(force=None): if force: return force return 'patch' def get_new_version(current_version, level_bump): return getattr(semver, 'bump_{0}'.format(level_bump))(current_version) def set_new_version(new_version): filename, variable = load_config().get('version_variable').split(':') variable = variable.strip() with open(filename, mode='r') as fr: content = fr.read() content = re.sub( r'{} ?= ?["\']\d+\.\d+(?:\.\d+)?["\']'.format(variable), '{} = \'{}\''.format(variable, new_version), content ) with open(filename, mode='w') as fw: fw.write(content) return True def load_config(): config = configparser.ConfigParser() with open(os.path.join(os.getcwd(), 'setup.cfg')) as f: config.read_file(f) return config._sections['semantic_release']
import configparser + import os + import re import semver from invoke import run def get_current_version(): return run('python setup.py --version', hide=True).stdout.strip() def evaluate_version_bump(force=None): if force: return force return 'patch' def get_new_version(current_version, level_bump): return getattr(semver, 'bump_{0}'.format(level_bump))(current_version) - def set_new_version(current_version): ? ^^^^ ^^ + def set_new_version(new_version): ? ^ ^ + filename, variable = load_config().get('version_variable').split(':') + variable = variable.strip() + with open(filename, mode='r') as fr: + content = fr.read() + + content = re.sub( + r'{} ?= ?["\']\d+\.\d+(?:\.\d+)?["\']'.format(variable), + '{} = \'{}\''.format(variable, new_version), + content + ) + + with open(filename, mode='w') as fw: + fw.write(content) return True def load_config(): config = configparser.ConfigParser() with open(os.path.join(os.getcwd(), 'setup.cfg')) as f: config.read_file(f) return config._sections['semantic_release']
95474b52fd81b8363809fe915bd38d00335424a9
thinglang/execution/builtins.py
thinglang/execution/builtins.py
class ThingObjectBase(object): def __getitem__(self, item): return getattr(self, item) def __contains__(self, item): return hasattr(self, item) class ThingObjectOutput(ThingObjectBase): def __init__(self): self.data = [] def write(self, *args): self.data.append(' '.join(str(x) for x in args)) class ThingObjectInput(ThingObjectBase): def __init__(self): self.data = [] def get_line(self): line = input() self.data.append(line) return line
class ThingObjectBase(object): def __getitem__(self, item): return getattr(self, item) def __contains__(self, item): return hasattr(self, item) class ThingObjectOutput(ThingObjectBase): def __init__(self): self.data = [] def write(self, *args): self.data.append(' '.join(str(x) for x in args)) class ThingObjectInput(ThingObjectBase): def __init__(self, heap): self.data = [] self.heap = heap def get_line(self, line=None): if line is not None: self.heap['Output'].write(line) line = input() self.data.append(line) return line
Update Input object to support direct output during get_line operations
Update Input object to support direct output during get_line operations
Python
mit
ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang
class ThingObjectBase(object): def __getitem__(self, item): return getattr(self, item) def __contains__(self, item): return hasattr(self, item) class ThingObjectOutput(ThingObjectBase): def __init__(self): self.data = [] def write(self, *args): self.data.append(' '.join(str(x) for x in args)) class ThingObjectInput(ThingObjectBase): - def __init__(self): + def __init__(self, heap): self.data = [] + self.heap = heap - def get_line(self): + def get_line(self, line=None): + if line is not None: + self.heap['Output'].write(line) + line = input() self.data.append(line) return line
Update Input object to support direct output during get_line operations
## Code Before: class ThingObjectBase(object): def __getitem__(self, item): return getattr(self, item) def __contains__(self, item): return hasattr(self, item) class ThingObjectOutput(ThingObjectBase): def __init__(self): self.data = [] def write(self, *args): self.data.append(' '.join(str(x) for x in args)) class ThingObjectInput(ThingObjectBase): def __init__(self): self.data = [] def get_line(self): line = input() self.data.append(line) return line ## Instruction: Update Input object to support direct output during get_line operations ## Code After: class ThingObjectBase(object): def __getitem__(self, item): return getattr(self, item) def __contains__(self, item): return hasattr(self, item) class ThingObjectOutput(ThingObjectBase): def __init__(self): self.data = [] def write(self, *args): self.data.append(' '.join(str(x) for x in args)) class ThingObjectInput(ThingObjectBase): def __init__(self, heap): self.data = [] self.heap = heap def get_line(self, line=None): if line is not None: self.heap['Output'].write(line) line = input() self.data.append(line) return line
class ThingObjectBase(object): def __getitem__(self, item): return getattr(self, item) def __contains__(self, item): return hasattr(self, item) class ThingObjectOutput(ThingObjectBase): def __init__(self): self.data = [] def write(self, *args): self.data.append(' '.join(str(x) for x in args)) class ThingObjectInput(ThingObjectBase): - def __init__(self): + def __init__(self, heap): ? ++++++ self.data = [] + self.heap = heap - def get_line(self): + def get_line(self, line=None): ? +++++++++++ + if line is not None: + self.heap['Output'].write(line) + line = input() self.data.append(line) return line
f25a32dd0180af91277ace186fc878c8baffed65
heisen/core/__init__.py
heisen/core/__init__.py
from heisen.config import settings from heisen.core.log import logger from jsonrpclib.request import Connection def get_rpc_connection(): servers = { 'self': [ ('127.0.0.1', settings.RPC_PORT, 'aliehsanmilad', 'Key1_s!3cr3t') ], } servers.update(getattr(settings, 'RPC_SERVERS', {})) return Connection(servers, 'heisen', settings.APP_NAME) rpc_call = get_rpc_connection()
from heisen.config import settings from heisen.core.log import logger from jsonrpclib.request import ConnectionPool def get_rpc_connection(): if settings.CREDENTIALS: username, passowrd = settings.CREDENTIALS[0] else: username = passowrd = None servers = {'self': [('localhost', settings.RPC_PORT, username, passowrd)]} servers.update(getattr(settings, 'RPC_SERVERS', {})) return ConnectionPool(servers, 'heisen', settings.APP_NAME) rpc_call = get_rpc_connection()
Use connection pool for jsonrpc
Use connection pool for jsonrpc
Python
mit
HeisenCore/heisen
from heisen.config import settings from heisen.core.log import logger - from jsonrpclib.request import Connection + from jsonrpclib.request import ConnectionPool def get_rpc_connection(): - servers = { - 'self': [ - ('127.0.0.1', settings.RPC_PORT, 'aliehsanmilad', 'Key1_s!3cr3t') - ], - } + if settings.CREDENTIALS: + username, passowrd = settings.CREDENTIALS[0] + else: + username = passowrd = None + + servers = {'self': [('localhost', settings.RPC_PORT, username, passowrd)]} servers.update(getattr(settings, 'RPC_SERVERS', {})) - return Connection(servers, 'heisen', settings.APP_NAME) + return ConnectionPool(servers, 'heisen', settings.APP_NAME) rpc_call = get_rpc_connection()
Use connection pool for jsonrpc
## Code Before: from heisen.config import settings from heisen.core.log import logger from jsonrpclib.request import Connection def get_rpc_connection(): servers = { 'self': [ ('127.0.0.1', settings.RPC_PORT, 'aliehsanmilad', 'Key1_s!3cr3t') ], } servers.update(getattr(settings, 'RPC_SERVERS', {})) return Connection(servers, 'heisen', settings.APP_NAME) rpc_call = get_rpc_connection() ## Instruction: Use connection pool for jsonrpc ## Code After: from heisen.config import settings from heisen.core.log import logger from jsonrpclib.request import ConnectionPool def get_rpc_connection(): if settings.CREDENTIALS: username, passowrd = settings.CREDENTIALS[0] else: username = passowrd = None servers = {'self': [('localhost', settings.RPC_PORT, username, passowrd)]} servers.update(getattr(settings, 'RPC_SERVERS', {})) return ConnectionPool(servers, 'heisen', settings.APP_NAME) rpc_call = get_rpc_connection()
from heisen.config import settings from heisen.core.log import logger - from jsonrpclib.request import Connection + from jsonrpclib.request import ConnectionPool ? ++++ def get_rpc_connection(): - servers = { - 'self': [ - ('127.0.0.1', settings.RPC_PORT, 'aliehsanmilad', 'Key1_s!3cr3t') - ], - } + if settings.CREDENTIALS: + username, passowrd = settings.CREDENTIALS[0] + else: + username = passowrd = None + + servers = {'self': [('localhost', settings.RPC_PORT, username, passowrd)]} servers.update(getattr(settings, 'RPC_SERVERS', {})) - return Connection(servers, 'heisen', settings.APP_NAME) + return ConnectionPool(servers, 'heisen', settings.APP_NAME) ? ++++ rpc_call = get_rpc_connection()
7f0097d240c4a231029222fdd2bf507ca7d5b2ed
tests/v6/exemplar_generators.py
tests/v6/exemplar_generators.py
from .context import tohu from tohu.v5.primitive_generators import * EXEMPLAR_PRIMITIVE_GENERATORS = [ Constant("quux"), Integer(100, 200), ] EXEMPLAR_DERIVED_GENERATORS = [] EXEMPLAR_GENERATORS = EXEMPLAR_PRIMITIVE_GENERATORS + EXEMPLAR_DERIVED_GENERATORS
from .context import tohu from tohu.v5.primitive_generators import * EXEMPLAR_PRIMITIVE_GENERATORS = [ Constant("quux"), Integer(100, 200), HashDigest(length=8), FakerGenerator(method="name"), ] EXEMPLAR_DERIVED_GENERATORS = [] EXEMPLAR_GENERATORS = EXEMPLAR_PRIMITIVE_GENERATORS + EXEMPLAR_DERIVED_GENERATORS
Add exemplar generators for HashDigest, FakerGenerator
Add exemplar generators for HashDigest, FakerGenerator
Python
mit
maxalbert/tohu
from .context import tohu from tohu.v5.primitive_generators import * EXEMPLAR_PRIMITIVE_GENERATORS = [ Constant("quux"), Integer(100, 200), + HashDigest(length=8), + FakerGenerator(method="name"), ] EXEMPLAR_DERIVED_GENERATORS = [] EXEMPLAR_GENERATORS = EXEMPLAR_PRIMITIVE_GENERATORS + EXEMPLAR_DERIVED_GENERATORS
Add exemplar generators for HashDigest, FakerGenerator
## Code Before: from .context import tohu from tohu.v5.primitive_generators import * EXEMPLAR_PRIMITIVE_GENERATORS = [ Constant("quux"), Integer(100, 200), ] EXEMPLAR_DERIVED_GENERATORS = [] EXEMPLAR_GENERATORS = EXEMPLAR_PRIMITIVE_GENERATORS + EXEMPLAR_DERIVED_GENERATORS ## Instruction: Add exemplar generators for HashDigest, FakerGenerator ## Code After: from .context import tohu from tohu.v5.primitive_generators import * EXEMPLAR_PRIMITIVE_GENERATORS = [ Constant("quux"), Integer(100, 200), HashDigest(length=8), FakerGenerator(method="name"), ] EXEMPLAR_DERIVED_GENERATORS = [] EXEMPLAR_GENERATORS = EXEMPLAR_PRIMITIVE_GENERATORS + EXEMPLAR_DERIVED_GENERATORS
from .context import tohu from tohu.v5.primitive_generators import * EXEMPLAR_PRIMITIVE_GENERATORS = [ Constant("quux"), Integer(100, 200), + HashDigest(length=8), + FakerGenerator(method="name"), ] EXEMPLAR_DERIVED_GENERATORS = [] EXEMPLAR_GENERATORS = EXEMPLAR_PRIMITIVE_GENERATORS + EXEMPLAR_DERIVED_GENERATORS
962ae8a53c95e8ade1e0fd5804062b807837781e
pycalc.py
pycalc.py
import sys try: import readline # No idea if this is a license violation. Hope it isn't. except ImportError: print("Could not find readline, you will likely get no line editing functionality") if sys.version_info.major < 3: print("This program is for python version 3 only.") sys.exit(3) import lexer import execute while True: instr = input("» ") toks = lexer.to_toks(instr) rpn = lexer.to_rpn(toks) result = execute.eval_rpn(rpn) if result is not None: print(result) if len(sys.argv) >= 2: break
import sys try: import readline # noqa: this is used simply by being imported. # No idea if this is a license violation. Hope it isn't. except ImportError: print("Could not find readline, you will likely get no line editing functionality") if sys.version_info.major < 3: print("This program is for python version 3 only.") sys.exit(3) import lexer # noqa: These have to go here, as they use Unicode, which py2 can't handle. import execute # noqa while True: instr = input("» ") toks = lexer.to_toks(instr) rpn = lexer.to_rpn(toks) result = execute.eval_rpn(rpn) if result is not None: print(result) if len(sys.argv) >= 2: break
Add lines to shut flake8 up.
Add lines to shut flake8 up.
Python
mit
5225225/pycalc,5225225/pycalc
import sys try: - import readline + import readline # noqa: this is used simply by being imported. # No idea if this is a license violation. Hope it isn't. except ImportError: print("Could not find readline, you will likely get no line editing functionality") if sys.version_info.major < 3: print("This program is for python version 3 only.") sys.exit(3) - import lexer + import lexer # noqa: These have to go here, as they use Unicode, which py2 can't handle. - import execute + import execute # noqa while True: instr = input("» ") toks = lexer.to_toks(instr) rpn = lexer.to_rpn(toks) result = execute.eval_rpn(rpn) if result is not None: print(result) if len(sys.argv) >= 2: break
Add lines to shut flake8 up.
## Code Before: import sys try: import readline # No idea if this is a license violation. Hope it isn't. except ImportError: print("Could not find readline, you will likely get no line editing functionality") if sys.version_info.major < 3: print("This program is for python version 3 only.") sys.exit(3) import lexer import execute while True: instr = input("» ") toks = lexer.to_toks(instr) rpn = lexer.to_rpn(toks) result = execute.eval_rpn(rpn) if result is not None: print(result) if len(sys.argv) >= 2: break ## Instruction: Add lines to shut flake8 up. ## Code After: import sys try: import readline # noqa: this is used simply by being imported. # No idea if this is a license violation. Hope it isn't. except ImportError: print("Could not find readline, you will likely get no line editing functionality") if sys.version_info.major < 3: print("This program is for python version 3 only.") sys.exit(3) import lexer # noqa: These have to go here, as they use Unicode, which py2 can't handle. import execute # noqa while True: instr = input("» ") toks = lexer.to_toks(instr) rpn = lexer.to_rpn(toks) result = execute.eval_rpn(rpn) if result is not None: print(result) if len(sys.argv) >= 2: break
import sys try: - import readline + import readline # noqa: this is used simply by being imported. # No idea if this is a license violation. Hope it isn't. except ImportError: print("Could not find readline, you will likely get no line editing functionality") if sys.version_info.major < 3: print("This program is for python version 3 only.") sys.exit(3) - import lexer + import lexer # noqa: These have to go here, as they use Unicode, which py2 can't handle. - import execute + import execute # noqa ? ++++++++ while True: instr = input("» ") toks = lexer.to_toks(instr) rpn = lexer.to_rpn(toks) result = execute.eval_rpn(rpn) if result is not None: print(result) if len(sys.argv) >= 2: break
a003a7b0d52365c5f5976c7382bc1daf2f5960ac
glitter_news/search_indexes.py
glitter_news/search_indexes.py
from haystack import indexes from .models import Post class PostIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) def get_model(self): return Post def index_queryset(self, using=None): return self.get_model().objects.select_related().filter( published=True ).exclude( current_version=None )
from django.utils import timezone from haystack import indexes from .models import Post class PostIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) def get_model(self): return Post def index_queryset(self, using=None): return self.get_model().objects.published().select_related().filter( date__lte=timezone.now())
Fix the queryset for news indexing
Fix the queryset for news indexing
Python
bsd-2-clause
blancltd/glitter-news
+ from django.utils import timezone from haystack import indexes from .models import Post class PostIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) def get_model(self): return Post def index_queryset(self, using=None): - return self.get_model().objects.select_related().filter( + return self.get_model().objects.published().select_related().filter( + date__lte=timezone.now()) - published=True - ).exclude( - current_version=None - )
Fix the queryset for news indexing
## Code Before: from haystack import indexes from .models import Post class PostIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) def get_model(self): return Post def index_queryset(self, using=None): return self.get_model().objects.select_related().filter( published=True ).exclude( current_version=None ) ## Instruction: Fix the queryset for news indexing ## Code After: from django.utils import timezone from haystack import indexes from .models import Post class PostIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) def get_model(self): return Post def index_queryset(self, using=None): return self.get_model().objects.published().select_related().filter( date__lte=timezone.now())
+ from django.utils import timezone from haystack import indexes from .models import Post class PostIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) def get_model(self): return Post def index_queryset(self, using=None): - return self.get_model().objects.select_related().filter( + return self.get_model().objects.published().select_related().filter( ? ++++++++++++ + date__lte=timezone.now()) - published=True - ).exclude( - current_version=None - )
af328240631dd31b405e90c09052c1872490713d
setup.py
setup.py
from distutils.core import setup setup( name='gapi', version='0.5.0', author='Scott Hendrickson, Josh Montague', author_email='scott@drskippy.net', packages=[], scripts=['search_api.py', 'paged_search_api.py'], url='https://github.com/DrSkippy27/Gnip-Python-Search-API-Utilities', download_url='https://github.com/DrSkippy27/Gnip-Python-Search-API-Utilities/tags/', license='LICENSE.txt', description='Simple utilties to to explore the Gnip search API', install_requires=[ "gnacs > 0.7.0", "sngrams > 0.1.0" ] )
from distutils.core import setup setup( name='gapi', version='0.5.2', author='Scott Hendrickson, Josh Montague', author_email='scott@drskippy.net', packages=[], scripts=['search_api.py', 'paged_search_api.py'], url='https://github.com/DrSkippy27/Gnip-Python-Search-API-Utilities', download_url='https://github.com/DrSkippy27/Gnip-Python-Search-API-Utilities/tags/', license='LICENSE.txt', description='Simple utilties to to explore the Gnip search API', install_requires=[ "gnacs > 0.7.0", "sngrams > 0.1.0", "reqeusts > 1.2.2" ] )
Update pip package. Added proper requests dependency
Update pip package. Added proper requests dependency
Python
bsd-2-clause
DrSkippy/Gnip-Python-Search-API-Utilities,blehman/Gnip-Python-Search-API-Utilities,DrSkippy/Gnip-Python-Search-API-Utilities,blehman/Gnip-Python-Search-API-Utilities
from distutils.core import setup setup( name='gapi', - version='0.5.0', + version='0.5.2', author='Scott Hendrickson, Josh Montague', author_email='scott@drskippy.net', packages=[], scripts=['search_api.py', 'paged_search_api.py'], url='https://github.com/DrSkippy27/Gnip-Python-Search-API-Utilities', download_url='https://github.com/DrSkippy27/Gnip-Python-Search-API-Utilities/tags/', license='LICENSE.txt', description='Simple utilties to to explore the Gnip search API', install_requires=[ "gnacs > 0.7.0", - "sngrams > 0.1.0" + "sngrams > 0.1.0", + "reqeusts > 1.2.2" ] )
Update pip package. Added proper requests dependency
## Code Before: from distutils.core import setup setup( name='gapi', version='0.5.0', author='Scott Hendrickson, Josh Montague', author_email='scott@drskippy.net', packages=[], scripts=['search_api.py', 'paged_search_api.py'], url='https://github.com/DrSkippy27/Gnip-Python-Search-API-Utilities', download_url='https://github.com/DrSkippy27/Gnip-Python-Search-API-Utilities/tags/', license='LICENSE.txt', description='Simple utilties to to explore the Gnip search API', install_requires=[ "gnacs > 0.7.0", "sngrams > 0.1.0" ] ) ## Instruction: Update pip package. Added proper requests dependency ## Code After: from distutils.core import setup setup( name='gapi', version='0.5.2', author='Scott Hendrickson, Josh Montague', author_email='scott@drskippy.net', packages=[], scripts=['search_api.py', 'paged_search_api.py'], url='https://github.com/DrSkippy27/Gnip-Python-Search-API-Utilities', download_url='https://github.com/DrSkippy27/Gnip-Python-Search-API-Utilities/tags/', license='LICENSE.txt', description='Simple utilties to to explore the Gnip search API', install_requires=[ "gnacs > 0.7.0", "sngrams > 0.1.0", "reqeusts > 1.2.2" ] )
from distutils.core import setup setup( name='gapi', - version='0.5.0', ? ^ + version='0.5.2', ? ^ author='Scott Hendrickson, Josh Montague', author_email='scott@drskippy.net', packages=[], scripts=['search_api.py', 'paged_search_api.py'], url='https://github.com/DrSkippy27/Gnip-Python-Search-API-Utilities', download_url='https://github.com/DrSkippy27/Gnip-Python-Search-API-Utilities/tags/', license='LICENSE.txt', description='Simple utilties to to explore the Gnip search API', install_requires=[ "gnacs > 0.7.0", - "sngrams > 0.1.0" + "sngrams > 0.1.0", ? + + "reqeusts > 1.2.2" ] )
4ec8a5b5880f7e5300d71c34f5b293ea5993f5b2
tests/test_storage.py
tests/test_storage.py
import os import json import pytest def test_add_single(identity_fixures, identity_store): for d in identity_fixures: identity = identity_store.add_identity(d) for key, val in d.items(): assert getattr(identity, key) == val def test_add_multiple(identity_fixures, identity_store): identity_store.add_identities(*identity_fixures) assert len(identity_store.identities) == len(identity_fixures) def test_id_validation(identity_fixures, identity_store): from awsident.storage import IdentityExists identity_store.add_identities(*identity_fixures) with pytest.raises(IdentityExists): identity_store.add_identity(identity_fixures[0]) identity = identity_store.identities.values()[0] original_id = identity.id identity.access_key_id = 'ichanged' assert 'ichanged' in identity_store.keys() assert original_id not in identity_store.keys() def test_serialization(identity_fixures, identity_store): identity_store.add_identities(*identity_fixures) # data should have been saved at this point so clear and reload it identity_store.identities.clear() identity_store.load_from_config() for data in identity_fixures: identity = identity_store.get(data['access_key_id']) for key, val in data.items(): assert getattr(identity, key) == val
import os import json import pytest def test_add_single(identity_fixures, identity_store): for d in identity_fixures: identity = identity_store.add_identity(d) for key, val in d.items(): assert getattr(identity, key) == val def test_add_multiple(identity_fixures, identity_store): identity_store.add_identities(*identity_fixures) assert len(identity_store.identities) == len(identity_fixures) def test_id_validation(identity_fixures, identity_store): from awsident.storage import IdentityExists identity_store.add_identities(*identity_fixures) with pytest.raises(IdentityExists): identity_store.add_identity(identity_fixures[0]) identity = list(identity_store.values())[0] original_id = identity.id identity.access_key_id = 'ichanged' assert 'ichanged' in identity_store.keys() assert original_id not in identity_store.keys() def test_serialization(identity_fixures, identity_store): identity_store.add_identities(*identity_fixures) # data should have been saved at this point so clear and reload it identity_store.identities.clear() identity_store.load_from_config() for data in identity_fixures: identity = identity_store.get(data['access_key_id']) for key, val in data.items(): assert getattr(identity, key) == val
Convert dict view to list for Py3
Convert dict view to list for Py3
Python
mit
nocarryr/AWS-Identity-Manager
import os import json import pytest def test_add_single(identity_fixures, identity_store): for d in identity_fixures: identity = identity_store.add_identity(d) for key, val in d.items(): assert getattr(identity, key) == val def test_add_multiple(identity_fixures, identity_store): identity_store.add_identities(*identity_fixures) assert len(identity_store.identities) == len(identity_fixures) def test_id_validation(identity_fixures, identity_store): from awsident.storage import IdentityExists identity_store.add_identities(*identity_fixures) with pytest.raises(IdentityExists): identity_store.add_identity(identity_fixures[0]) - identity = identity_store.identities.values()[0] + identity = list(identity_store.values())[0] original_id = identity.id identity.access_key_id = 'ichanged' assert 'ichanged' in identity_store.keys() assert original_id not in identity_store.keys() def test_serialization(identity_fixures, identity_store): identity_store.add_identities(*identity_fixures) # data should have been saved at this point so clear and reload it identity_store.identities.clear() identity_store.load_from_config() for data in identity_fixures: identity = identity_store.get(data['access_key_id']) for key, val in data.items(): assert getattr(identity, key) == val
Convert dict view to list for Py3
## Code Before: import os import json import pytest def test_add_single(identity_fixures, identity_store): for d in identity_fixures: identity = identity_store.add_identity(d) for key, val in d.items(): assert getattr(identity, key) == val def test_add_multiple(identity_fixures, identity_store): identity_store.add_identities(*identity_fixures) assert len(identity_store.identities) == len(identity_fixures) def test_id_validation(identity_fixures, identity_store): from awsident.storage import IdentityExists identity_store.add_identities(*identity_fixures) with pytest.raises(IdentityExists): identity_store.add_identity(identity_fixures[0]) identity = identity_store.identities.values()[0] original_id = identity.id identity.access_key_id = 'ichanged' assert 'ichanged' in identity_store.keys() assert original_id not in identity_store.keys() def test_serialization(identity_fixures, identity_store): identity_store.add_identities(*identity_fixures) # data should have been saved at this point so clear and reload it identity_store.identities.clear() identity_store.load_from_config() for data in identity_fixures: identity = identity_store.get(data['access_key_id']) for key, val in data.items(): assert getattr(identity, key) == val ## Instruction: Convert dict view to list for Py3 ## Code After: import os import json import pytest def test_add_single(identity_fixures, identity_store): for d in identity_fixures: identity = identity_store.add_identity(d) for key, val in d.items(): assert getattr(identity, key) == val def test_add_multiple(identity_fixures, identity_store): identity_store.add_identities(*identity_fixures) assert len(identity_store.identities) == len(identity_fixures) def test_id_validation(identity_fixures, identity_store): from awsident.storage import IdentityExists identity_store.add_identities(*identity_fixures) with pytest.raises(IdentityExists): identity_store.add_identity(identity_fixures[0]) identity = list(identity_store.values())[0] original_id = identity.id identity.access_key_id = 'ichanged' assert 'ichanged' in identity_store.keys() assert original_id not in identity_store.keys() def test_serialization(identity_fixures, identity_store): identity_store.add_identities(*identity_fixures) # data should have been saved at this point so clear and reload it identity_store.identities.clear() identity_store.load_from_config() for data in identity_fixures: identity = identity_store.get(data['access_key_id']) for key, val in data.items(): assert getattr(identity, key) == val
import os import json import pytest def test_add_single(identity_fixures, identity_store): for d in identity_fixures: identity = identity_store.add_identity(d) for key, val in d.items(): assert getattr(identity, key) == val def test_add_multiple(identity_fixures, identity_store): identity_store.add_identities(*identity_fixures) assert len(identity_store.identities) == len(identity_fixures) def test_id_validation(identity_fixures, identity_store): from awsident.storage import IdentityExists identity_store.add_identities(*identity_fixures) with pytest.raises(IdentityExists): identity_store.add_identity(identity_fixures[0]) - identity = identity_store.identities.values()[0] ? ----------- + identity = list(identity_store.values())[0] ? +++++ + original_id = identity.id identity.access_key_id = 'ichanged' assert 'ichanged' in identity_store.keys() assert original_id not in identity_store.keys() def test_serialization(identity_fixures, identity_store): identity_store.add_identities(*identity_fixures) # data should have been saved at this point so clear and reload it identity_store.identities.clear() identity_store.load_from_config() for data in identity_fixures: identity = identity_store.get(data['access_key_id']) for key, val in data.items(): assert getattr(identity, key) == val
0f20599968b2ab848f8e3fde912f8d0ecdfba509
asyncio_irc/connection.py
asyncio_irc/connection.py
import asyncio from .message import Message class Connection: """ Communicates with an IRC network. Incoming data is transformed into Message objects, and sent to `listeners`. """ def __init__(self, *, listeners, host, port, ssl=True): self.listeners = listeners self.host = host self.port = port self.ssl = ssl @asyncio.coroutine def connect(self): """Connect to the server, and dispatch incoming messages.""" connection = asyncio.open_connection(self.host, self.port, ssl=self.ssl) self.reader, self.writer = yield from connection self.on_connect() self._connected = True while self._connected: raw_message = yield from self.reader.readline() self.handle(raw_message) def disconnect(self): """Close the connection to the server.""" self._connected = False self.writer.close() def handle(self, raw_message): """Dispatch the message to all listeners.""" if not raw_message: self.disconnect() return message = Message(raw_message) for listener in self.listeners: listener.handle(self, message) def on_connect(self): """Upon connection to the network, send user's credentials.""" self.send(b'USER meshybot 0 * :MeshyBot7') self.send(b'NICK meshybot') def send(self, message): """Dispatch a message to the IRC network.""" message = message + b'\r\n' print('write', message) self.writer.write(message)
import asyncio from .message import Message class Connection: """ Communicates with an IRC network. Incoming data is transformed into Message objects, and sent to `listeners`. """ def __init__(self, *, listeners, host, port, ssl=True): self.listeners = listeners self.host = host self.port = port self.ssl = ssl @asyncio.coroutine def connect(self): """Connect to the server, and dispatch incoming messages.""" connection = asyncio.open_connection(self.host, self.port, ssl=self.ssl) self.reader, self.writer = yield from connection self.on_connect() self._connected = True while self._connected: raw_message = yield from self.reader.readline() self.handle(raw_message) def disconnect(self): """Close the connection to the server.""" self._connected = False self.writer.close() def handle(self, raw_message): """Dispatch the message to all listeners.""" if not raw_message: self.disconnect() return message = Message(raw_message) for listener in self.listeners: listener.handle(self, message) def on_connect(self): """Upon connection to the network, send user's credentials.""" self.send('USER meshybot 0 * :MeshyBot7') self.send('NICK meshybot') def send(self, message): """Dispatch a message to the IRC network.""" # Cast to bytes try: message = message.encode() except AttributeError: pass # Add line ending. message = message + b'\r\n' print('write', message) self.writer.write(message)
Allow Connection.send to take unicode message
Allow Connection.send to take unicode message
Python
bsd-2-clause
meshy/framewirc
import asyncio from .message import Message class Connection: """ Communicates with an IRC network. Incoming data is transformed into Message objects, and sent to `listeners`. """ def __init__(self, *, listeners, host, port, ssl=True): self.listeners = listeners self.host = host self.port = port self.ssl = ssl @asyncio.coroutine def connect(self): """Connect to the server, and dispatch incoming messages.""" connection = asyncio.open_connection(self.host, self.port, ssl=self.ssl) self.reader, self.writer = yield from connection self.on_connect() self._connected = True while self._connected: raw_message = yield from self.reader.readline() self.handle(raw_message) def disconnect(self): """Close the connection to the server.""" self._connected = False self.writer.close() def handle(self, raw_message): """Dispatch the message to all listeners.""" if not raw_message: self.disconnect() return message = Message(raw_message) for listener in self.listeners: listener.handle(self, message) def on_connect(self): """Upon connection to the network, send user's credentials.""" - self.send(b'USER meshybot 0 * :MeshyBot7') + self.send('USER meshybot 0 * :MeshyBot7') - self.send(b'NICK meshybot') + self.send('NICK meshybot') def send(self, message): """Dispatch a message to the IRC network.""" + # Cast to bytes + try: + message = message.encode() + except AttributeError: + pass + + # Add line ending. message = message + b'\r\n' print('write', message) self.writer.write(message)
Allow Connection.send to take unicode message
## Code Before: import asyncio from .message import Message class Connection: """ Communicates with an IRC network. Incoming data is transformed into Message objects, and sent to `listeners`. """ def __init__(self, *, listeners, host, port, ssl=True): self.listeners = listeners self.host = host self.port = port self.ssl = ssl @asyncio.coroutine def connect(self): """Connect to the server, and dispatch incoming messages.""" connection = asyncio.open_connection(self.host, self.port, ssl=self.ssl) self.reader, self.writer = yield from connection self.on_connect() self._connected = True while self._connected: raw_message = yield from self.reader.readline() self.handle(raw_message) def disconnect(self): """Close the connection to the server.""" self._connected = False self.writer.close() def handle(self, raw_message): """Dispatch the message to all listeners.""" if not raw_message: self.disconnect() return message = Message(raw_message) for listener in self.listeners: listener.handle(self, message) def on_connect(self): """Upon connection to the network, send user's credentials.""" self.send(b'USER meshybot 0 * :MeshyBot7') self.send(b'NICK meshybot') def send(self, message): """Dispatch a message to the IRC network.""" message = message + b'\r\n' print('write', message) self.writer.write(message) ## Instruction: Allow Connection.send to take unicode message ## Code After: import asyncio from .message import Message class Connection: """ Communicates with an IRC network. Incoming data is transformed into Message objects, and sent to `listeners`. """ def __init__(self, *, listeners, host, port, ssl=True): self.listeners = listeners self.host = host self.port = port self.ssl = ssl @asyncio.coroutine def connect(self): """Connect to the server, and dispatch incoming messages.""" connection = asyncio.open_connection(self.host, self.port, ssl=self.ssl) self.reader, self.writer = yield from connection self.on_connect() self._connected = True while self._connected: raw_message = yield from self.reader.readline() self.handle(raw_message) def disconnect(self): """Close the connection to the server.""" self._connected = False self.writer.close() def handle(self, raw_message): """Dispatch the message to all listeners.""" if not raw_message: self.disconnect() return message = Message(raw_message) for listener in self.listeners: listener.handle(self, message) def on_connect(self): """Upon connection to the network, send user's credentials.""" self.send('USER meshybot 0 * :MeshyBot7') self.send('NICK meshybot') def send(self, message): """Dispatch a message to the IRC network.""" # Cast to bytes try: message = message.encode() except AttributeError: pass # Add line ending. message = message + b'\r\n' print('write', message) self.writer.write(message)
import asyncio from .message import Message class Connection: """ Communicates with an IRC network. Incoming data is transformed into Message objects, and sent to `listeners`. """ def __init__(self, *, listeners, host, port, ssl=True): self.listeners = listeners self.host = host self.port = port self.ssl = ssl @asyncio.coroutine def connect(self): """Connect to the server, and dispatch incoming messages.""" connection = asyncio.open_connection(self.host, self.port, ssl=self.ssl) self.reader, self.writer = yield from connection self.on_connect() self._connected = True while self._connected: raw_message = yield from self.reader.readline() self.handle(raw_message) def disconnect(self): """Close the connection to the server.""" self._connected = False self.writer.close() def handle(self, raw_message): """Dispatch the message to all listeners.""" if not raw_message: self.disconnect() return message = Message(raw_message) for listener in self.listeners: listener.handle(self, message) def on_connect(self): """Upon connection to the network, send user's credentials.""" - self.send(b'USER meshybot 0 * :MeshyBot7') ? - + self.send('USER meshybot 0 * :MeshyBot7') - self.send(b'NICK meshybot') ? - + self.send('NICK meshybot') def send(self, message): """Dispatch a message to the IRC network.""" + # Cast to bytes + try: + message = message.encode() + except AttributeError: + pass + + # Add line ending. message = message + b'\r\n' print('write', message) self.writer.write(message)
46511322dc8d738cc43561025bca3298946da2e6
server.py
server.py
from swiftdav.swiftdav import SwiftProvider, WsgiDAVDomainController from waitress import serve from wsgidav.wsgidav_app import DEFAULT_CONFIG, WsgiDAVApp proxy = 'http://127.0.0.1:8080/auth/v1.0' insecure = False # Set to True to disable SSL certificate validation config = DEFAULT_CONFIG.copy() config.update({ "provider_mapping": {"": SwiftProvider()}, "verbose": 1, "propsmanager": True, "locksmanager": True, "acceptbasic": True, "acceptdigest": False, "defaultdigest": False, "domaincontroller": WsgiDAVDomainController(proxy, insecure) }) app = WsgiDAVApp(config) serve(app, host="0.0.0.0", port=8000)
from swiftdav.swiftdav import SwiftProvider, WsgiDAVDomainController from waitress import serve from wsgidav.wsgidav_app import DEFAULT_CONFIG, WsgiDAVApp proxy = 'http://127.0.0.1:8080/auth/v1.0' insecure = False # Set to True to disable SSL certificate validation config = DEFAULT_CONFIG.copy() config.update({ "provider_mapping": {"": SwiftProvider()}, "verbose": 1, "propsmanager": True, "locksmanager": True, "acceptbasic": True, "acceptdigest": False, "defaultdigest": False, "domaincontroller": WsgiDAVDomainController(proxy, insecure) }) app = WsgiDAVApp(config) serve(app, host="0.0.0.0", port=8000, max_request_body_size=5*1024*1024*1024)
Increase waitress setting max_request_body_size to 5GiB
Increase waitress setting max_request_body_size to 5GiB Python waitress limits the body size to 1GiB by default, thus uploading of larger objects will fail if this value is not increased. Please note that this value should be increased if your Swift cluster supports uploading of objects larger than 5GiB.
Python
apache-2.0
cschwede/swiftdav,cschwede/swiftdav
from swiftdav.swiftdav import SwiftProvider, WsgiDAVDomainController from waitress import serve from wsgidav.wsgidav_app import DEFAULT_CONFIG, WsgiDAVApp proxy = 'http://127.0.0.1:8080/auth/v1.0' insecure = False # Set to True to disable SSL certificate validation config = DEFAULT_CONFIG.copy() config.update({ "provider_mapping": {"": SwiftProvider()}, "verbose": 1, "propsmanager": True, "locksmanager": True, "acceptbasic": True, "acceptdigest": False, "defaultdigest": False, "domaincontroller": WsgiDAVDomainController(proxy, insecure) }) app = WsgiDAVApp(config) - serve(app, host="0.0.0.0", port=8000) + serve(app, host="0.0.0.0", port=8000, max_request_body_size=5*1024*1024*1024)
Increase waitress setting max_request_body_size to 5GiB
## Code Before: from swiftdav.swiftdav import SwiftProvider, WsgiDAVDomainController from waitress import serve from wsgidav.wsgidav_app import DEFAULT_CONFIG, WsgiDAVApp proxy = 'http://127.0.0.1:8080/auth/v1.0' insecure = False # Set to True to disable SSL certificate validation config = DEFAULT_CONFIG.copy() config.update({ "provider_mapping": {"": SwiftProvider()}, "verbose": 1, "propsmanager": True, "locksmanager": True, "acceptbasic": True, "acceptdigest": False, "defaultdigest": False, "domaincontroller": WsgiDAVDomainController(proxy, insecure) }) app = WsgiDAVApp(config) serve(app, host="0.0.0.0", port=8000) ## Instruction: Increase waitress setting max_request_body_size to 5GiB ## Code After: from swiftdav.swiftdav import SwiftProvider, WsgiDAVDomainController from waitress import serve from wsgidav.wsgidav_app import DEFAULT_CONFIG, WsgiDAVApp proxy = 'http://127.0.0.1:8080/auth/v1.0' insecure = False # Set to True to disable SSL certificate validation config = DEFAULT_CONFIG.copy() config.update({ "provider_mapping": {"": SwiftProvider()}, "verbose": 1, "propsmanager": True, "locksmanager": True, "acceptbasic": True, "acceptdigest": False, "defaultdigest": False, "domaincontroller": WsgiDAVDomainController(proxy, insecure) }) app = WsgiDAVApp(config) serve(app, host="0.0.0.0", port=8000, max_request_body_size=5*1024*1024*1024)
from swiftdav.swiftdav import SwiftProvider, WsgiDAVDomainController from waitress import serve from wsgidav.wsgidav_app import DEFAULT_CONFIG, WsgiDAVApp proxy = 'http://127.0.0.1:8080/auth/v1.0' insecure = False # Set to True to disable SSL certificate validation config = DEFAULT_CONFIG.copy() config.update({ "provider_mapping": {"": SwiftProvider()}, "verbose": 1, "propsmanager": True, "locksmanager": True, "acceptbasic": True, "acceptdigest": False, "defaultdigest": False, "domaincontroller": WsgiDAVDomainController(proxy, insecure) }) app = WsgiDAVApp(config) - serve(app, host="0.0.0.0", port=8000) + serve(app, host="0.0.0.0", port=8000, max_request_body_size=5*1024*1024*1024)
08adcf2402f46dfc3332146cac1705e149b18e32
tree/108.py
tree/108.py
class Solution: def sortedArrayToBST(self, nums: List[int]) -> TreeNode: if not nums: return None pivot = len(nums) // 2 root = TreeNode(nums[pivot]) root.left = self.sortedArrayToBST(nums[:pivot]) root.right = self.sortedArrayToBST(nums[pivot+1:]) return root
class Solution: def sortedArrayToBST(self, nums: List[int]) -> TreeNode: if not nums: return None pivot = len(nums) // 2 root = TreeNode(nums[pivot]) root.left = self.sortedArrayToBST(nums[:pivot]) root.right = self.sortedArrayToBST(nums[pivot+1:]) return root #non-ercursive solution # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def sortedArrayToBST(self, nums: List[int]) -> TreeNode: if not nums: return None pivot = (len(nums)-1) // 2 l = [] root = TreeNode(nums[pivot]) l.append([root, 0, pivot-1]) l.append([root, pivot+1, len(nums)-1]) while l: cur, left, right = l.pop() if left <= right: pivot = left + (right - left) // 2 #注意与(right - left) // 2的区别 node = TreeNode(nums[pivot]) if nums[pivot] <= cur.val: cur.left = node else: cur.right = node l.append([node, left, pivot-1]) l.append([node, pivot+1, right]) return root
Convert Sorted Array to Binary Search Tree
Convert Sorted Array to Binary Search Tree
Python
apache-2.0
MingfeiPan/leetcode,MingfeiPan/leetcode,MingfeiPan/leetcode,MingfeiPan/leetcode,MingfeiPan/leetcode
class Solution: def sortedArrayToBST(self, nums: List[int]) -> TreeNode: if not nums: return None pivot = len(nums) // 2 root = TreeNode(nums[pivot]) root.left = self.sortedArrayToBST(nums[:pivot]) root.right = self.sortedArrayToBST(nums[pivot+1:]) return root + #non-ercursive solution + # Definition for a binary tree node. + # class TreeNode: + # def __init__(self, x): + # self.val = x + # self.left = None + # self.right = None + + class Solution: + def sortedArrayToBST(self, nums: List[int]) -> TreeNode: + + if not nums: + return None + + pivot = (len(nums)-1) // 2 + + l = [] + root = TreeNode(nums[pivot]) + l.append([root, 0, pivot-1]) + l.append([root, pivot+1, len(nums)-1]) + + while l: + cur, left, right = l.pop() + + if left <= right: + pivot = left + (right - left) // 2 #注意与(right - left) // 2的区别 + node = TreeNode(nums[pivot]) + if nums[pivot] <= cur.val: + cur.left = node + else: + cur.right = node + + l.append([node, left, pivot-1]) + l.append([node, pivot+1, right]) + + return root +
Convert Sorted Array to Binary Search Tree
## Code Before: class Solution: def sortedArrayToBST(self, nums: List[int]) -> TreeNode: if not nums: return None pivot = len(nums) // 2 root = TreeNode(nums[pivot]) root.left = self.sortedArrayToBST(nums[:pivot]) root.right = self.sortedArrayToBST(nums[pivot+1:]) return root ## Instruction: Convert Sorted Array to Binary Search Tree ## Code After: class Solution: def sortedArrayToBST(self, nums: List[int]) -> TreeNode: if not nums: return None pivot = len(nums) // 2 root = TreeNode(nums[pivot]) root.left = self.sortedArrayToBST(nums[:pivot]) root.right = self.sortedArrayToBST(nums[pivot+1:]) return root #non-ercursive solution # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def sortedArrayToBST(self, nums: List[int]) -> TreeNode: if not nums: return None pivot = (len(nums)-1) // 2 l = [] root = TreeNode(nums[pivot]) l.append([root, 0, pivot-1]) l.append([root, pivot+1, len(nums)-1]) while l: cur, left, right = l.pop() if left <= right: pivot = left + (right - left) // 2 #注意与(right - left) // 2的区别 node = TreeNode(nums[pivot]) if nums[pivot] <= cur.val: cur.left = node else: cur.right = node l.append([node, left, pivot-1]) l.append([node, pivot+1, right]) return root
class Solution: def sortedArrayToBST(self, nums: List[int]) -> TreeNode: if not nums: return None pivot = len(nums) // 2 root = TreeNode(nums[pivot]) root.left = self.sortedArrayToBST(nums[:pivot]) root.right = self.sortedArrayToBST(nums[pivot+1:]) return root + + #non-ercursive solution + # Definition for a binary tree node. + # class TreeNode: + # def __init__(self, x): + # self.val = x + # self.left = None + # self.right = None + + class Solution: + def sortedArrayToBST(self, nums: List[int]) -> TreeNode: + + if not nums: + return None + + pivot = (len(nums)-1) // 2 + + l = [] + root = TreeNode(nums[pivot]) + l.append([root, 0, pivot-1]) + l.append([root, pivot+1, len(nums)-1]) + + while l: + cur, left, right = l.pop() + + if left <= right: + pivot = left + (right - left) // 2 #注意与(right - left) // 2的区别 + node = TreeNode(nums[pivot]) + if nums[pivot] <= cur.val: + cur.left = node + else: + cur.right = node + + l.append([node, left, pivot-1]) + l.append([node, pivot+1, right]) + + return root
da5386234ec66968a1010d073af56ab7f01e4792
openshift/ose_object.py
openshift/ose_object.py
class OSEObject(object): """Superclass to all OSE objects that hold data about remote API.""" def __init__(self, ose): self.ose = ose self.refresh() def refresh(self): """Reloads all info about this object. Uses _request_fresh() method defined by subclasses to obtain fresh response. """ self._response = self._request_fresh() self._json = self._response.json() def _request_fresh(self): raise NotImplementedError('Class {cls} doesn\'t implement _request_fresh method.'.\ format(cls=type(self))) def __getattr__(self, attr): return self._response.json()['data'][attr]
class OSEObject(object): """Superclass to all OSE objects that hold data about remote API.""" def __init__(self, ose): self.ose = ose self.refresh() def refresh(self): """Reloads all info about this object. Uses _request_fresh() method defined by subclasses to obtain fresh response. """ self._response = self._request_fresh() self._json = self._response.json() def _request_fresh(self): raise NotImplementedError('Class {cls} doesn\'t implement _request_fresh method.'.\ format(cls=type(self))) def __getattr__(self, attr): return self._json['data'][attr]
Use the extracted json for getting data from OSEObject to not extract it every time
Use the extracted json for getting data from OSEObject to not extract it every time
Python
mit
atodorov/python-openshift,atodorov/python-openshift
class OSEObject(object): """Superclass to all OSE objects that hold data about remote API.""" def __init__(self, ose): self.ose = ose self.refresh() def refresh(self): """Reloads all info about this object. Uses _request_fresh() method defined by subclasses to obtain fresh response. """ self._response = self._request_fresh() self._json = self._response.json() def _request_fresh(self): raise NotImplementedError('Class {cls} doesn\'t implement _request_fresh method.'.\ format(cls=type(self))) def __getattr__(self, attr): - return self._response.json()['data'][attr] + return self._json['data'][attr]
Use the extracted json for getting data from OSEObject to not extract it every time
## Code Before: class OSEObject(object): """Superclass to all OSE objects that hold data about remote API.""" def __init__(self, ose): self.ose = ose self.refresh() def refresh(self): """Reloads all info about this object. Uses _request_fresh() method defined by subclasses to obtain fresh response. """ self._response = self._request_fresh() self._json = self._response.json() def _request_fresh(self): raise NotImplementedError('Class {cls} doesn\'t implement _request_fresh method.'.\ format(cls=type(self))) def __getattr__(self, attr): return self._response.json()['data'][attr] ## Instruction: Use the extracted json for getting data from OSEObject to not extract it every time ## Code After: class OSEObject(object): """Superclass to all OSE objects that hold data about remote API.""" def __init__(self, ose): self.ose = ose self.refresh() def refresh(self): """Reloads all info about this object. Uses _request_fresh() method defined by subclasses to obtain fresh response. """ self._response = self._request_fresh() self._json = self._response.json() def _request_fresh(self): raise NotImplementedError('Class {cls} doesn\'t implement _request_fresh method.'.\ format(cls=type(self))) def __getattr__(self, attr): return self._json['data'][attr]
class OSEObject(object): """Superclass to all OSE objects that hold data about remote API.""" def __init__(self, ose): self.ose = ose self.refresh() def refresh(self): """Reloads all info about this object. Uses _request_fresh() method defined by subclasses to obtain fresh response. """ self._response = self._request_fresh() self._json = self._response.json() def _request_fresh(self): raise NotImplementedError('Class {cls} doesn\'t implement _request_fresh method.'.\ format(cls=type(self))) def __getattr__(self, attr): - return self._response.json()['data'][attr] ? --------- -- + return self._json['data'][attr]
a27a525650571b6f3756edf7f0fdf82d724f22d3
performance/web.py
performance/web.py
import requests from time import time class Client: def __init__(self, host, requests, do_requests_counter): self.host = host self.requests = requests self.counter = do_requests_counter class Request: GET = 'get' POST = 'post' def __init__(self, url, type=GET, data=None): self.url = url self.type = type self.data = data def do(self): try: data = '' if isinstance(self.data, RequestData): data = self.data.for_type(type=self.type) started = time() response = getattr(requests, self.type)( url=self.url, data=data ) finished = time() return finished - started except AttributeError: raise RequestTypeError(type=self.type) class RequestData: def __init__(self, data=None): self.data = data def for_type(self, type=Request.GET): if type is Request.GET: return data class RequestTypeError(Exception): def __init__(self, type): self.type = type def __str__(self): return 'Invalid request type "%s"' % self.type
import requests from time import time class Client: def __init__(self, host, requests, do_requests_counter): self.host = host self.requests = requests self.counter = do_requests_counter class Request: GET = 'get' POST = 'post' def __init__(self, url, type=GET, data=None): self.url = url self.type = type self.data = data def do(self): try: data = '' if isinstance(self.data, RequestData): data = self.data.for_type(type=self.type) started = time() response = getattr(requests, self.type)( url=self.url, data=data ) finished = time() return finished - started except AttributeError: raise RequestTypeError(type=self.type) class RequestData: def __init__(self, data=None): self.data = data def get_converted(self, type=Request.GET): if type is Request.GET: return self.data class RequestTypeError(Exception): def __init__(self, type): self.type = type def __str__(self): return 'Invalid request type "%s"' % self.type
Update function name and return value
Update function name and return value
Python
mit
BakeCode/performance-testing,BakeCode/performance-testing
import requests from time import time class Client: def __init__(self, host, requests, do_requests_counter): self.host = host self.requests = requests self.counter = do_requests_counter class Request: GET = 'get' POST = 'post' def __init__(self, url, type=GET, data=None): self.url = url self.type = type self.data = data def do(self): try: data = '' if isinstance(self.data, RequestData): data = self.data.for_type(type=self.type) started = time() response = getattr(requests, self.type)( url=self.url, data=data ) finished = time() return finished - started except AttributeError: raise RequestTypeError(type=self.type) class RequestData: def __init__(self, data=None): self.data = data - def for_type(self, type=Request.GET): + def get_converted(self, type=Request.GET): if type is Request.GET: - return data + return self.data class RequestTypeError(Exception): def __init__(self, type): self.type = type def __str__(self): return 'Invalid request type "%s"' % self.type
Update function name and return value
## Code Before: import requests from time import time class Client: def __init__(self, host, requests, do_requests_counter): self.host = host self.requests = requests self.counter = do_requests_counter class Request: GET = 'get' POST = 'post' def __init__(self, url, type=GET, data=None): self.url = url self.type = type self.data = data def do(self): try: data = '' if isinstance(self.data, RequestData): data = self.data.for_type(type=self.type) started = time() response = getattr(requests, self.type)( url=self.url, data=data ) finished = time() return finished - started except AttributeError: raise RequestTypeError(type=self.type) class RequestData: def __init__(self, data=None): self.data = data def for_type(self, type=Request.GET): if type is Request.GET: return data class RequestTypeError(Exception): def __init__(self, type): self.type = type def __str__(self): return 'Invalid request type "%s"' % self.type ## Instruction: Update function name and return value ## Code After: import requests from time import time class Client: def __init__(self, host, requests, do_requests_counter): self.host = host self.requests = requests self.counter = do_requests_counter class Request: GET = 'get' POST = 'post' def __init__(self, url, type=GET, data=None): self.url = url self.type = type self.data = data def do(self): try: data = '' if isinstance(self.data, RequestData): data = self.data.for_type(type=self.type) started = time() response = getattr(requests, self.type)( url=self.url, data=data ) finished = time() return finished - started except AttributeError: raise RequestTypeError(type=self.type) class RequestData: def __init__(self, data=None): self.data = data def get_converted(self, type=Request.GET): if type is Request.GET: return self.data class RequestTypeError(Exception): def __init__(self, type): self.type = type def __str__(self): return 'Invalid request type "%s"' % self.type
import requests from time import time class Client: def __init__(self, host, requests, do_requests_counter): self.host = host self.requests = requests self.counter = do_requests_counter class Request: GET = 'get' POST = 'post' def __init__(self, url, type=GET, data=None): self.url = url self.type = type self.data = data def do(self): try: data = '' if isinstance(self.data, RequestData): data = self.data.for_type(type=self.type) started = time() response = getattr(requests, self.type)( url=self.url, data=data ) finished = time() return finished - started except AttributeError: raise RequestTypeError(type=self.type) class RequestData: def __init__(self, data=None): self.data = data - def for_type(self, type=Request.GET): ? ^ - -- + def get_converted(self, type=Request.GET): ? ^^^^^ +++ + if type is Request.GET: - return data + return self.data ? +++++ class RequestTypeError(Exception): def __init__(self, type): self.type = type def __str__(self): return 'Invalid request type "%s"' % self.type
f0166ba101c131b5331e141128fc65e71c753015
flocker/common/__init__.py
flocker/common/__init__.py
__all__ = [ 'INode', 'FakeNode', 'ProcessNode', 'gather_deferreds', 'auto_threaded', 'auto_openstack_logging', 'get_all_ips', ] import platform from ._ipc import INode, FakeNode, ProcessNode from ._defer import gather_deferreds from ._thread import auto_threaded from ._net import get_all_ips if platform.system() == 'Linux': # For some reason I don't understand, keystoneclient has problems on OS X. # Fortunately, we don't need keystoneclient on OS X. from ._openstack import auto_openstack_logging
__all__ = [ 'INode', 'FakeNode', 'ProcessNode', 'gather_deferreds', 'auto_threaded', 'auto_openstack_logging', 'get_all_ips', 'ipaddress_from_string', ] import platform from ._ipc import INode, FakeNode, ProcessNode from ._defer import gather_deferreds from ._thread import auto_threaded from ._net import get_all_ips, ipaddress_from_string if platform.system() == 'Linux': # For some reason I don't understand, keystoneclient has problems on OS X. # Fortunately, we don't need keystoneclient on OS X. from ._openstack import auto_openstack_logging
Make the new helper function public
Make the new helper function public
Python
apache-2.0
Azulinho/flocker,1d4Nf6/flocker,hackday-profilers/flocker,wallnerryan/flocker-profiles,mbrukman/flocker,adamtheturtle/flocker,1d4Nf6/flocker,AndyHuu/flocker,jml/flocker,wallnerryan/flocker-profiles,achanda/flocker,agonzalezro/flocker,AndyHuu/flocker,adamtheturtle/flocker,runcom/flocker,achanda/flocker,runcom/flocker,agonzalezro/flocker,lukemarsden/flocker,1d4Nf6/flocker,jml/flocker,wallnerryan/flocker-profiles,runcom/flocker,w4ngyi/flocker,mbrukman/flocker,achanda/flocker,hackday-profilers/flocker,lukemarsden/flocker,LaynePeng/flocker,moypray/flocker,jml/flocker,adamtheturtle/flocker,hackday-profilers/flocker,agonzalezro/flocker,w4ngyi/flocker,w4ngyi/flocker,LaynePeng/flocker,moypray/flocker,mbrukman/flocker,lukemarsden/flocker,LaynePeng/flocker,Azulinho/flocker,moypray/flocker,Azulinho/flocker,AndyHuu/flocker
__all__ = [ 'INode', 'FakeNode', 'ProcessNode', 'gather_deferreds', 'auto_threaded', 'auto_openstack_logging', - 'get_all_ips', + 'get_all_ips', 'ipaddress_from_string', ] import platform from ._ipc import INode, FakeNode, ProcessNode from ._defer import gather_deferreds from ._thread import auto_threaded - from ._net import get_all_ips + from ._net import get_all_ips, ipaddress_from_string if platform.system() == 'Linux': # For some reason I don't understand, keystoneclient has problems on OS X. # Fortunately, we don't need keystoneclient on OS X. from ._openstack import auto_openstack_logging
Make the new helper function public
## Code Before: __all__ = [ 'INode', 'FakeNode', 'ProcessNode', 'gather_deferreds', 'auto_threaded', 'auto_openstack_logging', 'get_all_ips', ] import platform from ._ipc import INode, FakeNode, ProcessNode from ._defer import gather_deferreds from ._thread import auto_threaded from ._net import get_all_ips if platform.system() == 'Linux': # For some reason I don't understand, keystoneclient has problems on OS X. # Fortunately, we don't need keystoneclient on OS X. from ._openstack import auto_openstack_logging ## Instruction: Make the new helper function public ## Code After: __all__ = [ 'INode', 'FakeNode', 'ProcessNode', 'gather_deferreds', 'auto_threaded', 'auto_openstack_logging', 'get_all_ips', 'ipaddress_from_string', ] import platform from ._ipc import INode, FakeNode, ProcessNode from ._defer import gather_deferreds from ._thread import auto_threaded from ._net import get_all_ips, ipaddress_from_string if platform.system() == 'Linux': # For some reason I don't understand, keystoneclient has problems on OS X. # Fortunately, we don't need keystoneclient on OS X. from ._openstack import auto_openstack_logging
__all__ = [ 'INode', 'FakeNode', 'ProcessNode', 'gather_deferreds', 'auto_threaded', 'auto_openstack_logging', - 'get_all_ips', + 'get_all_ips', 'ipaddress_from_string', ] import platform from ._ipc import INode, FakeNode, ProcessNode from ._defer import gather_deferreds from ._thread import auto_threaded - from ._net import get_all_ips + from ._net import get_all_ips, ipaddress_from_string if platform.system() == 'Linux': # For some reason I don't understand, keystoneclient has problems on OS X. # Fortunately, we don't need keystoneclient on OS X. from ._openstack import auto_openstack_logging
f01841e5b3fb9fe6a4f30b15dbf12146971d1b6f
flask_aggregator.py
flask_aggregator.py
import json from flask import request as current_request, Response from werkzeug.exceptions import BadRequest class Aggregator(object): def __init__(self, app=None, endpoint=None): self.url_map = {} self.endpoint = endpoint or "/aggregator" if app: self.init_app(app) def init_app(self, app): self.client = app.test_client() app.add_url_rule(self.endpoint, view_func=self.post, methods=["POST"]) def post(self): try: requests = json.loads(current_request.data) if not isinstance(requests, list): raise TypeError except (ValueError, TypeError): raise BadRequest("Can't get requests list.") def __generate(): data = None for request in requests: yield data + ',' if data else '{' data = '"{}": {}'.format(request, self.client.get(request).data) yield data + '}' return Response(__generate(), mimetype='application/json')
import json from flask import request, Request, Response from werkzeug.exceptions import BadRequest from werkzeug.test import EnvironBuilder class Aggregator(object): def __init__(self, app=None, endpoint=None): self.url_map = {} self.endpoint = endpoint or "/aggregator" if app: self.init_app(app) def init_app(self, app): self.app = app self.app.add_url_rule(self.endpoint, view_func=self.post, methods=["POST"]) def get_response(self, route): query_string = "" if '?' in route: route, query_string = route.split('?', 1) builder = EnvironBuilder(path=route, query_string=query_string) self.app.request_context(builder.get_environ()).push() return self.app.dispatch_request() def post(self): try: data = request.data.decode('utf-8') routes = json.loads(data) if not isinstance(routes, list): raise TypeError except (ValueError, TypeError) as e: raise BadRequest("Can't get requests list.") def __generate(): data = None for route in routes: yield data + ', ' if data else '{' response = self.get_response(route) json_response = json.dumps(response) data = '"{}": {}'.format(route, json_response) yield data + '}' return Response(__generate(), mimetype='application/json')
Use app request context directly rather than hacking with a test client
Use app request context directly rather than hacking with a test client
Python
mit
ramnes/flask-aggregator
import json - from flask import request as current_request, Response + from flask import request, Request, Response from werkzeug.exceptions import BadRequest + from werkzeug.test import EnvironBuilder class Aggregator(object): def __init__(self, app=None, endpoint=None): self.url_map = {} self.endpoint = endpoint or "/aggregator" if app: self.init_app(app) def init_app(self, app): - self.client = app.test_client() + self.app = app - app.add_url_rule(self.endpoint, view_func=self.post, methods=["POST"]) + self.app.add_url_rule(self.endpoint, view_func=self.post, methods=["POST"]) + + def get_response(self, route): + query_string = "" + if '?' in route: + route, query_string = route.split('?', 1) + + builder = EnvironBuilder(path=route, query_string=query_string) + self.app.request_context(builder.get_environ()).push() + return self.app.dispatch_request() def post(self): try: + data = request.data.decode('utf-8') - requests = json.loads(current_request.data) + routes = json.loads(data) - if not isinstance(requests, list): + if not isinstance(routes, list): raise TypeError - except (ValueError, TypeError): + except (ValueError, TypeError) as e: raise BadRequest("Can't get requests list.") def __generate(): data = None - for request in requests: + for route in routes: - yield data + ',' if data else '{' + yield data + ', ' if data else '{' - data = '"{}": {}'.format(request, self.client.get(request).data) + response = self.get_response(route) + json_response = json.dumps(response) + data = '"{}": {}'.format(route, json_response) yield data + '}' return Response(__generate(), mimetype='application/json')
Use app request context directly rather than hacking with a test client
## Code Before: import json from flask import request as current_request, Response from werkzeug.exceptions import BadRequest class Aggregator(object): def __init__(self, app=None, endpoint=None): self.url_map = {} self.endpoint = endpoint or "/aggregator" if app: self.init_app(app) def init_app(self, app): self.client = app.test_client() app.add_url_rule(self.endpoint, view_func=self.post, methods=["POST"]) def post(self): try: requests = json.loads(current_request.data) if not isinstance(requests, list): raise TypeError except (ValueError, TypeError): raise BadRequest("Can't get requests list.") def __generate(): data = None for request in requests: yield data + ',' if data else '{' data = '"{}": {}'.format(request, self.client.get(request).data) yield data + '}' return Response(__generate(), mimetype='application/json') ## Instruction: Use app request context directly rather than hacking with a test client ## Code After: import json from flask import request, Request, Response from werkzeug.exceptions import BadRequest from werkzeug.test import EnvironBuilder class Aggregator(object): def __init__(self, app=None, endpoint=None): self.url_map = {} self.endpoint = endpoint or "/aggregator" if app: self.init_app(app) def init_app(self, app): self.app = app self.app.add_url_rule(self.endpoint, view_func=self.post, methods=["POST"]) def get_response(self, route): query_string = "" if '?' in route: route, query_string = route.split('?', 1) builder = EnvironBuilder(path=route, query_string=query_string) self.app.request_context(builder.get_environ()).push() return self.app.dispatch_request() def post(self): try: data = request.data.decode('utf-8') routes = json.loads(data) if not isinstance(routes, list): raise TypeError except (ValueError, TypeError) as e: raise BadRequest("Can't get requests list.") def __generate(): data = None for route in routes: yield data + ', ' if data else '{' response = self.get_response(route) json_response = json.dumps(response) data = '"{}": {}'.format(route, json_response) yield data + '}' return Response(__generate(), mimetype='application/json')
import json - from flask import request as current_request, Response ? ^^^^^^^^^^^^ + from flask import request, Request, Response ? + ^ from werkzeug.exceptions import BadRequest + from werkzeug.test import EnvironBuilder class Aggregator(object): def __init__(self, app=None, endpoint=None): self.url_map = {} self.endpoint = endpoint or "/aggregator" if app: self.init_app(app) def init_app(self, app): - self.client = app.test_client() + self.app = app - app.add_url_rule(self.endpoint, view_func=self.post, methods=["POST"]) + self.app.add_url_rule(self.endpoint, view_func=self.post, methods=["POST"]) ? +++++ + + def get_response(self, route): + query_string = "" + if '?' in route: + route, query_string = route.split('?', 1) + + builder = EnvironBuilder(path=route, query_string=query_string) + self.app.request_context(builder.get_environ()).push() + return self.app.dispatch_request() def post(self): try: - requests = json.loads(current_request.data) + data = request.data.decode('utf-8') + routes = json.loads(data) - if not isinstance(requests, list): ? ----- + if not isinstance(routes, list): ? +++ raise TypeError - except (ValueError, TypeError): + except (ValueError, TypeError) as e: ? +++++ raise BadRequest("Can't get requests list.") def __generate(): data = None - for request in requests: ? ----- ^^ -- + for route in routes: ? +++ ^ + - yield data + ',' if data else '{' + yield data + ', ' if data else '{' ? + - data = '"{}": {}'.format(request, self.client.get(request).data) + response = self.get_response(route) + json_response = json.dumps(response) + data = '"{}": {}'.format(route, json_response) yield data + '}' return Response(__generate(), mimetype='application/json')
94b73811a4986dee5ac32fe1d91f377828a5bca5
mnemosyne/app/__init__.py
mnemosyne/app/__init__.py
import aiohttp import aiohttp.web from mnemosyne.app import by_time, by_uuid application = aiohttp.web.Application() # by_uuid API # app.router.add_route('GET', '/applications', mnemosyne.applications.index) application.router.add_route('GET', '/trace/{traceUuid}', by_uuid.getTrace) application.router.add_route('GET', '/transaction/{transactionUuid}', by_uuid.getTransaction) application.router.add_route('GET', '/application/{applicationUuid}', by_uuid.getApplication) # by_time API application.router.add_route('GET', '/traces/frontend/age/{ageInMin}', by_time.getFrontendTraces)
import os import aiohttp import aiohttp.web from mnemosyne.app import by_time, by_uuid application = aiohttp.web.Application() class DirectoryIndex(aiohttp.web.StaticRoute): def handle(self, request): filename = request.match_info['filename'] if not filename: filename = 'index.html' elif filename.endswith('/'): filename += 'index.html' request.match_info['filename'] = filename return super().handle(request) public_dir = os.path.abspath(os.path.join(__file__, '../../../public')) application.router.register_route(DirectoryIndex(None, '/', public_dir)) # by_uuid API application.router.add_route('GET', '/trace/{traceUuid}', by_uuid.getTrace) application.router.add_route( 'GET', '/transaction/{transactionUuid}', by_uuid.getTransaction) application.router.add_route( 'GET', '/application/{applicationUuid}', by_uuid.getApplication) # by_time API application.router.add_route( 'GET', '/traces/frontend/age/{ageInMin}', by_time.getFrontendTraces)
Add static route serving files
Add static route serving files Custom static file handler resolves `/` to `/index.html`.
Python
agpl-3.0
jgraichen/mnemosyne,jgraichen/mnemosyne,jgraichen/mnemosyne
+ + import os import aiohttp import aiohttp.web from mnemosyne.app import by_time, by_uuid application = aiohttp.web.Application() + class DirectoryIndex(aiohttp.web.StaticRoute): + def handle(self, request): + filename = request.match_info['filename'] + + if not filename: + filename = 'index.html' + elif filename.endswith('/'): + filename += 'index.html' + + request.match_info['filename'] = filename + + return super().handle(request) + + public_dir = os.path.abspath(os.path.join(__file__, '../../../public')) + + application.router.register_route(DirectoryIndex(None, '/', public_dir)) + + # by_uuid API - # app.router.add_route('GET', '/applications', mnemosyne.applications.index) application.router.add_route('GET', '/trace/{traceUuid}', by_uuid.getTrace) + application.router.add_route( - application.router.add_route('GET', '/transaction/{transactionUuid}', by_uuid.getTransaction) + 'GET', '/transaction/{transactionUuid}', by_uuid.getTransaction) + application.router.add_route( - application.router.add_route('GET', '/application/{applicationUuid}', by_uuid.getApplication) + 'GET', '/application/{applicationUuid}', by_uuid.getApplication) # by_time API + application.router.add_route( - application.router.add_route('GET', '/traces/frontend/age/{ageInMin}', by_time.getFrontendTraces) + 'GET', '/traces/frontend/age/{ageInMin}', by_time.getFrontendTraces)
Add static route serving files
## Code Before: import aiohttp import aiohttp.web from mnemosyne.app import by_time, by_uuid application = aiohttp.web.Application() # by_uuid API # app.router.add_route('GET', '/applications', mnemosyne.applications.index) application.router.add_route('GET', '/trace/{traceUuid}', by_uuid.getTrace) application.router.add_route('GET', '/transaction/{transactionUuid}', by_uuid.getTransaction) application.router.add_route('GET', '/application/{applicationUuid}', by_uuid.getApplication) # by_time API application.router.add_route('GET', '/traces/frontend/age/{ageInMin}', by_time.getFrontendTraces) ## Instruction: Add static route serving files ## Code After: import os import aiohttp import aiohttp.web from mnemosyne.app import by_time, by_uuid application = aiohttp.web.Application() class DirectoryIndex(aiohttp.web.StaticRoute): def handle(self, request): filename = request.match_info['filename'] if not filename: filename = 'index.html' elif filename.endswith('/'): filename += 'index.html' request.match_info['filename'] = filename return super().handle(request) public_dir = os.path.abspath(os.path.join(__file__, '../../../public')) application.router.register_route(DirectoryIndex(None, '/', public_dir)) # by_uuid API application.router.add_route('GET', '/trace/{traceUuid}', by_uuid.getTrace) application.router.add_route( 'GET', '/transaction/{transactionUuid}', by_uuid.getTransaction) application.router.add_route( 'GET', '/application/{applicationUuid}', by_uuid.getApplication) # by_time API application.router.add_route( 'GET', '/traces/frontend/age/{ageInMin}', by_time.getFrontendTraces)
+ + import os import aiohttp import aiohttp.web from mnemosyne.app import by_time, by_uuid application = aiohttp.web.Application() + class DirectoryIndex(aiohttp.web.StaticRoute): + def handle(self, request): + filename = request.match_info['filename'] + + if not filename: + filename = 'index.html' + elif filename.endswith('/'): + filename += 'index.html' + + request.match_info['filename'] = filename + + return super().handle(request) + + public_dir = os.path.abspath(os.path.join(__file__, '../../../public')) + + application.router.register_route(DirectoryIndex(None, '/', public_dir)) + + # by_uuid API - # app.router.add_route('GET', '/applications', mnemosyne.applications.index) application.router.add_route('GET', '/trace/{traceUuid}', by_uuid.getTrace) + application.router.add_route( - application.router.add_route('GET', '/transaction/{transactionUuid}', by_uuid.getTransaction) ? ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 'GET', '/transaction/{transactionUuid}', by_uuid.getTransaction) ? ^^^^ + application.router.add_route( - application.router.add_route('GET', '/application/{applicationUuid}', by_uuid.getApplication) ? ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 'GET', '/application/{applicationUuid}', by_uuid.getApplication) ? ^^^^ # by_time API + application.router.add_route( - application.router.add_route('GET', '/traces/frontend/age/{ageInMin}', by_time.getFrontendTraces) ? ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 'GET', '/traces/frontend/age/{ageInMin}', by_time.getFrontendTraces) ? ^^^^
bc36a19d3bb1c07cbe2a44de88f227ef71c50b8c
notebooks/utils.py
notebooks/utils.py
def print_generated_sequence(g, num, *, sep=", "): """ Helper function which prints a sequence of `num` items produced by the random generator `g`. """ elems = [str(next(g)) for _ in range(num)] sep_initial = "\n" if sep == "\n" else " " print("Generated sequence:{}{}".format(sep_initial, sep.join(elems)))
def print_generated_sequence(g, num, *, sep=", ", seed=None): """ Helper function which prints a sequence of `num` items produced by the random generator `g`. """ if seed: g.reset(seed) elems = [str(next(g)) for _ in range(num)] sep_initial = "\n" if sep == "\n" else " " print("Generated sequence:{}{}".format(sep_initial, sep.join(elems)))
Allow passing seed directly to helper function
Allow passing seed directly to helper function
Python
mit
maxalbert/tohu
- def print_generated_sequence(g, num, *, sep=", "): + def print_generated_sequence(g, num, *, sep=", ", seed=None): """ Helper function which prints a sequence of `num` items produced by the random generator `g`. """ + if seed: + g.reset(seed) elems = [str(next(g)) for _ in range(num)] sep_initial = "\n" if sep == "\n" else " " print("Generated sequence:{}{}".format(sep_initial, sep.join(elems)))
Allow passing seed directly to helper function
## Code Before: def print_generated_sequence(g, num, *, sep=", "): """ Helper function which prints a sequence of `num` items produced by the random generator `g`. """ elems = [str(next(g)) for _ in range(num)] sep_initial = "\n" if sep == "\n" else " " print("Generated sequence:{}{}".format(sep_initial, sep.join(elems))) ## Instruction: Allow passing seed directly to helper function ## Code After: def print_generated_sequence(g, num, *, sep=", ", seed=None): """ Helper function which prints a sequence of `num` items produced by the random generator `g`. """ if seed: g.reset(seed) elems = [str(next(g)) for _ in range(num)] sep_initial = "\n" if sep == "\n" else " " print("Generated sequence:{}{}".format(sep_initial, sep.join(elems)))
- def print_generated_sequence(g, num, *, sep=", "): + def print_generated_sequence(g, num, *, sep=", ", seed=None): ? +++++++++++ """ Helper function which prints a sequence of `num` items produced by the random generator `g`. """ + if seed: + g.reset(seed) elems = [str(next(g)) for _ in range(num)] sep_initial = "\n" if sep == "\n" else " " print("Generated sequence:{}{}".format(sep_initial, sep.join(elems)))
dec97fd68509cabfd53dcf588952b3b25d3e0e17
normandy/base/urls.py
normandy/base/urls.py
from django.conf.urls import include, url from normandy.base import views from normandy.base.api import views as api_views from normandy.base.api.routers import MixedViewRouter # API Router router = MixedViewRouter() router.register("user", api_views.UserViewSet) router.register("group", api_views.GroupViewSet) urlpatterns = [ url(r"^$", views.index, name="index"), url(r"^favicon.ico", views.favicon), url(r"^api/v2/service_info/", api_views.ServiceInfoView.as_view(), name="service-info"), url(r"^api/v1/user/me/", api_views.CurrentUserView.as_view(), name="current-user"), url(r"^api/v3/", include(router.urls)), ]
from django.conf.urls import include, url from normandy.base import views from normandy.base.api import views as api_views from normandy.base.api.routers import MixedViewRouter # API Router router = MixedViewRouter() router.register("user", api_views.UserViewSet) router.register("group", api_views.GroupViewSet) urlpatterns = [ url(r"^$", views.index, name="index"), url(r"^favicon.ico", views.favicon), url(r"^api/v2/service_info/", api_views.ServiceInfoView.as_view(), name="service-info-v2"), url(r"^api/v3/service_info/", api_views.ServiceInfoView.as_view(), name="service-info"), url(r"^api/v1/user/me/", api_views.CurrentUserView.as_view(), name="current-user"), url(r"^api/v3/", include(router.urls)), ]
Make service info available on v3 API
Make service info available on v3 API
Python
mpl-2.0
mozilla/normandy,mozilla/normandy,mozilla/normandy,mozilla/normandy
from django.conf.urls import include, url from normandy.base import views from normandy.base.api import views as api_views from normandy.base.api.routers import MixedViewRouter # API Router router = MixedViewRouter() router.register("user", api_views.UserViewSet) router.register("group", api_views.GroupViewSet) urlpatterns = [ url(r"^$", views.index, name="index"), url(r"^favicon.ico", views.favicon), + url(r"^api/v2/service_info/", api_views.ServiceInfoView.as_view(), name="service-info-v2"), - url(r"^api/v2/service_info/", api_views.ServiceInfoView.as_view(), name="service-info"), + url(r"^api/v3/service_info/", api_views.ServiceInfoView.as_view(), name="service-info"), url(r"^api/v1/user/me/", api_views.CurrentUserView.as_view(), name="current-user"), url(r"^api/v3/", include(router.urls)), ]
Make service info available on v3 API
## Code Before: from django.conf.urls import include, url from normandy.base import views from normandy.base.api import views as api_views from normandy.base.api.routers import MixedViewRouter # API Router router = MixedViewRouter() router.register("user", api_views.UserViewSet) router.register("group", api_views.GroupViewSet) urlpatterns = [ url(r"^$", views.index, name="index"), url(r"^favicon.ico", views.favicon), url(r"^api/v2/service_info/", api_views.ServiceInfoView.as_view(), name="service-info"), url(r"^api/v1/user/me/", api_views.CurrentUserView.as_view(), name="current-user"), url(r"^api/v3/", include(router.urls)), ] ## Instruction: Make service info available on v3 API ## Code After: from django.conf.urls import include, url from normandy.base import views from normandy.base.api import views as api_views from normandy.base.api.routers import MixedViewRouter # API Router router = MixedViewRouter() router.register("user", api_views.UserViewSet) router.register("group", api_views.GroupViewSet) urlpatterns = [ url(r"^$", views.index, name="index"), url(r"^favicon.ico", views.favicon), url(r"^api/v2/service_info/", api_views.ServiceInfoView.as_view(), name="service-info-v2"), url(r"^api/v3/service_info/", api_views.ServiceInfoView.as_view(), name="service-info"), url(r"^api/v1/user/me/", api_views.CurrentUserView.as_view(), name="current-user"), url(r"^api/v3/", include(router.urls)), ]
from django.conf.urls import include, url from normandy.base import views from normandy.base.api import views as api_views from normandy.base.api.routers import MixedViewRouter # API Router router = MixedViewRouter() router.register("user", api_views.UserViewSet) router.register("group", api_views.GroupViewSet) urlpatterns = [ url(r"^$", views.index, name="index"), url(r"^favicon.ico", views.favicon), + url(r"^api/v2/service_info/", api_views.ServiceInfoView.as_view(), name="service-info-v2"), - url(r"^api/v2/service_info/", api_views.ServiceInfoView.as_view(), name="service-info"), ? ^ + url(r"^api/v3/service_info/", api_views.ServiceInfoView.as_view(), name="service-info"), ? ^ url(r"^api/v1/user/me/", api_views.CurrentUserView.as_view(), name="current-user"), url(r"^api/v3/", include(router.urls)), ]
36663add9f53da925f1d29c8c567ab30a1f33139
tests/api_resources/checkout/test_session.py
tests/api_resources/checkout/test_session.py
from __future__ import absolute_import, division, print_function import stripe TEST_RESOURCE_ID = "loc_123" class TestSession(object): def test_is_creatable(self, request_mock): resource = stripe.checkout.Session.create( cancel_url="https://stripe.com/cancel", client_reference_id="1234", line_items=[ { "amount": 123, "currency": "usd", "description": "item 1", "images": ["https://stripe.com/img1"], "name": "name", "quantity": 2, } ], payment_intent_data={"receipt_email": "test@stripe.com"}, payment_method_types=["card"], success_url="https://stripe.com/success", ) request_mock.assert_requested("post", "/v1/checkout/sessions") assert isinstance(resource, stripe.checkout.Session)
from __future__ import absolute_import, division, print_function import stripe TEST_RESOURCE_ID = "cs_123" class TestSession(object): def test_is_creatable(self, request_mock): resource = stripe.checkout.Session.create( cancel_url="https://stripe.com/cancel", client_reference_id="1234", line_items=[ { "amount": 123, "currency": "usd", "description": "item 1", "images": ["https://stripe.com/img1"], "name": "name", "quantity": 2, } ], payment_intent_data={"receipt_email": "test@stripe.com"}, payment_method_types=["card"], success_url="https://stripe.com/success", ) request_mock.assert_requested("post", "/v1/checkout/sessions") assert isinstance(resource, stripe.checkout.Session) def test_is_retrievable(self, request_mock): resource = stripe.checkout.Session.retrieve(TEST_RESOURCE_ID) request_mock.assert_requested( "get", "/v1/checkout/sessions/%s" % TEST_RESOURCE_ID ) assert isinstance(resource, stripe.checkout.Session)
Add support for retrieving a Checkout Session
Add support for retrieving a Checkout Session
Python
mit
stripe/stripe-python
from __future__ import absolute_import, division, print_function import stripe - TEST_RESOURCE_ID = "loc_123" + TEST_RESOURCE_ID = "cs_123" class TestSession(object): def test_is_creatable(self, request_mock): resource = stripe.checkout.Session.create( cancel_url="https://stripe.com/cancel", client_reference_id="1234", line_items=[ { "amount": 123, "currency": "usd", "description": "item 1", "images": ["https://stripe.com/img1"], "name": "name", "quantity": 2, } ], payment_intent_data={"receipt_email": "test@stripe.com"}, payment_method_types=["card"], success_url="https://stripe.com/success", ) request_mock.assert_requested("post", "/v1/checkout/sessions") assert isinstance(resource, stripe.checkout.Session) + def test_is_retrievable(self, request_mock): + resource = stripe.checkout.Session.retrieve(TEST_RESOURCE_ID) + request_mock.assert_requested( + "get", "/v1/checkout/sessions/%s" % TEST_RESOURCE_ID + ) + assert isinstance(resource, stripe.checkout.Session) +
Add support for retrieving a Checkout Session
## Code Before: from __future__ import absolute_import, division, print_function import stripe TEST_RESOURCE_ID = "loc_123" class TestSession(object): def test_is_creatable(self, request_mock): resource = stripe.checkout.Session.create( cancel_url="https://stripe.com/cancel", client_reference_id="1234", line_items=[ { "amount": 123, "currency": "usd", "description": "item 1", "images": ["https://stripe.com/img1"], "name": "name", "quantity": 2, } ], payment_intent_data={"receipt_email": "test@stripe.com"}, payment_method_types=["card"], success_url="https://stripe.com/success", ) request_mock.assert_requested("post", "/v1/checkout/sessions") assert isinstance(resource, stripe.checkout.Session) ## Instruction: Add support for retrieving a Checkout Session ## Code After: from __future__ import absolute_import, division, print_function import stripe TEST_RESOURCE_ID = "cs_123" class TestSession(object): def test_is_creatable(self, request_mock): resource = stripe.checkout.Session.create( cancel_url="https://stripe.com/cancel", client_reference_id="1234", line_items=[ { "amount": 123, "currency": "usd", "description": "item 1", "images": ["https://stripe.com/img1"], "name": "name", "quantity": 2, } ], payment_intent_data={"receipt_email": "test@stripe.com"}, payment_method_types=["card"], success_url="https://stripe.com/success", ) request_mock.assert_requested("post", "/v1/checkout/sessions") assert isinstance(resource, stripe.checkout.Session) def test_is_retrievable(self, request_mock): resource = stripe.checkout.Session.retrieve(TEST_RESOURCE_ID) request_mock.assert_requested( "get", "/v1/checkout/sessions/%s" % TEST_RESOURCE_ID ) assert isinstance(resource, stripe.checkout.Session)
from __future__ import absolute_import, division, print_function import stripe - TEST_RESOURCE_ID = "loc_123" ? -- + TEST_RESOURCE_ID = "cs_123" ? + class TestSession(object): def test_is_creatable(self, request_mock): resource = stripe.checkout.Session.create( cancel_url="https://stripe.com/cancel", client_reference_id="1234", line_items=[ { "amount": 123, "currency": "usd", "description": "item 1", "images": ["https://stripe.com/img1"], "name": "name", "quantity": 2, } ], payment_intent_data={"receipt_email": "test@stripe.com"}, payment_method_types=["card"], success_url="https://stripe.com/success", ) request_mock.assert_requested("post", "/v1/checkout/sessions") assert isinstance(resource, stripe.checkout.Session) + + def test_is_retrievable(self, request_mock): + resource = stripe.checkout.Session.retrieve(TEST_RESOURCE_ID) + request_mock.assert_requested( + "get", "/v1/checkout/sessions/%s" % TEST_RESOURCE_ID + ) + assert isinstance(resource, stripe.checkout.Session)
db41b744b4fea9d16ad53cb7915ddee5ddcffed0
scheduler.py
scheduler.py
import logging import os from apscheduler.schedulers.blocking import BlockingScheduler from raven.base import Client as RavenClient import warner import archiver import announcer import flagger raven_client = RavenClient() logger = logging.getLogger(__name__) # When testing changes, set the "TEST_SCHEDULE" envvar to run more often if os.getenv("TEST_SCHEDULE"): schedule_kwargs = {"hour": "*", "minute": "*/10"} else: schedule_kwargs = {"hour": 4} sched = BlockingScheduler() @sched.scheduled_job("cron", **schedule_kwargs) def destalinate_job(): logger.info("Destalinating") if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ: logger.error("Missing at least one Slack environment variable.") else: try: warner.Warner().warn() archiver.Archiver().archive() announcer.Announcer().announce() flagger.Flagger().flag() logger.info("OK: destalinated") except Exception as e: # pylint: disable=W0703 raven_client.captureException() raise e logger.info("END: destalinate_job") if __name__ == "__main__": sched.start()
import logging import os from apscheduler.schedulers.blocking import BlockingScheduler from raven.base import Client as RavenClient import warner import archiver import announcer import flagger raven_client = RavenClient() logger = logging.getLogger(__name__) # When testing changes, set the "TEST_SCHEDULE" envvar to run more often if os.getenv("TEST_SCHEDULE"): schedule_kwargs = {"hour": "*", "minute": "*/10"} else: schedule_kwargs = {"hour": 4} sched = BlockingScheduler() @sched.scheduled_job("cron", **schedule_kwargs) def destalinate_job(): logger.info("Destalinating") if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ: logger.error("Missing at least one Slack environment variable.") else: try: warner.Warner().warn() archiver.Archiver().archive() announcer.Announcer().announce() flagger.Flagger().flag() logger.info("OK: destalinated") except Exception as e: # pylint: disable=W0703 raven_client.captureException() if not os.getenv('SENTRY_DSN'): raise e logger.info("END: destalinate_job") if __name__ == "__main__": sched.start()
Revert "Re-raise even when capturing by Sentry"
Revert "Re-raise even when capturing by Sentry" This reverts commit 3fe290fe02390e79910e7ded87070d6e03a705a5.
Python
apache-2.0
randsleadershipslack/destalinator,royrapoport/destalinator,royrapoport/destalinator,randsleadershipslack/destalinator,TheConnMan/destalinator,TheConnMan/destalinator
import logging import os from apscheduler.schedulers.blocking import BlockingScheduler from raven.base import Client as RavenClient import warner import archiver import announcer import flagger raven_client = RavenClient() logger = logging.getLogger(__name__) # When testing changes, set the "TEST_SCHEDULE" envvar to run more often if os.getenv("TEST_SCHEDULE"): schedule_kwargs = {"hour": "*", "minute": "*/10"} else: schedule_kwargs = {"hour": 4} sched = BlockingScheduler() @sched.scheduled_job("cron", **schedule_kwargs) def destalinate_job(): logger.info("Destalinating") if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ: logger.error("Missing at least one Slack environment variable.") else: try: warner.Warner().warn() archiver.Archiver().archive() announcer.Announcer().announce() flagger.Flagger().flag() logger.info("OK: destalinated") except Exception as e: # pylint: disable=W0703 raven_client.captureException() + if not os.getenv('SENTRY_DSN'): - raise e + raise e logger.info("END: destalinate_job") if __name__ == "__main__": sched.start()
Revert "Re-raise even when capturing by Sentry"
## Code Before: import logging import os from apscheduler.schedulers.blocking import BlockingScheduler from raven.base import Client as RavenClient import warner import archiver import announcer import flagger raven_client = RavenClient() logger = logging.getLogger(__name__) # When testing changes, set the "TEST_SCHEDULE" envvar to run more often if os.getenv("TEST_SCHEDULE"): schedule_kwargs = {"hour": "*", "minute": "*/10"} else: schedule_kwargs = {"hour": 4} sched = BlockingScheduler() @sched.scheduled_job("cron", **schedule_kwargs) def destalinate_job(): logger.info("Destalinating") if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ: logger.error("Missing at least one Slack environment variable.") else: try: warner.Warner().warn() archiver.Archiver().archive() announcer.Announcer().announce() flagger.Flagger().flag() logger.info("OK: destalinated") except Exception as e: # pylint: disable=W0703 raven_client.captureException() raise e logger.info("END: destalinate_job") if __name__ == "__main__": sched.start() ## Instruction: Revert "Re-raise even when capturing by Sentry" ## Code After: import logging import os from apscheduler.schedulers.blocking import BlockingScheduler from raven.base import Client as RavenClient import warner import archiver import announcer import flagger raven_client = RavenClient() logger = logging.getLogger(__name__) # When testing changes, set the "TEST_SCHEDULE" envvar to run more often if os.getenv("TEST_SCHEDULE"): schedule_kwargs = {"hour": "*", "minute": "*/10"} else: schedule_kwargs = {"hour": 4} sched = BlockingScheduler() @sched.scheduled_job("cron", **schedule_kwargs) def destalinate_job(): logger.info("Destalinating") if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ: logger.error("Missing at least one Slack environment variable.") else: try: warner.Warner().warn() archiver.Archiver().archive() announcer.Announcer().announce() flagger.Flagger().flag() logger.info("OK: destalinated") except Exception as e: # pylint: disable=W0703 raven_client.captureException() if not os.getenv('SENTRY_DSN'): raise e logger.info("END: destalinate_job") if __name__ == "__main__": sched.start()
import logging import os from apscheduler.schedulers.blocking import BlockingScheduler from raven.base import Client as RavenClient import warner import archiver import announcer import flagger raven_client = RavenClient() logger = logging.getLogger(__name__) # When testing changes, set the "TEST_SCHEDULE" envvar to run more often if os.getenv("TEST_SCHEDULE"): schedule_kwargs = {"hour": "*", "minute": "*/10"} else: schedule_kwargs = {"hour": 4} sched = BlockingScheduler() @sched.scheduled_job("cron", **schedule_kwargs) def destalinate_job(): logger.info("Destalinating") if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ: logger.error("Missing at least one Slack environment variable.") else: try: warner.Warner().warn() archiver.Archiver().archive() announcer.Announcer().announce() flagger.Flagger().flag() logger.info("OK: destalinated") except Exception as e: # pylint: disable=W0703 raven_client.captureException() + if not os.getenv('SENTRY_DSN'): - raise e + raise e ? ++++ logger.info("END: destalinate_job") if __name__ == "__main__": sched.start()
c3f8860c717a139d396b0d902db989ab7b8369ba
stock_inventory_hierarchical/__openerp__.py
stock_inventory_hierarchical/__openerp__.py
{ "name": "Hierarchical Inventory adjustments", "summary": "Group several Inventory adjustments in a master inventory", "version": "8.0.2.0.0", "depends": ["stock"], "author": u"Numérigraphe,Odoo Community Association (OCA)", "category": "Warehouse Management", "data": ["views/stock_inventory_view.xml", "wizard/generate_inventory_view.xml"], "images": ["inventory_form.png", "inventory_form_actions.png", "wizard.png"], 'license': 'AGPL-3', 'installable': True }
{ "name": "Hierarchical Inventory adjustments", "summary": "Group several Inventory adjustments in a master inventory", "version": "8.0.2.0.0", "depends": ["stock"], "author": u"Numérigraphe,Odoo Community Association (OCA)", "category": "Warehouse Management", "data": ["views/stock_inventory_view.xml", "wizard/generate_inventory_view.xml"], "images": ["images/inventory_form.png", "images/inventory_form_actions.png", "images/wizard.png"], 'license': 'AGPL-3', 'installable': True }
Fix image path in manifest
Fix image path in manifest
Python
agpl-3.0
kmee/stock-logistics-warehouse,factorlibre/stock-logistics-warehouse,open-synergy/stock-logistics-warehouse,acsone/stock-logistics-warehouse,avoinsystems/stock-logistics-warehouse
{ "name": "Hierarchical Inventory adjustments", "summary": "Group several Inventory adjustments in a master inventory", "version": "8.0.2.0.0", "depends": ["stock"], "author": u"Numérigraphe,Odoo Community Association (OCA)", "category": "Warehouse Management", "data": ["views/stock_inventory_view.xml", "wizard/generate_inventory_view.xml"], - "images": ["inventory_form.png", + "images": ["images/inventory_form.png", - "inventory_form_actions.png", + "images/inventory_form_actions.png", - "wizard.png"], + "images/wizard.png"], 'license': 'AGPL-3', 'installable': True }
Fix image path in manifest
## Code Before: { "name": "Hierarchical Inventory adjustments", "summary": "Group several Inventory adjustments in a master inventory", "version": "8.0.2.0.0", "depends": ["stock"], "author": u"Numérigraphe,Odoo Community Association (OCA)", "category": "Warehouse Management", "data": ["views/stock_inventory_view.xml", "wizard/generate_inventory_view.xml"], "images": ["inventory_form.png", "inventory_form_actions.png", "wizard.png"], 'license': 'AGPL-3', 'installable': True } ## Instruction: Fix image path in manifest ## Code After: { "name": "Hierarchical Inventory adjustments", "summary": "Group several Inventory adjustments in a master inventory", "version": "8.0.2.0.0", "depends": ["stock"], "author": u"Numérigraphe,Odoo Community Association (OCA)", "category": "Warehouse Management", "data": ["views/stock_inventory_view.xml", "wizard/generate_inventory_view.xml"], "images": ["images/inventory_form.png", "images/inventory_form_actions.png", "images/wizard.png"], 'license': 'AGPL-3', 'installable': True }
{ "name": "Hierarchical Inventory adjustments", "summary": "Group several Inventory adjustments in a master inventory", "version": "8.0.2.0.0", "depends": ["stock"], "author": u"Numérigraphe,Odoo Community Association (OCA)", "category": "Warehouse Management", "data": ["views/stock_inventory_view.xml", "wizard/generate_inventory_view.xml"], - "images": ["inventory_form.png", + "images": ["images/inventory_form.png", ? +++++++ - "inventory_form_actions.png", + "images/inventory_form_actions.png", ? +++++++ - "wizard.png"], + "images/wizard.png"], ? +++++++ 'license': 'AGPL-3', 'installable': True }
8d217c9797f19d4276484fd070a4a5f3de623e84
tapioca_toggl/__init__.py
tapioca_toggl/__init__.py
__version__ = '0.1.0'
__version__ = '0.1.0' from .tapioca_toggl import Toggl # noqa
Make api accessible from python package
Make api accessible from python package
Python
mit
hackebrot/tapioca-toggl
__version__ = '0.1.0' + from .tapioca_toggl import Toggl # noqa +
Make api accessible from python package
## Code Before: __version__ = '0.1.0' ## Instruction: Make api accessible from python package ## Code After: __version__ = '0.1.0' from .tapioca_toggl import Toggl # noqa
__version__ = '0.1.0' + + from .tapioca_toggl import Toggl # noqa
3a3d1f5b2c376de3e979aa17d11505dc66421852
test_journal.py
test_journal.py
from contextlib import closing import pytest from journal import app from journal import connect_db from journal import get_database_connection from journal import init_db TEST_DSN = 'dbname=test_learning_journal' def clear_db(): with closing(connect_db()) as db: db.cursor().execute("DROP TABLE entries") db.commit() @pytest.fixture(scope='session') def test_app(): """configure our app for use in testing""" app.config['DATABASE'] = TEST_DSN app.config['TESTING'] = True
from contextlib import closing import pytest from journal import app from journal import connect_db from journal import get_database_connection from journal import init_db TEST_DSN = 'dbname=test_learning_journal' def clear_db(): with closing(connect_db()) as db: db.cursor().execute("DROP TABLE entries") db.commit() @pytest.fixture(scope='session') def test_app(): """configure our app for use in testing""" app.config['DATABASE'] = TEST_DSN app.config['TESTING'] = True @pytest.fixture(scope='session') def db(test_app, request): """initialize the entries table and drop it when finished""" init_db() def cleanup(): clear_db() request.addfinalizer(cleanup)
Add db() to initialize a table and drop when finished
Add db() to initialize a table and drop when finished
Python
mit
sazlin/learning_journal
from contextlib import closing import pytest from journal import app from journal import connect_db from journal import get_database_connection from journal import init_db TEST_DSN = 'dbname=test_learning_journal' def clear_db(): with closing(connect_db()) as db: db.cursor().execute("DROP TABLE entries") db.commit() @pytest.fixture(scope='session') def test_app(): """configure our app for use in testing""" app.config['DATABASE'] = TEST_DSN app.config['TESTING'] = True + + @pytest.fixture(scope='session') + def db(test_app, request): + """initialize the entries table and drop it when finished""" + init_db() + + def cleanup(): + clear_db() + + request.addfinalizer(cleanup)
Add db() to initialize a table and drop when finished
## Code Before: from contextlib import closing import pytest from journal import app from journal import connect_db from journal import get_database_connection from journal import init_db TEST_DSN = 'dbname=test_learning_journal' def clear_db(): with closing(connect_db()) as db: db.cursor().execute("DROP TABLE entries") db.commit() @pytest.fixture(scope='session') def test_app(): """configure our app for use in testing""" app.config['DATABASE'] = TEST_DSN app.config['TESTING'] = True ## Instruction: Add db() to initialize a table and drop when finished ## Code After: from contextlib import closing import pytest from journal import app from journal import connect_db from journal import get_database_connection from journal import init_db TEST_DSN = 'dbname=test_learning_journal' def clear_db(): with closing(connect_db()) as db: db.cursor().execute("DROP TABLE entries") db.commit() @pytest.fixture(scope='session') def test_app(): """configure our app for use in testing""" app.config['DATABASE'] = TEST_DSN app.config['TESTING'] = True @pytest.fixture(scope='session') def db(test_app, request): """initialize the entries table and drop it when finished""" init_db() def cleanup(): clear_db() request.addfinalizer(cleanup)
from contextlib import closing import pytest from journal import app from journal import connect_db from journal import get_database_connection from journal import init_db TEST_DSN = 'dbname=test_learning_journal' def clear_db(): with closing(connect_db()) as db: db.cursor().execute("DROP TABLE entries") db.commit() @pytest.fixture(scope='session') def test_app(): """configure our app for use in testing""" app.config['DATABASE'] = TEST_DSN app.config['TESTING'] = True + + + @pytest.fixture(scope='session') + def db(test_app, request): + """initialize the entries table and drop it when finished""" + init_db() + + def cleanup(): + clear_db() + + request.addfinalizer(cleanup)
c5eb0358e763d626f503fa45228752da10b7c70d
openfisca_core/commons.py
openfisca_core/commons.py
unicode_type = u"".__class__ basestring_type = (b"".__class__, unicode_type) def to_unicode(string): """ :param string: a string that needs to be unicoded :param encoding: a string that represent the encoding type :return: a unicode string if the string is a python 2 str type, returns a unicode version of the string. """ if not isinstance(string, basestring_type): string = str(string) if isinstance(string, unicode_type): return string # Next line only gets triggered if the code is run in python 2 return unicode(string, 'utf-8') class Dummy(object): """A class that does nothing Used by function ``empty_clone`` to create an empty instance from an existing object. """ pass def empty_clone(original): """Create a new empty instance of the same class of the original object.""" new = Dummy() new.__class__ = original.__class__ return new def stringify_array(array): """ Generate a clean string representation of a NumPY array. """ return u'[{}]'.format(u', '.join( to_unicode(cell) for cell in array )) if array is not None else u'None'
unicode_type = u"".__class__ basestring_type = (b"".__class__, unicode_type) def to_unicode(string): """ :param string: a string that needs to be unicoded :param encoding: a string that represent the encoding type :return: a unicode string if the string is a python 2 str type, returns a unicode version of the string. """ if not isinstance(string, basestring_type): string = str(string) if isinstance(string, unicode_type): return string # Next line only gets triggered if the code is run in python 2 return string.decode('utf-8') class Dummy(object): """A class that does nothing Used by function ``empty_clone`` to create an empty instance from an existing object. """ pass def empty_clone(original): """Create a new empty instance of the same class of the original object.""" new = Dummy() new.__class__ = original.__class__ return new def stringify_array(array): """ Generate a clean string representation of a NumPY array. """ return u'[{}]'.format(u', '.join( to_unicode(cell) for cell in array )) if array is not None else u'None'
Make to_unicode work in Python 3
Make to_unicode work in Python 3
Python
agpl-3.0
openfisca/openfisca-core,openfisca/openfisca-core
unicode_type = u"".__class__ basestring_type = (b"".__class__, unicode_type) def to_unicode(string): """ :param string: a string that needs to be unicoded :param encoding: a string that represent the encoding type :return: a unicode string if the string is a python 2 str type, returns a unicode version of the string. """ if not isinstance(string, basestring_type): string = str(string) if isinstance(string, unicode_type): return string # Next line only gets triggered if the code is run in python 2 - return unicode(string, 'utf-8') + return string.decode('utf-8') class Dummy(object): """A class that does nothing Used by function ``empty_clone`` to create an empty instance from an existing object. """ pass def empty_clone(original): """Create a new empty instance of the same class of the original object.""" new = Dummy() new.__class__ = original.__class__ return new def stringify_array(array): """ Generate a clean string representation of a NumPY array. """ return u'[{}]'.format(u', '.join( to_unicode(cell) for cell in array )) if array is not None else u'None'
Make to_unicode work in Python 3
## Code Before: unicode_type = u"".__class__ basestring_type = (b"".__class__, unicode_type) def to_unicode(string): """ :param string: a string that needs to be unicoded :param encoding: a string that represent the encoding type :return: a unicode string if the string is a python 2 str type, returns a unicode version of the string. """ if not isinstance(string, basestring_type): string = str(string) if isinstance(string, unicode_type): return string # Next line only gets triggered if the code is run in python 2 return unicode(string, 'utf-8') class Dummy(object): """A class that does nothing Used by function ``empty_clone`` to create an empty instance from an existing object. """ pass def empty_clone(original): """Create a new empty instance of the same class of the original object.""" new = Dummy() new.__class__ = original.__class__ return new def stringify_array(array): """ Generate a clean string representation of a NumPY array. """ return u'[{}]'.format(u', '.join( to_unicode(cell) for cell in array )) if array is not None else u'None' ## Instruction: Make to_unicode work in Python 3 ## Code After: unicode_type = u"".__class__ basestring_type = (b"".__class__, unicode_type) def to_unicode(string): """ :param string: a string that needs to be unicoded :param encoding: a string that represent the encoding type :return: a unicode string if the string is a python 2 str type, returns a unicode version of the string. """ if not isinstance(string, basestring_type): string = str(string) if isinstance(string, unicode_type): return string # Next line only gets triggered if the code is run in python 2 return string.decode('utf-8') class Dummy(object): """A class that does nothing Used by function ``empty_clone`` to create an empty instance from an existing object. """ pass def empty_clone(original): """Create a new empty instance of the same class of the original object.""" new = Dummy() new.__class__ = original.__class__ return new def stringify_array(array): """ Generate a clean string representation of a NumPY array. """ return u'[{}]'.format(u', '.join( to_unicode(cell) for cell in array )) if array is not None else u'None'
unicode_type = u"".__class__ basestring_type = (b"".__class__, unicode_type) def to_unicode(string): """ :param string: a string that needs to be unicoded :param encoding: a string that represent the encoding type :return: a unicode string if the string is a python 2 str type, returns a unicode version of the string. """ if not isinstance(string, basestring_type): string = str(string) if isinstance(string, unicode_type): return string # Next line only gets triggered if the code is run in python 2 - return unicode(string, 'utf-8') + return string.decode('utf-8') class Dummy(object): """A class that does nothing Used by function ``empty_clone`` to create an empty instance from an existing object. """ pass def empty_clone(original): """Create a new empty instance of the same class of the original object.""" new = Dummy() new.__class__ = original.__class__ return new def stringify_array(array): """ Generate a clean string representation of a NumPY array. """ return u'[{}]'.format(u', '.join( to_unicode(cell) for cell in array )) if array is not None else u'None'
274f5b738386e8a7ad0a7fd5ae46719fe15712de
clowder/clowder/cli/stash_controller.py
clowder/clowder/cli/stash_controller.py
from cement.ext.ext_argparse import expose from clowder.cli.abstract_base_controller import AbstractBaseController class StashController(AbstractBaseController): class Meta: label = 'stash' stacked_on = 'base' stacked_type = 'nested' description = 'Stash current changes' @expose(help="second-controller default command", hide=True) def default(self): print("Inside SecondController.default()")
from cement.ext.ext_argparse import expose from clowder.cli.abstract_base_controller import AbstractBaseController from clowder.commands.util import ( filter_groups, filter_projects_on_project_names, run_group_command, run_project_command ) from clowder.util.decorators import ( print_clowder_repo_status, valid_clowder_yaml_required ) class StashController(AbstractBaseController): class Meta: label = 'stash' stacked_on = 'base' stacked_type = 'nested' description = 'Stash current changes' @expose(help="second-controller default command", hide=True) @valid_clowder_yaml_required @print_clowder_repo_status def default(self): if not any([g.is_dirty() for g in self.clowder.groups]): print('No changes to stash') return if self.app.pargs.projects is None: groups = filter_groups(self.clowder.groups, self.app.pargs.groups) for group in groups: run_group_command(group, self.app.pargs.skip, 'stash') return projects = filter_projects_on_project_names(self.clowder.groups, self.app.pargs.projects) for project in projects: run_project_command(project, self.app.pargs.skip, 'stash')
Add `clowder stash` logic to Cement controller
Add `clowder stash` logic to Cement controller
Python
mit
JrGoodle/clowder,JrGoodle/clowder,JrGoodle/clowder
from cement.ext.ext_argparse import expose from clowder.cli.abstract_base_controller import AbstractBaseController + from clowder.commands.util import ( + filter_groups, + filter_projects_on_project_names, + run_group_command, + run_project_command + ) + from clowder.util.decorators import ( + print_clowder_repo_status, + valid_clowder_yaml_required + ) class StashController(AbstractBaseController): class Meta: label = 'stash' stacked_on = 'base' stacked_type = 'nested' description = 'Stash current changes' @expose(help="second-controller default command", hide=True) + @valid_clowder_yaml_required + @print_clowder_repo_status def default(self): - print("Inside SecondController.default()") + if not any([g.is_dirty() for g in self.clowder.groups]): + print('No changes to stash') + return + if self.app.pargs.projects is None: + groups = filter_groups(self.clowder.groups, self.app.pargs.groups) + for group in groups: + run_group_command(group, self.app.pargs.skip, 'stash') + return + + projects = filter_projects_on_project_names(self.clowder.groups, self.app.pargs.projects) + for project in projects: + run_project_command(project, self.app.pargs.skip, 'stash') +
Add `clowder stash` logic to Cement controller
## Code Before: from cement.ext.ext_argparse import expose from clowder.cli.abstract_base_controller import AbstractBaseController class StashController(AbstractBaseController): class Meta: label = 'stash' stacked_on = 'base' stacked_type = 'nested' description = 'Stash current changes' @expose(help="second-controller default command", hide=True) def default(self): print("Inside SecondController.default()") ## Instruction: Add `clowder stash` logic to Cement controller ## Code After: from cement.ext.ext_argparse import expose from clowder.cli.abstract_base_controller import AbstractBaseController from clowder.commands.util import ( filter_groups, filter_projects_on_project_names, run_group_command, run_project_command ) from clowder.util.decorators import ( print_clowder_repo_status, valid_clowder_yaml_required ) class StashController(AbstractBaseController): class Meta: label = 'stash' stacked_on = 'base' stacked_type = 'nested' description = 'Stash current changes' @expose(help="second-controller default command", hide=True) @valid_clowder_yaml_required @print_clowder_repo_status def default(self): if not any([g.is_dirty() for g in self.clowder.groups]): print('No changes to stash') return if self.app.pargs.projects is None: groups = filter_groups(self.clowder.groups, self.app.pargs.groups) for group in groups: run_group_command(group, self.app.pargs.skip, 'stash') return projects = filter_projects_on_project_names(self.clowder.groups, self.app.pargs.projects) for project in projects: run_project_command(project, self.app.pargs.skip, 'stash')
from cement.ext.ext_argparse import expose from clowder.cli.abstract_base_controller import AbstractBaseController + from clowder.commands.util import ( + filter_groups, + filter_projects_on_project_names, + run_group_command, + run_project_command + ) + from clowder.util.decorators import ( + print_clowder_repo_status, + valid_clowder_yaml_required + ) class StashController(AbstractBaseController): class Meta: label = 'stash' stacked_on = 'base' stacked_type = 'nested' description = 'Stash current changes' @expose(help="second-controller default command", hide=True) + @valid_clowder_yaml_required + @print_clowder_repo_status def default(self): - print("Inside SecondController.default()") + if not any([g.is_dirty() for g in self.clowder.groups]): + print('No changes to stash') + return + + if self.app.pargs.projects is None: + groups = filter_groups(self.clowder.groups, self.app.pargs.groups) + for group in groups: + run_group_command(group, self.app.pargs.skip, 'stash') + return + + projects = filter_projects_on_project_names(self.clowder.groups, self.app.pargs.projects) + for project in projects: + run_project_command(project, self.app.pargs.skip, 'stash')
67daf4140c17ce28b0ab45ddd2366968082de739
two_factor/auth_backends.py
two_factor/auth_backends.py
from django.contrib.auth.backends import ModelBackend from django.utils.timezone import now from oath import accept_totp class TokenBackend(ModelBackend): def authenticate(self, user, token): accepted, drift = accept_totp(key=user.token.seed, response=token) return user if accepted else None class VerifiedComputerBackend(ModelBackend): def authenticate(self, user, computer_id): verification = user.verifiedcomputer_set.get(pk=computer_id) return user if verification.verified_until > now() else None
from django.contrib.auth.backends import ModelBackend from django.utils.timezone import now from oath import accept_totp class TokenBackend(ModelBackend): def authenticate(self, user, token): accepted, drift = accept_totp(key=user.token.seed, response=token) return user if accepted else None class VerifiedComputerBackend(ModelBackend): def authenticate(self, user, computer_id): verification = user.verifiedcomputer_set.get(pk=computer_id) if verification.verified_until < now(): return None verification.last_used_at=now() verification.save() return user
Update last_used_at after successful computer verification
Update last_used_at after successful computer verification
Python
mit
mathspace/django-two-factor-auth,percipient/django-two-factor-auth,percipient/django-two-factor-auth,moreati/django-two-factor-auth,Bouke/django-two-factor-auth,moreati/django-two-factor-auth,mathspace/django-two-factor-auth,koleror/django-two-factor-auth,koleror/django-two-factor-auth,Bouke/django-two-factor-auth,fusionbox/django-two-factor-auth,fusionbox/django-two-factor-auth
from django.contrib.auth.backends import ModelBackend from django.utils.timezone import now from oath import accept_totp class TokenBackend(ModelBackend): def authenticate(self, user, token): accepted, drift = accept_totp(key=user.token.seed, response=token) return user if accepted else None class VerifiedComputerBackend(ModelBackend): def authenticate(self, user, computer_id): verification = user.verifiedcomputer_set.get(pk=computer_id) - return user if verification.verified_until > now() else None + if verification.verified_until < now(): + return None + verification.last_used_at=now() + verification.save() + return user
Update last_used_at after successful computer verification
## Code Before: from django.contrib.auth.backends import ModelBackend from django.utils.timezone import now from oath import accept_totp class TokenBackend(ModelBackend): def authenticate(self, user, token): accepted, drift = accept_totp(key=user.token.seed, response=token) return user if accepted else None class VerifiedComputerBackend(ModelBackend): def authenticate(self, user, computer_id): verification = user.verifiedcomputer_set.get(pk=computer_id) return user if verification.verified_until > now() else None ## Instruction: Update last_used_at after successful computer verification ## Code After: from django.contrib.auth.backends import ModelBackend from django.utils.timezone import now from oath import accept_totp class TokenBackend(ModelBackend): def authenticate(self, user, token): accepted, drift = accept_totp(key=user.token.seed, response=token) return user if accepted else None class VerifiedComputerBackend(ModelBackend): def authenticate(self, user, computer_id): verification = user.verifiedcomputer_set.get(pk=computer_id) if verification.verified_until < now(): return None verification.last_used_at=now() verification.save() return user
from django.contrib.auth.backends import ModelBackend from django.utils.timezone import now from oath import accept_totp class TokenBackend(ModelBackend): def authenticate(self, user, token): accepted, drift = accept_totp(key=user.token.seed, response=token) return user if accepted else None class VerifiedComputerBackend(ModelBackend): def authenticate(self, user, computer_id): verification = user.verifiedcomputer_set.get(pk=computer_id) - return user if verification.verified_until > now() else None ? ------------ ^ ^^^^^^^^^^ + if verification.verified_until < now(): ? ^ ^ + return None + verification.last_used_at=now() + verification.save() + return user
683a3727fc5363c2a2a53fabfde555207e8bab66
brains/orders/models.py
brains/orders/models.py
from django.db import models from django.contrib.auth.models import User # Create your models here. class Order(models.Model): user = models.ForeignKey(User) # Last updated timestamp, used for sorting date = models.DateTimeField(auto_now_add=True, auto_now=True) # When we will strike striketime = models.DateTimeField(null=True) message = models.TextField() subject = models.CharField(max_length=250) # Coordinates of where this news applies # By default, set it to the middle of the map x = models.IntegerField(default=50) y = models.IntegerField(default=50) def __unicode__(self): return self.subject
from django.db import models from django.contrib.auth.models import User # Create your models here. class Order(models.Model): user = models.ForeignKey(User) # Last updated timestamp, used for sorting date = models.DateTimeField(auto_now_add=True, auto_now=True) # When we will strike striketime = models.DateTimeField(null=True, blank=True) message = models.TextField() subject = models.CharField(max_length=250) # Coordinates of where this news applies # By default, set it to the middle of the map x = models.IntegerField(default=50) y = models.IntegerField(default=50) def __unicode__(self): return self.subject
Allow strike time to be blank.
Allow strike time to be blank.
Python
bsd-3-clause
crisisking/udbraaains,crisisking/udbraaains,crisisking/udbraaains,crisisking/udbraaains
from django.db import models from django.contrib.auth.models import User # Create your models here. class Order(models.Model): user = models.ForeignKey(User) # Last updated timestamp, used for sorting date = models.DateTimeField(auto_now_add=True, auto_now=True) # When we will strike - striketime = models.DateTimeField(null=True) + striketime = models.DateTimeField(null=True, blank=True) message = models.TextField() subject = models.CharField(max_length=250) # Coordinates of where this news applies # By default, set it to the middle of the map x = models.IntegerField(default=50) y = models.IntegerField(default=50) def __unicode__(self): return self.subject
Allow strike time to be blank.
## Code Before: from django.db import models from django.contrib.auth.models import User # Create your models here. class Order(models.Model): user = models.ForeignKey(User) # Last updated timestamp, used for sorting date = models.DateTimeField(auto_now_add=True, auto_now=True) # When we will strike striketime = models.DateTimeField(null=True) message = models.TextField() subject = models.CharField(max_length=250) # Coordinates of where this news applies # By default, set it to the middle of the map x = models.IntegerField(default=50) y = models.IntegerField(default=50) def __unicode__(self): return self.subject ## Instruction: Allow strike time to be blank. ## Code After: from django.db import models from django.contrib.auth.models import User # Create your models here. class Order(models.Model): user = models.ForeignKey(User) # Last updated timestamp, used for sorting date = models.DateTimeField(auto_now_add=True, auto_now=True) # When we will strike striketime = models.DateTimeField(null=True, blank=True) message = models.TextField() subject = models.CharField(max_length=250) # Coordinates of where this news applies # By default, set it to the middle of the map x = models.IntegerField(default=50) y = models.IntegerField(default=50) def __unicode__(self): return self.subject
from django.db import models from django.contrib.auth.models import User # Create your models here. class Order(models.Model): user = models.ForeignKey(User) # Last updated timestamp, used for sorting date = models.DateTimeField(auto_now_add=True, auto_now=True) # When we will strike - striketime = models.DateTimeField(null=True) + striketime = models.DateTimeField(null=True, blank=True) ? ++++++++++++ message = models.TextField() subject = models.CharField(max_length=250) # Coordinates of where this news applies # By default, set it to the middle of the map x = models.IntegerField(default=50) y = models.IntegerField(default=50) def __unicode__(self): return self.subject
05b54e3ac66da81733e8bb04eb949dec4e6be904
lamana/lt_exceptions.py
lamana/lt_exceptions.py
'''General classes for a custom exceptions.''' class Error(Exception): pass class FormatError(Error): '''Associate with geo_string formatting.''' pass class InvalidError(Error): '''Associate with invalid, impossible geo_strings.''' pass class KeyError(Error): pass class NotImplementedError(Error): pass class IndeterminateError(Error): '''Associate with INDET exceptions. See Also -------- - "More on IndeterminateError" in the documentation. ''' pass class PlottingError(Error): '''Associated with plotting errors.''' pass
'''General classes for a custom exceptions.''' class Error(Exception): pass class FormatError(Error): '''Associated with geo_string formatting.''' pass #class ValidationError(Error): # '''Associate with invalid, impossible geo_strings.''' # pass #class KeyError(Error): # pass class InputError(Error): '''Associated with invalid user inputs.''' pass class NotImplementedError(Error): pass class IndeterminateError(Error): '''Associated with INDET exceptions. See Also -------- - "More on IndeterminateError" in the documentation. ''' pass class PlottingError(Error): '''Associated with plotting errors.''' pass
Add and deprecate custom expections
Add and deprecate custom expections
Python
bsd-3-clause
par2/lamana
'''General classes for a custom exceptions.''' class Error(Exception): pass class FormatError(Error): - '''Associate with geo_string formatting.''' + '''Associated with geo_string formatting.''' pass - class InvalidError(Error): + #class ValidationError(Error): - '''Associate with invalid, impossible geo_strings.''' + # '''Associate with invalid, impossible geo_strings.''' - pass + # pass - class KeyError(Error): + #class KeyError(Error): + # pass + + + class InputError(Error): + '''Associated with invalid user inputs.''' pass class NotImplementedError(Error): pass class IndeterminateError(Error): - '''Associate with INDET exceptions. + '''Associated with INDET exceptions. See Also -------- - "More on IndeterminateError" in the documentation. ''' pass class PlottingError(Error): '''Associated with plotting errors.''' pass
Add and deprecate custom expections
## Code Before: '''General classes for a custom exceptions.''' class Error(Exception): pass class FormatError(Error): '''Associate with geo_string formatting.''' pass class InvalidError(Error): '''Associate with invalid, impossible geo_strings.''' pass class KeyError(Error): pass class NotImplementedError(Error): pass class IndeterminateError(Error): '''Associate with INDET exceptions. See Also -------- - "More on IndeterminateError" in the documentation. ''' pass class PlottingError(Error): '''Associated with plotting errors.''' pass ## Instruction: Add and deprecate custom expections ## Code After: '''General classes for a custom exceptions.''' class Error(Exception): pass class FormatError(Error): '''Associated with geo_string formatting.''' pass #class ValidationError(Error): # '''Associate with invalid, impossible geo_strings.''' # pass #class KeyError(Error): # pass class InputError(Error): '''Associated with invalid user inputs.''' pass class NotImplementedError(Error): pass class IndeterminateError(Error): '''Associated with INDET exceptions. See Also -------- - "More on IndeterminateError" in the documentation. ''' pass class PlottingError(Error): '''Associated with plotting errors.''' pass
'''General classes for a custom exceptions.''' class Error(Exception): pass class FormatError(Error): - '''Associate with geo_string formatting.''' + '''Associated with geo_string formatting.''' ? + pass - class InvalidError(Error): ? ^^^ + #class ValidationError(Error): ? + ^ +++++ - '''Associate with invalid, impossible geo_strings.''' + # '''Associate with invalid, impossible geo_strings.''' ? + - pass + # pass ? + - class KeyError(Error): + #class KeyError(Error): ? + + # pass + + + class InputError(Error): + '''Associated with invalid user inputs.''' pass class NotImplementedError(Error): pass class IndeterminateError(Error): - '''Associate with INDET exceptions. + '''Associated with INDET exceptions. ? + See Also -------- - "More on IndeterminateError" in the documentation. ''' pass class PlottingError(Error): '''Associated with plotting errors.''' pass
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)
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)
deb5775d0c8adad078ce5d0976f7f6f49963ca2e
accounts/features/steps/logout.py
accounts/features/steps/logout.py
from behave import * # Unique to Scenario: User logs out @when('I click on the logout link') def impl(context): context.browser.find_link_by_text('Logout').first.click() @then('I am no longer authenticated') def impl(context): pass
from behave import * # Unique to Scenario: User logs out @when('I click on the logout link') def impl(context): context.browser.find_link_by_text('Logout').first.click() @then('I am no longer authenticated') def impl(context): #Try to visit my profile page context.browser.visit(context.server_url + 'accounts/profile/') #But find that we're redirected to the login page assert context.browser.url == 'http://localhost:8081/accounts/login/?next=/accounts/profile/'
Test that the user is logged out
Test that the user is logged out
Python
bsd-3-clause
f3r3nc/connect,nlhkabu/connect,nlhkabu/connect,f3r3nc/connect,f3r3nc/connect,nlhkabu/connect,f3r3nc/connect,nlhkabu/connect
from behave import * # Unique to Scenario: User logs out @when('I click on the logout link') def impl(context): context.browser.find_link_by_text('Logout').first.click() @then('I am no longer authenticated') def impl(context): - pass + #Try to visit my profile page + context.browser.visit(context.server_url + 'accounts/profile/') + #But find that we're redirected to the login page + assert context.browser.url == 'http://localhost:8081/accounts/login/?next=/accounts/profile/' +
Test that the user is logged out
## Code Before: from behave import * # Unique to Scenario: User logs out @when('I click on the logout link') def impl(context): context.browser.find_link_by_text('Logout').first.click() @then('I am no longer authenticated') def impl(context): pass ## Instruction: Test that the user is logged out ## Code After: from behave import * # Unique to Scenario: User logs out @when('I click on the logout link') def impl(context): context.browser.find_link_by_text('Logout').first.click() @then('I am no longer authenticated') def impl(context): #Try to visit my profile page context.browser.visit(context.server_url + 'accounts/profile/') #But find that we're redirected to the login page assert context.browser.url == 'http://localhost:8081/accounts/login/?next=/accounts/profile/'
from behave import * # Unique to Scenario: User logs out @when('I click on the logout link') def impl(context): context.browser.find_link_by_text('Logout').first.click() @then('I am no longer authenticated') def impl(context): - pass + #Try to visit my profile page + context.browser.visit(context.server_url + 'accounts/profile/') + + #But find that we're redirected to the login page + assert context.browser.url == 'http://localhost:8081/accounts/login/?next=/accounts/profile/'
cbae962b77b7277f5904279a5418a53e38148f2c
karspexet/show/models.py
karspexet/show/models.py
from django.db import models import datetime class Production(models.Model): name = models.CharField(max_length=100) description = models.TextField(blank=True) def __str__(self): return self.name class Show(models.Model): production = models.ForeignKey(Production, on_delete=models.PROTECT) date = models.DateTimeField() venue = models.ForeignKey('venue.Venue', on_delete=models.PROTECT) @staticmethod def upcoming(): return Show.objects.filter(date__gte=datetime.date.today()) def date_string(self): return self.date.strftime("%Y-%m-%d %H:%M") def __str__(self): return self.production.name + " " + self.date_string() class Meta: ordering = ('date',)
from django.db import models import datetime class Production(models.Model): name = models.CharField(max_length=100) description = models.TextField(blank=True) def __str__(self): return self.name class Show(models.Model): production = models.ForeignKey(Production, on_delete=models.PROTECT) date = models.DateTimeField() venue = models.ForeignKey('venue.Venue', on_delete=models.PROTECT) @staticmethod def upcoming(): return Show.objects.filter(date__gte=datetime.date.today()) @staticmethod def ticket_coverage(): return Show.objects.raw(""" select show.id, show.production_id, show.venue_id, venue.name as venue_name, production.name as production_name, show.date, count(distinct(ticket.id)) as ticket_count, count(distinct(seat.id)) as seat_count, 100 * (count(distinct(ticket.id))::float / count(distinct(seat.id))) as sales_percentage from show_show show left outer join ticket_ticket ticket on ticket.show_id = show.id left join venue_venue venue on show.venue_id = venue.id left join venue_seatinggroup sg on sg.venue_id = venue.id left join venue_seat seat on sg.id = seat.group_id left join show_production production on show.production_id = production.id group by show.id, venue.name, production.name order by show.date desc """) def date_string(self): return self.date.strftime("%Y-%m-%d %H:%M") def __str__(self): return self.production.name + " " + self.date_string() class Meta: ordering = ('date',)
Add Show.ticket_coverage() to get statistics on coverage
Add Show.ticket_coverage() to get statistics on coverage Very left join, much SQL, wow.
Python
mit
Karspexet/Karspexet,Karspexet/Karspexet,Karspexet/Karspexet,Karspexet/Karspexet,Karspexet/Karspexet
from django.db import models import datetime class Production(models.Model): name = models.CharField(max_length=100) description = models.TextField(blank=True) def __str__(self): return self.name class Show(models.Model): production = models.ForeignKey(Production, on_delete=models.PROTECT) date = models.DateTimeField() venue = models.ForeignKey('venue.Venue', on_delete=models.PROTECT) @staticmethod def upcoming(): return Show.objects.filter(date__gte=datetime.date.today()) + @staticmethod + def ticket_coverage(): + return Show.objects.raw(""" + select show.id, + show.production_id, + show.venue_id, + venue.name as venue_name, + production.name as production_name, + show.date, + count(distinct(ticket.id)) as ticket_count, + count(distinct(seat.id)) as seat_count, + 100 * (count(distinct(ticket.id))::float / count(distinct(seat.id))) as sales_percentage + from show_show show + left outer join ticket_ticket ticket on ticket.show_id = show.id + left join venue_venue venue on show.venue_id = venue.id + left join venue_seatinggroup sg on sg.venue_id = venue.id + left join venue_seat seat on sg.id = seat.group_id + left join show_production production on show.production_id = production.id + group by show.id, venue.name, production.name + order by show.date desc + """) + def date_string(self): return self.date.strftime("%Y-%m-%d %H:%M") def __str__(self): return self.production.name + " " + self.date_string() class Meta: ordering = ('date',)
Add Show.ticket_coverage() to get statistics on coverage
## Code Before: from django.db import models import datetime class Production(models.Model): name = models.CharField(max_length=100) description = models.TextField(blank=True) def __str__(self): return self.name class Show(models.Model): production = models.ForeignKey(Production, on_delete=models.PROTECT) date = models.DateTimeField() venue = models.ForeignKey('venue.Venue', on_delete=models.PROTECT) @staticmethod def upcoming(): return Show.objects.filter(date__gte=datetime.date.today()) def date_string(self): return self.date.strftime("%Y-%m-%d %H:%M") def __str__(self): return self.production.name + " " + self.date_string() class Meta: ordering = ('date',) ## Instruction: Add Show.ticket_coverage() to get statistics on coverage ## Code After: from django.db import models import datetime class Production(models.Model): name = models.CharField(max_length=100) description = models.TextField(blank=True) def __str__(self): return self.name class Show(models.Model): production = models.ForeignKey(Production, on_delete=models.PROTECT) date = models.DateTimeField() venue = models.ForeignKey('venue.Venue', on_delete=models.PROTECT) @staticmethod def upcoming(): return Show.objects.filter(date__gte=datetime.date.today()) @staticmethod def ticket_coverage(): return Show.objects.raw(""" select show.id, show.production_id, show.venue_id, venue.name as venue_name, production.name as production_name, show.date, count(distinct(ticket.id)) as ticket_count, count(distinct(seat.id)) as seat_count, 100 * (count(distinct(ticket.id))::float / count(distinct(seat.id))) as sales_percentage from show_show show left outer join ticket_ticket ticket on ticket.show_id = show.id left join venue_venue venue on show.venue_id = venue.id left join venue_seatinggroup sg on sg.venue_id = venue.id left join venue_seat seat on sg.id = seat.group_id left join show_production production on show.production_id = production.id group by show.id, venue.name, production.name order by show.date desc """) def date_string(self): return self.date.strftime("%Y-%m-%d %H:%M") def __str__(self): return self.production.name + " " + self.date_string() class Meta: ordering = ('date',)
from django.db import models import datetime class Production(models.Model): name = models.CharField(max_length=100) description = models.TextField(blank=True) def __str__(self): return self.name class Show(models.Model): production = models.ForeignKey(Production, on_delete=models.PROTECT) date = models.DateTimeField() venue = models.ForeignKey('venue.Venue', on_delete=models.PROTECT) @staticmethod def upcoming(): return Show.objects.filter(date__gte=datetime.date.today()) + @staticmethod + def ticket_coverage(): + return Show.objects.raw(""" + select show.id, + show.production_id, + show.venue_id, + venue.name as venue_name, + production.name as production_name, + show.date, + count(distinct(ticket.id)) as ticket_count, + count(distinct(seat.id)) as seat_count, + 100 * (count(distinct(ticket.id))::float / count(distinct(seat.id))) as sales_percentage + from show_show show + left outer join ticket_ticket ticket on ticket.show_id = show.id + left join venue_venue venue on show.venue_id = venue.id + left join venue_seatinggroup sg on sg.venue_id = venue.id + left join venue_seat seat on sg.id = seat.group_id + left join show_production production on show.production_id = production.id + group by show.id, venue.name, production.name + order by show.date desc + """) + def date_string(self): return self.date.strftime("%Y-%m-%d %H:%M") def __str__(self): return self.production.name + " " + self.date_string() class Meta: ordering = ('date',)
cf6034fc62cc97a5655b371fdef4a4728707fdea
changes/utils/locking.py
changes/utils/locking.py
from flask import current_app from functools import wraps from hashlib import md5 from changes.ext.redis import UnableToGetLock from changes.config import redis def lock(func): @wraps(func) def wrapped(**kwargs): key = '{0}:{1}'.format( func.__name__, md5( '&'.join('{0}={1}'.format(k, repr(v)) for k, v in sorted(kwargs.iteritems())) ).hexdigest() ) try: with redis.lock(key, timeout=1, expire=300, nowait=True): return func(**kwargs) except UnableToGetLock: current_app.logger.warn('Unable to get lock for %s', key) return wrapped
from flask import current_app from functools import wraps from hashlib import md5 from changes.ext.redis import UnableToGetLock from changes.config import redis def lock(func): @wraps(func) def wrapped(**kwargs): key = '{0}:{1}:{2}'.format( func.__module__, func.__name__, md5( '&'.join('{0}={1}'.format(k, repr(v)) for k, v in sorted(kwargs.iteritems())) ).hexdigest() ) try: with redis.lock(key, timeout=1, expire=300, nowait=True): return func(**kwargs) except UnableToGetLock: current_app.logger.warn('Unable to get lock for %s', key) return wrapped
Use __module__ to make @lock unique
Use __module__ to make @lock unique Summary: Fixes T49428. Test Plan: Hard to test on changes_dev because it can't run both handlers (no place to send notifications to), but this seems simple enough... Reviewers: armooo, kylec Reviewed By: kylec Subscribers: changesbot, mkedia, jukka, vishal Maniphest Tasks: T49428 Differential Revision: https://tails.corp.dropbox.com/D122408
Python
apache-2.0
bowlofstew/changes,dropbox/changes,wfxiang08/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,wfxiang08/changes,bowlofstew/changes,dropbox/changes,dropbox/changes,bowlofstew/changes
from flask import current_app from functools import wraps from hashlib import md5 from changes.ext.redis import UnableToGetLock from changes.config import redis def lock(func): @wraps(func) def wrapped(**kwargs): - key = '{0}:{1}'.format( + key = '{0}:{1}:{2}'.format( + func.__module__, func.__name__, md5( '&'.join('{0}={1}'.format(k, repr(v)) for k, v in sorted(kwargs.iteritems())) ).hexdigest() ) try: with redis.lock(key, timeout=1, expire=300, nowait=True): return func(**kwargs) except UnableToGetLock: current_app.logger.warn('Unable to get lock for %s', key) return wrapped
Use __module__ to make @lock unique
## Code Before: from flask import current_app from functools import wraps from hashlib import md5 from changes.ext.redis import UnableToGetLock from changes.config import redis def lock(func): @wraps(func) def wrapped(**kwargs): key = '{0}:{1}'.format( func.__name__, md5( '&'.join('{0}={1}'.format(k, repr(v)) for k, v in sorted(kwargs.iteritems())) ).hexdigest() ) try: with redis.lock(key, timeout=1, expire=300, nowait=True): return func(**kwargs) except UnableToGetLock: current_app.logger.warn('Unable to get lock for %s', key) return wrapped ## Instruction: Use __module__ to make @lock unique ## Code After: from flask import current_app from functools import wraps from hashlib import md5 from changes.ext.redis import UnableToGetLock from changes.config import redis def lock(func): @wraps(func) def wrapped(**kwargs): key = '{0}:{1}:{2}'.format( func.__module__, func.__name__, md5( '&'.join('{0}={1}'.format(k, repr(v)) for k, v in sorted(kwargs.iteritems())) ).hexdigest() ) try: with redis.lock(key, timeout=1, expire=300, nowait=True): return func(**kwargs) except UnableToGetLock: current_app.logger.warn('Unable to get lock for %s', key) return wrapped
from flask import current_app from functools import wraps from hashlib import md5 from changes.ext.redis import UnableToGetLock from changes.config import redis def lock(func): @wraps(func) def wrapped(**kwargs): - key = '{0}:{1}'.format( + key = '{0}:{1}:{2}'.format( ? ++++ + func.__module__, func.__name__, md5( '&'.join('{0}={1}'.format(k, repr(v)) for k, v in sorted(kwargs.iteritems())) ).hexdigest() ) try: with redis.lock(key, timeout=1, expire=300, nowait=True): return func(**kwargs) except UnableToGetLock: current_app.logger.warn('Unable to get lock for %s', key) return wrapped
7e7b0ce7c31c50bdcfaf80d950206e58401c5a8c
workshopvenues/venues/models.py
workshopvenues/venues/models.py
from django.db import models class Facility(models.Model): name = models.CharField(max_length=30) def __unicode__(self): return self.name class Address(models.Model): street = models.CharField(max_length=200) town = models.CharField(max_length=30) postcode = models.CharField(max_length=10) class Venue(models.Model): name = models.CharField(max_length=30) website = models.CharField(max_length=50) address = models.ForeignKey(Address) facilities = models.ManyToManyField(Facility) def __unicode__(self): return self.name
from django.db import models class Facility(models.Model): name = models.CharField(max_length=30) def __unicode__(self): return self.name class Address(models.Model): street = models.CharField(max_length=200) town = models.CharField(max_length=30) postcode = models.CharField(max_length=10) country = models.CharField(max_length=30, blank=True) class Venue(models.Model): name = models.CharField(max_length=30) website = models.CharField(max_length=50) address = models.ForeignKey(Address) facilities = models.ManyToManyField(Facility) def __unicode__(self): return self.name
Add country field to Address model
Add country field to Address model
Python
bsd-3-clause
andreagrandi/workshopvenues
from django.db import models class Facility(models.Model): name = models.CharField(max_length=30) def __unicode__(self): return self.name class Address(models.Model): street = models.CharField(max_length=200) town = models.CharField(max_length=30) postcode = models.CharField(max_length=10) + country = models.CharField(max_length=30, blank=True) class Venue(models.Model): name = models.CharField(max_length=30) website = models.CharField(max_length=50) address = models.ForeignKey(Address) facilities = models.ManyToManyField(Facility) def __unicode__(self): return self.name
Add country field to Address model
## Code Before: from django.db import models class Facility(models.Model): name = models.CharField(max_length=30) def __unicode__(self): return self.name class Address(models.Model): street = models.CharField(max_length=200) town = models.CharField(max_length=30) postcode = models.CharField(max_length=10) class Venue(models.Model): name = models.CharField(max_length=30) website = models.CharField(max_length=50) address = models.ForeignKey(Address) facilities = models.ManyToManyField(Facility) def __unicode__(self): return self.name ## Instruction: Add country field to Address model ## Code After: from django.db import models class Facility(models.Model): name = models.CharField(max_length=30) def __unicode__(self): return self.name class Address(models.Model): street = models.CharField(max_length=200) town = models.CharField(max_length=30) postcode = models.CharField(max_length=10) country = models.CharField(max_length=30, blank=True) class Venue(models.Model): name = models.CharField(max_length=30) website = models.CharField(max_length=50) address = models.ForeignKey(Address) facilities = models.ManyToManyField(Facility) def __unicode__(self): return self.name
from django.db import models class Facility(models.Model): name = models.CharField(max_length=30) def __unicode__(self): return self.name class Address(models.Model): street = models.CharField(max_length=200) town = models.CharField(max_length=30) postcode = models.CharField(max_length=10) + country = models.CharField(max_length=30, blank=True) class Venue(models.Model): name = models.CharField(max_length=30) website = models.CharField(max_length=50) address = models.ForeignKey(Address) facilities = models.ManyToManyField(Facility) def __unicode__(self): return self.name
593020cf6305701e712d04b5bb3e68612dcf7bb4
fireplace/cards/wog/warrior.py
fireplace/cards/wog/warrior.py
from ..utils import * ## # Minions ## # Spells class OG_276: "Blood Warriors" play = Give(CONTROLLER, Copy(FRIENDLY_MINIONS + DAMAGED)) class OG_314: "Blood To Ichor" play = Hit(TARGET,1), Dead(TARGET) | Summon(CONTROLLER, "OG_314b")
from ..utils import * ## # Minions class OG_149: "Ravaging Ghoul" play = Hit(ALL_MINIONS - SELF, 1) class OG_218: "Bloodhoof Brave" enrage = Refresh(SELF, buff="OG_218e") OG_218e = buff(atk=3) class OG_312: "N'Zoth's First Mate" play = Summon(CONTROLLER, "OG_058") ## # Spells class OG_276: "Blood Warriors" play = Give(CONTROLLER, Copy(FRIENDLY_MINIONS + DAMAGED)) class OG_314: "Blood To Ichor" play = Hit(TARGET,1), Dead(TARGET) | Summon(CONTROLLER, "OG_314b")
Implement Ravaging Ghoul, Bloodhoof Brave, N'Zoth's First Mate
Implement Ravaging Ghoul, Bloodhoof Brave, N'Zoth's First Mate
Python
agpl-3.0
beheh/fireplace,NightKev/fireplace,jleclanche/fireplace
from ..utils import * ## # Minions + + class OG_149: + "Ravaging Ghoul" + play = Hit(ALL_MINIONS - SELF, 1) + + + class OG_218: + "Bloodhoof Brave" + enrage = Refresh(SELF, buff="OG_218e") + + OG_218e = buff(atk=3) + + + class OG_312: + "N'Zoth's First Mate" + play = Summon(CONTROLLER, "OG_058") ## # Spells class OG_276: "Blood Warriors" play = Give(CONTROLLER, Copy(FRIENDLY_MINIONS + DAMAGED)) class OG_314: "Blood To Ichor" play = Hit(TARGET,1), Dead(TARGET) | Summon(CONTROLLER, "OG_314b")
Implement Ravaging Ghoul, Bloodhoof Brave, N'Zoth's First Mate
## Code Before: from ..utils import * ## # Minions ## # Spells class OG_276: "Blood Warriors" play = Give(CONTROLLER, Copy(FRIENDLY_MINIONS + DAMAGED)) class OG_314: "Blood To Ichor" play = Hit(TARGET,1), Dead(TARGET) | Summon(CONTROLLER, "OG_314b") ## Instruction: Implement Ravaging Ghoul, Bloodhoof Brave, N'Zoth's First Mate ## Code After: from ..utils import * ## # Minions class OG_149: "Ravaging Ghoul" play = Hit(ALL_MINIONS - SELF, 1) class OG_218: "Bloodhoof Brave" enrage = Refresh(SELF, buff="OG_218e") OG_218e = buff(atk=3) class OG_312: "N'Zoth's First Mate" play = Summon(CONTROLLER, "OG_058") ## # Spells class OG_276: "Blood Warriors" play = Give(CONTROLLER, Copy(FRIENDLY_MINIONS + DAMAGED)) class OG_314: "Blood To Ichor" play = Hit(TARGET,1), Dead(TARGET) | Summon(CONTROLLER, "OG_314b")
from ..utils import * ## # Minions + + class OG_149: + "Ravaging Ghoul" + play = Hit(ALL_MINIONS - SELF, 1) + + + class OG_218: + "Bloodhoof Brave" + enrage = Refresh(SELF, buff="OG_218e") + + OG_218e = buff(atk=3) + + + class OG_312: + "N'Zoth's First Mate" + play = Summon(CONTROLLER, "OG_058") ## # Spells class OG_276: "Blood Warriors" play = Give(CONTROLLER, Copy(FRIENDLY_MINIONS + DAMAGED)) class OG_314: "Blood To Ichor" play = Hit(TARGET,1), Dead(TARGET) | Summon(CONTROLLER, "OG_314b")
f0ac78b3bfc0f81f142e66030e1e822dacfafe14
setup.py
setup.py
from distutils.core import setup setup(name='ansi', version='0.3.0', description='ANSI cursor movement and graphics', author='Wijnand Modderman-Lenstra', author_email='maze@pyth0n.org', url='https://github.com/tehmaze/ansi/', packages = ['ansi', 'ansi.colour'], long_description=''' ANSI ==== Various ANSI escape codes, used in moving the cursor in a text console or rendering coloured text. Example ------- Print something in bold yellow on a red background:: >>> from ansi.colour import fg, bg, reset >>> print map(str, [bg.red, fg.yellow, 'Hello world!', reset]) ... If you like syntactic sugar, you may also do:: >>> print bg.red(fg.yellow('Hello world!')) ... Also, 256 RGB colors are supported:: >>> from ansi.colour import rgb, reset >>> print rgb(0xff, 0x80, 0x00) + 'hello world' + reset ... If you prefer to use American English in stead:: >>> from ansi.color import ... ''')
from distutils.core import setup setup(name='ansi', version='0.3.0', description='ANSI cursor movement and graphics', author='Wijnand Modderman-Lenstra', author_email='maze@pyth0n.org', url='https://github.com/tehmaze/ansi/', packages = ['ansi', 'ansi.colour'], package_data = {'ansi': ['py.typed']}, long_description=''' ANSI ==== Various ANSI escape codes, used in moving the cursor in a text console or rendering coloured text. Example ------- Print something in bold yellow on a red background:: >>> from ansi.colour import fg, bg, reset >>> print map(str, [bg.red, fg.yellow, 'Hello world!', reset]) ... If you like syntactic sugar, you may also do:: >>> print bg.red(fg.yellow('Hello world!')) ... Also, 256 RGB colors are supported:: >>> from ansi.colour import rgb, reset >>> print rgb(0xff, 0x80, 0x00) + 'hello world' + reset ... If you prefer to use American English in stead:: >>> from ansi.color import ... ''')
Include py.typed marker in package
Include py.typed marker in package
Python
mit
tehmaze/ansi
from distutils.core import setup setup(name='ansi', version='0.3.0', description='ANSI cursor movement and graphics', author='Wijnand Modderman-Lenstra', author_email='maze@pyth0n.org', url='https://github.com/tehmaze/ansi/', packages = ['ansi', 'ansi.colour'], + package_data = {'ansi': ['py.typed']}, long_description=''' ANSI ==== Various ANSI escape codes, used in moving the cursor in a text console or rendering coloured text. Example ------- Print something in bold yellow on a red background:: >>> from ansi.colour import fg, bg, reset >>> print map(str, [bg.red, fg.yellow, 'Hello world!', reset]) ... If you like syntactic sugar, you may also do:: >>> print bg.red(fg.yellow('Hello world!')) ... Also, 256 RGB colors are supported:: >>> from ansi.colour import rgb, reset >>> print rgb(0xff, 0x80, 0x00) + 'hello world' + reset ... If you prefer to use American English in stead:: >>> from ansi.color import ... ''')
Include py.typed marker in package
## Code Before: from distutils.core import setup setup(name='ansi', version='0.3.0', description='ANSI cursor movement and graphics', author='Wijnand Modderman-Lenstra', author_email='maze@pyth0n.org', url='https://github.com/tehmaze/ansi/', packages = ['ansi', 'ansi.colour'], long_description=''' ANSI ==== Various ANSI escape codes, used in moving the cursor in a text console or rendering coloured text. Example ------- Print something in bold yellow on a red background:: >>> from ansi.colour import fg, bg, reset >>> print map(str, [bg.red, fg.yellow, 'Hello world!', reset]) ... If you like syntactic sugar, you may also do:: >>> print bg.red(fg.yellow('Hello world!')) ... Also, 256 RGB colors are supported:: >>> from ansi.colour import rgb, reset >>> print rgb(0xff, 0x80, 0x00) + 'hello world' + reset ... If you prefer to use American English in stead:: >>> from ansi.color import ... ''') ## Instruction: Include py.typed marker in package ## Code After: from distutils.core import setup setup(name='ansi', version='0.3.0', description='ANSI cursor movement and graphics', author='Wijnand Modderman-Lenstra', author_email='maze@pyth0n.org', url='https://github.com/tehmaze/ansi/', packages = ['ansi', 'ansi.colour'], package_data = {'ansi': ['py.typed']}, long_description=''' ANSI ==== Various ANSI escape codes, used in moving the cursor in a text console or rendering coloured text. Example ------- Print something in bold yellow on a red background:: >>> from ansi.colour import fg, bg, reset >>> print map(str, [bg.red, fg.yellow, 'Hello world!', reset]) ... If you like syntactic sugar, you may also do:: >>> print bg.red(fg.yellow('Hello world!')) ... Also, 256 RGB colors are supported:: >>> from ansi.colour import rgb, reset >>> print rgb(0xff, 0x80, 0x00) + 'hello world' + reset ... If you prefer to use American English in stead:: >>> from ansi.color import ... ''')
from distutils.core import setup setup(name='ansi', version='0.3.0', description='ANSI cursor movement and graphics', author='Wijnand Modderman-Lenstra', author_email='maze@pyth0n.org', url='https://github.com/tehmaze/ansi/', packages = ['ansi', 'ansi.colour'], + package_data = {'ansi': ['py.typed']}, long_description=''' ANSI ==== Various ANSI escape codes, used in moving the cursor in a text console or rendering coloured text. Example ------- Print something in bold yellow on a red background:: >>> from ansi.colour import fg, bg, reset >>> print map(str, [bg.red, fg.yellow, 'Hello world!', reset]) ... If you like syntactic sugar, you may also do:: >>> print bg.red(fg.yellow('Hello world!')) ... Also, 256 RGB colors are supported:: >>> from ansi.colour import rgb, reset >>> print rgb(0xff, 0x80, 0x00) + 'hello world' + reset ... If you prefer to use American English in stead:: >>> from ansi.color import ... ''')
c04103b457040355da9dcf6a1059539bf6470092
mutt-addressbook.py
mutt-addressbook.py
try: from sys import argv import ldap3 LDAPDIRS = [ ('ldaps://ldappv.rwth-aachen.de', 'ou=People,dc=rwth-aachen,dc=de') ] FILTER = '(mail=*)' ATTRS = ['cn', 'mail'] print('Searching … ', end='', flush=True) entries = [] for d in LDAPDIRS: with ldap3.Connection(d[0], auto_bind=True) as conn: print(d[0] + ' … ', end='', flush=True) flt = '(&' + FILTER + \ '(|(mail=' + argv[1] + '*)(cn=' + argv[1] + '*)))' conn.search(d[1], flt, attributes=ATTRS) entries.extend(conn.entries) if len(entries) == 0: print('No entries found!') exit(1) print(str(len(entries)) + ' entries found!') for i in entries: for m in i.mail.values: print(m + '\t' + i.cn[0] + '\t' + i.entry_dn) except Exception as e: print("Error: " + type(e).__name__ + ": " + str(e)) exit(1)
try: from sys import argv import ldap3 LDAPDIRS = [ ('ldaps://ldappv.rwth-aachen.de', 'ou=People,dc=rwth-aachen,dc=de') ] FILTER = '(mail=*)' ATTRS = ['cn', 'mail'] print('Searching … ', end='', flush=True) entries = [] for d in LDAPDIRS: with ldap3.Connection(d[0], auto_bind=True) as conn: print(''.join((d[0], ' … ')), end='', flush=True) flt = '(&{0}(|(mail={1}*)(cn={1}*)))'.format(FILTER, argv[1]) conn.search(d[1], flt, attributes=ATTRS) entries.extend(conn.entries) if len(entries) == 0: print('No entries found!') exit(1) print('{:d} entries found!'.format(len(entries))) for i in entries: for m in i.mail.values: print('{}\t{}\t{}'.format(m, i.cn[0], i.entry_dn)) except Exception as e: print('Error: {}: {}'.format(type(e).__name__, e)) exit(1)
Rework string concatenation with join and format
Rework string concatenation with join and format Signed-off-by: Alwed <b03a9dbc84dbfcd49b3dd10dfbe7e015dc04cee5@t-online.de>
Python
isc
qsuscs/mutt-addressbook
try: from sys import argv import ldap3 LDAPDIRS = [ ('ldaps://ldappv.rwth-aachen.de', 'ou=People,dc=rwth-aachen,dc=de') ] FILTER = '(mail=*)' ATTRS = ['cn', 'mail'] print('Searching … ', end='', flush=True) entries = [] for d in LDAPDIRS: with ldap3.Connection(d[0], auto_bind=True) as conn: - print(d[0] + ' … ', end='', flush=True) + print(''.join((d[0], ' … ')), end='', flush=True) + flt = '(&{0}(|(mail={1}*)(cn={1}*)))'.format(FILTER, argv[1]) - flt = '(&' + FILTER + \ - '(|(mail=' + argv[1] + '*)(cn=' + argv[1] + '*)))' conn.search(d[1], flt, attributes=ATTRS) entries.extend(conn.entries) if len(entries) == 0: print('No entries found!') exit(1) - print(str(len(entries)) + ' entries found!') + print('{:d} entries found!'.format(len(entries))) for i in entries: for m in i.mail.values: - print(m + '\t' + i.cn[0] + '\t' + i.entry_dn) + print('{}\t{}\t{}'.format(m, i.cn[0], i.entry_dn)) except Exception as e: - print("Error: " + type(e).__name__ + ": " + str(e)) + print('Error: {}: {}'.format(type(e).__name__, e)) exit(1)
Rework string concatenation with join and format
## Code Before: try: from sys import argv import ldap3 LDAPDIRS = [ ('ldaps://ldappv.rwth-aachen.de', 'ou=People,dc=rwth-aachen,dc=de') ] FILTER = '(mail=*)' ATTRS = ['cn', 'mail'] print('Searching … ', end='', flush=True) entries = [] for d in LDAPDIRS: with ldap3.Connection(d[0], auto_bind=True) as conn: print(d[0] + ' … ', end='', flush=True) flt = '(&' + FILTER + \ '(|(mail=' + argv[1] + '*)(cn=' + argv[1] + '*)))' conn.search(d[1], flt, attributes=ATTRS) entries.extend(conn.entries) if len(entries) == 0: print('No entries found!') exit(1) print(str(len(entries)) + ' entries found!') for i in entries: for m in i.mail.values: print(m + '\t' + i.cn[0] + '\t' + i.entry_dn) except Exception as e: print("Error: " + type(e).__name__ + ": " + str(e)) exit(1) ## Instruction: Rework string concatenation with join and format ## Code After: try: from sys import argv import ldap3 LDAPDIRS = [ ('ldaps://ldappv.rwth-aachen.de', 'ou=People,dc=rwth-aachen,dc=de') ] FILTER = '(mail=*)' ATTRS = ['cn', 'mail'] print('Searching … ', end='', flush=True) entries = [] for d in LDAPDIRS: with ldap3.Connection(d[0], auto_bind=True) as conn: print(''.join((d[0], ' … ')), end='', flush=True) flt = '(&{0}(|(mail={1}*)(cn={1}*)))'.format(FILTER, argv[1]) conn.search(d[1], flt, attributes=ATTRS) entries.extend(conn.entries) if len(entries) == 0: print('No entries found!') exit(1) print('{:d} entries found!'.format(len(entries))) for i in entries: for m in i.mail.values: print('{}\t{}\t{}'.format(m, i.cn[0], i.entry_dn)) except Exception as e: print('Error: {}: {}'.format(type(e).__name__, e)) exit(1)
try: from sys import argv import ldap3 LDAPDIRS = [ ('ldaps://ldappv.rwth-aachen.de', 'ou=People,dc=rwth-aachen,dc=de') ] FILTER = '(mail=*)' ATTRS = ['cn', 'mail'] print('Searching … ', end='', flush=True) entries = [] for d in LDAPDIRS: with ldap3.Connection(d[0], auto_bind=True) as conn: - print(d[0] + ' … ', end='', flush=True) ? ^^ + print(''.join((d[0], ' … ')), end='', flush=True) ? +++++++++ ^ ++ + flt = '(&{0}(|(mail={1}*)(cn={1}*)))'.format(FILTER, argv[1]) - flt = '(&' + FILTER + \ - '(|(mail=' + argv[1] + '*)(cn=' + argv[1] + '*)))' conn.search(d[1], flt, attributes=ATTRS) entries.extend(conn.entries) if len(entries) == 0: print('No entries found!') exit(1) - print(str(len(entries)) + ' entries found!') + print('{:d} entries found!'.format(len(entries))) for i in entries: for m in i.mail.values: - print(m + '\t' + i.cn[0] + '\t' + i.entry_dn) + print('{}\t{}\t{}'.format(m, i.cn[0], i.entry_dn)) except Exception as e: - print("Error: " + type(e).__name__ + ": " + str(e)) + print('Error: {}: {}'.format(type(e).__name__, e)) exit(1)
6dfb0c1ea4fb3d12d14a07d0e831eb32f3b2f340
yaml_argparse.py
yaml_argparse.py
import argparse import yaml def parse_arguments_based_on_yaml(yaml_file): with open(yaml_file) as f: yaml_data = yaml.load(f) # to start with, support only a single parameter key = list(yaml_data.keys())[0] value = yaml_data[key] parser = argparse.ArgumentParser() parser.add_argument("-{}".format(key), default=value) args = parser.parse_args() return args
import argparse import yaml def parse_arguments_based_on_yaml(yaml_file): with open(yaml_file) as f: yaml_data = yaml.load(f) parser = argparse.ArgumentParser() for key, value in yaml_data.items(): parser.add_argument("-{}".format(key), default=value) args = parser.parse_args() return args
Implement creating arguments for multiple strings
Implement creating arguments for multiple strings
Python
mit
krasch/yaml_argparse,krasch/quickargs
import argparse import yaml def parse_arguments_based_on_yaml(yaml_file): with open(yaml_file) as f: yaml_data = yaml.load(f) - # to start with, support only a single parameter - key = list(yaml_data.keys())[0] - value = yaml_data[key] parser = argparse.ArgumentParser() + for key, value in yaml_data.items(): - parser.add_argument("-{}".format(key), default=value) + parser.add_argument("-{}".format(key), default=value) args = parser.parse_args() return args
Implement creating arguments for multiple strings
## Code Before: import argparse import yaml def parse_arguments_based_on_yaml(yaml_file): with open(yaml_file) as f: yaml_data = yaml.load(f) # to start with, support only a single parameter key = list(yaml_data.keys())[0] value = yaml_data[key] parser = argparse.ArgumentParser() parser.add_argument("-{}".format(key), default=value) args = parser.parse_args() return args ## Instruction: Implement creating arguments for multiple strings ## Code After: import argparse import yaml def parse_arguments_based_on_yaml(yaml_file): with open(yaml_file) as f: yaml_data = yaml.load(f) parser = argparse.ArgumentParser() for key, value in yaml_data.items(): parser.add_argument("-{}".format(key), default=value) args = parser.parse_args() return args
import argparse import yaml def parse_arguments_based_on_yaml(yaml_file): with open(yaml_file) as f: yaml_data = yaml.load(f) - # to start with, support only a single parameter - key = list(yaml_data.keys())[0] - value = yaml_data[key] parser = argparse.ArgumentParser() + for key, value in yaml_data.items(): - parser.add_argument("-{}".format(key), default=value) + parser.add_argument("-{}".format(key), default=value) ? ++++ args = parser.parse_args() return args
7e63e514c041ccc12ff5caa01fb4f6684727788b
src/PerformerIndexEntry.py
src/PerformerIndexEntry.py
from BaseIndexEntry import BaseIndexEntry class PerformerIndexEntry(BaseIndexEntry): def __init__(self, name, titles, number): super(PerformerIndexEntry, self).__init__(name, titles, number) # Set the performer number on each of the titles for title in self._titles: title.performer_number = self._number # To be set later self._albums = [] self._albums_initialised = False self._freeze() def __str__(self): return '{}: {} {}, albums: {} {}, titles: {}'.format( self.__class__.__name__, self._number, self._name, self.number_of_albums, self._albums, self.number_of_titles) def init_albums(self): for title in self._titles: if title.album_number not in self._albums: self._albums.append(title.album_number) self._albums_initialised = True @property def albums(self): if self._albums_initialised: return self._albums else: raise Exception("Albums not initialised.") @property def number_of_albums(self): return len(self._albums)
from BaseIndexEntry import BaseIndexEntry class PerformerIndexEntry(BaseIndexEntry): '''A class to hold index data for performers. Performers have titles and albums. ''' def __init__(self, name, titles, number): super(PerformerIndexEntry, self).__init__(name, titles, number) # Set the performer number on each of the titles for title in self._titles: title.performer_number = self._number # To be set later self._albums = [] self._album_numbers = [] self._albums_initialised = False self._freeze() def __str__(self): return '{}: {} {}, albums: {} {}, titles: {}'.format( self.__class__.__name__, self._number, self._name, self.number_of_albums, self._album_numbers, self.number_of_titles) def init_albums(self, albums): for title in self._titles: if title.album_number not in self._album_numbers: self._album_numbers.append(title.album_number) self._albums.append(albums[title.album_number]) self._albums_initialised = True @property def album_numbers(self): if self._albums_initialised: return self._album_numbers else: raise Exception("Albums not initialised.") @property def number_of_albums(self): if self._albums_initialised: return len(self._album_numbers) else: raise Exception("Albums not initialised.") def album(self, album_number): for a in self._albums: if a.number == album_number: return a return None def number_of_titles_for_album(self, album_number): count = set() for title in self._titles: if title.album_number == album_number: count.add(title.index) return len(count)
Store references to albums, add new methods.
Store references to albums, add new methods.
Python
apache-2.0
chrrrisw/kmel_db,chrrrisw/kmel_db
from BaseIndexEntry import BaseIndexEntry class PerformerIndexEntry(BaseIndexEntry): + '''A class to hold index data for performers. + + Performers have titles and albums. + ''' def __init__(self, name, titles, number): super(PerformerIndexEntry, self).__init__(name, titles, number) # Set the performer number on each of the titles for title in self._titles: title.performer_number = self._number # To be set later self._albums = [] + self._album_numbers = [] self._albums_initialised = False self._freeze() def __str__(self): return '{}: {} {}, albums: {} {}, titles: {}'.format( self.__class__.__name__, self._number, self._name, - self.number_of_albums, self._albums, + self.number_of_albums, self._album_numbers, self.number_of_titles) - def init_albums(self): + def init_albums(self, albums): for title in self._titles: - if title.album_number not in self._albums: + if title.album_number not in self._album_numbers: - self._albums.append(title.album_number) + self._album_numbers.append(title.album_number) + self._albums.append(albums[title.album_number]) self._albums_initialised = True @property - def albums(self): + def album_numbers(self): if self._albums_initialised: - return self._albums + return self._album_numbers else: raise Exception("Albums not initialised.") @property def number_of_albums(self): + if self._albums_initialised: - return len(self._albums) + return len(self._album_numbers) + else: + raise Exception("Albums not initialised.") + def album(self, album_number): + for a in self._albums: + if a.number == album_number: + return a + return None + + def number_of_titles_for_album(self, album_number): + count = set() + for title in self._titles: + if title.album_number == album_number: + count.add(title.index) + return len(count) +
Store references to albums, add new methods.
## Code Before: from BaseIndexEntry import BaseIndexEntry class PerformerIndexEntry(BaseIndexEntry): def __init__(self, name, titles, number): super(PerformerIndexEntry, self).__init__(name, titles, number) # Set the performer number on each of the titles for title in self._titles: title.performer_number = self._number # To be set later self._albums = [] self._albums_initialised = False self._freeze() def __str__(self): return '{}: {} {}, albums: {} {}, titles: {}'.format( self.__class__.__name__, self._number, self._name, self.number_of_albums, self._albums, self.number_of_titles) def init_albums(self): for title in self._titles: if title.album_number not in self._albums: self._albums.append(title.album_number) self._albums_initialised = True @property def albums(self): if self._albums_initialised: return self._albums else: raise Exception("Albums not initialised.") @property def number_of_albums(self): return len(self._albums) ## Instruction: Store references to albums, add new methods. ## Code After: from BaseIndexEntry import BaseIndexEntry class PerformerIndexEntry(BaseIndexEntry): '''A class to hold index data for performers. Performers have titles and albums. ''' def __init__(self, name, titles, number): super(PerformerIndexEntry, self).__init__(name, titles, number) # Set the performer number on each of the titles for title in self._titles: title.performer_number = self._number # To be set later self._albums = [] self._album_numbers = [] self._albums_initialised = False self._freeze() def __str__(self): return '{}: {} {}, albums: {} {}, titles: {}'.format( self.__class__.__name__, self._number, self._name, self.number_of_albums, self._album_numbers, self.number_of_titles) def init_albums(self, albums): for title in self._titles: if title.album_number not in self._album_numbers: self._album_numbers.append(title.album_number) self._albums.append(albums[title.album_number]) self._albums_initialised = True @property def album_numbers(self): if self._albums_initialised: return self._album_numbers else: raise Exception("Albums not initialised.") @property def number_of_albums(self): if self._albums_initialised: return len(self._album_numbers) else: raise Exception("Albums not initialised.") def album(self, album_number): for a in self._albums: if a.number == album_number: return a return None def number_of_titles_for_album(self, album_number): count = set() for title in self._titles: if title.album_number == album_number: count.add(title.index) return len(count)
from BaseIndexEntry import BaseIndexEntry class PerformerIndexEntry(BaseIndexEntry): + '''A class to hold index data for performers. + + Performers have titles and albums. + ''' def __init__(self, name, titles, number): super(PerformerIndexEntry, self).__init__(name, titles, number) # Set the performer number on each of the titles for title in self._titles: title.performer_number = self._number # To be set later self._albums = [] + self._album_numbers = [] self._albums_initialised = False self._freeze() def __str__(self): return '{}: {} {}, albums: {} {}, titles: {}'.format( self.__class__.__name__, self._number, self._name, - self.number_of_albums, self._albums, + self.number_of_albums, self._album_numbers, ? +++++++ self.number_of_titles) - def init_albums(self): + def init_albums(self, albums): ? ++++++++ for title in self._titles: - if title.album_number not in self._albums: + if title.album_number not in self._album_numbers: ? +++++++ - self._albums.append(title.album_number) + self._album_numbers.append(title.album_number) ? +++++++ + self._albums.append(albums[title.album_number]) self._albums_initialised = True @property - def albums(self): + def album_numbers(self): ? +++++++ if self._albums_initialised: - return self._albums + return self._album_numbers ? +++++++ else: raise Exception("Albums not initialised.") @property def number_of_albums(self): + if self._albums_initialised: - return len(self._albums) + return len(self._album_numbers) ? ++++ +++++++ + else: + raise Exception("Albums not initialised.") + + def album(self, album_number): + for a in self._albums: + if a.number == album_number: + return a + return None + + def number_of_titles_for_album(self, album_number): + count = set() + for title in self._titles: + if title.album_number == album_number: + count.add(title.index) + return len(count)
159aea1c97b8e8de45802cace031e7206c3c8fec
thecure/sprites/tile.py
thecure/sprites/tile.py
from thecure.resources import load_spritesheet_frame from thecure.sprites import Sprite class Tile(Sprite): NAME = 'tile' WIDTH = 64 HEIGHT = 64 NEED_TICKS = False def __init__(self, filename, tile_offset): super(Tile, self).__init__() self.filename = filename self.tile_offset = tile_offset self.rect.size = (self.WIDTH, self.HEIGHT) def update_image(self): self.image = load_spritesheet_frame(self.filename, self.tile_offset, frame_size=(self.WIDTH, self.HEIGHT)) assert self.image
from thecure.resources import load_spritesheet_frame from thecure.sprites import Sprite class Tile(Sprite): NAME = 'tile' WIDTH = 64 HEIGHT = 64 NEED_TICKS = False def __init__(self, filename, tile_offset): super(Tile, self).__init__() self.filename = filename self.tile_offset = tile_offset self.rect.size = (self.WIDTH, self.HEIGHT) def __str__(self): return 'Tile %s:%s at %s' % (self.filename, self.tile_offset, self.rect.topleft) def update_image(self): self.image = load_spritesheet_frame(self.filename, self.tile_offset, frame_size=self.rect.size) assert self.image
Add a __str__ for Tile.
Add a __str__ for Tile.
Python
mit
chipx86/the-cure
from thecure.resources import load_spritesheet_frame from thecure.sprites import Sprite class Tile(Sprite): NAME = 'tile' WIDTH = 64 HEIGHT = 64 NEED_TICKS = False def __init__(self, filename, tile_offset): super(Tile, self).__init__() self.filename = filename self.tile_offset = tile_offset self.rect.size = (self.WIDTH, self.HEIGHT) + def __str__(self): + return 'Tile %s:%s at %s' % (self.filename, self.tile_offset, + self.rect.topleft) + def update_image(self): self.image = load_spritesheet_frame(self.filename, self.tile_offset, - frame_size=(self.WIDTH, + frame_size=self.rect.size) - self.HEIGHT)) assert self.image
Add a __str__ for Tile.
## Code Before: from thecure.resources import load_spritesheet_frame from thecure.sprites import Sprite class Tile(Sprite): NAME = 'tile' WIDTH = 64 HEIGHT = 64 NEED_TICKS = False def __init__(self, filename, tile_offset): super(Tile, self).__init__() self.filename = filename self.tile_offset = tile_offset self.rect.size = (self.WIDTH, self.HEIGHT) def update_image(self): self.image = load_spritesheet_frame(self.filename, self.tile_offset, frame_size=(self.WIDTH, self.HEIGHT)) assert self.image ## Instruction: Add a __str__ for Tile. ## Code After: from thecure.resources import load_spritesheet_frame from thecure.sprites import Sprite class Tile(Sprite): NAME = 'tile' WIDTH = 64 HEIGHT = 64 NEED_TICKS = False def __init__(self, filename, tile_offset): super(Tile, self).__init__() self.filename = filename self.tile_offset = tile_offset self.rect.size = (self.WIDTH, self.HEIGHT) def __str__(self): return 'Tile %s:%s at %s' % (self.filename, self.tile_offset, self.rect.topleft) def update_image(self): self.image = load_spritesheet_frame(self.filename, self.tile_offset, frame_size=self.rect.size) assert self.image
from thecure.resources import load_spritesheet_frame from thecure.sprites import Sprite class Tile(Sprite): NAME = 'tile' WIDTH = 64 HEIGHT = 64 NEED_TICKS = False def __init__(self, filename, tile_offset): super(Tile, self).__init__() self.filename = filename self.tile_offset = tile_offset self.rect.size = (self.WIDTH, self.HEIGHT) + def __str__(self): + return 'Tile %s:%s at %s' % (self.filename, self.tile_offset, + self.rect.topleft) + def update_image(self): self.image = load_spritesheet_frame(self.filename, self.tile_offset, - frame_size=(self.WIDTH, ? - ^^^^^^ + frame_size=self.rect.size) ? ^^^^^^^^^^ - self.HEIGHT)) assert self.image
de11b473a6134ed1403e91d55d30c23e6683a926
test/runner/versions.py
test/runner/versions.py
"""Show python and pip versions.""" import os import sys try: import pip except ImportError: pip = None print('.'.join(u'%s' % i for i in sys.version_info)) if pip: print('pip %s from %s' % (pip.__version__, os.path.dirname(pip.__file__)))
"""Show python and pip versions.""" import os import sys try: import pip except ImportError: pip = None print(sys.version) if pip: print('pip %s from %s' % (pip.__version__, os.path.dirname(pip.__file__)))
Revert "Relax ansible-test python version checking."
Revert "Relax ansible-test python version checking." This reverts commit d6cc3c41874b64e346639549fd18d8c41be0db8b.
Python
mit
thaim/ansible,thaim/ansible
"""Show python and pip versions.""" import os import sys try: import pip except ImportError: pip = None - print('.'.join(u'%s' % i for i in sys.version_info)) + print(sys.version) if pip: print('pip %s from %s' % (pip.__version__, os.path.dirname(pip.__file__)))
Revert "Relax ansible-test python version checking."
## Code Before: """Show python and pip versions.""" import os import sys try: import pip except ImportError: pip = None print('.'.join(u'%s' % i for i in sys.version_info)) if pip: print('pip %s from %s' % (pip.__version__, os.path.dirname(pip.__file__))) ## Instruction: Revert "Relax ansible-test python version checking." ## Code After: """Show python and pip versions.""" import os import sys try: import pip except ImportError: pip = None print(sys.version) if pip: print('pip %s from %s' % (pip.__version__, os.path.dirname(pip.__file__)))
"""Show python and pip versions.""" import os import sys try: import pip except ImportError: pip = None - print('.'.join(u'%s' % i for i in sys.version_info)) + print(sys.version) if pip: print('pip %s from %s' % (pip.__version__, os.path.dirname(pip.__file__)))
e7a8c76c1f8f07866a4b7ea55870dacb5c76ef90
face/tests/model_tests.py
face/tests/model_tests.py
from django.test import TestCase from functional_tests.factory import FaceFactory class Facetest(TestCase): def setUp(self): self.face = FaceFactory(title='Lokesh') def test_title_to_share_returns_meet_Lokesh__farmer_from_sivaganga_tamil_nadu(self): self.assertEqual(self.face.title_to_share,'Meet Lokesh, farmer from Sivaganga, Tamil Nadu') def test_featured_image_returnes_the_image(self): self.assertEqual(self.face.featured_image,self.face.image) def test_to_str_returns_lokesh_sivaganga(self): self.assertEqual(str(self.face),'Lokesh Sivaganga') def test_get_absolute_url_return_path_with_faces_s_face_page(self): self.assertEqual(self.face.get_absolute_url(),'/categories/faces/s/lokesh/')
from django.test import TestCase from functional_tests.factory import FaceFactory class Facetest(TestCase): def setUp(self): self.face = FaceFactory(title='Lokesh') def test_title_to_share_returns_meet_Lokesh__farmer_from_sivaganga_tamil_nadu(self): self.assertEqual(self.face.title_to_share,'Meet Lokesh, farmer from Sivaganga, Tamil Nadu') def test_featured_image_returnes_the_image(self): self.assertEqual(self.face.featured_image,self.face.image) def test_to_str_returns_lokesh_sivaganga(self): self.assertEqual(str(self.face),'Lokesh Sivaganga') def test_get_absolute_url_return_path_with_faces_s_face_page(self): self.assertRegexpMatches(self.face.get_absolute_url(),'/categories/faces/s/lokesh/?')
Fix unit test for seo faces url
Fix unit test for seo faces url
Python
bsd-3-clause
PARINetwork/pari,PARINetwork/pari,PARINetwork/pari,PARINetwork/pari
from django.test import TestCase from functional_tests.factory import FaceFactory class Facetest(TestCase): def setUp(self): self.face = FaceFactory(title='Lokesh') def test_title_to_share_returns_meet_Lokesh__farmer_from_sivaganga_tamil_nadu(self): self.assertEqual(self.face.title_to_share,'Meet Lokesh, farmer from Sivaganga, Tamil Nadu') def test_featured_image_returnes_the_image(self): self.assertEqual(self.face.featured_image,self.face.image) def test_to_str_returns_lokesh_sivaganga(self): self.assertEqual(str(self.face),'Lokesh Sivaganga') def test_get_absolute_url_return_path_with_faces_s_face_page(self): - self.assertEqual(self.face.get_absolute_url(),'/categories/faces/s/lokesh/') + self.assertRegexpMatches(self.face.get_absolute_url(),'/categories/faces/s/lokesh/?')
Fix unit test for seo faces url
## Code Before: from django.test import TestCase from functional_tests.factory import FaceFactory class Facetest(TestCase): def setUp(self): self.face = FaceFactory(title='Lokesh') def test_title_to_share_returns_meet_Lokesh__farmer_from_sivaganga_tamil_nadu(self): self.assertEqual(self.face.title_to_share,'Meet Lokesh, farmer from Sivaganga, Tamil Nadu') def test_featured_image_returnes_the_image(self): self.assertEqual(self.face.featured_image,self.face.image) def test_to_str_returns_lokesh_sivaganga(self): self.assertEqual(str(self.face),'Lokesh Sivaganga') def test_get_absolute_url_return_path_with_faces_s_face_page(self): self.assertEqual(self.face.get_absolute_url(),'/categories/faces/s/lokesh/') ## Instruction: Fix unit test for seo faces url ## Code After: from django.test import TestCase from functional_tests.factory import FaceFactory class Facetest(TestCase): def setUp(self): self.face = FaceFactory(title='Lokesh') def test_title_to_share_returns_meet_Lokesh__farmer_from_sivaganga_tamil_nadu(self): self.assertEqual(self.face.title_to_share,'Meet Lokesh, farmer from Sivaganga, Tamil Nadu') def test_featured_image_returnes_the_image(self): self.assertEqual(self.face.featured_image,self.face.image) def test_to_str_returns_lokesh_sivaganga(self): self.assertEqual(str(self.face),'Lokesh Sivaganga') def test_get_absolute_url_return_path_with_faces_s_face_page(self): self.assertRegexpMatches(self.face.get_absolute_url(),'/categories/faces/s/lokesh/?')
from django.test import TestCase from functional_tests.factory import FaceFactory class Facetest(TestCase): def setUp(self): self.face = FaceFactory(title='Lokesh') def test_title_to_share_returns_meet_Lokesh__farmer_from_sivaganga_tamil_nadu(self): self.assertEqual(self.face.title_to_share,'Meet Lokesh, farmer from Sivaganga, Tamil Nadu') def test_featured_image_returnes_the_image(self): self.assertEqual(self.face.featured_image,self.face.image) def test_to_str_returns_lokesh_sivaganga(self): self.assertEqual(str(self.face),'Lokesh Sivaganga') def test_get_absolute_url_return_path_with_faces_s_face_page(self): - self.assertEqual(self.face.get_absolute_url(),'/categories/faces/s/lokesh/') ? ^^^ ^ + self.assertRegexpMatches(self.face.get_absolute_url(),'/categories/faces/s/lokesh/?') ? ^^^^^^^ ^^^^^ +
838012c457d6c963707bb16259cd72d28c231672
cellcounter/accounts/decorators.py
cellcounter/accounts/decorators.py
__author__ = 'jvc26'
from functools import wraps from ratelimit.exceptions import Ratelimited from ratelimit.helpers import is_ratelimited def registration_ratelimit(ip=True, block=False, method=['POST'], field=None, rate='1/h', skip_if=None, keys=None): def decorator(fn): @wraps(fn) def _wrapped(request, *args, **kw): request.limited = getattr(request, 'limited', False) if skip_if is None or not skip_if(request): ratelimited = is_ratelimited(request=request, increment=False, ip=ip, method=method, field=field, rate=rate, keys=keys) if ratelimited and block: raise Ratelimited() return_val, success = fn(request, *args, **kw) if success: is_ratelimited(request=request, increment=True, ip=ip, method=method, field=field, rate=rate, keys=keys) return return_val return _wrapped return decorator
Use custom decorator to allow ratelimiting only on successful POST - prevents blocking form errors
Use custom decorator to allow ratelimiting only on successful POST - prevents blocking form errors
Python
mit
haematologic/cellcounter,cellcounter/cellcounter,cellcounter/cellcounter,haematologic/cellcounter,cellcounter/cellcounter,cellcounter/cellcounter,haematologic/cellcounter
- __author__ = 'jvc26' + from functools import wraps + from ratelimit.exceptions import Ratelimited + from ratelimit.helpers import is_ratelimited + + + def registration_ratelimit(ip=True, block=False, method=['POST'], field=None, rate='1/h', + skip_if=None, keys=None): + def decorator(fn): + @wraps(fn) + def _wrapped(request, *args, **kw): + request.limited = getattr(request, 'limited', False) + if skip_if is None or not skip_if(request): + ratelimited = is_ratelimited(request=request, increment=False, + ip=ip, method=method, field=field, + rate=rate, keys=keys) + if ratelimited and block: + raise Ratelimited() + return_val, success = fn(request, *args, **kw) + if success: + is_ratelimited(request=request, increment=True, ip=ip, + method=method, field=field, rate=rate, keys=keys) + return return_val + return _wrapped + return decorator
Use custom decorator to allow ratelimiting only on successful POST - prevents blocking form errors
## Code Before: __author__ = 'jvc26' ## Instruction: Use custom decorator to allow ratelimiting only on successful POST - prevents blocking form errors ## Code After: from functools import wraps from ratelimit.exceptions import Ratelimited from ratelimit.helpers import is_ratelimited def registration_ratelimit(ip=True, block=False, method=['POST'], field=None, rate='1/h', skip_if=None, keys=None): def decorator(fn): @wraps(fn) def _wrapped(request, *args, **kw): request.limited = getattr(request, 'limited', False) if skip_if is None or not skip_if(request): ratelimited = is_ratelimited(request=request, increment=False, ip=ip, method=method, field=field, rate=rate, keys=keys) if ratelimited and block: raise Ratelimited() return_val, success = fn(request, *args, **kw) if success: is_ratelimited(request=request, increment=True, ip=ip, method=method, field=field, rate=rate, keys=keys) return return_val return _wrapped return decorator
- __author__ = 'jvc26' + from functools import wraps + + from ratelimit.exceptions import Ratelimited + from ratelimit.helpers import is_ratelimited + + + def registration_ratelimit(ip=True, block=False, method=['POST'], field=None, rate='1/h', + skip_if=None, keys=None): + def decorator(fn): + @wraps(fn) + def _wrapped(request, *args, **kw): + request.limited = getattr(request, 'limited', False) + if skip_if is None or not skip_if(request): + ratelimited = is_ratelimited(request=request, increment=False, + ip=ip, method=method, field=field, + rate=rate, keys=keys) + if ratelimited and block: + raise Ratelimited() + return_val, success = fn(request, *args, **kw) + if success: + is_ratelimited(request=request, increment=True, ip=ip, + method=method, field=field, rate=rate, keys=keys) + return return_val + return _wrapped + return decorator
08d838e87bd92dacbbbfe31b19c628b9d3b271a8
src/plone.example/plone/example/todo.py
src/plone.example/plone/example/todo.py
from plone.dexterity.interfaces import IDexterityContent from plone.dexterity.interfaces import IFormFieldProvider from plone.server.api.service import Service from plone.supermodel import model from zope import schema from zope.component import adapter from zope.dublincore.annotatableadapter import ZDCAnnotatableAdapter from zope.dublincore.interfaces import IWriteZopeDublinCore from zope.interface import provider class ITodo(model.Schema): title = schema.TextLine( title=u"Title", required=False, description=u"It's a title", ) done = schema.Bool( title=u"Done", required=False, description=u"Has the task been completed?", ) class View(Service): def __init__(self, context, request): self.context = context self.request = request async def __call__(self): return { 'context': str(self.context), 'portal_type': self.context.portal_type, } @provider(IFormFieldProvider) class IDublinCore(IWriteZopeDublinCore): """ We basically just want the IFormFieldProvider interface applied There's probably a zcml way of doing this. """ @adapter(IDexterityContent) class DublinCore(ZDCAnnotatableAdapter): pass
from plone.dexterity.interfaces import IDexterityContent from plone.dexterity.interfaces import IFormFieldProvider from plone.server.api.service import Service from plone.supermodel import model from zope import schema from zope.component import adapter from zope.dublincore.annotatableadapter import ZDCAnnotatableAdapter from zope.dublincore.interfaces import IWriteZopeDublinCore from zope.interface import provider class ITodo(model.Schema): title = schema.TextLine( title=u"Title", required=False, description=u"It's a title", default=u'' ) done = schema.Bool( title=u"Done", required=False, description=u"Has the task been completed?", default=False ) class View(Service): def __init__(self, context, request): self.context = context self.request = request async def __call__(self): return { 'context': str(self.context), 'portal_type': self.context.portal_type, } @provider(IFormFieldProvider) class IDublinCore(IWriteZopeDublinCore): """ We basically just want the IFormFieldProvider interface applied There's probably a zcml way of doing this. """ @adapter(IDexterityContent) class DublinCore(ZDCAnnotatableAdapter): pass
Set default values for fields
Set default values for fields
Python
bsd-2-clause
plone/plone.server,plone/plone.server
from plone.dexterity.interfaces import IDexterityContent from plone.dexterity.interfaces import IFormFieldProvider from plone.server.api.service import Service from plone.supermodel import model from zope import schema from zope.component import adapter from zope.dublincore.annotatableadapter import ZDCAnnotatableAdapter from zope.dublincore.interfaces import IWriteZopeDublinCore from zope.interface import provider class ITodo(model.Schema): title = schema.TextLine( title=u"Title", required=False, description=u"It's a title", + default=u'' ) done = schema.Bool( title=u"Done", required=False, description=u"Has the task been completed?", + default=False ) class View(Service): def __init__(self, context, request): self.context = context self.request = request async def __call__(self): return { 'context': str(self.context), 'portal_type': self.context.portal_type, } @provider(IFormFieldProvider) class IDublinCore(IWriteZopeDublinCore): """ We basically just want the IFormFieldProvider interface applied There's probably a zcml way of doing this. """ @adapter(IDexterityContent) class DublinCore(ZDCAnnotatableAdapter): pass
Set default values for fields
## Code Before: from plone.dexterity.interfaces import IDexterityContent from plone.dexterity.interfaces import IFormFieldProvider from plone.server.api.service import Service from plone.supermodel import model from zope import schema from zope.component import adapter from zope.dublincore.annotatableadapter import ZDCAnnotatableAdapter from zope.dublincore.interfaces import IWriteZopeDublinCore from zope.interface import provider class ITodo(model.Schema): title = schema.TextLine( title=u"Title", required=False, description=u"It's a title", ) done = schema.Bool( title=u"Done", required=False, description=u"Has the task been completed?", ) class View(Service): def __init__(self, context, request): self.context = context self.request = request async def __call__(self): return { 'context': str(self.context), 'portal_type': self.context.portal_type, } @provider(IFormFieldProvider) class IDublinCore(IWriteZopeDublinCore): """ We basically just want the IFormFieldProvider interface applied There's probably a zcml way of doing this. """ @adapter(IDexterityContent) class DublinCore(ZDCAnnotatableAdapter): pass ## Instruction: Set default values for fields ## Code After: from plone.dexterity.interfaces import IDexterityContent from plone.dexterity.interfaces import IFormFieldProvider from plone.server.api.service import Service from plone.supermodel import model from zope import schema from zope.component import adapter from zope.dublincore.annotatableadapter import ZDCAnnotatableAdapter from zope.dublincore.interfaces import IWriteZopeDublinCore from zope.interface import provider class ITodo(model.Schema): title = schema.TextLine( title=u"Title", required=False, description=u"It's a title", default=u'' ) done = schema.Bool( title=u"Done", required=False, description=u"Has the task been completed?", default=False ) class View(Service): def __init__(self, context, request): self.context = context self.request = request async def __call__(self): return { 'context': str(self.context), 'portal_type': self.context.portal_type, } @provider(IFormFieldProvider) class IDublinCore(IWriteZopeDublinCore): """ We basically just want the IFormFieldProvider interface applied There's probably a zcml way of doing this. """ @adapter(IDexterityContent) class DublinCore(ZDCAnnotatableAdapter): pass
from plone.dexterity.interfaces import IDexterityContent from plone.dexterity.interfaces import IFormFieldProvider from plone.server.api.service import Service from plone.supermodel import model from zope import schema from zope.component import adapter from zope.dublincore.annotatableadapter import ZDCAnnotatableAdapter from zope.dublincore.interfaces import IWriteZopeDublinCore from zope.interface import provider class ITodo(model.Schema): title = schema.TextLine( title=u"Title", required=False, description=u"It's a title", + default=u'' ) done = schema.Bool( title=u"Done", required=False, description=u"Has the task been completed?", + default=False ) class View(Service): def __init__(self, context, request): self.context = context self.request = request async def __call__(self): return { 'context': str(self.context), 'portal_type': self.context.portal_type, } @provider(IFormFieldProvider) class IDublinCore(IWriteZopeDublinCore): """ We basically just want the IFormFieldProvider interface applied There's probably a zcml way of doing this. """ @adapter(IDexterityContent) class DublinCore(ZDCAnnotatableAdapter): pass
938043259eefdec21994489d68b1cf737618ba34
test/test_conversion.py
test/test_conversion.py
import unittest from src import conversion class TestNotationConverter(unittest.TestCase): """Tests for NotationConverter class""" def test_alg_search_good_input_a5(self): """Input with 'a5'""" actual_result = main.TileLine('w').line expected_result = ' ' self.assertEqual(actual_result, expected_result)
"""Tests for conversion module""" import unittest from src import conversion class TestNotationConverter(unittest.TestCase): """Tests for NotationConverter class""" def test_alg_search_good_input_a5(self): """Input with 'a5'""" n_con = conversion.NotationConverter() actual_result = n_con.alg_search('a5') expected_result = ('a5', 'qr5', 'qr4') self.assertEqual(actual_result, expected_result) def test_alg_search_good_input_f7(self): """Input with 'f7'""" n_con = conversion.NotationConverter() actual_result = n_con.alg_search('f7') expected_result = ('f7', 'kb7', 'kb2') self.assertEqual(actual_result, expected_result) def test_alg_search_nonexistant(self): """Input which does not exist""" n_con = conversion.NotationConverter() self.assertRaises(LookupError, n_con.alg_search, 'f99') def test_desc_search_good_white(self): """Input with good value""" n_con = conversion.NotationConverter() actual_result = n_con.desc_search('qn3', 'white') expected_result = ('b3', 'qn3', 'qn6') self.assertEqual(actual_result, expected_result) def test_desc_search_good_black(self): """Input with good value""" n_con = conversion.NotationConverter() actual_result = n_con.desc_search('qn6', 'black') expected_result = ('b3', 'qn3', 'qn6') self.assertEqual(actual_result, expected_result) def test_desc_search_nonexistant(self): """Input with good value""" n_con = conversion.NotationConverter() self.assertRaises(LookupError, n_con.desc_search, 'qn333', 'white')
Add tests for NotationConverter methods
Add tests for NotationConverter methods
Python
mit
blairck/chess_notation
+ """Tests for conversion module""" + import unittest from src import conversion class TestNotationConverter(unittest.TestCase): """Tests for NotationConverter class""" def test_alg_search_good_input_a5(self): """Input with 'a5'""" - actual_result = main.TileLine('w').line - expected_result = ' ' + n_con = conversion.NotationConverter() + actual_result = n_con.alg_search('a5') + expected_result = ('a5', 'qr5', 'qr4') self.assertEqual(actual_result, expected_result) + + def test_alg_search_good_input_f7(self): + """Input with 'f7'""" + n_con = conversion.NotationConverter() + actual_result = n_con.alg_search('f7') + expected_result = ('f7', 'kb7', 'kb2') + self.assertEqual(actual_result, expected_result) + + def test_alg_search_nonexistant(self): + """Input which does not exist""" + n_con = conversion.NotationConverter() + self.assertRaises(LookupError, n_con.alg_search, 'f99') + + def test_desc_search_good_white(self): + """Input with good value""" + n_con = conversion.NotationConverter() + actual_result = n_con.desc_search('qn3', 'white') + expected_result = ('b3', 'qn3', 'qn6') + self.assertEqual(actual_result, expected_result) + + def test_desc_search_good_black(self): + """Input with good value""" + n_con = conversion.NotationConverter() + actual_result = n_con.desc_search('qn6', 'black') + expected_result = ('b3', 'qn3', 'qn6') + self.assertEqual(actual_result, expected_result) + + def test_desc_search_nonexistant(self): + """Input with good value""" + n_con = conversion.NotationConverter() + self.assertRaises(LookupError, n_con.desc_search, 'qn333', 'white') +
Add tests for NotationConverter methods
## Code Before: import unittest from src import conversion class TestNotationConverter(unittest.TestCase): """Tests for NotationConverter class""" def test_alg_search_good_input_a5(self): """Input with 'a5'""" actual_result = main.TileLine('w').line expected_result = ' ' self.assertEqual(actual_result, expected_result) ## Instruction: Add tests for NotationConverter methods ## Code After: """Tests for conversion module""" import unittest from src import conversion class TestNotationConverter(unittest.TestCase): """Tests for NotationConverter class""" def test_alg_search_good_input_a5(self): """Input with 'a5'""" n_con = conversion.NotationConverter() actual_result = n_con.alg_search('a5') expected_result = ('a5', 'qr5', 'qr4') self.assertEqual(actual_result, expected_result) def test_alg_search_good_input_f7(self): """Input with 'f7'""" n_con = conversion.NotationConverter() actual_result = n_con.alg_search('f7') expected_result = ('f7', 'kb7', 'kb2') self.assertEqual(actual_result, expected_result) def test_alg_search_nonexistant(self): """Input which does not exist""" n_con = conversion.NotationConverter() self.assertRaises(LookupError, n_con.alg_search, 'f99') def test_desc_search_good_white(self): """Input with good value""" n_con = conversion.NotationConverter() actual_result = n_con.desc_search('qn3', 'white') expected_result = ('b3', 'qn3', 'qn6') self.assertEqual(actual_result, expected_result) def test_desc_search_good_black(self): """Input with good value""" n_con = conversion.NotationConverter() actual_result = n_con.desc_search('qn6', 'black') expected_result = ('b3', 'qn3', 'qn6') self.assertEqual(actual_result, expected_result) def test_desc_search_nonexistant(self): """Input with good value""" n_con = conversion.NotationConverter() self.assertRaises(LookupError, n_con.desc_search, 'qn333', 'white')
+ """Tests for conversion module""" + import unittest from src import conversion class TestNotationConverter(unittest.TestCase): """Tests for NotationConverter class""" def test_alg_search_good_input_a5(self): """Input with 'a5'""" - actual_result = main.TileLine('w').line - expected_result = ' ' + n_con = conversion.NotationConverter() + actual_result = n_con.alg_search('a5') + expected_result = ('a5', 'qr5', 'qr4') self.assertEqual(actual_result, expected_result) + + def test_alg_search_good_input_f7(self): + """Input with 'f7'""" + n_con = conversion.NotationConverter() + actual_result = n_con.alg_search('f7') + expected_result = ('f7', 'kb7', 'kb2') + self.assertEqual(actual_result, expected_result) + + def test_alg_search_nonexistant(self): + """Input which does not exist""" + n_con = conversion.NotationConverter() + self.assertRaises(LookupError, n_con.alg_search, 'f99') + + def test_desc_search_good_white(self): + """Input with good value""" + n_con = conversion.NotationConverter() + actual_result = n_con.desc_search('qn3', 'white') + expected_result = ('b3', 'qn3', 'qn6') + self.assertEqual(actual_result, expected_result) + + def test_desc_search_good_black(self): + """Input with good value""" + n_con = conversion.NotationConverter() + actual_result = n_con.desc_search('qn6', 'black') + expected_result = ('b3', 'qn3', 'qn6') + self.assertEqual(actual_result, expected_result) + + def test_desc_search_nonexistant(self): + """Input with good value""" + n_con = conversion.NotationConverter() + self.assertRaises(LookupError, n_con.desc_search, 'qn333', 'white')
a95f6806ab4e591cfb404624631306932fd69e85
ninja/__init__.py
ninja/__init__.py
import os import platform import subprocess import sys from ._version import get_versions __version__ = get_versions()['version'] del get_versions DATA = os.path.join(os.path.dirname(__file__), 'data') # Support running tests from the source tree if not os.path.exists(DATA): _data = os.path.abspath(os.path.join( os.path.dirname(__file__), '../_skbuild/cmake-install/ninja/data')) if os.path.exists(_data): DATA = _data if platform.system().lower() == "darwin": DATA = os.path.join(DATA, 'CMake.app', 'Contents') BIN_DIR = os.path.join(DATA, 'bin') def _program(name, args): return subprocess.call([os.path.join(BIN_DIR, name)] + args) def ninja(): raise SystemExit(_program('ninja', sys.argv[1:]))
import os import platform import subprocess import sys from ._version import get_versions __version__ = get_versions()['version'] del get_versions DATA = os.path.join(os.path.dirname(__file__), 'data') # Support running tests from the source tree if not os.path.exists(DATA): _data = os.path.abspath(os.path.join( os.path.dirname(__file__), '../_skbuild/cmake-install/ninja/data')) if os.path.exists(_data): DATA = _data BIN_DIR = os.path.join(DATA, 'bin') def _program(name, args): return subprocess.call([os.path.join(BIN_DIR, name)] + args) def ninja(): raise SystemExit(_program('ninja', sys.argv[1:]))
Fix lookup of ninja executable on MacOSX
ninja: Fix lookup of ninja executable on MacOSX
Python
apache-2.0
scikit-build/ninja-python-distributions
import os import platform import subprocess import sys from ._version import get_versions __version__ = get_versions()['version'] del get_versions DATA = os.path.join(os.path.dirname(__file__), 'data') # Support running tests from the source tree if not os.path.exists(DATA): _data = os.path.abspath(os.path.join( os.path.dirname(__file__), '../_skbuild/cmake-install/ninja/data')) if os.path.exists(_data): DATA = _data - if platform.system().lower() == "darwin": - DATA = os.path.join(DATA, 'CMake.app', 'Contents') - BIN_DIR = os.path.join(DATA, 'bin') def _program(name, args): return subprocess.call([os.path.join(BIN_DIR, name)] + args) def ninja(): raise SystemExit(_program('ninja', sys.argv[1:]))
Fix lookup of ninja executable on MacOSX
## Code Before: import os import platform import subprocess import sys from ._version import get_versions __version__ = get_versions()['version'] del get_versions DATA = os.path.join(os.path.dirname(__file__), 'data') # Support running tests from the source tree if not os.path.exists(DATA): _data = os.path.abspath(os.path.join( os.path.dirname(__file__), '../_skbuild/cmake-install/ninja/data')) if os.path.exists(_data): DATA = _data if platform.system().lower() == "darwin": DATA = os.path.join(DATA, 'CMake.app', 'Contents') BIN_DIR = os.path.join(DATA, 'bin') def _program(name, args): return subprocess.call([os.path.join(BIN_DIR, name)] + args) def ninja(): raise SystemExit(_program('ninja', sys.argv[1:])) ## Instruction: Fix lookup of ninja executable on MacOSX ## Code After: import os import platform import subprocess import sys from ._version import get_versions __version__ = get_versions()['version'] del get_versions DATA = os.path.join(os.path.dirname(__file__), 'data') # Support running tests from the source tree if not os.path.exists(DATA): _data = os.path.abspath(os.path.join( os.path.dirname(__file__), '../_skbuild/cmake-install/ninja/data')) if os.path.exists(_data): DATA = _data BIN_DIR = os.path.join(DATA, 'bin') def _program(name, args): return subprocess.call([os.path.join(BIN_DIR, name)] + args) def ninja(): raise SystemExit(_program('ninja', sys.argv[1:]))
import os import platform import subprocess import sys from ._version import get_versions __version__ = get_versions()['version'] del get_versions DATA = os.path.join(os.path.dirname(__file__), 'data') # Support running tests from the source tree if not os.path.exists(DATA): _data = os.path.abspath(os.path.join( os.path.dirname(__file__), '../_skbuild/cmake-install/ninja/data')) if os.path.exists(_data): DATA = _data - if platform.system().lower() == "darwin": - DATA = os.path.join(DATA, 'CMake.app', 'Contents') - BIN_DIR = os.path.join(DATA, 'bin') def _program(name, args): return subprocess.call([os.path.join(BIN_DIR, name)] + args) def ninja(): raise SystemExit(_program('ninja', sys.argv[1:]))
cf8f3dc4d2cde04a1f822627db522c1b021c3359
dataset/__init__.py
dataset/__init__.py
import warnings warnings.filterwarnings( 'ignore', 'Unicode type received non-unicode bind param value.') from dataset.persistence.database import Database from dataset.persistence.table import Table from dataset.freeze.app import freeze __all__ = ['Database', 'Table', 'freeze', 'connect'] def connect(url, reflectMetadata=True): """ Opens a new connection to a database. *url* can be any valid `SQLAlchemy engine URL`_. Returns an instance of :py:class:`Database <dataset.Database>`. Set *reflectMetadata* to False if you don't want the entire database schema to be pre-loaded. This significantly speeds up connecting to large databases with lots of tables. :: db = dataset.connect('sqlite:///factbook.db') .. _SQLAlchemy Engine URL: http://docs.sqlalchemy.org/en/latest/core/engines.html#sqlalchemy.create_engine """ return Database(url, reflectMetadata)
import os # shut up useless SA warning: import warnings warnings.filterwarnings( 'ignore', 'Unicode type received non-unicode bind param value.') from dataset.persistence.database import Database from dataset.persistence.table import Table from dataset.freeze.app import freeze __all__ = ['Database', 'Table', 'freeze', 'connect'] def connect(url=None, reflectMetadata=True): """ Opens a new connection to a database. *url* can be any valid `SQLAlchemy engine URL`_. If *url* is not defined it will try to use *DATABASE_URL* from environment variable. Returns an instance of :py:class:`Database <dataset.Database>`. Set *reflectMetadata* to False if you don't want the entire database schema to be pre-loaded. This significantly speeds up connecting to large databases with lots of tables. :: db = dataset.connect('sqlite:///factbook.db') .. _SQLAlchemy Engine URL: http://docs.sqlalchemy.org/en/latest/core/engines.html#sqlalchemy.create_engine """ url = os.environ.get('DATABASE_URL', url) return Database(url, reflectMetadata)
Allow to use `url` defined as env variable.
Allow to use `url` defined as env variable.
Python
mit
pudo/dataset,askebos/dataset,twds/dataset,vguzmanp/dataset,stefanw/dataset,saimn/dataset,reubano/dataset
+ import os + # shut up useless SA warning: import warnings warnings.filterwarnings( 'ignore', 'Unicode type received non-unicode bind param value.') from dataset.persistence.database import Database from dataset.persistence.table import Table from dataset.freeze.app import freeze __all__ = ['Database', 'Table', 'freeze', 'connect'] - def connect(url, reflectMetadata=True): + def connect(url=None, reflectMetadata=True): """ - Opens a new connection to a database. *url* can be any valid `SQLAlchemy engine URL`_. Returns + Opens a new connection to a database. *url* can be any valid `SQLAlchemy engine URL`_. + If *url* is not defined it will try to use *DATABASE_URL* from environment variable. - an instance of :py:class:`Database <dataset.Database>`. Set *reflectMetadata* to False if you + Returns an instance of :py:class:`Database <dataset.Database>`. Set *reflectMetadata* to False if you don't want the entire database schema to be pre-loaded. This significantly speeds up connecting to large databases with lots of tables. :: db = dataset.connect('sqlite:///factbook.db') .. _SQLAlchemy Engine URL: http://docs.sqlalchemy.org/en/latest/core/engines.html#sqlalchemy.create_engine """ + url = os.environ.get('DATABASE_URL', url) return Database(url, reflectMetadata)
Allow to use `url` defined as env variable.
## Code Before: import warnings warnings.filterwarnings( 'ignore', 'Unicode type received non-unicode bind param value.') from dataset.persistence.database import Database from dataset.persistence.table import Table from dataset.freeze.app import freeze __all__ = ['Database', 'Table', 'freeze', 'connect'] def connect(url, reflectMetadata=True): """ Opens a new connection to a database. *url* can be any valid `SQLAlchemy engine URL`_. Returns an instance of :py:class:`Database <dataset.Database>`. Set *reflectMetadata* to False if you don't want the entire database schema to be pre-loaded. This significantly speeds up connecting to large databases with lots of tables. :: db = dataset.connect('sqlite:///factbook.db') .. _SQLAlchemy Engine URL: http://docs.sqlalchemy.org/en/latest/core/engines.html#sqlalchemy.create_engine """ return Database(url, reflectMetadata) ## Instruction: Allow to use `url` defined as env variable. ## Code After: import os # shut up useless SA warning: import warnings warnings.filterwarnings( 'ignore', 'Unicode type received non-unicode bind param value.') from dataset.persistence.database import Database from dataset.persistence.table import Table from dataset.freeze.app import freeze __all__ = ['Database', 'Table', 'freeze', 'connect'] def connect(url=None, reflectMetadata=True): """ Opens a new connection to a database. *url* can be any valid `SQLAlchemy engine URL`_. If *url* is not defined it will try to use *DATABASE_URL* from environment variable. Returns an instance of :py:class:`Database <dataset.Database>`. Set *reflectMetadata* to False if you don't want the entire database schema to be pre-loaded. This significantly speeds up connecting to large databases with lots of tables. :: db = dataset.connect('sqlite:///factbook.db') .. _SQLAlchemy Engine URL: http://docs.sqlalchemy.org/en/latest/core/engines.html#sqlalchemy.create_engine """ url = os.environ.get('DATABASE_URL', url) return Database(url, reflectMetadata)
+ import os + # shut up useless SA warning: import warnings warnings.filterwarnings( 'ignore', 'Unicode type received non-unicode bind param value.') from dataset.persistence.database import Database from dataset.persistence.table import Table from dataset.freeze.app import freeze __all__ = ['Database', 'Table', 'freeze', 'connect'] - def connect(url, reflectMetadata=True): + def connect(url=None, reflectMetadata=True): ? +++++ """ - Opens a new connection to a database. *url* can be any valid `SQLAlchemy engine URL`_. Returns ? -------- + Opens a new connection to a database. *url* can be any valid `SQLAlchemy engine URL`_. + If *url* is not defined it will try to use *DATABASE_URL* from environment variable. - an instance of :py:class:`Database <dataset.Database>`. Set *reflectMetadata* to False if you + Returns an instance of :py:class:`Database <dataset.Database>`. Set *reflectMetadata* to False if you ? ++++++++ don't want the entire database schema to be pre-loaded. This significantly speeds up connecting to large databases with lots of tables. :: db = dataset.connect('sqlite:///factbook.db') .. _SQLAlchemy Engine URL: http://docs.sqlalchemy.org/en/latest/core/engines.html#sqlalchemy.create_engine """ + url = os.environ.get('DATABASE_URL', url) return Database(url, reflectMetadata)
970d296cd4344fbbde28552dbf2aa5fbbb329c9d
gh_user_download.py
gh_user_download.py
from __future__ import print_function import os from pygithub3 import Github from docopt import docopt def main(): arguments = docopt(__doc__, version="testing") who = arguments['<who>'] where = arguments['<where>'] gh = Github() repos = gh.repos.list(who).all() for repo in repos: url = repo.git_url print(url, 'to', os.path.join(where, repo.name)) os.system('git clone ' + url + ' ' + os.path.join(where, repo.name)) if __name__ == '__main__': main()
from __future__ import print_function import os from pygithub3 import Github from docopt import docopt def main(): arguments = docopt(__doc__, version="1.0") who = arguments['<who>'] where = arguments['<where>'] ssh = arguments['--ssh'] gh = Github() repos = gh.repos.list(who).all() for repo in repos: if ssh: url = 'git@github.com:' + who + '/' + repo.name else: url = repo.git_url path = os.path.join(where, repo.name) print(url, 'to', path) os.system('git clone ' + url + ' ' + path) if __name__ == '__main__': main()
Add option to download via SSH
Add option to download via SSH
Python
mit
JackMc/git_tools
from __future__ import print_function import os from pygithub3 import Github from docopt import docopt def main(): - arguments = docopt(__doc__, version="testing") + arguments = docopt(__doc__, version="1.0") who = arguments['<who>'] where = arguments['<where>'] + ssh = arguments['--ssh'] gh = Github() repos = gh.repos.list(who).all() for repo in repos: + if ssh: + url = 'git@github.com:' + who + '/' + repo.name + else: - url = repo.git_url + url = repo.git_url - print(url, 'to', os.path.join(where, repo.name)) + path = os.path.join(where, repo.name) + print(url, 'to', path) - os.system('git clone ' + url + ' ' + os.path.join(where, repo.name)) + os.system('git clone ' + url + ' ' + path) if __name__ == '__main__': main()
Add option to download via SSH
## Code Before: from __future__ import print_function import os from pygithub3 import Github from docopt import docopt def main(): arguments = docopt(__doc__, version="testing") who = arguments['<who>'] where = arguments['<where>'] gh = Github() repos = gh.repos.list(who).all() for repo in repos: url = repo.git_url print(url, 'to', os.path.join(where, repo.name)) os.system('git clone ' + url + ' ' + os.path.join(where, repo.name)) if __name__ == '__main__': main() ## Instruction: Add option to download via SSH ## Code After: from __future__ import print_function import os from pygithub3 import Github from docopt import docopt def main(): arguments = docopt(__doc__, version="1.0") who = arguments['<who>'] where = arguments['<where>'] ssh = arguments['--ssh'] gh = Github() repos = gh.repos.list(who).all() for repo in repos: if ssh: url = 'git@github.com:' + who + '/' + repo.name else: url = repo.git_url path = os.path.join(where, repo.name) print(url, 'to', path) os.system('git clone ' + url + ' ' + path) if __name__ == '__main__': main()
from __future__ import print_function import os from pygithub3 import Github from docopt import docopt def main(): - arguments = docopt(__doc__, version="testing") ? ^^^^^^^ + arguments = docopt(__doc__, version="1.0") ? ^^^ who = arguments['<who>'] where = arguments['<where>'] + ssh = arguments['--ssh'] gh = Github() repos = gh.repos.list(who).all() for repo in repos: + if ssh: + url = 'git@github.com:' + who + '/' + repo.name + else: - url = repo.git_url + url = repo.git_url ? ++++ - print(url, 'to', os.path.join(where, repo.name)) ? ^^^ ^^^^^ ^^^^^ - + path = os.path.join(where, repo.name) ? ^ ^ ^ + print(url, 'to', path) - os.system('git clone ' + url + ' ' + os.path.join(where, repo.name)) ? --- ---------------------- - + os.system('git clone ' + url + ' ' + path) if __name__ == '__main__': main()
1f59870fd321be570ce6cfead96307fcc3366e09
d1lod/tests/test_sesame_interface.py
d1lod/tests/test_sesame_interface.py
import pytest from d1lod.sesame import Store, Repository, Interface from d1lod import dataone def test_interface_can_be_created(interface): assert isinstance(interface, Interface)
import pytest from d1lod.sesame import Store, Repository, Interface from d1lod import dataone def test_interface_can_be_created(interface): assert isinstance(interface, Interface) def test_can_add_a_dataset(): """Test whether the right triples are added when we add a known dataset. We pass the store to this test because we'll need to specify namespaces. """ namespaces = { 'owl': 'http://www.w3.org/2002/07/owl#', 'rdfs': 'http://www.w3.org/2000/01/rdf-schema#', 'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'xsd': 'http://www.w3.org/2001/XMLSchema#', 'foaf': 'http://xmlns.com/foaf/0.1/', 'dcterms': 'http://purl.org/dc/terms/', 'datacite': 'http://purl.org/spar/datacite/', 'glbase': 'http://schema.geolink.org/', 'd1dataset': 'http://lod.dataone.org/dataset/', 'd1person': 'http://lod.dataone.org/person/', 'd1org': 'http://lod.dataone.org/organization/', 'd1node': 'https://cn.dataone.org/cn/v1/node/', 'd1landing': 'https://search.dataone.org/#view/' } store = Store('localhost', 8080) repo = Repository(store, 'test', ns = namespaces) interface = Interface(repo) repo.clear() identifier = 'doi:10.6073/AA/knb-lter-cdr.70061.123' doc = dataone.getSolrIndexFields(identifier) interface.addDataset(doc) assert interface.repository.size() == 20
Add repository test for adding a dataset
Add repository test for adding a dataset
Python
apache-2.0
ec-geolink/d1lod,ec-geolink/d1lod,ec-geolink/d1lod,ec-geolink/d1lod
import pytest from d1lod.sesame import Store, Repository, Interface from d1lod import dataone def test_interface_can_be_created(interface): assert isinstance(interface, Interface) + + def test_can_add_a_dataset(): + """Test whether the right triples are added when we add a known dataset. + + We pass the store to this test because we'll need to specify namespaces. + """ + namespaces = { + 'owl': 'http://www.w3.org/2002/07/owl#', + 'rdfs': 'http://www.w3.org/2000/01/rdf-schema#', + 'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', + 'xsd': 'http://www.w3.org/2001/XMLSchema#', + 'foaf': 'http://xmlns.com/foaf/0.1/', + 'dcterms': 'http://purl.org/dc/terms/', + 'datacite': 'http://purl.org/spar/datacite/', + 'glbase': 'http://schema.geolink.org/', + 'd1dataset': 'http://lod.dataone.org/dataset/', + 'd1person': 'http://lod.dataone.org/person/', + 'd1org': 'http://lod.dataone.org/organization/', + 'd1node': 'https://cn.dataone.org/cn/v1/node/', + 'd1landing': 'https://search.dataone.org/#view/' + } + + store = Store('localhost', 8080) + repo = Repository(store, 'test', ns = namespaces) + interface = Interface(repo) + + + repo.clear() + + identifier = 'doi:10.6073/AA/knb-lter-cdr.70061.123' + doc = dataone.getSolrIndexFields(identifier) + + interface.addDataset(doc) + + assert interface.repository.size() == 20 +
Add repository test for adding a dataset
## Code Before: import pytest from d1lod.sesame import Store, Repository, Interface from d1lod import dataone def test_interface_can_be_created(interface): assert isinstance(interface, Interface) ## Instruction: Add repository test for adding a dataset ## Code After: import pytest from d1lod.sesame import Store, Repository, Interface from d1lod import dataone def test_interface_can_be_created(interface): assert isinstance(interface, Interface) def test_can_add_a_dataset(): """Test whether the right triples are added when we add a known dataset. We pass the store to this test because we'll need to specify namespaces. """ namespaces = { 'owl': 'http://www.w3.org/2002/07/owl#', 'rdfs': 'http://www.w3.org/2000/01/rdf-schema#', 'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'xsd': 'http://www.w3.org/2001/XMLSchema#', 'foaf': 'http://xmlns.com/foaf/0.1/', 'dcterms': 'http://purl.org/dc/terms/', 'datacite': 'http://purl.org/spar/datacite/', 'glbase': 'http://schema.geolink.org/', 'd1dataset': 'http://lod.dataone.org/dataset/', 'd1person': 'http://lod.dataone.org/person/', 'd1org': 'http://lod.dataone.org/organization/', 'd1node': 'https://cn.dataone.org/cn/v1/node/', 'd1landing': 'https://search.dataone.org/#view/' } store = Store('localhost', 8080) repo = Repository(store, 'test', ns = namespaces) interface = Interface(repo) repo.clear() identifier = 'doi:10.6073/AA/knb-lter-cdr.70061.123' doc = dataone.getSolrIndexFields(identifier) interface.addDataset(doc) assert interface.repository.size() == 20
import pytest from d1lod.sesame import Store, Repository, Interface from d1lod import dataone def test_interface_can_be_created(interface): assert isinstance(interface, Interface) + + + def test_can_add_a_dataset(): + """Test whether the right triples are added when we add a known dataset. + + We pass the store to this test because we'll need to specify namespaces. + """ + namespaces = { + 'owl': 'http://www.w3.org/2002/07/owl#', + 'rdfs': 'http://www.w3.org/2000/01/rdf-schema#', + 'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', + 'xsd': 'http://www.w3.org/2001/XMLSchema#', + 'foaf': 'http://xmlns.com/foaf/0.1/', + 'dcterms': 'http://purl.org/dc/terms/', + 'datacite': 'http://purl.org/spar/datacite/', + 'glbase': 'http://schema.geolink.org/', + 'd1dataset': 'http://lod.dataone.org/dataset/', + 'd1person': 'http://lod.dataone.org/person/', + 'd1org': 'http://lod.dataone.org/organization/', + 'd1node': 'https://cn.dataone.org/cn/v1/node/', + 'd1landing': 'https://search.dataone.org/#view/' + } + + store = Store('localhost', 8080) + repo = Repository(store, 'test', ns = namespaces) + interface = Interface(repo) + + + repo.clear() + + identifier = 'doi:10.6073/AA/knb-lter-cdr.70061.123' + doc = dataone.getSolrIndexFields(identifier) + + interface.addDataset(doc) + + assert interface.repository.size() == 20
417415283d87654b066c11d807516d3cd5b5bf3d
tests/test_probabilistic_interleave_speed.py
tests/test_probabilistic_interleave_speed.py
import interleaving as il import numpy as np import pytest np.random.seed(0) from .test_methods import TestMethods class TestProbabilisticInterleaveSpeed(TestMethods): def test_interleave(self): r1 = list(range(100)) r2 = list(range(100, 200)) for i in range(1000): method = il.Probabilistic([r1, r2]) ranking = method.interleave() print(list(ranking))
import interleaving as il import numpy as np import pytest np.random.seed(0) from .test_methods import TestMethods class TestProbabilisticInterleaveSpeed(TestMethods): def test_interleave(self): r1 = list(range(100)) r2 = list(range(50, 150)) r3 = list(range(100, 200)) r4 = list(range(150, 250)) for i in range(1000): method = il.Probabilistic([r1, r2, r3, r4]) ranking = method.interleave() method.evaluate(ranking, [0, 1, 2])
Add tests for measuring the speed of probabilistic interleaving
Add tests for measuring the speed of probabilistic interleaving
Python
mit
mpkato/interleaving
import interleaving as il import numpy as np import pytest np.random.seed(0) from .test_methods import TestMethods class TestProbabilisticInterleaveSpeed(TestMethods): def test_interleave(self): r1 = list(range(100)) + r2 = list(range(50, 150)) - r2 = list(range(100, 200)) + r3 = list(range(100, 200)) + r4 = list(range(150, 250)) for i in range(1000): - method = il.Probabilistic([r1, r2]) + method = il.Probabilistic([r1, r2, r3, r4]) ranking = method.interleave() - print(list(ranking)) + method.evaluate(ranking, [0, 1, 2])
Add tests for measuring the speed of probabilistic interleaving
## Code Before: import interleaving as il import numpy as np import pytest np.random.seed(0) from .test_methods import TestMethods class TestProbabilisticInterleaveSpeed(TestMethods): def test_interleave(self): r1 = list(range(100)) r2 = list(range(100, 200)) for i in range(1000): method = il.Probabilistic([r1, r2]) ranking = method.interleave() print(list(ranking)) ## Instruction: Add tests for measuring the speed of probabilistic interleaving ## Code After: import interleaving as il import numpy as np import pytest np.random.seed(0) from .test_methods import TestMethods class TestProbabilisticInterleaveSpeed(TestMethods): def test_interleave(self): r1 = list(range(100)) r2 = list(range(50, 150)) r3 = list(range(100, 200)) r4 = list(range(150, 250)) for i in range(1000): method = il.Probabilistic([r1, r2, r3, r4]) ranking = method.interleave() method.evaluate(ranking, [0, 1, 2])
import interleaving as il import numpy as np import pytest np.random.seed(0) from .test_methods import TestMethods class TestProbabilisticInterleaveSpeed(TestMethods): def test_interleave(self): r1 = list(range(100)) + r2 = list(range(50, 150)) - r2 = list(range(100, 200)) ? ^ + r3 = list(range(100, 200)) ? ^ + r4 = list(range(150, 250)) for i in range(1000): - method = il.Probabilistic([r1, r2]) + method = il.Probabilistic([r1, r2, r3, r4]) ? ++++++++ ranking = method.interleave() - print(list(ranking)) + method.evaluate(ranking, [0, 1, 2])
86f6191867141d7a7a165b227255d7b4406eb4f4
accounts/utils.py
accounts/utils.py
from django.core.exceptions import ObjectDoesNotExist def get_user_city(user): """Return the user's city. If unavailable, return an empty string.""" # If the profile is absent (i.e. superuser), return None. try: city = user.common_profile.city except ObjectDoesNotExist: city = '' return city def get_user_gender(user): """Return the user's city. If unavailable, return an empty string.""" # If either the profile (i.e. superuser) or the college # (i.e. non-student) are absent, return an empty string. try: gender = user.common_profile.college.gender except (ObjectDoesNotExist, AttributeError): gender = '' return gender
from django.core.exceptions import ObjectDoesNotExist def get_user_city(user): """Return the user's city. If unavailable, return an empty string.""" # If the profile is absent (i.e. superuser), return None. try: city = user.common_profile.city except (ObjectDoesNotExist, AttributeError): city = '' return city def get_user_gender(user): """Return the user's city. If unavailable, return an empty string.""" # If either the profile (i.e. superuser) or the college # (i.e. non-student) are absent, return an empty string. try: gender = user.common_profile.college.gender except (ObjectDoesNotExist, AttributeError): gender = '' return gender
Fix crash on non-logged in users.
Fix crash on non-logged in users.
Python
agpl-3.0
osamak/student-portal,osamak/student-portal,osamak/student-portal,osamak/student-portal,enjaz/enjaz,enjaz/enjaz,enjaz/enjaz,enjaz/enjaz,osamak/student-portal,enjaz/enjaz
from django.core.exceptions import ObjectDoesNotExist def get_user_city(user): """Return the user's city. If unavailable, return an empty string.""" # If the profile is absent (i.e. superuser), return None. try: city = user.common_profile.city - except ObjectDoesNotExist: + except (ObjectDoesNotExist, AttributeError): city = '' return city def get_user_gender(user): """Return the user's city. If unavailable, return an empty string.""" # If either the profile (i.e. superuser) or the college # (i.e. non-student) are absent, return an empty string. try: gender = user.common_profile.college.gender except (ObjectDoesNotExist, AttributeError): gender = '' return gender
Fix crash on non-logged in users.
## Code Before: from django.core.exceptions import ObjectDoesNotExist def get_user_city(user): """Return the user's city. If unavailable, return an empty string.""" # If the profile is absent (i.e. superuser), return None. try: city = user.common_profile.city except ObjectDoesNotExist: city = '' return city def get_user_gender(user): """Return the user's city. If unavailable, return an empty string.""" # If either the profile (i.e. superuser) or the college # (i.e. non-student) are absent, return an empty string. try: gender = user.common_profile.college.gender except (ObjectDoesNotExist, AttributeError): gender = '' return gender ## Instruction: Fix crash on non-logged in users. ## Code After: from django.core.exceptions import ObjectDoesNotExist def get_user_city(user): """Return the user's city. If unavailable, return an empty string.""" # If the profile is absent (i.e. superuser), return None. try: city = user.common_profile.city except (ObjectDoesNotExist, AttributeError): city = '' return city def get_user_gender(user): """Return the user's city. If unavailable, return an empty string.""" # If either the profile (i.e. superuser) or the college # (i.e. non-student) are absent, return an empty string. try: gender = user.common_profile.college.gender except (ObjectDoesNotExist, AttributeError): gender = '' return gender
from django.core.exceptions import ObjectDoesNotExist def get_user_city(user): """Return the user's city. If unavailable, return an empty string.""" # If the profile is absent (i.e. superuser), return None. try: city = user.common_profile.city - except ObjectDoesNotExist: + except (ObjectDoesNotExist, AttributeError): ? + +++++++++++++++++ city = '' return city def get_user_gender(user): """Return the user's city. If unavailable, return an empty string.""" # If either the profile (i.e. superuser) or the college # (i.e. non-student) are absent, return an empty string. try: gender = user.common_profile.college.gender except (ObjectDoesNotExist, AttributeError): gender = '' return gender
a6300723150d7d1ff9a58f4f3f1297e0fe2c6f78
css_updater/git/manager.py
css_updater/git/manager.py
"""manages github repos""" import os import tempfile from typing import Dict, Any import pygit2 as git from .webhook.handler import Handler class Manager(object): """handles git repos""" def __init__(self: Manager, handler: Handler) -> None: self.webhook_handler: Handler = handler self.temp_dir: tempfile.TemporaryDirectory = tempfile.TemporaryDirectory() self.repo: git.Repository = git.clone_repository( self.webhook_handler.git_url, path=self.temp_dir.name) with open(os.path.join(self.temp_dir.name, "css-updater.json")) as config: import json self.config: Dict[str, Any] = json.loads(config.read()) def __del__(self: Manager) -> None: self.temp_dir.cleanup()
"""manages github repos""" import os import tempfile from typing import Dict, Any import pygit2 as git from .webhook.handler import Handler class Manager(object): """handles git repos""" def __init__(self: Manager, handler: Handler) -> None: self.webhook_handler: Handler = handler self.temp_dir: tempfile.TemporaryDirectory = tempfile.TemporaryDirectory() self.repo: git.Repository = git.clone_repository( self.webhook_handler.git_url, path=self.temp_dir.name) with open(os.path.join(self.temp_dir.name, "css-updater.json")) as config: import json try: self.config: Dict[str, Any] = json.loads(config.read())["css_updater"] except KeyError as invalid_json: print(invalid_json) except IOError as io_error: print(io_error) def __del__(self: Manager) -> None: self.temp_dir.cleanup()
Check for errors in config
Check for errors in config
Python
mit
neoliberal/css-updater
"""manages github repos""" import os import tempfile from typing import Dict, Any import pygit2 as git from .webhook.handler import Handler class Manager(object): """handles git repos""" def __init__(self: Manager, handler: Handler) -> None: self.webhook_handler: Handler = handler self.temp_dir: tempfile.TemporaryDirectory = tempfile.TemporaryDirectory() self.repo: git.Repository = git.clone_repository( self.webhook_handler.git_url, path=self.temp_dir.name) with open(os.path.join(self.temp_dir.name, "css-updater.json")) as config: import json + try: - self.config: Dict[str, Any] = json.loads(config.read()) + self.config: Dict[str, Any] = json.loads(config.read())["css_updater"] + except KeyError as invalid_json: + print(invalid_json) + except IOError as io_error: + print(io_error) def __del__(self: Manager) -> None: self.temp_dir.cleanup()
Check for errors in config
## Code Before: """manages github repos""" import os import tempfile from typing import Dict, Any import pygit2 as git from .webhook.handler import Handler class Manager(object): """handles git repos""" def __init__(self: Manager, handler: Handler) -> None: self.webhook_handler: Handler = handler self.temp_dir: tempfile.TemporaryDirectory = tempfile.TemporaryDirectory() self.repo: git.Repository = git.clone_repository( self.webhook_handler.git_url, path=self.temp_dir.name) with open(os.path.join(self.temp_dir.name, "css-updater.json")) as config: import json self.config: Dict[str, Any] = json.loads(config.read()) def __del__(self: Manager) -> None: self.temp_dir.cleanup() ## Instruction: Check for errors in config ## Code After: """manages github repos""" import os import tempfile from typing import Dict, Any import pygit2 as git from .webhook.handler import Handler class Manager(object): """handles git repos""" def __init__(self: Manager, handler: Handler) -> None: self.webhook_handler: Handler = handler self.temp_dir: tempfile.TemporaryDirectory = tempfile.TemporaryDirectory() self.repo: git.Repository = git.clone_repository( self.webhook_handler.git_url, path=self.temp_dir.name) with open(os.path.join(self.temp_dir.name, "css-updater.json")) as config: import json try: self.config: Dict[str, Any] = json.loads(config.read())["css_updater"] except KeyError as invalid_json: print(invalid_json) except IOError as io_error: print(io_error) def __del__(self: Manager) -> None: self.temp_dir.cleanup()
"""manages github repos""" import os import tempfile from typing import Dict, Any import pygit2 as git from .webhook.handler import Handler class Manager(object): """handles git repos""" def __init__(self: Manager, handler: Handler) -> None: self.webhook_handler: Handler = handler self.temp_dir: tempfile.TemporaryDirectory = tempfile.TemporaryDirectory() self.repo: git.Repository = git.clone_repository( self.webhook_handler.git_url, path=self.temp_dir.name) with open(os.path.join(self.temp_dir.name, "css-updater.json")) as config: import json + try: - self.config: Dict[str, Any] = json.loads(config.read()) + self.config: Dict[str, Any] = json.loads(config.read())["css_updater"] ? ++++ +++++++++++++++ + except KeyError as invalid_json: + print(invalid_json) + except IOError as io_error: + print(io_error) def __del__(self: Manager) -> None: self.temp_dir.cleanup()
15619b7f0eeac9be4cbeaea35185abc413992e5c
devito/yask/grid.py
devito/yask/grid.py
import devito.grid as grid from devito.yask.function import Constant from devito.yask.wrappers import contexts __all__ = ['Grid'] class Grid(grid.Grid): def __init__(self, *args, **kwargs): super(Grid, self).__init__(*args, **kwargs) # Initialize a new YaskContext for this Grid contexts.putdefault(self) @property def _const(self): return Constant def _make_stepping_dim(self, time_dim, **kwargs): # In the `yask` backend, the stepping dimension is an alias of the # time dimension return time_dim def __setstate__(self, state): for k, v in state.items(): setattr(self, k, v) # A new context is created, as the unpickled Dimensions are new objects contexts.putdefault(self)
import devito.grid as grid from devito.yask.function import Constant from devito.yask.wrappers import contexts __all__ = ['Grid'] class Grid(grid.Grid): def __init__(self, *args, **kwargs): super(Grid, self).__init__(*args, **kwargs) # Initialize a new YaskContext for this Grid contexts.putdefault(self) @property def _const(self): return Constant def _make_stepping_dim(self, time_dim, **kwargs): # In the `yask` backend, the stepping dimension is an alias of the # time dimension return time_dim def __setstate__(self, state): super(Grid, self).__setstate__(state) # A new context is created, as the unpickled Dimensions are new objects contexts.putdefault(self)
Fix Grid pickling in YASK
mpi: Fix Grid pickling in YASK
Python
mit
opesci/devito,opesci/devito
import devito.grid as grid from devito.yask.function import Constant from devito.yask.wrappers import contexts __all__ = ['Grid'] class Grid(grid.Grid): def __init__(self, *args, **kwargs): super(Grid, self).__init__(*args, **kwargs) # Initialize a new YaskContext for this Grid contexts.putdefault(self) @property def _const(self): return Constant def _make_stepping_dim(self, time_dim, **kwargs): # In the `yask` backend, the stepping dimension is an alias of the # time dimension return time_dim def __setstate__(self, state): + super(Grid, self).__setstate__(state) - for k, v in state.items(): - setattr(self, k, v) # A new context is created, as the unpickled Dimensions are new objects contexts.putdefault(self)
Fix Grid pickling in YASK
## Code Before: import devito.grid as grid from devito.yask.function import Constant from devito.yask.wrappers import contexts __all__ = ['Grid'] class Grid(grid.Grid): def __init__(self, *args, **kwargs): super(Grid, self).__init__(*args, **kwargs) # Initialize a new YaskContext for this Grid contexts.putdefault(self) @property def _const(self): return Constant def _make_stepping_dim(self, time_dim, **kwargs): # In the `yask` backend, the stepping dimension is an alias of the # time dimension return time_dim def __setstate__(self, state): for k, v in state.items(): setattr(self, k, v) # A new context is created, as the unpickled Dimensions are new objects contexts.putdefault(self) ## Instruction: Fix Grid pickling in YASK ## Code After: import devito.grid as grid from devito.yask.function import Constant from devito.yask.wrappers import contexts __all__ = ['Grid'] class Grid(grid.Grid): def __init__(self, *args, **kwargs): super(Grid, self).__init__(*args, **kwargs) # Initialize a new YaskContext for this Grid contexts.putdefault(self) @property def _const(self): return Constant def _make_stepping_dim(self, time_dim, **kwargs): # In the `yask` backend, the stepping dimension is an alias of the # time dimension return time_dim def __setstate__(self, state): super(Grid, self).__setstate__(state) # A new context is created, as the unpickled Dimensions are new objects contexts.putdefault(self)
import devito.grid as grid from devito.yask.function import Constant from devito.yask.wrappers import contexts __all__ = ['Grid'] class Grid(grid.Grid): def __init__(self, *args, **kwargs): super(Grid, self).__init__(*args, **kwargs) # Initialize a new YaskContext for this Grid contexts.putdefault(self) @property def _const(self): return Constant def _make_stepping_dim(self, time_dim, **kwargs): # In the `yask` backend, the stepping dimension is an alias of the # time dimension return time_dim def __setstate__(self, state): + super(Grid, self).__setstate__(state) - for k, v in state.items(): - setattr(self, k, v) # A new context is created, as the unpickled Dimensions are new objects contexts.putdefault(self)
28ee229284459402d73f41e756dc95fe99f0227b
pybot/resources/urls.py
pybot/resources/urls.py
FACEBOOK_MESSAGES_POST_URL = "https://graph.facebook.com/v2.6/me/messages"
FACEBOOK_MESSAGES_POST_URL = "https://graph.facebook.com/v2.6/"
Update URL for generic graph api url
Update URL for generic graph api url
Python
mit
ben-cunningham/python-messenger-bot,ben-cunningham/pybot
- FACEBOOK_MESSAGES_POST_URL = "https://graph.facebook.com/v2.6/me/messages" + FACEBOOK_MESSAGES_POST_URL = "https://graph.facebook.com/v2.6/"
Update URL for generic graph api url
## Code Before: FACEBOOK_MESSAGES_POST_URL = "https://graph.facebook.com/v2.6/me/messages" ## Instruction: Update URL for generic graph api url ## Code After: FACEBOOK_MESSAGES_POST_URL = "https://graph.facebook.com/v2.6/"
- FACEBOOK_MESSAGES_POST_URL = "https://graph.facebook.com/v2.6/me/messages" ? ----------- + FACEBOOK_MESSAGES_POST_URL = "https://graph.facebook.com/v2.6/"
31073969ed99dd6f57ff1959c050fd0f8f59f58c
tests/scipy_argrelextrema.py
tests/scipy_argrelextrema.py
import numpy as np from vector import vector, plot_peaks import scipy.signal print('Detect peaks without any filters (maxima).') indexes = scipy.signal.argrelextrema( np.array(vector), comparator=np.greater ) print('Peaks are: %s' % (indexes[0])) plot_peaks( np.array(vector), indexes[0], algorithm='scipy.signal.argrelmax' ) print('Detect peaks without any filters (minima).') indexes = scipy.signal.argrelextrema( np.array(vector), comparator=np.less ) print('Peaks are: %s' % (indexes[0])) plot_peaks( np.array(vector), indexes[0], algorithm='scipy.signal.argrelmax' ) print('Detect peaks with order (distance) filter.') indexes = scipy.signal.argrelextrema( np.array(vector), comparator=np.greater, order=2 ) print('Peaks are: %s' % (indexes[0])) plot_peaks( np.array(vector), indexes[0], mpd=2, algorithm='scipy.signal.argrelmax' )
import numpy as np from vector import vector, plot_peaks import scipy.signal print('Detect peaks without any filters (maxima).') indexes = scipy.signal.argrelextrema( np.array(vector), comparator=np.greater ) print('Peaks are: %s' % (indexes[0])) # To get number of peaks: # print("{} peaks".format(len(indexes[0]))) plot_peaks( np.array(vector), indexes[0], algorithm='scipy.signal.argrelmax' ) print('Detect peaks without any filters (minima).') indexes = scipy.signal.argrelextrema( np.array(vector), comparator=np.less ) print('Peaks are: %s' % (indexes[0])) plot_peaks( np.array(vector), indexes[0], algorithm='scipy.signal.argrelmax' ) print('Detect peaks with order (distance) filter.') indexes = scipy.signal.argrelextrema( np.array(vector), comparator=np.greater, order=2 ) print('Peaks are: %s' % (indexes[0])) plot_peaks( np.array(vector), indexes[0], mpd=2, algorithm='scipy.signal.argrelmax' )
Add eg to get number of peaks
Add eg to get number of peaks
Python
mit
MonsieurV/py-findpeaks,MonsieurV/py-findpeaks
import numpy as np from vector import vector, plot_peaks import scipy.signal print('Detect peaks without any filters (maxima).') indexes = scipy.signal.argrelextrema( np.array(vector), comparator=np.greater ) print('Peaks are: %s' % (indexes[0])) + # To get number of peaks: + # print("{} peaks".format(len(indexes[0]))) plot_peaks( np.array(vector), indexes[0], algorithm='scipy.signal.argrelmax' ) print('Detect peaks without any filters (minima).') indexes = scipy.signal.argrelextrema( np.array(vector), comparator=np.less ) print('Peaks are: %s' % (indexes[0])) plot_peaks( np.array(vector), indexes[0], algorithm='scipy.signal.argrelmax' ) print('Detect peaks with order (distance) filter.') indexes = scipy.signal.argrelextrema( np.array(vector), comparator=np.greater, order=2 ) print('Peaks are: %s' % (indexes[0])) plot_peaks( np.array(vector), indexes[0], mpd=2, algorithm='scipy.signal.argrelmax' )
Add eg to get number of peaks
## Code Before: import numpy as np from vector import vector, plot_peaks import scipy.signal print('Detect peaks without any filters (maxima).') indexes = scipy.signal.argrelextrema( np.array(vector), comparator=np.greater ) print('Peaks are: %s' % (indexes[0])) plot_peaks( np.array(vector), indexes[0], algorithm='scipy.signal.argrelmax' ) print('Detect peaks without any filters (minima).') indexes = scipy.signal.argrelextrema( np.array(vector), comparator=np.less ) print('Peaks are: %s' % (indexes[0])) plot_peaks( np.array(vector), indexes[0], algorithm='scipy.signal.argrelmax' ) print('Detect peaks with order (distance) filter.') indexes = scipy.signal.argrelextrema( np.array(vector), comparator=np.greater, order=2 ) print('Peaks are: %s' % (indexes[0])) plot_peaks( np.array(vector), indexes[0], mpd=2, algorithm='scipy.signal.argrelmax' ) ## Instruction: Add eg to get number of peaks ## Code After: import numpy as np from vector import vector, plot_peaks import scipy.signal print('Detect peaks without any filters (maxima).') indexes = scipy.signal.argrelextrema( np.array(vector), comparator=np.greater ) print('Peaks are: %s' % (indexes[0])) # To get number of peaks: # print("{} peaks".format(len(indexes[0]))) plot_peaks( np.array(vector), indexes[0], algorithm='scipy.signal.argrelmax' ) print('Detect peaks without any filters (minima).') indexes = scipy.signal.argrelextrema( np.array(vector), comparator=np.less ) print('Peaks are: %s' % (indexes[0])) plot_peaks( np.array(vector), indexes[0], algorithm='scipy.signal.argrelmax' ) print('Detect peaks with order (distance) filter.') indexes = scipy.signal.argrelextrema( np.array(vector), comparator=np.greater, order=2 ) print('Peaks are: %s' % (indexes[0])) plot_peaks( np.array(vector), indexes[0], mpd=2, algorithm='scipy.signal.argrelmax' )
import numpy as np from vector import vector, plot_peaks import scipy.signal print('Detect peaks without any filters (maxima).') indexes = scipy.signal.argrelextrema( np.array(vector), comparator=np.greater ) print('Peaks are: %s' % (indexes[0])) + # To get number of peaks: + # print("{} peaks".format(len(indexes[0]))) plot_peaks( np.array(vector), indexes[0], algorithm='scipy.signal.argrelmax' ) print('Detect peaks without any filters (minima).') indexes = scipy.signal.argrelextrema( np.array(vector), comparator=np.less ) print('Peaks are: %s' % (indexes[0])) plot_peaks( np.array(vector), indexes[0], algorithm='scipy.signal.argrelmax' ) print('Detect peaks with order (distance) filter.') indexes = scipy.signal.argrelextrema( np.array(vector), comparator=np.greater, order=2 ) print('Peaks are: %s' % (indexes[0])) plot_peaks( np.array(vector), indexes[0], mpd=2, algorithm='scipy.signal.argrelmax' )
28627a41918be15037ba22e930a45d022e88388d
opps/articles/adminx.py
opps/articles/adminx.py
from .models import Post, Album, Link from opps.contrib import admin admin.site.register(Post) admin.site.register(Album) admin.site.register(Link)
from django.utils.translation import ugettext_lazy as _ from .models import Post, Album, Link from opps.containers.models import ContainerSource, ContainerImage from opps.contrib import admin from opps.contrib.admin.layout import * from xadmin.plugins.inline import Inline class ImageInline(object): model = ContainerImage style = 'accordion' class SourceInline(object): model = ContainerSource style = 'accordion' class PostAdmin(object): raw_id_fields = ['main_image', 'channel', 'albums'] inlines = [ImageInline, SourceInline] style_fields = {'system': "radio-inline"} form_layout = ( Main( TabHolder( Tab(_(u'Identification'), Fieldset('site', 'title', 'slug', 'get_http_absolute_url', 'short_url'), ), Tab(_(u'Content'), Fieldset('hat', 'short_title', 'headline', 'content', 'main_image', 'main_image_caption', 'image_thumb' 'tags'), Inline(ContainerImage), Inline(ContainerSource), ), Tab(_(u'Relationships'), Fieldset('channel', 'albums'), ), )), Side( Fieldset(_(u'Publication'), 'published', 'date_available', 'show_on_root_channel', 'in_containerboxes') ) ) reversion_enable = True admin.site.register(Post, PostAdmin) admin.site.register(Album) admin.site.register(Link)
Add Inline example on post model xadmin
Add Inline example on post model xadmin
Python
mit
jeanmask/opps,opps/opps,YACOWS/opps,williamroot/opps,opps/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,opps/opps,williamroot/opps,jeanmask/opps,opps/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,YACOWS/opps
+ from django.utils.translation import ugettext_lazy as _ from .models import Post, Album, Link + from opps.containers.models import ContainerSource, ContainerImage from opps.contrib import admin + from opps.contrib.admin.layout import * + from xadmin.plugins.inline import Inline + + class ImageInline(object): + model = ContainerImage + style = 'accordion' + + + class SourceInline(object): + model = ContainerSource + style = 'accordion' + + + class PostAdmin(object): + raw_id_fields = ['main_image', 'channel', 'albums'] + inlines = [ImageInline, SourceInline] + style_fields = {'system': "radio-inline"} + + form_layout = ( + Main( + TabHolder( + Tab(_(u'Identification'), + Fieldset('site', 'title', 'slug', + 'get_http_absolute_url', 'short_url'), + ), + Tab(_(u'Content'), + Fieldset('hat', 'short_title', 'headline', + 'content', 'main_image', 'main_image_caption', + 'image_thumb' 'tags'), + Inline(ContainerImage), + Inline(ContainerSource), + ), + Tab(_(u'Relationships'), + Fieldset('channel', 'albums'), + ), + )), + Side( + Fieldset(_(u'Publication'), 'published', 'date_available', + 'show_on_root_channel', 'in_containerboxes') + + ) + ) + + reversion_enable = True + + - admin.site.register(Post) + admin.site.register(Post, PostAdmin) admin.site.register(Album) admin.site.register(Link)
Add Inline example on post model xadmin
## Code Before: from .models import Post, Album, Link from opps.contrib import admin admin.site.register(Post) admin.site.register(Album) admin.site.register(Link) ## Instruction: Add Inline example on post model xadmin ## Code After: from django.utils.translation import ugettext_lazy as _ from .models import Post, Album, Link from opps.containers.models import ContainerSource, ContainerImage from opps.contrib import admin from opps.contrib.admin.layout import * from xadmin.plugins.inline import Inline class ImageInline(object): model = ContainerImage style = 'accordion' class SourceInline(object): model = ContainerSource style = 'accordion' class PostAdmin(object): raw_id_fields = ['main_image', 'channel', 'albums'] inlines = [ImageInline, SourceInline] style_fields = {'system': "radio-inline"} form_layout = ( Main( TabHolder( Tab(_(u'Identification'), Fieldset('site', 'title', 'slug', 'get_http_absolute_url', 'short_url'), ), Tab(_(u'Content'), Fieldset('hat', 'short_title', 'headline', 'content', 'main_image', 'main_image_caption', 'image_thumb' 'tags'), Inline(ContainerImage), Inline(ContainerSource), ), Tab(_(u'Relationships'), Fieldset('channel', 'albums'), ), )), Side( Fieldset(_(u'Publication'), 'published', 'date_available', 'show_on_root_channel', 'in_containerboxes') ) ) reversion_enable = True admin.site.register(Post, PostAdmin) admin.site.register(Album) admin.site.register(Link)
+ from django.utils.translation import ugettext_lazy as _ from .models import Post, Album, Link + from opps.containers.models import ContainerSource, ContainerImage from opps.contrib import admin + from opps.contrib.admin.layout import * + from xadmin.plugins.inline import Inline + + class ImageInline(object): + model = ContainerImage + style = 'accordion' + + + class SourceInline(object): + model = ContainerSource + style = 'accordion' + + + class PostAdmin(object): + raw_id_fields = ['main_image', 'channel', 'albums'] + inlines = [ImageInline, SourceInline] + style_fields = {'system': "radio-inline"} + + form_layout = ( + Main( + TabHolder( + Tab(_(u'Identification'), + Fieldset('site', 'title', 'slug', + 'get_http_absolute_url', 'short_url'), + ), + Tab(_(u'Content'), + Fieldset('hat', 'short_title', 'headline', + 'content', 'main_image', 'main_image_caption', + 'image_thumb' 'tags'), + Inline(ContainerImage), + Inline(ContainerSource), + ), + Tab(_(u'Relationships'), + Fieldset('channel', 'albums'), + ), + )), + Side( + Fieldset(_(u'Publication'), 'published', 'date_available', + 'show_on_root_channel', 'in_containerboxes') + + ) + ) + + reversion_enable = True + + - admin.site.register(Post) + admin.site.register(Post, PostAdmin) ? +++++++++++ admin.site.register(Album) admin.site.register(Link)
edd50431f9c99bcbc765cc85786ead60ba8ba6e4
admin/base/migrations/0002_groups.py
admin/base/migrations/0002_groups.py
from __future__ import unicode_literals from django.db import migrations from django.contrib.auth.models import Group import logging logger = logging.getLogger(__file__) def add_groups(*args): group, created = Group.objects.get_or_create(name='nodes_and_users') if created: logger.info('nodes_and_users group created') try: group = Group.objects.get(name='prereg_group') group.name = 'prereg' group.save() logger.info('prereg_group renamed to prereg') except Group.DoesNotExist: group, created = Group.objects.get_or_create(name='prereg') if created: logger.info('prereg group created') class Migration(migrations.Migration): dependencies = [ ('base', '0001_groups'), ] operations = [ migrations.RunPython(add_groups), ]
from __future__ import unicode_literals from django.db import migrations from django.contrib.auth.models import Group import logging logger = logging.getLogger(__file__) def add_groups(*args): group, created = Group.objects.get_or_create(name='nodes_and_users') if created: logger.info('nodes_and_users group created') try: group = Group.objects.get(name='prereg_group') group.name = 'prereg' group.save() logger.info('prereg_group renamed to prereg') except Group.DoesNotExist: group, created = Group.objects.get_or_create(name='prereg') if created: logger.info('prereg group created') def remove_groups(*args): Group.objects.filter(name='nodes_and_users').delete() group = Group.objects.get(name='prereg') group.name = 'prereg_group' group.save() class Migration(migrations.Migration): dependencies = [ ('base', '0001_groups'), ] operations = [ migrations.RunPython(add_groups, remove_groups), ]
Add reverse migration for new groups
Add reverse migration for new groups
Python
apache-2.0
brianjgeiger/osf.io,chennan47/osf.io,CenterForOpenScience/osf.io,sloria/osf.io,Johnetordoff/osf.io,leb2dg/osf.io,brianjgeiger/osf.io,monikagrabowska/osf.io,binoculars/osf.io,acshi/osf.io,chrisseto/osf.io,acshi/osf.io,crcresearch/osf.io,aaxelb/osf.io,erinspace/osf.io,brianjgeiger/osf.io,chrisseto/osf.io,erinspace/osf.io,baylee-d/osf.io,mfraezz/osf.io,cwisecarver/osf.io,CenterForOpenScience/osf.io,binoculars/osf.io,saradbowman/osf.io,acshi/osf.io,HalcyonChimera/osf.io,cslzchen/osf.io,monikagrabowska/osf.io,leb2dg/osf.io,chennan47/osf.io,Johnetordoff/osf.io,mfraezz/osf.io,CenterForOpenScience/osf.io,leb2dg/osf.io,felliott/osf.io,hmoco/osf.io,cwisecarver/osf.io,pattisdr/osf.io,chrisseto/osf.io,adlius/osf.io,pattisdr/osf.io,monikagrabowska/osf.io,adlius/osf.io,icereval/osf.io,baylee-d/osf.io,cslzchen/osf.io,felliott/osf.io,caneruguz/osf.io,TomBaxter/osf.io,caneruguz/osf.io,baylee-d/osf.io,TomBaxter/osf.io,HalcyonChimera/osf.io,aaxelb/osf.io,caseyrollins/osf.io,hmoco/osf.io,felliott/osf.io,cslzchen/osf.io,monikagrabowska/osf.io,aaxelb/osf.io,crcresearch/osf.io,mattclark/osf.io,cwisecarver/osf.io,laurenrevere/osf.io,hmoco/osf.io,saradbowman/osf.io,cslzchen/osf.io,HalcyonChimera/osf.io,pattisdr/osf.io,CenterForOpenScience/osf.io,monikagrabowska/osf.io,mfraezz/osf.io,icereval/osf.io,cwisecarver/osf.io,brianjgeiger/osf.io,TomBaxter/osf.io,laurenrevere/osf.io,sloria/osf.io,caseyrollins/osf.io,Nesiehr/osf.io,leb2dg/osf.io,acshi/osf.io,caseyrollins/osf.io,HalcyonChimera/osf.io,Nesiehr/osf.io,mattclark/osf.io,Johnetordoff/osf.io,Johnetordoff/osf.io,felliott/osf.io,icereval/osf.io,crcresearch/osf.io,mattclark/osf.io,acshi/osf.io,sloria/osf.io,caneruguz/osf.io,mfraezz/osf.io,binoculars/osf.io,adlius/osf.io,aaxelb/osf.io,caneruguz/osf.io,Nesiehr/osf.io,laurenrevere/osf.io,erinspace/osf.io,hmoco/osf.io,chrisseto/osf.io,Nesiehr/osf.io,chennan47/osf.io,adlius/osf.io
from __future__ import unicode_literals from django.db import migrations from django.contrib.auth.models import Group import logging logger = logging.getLogger(__file__) def add_groups(*args): group, created = Group.objects.get_or_create(name='nodes_and_users') if created: logger.info('nodes_and_users group created') try: group = Group.objects.get(name='prereg_group') group.name = 'prereg' group.save() logger.info('prereg_group renamed to prereg') except Group.DoesNotExist: group, created = Group.objects.get_or_create(name='prereg') if created: logger.info('prereg group created') + def remove_groups(*args): + Group.objects.filter(name='nodes_and_users').delete() + + group = Group.objects.get(name='prereg') + group.name = 'prereg_group' + group.save() + + class Migration(migrations.Migration): dependencies = [ ('base', '0001_groups'), ] operations = [ - migrations.RunPython(add_groups), + migrations.RunPython(add_groups, remove_groups), ]
Add reverse migration for new groups
## Code Before: from __future__ import unicode_literals from django.db import migrations from django.contrib.auth.models import Group import logging logger = logging.getLogger(__file__) def add_groups(*args): group, created = Group.objects.get_or_create(name='nodes_and_users') if created: logger.info('nodes_and_users group created') try: group = Group.objects.get(name='prereg_group') group.name = 'prereg' group.save() logger.info('prereg_group renamed to prereg') except Group.DoesNotExist: group, created = Group.objects.get_or_create(name='prereg') if created: logger.info('prereg group created') class Migration(migrations.Migration): dependencies = [ ('base', '0001_groups'), ] operations = [ migrations.RunPython(add_groups), ] ## Instruction: Add reverse migration for new groups ## Code After: from __future__ import unicode_literals from django.db import migrations from django.contrib.auth.models import Group import logging logger = logging.getLogger(__file__) def add_groups(*args): group, created = Group.objects.get_or_create(name='nodes_and_users') if created: logger.info('nodes_and_users group created') try: group = Group.objects.get(name='prereg_group') group.name = 'prereg' group.save() logger.info('prereg_group renamed to prereg') except Group.DoesNotExist: group, created = Group.objects.get_or_create(name='prereg') if created: logger.info('prereg group created') def remove_groups(*args): Group.objects.filter(name='nodes_and_users').delete() group = Group.objects.get(name='prereg') group.name = 'prereg_group' group.save() class Migration(migrations.Migration): dependencies = [ ('base', '0001_groups'), ] operations = [ migrations.RunPython(add_groups, remove_groups), ]
from __future__ import unicode_literals from django.db import migrations from django.contrib.auth.models import Group import logging logger = logging.getLogger(__file__) def add_groups(*args): group, created = Group.objects.get_or_create(name='nodes_and_users') if created: logger.info('nodes_and_users group created') try: group = Group.objects.get(name='prereg_group') group.name = 'prereg' group.save() logger.info('prereg_group renamed to prereg') except Group.DoesNotExist: group, created = Group.objects.get_or_create(name='prereg') if created: logger.info('prereg group created') + def remove_groups(*args): + Group.objects.filter(name='nodes_and_users').delete() + + group = Group.objects.get(name='prereg') + group.name = 'prereg_group' + group.save() + + class Migration(migrations.Migration): dependencies = [ ('base', '0001_groups'), ] operations = [ - migrations.RunPython(add_groups), + migrations.RunPython(add_groups, remove_groups), ? +++++++++++++++ ]
443cc0114d7669471e39661c97e2bad91c8eabb8
tests/basics/set_difference.py
tests/basics/set_difference.py
l = [1, 2, 3, 4] s = set(l) outs = [s.difference(), s.difference({1}), s.difference({1}, [1, 2]), s.difference({1}, {1, 2}, {2, 3})] for out in outs: print(sorted(out)) s = set(l) print(s.difference_update()) print(sorted(s)) print(s.difference_update({1})) print(sorted(s)) print(s.difference_update({1}, [2])) print(sorted(s))
l = [1, 2, 3, 4] s = set(l) outs = [s.difference(), s.difference({1}), s.difference({1}, [1, 2]), s.difference({1}, {1, 2}, {2, 3})] for out in outs: print(sorted(out)) s = set(l) print(s.difference_update()) print(sorted(s)) print(s.difference_update({1})) print(sorted(s)) print(s.difference_update({1}, [2])) print(sorted(s)) s.difference_update(s) print(s)
Add test for set.difference_update with arg being itself.
tests/basics: Add test for set.difference_update with arg being itself.
Python
mit
blazewicz/micropython,tobbad/micropython,tuc-osg/micropython,henriknelson/micropython,SHA2017-badge/micropython-esp32,cwyark/micropython,ryannathans/micropython,Timmenem/micropython,alex-robbins/micropython,PappaPeppar/micropython,dxxb/micropython,Peetz0r/micropython-esp32,jmarcelino/pycom-micropython,hiway/micropython,cwyark/micropython,pramasoul/micropython,lowRISC/micropython,jmarcelino/pycom-micropython,trezor/micropython,selste/micropython,dmazzella/micropython,HenrikSolver/micropython,alex-march/micropython,tralamazza/micropython,hosaka/micropython,deshipu/micropython,alex-march/micropython,SHA2017-badge/micropython-esp32,chrisdearman/micropython,hiway/micropython,pramasoul/micropython,bvernoux/micropython,Peetz0r/micropython-esp32,torwag/micropython,pramasoul/micropython,ryannathans/micropython,dxxb/micropython,tuc-osg/micropython,deshipu/micropython,adafruit/circuitpython,ryannathans/micropython,puuu/micropython,TDAbboud/micropython,oopy/micropython,HenrikSolver/micropython,AriZuu/micropython,kerneltask/micropython,oopy/micropython,mhoffma/micropython,blazewicz/micropython,micropython/micropython-esp32,infinnovation/micropython,blazewicz/micropython,pozetroninc/micropython,SHA2017-badge/micropython-esp32,Peetz0r/micropython-esp32,puuu/micropython,dmazzella/micropython,alex-march/micropython,tralamazza/micropython,alex-robbins/micropython,AriZuu/micropython,toolmacher/micropython,PappaPeppar/micropython,swegener/micropython,pramasoul/micropython,trezor/micropython,puuu/micropython,Timmenem/micropython,tobbad/micropython,tuc-osg/micropython,alex-march/micropython,MrSurly/micropython-esp32,kerneltask/micropython,puuu/micropython,dmazzella/micropython,hosaka/micropython,adafruit/micropython,pfalcon/micropython,pozetroninc/micropython,MrSurly/micropython-esp32,selste/micropython,selste/micropython,adafruit/circuitpython,infinnovation/micropython,henriknelson/micropython,ryannathans/micropython,tobbad/micropython,HenrikSolver/micropython,hosaka/micropython,matthewelse/micropython,adafruit/circuitpython,AriZuu/micropython,matthewelse/micropython,mhoffma/micropython,dxxb/micropython,kerneltask/micropython,SHA2017-badge/micropython-esp32,hiway/micropython,tralamazza/micropython,selste/micropython,toolmacher/micropython,turbinenreiter/micropython,dxxb/micropython,deshipu/micropython,cwyark/micropython,hosaka/micropython,swegener/micropython,Timmenem/micropython,pfalcon/micropython,ryannathans/micropython,bvernoux/micropython,kerneltask/micropython,bvernoux/micropython,torwag/micropython,cwyark/micropython,cwyark/micropython,chrisdearman/micropython,infinnovation/micropython,tuc-osg/micropython,dmazzella/micropython,alex-march/micropython,micropython/micropython-esp32,jmarcelino/pycom-micropython,mhoffma/micropython,hiway/micropython,TDAbboud/micropython,lowRISC/micropython,chrisdearman/micropython,MrSurly/micropython,alex-robbins/micropython,selste/micropython,adafruit/micropython,tobbad/micropython,swegener/micropython,deshipu/micropython,micropython/micropython-esp32,mhoffma/micropython,tuc-osg/micropython,Timmenem/micropython,turbinenreiter/micropython,lowRISC/micropython,PappaPeppar/micropython,tobbad/micropython,MrSurly/micropython-esp32,HenrikSolver/micropython,jmarcelino/pycom-micropython,pozetroninc/micropython,toolmacher/micropython,adafruit/micropython,TDAbboud/micropython,lowRISC/micropython,torwag/micropython,adafruit/micropython,pozetroninc/micropython,swegener/micropython,pfalcon/micropython,bvernoux/micropython,deshipu/micropython,adafruit/circuitpython,MrSurly/micropython-esp32,PappaPeppar/micropython,blazewicz/micropython,mhoffma/micropython,oopy/micropython,MrSurly/micropython,jmarcelino/pycom-micropython,pramasoul/micropython,chrisdearman/micropython,toolmacher/micropython,MrSurly/micropython,blazewicz/micropython,puuu/micropython,toolmacher/micropython,hosaka/micropython,torwag/micropython,swegener/micropython,henriknelson/micropython,Peetz0r/micropython-esp32,chrisdearman/micropython,henriknelson/micropython,AriZuu/micropython,adafruit/circuitpython,matthewelse/micropython,tralamazza/micropython,matthewelse/micropython,Timmenem/micropython,matthewelse/micropython,HenrikSolver/micropython,adafruit/circuitpython,torwag/micropython,kerneltask/micropython,infinnovation/micropython,turbinenreiter/micropython,adafruit/micropython,trezor/micropython,oopy/micropython,hiway/micropython,oopy/micropython,pfalcon/micropython,MrSurly/micropython-esp32,micropython/micropython-esp32,MrSurly/micropython,MrSurly/micropython,alex-robbins/micropython,TDAbboud/micropython,dxxb/micropython,SHA2017-badge/micropython-esp32,turbinenreiter/micropython,turbinenreiter/micropython,pozetroninc/micropython,Peetz0r/micropython-esp32,pfalcon/micropython,matthewelse/micropython,trezor/micropython,henriknelson/micropython,lowRISC/micropython,infinnovation/micropython,micropython/micropython-esp32,bvernoux/micropython,AriZuu/micropython,PappaPeppar/micropython,trezor/micropython,alex-robbins/micropython,TDAbboud/micropython
l = [1, 2, 3, 4] s = set(l) outs = [s.difference(), s.difference({1}), s.difference({1}, [1, 2]), s.difference({1}, {1, 2}, {2, 3})] for out in outs: print(sorted(out)) s = set(l) print(s.difference_update()) print(sorted(s)) print(s.difference_update({1})) print(sorted(s)) print(s.difference_update({1}, [2])) print(sorted(s)) + s.difference_update(s) + print(s) +
Add test for set.difference_update with arg being itself.
## Code Before: l = [1, 2, 3, 4] s = set(l) outs = [s.difference(), s.difference({1}), s.difference({1}, [1, 2]), s.difference({1}, {1, 2}, {2, 3})] for out in outs: print(sorted(out)) s = set(l) print(s.difference_update()) print(sorted(s)) print(s.difference_update({1})) print(sorted(s)) print(s.difference_update({1}, [2])) print(sorted(s)) ## Instruction: Add test for set.difference_update with arg being itself. ## Code After: l = [1, 2, 3, 4] s = set(l) outs = [s.difference(), s.difference({1}), s.difference({1}, [1, 2]), s.difference({1}, {1, 2}, {2, 3})] for out in outs: print(sorted(out)) s = set(l) print(s.difference_update()) print(sorted(s)) print(s.difference_update({1})) print(sorted(s)) print(s.difference_update({1}, [2])) print(sorted(s)) s.difference_update(s) print(s)
l = [1, 2, 3, 4] s = set(l) outs = [s.difference(), s.difference({1}), s.difference({1}, [1, 2]), s.difference({1}, {1, 2}, {2, 3})] for out in outs: print(sorted(out)) s = set(l) print(s.difference_update()) print(sorted(s)) print(s.difference_update({1})) print(sorted(s)) print(s.difference_update({1}, [2])) print(sorted(s)) + + s.difference_update(s) + print(s)
0e9c2fead2c8ad0194f1174ea7d5ad6acd74a12c
private_storage/storage.py
private_storage/storage.py
from django.core.files.storage import FileSystemStorage from django.core.urlresolvers import reverse_lazy from . import appconfig __all__ = ( 'private_storage', 'PrivateStorage', ) class PrivateStorage(FileSystemStorage): """ Interface to the Django storage system, storing the files in a private folder. """ def __init__(self, location=None, base_url=None, **kwargs): if location is None: location = appconfig.PRIVATE_STORAGE_ROOT super(PrivateStorage, self).__init__( location=location, base_url=base_url, **kwargs ) if base_url is None: # When base_url is not given, it's autodetected. # However, as the super method checks for base_url.endswith('/'), # the attribute is overwritten here to avoid breaking lazy evaluation. self.base_url = reverse_lazy('serve_private_file', kwargs={'path': ''}) # Singleton instance. private_storage = PrivateStorage()
from django.core.files.storage import FileSystemStorage from django.core.urlresolvers import reverse_lazy from django.utils.encoding import force_text from . import appconfig __all__ = ( 'private_storage', 'PrivateStorage', ) class PrivateStorage(FileSystemStorage): """ Interface to the Django storage system, storing the files in a private folder. """ def __init__(self, location=None, base_url=None, **kwargs): if location is None: location = appconfig.PRIVATE_STORAGE_ROOT super(PrivateStorage, self).__init__( location=location, base_url=base_url, **kwargs ) if base_url is None: # When base_url is not given, it's autodetected. # However, as the super method checks for base_url.endswith('/'), # the attribute is overwritten here to avoid breaking lazy evaluation. self.base_url = reverse_lazy('serve_private_file', kwargs={'path': ''}) def url(self, name): # Make sure reverse_lazy() is evaluated, as Python 3 won't do this here. self.base_url = force_text(self.base_url) return super(PrivateStorage, self).url(name) # Singleton instance. private_storage = PrivateStorage()
Fix url reversing in Python 3
Fix url reversing in Python 3
Python
apache-2.0
edoburu/django-private-storage
from django.core.files.storage import FileSystemStorage from django.core.urlresolvers import reverse_lazy + from django.utils.encoding import force_text + from . import appconfig __all__ = ( 'private_storage', 'PrivateStorage', ) class PrivateStorage(FileSystemStorage): """ Interface to the Django storage system, storing the files in a private folder. """ def __init__(self, location=None, base_url=None, **kwargs): if location is None: location = appconfig.PRIVATE_STORAGE_ROOT super(PrivateStorage, self).__init__( location=location, base_url=base_url, **kwargs ) if base_url is None: # When base_url is not given, it's autodetected. # However, as the super method checks for base_url.endswith('/'), # the attribute is overwritten here to avoid breaking lazy evaluation. self.base_url = reverse_lazy('serve_private_file', kwargs={'path': ''}) + def url(self, name): + # Make sure reverse_lazy() is evaluated, as Python 3 won't do this here. + self.base_url = force_text(self.base_url) + return super(PrivateStorage, self).url(name) + # Singleton instance. private_storage = PrivateStorage()
Fix url reversing in Python 3
## Code Before: from django.core.files.storage import FileSystemStorage from django.core.urlresolvers import reverse_lazy from . import appconfig __all__ = ( 'private_storage', 'PrivateStorage', ) class PrivateStorage(FileSystemStorage): """ Interface to the Django storage system, storing the files in a private folder. """ def __init__(self, location=None, base_url=None, **kwargs): if location is None: location = appconfig.PRIVATE_STORAGE_ROOT super(PrivateStorage, self).__init__( location=location, base_url=base_url, **kwargs ) if base_url is None: # When base_url is not given, it's autodetected. # However, as the super method checks for base_url.endswith('/'), # the attribute is overwritten here to avoid breaking lazy evaluation. self.base_url = reverse_lazy('serve_private_file', kwargs={'path': ''}) # Singleton instance. private_storage = PrivateStorage() ## Instruction: Fix url reversing in Python 3 ## Code After: from django.core.files.storage import FileSystemStorage from django.core.urlresolvers import reverse_lazy from django.utils.encoding import force_text from . import appconfig __all__ = ( 'private_storage', 'PrivateStorage', ) class PrivateStorage(FileSystemStorage): """ Interface to the Django storage system, storing the files in a private folder. """ def __init__(self, location=None, base_url=None, **kwargs): if location is None: location = appconfig.PRIVATE_STORAGE_ROOT super(PrivateStorage, self).__init__( location=location, base_url=base_url, **kwargs ) if base_url is None: # When base_url is not given, it's autodetected. # However, as the super method checks for base_url.endswith('/'), # the attribute is overwritten here to avoid breaking lazy evaluation. self.base_url = reverse_lazy('serve_private_file', kwargs={'path': ''}) def url(self, name): # Make sure reverse_lazy() is evaluated, as Python 3 won't do this here. self.base_url = force_text(self.base_url) return super(PrivateStorage, self).url(name) # Singleton instance. private_storage = PrivateStorage()
from django.core.files.storage import FileSystemStorage from django.core.urlresolvers import reverse_lazy + from django.utils.encoding import force_text + from . import appconfig __all__ = ( 'private_storage', 'PrivateStorage', ) class PrivateStorage(FileSystemStorage): """ Interface to the Django storage system, storing the files in a private folder. """ def __init__(self, location=None, base_url=None, **kwargs): if location is None: location = appconfig.PRIVATE_STORAGE_ROOT super(PrivateStorage, self).__init__( location=location, base_url=base_url, **kwargs ) if base_url is None: # When base_url is not given, it's autodetected. # However, as the super method checks for base_url.endswith('/'), # the attribute is overwritten here to avoid breaking lazy evaluation. self.base_url = reverse_lazy('serve_private_file', kwargs={'path': ''}) + def url(self, name): + # Make sure reverse_lazy() is evaluated, as Python 3 won't do this here. + self.base_url = force_text(self.base_url) + return super(PrivateStorage, self).url(name) + # Singleton instance. private_storage = PrivateStorage()
ed48c19844ee4f78c897c26555bdba9977a9a6ac
bluebottle/test/test_runner.py
bluebottle/test/test_runner.py
from django.test.runner import DiscoverRunner from django.db import connection from tenant_schemas.utils import get_tenant_model from bluebottle.test.utils import InitProjectDataMixin class MultiTenantRunner(DiscoverRunner, InitProjectDataMixin): def setup_databases(self, *args, **kwargs): result = super(MultiTenantRunner, self).setup_databases(*args, **kwargs) # Create secondary tenant connection.set_schema_to_public() tenant_domain = 'testserver2' tenant2 = get_tenant_model()( domain_url=tenant_domain, schema_name='test2', client_name='test2') tenant2.save( verbosity=self.verbosity) # Add basic data for tenant connection.set_tenant(tenant2) self.init_projects() # Create main tenant connection.set_schema_to_public() tenant_domain = 'testserver' tenant = get_tenant_model()( domain_url=tenant_domain, schema_name='test', client_name='test') tenant.save( verbosity=self.verbosity) connection.set_tenant(tenant) return result
from django.test.runner import DiscoverRunner from django.db import connection from tenant_schemas.utils import get_tenant_model from bluebottle.test.utils import InitProjectDataMixin class MultiTenantRunner(DiscoverRunner, InitProjectDataMixin): def setup_databases(self, *args, **kwargs): result = super(MultiTenantRunner, self).setup_databases(*args, **kwargs) # Create secondary tenant connection.set_schema_to_public() tenant_domain = 'testserver2' tenant2, _created = get_tenant_model().objects.get_or_create( domain_url=tenant_domain, schema_name='test2', client_name='test2') tenant2.save( verbosity=self.verbosity) # Add basic data for tenant connection.set_tenant(tenant2) self.init_projects() # Create main tenant connection.set_schema_to_public() tenant_domain = 'testserver' tenant, _created = get_tenant_model().objects.get_or_create( domain_url=tenant_domain, schema_name='test', client_name='test') tenant.save( verbosity=self.verbosity) connection.set_tenant(tenant) return result
Make it possible to run tests with --keepdb
Make it possible to run tests with --keepdb
Python
bsd-3-clause
onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle
from django.test.runner import DiscoverRunner from django.db import connection from tenant_schemas.utils import get_tenant_model from bluebottle.test.utils import InitProjectDataMixin class MultiTenantRunner(DiscoverRunner, InitProjectDataMixin): def setup_databases(self, *args, **kwargs): result = super(MultiTenantRunner, self).setup_databases(*args, **kwargs) # Create secondary tenant connection.set_schema_to_public() tenant_domain = 'testserver2' - tenant2 = get_tenant_model()( + tenant2, _created = get_tenant_model().objects.get_or_create( domain_url=tenant_domain, schema_name='test2', client_name='test2') tenant2.save( verbosity=self.verbosity) # Add basic data for tenant connection.set_tenant(tenant2) self.init_projects() # Create main tenant connection.set_schema_to_public() tenant_domain = 'testserver' - tenant = get_tenant_model()( + + tenant, _created = get_tenant_model().objects.get_or_create( domain_url=tenant_domain, schema_name='test', client_name='test') tenant.save( verbosity=self.verbosity) connection.set_tenant(tenant) return result
Make it possible to run tests with --keepdb
## Code Before: from django.test.runner import DiscoverRunner from django.db import connection from tenant_schemas.utils import get_tenant_model from bluebottle.test.utils import InitProjectDataMixin class MultiTenantRunner(DiscoverRunner, InitProjectDataMixin): def setup_databases(self, *args, **kwargs): result = super(MultiTenantRunner, self).setup_databases(*args, **kwargs) # Create secondary tenant connection.set_schema_to_public() tenant_domain = 'testserver2' tenant2 = get_tenant_model()( domain_url=tenant_domain, schema_name='test2', client_name='test2') tenant2.save( verbosity=self.verbosity) # Add basic data for tenant connection.set_tenant(tenant2) self.init_projects() # Create main tenant connection.set_schema_to_public() tenant_domain = 'testserver' tenant = get_tenant_model()( domain_url=tenant_domain, schema_name='test', client_name='test') tenant.save( verbosity=self.verbosity) connection.set_tenant(tenant) return result ## Instruction: Make it possible to run tests with --keepdb ## Code After: from django.test.runner import DiscoverRunner from django.db import connection from tenant_schemas.utils import get_tenant_model from bluebottle.test.utils import InitProjectDataMixin class MultiTenantRunner(DiscoverRunner, InitProjectDataMixin): def setup_databases(self, *args, **kwargs): result = super(MultiTenantRunner, self).setup_databases(*args, **kwargs) # Create secondary tenant connection.set_schema_to_public() tenant_domain = 'testserver2' tenant2, _created = get_tenant_model().objects.get_or_create( domain_url=tenant_domain, schema_name='test2', client_name='test2') tenant2.save( verbosity=self.verbosity) # Add basic data for tenant connection.set_tenant(tenant2) self.init_projects() # Create main tenant connection.set_schema_to_public() tenant_domain = 'testserver' tenant, _created = get_tenant_model().objects.get_or_create( domain_url=tenant_domain, schema_name='test', client_name='test') tenant.save( verbosity=self.verbosity) connection.set_tenant(tenant) return result
from django.test.runner import DiscoverRunner from django.db import connection from tenant_schemas.utils import get_tenant_model from bluebottle.test.utils import InitProjectDataMixin class MultiTenantRunner(DiscoverRunner, InitProjectDataMixin): def setup_databases(self, *args, **kwargs): result = super(MultiTenantRunner, self).setup_databases(*args, **kwargs) # Create secondary tenant connection.set_schema_to_public() tenant_domain = 'testserver2' - tenant2 = get_tenant_model()( + tenant2, _created = get_tenant_model().objects.get_or_create( domain_url=tenant_domain, schema_name='test2', client_name='test2') tenant2.save( verbosity=self.verbosity) # Add basic data for tenant connection.set_tenant(tenant2) self.init_projects() # Create main tenant connection.set_schema_to_public() tenant_domain = 'testserver' - tenant = get_tenant_model()( + + tenant, _created = get_tenant_model().objects.get_or_create( domain_url=tenant_domain, schema_name='test', client_name='test') tenant.save( verbosity=self.verbosity) connection.set_tenant(tenant) return result
a1bcb99691f5a0238f6a34a5579df3e89e8d6823
child_sync_gp/model/project_compassion.py
child_sync_gp/model/project_compassion.py
from openerp.osv import orm from . import gp_connector class project_compassion(orm.Model): _inherit = 'compassion.project' def write(self, cr, uid, ids, vals, context=None): """Update Project in GP.""" res = super(project_compassion, self).write(cr, uid, ids, vals, context) gp_connect = gp_connector.GPConnect() for project in self.browse(cr, uid, ids, context): gp_connect.upsert_project(uid, project) return res
from openerp.osv import orm from . import gp_connector class project_compassion(orm.Model): _inherit = 'compassion.project' def write(self, cr, uid, ids, vals, context=None): """Update Project in GP.""" res = super(project_compassion, self).write(cr, uid, ids, vals, context) if not isinstance(ids, list): ids = [ids] gp_connect = gp_connector.GPConnect() for project in self.browse(cr, uid, ids, context): gp_connect.upsert_project(uid, project) return res
Fix bug in write project.
Fix bug in write project.
Python
agpl-3.0
CompassionCH/compassion-switzerland,ndtran/compassion-switzerland,MickSandoz/compassion-switzerland,eicher31/compassion-switzerland,Secheron/compassion-switzerland,CompassionCH/compassion-switzerland,Secheron/compassion-switzerland,CompassionCH/compassion-switzerland,MickSandoz/compassion-switzerland,ecino/compassion-switzerland,ndtran/compassion-switzerland,eicher31/compassion-switzerland,ecino/compassion-switzerland,ecino/compassion-switzerland,eicher31/compassion-switzerland
from openerp.osv import orm from . import gp_connector class project_compassion(orm.Model): _inherit = 'compassion.project' def write(self, cr, uid, ids, vals, context=None): """Update Project in GP.""" res = super(project_compassion, self).write(cr, uid, ids, vals, context) + if not isinstance(ids, list): + ids = [ids] gp_connect = gp_connector.GPConnect() for project in self.browse(cr, uid, ids, context): gp_connect.upsert_project(uid, project) return res
Fix bug in write project.
## Code Before: from openerp.osv import orm from . import gp_connector class project_compassion(orm.Model): _inherit = 'compassion.project' def write(self, cr, uid, ids, vals, context=None): """Update Project in GP.""" res = super(project_compassion, self).write(cr, uid, ids, vals, context) gp_connect = gp_connector.GPConnect() for project in self.browse(cr, uid, ids, context): gp_connect.upsert_project(uid, project) return res ## Instruction: Fix bug in write project. ## Code After: from openerp.osv import orm from . import gp_connector class project_compassion(orm.Model): _inherit = 'compassion.project' def write(self, cr, uid, ids, vals, context=None): """Update Project in GP.""" res = super(project_compassion, self).write(cr, uid, ids, vals, context) if not isinstance(ids, list): ids = [ids] gp_connect = gp_connector.GPConnect() for project in self.browse(cr, uid, ids, context): gp_connect.upsert_project(uid, project) return res
from openerp.osv import orm from . import gp_connector class project_compassion(orm.Model): _inherit = 'compassion.project' def write(self, cr, uid, ids, vals, context=None): """Update Project in GP.""" res = super(project_compassion, self).write(cr, uid, ids, vals, context) + if not isinstance(ids, list): + ids = [ids] gp_connect = gp_connector.GPConnect() for project in self.browse(cr, uid, ids, context): gp_connect.upsert_project(uid, project) return res
2f6c82d74592c80b5042c0b808a658650896cbec
rebulk/__init__.py
rebulk/__init__.py
from .rebulk import Rebulk from .match import Match from .rules import Rule from .pattern import REGEX_AVAILABLE
from .rebulk import Rebulk from .match import Match from .rules import Rule, AppendMatchRule, RemoveMatchRule from .pattern import REGEX_AVAILABLE
Add global imports for rules classes
Add global imports for rules classes
Python
mit
Toilal/rebulk
from .rebulk import Rebulk from .match import Match - from .rules import Rule + from .rules import Rule, AppendMatchRule, RemoveMatchRule from .pattern import REGEX_AVAILABLE
Add global imports for rules classes
## Code Before: from .rebulk import Rebulk from .match import Match from .rules import Rule from .pattern import REGEX_AVAILABLE ## Instruction: Add global imports for rules classes ## Code After: from .rebulk import Rebulk from .match import Match from .rules import Rule, AppendMatchRule, RemoveMatchRule from .pattern import REGEX_AVAILABLE
from .rebulk import Rebulk from .match import Match - from .rules import Rule + from .rules import Rule, AppendMatchRule, RemoveMatchRule from .pattern import REGEX_AVAILABLE
f87a923678f5d7e9f6390ffcb42eae6b2a0f9cc2
services/views.py
services/views.py
import json import requests from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotAllowed, HttpResponseNotFound from django.conf import settings from django.views.decorators.csrf import csrf_exempt from .patch_ssl import get_session @csrf_exempt def post_service_request(request): if request.method != 'POST': return HttpResponseNotAllowed(['POST']) payload = request.POST.copy() outgoing = payload.dict() outgoing['api_key'] = settings.OPEN311['API_KEY'] url = settings.OPEN311['URL_BASE'] session = get_session() r = session.post(url, data=outgoing) if r.status_code != 200: return HttpResponseBadRequest() return HttpResponse(r.content, content_type="application/json")
import json import requests from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotAllowed, HttpResponseNotFound from django.conf import settings from django.views.decorators.csrf import csrf_exempt from .patch_ssl import get_session @csrf_exempt def post_service_request(request): if request.method != 'POST': return HttpResponseNotAllowed(['POST']) payload = request.POST.copy() outgoing = payload.dict() if outgoing.get('internal_feedback', False): if 'internal_feedback' in outgoing: del outgoing['internal_feedback'] api_key = settings.OPEN311['INTERNAL_FEEDBACK_API_KEY'] else: api_key = settings.OPEN311['API_KEY'] outgoing['api_key'] = api_key url = settings.OPEN311['URL_BASE'] session = get_session() r = session.post(url, data=outgoing) if r.status_code != 200: return HttpResponseBadRequest() return HttpResponse(r.content, content_type="application/json")
Use separate API key for feedback about app.
Use separate API key for feedback about app.
Python
agpl-3.0
City-of-Helsinki/smbackend,City-of-Helsinki/smbackend
import json import requests from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotAllowed, HttpResponseNotFound from django.conf import settings from django.views.decorators.csrf import csrf_exempt from .patch_ssl import get_session @csrf_exempt def post_service_request(request): if request.method != 'POST': return HttpResponseNotAllowed(['POST']) payload = request.POST.copy() outgoing = payload.dict() + if outgoing.get('internal_feedback', False): + if 'internal_feedback' in outgoing: + del outgoing['internal_feedback'] + api_key = settings.OPEN311['INTERNAL_FEEDBACK_API_KEY'] + else: - outgoing['api_key'] = settings.OPEN311['API_KEY'] + api_key = settings.OPEN311['API_KEY'] + outgoing['api_key'] = api_key url = settings.OPEN311['URL_BASE'] session = get_session() r = session.post(url, data=outgoing) if r.status_code != 200: return HttpResponseBadRequest() return HttpResponse(r.content, content_type="application/json")
Use separate API key for feedback about app.
## Code Before: import json import requests from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotAllowed, HttpResponseNotFound from django.conf import settings from django.views.decorators.csrf import csrf_exempt from .patch_ssl import get_session @csrf_exempt def post_service_request(request): if request.method != 'POST': return HttpResponseNotAllowed(['POST']) payload = request.POST.copy() outgoing = payload.dict() outgoing['api_key'] = settings.OPEN311['API_KEY'] url = settings.OPEN311['URL_BASE'] session = get_session() r = session.post(url, data=outgoing) if r.status_code != 200: return HttpResponseBadRequest() return HttpResponse(r.content, content_type="application/json") ## Instruction: Use separate API key for feedback about app. ## Code After: import json import requests from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotAllowed, HttpResponseNotFound from django.conf import settings from django.views.decorators.csrf import csrf_exempt from .patch_ssl import get_session @csrf_exempt def post_service_request(request): if request.method != 'POST': return HttpResponseNotAllowed(['POST']) payload = request.POST.copy() outgoing = payload.dict() if outgoing.get('internal_feedback', False): if 'internal_feedback' in outgoing: del outgoing['internal_feedback'] api_key = settings.OPEN311['INTERNAL_FEEDBACK_API_KEY'] else: api_key = settings.OPEN311['API_KEY'] outgoing['api_key'] = api_key url = settings.OPEN311['URL_BASE'] session = get_session() r = session.post(url, data=outgoing) if r.status_code != 200: return HttpResponseBadRequest() return HttpResponse(r.content, content_type="application/json")
import json import requests from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotAllowed, HttpResponseNotFound from django.conf import settings from django.views.decorators.csrf import csrf_exempt from .patch_ssl import get_session @csrf_exempt def post_service_request(request): if request.method != 'POST': return HttpResponseNotAllowed(['POST']) payload = request.POST.copy() outgoing = payload.dict() + if outgoing.get('internal_feedback', False): + if 'internal_feedback' in outgoing: + del outgoing['internal_feedback'] + api_key = settings.OPEN311['INTERNAL_FEEDBACK_API_KEY'] + else: - outgoing['api_key'] = settings.OPEN311['API_KEY'] ? ^^^^^^^^^^ -- + api_key = settings.OPEN311['API_KEY'] ? ^^^^ + outgoing['api_key'] = api_key url = settings.OPEN311['URL_BASE'] session = get_session() r = session.post(url, data=outgoing) if r.status_code != 200: return HttpResponseBadRequest() return HttpResponse(r.content, content_type="application/json")
ca2b02d551e9bb4c8625ae79f7878892673fa731
corehq/apps/es/domains.py
corehq/apps/es/domains.py
from .es_query import HQESQuery from . import filters class DomainES(HQESQuery): index = 'domains' @property def builtin_filters(self): return [ real_domains, commconnect_domains, created, ] + super(DomainES, self).builtin_filters def real_domains(): return filters.term("is_test", False) def commconnect_domains(): return filters.term("commconnect_enabled", True) def created(gt=None, gte=None, lt=None, lte=None): return filters.date_range('date_created', gt, gte, lt, lte)
from .es_query import HQESQuery from . import filters class DomainES(HQESQuery): index = 'domains' @property def builtin_filters(self): return [ real_domains, commcare_domains, commconnect_domains, commtrack_domains, created, ] + super(DomainES, self).builtin_filters def real_domains(): return filters.term("is_test", False) def commcare_domains(): return filters.AND(filters.term("commconnect_enabled", False), filters.term("commtrack_enabled", False)) def commconnect_domains(): return filters.term("commconnect_enabled", True) def commtrack_domains(): return filters.term("commtrack_enabled", True) def created(gt=None, gte=None, lt=None, lte=None): return filters.date_range('date_created', gt, gte, lt, lte)
Add CommCare, CommTrack filters for DomainES
Add CommCare, CommTrack filters for DomainES
Python
bsd-3-clause
qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq
from .es_query import HQESQuery from . import filters class DomainES(HQESQuery): index = 'domains' @property def builtin_filters(self): return [ real_domains, + commcare_domains, commconnect_domains, + commtrack_domains, created, ] + super(DomainES, self).builtin_filters def real_domains(): return filters.term("is_test", False) + def commcare_domains(): + return filters.AND(filters.term("commconnect_enabled", False), + filters.term("commtrack_enabled", False)) + + def commconnect_domains(): return filters.term("commconnect_enabled", True) + + + def commtrack_domains(): + return filters.term("commtrack_enabled", True) def created(gt=None, gte=None, lt=None, lte=None): return filters.date_range('date_created', gt, gte, lt, lte)
Add CommCare, CommTrack filters for DomainES
## Code Before: from .es_query import HQESQuery from . import filters class DomainES(HQESQuery): index = 'domains' @property def builtin_filters(self): return [ real_domains, commconnect_domains, created, ] + super(DomainES, self).builtin_filters def real_domains(): return filters.term("is_test", False) def commconnect_domains(): return filters.term("commconnect_enabled", True) def created(gt=None, gte=None, lt=None, lte=None): return filters.date_range('date_created', gt, gte, lt, lte) ## Instruction: Add CommCare, CommTrack filters for DomainES ## Code After: from .es_query import HQESQuery from . import filters class DomainES(HQESQuery): index = 'domains' @property def builtin_filters(self): return [ real_domains, commcare_domains, commconnect_domains, commtrack_domains, created, ] + super(DomainES, self).builtin_filters def real_domains(): return filters.term("is_test", False) def commcare_domains(): return filters.AND(filters.term("commconnect_enabled", False), filters.term("commtrack_enabled", False)) def commconnect_domains(): return filters.term("commconnect_enabled", True) def commtrack_domains(): return filters.term("commtrack_enabled", True) def created(gt=None, gte=None, lt=None, lte=None): return filters.date_range('date_created', gt, gte, lt, lte)
from .es_query import HQESQuery from . import filters class DomainES(HQESQuery): index = 'domains' @property def builtin_filters(self): return [ real_domains, + commcare_domains, commconnect_domains, + commtrack_domains, created, ] + super(DomainES, self).builtin_filters def real_domains(): return filters.term("is_test", False) + def commcare_domains(): + return filters.AND(filters.term("commconnect_enabled", False), + filters.term("commtrack_enabled", False)) + + def commconnect_domains(): return filters.term("commconnect_enabled", True) + def commtrack_domains(): + return filters.term("commtrack_enabled", True) + + def created(gt=None, gte=None, lt=None, lte=None): return filters.date_range('date_created', gt, gte, lt, lte)
f99a898d66c9f88496dee73ec574c7b9b69e8dc2
ocds/storage/backends/design/tenders.py
ocds/storage/backends/design/tenders.py
from ocds.storage.helpers import CouchView class AllDocs(CouchView): design = 'docs' @staticmethod def map(doc): yield (doc['tenderID'], doc) class DateView(CouchView): design = 'dates' @staticmethod def map(doc): yield (doc['dateModified'], doc) views = [ AllDocs(), DateView() ]
from ocds.storage.helpers import CouchView class AllDocs(CouchView): design = 'docs' @staticmethod def map(doc): if 'doc_type' in doc and doc['doc_type'] != 'Tender': return yield doc['_id'], doc class DateView(CouchView): design = 'dates' @staticmethod def map(doc): if 'doc_type' in doc and doc['doc_type'] != 'Tender': return yield doc['_id'], doc['dateModified'] views = [ AllDocs(), DateView() ]
Add filter in design docs
Add filter in design docs
Python
apache-2.0
yshalenyk/openprocurement.ocds.export,yshalenyk/ocds.export,yshalenyk/openprocurement.ocds.export
from ocds.storage.helpers import CouchView class AllDocs(CouchView): design = 'docs' @staticmethod def map(doc): + if 'doc_type' in doc and doc['doc_type'] != 'Tender': + return + - yield (doc['tenderID'], doc) + yield doc['_id'], doc class DateView(CouchView): design = 'dates' @staticmethod def map(doc): + if 'doc_type' in doc and doc['doc_type'] != 'Tender': + return + - yield (doc['dateModified'], doc) + yield doc['_id'], doc['dateModified'] views = [ AllDocs(), DateView() ]
Add filter in design docs
## Code Before: from ocds.storage.helpers import CouchView class AllDocs(CouchView): design = 'docs' @staticmethod def map(doc): yield (doc['tenderID'], doc) class DateView(CouchView): design = 'dates' @staticmethod def map(doc): yield (doc['dateModified'], doc) views = [ AllDocs(), DateView() ] ## Instruction: Add filter in design docs ## Code After: from ocds.storage.helpers import CouchView class AllDocs(CouchView): design = 'docs' @staticmethod def map(doc): if 'doc_type' in doc and doc['doc_type'] != 'Tender': return yield doc['_id'], doc class DateView(CouchView): design = 'dates' @staticmethod def map(doc): if 'doc_type' in doc and doc['doc_type'] != 'Tender': return yield doc['_id'], doc['dateModified'] views = [ AllDocs(), DateView() ]
from ocds.storage.helpers import CouchView class AllDocs(CouchView): design = 'docs' @staticmethod def map(doc): + if 'doc_type' in doc and doc['doc_type'] != 'Tender': + return + - yield (doc['tenderID'], doc) ? - ^^^ ---- - + yield doc['_id'], doc ? ^^ class DateView(CouchView): design = 'dates' @staticmethod def map(doc): + if 'doc_type' in doc and doc['doc_type'] != 'Tender': + return + - yield (doc['dateModified'], doc) ? ^ ------ + yield doc['_id'], doc['dateModified'] ? ^^^^^^^^^^^^ views = [ AllDocs(), DateView() ]
9cd72406d63d1ce3a6cd75a65131c8bde3df95ba
push_plugin.py
push_plugin.py
import requests class PushClient: def __init__(self, app): self.app = app def handle_new_or_edit(self, post): data = { 'hub.mode' : 'publish', 'hub.url' : 'http://kylewm.com/all.atom' } response = requests.post('https://pubsubhubbub.appspot.com/', data) if response.status_code == 204: self.app.logger.info('successfully sent PuSH notification')
import requests class PushClient: def __init__(self, app): self.app = app def publish(self, url): data = { 'hub.mode' : 'publish', 'hub.url' : url } response = requests.post('https://pubsubhubbub.appspot.com/', data) if response.status_code == 204: self.app.logger.info('successfully sent PuSH notification') else: self.app.logger.warn('unexpected response from PuSH hub %s', response) def handle_new_or_edit(self, post): self.publish('http://kylewm.com/all.atom') if post.post_type=='article': self.publish('http://kylewm.com/articles.atom') elif post.post_type=='note': self.publish('http://kylewm.com/notes.atom')
Send the all.atom feed and the articles/notes feeds to PuSH
Send the all.atom feed and the articles/notes feeds to PuSH
Python
bsd-2-clause
thedod/redwind,Lancey6/redwind,thedod/redwind,Lancey6/redwind,Lancey6/redwind
import requests class PushClient: def __init__(self, app): self.app = app - def handle_new_or_edit(self, post): + def publish(self, url): - data = { 'hub.mode' : 'publish', + data = { 'hub.mode' : 'publish', 'hub.url' : url } - 'hub.url' : 'http://kylewm.com/all.atom' } response = requests.post('https://pubsubhubbub.appspot.com/', data) if response.status_code == 204: self.app.logger.info('successfully sent PuSH notification') + else: + self.app.logger.warn('unexpected response from PuSH hub %s', response) + + def handle_new_or_edit(self, post): + self.publish('http://kylewm.com/all.atom') + if post.post_type=='article': + self.publish('http://kylewm.com/articles.atom') + elif post.post_type=='note': + self.publish('http://kylewm.com/notes.atom') +
Send the all.atom feed and the articles/notes feeds to PuSH
## Code Before: import requests class PushClient: def __init__(self, app): self.app = app def handle_new_or_edit(self, post): data = { 'hub.mode' : 'publish', 'hub.url' : 'http://kylewm.com/all.atom' } response = requests.post('https://pubsubhubbub.appspot.com/', data) if response.status_code == 204: self.app.logger.info('successfully sent PuSH notification') ## Instruction: Send the all.atom feed and the articles/notes feeds to PuSH ## Code After: import requests class PushClient: def __init__(self, app): self.app = app def publish(self, url): data = { 'hub.mode' : 'publish', 'hub.url' : url } response = requests.post('https://pubsubhubbub.appspot.com/', data) if response.status_code == 204: self.app.logger.info('successfully sent PuSH notification') else: self.app.logger.warn('unexpected response from PuSH hub %s', response) def handle_new_or_edit(self, post): self.publish('http://kylewm.com/all.atom') if post.post_type=='article': self.publish('http://kylewm.com/articles.atom') elif post.post_type=='note': self.publish('http://kylewm.com/notes.atom')
import requests class PushClient: def __init__(self, app): self.app = app - def handle_new_or_edit(self, post): + def publish(self, url): - data = { 'hub.mode' : 'publish', + data = { 'hub.mode' : 'publish', 'hub.url' : url } ? +++++++++++++++++ - 'hub.url' : 'http://kylewm.com/all.atom' } response = requests.post('https://pubsubhubbub.appspot.com/', data) if response.status_code == 204: self.app.logger.info('successfully sent PuSH notification') + else: + self.app.logger.warn('unexpected response from PuSH hub %s', response) + + def handle_new_or_edit(self, post): + self.publish('http://kylewm.com/all.atom') + if post.post_type=='article': + self.publish('http://kylewm.com/articles.atom') + elif post.post_type=='note': + self.publish('http://kylewm.com/notes.atom') +
b89a6a10e2a1beafe893faa6eec6e2562ded7492
local-celery.py
local-celery.py
import sys from deployer.celery import app if __name__ == '__main__': argv = sys.argv if len(sys.argv) > 1 else [__file__, '--loglevel=info'] app.worker_main(argv=argv)
import sys from deployer.celery import app if __name__ == '__main__': argv = sys.argv if len(sys.argv) > 1 else [__file__, '--loglevel=info'] app.conf.CELERYD_CONCURRENCY = 2 app.worker_main(argv=argv)
Set concurrency to 2 for local
Set concurrency to 2 for local
Python
mit
totem/cluster-deployer,totem/cluster-deployer,totem/cluster-deployer
import sys from deployer.celery import app if __name__ == '__main__': argv = sys.argv if len(sys.argv) > 1 else [__file__, '--loglevel=info'] + app.conf.CELERYD_CONCURRENCY = 2 app.worker_main(argv=argv)
Set concurrency to 2 for local
## Code Before: import sys from deployer.celery import app if __name__ == '__main__': argv = sys.argv if len(sys.argv) > 1 else [__file__, '--loglevel=info'] app.worker_main(argv=argv) ## Instruction: Set concurrency to 2 for local ## Code After: import sys from deployer.celery import app if __name__ == '__main__': argv = sys.argv if len(sys.argv) > 1 else [__file__, '--loglevel=info'] app.conf.CELERYD_CONCURRENCY = 2 app.worker_main(argv=argv)
import sys from deployer.celery import app if __name__ == '__main__': argv = sys.argv if len(sys.argv) > 1 else [__file__, '--loglevel=info'] + app.conf.CELERYD_CONCURRENCY = 2 app.worker_main(argv=argv)
c889ffd1f86a445f2e5ba157fc81cbb64e92dc12
voctocore/lib/sources/videoloopsource.py
voctocore/lib/sources/videoloopsource.py
import logging import re from gi.repository import Gst from lib.config import Config from lib.sources.avsource import AVSource class VideoLoopSource(AVSource): def __init__(self, name): super().__init__('VideoLoopSource', name, False, True) self.location = Config.getLocation(name) self.build_pipeline() def __str__(self): return 'VideoLoopSource[{name}] displaying {location}'.format( name=self.name, location=self.location ) def port(self): m = re.search('.*/([^/]*)', self.location) return self.location def num_connections(self): return 1 def video_channels(self): return 1 def build_source(self): return """ multifilesrc name=videoloop-{name} location={location} loop=true ! decodebin ! videoconvert ! videoscale name=videoloop """.format( name=self.name, location=self.location ) def build_videoport(self): return 'videoloop.' def build_audioport(self, audiostream): return 'audioloop.'
import logging import re from gi.repository import Gst from lib.config import Config from lib.sources.avsource import AVSource class VideoLoopSource(AVSource): timer_resolution = 0.5 def __init__(self, name, has_audio=True, has_video=True, force_num_streams=None): super().__init__('VideoLoopSource', name, has_audio, has_video, show_no_signal=True) self.location = Config.getLocation(name) self.build_pipeline() def __str__(self): return 'VideoLoopSource[{name}] displaying {location}'.format( name=self.name, location=self.location ) def port(self): m = re.search('.*/([^/]*)', self.location) return self.location def num_connections(self): return 1 def video_channels(self): return 1 def build_source(self): return """ multifilesrc location={location} loop=true ! decodebin name=videoloop-{name} """.format( name=self.name, location=self.location ) def build_videoport(self): return """ videoloop-{name}. ! videoconvert ! videoscale """.format(name=self.name) def build_audioport(self): return """ videoloop-{name}. ! audioconvert ! audioresample """.format(name=self.name)
Modify videoloop to allow for audio
Modify videoloop to allow for audio
Python
mit
voc/voctomix,voc/voctomix
import logging import re from gi.repository import Gst from lib.config import Config from lib.sources.avsource import AVSource class VideoLoopSource(AVSource): - def __init__(self, name): - super().__init__('VideoLoopSource', name, False, True) + timer_resolution = 0.5 + + def __init__(self, name, has_audio=True, has_video=True, + force_num_streams=None): + super().__init__('VideoLoopSource', name, has_audio, has_video, show_no_signal=True) self.location = Config.getLocation(name) self.build_pipeline() def __str__(self): return 'VideoLoopSource[{name}] displaying {location}'.format( name=self.name, location=self.location ) def port(self): m = re.search('.*/([^/]*)', self.location) return self.location def num_connections(self): return 1 def video_channels(self): return 1 def build_source(self): return """ multifilesrc - name=videoloop-{name} location={location} loop=true ! decodebin - ! videoconvert - ! videoscale - name=videoloop + name=videoloop-{name} """.format( name=self.name, location=self.location ) def build_videoport(self): - return 'videoloop.' + return """ + videoloop-{name}. + ! videoconvert + ! videoscale + """.format(name=self.name) - def build_audioport(self, audiostream): + def build_audioport(self): - return 'audioloop.' - + return """ + videoloop-{name}. + ! audioconvert + ! audioresample + """.format(name=self.name)
Modify videoloop to allow for audio
## Code Before: import logging import re from gi.repository import Gst from lib.config import Config from lib.sources.avsource import AVSource class VideoLoopSource(AVSource): def __init__(self, name): super().__init__('VideoLoopSource', name, False, True) self.location = Config.getLocation(name) self.build_pipeline() def __str__(self): return 'VideoLoopSource[{name}] displaying {location}'.format( name=self.name, location=self.location ) def port(self): m = re.search('.*/([^/]*)', self.location) return self.location def num_connections(self): return 1 def video_channels(self): return 1 def build_source(self): return """ multifilesrc name=videoloop-{name} location={location} loop=true ! decodebin ! videoconvert ! videoscale name=videoloop """.format( name=self.name, location=self.location ) def build_videoport(self): return 'videoloop.' def build_audioport(self, audiostream): return 'audioloop.' ## Instruction: Modify videoloop to allow for audio ## Code After: import logging import re from gi.repository import Gst from lib.config import Config from lib.sources.avsource import AVSource class VideoLoopSource(AVSource): timer_resolution = 0.5 def __init__(self, name, has_audio=True, has_video=True, force_num_streams=None): super().__init__('VideoLoopSource', name, has_audio, has_video, show_no_signal=True) self.location = Config.getLocation(name) self.build_pipeline() def __str__(self): return 'VideoLoopSource[{name}] displaying {location}'.format( name=self.name, location=self.location ) def port(self): m = re.search('.*/([^/]*)', self.location) return self.location def num_connections(self): return 1 def video_channels(self): return 1 def build_source(self): return """ multifilesrc location={location} loop=true ! decodebin name=videoloop-{name} """.format( name=self.name, location=self.location ) def build_videoport(self): return """ videoloop-{name}. ! videoconvert ! videoscale """.format(name=self.name) def build_audioport(self): return """ videoloop-{name}. ! audioconvert ! audioresample """.format(name=self.name)
import logging import re from gi.repository import Gst from lib.config import Config from lib.sources.avsource import AVSource class VideoLoopSource(AVSource): - def __init__(self, name): - super().__init__('VideoLoopSource', name, False, True) + timer_resolution = 0.5 + + def __init__(self, name, has_audio=True, has_video=True, + force_num_streams=None): + super().__init__('VideoLoopSource', name, has_audio, has_video, show_no_signal=True) self.location = Config.getLocation(name) self.build_pipeline() def __str__(self): return 'VideoLoopSource[{name}] displaying {location}'.format( name=self.name, location=self.location ) def port(self): m = re.search('.*/([^/]*)', self.location) return self.location def num_connections(self): return 1 def video_channels(self): return 1 def build_source(self): return """ multifilesrc - name=videoloop-{name} location={location} loop=true ! decodebin - ! videoconvert - ! videoscale - name=videoloop ? - + name=videoloop-{name} ? +++++++ """.format( name=self.name, location=self.location ) def build_videoport(self): - return 'videoloop.' + return """ + videoloop-{name}. + ! videoconvert + ! videoscale + """.format(name=self.name) - def build_audioport(self, audiostream): ? ------------- + def build_audioport(self): - return 'audioloop.' + return """ + videoloop-{name}. + ! audioconvert + ! audioresample + """.format(name=self.name)